forked from Goldie643/SKReact
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathskreact.py
1985 lines (1778 loc) · 80.1 KB
/
skreact.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
#!/usr/bin/env python
__author__ = "Alex Goldsack"
"""
Ver v1.3
A GUI program to generate information regarding
reactor neutrinos in Super-Kamiokande: production,
oscillation, interaction and detection.
"""
from params import *
from reactor import Reactor
from smear import Smear
from fit import fit_win
from scipy import stats
from tkinter import *
from tkinter import messagebox
from tkinter import filedialog
import tkinter.ttk as ttk
# Lots of matplotlib gubbins to embed into tkinter
import matplotlib
matplotlib.use("TkAgg")
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import matplotlib.dates as mdates
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
from matplotlib.figure import Figure
import matplotlib.ticker as ticker
import pandas as pd
import numpy as np
from datetime import datetime as dt
from calendar import monthrange
from PIL import ImageTk, Image
import pickle
import random
import time
import math
import cmath
import copy
import io
import os
# Surpressing a warning bug in numpy library when comparing
import warnings
warnings.simplefilter(action="ignore", category=FutureWarning)
# For formatting the lf plot later
years = mdates.YearLocator()
years_fmt = mdates.DateFormatter("%Y")
months = mdates.MonthLocator()
months_fmt = mdates.DateFormatter("")
# The years covered by the files in react_dir
# updated when extract_reactor_info is called
file_year_start = 0
file_year_end = 0
# Getting all reactor power information into pd df
def extract_reactor_info(react_dir):
# List of reactors, only select JP and KR reactors for now
reactors = []
file_names = []
# Create ordered list of filenames
for file in os.listdir(react_dir):
file_name = os.fsdecode(file)
if (file_name.startswith("DB") and
(file_name.endswith(".xls") or file_name.endswith(".xlsx"))):
file_names.append(os.fsdecode(file))
# Best to have it in order
file_names.sort()
global file_year_start
global file_year_end
file_year_start = int(file_names[0][2:6])
file_year_end = int(file_names[-1][2:6])
for file_name in file_names:
# Pull reactor info from first file
file_year = file_name[2:6]
print("Importing " + file_name + "...")
if file_name.endswith(".xlsx"):
engine = "openpyxl"
else:
engine = "xlrd"
react_dat = pd.read_excel(react_dir + file_name, header=None,
engine=engine)
# Must be in format Country,Name,Lat,Long,Type,Mox?,Pth,LF-monthly
# Look through xls file's reactors.
for index, data in react_dat.iterrows():
# Set the data first to check it makes sense
# Just reactor info, will deal with erros in lf later
try:
data_country = str(data[0]).strip()
data_name = str(data[1]).strip()
data_latitude = float(data[2])
data_longitude = float(data[3])
data_core_type = str(data[4]).strip()
data_mox = bool(data[5])
# data_p_th = pd.Series(float(data[6]),index=file_year)
data_p_th = float(data[6])
# data_lf = []
# for month in range(1, 13):
# data_lf.append(float(data[6 + month]))
except ValueError:
if VERBOSE_IMPORT_ERR:
print("PROBLEM IN .XLS FILE")
print(
"Check file "
+ file_name
+ ", row "
+ str(index)
+ " for odd data"
)
input("Press Enter to continue importing...")
continue
# Check if the reactor on this row is in reactors[]
in_reactors = False
for reactor in reactors:
if reactor.name == data_name:
in_reactors = True
# Checking if any of the reactor's info has changed
# updating to most recent if so
if data_country != reactor.country:
print("Reactor country has changed in file " + file_name + "!")
print("Reactor: " + reactor.name)
print(reactor.country + " -> " + data_country)
print("Updating...")
reactor.country = data_country
if data_latitude != reactor.latitude:
print("Reactor latitude has changed in file " + file_name + "!")
print("Reactor: " + reactor.name)
print(str(reactor.latitude) + " -> " + str(data_latitude))
print("Updating...")
reactor.latitude = data_latitude
if data_longitude != reactor.longitude:
print(
"Reactor longitude has changed in file " + file_name + "!"
)
print("Reactor: " + reactor.name)
print(str(reactor.longitude) + " -> " + str(data_longitude))
print("Updating...")
reactor.longitude = data_longitude
if data_core_type != reactor.core_type:
print(
"Reactor core type has changed in file " + file_name + "!"
)
print("Reactor: " + reactor.name)
print(str(reactor.core_type) + " -> " + str(data_core_type))
print("Updating...")
reactor.core_type = data_core_type
if data_mox != reactor.mox:
print("Reactor mox has changed in file " + file_name + "!")
print("Reactor: " + reactor.name)
print(str(reactor.mox) + " -> " + str(data_mox))
print("Updating...")
reactor.mox = data_mox
# Reactor p_th needs to be tracked
# reactor.p_th.set_value(file_year, data_p_th)
reactor.p_th.loc[file_year] = data_p_th
# Add headers in form used throughout
for month in range(1, 13):
lf_header = file_year + "/%02i" % month
try:
# 6 is to skip the reactor data
reactor.add_to_lf(lf_header, float(data[6 + month]))
except:
if VERBOSE_IMPORT_ERR:
print(
"Load factor data for "
+ reactor.name
+ " in month %i/%02i" % (int(file_year), int(month))
+ " not float compatible"
)
print("Load factor entry: %s" % data[6 + month])
# input("Press Enter to continue importing...")
print("Adding zeros...")
reactor.add_to_lf(lf_header, 0.0)
# Adds reactor if it's not in reactors
ang_dist = math.sqrt(
(data_latitude - SK_LAT) ** 2 + (data_longitude - SK_LONG) ** 2
)
if not in_reactors and ang_dist < R_THRESH_DEG:
if VERBOSE_IMPORT:
print("NEW REACTOR: " + data_name)
reactors.append(
Reactor(
data_country,
data_name,
data_latitude,
data_longitude,
data_core_type,
data_mox,
pd.Series(data_p_th, index=[file_year]),
pd.Series([]), # Load factor
default=True,
calc_spec=True,
)
)
# Add up until current file with 0s
if file_year_start != int(file_year):
if VERBOSE_IMPORT:
print("Retroactively filling data with zeros...")
for year in range(file_year_start, int(file_year)):
# Use current file's p_th for previous years
# reactors[-1].p_th.set_value(str(year), data_p_th)
reactors[-1].p_th.loc[str(year)] = data_p_th
for month in range(1, 13):
lf_header = "%i/%02i" % (year, month)
reactors[-1].add_to_lf(lf_header, 0.0)
# Now add in current file data
for month in range(1, 13):
lf_header = file_year + "/%02i" % month
try:
reactors[-1].add_to_lf(lf_header, float(data[6 + month]))
except:
if VERBOSE_IMPORT_ERR:
print(
"Load factor data for "
+ reactors[-1].name
+ " in month %i/%02i" % (int(file_year), month)
+ " not float compatible"
)
print(
"Load factor entry: %s"
% reactors[-1].lf_monthly[lf_header]
)
reactors[-1].add_to_lf(lf_header, 0.0)
if not in_reactors and ang_dist >= R_THRESH_DEG:
if VERBOSE_IMPORT:
print(data[1].strip() + " out of range, skipping...")
# Checking if reactor isn't present in this file
# adds zeros for load factor if so, use the previous p_th
for reactor in reactors:
in_file = False
for index, data in react_dat.iterrows():
try:
# Check if data[1] is string like
data_name = data[1].strip()
data_p_th = float(data[6])
except:
# Already handled above
continue
if reactor.name == data_name:
in_file = True
if not in_file:
if VERBOSE_IMPORT:
print("NOT IN FILE: " + reactor.name + ", adding zeros")
# Set the P_th to value of the last year
# reactor.p_th.set_value(file_year, reactor.p_th.iloc[-1])
reactor.p_th.loc[file_year] = reactor.p_th.iloc[-1]
for month in range(1, 13):
lf_header = file_year + "/%02i" % month
reactor.add_to_lf(file_year + "/%02i" % month, 0.0)
print("...done!")
reactors.sort(key=lambda x: x.name)
return reactors
# Creating the list of reactors and buttons
highlighted_reactors = []
highlighted_reactors_names = []
# For properly tracking the multiple highlighted reactors
last_selection_list = []
last_selected_reactor_i = None
# Making this global so values can be put in file later
reactor_lf_tot = pd.Series(dtype="float64")
total_prod_spec = pd.Series(dtype="float64") # Interacted
total_osc_spec = pd.Series(dtype="float64") # Incoming
total_int_spec = pd.Series(dtype="float64") # Interacted
highlighted_spec_df = pd.DataFrame()
smear_spec = pd.Series(dtype="float64") # WIT smeared
period = "1800/01-1900/01"
def main():
# A splash screen while initialising everything
splash_win = Tk()
splash_logo_img = ImageTk.PhotoImage(Image.open(LOGO_FILE))
splash_logo_lbl = Label(splash_win, image=splash_logo_img)
splash_logo_lbl.grid(column=0, row=0)
splash_label = Label(splash_win, text="Loading SKReact...")
splash_label.grid(column=0, row=1)
progress_length = 500
total_progress = ttk.Progressbar(
splash_win, orient=HORIZONTAL, length=progress_length, mode="determinate"
)
total_progress.grid(column=0, row=2)
splash_task_label = Label(splash_win, text="Calculating smearing matrix...")
splash_task_label.grid(column=0, row=3)
sub_progress = ttk.Progressbar(
splash_win, orient=HORIZONTAL, length=progress_length, mode="determinate"
)
sub_progress.grid(column=0, row=4)
# Centering in the screen
splash_w = splash_win.winfo_reqwidth()
splash_h = splash_win.winfo_reqheight()
splash_x = int(splash_win.winfo_screenwidth() / 2 - 2 * splash_w)
splash_y = int(splash_win.winfo_screenheight() / 2 - splash_h)
splash_win.geometry("+%i+%i" % (splash_x, splash_y))
splash_win.update()
# Try to import geo_nu info
geo_imported = False
try:
# geo_lumi = pd.read_csv(GEO_FILE, sep=" ")
geo_imported = True
except FileNotFoundError:
print("Geo file " + GEO_FILE + " not found!")
print("Cannot import geoneutrinos information.")
# Try to calculate smearing matrix
smear_imported = False
try:
splash_task_label["text"] = (
"Calculating smearing matrix using " + WIT_SMEAR_FILE + "..."
)
splash_win.update()
wit_smear = Smear(WIT_SMEAR_FILE)
smear_imported = True
except FileNotFoundError:
print("Smear file " + WIT_SMEAR_FILE + " not found!")
print("Cannot import smearing information.")
total_progress["value"] = 10
splash_task_label["text"] = "Unpickling reactor data from " + REACT_PICKLE + "..."
splash_win.update()
# Extracts from .xls if forced to, does not pickle in this case
if FORCE_XLS_IMPORT:
print("Extracting reactor info from " + REACT_DIR)
default_reactors = extract_reactor_info(REACT_DIR)
else:
# Set up the reactor list and names
if os.path.exists(REACT_PICKLE):
# Pulls from pickle if it exists
with open(REACT_PICKLE, "rb") as pickle_file:
default_reactors = pickle.load(pickle_file)
# Have to manually set the whole period from the file
global file_year_start
global file_year_end
file_year_start = int(default_reactors[0].lf_monthly.index[0][:4])
file_year_end = int(default_reactors[0].lf_monthly.index[-1][:4])
else:
print("Reactor file " + REACT_PICKLE + " not found!")
print("Extracting reactor info from " + REACT_DIR)
default_reactors = extract_reactor_info(REACT_DIR)
with open(REACT_PICKLE, "wb") as pickle_file:
pickle.dump(default_reactors, pickle_file)
total_progress["value"] = 20
splash_win.update()
splash_task_label["text"] = "Calculating default spectra for all reactors..."
n_reactors = len(default_reactors)
update_splash_i = 0
update_splash_interval = 10
# Calculate produced spectra for these bins
for default_reactor in default_reactors:
default_reactor.set_all_spec()
# Update the loading bar on the splash
if update_splash_i % update_splash_interval == 0:
sub_progress["value"] = update_splash_i * 100 / n_reactors
splash_win.update()
update_splash_i += 1
default_reactor_names = [reactor.name for reactor in default_reactors]
reactors = copy.deepcopy(default_reactors)
reactor_names = default_reactor_names.copy()
n_reactors = len(reactors)
total_progress["value"] = 70
splash_win.update()
# Setup dt objects of dataset
data_start_date = reactors[0].lf_monthly.index[0]
data_start_year = int(data_start_date[:4])
data_start_month = int(data_start_date[5:7])
data_start_dt = dt(data_start_year, data_start_month, 1)
data_end_date = reactors[0].lf_monthly.index[-1]
data_end_year = int(data_end_date[:4])
data_end_month = int(data_end_date[5:7])
data_end_dt = dt(data_end_year, data_end_month, 1)
data_start_mdate = mdates.date2num(data_start_dt)
data_end_mdate = mdates.date2num(data_end_dt)
monthly_tot_spec = []
month_centre_days = [] # Middle of the month, interp around
n_months = reactors[0].lf_monthly.size
day_int = 0 # N days since start of data
splash_task_label["text"] = "Generating spectrogram: "
sub_progress["value"] = 0
update_splash_i = 0
splash_win.update()
for date, lf in reactors[0].lf_monthly.iteritems():
# Update splash every interval times
if update_splash_i % update_splash_interval == 0:
sub_progress["value"] = update_splash_i * 100 / n_months
splash_win.update()
update_splash_i += 1
this_month_tot_spec = np.zeros(E_BINS)
for reactor in reactors:
osc_spec = reactor.osc_spec(period=(date + "-" + date))
int_spec = reactor.int_spec(osc_spec)
this_month_tot_spec += int_spec
reactor.n_ints_monthly.append(np.trapz(int_spec, dx=E_INTERVAL))
# smear_spec = wit_smear.smear(this_month_tot_spec)
# monthly_ints.append(np.trapz(this_month_tot_spec, dx=E_INTERVAL))
year = int(date[:4])
month = int(date[5:7])
# X axis is integer days since start of data
# Put month's average in centre of month, interp later
days_in_month = monthrange(year, month)[1]
month_centre_days.append(day_int + days_in_month / 2)
day_int += days_in_month
monthly_tot_spec.append(this_month_tot_spec)
# monthly_tot_spec.append(smear_spec)
# Change n_ints monthly to pd Series for ease of plotting later
for reactor in reactors:
reactor.n_ints_monthly = pd.Series(
reactor.n_ints_monthly, index=reactor.lf_monthly.index
)
# Turn number of interactions in pd Series
# monthly_ints = pd.Series(monthly_ints, index=reactors[0].lf_monthly.index)
# One bin per month spectogram
e_spectogram_mo = np.transpose(np.vstack(monthly_tot_spec))
e_spectogram_mo = np.flip(e_spectogram_mo, 0)
# Full x axis
total_days = np.arange(day_int)
# Iterate through each energy bin, interpolate
inter_tot_spec = []
for row in e_spectogram_mo:
inter_row = np.interp(total_days, month_centre_days, row)
inter_tot_spec.append(inter_row)
e_spectogram_inter = np.vstack(inter_tot_spec)
# plts, ax = plt.subplots()
# ax.imshow(
# e_spectogram_inter,
# aspect="auto",
# extent=[data_start_mdate, data_end_mdate, E_MIN, E_MAX],
# )
# ax.xaxis_date()
# plt.show()
splash_win.destroy()
# Get oscillation parameters from default (will vary)
dm_21 = DM_21
c_13 = C_13_NH
s_12 = S_12
s_13 = S_13_NH
# INITIALISING ALL MAIN FRAMES
# =========================================================================
# Set up tkinter window
skreact_win = Tk()
skreact_win.title("SKReact")
skreact_win.call("tk", "scaling", 1.0)
# skreact_win.geometry("%dx%d" % (WIN_X,WIN_Y))
# A hack to get the OS's name for the default button colour
test_button = Button()
default_button_fgc = test_button.cget("fg")
top_bar = Frame(skreact_win)
top_bar.pack()
skreact_title = ttk.Label(
top_bar,
text=(
"Welcome to SKReact, a GUI reactor neutrino "
"simulation for Super-Kamiokande"
),
)
skreact_title.pack()
# skreact_title.grid(column=0, row=0, columnspan=4)
title_divider = ttk.Separator(skreact_win, orient=HORIZONTAL)
# title_divider.grid(column=0, row=1, columnspan=5, sticky="ew")
title_divider.pack()
main_frame = Frame(skreact_win)
main_frame.pack()
# Three main columns
lh_frame = Frame(main_frame)
lh_frame.pack(side=LEFT, expand=True, fill=Y)
centre_frame = Frame(main_frame)
centre_frame.pack(side=LEFT, expand=True, fill=Y)
rh_frame = Frame(main_frame)
rh_frame.pack(side=LEFT, expand=True, fill=Y)
# map_labelframe = ttk.Labelframe(skreact_win,
# text = "Map of SK and Nearby Reactors UNFINISHED")
# map_labelframe.grid(column=0, row=2)
reactor_fluxes_labelframe = ttk.LabelFrame(
lh_frame, text="Individual Reactor Contributions"
)
# reactor_fluxes_labelframe.grid(column=0, row=3, rowspan=1, sticky=N + S + E + W)
reactor_fluxes_labelframe.pack(fill=BOTH, expand=True)
# Last clicked reactor info (has to go here really)
reactor_info_labelframe = ttk.LabelFrame(
lh_frame, text="Last Selected Reactor info"
)
# reactor_info_labelframe.grid(column=0, row=1, rowspan=2)
reactor_info_labelframe.pack()
# Ordered flux/n int list of reactors
# List of reactors to select if they contribute
# Alongside list of buttons to highlight one specifically
# reactors_labelframe = ttk.Labelframe(skreact_win, text="Reactor Selection")
# reactors_labelframe.grid(column=0, row=3, rowspan=1, sticky=N + S + E + W)
# Incident spectrum.
int_spec_labelframe = ttk.Labelframe(
centre_frame, text="Interaction Spectrum at SK"
)
# int_spec_labelframe.grid(
# column=1, row=2, columnspan=2, rowspan=2, sticky=N + S + E + W
# )
int_spec_labelframe.grid(column=0, row=0, columnspan=2, sticky=N + S + E + W)
# Options for the inc spec, as well as varying osc. params
int_spec_options_frame = Frame(centre_frame)
int_spec_options_frame.grid(column=0, row=1)
osc_spec_options_labelframe = ttk.Labelframe(centre_frame, text="Vary Osc. Params")
osc_spec_options_labelframe.grid(column=1, row=1)
# Produced E_spectra
prod_spec_labelframe = ttk.Labelframe(centre_frame, text="E Spectrum at Production")
prod_spec_labelframe.grid(column=0, row=2)
# Oscillated spectrum.
osc_spec_labelframe = ttk.Labelframe(centre_frame, text="Oscillated Flux at SK")
osc_spec_labelframe.grid(column=1, row=2)
osc_spec_options_frame = Frame(osc_spec_labelframe)
osc_spec_options_frame.grid(column=0, row=1)
# Mini logo in the corner
logo = Image.open(LOGO_FILE)
logo_w = 300
w_percent = logo_w / float(logo.size[0])
h_size = int((float(logo.size[1]) * float(w_percent)))
logo = logo.resize((logo_w, h_size), Image.Resampling.LANCZOS)
logo_tk = ImageTk.PhotoImage(logo)
logo_label = Label(rh_frame, image=logo_tk)
logo_label.grid(column=0, row=0, sticky=N + S + E + W)
# Energy spectrogram
spectro_labelframe = ttk.Labelframe(rh_frame, text="E Spectrogram")
spectro_labelframe.grid(column=0, row=1, sticky=N)
# Load factors/ (P/R^2) / event rate etc.
lf_labelframe = ttk.Labelframe(rh_frame, text="Reactor Monthly Load Factors")
lf_labelframe.grid(column=0, row=2, sticky=N)
# =========================================================================
# Defining the scrollable canvas
# factor of 25 gives just enough room
# 30 for extra reactors
# TODO: Update length dynamically
# reactors_list_canvas = Canvas(
# reactors_labelframe, scrollregion=(0, 0, 400, n_reactors * 30)
# )
# reactors_list_canvas.pack(fill="both", expand=True)
# reactors_scrollbar = Scrollbar(reactors_list_canvas)
# reactors_scrollbar.pack(side=RIGHT, fill=Y)
# reactors_scrollbar.config(command=reactors_list_canvas.yview)
# reactors_list_canvas.config(yscrollcommand=reactors_scrollbar.set)
# # Binding to only scroll canvas if hovering over it
# def _bind_list_to_mousewheel(event):
# reactors_list_canvas.bind_all("<MouseWheel>", _on_mousewheel)
# def _unbind_list_to_mousewheel(event):
# reactors_list_canvas.unbind_all("<MouseWheel>")
# # Dealing with scrolling the reactor list box
# def _on_mousewheel(event):
# reactors_list_canvas.yview_scroll(-1 * (event.delta), "units")
# # Binding scrolling to scroll the reactor list
# # TODO: make it so it only controls it when hovering over
# reactors_list_canvas.bind("<Enter>", _bind_list_to_mousewheel)
# reactors_list_canvas.bind("<Leave>", _unbind_list_to_mousewheel)
# # Select/deselct all reactors in the list then update
# def select_all_reactors(*args):
# for var in reactors_checkbox_vars:
# var.set(1)
# update_n_nu
# return
# def deselect_all_reactors(*args):
# for var in reactors_checkbox_vars:
# var.set(0)
# update_n_nu
# return
# # Buttons to select all, deselect all, add new reactors
# reactor_list_control_frame = Frame(skreact_win)
# select_all_button = Button(text="Select All", command=select_all_reactors)
# select_all_button.grid(in_=reactor_list_control_frame, column=0, row=0)
# deselect_all_button = Button(text="Deselect All", command=deselect_all_reactors)
# deselect_all_button.grid(in_=reactor_list_control_frame, column=1, row=0)
# Create new generic reactor, add to reactor list, show info
def add_reactor(*args):
new_reactor = Reactor(
"CUSTOM",
"Custom Reactor",
35.36,
138.7,
"BWR",
False,
pd.Series(2000.0, index=reactors[0].p_th.index),
pd.Series(100.0, index=reactors[0].lf_monthly.index),
False,
True,
)
reactors.append(new_reactor)
update_n_nu()
new_reactor_sorted_i = [reactor.name for reactor in reactors].index(
new_reactor.name
)
reactor_fluxes_list.selection_set(new_reactor_sorted_i)
reactor_fluxes_list.activate(new_reactor_sorted_i)
highlight_reactor(reactors.index(new_reactor))
# Index will alwas be -1 as it was just added
# show_info(new_reactor)
return
add_reactor_button = Button(
reactor_fluxes_labelframe, text="Add Reactor", command=add_reactor
)
add_reactor_button.pack()
# Listbox of reactor fluxes and names
reactor_fluxes_scroll = Scrollbar(reactor_fluxes_labelframe)
reactor_fluxes_scroll.pack(side=RIGHT, fill=BOTH)
# reactor_fluxes_scroll.grid(column=1,row=0,sticky=N+S)
reactor_fluxes_list = Listbox(reactor_fluxes_labelframe, selectmode="multiple")
# reactor_fluxes_list.grid(column=0,row=0,sticky=N+S+E+W)
reactor_fluxes_list.pack(side=LEFT, fill=BOTH, expand=1)
reactor_fluxes_list.config(yscrollcommand=reactor_fluxes_scroll.set)
reactor_fluxes_list.config(exportselection=False)
reactor_fluxes_scroll.config(command=reactor_fluxes_list.yview)
# # Adding custom reactors
# add_reactor_button = Button(text="Add Reactor", command=add_reactor)
# add_reactor_button.grid(in_=reactor_list_control_frame, column=2, row=0)
# Boxes to select start/end dates
period_labelframe = ttk.Labelframe(skreact_win,
text="Period Selection (Inclusive)")
# period_labelframe.pack(in_=reactors_labelframe,side=BOTTOM)
period_labelframe.grid(in_=lf_labelframe, column=0, row=1)
# Want this to be above the period selection so needs to pack after
# reactor_list_control_frame.pack(in_=reactors_labelframe, side=BOTTOM)
start_lbl = ttk.Label(skreact_win, text="From:")
start_lbl.grid(in_=period_labelframe, column=0, row=0)
start_year_combo = ttk.Combobox(skreact_win, width=5)
start_year_combo["values"] = list(range(file_year_start, file_year_end + 1))
start_year_combo.set(file_year_end)
start_year_combo.grid(in_=period_labelframe, column=1, row=0)
start_div_lbl = ttk.Label(skreact_win, text="/")
start_div_lbl.grid(in_=period_labelframe, column=2, row=0)
start_month_combo = ttk.Combobox(skreact_win, width=2)
start_month_combo["values"] = list(range(1, 13))
start_month_combo.current(0)
start_month_combo.grid(in_=period_labelframe, column=3, row=0)
start_year = start_year_combo.get()
start_month = start_month_combo.get()
end_lbl = ttk.Label(skreact_win, text=" To: ")
end_lbl.grid(in_=period_labelframe, column=4, row=0)
end_year_combo = ttk.Combobox(skreact_win, width=5)
end_year_combo["values"] = list(range(file_year_start, file_year_end + 1))
end_year_combo.set(file_year_end)
end_year_combo.grid(in_=period_labelframe, column=5, row=0)
end_div_lbl = ttk.Label(skreact_win, text="/")
end_div_lbl.grid(in_=period_labelframe, column=6, row=0)
end_month_combo = ttk.Combobox(skreact_win, width=2)
end_month_combo["values"] = list(range(1, 13))
end_month_combo.current(11)
end_month_combo.grid(in_=period_labelframe, column=7, row=0)
end_year = end_year_combo.get()
end_month = end_month_combo.get()
# PLOTS ===================================================================
plt.rc("xtick", labelsize=8)
# Spectrogram
spectro_fig = Figure(figsize=(FIG_X, FIG_Y), dpi=100)
spectro_ax = spectro_fig.add_subplot(111)
# Load factor is a %age which occasionally goes over 100
# spectro_ax.set_ylim(0,110)
spectro_canvas = FigureCanvasTkAgg(spectro_fig, master=spectro_labelframe)
spectro_canvas.get_tk_widget().grid(column=0, row=0)
# SPECTROGRAM PLOTTING
# This doesn't change (for now) so just plot here
# =================================================================
spectro_ax.imshow(
e_spectogram_inter,
aspect="auto",
extent=[data_start_mdate, data_end_mdate, E_MIN, E_MAX],
)
# Days from start of data to start of period
# data_start_period_start = (period_start_dt - data_start_dt).days
# data_start_period_end = (period_end_dt - data_start_dt).days
# spectro_ax.imshow(
# e_spectogram_inter[:,[data_start_period_start,data_start_period_end-1]],
# aspect="auto",
# extent= [period_start_mdate,period_end_mdate,E_MIN,E_MAX])
spectro_ax.xaxis_date()
# date_format = mdates.DateFormatter("%Y/%m")
# spectro_ax.xaxis.set_major_formatter(date_format)
# spectro_fig.autofmt_xdate()
spectro_ax.set_ylabel(r"$E_\bar{\nu}$ (MeV)")
# spectro_ax.set_ylabel(r"$E_{e^+}$ (MeV)")
# Opens the plot in its own matplotlib window
def expand_spectro(*args):
# Can't copy a figure object, so pickle and create new from that
buf = io.BytesIO()
pickle.dump(spectro_fig, buf)
buf.seek(0)
new_spectro_fig = pickle.load(buf)
# Make dummy plot to start gca handler
dummy = plt.figure()
new_manager = dummy.canvas.manager
# Move the copied figure over to new handler
new_manager.canvas.figure = new_spectro_fig
new_spectro_fig.set_canvas(new_manager.canvas)
new_spectro_fig.show()
return
spectro_expand_button = Button(spectro_labelframe, text="Open in new win",
command=expand_spectro)
spectro_expand_button.grid(column=0, row=3)
lf_fig = Figure(figsize=(FIG_X, FIG_Y), dpi=100)
lf_ax = lf_fig.add_subplot(111)
# Load factor is a %age which occasionally goes over 100
# lf_ax.set_ylim(0,110)
# lf_tot_ax = lf_ax.twinx()
lf_tot_ax = lf_ax
lf_canvas = FigureCanvasTkAgg(lf_fig, master=lf_labelframe)
lf_canvas.get_tk_widget().grid(column=0, row=0)
lf_options_frame = Frame(lf_labelframe)
lf_options_frame.grid(column=0, row=2)
lf_combo = ttk.Combobox(
lf_options_frame,
values=[
"N interactions in SK ID",
"P/r^2 to SK (MW/km^2)",
"P (MW)",
"Load Factor (%)",
],
)
lf_combo.current(0)
lf_combo.grid(column=0, row=0)
# lf_toolbar = NavigationToolbar2Tk(lf_canvas, lf_labelframe)
# Opens the plot in its own matplotlib window
def expand_lf(*args):
# Can't copy a figure object, so pickle and create new from that
buf = io.BytesIO()
pickle.dump(lf_fig, buf)
buf.seek(0)
new_lf_fig = pickle.load(buf)
# Make dummy plot to start gca handler
dummy = plt.figure()
new_manager = dummy.canvas.manager
# Move the copied figure over to new handler
new_manager.canvas.figure = new_lf_fig
new_lf_fig.set_canvas(new_manager.canvas)
new_lf_fig.show()
return
# Saving the load factor plot
def save_lf(*args):
lf_save_win = Toplevel(skreact_win)
lf_save_win.title("Save n_int/LF/P/Pr^-2 Plot")
filename_label = Label(lf_save_win, text="Filename:")
filename_label.grid(column=0, row=0)
filename = Entry(lf_save_win)
filename.insert(0, "lf_" + time.strftime("%Y%m%d-%H%M%S"))
filename.grid(column=1, row=0)
extension = Label(lf_save_win, text=".csv")
extension.grid(column=2, row=0)
def save_and_close(*args):
# TODO: Tidy up when OO is implemented
reactor_lf_tot.to_csv(filename.get() + ".csv")
lf_save_win.destroy()
save_button = Button(lf_save_win, text="Save", command=save_and_close)
save_button.grid(column=0, row=1, columnspan=3)
# Options to do with the load factor
# Stack option put in further down after update_n_nu definition
lf_save_button = Button(lf_options_frame, text="Save .csv", command=save_lf)
lf_save_button.grid(column=2, row=0)
lf_expand_button = Button(lf_options_frame, text="Open in new win",
command=expand_lf)
lf_expand_button.grid(column=2, row=1)
prod_spec_fig = Figure(figsize=(FIG_X, FIG_Y), dpi=100)
prod_spec_ax = prod_spec_fig.add_subplot(111)
# osc_spec_ax.set_xlabel("E_nu (MeV)")
# osc_spec_ax.set_ylabel("n_int (keV^-1 ????)")
prod_spec_canvas = FigureCanvasTkAgg(prod_spec_fig, master=prod_spec_labelframe)
# prod_spec_canvas.get_tk_widget().pack(side=TOP,fill=BOTH,expand=1)
prod_spec_canvas.get_tk_widget().grid(column=0, row=0)
# prod_spec_toolbar = NavigationToolbar2Tk(prod_spec_canvas, prod_spec_labelframe)
prod_spec_options_frame = Frame(prod_spec_labelframe)
prod_spec_options_frame.grid(column=0, row=1)
prod_spec_label = Label(prod_spec_options_frame, text="N_prod in period = ")
prod_spec_label.grid(column=2, row=0)
prod_spec_options_labelframe = ttk.Labelframe(
prod_spec_labelframe, text="View Fuel Contribution"
)
prod_spec_options_labelframe.grid(column=0, row=2)
# osc_spec_fig = Figure(figsize=(FIG_X, FIG_Y), dpi=100)
osc_spec_fig = Figure(figsize=(FIG_X, FIG_Y), dpi=100)
osc_spec_ax = osc_spec_fig.add_subplot(111)
osc_spec_canvas = FigureCanvasTkAgg(osc_spec_fig, master=osc_spec_labelframe)
osc_spec_canvas.get_tk_widget().grid(column=0, row=0)
int_spec_fig = Figure(figsize=(2 * FIG_X, 2 * FIG_Y), dpi=100)
int_spec_ax = int_spec_fig.add_subplot(111)
smear_spec_ax = int_spec_ax
effs_ax = int_spec_ax.twinx()
int_spec_canvas = FigureCanvasTkAgg(int_spec_fig, master=int_spec_labelframe)
int_spec_canvas.get_tk_widget().grid(column=0, row=0, columnspan=2)
# osc_spec_toolbar = NavigationToolbar2Tk(osc_spec_canvas,
# osc_spec_labelframe)
def expand_prod_spec(*args):
# Can't copy a figure object, so pickle and create new from that
buf = io.BytesIO()
pickle.dump(prod_spec_fig, buf)
buf.seek(0)
new_prod_spec_fig = pickle.load(buf)
# Make dummy plot to start gca handler
dummy = plt.figure()
new_manager = dummy.canvas.manager
# Move the copied figure over to new handler
new_manager.canvas.figure = new_prod_spec_fig
new_prod_spec_fig.set_canvas(new_manager.canvas)
new_prod_spec_fig.show()
return
# Saving the prodillated spectrum as .csv
def save_prod_spec(*args):
prod_spec_save_win = Toplevel(skreact_win)
prod_spec_save_win.title("Save Oscillated Spectrum .csv")
filename_label = Label(prod_spec_save_win, text="Filename:")
filename_label.grid(column=0, row=0)
filename = Entry(prod_spec_save_win)
filename.insert(0, "prod_" + time.strftime("%Y%m%d-%H%M%S"))
filename.grid(column=1, row=0)
extension = Label(prod_spec_save_win, text=".csv")
extension.grid(column=2, row=0)
def save_and_close(*args):
total_prod_spec_pd = pd.Series(total_prod_spec, ENERGIES)
total_prod_spec_pd.to_csv(filename.get() + ".csv")
prod_spec_save_win.destroy()
save_button = Button(prod_spec_save_win, text="Save", command=save_and_close)
save_button.grid(column=0, row=1, columnspan=3)
# Generating a nuance file from the oscillated spectrum
def nuance_osc_spec(*args):
osc_spec_nuance_win = Toplevel(skreact_win)
osc_spec_nuance_win.title("Generate POSITRON nuance file for SK")
filename_label = Label(osc_spec_nuance_win, text="Filename:")
filename_label.grid(column=0, row=0)
filename = Entry(osc_spec_nuance_win)
filename.insert(0, time.strftime("%Y%m%d-%H%M%S"))
filename.grid(column=1, row=0)
extension_label = Label(osc_spec_nuance_win, text=".nuance")
extension_label.grid(column=2, row=0)
n_events_label = Label(osc_spec_nuance_win, text="n_events:")
n_events_label.grid(column=0, row=1)
n_events_entry = Entry(osc_spec_nuance_win)
n_events_entry.insert(0, "100000")
n_events_entry.grid(column=1, row=1)
def nuance_and_close(*args):
nuance_out = open(filename.get() + ".nuance", "x")
# Setting up the prob distribution from the spec using rv_discrete
# rv_discrete only works with integers, so have to map energies to
# list of integers
int_map = range(E_BINS)
# Converting spectrum to probability distribution
# spec = total_int_spec.to_list()
# probs = [x/total_int_spec.sum() for x in spec]
# probs = total_int_spec.divide(total_int_spec.sum()).tolist()
probs = np.divide(total_int_spec,total_int_spec.sum()).tolist()
# Set up the dist and generate list from that
prob_distribution = stats.rv_discrete(
name="prob_distribution", values=(int_map, probs)
)
rvs = prob_distribution.rvs(size=int(n_events_entry.get()))
nuance_energies = []
for rv in rvs:
nuance_out.write("begin \n")
nuance_out.write("info 2 949000 0.0000E+00\n")
# nuance_out.write("nuance 3 \n")
theta = random.uniform(0, 2 * math.pi)
# -1 to get rid of rounding errors causing events
# to appear nuance_outside the tank
r = SK_R * math.sqrt(random.random())
x = (r)*math.cos(theta)
y = (r)*math.sin(theta)
z = random.uniform(-SK_HH, SK_HH)
vx = random.uniform(-1, 1)
vy = random.uniform(-1, 1)
vz = random.uniform(-1, 1)
px = vx / math.sqrt(vx * vx + vy * vy + vz * vz)
py = vy / math.sqrt(vx * vx + vy * vy + vz * vz)
pz = vz / math.sqrt(vx * vx + vy * vy + vz * vz)
nuance_out.write("vertex %f %f %f 0\n" % (x, y, z))
nuance_out.write(
"track %i %f %f %f %f 0\n"
% (POSITRON_PDG, DOWN_ENERGIES[rv], px, py, pz)
)
nuance_out.write("end \n")
nuance_energies.append(DOWN_ENERGIES[rv])
nuance_out.close()
osc_spec_nuance_win.destroy()
plt.hist(nuance_energies,bins=100,label="Generated Energies")
plt.legend()
plt.show()
nuance_button = Button(
osc_spec_nuance_win, text="Save", command=nuance_and_close
)
nuance_button.grid(column=2, row=1)
# Opens the plot in its own matplotlib window
def expand_osc_spec(*args):
# Can't copy a figure object, so pickle and create new from that
buf = io.BytesIO()
pickle.dump(osc_spec_fig, buf)
buf.seek(0)
new_osc_spec_fig = pickle.load(buf)
# Make dummy plot to start gca handler
dummy = plt.figure()
new_manager = dummy.canvas.manager
# Move the copied figure over to new handler
new_manager.canvas.figure = new_osc_spec_fig
new_osc_spec_fig.set_canvas(new_manager.canvas)
new_osc_spec_fig.show()
return
# Saving the oscillated spectrum as .csv
def save_osc_spec(*args):
osc_spec_save_win = Toplevel(skreact_win)
osc_spec_save_win.title("Save Oscillated Spectrum .csv")
filename_label = Label(osc_spec_save_win, text="Filename:")
filename_label.grid(column=0, row=0)
filename = Entry(osc_spec_save_win)
filename.insert(0, "osc_" + time.strftime("%Y%m%d-%H%M%S"))
filename.grid(column=1, row=0)