def build_namelist_pc(rho_core,Mcore): import f90nml #fortran namelist tools from f90nml.namelist import Namelist as NmlDict #namelist class #build namelist nml=NmlDict() sj=NmlDict() #star_job cn=NmlDict() #controls pg=NmlDict() #pgplot pg['read_extra_pgstar_inlist1']=True pg['extra_pgstar_inlist1_name']='inlist_pgstar' sj['read_extra_star_job_inlist1']=True sj['extra_star_job_inlist1_name']='inlist_cache' sj['show_log_description_at_start'] = False sj['load_saved_model'] = True sj['saved_model_name'] = 'model_in.mod' sj['save_model_when_terminate'] = True sj['save_model_filename'] = 'model_out.mod' sj['set_initial_age'] = True sj['initial_age'] = 0 sj['pgstar_flag'] = False sj['change_v_flag'] = True sj['new_v_flag'] = False sj['eos_file_prefix'] = 'mesa' sj['kappa_file_prefix'] = 'gs98' sj['kappa_lowT_prefix'] = 'lowT_Freedman11' sj['change_lnPgas_flag'] = True sj['new_lnPgas_flag'] = True sj['set_initial_model_number'] = True sj['initial_model_number'] = 0 sj['relax_core'] = True sj['new_core_mass'] = Mcore sj['core_avg_rho'] = rho_core sj['dlg_core_mass_per_step'] = 0.05 sj['relax_core_years_for_dt'] = 0.1 sj['core_avg_eps'] = 0 cn['T_mix_limit'] = -1 cn['logQ_limit'] = 10 cn['mixing_length_alpha'] = 1.89 cn['MLT_option'] = 'Henyey' cn['write_header_frequency'] = 1 cn['terminal_cnt'] = 10 cn['profile_interval'] = 10000 cn['varcontrol_target'] = 0.01 cn['mesh_delta_coeff'] = 1 cn['max_age'] = 1e3 cn['max_model_number']=2000 nml['star_job']=sj nml['controls']=cn nml['pgstar']=pg return nml;
def build_namelist_get_profile(log_directory="."): import f90nml #fortran namelist tools from f90nml.namelist import Namelist as NmlDict #namelist class #build namelist nml = NmlDict() sj = NmlDict() #star_job cn = NmlDict() #controls pg = NmlDict() #pgplot #declare some xctrl arrays x_ctrl = [0.0] * 30 x_integer_ctrl = [0] * 5 x_logical_ctrl = [False] * 10 x_ctrl[8] = 1 #safety factor x_ctrl[9] = 1 #safety factor x_ctrl[11] = 100 # sep AU x_ctrl[12] = 1 # stellar mass Msun pg['read_extra_pgstar_inlist1'] = False sj['read_extra_star_job_inlist1'] = False cn['photostep'] = 1000 # Store photos and logs in user-specified directory cn['log_directory'] = log_directory cn['photo_directory'] = log_directory sj['show_log_description_at_start'] = False sj['load_saved_model'] = True sj['saved_model_name'] = 'model_in.mod' sj['save_model_when_terminate'] = False sj['profile_starting_model'] = True sj['set_initial_age'] = False cn['max_age'] = 0.0 nml['star_job'] = sj nml['controls'] = cn nml['pgstar'] = pg return nml
def test_f90repr(self): nml = NmlDict() self.assertEqual(nml.f90repr(1), "1") self.assertEqual(nml.f90repr(1.0), "1.0") self.assertEqual(nml.f90repr(1 + 2j), "(1.0, 2.0)") self.assertEqual(nml.f90repr(True), ".true.") self.assertEqual(nml.f90repr(False), ".false.") self.assertEqual(nml.f90repr("abc"), "'abc'") for ptype in ({}, [], set()): self.assertRaises(ValueError, nml.f90repr, ptype)
def read(self, nml_fname, nml_patch_in=None, patch_fname=None): """Parse a Fortran 90 namelist file and store the contents. >>> from f90nml.parser import Parser >>> parser = Parser() >>> data_nml = parser.read('data.nml')""" nml_file = open(nml_fname, 'r') if nml_patch_in: nml_patch = copy.deepcopy(nml_patch_in) if not patch_fname: patch_fname = nml_fname + '~' elif nml_fname == patch_fname: nml_file.close() raise ValueError('f90nml: error: Patch filepath cannot be the ' 'same as the original filepath.') self.pfile = open(patch_fname, 'w') else: nml_patch = {} f90lex = shlex.shlex(nml_file) f90lex.whitespace = '' f90lex.wordchars += '.-+' # Include floating point tokens if nml_patch: f90lex.commenters = '' else: f90lex.commenters = '!' self.tokens = iter(f90lex) nmls = NmlDict() # TODO: Replace "while True" with an update_token() iterator self.update_tokens(write_token=False) while True: try: # Check for classic group terminator if self.token == 'end': self.update_tokens() # Ignore tokens outside of namelist groups while self.token not in ('&', '$'): self.update_tokens() except StopIteration: break # Create the next namelist self.update_tokens() g_name = self.token g_vars = NmlDict() v_name = None grp_patch = nml_patch.get(g_name, {}) # Populate the namelist group while g_name: if self.token not in ('=', '%', '('): self.update_tokens() # Set the next active variable if self.token in ('=', '(', '%'): try: v_name, v_values = self.parse_variable( g_vars, patch_nml=grp_patch) except ValueError: nml_file.close() if self.pfile: self.pfile.close() raise if v_name in g_vars: v_prior_values = g_vars[v_name] v_values = merge_values(v_prior_values, v_values) if v_name in g_vars and type(g_vars[v_name]) is NmlDict: g_vars[v_name].update(v_values) else: g_vars[v_name] = v_values # Deselect variable v_name = None v_values = [] # Finalise namelist group if self.token in ('/', '&', '$'): # Append any remaining patched variables for v_name, v_val in grp_patch.items(): g_vars[v_name] = v_val v_strs = var_strings(v_name, v_val) for v_str in v_strs: self.pfile.write(' {0}\n'.format(v_str)) # Append the grouplist to the namelist if g_name in nmls: g_update = nmls[g_name] # Update to list of groups if not type(g_update) is list: g_update = [g_update] g_update.append(g_vars) else: g_update = g_vars nmls[g_name] = g_update # Reset state g_name, g_vars = None, None try: self.update_tokens() except StopIteration: break nml_file.close() if self.pfile: self.pfile.close() return nmls
def parse_variable(self, parent, patch_nml=None): """Parse a variable and return its name and values.""" if not patch_nml: patch_nml = {} v_name = self.prior_token v_values = [] # Patch state patch_values = None write_token = v_name not in patch_nml if self.token == '(': v_indices = self.parse_index() # TODO: Multidimensional support i_s = 1 if not v_indices[0][0] else v_indices[0][0] i_e = v_indices[0][1] i_r = 1 if not v_indices[0][2] else v_indices[0][2] if i_e: v_idx = iter(range(i_s, i_e, i_r)) else: v_idx = (i_s + i_r * k for k in itertools.count()) else: v_idx = None if self.token == '%': # Resolve the derived type if parent and v_name in parent: v_parent = parent[v_name] else: v_parent = [] self.update_tokens() self.update_tokens() v_att, v_att_vals = self.parse_variable(v_parent) next_value = NmlDict() next_value[v_att] = v_att_vals append_value(v_values, next_value, v_idx) else: # Construct the variable array assert self.token == '=' n_vals = None prior_ws_sep = ws_sep = False self.update_tokens() if v_name in patch_nml: patch_values = f90repr(patch_nml.pop(v_name)) if not type(patch_values) is list: patch_values = [patch_values] for p_val in patch_values: self.pfile.write(p_val) # Add variables until next variable trigger while (self.token not in ('=', '(', '%') or (self.prior_token, self.token) == ('=', '(')): # Check for repeated values if self.token == '*': n_vals = self.parse_value(write_token) assert type(n_vals) is int self.update_tokens(write_token) elif not n_vals: n_vals = 1 # First check for implicit null values if self.prior_token in ('=', '%', ','): if (self.token in (',', '/', '&', '$') and not (self.prior_token == ',' and self.token in ('/', '&', '$'))): append_value(v_values, None, v_idx, n_vals) elif self.prior_token == '*': if self.token not in ('/', '&', '$'): self.update_tokens(write_token) if (self.token == '=' or (self.token in ('/', '&', '$') and self.prior_token == '*')): next_value = None else: next_value = self.parse_value(write_token) append_value(v_values, next_value, v_idx, n_vals) else: next_value = self.parse_value(write_token) # Finished reading old value, we can again write tokens write_token = True # Check for escaped strings if (v_values and (type(v_values[-1]) is str) and type(next_value) is str and not prior_ws_sep): quote_char = self.prior_token[0] v_values[-1] = quote_char.join( [v_values[-1], next_value]) else: append_value(v_values, next_value, v_idx, n_vals) # Exit for end of nml group (/, &, $) or null broadcast (=) if self.token in ('/', '&', '$', '='): break else: prior_ws_sep = ws_sep ws_sep = self.update_tokens(write_token) if patch_values: v_values = patch_values if not v_idx: v_values = delist(v_values) return v_name, v_values
def build_namelist_mp_hold(Thold, L_M_ratio, Flux, Sigma, log_directory="."): import f90nml #fortran namelist tools from f90nml.namelist import Namelist as NmlDict #namelist class #build namelist nml = NmlDict() sj = NmlDict() #star_job cn = NmlDict() #controls pg = NmlDict() #pgplot #declare some xctrl arrays x_ctrl = [0.0] * 30 x_integer_ctrl = [0] * 5 x_logical_ctrl = [False] * 10 x_ctrl[8] = 1 #safety factor x_ctrl[9] = 1 #safety factor x_ctrl[11] = 100 # sep AU x_ctrl[12] = 1 # stellar mass Msun x_ctrl[21] = L_M_ratio # luminisoity to core mass ratio x_logical_ctrl[0] = True # radio-active heating x_logical_ctrl[5] = True # core/envelope heating pg['read_extra_pgstar_inlist1'] = False sj['read_extra_star_job_inlist1'] = False cn['photostep'] = 1000 # Store photos and logs in user-specified directory cn['log_directory'] = log_directory cn['photo_directory'] = log_directory sj['show_log_description_at_start'] = False sj['load_saved_model'] = True sj['saved_model_name'] = 'model_in.mod' sj['save_model_when_terminate'] = True sj['save_model_filename'] = 'model_out.mod' sj['set_initial_age'] = True sj['initial_age'] = 0 sj['pgstar_flag'] = False sj['change_v_flag'] = True sj['new_v_flag'] = False sj['eos_file_prefix'] = 'mesa' sj['kappa_file_prefix'] = 'gs98' sj['kappa_lowT_prefix'] = 'lowT_Freedman11' sj['change_lnPgas_flag'] = True sj['new_lnPgas_flag'] = True sj['set_initial_model_number'] = True sj['initial_model_number'] = 0 sj['set_irradiation'] = True sj['set_to_this_irrad_flux'] = Flux sj['irrad_col_depth'] = Sigma cn['T_mix_limit'] = -1 cn['logQ_limit'] = 10 cn['mixing_length_alpha'] = 1.89 cn['MLT_option'] = 'Henyey' cn['write_header_frequency'] = 10 cn['terminal_cnt'] = 100 cn['profile_interval'] = 10000 cn['varcontrol_target'] = 0.01 cn['mesh_delta_coeff'] = 1 cn['max_age'] = Thold cn['use_other_energy'] = True cn['x_ctrl'] = x_ctrl cn['x_logical_ctrl'] = x_logical_ctrl cn['x_integer_ctrl'] = x_integer_ctrl cn['max_model_number'] = 2000 nml['star_job'] = sj nml['controls'] = cn nml['pgstar'] = pg return nml
def build_namelist_ev_Fsigma_we(Tmax, Flux, Sigma, Temp, sep, stop_mass, ES, log_directory=".", HIST_CADENCE=5.e7, include_core=True): import f90nml #fortran namelist tools from f90nml.namelist import Namelist as NmlDict #namelist class #build namelist nml = NmlDict() sj = NmlDict() #star_job cn = NmlDict() #controls pg = NmlDict() #pgplot #declare some xctrl arrays x_ctrl = [0.0] * 30 x_integer_ctrl = [0] * 5 x_logical_ctrl = [False] * 10 x_ctrl[8] = 1 #safety factor x_ctrl[9] = 1 #safety factor x_ctrl[11] = sep # sep AU x_ctrl[12] = 1 # stellar mass Msun x_ctrl[18] = Temp x_ctrl[23] = 6.9183e7 #saturation for X-rays x_ctrl[24] = 10**-3.6 x_ctrl[25] = 1.19 x_logical_ctrl[0] = include_core # radio-active heating x_logical_ctrl[1] = include_core # core heat capacity x_logical_ctrl[5] = False # core/envelope heating x_logical_ctrl[6] = True #evaporation x_logical_ctrl[7] = ES # include evolution of star or not x_logical_ctrl[8] = True # uniform history data x_ctrl[0] = HIST_CADENCE # history cadence cn['max_years_for_timestep'] = HIST_CADENCE # history cadence pg['read_extra_pgstar_inlist1'] = False sj['read_extra_star_job_inlist1'] = False cn['photostep'] = 1000 # Store photos and logs in user-specified directory cn['log_directory'] = log_directory cn['photo_directory'] = log_directory sj['show_log_description_at_start'] = False sj['load_saved_model'] = True sj['saved_model_name'] = 'model_in.mod' sj['save_model_when_terminate'] = True sj['save_model_filename'] = 'model_out.mod' sj['set_initial_age'] = True sj['initial_age'] = 0 sj['set_initial_dt'] = True sj['years_for_initial_dt'] = 1e5 sj['pgstar_flag'] = False sj['change_v_flag'] = True sj['new_v_flag'] = True sj['eos_file_prefix'] = 'mesa' sj['kappa_file_prefix'] = 'gs98' sj['kappa_lowT_prefix'] = 'lowT_Freedman11' sj['change_lnPgas_flag'] = True sj['new_lnPgas_flag'] = True sj['set_initial_model_number'] = True sj['initial_model_number'] = 0 sj['set_irradiation'] = True sj['set_to_this_irrad_flux'] = Flux sj['irrad_col_depth'] = Sigma cn['T_mix_limit'] = -1 cn['logQ_limit'] = 10 cn['mixing_length_alpha'] = 1.89 cn['MLT_option'] = 'Henyey' cn['write_header_frequency'] = 10 cn['terminal_cnt'] = 100 cn['profile_interval'] = 10000 cn['varcontrol_target'] = 3e-4 cn['mesh_delta_coeff'] = 1 cn['max_age'] = Tmax cn['max_years_for_timestep'] = 5e7 cn['use_other_energy'] = True cn['use_other_wind'] = True cn['star_mass_min_limit'] = stop_mass cn['x_ctrl'] = x_ctrl cn['x_logical_ctrl'] = x_logical_ctrl cn['x_integer_ctrl'] = x_integer_ctrl cn['min_q_for_k_below_const_q'] = 0.9 cn['min_q_for_k_const_mass'] = 0.5 nml['star_job'] = sj nml['controls'] = cn nml['pgstar'] = pg return nml
def read(self, nml_fname, nml_patch_in=None, patch_fname=None): """Parse a Fortran 90 namelist file and store the contents. >>> from f90nml.parser import Parser >>> parser = Parser() >>> data_nml = parser.read('data.nml')""" nml_file = open(nml_fname, 'r') if nml_patch_in: if not isinstance(nml_patch_in, dict): nml_file.close() raise ValueError('Input patch must be a dict or an NmlDict.') nml_patch = copy.deepcopy(NmlDict(nml_patch_in)) if not patch_fname: patch_fname = nml_fname + '~' elif nml_fname == patch_fname: nml_file.close() raise ValueError('f90nml: error: Patch filepath cannot be the ' 'same as the original filepath.') self.pfile = open(patch_fname, 'w') else: nml_patch = NmlDict() f90lex = shlex.shlex(nml_file) f90lex.whitespace = '' f90lex.wordchars += '.-+' # Include floating point tokens if nml_patch: f90lex.commenters = '' else: f90lex.commenters = '!' self.tokens = iter(f90lex) nmls = NmlDict() # TODO: Replace "while True" with an update_token() iterator self.update_tokens(write_token=False) while True: try: # Check for classic group terminator if self.token == 'end': self.update_tokens() # Ignore tokens outside of namelist groups while self.token not in ('&', '$'): self.update_tokens() except StopIteration: break # Create the next namelist self.update_tokens() g_name = self.token g_vars = NmlDict() v_name = None grp_patch = nml_patch.get(g_name, {}) # Populate the namelist group while g_name: if self.token not in ('=', '%', '('): self.update_tokens() # Set the next active variable if self.token in ('=', '(', '%'): try: v_name, v_values = self.parse_variable( g_vars, patch_nml=grp_patch) except ValueError: nml_file.close() if self.pfile: self.pfile.close() raise if v_name in g_vars: v_prior_values = g_vars[v_name] v_values = merge_values(v_prior_values, v_values) if v_name in g_vars and isinstance(g_vars[v_name], dict): g_vars[v_name].update(v_values) else: g_vars[v_name] = v_values # Deselect variable v_name = None v_values = [] # Finalise namelist group if self.token in ('/', '&', '$'): # Append any remaining patched variables for v_name, v_val in grp_patch.items(): g_vars[v_name] = v_val v_strs = nmls.var_strings(v_name, v_val) for v_str in v_strs: self.pfile.write(' {0}\n'.format(v_str)) # Append the grouplist to the namelist if g_name in nmls: g_update = nmls[g_name] # Update to list of groups if not isinstance(g_update, list): g_update = [g_update] g_update.append(g_vars) else: g_update = g_vars nmls[g_name] = g_update # Reset state g_name, g_vars = None, None try: self.update_tokens() except StopIteration: break nml_file.close() if self.pfile: self.pfile.close() return nmls
def parse_variable(self, parent, patch_nml=None): """Parse a variable and return its name and values.""" if not patch_nml: patch_nml = NmlDict() v_name = self.prior_token v_values = [] # Patch state patch_values = None write_token = v_name not in patch_nml if self.token == '(': v_indices = self.parse_index() # TODO: Multidimensional support i_s = 1 if not v_indices[0][0] else v_indices[0][0] i_e = v_indices[0][1] i_r = 1 if not v_indices[0][2] else v_indices[0][2] if i_e: v_idx = iter(range(i_s, i_e, i_r)) else: v_idx = (i_s + i_r * k for k in itertools.count()) else: v_idx = None if self.token == '%': # Resolve the derived type if parent and v_name in parent: v_parent = parent[v_name] else: v_parent = [] self.update_tokens() self.update_tokens() v_att, v_att_vals = self.parse_variable(v_parent) next_value = NmlDict() next_value[v_att] = v_att_vals append_value(v_values, next_value, v_idx) else: # Construct the variable array assert self.token == '=' n_vals = None prior_ws_sep = ws_sep = False self.update_tokens() if v_name in patch_nml: patch_values = patch_nml.f90repr(patch_nml.pop(v_name)) if not isinstance(patch_values, list): patch_values = [patch_values] for p_val in patch_values: self.pfile.write(p_val) # Add variables until next variable trigger while (self.token not in ('=', '(', '%') or (self.prior_token, self.token) == ('=', '(')): # Check for repeated values if self.token == '*': n_vals = self.parse_value(write_token) assert isinstance(n_vals, int) self.update_tokens(write_token) elif not n_vals: n_vals = 1 # First check for implicit null values if self.prior_token in ('=', '%', ','): if (self.token in (',', '/', '&', '$') and not (self.prior_token == ',' and self.token in ('/', '&', '$'))): append_value(v_values, None, v_idx, n_vals) elif self.prior_token == '*': if self.token not in ('/', '&', '$'): self.update_tokens(write_token) if (self.token == '=' or (self.token in ('/', '&', '$') and self.prior_token == '*')): next_value = None else: next_value = self.parse_value(write_token) append_value(v_values, next_value, v_idx, n_vals) else: next_value = self.parse_value(write_token) # Finished reading old value, we can again write tokens write_token = True # Check for escaped strings if (v_values and isinstance(v_values[-1], str) and isinstance(next_value, str) and not prior_ws_sep): quote_char = self.prior_token[0] v_values[-1] = quote_char.join([v_values[-1], next_value]) else: append_value(v_values, next_value, v_idx, n_vals) # Exit for end of nml group (/, &, $) or null broadcast (=) if self.token in ('/', '&', '$', '='): break else: prior_ws_sep = ws_sep ws_sep = self.update_tokens(write_token) if patch_values: v_values = patch_values if not v_idx: v_values = delist(v_values) return v_name, v_values
def build_namelist_ev_nothing(Tmax): import f90nml #fortran namelist tools from f90nml.namelist import Namelist as NmlDict #namelist class #build namelist nml=NmlDict() sj=NmlDict() #star_job cn=NmlDict() #controls pg=NmlDict() #pgplot #declare some xctrl arrays x_ctrl=[0.0]*30 x_integer_ctrl=[0]*5 x_logical_ctrl=[False]*10 x_ctrl[8]=1 #safety factor x_ctrl[9]=1 #safety factor x_ctrl[11]=100 # sep AU x_ctrl[12]=1 # stellar mass Msun x_logical_ctrl[0]=False # radio-active heating x_logical_ctrl[5]=False # core/envelope heating x_logical_ctrl[7]=False # evolve star pg['read_extra_pgstar_inlist1']=True pg['extra_pgstar_inlist1_name']='inlist_pgstar' sj['read_extra_star_job_inlist1']=True sj['extra_star_job_inlist1_name']='inlist_cache' sj['show_log_description_at_start'] = False sj['load_saved_model'] = True sj['saved_model_name'] = 'model_in.mod' sj['save_model_when_terminate'] = True sj['save_model_filename'] = 'model_out.mod' sj['set_initial_age'] = True sj['initial_age'] = 0 sj['set_initial_dt']=True sj['years_for_initial_dt']=1e5 sj['pgstar_flag'] = False sj['change_v_flag'] = True sj['new_v_flag'] = True sj['eos_file_prefix'] = 'mesa' sj['kappa_file_prefix'] = 'gs98' sj['kappa_lowT_prefix'] = 'lowT_Freedman11' sj['change_lnPgas_flag'] = True sj['new_lnPgas_flag'] = True sj['set_initial_model_number'] = True sj['initial_model_number'] = 0 sj['set_irradiation'] = False cn['T_mix_limit'] = -1 cn['logQ_limit'] = 10 cn['mixing_length_alpha'] = 1.89 cn['MLT_option'] = 'Henyey' cn['write_header_frequency'] = 10 cn['terminal_cnt'] = 100 cn['profile_interval'] = 10000 cn['varcontrol_target'] = 1e-4 cn['mesh_delta_coeff'] = 1 cn['max_age'] = Tmax cn['max_years_for_timestep']=1e8 cn['use_other_energy']=True cn['x_ctrl']=x_ctrl cn['x_logical_ctrl']=x_logical_ctrl cn['x_integer_ctrl']=x_integer_ctrl cn['max_model_number']=2000 nml['star_job']=sj nml['controls']=cn nml['pgstar']=pg return nml;