-
Notifications
You must be signed in to change notification settings - Fork 12
/
_plotting_mess.py
1298 lines (1011 loc) · 39.7 KB
/
_plotting_mess.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
import os as _os
import pylab as _pylab
import numpy as _n
import itertools as _itertools
import time as _time
import spinmob as _s
try: from . import _functions as _fun
except: import _functions as _fun
try: from . import _pylab_tweaks as _pt
except: import _pylab_tweaks as _pt
from . import _data as _data
try: from . import _data as _data
except: import _data as _data
# expose all the eval statements to all the functions in numpy
from numpy import *
from scipy.special import *
# handle for the colormap so it doesn't immediately close
_colormap = None
def _get_standard_title():
"""
Gets the standard title.
"""
title = 'Plot created ' + _time.asctime()
# Try to add the last command to the title.
try:
command = _fun.get_shell_history() # list(get_ipython().history_manager.get_range())[-1][2]
# Get the path of the runfile()
if command[0:8] == 'runfile(':
def f(*a, **kw): return a[0]
command = eval('f'+command[7:], dict(f=f))
# Just the last line
command = command.replace('\n', '; ')
title = title + '\n' + command
except: pass
return title
def _draw():
""" Method for interactive drawing used by all plotters at the end."""
_pylab.ion()
_pylab.draw()
_pylab.show() # This command always raises the figure, unfortunately, and is needed to see it on the first plot.
def complex_data(data, edata=None, draw=True, **kwargs):
"""
Plots the imaginary vs real for complex data.
Parameters
----------
data
Array of complex data
edata=None
Array of complex error bars
draw=True
Draw the plot after it's assembled?
See spinmob.plot.xy.data() for additional optional keyword arguments.
"""
_pylab.ioff()
# generate the data the easy way
try:
rdata = _n.real(data)
idata = _n.imag(data)
if edata is None:
erdata = None
eidata = None
else:
erdata = _n.real(edata)
eidata = _n.imag(edata)
# generate the data the hard way.
except:
rdata = []
idata = []
if edata is None:
erdata = None
eidata = None
else:
erdata = []
eidata = []
for n in range(len(data)):
rdata.append(_n.real(data[n]))
idata.append(_n.imag(data[n]))
if not edata is None:
erdata.append(_n.real(edata[n]))
eidata.append(_n.imag(edata[n]))
if 'xlabel' not in kwargs: kwargs['xlabel'] = 'Real'
if 'ylabel' not in kwargs: kwargs['ylabel'] = 'Imaginary'
xy_data(rdata, idata, eidata, erdata, draw=False, **kwargs)
if draw: _draw()
def complex_databoxes(ds, script='d[1]+1j*d[2]', escript=None, **kwargs):
"""
Uses databoxes and specified script to generate data and send to
spinmob.plot.complex_data()
Parameters
----------
ds
List of databoxes
script='d[1]+1j*d[2]'
Complex-valued script for data array.
escript=None
Complex-valued script for error bars
See spinmob.plot.complex.data() for additional optional keyword arguments.
See spinmob.data.databox.execute_script() for more information about scripts.
"""
datas = []
labels = []
if escript is None: errors = None
else: errors = []
for d in ds:
datas.append(d(script))
labels.append(_os.path.split(d.path)[-1])
if not escript is None: errors.append(d(escript))
complex_data(datas, errors, label=labels, **kwargs)
if "draw" in kwargs and not kwargs["draw"]: return
_pylab.ion()
_pylab.draw()
_pylab.show()
return ds
def complex_files(script='d[1]+1j*d[2]', escript=None, paths=None, **kwargs):
"""
Loads files and plots complex data in the real-imaginary plane.
Parameters
----------
script='d[1]+1j*d[2]'
Complex-valued script for data array.
escript=None
Complex-valued script for error bars
paths=None
List of paths to open. None means use a dialog
See spinmob.plot.complex.data() for additional optional keyword arguments.
See spinmob.data.databox.execute_script() for more information about scripts.
Common additional parameters
----------------------------
filters="*.*"
Set the file filters for the dialog.
"""
ds = _data.load_multiple(paths=paths)
if len(ds) == 0: return
if 'title' not in kwargs: kwargs['title'] = _os.path.split(ds[0].path)[0]
return complex_databoxes(ds, script=script, **kwargs)
def complex_function(f='1.0/(1+1j*x)', xmin=-1, xmax=1, steps=200, p='x', g=None, erange=False, **kwargs):
"""
Plots function(s) in the complex plane over the specified range.
Parameters
----------
f='1.0/(1+1j*x)'
Complex-valued function or list of functions to plot.
These can be string functions or single-argument python functions;
additional globals can be supplied by g.
xmin=-1, xmax=1, steps=200
Range over which to plot and how many points to plot
p='x'
If using strings for functions, p is the independent parameter name.
g=None
Optional dictionary of extra globals. Try g=globals()!
erange=False
Use exponential spacing of the x data?
See spinmob.plot.xy.data() for additional optional keyword arguments.
"""
kwargs2 = dict(xlabel='Real', ylabel='Imaginary')
kwargs2.update(kwargs)
function(f, xmin, xmax, steps, p, g, erange, plotter=xy_data, complex_plane=True, draw=True, **kwargs2)
def magphase_data(xdata, ydata, eydata=None, exdata=None, xscale='linear', mscale='linear', pscale='linear', mlabel='Magnitude', plabel='Phase', phase='degrees', figure='gcf', clear=1, draw=True, **kwargs):
"""
Plots the magnitude and phase of complex ydata vs xdata.
Parameters
----------
xdata
Real-valued x-axis data
ydata
Complex-valued y-axis data
eydata=None
Complex-valued y-error
exdata=None
Real-valued x-error
xscale='linear'
'log' or 'linear' scale of the x axis
mscale='linear'
'log' or 'linear' scale of the magnitude axis
pscale='linear'
'log' or 'linear' scale of the phase axis
mlabel='Magnitude'
y-axis label for magnitude plot
plabel='Phase'
y-axis label for phase plot
phase='degrees'
'degrees' or 'radians' for the phase axis
figure='gcf'
Plot on the specified figure instance or 'gcf' for current figure.
clear=1
Clear the figure?
draw=True
Draw the figure when complete?
See spinmob.plot.xy.data() for additional optional keyword arguments.
"""
_pylab.ioff()
# set up the figure and axes
if figure == 'gcf': f = _pylab.gcf()
if clear: f.clear()
axes1 = _pylab.subplot(211)
axes2 = _pylab.subplot(212,sharex=axes1)
# Make sure the dimensionality of the data sets matches
xdata, ydata = _fun._match_data_sets(xdata, ydata)
exdata = _fun._match_error_to_data_set(xdata, exdata)
eydata = _fun._match_error_to_data_set(ydata, eydata)
# convert to magnitude and phase
m = []
p = []
em = []
ep = []
# Note this is a loop over data sets, not points.
for l in range(len(ydata)):
m.append(_n.abs(ydata[l]))
p.append(_n.angle(ydata[l]))
# get the mag - phase errors
if eydata[l] is None:
em.append(None)
ep.append(None)
else:
er = _n.real(eydata[l])
ei = _n.imag(eydata[l])
em.append(0.5*((er+ei) + (er-ei)*_n.cos(p[l])) )
ep.append(0.5*((er+ei) - (er-ei)*_n.cos(p[l]))/m[l] )
# convert to degrees
if phase=='degrees':
p[-1] = p[-1]*180.0/_n.pi
if not ep[l] is None:
ep[l] = ep[l]*180.0/_n.pi
if phase=='degrees': plabel = plabel + " (degrees)"
else: plabel = plabel + " (radians)"
if 'xlabel' in kwargs: xlabel=kwargs.pop('xlabel')
else: xlabel=''
if 'ylabel' in kwargs: kwargs.pop('ylabel')
if 'autoformat' not in kwargs: kwargs['autoformat'] = True
autoformat = kwargs['autoformat']
kwargs['autoformat'] = False
kwargs['xlabel'] = ''
xy_data(xdata, m, em, exdata, ylabel=mlabel, axes=axes1, clear=0, xscale=xscale, yscale=mscale, draw=False, **kwargs)
kwargs['autoformat'] = autoformat
kwargs['xlabel'] = xlabel
xy_data(xdata, p, ep, exdata, ylabel=plabel, axes=axes2, clear=0, xscale=xscale, yscale=pscale, draw=False, **kwargs)
axes2.set_title('')
if draw: _draw()
def magphase_databoxes(ds, xscript=0, yscript='d[1]+1j*d[2]', eyscript=None, exscript=None, g=None, **kwargs):
"""
Use databoxes and scripts to generate data and plot the complex magnitude
and phase versus xdata.
Parameters
----------
ds
List of databoxes
xscript=0
Script for x data
yscript='d[1]+1j*d[2]'
Script for y data
eyscript=None
Script for y error
exscript=None
Script for x error
g=None
Optional dictionary of globals for the scripts
See spinmob.plot.magphase.data() for additional optional keyword arguments.
See spinmob.data.databox.execute_script() for more information about scripts.
"""
databoxes(ds, xscript, yscript, eyscript, exscript, plotter=magphase_data, g=g, **kwargs)
def magphase_files(xscript=0, yscript='d[1]+1j*d[2]', eyscript=None, exscript=None, paths=None, g=None, **kwargs):
"""
This will load a bunch of data files, generate data based on the supplied
scripts, and then plot the ydata's magnitude and phase versus xdata.
Parameters
----------
xscript=0
Script for x data
yscript='d[1]+1j*d[2]'
Script for y data
eyscript=None
Script for y error
exscript=None
Script for x error
paths=None
List of paths to open.
g=None
Optional dictionary of globals for the scripts
See spinmob.plot.magphase.data() for additional optional arguments.
See spinmob.data.databox.execute_script() for more information about scripts.
Common additional parameters
----------------------------
filters="*.*"
Set the file filters for the dialog.
"""
return files(xscript, yscript, eyscript, exscript, plotter=magphase_databoxes, paths=paths, g=g, **kwargs)
def magphase_function(f='1.0/(1+1j*x)', xmin=-1, xmax=1, steps=200, p='x', g=None, erange=False, **kwargs):
"""
Plots function(s) magnitude and phase over the specified range.
Parameters
----------
f='1.0/(1+1j*x)'
Complex-valued function or list of functions to plot.
These can be string functions or single-argument python functions;
additional globals can be supplied by g.
xmin=-1, xmax=1, steps=200
Range over which to plot and how many points to plot
p='x'
If using strings for functions, p is the independent parameter name.
g=None
Optional dictionary of extra globals. Try g=globals()!
erange=False
Use exponential spacing of the x data?
See spinmob.plot.xy.data() for additional optional keyword arguments.
"""
function(f, xmin, xmax, steps, p, g, erange, plotter=magphase_data, **kwargs)
def realimag_data(xdata, ydata, eydata=None, exdata=None, xscale='linear', rscale='linear', iscale='linear', rlabel='Real', ilabel='Imaginary', figure='gcf', clear=1, draw=True, **kwargs):
"""
Plots the real and imaginary parts of complex ydata vs xdata.
Parameters
----------
xdata
Real-valued x-axis data
ydata
Complex-valued y-axis data
eydata=None
Complex-valued y-error
exdata=None
Real-valued x-error
xscale='linear'
'log' or 'linear' scale of the x axis
rscale='linear'
'log' or 'linear' scale of the real axis
iscale='linear'
'log' or 'linear' scale of the imaginary axis
rlabel='Magnitude'
y-axis label for real value plot
ilabel='Phase'
y-axis label for imaginary value plot
figure='gcf'
Plot on the specified figure instance or 'gcf' for current figure.
clear=1
Clear the figure?
draw=True
Draw the figure when completed?
See spinmob.plot.xy.data() for additional optional keyword arguments.
"""
_pylab.ioff()
# Make sure the dimensionality of the data sets matches
xdata, ydata = _fun._match_data_sets(xdata, ydata)
exdata = _fun._match_error_to_data_set(xdata, exdata)
eydata = _fun._match_error_to_data_set(ydata, eydata)
# convert to real imag, and get error bars
rdata = []
idata = []
erdata = []
eidata = []
for l in range(len(ydata)):
rdata.append(_n.real(ydata[l]))
idata.append(_n.imag(ydata[l]))
if eydata[l] is None:
erdata.append(None)
eidata.append(None)
else:
erdata.append(_n.real(eydata[l]))
eidata.append(_n.imag(eydata[l]))
# set up the figure and axes
if figure == 'gcf': f = _pylab.gcf()
if clear: f.clear()
axes1 = _pylab.subplot(211)
axes2 = _pylab.subplot(212,sharex=axes1)
if 'xlabel' in kwargs : xlabel=kwargs.pop('xlabel')
else: xlabel=''
if 'ylabel' in kwargs : kwargs.pop('ylabel')
if 'tall' not in kwargs: kwargs['tall'] = False
if 'autoformat' not in kwargs: kwargs['autoformat'] = True
autoformat = kwargs['autoformat']
kwargs['autoformat'] = False
kwargs['xlabel'] = ''
xy_data(xdata, rdata, eydata=erdata, exdata=exdata, ylabel=rlabel, axes=axes1, clear=0, xscale=xscale, yscale=rscale, draw=False, **kwargs)
kwargs['autoformat'] = autoformat
kwargs['xlabel'] = xlabel
xy_data(xdata, idata, eydata=eidata, exdata=exdata, ylabel=ilabel, axes=axes2, clear=0, xscale=xscale, yscale=iscale, draw=False, **kwargs)
axes2.set_title('')
if draw: _draw()
def realimag_databoxes(ds, xscript=0, yscript="d[1]+1j*d[2]", eyscript=None, exscript=None, g=None, **kwargs):
"""
Use databoxes and scripts to generate data and plot the real and
imaginary ydata versus xdata.
Parameters
----------
ds
List of databoxes
xscript=0
Script for x data
yscript='d[1]+1j*d[2]'
Script for y data
eyscript=None
Script for y error
exscript=None
Script for x error
g=None
Optional dictionary of globals for the scripts
See spinmob.plot.realimag.data() for additional optional keyword arguments.
See spinmob.data.databox.execute_script() for more information about scripts.
"""
databoxes(ds, xscript, yscript, eyscript, exscript, plotter=realimag_data, g=g, **kwargs)
def realimag_files(xscript=0, yscript="d[1]+1j*d[2]", eyscript=None, exscript=None, paths=None, g=None, **kwargs):
"""
This will load a bunch of data files, generate data based on the supplied
scripts, and then plot the ydata's real and imaginary parts versus xdata.
Parameters
----------
xscript=0
Script for x data
yscript='d[1]+1j*d[2]'
Script for y data
eyscript=None
Script for y error
exscript=None
Script for x error
paths=None
List of paths to open.
g=None
Optional dictionary of globals for the scripts
See spinmob.plot.realimag.data() for additional optional arguments.
See spinmob.data.databox.execute_script() for more information about scripts.
Common additional parameters
----------------------------
filters="*.*"
Set the file filters for the dialog.
"""
return files(xscript, yscript, eyscript, exscript, plotter=realimag_databoxes, paths=paths, g=g, **kwargs)
def realimag_function(f='1.0/(1+1j*x)', xmin=-1, xmax=1, steps=200, p='x', g=None, erange=False, **kwargs):
"""
Plots function(s) real and imaginary parts over the specified range.
Parameters
----------
f='1.0/(1+1j*x)'
Complex-valued function or list of functions to plot.
These can be string functions or single-argument python functions;
additional globals can be supplied by g.
xmin=-1, xmax=1, steps=200
Range over which to plot and how many points to plot
p='x'
If using strings for functions, p is the independent parameter name.
g=None
Optional dictionary of extra globals. Try g=globals()!
erange=False
Use exponential spacing of the x data?
See spinmob.plot.xy.data() for additional optional keyword arguments.
"""
function(f, xmin, xmax, steps, p, g, erange, plotter=realimag_data, **kwargs)
def xy_data(xdata, ydata, eydata=None, exdata=None, label=None, xlabel='', ylabel='', \
title='', shell_history=0, xshift=0, yshift=0, xshift_every=1, yshift_every=1, \
coarsen=0, style=None, clear=True, axes=None, xscale='linear', yscale='linear', grid=False, \
legend='best', legend_max=20, autoformat=True, autoformat_window=True, tall=False, draw=True, **kwargs):
"""
Plots specified data.
Parameters
----------
xdata, ydata
Arrays (or arrays of arrays) of data to plot. You can also
specify None for one of these, which will result in a plot
versus the data point number (starting from zero). Or you can
specify a number (alone, generally not in a list) to set the
scale of the auto-generated data.
eydata=None, exdata=None
Arrays of x and y errorbar values
label=None
String or array of strings for the line labels
xlabel=''
Label for the x-axis
ylabel=''
Label for the y-axis
title=''
Title for the axes; set to None to have nothing.
shell_history=0
How many commands from the pyshell history to include with the title
xshift=0, yshift=0
Progressive shifts on the data, to make waterfall plots
xshift_every=1
Perform the progressive shift every 1 or n'th line. Set to 0 or False
to shift all the curves by the same amount.
yshift_every=1
perform the progressive shift every 1 or n'th line. Set to 0 or False
to shift all the curves by the same amount.
style=None
style cycle object.
clear=True
If no axes are specified (see below), clear the figure, otherwise clear just the axes.
axes=None
Which matplotlib axes to use, or "gca" for the current axes
xscale='linear', yscale='linear'
'linear' or 'log' x and y axis scales.
grid=False
Should we draw a grid on the axes?
legend='best'
Where to place the legend (see pylab.legend() for options)
Set this to None to ignore the legend.
legend_max=20
Number of legend entries before it's truncated with '...'
autoformat=True
Should we format the figure for printing?
autoformat_window=True
Should we resize and reposition the window when autoformatting?
tall=False
Should the format be tall?
draw=True
Whether or not to draw the plot and raise the figure after plotting.
See matplotlib's errorbar() function for additional optional keyword arguments.
"""
_pylab.ioff()
# Make sure the dimensionality of the data sets matches
xdata, ydata = _fun._match_data_sets(xdata, ydata)
exdata = _fun._match_error_to_data_set(xdata, exdata)
eydata = _fun._match_error_to_data_set(ydata, eydata)
# check that the labels is a list of strings of the same length
if not _fun.is_iterable(label): label = [label]*len(xdata)
while len(label) < len(ydata): label.append(label[0])
# concatenate if necessary
if len(label) > legend_max:
label[legend_max-2] = '...'
for n in range(legend_max-1,len(label)-1): label[n] = "_nolegend_"
# clear the figure?
if clear and not axes: _pylab.gcf().clear() # axes cleared later
# setup axes
if axes=="gca" or not axes: axes = _pylab.gca()
# if we're clearing the axes
if clear: axes.clear()
# set the current axes
_pylab.axes(axes)
# now loop over the list of data in xdata and ydata
for n in range(0,len(xdata)):
# get the label
if label[n]=='_nolegend_': l = '_nolegend_'
elif len(xdata) > 1: l = str(n)+": "+str(label[n])
else: l = str(label[n])
# calculate the x an y progressive shifts
if xshift_every: dx = xshift*(n/xshift_every)
else: dx = xshift
if yshift_every: dy = yshift*(n/yshift_every)
else: dy = yshift
# if we're supposed to coarsen the data, do so.
x = _fun.coarsen_array(xdata[n], coarsen)
y = _fun.coarsen_array(ydata[n], coarsen)
ey = _fun.coarsen_array(eydata[n], coarsen, 'quadrature')
ex = _fun.coarsen_array(exdata[n], coarsen, 'quadrature')
# update the style
if not style is None: kwargs.update(next(style))
axes.errorbar(x+dx, y+dy, label=l, yerr=ey, xerr=ex, **kwargs)
_pylab.xscale(xscale)
_pylab.yscale(yscale)
if legend: axes.legend(loc=legend)
axes.set_xlabel(xlabel)
axes.set_ylabel(ylabel)
# for some arguments there should be no title.
if title in [None, False, 0]:
axes.set_title('')
# add the commands to the title
else:
title = str(title) + '\n' + _get_standard_title()
axes.set_title(title)
if grid: _pylab.grid(True)
if autoformat:
_pt.format_figure(draw=False, modify_geometry=autoformat_window)
_pt.auto_zoom(axes=axes, draw=False)
# update the canvas
if draw: _draw()
return axes
def xy_databoxes(ds, xscript=0, yscript='d[1]', eyscript=None, exscript=None, g=None, **kwargs):
"""
Use databoxes and scripts to generate and plot ydata versus xdata.
Parameters
----------
ds
List of databoxes
xscript=0
Script for x data
yscript='d[1]'
Script for y data
eyscript=None
Script for y error
exscript=None
Script for x error
g=None
Optional dictionary of globals for the scripts
See spinmob.plot.xy.data() for additional optional keyword arguments.
See spinmob.data.databox.execute_script() for more information about scripts.
"""
databoxes(ds, xscript, yscript, eyscript, exscript, plotter=xy_data, g=g, **kwargs)
def xy_files(xscript=0, yscript='d[1]', eyscript=None, exscript=None, paths=None, g=None, **kwargs):
"""
This will load a bunch of data files, generate data based on the supplied
scripts, and then plot the ydata versus xdata.
Parameters
----------
xscript=0
Script for x data
yscript='d[1]'
Script for y data
eyscript=None
Script for y error
exscript=None
Script for x error
paths=None
List of paths to open.
g=None
Optional dictionary of globals for the scripts
See spinmob.plot.xy.data() for additional optional arguments.
See spinmob.data.databox.execute_script() for more information about scripts.
Common additional parameters
----------------------------
filters="*.*"
Set the file filters for the dialog.
"""
return files(xscript, yscript, eyscript, exscript, plotter=xy_databoxes, paths=paths, g=g, **kwargs)
def xy_function(f='sin(x)', xmin=-1, xmax=1, steps=200, p='x', g=None, erange=False, **kwargs):
"""
Plots function(s) over the specified range.
Parameters
----------
f='sin(x)'
Function or list of functions to plot.
These can be string functions or single-argument python functions;
additional globals can be supplied by g.
xmin=-1, xmax=1, steps=200
Range over which to plot and how many points to plot
p='x'
If using strings for functions, p is the independent parameter name.
g=None
Optional dictionary of extra globals. Try g=globals()!
erange=False
Use exponential spacing of the x data?
See spinmob.plot.xy.data() for additional optional keyword arguments.
"""
function(f, xmin, xmax, steps, p, g, erange, plotter=xy_data, **kwargs)
def databoxes(ds, xscript=0, yscript=1, eyscript=None, exscript=None, g=None, plotter=xy_data, transpose=False, **kwargs):
"""
Plots the listed databox objects with the specified scripts.
ds list of databoxes
xscript script for x data
yscript script for y data
eyscript script for y error
exscript script for x error
plotter function used to do the plotting
transpose applies databox.transpose() prior to plotting
g optional dictionary of globals for the supplied scripts
**kwargs are sent to plotter()
"""
if not _fun.is_iterable(ds): ds = [ds]
if 'xlabel' not in kwargs: kwargs['xlabel'] = str(xscript)
if 'ylabel' not in kwargs: kwargs['ylabel'] = str(yscript)
# First make sure everything is a list of scripts (or None's)
if not _fun.is_iterable(xscript): xscript = [xscript]
if not _fun.is_iterable(yscript): yscript = [yscript]
if not _fun.is_iterable(exscript): exscript = [exscript]
if not _fun.is_iterable(eyscript): eyscript = [eyscript]
# make sure exscript matches shape with xscript (and the same for y)
if len(exscript) < len(xscript):
for n in range(len(xscript)-1): exscript.append(exscript[0])
if len(eyscript) < len(yscript):
for n in range(len(yscript)-1): eyscript.append(eyscript[0])
# Make xscript and exscript match in shape with yscript and eyscript
if len(xscript) < len(yscript):
for n in range(len(yscript)-1):
xscript.append(xscript[0])
exscript.append(exscript[0])
# check for the reverse possibility
if len(yscript) < len(xscript):
for n in range(len(xscript)-1):
yscript.append(yscript[0])
eyscript.append(eyscript[0])
# now check for None's (counting scripts)
for n in range(len(xscript)):
if xscript[n] is None and yscript[n] is None:
print("Two None scripts? But... why?")
return
if xscript[n] is None:
if type(yscript[n])==str: xscript[n] = 'range(len('+yscript[n]+'))'
else: xscript[n] = 'range(len(c('+str(yscript[n])+')))'
if yscript[n] is None:
if type(xscript[n])==str: yscript[n] = 'range(len('+xscript[n]+'))'
else: yscript[n] = 'range(len(c('+str(xscript[n])+')))'
xdatas = []
ydatas = []
exdatas = []
eydatas = []
labels = []
# Loop over all the data boxes
for i in range(len(ds)):
# Reset the default globals
all_globals = dict(n=i,m=len(ds)-1-i)
# Update them with the user-specified globals
if not g==None: all_globals.update(g)
# For ease of coding
d = ds[i]
# Take the transpose if necessary
if transpose: d = d.transpose()
# Generate the x-data; returns a list of outputs, one for each xscript
xdata = d(xscript, all_globals)
# Loop over each xdata, appending to the master list, and generating a label
for n in range(len(xdata)):
xdatas.append(xdata[n])
# Normal data set is a 1d array
labels.append(_os.path.split(d.path)[-1])
# Special case: single-point per file
if _fun.is_a_number(xdata[0]) == 1 and len(ds) > 1:
labels = [_os.path.split(ds[0].path)[-1] + ' - ' + _os.path.split(ds[-1].path)[-1]]
# Append the other data sets to their master lists
for y in d( yscript, all_globals): ydatas.append(y)
for x in d(exscript, all_globals): exdatas.append(x)
for y in d(eyscript, all_globals): eydatas.append(y)
if "label" in kwargs: labels = kwargs.pop("label")
plotter(xdatas, ydatas, eydatas, exdatas, label=labels, **kwargs)
def files(xscript=0, yscript=1, eyscript=None, exscript=None, g=None, plotter=xy_databoxes, paths=None, **kwargs):
"""
This will load a bunch of data files, generate data based on the supplied
scripts, and then plot this data using the specified databox plotter.
xscript, yscript, eyscript, exscript scripts to generate x, y, and errors
g optional dictionary of globals
optional: filters="*.*" to set the file filters for the dialog.
**kwargs are sent to plotter()
"""
if 'delimiter' in kwargs: delimiter = kwargs.pop('delimiter')
else: delimiter = None
if 'filters' in kwargs: filters = kwargs.pop('filters')
else: filters = '*.*'
ds = _data.load_multiple(paths=paths, delimiter=delimiter, filters=filters)
if ds is None or len(ds) == 0: return
# generate a default title (the directory)
if 'title' not in kwargs: kwargs['title']=_os.path.split(ds[0].path)[0]
# run the databox plotter
plotter(ds, xscript=xscript, yscript=yscript, eyscript=eyscript, exscript=exscript, g=g, **kwargs)
return ds
def function(f='sin(x)', xmin=-1, xmax=1, steps=200, p='x', g=None, erange=False, plotter=xy_data, complex_plane=False, **kwargs):
"""
Plots the function over the specified range
f function or list of functions to plot; can be string functions
xmin, xmax, steps range over which to plot, and how many points to plot
p if using strings for functions, p is the parameter name
g optional dictionary of extra globals. Try g=globals()
erange Use exponential spacing of the x data?
plotter function used to plot the generated data
complex_plane plot imag versus real of f?
**kwargs are sent to spinmob.plot.real_imag.data()
"""
if not g: g = {}
# do the opposite kind of update()
for k in list(globals().keys()):
if k not in g: g[k] = globals()[k]
# if the x-axis is a log scale, use erange
steps = int(steps)
if erange: x = _fun.erange(xmin, xmax, steps)
else: x = _n.linspace(xmin, xmax, steps)
# make sure it's a list so we can loop over it
if not type(f) in [type([]), type(())]: f = [f]
# loop over the list of functions
xdatas = []
ydatas = []
labels = []
for fs in f:
# If it's just a number, make a function string
if _fun.is_a_number(fs):
a = eval('lambda ' + p + ': ' + str(fs) + '+0*' + p, g)
a.__name__ = str(fs)
# String function
elif type(fs) == str:
a = eval('lambda ' + p + ': ' + fs, g)
a.__name__ = fs
# Normal function
else:
a = fs
# try directly evaluating
try: y = a(x)
# do it the slow way.
except:
y = []
for z in x: y.append(a(z))
xdatas.append(x)
ydatas.append(y)
labels.append(a.__name__)
if 'xlabel' not in kwargs: kwargs['xlabel'] = p
if 'label' not in kwargs: kwargs['label'] = labels
# plot!
if complex_plane: plotter(_n.real(ydatas),_n.imag(ydatas), **kwargs)
else: plotter(xdatas, ydatas, **kwargs)
def image_data(Z, X=[0,1.0], Y=[0,1.0], aspect=1.0, zmin=None, zmax=None, clear=1, clabel='z', autoformat=True, colormap="Last Used", shell_history=0, **kwargs):
"""
Generates an image plot.
Parameters
----------
Z
2-d array of z-values
X=[0,1.0], Y=[0,1.0]
1-d array of x-values (only the first and last element are used)
See matplotlib's imshow() for additional optional arguments.
"""
global _colormap
# Set interpolation to something more relevant for every day science