-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPlot.py
More file actions
1930 lines (1853 loc) · 73.2 KB
/
Copy pathPlot.py
File metadata and controls
1930 lines (1853 loc) · 73.2 KB
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
# coding: utf-8
# In[1]:
pgfSys = "lualatex"
import matplotlib as mpl
# mpl.use("pgf")
import numpy as np
import scipy.interpolate as inter
import matplotlib.pyplot
import copy
import sys
import os
import string
import warnings
import functools
import copy
import inspect
from scipy.signal import savgol_filter
# import mpl_toolkits.axisartist as AA
from matplotlib import rc
from Filereader import fileToNpArray
from Data import Data
from Fitter import Fitter, FitException
# In[2]:
class Plot:
# constants
fig_width_default_pt = 424.75906
default_colors = [
(31 / 255, 119 / 255, 180 / 255, 1),
(214 / 255, 39 / 255, 40 / 255, 1),
(148 / 255, 103 / 255, 189 / 255, 1),
(140 / 255, 86 / 255, 75 / 255, 1),
(227 / 255, 119 / 255, 194 / 255, 1),
(127 / 255, 127 / 255, 127 / 255, 1),
(255 / 255, 127 / 255, 14 / 255, 1),
(188 / 255, 189 / 255, 34 / 255, 1),
(23 / 255, 190 / 255, 207 / 255, 1),
(248 / 255, 229 / 255, 32 / 255, 1),
(44 / 255, 160 / 255, 44 / 255, 1),
]
default_font = "DejaVu Sans"
default_font_size = [10, 10, 6, 6, 6]
axRect_default = [0.15, 0.15, 0.7, 0.7]
default_marker_size = 6
default_D3props = {"func": "contourf", "interp": 1000, "cmap": "afmhot"}
@classmethod
def gauss(cls, x, mu, amp, sigma):
return (
amp
/ (np.sqrt(2 * np.pi * sigma ** 2))
* np.exp(-((x - mu) ** 2 / (2 * sigma ** 2)))
)
@classmethod
def equalizeRanges(cls, data, norm=(390, 780, 401)):
arr, arr2 = data.getSplitData2D()
f = inter.CubicSpline(arr, arr2, extrapolate=True)
x = np.linspace(*norm)
data.setData(Data.mergeData((x, f(x))))
@classmethod
def div0(cls, a, b):
"""ignore / 0, div0( [-1, 0, 1], 0 ) -> [0, 0, 0]"""
with np.errstate(divide="ignore", invalid="ignore"):
c = np.true_divide(a, b)
c[~np.isfinite(c)] = 0 # -inf inf NaN
return c
@classmethod
def normalize2(cls, a):
return a / np.amax(a)
@classmethod
def normalize(cls, a):
return a / np.sum(a)
@classmethod
def absolute(cls, a):
return np.absolute(a)
@classmethod
def initByExistingPlot(cls, obj, **kwargs):
return cls(
obj.name,
obj.fileList,
dataList=obj.dataList,
errList=[obj.expectData, obj.deviaData, obj.logErr],
dataProcessed=True,
averageProcessed=True,
dataImported=True,
**kwargs,
)
@classmethod
def create_line_string(cls, line, sep):
string = ""
for element in line:
string += str(element) + sep
return string[: -len(sep)]
@classmethod
def concentenate_files(cls, fileList, fileFormat={}, subdir="", previous_subdir=""):
try:
end = fileFormat["fileEnding"]
except KeyError:
end = ""
try:
skip = fileFormat["skiplines"]
except KeyError:
skip = 0
con_filename = subdir + fileList[0][len(previous_subdir) :]
con_file = open(con_filename + end, "w")
m = 0
for fname in fileList:
with open(fname + end) as infile:
n = 0
for line in infile:
if n >= skip or m == 0:
con_file.write(line)
n += 1
m += 1
con_file.close()
return con_filename
@classmethod
def scaleRcParams(cls, scaleX, font=default_font):
mpl.rcParams["lines.linewidth"] = scaleX * mpl.rcParams["lines.linewidth"]
mpl.rcParams["lines.markeredgewidth"] = (
scaleX * mpl.rcParams["lines.markeredgewidth"]
)
mpl.rcParams["lines.markersize"] = scaleX * mpl.rcParams["lines.markersize"]
mpl.rcParams["axes.linewidth"] = scaleX * mpl.rcParams["axes.linewidth"]
mpl.rcParams["xtick.major.size"] = scaleX * mpl.rcParams["xtick.major.size"]
mpl.rcParams["xtick.major.width"] = scaleX * mpl.rcParams["xtick.major.width"]
mpl.rcParams["xtick.major.pad"] = scaleX * mpl.rcParams["xtick.major.pad"]
mpl.rcParams["xtick.minor.size"] = scaleX * mpl.rcParams["xtick.minor.size"]
mpl.rcParams["xtick.minor.width"] = scaleX * mpl.rcParams["xtick.minor.width"]
mpl.rcParams["xtick.minor.pad"] = scaleX * mpl.rcParams["xtick.minor.pad"]
mpl.rcParams["ytick.major.size"] = scaleX * mpl.rcParams["ytick.major.size"]
mpl.rcParams["ytick.major.width"] = scaleX * mpl.rcParams["ytick.major.width"]
mpl.rcParams["ytick.major.pad"] = scaleX * mpl.rcParams["ytick.major.pad"]
mpl.rcParams["ytick.minor.size"] = scaleX * mpl.rcParams["ytick.minor.size"]
mpl.rcParams["ytick.minor.width"] = scaleX * mpl.rcParams["ytick.minor.width"]
mpl.rcParams["ytick.minor.pad"] = scaleX * mpl.rcParams["ytick.minor.pad"]
mpl.rcParams["grid.linewidth"] = scaleX * mpl.rcParams["grid.linewidth"]
mpl.rcParams["pgf.preamble"] = (
"\\usepackage{fontspec}\n"
+ "\\usepackage{unicode-math}\n"
+ f"\\setmainfont{{{font}}}"
+ f"\\setmathfont{{{font}}}"
+ "\\usepackage{amsmath}\n"
+ "\\usepackage{upgreek}\n"
+ f"\\renewcommand{{\\tfrac}}[2]{{\\genfrac{{}}{{}}{{{0.6*scaleX:0.3f}pt}}{{1}}{{#1}}{{#2}}}}"
)
# "\\usepackage{sfmath}\n"+
@classmethod
def rescaleRcParams(cls, scaleX, font=default_font):
mpl.rcParams["lines.linewidth"] = 1 / scaleX * mpl.rcParams["lines.linewidth"]
mpl.rcParams["lines.markeredgewidth"] = (
1 / scaleX * mpl.rcParams["lines.markeredgewidth"]
)
mpl.rcParams["lines.markersize"] = 1 / scaleX * mpl.rcParams["lines.markersize"]
mpl.rcParams["axes.linewidth"] = 1 / scaleX * mpl.rcParams["axes.linewidth"]
mpl.rcParams["xtick.major.size"] = 1 / scaleX * mpl.rcParams["xtick.major.size"]
mpl.rcParams["xtick.major.width"] = (
1 / scaleX * mpl.rcParams["xtick.major.width"]
)
mpl.rcParams["xtick.major.pad"] = 1 / scaleX * mpl.rcParams["xtick.major.pad"]
mpl.rcParams["xtick.minor.size"] = 1 / scaleX * mpl.rcParams["xtick.minor.size"]
mpl.rcParams["xtick.minor.width"] = (
1 / scaleX * mpl.rcParams["xtick.minor.width"]
)
mpl.rcParams["xtick.minor.pad"] = 1 / scaleX * mpl.rcParams["xtick.minor.pad"]
mpl.rcParams["ytick.major.size"] = 1 / scaleX * mpl.rcParams["ytick.major.size"]
mpl.rcParams["ytick.major.width"] = (
1 / scaleX * mpl.rcParams["ytick.major.width"]
)
mpl.rcParams["ytick.major.pad"] = 1 / scaleX * mpl.rcParams["ytick.major.pad"]
mpl.rcParams["ytick.minor.size"] = 1 / scaleX * mpl.rcParams["ytick.minor.size"]
mpl.rcParams["ytick.minor.width"] = (
1 / scaleX * mpl.rcParams["ytick.minor.width"]
)
mpl.rcParams["ytick.minor.pad"] = 1 / scaleX * mpl.rcParams["ytick.minor.pad"]
mpl.rcParams["grid.linewidth"] = 1 / scaleX * mpl.rcParams["grid.linewidth"]
mpl.rcParams["pgf.preamble"] = (
"\\usepackage{fontspec}\n"
+ "\\usepackage{unicode-math}\n"
+ f"\\setmainfont{{{font}}}"
+ f"\\setmathfont{{{font}}}"
+ "\\usepackage{amsmath}\n"
+ "\\usepackage{upgreek}\n"
+ f"\\renewcommand{{\\tfrac}}[2]{{\\genfrac{{}}{{}}{{{0.6:0.3f}pt}}{{1}}{{#1}}{{#2}}}}"
)
@classmethod
def set_size(w, h, ax=None):
"""w, h: width, height in inches"""
if not ax:
ax = plt.gca()
l = ax.figure.subplotpars.left
r = ax.figure.subplotpars.right
t = ax.figure.subplotpars.top
b = ax.figure.subplotpars.bottom
figw = float(w) / (r - l)
figh = float(h) / (t - b)
ax.figure.set_size_inches(figw, figh)
@classmethod
def figsize(cls, fig_width_pt, fixedFigWidth, scaleX, HWratio):
inches_per_pt = 1.0 / 72.27 # Convert pt to inch
if fixedFigWidth:
fig_width = fig_width_pt * inches_per_pt
else:
fig_width = fig_width_pt * inches_per_pt * scaleX # width in inches
fig_height = fig_width * HWratio # height in inches
fig_size = [fig_width, fig_height]
return fig_size
@classmethod
def newFig(
cls,
customFontsize=None,
font=default_font,
axRect=axRect_default,
fig_width_pt=fig_width_default_pt,
fixedFigWidth=False,
scaleX=1,
HWratio=1,
marker_size=default_marker_size,
projection=None,
):
matplotlib.pyplot.clf()
cls.initTex(customFontsize=customFontsize, font=font, marker_size=marker_size)
fig = matplotlib.pyplot.figure(
figsize=cls.figsize(fig_width_pt, fixedFigWidth, scaleX, HWratio),
facecolor="none",
)
ax = matplotlib.pyplot.axes(axRect, projection=projection)
return fig, ax
@classmethod
def makeDataFromFile_with_cols(
cls, measurement, fileFormat, xCol, yCol, lower_crop=0, upper_crop=0
):
if upper_crop == 0:
return Data(
fileToNpArray(measurement, **fileFormat)[0][lower_crop:],
desc=fileToNpArray(measurement, **fileFormat)[1],
xCol=xCol,
yCol=yCol,
)
return Data(
fileToNpArray(measurement, **fileFormat)[0][lower_crop:upper_crop],
desc=fileToNpArray(measurement, **fileFormat)[1],
xCol=xCol,
yCol=yCol,
)
@classmethod
def initTex(
cls,
customFontsize=None,
font=default_font,
font_size=default_font_size,
scaleX=1,
marker_size=default_marker_size,
):
pgf_with_lualatex = {
"pgf.texsystem": pgfSys,
"font.family": "sans-serif", # use serif/main font for text elements
"font.sans-serif": [font],
"mathtext.fallback": "cm",
"axes.unicode_minus": False,
"mathtext.fontset": "custom",
"mathtext.tt": font,
"mathtext.rm": font,
"mathtext.sf": font,
"mathtext.it": font,
"font.size": font_size[0],
"axes.labelsize": font_size[1], # LaTeX default is 10pt font.
"legend.fontsize": font_size[
2
], # Make the legend/label fonts a little smaller
"xtick.labelsize": font_size[3],
"ytick.labelsize": font_size[4],
"text.usetex": False, # use inline math for ticks
"axes.formatter.use_mathtext": False,
"pgf.rcfonts": True,
"text.latex.preamble": "\\usepackage{fontspec}\n" +
# "\\usepackage{unicode-math}\n"+
f"\\setmainfont{{{font}}}" + f"\\setmathfont{{{font}}}" +
# "\\usepackage{amsmath}\n"+
# "\\usepackage{upgreek}\n"+
# "\\usepackage{sfmath}\n"+
f"\\renewcommand{{\\tfrac}}[2]{{\\genfrac{{}}{{}}{{{0.6*scaleX:0.3f}pt}}{{1}}{{#1}}{{#2}}}}",
"pgf.preamble": # "\\usepackage{amsmath}\n"+
# "\\usepackage{upgreek}\n"+
"\\usepackage{fontspec}\n" +
# "\\usepackage{unicode-math}\n"+
f"\\setmainfont{{{font}}}" + f"\\setmathfont{{{font}}}" +
# "\\usepackage{sfmath}\n"+
f"\\renewcommand{{\\tfrac}}[2]{{\\genfrac{{}}{{}}{{{0.6*scaleX:0.3f}pt}}{{1}}{{#1}}{{#2}}}}",
"lines.markersize": marker_size,
}
if customFontsize is not None and len(customFontsize) == 5:
pgf_with_lualatex.update(
{
"font.size": customFontsize[0],
"axes.labelsize": customFontsize[1], # LaTeX default is 10pt font.
"legend.fontsize": customFontsize[
2
], # Make the legend/label fonts a little smaller
"xtick.labelsize": customFontsize[3],
"ytick.labelsize": customFontsize[4],
}
)
else:
pgf_with_lualatex.update(
{
"pgf.texsystem": pgfSys,
"font.size": 12,
"axes.labelsize": "medium", # LaTeX default is 10pt font.
"legend.fontsize": "small", # Make the legend/label fonts a little smaller
"xtick.labelsize": "medium",
"ytick.labelsize": "medium",
}
)
mpl.rcParams.update(pgf_with_lualatex)
cls.scaleRcParams(scaleX)
def __init__(
self,
name,
fileList=None,
fileFormat={"separator": "\t", "skiplines": 1},
showColTup=(2, 3),
xLim=None,
limCol=None,
xLimOrig=None,
yLim=None,
scaleX=1,
customFontsize=None,
averageMedian=False,
xCol=1,
xCol2=0,
xColOrig=1,
title=None,
HWratio=1, # 3/4, # height to width ratio
fig_width_pt=fig_width_default_pt, # get it by \the\textwidth
titleBool=True,
legendEdgeSize=1,
ax2Labels=True,
# spectralDataformat={"separator":";", "skiplines":75}, #jeti csv format
showColAxType=[None, "lin", "lin", "lin"],
xAxisLim=None,
showColAxLim=[None, None, None, None],
colors=default_colors,
linestyles=["-", "--", ":", "-.","-", "--", ":", "-."],
markers=["o", "^", "s", "p", "P", "*","+","h","H","x","X"],
iterLinestyles=False,
linestyleOffset=0,
iterMarkers=False,
# markerOffset=0,
showColLabel=None,
showColLabel_filename=None,
showColLabelUnitNoTex=[None, "X", "Y", "Y2"],
showColLabelUnit=[None, "X", "Y", "Y2"],
fill="_",
show=None,
filename=None,
labels=None,
colorOffset=0,
errors=None,
showErrorOnlyEvery=1,
erroralpha=0.5,
ax2erroralpha=0.5,
erroralphabar=0.5,
ax2erroralphabar=0.5,
capsize=2,
capthick=1,
errorTypeUp=1,
errorTypeDown=1,
ax2errorTypeUp=1,
ax2errorTypeDown=1,
ls="-",
mk="o",
ax2ls="--",
ax2mk="^",
ax2LegendLabelAddString="",
overrideErrorTypes=False,
overrideFileList=False,
dataProcessed=False,
averageProcessed=False,
dataImported=False,
dataList=None,
errList=[None] * 3,
injCode="pass",
legLoc=0,
fitList=None,
fitLabels=None,
fitString="Fit of",
fitAlpha=0.75,
fitLs=":",
fitColors=None,
showFitInLegend=True,
fixedFigWidth=False,
xAxis2=False,
xAxisTickLabels=None,
xAxisTicks=None,
legendBool=True,
titleFontsize="x-large",
customLabelAx2=None,
doNotFit=False,
font=default_font,
filenamePrefix=None,
newFileList=None,
concentenate_files_instead_of_avg=False,
no_plot=False,
useTex=True,
partialFitLabels=[],
showLines=True,
showMarkers=False,
markerSize=default_marker_size,
markerFillstyles=["full", "none"],
subdir=None,
iterBoth=False,
append_col_in_label=True,
ax2colors=None,
axRect=axRect_default,
labelPad=None,
saveProps=None,
axAnnotations=None,
ax_grid=True,
_filter=None,
# ax_aspect='auto',
):
# static inits
self.fig = None
self.ax = None
self.ax2 = None
self.axX2 = None
self.alreadyFitted = False
# dyn inits
self.fileFormat = fileFormat
if len(showColTup) != 2:
raise
try:
if showColTup[0] <= 0 or showColTup[1] < 0:
raise
except TypeError:
pass
self.showColTup = showColTup
self.showCol = self.showColTup[0]
self.showCol2 = self.showColTup[1]
self.fill = fill
self.showColAxType = showColAxType
self.showColAxLim = showColAxLim
self.xCol = xCol
self.colors = colors
if showColLabel is None:
sCLU = copy.deepcopy(showColLabelUnit)
try:
sCLU[0] = "?"
self.showColLabel = [
showColLabelUnitElement.split()[0]
for showColLabelUnitElement in sCLU
]
self.showColLabel_filename = self.showColLabel
except:
raise
else:
self.showColLabel = showColLabel
if showColLabel_filename is None:
self.showColLabel_filename = showColLabel
else:
self.showColLabel_filename = showColLabel_filename
self.useTex = useTex
if self.useTex:
# mpl.use("pgf")
self.showColLabelUnit = showColLabelUnit
else:
mpl.use("Qt5Agg")
self.showColLabelUnit = showColLabelUnitNoTex
self.showColLabelUnitNoTex = showColLabelUnitNoTex
if yLim is not None:
if len(yLim) == 2:
try:
if len(yLim[0]) == 2:
self.showColAxLim[self.showCol] = yLim[0]
self.showColAxLim[self.showCol2] = yLim[1]
else:
Exception("yLim is of wrong format")
except TypeError:
self.showColAxLim[self.showCol] = yLim
else:
raise Exception("yLim is of wrong format")
self.scaleX = scaleX
if scaleX < 0.6 and customFontsize is None:
self.customFontsize = [10, 10, 6, 6, 6]
elif scaleX >= 0.6 and customFontsize is None:
self.customFontsize = (
mpl.rcParams["font.size"],
mpl.rcParams["axes.labelsize"],
mpl.rcParams["legend.fontsize"],
mpl.rcParams["xtick.labelsize"],
mpl.rcParams["ytick.labelsize"],
)
else:
self.customFontsize = customFontsize
self.averageMedian = averageMedian
self.xColOrig = xColOrig
self.xLimOrig = xLimOrig
self.xLim = xLim
self.axXLim = xAxisLim
try:
self.axYLim = self.showColAxLim[self.showCol]
self.axYLabel = self.showColLabelUnit[self.showCol]
except TypeError:
self.axYLim = self.showColAxLim[self.showCol[0]]
self.axYLabel = self.showColLabelUnit[self.showCol[0]]
try:
self.ax2YLim = self.showColAxLim[self.showCol2]
self.ax2YLabel = self.showColLabelUnit[self.showCol2]
except TypeError:
self.ax2YLim = self.showColAxLim[self.showCol2[0]]
self.ax2YLabel = self.showColLabelUnit[self.showCol2[0]]
self.ax2Labels = ax2Labels
# self.ax2LegendLabelAddString=ax2LegendLabelAddString
if title is None:
self.title = "Plot of " + name
else:
self.title = title
self.name = name
self.HWratio = HWratio
self.titleBool = titleBool
self.fig_width_pt = fig_width_pt
self.legendEdgeSize = legendEdgeSize * scaleX
self.colorOffset = colorOffset
try:
showErrorOnlyEvery[0]
self.showErrorOnlyEvery = showErrorOnlyEvery
except:
try:
self.showErrorOnlyEvery = [showErrorOnlyEvery] * len(fileList)
except TypeError:
self.showErrorOnlyEvery = [showErrorOnlyEvery] * len(dataList)
self.erroralpha = erroralpha
self.ax2erroralpha = ax2erroralpha
self.erroralphabar = erroralphabar
self.ax2erroralphabar = ax2erroralphabar
self.capsize = capsize * self.scaleX
self.capthick = capthick * self.scaleX
self.errorTypeUp = errorTypeUp
self.errorTypeDown = errorTypeDown
self.ax2errorTypeUp = ax2errorTypeUp
self.ax2errorTypeDown = ax2errorTypeDown
self.iterLinestyles = iterLinestyles
self.linestyles = linestyles
self.markers = markers
self.linestyleOffset = linestyleOffset
self.iterMarkers = iterMarkers
# self.markerOffset=markerOffset
if iterLinestyles:
self.ls = linestyles[0]
self.ax2ls = linestyles[0]
self.ax1color = colors[0]
self.ax2color = colors[1]
else:
self.ls = ls
self.ax2ls = ax2ls
if iterMarkers:
self.mk = markers[0]
self.ax2mk = markers[0]
self.ax1color = colors[0]
self.ax2color = colors[1]
else:
self.mk = mk
self.ax2mk = ax2mk
self.overrideErrorTypes = overrideErrorTypes
self.overrideFileList = overrideFileList
self.filename = filename
self.dataProcessed = dataProcessed
self.averageProcessed = averageProcessed
self.dataImported = dataImported
self.dataList = dataList
self.expectData = errList[0]
self.deviaData = errList[1]
self.logErr = errList[2]
self.injCode = injCode
self.legLoc = legLoc
self.fitList = fitList
if fitColors is None:
self.fitColors = self.colors
else:
self.fitColors = fitColors
self.fitLs = fitLs
self.fitAlpha = fitAlpha
self.fitString = fitString
self.showFitInLegend = showFitInLegend
self.fixedFigWidth = fixedFigWidth
self.xAxis2 = xAxis2
self.xAxisTickLabels = xAxisTickLabels
self.xAxisTicks = xAxisTicks
self.xCol2 = xCol2
self.ax2XLabel = self.showColLabelUnit[self.xCol2]
self.ax2XLim = self.showColAxLim[self.xCol2]
self.legendBool = legendBool
self.titleFontsize = titleFontsize
self.limCol = limCol
self.customLabelAx2 = customLabelAx2
self.doNotFit = doNotFit
self.font = font
self.filenamePrefix = filenamePrefix
self.concentenate_files_instead_of_avg = concentenate_files_instead_of_avg
self.no_plot = no_plot
self.partialFitLabels = partialFitLabels
self.markerSize = markerSize
self.markerFillstyles = markerFillstyles
self.iterBoth = iterBoth
self.append_col_in_label = append_col_in_label
self.ax2colors = ax2colors
self.axRect = axRect
self.labelpad = labelPad
self.saveProps = saveProps
self.axAnnotations = axAnnotations
self.ax_grid=ax_grid
self._filter = _filter
# self.ax_aspect=ax_aspect
# inits
# if mpl_use == "pgf":
# self.mpl_tex = True;
# else:
# self.mpl_tex = False
if self.dataList is None:
if newFileList is not None:
self.__initFileList(
newFileList, errors, labels, show, fitLabels, showLines, showMarkers
)
else:
self.__initFileList(
fileList, errors, labels, show, fitLabels, showLines, showMarkers
)
self.dataList = self.importData()
else:
self.__initFileList(
dataList, errors, labels, show, fitLabels, showLines, showMarkers
)
def __initFileList(
self, fileList, errors, labels, show, fitLabels, showLines, showMarkers
):
if self.overrideFileList:
self.fileList = []
self.errors = []
self.labels = []
self.show = []
self.fitLabels = []
else:
try:
fileList_cor = []
for file in fileList:
fileList_sub_cor = []
for filesub in file:
if isinstance(filesub, list):
new_file = self.concentenate_files(filesub)
else:
new_file = filesub
fileList_sub_cor.append(new_file)
fileList_cor.append(fileList_sub_cor)
self.fileList = fileList_cor
except IndexError:
raise ListShapeException(
"The filelist has to be formatted like: [[sampleApx1,sampleApx2],[sampleBpx1,sampleBpx2]]"
)
if errors is None and labels is None:
self.show = [[True, True] for device in self.fileList]
self.errors = self.show
self.labels = [
"Sample {:d}".format(m + 1) for m in range(0, len(self.fileList))
]
elif labels is not None:
try:
temp = [labels[m] for m in range(0, len(self.fileList))]
self.labels = labels
except IndexError:
raise ListShapeException(
'The labels\' list has to be formatted like: ["sampleALabel","sampleBLabel"]'
)
self.errors = [
[deviceLabel != "", deviceLabel != ""]
for deviceLabel in self.labels
]
self.show = self.errors
else:
try:
if self.showCol == 0 or self.showCol2 == 0:
temp = [errors[m][0] for m in range(0, len(self.fileList))]
else:
temp = [errors[m][1] for m in range(0, len(self.fileList))]
self.errors = errors
self.show = self.errors
except IndexError:
raise ListShapeException(
"The errors' list has to be formatted like: [[sampleAerrorAxis1,sampleAerrorAxis2],[sampleBerrorAxis1,sampleBerrorAxis2]]"
)
except TypeError:
if type(errors) == bool or isinstance(errors, (list, tuple)):
self.show = [[True, True] for device in self.fileList]
else:
raise ListShapeException("The error's TypeError")
self.labels = [
"Sample {:d}".format(m + 1) for m in range(0, len(self.fileList))
]
if show is not None:
try:
if self.showCol == 0 or self.showCol2 == 0:
temp = [show[m][0] for m in range(0, len(self.fileList))]
else:
temp = [show[m][1] for m in range(0, len(self.fileList))]
self.show = show
except IndexError:
raise ListShapeException(
"The show list has to be formatted like: [[sampleAshowAxis1,sampleAshowAxis2],[sampleBshowAxis1,sampleBshowAxis2]]"
)
if errors is not None:
if errors is False:
self.errors = [[False, False] for device in self.fileList]
elif errors is True:
self.errors = [[True, True] for device in self.fileList]
elif errors[0] is True and errors[1] is False:
self.errors = [[True, False] for device in self.fileList]
elif errors[0] is False and errors[1] is True:
self.errors = [[True, False] for device in self.fileList]
if fitLabels is None:
self.fitLabels = [self.fitString + label for label in self.labels]
else:
self.fitLabels = fitLabels
if isinstance(showLines, list):
self.showLines = showLines
else:
self.showLines = [[showLines, showLines] for device in self.fileList]
if isinstance(showMarkers, list):
self.showMarkers = showMarkers
else:
self.showMarkers = [
[showMarkers, showMarkers] for device in self.fileList
]
# fitTuple ([start, end], [show_start, show_end],func , (param1,param2), (textXPos,textYPos), desc, addKwArgs)
def __initFitter(self):
fitterList = []
for expect, devia, fitTuple in zip(
self.expectData, self.deviaData, self.fitList
):
if fitTuple == () or fitTuple is None:
fitterList.append(None)
elif type(fitTuple) is not tuple and type(fitTuple) is list:
fitSubList = []
n = 0
for fTuple in fitTuple:
if n == 0:
expectCopy = expect
deviaCopy = devia
else:
expectCopy = copy.deepcopy(expect)
deviaCopy = copy.deepcopy(devia)
n += 1
fitSubList.append(
Fitter(
expectCopy,
fTuple[2],
errorData=deviaCopy,
dataForFitXLim=fTuple[0],
dataForFitYLim=fTuple[6].pop("dataForFitYLim", None),
curveDataXLim=fTuple[1],
params=fTuple[3],
textPos=fTuple[4],
desc=fTuple[5],
addKwArgs=fTuple[6],
)
)
fitterList.append(fitSubList)
else:
fitterList.append(
Fitter(
expect,
fitTuple[2],
errorData=devia,
dataForFitXLim=fitTuple[0],
dataForFitYLim=fitTuple[6].pop("dataForFitYLim", None),
curveDataXLim=fitTuple[1],
params=fitTuple[3],
textPos=fitTuple[4],
desc=fitTuple[5],
addKwArgs=fitTuple[6],
)
)
return fitterList
def limit_fit_data_and_fit(self, fitter):
fitter.limitData(
xLim=fitter.dataForFitXLim, yLim=fitter.dataForFitYLim, feature=feature[0]
)
if not self.doNotFit:
try:
fitter.fit(xCol=self.xCol, yCol=self.showCol, p0=fitter.params)
except RuntimeError as err:
raise FitException(
self.fitterList.index(fitter),
self.fitList[(self.fitterList.index(fitter))],
err,
fitter.params,
)
fitter.doFitCurveData(xCol=self.xCol)
fitter.limitData(xLim=fitter.curveDataXLim, feature=feature[1])
def __processFit(self):
for fitter in self.fitterList:
if fitter is not None:
if type(fitter) is list:
for subFitter in fitter:
self.limit_fit_data_and_fit(subFitter)
else:
self.limit_fit_data_and_fit(fitter)
def saveFig(self):
if self.useTex:
self.fig.savefig(
self.processFileName(option=".pdf")
) # , bbox_inches='tight')
self.fig.savefig(
self.processFileName(option=".pgf")
) # , bbox_inches='tight')
else:
self.fig.savefig(self.processFileName(option=".png"))
if self.saveProps is not None:
option = self.saveProps.pop("saveAs")
self.fig.savefig(self.processFileName(option=option), **self.saveProps)
def processFileName_makedirs(self):
try:
folder = os.path.dirname(self.filenamePrefix)
os.makedirs(folder)
except TypeError:
pass
except FileExistsError as e:
if e.errno != 17:
raise
except FileNotFoundError as f:
if f.errno != 2:
raise
def processFileName(self, option=".pdf"):
string = ""
if self.filename is None:
if self.showCol2 == 0:
string += (
self.name.replace(" ", "")
+ self.fill
+ self.showColLabel_filename[self.showCol].replace(" ", "")
)
else:
string += (
self.name.replace(" ", "")
+ self.fill
+ self.showColLabel_filename[self.showCol].replace(" ", "")
+ "+"
+ self.showColLabel_filename[self.showCol2].replace(" ", "")
)
else:
string = (
self.filename.replace(" ", "")
+ self.fill
+ self.showColLabel_filename[self.showCol].replace(" ", "")
)
if self.scaleX != 1:
string += self.fill + "scaledWith{:03.0f}Pct".format(self.scaleX * 100)
if self.filenamePrefix is not None:
self.processFileName_makedirs()
if self.filenamePrefix[-1] == os.sep:
string = self.filenamePrefix + string
else:
string = self.filenamePrefix + self.fill + string
return string + option
def makeDataFromFile(self, measurement, fileFormat, lower_crop=0, upper_crop=0):
if upper_crop == 0:
return Data(
fileToNpArray(measurement, **fileFormat)[0][lower_crop:],
desc=fileToNpArray(measurement, **fileFormat)[1],
xCol=self.xCol,
yCol=self.showCol,
)
return Data(
fileToNpArray(measurement, **fileFormat)[0][lower_crop:upper_crop],
desc=fileToNpArray(measurement, **fileFormat)[1],
xCol=self.xCol,
yCol=self.showCol,
)
def importData(self, **kwargs):
if not self.dataImported:
try:
self.fileFormat[0]
self.dataList = [
[
self.makeDataFromFile(measurement, fileFormat, **kwargs)
for measurement in sample
]
for sample, fileFormat in zip(self.fileList, self.fileFormat)
]
except KeyError:
self.dataList = [
[
self.makeDataFromFile(measurement, self.fileFormat, **kwargs)
for measurement in sample
]
for sample in self.fileList
]
return self.dataList
def filter_data(self, data, yCol):
try:
if self._filter["type"] == "savgol":
def this_savgol_filter(data):
return savgol_filter(data, self._filter["p1"], self._filter["p2"])
data.processData(this_savgol_filter, yCol=yCol)
except:
return
def processData(self):
if not self.dataProcessed:
for deviceData in self.dataList:
for data in deviceData:
data.limitData(xLim=self.xLimOrig)
# print("limiting data to: "+str(self.xLimOrig))
if self._filter != None:
self.filter_data(data)
self.dataProcessed = True
return self.dataList
#
#
# returns List with arithmetic averaged values, List with standarddeviation values for each sample
@functools.lru_cache()
def processAvg(self, dataList=None):
if dataList is None:
dataList = self.dataList
errorData = True
for data in dataList:
try:
qtyCol = len(dataList[0][0].getData()[0])
errorData = False
except IndexError:
pass
if not errorData:
qtyCol = len(dataList[0][0].getData()[0])
dataColList = [
[
[data.getData()[:, m] for data in deviceData]
for deviceData in dataList
]
for m in range(0, qtyCol)
]
descList = [deviceData[0].desc for deviceData in dataList]
avgColList = [
[np.average(element, axis=0) for element in column]
for column in dataColList
]
avgList = [
[avgColList[m][n] for m in range(0, qtyCol)]
for n in range(0, len(dataList))
]
avgDataList = [Data.mergeData(avgData) for avgData in avgList]
devDataList = [
np.sqrt(
np.sum(
[