forked from sbradnam/JADE
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsphereoutput.py
1419 lines (1213 loc) · 51.4 KB
/
sphereoutput.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
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 2 10:36:38 2020
@author: Davide Laghi
Copyright 2021, the JADE Development Team. All rights reserved.
This file is part of JADE.
JADE is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
JADE is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with JADE. If not, see <http://www.gnu.org/licenses/>.
"""
import xlwings as xw
import excel_support as exsupp
import pandas as pd
import os
import shutil
import plotter
#import pythoncom
import math
from tqdm import tqdm
import atlas as at
import numpy as np
from output import BenchmarkOutput
from output import MCNPoutput
class SphereOutput(BenchmarkOutput):
def __init__(self, lib, testname, session):
super().__init__(lib, testname, session)
# Load the settings for zaids and materials
mat_path = os.path.join(self.cnf_path, 'MaterialsSettings.csv')
self.mat_settings = pd.read_csv(mat_path, sep=';').set_index('Symbol')
zaid_path = os.path.join(self.cnf_path, 'ZaidSettings.csv')
self.zaid_settings = pd.read_csv(zaid_path, sep=';').set_index('Z')
def single_postprocess(self):
"""
Execute the full post-processing of a single library (i.e. excel,
raw data and atlas)
Returns
-------
None.
"""
print(' Generating Excel Recap...')
self.pp_excel_single()
print(' Dumping Raw Data...')
self.print_raw()
print(' Generating plots...')
outpath = os.path.join(self.atlas_path, 'tmp')
os.mkdir(outpath)
self._generate_single_plots(outpath)
print(' Single library post-processing completed')
def _generate_single_plots(self, outpath):
"""
Generate all the requested plots in a temporary folder
Parameters
----------
outpath : str or path
path to the temporary folder where to store plots.
Returns
-------
None.
"""
for tally, title, quantity, unit in \
[(2, 'Leakage Neutron Flux (175 groups)',
'Neutron Flux', r'$\#/cm^2$'),
(32, 'Leakage Gamma Flux (24 groups)',
'Gamma Flux', r'$\#/cm^2$')]:
print(' Plotting tally n.'+str(tally))
for zaidnum, output in tqdm(self.outputs.items()):
title = title
tally_data = output.tallydata.set_index('Tally N.').loc[tally]
energy = tally_data['Energy'].values
values = tally_data['Value'].values
error = tally_data['Error'].values
lib_name = self.session.conf.get_lib_name(self.lib)
lib = {'x': energy, 'y': values, 'err': error,
'ylabel': str(zaidnum)+' ('+lib_name+')'}
data = [lib]
outname = str(zaidnum)+'-'+self.lib+'-'+str(tally)
plot = plotter.Plotter(data, title, outpath, outname, quantity,
unit, 'Energy [MeV]', self.testname)
plot.plot('Binned graph')
self._build_atlas(outpath)
def _build_atlas(self, outpath):
"""
Build the atlas using all plots contained in directory
Parameters
----------
outpath : str or path
temporary folder containing all plots.
Returns
-------
None.
"""
# Printing Atlas
template = os.path.join(self.code_path, 'templates',
'AtlasTemplate.docx')
if self.single:
name = self.lib
else:
name = self.name
atlas = at.Atlas(template, 'Sphere '+name)
atlas.build(outpath, self.session.lib_manager, self.mat_settings)
atlas.save(self.atlas_path)
# Remove tmp images
shutil.rmtree(outpath)
def compare(self):
"""
Execute the full post-processing of a comparison of libraries
(i.e. excel, and atlas)
Returns
-------
None.
"""
print(' Generating Excel Recap...')
self.pp_excel_comparison()
print(' Creating Atlas...')
outpath = os.path.join(self.atlas_path, 'tmp')
os.mkdir(outpath)
# Recover all libraries and zaids involved
libraries, allzaids, outputs = self._get_organized_output()
globalname = ''
for lib in self.lib:
globalname = globalname + lib + '_Vs_'
globalname = globalname[:-4]
# Plot everything
print(' Generating Plots Atlas...')
self._generate_plots(libraries, allzaids, outputs, globalname, outpath)
print(' Comparison post-processing completed')
def _generate_plots(self, libraries, allzaids, outputs, globalname,
outpath):
for tally, title, quantity, unit in [(2, 'Leakage Neutron Flux (175 groups)',
'Neutron Flux', r'$\#/cm^2$'),
(32, 'Leakage Gamma Flux (24 groups)',
'Gamma Flux', r'$\#/cm^2$')]:
print(' Plotting tally n.'+str(tally))
for zaidnum in tqdm(allzaids):
# title = title
data = []
for idx, output in enumerate(outputs):
try: # Zaid could not be common to the libraries
tally_data = output[zaidnum].tallydata.set_index('Tally N.').loc[tally]
energy = tally_data['Energy'].values
values = tally_data['Value'].values
error = tally_data['Error'].values
lib_name = self.session.conf.get_lib_name(libraries[idx])
lib = {'x': energy, 'y': values, 'err': error,
'ylabel': str(zaidnum)+' ('+lib_name+')'}
data.append(lib)
except KeyError:
# It is ok, simply nothing to plot here
pass
outname = str(zaidnum)+'-'+globalname+'-'+str(tally)
plot = plotter.Plotter(data, title, outpath, outname, quantity,
unit, 'Energy [MeV]', self.testname)
plot.plot('Binned graph')
self._build_atlas(outpath)
def _get_organized_output(self):
libraries = []
outputs = []
zaids = []
for libname, outputslib in self.outputs.items():
libraries.append(libname)
outputs.append(outputslib)
zaids.append(list(outputslib.keys()))
# Extend list to all zaids
allzaids = zaids[0]
for zaidlist in zaids[1:]:
allzaids.extend(zaidlist)
allzaids = set(allzaids) # no duplicates
return libraries, allzaids, outputs
def pp_excel_single(self):
"""
Generate the single library results excel
Returns
-------
None.
"""
template = os.path.join(os.getcwd(), 'templates', 'Sphere_single.xlsx')
outpath = os.path.join(self.excel_path, 'Sphere_single_' +
self.lib+'.xlsx')
# Get results
results = []
errors = []
stat_checks = []
outputs = {}
for folder in os.listdir(self.test_path):
results_path = os.path.join(self.test_path, folder)
pieces = folder.split('_')
# Get zaid
zaidnum = pieces[-2]
# Check for material exception
if zaidnum == 'Sphere':
zaidnum = pieces[-1].upper()
zaidname = self.mat_settings.loc[zaidnum, 'Name']
else:
zaidname = pieces[-1]
# Get mfile
for file in os.listdir(results_path):
if file[-1] == 'm':
mfile = file
elif file[-1] == 'o':
ofile = file
# Parse output
output = SphereMCNPoutput(os.path.join(results_path, mfile),
os.path.join(results_path, ofile))
outputs[zaidnum] = output
# Adjourn raw Data
self.raw_data[zaidnum] = output.tallydata
# Recover statistical checks
st_ck = output.stat_checks
# Recover results and precisions
res, err = output.get_single_excel_data()
for dic in [res, err, st_ck]:
dic['Zaid'] = zaidnum
dic['Zaid Name'] = zaidname
results.append(res)
errors.append(err)
stat_checks.append(st_ck)
# Generate DataFrames
results = pd.DataFrame(results)
errors = pd.DataFrame(errors)
stat_checks = pd.DataFrame(stat_checks)
# Swap Columns and correct zaid sorting
# results
for df in [results, errors, stat_checks]:
df['index'] = pd.to_numeric(df['Zaid'].values, errors='coerce')
df.sort_values('index', inplace=True)
del df['index']
df.set_index(['Zaid', 'Zaid Name'], inplace=True)
df.reset_index(inplace=True)
self.outputs = outputs
self.results = results
self.errors = errors
self.stat_checks = stat_checks
# Write excel
ex = SphereExcelOutputSheet(template, outpath)
# Results
ex.insert_df(9, 2, results, 0)
ex.insert_df(9, 2, errors, 1)
ex.insert_df(9, 2, stat_checks, 2)
lib_name = self.session.conf.get_lib_name(self.lib)
ex.wb.sheets[0].range('D1').value = lib_name
ex.save()
def pp_excel_comparison(self):
"""
Compute the data and create the excel for all libraries comparisons.
In the meantime, additional data is stored for future plots.
Returns
-------
None.
"""
template = os.path.join(os.getcwd(), 'templates',
'Sphere_comparison.xlsx')
outputs = {}
iteration = 0
for reflib, tarlib, name in self.couples:
outpath = os.path.join(self.excel_path, 'Sphere_comparison_' +
name+'.xlsx')
# Get results
dfs = []
for test_path in [self.test_path[reflib], self.test_path[tarlib]]:
results = []
iteration = iteration+1
outputs_lib = {}
for folder in os.listdir(test_path):
results_path = os.path.join(test_path, folder)
pieces = folder.split('_')
# Get zaid
zaidnum = pieces[-2]
# Check for material exception
if zaidnum == 'Sphere':
zaidnum = pieces[-1].upper()
zaidname = self.mat_settings.loc[zaidnum, 'Name']
else:
zaidname = pieces[-1]
# Get mfile
for file in os.listdir(results_path):
if file[-1] == 'm':
mfile = file
elif file[-1] == 'o':
outfile = file
# Parse output
mfile = os.path.join(results_path, mfile)
outfile = os.path.join(results_path, outfile)
output = SphereMCNPoutput(mfile, outfile)
outputs_lib[zaidnum] = output
res, columns = output.get_comparison_data()
try:
zn = int(zaidnum)
except ValueError: # Happens for typical materials
zn = zaidnum
res.append(zn)
res.append(zaidname)
results.append(res)
# Add reference library outputs
if iteration == 1:
outputs[reflib] = outputs_lib
if test_path == self.test_path[tarlib]:
outputs[tarlib] = outputs_lib
# Generate DataFrames
columns.extend(['Zaid', 'Zaid Name'])
df = pd.DataFrame(results, columns=columns)
df.set_index(['Zaid', 'Zaid Name'], inplace=True)
dfs.append(df)
# outputs_couple = outputs
# self.results = results
self.outputs = outputs
# Consider only common zaids
idx1 = dfs[0].index
idx2 = dfs[1].index
newidx = idx1.intersection(idx2)
# Build the final excel data
final = (dfs[0].loc[newidx]-dfs[1].loc[newidx])/dfs[0].loc[newidx]
absdiff = (dfs[0].loc[newidx]-dfs[1].loc[newidx])
self.diff_data = final
self.absdiff = absdiff
# Correct sorting
for df in [final, absdiff]:
df.reset_index(inplace=True)
df['index'] = pd.to_numeric(df['Zaid'].values, errors='coerce')
df.sort_values('index', inplace=True)
del df['index']
df.set_index(['Zaid', 'Zaid Name'], inplace=True)
# Create and concat the summary
old_l = 0
old_lim = 0
rows = []
limits = [0, 0.05, 0.1, 0.2, 0.2]
for i, sup_lim in enumerate(limits[1:]):
if i == len(limits)-2:
row = {'Range': '% of cells > '+str(sup_lim*100)}
for column in final.columns:
cleaned = final[column].replace('', np.nan).dropna()
l_range = len(cleaned[abs(cleaned) > sup_lim])
try:
row[column] = l_range/len(cleaned)
except ZeroDivisionError:
row[column] = np.nan
else:
row = {'Range': str(old_lim*100)+' < '+'% of cells' +
' < ' + str(sup_lim*100)}
for column in final.columns:
cleaned = final[column].replace('', np.nan).dropna()
lenght = len(cleaned[abs(cleaned) < sup_lim])
old_l = len(cleaned[abs(cleaned) < limits[i]])
l_range = lenght-old_l
try:
row[column] = l_range/len(cleaned)
except ZeroDivisionError:
row[column] = np.nan
old_lim = sup_lim
rows.append(row)
summary = pd.DataFrame(rows)
summary.set_index('Range', inplace=True)
# If it is zero the CS are equal! (NaN if both zeros)
for df in [final, absdiff]:
df[df == np.nan] = 'Not Available'
df[df == 0] = 'Identical'
df.replace(-np.inf, 'Reference = 0', inplace=True)
df.replace(1, 'Target = 0', inplace=True)
# --- Write excel ---
# Generate the excel
ex = SphereExcelOutputSheet(template, outpath)
# Prepare the copy of the comparison sheet
template_sheet = 'Comparison'
template_absdiff = 'Comparison (Abs diff)'
ws_comp = ex.wb.sheets[template_sheet]
ws_diff = ex.wb.sheets[template_absdiff]
# WRITE RESULTS
# Percentage comparison
rangeex = ws_comp.range('B10')
rangeex.options(index=True, header=True).value = final
ws_comp.range('D1').value = name
rangeex2 = ws_comp.range('V10')
rangeex2.options(index=True, header=True).value = summary
# Absolute difference comparison
rangeex = ws_diff.range('B10')
rangeex.options(index=True, header=True).value = absdiff
ws_diff.range('D1').value = name
# Add single pp sheets
for lib in [reflib, tarlib]:
cp = self.session.state.get_path('single',
[lib, 'Sphere', 'Excel'])
file = os.listdir(cp)[0]
cp = os.path.join(cp, file)
ex.copy_sheets(cp)
ex.save()
def print_raw(self):
for key, data in self.raw_data.items():
file = os.path.join(self.raw_path, key+'.csv')
data.to_csv(file, header=True, index=False)
class SphereMCNPoutput(MCNPoutput):
def organize_mctal(self):
"""
Retrieve and organize mctal data. Simplified for sphere leakage case
Returns: DataFrame containing the organized data
"""
# Extract data
rows = []
rowstotal = []
for t in self.mctal.tallies:
num = t.tallyNumber
des = t.tallyComment[0]
nCells = t.getNbins("f", False)
nCora = t.getNbins("i", False)
nCorb = t.getNbins("j", False)
nCorc = t.getNbins("k", False)
nDir = t.getNbins("d", False)
# usrAxis = t.getAxis("u")
nUsr = t.getNbins("u", False)
# segAxis = t.getAxis("s")
nSeg = t.getNbins("s", False)
nMul = t.getNbins("m", False)
# cosAxis = t.getAxis("c")
nCos = t.getNbins("c", False)
# ergAxis = t.getAxis("e")
nErg = t.getNbins("e", False)
# timAxis = t.getAxis("t")
nTim = t.getNbins("t", False)
for f in range(nCells):
for d in range(nDir):
for u in range(nUsr):
for s in range(nSeg):
for m in range(nMul):
for c in range(nCos):
for e in range(nErg):
try:
erg = t.erg[e]
except IndexError:
erg = None
for nt in range(nTim):
for k in range(nCorc):
for j in range(nCorb):
for i in range(nCora):
val = t.getValue(f, d,
u, s,
m, c,
e, nt,
i, j,
k, 0)
err = t.getValue(f, d,
u, s,
m, c,
e, nt,
i, j,
k, 1)
if val <= 0:
err = np.nan
row = [num, des,
erg,
val, err]
rows.append(row)
# If Energy binning is involved
if t.ergTC == 't':
# 7 steps to get to energy, + 4 for time and mesh directions
totalbin = t.valsErrors[-1][-1][-1][-1][-1][-1][-1][-1][-1][-1][-1]
totalvalue = totalbin[0]
if totalvalue > 0:
totalerror = totalbin[-1]
else:
totalerror = np.nan
row = [num, des, totalvalue, totalerror]
rowstotal.append(row)
df = pd.DataFrame(rows, columns=['Tally N.', 'Tally Description',
'Energy', 'Value', 'Error'])
dftotal = pd.DataFrame(rowstotal, columns=['Tally N.',
'Tally Description',
'Value', 'Error'])
return df, dftotal
def get_single_excel_data(self):
"""
Get the excel data of a single MCNP output
Returns
-------
results : dic
Excel result for different tallies
errors : dic
Error average in all tallies
"""
# Tallies to post process
tallies2pp = ['2', '32', '24', '14', '34']
heating_tallies = ['4', '6', '44', '46']
data = self.tallydata.set_index(['Tally Description', 'Energy'])
totbins = self.totalbin.set_index('Tally Description')
results = {} # Store excel results of different tallies
errors = {} # Store average error in different tallies
keys = {} # Tally names and numbers
heating_res = {} # Mid-process heating results
notes = 'Negative Bins:' # Record negative bins here
initial_notes_length = len(notes) # To check if notes are registered
for tally in self.mctal.tallies:
num = str(tally.tallyNumber)
keys[num] = tally.tallyComment[0]
# Isolate tally
masked = data.loc[tally.tallyComment[0]]
# Get mean error among bins, different for single bin
if tally.ergTC == 't':
mean_error = totbins.loc[tally.tallyComment[0]]['Error']
else:
mean_error = masked['Error'].mean()
if num in tallies2pp:
masked_zero = masked[masked['Value'] == 0]
original_length = len(masked)
masked = masked[masked['Value'] < 0]
if len(masked) > 0:
res = 'Value < 0 in '+str(len(masked))+' bin(s)'
# Get energy bins
bins = list(masked.reset_index()['Energy'].values)
notes = notes+'\n('+str(num)+'): '
for ebin in bins:
notes = notes+str(ebin)+', '
notes = notes[:-2] # Clear string from excess commas
elif len(masked_zero) == original_length:
res = 'Value = 0 for all bins'
else:
res = 'Value > 0 for all bins'
results[tally.tallyComment[0]] = res
errors[tally.tallyComment[0]] = mean_error
elif num in heating_tallies:
heating_res[num] = float(masked['Value'].values[0])
errors[tally.tallyComment[0]] = mean_error
comp = 'Heating comparison [F4 vs F6]'
try:
results['Neutron '+comp] = ((heating_res['6'] - heating_res['4']) /
heating_res['6'])
except ZeroDivisionError:
results['Neutron '+comp] = 0
try:
results['Gamma '+comp] = ((heating_res['46'] - heating_res['44']) /
heating_res['46'])
except ZeroDivisionError:
results['Gamma '+comp] = 0
# Notes adding
if len(notes) > initial_notes_length:
results['Notes'] = notes
else:
results['Notes'] = ''
return results, errors
def get_comparison_data(self):
"""
Get Data for single zaid to be used in comparison.
Returns
-------
results : list
All results per tally to compare
columns : list
Tally names
"""
# Tallies to post process
tallies2pp = ['12', '22', '24', '14', '34', '6', '46']
data = self.tallydata.set_index(['Tally Description', 'Energy'])
totalbins = self.totalbin.set_index('Tally Description')
results = [] # Store data to compare for different tallies
columns = [] # Tally names and numbers
# Reorder tallies
tallies = []
for tallynum in tallies2pp:
for tally in self.mctal.tallies:
num = str(tally.tallyNumber)
if num == tallynum:
tallies.append(tally)
for tally in tallies:
num = str(tally.tallyNumber)
# Isolate tally
masked = data.loc[tally.tallyComment[0]]
if num in tallies2pp:
if num in ['12', '22']: # Coarse Flux bins
masked_tot = totalbins.loc[tally.tallyComment[0]]
# Get energy bins
bins = list(masked.reset_index()['Energy'].values)
for ebin in bins:
# colname = '(T.ly '+str(num)+') '+str(ebin)
colname = str(ebin)+' [MeV]'+' [t'+num+']'
columns.append(colname)
results.append(masked['Value'].loc[ebin])
# Add the total bin
colname = 'Total'+' [t'+num+']'
columns.append(colname)
results.append(masked_tot['Value'])
else:
columns.append(tally.tallyComment[0])
results.append(masked['Value'].values[0])
return results, columns
class SphereSDDRoutput(SphereOutput):
times = ['0s', '2.7h', '24h', '11.6d', '30d', '10y']
timecols = {'0s': '1.0', '2.7h': '2.0', '24h': '3.0',
'11.6d': '4.0', '30d': '5.0', '10y': '6.0'}
def pp_excel_single(self):
"""
Generate the single library results excel
Returns
-------
None.
"""
template = os.path.join(os.getcwd(), 'templates',
'SphereSDDR_single.xlsx')
outpath = os.path.join(self.excel_path, 'SphereSDDR_single_' +
self.lib+'.xlsx')
# compute the results
results, errors, stat_checks = self._compute_single_results()
# Write excel
ex = SphereExcelOutputSheet(template, outpath)
# Results
ex.insert_df(11, 2, results, 0, header=False)
ex.insert_df(11, 2, errors, 1, header=False)
ex.insert_df(9, 2, stat_checks, 2, header=True)
lib_name = self.session.conf.get_lib_name(self.lib)
ex.wb.sheets[0].range('E1').value = lib_name
ex.save()
def pp_excel_comparison(self):
"""
Generate the excel comparison output
Returns
-------
None.
"""
template = os.path.join(os.getcwd(), 'templates',
'SphereSDDR_comparison.xlsx')
for reflib, tarlib, name in self.couples:
outpath = os.path.join(self.excel_path, 'Sphere_comparison_' +
name+'.xlsx')
final, absdiff = self._compute_compare_result(reflib, tarlib)
# --- Write excel ---
# Generate the excel
ex = SphereExcelOutputSheet(template, outpath)
# Prepare the copy of the comparison sheet
ws_comp = ex.wb.sheets['Comparison']
ws_diff = ex.wb.sheets['Comparison (Abs diff)']
# WRITE RESULTS
# Percentage comparison
rangeex = ws_comp.range('B11')
rangeex.options(index=True, header=False).value = final
ws_comp.range('E1').value = name
# Absolute difference comparison
rangeex = ws_diff.range('B11')
rangeex.options(index=True, header=False).value = absdiff
# Add single pp sheets
for lib in [reflib, tarlib]:
cp = self.session.state.get_path('single',
[lib, 'SphereSDDR', 'Excel'])
file = os.listdir(cp)[0]
cp = os.path.join(cp, file)
ex.copy_sheets(cp)
ex.save()
def _get_organized_output(self):
"""
Simply recover a list of the zaids and libraries involved
"""
zaids = []
for (zaidnum, mt, lib), _ in self.outputs.items():
zaids.append((zaidnum, mt))
zaids = list(set(zaids))
libs = [] # Not used
outputs = [] # Not used
return zaids, libs, outputs
def _generate_single_plots(self, outpath):
allzaids, libs, outputs = self._get_organized_output()
globalname = self.lib
self._generate_plots(libs, allzaids, outputs, globalname, outpath)
def _generate_plots(self, libraries, allzaids, outputs, globalname,
outpath):
"""
Generate all the plots requested by the Sphere SDDR benchmark
Parameters
----------
libraries : dummy
here only for compatibility issues.
allzaids : list
list of all zaids resulting from the union of the results from
both libraries.
outputs : dummy
here only for compatibility reasons.
globalname : str
name for the output.
outpath : str
path to use for the dumping of imgs.
Returns
-------
None.
"""
# Check if self libraries is already a list
if type(self.lib) != list:
libraries = [self.lib]
else:
libraries = self.lib
# Initialize atlas
template = os.path.join(self.code_path, 'templates',
'AtlasTemplate.docx')
atlas = at.Atlas(template, 'Sphere SDDR '+globalname)
libmanager = self.session.lib_manager
# ------------- Binned plots of gamma flux ------------
atlas.doc.add_heading('Photon Flux (32)', level=1)
fluxquantity = 'Photon Flux'
fluxunit = r'$p/(cm^2\cdot\#_S)$'
allzaids.sort()
# --- Binned plots of the gamma flux ---
for (zaidnum, mt) in tqdm(allzaids, desc=' Binned flux plots'):
# Get everything for the title of the zaid
try:
name, formula = libmanager.get_zaidname(zaidnum)
args = [zaidnum, name, formula, mt]
title = 'Zaid: {} ({} {}), MT={}'.format(*args)
# For zaids cooldown time does not change anything
# Keep the multiple times only for materials
times = [self.times[0]]
except ValueError: # A material is passed instead of zaid
matname = self.mat_settings.loc[zaidnum, 'Name']
title = zaidnum+' ('+matname+')'
times = self.times
atlas.doc.add_heading(title, level=2)
for time in times:
atlas.doc.add_heading('Cooldown time = {}'.format(time),
level=3)
title = 'Gamma Leakage flux after a {} cooldown'.format(time)
data = []
for lib in libraries:
try: # Zaid could not be common to the libraries
outp = self.outputs[zaidnum, mt, lib]
except KeyError:
# It is ok, simply nothing to plot here since zaid was
# not in library
continue
# Get the zaid flux
tally_data = outp.tallydata[32].set_index('Time')
# Select the correct time
t = 'F'+self.timecols[time]
tally_data = tally_data.loc[t]
# If for some reason a total survived just kill him
tally_data = tally_data[tally_data.Energy != 'total']
energy = tally_data['Energy'].values
values = tally_data['Value'].values
error = tally_data['Error'].values
lib_name = self.session.conf.get_lib_name(lib)
ylabel = '{}_{} ({})'.format(formula, mt, lib_name)
libdata = {'x': energy, 'y': values, 'err': error,
'ylabel': ylabel}
data.append(libdata)
outname = '{}-{}-{}-{}-{}'.format(zaidnum, mt, globalname,
32, t)
plot = plotter.Plotter(data, title, outpath, outname,
fluxquantity, fluxunit, 'Energy [MeV]',
self.testname)
outfile = plot.plot('Binned graph')
atlas.insert_img(outfile)
# --- Wave plots flux ---
# Do this block only if libs are more than one
lim = 35 # limit of zaids to be in a single plot
# Plot parameters which are not going to change
quantity = ['Neutron Flux', 'Photon Flux', 'SDDR']
unit = [r'$n/(cm^2\cdot n_S)$', r'$p/(cm^2\cdot n_S)$', 'Sv/h']
xlabel = 'Zaid/Material and MT value'
if len(libraries) > 1:
atlas.doc.add_heading('Flux and SDDR ratio plots', level=1)
# 1) collect zaid-mt couples in libraries and keep only the ones
# that appears on the reference + at least one lib
# Build a df will all possible zaid, mt, lib combination
allkeys = list(self.outputs.keys())
df = pd.DataFrame(allkeys)
df.columns = ['zaid', 'mt', 'lib']
df['zaid-mt'] = df['zaid'].astype(str)+'-'+df['mt'].astype(str)
df.set_index('lib', inplace=True)
# get the reference zaids
refzaids = set(df.loc[self.lib[0]]['zaid-mt'].values)
otherzaids = set(df.drop(self.lib[0])['zaid-mt'].values)
# Get the final zaid-mt couples to consider
zaid_couples = []
mat_couples = []
for zaidmt in refzaids:
if zaidmt in otherzaids:
zaid, mt = zaidmt.split('-')
if zaid[0] in 'mM':
mat_couples.append((zaid, mt))
else:
zaid_couples.append((zaid, mt))
# sort it
zaid_couples.sort(key=self._sortfunc_zaidMTcouples)
mat_couples.sort(key=self._sortfunc_zaidMTcouples)
# # There is going to be a plot for each cooldown time
# Only one plot necessary for zaids at cd=0
# 2) Recover/compute the data that needs to be plot for each lib
data = []
time = self.times[0]
for lib in self.lib:
nfluxs = []
pfluxs = []
sddrs = []
xlabels = []
ylabel = self.session.conf.get_lib_name(lib)
for zaid, mt in zaid_couples:
# Extract values
nflux, pflux, sddr = self._extract_data4plots(zaid, mt,
lib, time)
# Memorize values
nfluxs.append(nflux)
pfluxs.append(pflux)
sddrs.append(sddr)
name, formula = libmanager.get_zaidname(zaid)
xlabels.append(formula+' '+mt)
# Split the data if its length is more then the limit
datalenght = len(xlabels)
sets = math.ceil(datalenght/lim)
last_idx = 0
idxs = []
step = int(datalenght/sets)
for _ in range(sets):
newidx = last_idx+step
idxs.append((last_idx, newidx))
last_idx = newidx
for j, (start, end) in enumerate(idxs):
# build the dic
ydata = [nfluxs[start:end],
pfluxs[start:end],
sddrs[start:end]]
xlab = xlabels[start:end]
libdata = {'x': xlab, 'y': ydata, 'err': [],
'ylabel': ylabel}
# try to append it to the data in the correct index
# if the index is not found, then the list still needs
# to be initialized
try:
data[j].append(libdata)
except IndexError:
data.append([libdata])
# 3) Compute parameters for the plotter init
refname = self.session.conf.get_lib_name(self.lib[0])
for datapiece in data:
title = 'Ratio Vs {} (T0 + {})'.format(refname, time)
outname = 'dummy' # Does not matter if plot is added imm.
testname = self.testname
plot = plotter.Plotter(datapiece, title, outpath, outname,
quantity, unit, xlabel, testname)
outfile = plot.plot('Waves')
atlas.insert_img(outfile)
# --- Single wave plot for each material ---
atlas.doc.add_heading('Materials ratio plot', level=1)
xlab = self.times
quantity = ['Neutron Flux', 'Photon Flux', 'SDDR']
unit = ['', '', '']
xlabel = 'Cooldown time'
for material, _ in tqdm(mat_couples, desc=' Materials: '):
atlas.doc.add_heading(material, level=2)
data = []
for lib in self.lib:
ylabel = self.session.conf.get_lib_name(lib)
nfluxs = []
pfluxs = []
sddrs = []
for time in self.times:
nflux, pflux, sddr = self._extract_data4plots(material, 'All',
lib, time)
# Memorize
nfluxs.append(nflux)
pfluxs.append(pflux)