relap-py 0.0.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,7 @@
1
+ Metadata-Version: 2.1
2
+ Name: relap_py
3
+ Version: 0.0.1
4
+ Summary: Module for RELAP post-processing
5
+ Author: Jordi Freixa
6
+ Author-email: <jordi.freixa-terradas@upc.edu>
7
+ Keywords: relap,trace
File without changes
@@ -0,0 +1,29 @@
1
+ from .main import (
2
+ relapwin_loc,
3
+ relap_exe,
4
+ figures_type,
5
+ figures_loc,
6
+ hideplots,
7
+ show_plot,
8
+ exp_file_bool,
9
+ unc_bands,
10
+ hello,
11
+ make_strip,
12
+ read_stripf_df,
13
+ read_stripf,
14
+ run_strip,
15
+ extract_data,
16
+ extract_df,
17
+ plot_var,
18
+ plot_all,
19
+ plot,
20
+ general_fig,
21
+ plot_variables,
22
+ append_variable,
23
+ read_exp,
24
+ print_ss,
25
+ mkdir,
26
+ mypie
27
+ )
28
+
29
+
@@ -0,0 +1,1086 @@
1
+ def hello():
2
+ print('this is RELAP_py package')
3
+
4
+ """
5
+ Title: RELAP utilities
6
+ created: May 2020
7
+ last modified: 02/11/2020 20:52:47
8
+ Version: 3.1
9
+ Created by: Jordi Freixa
10
+ Description: This Module provides function tools for postprocessing RELAP data
11
+
12
+ INSTALLATION:
13
+ - put the file in the site-package folder
14
+ mine is in ~/Anaconda3/Lib/side-packages/
15
+ - modify the relapwin_loc and relap_exe variables to your environment
16
+
17
+
18
+ TODO:
19
+ - adapt to TRACE plotting (basically reading data from csv files)
20
+ - Make steady state table
21
+ - read and plot uncertainty bands
22
+ - just perform data extraction and write to file
23
+ """
24
+ import pandas as pd
25
+ import numpy as np
26
+ import matplotlib.pyplot as plt
27
+ import os
28
+ from subprocess import Popen, PIPE
29
+ from numpy.lib.recfunctions import append_fields
30
+
31
+ relapwin_loc = 'C:/cygwin64/usr/local/bin'
32
+ relap_exe = 'relap5-33iy-win32-ifc-opt.exe'
33
+ """
34
+ Defaults
35
+ :figures_type: (otional) figures format: pdf or png
36
+ :figures_loc: (optional) location where the figures will be saved
37
+ :hideplots: (optional) hideplots? True or False (could be deleted)
38
+ :show_plot: (optional) show interactive python plot window?
39
+ :exp_file_bool: (optional) is there a experimental file?
40
+ :unc_bands: (optional) is there a uncertainty file?
41
+ """
42
+ figures_type = 'pdf'
43
+ figures_loc = './figures/'
44
+ hideplots = True
45
+ show_plot = False
46
+ exp_file_bool = False
47
+ unc_bands = False
48
+
49
+ #▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄
50
+ relap_labels = {
51
+ "count": "Current attempted advancement count number",
52
+ "cputime": "CPU time(s)",
53
+ "dt": "Current time step (s)",
54
+ "dtcrnt": "Current Courant time step (s)",
55
+ "emass": "Estimate of mass error in all the systems (kg)",
56
+ "errmax": "Current estimate of the truncation mass error fraction",
57
+ "extsnn": "Extra system variables where NN goes from 01 to 20",
58
+ "maxvme": "Maximum value of all the individual volume mass errors (kg)",
59
+ "null": "Specifies null field",
60
+ "rktpow3d": "Total reactor power for the RELAP5/PARCS 3-D kinetics coupled code (W)",
61
+ "stdtrn": "Steady-state/transient flag",
62
+ "sysmer": "Estimate of mass error in system N (kg)",
63
+ "sysmerb": "Estimate of boron mass error in system N (kg)",
64
+ "sysmerf": "Estimate of liquid mass error in system N (kg)",
65
+ "sysmerg": "Estimate of vapor mass error in system N (kg)",
66
+ "sysmern": "Estimate of noncondensable mass error in system N (kg)",
67
+ "systmb": "Total mass of boron in system N (kg) from state equation",
68
+ "systmc": "Total mass of steam, water, and noncondensable in system N (kg) from continuity equation",
69
+ "systmf": "Total mass of liquid in system N (kg) from state equation",
70
+ "systmfc": "Total mass of liquid in system N (kg) from continuity equation",
71
+ "systmg": "Total mass of vapor (steam plus noncondensable) in system N (kg) from state equation",
72
+ "systmgc": "Total mass of vapor (steam plus noncondensable) in system N (kg) from continuity equation",
73
+ "systmn": "Total mass of noncondensables in system N (kg) from state equation",
74
+ "systmnc": "Total mass of noncondensables in system N (kg) from continuity equation",
75
+ "systms": "Total mass of steam, water, and noncondensable in system N (kg) from state equation",
76
+ "testda": "An array, testda, of one hundred quantities",
77
+ "time": "Time (s)",
78
+ "timeof": "Time of trip occurring (s)",
79
+ "tmass": "Total mass of water, steam, and noncondensables in all the systems (kg)",
80
+ "tothgen": "Total hydrogen generation from metal-water reactions in all the systems (kg)",
81
+ "vnmaxvme": "Volume number of the volume having the maximum volume mass error (see MAXVME)",
82
+ "acpgtg": "Accumulator vapor specific heat, Cp, at vapor temperature (J/kg•K)",
83
+ "acpnit": "Accumulator noncondensable specific heat, Cp, at vapor temperature (J/kg•K)",
84
+ "acqtank": "Total energy transport to the gas by heat and mass transfer in the accumulator (W)",
85
+ "acrhon": "Accumulator noncondensable density (kg/m3)",
86
+ "acttank": "Mean accumulator tank wall metal temperature (K)",
87
+ "acvdm": "Gas volume in the accumulator tank, standpipe, and surge line (m3)",
88
+ "acvgtg": "Accumulator vapor specific heat, Cv, at vapor temperature (J/kg•K)",
89
+ "acvliq": "Liquid volume in the accumulator tank, standipipe, and surge line (m3)",
90
+ "ahfgtf": "Accumulator heat of vaporization at liquid temperature (J/kg)",
91
+ "ahfgtg": "Accumulator heat of vaporization at vapor temperature (J/kg)",
92
+ "ahftg": "Accumulator liquid enthalpy at vapor temperature (J/kg)",
93
+ "ahgtf": "Accumulator vapor enthalpy at liquid temperature (J/kg)",
94
+ "avgtg": "Accumulator specific volume at vapor temperature (m3/kg)",
95
+ "aviscn": "Accumulator noncondensable viscosity (kg/m•s)",
96
+ "betav": "Accumulator steam saturation coefficient of expansion (K-1)",
97
+ "cdim": "GE mechanistic dryer critical inlet moisture quality",
98
+ "dim": "GE mechanistic dryer inlet moisture quality",
99
+ "dmgdt": "Accumulator/time rate of change in dome vapor mass (kg/s)",
100
+ "gdry": "GE mechanistic separator capacity factor",
101
+ "omega": "Inertial valve disk angular velocity (rad/s)",
102
+ "pmphead": "Pump head in the pump component (Pa)",
103
+ "pmpmt": "Pump motor torque (N•m)",
104
+ "pmpnrt": "Calculated pump inertia (kg•m 2)",
105
+ "pmptrq": "Pump torque in the pump component (N•m)",
106
+ "pmpvel": "Pump rotational velocity in the pump component (rad/s)",
107
+ "przlvl": "Pressurizer level in the PRIZER component (m)",
108
+ "theta": "Inertial valve disk angular position (deg)",
109
+ "tureff": "Efficiency of the turbine component",
110
+ "turpow": "Power developed in the turbine component (W)",
111
+ "turtrq": "Torque developed in the turbine component (N•m)",
112
+ "turvel": "Rotational velocity of the turbine component (rad/s)",
113
+ "vlvarea": "Ratio of the current valve physical area to the junction area",
114
+ "vlvstem": "Ratio of the current valve stem position to the fully open valve stem position for the motor and servo valves when the normalized stem position option is used",
115
+ "xco": "GE mechanistic separator liquid carryover quality",
116
+ "xcu": "GE mechanistic separator vapor carryunder quality",
117
+ "xi": "GE mechanistic separator inlet quality",
118
+ "avol": "Area of the volume (m2); the parameter is the volume number plus F",
119
+ "betaff": "Liquid isobaric coefficient of the thermal expansion, βf, bulk conditions (K-1, oF-1)",
120
+ "betagg": "Vapor isobaric coefficient of the thermal expansion, βg, bulk conditions (K-1, oF-1)",
121
+ "boron": "Spatial boron density, ρb (kg/m3)",
122
+ "csubpf": "Liquid specific heat, Cpf, bulk conditions (J/kg•K)",
123
+ "csubpg": "Vapor specific heat, Cpg, bulk conditions (J/kg•K)",
124
+ "drfdp": "Partial derivative of ρf with respect to P (s2/m2)",
125
+ "drfduf": "Partial derivative of ρf with respect to Uf (kg•s2/m5)",
126
+ "drgdp": "Partial derivative of ρg with respect to P (s2/m2)",
127
+ "drgdug": "Partial derivative of ρg with respect to Ug (kg•s 2/m5)",
128
+ "drgdxa": "Partial derivative of ρg with respect to Xn (kg/m3)",
129
+ "dtdp": "Partial derivative of Ts with respect to P (K/Pa)",
130
+ "dtdug": "Partial derivative of Ts with respect to Ug (s2•K/m2)",
131
+ "dtdxa": "Partial derivative of Ts with respect to Xn (K)",
132
+ "dtfdp": "Partial derivative of Tf with respect to pressure (K/Pa)",
133
+ "dtfduf": "Partial derivative of Tf with respect to Uf (s2•K/m2)",
134
+ "dtgdp": "Partial derivative of Tg with respect to P (K/Pa)",
135
+ "dtgdug": "Partial derivative of Tg with respect to Ug (s2•K/m2)",
136
+ "dtgdxa": "Partial derivative of Tg with respect to Xn (K)",
137
+ "entropyf": "Liquid specific entropy, sf, at bulk conditions (J/kg•K)",
138
+ "entropyg": "Vapor specific entropy, sg, at bulk conditions (J/kg•K)",
139
+ "extvnn": "Extra volume variables where NN goes from 01 to 20",
140
+ "floreg": "Flow regime number",
141
+ "fwalf": "Liquid wall frictional drag coefficient (kg/m3•s)",
142
+ "fwalg": "Vapor wall frictional drag coefficient (kg/m3•s)",
143
+ "gammac": "For explicit coupling of heat conduction/transfer and hydrodynamics, this is 0",
144
+ "gammai": "Mass transfer rate per unit volume at the vapor/liquid interface in the bulk fluid for vapor generation/condensation (kg/m3•s)",
145
+ "gammaw": "For explicit coupling of heat conduction/transfer and hydrodynamics, this is the mass transfer rate per unit volume at the vapor/liquid interface in the boundary layer near the wall for vapor generation/condensation (kg/m3•s)",
146
+ "hgf": "Direct heating heat transfer coefficient per unit volume (W/m3•K)",
147
+ "hif": "Liquid side interfacial heat transfer coefficient per unit volume (W/m3•K)",
148
+ "hig": "Vapor side interfacial heat transfer coefficient per unit volume (W/m3•K)",
149
+ "hsteam": "Steam specific enthalpy at bulk conditions using partial pressure of steam (J/kg)",
150
+ "hvmix": "Enthalpy of the liquid and vapor (J/kg)",
151
+ "kappaf": "Liquid isothermal compressibility, κf , at bulk conditions (Pa-1)",
152
+ "kappag": "Vapor isothermal compressibility, , at bulk conditions (Pa-1)",
153
+ "p": "Volume pressure (Pa)",
154
+ "pecltv": "Peclet number",
155
+ "pps": "Steam partial pressure (Pa)",
156
+ "q": "Total volume heat source from the wall and direct moderator heating to liquid and vapor (W)",
157
+ "quala": "Volume noncondensable mass fraction",
158
+ "qualair": "Volume noncondensable mass fraction for AIR",
159
+ "qualar": "Volume noncondensable mass fraction for ARGON",
160
+ "argon": "to the total mass of the noncondensable gas",
161
+ "argon": "is specified on the 110 card",
162
+ "quale": "Volume equilibrium quality",
163
+ "qualhe": "Volume noncondensable mass fraction for HELIUM",
164
+ "helium": "to the total mass of the noncondensable gas",
165
+ "helium": "is specified on the 110 card",
166
+ "qualhy": "Volume noncondensable mass fraction for HYDROGEN",
167
+ "hydrogen": "to the total mass of the noncondensable gas",
168
+ "qualkr": "Volume noncondensable mass fraction for KRYPTON",
169
+ "krypton": "to the total mass of the noncondensable gas",
170
+ "krypton": "is specified on the 110 card",
171
+ "qualni": "Volume noncondensable mass fraction for NITROGEN",
172
+ "nitrogen": "to the total mass of the noncondensable gas",
173
+ "nitrogen": "is specified on the 110 card",
174
+ "quals": "Volume static quality",
175
+ "qualxe": "Volume noncondensable mass fraction for XENON",
176
+ "xenon": "to the total mass of the noncondensable gas",
177
+ "xenon": "is specified on the 110 card",
178
+ "qwg": "Volume heat source from the wall and direct moderator heating to vapor (W)",
179
+ "rho": "Total density (kg/m3)",
180
+ "rhof": "Liquid density ρf (kg/m3)",
181
+ "rhog": "Vapor density ρg (kg/m3)",
182
+ "rhom": "Total density for the mass error check (kg/m3)",
183
+ "sathf": "Liquid specific enthalpy at saturation conditions using partial pressure of steam (J/kg)",
184
+ "sathg": "Steam specific enthalpy at saturation conditions using partial pressure of steam (J/kg)",
185
+ "sattemp": "Volume saturation temperature based on the partial pressure of steam (K)",
186
+ "sigma": "Surface tension (N/m)",
187
+ "sounde": "Volume sonic velocity (m/s)",
188
+ "tempf": "Volume liquid temperature Tf (K)",
189
+ "tempg": "Volume vapor temperature Tg (K)",
190
+ "thconf": "Liquid thermal conductivity (W/m•K)",
191
+ "thcong": "Vapor thermal conductivity (W/m•K)",
192
+ "tiengv": "Total internal energy (of both phases and noncondensables) in volume (J)",
193
+ "tmassbv": "Boron mass in volume from state equation (kg)",
194
+ "tmassfv": "Liquid mass in volume from state equation (kg)",
195
+ "tmassgv": "Vapor mass (includes noncondensables) in volume from state equation (kg)",
196
+ "tmassnv": "Noncondensable mass in volume from state equation (kg)",
197
+ "tmassv": "Total fluid mass (includes both phases) in volume from state equation (kg)",
198
+ "tsatt": "Saturation temperature corresponding to total pressure (K)",
199
+ "tspinf": "Liquid spinodal temperature (K)",
200
+ "tsping": "Vapor spinodal temperature (K)",
201
+ "uf": "Liquid specific internal energy (J/kg)",
202
+ "ug": "Vapor specific internal energy (J/kg)",
203
+ "usatf": "Liquid specific internal energy at saturation (J/kg)",
204
+ "usatg": "Vapor specific internal energy at saturation (J/kg)",
205
+ "vapgen": "Total mass transfer rate per unit volume at the vapor/liquid interface in the bulk fluid for vapor generation/condensation and in the boundary layer near the wall for vapor generation/condensation (kg/m3•s)",
206
+ "velf": "Volume oriented liquid velocity (m/s)",
207
+ "velg": "Volume oriented vapor velocity (m/s)",
208
+ "vlev": "Velocity of level in volume (m/s)",
209
+ "viscf": "Liquid viscosity (kg/m•s)",
210
+ "viscg": "Vapor viscosity (kg/m•s)",
211
+ "voidf": "Volume liquid fraction",
212
+ "voidg": "Volume vapor fraction",
213
+ "voidla": "Volume vapor fraction above the level",
214
+ "voidlb": "Volume vapor fraction below the level",
215
+ "vollev": "Elevation of the level in the volume (m)",
216
+ "volmas": "Volume mass in volume from continuity equation (kg)",
217
+ "volmasb": "Volume boron mass from continuity equation (kg)",
218
+ "volmasf": "Volume liquid mass from continuity equation (kg)",
219
+ "volmasg": "Volume vapor mass from continuity equation (kg)",
220
+ "volmasn": "Volume noncondensable mass from continuity equation (kg)",
221
+ "volmer": "Volume mass error (kg)",
222
+ "volmerb": "Volume boron mass error (kg)",
223
+ "volmerf": "Volume liquid mass error (kg)",
224
+ "volmerg": "Volume vapor mass error (kg)",
225
+ "volmern": "Volume noncondensable mass error (kg)",
226
+ "boronj": "Junction boron density (kg/m3)",
227
+ "c0j": "Junction distribution coefficient",
228
+ "chokef": "Junction choking flag",
229
+ "extjnn": "Extra junction variables where NN goes from 01 to 20",
230
+ "fij": "Interphase frictionΣ coefficient (N•s 2/m5)",
231
+ "fjunft": "Total forward user input form loss coefficient for irreversible losses)",
232
+ "fjunrt": "Total reverse user input form loss coefficient for irreversible losses)",
233
+ "flenth": "Total enthalpy flow in junction (includes both phases and noncondensables) (J/s)",
234
+ "flenthf": "Liquid enthalpy flow in junction (J/s)",
235
+ "flenthg": "Vapor enthalpy flow in junction (J/s)",
236
+ "florgj": "Junction flow regime number",
237
+ "formfj": "Liquid abrupt area change model form loss factor (dimensionless)",
238
+ "formgj": "Vapor abrupt area change model form loss factor (dimensionless)",
239
+ "fwalfj": "Non-dimensional liquid wall friction coefficient (dimensionless)",
240
+ "fwalgj": "Non-dimensional vapor wall friction coefficient (dimensionless)",
241
+ "iregj": "Vertical bubbly/slug flow junction flow regime number",
242
+ "mflowbj": "Boron flow rate (kg/s)",
243
+ "mflowfj": "Liquid flow rate (kg/s)",
244
+ "mflowgj": "Vapor flow rate (kg/s)",
245
+ "mflowj": "Mass flow rate (kg/s)",
246
+ "mflownj": "Noncondensable flow rate (kg/s)",
247
+ "qualaj": "Junction noncondensable mass fraction",
248
+ "qualjair": "Junction noncondensable mass fraction for AIR",
249
+ "qualjar": "Junction noncondensable mass fraction for ARGON",
250
+ "argon": "to the total mass of the noncondensable gas",
251
+ "argon": "is specified on the 110 card",
252
+ "qualjhe": "Junction noncondensable mass fraction for HELIUM",
253
+ "helium": "to the total mass of the noncondensable gas",
254
+ "helium": "is specified on the 110 card",
255
+ "qualjhy": "Junction noncondensable mass fraction for HYDROGEN",
256
+ "hydrogen": "to the total mass of the noncondensable gas",
257
+ "qualjkr": "Junction noncondensable mass fraction for KRYPTON",
258
+ "krypton": "to the total mass of the noncondensable gas",
259
+ "krypton": "is specified on the 110 card",
260
+ "qualjni": "Junction noncondensable mass fraction for NITROGEN",
261
+ "nitrogen": "to the total mass of the noncondensable gas",
262
+ "nitrogen": "is specified on the 110 card",
263
+ "qualjxe": "Junction noncondensable mass fraction for XENON",
264
+ "xenon": "to the total mass of the noncondensable gas",
265
+ "xenon": "is specified on the 110 card",
266
+ "rhofj": "Junction liquid density (kg/m3)",
267
+ "rhogj": "Junction vapor density (kg/m3)",
268
+ "sonicj": "Junction sound speed (m/s)",
269
+ "ufj": "Junction liquid specific internal energy (J/kg)",
270
+ "ugj": "Junction vapor specific internal energy (J/kg)",
271
+ "velfj": "Junction liquid velocity (m/s)",
272
+ "velgj": "Junction vapor velocity (m/s)",
273
+ "vgjj": "Vapor drift velocity (m/s)",
274
+ "voidfj": "Junction liquid fraction",
275
+ "voidgj": "Junction vapor fraction (void fraction)",
276
+ "voidj": "Junction vapor fraction (void fraction) used in the interphase friction",
277
+ "xej": "Junction equilibrium quality",
278
+ "hfrad": "Radiation heat flux (W/m2)",
279
+ "hftot": "Total heat flux, i",
280
+ "htchf": "Critical (maximum) heat flux (W/m2)",
281
+ "htchfr": "Critical hat flux ratio",
282
+ "htgamw": "Wall vapor generation rate per unit volume (kg/m3•s)",
283
+ "hthgen": "Total hydrogen generation at this heat structure (kg)",
284
+ "htmode": "Boundary heat transfer mode number",
285
+ "htoxi": "Inside oxide layer thickness (m)",
286
+ "htoxo": "Outside oxide layer thickness (m)",
287
+ "htrg": "Heat flux to vapor phase (W/m2)",
288
+ "htrnr": "Convective heat flux (W/m2)",
289
+ "httemp": "Mesh point temperature (K)",
290
+ "cccg0nn": "with a two-digit number appended (mesh point number)",
291
+ "htvat": "Volume averaged temperature in the heat structure (K)",
292
+ "pecl": "Liquid Peclet number for the heat structures",
293
+ "stant": "Stanton number",
294
+ "kgap": "Effective gap thermal conductivity (W/m•K)",
295
+ "pgap": "Pressure of the gas gap (Pa)",
296
+ "tgap": "Temperature of the gas gap (K)",
297
+ "gapwd": "Width of the gas gap (m)",
298
+ "clstrn": "Total cladding strain",
299
+ "clhoop": "Cladding hoop stress (Pa)",
300
+ "fines": "Current number of axial nodes on a reflood structure",
301
+ "tchfqf": "Temperature at the critical (maximum) heat flux (K)",
302
+ "trewet": "Rewet, quench, Leidenfrost, or minimum film boiling temperature (K)",
303
+ "zqbot": "Elevation of bottom quench front (m)",
304
+ "zqtop": "Elevation of top quench front (m)",
305
+ "reac": "Reactivity feedback total (dollars)",
306
+ "reactf.": "(Only available when the SEPARABL option is used on the 30000000 card)",
307
+ "reacm": "Reactivity feedback total from moderator density changes (dollars)",
308
+ "reacrb": "Reactivity feedback from boron density changes (dollars)",
309
+ "separabl": "option is used on the 30000000 card)",
310
+ "reacrm": "Reactivity feedback from moderator density changes (dollars)",
311
+ "separabl": "option is used on the 30000000 card)",
312
+ "reacs": "Reactivity feedback from scram curve (dollars)",
313
+ "reactf": "Reactivity feedback from fuel temperature changes (dollars)",
314
+ "separabl": "option is used on the 30000000 card)",
315
+ "reactm": "Reactivity feedback from moderator temperature (spectral) changes (dollars)",
316
+ "rkfipow": "Reactor power from fission (W)",
317
+ "rkgapow": "Reactor power from decay of fission products and actinides (W)",
318
+ "rkpowa": "Reactor power from decay of actinides (W)",
319
+ "rkpowk": "Reactor power from decay of fission products (W)",
320
+ "rkreac": "Reactivity (dollars)",
321
+ "rkrecper": "Reciprocal period (s-1)",
322
+ "rktpow": "Total reactor power, i",
323
+ "cntrlvar": "Control component",
324
+ "shaft": "component",
325
+ "trip": "Trip number",
326
+ }
327
+ #▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄
328
+ def make_strip(input_variables_file: str, strip_filename: str, type="fmtout"):
329
+
330
+ """make_strip: creates a strip file
331
+
332
+ :USAGE: your_name = make_strip(input_variables, strip_filename)
333
+
334
+ :input_variables_file: [str] the file that lists all the variables
335
+ to be stripped
336
+ :strip_filename: [str] the filename of the strip to be created
337
+ :type: [str] (optional) field 'csv' or 'fmtout'
338
+
339
+ :returns: the information in 'input_variables' stored in 'your_name' variable
340
+ - in addition, it creates a strip file in the folder
341
+ """
342
+ if type != 'csv' and type != 'fmtout' :
343
+ print('WARNING: argument 1 should be either csv or fmtout')
344
+ print('Argument 1 is set to fmtout')
345
+ type = 'fmtout'
346
+ with open(strip_filename, 'w+') as st:
347
+ variables = pd.read_csv(input_variables_file, delim_whitespace=True, comment='%')
348
+ st.truncate(0)
349
+ st.write('= stripf \n')
350
+ st.write('0000100 strip ' + type + '\n')
351
+ st.write('101 run \n')
352
+ st.write('103 0 \n')
353
+ st.write('*--------------------------------------------------------------------- \n')
354
+ for index, plot in variables.iterrows():
355
+ st.write(str(1001 + index) + ' ')
356
+ for word in plot:
357
+ st.write(str(word) + ' ')
358
+ st.write('\n')
359
+ st.write('. \n')
360
+ st.close()
361
+ print('Your strip file ' + strip_filename + ' has been created')
362
+ return variables
363
+ #▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄
364
+ def read_stripf_df(case_folder='', names=''):
365
+
366
+ """read_stripf performs the following consecutive actions:
367
+ 1.- reads the stripf file
368
+ 2.- stores the data in a narray to be used in python
369
+
370
+ :case_folder: [str] (optional) folder location of the stripf file
371
+ :names: list (optional) names to be added to the DataFrame. If you have
372
+ the variables file, you can specify the names column here
373
+
374
+ :returns:
375
+ - a [ndarry] with the data with name 'case_folder'
376
+ """
377
+ if case_folder != '':
378
+ case_folder = './' + case_folder + '/'
379
+ with open(case_folder + 'stripf', 'r+') as st:
380
+ val = [[]]
381
+ lin, lini = 0, 0
382
+ for l in st:
383
+ if not l == '\n':
384
+ line = l.split()
385
+ if (line[0] == 'plotrec' or line[0] == 'plotalf'
386
+ or line[0] == 'plotnum'):
387
+ val.append(line[1:])
388
+ lini = 1
389
+ lin = lin + 1
390
+ else :
391
+ if lini == 1:
392
+ for ii in range(len(line)):
393
+ val[lin].append(line[ii])
394
+ val.pop(0)
395
+ st.close()
396
+ tras = [*zip(*val)]
397
+ try:
398
+ os.remove(case_folder + 'stripf.dat')
399
+ except OSError:
400
+ pass
401
+ with open(case_folder + 'stripf.dat', 'w+') as auxi:
402
+ for i2 in range(len(tras[0])):
403
+ for i1 in range(len(tras)):
404
+ if i1 < len(tras) - 1:
405
+ if i2 == 0:
406
+ auxi.write(str(tras[i1][i2]) + '-' + str(tras[i1][i2+1]) + ',')
407
+ if i2 > 1:
408
+ auxi.write(str(tras[i1][i2]) + ',')
409
+ else :
410
+ if i2 == 0:
411
+ auxi.write(str(tras[i1][i2]) + '-' + str(tras[i1][i2+1]))
412
+ if i2 > 1:
413
+ auxi.write(str(tras[i1][i2]))
414
+ if i2 != 1:
415
+ auxi.write('\n')
416
+ auxi.close()
417
+ if names == '':
418
+ case = pd.read_csv(case_folder + 'stripf.dat', sep=',', header=0,
419
+ usecols=np.arange(0, len(tras)))
420
+ else :
421
+ case = pd.read_csv(case_folder + 'stripf.dat', sep=',',
422
+ skiprows=1, header=None, index_col=0)
423
+ case.columns = names[1:]
424
+ return case
425
+ #▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄
426
+ def read_stripf(case_folder='', names=''):
427
+
428
+ """read_stripf performs the following consecutive actions:
429
+ 1.- reads the stripf file
430
+ 2.- stores the data in a narray to be used in python
431
+
432
+ :case_folder: [str] (optional) folder location of the stripf file
433
+ :names: list (optional) names to be added to the DataFrame. If you have
434
+ the variables file, you can specify the names column here
435
+
436
+ :returns:
437
+ - a [ndarry] with the data with name 'case_folder'
438
+ """
439
+ if case_folder != '':
440
+ case_folder = './' + case_folder + '/'
441
+ with open(case_folder + 'stripf', 'r+') as st:
442
+ val = [[]]
443
+ lin, lini = 0, 0
444
+ for l in st:
445
+ if not l == '\n':
446
+ line = l.split()
447
+ if (line[0] == 'plotrec' or line[0] == 'plotalf'
448
+ or line[0]=='plotnum'):
449
+ val.append(line[1:])
450
+ lini = 1
451
+ lin = lin + 1
452
+ else:
453
+ if lini == 1:
454
+ for ii in range(len(line)):
455
+ val[lin].append(line[ii])
456
+ val.pop(0)
457
+ st.close()
458
+ tras = [*zip(*val)]
459
+ try:
460
+ os.remove(case_folder + 'stripf.dat')
461
+ except OSError:
462
+ pass
463
+ with open(case_folder + 'stripf.dat', 'w+') as auxi:
464
+ for i2 in range(len(tras[0])):
465
+ for i1 in range(len(tras)):
466
+ if i1 < len(tras) - 1:
467
+ if i2 == 0:
468
+ auxi.write(str(tras[i1][i2]) + '-' + str(tras[i1][i2+1]) + ',')
469
+ if i2>1:
470
+ auxi.write(str(tras[i1][i2]) + ',')
471
+ else :
472
+ if i2 == 0:
473
+ auxi.write(str(tras[i1][i2]) + '-' + str(tras[i1][i2+1]))
474
+ if i2 > 1:
475
+ auxi.write(str(tras[i1][i2]))
476
+ if i2 != 1:
477
+ auxi.write('\n')
478
+ auxi.close()
479
+ if names == '':
480
+ case = np.genfromtxt(case_folder + 'stripf.dat', delimiter=",",
481
+ usecols=np.arange(0, len(tras)), names=True)
482
+ else :
483
+ case = np.genfromtxt(case_folder + 'stripf.dat', delimiter=",",
484
+ usecols=np.arange(0, len(tras)), skip_header=1, names=names)
485
+ return case
486
+ #▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄
487
+ def run_strip(strip_file: str, restart: str, case_folder=''):
488
+
489
+ """ run_strip simply performs a strip with the defined strip_file
490
+
491
+ :strip_file: [str] strip file
492
+ :restart: case name without extension
493
+ :case_folder: (optional) folder of the case
494
+ :returns: nothing
495
+ - a file stripf is created in the specified case_folder
496
+
497
+ """
498
+ if case_folder != '':
499
+ case_folder = './' + case_folder + '/'
500
+ exe = relapwin_loc + '/' + relap_exe
501
+ arg1 = ' -i ' + strip_file
502
+ arg2 = ' -O ' + case_folder + 'stripout'
503
+ arg3 = ' -r ' + case_folder + restart + '.r'
504
+ arg4 = ' -Z ' + relapwin_loc + '/tpfh2onew'
505
+ cmd = exe + arg1 + arg2 + arg3 + arg4
506
+ print(cmd)
507
+ try :
508
+ os.remove('stripf')
509
+ except OSError :
510
+ pass
511
+ try :
512
+ os.remove(case_folder + 'stripf')
513
+ except OSError :
514
+ pass
515
+ try :
516
+ os.remove('screen')
517
+ except OSError :
518
+ pass
519
+ with Popen(cmd, stdout=PIPE, bufsize=1, universal_newlines=True) as p:
520
+ for line in p.stdout:
521
+ print(line, end='')
522
+ try :
523
+ os.rename('stripf', case_folder + 'stripf')
524
+ except OSError :
525
+ pass
526
+ try :
527
+ os.remove(case_folder + 'stripout')
528
+ except OSError :
529
+ pass
530
+ try :
531
+ os.remove('screen')
532
+ except OSError :
533
+ pass
534
+ # pd.read_csv('fjdklf', f)
535
+ # try :
536
+ # os.remove('stripf')
537
+ # except OSError :
538
+ # pass
539
+ #▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄
540
+ def extract_data(input_variables_file: str, restart: str, case_folder=''):
541
+
542
+ """extract_data performs the following consecutive actions:
543
+ 1.- creates a strip file from the input_variables and the paths
544
+ to each case_folder
545
+ 2.- runs the strip to load the data for each case
546
+
547
+ USAGE:
548
+ cases, variables = extract_data(input_variables_file: str, restart: str,
549
+ case_folder = '')
550
+
551
+ :input_variables_file: [str] the file that lists all the variables
552
+ to be stripped
553
+ :restart: [str] the case name
554
+ :case_folder: name of the case folder or a [list] with cases
555
+
556
+ :returns:
557
+ - a [DataFrame] with the read variables
558
+ - an [Ndarray] of Ndarrays for each case
559
+ :files:
560
+ - a file containing the extracted data in the calculation folder: 'stripf'
561
+ - a strip file with the requested filename in the running folder
562
+
563
+ 1.- creates a strip file from the input_variables and the paths to each
564
+ case_folder
565
+ """
566
+ variables = make_strip(input_variables_file, 'strip_' + restart + '.i')
567
+ noms_codi = ['time']
568
+ noms_codi.extend(variables.loc[:, 'experiment_tag'])
569
+ noms_descrip = ['Time']
570
+ noms_descrip.extend(variables.loc[:, 'figure_tag'])
571
+ for i in range(len(noms_descrip)):
572
+ noms_descrip[i] = str(noms_descrip[i]).replace('_', ' ')
573
+ noms_units = ['(s)']
574
+ for index, line in variables.iterrows():
575
+ noms_units.append('('+line['unit']+')')
576
+
577
+ case_paths = []
578
+ if type(case_folder) == str:
579
+ case_paths = [case_folder]
580
+ else :
581
+ for i in range(0, len(case_folder)):
582
+ case_paths.append(case_folder[i])
583
+ # if case_paths[i] != '':
584
+ # case_paths[i] = './' + case_folder[i] + '/'
585
+ """
586
+ 2.- runs the strip to load the data for each case
587
+ """
588
+ print(case_paths)
589
+ cases = {}
590
+ for item in case_paths:
591
+ run_strip('strip_' + restart + '.i', restart, item)
592
+ case = read_stripf(item, noms_codi)
593
+ cases[item] = case
594
+ case_df = pd.DataFrame(case)
595
+ case_df.to_csv('./'+item+'/' + restart + '.dat', float_format='%1.4e')
596
+ os.remove('./' + item + '/' + 'stripf.dat')
597
+ os.remove('./' + item + '/' + 'stripf')
598
+ return cases, variables
599
+ #▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄
600
+ def extract_df(input_variables_file: str, restart: str, case_folder=''):
601
+
602
+ """extract_data performs the following consecutive actions:
603
+ 1.- creates a strip file from the input_variables and the paths
604
+ to each case_folder
605
+ 2.- runs the strip to load the data for each case
606
+
607
+ USAGE:
608
+ cases, variables = extract_data(input_variables_file: str, restart: str,
609
+ case_folder = '')
610
+
611
+ :input_variables_file: [str] the file that lists all the variables
612
+ to be stripped
613
+ :restart: [str] the case name
614
+ :case_folder: name of the case folder or a [list] with cases
615
+
616
+ :returns:
617
+ - a [DataFrame] with the read variables
618
+ - an [Ndarray] of Ndarrays for each case
619
+ :files:
620
+ - a file containing the extracted data in the calculation folder: 'stripf'
621
+ - a strip file with the requested filename in the running folder
622
+
623
+ 1.- creates a strip file from the input_variables and the paths to each
624
+ case_folder
625
+ """
626
+ variables = make_strip(input_variables_file,'strip_'+restart+'.i')
627
+ noms_codi = ['time']
628
+ noms_codi.extend(variables.loc[:,'experiment_tag'])
629
+ noms_descrip = ['Time']
630
+ noms_descrip.extend(variables.loc[:,'figure_tag'])
631
+ for i in range(len(noms_descrip)):
632
+ noms_descrip[i] = str(noms_descrip[i]).replace('_',' ')
633
+ noms_units = ['(s)']
634
+ for index, line in variables.iterrows():
635
+ noms_units.append('('+line['unit']+')')
636
+
637
+ case_paths = []
638
+ if type(case_folder) == str:
639
+ case_paths = [case_folder]
640
+ else :
641
+ for i in range(0,len(case_folder)):
642
+ case_paths.append(case_folder[i])
643
+ # if case_paths[i] != '':
644
+ # case_paths[i] = './' + case_folder[i] + '/'
645
+ """
646
+ 2.- runs the strip to load the data for each case
647
+ """
648
+ print(noms_codi)
649
+ # cases = {}
650
+ cases = []
651
+ for item in case_paths:
652
+ run_strip('strip_' + restart + '.i', restart, item)
653
+ case = read_stripf_df(item, noms_codi)
654
+ # cases[item] = case
655
+ cases.append(case)
656
+ result = pd.concat(cases, keys=case_paths)
657
+ return result, variables
658
+ #▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄
659
+ def plot_var(variable: str, variables_df, cases_df, case_folder = '',
660
+ dataExp = '', label = ''):
661
+
662
+ """ plots one of the variables extracted. It may plot for each of the cases
663
+ specified in case_folder
664
+
665
+ :variable: str name of the variable to be plotted
666
+ :variables_df: Dataframe containing the variables and properties
667
+ of each variable
668
+ :cases_df: Ndarray containing the data cases
669
+ :case_folder: (optional) name of the case folder or a [list] with cases
670
+ :dataExp: (optional) name of the Ndarray containing the experimental data
671
+ :label: str (optional) Label of the y axis
672
+
673
+ :returns: if used as
674
+ figure, axes = rp.plot_var(...)
675
+ a figure and axes objects are returned
676
+ :output: TODO
677
+
678
+ """
679
+ global exp_file_bool
680
+ exp_file_bool = False
681
+ if type(dataExp) != str : exp_file_bool = True
682
+ if type(case_folder) == str : case_folder = [case_folder]
683
+ print('making plot for', variable)
684
+ # plt.figure(variable)
685
+ fig, ax = plt.subplots()
686
+ i = variables_df[variables_df['figure_tag'] == variable].index.values[0]
687
+ tag = variables_df['experiment_tag'][i]
688
+ if exp_file_bool :
689
+ if tag in dataExp.dtype.names :
690
+ ax.plot(dataExp['time'], dataExp[tag],
691
+ linewidth=0.75,color='k',label='Experimental')
692
+ for j in case_folder :
693
+ ax.plot(cases_df[j]['time'], cases_df[j][tag], linewidth=0.75, label=j)
694
+ # plt.ylabel(variable.replace('_',' ') + ' (' + variables_df['unit'][i] + ')')
695
+ if label == '' : label = relap_labels.get(variables_df['alphanum'][i])
696
+ ax.set(ylabel =label, xlabel ='Time (s)',
697
+ xlim =(float(variables_df['timei'][i]), float(variables_df['timee'][i])),
698
+ title = variable.replace('_',' '))
699
+ if float(variables_df['ymin'][i]) != 0 or float(variables_df['ymax'][i]) != 0:
700
+ ax.set_ylim(variables_df['ymin'][i], variables_df['ymax'][i])
701
+ ax.grid(which='major', linestyle=':', linewidth=1.0,
702
+ alpha=0.8, color='grey')
703
+ ax.legend()
704
+ fig.tight_layout()
705
+ fig.savefig(figures_loc + variable + '.' + figures_type,
706
+ format= figures_type, dpi=300,bbox_inches='tight')
707
+ # if show_plot : fig.show()
708
+ # if hideplots :
709
+ # fig.clf()
710
+ # plt.close()
711
+ return fig, ax
712
+ #▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄
713
+ def plot_all(variables_df, cases_df, case_folder='', dataExp=''):
714
+
715
+ """TODO: Docstring for plot_all.
716
+
717
+ :variables_df: dataframe containing the requested variables
718
+ :cases_df: numpy array containing all results
719
+ :case_folder: name of the case folder or a [list] with cases
720
+ :dataExp: (optional) name of the Ndarray containing the experimental data
721
+
722
+ :returns: TODO
723
+ :output: TODO
724
+
725
+ """
726
+ for item in variables_df['figure_tag'] :
727
+ plot_var(item, variables_df, cases_df, case_folder, dataExp)
728
+ #▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄
729
+ def plot(alpha: str, numeric: str, restart: str, case_folder='', save_fig=''):
730
+
731
+ """ plot is used to plot a single relap variable. It can be done for
732
+ one single case or for a list of cases
733
+
734
+ :alpha: [str] type of variable to be plotted
735
+ :numeric: [str] numeric part of the variable
736
+ :restart: [str] the restart code name
737
+ :case_folder: [str or list] (optional) case or cases to be plotted
738
+ :save_fig: [str] (optional) write 'pdf' or 'png' if you want to save a fig
739
+ :returns: [ndarray] with the data extracted
740
+ - it plots the specified variable for all specified cases
741
+ - you may save the figure
742
+ """
743
+ with open('dummy_strip.i', 'w+') as st:
744
+ st.truncate(0)
745
+ st.write('= stripf \n')
746
+ st.write('0000100 strip fmtout \n')
747
+ st.write('101 run \n')
748
+ st.write('103 0 \n')
749
+ st.write('*--------------------------------------------------------------------- \n')
750
+ st.write('1001 ' + alpha + ' ' + numeric + '\n')
751
+ st.write('. \n')
752
+ if type(case_folder) == str:
753
+ case_folder = [case_folder]
754
+ # cases = []
755
+ for i in range(0, len(case_folder)):
756
+ try :
757
+ os.remove('./' + case_folder[i] + '/' + 'stripf')
758
+ except OSError :
759
+ pass
760
+ run_strip('dummy_strip.i', restart, case_folder[i])
761
+ cas = read_stripf(case_folder[i])
762
+ # cases.append(cas)
763
+ what = alpha + numeric
764
+ plt.plot(cas['time0'],cas[what],linewidth=0.75,label=case_folder[i])
765
+ if alpha in relap_labels:
766
+ plt.ylabel(relap_labels.get(alpha))
767
+ else :
768
+ plt.ylabel('-')
769
+ plt.xlabel('Time (s)')
770
+ plt.legend()
771
+ plt.title(alpha + '-' + numeric)
772
+ plt.tight_layout()
773
+ if save_fig == 'pdf' or save_fig == 'png':
774
+ plt.savefig(figures_loc + what + '.' + save_fig, format=save_fig,
775
+ dpi=300,bbox_inches='tight')
776
+ if show_plot : plt.show()
777
+ if hideplots :
778
+ plt.clf()
779
+ plt.close()
780
+ return cas
781
+ #▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄
782
+ def general_fig(variables, dataCalc0, dataExp='' , annotations=[], labels=[]):
783
+ """
784
+
785
+ :variables: Dataframe containing all the requested variables and properties
786
+ :dataCalc0: Numpy array containing all results: cases_df['base']
787
+ :annotations: (optional) location of the tags for each line
788
+ :labels: (optional) list of labels for each y_axes
789
+
790
+ :USAGE:
791
+ rp.general_fig(variables, cases_df_sbloca['base'])
792
+ your_name, your_axes = rp.general_fig(variables, cases_df_sbloca['base'])
793
+ :with annotations:
794
+
795
+ rp.general_fig(variables, cases_df[item], data_test62,
796
+ [[300., 15030000.0],
797
+ [7500.0, 8000000.0],
798
+ [100.0,5500000.0],
799
+ [23930.06, 1445.9],
800
+ [18930.06, 6191.244],
801
+ [920.04699999999, 44.045],
802
+ [920.04699999999, 38.1251],
803
+ [1500, 4.045],
804
+ [1500, 1.9],
805
+ [300, 8.59974]])
806
+
807
+ You add a list of pairs of data for each plot. The pairs of values
808
+ are the time and y coordinate (same as the data)
809
+
810
+ You can first run the case without the annotations and the default
811
+ values appear on screen, you can use them later to edit
812
+
813
+ :returns: A figure with the general evolution of the transient
814
+ - a figure object and axes named 'your_name' and 'your_axes'
815
+
816
+ """
817
+ global exp_file_bool
818
+ initial_time = variables.loc[1,'timei']
819
+ final_time = variables.loc[1,'timee']
820
+ ticks = variables.loc[1,'timee']/10
821
+ initial_index = np.where(dataCalc0['time'] >= initial_time)[0][0]
822
+ try : final_index = np.where(dataCalc0['time'] >= final_time)[0][0]
823
+ except : final_index = -1
824
+ exp_file_bool = False
825
+ if type(dataExp) != str : exp_file_bool = True
826
+
827
+ f, axes = plt.subplots(3, sharex=True, sharey=False)
828
+ colors = ['k','mediumblue','red','green','tab:orange','tab:purple',
829
+ 'tab:brown','tab:pink','tab:olive','tab:cyan']
830
+ label = 'UPC'
831
+ label_exp = 'Experimental'
832
+ l_style = '-'
833
+ tags = ['top_left', 'mid_left', 'bottom_left']
834
+ tags_right = ['top_right', 'mid_right', 'bottom_right']
835
+ ll = 0
836
+ prop_box = dict(boxstyle="round", color = 'w', alpha=0.5)
837
+
838
+ print('annotation locations are as follows')
839
+ for i in range(0,3):
840
+ l = 0
841
+ axes[i].grid( linestyle = '-', linewidth = 0.5)
842
+ plotted = variables[variables['general'] == tags[i]].reset_index()
843
+ try :
844
+ axes[i].set_ylabel(labels[i])
845
+ except :
846
+ axes[i].set_ylabel(relap_labels.get(plotted['alphanum'][0]))
847
+ for k, plot in plotted.iterrows():
848
+ align = 'left'
849
+ time_coord = (dataCalc0['time'][initial_index
850
+ + np.argmax(dataCalc0[plot[4]][initial_index:final_index])])
851
+ time_var = max(dataCalc0[plot[4]][initial_index:final_index])
852
+ if time_coord <= initial_time or time_coord >= final_time :
853
+ time_coord = 0.0
854
+ time_var = dataCalc0[plot[4]][initial_index]
855
+ if time_coord > (final_time - initial_time) / 2 : align = 'right'
856
+ if not annotations:
857
+ anot = [time_coord, time_var]
858
+ else :
859
+ anot = annotations[ll]
860
+ print(anot)
861
+ if exp_file_bool :
862
+ l_style = ':'
863
+ if plot[4] in dataExp.dtype.names :
864
+ axes[i].plot(dataExp['time'],dataExp[plot[4]], linewidth=1,
865
+ color=colors[l], alpha=1.0, linestyle='-',
866
+ label=label_exp)
867
+ label_exp = '_nolegend_'
868
+ axes[i].plot(dataCalc0['time'],dataCalc0[plot[4]], linewidth=1,
869
+ color=colors[l], alpha=1.0, linestyle= l_style,label=label)
870
+ axes[i].annotate(plot[5].replace('_',' '), xy = anot,
871
+ xycoords='data', color=colors[l],horizontalalignment=align,
872
+ bbox= prop_box, verticalalignment='bottom' )
873
+ label = '_nolegend_'
874
+ ll += 1
875
+ l += 1
876
+ plotted = variables[variables['general'] == tags_right[i]].reset_index()
877
+ for k, plot in plotted.iterrows():
878
+ align = 'left'
879
+ time_coord = (dataCalc0['time'][initial_index +
880
+ np.argmax(dataCalc0[plot[4]][initial_index:final_index])])
881
+ time_var = max(dataCalc0[plot[4]][initial_index:final_index])
882
+ if time_coord > (final_time - initial_time) / 2 : align = 'right'
883
+ if not annotations:
884
+ anot = [time_coord, time_var]
885
+ else :
886
+ anot = annotations[ll]
887
+ print(anot)
888
+ if k == 0 : ax2=axes[i].twinx()
889
+ if exp_file_bool :
890
+ l_style = ':'
891
+ if plot[4] in dataExp.dtype.names :
892
+ ax2.plot(dataExp['time'], dataExp[plot[4]], linewidth=1,
893
+ color=colors[l], alpha=1.0, linestyle='-',
894
+ label=label_exp)
895
+ label_exp = '_nolegend_'
896
+ ax2.plot(dataCalc0['time'], dataCalc0[plot[4]], linewidth=1,
897
+ color=colors[l], alpha=1.0, linestyle= l_style,label=label)
898
+ ax2.annotate(plot[5].replace('_', ' '), xy=anot, xycoords='data',
899
+ color=colors[l], horizontalalignment=align, bbox=prop_box,
900
+ verticalalignment='bottom' )
901
+ l += 1
902
+ ll += 1
903
+ try :
904
+ ax2.set_ylabel(labels[i+3])
905
+ except :
906
+ ax2.set_ylabel(relap_labels.get(plotted['alphanum'][0]))
907
+ axes[0].legend(bbox_to_anchor=(0.6, 1.0, 0.4, 0.1), loc='lower left',
908
+ frameon=False, ncol=2, mode="expand")
909
+ axes[2].set_xlabel('Time(s)')
910
+ axes[0].tick_params(axis="x", direction="in")
911
+ axes[1].tick_params(axis="x", direction="in")
912
+ axes[2].tick_params(axis="x", direction="inout")
913
+ axes[2].set_xlim(initial_time,final_time)
914
+ axes[2].set_xticks(np.arange(0, final_time + ticks / 2, ticks))
915
+ f.subplots_adjust(hspace=0)
916
+ f.set_size_inches(10, 12)
917
+ f.savefig(figures_loc + 'general.' + figures_type, format=figures_type, dpi=300)
918
+ if show_plot : plt.show()
919
+ return f, axes
920
+
921
+
922
+ def plot_variables(variable: list, variables_df, cases_df):
923
+
924
+ """ plots various variables in the same plot. Only one Yaxes so must have
925
+ the same units.
926
+
927
+ :variable: list containing the variables to be plotted
928
+ :variables_df: Dataframe containing the variables and properties
929
+ of each variable
930
+ :cases_df: Ndarray containing the data for the particular case:
931
+ cases_df['base']
932
+
933
+ :USAGE:
934
+ rp.plot_variables(['SGTR_MF', 'REL_VLV_MF'], variables, cases_df['base'])
935
+
936
+ :returns: TODO
937
+ :output: a plot with the two variables listed
938
+
939
+ """
940
+ print('making plot for', variable[0] + '_' + variable[-1])
941
+ plt.figure(variable[0] + '_' + variable[-1])
942
+ for var in variable :
943
+ i = variables_df[variables_df['experiment_tag'] == var].index.values[0]
944
+ plt.plot(cases_df['time'], cases_df[variables_df['experiment_tag'][i]],
945
+ linewidth=0.75, label=var)
946
+ plt.ylabel(relap_labels.get(variables_df['alphanum'][i]))
947
+ plt.xlabel('Time (s)')
948
+ plt.xlim(float(variables_df['timei'][i]), float(variables_df['timee'][i]))
949
+ if float(variables_df['ymin'][i]) !=0 or float(variables_df['ymax'][i]) !=0:
950
+ plt.ylim(variables_df['ymin'][i], variables_df['ymax'][i])
951
+ plt.grid(b=True, which='major', linestyle=':', linewidth=1.0, alpha=0.8,
952
+ color='grey')
953
+ plt.legend()
954
+ plt.tight_layout()
955
+ plt.savefig(figures_loc + variable[0] +'_'+ variable[-1] +'.'+ figures_type,
956
+ format= figures_type, dpi=300, bbox_inches='tight')
957
+ if show_plot : plt.show()
958
+ if hideplots :
959
+ plt.clf()
960
+ plt.close()
961
+
962
+
963
+ def append_variable(dataframe, experiment_tag: str, unit: str,
964
+ general='no', figure_tag=''):
965
+ """ Append a variable to the variables dataframe.
966
+
967
+ :dataframe: dataframe where to add the line
968
+ :experiment_tag:
969
+ :unit:
970
+ :general: (optional) change column 'general' if you wish
971
+ :figure_tag: (optional) same as experiment_tag if not entered
972
+ :returns: the dataframe with the added row
973
+
974
+ :USAGE:
975
+ variables = append_variable(variables, 'Maximum_PCT', 'K', 'top_right')
976
+ """
977
+ if figure_tag == '' : figure_tag = experiment_tag
978
+ new_line = dataframe.loc[[0]]
979
+ new_line.loc[0, 'experiment_tag'] = experiment_tag
980
+ new_line.loc[0, 'figure_tag'] = figure_tag
981
+ new_line.loc[0, 'unit'] = unit
982
+ new_line.loc[0, 'general'] = general
983
+ dataframe = pd.concat([dataframe, new_line], ignore_index=True)
984
+ return dataframe
985
+
986
+ def read_exp(expdata_loc: str):
987
+ """TODO: Docstring for read_exp.
988
+
989
+ :expdata_loc: the file path to the experimental data
990
+ :returns: Ndarray with the experimental data
991
+ :USAGE:
992
+ your_exp_data = read_exp('your_path.txt')
993
+
994
+ """
995
+ global exp_file_bool
996
+ try :
997
+ dataExp=np.genfromtxt(expdata_loc, dtype=float, delimiter='\t',
998
+ names=True)
999
+ exp_file_bool = True
1000
+ except :
1001
+ print('WARNING! Experimental data not used')
1002
+ dataExp = np.zeros(shape=(10, 10))
1003
+ exp_file_bool = False
1004
+ return dataExp
1005
+ def print_ss(case, exp, llista= False, end_ss = 0, lenght = 60):
1006
+ """TODO: Docstring for print_ss.
1007
+
1008
+ :case: TODO
1009
+ :exp: TODO
1010
+ :llista: TODO
1011
+ :end_ss: TODO
1012
+ :lenght: TODO
1013
+ :returns: TODO
1014
+
1015
+ """
1016
+ def avg_ss(var):
1017
+ """ Makes the average of the variable for the specified lenght
1018
+ :var: name of the variable
1019
+ """
1020
+ i = 0
1021
+ while case['time'][i] < (end_ss - lenght):
1022
+ index_start = i
1023
+ i += 1
1024
+ while case['time'][i] < end_ss:
1025
+ index_end = i
1026
+ i += 1
1027
+ return sum(case[var][index_start:index_end]) / (index_end - index_start)
1028
+ dash = '-' * 50
1029
+ print(dash)
1030
+ print('{:<20s}{:>8s}{:>18s}'.format('variable', 'calc', 'experiment'))
1031
+ print(dash)
1032
+ for var in llista:
1033
+ print('{:<20s}{:>8E}{:>18E}'.format(var, avg_ss(var), avg_ss(var)))
1034
+ print(dash)
1035
+
1036
+ def mkdir(path: str):
1037
+ try :
1038
+ os.mkdir(path)
1039
+ except OSError :
1040
+ print(30*'-'+'WARNING'+30*'-')
1041
+ print(' directory ' + path + ' already present')
1042
+ print(67*'-')
1043
+
1044
+ def mypie(data: list, labels: list, title='',unit: str='%'):
1045
+ """TODO: Docstring for mypie.
1046
+ :data: a list or array with the data to plot
1047
+ :labels: a list or array with the labels
1048
+ :title: title of the pie
1049
+ :unit: the unit of the variables
1050
+ :returns: a pie plot
1051
+ """
1052
+ # colors = ['#E6E6FA', '#D8BFD8', '#DDA0DD', '#EE82EE', '#DA70D6', '#FF00FF',
1053
+ # '#FF00FF', '#BA55D3', '#9370DB', '#8A2BE2', '#9400D3', '#9932CC',
1054
+ # '#8B008B', '#800080', '#4B0082']
1055
+ colors = ['#FCD8F9', '#F8B1F1', '#F273E7', '#EE44DE', '#EB25D8', '#DA14C7',
1056
+ '#A40F96', '#7C0C72']
1057
+
1058
+ fig, ax = plt.subplots(figsize=(10, 5), subplot_kw=dict(aspect="equal"))
1059
+ perc = [str(round(e / s * 100., 1)) + '%' for s in (sum(data),) for e in data]
1060
+ wedges, texts = ax.pie(data, colors=colors, wedgeprops=dict(width=0.5), startangle=-40)
1061
+ bbox_props = dict(boxstyle="square,pad=0.3", fc="w", ec="k", lw=0.72)
1062
+ kw = dict(arrowprops=dict(arrowstyle="-"),
1063
+ #bbox=bbox_props,
1064
+ zorder=0, va="center")
1065
+ for i, p in enumerate(wedges):
1066
+ ang = (p.theta2 - p.theta1)/2. + p.theta1
1067
+ y = np.sin(np.deg2rad(ang))
1068
+ x = np.cos(np.deg2rad(ang))
1069
+ horizontalalignment = {-1: "right", 1: "left"}[int(np.sign(x))]
1070
+ connectionstyle = "angle,angleA=0,angleB={}".format(ang)
1071
+ kw["arrowprops"].update({"connectionstyle": connectionstyle})
1072
+ ax.annotate(labels[i] + ' ' + perc[i], xy=(x, y), xytext=(1.2*np.sign(x), 1.2*y),
1073
+ horizontalalignment=horizontalalignment, fontsize=12, **kw)
1074
+ centre_circle = plt.Circle((0,0),0.40,fc='white')
1075
+ fig = plt.gcf()
1076
+ fig.gca().add_artist(centre_circle)
1077
+ total = sum(data)
1078
+ ax.annotate('Total\n{t:.0f}\n{u}'.format(t=total, u=unit), [0,0],
1079
+ xycoords='data', va='center', ha='center', fontsize=16)
1080
+ plt.title(title, fontsize=16)
1081
+ plt.tight_layout()
1082
+ plt.savefig(figures_loc + title.replace(' ','_')+'.'+figures_type,
1083
+ format=figures_type, dpi=300, bbox_inches='tight')
1084
+ plt.close('all')
1085
+ return fig, ax
1086
+
@@ -0,0 +1,7 @@
1
+ Metadata-Version: 2.1
2
+ Name: relap-py
3
+ Version: 0.0.1
4
+ Summary: Module for RELAP post-processing
5
+ Author: Jordi Freixa
6
+ Author-email: <jordi.freixa-terradas@upc.edu>
7
+ Keywords: relap,trace
@@ -0,0 +1,8 @@
1
+ README.md
2
+ setup.py
3
+ relap_py/__init__.py
4
+ relap_py/main.py
5
+ relap_py.egg-info/PKG-INFO
6
+ relap_py.egg-info/SOURCES.txt
7
+ relap_py.egg-info/dependency_links.txt
8
+ relap_py.egg-info/top_level.txt
@@ -0,0 +1 @@
1
+ relap_py
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,24 @@
1
+ from setuptools import setup, find_packages
2
+ import os
3
+
4
+ # here = os.path.abspath(os.path.dirname(__file__))
5
+
6
+ # with codecs.open(os.path.join(here, "README.md"), encoding="utf-8") as fh:
7
+ # long_description = "\n" + fh.read()
8
+
9
+ VERSION = '0.0.1'
10
+ DESCRIPTION = 'Module for RELAP post-processing'
11
+
12
+ # Setting up
13
+ setup(
14
+ name="relap_py",
15
+ version=VERSION,
16
+ author="Jordi Freixa",
17
+ author_email="<jordi.freixa-terradas@upc.edu>",
18
+ description=DESCRIPTION,
19
+ # long_description_content_type="text/markdown",
20
+ # long_description=long_description,
21
+ packages=find_packages(),
22
+ # install_requires=['os', 'matplotlib'],
23
+ keywords=['relap', 'trace']
24
+ )