-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathasciigui_backend.py
2055 lines (1740 loc) · 85.4 KB
/
asciigui_backend.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
# PYTHON 3.9.1
"""
Tristan Anderson
Proceed Formally.
"""
# Fortune
"""
This universe shipped by weight, not by volume. Some expansion of the
contents may have occurred during shipment.
"""
import NMR_Analyzer as v
import daq_muncher, directory_sorter,sweep_averager,global_interpreter,spin_extractor,asciigui_backend
from matplotlib import pyplot as plt
import datetime,pandas,os,numpy,gc,time,multiprocessing,variablenames,matplotlib,argparse,traceback,sys
"""
# TODO: Add overview of current settings on each mainloop in table format.
"""
class AsciiGUI():
"""
The master template
for the different frames of the
ascii-gui page.
Each option will need to have access to a:
- File/Dir selector
- Output formatting
- And an Options selection method,
"""
def __init__(self, **passed):
self.delimeter = '\t'
self.hardinit = passed.pop('hardinit',False)
if passed.pop('getrootdir',False):
self.rootdir = os.getcwd()
self.processes = 1
self.servermode = False
def fileDirectorySelector(self, dironly=False, fileonly=False):
cwd = os.getcwd()
status = True
while status:
fixeddirs, fixedfiles, cleanfiles, dirs = self.getdir(cwd)
print("Current working Directory:", cwd)
print("Enter choice in the format of: \'LineNum(f/d)\n\t ex: 1f\t ex: 1d\n\t ex: ok\t ex: ..\n or type: \'help\', \'?\' for more details.")
status, path = self.choice(fixeddirs, fixedfiles, cleanfiles, dirs, dironly=dironly, fileonly=fileonly)
cwd = path
return path
def getdir(self, cwd):
# Get the items in a directory
for subdir, dirs, files in os.walk(cwd):
break
#print("Current directory:", cwd)
cleanfiles = []
for f in files:
if any(ext in f for ext in variablenames.agui_allowable_file_extensions):
# If theres a match in the allowable extensions, then save it
# Otherwise, dont.
cleanfiles.append(f)
# String-lengths of the allowable file extensions
filewidth = [len(i) for i in cleanfiles]
try:
# Width for output formatting.
filewidth = max(filewidth)+2
except ValueError:
# If theres no allowable extenstions, cleanfiles is of length 0
# And therefor has no max value in zero-len list.
filewidth = 0
if filewidth < 7:
# Is the minimum width of the file column in ascii format
filewidth = 7
dwidth = [len(i) for i in dirs]
try:
dwidth = max(dwidth)+2
except ValueError:
dwidth= 2
if dwidth < 13:
# is the minimum width of the directory column in the ascii output formatted table
dwidth = 13
crossbar_width = filewidth+dwidth+3+9
dirlongfile = len(dirs) > len(cleanfiles)
fixeddirs = []
fixedfiles = []
###########################
"""
If the file list and directory list are not of the same length,
make whichever list is shorter, as long as the longest width, filling
the missing values with sentinals (i.e. '') so that output formatting
can print the options.
"""
if dirlongfile:
for index,value in enumerate(dirs):
fixeddirs.append(value)
if index < len(cleanfiles):
fixedfiles.append(cleanfiles[index])
else:
fixedfiles.append(' '*filewidth)
else:
for index,value in enumerate(cleanfiles):
fixedfiles.append(value)
if index < len(dirs):
fixeddirs.append(dirs[index])
else:
fixeddirs.append(' '*dwidth)
##########################
######## BEGIN OUTPUT FORMATTING ###########
print('#'*crossbar_width)
print(str("{0:^1}{3:^8}{0:^1}{1:^"+str(filewidth)+"}{0:^1}{2:^"+str(dwidth)+"}{0:^1}").format("#","Files","Directories","LinNUM"))
print('#'*crossbar_width)
bbreak = False
for index, value in enumerate(fixedfiles):
print(str("{0:^1}{3:^8}{0:^1}{1:^"+str(filewidth)+"}{0:^1}{2:^"+str(dwidth)+"}{0:^1}").format('#', value, fixeddirs[index], index))
if index > 25:
bbreak = True
break
print('#'*crossbar_width)
if bbreak:
print("Printing exceeded 100 lines.")
return fixeddirs, fixedfiles, cleanfiles, dirs
def choice(self, fixeddirs, fixedfiles, cleanfiles, dirs, dironly, fileonly):
c = input("Enter Choice: ")
if 'help' in c.lower() or '?' in c.lower():
print("To navigate into a directory, enter choice in the format of: LineNum(d)\n\t ex: 1d")
print("To navigate out of the current directory, (into the parent of the current directory) enter choice in the format of: \'..\'\n\t ex: ..")
print("To select a directory, you must navigate into the directory you want to select. Then enter choice in the format of: \'ok\'\n\t ex: ok")
print("To select a particular file, enter choice in the format of: LineNum(f)\n\t ex: 1f")
return True, os.getcwd()
try:
if 'd' in c.lower():
item = int(c.split('d')[0])
if item in range(len(dirs)):
newpath = fixeddirs[item]
os.chdir(newpath)
return True, os.getcwd()
elif 'f' in c.lower() and not dironly:
item = int(c.split('f')[0])
if item in range(len(cleanfiles)):
newpath = fixedfiles[int(c.split('f')[0])]
return False, os.getcwd()+'/'+newpath
elif '..' == c:
os.chdir(c)
return True, os.getcwd()
elif 'ok' in c.lower() and not fileonly:
print('okay. Saving current directory choice.')
return False, os.getcwd()+'/'
except ValueError as e:
self.announcement("Invalid Choice.")
print(e)
return True, os.getcwd()
self.announcement("You selected " +c+ ' which is not a valid option.')
if dironly:
self.announcement("File browser is in DIRECTORY-only mode. Select a valid Directory.")
elif fileonly:
self.announcement("File browser is in FILE-only mode. Select a valid file.")
return True, os.getcwd()
def dict_selector(self, dic):
"""
expects a key:tupple unorganized dictionary where
tuple = [String, Function]
such that the string describes the properties of the function.
the "key"
has the function of not only being the ouput choice of this selector
function, but it also is the key to the tuple.
"""
def tableformatter(keys, strs):
len_keys = [len(key) for key in keys]
maxlen_keys = max(len_keys)+2
keydescribers = strs
len_keydescribers = [len(k) for k in keydescribers]
maxlen_key_descrbers = max(len_keydescribers)+2
maxlen_key_descrbers = 10 if maxlen_key_descrbers < 10 else maxlen_key_descrbers
xbar = maxlen_keys + maxlen_key_descrbers +4+8+1
print('#'*xbar)
print(str('{0:1}{1:^9}{0:1}{2:^'+str(maxlen_keys)+'}{0:1}{3:^'+str(maxlen_key_descrbers)+'}{0:1}').format('#','option#','name','describers'))
print('#'*xbar)
for index,value in enumerate(keys):
print(str('{0:1}{1:^9}{0:1}{2:^'+str(maxlen_keys)+'}{0:1}{3:^'+str(maxlen_key_descrbers)+'}{0:1}').format('#',index,value,keydescribers[index]))
print('#'*xbar)
return True
keys = dic.keys()
options = [i for i in range(len(keys))]
reconsile = dict(zip(options, keys))
keydescribers = []
for k in keys:
value = dic[k]
if type(value) == list:
keydescribers.append(dic[k][0])
else:
keydescribers.append(dic[k])
tableformatter(keys,keydescribers)
choices = 'hey'
while True:
try:
choices = int(input("Enter option number: "))
print("Your choice was", reconsile[choices], 'returning...')
break
except KeyboardInterrupt:
print('keyboard inturrupt recived. Breaking.')
raise KeyboardInterrupt
except ValueError as e:
print("Invalid input. Try again.", '\n'*2)
continue
except KeyError:
print("Incorrect Key. Make sure option number matches that which is in the table of options.")
continue
return reconsile[choices]
def announcement(self, mystr):
print('\n')
print("#"*3, mystr, '#'*3)
print('\n')
def header(self, mystr):
s = 7
lstr = len(mystr) +2
width = lstr+s*2+2
print("@"*width)
print(str("{0:1}{2:^"+str(s)+"}{1:^"+str(lstr)+"}{2:^"+str(s)+"}{0:1}").format("@",mystr, ' '*s))
print("@"*width)
def getNumInRange(self, a,b):
choice = None
maxn = max([a,b])
minn = min([a,b])
inputstring = 'Please enter a number between '+str(a) + ' ' + str(b) + ' or press enter to skip: '
while True:
r = input(inputstring)
if r == '':
print('Sentinal recieved - ignoring and returning.')
choice = 0
return choice
try:
choice = float(r)
if choice <= maxn and choice >= minn:
return choice
except ValueError:
print("ValueError, improper-input. Numbers only please, within the appropriate range.")
def getMDY(self, end=False):
x = ''
date = None
while type(date) != datetime.datetime:
try:
if end:
print("Press ENTER if the start and end DATE are the same.")
k = input("Your Date: ")
if end and k == '':
return None
date = datetime.datetime.strptime(k, "%m/%d/%Y")
return date
except KeyboardInterrupt:
print("Inturrupt Recieved")
raise KeyboardInterrupt
except:
print("Invalid Format. Enter date in MM/DD/YYYY format.")
def NMRAnalyzer():
"""
Get the baseline and rawsignal from the user.
"""
instance = nmrAnalyser(hardinit=True)
del instance
class nmrAnalyser(AsciiGUI):
def __init__(self,args='', hardinit=False, evademainloop=False):
# Intialize critical variables
matplotlib.use(variablenames.asciigui_matplotlib_backend_on)
self.rootdir = os.getcwd()
self.delimeter = variablenames.asciigui_default_delimiter
self.hardinit = hardinit
self.processes = 1 # The number of processing threads
self.servermode = False
self.analysisfile = pandas.DataFrame()
self.failedfiles = []
if hardinit:
self.servermode = False
self.processes = int(8*multiprocessing.cpu_count()/10)
print(self.processes, "Processing threads available")
if not evademainloop:
self.mainloop()
def overrideRootDir(self, override):
# Used only for the automate method.
self.rootdir = override
pass
def getBaseline(self):
# Gets the PATH for the baseline
self.announcement("Update Baseline")
print("Current working directory:",os.getcwd())
self.baselinepath = self.fileDirectorySelector(fileonly=True)
os.chdir(self.rootdir)
self.announcement("Baseline path updated")
def getRawsig(self):
# Gets the PATH for the rawsig
self.announcement("Update Raw Signal")
print("Current working directory:",os.getcwd())
self.rawsigpath = self.fileDirectorySelector(fileonly=True)
os.chdir(self.rootdir)
self.announcement("Raw Signal path updated")
def refreshAnalysis(self):
# Resets basic settings in the instance needed for
# when any nmr signal is re-loaded into the signal
# or the user decides to re-bin the data.
self.automatefits = []
self.fitnumber = 0
self.xname = variablenames.agui_xname_default
self.yname = variablenames.agui_yname_default
self.blSkipLinesGetter()
self.rawsigSkipLinesGetter()
self.updateDataFrame()
def collectFiles(self): #diagnostic only
self.blSkipLinesGetter()
self.rawsigSkipLinesGetter()
self.updateDataFrame()
def diagnosticFitting(self): #diagnostic only
self.updateIndecies()
npriev = self.startcolumn[0]
for index, tupp in enumerate(self.automatefits):
f = tupp[0] # Function name (sin, third-order, fourth-order ... , exponential)
# Litterally eval()'ed, dont tell opsec, or Professor Arvind Narayan that I did this
n = tupp[1] # The name that the user gave their template fit before clicking the "fit data" button
# Used to itteratively map / shift fitting, and naming of fits, subtractions, etc.
self.df, fig, chsq, rawsigfit, self.didfailfit = v.gff(
self.df, self.start_index, self.end_index, fit_sans_signal=True,
function=[f], fitname=n, x=self.xname,
binning=self.binning, gui=True, redsig=True,
y=npriev, plottitle=self.plottitle
)
npriev = tupp[1]
def fetchArgs(self, **kwargs):
self.isautomated = kwargs.pop('isautomated', False)
self.diagnostic = kwargs.pop('diagnostic', False)
if self.isautomated or self.diagnostic:
self.baselinepath = kwargs.pop('baselinepath', '')
self.rawsigpath = kwargs.pop('rawsigpath', '')
self.material_type = kwargs.pop('material_type', '') # User defined that tagges NMR sweeps in global_analysis
self.fitnumber = kwargs.pop('fitnumber',0) # The user does not see this, but it is used to generate unique names during fit and fit subtractions.
self.automatefits = kwargs.pop('automatefits',[]) # Is the list that the program tracks to apply fits during the automate method
self.mutouse= kwargs.pop('mutouse','proton') # string that controls what statistcs are used in TE equation. (spin 1/2 v. spin 1)
self.binning= kwargs.pop('binning',1) # Binning of NMR data
self.integrate= kwargs.pop('integrate', False) # Shading of NMR user selected region
self.vnavme= kwargs.pop('vnavme', variablenames.agui_vnavme_default)
self.startindex= kwargs.pop('startindex',0) #NMR Analyzer used
self.signalstart= kwargs.pop('signalstart',0) #User selected start
self.signalend=kwargs.pop('signalend',0) #User selected end
self.endindex= kwargs.pop('endindex',1) #NMR Analyzer used
self.fitlorentzian = kwargs.pop('fitlorentzian',False) # Fits a lorentzian to current signal.
self.xname= kwargs.pop('xname',variablenames.agui_xname_default) # Current name to get the xaxis data from pandas dataframe
self.xaxlabel= kwargs.pop('xaxlabel',self.xname) # xax plot label
self.yname= kwargs.pop('yname',variablenames.agui_yname_default) # Current name to get the xaxis data from pandas dataframe
self.yaxlabel= kwargs.pop('yaxlabel',self.yname) # yax plot label
self.impression= kwargs.pop('impression',variablenames.agui_impression) # If the user wants to generate an impression of the data
# This will substantially slow down the program.
self.xmin= kwargs.pop('xmin', '') # User selected x minimum for signal region
self.xmax= kwargs.pop('xmax', '') # User selected x maximum for signal region
self.startcolumn = kwargs.pop('startcolumn',[]) # The column in which it's appropriate to begin looking at in the automate method.
self.instancename = kwargs.pop('instancename', datetime.datetime.now().strftime('%Y%m%d_%H%M%s Instance')) # Instance name, similar to material type that tagges global_analysis entries with a unique
# name that is preserved throughout the automate method.
self.plottitle= kwargs.pop('title',self.rawsigpath.split('/')[-1]) # Default plot title. (Name of the first file that's selected.)
self.self_itemseed = kwargs.pop('the_new_list', None) # Used to track data during the refitting portion of the NMR automate method - when failed fits occured.
self.filelist = kwargs.pop('filelist', []) # The automate method's todo list in terms of files to analyze.
if not self.hardinit:
self.processes = kwargs.pop('processes',1)
self.blSkipLinesGetter() # Find the header size of the bl file
self.rawsigSkipLinesGetter() # Find the header size of the rawsig file
self.updateDataFrame() # Generate dataframe based on the user selected filed
if self.isautomated or self.diagnostic:
# If it's automated, skip the subsequent functions since they were already passed
# into the fetchArgs(**kwargs)
return True
self.updateMaterialType()
self.updateInstanceName()
self.updateGraph()
def blSkipLinesGetter(self):
# Collects the number of lines in the header of the baseline file
# that the program needs to know to skip
delimeter = self.delimeter
choices = self.vnavme
_, _, _, self.blskiplines = v.gui_bl_file_preview(self.baselinepath, self.delimeter)
def updateInstanceName(self):
# Updates the user-defined tag of the analysis-session name.
# The session name allows the user to keep track of particular analysis
# sets during a larger chain of analyses.
self.announcement("Current instance name: "+self.instancename)
self.instancename = input("Input new instance name: ")
def rawsigSkipLinesGetter(self):
# Collects the number of lines in the header of the raw signal file
# that the program needs to know to skip
_, _, self.te_date, self.I, self.T, self.primary_thermistor,\
self.secondary_thermistor, self.rawsigskiplines, self.centroid,\
self.spread = v.gui_rawsig_file_preview(self.rawsigpath,self.delimeter,self.vnavme)
try:
self.B = round(int(self.I)/9.7332,4)
except (ValueError,TypeError):
print("WARNING: No Magnet current exists in", self.rawsigpath.split('/')[-1],
"TE-Value will NOT be calculated")
self.B = self.I
def updateDataFrame(self):
# Re-reads the baseline and the rawsignal file
# and populates a pandas dataframe accordingly.
self.df = v.gui_file_fetcher(
self.rawsigpath, self.baselinepath,
self.vnavme,
blskiplines=self.blskiplines, rawsigskiplines=self.rawsigskiplines,
binning=self.binning
)
def changeSignalStartEnd(self):
self.announcement("Changing start / end of signal boundaries. Use current x-coordinates.")
print("To skip changing value for a particular entry, please hit ENTER")
startsignal = input("Signal Start X-value: ")
if startsignal == '':
pass
else:
self.signalstart = float(startsignal)
endsignal = input("Signal End X-Value: ")
if endsignal == '':
pass
else:
self.signalend = float(endsignal)
self.updateGraph()
def updateMaterialType(self):
self.announcement("Current material type: "+self.material_type)
self.material_type = input("Input new material type: ")
def updateIndecies(self):
try:
self.start_index = self.df.index[self.df[self.xname] == \
v.nearest(float(self.signalstart),
self.df[self.xname])][0]-\
self.df.index[0]
self.end_index = self.df.index[self.df[self.xname] == \
v.nearest(float(self.signalend),
self.df[self.xname])][0]-\
self.df.index[0]
except IndexError:
print("Some index error was raised at the index finding for"
"the pandas dataframe when you entered the "
"signal start and end information")
print("Could be due to malformed signal range. Please recheck your inputs.")
except:
print("Error in index finding. Signal highlighting failed.")
def updateGraph(self, graph=None, repeat=False, p_title=None, automated=False):
self.updateIndecies()
if graph is None:
plt.clf()
plt.close('all')
b = self.B
T = self.T
try:
xmin = float(self.xmin)
xmax = float(self.xmax)
except ValueError:
xmin =self.xmin
xmax = self.xmax
try:
fls, fle = float(self.signalstart), float(self.signalend)
except ValueError:
fls, fle =0,0
pass # It doesn't even matter if this fails because of fltest.
# Get that plot title during automation
plot_title = p_title if p_title is not None else self.plottitle
fltest = self.fitlorentzian
ub = 9.274009994*10**(-24) # Bohr Magnetron
up = 1.521*10**(-3)*ub # Proton Magnetic Moment
ud = 0.307012207*up # doi.org/10.1016/j.physleta.2003.09.030
temuval = up if self.mutouse == "proton" else ud
#print(self.mutouse)
quirky = v.ggf(
self.df, self.start_index, self.end_index, gui=True,
plttitle=plot_title, x=self.xname, y=self.yname,
xlabel=self.xaxlabel, ylabel=self.yaxlabel,
redsig=True if [self.start_index, self.end_index] != [0, len(self.df)]\
else False,
binning=int(self.binning),
integrate=self.integrate,
fitlorentzian=fltest, fitlorentziancenter_bounds=[fls,fle],
b=b, T=T, # Its okay if type isnt right, because below line ensures type
thermal_equalibrium_value=True if type(b) == float and type (T) == float\
else False,
xmin=xmin if type(xmin) == float else None, xmax=xmax if type(xmax) ==\
float else None,filename=self.rawsigpath,
clearfigs=True, automated=automated, temu=temuval
)
self.tlorentzian_chisquared = quirky.pop('tristan lorentzian chisquared',None)
self.klorentzian_chisquared = quirky.pop('karl chisquared', None)
self.sigmaforchisquared = quirky.pop("karl sigma", None)
self.figure = quirky['fig']
self.data_cal_constant = quirky.pop("data_cal_constant", None)
self.fit_cal_constant = quirky.pop("fit_cal_constant", None)
self.tevalue = quirky.pop("TE_Value", None)
self.dataarea = quirky.pop('data_area', None)
self.ltzian_integration = quirky.pop('ltzian_integration', None)
self.df = quirky.pop('df', None)
self.ltzian_a = quirky.pop('a', None)
self.ltzian_w = quirky.pop('w', None)
self.ltzian_x0 = quirky.pop('x0',None)
self.sigma_error = quirky.pop('noisesigma', None)
else:
self.figure = graph
def mainloop(self, failedfit=False, diagnostic=False):
try:
if not diagnostic:
if not failedfit:
self.getBaseline()
them = '/'.join(self.baselinepath.split('/')[:-1])
os.chdir(them)
os.chdir('..')
self.getRawsig()
self.fetchArgs()
else:
self.blSkipLinesGetter()
self.rawsigSkipLinesGetter()
self.updateDataFrame()
#self.updateMaterialType()
#self.updateInstanceName()
self.updateGraph()
while True:
print("#"*70)
self.currentSettings()
print("#"*70)
self.header("Data frame head")
print("#"*70)
print(self.df.head(3))
self.figure.show()
_ = self.allchoices(failedfit)
if _ == "triggerAutomateMethod":
break
elif _ == "giveUpRefitting":
break
except KeyboardInterrupt:
if diagnostic:
pass
else:
print("Keyboard Inturrupt recieved in mainloop. Exiting.")
return True
def allchoices(self, failedfit):
nameinstancemsg = "Label this current analysis cycle in the global analysis file."
mumsg= 'Toggles between two available mu values for the TE equation'
binningmsg = 'Bin width for the data'
signalstartendmsg = 'Update start and end x-axis values to mark signal region'
fit_subtractionmsg = 'Fit subtract current-data'
integratemsg = 'Shade region below signal selection on graph. Useful for conceptualizing signal area'
lorentzian_rawfitmsg = 'Fit lorentzian to current data selection.'
xnamemsg = 'Select different x-axis for plot'
ynamemsg = 'Select different y-axis for plot'
xaxlabelmsg = 'Set x-axis label'
yaxlabelmsg = 'Set y-axis label'
titlemsg = 'Change the plot title'
automatemsg = 'Take all previous settings and apply them to the rawsignal directory'
savefigmsg = 'Save the current figure as is.'
savedatamsg ='Save the current data as is'
savefiganddatamsg ='Save the current figure and data as is'
updatebaselinemsg = "Update baseline file"
updaterawsigmsg = "Update signal file"
changematerialmsg = "Update Material Type"
ignorefilemsg = "Ignore / Skip refitting of this file"
giveupmsg = "This data is insufferable: I'm done re-fitting"
if failedfit:
choices = {
"binning":[binningmsg, self.setBinning],
'signal highlighting':[signalstartendmsg, self.changeSignalStartEnd],
'fit subtraction':[fit_subtractionmsg, self.fitSubtract],
'toggleintegrate':[integratemsg, self.toggleIntegrate],
'fitlorentziancurve':[lorentzian_rawfitmsg, self.toggleLorentzian],
'x-data':[xnamemsg, self.changexname],
'y-data':[ynamemsg, self.changeyname],
'automate':[automatemsg, self.dudToReturnTrue],
'skip':[ignorefilemsg, self.pleaseSkipMe],
'giveup':[giveupmsg, self.giveUpRefitting]}
else:
choices = {
"binning":[binningmsg, self.setBinning],
'signal highlighting':[signalstartendmsg, self.changeSignalStartEnd],
'fit subtraction':[fit_subtractionmsg, self.fitSubtract],
'toggleintegrate':[integratemsg, self.toggleIntegrate],
'fitlorentziancurve':[lorentzian_rawfitmsg, self.toggleLorentzian],
'x-data':[xnamemsg, self.changexname],
'y-data':[ynamemsg, self.changeyname],
'xlabel':[xaxlabelmsg, self.changexlabel],
'ylabel':[yaxlabelmsg, self.changeylabel],
'plottitle':[titlemsg, self.changetitle],
'togglemu':[mumsg, self.adjustmu],
'savefiganddata':[savefiganddatamsg,self.saveBoth],
'automate':[automatemsg, self.automate],
"updatebaseline":[updatebaselinemsg, self.getBaseline],
"updaterawsignal":[updaterawsigmsg, self.getRawsig],
"updatematerial":[changematerialmsg, self.updateMaterialType],
"nameinstance":[nameinstancemsg, self.setInstanceName]}
key = self.dict_selector(choices)
f = choices[key][1]
if failedfit:
_ = f()
if _ == "triggerAutomateMethod":
return _
elif _ == "giveUpRefitting":
return _
else:
f()
if key in ["updatebaseline", "updaterawsignal"]:
self.refreshAnalysis()
self.updateGraph()
def giveUpRefitting(self):
return "giveUpRefitting"
def pleaseSkipMe(self):
try:
self.rawsigpath = self.filelist.pop(0)
self.failed_sindexes.pop(0)
self.failed_eindexes.pop(0)
self.failed_itemnos.pop(0)
except IndexError as e:
print("Index error (OUT OF FILES!) in re-fitting routine. Returning to normal:", e)
return "triggerAutomateMethod"
self.xname= variablenames.agui_xname_default
self.yname= variablenames.agui_yname_default
self.blSkipLinesGetter()
self.rawsigSkipLinesGetter()
self.updateDataFrame()
self.updateGraph()
def dudToReturnTrue(self):
return 'triggerAutomateMethod'
def currentSettings(self):
self.header("Current Settings:")
x = self.xname
lineone = "# Data Range: " + str(min(self.df[x]))+ ' to ' + str(max(self.df[x])) + ' ' + str(x) \
+ '\n# Current Signal Highlighting Region ' + str(self.signalstart) + ' to ' + str(self.signalend)+ ' ' + str(x)
linetwo = "# Shading: " + ('Enabled' if self.integrate else 'Disabled') \
+ " \n# Current binning: " + str(self.binning) + " \n# Current mu: " + str(self.mutouse.upper())
linethree = '# Current Baseline File: ' + str(self.baselinepath) + '\n# Current Raw-Signal File: '+ str(self.rawsigpath)
lines = [lineone, linetwo]
print(lineone, linetwo, linethree, sep='\n')
def setInstanceName(self):
self.announcement("Current instance name is: "+self.instancename)
self.instancename = input("Input new instance name: ")
print("Instance name changed to", self.instancename)
def toggleLorentzian(self):
self.fitlorentzian = not self.fitlorentzian
self.updateGraph()
def setBinning(self):
self.announcement('Please note that updating the data binning will reset the current session.')
self.announcement('Current binning is '+str(self.binning)+'.')
print('Please select new binning')
choices = 'im a string.'
while type(choices) != int:
try:
choices = int(input("Enter bin width: "))
except KeyboardInterrupt:
print('keyboard inturrupt recived. Breaking.')
return False
except ValueError as e:
print("Invalid input. Try again.", '\n'*2)
self.binning = choices
self.refreshAnalysis()
self.updateDataFrame()
self.updateGraph()
def adjustmu(self):
allowable_mus = ['proton', 'deuteron']
print("Current mu is", self.mutouse)
protonmsg = 'Proton Mu'
deuteronmsg = 'Deuteron Mu'
messages = [protonmsg, deuteronmsg]
choices = dict(zip(allowable_mus, messages))
self.mutouse = self.dict_selector(choices)
print("Mu is now: ", self.mutouse)
self.updateGraph()
def toggleIntegrate(self):
self.integrate = not self.integrate
print("Shading toggle is now", 'on' if self.integrate else 'off')
self.updateGraph()
def changexname(self):
self.announcement("Current X name "+str(self.xname))
columns = self.df.columns.tolist()
columnmsg = "Column in dataframe."
print("available columns:")
nice = [columnmsg for _ in range(len(columns))]
choices = dict(zip(columns, nice))
self.xname = self.dict_selector(choices)
self.xaxlabel = self.xname
self.updateGraph()
def overrideYname(self, yname):
self.yname = yname
self.yaxlabel = self.yname
self.updateGraph()
def changeyname(self):
self.announcement("Current Y name "+str(self.yname))
columns = self.df.columns.tolist()
columnmsg = "Column in dataframe."
print("available columns:")
nice = [columnmsg for i in range(len(columns))]
choices = dict(zip(columns, nice))
self.overrideYname(self.dict_selector(choices))
def changexlabel(self):
self.announcement("Current xlabel "+str(self.xaxlabel))
self.xaxlabel = input("Input xlabel: ")
self.updateGraph()
def changeylabel(self):
self.announcement("Current ylabel "+str(self.yaxlabel))
self.yaxlabel = input("Input xlabel: ")
self.updateGraph()
def __user_fit_selection__(self):
keys = ['Sin', 'Third order Polynomial', 'Fourth order Polynomial',
'Fifth Order Polynomial', 'Sixth Order Polynomial',
'True Lorentzian',"Lorentzian (absorbtion/dispersion)", "Cancel Fit"]
values = ['sin', 'third_order', 'fourth_order', 'fifth_order',
'sixth_order','lorentzian_ellie','absorbtion_dispersion_ellie', "Cancel Fit"]
choices = dict(zip(keys,values))
reverse = dict(zip(values,keys))
self.fitname = self.dict_selector(choices)
if self.fitname == False:
print("Fit subtraction cancelled")
return True
self.type_of_fit = choices[self.fitname]
self.fitname = self.fitname +str(' '+str(self.fitnumber))
#print("Fit name",self.fitname, "Function Name", self.type_of_fit)
def __ensure_unique_fit__(self):
test = len(self.automatefits)-1
if test >= 0:
if self.automatefits[test][1] == self.fitname:
print("\nWARNING: Previous fit named:", self.automatefits[test][1],
"was overridden.\nChange fit name if you are doing multiple subtraction\n")
self.automatefits[test] = [self.type_of_fit, self.fitname]
self.startcolumn[test] = self.yname
else:
self.automatefits.append([self.type_of_fit, self.fitname])
self.startcolumn.append(self.yname)
else:
self.automatefits.append([self.type_of_fit, self.fitname])
self.startcolumn.append(self.yname)
def __fitbound_coersion__(self):
try:
p0 = [float(self.lorentzian_x0), float(self.lorentzian_w),
float(self.lorentzian_A), float(self.lorentzian_B)]\
if self.fitname == "lorentzian_ellie" else None
bounds = [[float(self.lorentzian_x0)-.1, -numpy.inf,
float(self.lorentzian_A)-.05, -numpy.inf],
[float(self.lorentzian_x0)+.1, numpy.inf, float(self.lorentzian_A)+\
.05, numpy.inf]] if self.fitname == "lorentzian_ellie" else \
[[-numpy.inf, -numpy.inf, -numpy.inf, -numpy.inf ],
[numpy.inf,numpy.inf,numpy.inf,numpy.inf]]
except ValueError:
print("***WARNING: Error in type conversion for RAWSIGNAL fit \
coersion. p0 WILL NOT be passed.")
p0 = None
return p0, bounds
def fitSubtract(self,automated=False):
# User selection of fit #
if self.__user_fit_selection__():
return True
# Free some memory
if not automated:
plt.clf()
plt.close('all')
# don't duplicate fits #
self.__ensure_unique_fit__()
# Update the indecies before we fit the data
self.updateIndecies()
# Collect p0 / bounds if it exists #
p0, bounds = self.__fitbound_coersion__()
# Fit the function #
self.df, fig, chsq, rawsigfit, self.didfailfit = v.gff(
self.df, self.start_index, self.end_index, fit_sans_signal=True,
function=[self.type_of_fit], fitname=self.fitname,
binning=self.binning, gui=True, redsig=True, x=self.xname,
y=self.yname, plottitle=self.plottitle, p0=p0, bounds = bounds)
if self.didfailfit and not automated:
print('Fit failed, try another.')
self.disapprovePlot()
return True
self.e_f0= rawsigfit.pop('e_f0', None)
self.e_w=rawsigfit.pop("e_w", None)
self.e_kmax=rawsigfit.pop('e_kmax', None)
self.e_theta=rawsigfit.pop("e_theta", None)
print(" "*15, "CHI SQUARED VALUES FOR EACH FIT")
print("#"*65)
for key in chsq:
val = chsq[key]
print("{0:<1s}{1:^5s}{0:1s}{2:^31s}{0:1s}{3:^25s}{0:1s}"\
.format("#","Fit", key, str(val)))
#print("#Fit #\t", key, " #\t Chisquared:", val, " #")
print("#" * 65)
self.updateGraph(graph=fig)
# User approve/deny #
if not automated:
if not self.servermode:
self.figure.show()
cancelmsg = 'Cancel the fit subtraction, and do not change the graph.'
approvemsg = 'The fit looks good, let me see the fit subtraction'
disapprovemsg = 'The fit looks bad, let me redo it.'
choices = {'approve':[approvemsg, self.approvePlot],
'disapprove':[disapprovemsg, self.disapprovePlot],
'cancel':[cancelmsg,self.cancelFit]}
key = self.dict_selector(choices)
f = choices[key][1]
f(manual=True)
elif automated:
self.approvePlot()
def approvePlot(self, **kwargs):
availablecolums = self.df.columns.to_list()
(fit_data, fitsubtraction) = availablecolums[-2:]
self.yname = fitsubtraction
self.updateGraph()
self.fitnumber += 1
def disapprovePlot(self, manual=False):
if not manual:
self.announcement("Plot rejected. Try alternate fitting strategy, or adjust signal highlighted region")
self.fitSubtract()
def cancelFit(self, manual='False'):
self.updateGraph()
return False
def changetitle(self):
c = input("Input new plot title: ")
self.plottitle = c
self.updateGraph()
def saveFig(self,filename=None, automated=False):
filename = self.plottitle if filename is None else filename
self.updateGraph(automated=automated)
plt.savefig(filename)
def updateItemSeed(self, itemseed):
# Reseed the item in the class.
# Used for multithreading
self.item=itemseed
def getFileList(self):
print("Filelist")
print(self.filelist)
def automate(self, **kwargs):
"""
Replicated from the tkinter version of the gui
"""
addition = kwargs.pop("addition", '')
singleThread = False
matplotlib.use(variablenames.asciigui_matplotlib_backend_off) # Thwarts X-server Errors
# Matplotlib is NOT thread-safe w/ known race conditions.
# Care has been used to avoid these conditions (unique namespaces (instances of this class) should isolate mpl stacks from eachother.)
# Let me know if I missed any.
##################################################
# Ensure Directories exist where we can put file #
##################################################
os.chdir(self.rootdir)
home = self.rootdir
os.chdir(home)
try:
os.chdir("graphs")
except FileNotFoundError:
os.mkdir("graphs")
os.chdir(home)
try:
os.chdir("graph_data")
except FileNotFoundError:
os.mkdir("graph_data")
os.chdir(home)
graphs = home+"/graphs/"
graphdata = home+"/graph_data/"
tedirectory = "/".join(self.rawsigpath.split('/')[:-1])
tefiles = []
#########################################################
extension = ".ta1" if self.vnavme.upper() == "VME" else ".s1p"
# Create the TE/Enchanced files list
for file in os.listdir(tedirectory):
if file.endswith(extension):
tefiles.append(tedirectory+'/'+file)
# create a list of tuples that split the files between multiple threads
oh_indexes = self.__forkitindexer__(tefiles)
# Used to create unique instance names so pandas doesn't overwrite identical entries. (also human readability)
self.workpool = []
self.plottitle = self.instancename if self.plottitle == self.rawsigpath.split('/')[-1] else self.plottitle
for index, value in enumerate(oh_indexes):
(start, end) = value
self.workpool.append(nmrAnalyser(evademainloop=True))
self.workpool[index].overrideRootDir(self.rootdir)
self.workpool[index].fetchArgs(fitnumber='fitnumber',
automatefits= self.automatefits,
material_type = self.material_type,
mutouse= self.mutouse,
binning= self.binning,
integrate= self.integrate,
vnavme= self.vnavme,
signalstart= self.signalstart,
signalend=self.signalend,
fitlorentzian= self.fitlorentzian,
xname= self.xname,
xaxlabel= self.xaxlabel,
yname= self.yname,
yaxlabel= self.yaxlabel,
xmin= self.xmin,
xmax= self.xmax,
startcolumn= self.startcolumn,
instancename= self.instancename,
title= self.plottitle,
isautomated= True,