-
Notifications
You must be signed in to change notification settings - Fork 10
/
PyscesPlot2.py
1534 lines (1271 loc) · 49.7 KB
/
PyscesPlot2.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
PySCeS - Python Simulator for Cellular Systems (http://pysces.sourceforge.net)
Copyright (C) 2004-2020 B.G. Olivier, J.M. Rohwer, J.-H.S Hofmeyr all rights reserved,
Brett G. Olivier (bgoli@users.sourceforge.net)
Triple-J Group for Molecular Cell Physiology
Stellenbosch University, South Africa.
Permission to use, modify, and distribute this software is given under the
terms of the PySceS (BSD style) license. See LICENSE.txt that came with
this distribution for specifics.
NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
Brett G. Olivier
"""
from __future__ import division, print_function
from __future__ import absolute_import
from __future__ import unicode_literals
from pysces.version import __version__
from pysces import __SILENT_START__
import subprocess, os, shutil, time, math, itertools, copy
from getpass import getuser
import numpy, scipy
try:
input = raw_input # Py2 compatibility
except NameError:
pass
__doc__ = '''
PyscesPlot2
-----------
PyscesPlot2 is a new graphics susbsystem for PySCeS which will include a
Unified Plotting Interface which can take advantage of different plotting
backends via a common user interface.
'''
class PlotBase(object):
"""
Abstract class defining the Unified Plotting Interface methods. These methods should
be overridden and the class extended by interface specific subclasses.
"""
CommonStyleDefs = {'points' : '',
'lines' : ''
}
def plot(self, data, x, y, title='', format=''):
"""
Plot a single line data[y] vs data[x] where:
- *data* the data array
- *x* x column index
- *y* y column index
- *title* is the line key
- *format* is the XXX format string (default='')
Format can also be the *CommonStyle* 'lines' or 'points'
"""
raise NotImplementedError
def plotLines(self, data, x, y=[], titles=[], formats=['']):
"""
Plot a multiple lines data[y1, y2, ] vs data[x] where:
- *data* the data array
- *x* x column index
- *y* is a list of line indexes, if empty all of y not including x is plotted
- *titles* is a list of line keys, if empty Line1,Line2,Line3 is used
- *formats* is a list (per line) of XXX format strings.
If *formats* only contains a single item, this format is used for all lines
and can also be the *CommonStyle* 'lines' or 'points'.
"""
raise NotImplementedError
def splot(self, data, x, y, z, titles='', format=''):
"""
Plot a surface data[z] vs data[y] vs data[x] where:
- *data* the data array
- *x* x column index
- *y* y column index
- *z* z column index
- *title* is the surface key
- *format* is the XXX format string (default='')
Format can also be the *CommonStyle* 'lines' or 'points'.
"""
raise NotImplementedError
def splotSurfaces(self, data, x, y, z=[], titles=[], formats=['']):
"""
Plot data[z1, z2, ] vs data[y] vs data[x] where:
- *data* the data array
- *x* x column index
- *y* y column index
- *z* list of z column indexes, if empty all of z not including x, y are plotted
- *titles* is a list of surface keys, if empty Surf1, Surf2, Surf3 is used
- *formats* is a list (per line) of XXX format strings (default='').
If *formats* only contains a single item, this format is used for all surfaces
and can also be the *CommonStyle* 'lines' or 'points'.
"""
raise NotImplementedError
def setLogScale(self, axis):
"""
Set axis to logscale where:
- *axis* = x, y, z, xy, xz, yz, zyx
"""
raise NotImplementedError
def setNoLogScale(self, axis):
"""
Set axis to a linear scale where:
- *axis* = x, y, z, xy, xz, yz, zyx
"""
raise NotImplementedError
def setRange(self, axis, min=None, max=None):
"""
Set axis range where
- *axis* = x, y, z, xy, xz, yz, zyx
- *min* = range(s) lower bound (default=None) autoscale
- *max* = range(s) upper bound (default=None) autoscale
"""
raise NotImplementedError
def setGrid(self, value):
"""
Display or remove graph grid.
- *value* (boolean) True (on) or False (off)
"""
raise NotImplementedError
def setGraphTitle(self, title='PySCeS Plot'):
"""
Set the graph title, unset if title=None
- *title* (string, default='PySCeS Plot') the graph title
"""
raise NotImplementedError
def setKey(self, value=False):
"""
Enable or disable the current plot key, no arguments removes key.
- *value* boolean (default = False)
"""
raise NotImplementedError
def setAxisLabel(self, axis, label=''):
"""
Set the axis label:
- *axis* = x, y, z, xy, xz, yz, zyx
- *label* = string (default='')
Called with only the axis argument clears the axis label.
"""
raise NotImplementedError
def save(self, name, directory=None, dfmt='%.8e'):
"""
Save the plot data and (optionally) XXX format file
- *filename* the filename
- *directory* optional (default = current working directory)
- *dfmt* the data format string (default='%.8e')
"""
raise NotImplementedError
def export(self, name, directory=None, type='png'):
"""
Export the current plot as a <format> file.
- *filename* the filename
- *directory* optional (default = current working directory)
- *type* the file format (default='png').
Currently only PNG is guaranteed to be available in all interfaces.
"""
raise NotImplementedError
def axisInputStringToList(self, input):
"""
Extracts axis information from a string input, returns a boolean triple
representing (x=True/False, y=True/False, z=True/False).
- *input* the input string
"""
out = [None, None, None]
input = input.lower()
if 'x' in input:
out[0] = 'x'
if 'y' in input:
out[1] = 'y'
if 'z' in input:
out[2] = 'z'
return out
def wait(self, seconds=3):
"""
Wait *seconds* (default = 3) or until enter is pressed (seconds = -1)
"""
if seconds == -1:
input("\nPress <enter> to continue ...\n")
else:
time.sleep(seconds)
class GnuPlotUPI(PlotBase):
"""
PySCeS/GnuPlot is reborn, leaner and meaner than ever before. This class enables
plotting with GnuPlot via a subprocess link:
- *work_dir* optional argument setting directory for dat file(s)
- *gnuplot_dir* optional argument specifying the location of pgnuplot.exe (win32) or gnuplot
GnuPlot backend to the Unified Plotting Interface.
"""
__G_SUBPROC__ = None
__ECHO__ = False
__DATA_FILE_NAME__ = '_gnuplot.dat'
__WORK_DIR__ = None
__DATA_FILE_PATH__ = None
DATF_FORMAT = '%.8e'
__LAST_COMMAND__ = ''
__MULTIPLOT__ = False
PAUSE_TIME = 0.1
__GNUPLOT_EXE_PATH__ = None
__DISP_TERMINAL__ = None
## MULTIPLOT_CNTR = 0
## MULTIPLOT_MAX = 3
## datFbuffsize = 5
## datFcache = None
CommonStyleDefs = {'points' : 'w p',
'lines' : 'w l'
}
Terminals = {'x11' : '', 'windows' : '',
'png' : 'medium size 800,600'
# 'xffffff x000000 x404040 xff0000 xffa500 x66cdaa xcdb5cd xadd8e6 x0000ff xdda0dd x9500d3'
}
def __init__(self, work_dir=None, gnuplot_dir=None):
if gnuplot_dir != None or not os.path.exists(gnuplot_dir):
GNUPLOT_PATH = gnuplot_dir
else:
GNUPLOT_PATH = ''
if os.sys.platform == 'win32':
self.__GNUPLOT_EXE_PATH__ = os.path.join(GNUPLOT_PATH, 'pgnuplot.exe')
self.__DISP_TERMINAL__ = 'windows'
else:
self.__GNUPLOT_EXE_PATH__ = os.path.join(GNUPLOT_PATH, 'gnuplot')
self.__DISP_TERMINAL__ = 'x11'
try:
self.__G_SUBPROC__ = subprocess.Popen(self.__GNUPLOT_EXE_PATH__, stdin=subprocess.PIPE)
except Exception as ex:
print('\nGnuPlot load failure\n')
print(ex)
if work_dir == None or not os.path.exists(work_dir):
work_dir = os.getcwd()
self.__DATA_FILE_PATH__ = os.path.join(work_dir, self.__DATA_FILE_NAME__)
self.__WORK_DIR__ = work_dir
def set(self, key, value=''):
"""
Send *set <key>* or optionally *set <key> <value>* to GnuPlot.
"""
self.g_write("set %s %s" % (key, value))
def unset(self, key, value=''):
"""
Send *unset <key>* or optionally *unset <key> <value>* to GnuPlot.
"""
self.g_write("unset %s %s" % (key, value))
def g_write(self, cmd):
"""
Write a command to the GnuPlot interpreter
- *cmd* the GnuPlot command
"""
cmd = cmd.replace('\\','/')
self.last_command = cmd
if self.__ECHO__: print('SENT: %s' % cmd)
self.__G_SUBPROC__.stdin.write("""%s\n""" % cmd)
def g_file_write_array(self, arr, dfmt=None):
"""
Write a normal (2D) dataset to temp file. Dumps the array to file
using the format:
- *arr* the array (r>0, c>1)
- *fmt* default '%.8e'
"""
if dfmt == None:
dfmt = self.DATF_FORMAT
numpy.savetxt(self.__DATA_FILE_PATH__, arr, fmt=dfmt, delimiter=' ')
if self.__ECHO__: print('WROTE: %s' % self.__DATA_FILE_PATH__)
self.g_pause() # multiplot protection
def g_file_write_array3D(self, arr, yaxis=1, dfmt=None):
"""
Write a GnuPlot format 3D dataset. The *yaxis* argument
specifies the column that should be used to split the dataset
into GnuPlot slices.
- *arr* the array (r>1, c>2)
- *fmt* default '%.8e'
- *yaxis* default 1
"""
outlist = []
set_idx = 0
curr_y = arr[0,yaxis]
for r in range(arr.shape[0]):
if arr[r, yaxis] != curr_y:
outlist.append(arr[set_idx:r, :])
curr_y = arr[r, yaxis]
set_idx = r
if set_idx < arr.shape[0]:
outlist.append(arr[set_idx:, :])
if dfmt == None:
dfmt = self.DATF_FORMAT
if len(outlist) <= 1:
self.g_file_write_array(arr, dfmt=dfmt)
else:
F = open(self.__DATA_FILE_PATH__, 'w+')
for d in range(len(outlist)):
numpy.savetxt(F, outlist.pop(0), fmt=dfmt)
F.write(' \n')
F.flush()
F.close()
if self.__ECHO__: print('WROTE: %s' % self.__DATA_FILE_PATH__)
del outlist
self.g_pause()
def g_pause(self):
"""
A small pause defined by *self.PAUSE_TIME* (multiplied by 2 when in multiplot).
"""
if self.__MULTIPLOT__:
time.sleep(self.PAUSE_TIME*2.0)
else:
time.sleep(self.PAUSE_TIME)
def plot(self, data, x, y, title='', format='w l'):
"""
Plot a single line data[y] vs data[x] where:
- *data* the data array
- *x* x column index
- *y* y column index
- *title* is the line key
- *format* is the GnuPlot format string (default='w l')
Format can also be the *CommonStyle* 'lines' or 'points'.
"""
if format in list(self.CommonStyleDefs.keys()):
format = self.CommonStyleDefs[format]
if title == '':
title = []
else:
title = ['X', title]
if format == '':
format = 'w l'
self.plotLines(data, x, [y], title, [format]*data.shape[1])
def plotLines(self, data, x, y=[], titles=[], formats=['w l']):
"""
Plot a multiple lines data[y1, y2, ] vs data[x] where:
- *data* the data array
- *x* x column index
- *y* is a list of line indexes, if empty all of y not including x is plotted
- *titles* is a list of line keys if empty Line1, Line2, Line3 is used
- *formats* is a list (per line) of GnuPlot format strings (default='w l').
If *formats* only contains a single item, this format is used for all lines
and can also be the *CommonStyle* 'lines' or 'points'.
"""
self.g_file_write_array(data, dfmt=self.DATF_FORMAT)
if len(y) == 0:
y = list(range(data.shape[1]))
y.pop(x)
if len(formats) != 1 and len(formats) != data.shape[1]:
print("len(titles) must be one or equal the number data columns (%s) using: %s" % (data.shape[1], formats[-1]))
formats = [formats[-1]]
elif formats[0] == '' or formats[0] == None:
formats = ['w l']
if len(formats) == 1 and data.shape[1] > 1:
formats = data.shape[1]*formats
cFormats = list(self.CommonStyleDefs.keys())
for f in range(len(formats)):
if formats[f] in cFormats:
formats[f] = self.CommonStyleDefs[formats[f]]
if len(titles) == 0:
titles = ['col%s' % (l) for l in range(data.shape[1])]
cmd = '''plot '''
for yi in y:
cmd += '''"%s" u %s:%s t "%s" %s, ''' % (self.__DATA_FILE_PATH__, x+1, yi+1, titles[yi], formats[yi])
cmd = cmd[:-2]
self.g_write(cmd)
self.setKey(True)
def splot(self, data, x, y, z, titles='', format='w l'):
"""
Plot a surface data[z] vs data[y] vs data[x] where:
- *data* the data array
- *x* x column index
- *y* y column index
- *z* z column index
- *titles* is the surface key
- *format* is the GnuPlot format string (default='w l')
Format can also be the *CommonStyle* 'lines' or 'points'.
"""
if format in list(self.CommonStyleDefs.keys()):
format = self.CommonStyleDefs[format]
if titles == '':
titles = []
else:
assert len(titles) == data.shape[1], '\nTitle list must match number of columns'
if format == '':
format = 'w l'
self.splotSurfaces(data, x, y, [z], titles, [format]*data.shape[1])
def splotSurfaces(self, data, x, y, z=[], titles=[], formats=['w l']):
"""
Plot data[z1, z2, ] vs data[y] vs data[x] where:
- *data* the data array
- *x* x column index
- *y* y column index
- *z* list of z column indexes, if empty all of z not including x, y are plotted
- *titles* is a list of surface keys, if empty Surf1, Surf2, Surf3 is used
- *formats* is a list (per line) of GnuPlot format strings (default='w l').
If *formats* only contains a single item, this format is used for all surface and
can also be the *CommonStyle* 'lines' or 'points'.
"""
self.g_file_write_array3D(data, yaxis=y, dfmt=self.DATF_FORMAT)
if len(z) == 0:
z = list(range(data.shape[1]))
if len(formats) != 1 and len(formats) != data.shape[1]:
print("len(titles) must be one or equal the number data columns (%s) using: %s" % (data.shape[1], formats[-1]))
formats = [formats[-1]]
elif formats[0] == '' or formats[0] == None:
formats = ['w l']
if len(formats) == 1 and data.shape[1] > 1:
formats = data.shape[1]*formats
cFormats = list(self.CommonStyleDefs.keys())
for f in range(len(formats)):
if formats[f] in cFormats:
formats[f] = self.CommonStyleDefs[formats[f]]
if len(titles) == 0:
titles = ['col%s' % (s+1) for s in range(data.shape[1])]
cmd = '''splot '''
for zi in z:
if zi not in (x,y):
cmd += '''"%s" u %s:%s:%s t "%s" %s, ''' % (self.__DATA_FILE_PATH__, x+1, y+1, zi+1, titles[zi], formats[zi])
cmd = cmd[:-2]
print(cmd)
self.g_write(cmd)
self.setKey(True)
def save(self, name, directory=None, dfmt=None):
"""
Save the last plot as a GnuPlot file *name*.plt which references
*name*.dat.
- *name* the name of the GnuPlot plt and and datafile
- *directory* (optional) the directory to use (defaults to working directory)
- *dfmt* is ignored and uses the value of self.DATF_FORMAT
"""
if directory != None:
out_n = os.path.join(directory, name)
else:
out_n = os.path.join(self.__WORK_DIR__, name)
self.g_write('save "%s.plt"' % out_n)
shutil.copy(os.path.join(self.__WORK_DIR__, self.__DATA_FILE_NAME__), "%s.dat" % out_n)
F = open('%s.plt'% out_n, 'r')
fnew = F.read().replace('_gnuplot.dat','%s.dat' % name)
fnew = fnew.replace('noequal_axes','') # fixes the "noequal_axes" bug in gnuplot save
fnew = fnew.replace('#!/gnuplot','#!/gnuplot\n#\n# Plot created using PySCeS %s (http://pysces.sourceforge.net)' % __version__) # fixes the "noequal_axes" bug in gnuplot save
F.close()
F = open('%s.plt'% out_n, 'w')
F.write(fnew)
F.flush()
F.close()
def replot(self):
"""
Replot the current GnuPlot plot
"""
self.g_write('replot')
self.g_pause()
def replotAndWait(self, seconds=0.5):
"""
Replot the current GnuPlot plot and wait default (*seconds* = 0.5)
or until enter is pressed (*seconds* = -1)
"""
self.replot()
self.wait(seconds)
def setLogScale(self, axis):
"""
Set axis to logscale where:
- *axis* = x, y, z, xy, xz, yz, zyx
"""
axout = self.axisInputStringToList(axis)
axstr = ''
for s in axout:
if s != None:
axstr += s
self.set('logscale', axstr)
def setNoLogScale(self, axis):
"""
Set axis to a linear scale where:
- *axis* = x, y, z, xy, xz, yz, zyx
"""
axout = self.axisInputStringToList(axis)
axstr = ''
for s in axout:
if s != None:
axstr += s
self.unset('logscale', axstr)
def setRange(self, axis, min=None, max=None):
"""
Set axis range where:
- *axis* = x, y, z, xy, xz, yz, zyx
- *min* = range(s) lower bound (default=None) autoscale
- *max* = range(s) upper bound (default=None) autoscale
If only the *axis* argument is provided, GnuPlot will autoscale the
ranges to the data.
"""
axout = self.axisInputStringToList(axis)
if min == None:
min = '*'
else:
min = '%s' % min
if max == None:
max = '*'
else:
max = '%s' % max
for ax in axout:
if ax != None:
self.set('%srange' % ax, '[ %s : %s ]' % (min,max))
def setGrid(self, value):
"""
Display or remove graph grid.
- *value* (boolean) True (on) or False (off)
"""
if value:
self.set('grid')
else:
self.unset('grid')
def setGraphTitle(self, title='PySCeS Plot'):
"""
Set the graph title, unset if title argument is None
- *title* (string, default='PySCeS Plot') the graph title
"""
if title == None:
self.unset('title')
else:
self.set('title', '\"%s\"' % title)
def setKey(self, value=False):
"""
Enable or disable the current plot key, no arguments removes key.
- *value* boolean (default = False)
"""
if value:
self.set('key')
else:
self.unset('key')
def setAxisLabel(self, axis, label=''):
"""
Set the axis label:
- *axis* = x, y, z, xy, xz, yz, zyx
- *label* = string (default='')
Called with only the axis argument clears the axis label.
"""
axout = self.axisInputStringToList(axis)
for ax in axout:
if ax != None:
self.set('%slabel \"%s\"' % (ax, label))
def export(self, name, directory=None, type='png'):
"""
Export the current plot as a <format> file.
- *filename* the filename
- *directory* optional (default = current working directory)
- *type* the file format (default='png').
Currently only PNG is guaranteed to be available in all interfaces.
"""
imgPath = None
if type.lower() == 'png':
if name[-4:] != '.%s' % type:
name += '.%s' % type
if directory!=None and os.path.exists(directory):
imgPath = os.path.join(directory, name)
else:
imgPath = os.path.join(os.getcwd(), name)
if imgPath != None and type in list(self.Terminals.keys()):
self.set('output', '\"%s\"' % imgPath)
self.setTerminal(type, self.Terminals[type])
self.replot()
self.set('output')
self.setTerminal(self.__DISP_TERMINAL__, self.Terminals[self.__DISP_TERMINAL__])
print('Image exported as \"%s\"' % imgPath)
else:
print('Image not exported as type \"%s\"' % type)
def setDataFileNumberFormat(self, format='%.8e'):
"""
Sets the format string for data written to file
- *format* format string (default='%.8e')
"""
print('GnuPlot array data will be written as %s' % format % 0.123456789)
self.DATF_FORMAT = format
def setTerminal(self, name, options=''):
"""
Sets the terminal, gnuplot: set terminal *name* *options*
"""
self.set('terminal', '%s %s' % (name, options))
def setMultiplot(self):
"""
Begin a multiplot session
"""
self.__MULTIPLOT__ = True
self.set("multiplot")
def unsetMultiplot(self):
"""
End a multiplot session.
"""
self.__MULTIPLOT__ = False
self.unset("multiplot")
def setSize(self, width=1.0, height=1.0):
"""
Set the size of the next plot relative to the GnuPlot canvas (e.g. screen)
size which is defined to be 1. For example if ``width = height = 0.5`` the
plot is 1/4 the size of the viewable canvas. If no arguments are supplied
reset size to 1,1.
- *width* of next plot (default = 1.0)
- *height* of next plot (default = 1.0)
"""
self.set("size", "%s,%s" % (width, height))
def setOrigin(self, xpos=0, ypos=0):
"""
Set the origin (lower left corner) of the next plot. Uses GnuPlot
screen coordinates. If no arguments are supplied reset origin to 0,0.
- *xpos* of next plot (default = 0)
- *ypos* of next plot (default = 0)
"""
self.set("origin", "%s,%s" % (xpos, ypos))
def setSizeAndOrigin(self, width=1, height=1, xpos=0, ypos=0):
"""
Set the size and origin of the next plot. If no arguments
are supplied, reset the size to 1,1 and origin to 0.0
- *width* of next plot (default = 1.0)
- *height* of next plot (default = 1.0)
- *xpos* of next plot (default = 0)
- *ypos* of next plot (default = 0)
"""
self.setSize(width, height)
self.setOrigin(xpos, ypos)
class MatplotlibUPI(PlotBase):
"""
Refactored Matplotlib backend to the Unified Plotting Interface
- *work_dir* (optional) working directory
"""
__MODE_INTERACTIVE__ = True
__MODE_NEW_FIGURE__ = True
__FIGURE_GENERATOR__ = None
__CURRENT_FIGURE__ = None
__MODE_HOLD__ = False
MAX_OPEN_WINDOWS = 10
__ARRAY_DATA__ = None
__WORK_DIR__ = None
pyplot = None
#__ENABLE_HTML5__ = False
CommonStyleDefs = {'points' : 'o',
'lines' : '-'
}
__BACKENDS__ = ('GTK', 'GTKAgg', 'GTKCairo', 'FltkAgg', 'MacOSX', 'QtAgg', 'Qt4Agg', 'TkAgg', 'WX', 'WXAgg', 'CocoaAgg',\
'agg', 'nbAgg', 'cairo', 'emf', 'gdk', 'pdf', 'ps', 'svg', 'template')
__INTERACTIVE_BACKENDS__ = ['GTK', 'GTKAgg', 'GTKCairo', 'FltkAgg', 'MacOSX', 'QtAgg', 'Qt4Agg', 'TkAgg', 'WX', 'WXAgg',\
'CocoaAgg', 'nbAgg']
__BACKEND__ = None
def __init__(self, work_dir=None, backend=None):
if work_dir != None and os.path.exists(work_dir):
self.__WORK_DIR__ = work_dir
else:
self.__WORK_DIR__ = os.getcwd()
try:
import matplotlib
if self.isnotebook():
backend='nbAgg'
import pysces
pysces.__MATPLOTLIB_BACKEND__ = 'nbAgg'
if backend in self.__INTERACTIVE_BACKENDS__:
matplotlib.use(backend)
self.__BACKEND__ = backend
if not __SILENT_START__:
print(('Matplotlib backend set to: \"{}\"'.format(backend)))
else:
if backend == 'native':
print(('Using natively configured Matplotlib backend: \"{}\"'.format(matplotlib.get_backend())))
self.__BACKEND__ = matplotlib.get_backend()
else:
matplotlib.use('TkAgg')
self.__BACKEND__ = 'TkAgg'
print(('Matplotlib \"{}\" backend not set, defaulting to: \"{}\"'.format(backend, 'TkAgg')))
#if self.__ENABLE_HTML5__:
#matplotlib.use('module://mplh5canvas.backend_h5canvas') # HTML5
#else:
#matplotlib.use('TKagg', warn=False)
except Exception as ex:
print(ex)
print("\nPySCeS defaults to matplotlib's TKagg backend if not specified \
in the user configuration file, set \"matplotlib_backend = <backend>\" ")
from matplotlib import pyplot
from matplotlib import pylab
## self.pyplot = pyplot
self.pyplot = pylab
if self.__MODE_INTERACTIVE__: self.pyplot.ion()
self._setNewFigureGenerator(self.MAX_OPEN_WINDOWS)
def isnotebook(self):
try:
shell = get_ipython().__class__.__name__
if shell == 'ZMQInteractiveShell':
return True # Jupyter notebook or qtconsole
elif shell == 'TerminalInteractiveShell':
return False # Terminal running IPython
else:
return False # Other type (?)
except NameError:
return False # Probably standard Python interpreter
def _setNewFigureGenerator(self, num):
"""
Create a figure_generator with range [1,num+1]
"""
self.__FIGURE_GENERATOR__ = itertools.cycle(list(range(1,num+1)))
self.MAX_OPEN_WINDOWS = num
def _setActiveFigure(self, fignum):
self.__CURRENT_FIGURE__ = self.pyplot.figure(fignum)
def _setNewFigure(self):
self._setActiveFigure(next(self.__FIGURE_GENERATOR__))
def closeAll(self):
"""
Close all open matplotlib figures.
"""
for x in range(self.MAX_OPEN_WINDOWS):
self.pyplot.close()
def hold(self, hold=False):
"""
Enable plot holding where each new graph is plotted on top of
the previous one.
- *hold* boolean (default = False)
"""
if hold:
self.__MODE_NEW_FIGURE__ = False
self.__MODE_HOLD__ = True
else:
self.__MODE_NEW_FIGURE__ = True
self.__MODE_HOLD__ = False
def plot(self, data, x, y, title='', format='-'):
"""
Plot a single line data[y] vs data[x] where:
- *data* the data array
- *x* x column index
- *y* y column index
- *title* is the line key
- *format* is the Matplotlib format string (default='-')
Format can also be the *CommonStyle* 'lines' or 'points'.
"""
if format in list(self.CommonStyleDefs.keys()):
format = self.CommonStyleDefs[format]
if title == '':
title = []
else:
title = data.shape[1]*[title]
#print(title)
self.plotLines(data, x, [y], title, [format]*data.shape[1])
def plotLines(self, data, x, y=[], titles=[], formats=['-']):
"""
Plot a multiple lines data[y1, y2, ] vs data[x] where:
- *data* the data array
- *x* x column index
- *y* is a list of line indexes
- *titles* is a list of line keys
- *formats* is a list (per line) of Matplotlib format strings.
If *formats* only contains a single item, this format is used for all lines
and can also be the *CommonStyle* 'lines' or 'points'.
"""
self.__ARRAY_DATA__ = data
if self.__MODE_NEW_FIGURE__:
self._setNewFigure()
if not self.__MODE_HOLD__: self.pyplot.clf()
if len(y) == 0:
y = list(range(self.__ARRAY_DATA__.shape[1]))
y.pop(x)
if len(formats) != 1 and len(formats) != data.shape[1]:
print("len(titles) must be one or equal the number data columns (%s) using: \"%s\"" % (data.shape[1], formats[-1]))
formats = [copy.copy(formats[-1])]
elif formats[0] == '' or formats[0] == None:
formats = ['-']
if len(formats) == 1 and data.shape[1] > 1:
formats = data.shape[1]*formats
cFormats = list(self.CommonStyleDefs.keys())
for f in range(len(formats)):
if formats[f] in cFormats:
formats[f] = self.CommonStyleDefs[formats[f]]
if len(titles) == 0:
titles = ['col%s' % (l) for l in range(data.shape[1])]
self.pyplot.ioff()
for yi in y:
#print(self.__ARRAY_DATA__.take([x],axis=1))
#print(self.__ARRAY_DATA__.take([yi],axis=1))
self.pyplot.plot(self.__ARRAY_DATA__.take([x],axis=1), self.__ARRAY_DATA__.take([yi],axis=1), formats[yi], label=titles[yi])
if self.__MODE_INTERACTIVE__: self.pyplot.ion()
self.pyplot.legend()
#if self.__ENABLE_HTML5__:
#self.pyplot.show()
def setLogScale(self, axis):
"""
Set axis to logscale where:
- *axis* = x, y, z, xy, xz, yz, zyx
"""
axout = self.axisInputStringToList(axis)
A = self.pyplot.gca()
for ax in axout:
if ax != None and ax in ['x','y']:
getattr(A, 'set_%sscale' % ax)('log')
if self.__MODE_INTERACTIVE__: self.pyplot.draw()
def setNoLogScale(self, axis):
"""
Set axis to a linear scale where:
- *axis* = x, y, z, xy, xz, yz, zyx
"""
axout = self.axisInputStringToList(axis)
A = self.pyplot.gca()
for ax in axout:
if ax != None and ax in ['x','y']:
getattr(A, 'set_%sscale' % ax)('linear')
if self.__MODE_INTERACTIVE__: self.pyplot.draw()
def setRange(self, axis, min=None, max=None):
"""
Set axis range where
- *axis* = x, y, z, xy, xz, yz, zyx
- *min* = range(s) lower bound (default=None) autoscale
- *max* = range(s) upper bound (default=None) autoscale
"""
axout = self.axisInputStringToList(axis)
for ax in axout:
if ax != None and ax in ['x','y']:
getattr(self.pyplot, '%slim' % ax)(min, max)
## if self.__MODE_INTERACTIVE__: self.pyplot.draw()
def setGrid(self, value):
"""
Display or remove graph grid.
- *value* (boolean) True (on) or False (off)
"""
self.pyplot.grid(value)
def setGraphTitle(self, title='PySCeS Plot'):
"""
Set the graph title, unset if title=None
- *title* (string, default='PySCeS Plot') the graph title
"""
self.pyplot.title(title)
def setKey(self, value=False):
"""
Enable or disable the current plot key, no arguments removes key.
- *value* boolean (default = False)
"""
L = self.pyplot.gca().get_legend()
if value:
L._visible = True
else:
L._visible = False
if self.__MODE_INTERACTIVE__: self.pyplot.draw()
def setAxisLabel(self, axis, label=''):
"""
Set the axis label:
- *axis* = x, y, z, xy, xz, yz, zyx
- *label* = string (default='')
Called with only the axis argument clears the axis label.
"""
axout = self.axisInputStringToList(axis)
for ax in axout:
if ax in ['x','y']:
getattr(self.pyplot, '%slabel' % ax)(label)
def save(self, name, directory=None, dfmt='%.8e'):
"""
Save the plot data to
- *filename* the filename
- *directory* optional (default = current working directory)
- *dfmt* the data format string (default='%.8e')
"""
if directory != None:
out_n = os.path.join(directory, name)
else:
out_n = os.path.join(self.__WORK_DIR__, name)
numpy.savetxt(out_n, self.__ARRAY_DATA__, fmt=dfmt, delimiter=' ')
print('Data saved as \"%s\"' % out_n)
def export(self, name, directory=None, type='png'):
"""
Export the current plot as a <format> file.
- *filename* the filename