diff --git a/docs/source/usage/benchmarks.rst b/docs/source/usage/benchmarks.rst index 3774b6a5..6a746723 100644 --- a/docs/source/usage/benchmarks.rst +++ b/docs/source/usage/benchmarks.rst @@ -27,6 +27,8 @@ benchmark in JADE. expect a single library (e.g. ``31c``), activation ones require two: an activation library and a transport one for all zaids that cannot be activated (e.g. ``99c-31c``). + * The irradiation and activation files if present for a SDDR benchmark should be + placed in the same folder as the input file. * In activation benchmarks, the library that is considered the assessed one is always the activation library (i.e. the first provided). No track is kept during the post-processing of which was the transport library used diff --git a/jade/computational.py b/jade/computational.py index f0856795..5e254bbd 100644 --- a/jade/computational.py +++ b/jade/computational.py @@ -87,9 +87,14 @@ def executeBenchmarksRoutines(session, lib: str, runoption, exp=False) -> None: bool(row["d1S"]), ]) ): - print("Transport code was not specified or is not available for input generation, defaulting to MCNP") - print("") - row["MCNP"]=True + if ( + testname in ["SphereSDDR", "FNG", "ITER_Cyl_SDDR"] + ): + row["d1S"] = True + else: + print("Transport code was not specified or is not available for input generation, defaulting to MCNP") + print("") + row["MCNP"] = True print(" -- " + testname.upper() + " STARTED --\n") print(" Generating input files:" + " " + str(datetime.datetime.now())) diff --git a/jade/configuration.py b/jade/configuration.py index c02eb4e8..3f674ab9 100644 --- a/jade/configuration.py +++ b/jade/configuration.py @@ -69,7 +69,7 @@ def _process_path(self, file_path: str) -> str: if not os.path.exists(file_path): # If to terminate or not the session is lef to the user # other codes path may be present but not used - logging.warning("Path {file_path} do not exist") + logging.warning(f"Path {file_path} do not exist") # fatal_exception(file_path + ' does not exist') return file_path diff --git a/jade/default_settings/Config.xlsx b/jade/default_settings/Config.xlsx index edb2ba00..b324648b 100644 Binary files a/jade/default_settings/Config.xlsx and b/jade/default_settings/Config.xlsx differ diff --git a/jade/excel_support.py b/jade/excel_support.py deleted file mode 100644 index 65b3f744..00000000 --- a/jade/excel_support.py +++ /dev/null @@ -1,588 +0,0 @@ -# -*- coding: utf-8 -*- -""" -Created on Thu Jan 2 12:05:36 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 . -""" -# from copy import copy -# import openpyxl -import pandas as pd - - -# def createNewWorkbook(manyWb, theOne): -# for wb in manyWb: -# for sheetName in wb.sheetnames: -# o = theOne.create_sheet(sheetName) -# safeTitle = o.title -# copySheet(wb[sheetName], theOne[safeTitle]) - - -# def copySheet(sourceSheet, newSheet): -# for row in sourceSheet.rows: -# for cell in row: -# newCell = newSheet.cell(row=cell.row, column=cell.col_idx, -# value=cell.value) -# if cell.has_style: -# newCell.font = copy(cell.font) -# newCell.border = copy(cell.border) -# newCell.fill = copy(cell.fill) -# newCell.number_format = copy(cell.number_format) -# newCell.protection = copy(cell.protection) -# newCell.alignment = copy(cell.alignment) - - -# def merge_sheets(filesInput, outfile): -# myfriends = [openpyxl.load_workbook(f, read_only=False, -# keep_vba=True) for f in filesInput] -# # theOne = openpyxl.Workbook() -# # del theOne['Sheet'] # We want our new book to be empty. Thanks. -# createNewWorkbook(myfriends, outfile) -# for excel in myfriends: -# excel.close() - -# # outfile.save(outfile) - - -def insert_df(startrow, startcolumn, df, ws, header=True): - """ - Insert a DataFrame (df) into a Worksheet (ws) using xlwings. - (startrow) and (startcolumn) identify the starting data entry - """ - columns = list(df.columns) - values = df.values - if header: - for i, column in enumerate(range(startcolumn, - startcolumn+len(columns))): - value = columns[i] - try: - ws.cell(column=column, row=startrow,value=value) - #ws.range((startrow, column)).value = value - except (AttributeError, ValueError) as e: - print(e) - print('Warning! header not printes: column,value', - column, value) - startrow = startrow+1 - - for i, row in enumerate(range(startrow, startrow+len(df))): - for j, column in enumerate(range(startcolumn, - startcolumn+len(df.columns))): - value = values[i][j] - try: - ws.cell(column=column,row=row,value=value) - #ws.range((row, column)).value = value - except (AttributeError, ValueError) as e: - print(e) - print('Warning! value not printed: row,column,value', row, - column, value) -def single_excel_writer(self, outpath, lib, tallies, stats=None): - """ - Produces single library summary excel file using XLSXwriter - - Parameters - ---------- - outpath : path or str - path to the output in Tests/Postprocessing. - lib : str - Shorthand representation of data library (i.e 00c, 31c). - tallies : Dataframe - Summary of tally tallies - errors: Dataframe - Errors on tally tallies - stats: Dataframe - Results of statistical checks - - Returns - ------- - None - """ - writer = pd.ExcelWriter(outpath, engine="xlsxwriter") - - #for df in (tallies, errors): - #df.set_index("Zaid", inplace=True) - - startrow = 8 - startcol = 1 - max_len = 0 - max_width = 0 - df_positions = [] - - - - for tally, results in tallies.items(): - #print(results) - tally_len, tally_width = results["Value"].shape - df_positions.append([startrow,startcol]) - #print(pd.Series(results["title"])) - #pd.Series(results["title"]).to_excel(writer, startrow=startrow, startcol=startcol+1, sheet_name="Values", index=False, header=False) - results["Value"].to_excel(writer, startrow=startrow+1, startcol=startcol, sheet_name="Values") - startrow = startrow + tally_len + 3 - max_len = max_len + tally_len - if tally_width > max_width: - max_width = tally_width - - wb = writer.book - tal_sheet = writer.sheets["Values"] - #errors.to_excel(writer, startrow=8, startcol=1, sheet_name="Errors") - #err_sheet = writer.sheets["Errors"] - - #tallies_len, tallies_width = tallies.shape - #errors_len, errors_width = errors.shape - - if stats is not None: - print(stats) - #stats.set_index("Zaid", inplace=True) - stats.to_excel( - writer, startrow=8, startcol=1, sheet_name="Statistical Checks" - ) - stat_sheet = writer.sheets["Statistical Checks"] - stats_len, stats_width = stats.shape - - # Formatting styles - plain_format = wb.add_format({"bg_color": "#FFFFFF"}) - oob_format = wb.add_format( - { - "align": "center", - "valign": "center", - "bg_color": "#D9D9D9", - "text_wrap": True, - } - ) - tally_format = wb.add_format({"bg_color": "#D9D9D9"}) - merge_format = wb.add_format( - {"align": "center", "valign": "center", "border": 2} - ) - title_merge_format = wb.add_format( - { - "font_size": "36", - "align": "center", - "valign": "center", - "bold": True, - "border": 2, - } - ) - subtitle_merge_format = wb.add_format( - { - "font_size": "16", - "align": "center", - "valign": "center", - "bold": True, - "border": 2, - } - ) - legend_text_format = wb.add_format({"align": "center", "bg_color": "white"}) - red_cell_format = wb.add_format({"bg_color": "red"}) - orange_cell_format = wb.add_format({"bg_color": "orange"}) - yellow_cell_format = wb.add_format({"bg_color": "yellow"}) - green_cell_format = wb.add_format({"bg_color": "#A6D86E"}) - value_allzero_format = wb.add_format({"bg_color": "#EDEDED"}) - value_belowzero_format = wb.add_format({"bg_color": "#FFC7CE"}) - value_abovezero_format = wb.add_format({"bg_color": "#C6EFCE"}) - - # tallies - - # Title Format - tal_sheet.merge_range("B1:C2", "LIBRARY", subtitle_merge_format) - tal_sheet.merge_range("D1:D2", lib, subtitle_merge_format) - tal_sheet.merge_range( - "B3:L8", "SPHERE LEAKAGE TEST RESULTS RECAP: TALLIES", title_merge_format - ) - for tal in range(len(df_positions)): - tal_sheet.merge_range(df_positions[tal][0], - df_positions[tal][1] + 1, - df_positions[tal][0], - df_positions[tal][1] + 4, - list(tallies.values())[tal]["title"], - subtitle_merge_format) - #tal_sheet.merge_range("B8:C8", "ZAID", subtitle_merge_format) - #tal_sheet.merge_range("D8:L8", "TALLY", subtitle_merge_format) - - # Freeze title - tal_sheet.freeze_panes(8, 2) - - # out of bounds - tal_sheet.set_column(0, 0, 4, oob_format) - tal_sheet.set_column(max_width + 2, 1000, 18, oob_format) - for i in range(9): - tal_sheet.set_row(i, None, oob_format) - for i in range(9 + max_len, 1000): - tal_sheet.set_row(i, None, oob_format) - - # Column widths for tallies, set up to 15th col to ensure title format correct - tal_sheet.set_column(1, 14, 20) - tal_sheet.set_column(1, max_width + 2, 20) - - # Row Heights - tal_sheet.set_row(7, 31) - #tal_sheet.set_row(8, 73.25) - - # Legend - tal_sheet.merge_range("N3:O3", "LEGEND", merge_format) - tal_sheet.merge_range("N8:O8", "According to MCNP manual", oob_format) - tal_sheet.write("N4", "", red_cell_format) - tal_sheet.write("O4", ">|5|%", legend_text_format) - tal_sheet.write("N5", "", orange_cell_format) - tal_sheet.write("O5", "|1|%≤|5|%", legend_text_format) - tal_sheet.write("N6", "", yellow_cell_format) - tal_sheet.write("O6", "|0.5|%≤|1|%", legend_text_format) - tal_sheet.write("N7", "", green_cell_format) - tal_sheet.write("O7", "<|0.5|%", legend_text_format) - - # Conditional Formatting - tal_sheet.conditional_format( - 10, - 1, - 8 + max_len, - max_width + 1, - {"type": "blanks", "format": oob_format}, - ) - tal_sheet.conditional_format( - 10, - 2, - 8 + max_len, - max_width + 1, - { - "type": "text", - "criteria": "containing", - "value": "Value = 0", - "format": value_allzero_format, - }, - ) - tal_sheet.conditional_format( - 10, - 2, - 8 + max_len, - max_width + 1, - { - "type": "text", - "criteria": "containing", - "value": "Value < 0", - "format": value_belowzero_format, - }, - ) - tal_sheet.conditional_format( - 10, - 2, - 8 + max_len, - max_width + 1, - { - "type": "text", - "criteria": "containing", - "value": "Value > 0", - "format": value_abovezero_format, - }, - ) - tal_sheet.conditional_format( - 10, - 2, - 8 + max_len, - max_width + 1, - { - "type": "cell", - "criteria": "greater than", - "value": 0.05, - "format": red_cell_format, - }, - ) - tal_sheet.conditional_format( - 10, - 2, - 8 + max_len, - max_width + 1, - { - "type": "cell", - "criteria": "between", - "minimum": 0.01, - "maximum": 0.05, - "format": orange_cell_format, - }, - ) - tal_sheet.conditional_format( - 10, - 2, - 8 + max_len, - max_width + 1, - { - "type": "cell", - "criteria": "between", - "minimum": 0.005, - "maximum": 0.01, - "format": yellow_cell_format, - }, - ) - tal_sheet.conditional_format( - 10, - 2, - 8 + max_len, - max_width + 1, - { - "type": "cell", - "criteria": "less than", - "value": -0.05, - "format": red_cell_format, - }, - ) - tal_sheet.conditional_format( - 10, - 2, - 8 + max_len, - max_width + 1, - { - "type": "cell", - "criteria": "between", - "minimum": -0.05, - "maximum": -0.01, - "format": orange_cell_format, - }, - ) - tal_sheet.conditional_format( - 10, - 2, - 8 + max_len, - max_width + 1, - { - "type": "cell", - "criteria": "between", - "minimum": -0.01, - "maximum": -0.005, - "format": yellow_cell_format, - }, - ) - tal_sheet.conditional_format( - 10, - 2, - 8 + max_len, - max_width + 1, - { - "type": "cell", - "criteria": "between", - "minimum": -0.005, - "maximum": 0.005, - "format": green_cell_format, - }, - ) - - # ERRORS - - # Title - #err_sheet.merge_range("B1:C2", "LIBRARY", subtitle_merge_format) - #err_sheet.merge_range("D1:D2", lib, subtitle_merge_format) - #err_sheet.merge_range( - # "B3:L7", "SPHERE LEAKAGE TEST RESULTS RECAP: ERRORS", title_merge_format - #) - #err_sheet.merge_range("B8:C8", "ZAID", subtitle_merge_format) - #err_sheet.merge_range("D8:L8", "TALLY", subtitle_merge_format) -# - ## Freeze title - #err_sheet.freeze_panes(9, 0) -# - ## out of bounds - #err_sheet.set_column(0, 0, 4, oob_format) - #err_sheet.set_column(errors_width + 2, 1000, 18, oob_format) - #for i in range(9): - # err_sheet.set_row(i, None, oob_format) - #for i in range(9 + errors_len, 1000): - # err_sheet.set_row(i, None, oob_format) -# - ## Column widths for errors, set up to 15th col by default to ensure title format correct - #err_sheet.set_column(1, 14, 20) - #err_sheet.set_column(1, errors_width + 2, 20) -# - ## Row Heights - #err_sheet.set_row(7, 31) - #err_sheet.set_row(8, 73.25) -# - ## Legend - #err_sheet.merge_range("N3:O3", "LEGEND", merge_format) - #err_sheet.merge_range("N8:O8", "According to MCNP manual", oob_format) - #err_sheet.write("N4", "", red_cell_format) - #err_sheet.write("O4", "> 50%", legend_text_format) - #err_sheet.write("N5", "", orange_cell_format) - #err_sheet.write("O5", "20% ≤ 50%", legend_text_format) - #err_sheet.write("N6", "", yellow_cell_format) - #err_sheet.write("O6", "10% ≤ 20%", legend_text_format) - #err_sheet.write("N7", "", green_cell_format) - #err_sheet.write("O7", "< 10%", legend_text_format) -# - ## Conditional Formatting - #err_sheet.conditional_format( - # 9, - # 3, - # 8 + errors_len, - # errors_width + 1, - # {"type": "blanks", "format": plain_format}, - #) - #err_sheet.conditional_format( - # 9, - # 3, - # 8 + errors_len, - # errors_width + 1, - # {"type": "cell", "criteria": ">", "value": 0.5, "format": red_cell_format}, - #) - #err_sheet.conditional_format( - # 9, - # 3, - # 8 + errors_len, - # errors_width + 1, - # { - # "type": "cell", - # "criteria": "between", - # "minimum": 0.2, - # "maximum": 0.5, - # "format": orange_cell_format, - # }, - #) - #err_sheet.conditional_format( - # 9, - # 3, - # 8 + errors_len, - # errors_width + 1, - # { - # "type": "cell", - # "criteria": "between", - # "minimum": 0.1, - # "maximum": 0.2, - # "format": yellow_cell_format, - # }, - #) - #err_sheet.conditional_format( - # 9, - # 3, - # 8 + errors_len, - # errors_width + 1, - # {"type": "cell", "criteria": "<", "value": -0.5, "format": red_cell_format}, - #) - #err_sheet.conditional_format( - # 9, - # 3, - # 8 + errors_len, - # errors_width + 1, - # { - # "type": "cell", - # "criteria": "between", - # "minimum": -0.5, - # "maximum": -0.2, - # "format": orange_cell_format, - # }, - #) - #err_sheet.conditional_format( - # 9, - # 3, - # 8 + errors_len, - # errors_width + 1, - # { - # "type": "cell", - # "criteria": "between", - # "minimum": -0.2, - # "maximum": -0.1, - # "format": yellow_cell_format, - # }, - #) - #err_sheet.conditional_format( - # 9, - # 3, - # 8 + errors_len, - # errors_width + 1, - # { - # "type": "cell", - # "criteria": "between", - # "minimum": -0.1, - # "maximum": 0.1, - # "format": green_cell_format, - # }, - #) - - # STAT CHECKS - if stats is not None: - # Title - stat_sheet.merge_range("B1:C2", "LIBRARY", subtitle_merge_format) - stat_sheet.merge_range("D1:D2", lib, subtitle_merge_format) - stat_sheet.merge_range( - "B3:L7", - "SPHERE LEAKAGE TEST RESULTS RECAP: STATISTICAL CHECKS", - title_merge_format, - ) - stat_sheet.merge_range("B8:C8", "ZAID", subtitle_merge_format) - stat_sheet.merge_range("D8:L8", "TALLY", subtitle_merge_format) - - # Freeze title - stat_sheet.freeze_panes(9, 0) - - # out of bounds - stat_sheet.set_column(0, 0, 4, oob_format) - stat_sheet.set_column(stats_width + 2, 1000, 18, oob_format) - for i in range(9): - stat_sheet.set_row(i, None, oob_format) - for i in range(9 + stats_len, 1000): - stat_sheet.set_row(i, None, oob_format) - - # Column widths for errors, set up to 15th col by default to ensure title format correct - stat_sheet.set_column(1, 14, 20) - stat_sheet.set_column(1, stats_width + 2, 20) - - # Row Heights - stat_sheet.set_row(7, 31) - stat_sheet.set_row(8, 73.25) - - # Formatting - stat_sheet.conditional_format( - 9, - 3, - 8 + stats_len, - stats_width + 1, - {"type": "blanks", "format": plain_format}, - ) - stat_sheet.conditional_format( - 9, - 3, - 8 + stats_len, - stats_width + 1, - { - "type": "text", - "criteria": "containing", - "value": "Passed", - "format": value_abovezero_format, - }, - ) - stat_sheet.conditional_format( - 9, - 3, - 8 + stats_len, - stats_width + 1, - { - "type": "text", - "criteria": "containing", - "value": "All zeros", - "format": value_allzero_format, - }, - ) - stat_sheet.conditional_format( - 9, - 3, - 8 + stats_len, - stats_width + 1, - { - "type": "text", - "criteria": "containing", - "value": "Missed", - "format": value_belowzero_format, - }, - ) - - wb.close() \ No newline at end of file diff --git a/jade/excelsupport.py b/jade/excelsupport.py index d413c83d..399e2fe3 100644 --- a/jade/excelsupport.py +++ b/jade/excelsupport.py @@ -89,7 +89,7 @@ def insert_df(startrow, startcolumn, df, ws, header=True): #ws.range((row, column)).value = value except (AttributeError, ValueError) as e: print(e) - print('Warning! value not printed: row,column,value', row, + print('Warning! value not printed: row, column, value', row, column, value) def single_excel_writer(self, outpath, lib, testname, tallies, stats=None): """ @@ -124,7 +124,7 @@ def single_excel_writer(self, outpath, lib, testname, tallies, stats=None): df_positions = [] - + print(tallies) for tally, results in tallies.items(): #print(results) tally_len, tally_width = results["Value"].shape @@ -459,4 +459,560 @@ def single_excel_writer(self, outpath, lib, testname, tallies, stats=None): }, ) + wb.close() + +def comp_excel_writer(self, outpath, lib_to_comp, testname, comps, abs_diffs, std_devs): + """ + Produces single library summary excel file using XLSXwriter + + Parameters + ---------- + outpath : path or str + path to the output in Tests/Postprocessing. + lib_to_comp : str + Shorthand representation of data libraries to be + compared (i.e 00c_vs_31c). + tallies : Dataframe + Summary of tally tallies + errors: Dataframe + Errors on tally tallies + stats: Dataframe + Results of statistical checks + + Returns + ------- + None + """ + writer = pd.ExcelWriter(outpath, engine="xlsxwriter") + + title = testname + " RESULTS RECAP: Comparison" + startrow = 8 + startcol = 1 + max_len = 0 + max_width = 0 + df_positions = [] + + for i in range(len(comps.keys())): + comp_len, comp_width = list(comps.values())[i]["Value"].shape + df_positions.append([startrow,startcol]) + list(comps.values())[i]["Value"].to_excel(writer, startrow=startrow+1, + startcol=startcol, + sheet_name="Comparisons (%)") + list(std_devs.values())[i]["Value"].to_excel(writer, startrow=startrow+1, + startcol=startcol, + sheet_name="Comparisons (std. dev.)") + list(abs_diffs.values())[i]["Value"].to_excel(writer, startrow=startrow+1, + startcol=startcol, + sheet_name="Comparisons (abs. diff.)") + + startrow = startrow + comp_len + 3 + max_len = max_len + comp_len + 3 + if comp_width > max_width: + max_width = comp_width + + wb = writer.book + comp_sheet = writer.sheets["Comparisons (%)"] + std_dev_sheet = writer.sheets["Comparisons (std. dev.)"] + absdiff_sheet = writer.sheets["Comparisons (abs. diff.)"] + + # Formatting styles + plain_format = wb.add_format({"bg_color": "#FFFFFF"}) + oob_format = wb.add_format( + { + "align": "center", + "valign": "center", + "bg_color": "#D9D9D9", + "text_wrap": True, + } + ) + tally_format = wb.add_format({"bg_color": "#D9D9D9"}) + merge_format = wb.add_format( + {"align": "center", "valign": "center", "border": 2} + ) + title_merge_format = wb.add_format( + { + "font_size": "36", + "align": "center", + "valign": "center", + "bold": True, + "border": 2, + } + ) + subtitle_merge_format = wb.add_format( + { + "font_size": "16", + "align": "center", + "valign": "center", + "bold": True, + "border": 2, + } + ) + legend_text_format = wb.add_format({"align": "center", "bg_color": "white"}) + red_cell_format = wb.add_format({"bg_color": "red"}) + orange_cell_format = wb.add_format({"bg_color": "orange"}) + yellow_cell_format = wb.add_format({"bg_color": "yellow"}) + green_cell_format = wb.add_format({"bg_color": "#A6D86E"}) + value_allzero_format = wb.add_format({"bg_color": "#EDEDED"}) + value_belowzero_format = wb.add_format({"bg_color": "#FFC7CE"}) + value_abovezero_format = wb.add_format({"bg_color": "#C6EFCE"}) + not_avail_format = wb.add_format({"bg_color": "#B8B8B8"}) + target_ref_format = wb.add_format({"bg_color": "#8465C5"}) + identical_format = wb.add_format({"bg_color": "#7ABD7E"}) + + # COMPARISON + + # Title Format + comp_sheet.merge_range("B1:C2", "LIBRARY", subtitle_merge_format) + comp_sheet.merge_range("D1:D2", lib_to_comp, subtitle_merge_format) + comp_sheet.merge_range( + "B3:L8", "{} RESULTS RECAP: COMPARISON (%)".format(testname), title_merge_format + ) + for tal in range(len(df_positions)): + comp_sheet.merge_range(df_positions[tal][0], + df_positions[tal][1] + 1, + df_positions[tal][0], + df_positions[tal][1] + 4, + list(comps.values())[tal]["title"], + subtitle_merge_format) + #comp_sheet.merge_range("B8:C8", "ZAID", subtitle_merge_format) + #comp_sheet.merge_range("D8:L8", "TALLY", subtitle_merge_format) + + # Freeze title + comp_sheet.freeze_panes(8, 2) + + # out of bounds + comp_sheet.set_column(0, 0, 4, oob_format) + comp_sheet.set_column(max_width + 2, max_width + 20, 18, oob_format) + for i in range(9): + comp_sheet.set_row(i, None, oob_format) + for i in range(8 + max_len, max_len + 50): + comp_sheet.set_row(i, None, oob_format) + + # Column widths for tallies, set up to 15th col to ensure title format correct + comp_sheet.set_column(1, 14, 20) + comp_sheet.set_column(1, max_width + 2, 20) + + # Row Heights + comp_sheet.set_row(7, 31) + #comp_sheet.set_row(8, 73.25) + + # Legend + comp_sheet.merge_range("N3:O3", "LEGEND", merge_format) + comp_sheet.write("N4", "", red_cell_format) + comp_sheet.write("O4", ">|20|%", legend_text_format) + comp_sheet.write("N5", "", orange_cell_format) + comp_sheet.write("O5", "|20|%≤|10|%", legend_text_format) + comp_sheet.write("N6", "", yellow_cell_format) + comp_sheet.write("O6", "|10|%≤|5|%", legend_text_format) + comp_sheet.write("N7", "", green_cell_format) + comp_sheet.write("O7", "<|5|%", legend_text_format) + + comp_sheet.conditional_format( + 10, + 2, + 8 + max_len, + max_width + 1, + {"type": "blanks", "format": oob_format}, + ) + comp_sheet.conditional_format( + 10, + 2, + 8 + max_len, + max_width + 1, + {"type": "blanks", "format": plain_format}, + ) + comp_sheet.conditional_format( + 10, + 2, + 8 + max_len, + max_width + 1, + { + "type": "text", + "criteria": "containing", + "value": "Not Available", + "format": not_avail_format, + }, + ) + comp_sheet.conditional_format( + 10, + 2, + 8 + max_len, + max_width + 1, + { + "type": "text", + "criteria": "containing", + "value": "Target = 0", + "format": target_ref_format, + }, + ) + comp_sheet.conditional_format( + 10, + 2, + 8 + max_len, + max_width + 1, + { + "type": "text", + "criteria": "containing", + "value": "Reference = 0", + "format": target_ref_format, + }, + ) + comp_sheet.conditional_format( + 10, + 2, + 8 + max_len, + max_width + 1, + { + "type": "text", + "criteria": "containing", + "value": "Identical", + "format": identical_format, + }, + ) + comp_sheet.conditional_format( + 10, + 2, + 8 + max_len, + max_width + 1, + { + "type": "cell", + "criteria": "greater than", + "value": 0.2, + "format": red_cell_format, + }, + ) + comp_sheet.conditional_format( + 10, + 2, + 8 + max_len, + max_width + 1, + { + "type": "cell", + "criteria": "between", + "minimum": 0.1, + "maximum": 0.2, + "format": orange_cell_format, + }, + ) + comp_sheet.conditional_format( + 10, + 2, + 8 + max_len, + max_width + 1, + { + "type": "cell", + "criteria": "between", + "minimum": 0.05, + "maximum": 0.1, + "format": yellow_cell_format, + }, + ) + comp_sheet.conditional_format( + 10, + 2, + 8 + max_len, + max_width + 1, + { + "type": "cell", + "criteria": "less than", + "value": -0.2, + "format": red_cell_format, + }, + ) + comp_sheet.conditional_format( + 10, + 2, + 8 + max_len, + max_width + 1, + { + "type": "cell", + "criteria": "between", + "minimum": -0.5, + "maximum": -0.1, + "format": orange_cell_format, + }, + ) + comp_sheet.conditional_format( + 10, + 2, + 8 + max_len, + max_width + 1, + { + "type": "cell", + "criteria": "between", + "minimum": -0.1, + "maximum": -0.05, + "format": yellow_cell_format, + }, + ) + comp_sheet.conditional_format( + 10, + 2, + 8 + max_len, + max_width + 1, + { + "type": "cell", + "criteria": "between", + "minimum": -0.05, + "maximum": 0.05, + "format": green_cell_format, + }, + ) + # ABSOLUTE DIFFERENCE + # Title + absdiff_sheet.merge_range("B1:C2", "LIBRARY", subtitle_merge_format) + absdiff_sheet.merge_range("D1:D2", lib_to_comp, subtitle_merge_format) + absdiff_sheet.merge_range( + "B3:L8", "{} RESULTS RECAP: COMPARISON (Absolute Difference)".format(testname), title_merge_format + ) + for tal in range(len(df_positions)): + absdiff_sheet.merge_range(df_positions[tal][0], + df_positions[tal][1] + 1, + df_positions[tal][0], + df_positions[tal][1] + 4, + list(comps.values())[tal]["title"], + subtitle_merge_format) + #absdiff_sheet.merge_range("B8:C8", "ZAID", subtitle_merge_format) + #absdiff_sheet.merge_range("D8:L8", "TALLY", subtitle_merge_format) + + # Freeze title + absdiff_sheet.freeze_panes(8, 2) + + # out of bounds + absdiff_sheet.set_column(0, 0, 4, oob_format) + absdiff_sheet.set_column(max_width + 2, max_width + 20, 18, oob_format) + for i in range(9): + absdiff_sheet.set_row(i, None, oob_format) + for i in range(8 + max_len, max_len + 50): + absdiff_sheet.set_row(i, None, oob_format) + + + # Column widths for errors, set up to 15th col by default to ensure title format correct + absdiff_sheet.set_column(1, 14, 20) + absdiff_sheet.set_column(1, max_width + 2, 20) + + # Row Heights + absdiff_sheet.set_row(7, 31) + #absdiff_sheet.set_row(8, 73.25) + + # Legend + absdiff_sheet.merge_range("N3:O3", "LEGEND", merge_format) + absdiff_sheet.merge_range("N8:O8", "According to MCNP manual", oob_format) + absdiff_sheet.write("N4", "", red_cell_format) + absdiff_sheet.write("O4", "> 50%", legend_text_format) + absdiff_sheet.write("N5", "", orange_cell_format) + absdiff_sheet.write("O5", "20% ≤ 50%", legend_text_format) + absdiff_sheet.write("N6", "", yellow_cell_format) + absdiff_sheet.write("O6", "10% ≤ 20%", legend_text_format) + absdiff_sheet.write("N7", "", green_cell_format) + absdiff_sheet.write("O7", "< 10%", legend_text_format) + + # Conditional Formatting + absdiff_sheet.conditional_format( + 10, + 1, + 8 + max_len, + max_width + 1, + {"type": "blanks", "format": oob_format}, + ) + # STANDARD DEVIATIONS + + # Title Format + std_dev_sheet.merge_range("B1:C2", "LIBRARY", subtitle_merge_format) + std_dev_sheet.merge_range("D1:D2", lib_to_comp, subtitle_merge_format) + std_dev_sheet.merge_range( + "B3:L8", "{} RESULTS RECAP: COMPARISON (Standard deviations from reference library)".format(testname), title_merge_format + ) + for tal in range(len(df_positions)): + std_dev_sheet.merge_range(df_positions[tal][0], + df_positions[tal][1] + 1, + df_positions[tal][0], + df_positions[tal][1] + 4, + list(comps.values())[tal]["title"], + subtitle_merge_format) + #std_dev_sheet.merge_range("B8:C8", "ZAID", subtitle_merge_format) + #std_dev_sheet.merge_range("D8:L8", "TALLY", subtitle_merge_format) + + # Freeze title + std_dev_sheet.freeze_panes(8, 2) + + # out of bounds + std_dev_sheet.set_column(0, 0, 4, oob_format) + std_dev_sheet.set_column(max_width + 2, max_width + 20, 18, oob_format) + for i in range(9): + std_dev_sheet.set_row(i, None, oob_format) + for i in range(8 + max_len, max_len + 50): + std_dev_sheet.set_row(i, None, oob_format) + + # Column widths for tallies, set up to 15th col to ensure title format correct + std_dev_sheet.set_column(1, 14, 20) + std_dev_sheet.set_column(1, max_width + 2, 20) + + # Row Heights + std_dev_sheet.set_row(7, 31) + #std_dev_sheet.set_row(8, 73.25) + + # Legend + std_dev_sheet.merge_range("N3:O3", "LEGEND", merge_format) + std_dev_sheet.write("N4", "", red_cell_format) + std_dev_sheet.write("O4", ">|3|%", legend_text_format) + std_dev_sheet.write("N5", "", orange_cell_format) + std_dev_sheet.write("O5", "|2|%≤|3|%", legend_text_format) + std_dev_sheet.write("N6", "", yellow_cell_format) + std_dev_sheet.write("O6", "|1|%≤|2|%", legend_text_format) + std_dev_sheet.write("N7", "", green_cell_format) + std_dev_sheet.write("O7", "<|1|%", legend_text_format) + + std_dev_sheet.conditional_format( + 10, + 1, + 8 + max_len, + max_width + 1, + {"type": "blanks", "format": oob_format}, + ) + std_dev_sheet.conditional_format( + 10, + 2, + 8 + max_len, + max_width + 1, + {"type": "blanks", "format": plain_format}, + ) + std_dev_sheet.conditional_format( + 10, + 2, + 8 + max_len, + max_width + 1, + { + "type": "text", + "criteria": "containing", + "value": "Not Available", + "format": not_avail_format, + }, + ) + std_dev_sheet.conditional_format( + 10, + 2, + 8 + max_len, + max_width + 1, + { + "type": "text", + "criteria": "containing", + "value": "Target = 0", + "format": target_ref_format, + }, + ) + std_dev_sheet.conditional_format( + 10, + 2, + 8 + max_len, + max_width + 1, + { + "type": "text", + "criteria": "containing", + "value": "Reference = 0", + "format": target_ref_format, + }, + ) + std_dev_sheet.conditional_format( + 10, + 2, + 8 + max_len, + max_width + 1, + { + "type": "text", + "criteria": "containing", + "value": "Identical", + "format": identical_format, + }, + ) + std_dev_sheet.conditional_format( + 10, + 2, + 8 + max_len, + max_width + 1, + { + "type": "cell", + "criteria": "greater than", + "value": 3, + "format": red_cell_format, + }, + ) + std_dev_sheet.conditional_format( + 10, + 2, + 8 + max_len, + max_width + 1, + { + "type": "cell", + "criteria": "between", + "minimum": 2, + "maximum": 3, + "format": orange_cell_format, + }, + ) + std_dev_sheet.conditional_format( + 10, + 2, + 8 + max_len, + max_width + 1, + { + "type": "cell", + "criteria": "between", + "minimum": 1, + "maximum": 2, + "format": yellow_cell_format, + }, + ) + std_dev_sheet.conditional_format( + 10, + 2, + 8 + max_len, + max_width + 1, + { + "type": "cell", + "criteria": "less than", + "value": -3, + "format": red_cell_format, + }, + ) + std_dev_sheet.conditional_format( + 10, + 2, + 8 + max_len, + max_width + 1, + { + "type": "cell", + "criteria": "between", + "minimum": -3, + "maximum": -2, + "format": orange_cell_format, + }, + ) + std_dev_sheet.conditional_format( + 10, + 2, + 8 + max_len, + max_width + 1, + { + "type": "cell", + "criteria": "between", + "minimum": -2, + "maximum": -1, + "format": yellow_cell_format, + }, + ) + std_dev_sheet.conditional_format( + 10, + 2, + 8 + max_len, + max_width + 1, + { + "type": "cell", + "criteria": "between", + "minimum": -1, + "maximum": 1, + "format": green_cell_format, + }, + ) + wb.close() \ No newline at end of file diff --git a/jade/expoutput.py b/jade/expoutput.py index bf14f6cf..d594e7be 100644 --- a/jade/expoutput.py +++ b/jade/expoutput.py @@ -81,7 +81,15 @@ def __init__(self, *args, **kwargs): self.path_exp_res = os.path.join(session.path_exp_res, testname) # Add the raw path data (not created because it is a comparison) - out = os.path.dirname(self.atlas_path_mcnp) + if self.mcnp: + out = os.path.dirname(self.atlas_path_mcnp) + elif self.d1s: + out = os.path.dirname(self.atlas_path_d1s) + elif self.serpent: + out = os.path.dirname(self.atlas_path_serpent) + elif self.openmc: + out = os.path.dirname(self.atlas_path_openmc) + raw_path = os.path.join(out, 'Raw_Data') if not os.path.exists(raw_path): os.mkdir(raw_path) @@ -147,7 +155,15 @@ def build_atlas(self): None. """ # Build a temporary folder for images - tmp_path = os.path.join(self.atlas_path_mcnp, 'tmp') + if self.mcnp: + tmp_path = os.path.join(self.atlas_path_mcnp, 'tmp') + elif self.d1s: + tmp_path = os.path.join(self.atlas_path_d1s, 'tmp') + elif self.openmc: + tmp_path = os.path.join(self.atlas_path_openmc, 'tmp') + elif self.serpent: + tmp_path = os.path.join(self.atlas_path_serpent, 'tmp') + os.mkdir(tmp_path) globalname = '' @@ -165,7 +181,10 @@ def build_atlas(self): # Save Atlas print(' Producing the PDF...') - atlas.save(self.atlas_path_mcnp) + if self.mcnp: + atlas.save(self.atlas_path_mcnp) + elif self.d1s: + atlas.save(self.atlas_path_d1s) # Remove tmp images shutil.rmtree(tmp_path) @@ -205,19 +224,34 @@ def _extract_outputs(self): if input not in inputs: inputs.append(input) if self.openmc: - print("Experimental comparison not impletmented \ + print("Experimental comparison not implemented \ for OpenMC") break if self.serpent: - print("Experimental comparison not impletmented \ + print("Experimental comparison not implemented \ for Serpent") break if self.d1s: - print("Experimental comparison not impletmented \ - for D1S") - break + results_path = os.path.join(test_path, + folder, "d1s") + pieces = folder.split('_') + # Get zaid + input = pieces[-1] + mfile, ofile = self._get_output_files(results_path) + # Parse output + output = MCNPoutput(mfile, ofile) + outputs[input, lib] = output + code_raw_data[input, lib] = output.tallydata + # self.raw_data[input, lib] = output.tallydata + + # Get the meaningful results + results[input, lib] = self._processMCNPdata(output) + if input not in inputs: + inputs.append(input) if self.mcnp: self.raw_data["mcnp"] = code_raw_data + if self.d1s: + self.raw_data["d1s"] = code_raw_data # Results are organized just by lib else: mfile, ofile = self._get_output_files(test_path) @@ -307,7 +341,8 @@ def _print_raw(self): if self.serpent: pass if self.d1s: - pass + raw_to_print = self.raw_data['d1s'].items() + for (folder, lib), item in raw_to_print: # Create the lib directory if it is not there cd_lib = os.path.join(self.raw_path, lib) @@ -451,7 +486,7 @@ def _pp_excel_comparison(self): ''' # Dump the global C/E table print(' Dump the C/E table in Excel...') - ex_outpath = os.path.join(self.excel_path_mcnp, 'C over E table.xlsx') + ex_outpath = os.path.join(self.excel_path_d1s, self.testname + '_CE_tables.xlsx') # Create a Pandas Excel writer using XlsxWriter as the engine. with pd.ExcelWriter(ex_outpath, engine='xlsxwriter') as writer: # --- build and dump the C/E table --- @@ -568,7 +603,7 @@ def _build_atlas(self, tmp_path, atlas): # There is the need to recover the tracked parents and daughters zaid_tracked = {} for lib in self.lib[1:]: - file = os.path.join(self.test_path[lib], folder, folder) + file = os.path.join(self.test_path[lib], folder, "d1s", folder) inp = D1S_Input.from_text(file) for tallynum in ['24', '14']: card = inp.get_card_byID('settings', 'FU' + tallynum) diff --git a/jade/gui.py b/jade/gui.py index 0ffe1161..fbcf3cdf 100644 --- a/jade/gui.py +++ b/jade/gui.py @@ -31,28 +31,37 @@ from jade.__version__ import __version__ from jade.status import EXP_TAG from tqdm import tqdm +from jade.main import Session -date = '10/05/2022' +date = "10/05/2022" version = __version__ -POWERED_BY = 'NIER, UNIBO, F4E, UKAEA' +POWERED_BY = "NIER, UNIBO, F4E, UKAEA" def clear_screen(): - if os.name == 'nt': - os.system('cls') + if os.name == "nt": + os.system("cls") else: - os.system('clear') + os.system("clear") -exit_text = '\nSession concluded normally \n' +exit_text = "\nSession concluded normally \n" -header = """ +header = ( + """ *********************************************** - Welcome to JADE """+version+""" + Welcome to JADE """ + + version + + """ A nuclear libraries V&V Test Suite - Release date: """+date+'\n' - -principal_menu = header+""" + Release date: """ + + date + + "\n" +) + +principal_menu = ( + header + + """ MAIN MENU Powered by {} @@ -79,7 +88,10 @@ def clear_screen(): ----------------------------------------------- * Exit (exit) -""".format(POWERED_BY) +""".format( + POWERED_BY + ) +) def mainloop(session): @@ -91,144 +103,164 @@ def mainloop(session): clear_screen() print(principal_menu) while True: - option = input(' Enter action: ') + option = input(" Enter action: ") - if option == 'comp': + if option == "comp": comploop(session) - elif option == 'exp': + elif option == "exp": exploop(session) - elif option == 'qual': + elif option == "qual": clear_screen() print(principal_menu) - print(' Currently not developed. Please select another option') + print(" Currently not developed. Please select another option") - elif option == 'post': + elif option == "post": pploop(session) - elif option == 'printlib': + elif option == "printlib": uty.print_libraries(session.lib_manager) - elif option == 'restore': + elif option == "restore": uty.restore_default_config(session) - elif option == 'trans': + elif option == "trans": newlib = session.lib_manager.select_lib() if newlib == "back": mainloop(session) if newlib == "exit": session.log.adjourn(exit_text) sys.exit() - inputfile = input(' MCNP input file: ') + inputfile = input(" MCNP input file: ") if newlib in session.lib_manager.libraries: ans = uty.translate_input(session, newlib, inputfile) if ans: - print(' Translation successfully completed!\n') - session.log.adjourn('file'+inputfile + - ' successfully translated to ' + newlib) + print(" Translation successfully completed!\n") + session.log.adjourn( + "file" + inputfile + " successfully translated to " + newlib + ) else: - print(''' + print( + """ Error: The file does not exist or can't be opened - ''') + """ + ) else: - print(''' + print( + """ Error: The selected library is not available. Check your available libraries using 'printlib' - ''') + """ + ) - elif option == 'printmat': - inputfile = input(' MCNP Input file of interest: ') + elif option == "printmat": + inputfile = input(" MCNP Input file of interest: ") ans = uty.print_material_info(session, inputfile) if ans: - print(' Material infos printed') + print(" Material infos printed") else: - print(''' + print( + """ Error: Either the input or output files do not exist or can't be opened - ''') + """ + ) - elif option == 'generate': - inputfile = uty.select_inputfile(' MCNP input file: ') + elif option == "generate": + inputfile = uty.select_inputfile(" MCNP input file: ") message = " Fraction type (either 'mass' or 'atom'): " - options = ['mass', 'atom'] + options = ["mass", "atom"] fraction_type = uty.input_with_options(message, options) - materials = input(' Source materials (e.g. m1-m10): ') - percentages = input(' Materials percentages (e.g. 0.1-0.9): ') + materials = input(" Source materials (e.g. m1-m10): ") + percentages = input(" Materials percentages (e.g. 0.1-0.9): ") lib = session.lib_manager.select_lib() if lib == "back": mainloop(session) if lib == "exit": session.log.adjourn(exit_text) sys.exit() - materials = materials.split('-') - percentages = percentages.split('-') + materials = materials.split("-") + percentages = percentages.split("-") if len(materials) == len(percentages): - ans = uty.generate_material(session, inputfile, - materials, percentages, lib, - fractiontype=fraction_type) + ans = uty.generate_material( + session, + inputfile, + materials, + percentages, + lib, + fractiontype=fraction_type, + ) if ans: - print(' Material generated') + print(" Material generated") else: - print(''' + print( + """ Error: Either the input or output files can't be opened - ''') + """ + ) else: - print(''' + print( + """ Error: The number of materials and percentages must be the same - ''') + """ + ) - elif option == 'switch': + elif option == "switch": # Select MCNP input - inputfile = uty.select_inputfile(' MCNP input file: ') + inputfile = uty.select_inputfile(" MCNP input file: ") # Select fraction type - options = ['mass', 'atom'] + options = ["mass", "atom"] message = " Fraction to switch to (either 'mass' or 'atom'): " fraction_type = uty.input_with_options(message, options) # Switch fraction ans = uty.switch_fractions(session, inputfile, fraction_type) if ans: - print(' Fractions have been switched') + print(" Fractions have been switched") else: - print(''' + print( + """ Error: - Either the input or output files can't be opened''') + Either the input or output files can't be opened""" + ) - elif option == 'acelib': + elif option == "acelib": uty.change_ACElib_suffix() - print('\n Suffix change was completed\n') + print("\n Suffix change was completed\n") - elif option == 'react': + elif option == "react": uty.get_reaction_file(session) - print('\n Reaction file has been dumped\n') + print("\n Reaction file has been dumped\n") - elif option == 'rmvruntpe': + elif option == "rmvruntpe": uty.clean_runtpe(session.path_run) - print('\n Runtpe files have been removed\n') + print("\n Runtpe files have been removed\n") - elif option == 'comparelib': + elif option == "comparelib": uty.print_XS_EXFOR(session) - elif option == 'exit': - session.log.adjourn('\nSession concluded normally \n') + elif option == "exit": + session.log.adjourn("\nSession concluded normally \n") sys.exit() else: clear_screen() print(principal_menu) - print(' Please enter a valid option!') + print(" Please enter a valid option!") -computational_menu = header+""" +computational_menu = ( + header + + """ COMPUTATIONAL BENCHMARK MENU Powered by {} @@ -239,10 +271,13 @@ def mainloop(session): * Continue assessment (continue) * Back to main menu (back) * Exit (exit) -""".format(POWERED_BY) +""".format( + POWERED_BY + ) +) -def comploop(session): +def comploop(session: Session): """ This handle the actions related to the computational benchmarck menu @@ -252,12 +287,12 @@ def comploop(session): clear_screen() print(computational_menu) while True: - option = input(' Enter action: ') + option = input(" Enter action: ") - if option == 'printlib': + if option == "printlib": uty.print_libraries(session.lib_manager) - elif option == 'assess': + elif option == "assess": # Select and check library lib = session.lib_manager.select_lib() if lib == "back": @@ -270,26 +305,31 @@ def comploop(session): comploop(session) if runoption == "exit": session.log.adjourn(exit_text) - sys.exit() + sys.exit() ans = session.state.check_override_run(lib, session) # If checks are ok perform assessment if ans: - # Logging - bartext = 'Computational benchmark execution started' + # Logging + bartext = "Computational benchmark execution started" session.log.bar_adjourn(bartext) - session.log.adjourn('Selected Library: '+lib, - spacing=False, time=True) - print(' ########################### COMPUTATIONAL BENCHMARKS EXECUTION ###########################\n') + session.log.adjourn( + "Selected Library: " + lib, spacing=False, time=True + ) + print( + " ########################### COMPUTATIONAL BENCHMARKS EXECUTION ###########################\n" + ) cmp.executeBenchmarksRoutines(session, lib, runoption) # Core function - print(' ####################### COMPUTATIONAL BENCHMARKS RUN ENDED ###############################\n') - t = 'Computational benchmark execution ended' + print( + " ####################### COMPUTATIONAL BENCHMARKS RUN ENDED ###############################\n" + ) + t = "Computational benchmark execution ended" session.log.bar_adjourn(t) else: clear_screen() print(computational_menu) - print(' Assessment cancelled.') + print(" Assessment cancelled.") - elif option == 'continue': + elif option == "continue": # Select and check library # Warning: this is done only for sphere test at the moment lib = session.lib_manager.select_lib() @@ -304,49 +344,55 @@ def comploop(session): unfinished = None if unfinished is None: - print(' The selected library was not assessed') + print(" The selected library was not assessed") elif len(unfinished) == 0: - print(' The assessment is already completed') + print(" The assessment is already completed") else: - print(' Completing sphere assessment:') - session.log.adjourn('Assessment of: '+lib+' started', - spacing=False, time=True) + print(" Completing sphere assessment:") + session.log.adjourn( + "Assessment of: " + lib + " started", spacing=False, time=True + ) flagOk = True for directory in tqdm(unfinished): path = os.path.join(motherdir, directory) - name = directory+'_' + name = directory + "_" - flag = testrun.Test._runMCNP('mcnp6', name, path, - cpu=session.conf.cpu) + flag = testrun.Test._runMCNP( + "mcnp6", name, path, cpu=session.conf.cpu + ) if flag: flagOk = False - session.log.adjourn(name + - ' reached timeout, eliminate folder') + session.log.adjourn(name + " reached timeout, eliminate folder") if not flagOk: - print(""" + print( + """ Some MCNP run reached timeout, they are listed in the log file. - Please remove their folders before attempting to postprocess the library""") + Please remove their folders before attempting to postprocess the library""" + ) - print(' Assessment completed') + print(" Assessment completed") - session.log.adjourn('Assessment of: '+lib+' completed', - spacing=True, time=True) + session.log.adjourn( + "Assessment of: " + lib + " completed", spacing=True, time=True + ) - elif option == 'back': + elif option == "back": mainloop(session) - elif option == 'exit': + elif option == "exit": session.log.adjourn(exit_text) sys.exit() else: clear_screen() print(computational_menu) - print(' Please enter a valid option!') + print(" Please enter a valid option!") -experimental_menu = header+""" +experimental_menu = ( + header + + """ EXPERIMENTAL BENCHMARK MENU Powered by {} @@ -357,7 +403,10 @@ def comploop(session): * Continue assessment (continue) * Back to main menu (back) * Exit (exit) -""".format(POWERED_BY) +""".format( + POWERED_BY + ) +) def exploop(session): @@ -370,12 +419,12 @@ def exploop(session): clear_screen() print(experimental_menu) while True: - option = input(' Enter action: ') + option = input(" Enter action: ") - if option == 'printlib': + if option == "printlib": uty.print_libraries(session.lib_manager) - elif option == 'assess': + elif option == "assess": # Update the configuration file session.conf.read_settings() # Select and check library @@ -392,53 +441,59 @@ def exploop(session): session.log.adjourn(exit_text) sys.exit() # it may happen that lib are two but only the first is the assessed - pieces = lib.split('-') + pieces = lib.split("-") if len(pieces) > 1: libtocheck = pieces[0] else: libtocheck = lib - ans = session.state.check_override_run(libtocheck, - session, exp=True) + ans = session.state.check_override_run(libtocheck, session, exp=True) # If checks are ok perform assessment if ans: # Logging runoption = session.conf.run_option(exp=True) - bartext = 'Experimental benchmark execution started' + bartext = "Experimental benchmark execution started" session.log.bar_adjourn(bartext) - session.log.adjourn('Selected Library: '+lib, - spacing=False, time=True) - print(' ########################### EXPERIMENTAL BENCHMARKS EXECUTION ###########################\n') + session.log.adjourn( + "Selected Library: " + lib, spacing=False, time=True + ) + print( + " ########################### EXPERIMENTAL BENCHMARKS EXECUTION ###########################\n" + ) # Core function cmp.executeBenchmarksRoutines(session, lib, runoption, exp=True) - print(' ####################### EXPERIMENTAL BENCHMARKS RUN ENDED ###############################\n') - t = 'Experimental benchmark execution ended' + print( + " ####################### EXPERIMENTAL BENCHMARKS RUN ENDED ###############################\n" + ) + t = "Experimental benchmark execution ended" session.log.bar_adjourn(t) else: clear_screen() print(computational_menu) - print(' Assessment canceled.') + print(" Assessment canceled.") - elif option == 'continue': + elif option == "continue": # Update the configuration file session.conf.read_settings() clear_screen() print(principal_menu) - print(' Currently not developed. Please select another option') + print(" Currently not developed. Please select another option") - elif option == 'back': + elif option == "back": mainloop(session) - elif option == 'exit': + elif option == "exit": session.log.adjourn(exit_text) sys.exit() else: clear_screen() print(computational_menu) - print(' Please enter a valid option!') + print(" Please enter a valid option!") -pp_menu = header+""" +pp_menu = ( + header + + """ POST PROCESSING MENU Powered by {} @@ -450,7 +505,10 @@ def exploop(session): * Compare Vs Experiments (compexp) * Back to main menu (back) * Exit (exit) -""".format(POWERED_BY) +""".format( + POWERED_BY + ) +) def pploop(session): @@ -463,13 +521,13 @@ def pploop(session): clear_screen() print(pp_menu) while True: - option = input(' Enter action: ') + option = input(" Enter action: ") - if option == 'printlib': + if option == "printlib": lib_tested = list(session.state.run_tree.keys()) print(lib_tested) - elif option == 'pp': + elif option == "pp": # Update the configuration file session.conf.read_settings() # Select and check library @@ -482,20 +540,22 @@ def pploop(session): if ans: lib = to_single_pp[0] # Check active tests - #to_perform = session.check_active_tests('Post-Processing') + # to_perform = session.check_active_tests('Post-Processing') # For the moment no pp is foreseen for experimental benchmarks # to_perf_exp = session.check_active_tests('Post-Processing', # exp=True) # to_perform.extend(to_perf_exp) # Logging - bartext = 'Post-Processing started' + bartext = "Post-Processing started" session.log.bar_adjourn(bartext) - session.log.adjourn('Selected Library: '+lib, spacing=False) - print('\n ########################### POST-PROCESSING STARTED ###########################\n') + session.log.adjourn("Selected Library: " + lib, spacing=False) + print( + "\n ########################### POST-PROCESSING STARTED ###########################\n" + ) # Core function - pp.postprocessBenchmark(session, lib) - #for testname in to_perform: + pp.postprocessBenchmark(session, lib) + # for testname in to_perform: # try: # pp.postprocessBenchmark(session, lib, testname) # except PermissionError as e: @@ -504,11 +564,13 @@ def pploop(session): # print(' '+str(e)) # print(' Please close all excel/word files and retry') # continue - print('\n ######################### POST-PROCESSING ENDED ###############################\n') - t = 'Post-Processing completed' + print( + "\n ######################### POST-PROCESSING ENDED ###############################\n" + ) + t = "Post-Processing completed" session.log.bar_adjourn(t, spacing=False) - elif option == 'compare': + elif option == "compare": # Update the configuration file session.conf.read_settings() @@ -517,30 +579,36 @@ def pploop(session): if ans: # Logging - bartext = 'Comparison Post-Processing started' + bartext = "Comparison Post-Processing started" session.log.bar_adjourn(bartext) - session.log.adjourn('Selected Library: '+lib_input, - spacing=True) - print('\n ########################### COMPARISON STARTED ###########################\n') + session.log.adjourn("Selected Library: " + lib_input, spacing=True) + print( + "\n ########################### COMPARISON STARTED ###########################\n" + ) # Check active tests - to_perform = session.check_active_tests('Post-Processing') + to_perform = session.check_active_tests("Post-Processing") # Execute single pp for lib in to_single_pp: - print('to single pp', to_single_pp) + print("to single pp", to_single_pp) for testname in to_perform: - print("to_perform",to_perform) + print("to_perform", to_perform) try: - print(' Single PP of library '+lib+' required') + print(" Single PP of library " + lib + " required") pp.postprocessBenchmark(session, lib) - session.log.adjourn(""" -Additional Post-Processing of library:"""+lib+' completed\n', spacing=False) + session.log.adjourn( + """ +Additional Post-Processing of library:""" + + lib + + " completed\n", + spacing=False, + ) except PermissionError as e: clear_screen() print(pp_menu) - print(' '+str(e)) - print(' Please close all excel/word files and retry') + print(" " + str(e)) + print(" Please close all excel/word files and retry") continue # Execute Comparison @@ -550,72 +618,78 @@ def pploop(session): except PermissionError as e: clear_screen() print(pp_menu) - print(' '+str(e)) - print(' Please close all excel/word files and retry') + print(" " + str(e)) + print(" Please close all excel/word files and retry") continue - print('\n ######################### COMPARISON ENDED ###############################\n') - t = 'Post-Processing completed' + print( + "\n ######################### COMPARISON ENDED ###############################\n" + ) + t = "Post-Processing completed" session.log.bar_adjourn(t, spacing=False) - elif option == 'compexp': + elif option == "compexp": # Update the configuration file session.conf.read_settings() # Select and check library - ans, to_single_pp, lib_input = session.state.check_override_pp(session, exp=True) + ans, to_single_pp, lib_input = session.state.check_override_pp( + session, exp=True + ) if ans: # Logging - bartext = 'Comparison Post-Processing started' + bartext = "Comparison Post-Processing started" session.log.bar_adjourn(bartext) - session.log.adjourn('Selected Library: '+lib_input, - spacing=True) - print('\n ########################### COMPARISON STARTED ###########################\n') + session.log.adjourn("Selected Library: " + lib_input, spacing=True) + print( + "\n ########################### COMPARISON STARTED ###########################\n" + ) # Check active tests - to_perform = session.check_active_tests('Post-Processing', - exp=True) - -# # Execut single pp -# for lib in to_single_pp: -# for testname in to_perform: -# try: -# print(' Single PP of library '+lib+' required') -# pp.postprocessBenchmark(session, lib, testname) -# session.log.adjourn(""" -# Additional Post-Processing of library:"""+lib+' completed\n', spacing=False) -# except PermissionError as e: -# clear_screen() -# print(pp_menu) -# print(' '+str(e)) -# print(' Please close all excel/word files and retry') -# continue + to_perform = session.check_active_tests("Post-Processing", exp=True) + + # # Execut single pp + # for lib in to_single_pp: + # for testname in to_perform: + # try: + # print(' Single PP of library '+lib+' required') + # pp.postprocessBenchmark(session, lib, testname) + # session.log.adjourn(""" + # Additional Post-Processing of library:"""+lib+' completed\n', spacing=False) + # except PermissionError as e: + # clear_screen() + # print(pp_menu) + # print(' '+str(e)) + # print(' Please close all excel/word files and retry') + # continue # Execute Comparison - lib_input = EXP_TAG+'-'+lib_input # Insert the exp tag + lib_input = EXP_TAG + "-" + lib_input # Insert the exp tag for testname in to_perform: try: - pp.compareBenchmark(session, lib_input, testname, exp = True) + pp.compareBenchmark(session, lib_input, testname, exp=True) except PermissionError as e: clear_screen() print(pp_menu) - print(' '+str(e)) - print(' Please close all excel/word files and retry') + print(" " + str(e)) + print(" Please close all excel/word files and retry") continue - print('\n ######################### COMPARISON ENDED ###############################\n') - t = 'Post-Processing completed' + print( + "\n ######################### COMPARISON ENDED ###############################\n" + ) + t = "Post-Processing completed" session.log.bar_adjourn(t, spacing=False) - elif option == 'back': + elif option == "back": mainloop(session) - elif option == 'exit': + elif option == "exit": session.log.adjourn(exit_text) sys.exit() else: clear_screen() print(pp_menu) - print(' Please enter a valid option!') + print(" Please enter a valid option!") diff --git a/jade/inputfile.py b/jade/inputfile.py index 9b784b75..68c0dec7 100644 --- a/jade/inputfile.py +++ b/jade/inputfile.py @@ -233,7 +233,6 @@ def update_zaidinfo(self, lib_manager): self.matlist.update_info(lib_manager) -# def add_stopCard(self, nps, ctme, precision): def add_stopCard(self, nps): """ Add STOP card @@ -242,10 +241,6 @@ def add_stopCard(self, nps): ---------- nps : int number of particles to simulate. - ctme : int - copmuter time. - precision : (str, float) - tally number, precision. Returns ------- @@ -259,21 +254,9 @@ def add_stopCard(self, nps): line = line+'NPS '+str(int(nps))+' ' except ValueError: pass # an escaped NaN - """ - if ctme is not None: - try: - line = line+'CTME '+str(int(ctme))+' ' - except ValueError: - pass # an escaped NaN - - if precision is not None: - tally = precision[0] - error = precision[1] - line = line+str(tally)+' '+str(error) - """ if line == 'STOP ': raise ValueError(""" -Specify at least one among nps, ctme or precision""") +Specify an nps for the simulation""") line = line+'\n' @@ -676,32 +659,21 @@ def add_track_contribution(self, tallyID, zaids, who='parent'): class D1S5_InputFile(D1S_Input): - def add_stopCard(self, nps, ctme, precision): + def add_stopCard(self, nps): """ STOP card is not supported in MCNP 5. This simply is translated to a - nps card. Warnings are prompt to the user if ctme or precision are - specified. + nps card. Parameters ---------- nps : int number of particles to simulate - ctme = int - computer time - precision = (str, float) - tuple indicating the tally number and the precision requested Returns ------- None. """ - if ctme is not None or precision is not None: - if self.name != 'SphereSDDR': - warnings.warn(''' -STOP card is substituted with normal NPS card for MCNP5. -specified ctme or precision parameters will be ignored -''') if nps is None: raise ValueError(' NPS value is mandatory for MCNP 5 inputs') @@ -709,7 +681,6 @@ def add_stopCard(self, nps, ctme, precision): card = par.Card([line], 5, -1) self.cards['settings'].append(card) - @contextmanager def suppress_stdout(): with open(os.devnull, "w") as devnull: @@ -724,7 +695,7 @@ def suppress_stdout(): def check_transport_activation(lib): # Operate on the newlib, should arrive in the 99c-31c format errmsg = """ - Please define the pair activation-transport lib for the FNG benchmark + Please define the pair activation-transport lib for SDDR benchmarks (e.g. 99c-31c). See additional details on the documentation. """ try: diff --git a/jade/install_files/Benchmarks_Inputs/ITER_Cyl_SDDR/mcnp/ITER_Cyl_SDDR.i b/jade/install_files/Benchmarks_Inputs/ITER_Cyl_SDDR/d1s/ITER_Cyl_SDDR.i similarity index 100% rename from jade/install_files/Benchmarks_Inputs/ITER_Cyl_SDDR/mcnp/ITER_Cyl_SDDR.i rename to jade/install_files/Benchmarks_Inputs/ITER_Cyl_SDDR/d1s/ITER_Cyl_SDDR.i diff --git a/jade/install_files/Benchmarks_Inputs/ITER_Cyl_SDDR/d1S/ITER_Cyl_SDDR/ITER_Cyl_SDDR_irrad b/jade/install_files/Benchmarks_Inputs/ITER_Cyl_SDDR/d1s/ITER_Cyl_SDDR_irrad similarity index 100% rename from jade/install_files/Benchmarks_Inputs/ITER_Cyl_SDDR/d1S/ITER_Cyl_SDDR/ITER_Cyl_SDDR_irrad rename to jade/install_files/Benchmarks_Inputs/ITER_Cyl_SDDR/d1s/ITER_Cyl_SDDR_irrad diff --git a/jade/install_files/Benchmarks_Inputs/ITER_Cyl_SDDR/d1S/ITER_Cyl_SDDR/ITER_Cyl_SDDR_react b/jade/install_files/Benchmarks_Inputs/ITER_Cyl_SDDR/d1s/ITER_Cyl_SDDR_react similarity index 100% rename from jade/install_files/Benchmarks_Inputs/ITER_Cyl_SDDR/d1S/ITER_Cyl_SDDR/ITER_Cyl_SDDR_react rename to jade/install_files/Benchmarks_Inputs/ITER_Cyl_SDDR/d1s/ITER_Cyl_SDDR_react diff --git a/jade/install_files/Benchmarks_Inputs/ITER_Cyl_SDDR/openmc/geometry.xml b/jade/install_files/Benchmarks_Inputs/ITER_Cyl_SDDR/openmc/geometry.xml deleted file mode 100644 index aee3bc6b..00000000 --- a/jade/install_files/Benchmarks_Inputs/ITER_Cyl_SDDR/openmc/geometry.xml +++ /dev/null @@ -1,219 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/jade/install_files/Benchmarks_Inputs/ITER_Cyl_SDDR/openmc/materials.xml b/jade/install_files/Benchmarks_Inputs/ITER_Cyl_SDDR/openmc/materials.xml deleted file mode 100644 index 96d9f9f9..00000000 --- a/jade/install_files/Benchmarks_Inputs/ITER_Cyl_SDDR/openmc/materials.xml +++ /dev/null @@ -1,158 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/jade/install_files/Benchmarks_Inputs/ITER_Cyl_SDDR/serpent/ITER_Cyl_SDDR.i b/jade/install_files/Benchmarks_Inputs/ITER_Cyl_SDDR/serpent/ITER_Cyl_SDDR.i deleted file mode 100644 index aad839d1..00000000 --- a/jade/install_files/Benchmarks_Inputs/ITER_Cyl_SDDR/serpent/ITER_Cyl_SDDR.i +++ /dev/null @@ -1,374 +0,0 @@ -% --- surface definitions --- % -surf 1 cylz 0.0 0.0 7.5 -surf 2 cylz 0.0 0.0 48.0 -surf 3 cylz 0.0 0.0 50.0 -surf 4 cylz 0.0 0.0 100.0 -surf 101 cylz 0.0 0.0 12.0 -surf 102 cylz 0.0 0.0 42.0 -surf 103 cylz 0.0 0.0 56.0 -surf 104 cylz 0.0 0.0 94.0 -surf 10 cylz 0.0 0.0 15.0 -surf 11 cylz 0.0 0.0 30.0 -surf 12 cylz 0.0 0.0 45.0 -surf 13 cylz 0.0 0.0 60.0 -surf 20 pz -110.0 -surf 21 pz -100.0 -surf 22 pz 0.0 -surf 23 pz 210.0 -surf 24 pz 535.0 -surf 25 pz 550.0 -surf 26 pz 580.0 -surf 27 pz 590.0 -surf 201 pz 20.0 -surf 202 pz 40.0 -surf 203 pz 60.0 -surf 204 pz 80.0 -surf 205 pz 100.0 -surf 206 pz 120.0 -surf 207 pz 140.0 -surf 208 pz 160.0 -surf 209 pz 180.0 -surf 210 pz 200.0 -surf 211 pz 220.0 -surf 212 pz 240.0 -surf 213 pz 260.0 -surf 214 pz 280.0 -surf 215 pz 300.0 -surf 216 pz 320.0 -surf 217 pz 340.0 -surf 218 pz 360.0 -surf 219 pz 380.0 -surf 220 pz 400.0 -surf 221 pz 420.0 -surf 222 pz 440.0 -surf 223 pz 460.0 -surf 224 pz 480.0 -surf 225 pz 500.0 -surf 226 pz 520.0 -surf 227 pz 540.0 -surf 228 pz 545.0 -surf 229 pz 547.0 -surf 230 pz 549.0 -% --- cell definitions --- % -cell 1100 0 2 ( 3 -103 22 -201 ) -cell 1101 0 2 ( 3 -103 201 -202 ) -cell 1102 0 2 ( 3 -103 202 -203 ) -cell 1103 0 2 ( 3 -103 203 -204 ) -cell 1104 0 2 ( 3 -103 204 -205 ) -cell 1105 0 2 ( 3 -103 205 -206 ) -cell 1106 0 2 ( 3 -103 206 -207 ) -cell 1107 0 2 ( 3 -103 207 -208 ) -cell 1108 0 2 ( 3 -103 208 -209 ) -cell 1109 0 2 ( 3 -103 209 -210 ) -cell 1110 0 2 ( 3 -103 210 -211 ) -cell 1111 0 2 ( 3 -103 211 -212 ) -cell 1112 0 2 ( 3 -103 212 -213 ) -cell 1113 0 2 ( 3 -103 213 -214 ) -cell 1114 0 2 ( 3 -103 214 -215 ) -cell 1115 0 2 ( 3 -103 215 -216 ) -cell 1116 0 2 ( 3 -103 216 -217 ) -cell 1117 0 2 ( 3 -103 217 -218 ) -cell 1118 0 2 ( 3 -103 218 -219 ) -cell 1119 0 2 ( 3 -103 219 -220 ) -cell 1120 0 2 ( 3 -103 220 -221 ) -cell 1121 0 2 ( 3 -103 221 -222 ) -cell 1122 0 2 ( 3 -103 222 -223 ) -cell 1123 0 2 ( 3 -103 223 -224 ) -cell 1124 0 2 ( 3 -103 224 -225 ) -cell 1125 0 2 ( 3 -103 225 -226 ) -cell 1126 0 2 ( 3 -103 226 -24 ) -cell 1127 0 2 ( 3 -103 24 -227 ) -cell 1128 0 2 ( 3 -103 227 -228 ) -cell 1129 0 2 ( 3 -103 228 -229 ) -cell 1130 0 2 ( 3 -103 229 -230 ) -cell 1131 0 2 ( 3 -103 230 -25 ) -cell 1200 0 2 ( 103 -104 22 -201 ) -cell 1201 0 2 ( 103 -104 201 -202 ) -cell 1202 0 2 ( 103 -104 202 -203 ) -cell 1203 0 2 ( 103 -104 203 -204 ) -cell 1204 0 2 ( 103 -104 204 -205 ) -cell 1205 0 2 ( 103 -104 205 -206 ) -cell 1206 0 2 ( 103 -104 206 -207 ) -cell 1207 0 2 ( 103 -104 207 -208 ) -cell 1208 0 2 ( 103 -104 208 -209 ) -cell 1209 0 2 ( 103 -104 209 -210 ) -cell 1210 0 2 ( 103 -104 210 -211 ) -cell 1211 0 2 ( 103 -104 211 -212 ) -cell 1212 0 2 ( 103 -104 212 -213 ) -cell 1213 0 2 ( 103 -104 213 -214 ) -cell 1214 0 2 ( 103 -104 214 -215 ) -cell 1215 0 2 ( 103 -104 215 -216 ) -cell 1216 0 2 ( 103 -104 216 -217 ) -cell 1217 0 2 ( 103 -104 217 -218 ) -cell 1218 0 2 ( 103 -104 218 -219 ) -cell 1219 0 2 ( 103 -104 219 -220 ) -cell 1220 0 2 ( 103 -104 220 -221 ) -cell 1221 0 2 ( 103 -104 221 -222 ) -cell 1222 0 2 ( 103 -104 222 -223 ) -cell 1223 0 2 ( 103 -104 223 -224 ) -cell 1224 0 2 ( 103 -104 224 -225 ) -cell 1225 0 2 ( 103 -104 225 -226 ) -cell 1226 0 2 ( 103 -104 226 -24 ) -cell 1227 0 2 ( 103 -104 24 -227 ) -cell 1228 0 2 ( 103 -104 227 -228 ) -cell 1229 0 2 ( 103 -104 228 -229 ) -cell 1230 0 2 ( 103 -104 229 -230 ) -cell 1231 0 2 ( 103 -104 230 -25 ) -cell 1300 0 2 ( 104 -4 22 -201 ) -cell 1301 0 2 ( 104 -4 201 -202 ) -cell 1302 0 2 ( 104 -4 202 -203 ) -cell 1303 0 2 ( 104 -4 203 -204 ) -cell 1304 0 2 ( 104 -4 204 -205 ) -cell 1305 0 2 ( 104 -4 205 -206 ) -cell 1306 0 2 ( 104 -4 206 -207 ) -cell 1307 0 2 ( 104 -4 207 -208 ) -cell 1308 0 2 ( 104 -4 208 -209 ) -cell 1309 0 2 ( 104 -4 209 -210 ) -cell 1310 0 2 ( 104 -4 210 -211 ) -cell 1311 0 2 ( 104 -4 211 -212 ) -cell 1312 0 2 ( 104 -4 212 -213 ) -cell 1313 0 2 ( 104 -4 213 -214 ) -cell 1314 0 2 ( 104 -4 214 -215 ) -cell 1315 0 2 ( 104 -4 215 -216 ) -cell 1316 0 2 ( 104 -4 216 -217 ) -cell 1317 0 2 ( 104 -4 217 -218 ) -cell 1318 0 2 ( 104 -4 218 -219 ) -cell 1319 0 2 ( 104 -4 219 -220 ) -cell 1320 0 2 ( 104 -4 220 -221 ) -cell 1321 0 2 ( 104 -4 221 -222 ) -cell 1322 0 2 ( 104 -4 222 -223 ) -cell 1323 0 2 ( 104 -4 223 -224 ) -cell 1324 0 2 ( 104 -4 224 -225 ) -cell 1325 0 2 ( 104 -4 225 -226 ) -cell 1326 0 2 ( 104 -4 226 -24 ) -cell 1327 0 2 ( 104 -4 24 -227 ) -cell 1328 0 2 ( 104 -4 227 -228 ) -cell 1329 0 2 ( 104 -4 228 -229 ) -cell 1330 0 2 ( 104 -4 229 -230 ) -cell 1331 0 2 ( 104 -4 230 -25 ) -cell 2100 0 1 ( 1 -101 22 -201 ) -cell 2101 0 1 ( 1 -101 201 -202 ) -cell 2102 0 1 ( 1 -101 202 -203 ) -cell 2103 0 1 ( 1 -101 203 -204 ) -cell 2104 0 1 ( 1 -101 204 -205 ) -cell 2105 0 1 ( 1 -101 205 -206 ) -cell 2106 0 1 ( 1 -101 206 -207 ) -cell 2107 0 1 ( 1 -101 207 -208 ) -cell 2108 0 1 ( 1 -101 208 -209 ) -cell 2109 0 1 ( 1 -101 209 -210 ) -cell 2110 0 1 ( 1 -101 210 -23 ) -cell 2200 0 1 ( 101 -102 22 -201 ) -cell 2201 0 1 ( 101 -102 201 -202 ) -cell 2202 0 1 ( 101 -102 202 -203 ) -cell 2203 0 1 ( 101 -102 203 -204 ) -cell 2204 0 1 ( 101 -102 204 -205 ) -cell 2205 0 1 ( 101 -102 205 -206 ) -cell 2206 0 1 ( 101 -102 206 -207 ) -cell 2207 0 1 ( 101 -102 207 -208 ) -cell 2208 0 1 ( 101 -102 208 -209 ) -cell 2209 0 1 ( 101 -102 209 -210 ) -cell 2210 0 1 ( 101 -102 210 -23 ) -cell 2300 0 1 ( 102 -2 22 -201 ) -cell 2301 0 1 ( 102 -2 201 -202 ) -cell 2302 0 1 ( 102 -2 202 -203 ) -cell 2303 0 1 ( 102 -2 203 -204 ) -cell 2304 0 1 ( 102 -2 204 -205 ) -cell 2305 0 1 ( 102 -2 205 -206 ) -cell 2306 0 1 ( 102 -2 206 -207 ) -cell 2307 0 1 ( 102 -2 207 -208 ) -cell 2308 0 1 ( 102 -2 208 -209 ) -cell 2309 0 1 ( 102 -2 209 -210 ) -cell 2310 0 1 ( 102 -2 210 -23 ) -cell 3100 0 2 ( -1 24 -227 ) -cell 3101 0 2 ( -1 227 -228 ) -cell 3102 0 2 ( -1 228 -229 ) -cell 3103 0 2 ( -1 229 -230 ) -cell 3104 0 2 ( -1 230 -25 ) -cell 3200 0 2 ( 1 -10 24 -227 ) -cell 3201 0 2 ( 1 -10 227 -228 ) -cell 3202 0 2 ( 1 -10 228 -229 ) -cell 3203 0 2 ( 1 -10 229 -230 ) -cell 3204 0 2 ( 1 -10 230 -25 ) -cell 3300 0 2 ( 10 -11 24 -227 ) -cell 3301 0 2 ( 10 -11 227 -228 ) -cell 3302 0 2 ( 10 -11 228 -229 ) -cell 3303 0 2 ( 10 -11 229 -230 ) -cell 3304 0 2 ( 10 -11 230 -25 ) -cell 3400 0 2 ( 11 -12 24 -227 ) -cell 3401 0 2 ( 11 -12 227 -228 ) -cell 3402 0 2 ( 11 -12 228 -229 ) -cell 3403 0 2 ( 11 -12 229 -230 ) -cell 3404 0 2 ( 11 -12 230 -25 ) -cell 3500 0 2 ( 12 -2 24 -227 ) -cell 3501 0 2 ( 12 -2 227 -228 ) -cell 3502 0 2 ( 12 -2 228 -229 ) -cell 3503 0 2 ( 12 -2 229 -230 ) -cell 3504 0 2 ( 12 -2 230 -25 ) -cell 3600 0 2 ( 2 -3 24 -25 ) -cell 10 0 void ( 26 -27 -10 ) -cell 11 0 void ( 26 -27 10 -11 ) -cell 12 0 void ( 26 -27 11 -12 ) -cell 13 0 void ( 26 -27 12 -13 ) -cell 14 0 void ( 26 -27 13 -4 ) -cell 15 0 void ( -4 21 -22 ) -cell 16 0 void ( -1 22 -23 ) -cell 17 0 void ( -3 23 -24 ) -cell 18 0 void ( -4 25 -26 ) -cell 19 0 void ( 2 -3 22 -23 ) -cell 50 0 void ( -4 20 -21 ) -cell 100 0 void ( 4: -20: 27 ) -% --- material definitions --- % -% M1 -mat 1 -6.536 rgb 0 208 31 -1001 1.457907e-01 -1002 1.676788e-05 -5010 7.989261e-06 -5011 3.215778e-05 -6012 8.129276e-04 -7014 2.159162e-03 -7015 7.975079e-05 -8016 7.280396e-02 -13027 8.029408e-04 -14028 7.119967e-03 -14029 3.615341e-04 -14030 2.383266e-04 -15031 3.495389e-04 -22046 1.120522e-04 -22047 1.010507e-04 -22048 1.001269e-03 -22049 7.347907e-05 -22050 7.035519e-05 -24050 6.335342e-03 -24052 1.221708e-01 -24053 1.385322e-02 -24054 3.448351e-03 -25055 1.418129e-02 -26054 2.936167e-02 -26056 4.609150e-01 -26057 1.064456e-02 -26058 1.416591e-03 -27059 3.675152e-04 -28058 6.159644e-02 -28060 2.372680e-02 -28061 1.031389e-03 -28062 3.288522e-03 -28064 8.374892e-04 -29063 1.416122e-03 -29065 6.311824e-04 -41093 4.663848e-05 -42092 1.674711e-03 -42094 1.043873e-03 -42095 1.796590e-03 -42096 1.882357e-03 -42097 1.077728e-03 -42098 2.723098e-03 -42100 1.086756e-03 -73181 2.396838e-05 -74182 6.245761e-07 -74183 3.372711e-07 -74184 7.221513e-07 -74186 6.700641e-07 -82206 4.043466e-07 -82207 3.707909e-07 -82208 8.791602e-07 -83209 1.657813e-06 -16032 9.676215e-05 -16033 7.639922e-07 -16034 4.329289e-06 -16036 1.018656e-08 -19039 5.169006e-06 -19040 6.484945e-10 -19041 3.730340e-07 -23050 3.395521e-06 -23051 1.354813e-03 -40090 4.891587e-06 -40091 1.066737e-06 -40092 1.630529e-06 -40094 1.652396e-06 -40096 2.662088e-07 -50112 7.081358e-08 -50114 4.818244e-08 -50115 2.482126e-08 -50116 1.061474e-06 -50117 5.606684e-07 -50118 1.768149e-06 -50119 6.271017e-07 -50120 2.378460e-06 -50122 3.380071e-07 -50124 4.226914e-07 -% M2 -mat 2 -7.93 rgb 0 0 255 -5010 1.022623e-05 -5011 4.116186e-05 -6012 1.039759e-03 -7014 2.769128e-03 -7015 1.022803e-04 -8016 6.948389e-05 -13027 1.029761e-03 -14028 9.119405e-03 -14029 4.630606e-04 -14030 3.052532e-04 -15031 4.478961e-04 -22046 1.435167e-04 -22047 1.294260e-04 -22048 1.282433e-03 -22049 9.411218e-05 -22050 9.011110e-05 -24050 8.123266e-03 -24052 1.566487e-01 -24053 1.776278e-02 -24054 4.421525e-03 -25055 1.819578e-02 -26054 3.763307e-02 -26056 5.907590e-01 -26057 1.364324e-02 -26058 1.815659e-03 -27059 4.708908e-04 -28058 7.895089e-02 -28060 3.041175e-02 -28061 1.321973e-03 -28062 4.215043e-03 -28064 1.073451e-03 -29063 1.811830e-03 -29065 8.075587e-04 -41093 5.978614e-05 -42092 2.151301e-03 -42094 1.340939e-03 -42095 2.307865e-03 -42096 2.418039e-03 -42097 1.384429e-03 -42098 3.498039e-03 -42100 1.396026e-03 -73181 3.069288e-05 -74182 8.001145e-07 -74183 4.320618e-07 -74184 9.251135e-07 -74186 8.583870e-07 -82206 5.156204e-07 -82207 4.728304e-07 -82208 1.121100e-06 -83209 2.129506e-06 -16032 1.234584e-04 -16033 9.747740e-07 -16034 5.523719e-06 -16036 1.299699e-08 -19039 6.619790e-06 -19040 8.305074e-10 -19041 4.777334e-07 -23050 1.089747e-07 -23051 4.348092e-05 -40090 6.275445e-06 -40091 1.368523e-06 -40092 2.091815e-06 -40094 2.119868e-06 -40096 3.415208e-07 -50112 9.077095e-08 -50114 6.176168e-08 -50115 3.181662e-08 -50116 1.360628e-06 -50117 7.186814e-07 -50118 2.266466e-06 -50119 8.038376e-07 -50120 3.048781e-06 -50122 4.332675e-07 -50124 5.418184e-07 diff --git a/jade/install_files/Benchmarks_Inputs/SphereSDDR/mcnp/SphereSDDR.i b/jade/install_files/Benchmarks_Inputs/SphereSDDR/d1s/SphereSDDR.i similarity index 100% rename from jade/install_files/Benchmarks_Inputs/SphereSDDR/mcnp/SphereSDDR.i rename to jade/install_files/Benchmarks_Inputs/SphereSDDR/d1s/SphereSDDR.i diff --git a/jade/install_files/Benchmarks_Inputs/SphereSDDR/openmc/geometry.xml b/jade/install_files/Benchmarks_Inputs/SphereSDDR/openmc/geometry.xml deleted file mode 100644 index d795ebde..00000000 --- a/jade/install_files/Benchmarks_Inputs/SphereSDDR/openmc/geometry.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - diff --git a/jade/install_files/Benchmarks_Inputs/SphereSDDR/serpent/SphereSDDR.i b/jade/install_files/Benchmarks_Inputs/SphereSDDR/serpent/SphereSDDR.i deleted file mode 100644 index f4e588e5..00000000 --- a/jade/install_files/Benchmarks_Inputs/SphereSDDR/serpent/SphereSDDR.i +++ /dev/null @@ -1,10 +0,0 @@ -% --- surface definitions --- % -surf 1 sph 0.0 0.0 0.0 5.0 -surf 2 sph 0.0 0.0 0.0 50.0 -surf 3 sph 0.0 0.0 0.0 55.0 -surf 4 sph 0.0 0.0 0.0 60.0 -% --- cell definitions --- % -cell 1 0 void ( -1 ) -cell 2 0 1 ( 1 -2 ) -cell 3 0 void ( 2 -3 ) -cell 4 0 void ( 3 ) diff --git a/jade/libmanager.py b/jade/libmanager.py index f995c341..f7d01e53 100644 --- a/jade/libmanager.py +++ b/jade/libmanager.py @@ -27,7 +27,9 @@ import os import re import sys +import logging import warnings +import numpy as np import jade.acepyne as ace import jade.xsdirpyne as xs @@ -36,28 +38,28 @@ from jade.exceptions import fatal_exception # colors -CRED = '\033[91m' -CEND = '\033[0m' +CRED = "\033[91m" +CEND = "\033[0m" -MSG_DEFLIB = ' The Default library {} was used for zaid {}' +MSG_DEFLIB = " The Default library {} was used for zaid {}" class IsotopeDataParser: def __init__(self, isotopes_file: os.PathLike) -> None: # load the natural abundance file abundances = pd.read_csv(isotopes_file, skiprows=2) - abundances['idx'] = abundances['idx'].astype(str) - abundances.set_index('idx', inplace=True) + abundances["idx"] = abundances["idx"].astype(str) + abundances.set_index("idx", inplace=True) self.isotopes = abundances def get_formulazaid(self, formula): match = re.match(r"([a-z]+)([0-9]+)", formula, re.I) parts = match.groups() E, A = parts[0], int(parts[1]) - newiso = self.isotopes[self.isotopes['E'] == E] - Z = newiso['Z'].values[0] - zaid = '{0}{1:0>3}'.format(Z, A) + newiso = self.isotopes[self.isotopes["E"] == E] + Z = newiso["Z"].values[0] + zaid = "{0}{1:0>3}".format(Z, A) return zaid @@ -65,11 +67,15 @@ class LibManager: # def __init__(self, xsdir_file, defaultlib='81c', activationfile=None, # isotopes_file=None): - def __init__(self, lib_df: pd.DataFrame, defaultlib: str = None, - activationfile: os.PathLike = None, - isotopes_file: os.PathLike = None): + def __init__( + self, + lib_df: pd.DataFrame, + defaultlib: str = None, + activationfile: os.PathLike = None, + isotopes_file: os.PathLike = None, + ) -> None: """ - Object dealing with all complex operations that involves nuclear data + Object dealing with all complex operations that involves nuclear data. Parameters ---------- @@ -85,13 +91,32 @@ def __init__(self, lib_df: pd.DataFrame, defaultlib: str = None, path to the isotopes files. If None (default) the file is searched in the current directory. + Attributes + ---------- + isotope_parser : IsotopeDataParser + object dealing with the isotopes data. + isotopes : pd.DataFrame + contains the isotopes data. + defaultlib : str + lib suffix to be used as default in translation operations. + data : dict[str, dict[str, Union[Xsdir, OpenMCXsdir, SerpentXsdir]]] + contains the libraries data. first level keys are the codes, second + level keys are the library suffixes. ultimate value is the xsdir + object. + codes : list + list of codes available. + libraries : dict[str, list[str]] + contains the libraries available for each code. + reactions : dict[str, pd.DataFrame] + contains the reactions data for the different activation libraries. + Returns ------- None. """ if isotopes_file is None: - isotopes_file = os.path.join('resources', 'Isotopes.txt') + isotopes_file = os.path.join("resources", "Isotopes.txt") self.isotope_parser = IsotopeDataParser(isotopes_file) self.isotopes = self.isotope_parser.isotopes @@ -103,56 +128,96 @@ def __init__(self, lib_df: pd.DataFrame, defaultlib: str = None, lib_df.columns = new_columns if defaultlib is None: - self.defaultlib = lib_df[lib_df['default'] == 'yes']['suffix'].values[0] + self.defaultlib = lib_df[lib_df["default"] == "yes"]["suffix"].values[0] else: self.defaultlib = defaultlib self.data = {} self.codes = [] - lib_df.set_index('suffix', inplace=True) + lib_df.set_index("suffix", inplace=True) # Initilize the Xsdir object # self.XS = xs.Xsdir(xsdir_file) + + # this block of code needs to check the availability of the libraries. + # Only libraries specified in the config file are checked, if paths + # for the libraries are left empty, the library is not not checked and + # it is not registered as available. If the path is not empty but + # library is not found, a warning is raised, choice for interrupting the + # session is left to the user. for code in lib_df.columns[2:]: code = code.lower() self.codes.append(code) self.data[code] = {} for library, row in lib_df.iterrows(): path = row[code] - if path != '': - if not os.path.exists(path): - fatal_exception(path + ' does not exist') - - if len(path) != 0 : - - if code == 'mcnp': - self.data[code][library] = Xsdir(path) - - elif code == 'openmc': - self.data[code][library] = OpenMCXsdir(path, self, library) - - elif code == 'serpent': - self.data[code][library] = SerpentXsdir(path) - - elif code == 'd1s': - self.data[code][library] = Xsdir(path) - + # if the path is empty just ignore it + if path is None or path == "": + logging.info("No path for %s library", library) + continue + + # if the path is not empty, check if the file exists + # and if it does not, raise a warning since it may not be the + # intended behaviour by the user + if not os.path.exists(path): + logging.warning( + "Library %s for code %s not found at %s", library, code, path + ) + # fatal_exception(path + " does not exist") + + if code == "mcnp": + xsdir = Xsdir(path) + # verify that the library is actually in the xsdir + available_libs = set(np.array(xsdir.tablenames)[:, 1]) + if library in available_libs: + self.data[code][library] = xsdir + else: + logging.warning( + "Library %s not present in XSDIR file: %s", library, path + ) + + elif code == "openmc": + self.data[code][library] = OpenMCXsdir(path, self, library) + + elif code == "serpent": + self.data[code][library] = SerpentXsdir(path) + + elif code == "d1s": + xsdir = Xsdir(path) + # verify that the library is actually in the xsdir + available_libs = set(np.array(xsdir.tablenames)[:, 1]) + if library in available_libs: + self.data[code][library] = xsdir else: - raise ValueError('{} code not implemented'.format(code)) + logging.warning( + "Library %s not present in XSDIR file: %s", library, path + ) + + else: + raise ValueError(f"{code} code not implemented") # Identify different libraries installed. This is done checking H # libraries = self.check4zaid('1001') # libraries.extend(self.check4zaid('1000')) # photons - """ Legacy library definition changed """ - """ - libraries = [] - for table in self.XS: - lib = table.name.split('.')[1] - if lib not in libraries: - libraries.append(lib) + # """ Legacy library definition changed """ + # """ + # libraries = [] + # for table in self.XS: + # lib = table.name.split('.')[1] + # if lib not in libraries: + # libraries.append(lib) + + # self.libraries = libraries + # """ + + # libraries have now been checked at the source, they may be different + # for each code + libraries = {} + for key, value in self.data.items(): + libraries[key] = [] + for lib, _ in value.items(): + libraries[key].append(lib) self.libraries = libraries - """ - self.libraries = list(lib_df.index) # Load the activation reaction data if available if activationfile is not None: @@ -167,7 +232,7 @@ def __init__(self, lib_df: pd.DataFrame, defaultlib: str = None, self.reactions = reactions - def check4zaid(self, zaid: str, code: str = 'mcnp'): + def check4zaid(self, zaid: str, code: str = "mcnp"): # Needs fixing """ Check which libraries are available for the selected zaid and return it @@ -186,13 +251,13 @@ def check4zaid(self, zaid: str, code: str = 'mcnp'): """ libraries = [] - if code != 'openmc': - for lib in self.libraries: + if code != "openmc": + for lib in self.libraries[code]: xsdir = self.data[code][lib] - if lib in xsdir.find_table(zaid, mode='default-fast'): + if lib in xsdir.find_table(zaid, mode="default-fast"): libraries.append(lib) else: - raise NotImplementedError('{} not implemented yet'.format(code)) + raise NotImplementedError("{} not implemented yet".format(code)) return libraries @@ -205,7 +270,7 @@ def check4zaid(self, zaid: str, code: str = 'mcnp'): # else: # return False - def convertZaid(self, zaid, lib, code: str = 'mcnp'): + def convertZaid(self, zaid: str, lib: str, code: str = "mcnp"): # Needs fixing """ This methods will convert a zaid into the requested library @@ -238,36 +303,43 @@ def convertZaid(self, zaid, lib, code: str = 'mcnp'): """ # Check if library is available in Xsdir - if lib not in self.libraries: - raise ValueError('Library '+lib+' is not available in xsdir file') + if lib not in self.libraries[code]: + raise ValueError("Library " + lib + " is not available in xsdir file") zaidlibs = self.check4zaid(zaid, code) - if code in ['mcnp', 'd1s', 'serpent']: + if code in ["mcnp", "d1s", "serpent"]: XS = self.data[code][lib] # Natural zaid - if zaid[-3:] == '000': + if zaid[-3:] == "000": # Check if zaid has natural info - if XS.find_table(zaid+'.'+lib, mode='exact'): + if XS.find_table(zaid + "." + lib, mode="exact"): translation = {zaid: (lib, 1, 1)} # mass not important else: # Has to be expanded translation = {} - reduced = self.isotopes[self.isotopes['Z'] == int(zaid[:-3])] + reduced = self.isotopes[self.isotopes["Z"] == int(zaid[:-3])] for idx, row in reduced.iterrows(): # zaid availability must be checked - if XS.find_table(idx+'.'+lib, mode='exact'): + if XS.find_table(idx + "." + lib, mode="exact"): newlib = lib - elif self.data[code][self.defaultlib].find_table(idx+'.'+self.defaultlib, - mode='exact'): + elif self.data[code][self.defaultlib].find_table( + idx + "." + self.defaultlib, mode="exact" + ): warnings.warn(MSG_DEFLIB.format(self.defaultlib, zaid)) newlib = self.defaultlib else: - raise ValueError('No available translation for zaid :' + - zaid+'It is needed for natural zaid expansion.') - - translation[idx] = (newlib, row['Mean value'], - row['Atomic Mass']) + raise ValueError( + "No available translation for zaid :" + + zaid + + "It is needed for natural zaid expansion." + ) + + translation[idx] = ( + newlib, + row["Mean value"], + row["Atomic Mass"], + ) # 1to1 elif lib in zaidlibs: translation = {zaid: (lib, 1, 1)} # mass not important @@ -275,22 +347,23 @@ def convertZaid(self, zaid, lib, code: str = 'mcnp'): # No possible correspondence, natural or default lib has to be used else: # Check if the natural zaid is available - natzaid = zaid[:-3]+'000' - if XS.find_table(natzaid+'.'+lib, mode='exact'): + natzaid = zaid[:-3] + "000" + if XS.find_table(natzaid + "." + lib, mode="exact"): translation = {natzaid: (lib, 1, 1)} # mass not important # Check if default lib is available - elif self.data[code][self.defaultlib].find_table(zaid+'.'+self.defaultlib, mode='exact'): + elif self.data[code][self.defaultlib].find_table( + zaid + "." + self.defaultlib, mode="exact" + ): warnings.warn(MSG_DEFLIB.format(self.defaultlib, zaid)) translation = {zaid: (self.defaultlib, 1, 1)} # mass not imp else: - raise ValueError('No available translation for zaid :' + - zaid) + raise ValueError("No available translation for zaid :" + zaid) else: - raise ValueError('Translation not required for code '+code) + raise ValueError("Translation not required for code " + code) return translation - def get_libzaids(self, lib: str, code: str = 'mcnp'): + def get_libzaids(self, lib: str, code: str = "mcnp"): # Needs fixing """ Given a library, returns all zaids available @@ -314,11 +387,11 @@ def get_libzaids(self, lib: str, code: str = 'mcnp'): if isinstance(XS, xs.Xsdir): for table in XS.find_zaids(lib): - zaid = table.name.split('.')[0] + zaid = table.name.split(".")[0] if zaid not in zaids: zaids.append(zaid) else: - raise NotImplementedError('{} code is not yet implemented'.format(code)) + raise NotImplementedError("{} code is not yet implemented".format(code)) return zaids @@ -344,7 +417,7 @@ def get_zaidname(self, zaid): """ if type(zaid) == str: - splitted = zaid.split('.') + splitted = zaid.split(".") elem = splitted[0][:-3] i = int(elem) isotope = splitted[0][-3:] @@ -353,11 +426,11 @@ def get_zaidname(self, zaid): i = int(zaid.element) isotope = zaid.isotope - newiso = self.isotopes.set_index('Z') - newiso = newiso.loc[~newiso.index.duplicated(keep='first')] + newiso = self.isotopes.set_index("Z") + newiso = newiso.loc[~newiso.index.duplicated(keep="first")] - name = newiso['Element'].loc[i] - formula = newiso['E'].loc[i]+'-'+str(int(isotope)) + name = newiso["Element"].loc[i] + formula = newiso["E"].loc[i] + "-" + str(int(isotope)) return name, formula @@ -377,24 +450,24 @@ def get_zaidnum(self, zaidformula): """ # get the table and drop the duplicates - newiso = self.isotopes.set_index(['E']) - newiso = newiso.loc[~newiso.index.duplicated(keep='first')] + newiso = self.isotopes.set_index(["E"]) + newiso = newiso.loc[~newiso.index.duplicated(keep="first")] # split the name - patnum = re.compile(r'\d+') - patname = re.compile(r'[a-zA-Z]+') + patnum = re.compile(r"\d+") + patname = re.compile(r"[a-zA-Z]+") try: num = patnum.search(zaidformula).group() name = patname.search(zaidformula).group() except AttributeError: - raise ValueError('No correspondent zaid found for '+zaidformula) + raise ValueError("No correspondent zaid found for " + zaidformula) - atomnumber = newiso.loc[name, 'Z'] + atomnumber = newiso.loc[name, "Z"] zaidnum = "{}{:03d}".format(atomnumber, int(num)) return zaidnum - def select_lib(self): + def select_lib(self, code: str = "mcnp") -> str: """ Prompt an library input selection with Xsdir availabilty check @@ -402,54 +475,60 @@ def select_lib(self): ------- lib : str Library to assess. + code: str, optional + code for which the library is selected. default is MCNP """ - error = CRED+''' + error = ( + CRED + + """ Error: {} The selected library is not available. - '''+CEND + """ + + CEND + ) # Add a counter to avoid falling in an endless loop i = 0 while True: i += 1 - lib = input(' Select library (e.g. 31c or 99c-31c): ') - if lib in self.libraries: + lib = input(" Select library (e.g. 31c or 99c-31c): ") + if lib in self.libraries[code]: break - elif lib[0] == '{': + elif lib[0] == "{": libs = json.loads(lib) # all libraries should be available tocheck = list(libs.values()) tocheck.extend(list(libs.keys())) flag = True for val in tocheck: - if val not in self.libraries: + if val not in self.libraries[code]: print(error.format(val)) flag = False if flag: break - elif '-' in lib: - libs = lib.split('-') + elif "-" in lib: + libs = lib.split("-") flag = True for val in libs: - if val not in self.libraries: + if val not in self.libraries[code]: print(error.format(val)) flag = False if flag: break - - elif lib == 'back': + + elif lib == "back": break - + elif lib == "exit": - break + break else: print(error.format(lib)) if i > 10: - raise ValueError('Too many wrong inputs') + raise ValueError("Too many wrong inputs") return lib def get_zaid_mass(self, zaid): @@ -468,13 +547,13 @@ def get_zaid_mass(self, zaid): """ try: - m = self.isotopes['Atomic Mass'].loc[zaid.element+zaid.isotope] + m = self.isotopes["Atomic Mass"].loc[zaid.element + zaid.isotope] except KeyError: # It means that it is a natural zaid # For a natural zaid the natural abundance mass is used df = self.isotopes.reset_index() - df['Partial mass'] = df['Atomic Mass']*df['Mean value'] - masked = df.set_index('Z').loc[int(zaid.element)] - m = masked['Partial mass'].sum() + df["Partial mass"] = df["Atomic Mass"] * df["Mean value"] + masked = df.set_index("Z").loc[int(zaid.element)] + m = masked["Partial mass"].sum() return float(m) @@ -497,22 +576,22 @@ def get_reactions(self, lib, parent): """ reactions = [] try: - df = self.reactions[lib].set_index('Parent') + df = self.reactions[lib].set_index("Parent") isotopename, formula = self.get_zaidname(parent) - formulazaid = formula.replace('-', '') # eliminate the '-' + formulazaid = formula.replace("-", "") # eliminate the '-' # collect and provide as tuples subset = df.loc[formulazaid] try: for _, row in subset.iterrows(): - MT = str(int(row['MT'])) - daughter = row['Daughter'] + MT = str(int(row["MT"])) + daughter = row["Daughter"] daughter = self.get_zaidnum(daughter) reactions.append((MT, daughter)) except AttributeError: # then is not a DF but a Series - MT = str(int(subset['MT'])) - daughter = subset['Daughter'] + MT = str(int(subset["MT"])) + daughter = subset["Daughter"] daughter = self.get_zaidnum(daughter) reactions.append((MT, daughter)) diff --git a/jade/main.py b/jade/main.py index b20fe906..f9f949e8 100644 --- a/jade/main.py +++ b/jade/main.py @@ -52,7 +52,7 @@ class Session: - def __init__(self): + def __init__(self) -> None: """ This object represent a JADE session. All "environment" variables are initialized @@ -64,7 +64,7 @@ def __init__(self): """ self.initialize() - def initialize(self): + def initialize(self) -> None: """ Initialize JADE session: - folders structure is created if absent @@ -82,45 +82,54 @@ def initialize(self): jade_root = os.getcwd() if os.path.dirname(code_root) in jade_root: - fatal_exception('Cannot initialise JADE in Code directory') - - self.path_default_settings = os.path.join(code_root, 'default_settings') - self.path_templates = os.path.join(code_root, 'templates') + fatal_exception("Cannot initialise JADE in Code directory") + + self.path_default_settings = os.path.join(code_root, "default_settings") + self.path_templates = os.path.join(code_root, "templates") # --- INITIALIZATION --- # --- Create/memorize JADE folder structure --- # Future implementation - self.path_quality = os.path.join(jade_root, 'Quality') + self.path_quality = os.path.join(jade_root, "Quality") # Test level 1 - self.path_test = os.path.join(jade_root, 'Tests') + self.path_test = os.path.join(jade_root, "Tests") # Test level 2 - self.path_run = os.path.join(self.path_test, 'Simulations') - self.path_pp = os.path.join(self.path_test, 'Post-Processing') + self.path_run = os.path.join(self.path_test, "Simulations") + self.path_pp = os.path.join(self.path_test, "Post-Processing") # Test level 3 - self.path_single = os.path.join(self.path_pp, 'Single_Libraries') - self.path_comparison = os.path.join(self.path_pp, 'Comparisons') + self.path_single = os.path.join(self.path_pp, "Single_Libraries") + self.path_comparison = os.path.join(self.path_pp, "Comparisons") # Utilities - self.path_uti = os.path.join(jade_root, 'Utilities') - self.path_logs = os.path.join(jade_root, 'Utilities', 'Log_Files') - self.path_test_install = os.path.join(jade_root, 'Utilities', - 'Installation_Test') - - keypaths = [self.path_quality, self.path_test, - self.path_run, self.path_pp, self.path_uti, - self.path_single, self.path_comparison, self.path_logs, - self.path_test_install] + self.path_uti = os.path.join(jade_root, "Utilities") + self.path_logs = os.path.join(jade_root, "Utilities", "Log_Files") + self.path_test_install = os.path.join( + jade_root, "Utilities", "Installation_Test" + ) + + keypaths = [ + self.path_quality, + self.path_test, + self.path_run, + self.path_pp, + self.path_uti, + self.path_single, + self.path_comparison, + self.path_logs, + self.path_test_install, + ] for path in keypaths: if not os.path.exists(path): os.mkdir(path) # --This paths must exist or are created at the first initialization-- # Configuration - self.path_cnf = os.path.join(jade_root, 'Configuration', - 'Benchmarks_Configuration') + self.path_cnf = os.path.join( + jade_root, "Configuration", "Benchmarks_Configuration" + ) # Experimental results - self.path_exp_res = os.path.join(jade_root, 'Experimental_Results') + self.path_exp_res = os.path.join(jade_root, "Experimental_Results") # Benchmark inputs - self.path_inputs = os.path.join(jade_root, 'Benchmarks_Inputs') + self.path_inputs = os.path.join(jade_root, "Benchmarks_Inputs") # Copy default settings if it is the first initialization if not os.path.exists(self.path_cnf): @@ -129,32 +138,34 @@ def initialize(self): shutil.copytree(files, os.path.dirname(self.path_cnf)) # Copy files into benchmark inputs folder - files = os.path.join(code_root, 'install_files', 'Benchmarks_Inputs') + files = os.path.join(code_root, "install_files", "Benchmarks_Inputs") shutil.copytree(files, self.path_inputs) # Copy experimental results folder - files = os.path.join(code_root, 'install_files', 'Experimental_Results') + files = os.path.join(code_root, "install_files", "Experimental_Results") shutil.copytree(files, self.path_exp_res) # the application needs to be closed sys.exit() # Read global configuration file. All vital variables are stored here - self.conf = cnf.Configuration(os.path.join(jade_root, 'Configuration', - 'Config.xlsx')) + self.conf = cnf.Configuration( + os.path.join(jade_root, "Configuration", "Config.xlsx") + ) # --- Create the session LOG --- - log = os.path.join(self.path_logs, - 'Log '+time.ctime().replace(':', '-')+'.txt') + log = os.path.join( + self.path_logs, "Log " + time.ctime().replace(":", "-") + ".txt" + ) self.log = cnf.Log(log) # --- Create the library manager --- - #dl = self.conf.default_lib - activationfile = os.path.join(jade_root, 'Configuration', 'Activation.xlsx') - isotopes_file = os.path.join(code_root, 'resources', 'Isotopes.txt') - self.lib_manager = libmanager.LibManager(self.conf.lib, - activationfile=activationfile, - isotopes_file=isotopes_file) + # dl = self.conf.default_lib + activationfile = os.path.join(jade_root, "Configuration", "Activation.xlsx") + isotopes_file = os.path.join(code_root, "resources", "Isotopes.txt") + self.lib_manager = libmanager.LibManager( + self.conf.lib, activationfile=activationfile, isotopes_file=isotopes_file + ) # --- Initialize status --- self.state = status.Status(self) @@ -187,11 +198,11 @@ def check_active_tests(self, action, exp=False): to_perform = [] for idx, row in config.iterrows(): - filename = str(row['Folder Name']) - testname = filename.split('.')[0] + filename = str(row["Folder Name"]) + testname = filename.split(".")[0] pp = row[action] - if pp is True or pp == 'True' or pp == 'true': + if pp is True or pp == "True" or pp == "true": to_perform.append(testname) return to_perform @@ -217,13 +228,12 @@ def restore_default_settings(self): def main(): # Module having problem with log(0) for tick position in graphs - warnings.filterwarnings('ignore', - r'invalid value encountered in double_scalars') - warnings.filterwarnings('ignore', - r'overflow encountered in power') - warnings.filterwarnings('ignore', module=r'plotter') - warnings.filterwarnings('ignore', - message=r'Warning: converting a masked element to nan.') + warnings.filterwarnings("ignore", r"invalid value encountered in double_scalars") + warnings.filterwarnings("ignore", r"overflow encountered in power") + warnings.filterwarnings("ignore", module=r"plotter") + warnings.filterwarnings( + "ignore", message=r"Warning: converting a masked element to nan." + ) session = Session() gui.mainloop(session) diff --git a/jade/output.py b/jade/output.py index dd5a9710..65deee82 100644 --- a/jade/output.py +++ b/jade/output.py @@ -242,36 +242,6 @@ def __init__(self, lib, config, session): self.atlas_path_d1s = atlas_path_d1s self.couples = couples # Couples of libraries to post process - """ - if self.mcnp: - atlas_path_mcnp = os.path.join(self.atlas_path, "mcnp") - os.mkdir(atlas_path_mcnp) - self.atlas_path_mcnp = atlas_path_mcnp - raw_path_mcnp = os.path.join(self.raw_path, "mcnp") - os.mkdir(raw_path_mcnp) - self.raw_path_mcnp = raw_path_mcnp - if self.serpent: - atlas_path_serpent = os.path.join(self.atlas_path, "serpent") - os.mkdir(atlas_path_serpent) - self.atlas_path_serpent = atlas_path_serpent - raw_path_serpent = os.path.join(self.raw_path, "serpent") - os.mkdir(raw_path_serpent) - self.raw_path_serpent = raw_path_serpent - if self.openmc: - atlas_path_openmc = os.path.join(self.atlas_path, "openmc") - os.mkdir(atlas_path_openmc) - self.atlas_path_openmc = atlas_path_openmc - raw_path_openmc = os.path.join(self.raw_path, "openmc") - os.mkdir(raw_path_openmc) - self.raw_path_openmc = raw_path_openmc - if self.d1s: - atlas_path_d1s = os.path.join(self.atlas_path, "d1s") - os.mkdir(atlas_path_d1s) - self.atlas_path_d1s = atlas_path_d1s - raw_path_d1s = os.path.join(self.raw_path, "d1s") - os.mkdir(raw_path_d1s) - self.raw_path_d1s = raw_path_d1s - """ # SINGLE-LIBRARY else: self.single = True # Indicator for single or comparison @@ -331,92 +301,6 @@ def __init__(self, lib, config, session): self.raw_path_d1s = raw_path_d1s self.atlas_path_d1s = atlas_path_d1s - - # Generate folders for each code - """if self.mcnp: - atlas_path_mcnp = os.path.join(self.atlas_path, "mcnp") - os.mkdir(atlas_path_mcnp) - self.atlas_path_mcnp = atlas_path_mcnp - raw_path_mcnp = os.path.join(self.raw_path, "mcnp") - os.mkdir(raw_path_mcnp) - self.raw_path_mcnp = raw_path_mcnp - if self.serpent: - atlas_path_serpent = os.path.join(self.atlas_path, "serpent") - os.mkdir(atlas_path_serpent) - self.atlas_path_serpent = atlas_path_serpent - raw_path_serpent = os.path.join(self.raw_path, "serpent") - os.mkdir(raw_path_serpent) - self.raw_path_serpent = raw_path_serpent - if self.openmc: - atlas_path_openmc = os.path.join(self.atlas_path, "openmc") - os.mkdir(atlas_path_openmc) - self.atlas_path_openmc = atlas_path_openmc - raw_path_openmc = os.path.join(self.raw_path, "openmc") - os.mkdir(raw_path_openmc) - self.raw_path_openmc = raw_path_openmc - if self.d1s: - atlas_path_d1s = os.path.join(self.atlas_path, "d1s") - os.mkdir(atlas_path_d1s) - self.atlas_path_d1s = atlas_path_d1s - raw_path_d1s = os.path.join(self.raw_path, "d1s") - os.mkdir(raw_path_d1s) - self.raw_path_d1s = raw_path_d1s""" - """ - # Attempt to fix folder structure - unfinished - if self.mcnp: - path_mcnp = os.path.join(out, 'mcnp') - os.mkdir(path_mcnp) - self.path_mcnp = path_mcnp - atlas_path_mcnp = os.path.join(path_mcnp, 'Atlas') - os.mkdir(atlas_path_mcnp) - self.atlas_path_mcnp = atlas_path_mcnp - excel_path_mcnp = os.path.join(path_mcnp, 'Excel') - os.mkdir(excel_path_mcnp) - self.excel_path_mcnp = excel_path_mcnp - raw_path_mcnp = os.path.join(path_mcnp, 'Raw') - os.mkdir(raw_path_mcnp) - self.raw_path_mcnp = raw_path_mcnp - if self.serpent: - path_serpent = os.path.join(out, 'serpent') - os.mkdir(path_serpent) - self.path_serpent = path_serpent - atlas_path_serpent = os.path.join(path_serpent, 'Atlas') - os.mkdir(atlas_path_serpent) - self.atlas_path_serpent = atlas_path_serpent - excel_path_serpent = os.path.join(path_serpent, 'Excel') - os.mkdir(excel_path_serpent) - self.excel_path_serpent = excel_path_serpent - raw_path_serpent = os.path.join(path_serpent, 'Raw') - os.mkdir(raw_path_serpent) - self.raw_path_serpent = raw_path_serpent - if self.openmc: - path_openmc = os.path.join(out, 'openmc') - os.mkdir(path_openmc) - self.path_openmc = path_openmc - atlas_path_openmc = os.path.join(path_openmc, 'Atlas') - os.mkdir(atlas_path_openmc) - self.atlas_path_openmc = atlas_path_openmc - excel_path_openmc = os.path.join(path_openmc, 'Excel') - os.mkdir(excel_path_openmc) - self.excel_path_openmc = excel_path_openmc - raw_path_openmc = os.path.join(path_openmc, 'Raw') - os.mkdir(raw_path_openmc) - self.raw_path_openmc = raw_path_openmc - if self.d1s: - path_d1s = os.path.join(out, 'd1s') - os.mkdir(path_d1s) - self.path_d1s = path_d1s - atlas_path_d1s = os.path.join(path_d1s, 'Atlas') - os.mkdir(atlas_path_d1s) - self.atlas_path_d1s = atlas_path_d1s - excel_path_d1s = os.path.join(path_d1s, 'Excel') - os.mkdir(excel_path_d1s) - self.excel_path_d1s = excel_path_d1s - raw_path_d1s = os.path.join(path_d1s, 'Raw') - os.mkdir(raw_path_d1s) - self.raw_path_d1s = raw_path_d1s - """ - def single_postprocess(self): """ Execute the full post-processing of a single library (i.e. excel, @@ -455,6 +339,7 @@ def single_postprocess(self): print(tally_num) try: if self.mcnp: + print(self.outputs["mcnp"]) output = self.outputs["mcnp"][tally_num] except KeyError: fatal_exception( @@ -544,7 +429,8 @@ def compare(self): self._generate_comparison_excel_output() print(" Creating Atlas...") - outpath = os.path.join(self.atlas_path, "tmp") + if self.mcnp: + outpath = os.path.join(self.atlas_path_mcnp, "tmp") os.mkdir(outpath) # Get atlas configuration @@ -552,10 +438,7 @@ def compare(self): atl_cnf.set_index("Tally", inplace=True) # Printing Atlas - template = os.path.join( - self.code_path, - "templates", - "AtlasTemplate.docx") + template = os.path.join(self.path_templates, "AtlasTemplate.docx") atlas = at.Atlas(template, self.testname + "_" + self.name) @@ -563,13 +446,13 @@ def compare(self): outputs_dic = {} for lib in self.lib: # Recover lib output - out_path = os.path.join( - self.session.path_single, - lib, - self.testname, - "Raw_Data", - lib + ".pickle", - ) + if self.mcnp: + out_path = os.path.join( + self.session.path_single, + lib, self.testname, + "mcnp", "Raw_Data", + lib + ".pickle" + ) with open(out_path, "rb") as handle: outputs = pickle.load(handle) outputs_dic[lib] = outputs @@ -583,7 +466,15 @@ def compare(self): atl_cnf_plot = atl_cnf[atl_cnf[plot_type]] for tally_num in tqdm(atl_cnf_plot.index, desc="Tallies"): # The last 'outputs' can be easily used for common data - output = outputs[tally_num] + try: + if self.mcnp: + output = self.outputs["mcnp"][tally_num] + except KeyError: + fatal_exception( + "tally n. " + + str(tally_num) + + " is in config but not in the MCNP output" + ) vals_df = output["Value"] err_df = output["Error"] quantity = str(atl_cnf_plot["Quantity"].loc[tally_num]) @@ -656,8 +547,9 @@ def compare(self): img_path = plot.plot(plot_type) atlas.insert_img(img_path) + if self.mcnp: + atlas.save(self.atlas_path_mcnp) - atlas.save(self.atlas_path) # Remove tmp images shutil.rmtree(outpath) @@ -702,6 +594,7 @@ def _generate_single_excel_output(self): outpath = os.path.join( self.excel_path_mcnp, self.testname + "_" + self.lib + ".xlsx" ) + outputs = {} #ex = ExcelOutputSheet(template, outpath) # Get results # results = [] @@ -724,7 +617,7 @@ def _generate_single_excel_output(self): self.raw_data = mcnp_output.tallydata # res, err = output.get_single_excel_data() - outputs = {} + for label in ["Value", "Error"]: # keys = {} @@ -852,9 +745,9 @@ def _generate_single_excel_output(self): self.outputs["mcnp"] = outputs # print(outputs) # Dump them for comparisons - #outpath = os.path.join(self.raw_path_mcnp, self.lib + ".pickle") - #with open(outpath, "wb") as outfile: - # pickle.dump(outputs, outfile) + raw_outpath = os.path.join(self.raw_path_mcnp, self.lib + ".pickle") + with open(raw_outpath, "wb") as outfile: + pickle.dump(outputs, outfile) # Compile general infos in the sheet #ws = ex.current_ws @@ -892,163 +785,233 @@ def _print_raw(self): def _generate_comparison_excel_output(self): # Get excel configuration + self.outputs = {} + self.results = {} + self.errors = {} + self.stat_checks = {} ex_cnf = pd.read_excel(self.cnf_path, sheet_name="Excel") ex_cnf.set_index("Tally", inplace=True) # Open the excel file - name_tag = "Generic_comparison.xlsx" - template = os.path.join(os.getcwd(), "templates", name_tag) - - mcnp_outputs = {} - iteration = 0 - for reflib, tarlib, name in self.couples: - iteration = iteration + 1 - outpath = os.path.join( - self.excel_path, - self.testname + - "_Comparison_" + - name + - ".xlsx") - ex = ExcelOutputSheet(template, outpath) - # Get results - if iteration == 1: - to_read = [reflib, tarlib] - else: - to_read = [tarlib] - - for lib in to_read: - results_path = self.test_path[lib] - - # Get mfile and outfile and possibly meshtal file - meshtalfile = None - for file in os.listdir(results_path): - if file[-1] == "m": - mfile = os.path.join(results_path, file) - elif file[-1] == "o": - ofile = os.path.join(results_path, file) - elif file[-4:] == "msht": - meshtalfile = os.path.join(results_path, file) - # Parse output - mcnp_output = MCNPoutput( - mfile, ofile, meshtal_file=meshtalfile) - mcnp_outputs[lib] = mcnp_output - - # Build the comparison - for tally in mcnp_outputs[reflib].mctal.tallies: - num = tally.tallyNumber - key = tally.tallyComment[0] + #name_tag = "Generic_comparison.xlsx" + #template = os.path.join(os.getcwd(), "templates", name_tag) - # Full tally data - tdata_ref = mcnp_outputs[reflib].tallydata[num].copy() - tdata_tar = mcnp_outputs[tarlib].tallydata[num].copy() - try: - tally_settings = ex_cnf.loc[num] - except KeyError: - print( - " Warning!: tally n." + - str(num) + - " is not in configuration") - continue - - # Re-Elaborate tdata Dataframe - x_name = tally_settings["x"] - x_tag = tally_settings["x name"] - y_name = tally_settings["y"] - y_tag = tally_settings["y name"] - ylim = tally_settings["cut Y"] - # select the index format - if x_name == "Energy": - idx_format = "0.00E+00" - # TODO all possible cases should be addressed - else: - idx_format = "0" + + if self.mcnp: + mcnp_outputs = {} + comps = {} + abs_diffs = {} + std_devs = {} + for reflib, tarlib, name in self.couples: + lib_to_comp = name + outfolder_path = self.excel_path_mcnp + outpath = os.path.join( + outfolder_path, "Comparison_" + name + "_mcnp.xlsx" + ) - if y_name != "tally": - tdata_ref.set_index(x_name, inplace=True) - tdata_tar.set_index(x_name, inplace=True) - x_set = list(set(tdata_ref.index)) - y_set = list(set(tdata_ref[y_name].values)) - rows = [] - for xval in x_set: + #ex = ExcelOutputSheet(template, outpath) + # Get results + + #for lib in to_read: + # results_path = self.test_path[lib] + for lib, results_path in { + reflib: os.path.join(self.test_path[reflib], "mcnp"), + tarlib: os.path.join(self.test_path[tarlib], "mcnp"), + }.items(): + results = [] + errors = [] + # Get mfile and outfile and possibly meshtal file + meshtalfile = None + for file in os.listdir(results_path): + if file[-1] == "m": + mfile = os.path.join(results_path, file) + elif file[-1] == "o": + ofile = os.path.join(results_path, file) + elif file[-4:] == "msht": + meshtalfile = os.path.join(results_path, file) + # Parse output + mcnp_output = MCNPoutput( + mfile, ofile, meshtal_file=meshtalfile) + mcnp_outputs[lib] = mcnp_output + # Build the comparison + for label in ["Value", "Error"]: + for tally in mcnp_outputs[reflib].mctal.tallies: + num = tally.tallyNumber + key = tally.tallyComment[0] + + # Full tally data + tdata_ref = mcnp_outputs[reflib].tallydata[num].copy() + tdata_tar = mcnp_outputs[tarlib].tallydata[num].copy() try: - ref = tdata_ref.loc[xval, "Value"].values - tar = tdata_tar.loc[xval, "Value"].values + tally_settings = ex_cnf.loc[num] + except KeyError: + print( + " Warning!: tally n." + + str(num) + + " is not in configuration") + continue + + # Re-Elaborate tdata Dataframe + x_name = tally_settings["x"] + x_tag = tally_settings["x name"] + y_name = tally_settings["y"] + y_tag = tally_settings["y name"] + ylim = tally_settings["cut Y"] + # select the index format + if label == "Value": + for dic in [comps, abs_diffs, std_devs]: + dic[num] = {"title": key, "x_label": x_tag} + + + if x_name == "Energy": + idx_format = "0.00E+00" + # TODO all possible cases should be addressed + else: + idx_format = "0" + + if y_name != "tally": + tdata_ref.set_index(x_name, inplace=True) + tdata_tar.set_index(x_name, inplace=True) + x_set = list(set(tdata_ref.index)) + y_set = list(set(tdata_ref[y_name].values)) + rows_fin = [] + rows_abs_diff = [] + rows_std_dev = [] + for xval in x_set: + try: + ref = tdata_ref.loc[xval, "Value"].values + ref_err = tdata_ref.loc[xval, "Error"].values + tar = tdata_tar.loc[xval, "Value"].values + # !!! True divide warnings are suppressed !!! + with np.errstate(divide="ignore", invalid="ignore"): + row_fin = (ref - tar) / ref + row_abs_diff = (ref - tar) + row_std_dev = row_abs_diff / (ref_err*ref) + prev_len = len(ref) + except AttributeError: + # This is raised when total values are + # collected only for one bin. + # the rest needs to be filled by nan + ref = tdata_ref.loc[xval, "Value"] + ref_err = tdata_ref.loc[xval, "Error"] + tar = tdata_tar.loc[xval, "Value"] + for i in range(prev_len - 1): + row_fin.append(np.nan) + row_abs_diff.append(np.nan) + row_std_dev.append(np.nan) + row_fin.append((ref - tar) / ref) + row_abs_diff.append(ref - tar) + row_std_dev.append((ref - tar)/(ref_err*ref)) + + rows_fin.append(row_fin) + rows_abs_diff.append(row_abs_diff) + rows_std_dev.append(row_std_dev) + try: + final = pd.DataFrame( + rows_fin, columns=y_set, index=x_set) + abs_diff = pd.DataFrame( + rows_abs_diff, columns=y_set, index=x_set) + std_dev = pd.DataFrame( + rows_std_dev, columns=y_set, index=x_set) + for df in [final, abs_diff, std_dev]: + df.index.name = x_name + df.replace(np.nan, "Not Available", inplace=True) + df.replace(float(0), "Identical", inplace=True) + df.replace(-np.inf, "Reference = 0", inplace=True) + df.replace(1, "Target = 0", inplace=True) + except ValueError: + print( + CRED + + """ + A ValueError was triggered, a probable cause may be that more than 2 binnings + are defined in tally {}. This is a fatal exception, application will now + close""".format( + str(num) + ) + + CEND + ) + # Safely exit from excel and from application + sys.exit() + + # reorder index and quick index reset + for df in [final, abs_diff, std_dev]: + df.reset_index(inplace=True) + df = self._reorder_df(df, x_name) + df.set_index(x_name, inplace=True) + comps[num][label] = final + abs_diffs[num][label] = abs_diff + std_devs[num][label] = std_dev + # insert the df in pieces + #ex.insert_cutted_df( + # "B", + # main_value_df, + # "Comparison", + # ylim, + # header=(key, "Tally n." + str(num)), + # index_name=x_tag, + # cols_name=y_tag, + # index_num_format=idx_format, + # values_format="0.00%", + #) + else: + # reorder dfs + try: + tdata_ref = self._reorder_df(tdata_ref, x_name) + except KeyError: + print( + CRED + + """ + {} is not available in tally {}. Please check the configuration file. + The application will now exit """.format( + x_name, str(num) + ) + + CEND + ) + # Safely exit from excel and from application + sys.exit() + + del tdata_ref["Error"] + tdata_ref.set_index(x_name, inplace=True) + + tdata_tar = self._reorder_df(tdata_tar, x_name) + del tdata_tar["Error"] + tdata_tar.set_index(x_name, inplace=True) + # !!! True divide warnings are suppressed !!! with np.errstate(divide="ignore", invalid="ignore"): - row = (ref - tar) / ref - prev_len = len(ref) - except AttributeError: - # This is raised when total values are - # collected only for one bin. - # the rest needs to be filled by nan - ref = tdata_ref.loc[xval, "Value"] - tar = tdata_tar.loc[xval, "Value"] - row = [] - for i in range(prev_len - 1): - row.append(np.nan) - row.append((ref - tar) / ref) - - rows.append(row) - - main_value_df = pd.DataFrame( - rows, columns=y_set, index=x_set) - main_value_df.index.name = x_name - # reorder index and quick index reset - main_value_df.reset_index(inplace=True) - main_value_df = self._reorder_df(main_value_df, x_name) - main_value_df.set_index(x_name, inplace=True) - - # insert the df in pieces - ex.insert_cutted_df( - "B", - main_value_df, - "Comparison", - ylim, - header=(key, "Tally n." + str(num)), - index_name=x_tag, - cols_name=y_tag, - index_num_format=idx_format, - values_format="0.00%", - ) - else: - # reorder dfs - tdata_ref = self._reorder_df(tdata_ref, x_name) - del tdata_ref["Error"] - tdata_ref.set_index(x_name, inplace=True) - - tdata_tar = self._reorder_df(tdata_tar, x_name) - del tdata_tar["Error"] - tdata_tar.set_index(x_name, inplace=True) - - # !!! True divide warnings are suppressed !!! - with np.errstate(divide="ignore", invalid="ignore"): - df = (tdata_ref - tdata_tar) / tdata_ref - - # Insert DF - ex.insert_df( - "B", - df, - "Comparison", - print_index=True, - header=(key, "Tally n." + str(num)), - values_format="0.00%", - ) + comp_df = (tdata_ref - tdata_tar) / tdata_ref + abs_diff_df = (tdata_ref - tdata_tar) + std_dev_df = abs_diff_df + comps[num][label] = comp_df + abs_diffs[num][label] = abs_diff_df + std_devs[num][label] = abs_diff_df + # Insert DF + #ex.insert_df( + # "B", + # df, + # "Comparison", + # print_index=True, + # header=(key, "Tally n." + str(num)), + # values_format="0.00%", + #) - # Compile general infos in the sheet - ws = ex.current_ws - title = self.testname + " RESULTS RECAP: Comparison" - ws.range("A3").value = title - ws.range("C1").value = tarlib + " Vs " + reflib - - # Add single pp sheets - for lib in [reflib, tarlib]: - cp = self.state.get_path( - "single", [lib, self.testname, "Excel"]) - file = os.listdir(cp)[0] - cp = os.path.join(cp, file) - ex.copy_sheets(cp) - - ex.save() + # Compile general infos in the sheet + #ws = ex.current_ws + #title = self.testname + " RESULTS RECAP: Comparison" + #ws.range("A3").value = title + #ws.range("C1").value = tarlib + " Vs " + reflib + + # Add single pp sheets + #for lib in [reflib, tarlib]: + # cp = self.state.get_path( + # "single", [lib, self.testname, "Excel"]) + # file = os.listdir(cp)[0] + # cp = os.path.join(cp, file) + # ex.copy_sheets(cp) + + #ex.save() + self.outputs["mcnp"] = comps + exsupp.comp_excel_writer(self, outpath, lib_to_comp, self.testname, comps, abs_diffs, std_devs) class MCNPoutput: diff --git a/jade/plotter.py b/jade/plotter.py index 81a4d76c..ef6a7e06 100644 --- a/jade/plotter.py +++ b/jade/plotter.py @@ -38,7 +38,7 @@ # ============================================================================ # Specify parameters for plots # ============================================================================ -np.seterr(divide="ignore") # Suppressing divide by zero error in plots +np.seterr(divide="ignore", invalid="ignore") # Suppressing divide by zero error in plots DEFAULT_EXTENSION = ".png" SMALL_SIZE = 22 diff --git a/jade/sphereoutput.py b/jade/sphereoutput.py index 0d2da12e..a2f1260e 100644 --- a/jade/sphereoutput.py +++ b/jade/sphereoutput.py @@ -1325,8 +1325,7 @@ def pp_excel_comparison(self): # Build the final excel data final = (comp_dfs[0].loc[newidx] - comp_dfs[1].loc[newidx]) / comp_dfs[ - 0 - ].loc[newidx] + 0].loc[newidx] absdiff = comp_dfs[0].loc[newidx] - comp_dfs[1].loc[newidx] #self.diff_data["openmc"] = final @@ -1839,7 +1838,7 @@ def sphere_comp_excel_writer(self, outpath, name, final, absdiff, std_dev, summa { "type": "cell", "criteria": "greater than", - "value": 0.2, + "value": 3, "format": red_cell_format, }, ) @@ -1851,8 +1850,8 @@ def sphere_comp_excel_writer(self, outpath, name, final, absdiff, std_dev, summa { "type": "cell", "criteria": "between", - "minimum": 0.1, - "maximum": 0.2, + "minimum": 3, + "maximum": 2, "format": orange_cell_format, }, ) @@ -1864,8 +1863,8 @@ def sphere_comp_excel_writer(self, outpath, name, final, absdiff, std_dev, summa { "type": "cell", "criteria": "between", - "minimum": 0.05, - "maximum": 0.1, + "minimum": 2, + "maximum": 1, "format": yellow_cell_format, }, ) @@ -1877,7 +1876,7 @@ def sphere_comp_excel_writer(self, outpath, name, final, absdiff, std_dev, summa { "type": "cell", "criteria": "less than", - "value": -0.2, + "value": -3, "format": red_cell_format, }, ) @@ -1889,8 +1888,8 @@ def sphere_comp_excel_writer(self, outpath, name, final, absdiff, std_dev, summa { "type": "cell", "criteria": "between", - "minimum": -0.5, - "maximum": -0.1, + "minimum": -3, + "maximum": -2, "format": orange_cell_format, }, ) @@ -1902,8 +1901,8 @@ def sphere_comp_excel_writer(self, outpath, name, final, absdiff, std_dev, summa { "type": "cell", "criteria": "between", - "minimum": -0.1, - "maximum": -0.05, + "minimum": -2, + "maximum": -1, "format": yellow_cell_format, }, ) @@ -1915,8 +1914,8 @@ def sphere_comp_excel_writer(self, outpath, name, final, absdiff, std_dev, summa { "type": "cell", "criteria": "between", - "minimum": -0.05, - "maximum": 0.05, + "minimum": -1, + "maximum": 1, "format": green_cell_format, }, ) diff --git a/jade/status.py b/jade/status.py index efc7c666..006b138d 100644 --- a/jade/status.py +++ b/jade/status.py @@ -21,28 +21,32 @@ You should have received a copy of the GNU General Public License along with JADE. If not, see . """ +from __future__ import annotations import os import re +from jade.main import Session + MULTI_TEST = [ - 'Sphere', - 'Oktavian', - 'SphereSDDR', - 'FNG', - 'Tiara-BC', - 'Tiara-BS', - 'Tiara-FC', - 'FNS-TOF', - 'FNG-BKT', - 'FNG-W', - 'ASPIS-Fe88', - 'TUD-Fe', - 'TUD-W'] -EXP_TAG = 'Exp' - - -class Status(): - def __init__(self, session): + "Sphere", + "Oktavian", + "SphereSDDR", + "FNG", + "Tiara-BC", + "Tiara-BS", + "Tiara-FC", + "FNS-TOF", + "FNG-BKT", + "FNG-W", + "ASPIS-Fe88", + "TUD-Fe", + "TUD-W", +] +EXP_TAG = "Exp" + + +class Status: + def __init__(self, session: Session) -> None: """ Stores the state of the JADE runs and post-processing. @@ -70,14 +74,14 @@ def __init__(self, session): self.comparison_tree, self.single_tree = self.update_pp_status() # Updated by S. Bradnam to include new level, code, between test and zaid. - def update_run_status(self): + def update_run_status(self) -> dict: """ Read/Update the run tree status. All files produced by runs are registered Returns ------- - libraries : dic + libraries : dict dictionary of dictionaries representing the run tree """ @@ -115,17 +119,17 @@ def update_run_status(self): return libraries # Updated by S. Bradnam, UKAEA to include new level, code. - def update_pp_status(self) -> tuple: + def update_pp_status(self) -> tuple[dict, dict]: """ Read/Update the post processing tree status. All files produced by post processing registered Returns ------- - comparison_tree : dic + comparison_tree : dict Dictionary registering all test post processed for each comparison of libraries. - single_tree : dic + single_tree : dict Dictionary registering all test post processed performed for single libraries. @@ -160,7 +164,7 @@ def update_pp_status(self) -> tuple: return comparison_tree, single_tree - def get_path(self, tree: str, itinerary: list) -> str: + def get_path(self, tree: str, itinerary: list[str]) -> str | os.PathLike: """ Get the resulting path of an itinery on one tree @@ -168,7 +172,7 @@ def get_path(self, tree: str, itinerary: list) -> str: ---------- tree : str Either 'comparison', 'single', or 'run'. - itinerary : list + itinerary : list[str] list of strings representing the step to take inside the tree. Raises @@ -178,7 +182,7 @@ def get_path(self, tree: str, itinerary: list) -> str: Returns ------- - cp : str/path + cp : str | os.PathLike path to final step. """ @@ -200,7 +204,9 @@ def get_path(self, tree: str, itinerary: list) -> str: return cp - def get_unfinished_zaids(self, lib) -> tuple: + def get_unfinished_zaids( + self, lib: str + ) -> tuple[dict[str, list], str | os.PathLike] | None: """ Identify zaids to run for rerun or continuation purposes @@ -211,8 +217,10 @@ def get_unfinished_zaids(self, lib) -> tuple: Returns ------- - unfinished : list - zaids/typical materials not run. + unfinished : dict[str, list] + list of zaids/typical materials not run for each code. + motherdir : str | os.PathLike + root of test folder. """ @@ -236,12 +244,12 @@ def get_unfinished_zaids(self, lib) -> tuple: return unfinished, motherdir - def check_test_run(self, files: list, code: str) -> bool: + def check_test_run(self, files: list[str], code: str) -> bool: """Check if a test was run successfully for the specified code. Parameters ---------- - files : list + files : list[str] filenames inside the test folder code : str Transport code @@ -261,13 +269,13 @@ def check_test_run(self, files: list, code: str) -> bool: return flag_run_test - def _check_test_mcnp(self, files: list) -> bool: + def _check_test_mcnp(self, files: list[str]) -> bool: """ Check if a test has been run Parameters ---------- - files : list + files : list[str] file names inside test folder. Returns @@ -285,12 +293,12 @@ def _check_test_mcnp(self, files: list) -> bool: return flag_run_test - def _check_test_serpent(self, files: list) -> bool: + def _check_test_serpent(self, files: list[str]) -> bool: """Checks to see if Serpent simualtion has been run. Parameters ---------- - files : list + files : list[str] file names inside test folder. Returns @@ -306,12 +314,12 @@ def _check_test_serpent(self, files: list) -> bool: flag_run_test = True return flag_run_test - def _check_test_openmc(self, files: list) -> bool: + def _check_test_openmc(self, files: list[str]) -> bool: """Checks to see if OpenMC simualtion has been run. Parameters ---------- - files : list + files : list[str] file names inside test folder. Returns @@ -328,7 +336,7 @@ def _check_test_openmc(self, files: list) -> bool: return flag_run_test # TODO checking for multiple codes - def check_override_run(self, lib, session, exp=False): + def check_override_run(self, lib: str, session: Session, exp: bool = False) -> bool: """ Check status of the requested run. If overridden is required permission is requested to the user @@ -395,12 +403,7 @@ def check_override_run(self, lib, session, exp=False): return ans - def check_lib_run( - self, - lib, - session, - config_option="Run", - exp=False) -> dict: + def check_lib_run(self, lib, session, config_option="Run", exp=False) -> dict: """ Check if a library has been run. To be considered run a meshtally or meshtal have to be produced (for MCNP). Only active benchmarks (specified in @@ -460,8 +463,7 @@ def check_lib_run( exps = self.run_tree[lib][testname] for experiment, codes in exps.items(): for code, files in codes.items(): - flag_run_zaid = self.check_test_run( - files, code) + flag_run_zaid = self.check_test_run(files, code) if flag_run_zaid: flag_test_run = True if flag_test_run: @@ -473,8 +475,7 @@ def check_lib_run( if testname in MULTI_TEST: flag_test_run = False for zaid, files in test.items(): - flag_run_zaid = self.check_test_run( - files, code) + flag_run_zaid = self.check_test_run(files, code) if flag_run_zaid: flag_test_run = True if flag_test_run: @@ -518,9 +519,7 @@ def check_pp_single(self, lib, session, tree="single", exp=False): """ self.update_pp_status() - trees = { - "single": self.single_tree, - "comparison": self.comparison_tree} + trees = {"single": self.single_tree, "comparison": self.comparison_tree} try: library_tests = trees[tree][lib] to_pp = session.check_active_tests("Post-Processing", exp=exp) @@ -582,8 +581,7 @@ def check_override_pp(self, session, exp=False): # Check if libraries have been run flag_not_run = False for lib in libs: - test_run = self.check_lib_run( - lib, session, "Post-Processing", exp=exp) + test_run = self.check_lib_run(lib, session, "Post-Processing", exp=exp) if len(test_run) == 0: # TODO not checking for each benchmark flag_not_run = True lib_not_run = lib @@ -613,8 +611,7 @@ def check_override_pp(self, session, exp=False): You can manage the selection of benchmarks in the Config.xlsx file. """ ) - i = input( - " Would you like to override the results?(y/n) ") + i = input(" Would you like to override the results?(y/n) ") if i == "y": ans = True logtext = ( @@ -656,8 +653,7 @@ def check_override_pp(self, session, exp=False): A comparison for these libraries was already performed. """ ) - i = input( - " Would you like to override the results?(y/n) ") + i = input(" Would you like to override the results?(y/n) ") if i == "y": ans = True logtext = ( diff --git a/jade/testrun.py b/jade/testrun.py index 9107feb9..d8faaa43 100644 --- a/jade/testrun.py +++ b/jade/testrun.py @@ -103,9 +103,6 @@ def __init__(self, inp, lib, config, log, confpath, runoption): # Path variables self.run_dir = None - # self.serpent_dir = None - # self.openmc_dir = None - # self.d1s_dir = None config = config.dropna() @@ -136,25 +133,13 @@ def __init__(self, inp, lib, config, log, confpath, runoption): except KeyError: self.d1s = False - """ - # Chek for valid code - code = config['Code'] - if code not in CODE_TAGS.keys(): - raise ValueError(code+' is not an admissible value for code.\n' + - 'Please double check the configuration file.') - else: - self.code = code # transport code to be used for the benchmark - """ # Generate input file template according to transport code if self.d1s: - d1s_ipt = os.path.join(inp, "d1s", self.name + ".i") + d1s_ipt = os.path.join(inp, "d1s", os.path.basename(inp) + ".i") self.d1s_inp = ipt.D1S5_InputFile.from_text(d1s_ipt) - # It also have additional files then that must be in the - # VRT folder (irradiation and reaction files) - # To change with revised folder structure - removed VRT. - irrfile = os.path.join(VRTpath, self.d1s_inp.name, self.inp.name + "_irrad") + irrfile = os.path.join(inp, "d1s", os.path.basename(inp) + "_irrad") reacfile = os.path.join( - VRTpath, self.d1s_inp.name, self.d1s_inp.name + "_react" + inp, "d1s", os.path.basename(inp) + "_react" ) try: self.irrad = IrradiationFile.from_text(irrfile) @@ -163,17 +148,11 @@ def __init__(self, inp, lib, config, log, confpath, runoption): self.log.adjourn( "d1S irradition and reaction files not found, skipping..." ) - # For instance in sphere test they are not provided - # There may be reasons why these files are not provided, it is - # responsability of the user to make them available or not. - # self.irrad = None - # self.react = None + self.name = self.d1s_inp.name if self.mcnp: mcnp_ipt = os.path.join(inp, "mcnp", os.path.basename(inp) + ".i") self.mcnp_inp = ipt.InputFile.from_text(mcnp_ipt) self.name = self.mcnp_inp.name - # self.irrad = None - # self.react = None if self.serpent: serpent_ipt = os.path.join(inp, "serpent", os.path.basename(inp) + ".i") self.serpent_inp = ipt.SerpentInputFile.from_text(serpent_ipt) @@ -181,37 +160,6 @@ def __init__(self, inp, lib, config, log, confpath, runoption): openmc_ipt = os.path.join(inp, "openmc") self.openmc_inp = ipt.OpenMCInputFiles.from_path(openmc_ipt) - # Need to add this back if user only running MCNP - # Add the stop card according to config - """ - config = config.dropna() - try: - nps = config['NPS cut-off'] - except KeyError: - nps = None - if nps is np.nan: - nps = None - try: - ctme = config['CTME cut-off'] - except KeyError: - ctme = None - if ctme is np.nan: - ctme = None - try: - tally = config['Relative Error cut-off'].split('-')[0] - error = config['Relative Error cut-off'].split('-')[1] - precision = (tally, error) - except KeyError: - precision = None - - self.nps = nps - self.ctme = ctme - self.precision = precision - - # Directory where the MCNP run will be performed - self.MCNPdir = None - """ - def _translate_input(self, lib, libmanager): """ Translate the input template to selected library @@ -236,7 +184,6 @@ def _translate_input(self, lib, libmanager): add = self.d1s_inp.translate( lib, libmanager, - "d1s", original_irradfile=self.irrad, original_reacfile=self.react, ) @@ -277,8 +224,6 @@ def generate_test(self, lib_directory, libmanager, run_dir=None): self._translate_input(self.lib, libmanager) # Add stop card - # Need to retain adding ctme and precision for MCNP - # self.inp.add_stopCard(self.nps, self.ctme, self.precision) if self.d1s: self.d1s_inp.add_stopCard(self.nps) if self.mcnp: @@ -301,25 +246,20 @@ def generate_test(self, lib_directory, libmanager, run_dir=None): shutil.rmtree(motherdir) os.mkdir(motherdir) - # edits_file = os.path.join(directoryVRT, 'inp_edits.txt') - # ww_file = os.path.join(directoryVRT, 'wwinp') - # if os.path.exists(directoryVRT): - # # This was tested only for sphere... be careful - # self.inp.add_edits(edits_file) # Add variance reduction - # Allow space for personalization getting additional modification self.custom_inp_modifications() if self.d1s: - os.mkdir(os.path.join(motherdir, "d1s")) - outinpfile = os.path.join(motherdir, "d1s", testname) + d1s_dir = os.path.join(motherdir, "d1s") + os.mkdir(d1s_dir) + outinpfile = os.path.join(d1s_dir, testname) self.d1s_inp.write(outinpfile) # And accessory files if needed if self.irrad is not None: - self.irrad.write(motherdir, "d1s") + self.irrad.write(d1s_dir) if self.react is not None: - self.react.write(motherdir, "d1s") - # Get VRT files if available + self.react.write(d1s_dir) + # Get WW files if available wwinp = os.path.join(self.original_inp, "d1s", "wwinp") if os.path.exists(wwinp): outfile = os.path.join(motherdir, "d1s", "wwinp") @@ -336,30 +276,13 @@ def generate_test(self, lib_directory, libmanager, run_dir=None): shutil.copyfile(wwinp, outfile) if self.serpent: - # Impliment serpent outputfile generation here + # Implement serpent outputfile generation here pass if self.openmc: - # Impliment openmc outputfile generation here + # Implement openmc outputfile generation here pass - """ - # Write new input file - outinpfile = os.path.join(motherdir, testname) - self.inp.write(outinpfile) - # And accessory files if needed - if self.irrad is not None: - self.irrad.write(motherdir) - if self.react is not None: - self.react.write(motherdir) - - # Get VRT files if available - wwinp = os.path.join(self.path_VRT, testname, 'wwinp') - if os.path.exists(wwinp): - outfile = os.path.join(motherdir, 'wwinp') - shutil.copyfile(wwinp, outfile) - """ - def custom_inp_modifications(self): """ Perform additional operation on the input before generation. In this @@ -482,8 +405,118 @@ def job_submission( config.batch_system + " " + job_script, cwd=directory, shell=True ) - def run_d1s(self, config, libmanager, name, directory): - pass + def run_d1s( + self, + config, + lib_manager, + name: str, + directory: Path, + runoption: str, + timeout=None, + ) -> bool: + """Run D1S simulation either on the command line or submitted as a job. + + Parameters + ---------- + config : + Configuration settings + lib_manager : + libmanager + name : str + Name of the simulation + directory : str, path + Directory where the simulation will be executed + runoption: str + Whether JADE run in parallel or command line + timeout : float, optional + Maximum time to wait for simulation of complete, by default None + + Returns + ------- + bool + Flag if simulation not run + """ + + # Calculate MPI tasks and OpenMP threads + mpi_tasks = int(config.openmp_threads) * int(config.mpi_tasks) + omp_threads = 1 + run_mpi = False + if mpi_tasks > 1: + run_mpi = True + + executable = config.d1s_exec + env_variables = config.d1s_config + inputstring = "i=" + name + outputstring = "n=" + name + + #TODO change for D1S + if isinstance(self.lib, dict): + lib = list(self.lib.values())[0] + elif isinstance(self.lib, str): + lib = self.lib + + xsstring = "xs=" + str(lib_manager.data["mcnp"][lib].filename) + + if run_mpi: + run_command = [ + "mpirun", + "-n", + str(mpi_tasks), + executable, + inputstring, + outputstring, + xsstring, + ] + else: + run_command = [executable, inputstring, outputstring, xsstring] + + flagnotrun = False + + try: + cwd = os.getcwd() + os.chdir(directory) + # cancel eventual previous output file + outputfile = name + ".o" + if os.path.exists(outputfile): + os.remove(outputfile) + + # check if runtpe exists + runtpe = name + ".r" + if os.path.exists(runtpe): + command = command + " runtpe=" + name + ".r" + + if runoption.lower() == "c": + try: + if not sys.platform.startswith("win"): + unix.configure(env_variables) + print(" ".join(run_command)) + subprocess.run( + " ".join(run_command), cwd=directory, shell=True, timeout=43200 + ) + + except subprocess.TimeoutExpired: + print( + "Sesion timed out after 12 hours. Consider submitting as a job." + ) + flagnotrun = True + + elif runoption.lower() == "s": + # Run MCNP as a job + cwd = os.getcwd() + os.chdir(directory) + self.job_submission( + config, + directory, + run_command, + mpi_tasks, + omp_threads, + env_variables, + ) + os.chdir(cwd) + except subprocess.TimeoutExpired: + pass + + return flagnotrun def run_mcnp( self, @@ -832,7 +865,10 @@ def generate_test(self, directory, libmanager, limit=None, lib=None): zaids = libmanager.get_libzaids(lib, "mcnp") # testname = self.inp.name - testname = "Sphere" + if self.d1s: + testname = "SphereSDDR" + else: + testname = "Sphere" motherdir = os.path.join(directory, testname) # If previous results are present they are canceled @@ -875,42 +911,12 @@ def generate_test(self, directory, libmanager, limit=None, lib=None): else: nps = self.nps - # if self.ctme is None: - # ctme = settings.loc[Z, 'CTME cut-off'] - # if ctme is np.nan: - # ctme = None - # else: - # ctme = self.ctme - # - # if self.precision is None: - # prec = settings.loc[Z, 'Relative Error cut-off'] - # if prec is np.nan: - # precision = None - # else: - # tally = prec.split('-')[0] - # error = prec.split('-')[1] - # precision = (tally, error) - # else: - # precision = self.precision - # Zaid local settings are prioritized else: nps = settings.loc[Z, "NPS cut-off"] if nps is np.nan: nps = None - # ctme = settings.loc[Z, 'CTME cut-off'] - # if ctme is np.nan: - # ctme = None - # - # prec = settings.loc[Z, 'Relative Error cut-off'] - # if prec is np.nan: - # precision = None - # else: - # tally = prec.split('-')[0] - # error = prec.split('-')[1] - # precision = (tally, error) - self.generate_zaid_test( zaid, libmanager, testname, motherdir, -1 * density, nps ) @@ -925,9 +931,6 @@ def generate_test(self, directory, libmanager, limit=None, lib=None): material, -1 * density, libmanager, testname, motherdir ) - # def generate_zaid_test(self, zaid, libmanager, testname, motherdir, - # density, nps, ctme, precision, addtag=None, - # parentlist=None, lib=None): def generate_zaid_test( self, zaid, @@ -957,10 +960,6 @@ def generate_zaid_test( Density value for the sphere. nps : float number of particles cut-off - ctme : float - computer time cut-off - precision : float - precision cut-off addtag : str, optional add tag at the end of the single zaid test name. The default is None @@ -978,15 +977,10 @@ def generate_zaid_test( # Adjourn the material cards for the zaid zaid = mat.Zaid(1, zaid[:-3], zaid[-3:], lib) name, formula = libmanager.get_zaidname(zaid) - if self.d1s: - # Add d1s function here - pass - - if self.mcnp: # Retrieve wwinp & other misc files if they exist directoryVRT = os.path.join( - self.path_VRT, "mcnp", zaid.element + zaid.isotope + self.path_VRT, "d1s", zaid.element + zaid.isotope ) edits_file = os.path.join(directoryVRT, "inp_edits.txt") ww_file = os.path.join(directoryVRT, "wwinp") @@ -996,19 +990,49 @@ def generate_zaid_test( matlist = mat.MatCardsList([material]) # Generate the new input - newinp = deepcopy(self.mcnp_inp) + newinp = deepcopy(self.d1s_inp) newinp.matlist = matlist # Assign material # adjourn density newinp.change_density(density) # assign stop card - newinp.add_stopCard(nps) # , ctme, precision) + newinp.add_stopCard(nps) # add PIKMT if requested if parentlist is not None: newinp.add_PIKMT_card(parentlist) - # if os.path.exists(directoryVRT): - # newinp.add_edits(edits_file) # Add variance reduction + # Write new input file + outfile, outdir = self._get_zaidtestname( + testname, zaid, formula, addtag=addtag + ) + outpath = os.path.join(motherdir, "d1s", outdir) + os.mkdir(outpath) + outinpfile = os.path.join(outpath, outfile) + newinp.write(outinpfile) + # Copy also wwinp file + if os.path.exists(directoryVRT): + outwwfile = os.path.join(outpath, "wwinp") + shutil.copyfile(ww_file, outwwfile) + + if self.mcnp: + # Retrieve wwinp & other misc files if they exist + directoryVRT = os.path.join( + self.path_VRT, "mcnp", zaid.element + zaid.isotope + ) + edits_file = os.path.join(directoryVRT, "inp_edits.txt") + ww_file = os.path.join(directoryVRT, "wwinp") + # Create MCNP material card + submat = mat.SubMaterial("M1", [zaid], header="C " + name + " " + formula) + material = mat.Material([zaid], None, "M1", submaterials=[submat]) + matlist = mat.MatCardsList([material]) + + # Generate the new input + newinp = deepcopy(self.mcnp_inp) + newinp.matlist = matlist # Assign material + # adjourn density + newinp.change_density(density) + # assign stop card + newinp.add_stopCard(nps) # Write new input file outfile, outdir = self._get_zaidtestname( testname, zaid, formula, addtag=addtag @@ -1122,7 +1146,40 @@ def generate_material_test( truename = material.name if self.d1s: - # Add d1s function here + # Retrieve wwinp & other misc files if they exist + directoryVRT = os.path.join(self.path_VRT, "d1s", truename) + edits_file = os.path.join(directoryVRT, "inp_edits.txt") + ww_file = os.path.join(directoryVRT, "wwinp") + newmat = deepcopy(material) + # Translate and assign the material + newmat.translate(lib, libmanager, "mcnp") + newmat.header = material.header + "C\nC True name:" + truename + newmat.name = "M1" + matlist = mat.MatCardsList([newmat]) + + # Generate the new input + newinp = deepcopy(self.d1s_inp) + newinp.matlist = matlist # Assign material + # adjourn density + newinp.change_density(density) + # add stop card + newinp.add_stopCard(self.nps) + # Add PIKMT card if required + if parentlist is not None: + newinp.add_PIKMT_card(parentlist) + + # Write new input file + outfile = testname + "_" + truename + "_" + outdir = testname + "_" + truename + outpath = os.path.join(motherdir, "d1s", outdir) + os.mkdir(outpath) + outinpfile = os.path.join(outpath, outfile) + newinp.write(outinpfile) + + # Copy also wwinp file + if os.path.exists(directoryVRT): + outwwfile = os.path.join(outpath, "wwinp") + shutil.copyfile(ww_file, outwwfile) pass if self.mcnp: @@ -1143,14 +1200,11 @@ def generate_material_test( # adjourn density newinp.change_density(density) # add stop card - newinp.add_stopCard(self.nps) # , self.ctme, self.precision) + newinp.add_stopCard(self.nps) # Add PIKMT card if required if parentlist is not None: newinp.add_PIKMT_card(parentlist) - # if os.path.exists(directoryVRT): - # newinp.add_edits(edits_file) # Add variance reduction - # Write new input file outfile = testname + "_" + truename + "_" outdir = testname + "_" + truename @@ -1257,7 +1311,6 @@ def run(self, config, libmanager, runoption: str) -> None: ) -# Fix from here class SphereTestSDDR(SphereTest): def __init__(self, *args, **keyargs): super().__init__(*args, **keyargs) @@ -1272,7 +1325,7 @@ def generate_test(self, directory, libmanager, limit=None, lib=None): ) def generate_zaid_test( - self, zaid, libmanager, testname, motherdir, density, nps, ctme, precision + self, zaid, libmanager, testname, motherdir, density, nps ): """ Generate input for a single zaid sphere SDDR benchmark run. @@ -1293,10 +1346,6 @@ def generate_zaid_test( Density value for the sphere. nps : float number of particles cut-off - ctme : float - computer time cut-off - precision : float - precision cut-off Returns ------- @@ -1318,8 +1367,6 @@ def generate_zaid_test( motherdir, density, nps, - ctme, - precision, addtag=MT, parentlist=[zaid], lib=self.activationlib, @@ -1503,7 +1550,7 @@ def _generate_irradiation_file(self, daughters): print( CORANGE + """ - Warning: irradiations schedules were not find for all specified daughters. + Warning: irradiation schedules were not found for all specified daughters. """ + CEND ) @@ -1519,10 +1566,10 @@ class FNGTest(Test): def custom_inp_modifications(self): # Add the tracking for daughters in tally 14 zaids = self.irrad.get_daughters() - self.inp.add_track_contribution("F14:p", zaids, who="daughter") + self.d1s_inp.add_track_contribution("F14:p", zaids, who="daughter") # Add the tracking for daughters in tally 24 zaids = self.react.get_parents() - self.inp.add_track_contribution("F24:p", zaids, who="parent") + self.d1s_inp.add_track_contribution("F24:p", zaids, who="parent") class MultipleTest: diff --git a/jade/xsdirpyne.py b/jade/xsdirpyne.py index 0ca81e35..f9cc7bea 100644 --- a/jade/xsdirpyne.py +++ b/jade/xsdirpyne.py @@ -139,22 +139,27 @@ def read(self): self.tables.append(table) # All tables have at least 7 attributes - table.name = words[0] - table.awr = float(words[1]) - table.filename = words[2] - table.access = words[3] - table.filetype = int(words[4]) - table.address = int(words[5]) - table.tablelength = int(words[6]) - - if len(words) > 7: - table.recordlength = int(words[7]) - if len(words) > 8: - table.entries = int(words[8]) - if len(words) > 9: - table.temperature = float(words[9]) - if len(words) > 10: - table.ptable = (words[10] == 'ptable') + try: + table.name = words[0] + table.awr = float(words[1]) + table.filename = words[2] + table.access = words[3] + table.filetype = int(words[4]) + table.address = int(words[5]) + table.tablelength = int(words[6]) + + if len(words) > 7: + table.recordlength = int(words[7]) + if len(words) > 8: + table.entries = int(words[8]) + if len(words) > 9: + table.temperature = float(words[9]) + if len(words) > 10: + table.ptable = (words[10] == 'ptable') + except ValueError: + problem_line = words[0] + print("Error reading line corresponding to {}, passing for now, please adjust XSDIR file".format(problem_line)) + pass def find_table(self, name, mode='default'): """Find all tables for a given ZIAD. diff --git a/templates/AtlasTemplate.docx b/templates/AtlasTemplate.docx deleted file mode 100644 index a0572897..00000000 Binary files a/templates/AtlasTemplate.docx and /dev/null differ diff --git a/tests/libmanager_test.py b/tests/libmanager_test.py index d1119f6a..ab840d70 100644 --- a/tests/libmanager_test.py +++ b/tests/libmanager_test.py @@ -36,10 +36,9 @@ from jade.matreader import Zaid -ACTIVATION_FILE = os.path.join(cp, 'TestFiles', 'libmanager', - 'Activation libs.xlsx') -XSDIR_FILE = os.path.join(cp, 'TestFiles', 'libmanager', 'xsdir') -ISOTOPES_FILE = os.path.join(root, 'jade', 'resources', 'Isotopes.txt') +ACTIVATION_FILE = os.path.join(cp, "TestFiles", "libmanager", "Activation libs.xlsx") +XSDIR_FILE = os.path.join(cp, "TestFiles", "libmanager", "xsdir") +ISOTOPES_FILE = os.path.join(root, "jade", "resources", "Isotopes.txt") class TestLibManger: @@ -47,75 +46,89 @@ class TestLibManger: @pytest.fixture def lm(self): df_rows = [ - ['99c', 'sda', '', XSDIR_FILE], - ['98c', 'acsdc', '', XSDIR_FILE], - ['21c', 'adsadsa', '', XSDIR_FILE], - ['31c', 'adsadas', '', XSDIR_FILE], - ['00c', 'sdas', 'yes', XSDIR_FILE], - ['71c', 'sdasxcx', '', XSDIR_FILE]] + ["99c", "sda", "", XSDIR_FILE], + ["98c", "acsdc", "", XSDIR_FILE], + ["21c", "adsadsa", "", XSDIR_FILE], + ["31c", "adsadas", "", XSDIR_FILE], + ["00c", "sdas", "yes", XSDIR_FILE], + ["71c", "sdasxcx", "", XSDIR_FILE], + ] df_lib = pd.DataFrame(df_rows) - df_lib.columns = ['Suffix', 'Name', 'Default', 'MCNP'] + df_lib.columns = ["Suffix", "Name", "Default", "MCNP"] - return LibManager(df_lib, activationfile=ACTIVATION_FILE, - isotopes_file=ISOTOPES_FILE) + return LibManager( + df_lib, activationfile=ACTIVATION_FILE, isotopes_file=ISOTOPES_FILE + ) + + def test_available_libs(self, lm: LibManager): + """ + Test the ability to recover the available libraries + """ + libs = lm.libraries["mcnp"] + assert "99c" in libs + assert "98c" in libs + assert "21c" in libs + assert "31c" in libs + assert "00c" in libs + assert "71c" in libs def test_reactionfilereading(self, lm): - assert len(lm.reactions['99c']) == 100 - assert len(lm.reactions['98c']) == 34 + assert len(lm.reactions["99c"]) == 100 + assert len(lm.reactions["98c"]) == 34 def test_get_reactions1(self, lm): """ Test ability to recover reactions for parent zaid (one) """ - parent = '9019' - reaction = lm.get_reactions('99c', parent)[0] - assert reaction[0] == '16' - assert reaction[1] == '9018' + parent = "9019" + reaction = lm.get_reactions("99c", parent)[0] + assert reaction[0] == "16" + assert reaction[1] == "9018" def test_get_reactions2(self, lm): """ Test ability to recover reactions for parent zaid (multiple) """ - parent = '11023' - reactions = lm.get_reactions('99c', parent) + parent = "11023" + reactions = lm.get_reactions("99c", parent) print(reactions) reaction1 = reactions[0] reaction2 = reactions[1] - assert reaction1[0] == '16' - assert reaction1[1] == '11022' - assert reaction2[0] == '102' - assert reaction2[1] == '11024' + assert reaction1[0] == "16" + assert reaction1[1] == "11022" + assert reaction2[0] == "102" + assert reaction2[1] == "11024" def test_formula_conversion(self, lm): """ Test the abilty to switch between isotopes formulas and zaid number """ - tests = ['N15', 'Er164', 'Kr83'] - finals = ['N-15', 'Er-164', 'Kr-83'] + tests = ["N15", "Er164", "Kr83"] + finals = ["N-15", "Er-164", "Kr-83"] for test, final in zip(tests, finals): conversion = lm.get_zaidnum(test) name, formula = lm.get_zaidname(conversion) assert final == formula - def test_check4zaid(self, lm): + def test_check4zaid(self, lm: LibManager): """ Correctly checks availability of zaids """ - zaid = '1001' + zaid = "1001" libs = lm.check4zaid(zaid) assert len(libs) > 1 assert len(libs[0]) == 3 - zaid = '1010' + zaid = "1010" assert len(lm.check4zaid(zaid)) == 0 - def test_convertZaid(self, lm): + def test_convertZaid(self, lm: LibManager): # --- Exception if library is not available --- try: - zaid = '1001' - lib = '44c' + zaid = "1001" + lib = "44c" lm.convertZaid(zaid, lib) assert False except ValueError: @@ -123,44 +136,40 @@ def test_convertZaid(self, lm): # --- Natural zaid --- # 1 to 1 - zaid = '12000' - lib = '21c' + zaid = "12000" + lib = "21c" translation = lm.convertZaid(zaid, lib) assert translation == {zaid: (lib, 1, 1)} # expansion - lib = '31c' + lib = "31c" translation = lm.convertZaid(zaid, lib) assert len(translation) == 3 # not available in the requested lib but available in default - # not available - # try: - zaid = '84000' + # available only in the default library + zaid = "84000" translation = lm.convertZaid(zaid, lib) - translation['84209'][0] == '00c' - # assert False - # except ValueError: - # assert True + assert translation["84209"][0] == "00c" # --- 1 to 1 --- - zaid = '1001' + zaid = "1001" translation = lm.convertZaid(zaid, lib) assert translation == {zaid: (lib, 1, 1)} # --- absent --- # Use the natural zaid - zaid = '12024' - lib = '21c' + zaid = "12024" + lib = "21c" translation = lm.convertZaid(zaid, lib) - assert translation == {'12000': (lib, 1, 1)} + assert translation == {"12000": (lib, 1, 1)} # zaid available in default or other library - zaid = '84210' + zaid = "84210" translation = lm.convertZaid(zaid, lib) assert translation[zaid][0] != lib # zaid does not exist or not available in any library - zaid = '84200' + zaid = "84200" try: translation = lm.convertZaid(zaid, lib) assert False @@ -169,46 +178,46 @@ def test_convertZaid(self, lm): def test_get_libzaids(self, lm): - lib = '21c' + lib = "21c" zaids = lm.get_libzaids(lib) assert len(zaids) == 76 - assert zaids[0] == '1001' + assert zaids[0] == "1001" def test_get_zaidname(self, lm): - zaid = '1001' + zaid = "1001" name, formula = lm.get_zaidname(zaid) - assert name == 'hydrogen' - assert formula == 'H-1' + assert name == "hydrogen" + assert formula == "H-1" - zaid = '1000' + zaid = "1000" name, formula = lm.get_zaidname(zaid) - assert name == 'hydrogen' - assert formula == 'H-0' + assert name == "hydrogen" + assert formula == "H-0" def test_get_zaidnum(self, lm): - zaid = '92235' + zaid = "92235" try: zaidnum = lm.get_zaidnum(zaid) assert False except ValueError: assert True - zaid = 'U235' + zaid = "U235" zaidnum = lm.get_zaidnum(zaid) - assert zaidnum == '92235' + assert zaidnum == "92235" def test_select_lib(self, monkeypatch, lm): # monkeypatch the "input" function # Good trials - for lib in ['31c', '{"21c": "31c", "00c": "71c"}', '21c-31c']: - monkeypatch.setattr('builtins.input', lambda _: lib) + for lib in ["31c", '{"21c": "31c", "00c": "71c"}', "21c-31c"]: + monkeypatch.setattr("builtins.input", lambda _: lib) selectedlib = lm.select_lib() assert selectedlib == lib # Not found - for lib in ['44c', '{"21c": "44c", "44c": "71c"}', '21c-44c']: - monkeypatch.setattr('builtins.input', lambda _: lib) + for lib in ["44c", '{"21c": "44c", "44c": "71c"}', "21c-44c"]: + monkeypatch.setattr("builtins.input", lambda _: lib) try: selectedlib = lm.select_lib() print(lib) @@ -218,12 +227,12 @@ def test_select_lib(self, monkeypatch, lm): def test_get_zaid_mass(self, lm): # Normal zaid - zaid = '99235.31c -1' + zaid = "99235.31c -1" zaid = Zaid.from_string(zaid) mass = lm.get_zaid_mass(zaid) assert mass == 252.08298 # Natural zaid - zaid = '8000.21c 1' + zaid = "8000.21c 1" zaid = Zaid.from_string(zaid) mass = lm.get_zaid_mass(zaid) assert mass == 15.99937442590581