-
Notifications
You must be signed in to change notification settings - Fork 6
/
pydvpy.py
4047 lines (3063 loc) · 108 KB
/
pydvpy.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
# Copyright (c) 2011-2023, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory
# Written by Mason Kwiat, Douglas S. Miller, and Kevin Griffin, Edward Rusu
# e-mail: rusu1@llnl.gov
# LLNL-CODE-507071
# All rights reserved.
# This file is part of PDV. For details, see <URL describing code and
# how to download source>. Please also read "Additional BSD Notice".
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# Redistributions of source code must retain the above copyright
# notice, this list of conditions and the disclaimer below.
# Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the disclaimer (as noted below)
# in the documentation and/or other materials provided with the
# distribution. Neither the name of the LLNS/LLNL nor the names of
# its contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL LAWRENCE
# LIVERMORE NATIONAL SECURITY, LLC, THE U.S. DEPARTMENT OF ENERGY OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
# Additional BSD Notice
# 1. This notice is required to be provided under our contract with
# the U.S. Department of Energy (DOE). This work was produced at
# Lawrence Livermore National Laboratory under Contract
# No. DE-AC52-07NA27344 with the DOE.
# 2. Neither the United States Government nor Lawrence Livermore
# National Security, LLC nor any of their employees, makes any
# warranty, express or implied, or assumes any liability or
# responsibility for the accuracy, completeness, or usefulness of any
# information, apparatus, product, or process disclosed, or represents
# that its use would not infringe privately-owned rights.
# 3. Also, reference herein to any specific commercial products,
# process, or services by trade name, trademark, manufacturer or
# otherwise does not necessarily constitute or imply its endorsement,
# recommendation, or favoring by the United States Government or
# Lawrence Livermore National Security, LLC. The views and opinions
# of authors expressed herein do not necessarily state or reflect
# those of the United States Government or Lawrence Livermore National
# Security, LLC, and shall not be used for advertising or product
# endorsement purposes.
"""
A python interface for PyDV functionality.
.. module: pydvpy
.. moduleauthor:: Edward Rusu <rusu1@llnl.gov>
>>> import pydvpy as pydvif
"""
import json
import os
import string
import traceback
import sys
import re
import random as sysrand
from distutils.version import LooseVersion
import numpy as np
import scipy
import scipy.integrate
import scipy.special
import scipy.signal
import scipy.misc
import matplotlib.pyplot as plt
try:
from matplotlib import style
stylesLoaded = True
except:
stylesLoaded = False
try:
from . import curve
except ImportError:
import curve
try:
import pact.pdb as pdb
pdbLoaded = True
except:
pdbLoaded = False
def span(xmin, xmax, numpts=100):
"""
Generates a straight line of slope 1 and y intercept 0 in the specified domain with an optional number
of points.
>>> c = pydvif.span(1, 10)
:param xmin: The minimum x value
:type xmin: float
:param xmax: The maximum x value
:type xmax: float
:param numpts: The number of points used to plot the line
:type numpts: int
:returns: curve -- the curve object representing the straight line.
"""
spacing = (float(xmax) - float(xmin)) / (float(numpts) - 1.0)
fxmin = float(xmin)
x = []
for i in range(numpts):
x.append(fxmin)
fxmin += spacing
x = np.array(x)
y = np.array(x)
c = makecurve(x, y, 'Straight Line')
return c
def makecurve(x, y, name='Curve', fname='', xlabel='', ylabel='', title='', record_id=''):
"""
Generate a curve from two lists of numbers.
>>> c1 = pydvif.makecurve([1, 2, 3, 4], [5, 10, 15, 20])
>>> c2 = pydvif.makecurve([1, 2, 3, 4], [7, 8, 9, 10], 'Line')
:param x: list of x values
:type x: list
:param y: list of y values
:type y: list
:param name: the name of the new curve
:type name: str
:param fname: the name of the file containing this curves data.
:type fname: str
:returns: curve -- the curve generated from the x and y list of values.
"""
if len(x) != len(y):
print(f"Curve {name} doesn't have the same length: len(x)={len(x)} and len(y)={len(y)} ")
name += " !!!ERROR:len(x)!=len(y)!!!"
c = curve.Curve(fname, name, record_id, xlabel, ylabel, title)
c.x = np.array(x, dtype=float)
c.y = np.array(y, dtype=float)
return c
def get_styles():
"""
Get the list of available plot styles.
:return: list -- the list of available style names or an empty list if no styles exist.
"""
if stylesLoaded:
return plt.style.available
return list()
def create_plot(curvelist, **kwargs):
"""
Create a plot from of the curves in curvelist. The available keyword arguments are:
* Filename: fname='myFile'
* Save Format: ftype='pdf'
* Plot Title: title='My Title'
* X-Axis Label: xlabel='X'
* Y-Axis Label: ylabel='Y'
* Show/Hide Plot Legend: legend=True
* Plot Style: stylename='ggplot'
* Show X-Axis in log scale: xls=True
* Show Y-Axis in log scale: yls=True
* Set the width of the figure in inches: fwidth=1.2
* Set the height of the figure in inches: fheight=2.1
>>> curves = pydvif.read('testData.txt')
>>> plot1 = pydvif.create_plot(curves, fname='myPlot1')
>>> plot2 = pydvif.create_plot(curves, fname='myPlot2', ftype='pdf', fwidth=10.1, fheight=11.3, title='My Plot', xlabel='X', ylabel='Y', legend=True, stylename='ggplot')
:param curvelist: The curve or list of curves to plot
:type curvelist: list
:param kwargs: The keyword arguments to modify the plot.
:type kwargs: dict
:return: matplotlib.pyplot -- the plot of the curves
"""
fname = None
ftype = 'png'
title = ''
xlabel = ''
ylabel = ''
legend = False
stylename = 'ggplot'
xls = False
yls = False
fwidth = None
fheight = None
# Process kwargs
for key, val in list(kwargs.items()):
if key == 'fname':
fname = val
elif key == 'ftype':
ftype = val
elif key == 'title':
title = val
elif key == 'xlabel':
xlabel = val
elif key == 'ylabel':
ylabel = val
elif key == 'legend':
legend = val
elif key == 'stylename':
stylename = val
elif key == 'xls':
xls = val
elif key == 'yls':
yls = val
elif key == 'fwidth':
fwidth = val
elif key == 'fheight':
fheight = val
if stylesLoaded:
styles = get_styles()
try:
idx = styles.index(stylename)
style.use(styles[idx])
except:
if len(styles) > 0:
style.use(styles[0])
plt.clf()
plt.cla()
axis = plt.gca()
if(xls):
axis.set_xscale('log', nonposx='clip')
if(yls):
axis.set_yscale('log', nonposy='clip')
curves = list()
if isinstance(curvelist, list):
curves.extend(curvelist)
else:
curves.append(curvelist)
for curve in curves:
if not curve.hidden:
xdat = np.array(curve.x)
ydat = np.array(curve.y)
if(yls):
for i in range(len(ydat)):
if(ydat[i] < 0):
ydat[i] = 1e-301 #custom ydata clipping
if(xls):
for i in range(len(xdat)):
if(xdat[i] < 0):
xdat[i] = 1e-301 #custom xdata clipping
if curve.ebar is not None:
c = plt.errorbar(xdat, ydat, yerr=[curve.ebar[0], curve.ebar[1]], xerr=[curve.ebar[2], curve.ebar[3]], fmt='-')
elif curve.erange is not None:
c = plt.plot(xdat, ydat)
plt.fill_between(xdat, ydat - curve.erange[0], ydat + curve.erange[1], alpha=0.4, color=c[0].get_color())
else:
c = plt.plot(xdat, ydat)
if curve.linespoints:
plt.setp(c[0], marker=curve.marker, markersize=curve.markersize, linestyle=curve.linestyle)
elif curve.scatter:
plt.setp(c[0], marker=curve.marker, markersize=curve.markersize, linestyle=' ')
else:
plt.setp(c[0], linestyle=curve.linestyle)
if curve.linewidth:
plt.setp(c[0], lw=curve.linewidth)
plt.setp(c[0], mew=curve.linewidth)
plt.setp(c[0], label=curve.name)
if curve.color != '':
plt.setp(c, color=curve.color)
else:
curve.color = c[0].get_color()
if curve.dashes is not None:
c[0].set_dashes(curve.dashes)
if legend:
plt.legend(fancybox=True, numpoints=1, loc=1, ncol=1).get_frame().set_alpha(0.5)
plt.xlabel(xlabel)
plt.ylabel(ylabel)
plt.title(title)
# Change figure size
figure = plt.gcf()
if fwidth is not None:
figure.set_figwidth(float(fwidth), True)
if fheight is not None:
figure.set_figheight(float(fheight), True)
if fname is not None:
try:
plt.savefig(fname + '.' + ftype, format=ftype)
except:
print('Error: Could not save image to ' + fname + ' of type ' + ftype)
return plt
def save(fname, curvelist, verbose=False):
"""
Saves the given Curve or list of Curves to a file named fname.
>>> curves = list()
>>> curves.append(pydvif.makecurve([1, 2, 3, 4], [5, 10, 15, 20]))
>>> pydvif.save('myfile.txt', curves) OR
>>> pydvif.save('myfile.txt', curves[0])
:param fname: ULTRA filename
:type fname: str
:param curvelist: The curve or list of curves to save
:type curvelist: Curve or list
:param verbose: prints the error stacktrace when True
:type verbose: bool
"""
curves = list()
if isinstance(curvelist, list):
curves.extend(curvelist)
else:
curves.append(curvelist)
try:
f = open(fname, 'w')
for curve in curves:
f.write('# ' + curve.name + '\n')
for dex in range(len(curve.x)):
f.write(' ' + str(curve.x[dex]) + ' ' + str(curve.y[dex]) + '\n')
except:
print('Error: Can not write to: ' + fname)
if verbose:
traceback.print_exc(file=sys.stdout)
finally:
if f:
f.close()
def savecsv(fname, curvelist, verbose=False):
"""
Saves the Curve or list of Curves to file in comma separated values (csv) format. Assumes
all curves have the same x basis.
>>> curves = list()
>>> curves.append(pydvif.makecurve([1, 2, 3, 4], [5, 10, 15, 20]))
>>> pydvif.savecsv('myfile.csv', curves)
:param fname: ULTRA filename
:type fname: str
:param curvelist: The Curve or list of Curves to save
:type curvelist: list
:param verbose: prints the error stacktrace when True
:type verbose: bool
"""
curves = list()
if isinstance(curvelist, list):
curves.extend(curvelist)
else:
curves.append(curvelist)
try:
f = open(fname, 'w')
s = '# time'
for curve in curves:
s += ', ' + curve.name
s += '\n'
f.write(s)
for i in range(len(curvelist[0].x)):
s = str(curvelist[0].x[i])
for j in range(len(curvelist)):
s += ', ' + str(curvelist[j].y[i])
s += '\n'
f.write(s)
except:
print('Error: Can not write to: ' + fname)
if verbose:
traceback.print_exc(file=sys.stdout)
finally:
if f:
f.close()
def read(fname, gnu=False, xcol=0, verbose=False, pattern=None, matches=None):
"""
Read the file and add parsed curves to a curvelist
>>> curves = pydvif.read('testData.txt')
>>> curves = pydvif.read('testData.txt', False, 0, False, '*_name', 20)
:param fname: ULTRA filename
:type fname: str
:param gnu: optional, flag to determine if the file is a column oriented (.gnu) file.
:type gnu: bool
:param xcol: optional, x-column number for column oriented (.gnu) files
:type xcol: int
:param verbose: optional, prints the error stacktrace when True
:type verbose: bool
:param pattern: optional, the regular expression pattern
:type pattern: str
:param matches: optional, maximum number of times to match pattern, if specified
:type matches: int
:returns: list -- the list of curves from the file matching pattern, if specified
"""
def bundle_curve(_curve, build_x, build_y):
if len(build_x) != len(build_y):
build_y.append(build_y[-1])
_curve.x = np.array(build_x, dtype=float).repeat(2)[1:]
_curve.y = np.array(build_y, dtype=float).repeat(2)[:-1]
_curve.step = True
else:
_curve.x = np.array(build_x, dtype=float)
_curve.y = np.array(build_y, dtype=float)
_curve.step = False
return _curve
curve_list = list()
regex = None
if pattern:
regex = re.compile(r"%s" % pattern)
fname = os.path.expanduser(fname)
_, ext = os.path.splitext(fname)
try:
if gnu or ext == '.gnu':
return __loadcolumns(fname, xcol)
if pdbLoaded:
try:
fpdb = pdb.open(fname, 'r')
return __loadpdb(fname, fpdb)
except:
pass
match_count = 0
build_list_x = list()
build_list_y = list()
current = None
new_curve = True
potential_curve_name = ""
with open(fname, 'r') as f:
for line in f:
split_line = re.split(r'[ _\t]+', str.strip(line))
if not split_line or not split_line[0]:
continue
elif split_line[0] in {'##', 'end', 'End', 'END'}:
continue
elif split_line[0] == '#':
# We may have just finished buiding a curve, so we need to
# add it to the list of curves.
# If this is the first curve, then current will be None, so
# we won't add anything.
# If there is a sequence of lines that start with # before
# getting to the actual data, then the new_curve flag will
# keep us from adding all those comments as curves.
if current and not new_curve:
# Need this since it will add last match below and outside loop
if matches and match_count >= matches:
break
curve_list.append(bundle_curve(current, build_list_x, build_list_y))
build_list_x = list()
build_list_y = list()
# Begin setup of new curve
new_curve = True
potential_curve_name = ' '.join(split_line[1:])
else:
if new_curve:
curve_name = potential_curve_name
new_curve = False
if regex:
if regex.search(curve_name):
match_count += 1
current = curve.Curve(fname, curve_name)
build_list_x += split_line[::2]
build_list_y += split_line[1::2]
else:
current = None
else:
current = curve.Curve(fname, curve_name)
build_list_x += split_line[::2]
build_list_y += split_line[1::2]
elif current and not new_curve: # add data to current curve
build_list_x += split_line[::2]
build_list_y += split_line[1::2]
# Append the last curve that we built
if current:
curve_list.append(bundle_curve(current, build_list_x, build_list_y))
except IOError:
print('could not load file: {}'.format(fname))
if verbose:
traceback.print_exc(file=sys.stdout)
except ValueError:
print('invalid pydv file: {}'.format(fname))
if verbose:
traceback.print_exc(file=sys.stdout)
return curve_list
def filtercurves(curvelist, pattern):
"""
Filters the list of curves based on the regular expression pattern.
>>> curves = pydvif.filtercurves(curves, "*_name")
:param curvelist: the list of curves
:type curvelist: Curve
:param pattern: the regular expression pattern
:type pattern: str
:return: list -- The list of filtered curves from curvelist based on the regular expression pattern
"""
results = list()
regex = re.compile(r"%s" % pattern)
for c in curvelist:
if regex.search(c.name) is not None:
results.append(c)
return results
def readcsv(fname, xcol=0, verbose=False):
"""
Load a csv (comma separated values) data file, add parsed curves to
a curvelist. '#' is the comment character. First uncommented line must
be the column labels. We assume the first column is the x-data, every
other column is y-data. We also assume all columns are the same length.
>>> curves = readcsv('testData.csv')
:param fname: csv filename
:type fname: str
:param xcol: x-column number for column oriented (.gnu) files
:type xcol: int
:param verbose: prints the error stacktrace when True
:type verbose: bool
:returns: list -- the list of curves from the csv file
"""
curvelist = list()
try:
f = open(fname, 'r')
except IOError:
print('readcsv: could not load file: ' + fname)
if verbose:
traceback.print_exc(file=sys.stdout)
return curvelist
try:
lines = f.readlines()
iLine = 0
for l in lines:
if l[0] != '#':
break;
iLine += 1
if iLine == 0 and False: # FIXME make condition to catch no labels
print('WARNING: columns have no labels, labels will be assigned...someday')
alllabels = lines[iLine] # this line has the labels on it.
colLabels = alllabels.split(',')
colLabels = [w.strip() for w in colLabels]
for w in colLabels: # if someone made labels with quotes, kill the quotes
if '"' in w: w.replace('"','')
# check that we have a label for every column
if len(colLabels) != len(lines[iLine].split(',')) and iLine > 0:
raise RuntimeError('Sorry, right now PDV requires you to have a label for every column.')
# We assume some column is the x-data, every other column
# is y-data
iLine += 1 # go to next line after header labels
numcurves = len(lines[iLine].split(',')) - 1
# Make the curves, append them to self.curvelist.
# First, get data into lists of numbers
numDataLines = len(lines) - iLine
localCurves = []
for i in range(numcurves+1):
localCurves.append([]) # FIGURE OUT COOL WAY TO DO THIS LATER: localCurves = (numcurves+1)*[[]]
# turn the strings into numbers
for l in lines[iLine:]:
nums = [float(n) for n in l.split(',')]
# print 'nums = ', nums, 'numcurves = ', numcurves
assert len(nums) == numcurves + 1
if xcol >= numcurves:
print('xcolumn is %d, larger than the number of curves in the file, use "setxcolumn" to fix that' % xcol)
for colID in range(numcurves + 1):
localCurves[colID].append(nums[colID])
# convert lists to numpy arrays
for colID in range(numcurves):
localCurves[colID] = np.array(localCurves[colID])
# Make Curve objects, add to self.curvelist
for colID in range(numcurves + 1):
if colID != xcol:
c = makecurve(localCurves[xcol], localCurves[colID], colLabels[colID], fname)
print("Appended curve: ", colLabels[colID], len(c.x), len(c.y))
curvelist.append(c)
# tidy up
f.close()
# anticipate failure!
except ValueError as e:
print(e.message)
print('readcsv: invalid pydv file: ' + fname)
if verbose:
traceback.print_exc(file=sys.stdout)
return curvelist
def readsina(fname, verbose=False):
"""
Load a Sina JSON data file, add parsed curves to a curvelist.
We assume JSON conforming to the Sina schema, with each curve defined in a curve_set. We assume
there is only one record, and if there are more then we only read the first one. We also assume
only one independent variable per curve_set; if there are more than one, then PyDV may exhibit
undefined behavior. Can also read curve_sets within libraries in library_data.
>>> curves = readsina('testData.json')
:param fname: Sina JSON filename
:type fname: str
:param verbose: prints the error stacktrace when True
:type verbose: bool
:returns: list: the list of curves from the sina file
"""
curves = {}
listed_order = []
try:
# Load the curve data from the curve_sets
with open(fname, 'r') as fp:
try:
sina_file = json.load(fp)
record_id = sina_file['records'][0]['id']
curve_sets = sina_file['records'][0]['curve_sets']
library_data = sina_file['records'][0]['library_data']
def add_curve_set(curve_sets, curves, listed_order, library=''):
for curve_set_name, curve_set in curve_sets.items():
independent_dict = next(iter(curve_set['independent'].items()))
independent_name = independent_dict[0]
independent_value = independent_dict[1]['value']
for name, v in curve_set['dependent'].items():
# TODO: Save the name x and y names with the curves
dependent_variable_name = name
full_name = curve_set_name + '__SINA_DEP__' + dependent_variable_name
dependent_variable_value = v['value']
curve_name = dependent_variable_name + ' vs ' + independent_name + " (" + \
curve_set_name + ")"
if library != '':
curve_name += ' ' + library
full_name += '__LIBRARY__' + library
c = makecurve(x=independent_value, y=dependent_variable_value,
name=curve_name, fname=fname, xlabel=independent_name,
ylabel=dependent_variable_name, title=curve_name, record_id=record_id)
c.step = False
print("Appended curve: {}, len x,y: {},{}"
.format(dependent_variable_name, len(c.x), len(c.y)))
curves[full_name] = c
listed_order.append(full_name)
return curves, listed_order
curves, listed_order = add_curve_set(curve_sets, curves, listed_order)
for library in library_data:
if 'curve_sets' in library_data[library]:
curve_sets = library_data[library]['curve_sets']
curves, listed_order = add_curve_set(curve_sets, curves, listed_order, library=library)
except KeyError:
print('readsina: Sina file {} is malformed'.format(fname))
if verbose:
traceback.print_exc(file=sys.stdout)
return []
# Try to load the order in which the user wants to load the curves into PyDV
with open(fname, 'r') as fp:
try:
order_options = json.load(fp)['records'][0]['data']['SINA_timeplot_order']['value']
except:
order_options = listed_order
except IOError:
print('readsina: could not load file: {}'.format(fname))
if verbose:
traceback.print_exc(file=sys.stdout)
return []
try:
curves_lst = [curves[name] for name in order_options]
except KeyError:
print('readsina: mismatch between dependent variable names in the curve_sets and the ' + \
'ordering specified in SINA_timeplot_order. Using default ordering instead.')
if verbose:
traceback.print_exc(File=sys.stdout)
curves_lst = [curves[name] for name in listed_order]
return curves_lst
########################################################
################## Math Functions #####################
########################################################
def cos(curvelist):
"""
Take the cosine of y values of a Curve or list of Curves.
>>> curves = pydvif.read('testData.txt')
>>> pydvif.cos(curves) OR
>>> pydvif.cos(curves[0])
:param curvelist: The Curve or list of Curves
:type curvelist: Curve or list
"""
curves = list()
if isinstance(curvelist, list):
curves.extend(curvelist)
else:
curves.append(curvelist)
for curve in curves:
curve.y = np.cos(curve.y)
def cosx(curvelist):
"""
Take the cosine of x values of a Curve or list of Curves.
>>> curves = pydvif.read('testData.txt')
>>> pydvif.cosx(curves) OR
>>> pydvif.cosx(curves[0])
:param curvelist: The Curve or list of Curves
:type curvelist: Curve or list
"""
curves = list()
if isinstance(curvelist, list):
curves.extend(curvelist)
else:
curves.append(curvelist)
for curve in curves:
curve.x = np.cos(curve.x)
def cosh(curvelist):
"""
Take the hyperbolic cosine of y values of a Curve or list of Curves.
>>> curves = pydvif.read('testData.txt')
>>> pydvif.cosh(curves) OR
>>> pydvif.cosh(curves[0])
:param curvelist: The Curve or list of curves
:type curvelist: Curve or list
"""
curves = list()
if isinstance(curvelist, list):
curves.extend(curvelist)
else:
curves.append(curvelist)
for curve in curves:
curve.y = np.cosh(curve.y)
def coshx(curvelist):
"""
Take the hyperbolic cosine of x values of a Curve or list of Curves.
>>> curves = pydvif.read('testData.txt')
>>> pydvif.coshx(curves) OR
>>> pydvif.coshx(curves[0])
:param curvelist: The Curve or list of curves
:type curvelist: Curve or list
"""
curves = list()
if isinstance(curvelist, list):
curves.extend(curvelist)
else:
curves.append(curvelist)
for curve in curves:
curve.x = np.cosh(curve.x)
def acosh(curvelist):
"""
Take the hyperbolic arccosine of y values of a Curve or list of Curves.
>>> curves = pydvif.read('testData.txt')
>>> pydvif.acosh(curves) OR
>>> pydvif.acosh(curves[0])
:param curvelist: The Curve or list of curves
:type curvelist: Curve or list
"""
curves = list()
if isinstance(curvelist, list):
curves.extend(curvelist)
else:
curves.append(curvelist)
for curve in curves:
curve.y = np.arccosh(curve.y)
def acoshx(curvelist):
"""
Take the hyperbolic arccosine of x values of a Curve or list of Curves.
>>> curves = pydvif.read('testData.txt')
>>> pydvif.acoshx(curves) OR
>>> pydvif.acoshx(curves[0])
:param curvelist: The Curve or list of curves
:type curvelist: Curve or list
"""
curves = list()
if isinstance(curvelist, list):
curves.extend(curvelist)
else:
curves.append(curvelist)
for curve in curves:
curve.x = np.arccosh(curve.x)
def acos(curvelist):
"""
Take the arccosine of y values of a Curve or list of Curves
>>> curves = pydvif.read('testData.txt')
>>> pydvif.acos(curves) OR
>>> pydvif.acos(curves[0])
:param curvelist: The Curve or list of curves
:type curvelist: Curve or list
"""
curves = list()
if isinstance(curvelist, list):
curves.extend(curvelist)
else:
curves.append(curvelist)
for curve in curves:
curve.y = np.arccos(curve.y)
def acosx(curvelist):
"""
Take the arccosine of x values of a Curve or list of Curves.
>>> curves = pydvif.read('testData.txt')
>>> pydvif.acosx(curves) OR
>>> pydvif.acosx(curves[0])
:param curvelist: The Curve or list of curves
:type curvelist: Curve or list
"""
curves = list()
if isinstance(curvelist, list):
curves.extend(curvelist)
else:
curves.append(curvelist)
for curve in curves:
curve.x = np.arccos(curve.x)
def sin(curvelist):
"""
Take the sine of y values of a single curve or multiple curves in list.
>>> curves = pydvif.read('testData.txt')
>>> pydvif.sin(curves)
:param curvelist: A single curve or a list of curves
:type curvelist: curve or list
"""
if isinstance(curvelist, list):
for c in curvelist:
c.y = np.sin(c.y)
else:
curvelist.y = np.sin(curvelist.y)
def sinx(curvelist):
"""
Take the sine of x values of a single curve or multiple curves in list.
>>> curves = pydvif.read('testData.txt')
>>> pydvif.sinx(curves)
:param curvelist: A single curve or a list of curves
:type curvelist: curve or list
"""
if isinstance(curvelist, list):
for c in curvelist:
c.x = np.sin(c.x)
else:
curvelist.x = np.sin(curvelist.x)
def sinh(curvelist):
"""
Take the hyperbolic sine of y values of a single curve or multiple curves in list.
>>> curves = pydvif.read('testData.txt')
>>> pydvif.sinh(curves)
:param curvelist: A single curve or a list of curves
:type curvelist: curve or list
"""
if isinstance(curvelist, list):
for c in curvelist:
c.y = np.sinh(c.y)
else:
curvelist.y = np.sinh(curvelist.y)
def sinhx(curvelist):
"""
Take the hyperbolic sine of x values of a single curve or multiple curves in list.
>>> curves = pydvif.read('testData.txt')
>>> pydvif.sinhx(curves)