mesaport.Access.gyre_access
1import glob 2import os 3# from . import loader 4import shutil 5from . import access_helper 6from .support.utils import cwd 7 8from threading import Lock 9file_operation_lock = Lock() 10 11""" 12This module defines the `GyreAccess` class, which handles GYRE input file operations. 13 14Attributes: 15 path (str): The path to the GYRE input file. 16 binary (str): The name of the binary file to be used. 17 target (str): The target to be used. 18 19Methods: 20 load(gyre_in="gyre.in"): Loads the GYRE input file into the project directory. 21 set(arg, gyre_in="gyre.in"): Sets the value of a parameter in the inlist file. 22 modify_gyre_params(wdir, filename, data_format, gyre_in="gyre.in", diff_scheme='MAGNUS_GL2'): Modifies the GYRE input file parameters. 23""" 24 25class GyreAccess: 26 def __init__(self): 27 """ 28 Args: 29 path (str): The path to the GYRE input file. 30 binary (str): The name of the binary file to be used. 31 target (str): The target to be used. 32 """ 33 self.check_env() 34 self.default_sections = self.gyreDefaults() 35 36 def check_env(self): 37 """ 38 Checks if GYRE_DIR is set in the environment. 39 """ 40 if "GYRE_DIR" not in os.environ: 41 raise EnvironmentError("GYRE_DIR is not set in your enviroment. Be sure to set it properly!!") 42 43 def load(self, gyre_in="gyre.in", dest=None): 44 """ 45 Loads the GYRE input file into the project directory. 46 """ 47 if dest is None: 48 dest = os.path.join(self.projectDir, "LOGS", 'gyre.in') 49 shutil.copy(gyre_in, os.path.join(dest, 'gyre.in')) 50 51 def gyreDefaults(self): 52 """Reads the defaults files and returns a dictionary with all the parameters and their values. 53 Returns: 54 dict: A dictionary with all the parameters and their values. 55 """ 56 gyre_dir = os.path.abspath(os.environ["GYRE_DIR"]) 57 gyre_defaults_dir = os.path.join(gyre_dir, "docs/source/ref-guide/input-files") 58 if not os.path.exists(gyre_defaults_dir): 59 gyre_defaults_dir = os.path.join(gyre_dir, "doc/source/ref-guide/input-files") 60 gyre_defaults_dir = os.path.join(gyre_defaults_dir, "*") 61 defaultsFiles = glob.glob(gyre_defaults_dir) 62 # sections = ["&"+name.split("/")[-1].split('.')[0].split('-')[0] for name in defaultsFiles] 63 # print(sections) 64 section_parameters = {} 65 for i, file in enumerate(defaultsFiles): 66 params = [] 67 sections = [] 68 with open(file) as file: 69 for line in file: 70 if ":nml_g:" in line: 71 splits = line.split(":nml_g:") 72 for s in splits: 73 if "`" in s: 74 sections.append("&"+s.split("`")[1]) 75 if ":nml_n:" in line: 76 params.append(line.split(":nml_n:")[1].split("`")[1]) 77 sections = list(set(sections)) 78 for section in sections: 79 section_parameters[section] = params 80 return section_parameters 81 82 83 def writetoGyreFile(self, wdir, parameter, value, default_section=None, gyre_in="gyre.in"): 84 """Writes the parameter and its value to the inlist file. 85 86 Args: 87 filename (str): The path to the inlist file. 88 parameter (str): The parameter to be written. 89 value (str): The value of the parameter to be written. 90 default_section (str): The section in which the parameter is to be written. 91 sections (list): A list with the sections of the inlist file. 92 """ 93 if default_section is None: 94 for section, values in self.default_sections.items(): 95 if parameter in values: 96 default_section = section 97 if default_section is None: 98 raise TypeError(f"Parameter {parameter} not found in any GYRE input files.") 99 this_section = False 100 with cwd(wdir): 101 with file_operation_lock: 102 with open(gyre_in, "r") as file: 103 lines = file.readlines() 104 with open(gyre_in, "w+") as f: 105 indent = " " 106 for line in lines: 107 edited = False 108 if default_section in line: 109 this_section = True 110 if this_section: 111 if parameter in line: 112 if parameter == line.split("=")[0].strip(): 113 f.write(line.replace(line.split("=")[1], f" {value} ! Changed\n")) 114 edited = True 115 this_section = False 116 elif line[0] == "/": 117 f.write(indent) 118 f.write(f"{parameter} = {value} ! Added\n") 119 f.write("/") 120 edited = True 121 this_section = False 122 if not edited: 123 f.write(line) 124 125 126 127 def modify_gyre_params(self, wdir, filename, data_format, gyre_in="gyre.in", diff_scheme='MAGNUS_GL2'): 128 if data_format == "GYRE": 129 file_format = "MESA" 130 elif data_format == "FGONG": 131 file_format = "FGONG" 132 else: 133 file_format = "GSM" 134 self.writetoGyreFile(wdir, parameter="model_type", value="'EVOL'", default_section="&model", gyre_in=gyre_in) 135 self.writetoGyreFile(wdir, parameter="file_format", value=f"'{file_format}'", default_section="&model", gyre_in=gyre_in) 136 self.writetoGyreFile(wdir, parameter="file", value=f"'{filename}'", default_section="&model", gyre_in=gyre_in) 137 self.writetoGyreFile(wdir, parameter="summary_file", value=f"'{filename.split('.')[0]}-freqs.dat'", default_section="&ad_output", gyre_in=gyre_in) 138 self.writetoGyreFile(wdir, parameter="summary_file", value=f"'{filename.split('.')[0]}-freqs-nad.dat'", default_section="&nad_output", gyre_in=gyre_in) 139 140 141 def set(self, arg, wdir, gyre_in="gyre.in"): 142 """Sets the value of a parameter in the inlist file. 143 144 Args: 145 arg (dict or list of dicts): A dictionary or a list of dictionaries with the parameters to be set. 146 """ 147 if isinstance(arg, dict): 148 for key, value in arg.items(): 149 self.writetoGyreFile(wdir, key, access_helper.toFortranType(value), gyre_in=gyre_in) 150 elif isinstance(arg, list): 151 for item in arg: 152 for key, value in item.items(): 153 self.writetoGyreFile(wdir, key, access_helper.toFortranType(value), gyre_in=gyre_in) 154 elif arg is None: 155 pass 156 else: 157 raise TypeError("Argument must be a dictionary or a list of dictionaries.") 158
file_operation_lock =
<unlocked _thread.lock object>
This module defines the GyreAccess
class, which handles GYRE input file operations.
Attributes:
- path (str): The path to the GYRE input file.
- binary (str): The name of the binary file to be used.
- target (str): The target to be used.
Methods:
load(gyre_in="gyre.in"): Loads the GYRE input file into the project directory. set(arg, gyre_in="gyre.in"): Sets the value of a parameter in the inlist file. modify_gyre_params(wdir, filename, data_format, gyre_in="gyre.in", diff_scheme='MAGNUS_GL2'): Modifies the GYRE input file parameters.
class
GyreAccess:
26class GyreAccess: 27 def __init__(self): 28 """ 29 Args: 30 path (str): The path to the GYRE input file. 31 binary (str): The name of the binary file to be used. 32 target (str): The target to be used. 33 """ 34 self.check_env() 35 self.default_sections = self.gyreDefaults() 36 37 def check_env(self): 38 """ 39 Checks if GYRE_DIR is set in the environment. 40 """ 41 if "GYRE_DIR" not in os.environ: 42 raise EnvironmentError("GYRE_DIR is not set in your enviroment. Be sure to set it properly!!") 43 44 def load(self, gyre_in="gyre.in", dest=None): 45 """ 46 Loads the GYRE input file into the project directory. 47 """ 48 if dest is None: 49 dest = os.path.join(self.projectDir, "LOGS", 'gyre.in') 50 shutil.copy(gyre_in, os.path.join(dest, 'gyre.in')) 51 52 def gyreDefaults(self): 53 """Reads the defaults files and returns a dictionary with all the parameters and their values. 54 Returns: 55 dict: A dictionary with all the parameters and their values. 56 """ 57 gyre_dir = os.path.abspath(os.environ["GYRE_DIR"]) 58 gyre_defaults_dir = os.path.join(gyre_dir, "docs/source/ref-guide/input-files") 59 if not os.path.exists(gyre_defaults_dir): 60 gyre_defaults_dir = os.path.join(gyre_dir, "doc/source/ref-guide/input-files") 61 gyre_defaults_dir = os.path.join(gyre_defaults_dir, "*") 62 defaultsFiles = glob.glob(gyre_defaults_dir) 63 # sections = ["&"+name.split("/")[-1].split('.')[0].split('-')[0] for name in defaultsFiles] 64 # print(sections) 65 section_parameters = {} 66 for i, file in enumerate(defaultsFiles): 67 params = [] 68 sections = [] 69 with open(file) as file: 70 for line in file: 71 if ":nml_g:" in line: 72 splits = line.split(":nml_g:") 73 for s in splits: 74 if "`" in s: 75 sections.append("&"+s.split("`")[1]) 76 if ":nml_n:" in line: 77 params.append(line.split(":nml_n:")[1].split("`")[1]) 78 sections = list(set(sections)) 79 for section in sections: 80 section_parameters[section] = params 81 return section_parameters 82 83 84 def writetoGyreFile(self, wdir, parameter, value, default_section=None, gyre_in="gyre.in"): 85 """Writes the parameter and its value to the inlist file. 86 87 Args: 88 filename (str): The path to the inlist file. 89 parameter (str): The parameter to be written. 90 value (str): The value of the parameter to be written. 91 default_section (str): The section in which the parameter is to be written. 92 sections (list): A list with the sections of the inlist file. 93 """ 94 if default_section is None: 95 for section, values in self.default_sections.items(): 96 if parameter in values: 97 default_section = section 98 if default_section is None: 99 raise TypeError(f"Parameter {parameter} not found in any GYRE input files.") 100 this_section = False 101 with cwd(wdir): 102 with file_operation_lock: 103 with open(gyre_in, "r") as file: 104 lines = file.readlines() 105 with open(gyre_in, "w+") as f: 106 indent = " " 107 for line in lines: 108 edited = False 109 if default_section in line: 110 this_section = True 111 if this_section: 112 if parameter in line: 113 if parameter == line.split("=")[0].strip(): 114 f.write(line.replace(line.split("=")[1], f" {value} ! Changed\n")) 115 edited = True 116 this_section = False 117 elif line[0] == "/": 118 f.write(indent) 119 f.write(f"{parameter} = {value} ! Added\n") 120 f.write("/") 121 edited = True 122 this_section = False 123 if not edited: 124 f.write(line) 125 126 127 128 def modify_gyre_params(self, wdir, filename, data_format, gyre_in="gyre.in", diff_scheme='MAGNUS_GL2'): 129 if data_format == "GYRE": 130 file_format = "MESA" 131 elif data_format == "FGONG": 132 file_format = "FGONG" 133 else: 134 file_format = "GSM" 135 self.writetoGyreFile(wdir, parameter="model_type", value="'EVOL'", default_section="&model", gyre_in=gyre_in) 136 self.writetoGyreFile(wdir, parameter="file_format", value=f"'{file_format}'", default_section="&model", gyre_in=gyre_in) 137 self.writetoGyreFile(wdir, parameter="file", value=f"'{filename}'", default_section="&model", gyre_in=gyre_in) 138 self.writetoGyreFile(wdir, parameter="summary_file", value=f"'{filename.split('.')[0]}-freqs.dat'", default_section="&ad_output", gyre_in=gyre_in) 139 self.writetoGyreFile(wdir, parameter="summary_file", value=f"'{filename.split('.')[0]}-freqs-nad.dat'", default_section="&nad_output", gyre_in=gyre_in) 140 141 142 def set(self, arg, wdir, gyre_in="gyre.in"): 143 """Sets the value of a parameter in the inlist file. 144 145 Args: 146 arg (dict or list of dicts): A dictionary or a list of dictionaries with the parameters to be set. 147 """ 148 if isinstance(arg, dict): 149 for key, value in arg.items(): 150 self.writetoGyreFile(wdir, key, access_helper.toFortranType(value), gyre_in=gyre_in) 151 elif isinstance(arg, list): 152 for item in arg: 153 for key, value in item.items(): 154 self.writetoGyreFile(wdir, key, access_helper.toFortranType(value), gyre_in=gyre_in) 155 elif arg is None: 156 pass 157 else: 158 raise TypeError("Argument must be a dictionary or a list of dictionaries.")
GyreAccess()
27 def __init__(self): 28 """ 29 Args: 30 path (str): The path to the GYRE input file. 31 binary (str): The name of the binary file to be used. 32 target (str): The target to be used. 33 """ 34 self.check_env() 35 self.default_sections = self.gyreDefaults()
Arguments:
- path (str): The path to the GYRE input file.
- binary (str): The name of the binary file to be used.
- target (str): The target to be used.
def
check_env(self):
37 def check_env(self): 38 """ 39 Checks if GYRE_DIR is set in the environment. 40 """ 41 if "GYRE_DIR" not in os.environ: 42 raise EnvironmentError("GYRE_DIR is not set in your enviroment. Be sure to set it properly!!")
Checks if GYRE_DIR is set in the environment.
def
load(self, gyre_in='gyre.in', dest=None):
44 def load(self, gyre_in="gyre.in", dest=None): 45 """ 46 Loads the GYRE input file into the project directory. 47 """ 48 if dest is None: 49 dest = os.path.join(self.projectDir, "LOGS", 'gyre.in') 50 shutil.copy(gyre_in, os.path.join(dest, 'gyre.in'))
Loads the GYRE input file into the project directory.
def
gyreDefaults(self):
52 def gyreDefaults(self): 53 """Reads the defaults files and returns a dictionary with all the parameters and their values. 54 Returns: 55 dict: A dictionary with all the parameters and their values. 56 """ 57 gyre_dir = os.path.abspath(os.environ["GYRE_DIR"]) 58 gyre_defaults_dir = os.path.join(gyre_dir, "docs/source/ref-guide/input-files") 59 if not os.path.exists(gyre_defaults_dir): 60 gyre_defaults_dir = os.path.join(gyre_dir, "doc/source/ref-guide/input-files") 61 gyre_defaults_dir = os.path.join(gyre_defaults_dir, "*") 62 defaultsFiles = glob.glob(gyre_defaults_dir) 63 # sections = ["&"+name.split("/")[-1].split('.')[0].split('-')[0] for name in defaultsFiles] 64 # print(sections) 65 section_parameters = {} 66 for i, file in enumerate(defaultsFiles): 67 params = [] 68 sections = [] 69 with open(file) as file: 70 for line in file: 71 if ":nml_g:" in line: 72 splits = line.split(":nml_g:") 73 for s in splits: 74 if "`" in s: 75 sections.append("&"+s.split("`")[1]) 76 if ":nml_n:" in line: 77 params.append(line.split(":nml_n:")[1].split("`")[1]) 78 sections = list(set(sections)) 79 for section in sections: 80 section_parameters[section] = params 81 return section_parameters
Reads the defaults files and returns a dictionary with all the parameters and their values.
Returns:
dict: A dictionary with all the parameters and their values.
def
writetoGyreFile( self, wdir, parameter, value, default_section=None, gyre_in='gyre.in'):
84 def writetoGyreFile(self, wdir, parameter, value, default_section=None, gyre_in="gyre.in"): 85 """Writes the parameter and its value to the inlist file. 86 87 Args: 88 filename (str): The path to the inlist file. 89 parameter (str): The parameter to be written. 90 value (str): The value of the parameter to be written. 91 default_section (str): The section in which the parameter is to be written. 92 sections (list): A list with the sections of the inlist file. 93 """ 94 if default_section is None: 95 for section, values in self.default_sections.items(): 96 if parameter in values: 97 default_section = section 98 if default_section is None: 99 raise TypeError(f"Parameter {parameter} not found in any GYRE input files.") 100 this_section = False 101 with cwd(wdir): 102 with file_operation_lock: 103 with open(gyre_in, "r") as file: 104 lines = file.readlines() 105 with open(gyre_in, "w+") as f: 106 indent = " " 107 for line in lines: 108 edited = False 109 if default_section in line: 110 this_section = True 111 if this_section: 112 if parameter in line: 113 if parameter == line.split("=")[0].strip(): 114 f.write(line.replace(line.split("=")[1], f" {value} ! Changed\n")) 115 edited = True 116 this_section = False 117 elif line[0] == "/": 118 f.write(indent) 119 f.write(f"{parameter} = {value} ! Added\n") 120 f.write("/") 121 edited = True 122 this_section = False 123 if not edited: 124 f.write(line)
Writes the parameter and its value to the inlist file.
Arguments:
- filename (str): The path to the inlist file.
- parameter (str): The parameter to be written.
- value (str): The value of the parameter to be written.
- default_section (str): The section in which the parameter is to be written.
- sections (list): A list with the sections of the inlist file.
def
modify_gyre_params( self, wdir, filename, data_format, gyre_in='gyre.in', diff_scheme='MAGNUS_GL2'):
128 def modify_gyre_params(self, wdir, filename, data_format, gyre_in="gyre.in", diff_scheme='MAGNUS_GL2'): 129 if data_format == "GYRE": 130 file_format = "MESA" 131 elif data_format == "FGONG": 132 file_format = "FGONG" 133 else: 134 file_format = "GSM" 135 self.writetoGyreFile(wdir, parameter="model_type", value="'EVOL'", default_section="&model", gyre_in=gyre_in) 136 self.writetoGyreFile(wdir, parameter="file_format", value=f"'{file_format}'", default_section="&model", gyre_in=gyre_in) 137 self.writetoGyreFile(wdir, parameter="file", value=f"'{filename}'", default_section="&model", gyre_in=gyre_in) 138 self.writetoGyreFile(wdir, parameter="summary_file", value=f"'{filename.split('.')[0]}-freqs.dat'", default_section="&ad_output", gyre_in=gyre_in) 139 self.writetoGyreFile(wdir, parameter="summary_file", value=f"'{filename.split('.')[0]}-freqs-nad.dat'", default_section="&nad_output", gyre_in=gyre_in)
def
set(self, arg, wdir, gyre_in='gyre.in'):
142 def set(self, arg, wdir, gyre_in="gyre.in"): 143 """Sets the value of a parameter in the inlist file. 144 145 Args: 146 arg (dict or list of dicts): A dictionary or a list of dictionaries with the parameters to be set. 147 """ 148 if isinstance(arg, dict): 149 for key, value in arg.items(): 150 self.writetoGyreFile(wdir, key, access_helper.toFortranType(value), gyre_in=gyre_in) 151 elif isinstance(arg, list): 152 for item in arg: 153 for key, value in item.items(): 154 self.writetoGyreFile(wdir, key, access_helper.toFortranType(value), gyre_in=gyre_in) 155 elif arg is None: 156 pass 157 else: 158 raise TypeError("Argument must be a dictionary or a list of dictionaries.")
Sets the value of a parameter in the inlist file.
Arguments:
- arg (dict or list of dicts): A dictionary or a list of dictionaries with the parameters to be set.