-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathARC-TF.py
2353 lines (1885 loc) · 106 KB
/
ARC-TF.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import tkinter as tk
from tkinter import ttk
from tkinter import filedialog as fd
from PIL import ImageTk, Image
import webbrowser
from matplotlib.pyplot import axhline
import matplotlib
matplotlib.use('Agg')
from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg, NavigationToolbar2Tk)
from matplotlib.figure import Figure
import os
import math
from shutil import copy2
import numpy as np
from Include.Analyze import*
from Include.Calibration import*
from Include.FitData import*
from Include.Eloss import*
from Include.Thick import*
########## Ajusta-se ao ecra e foca os widgets - Windows ######
import ctypes
ctypes.windll.shcore.SetProcessDpiAwareness(1)
###########################################################
# Returns the index of the Tab the user is on
###########################################################
def Current_Tab():
final_num = Notebook.notebook.index(Notebook.notebook.select()) - 1 # Devolve o id da tab onde o utilizador se encontra # Vai buscar o numero na string do id
# Altera-se o valor para corresponder aos indices da lista
if final_num >= 0:
return final_num
elif final_num < 0: # Para o caso do utilizador se encontrar na tab dos resultados finais
pass
#########################################################################################
# Apaga as widgets dentro de frames e tira a geometria de frames, para fazer renovacao
# de dados. Podera conter, eventualmente, mais frames do que contem agora
#########################################################################################
def ClearWidget(Frame, parameter):
num = Current_Tab()
if Frame == 'Graphic':
## Delete old plot and build new one
for widget in TabList[num][1].GraphicFrame.winfo_children():
widget.destroy()
TabList[num][1].GraphicFrame.grid_remove()
widget = 0
for widget in TabList[num][1].Extra_Frame.winfo_children():
widget.destroy()
TabList[num][1].Extra_Frame.grid_remove()
elif Frame == 'Algorithm':
for widget in TabList[num][1].AlgFrame.winfo_children():
widget.destroy() #Destroi a opcao de widgets anteriores dos algoritmos
if parameter == 1:
TabList[num][1].Algorithm_Method.set('Select Algorithm to Run')
TabList[num][1].Algorithm.set(0)
elif Frame == 'Results':
for widget in TabList[num][1].ResultFrame.winfo_children():
widget.destroy() #Destroi os resultados anteriores dos algoritmos
TabList[num][1].ResultFrame.grid_remove()
if parameter == 1: #Porque o search do algoritmo de selecao manual reconstroi os widgets
# da frame sempre que se encontra um novo ponto, e necessario
# configurar o caso onde ha reset dos dados e o caso onde nao ha reset
if os.path.isfile(TabList[num][3]) == True:
os.remove(TabList[num][3])
elif Frame == 'Source': # Este for remove as opcoes de energia de decaimento das fontes de alphas
for widget in TabList[num][1].SourceOptionsFrame.winfo_children():
widget.destroy()
TabList[num][1].SourceOptionsFrame.grid_remove()
if parameter == 1:
TabList[num][1].Source.set('Radiation Sources')
elif Frame == 'Popup': # Remove os popups que existem no programa
for widget in wng.warning.winfo_children():
widget.destroy()
wng.warning.destroy()
elif Frame == 'Image': # Remove a imagem sempre que se clicar a comecar outra
for widget in wng.decay.winfo_children():
widget.destroy()
wng.decay.destroy()
elif Frame == 'Linear': # Remove os resultados da regressao linear
for widget in TabList[num][1].LinearRegressionFrame.winfo_children():
widget.destroy()
TabList[num][1].LinearRegressionFrame.grid_remove()
widget = 0
for widget in Notebook.Calib_Result2.winfo_children():
widget.destroy()
if parameter == 1: # Nem todas as opcoes necessitam de destruir os resultados,
# portanto existe o parametro, para fazer a escolha de apagar o documento
os.remove(TabList[num][4])
elif Frame == 'Thickness': # Remove os resultados do calculo da espessura
for widget in TabList[num][1].ThicknessFrame.winfo_children():
widget.destroy()
TabList[num][1].ThicknessFrame.grid_remove()
widget = 0
for widget in Notebook.Mat_Result2.winfo_children():
widget.destroy()
if parameter == 1: # Apaga os resultados escritos calculados da espessura
TabList[num][1].Mat.set('Select Material')
os.remove(TabList[num][4])
elif Frame == 'Final': # Para o caso de se apagarem tabs, o final results e atualizado
for widget in Notebook.Mat_Result2.winfo_children():
widget.destroy()
widget = 0
for widget in Notebook.Calib_Result2.winfo_children():
widget.destroy()
elif Frame == 'Everything': # Esta e a opcao que da reset a tudo numa tab
for widget in TabList[num][1].GraphicFrame.winfo_children():
widget.destroy()
widget = 0
TabList[num][1].GraphicFrame.grid_remove()
for widget in TabList[num][1].Extra_Frame.winfo_children():
widget.destroy()
TabList[num][1].Extra_Frame.grid_remove()
widget = 0
for widget in TabList[num][1].AlgFrame.winfo_children():
widget.destroy()
widget = 0
TabList[num][1].AlgFrame.grid_remove()
TabList[num][1].Algorithm_Method.set('Select Algorithm to Run')
TabList[num][1].Algorithm.set(0)
for widget in TabList[num][1].ResultFrame.winfo_children():
widget.destroy()
widget = 0
TabList[num][1].ResultFrame.grid_remove()
if TabTracker[num] < 0:
for widget in TabList[num][1].SourceOptionsFrame.winfo_children():
widget.destroy()
widget = 0
TabList[num][1].SourceOptionsFrame.grid_remove()
TabList[num][1].Source.set('Radiation Sources')
for widget in TabList[num][1].LinearRegressionFrame.winfo_children():
widget.destroy()
widget = 0
TabList[num][1].LinearRegressionFrame.grid_remove()
elif TabTracker[num] > 0:
for widget in TabList[num][1].ThicknessFrame.winfo_children():
widget.destroy()
TabList[num][1].ThicknessFrame.grid_remove()
TabList[num][1].Mat.set('Select Material')
if parameter == 1:
if os.path.isfile(TabList[num][3]) == True:
os.remove(TabList[num][3])
if os.path.isfile(TabList[num][4]) == True:
os.remove(TabList[num][4])
############################################################################################
# Funcao que le os ficheiros e devolve listas. Estas podem ser 2d ou 1d, podem ter separadores
# diferentes (entre as colunas) e pode devolver as listas como strings, floats ou ints
############################################################################################
def File_Reader(Document, Separator, Decimal, Upload):
num = Current_Tab()
with open(Document, 'r') as OpenFile: # Abre (e fecha) o documento
lines = OpenFile.read() # Le os dados como string
lines = lines.splitlines() #Separa o array em linhas
if Upload == 'Yes':
TabList[num][1].Real_Time.set(lines[8] + ' s')
if Separator != '0': # O separator verifica se temos uma matriz ou um vetor
# caso seja '0', o documento a ser lido e um vetor, e nao e necessario
# separar por colunas
Results = [[0 for i in range(1)]for j in range(len(lines))] # Inicio de uma matriz com entradas
# independentes
i = 0
for line in lines:
Results[i] = (line.split(Separator)) # Aqui separam se as colunas
i += 1
i = 0
j = 0
for j in range(0, len(lines)): # Neste ciclo, sao transformados os resultados em int ou float,
# conforme o input
for i in range(0, len(Results[0])):
if Results[j][i] == '':
pass
elif Decimal == 'Yes':
Results[j][i] = float(Results[j][i])
elif Decimal == 'No':
Results[j][i] = int(Results[j][i])
return Results
else:
i = 0
if Decimal == 'String': # Caso queiramos apenas uma string, a funcao devolve logo o vetor lines
return lines
else:
for i in range(0, len(lines)): # Aqui transforma se o vetor string em int ou float e devolve
if Decimal == 'Yes':
lines[i] = float(lines[i])
elif Decimal == 'No':
lines[i] = int(lines[i])
return lines
##############################################################################################
# Devolve o numero de algarismos significativos com base numa incerteza
###############################################################################################
def Precision(value):
counter = 0
number = float(value)
if abs(number) < 1:
while abs(number) < 1:
number = number * 10
counter += 1
counter = counter + 1
return counter
elif abs(number) > 1:
counter = 0
return counter
############################################################################################
# Le os resultados finais e exibe os na primeira tab
############################################################################################
def Final_Results(tracker):
num = Current_Tab()
method = TabList[num][1].Algorithm_Method.get()
if tracker < 0 and method == 'ROI Select':
LinearizeWithErrors()
elif tracker < 0 and method != 'ROI Select':
Linearize()
elif tracker > 0 and method != 'ROI Select':
Final_Calculation()
elif tracker > 0 and method == 'ROI Select':
ROI_Thick_Calculation()
elif tracker == 0:
pass
for i in range(0, len(TabTracker)):
if (tracker < 0 or tracker == 0) and TabTracker[i] < 0:
if os.path.isfile(TabList[i][4]) == True:
if TabList[i][1].energy.get() == 1000:
unit_energy = 'MeV'
elif TabList[i][1].energy.get() == 1:
unit_energy = 'keV'
Results = File_Reader(TabList[i][4], '0', 'String', 'No')
tk.Label(Notebook.Calib_Result2, text = 'Calibration Trial ' +
str(-TabTracker[i]) + ' - ' +
TabList[i][1].Source.get()).grid(row = 4 * i + i, columnspan = 3)
tk.Label(Notebook.Calib_Result2,
text = '(' + unit_energy + ')').grid(row = 4 * i + i + 1, column = 0)
tk.Label(Notebook.Calib_Result2,
text = 'Values').grid(row = 4 * i + i + 1, column = 1)
tk.Label(Notebook.Calib_Result2,
text = 'Uncertainty').grid(row = 4 * i + i + 1, column = 2)
tk.Label(Notebook.Calib_Result2,
text = 'Slope').grid(row = 4 * i + i + 2, column = 0)
tk.Label(Notebook.Calib_Result2,
text = 'Intersect').grid(row = 4 * i + i + 3, column = 0)
tk.Label(Notebook.Calib_Result2,
text = '').grid(row = 4 * i + i + 4, column = 0)
tk.Label(Notebook.Calib_Result2,
text = '%.*f' %(int(Results[5]), float(Results[1]))).grid(
row = 4 * i + i + 2, column = 1)
tk.Label(Notebook.Calib_Result2,
text = '%.*f' %(int(Results[5]), float(Results[2]))).grid(
row = 4 * i + i + 2, column = 2)
tk.Label(Notebook.Calib_Result2,
text = '%.*f' %(int(Results[6]), float(Results[3]))).grid(
row = 4 * i + i + 3, column = 1)
tk.Label(Notebook.Calib_Result2,
text = '%.*f' %(int(Results[6]), float(Results[4]))).grid(
row = 4 * i + i + 3, column = 2)
else:
Notebook.calib_canvas.update_idletasks()
Notebook.calib_canvas.config(scrollregion = Notebook.Calib_Result2.bbox())
Notebook.Calib_Result2.bind('<Configure>',
lambda e: Notebook.calib_canvas.configure(
scrollregion = Notebook.calib_canvas.bbox('all'), width = e.width))
if (tracker > 0 or tracker == 0) and TabTracker[i] > 0:
if os.path.isfile(TabList[i][4]) == True and os.path.isfile(TabList[i][3]) == True:
Results = File_Reader(TabList[i][4], '0', 'Yes', 'No')
Peaks = File_Reader(TabList[i][3], ',', 'Yes', 'No')
Peaks.sort()
units_list = ['nm', '\u03bcm',
'\u03bcg' + ' cm' + '{}'.format('\u207B' + '\u00b2'),
'10' + '{}'.format('\u00b9' + '\u2075') + ' Atoms'
+ ' cm' + '{}'.format('\u207B' + '\u00b3')]
units_values = [10.0**9, 10.0**6, 0.0, -1.0]
index = units_values.index(TabList[i][1].units.get())
size = len(Peaks)
for j in range(0, size):
if j == 0:
tk.Label(Notebook.Mat_Result2, text = 'Material Trial ' +
str(TabTracker[i]) + ' - ' +
TabList[i][1].Mat.get()).grid(row = (4 + size) * i + i + j , columnspan = 2)
tk.Label(Notebook.Mat_Result2,
text = 'Peak Centroid').grid(row = (4 + size) * i + i + j + 1, column = 0)
tk.Label(Notebook.Mat_Result2,
text = 'Thickness').grid(row = (4 + size) * i + i + j + 1, column = 1)
tk.Label(Notebook.Mat_Result2,
text = str("{:.1f}".format(Peaks[j][0]))).grid(row = (4 + size) * i + i + j + 2,
column = 0)
tk.Label(Notebook.Mat_Result2,
text = '%.*f' % (int(Results[-1]), Results[j]) +
' ' + units_list[index] ).grid(row = (4 + size) * i + i + j + 2,
column = 1)
tk.Label(Notebook.Mat_Result2,
text = '\nAverage').grid(row = (4 + size) * i + i + j + 3, column = 0)
tk.Label(Notebook.Mat_Result2,
text = 'Uncertainty').grid(row = (4 + size) * i + i + j + 4, column = 0)
tk.Label(Notebook.Mat_Result2,
text = '\n' + '%.*f' % (int(Results[-1]), Results[j + 1])
+ ' ' + units_list[index]).grid(
row = (4 + size) * i + i + j + 3, column = 1)
tk.Label(Notebook.Mat_Result2,
text = '%.*f' % (int(Results[-1]), Results[j + 2])
+ ' ' + units_list[index]).grid(
row = (4 + size) * i + i + j + 4, column = 1)
tk.Label(Notebook.Mat_Result2,
text = '').grid(row = (4 + size) * i + i + j + 5,
columnspan = 2)
Notebook.mat_canvas.update_idletasks()
Notebook.mat_canvas.config(scrollregion = Notebook.Mat_Result2.bbox())
Notebook.Mat_Result2.bind('<Configure>',
lambda e: Notebook.mat_canvas.configure(
scrollregion = Notebook.mat_canvas.bbox('all'), width = e.width))
else:
print('WDK')
else:
print('WTF')
###########################################################################################
# Permite a escolha de regressoes lineares por parte do utilizador
###########################################################################################
def Calib_Choice():
num = Current_Tab()
Measure = []
for i in range(0, len(TabList[num][1].Regression_List)):
TabList[num][1].Regression_List[i].set(-1)
# Este for previne as escolhas antigas de interferir com a nova selecao de regressoes
for i in range(0, len(TabTracker)):
if TabTracker[i] < 0: # Certifica que so le ficheiros com regressoes lineares
if os.path.isfile(TabList[i][4]) == True:
Measure.append(TabTracker[i])
# Neste ciclo, o measure regista quantas tabs de calibracao tem uma regressao linear,
# ja que o tabtracker identifica as tabs de calibracao como sendo negativas,
# o measure tera sempre valores entre -1 e -10
if not Measure:
wng.popup('No Linear Regressions detected')
tk.Label(wng.warning, text = 'No linear Regressions were detected.\n\n' +
'Please Perform a Calibration Trial before calculating the Film\'s Thickness.\n\n').pack()
tk.Button(wng.warning, text = 'Return', command = lambda: wng.warning.destroy()).pack()
# No caso do Measure estar vazio, aparece um aviso que nenhuma regressao linear foi efetuada
else: # Caso contrario, entra o popup para selecionar quais as regressoes a utilizar
wng.popup('Linear Regression Selection Menu')
tk.Label(wng.warning, text = 'Please Select a Calibration Trial \n' +
'Choosing more than one calibration will average the slopes and intersects.\n\n').pack()
for i in range(0, len(Measure)):
button_Choice = tk.Checkbutton(wng.warning,
text = 'Linear Regression of Calibration Trial ' +
str(-Measure[i]),
variable = TabList[num][1].Regression_List[i],
onvalue = -Measure[i], offvalue = -1)
button_Choice.pack()
# Neste ciclo, por cada regressao linear efetuada, o utilizador pode esolher utilizar uma ou
# mais, para a calibracao. A Regression_List guarda valores 1 ou -1 sendo que o indice desta
# lista, e utilizado depois nos calculos finais
tk.Button(wng.warning, text = 'Return', command = lambda: ClearWidget('Popup', 0)).pack()
################################################################################################
# Calcula a espessura por cada pico e a media das espessuras
################################################################################################
def Final_Calculation():
num = Current_Tab()
ClearWidget('Thickness', 0)
TabList[num][1].ThicknessFrame.grid(row = 5, columnspan = 3, pady = 5)
units_list = ['nm', '\u03bcm',
'\u03bcg' + ' cm' + '{}'.format('\u207B' + '\u00b2'),
'10' + '{}'.format('\u00b9' + '\u2075') + ' Atoms'
+ ' cm' + '{}'.format('\u207B' + '\u00b3')]
units_values = [10.0**9, 10.0**6, 0.0, -1.0]
index = units_values.index(TabList[num][1].units.get())
Material_choice = TabList[num][1].Mat.get() # Determina qual o ficheiro do material a ler
Material_choice = 'Files\Materials\\' + Material_choice + '.txt'
slope = 0
intersect = 0
points = []
regressions_index = []
material_data = File_Reader(Material_choice, '|', 'Yes', 'No') #Daqui obtemos a lista que ira guardar
# as energias e o stopping power do material em uso
# Este ciclo determina a tab de calibracao cuja regressao foi selecionada para uso
# o regressions_index guarda o indice do Tab Tracker
# Com este valor, podemos aceder ao indice do TabList para obter todos os dados que queiramos
for i in range(0, len(TabList[num][1].Regression_List)):
if TabList[num][1].Regression_List[i].get() != -1:
regressions_index.append(TabTracker.index(-TabList[num][1].Regression_List[i].get()))
i = 0
j = 0
Aux_Channel = []
Temp = []
for j in range(0, len(TabList[regressions_index[i]][1].DecayList)):
if TabList[regressions_index[0]][1].DecayList[j].get() != -1: # Aqui, vamos buscar os valores de
# decaimento que a utilizar para o intervalo
Aux_Channel.append(TabList[regressions_index[0]][1].DecayList[j].get()) # de stopping powers
# Como a fonte e a mesma para todas as calibracoes, nao importa qual delas e selecionada
Aux_Channel.sort()
peaks = len(Aux_Channel) # Para referencia do tamanho
for i in range(0, len(regressions_index)):
Aux = File_Reader(TabList[regressions_index[i]][4], '0', 'String', 'No') # Aqui
#vamos buscar as regressoes lineares para fazer uma media
if Aux[0] == 'keV':
placeholder1 = float(Aux[1]) * 1000
Aux[1] = str(placeholder1)
placeholder2 = float(Aux[3]) * 1000
Aux[3] = str(placeholder2)
slope = float(Aux[1]) + slope # Acumular o declive
intersect = float(Aux[3]) + intersect # Acumular a ordenada na origem
points = File_Reader(TabList[num][3], ',', 'No', 'No') # Analise dos picos de materiais em estudo
points.sort() # Ordenar os picos por ordem crescente
slope = slope / len(regressions_index) # Buscar a media do declive
intersect = intersect / len(regressions_index) # Buscar a ordenada na origem
i = 0
j = 0
Aux.clear()
thickness = 0
tk.Label(TabList[num][1].ThicknessFrame,
text = 'Thickness (' + units_list[index] + ')').grid(row = 0, column = 0)
tk.Label(TabList[num][1].ThicknessFrame, text = 'Channel').grid(row = 0, column = 1)
for j in range(0, peaks):
Temp.append((slope * points[j][0]) + intersect ) # Calibracao dos picos do material
uncertain = 0 # Ira devolver a incerteza da media da espessura
summed_values = 0 # Faz o somatorio dos valores do stopping power
i = 1
for i in range(1, len(material_data)): # O ciclo comeca em 1 porque a linha 0 tem a densidade e
# o numero atomico
if material_data[i][0] >= Temp[j] and material_data[i][0] <= Aux_Channel[j]:
stopping_power = ( 1 / material_data[i][1]) # Stopping power a dividir pelo step
summed_values = summed_values + stopping_power # O somatorio que
#resulta na aproximacao da espessura
if index == 0 :
summed_values = summed_values / material_data[0][1]
summed_values = summed_values * 10000
if index == 1:
summed_values = summed_values / material_data[0][1]
summed_values = summed_values * 10
if index == 2:
summed_values = summed_values * 0.001
if index == 3:
summed_values = summed_values * 1000 * ((6.02214076**(-23)) / material_data[0][0])
Aux.append(summed_values) # Lista que guarda a espessura por perda de energia
thickness = thickness + (Aux[j]) # Espessua media
tk.Label(TabList[num][1].ThicknessFrame, text = '%.2f' % (Aux[j]) ).grid(
row = j + 1, column = 0)
tk.Label(TabList[num][1].ThicknessFrame, text = str(points[j][0])).grid(
row = j + 1, column = 1)
if j == peaks - 1: # No ultimo run do ciclo for
i = 0
thickness = thickness / len(Aux) # A fazer a media da espessura
my_file = open(TabList[num][4], 'w')
for i in range(0, len(Aux)): # Por fim faz se a incerteza da espessura media
uncertain = (Aux[i] - thickness)**2 + uncertain
my_file.write('%.3f' %(Aux[i]))
my_file.write('\n')
uncertain = uncertain / (peaks - 1)
uncertain = math.sqrt(uncertain) # Ultimo passo que resulta na espessura certa
sig_fig = Precision(('%.2g' % (uncertain)))
my_file.write(str(thickness) + '\n')
my_file.write(str(uncertain) + '\n')
my_file.write(str(sig_fig))
my_file.close()
tk.Label(TabList[num][1].ThicknessFrame,
text = 'Average Thickness (' + units_list[index] + ')').grid(row = j + 2, column = 0)
tk.Label(TabList[num][1].ThicknessFrame,
text = 'Uncertainty (' + units_list[index] + ')').grid(row = j + 2, column = 1)
tk.Label(TabList[num][1].ThicknessFrame,
text = '%.*f' %(sig_fig, thickness)).grid(row = j + 3, column = 0)
tk.Label(TabList[num][1].ThicknessFrame,
text = '%.*f' %(sig_fig, uncertain)).grid(row = j + 3, column = 1)
tk.Button(TabList[num][1].ThicknessFrame,
command = lambda: ClearWidget('Thickness', 1),
text = 'Reset Results').grid(row = j + 4, columnspan = 2)
#########################################################################################
# Calculo da espessura no método ROI Select
########################################################################################
def ROI_Thick_Calculation():
num = Current_Tab() ## Get current tab's index nr
ClearWidget('Thickness', 0)
TabList[num][1].ThicknessFrame.grid(row = 5, columnspan = 3, pady = 5)
units_list = ['nm', '\u03bcm',
'\u03bcg' + ' cm' + '{}'.format('\u207B' + '\u00b2'),
'10' + '{}'.format('\u00b9' + '\u2075') + ' Atoms'
+ ' cm' + '{}'.format('\u207B' + '\u00b3')]
units_values = [10.0**9, 10.0**6, 0.0, -1.0]
index = units_values.index(TabList[num][1].units.get())
calibration = TabList[num][1].Regression_List[0].get() ## vamos selecionar apenas uma calibração
## Get the selected material and stop. pow.
Material_choice = TabList[num][1].Mat.get() # Determina qual o ficheiro do material a ler
Material_choice = 'Files\Materials\\' + Material_choice + '.txt'
material_data = File_Reader(Material_choice, '|', 'Yes', 'No') #Daqui obtemos a lista que ira guardar
## Get energies of selected source
energies = [TabList[0][1].DecayList[k].get() for k in range(len(TabList[0][1].DecayList))]
energies.remove(-1.0) ## Remove unselected energies
## Get slope and intercept of the selected calib
calib_params = File_Reader(TabList[0][4], '0', 'String', 'No')
## Check energy units to match the stop. pow. ones
if calib_params[0] == 'keV':
m = str(float(calib_params[1])*1000) ## slope
dm = str(float(calib_params[2])*1000) ## slope uncertainty
else: ### !!!!!!!!!! VERIFICAR ESTA PARTE !!!!!!!!!!! ###
m = str(float(calib_params[1])*1000)
dm = str(float(calib_params[2])*1000)
## Get calibration centroids
calibCents = [File_Reader(TabList[0][3], ',', 'Yes', 'No')[k][0] for k in range(len(File_Reader(TabList[0][3], ',', 'Yes', 'No')))]
## Get calibration peak error
calibErr = [File_Reader(TabList[0][3], ',', 'Yes', 'No')[k][1] for k in range(len(File_Reader(TabList[0][3], ',', 'Yes', 'No')))]
## Get film centroids
filmCents = [File_Reader(TabList[num][3], ',', 'Yes', 'No')[k][0] for k in range(len(File_Reader(TabList[num][3], ',', 'Yes', 'No')))]
## Get film peak error
filmErr = [File_Reader(TabList[num][3], ',', 'Yes', 'No')[k][1] for k in range(len(File_Reader(TabList[num][3], ',', 'Yes', 'No')))]
## Calculate energy loss and uncertainty, returning min and max energy of alphas after crossing the film
Emin, Emax, eloss = Eloss(energies, calibCents, filmCents, calibErr, filmErr, m, dm)
## Get selected material stop. pow.
Material_choice = TabList[num][1].Mat.get()
Material_choice = 'Files\Materials\\' + Material_choice + '.txt'
material_data = File_Reader(Material_choice, '|', 'Yes', 'No')
## Calculate thickness from energy loss
## for each peak
thickPeak = Thickness(energies, Emin, Emax, material_data)
## the mean of all peaks
meanThick = np.mean([thick for thick in thickPeak])
## Calculate mean thickness std deviation
stdDevThick = np.std(thickPeak)
## Write results to file
result_file = open(TabList[num][4], 'w')
for i in range(0, len(thickPeak)):
result_file.write(str("{:.0f}".format(thickPeak[i]))+'\n')
result_file.write(str(meanThick) + '\n')
result_file.write(str(stdDevThick) + '\n')
result_file.write(str(0))
result_file.close()
## Display results in the frame
## header
tk.Label(TabList[num][1].ThicknessFrame, text = 'Peak Energy\n(MeV)').grid(row = 0, column = 0)
tk.Label(TabList[num][1].ThicknessFrame, text = ' ').grid(row = 0, column = 1) #spacer
tk.Label(TabList[num][1].ThicknessFrame, text = 'Channel\n').grid(row = 0, column = 2)
tk.Label(TabList[num][1].ThicknessFrame, text = ' ').grid(row = 0, column = 3) #spacer
tk.Label(TabList[num][1].ThicknessFrame, text = 'Eloss\n(keV)').grid(row = 0, column = 4)
tk.Label(TabList[num][1].ThicknessFrame, text = ' ').grid(row = 0, column = 5) #spacer
tk.Label(TabList[num][1].ThicknessFrame, text = 'Thickness\n(' + units_list[index] + ')').grid(row = 0, column = 6)
## peak info
for k in range(len(eloss)):
tk.Label(TabList[num][1].ThicknessFrame, text = '%.3f' % (energies[k]) ).grid(row = k + 1, column = 0)
tk.Label(TabList[num][1].ThicknessFrame, text = ' ').grid(row = 0, column = 1) #spacer
tk.Label(TabList[num][1].ThicknessFrame, text = '%.1f' % (filmCents[k]) ).grid(row = k + 1, column = 2)
tk.Label(TabList[num][1].ThicknessFrame, text = ' ').grid(row = 0, column = 3) #spacer
tk.Label(TabList[num][1].ThicknessFrame, text = '%.0f' % (eloss[k]) ).grid(row = k + 1, column = 4)
tk.Label(TabList[num][1].ThicknessFrame, text = ' ').grid(row = 0, column = 5) #spacer
tk.Label(TabList[num][1].ThicknessFrame, text = '%.0f' % (thickPeak[k]) ).grid(row = k + 1, column = 6)
## thickness final result
tk.Label(TabList[num][1].ThicknessFrame,
text = 'Average Thickness (' + units_list[index] + ')').grid(row = k + 2, column = 0)
tk.Label(TabList[num][1].ThicknessFrame,
text = 'Uncertainty (' + units_list[index] + ')').grid(row = k + 2, column = 4)
tk.Label(TabList[num][1].ThicknessFrame,
text = "{:.0f}".format(meanThick)).grid(row = k + 3, column = 0)
tk.Label(TabList[num][1].ThicknessFrame,
text = "{:.0f}".format(stdDevThick)).grid(row = k + 3, column = 4)
tk.Button(TabList[num][1].ThicknessFrame,
command = lambda: ClearWidget('Thickness', 1),
text = 'Reset Results').grid(row = k + 4, columnspan = 2)
return
#########################################################################################
# Recebe os resultados dos algoritmos e mostra no GUI
########################################################################################
def ResultManager():
num = Current_Tab()
ClearWidget('Results', 0) # A funcao e evocada para dar reset aos valores anteriores
TabList[num][1].ResultFrame.grid(row = 3, columnspan = 2, pady = 5)
values = File_Reader(TabList[num][3], ',', 'No', 'No') #Esta leitura devolve os valores de channel e counts
for j in range(0, len(values)): # O ciclo for apenas cria os checkbuttons e as labels para depois guardar
# os valores a serem apagados/usados nas funcoes seguintes
Result_Button = tk.Checkbutton(TabList[num][1].ResultFrame, variable = TabList[num][1].Var_Data[j],
onvalue = 1, offvalue = -1,
text = 'Channel: ' + str(values[j][0]))
Result_Button.grid(row = j , column = 0)
Result_Button.select()
tk.Label(TabList[num][1].ResultFrame,
text = '\t Counts: ' + str(values[j][1])).grid(row = j , column = 1)
#########################################################################################
# Recebe os resultados do algoritmo ROI Select e mostra no GUI
########################################################################################
def ROIResultManager():
num = Current_Tab()
ClearWidget('Results', 0) # A funcao e evocada para dar reset aos valores anteriores
TabList[num][1].ResultFrame.grid(row = 3, columnspan = 2, pady = 5)
values = File_Reader(TabList[num][3], ',', 'Yes', 'No') #Esta leitura devolve os valores de channel e counts
for j in range(0, len(values)): # O ciclo for apenas cria os checkbuttons e as labels para depois guardar
# os valores a serem apagados/usados nas funcoes seguintes
Result_Button = tk.Checkbutton(TabList[num][1].ResultFrame, variable = TabList[num][1].Var_Data[j],
onvalue = 1, offvalue = -1,
text = 'Centroid: ' + str("{:.1f}".format(values[j][0])))
Result_Button.grid(row = j , column = 0)
Result_Button.select()
tk.Label(TabList[num][1].ResultFrame,
text = '\t \u03C3 = ' + str("{:.1f}".format(values[j][2]))).grid(row = j , column = 1)
tk.Label(TabList[num][1].ResultFrame,
text = '\t \u03C3/\u221aN = ' + str("{:.3f}".format(values[j][1]))).grid(row = j , column = 2)
##########################################################################################
# Retira os resultados que nao estao checked e atualiza o txt dos resultados
##########################################################################################
def Unchecked_Results():
num = Current_Tab()
i = 0
j = 0
k = 0
Eraser = []
Aux = []
for widget in TabList[num][1].ResultFrame.winfo_children():
Eraser.append(widget) # Aqui guardamos todos os widgets que exibem os resultados.
# E necessario guardar num vetor, para que depois sejam apagados os corretos
values = File_Reader(TabList[num][3], '0', 'String', 'No') # Aqui vao se buscar os valores de channel e counts
# Como nao se fazem contas, apenas utilizamos a linha de
# string que contem ambos valores
for i in range(len(TabList[num][1].Var_Data)):
if TabList[num][1].Var_Data[i].get() == 1:
Aux.append(values[k]) # Caso seja selecionada a opcao, guardamos a linha para depois reescrever
# o documento que contem os resultados, de forma a guardar os pretendidos
elif TabList[num][1].Var_Data[i].get() == -1:
# No caso do Var_data devolver um -1, significa que se removeu a selecao do valor
# Nesse caso, tornamos esse valor num 0, destruimos o checkbutton no Eraser[j]
# e destruimos a label dos counts no Eraser[j + 1]
TabList[num][1].Var_Data[i].set(0)
Eraser[j].destroy()
Eraser[j + 1].destroy()
elif TabList[num][1].Var_Data[i].get() == 0:
# Caso haja um 0 no meio, na mudanca de dados, tiramos valores de iteracao do vetor Aux
# e do vetor Eraser, para manter todas as contas certas
k -= 1
j -= 2
j += 2
k += 1
for i in range(len(TabList[num][1].Var_Data)):
# Este for esta separado para nao haver confusoes de indices no primeiro ciclo
# Aqui, se for detetado um 0, pomos o IntVar no final do vetor Var_Data e
# eliminamos os Var_Data[i] = 0 do meio dos valores selecionados/nao selecionados
if TabList[num][1].Var_Data[i].get() == 0:
TabList[num][1].Var_Data.append(TabList[num][1].Var_Data[i])
TabList[num][1].Var_Data.pop(i)
with open(TabList[num][3], "w") as file: # Por fim, reescrevemos o documento dos resultados
# com os resultados unchecked removidos
for i in range(len(Aux)):
file.write(Aux[i] + '\n')
#########################################################################################
# Faz a regressao linear dos resultados
#########################################################################################
def Linearize():
num = Current_Tab()
xaxis = []
yaxis = []
values = File_Reader(TabList[num][3], ',', 'No', 'No') # Le os dados dos picos
for i in range(0, len(values)):
xaxis.append(values[i][0]) # Junto os canais apenas ao valor xaxis
for i in range(0, len(TabList[num][1].DecayList)):
if TabList[num][1].DecayList[i].get() != -1:
# Na lista que guarda os valores dos alfas, juntam se aqueles que foram selecionados pelo utilizador
yaxis.append(TabList[num][1].DecayList[i].get())
xvalues = sorted(xaxis) #Organizam se ambos dados por ordem
yvalues = sorted(yaxis)
if len(xvalues) != len(yvalues): # Esta condicao verifica se para a regressao linear
# existe uma relacao sobrejetiva
wng.popup('Invalid Linear Regression Configuration')
tk.Label(wng.warning,
text = "Number of Radiation Decay does not " +
"match the number of Peaks detected.\n").pack()
tk.Label(wng.warning, text ="Please adjust the Searching Algorithms or the " +
"number of Decay Energy.\n\n").pack()
tk.Button(wng.warning, text = 'Return',
command = lambda: wng.warning.destroy()).pack()
else:
ClearWidget('Linear', 0)
TabList[num][1].LinearRegressionFrame.grid(row = 3, columnspan = 2, pady = 5)
avgx = sum(xvalues) #Guardam se os valores das medias dos canais e da radiacao alfa
avgy = sum(yvalues)
avgx = avgx / len(xvalues)
avgy = avgy / len(yvalues)
Placeholder1 = 0
Placeholder2 = 0
for i in range(len(xvalues)):
Placeholder1 = Placeholder1 + ((xvalues[i] - avgx) * (yvalues[i] - avgy))
Placeholder2 = Placeholder2 + (xvalues[i] - avgx)**2
m = Placeholder1 / Placeholder2 # Valor do declive
b = avgy - m * avgx # Valor da ordenada na origem
sigma = 0
Placeholder1 = 0
Placeholder2 = 0
# Estes proximos somatorios e contas servem para obter as incertezas dos valores do
# declive e da ordenada de origem
for i in range(0, len(xvalues)):
sigma = (yvalues[i] - m * xvalues[i] - b)**2 + sigma
Placeholder1 = xvalues[i]**2 + Placeholder1
Placeholder2 = (sum(xvalues))**2
sigma = sigma / (len(xvalues) - 2)
sigma_m = math.sqrt(sigma / ( Placeholder1 - (Placeholder2/len(xvalues))))
sigma_b = math.sqrt((sigma * Placeholder1)/((len(xvalues) * Placeholder1) - Placeholder2))
if TabList[num][1].energy.get() == 1000:
unit_string = 'MeV'
significant_digits_m = Precision('%.2g' % (sigma_m))
significant_digits_b = Precision('%.2g' % (sigma_b))
elif TabList[num][1].energy.get() == 1:
unit_string = 'keV'
m = m * 1000
sigma_m = sigma_m * 1000
b = b * 1000
sigma_b = sigma_b * 1000
if sigma_m > 1:
significant_digits_m = 0
else:
significant_digits_m = Precision('%.2g' % (sigma_m))
if sigma_b > 1:
significant_digits_b = 0
else:
significant_digits_b = Precision('%.2g' % (sigma_b))
with open(TabList[num][4], 'w') as my_file:
# Aqui, escrevem se os resultados num documento txt para outras funcoes
# poderem aceder
my_file.write(unit_string + '\n')
my_file.write(str(m) + '\n')
my_file.write(str(sigma_m) + '\n')
my_file.write(str(b) + '\n')
my_file.write(str(sigma_b) + '\n')
my_file.write(str(significant_digits_m) + '\n')
my_file.write(str(significant_digits_b))
# Por fim, escreve se no GUI os resultados obtidos
tk.Label(TabList[num][1].LinearRegressionFrame, text = '(' + unit_string + ')').grid(
row = 0, column = 0)
tk.Label(TabList[num][1].LinearRegressionFrame, text = 'Values').grid(row = 0, column = 1)
tk.Label(TabList[num][1].LinearRegressionFrame, text = 'Uncertainty').grid(row = 0, column = 2)
tk.Label(TabList[num][1].LinearRegressionFrame, text = 'Slope').grid(row = 1, column = 0)
tk.Label(TabList[num][1].LinearRegressionFrame, text = 'Intersect').grid(row = 2, column = 0)
tk.Label(TabList[num][1].LinearRegressionFrame,
text = '%.*f' %(6, m)).grid(row = 1, column = 1)
tk.Label(TabList[num][1].LinearRegressionFrame,
text = '%.*f' % (6, sigma_m)).grid(row = 1, column = 2)
tk.Label(TabList[num][1].LinearRegressionFrame,
text = '%.*f' %(6, b)).grid(row = 2, column = 1)
tk.Label(TabList[num][1].LinearRegressionFrame,
text = '%.*f' % (6, sigma_b)).grid(row = 2, column = 2)
tk.Button(TabList[num][1].LinearRegressionFrame, text = 'Clear Regression',
command = lambda: ClearWidget('Linear', 1 )).grid(row = 3, column = 0, columnspan = 3)
#########################################################################################
# Faz a regressao linear dos resultados com input da incerteza nosa canais
#########################################################################################
def LinearizeWithErrors():
num = Current_Tab()
centroids = []
errors = []
energies = []
values = File_Reader(TabList[num][3], ',', 'Yes', 'No') # Le os dados dos picos
for i in range(0, len(values)):
centroids.append(values[i][0]) # Junto os canais apenas ao valor xaxis
errors.append(values[i][1])
for i in range(0, len(TabList[num][1].DecayList)):
if TabList[num][1].DecayList[i].get() != -1:
# Na lista que guarda os valores dos alfas, juntam se aqueles que foram selecionados pelo utilizador
energies.append(TabList[num][1].DecayList[i].get())
centroids = sorted(centroids) #Organizam se ambos dados por ordem
errors = sorted(errors)
energies = sorted(energies)
if len(centroids) != len(energies): # Esta condicao verifica se para a regressao linear
# existe uma relacao sobrejetiva
wng.popup('Invalid Linear Regression Configuration')
tk.Label(wng.warning,
text = "Number of Radiation Decay does not " +
"match the number of Peaks detected.\n").pack()
tk.Label(wng.warning, text ="Please adjust the Searching Algorithms or the " +
"number of Decay Energy.\n\n").pack()
tk.Button(wng.warning, text = 'Return',
command = lambda: wng.warning.destroy()).pack()
else:
ClearWidget('Linear', 0)
TabList[num][1].LinearRegressionFrame.grid(row = 3, columnspan = 2, pady = 5)
## Faz a a regressao linear com a função do ficheiro Calibration
m, b, sigma_m, sigma_b = Calib(energies, centroids, errors)
if TabList[num][1].energy.get() == 1000:
unit_string = 'MeV'
elif TabList[num][1].energy.get() == 1:
unit_string = 'keV'
m = m * 1000
sigma_m = sigma_m * 1000
b = b * 1000
sigma_b = sigma_b * 1000
with open(TabList[num][4], 'w') as my_file:
# Aqui, escrevem se os resultados num documento txt para outras funcoes
# poderem aceder
my_file.write(unit_string + '\n')
my_file.write(str(m) + '\n')
my_file.write(str(sigma_m) + '\n')
my_file.write(str(b) + '\n')
my_file.write(str(sigma_b) + '\n')
my_file.write(str(6) + '\n')
my_file.write(str(6))
# Por fim, escreve se no GUI os resultados obtidos
tk.Label(TabList[num][1].LinearRegressionFrame, text = '(' + unit_string + ')').grid(
row = 0, column = 0)
tk.Label(TabList[num][1].LinearRegressionFrame, text = 'Values').grid(row = 0, column = 1)
tk.Label(TabList[num][1].LinearRegressionFrame, text = 'Uncertainty').grid(row = 0, column = 2)
tk.Label(TabList[num][1].LinearRegressionFrame, text = 'Slope').grid(row = 1, column = 0)
tk.Label(TabList[num][1].LinearRegressionFrame, text = 'Intersect').grid(row = 2, column = 0)
tk.Label(TabList[num][1].LinearRegressionFrame,
text = '%.*f' %(6, m)).grid(row = 1, column = 1)
tk.Label(TabList[num][1].LinearRegressionFrame,
text = '%.*f' % (6, sigma_m)).grid(row = 1, column = 2)
tk.Label(TabList[num][1].LinearRegressionFrame,
text = '%.*f' %(6, b)).grid(row = 2, column = 1)
tk.Label(TabList[num][1].LinearRegressionFrame,
text = '%.*f' % (6, sigma_b)).grid(row = 2, column = 2)
tk.Button(TabList[num][1].LinearRegressionFrame, text = 'Clear Regression',
command = lambda: ClearWidget('Linear', 1 )).grid(row = 3, column = 0, columnspan = 3)
###############################################################################
# Este e o algoritmo que determina a distancia quadrada minima entre pontos
# input, e pontos de dados
###############################################################################
def ManSelec_Alg(Valuex, Valuey):
num = Current_Tab()
Counts = File_Reader(TabList[num][2], '0', 'No', 'No')
AuxList = [] #Lista para guardar minimos quadrados