mesaport.Access.access_helper

  1import os
  2import re
  3from .support import *
  4
  5
  6def readDefaults(filename, defaultsDir):
  7    """Reads the defaults files and returns a dictionary with all the parameters and their values.
  8
  9    Args:
 10        filename (str): The name of the defaults file.
 11        defaultsDir (str): The path to the defaults directory.
 12    Raises:
 13        FileNotFoundError: If the defaults files do not exist.
 14
 15    Returns:
 16        dict: A dictionary with all the parameters and their values.
 17    """    
 18    defaultsFile = defaultsDir + filename
 19    if not os.path.exists(defaultsFile):
 20        raise FileNotFoundError(f"Defaults file {filename} does not exist.")
 21    else:
 22        defaultParameters = {}
 23        with open(defaultsFile) as file:
 24            for line in file:
 25                line = line.strip().replace(" ", "")
 26                if not line.startswith("!") and not line.startswith("/") and line != "":
 27                    if "!" in line:
 28                        line = line.split("!")[0]
 29                    name, _, var = line.strip().partition("=")
 30                    defaultParameters[name] = var
 31                    if "(:)" in name:
 32                        # print(name)
 33                        for i in range(1, 101):
 34                            name_ = name.replace("(:)", f"({i})")
 35                            defaultParameters[name_] = var
 36
 37    # pprint(defaultParameters)
 38    return defaultParameters
 39
 40
 41
 42def matchtoDefaults(parameter, defaultsDict, sections):
 43    """Returns the section of the defaults file where the parameter is located.
 44
 45    Args:
 46        parameter (str): The parameter to be searched for.
 47        defaultsDict (dict): A dictionary with all the parameters and their values.
 48        sections (list): A list with the sections of the defaults file.
 49
 50    Raises:
 51        KeyError: If the parameter does not exist in the defaults files.
 52
 53    Returns:
 54        str: The section of the defaults file where the parameter is located.
 55    """    
 56    for section in sections:
 57        if parameter in defaultsDict[section]:
 58            return section, toPythonType(defaultsDict[section][parameter]),\
 59                     type(toPythonType(defaultsDict[section][parameter]))
 60    else:
 61        raise KeyError(f"Parameter {parameter} does not exist in the defaults files.")
 62
 63def getFilename(astero, binary, default_section, inlist_filenames):
 64        if not binary:
 65            if default_section in ["star_job", "controls"]:
 66                filename = "inlist_project"
 67            elif default_section == "pgstar":
 68                filename = "inlist_pgstar"
 69        if astero:
 70            if default_section == "astero_search_controls" or default_section == "astero_pgstar_controls":
 71                filename = "inlist_astero_search_controls"
 72        else:
 73            filename = inlist_filenames[0]
 74        return filename
 75
 76
 77def toPythonType(data):
 78    """Returns the 'Python' type of the value.
 79
 80    Args:
 81        data (str): The value to be checked.
 82
 83    Raises:
 84        AttributeError: If the value cannot be converted to a known type.
 85
 86    Returns:
 87        type: The type of the value.
 88    """
 89    regex_floatingValue = r"([-\d\.\d]+)[deDE]([\+\-\d]*)" # regex for floating point values
 90    if data[0] == "." and data[-1] == ".": # return boolean
 91        return True if data[1:-1] == "true" else False
 92    elif data[0] == "'": # return string
 93        return data[1:-1]
 94    elif re.compile(regex_floatingValue).match(data) is not None:
 95        matches = re.compile(regex_floatingValue).findall(data)
 96        if matches[0][1] == "":
 97            power = 0
 98        else:
 99            power = float(matches[0][1])
100        return float(matches[0][0])*pow(10, power)
101    elif "." in data:
102        try:
103            return float(data)
104        except:
105            return str(data)
106    else:
107        try:
108            return int(data)
109        except:
110            raise AttributeError(f"Cannot convert {data} to known type!")
111
112
113def toFortranType(data):
114    """Converts the value to a 'Fortran' type.
115
116    Args:
117        data (str): The value to be converted.
118
119    Raises:
120        AttributeError: If the value cannot be converted to a known type.
121
122    Returns:
123        str: The value converted to a 'Fortran' type.
124    """    
125    if isinstance(data, bool):
126        return "." + ("true" if data else "false") + "."
127    elif isinstance(data, str):
128        return "'"+data+"'"
129    elif isinstance(data, float):
130        if "e" in str(data):
131            return str(data).replace("e", "d")
132        elif "E" in str(data):
133            return str(data).replace("E", "d")
134        else:
135            return str(data)
136    elif isinstance(data, int):
137        return str(data)
138    else:
139        raise AttributeError(f"Cannot convert type {str(type(data))} to known type")
140
141
142def matchTypes(inputType, defaultType):
143    """Checks if the input type is the same as the default type.
144
145    Args:
146        inputType (type): The type of the input value.
147        defaultType (type): The type of the default value.
148
149    Raises:
150        TypeError: If the input type is not the same as the default type.
151
152    Returns:
153        bool: True if the types match, False otherwise.
154    """    
155    if inputType == defaultType:
156        return True
157    elif inputType == float and defaultType == int or inputType == int and defaultType == float:
158        return True
159    else:
160        return False
161
162
163def matchtoFile(parameter, inlistDict, sections, default_section):
164    """Returns the section of the inlist file where the parameter is located.
165
166    Args:
167        parameter (str): The parameter to be searched for.
168        inlistDict (dict): A dictionary with all the parameters and their values.
169        sections (list): A list with the sections of the inlist file.
170
171    Returns:
172        bool, str: A tuple with a boolean indicating if the parameter exists in the inlist file 
173                    and the section of the inlist file where the parameter is located.
174    """    
175    for section in sections:
176        if parameter in inlistDict[section] and section == default_section:
177            return True, toPythonType(inlistDict[section][parameter])
178    else:
179        return False, None
180
181
182
183def readFile(inlist, projectDir):
184    """Reads the inlist file and returns a dictionary with all the parameters and their values.
185
186    Args:
187        inlist (str): The path to the inlist file.
188
189    Raises:
190        FileNotFoundError: If the inlist file does not exist.
191
192    Returns:
193        dict : A dictionary with all the parameters and their values.
194    """    
195    with cwd(projectDir):
196        if not os.path.exists(inlist):
197            raise FileNotFoundError(f"Inlist {inlist} does not exist.")
198        else:
199            inlistParameters = {}
200            inlistSections = []
201            section = ""
202            with open(inlist) as file:
203                for line in file:
204                    line = line.strip().replace(" ", "")
205                    if line.startswith("&"):
206                        section = line.split("&")[1].split()[0]
207                        inlistParameters[section] = {}
208                        inlistSections.append(section)
209                    elif not line.startswith("!") and not line.startswith("/") and line != "":
210                        line = line.replace(" ", "")
211                        if "!" in line:
212                            line = line.split("!")[0]
213                        name, _, value = line.partition("=")
214                        if section != "":
215                            inlistParameters[section][name] = value
216                        else:
217                            print("Something went wrong, section not found!")
218        # pprint(inlistParameters)
219        return inlistSections, inlistParameters
220
221
222
223
224def writetoFile(projectDir, filename, parameter, value, exists, default_section, delete=False):
225    """Writes the parameter and its value to the inlist file.
226
227    Args:
228        projectDir (str): The path to the project directory.
229        filename (str): The name of the inlist file.
230        parameter (str): The parameter to be written to the inlist file.
231        value (str): The value of the parameter to be written to the inlist file.
232        exists (bool): A boolean indicating if the parameter exists in the inlist file.
233        default_section (str): The default section of the inlist file.
234        delete (bool, optional): A boolean indicating if the parameter should be deleted from the inlist file. Defaults to False.
235    """    
236    value = toFortranType(value)
237    this_section = False
238    with cwd(projectDir):
239        with open(filename, "r") as file:
240            lines = file.readlines()
241        with open(filename, "w+") as f:
242            indent = "    "
243            for line in lines:
244                if line.startswith("&"):
245                    if '&' + default_section in line:
246                        this_section = True
247                        # print("Writing to section: " + default_section)
248                    else:
249                        this_section = False
250                        # print("skip section: " + line.split("&")[1].split()[0])
251                if this_section:
252                    if exists and parameter in line:
253                        if parameter == line.split("=")[0].strip():
254                            if not delete:
255                                f.write(line.replace(line.split("=")[1], f" {value}    ! Changed\n"))
256                            else:
257                                f.write(indent)
258                                f.write(f"! {parameter} = {value}    ! Removed\n")
259                    elif not exists and line.startswith("/"):
260                        f.write(indent)
261                        f.write(f"{parameter} = {value}    ! Added\n")
262                        f.write("/\n")
263                        this_section = False
264                    else:
265                        f.write(line)
266                else:
267                    f.write(line)
268                
269                
270            
271        
def readDefaults(filename, defaultsDir):
 7def readDefaults(filename, defaultsDir):
 8    """Reads the defaults files and returns a dictionary with all the parameters and their values.
 9
10    Args:
11        filename (str): The name of the defaults file.
12        defaultsDir (str): The path to the defaults directory.
13    Raises:
14        FileNotFoundError: If the defaults files do not exist.
15
16    Returns:
17        dict: A dictionary with all the parameters and their values.
18    """    
19    defaultsFile = defaultsDir + filename
20    if not os.path.exists(defaultsFile):
21        raise FileNotFoundError(f"Defaults file {filename} does not exist.")
22    else:
23        defaultParameters = {}
24        with open(defaultsFile) as file:
25            for line in file:
26                line = line.strip().replace(" ", "")
27                if not line.startswith("!") and not line.startswith("/") and line != "":
28                    if "!" in line:
29                        line = line.split("!")[0]
30                    name, _, var = line.strip().partition("=")
31                    defaultParameters[name] = var
32                    if "(:)" in name:
33                        # print(name)
34                        for i in range(1, 101):
35                            name_ = name.replace("(:)", f"({i})")
36                            defaultParameters[name_] = var
37
38    # pprint(defaultParameters)
39    return defaultParameters

Reads the defaults files and returns a dictionary with all the parameters and their values.

Arguments:
  • filename (str): The name of the defaults file.
  • defaultsDir (str): The path to the defaults directory.
Raises:
  • FileNotFoundError: If the defaults files do not exist.
Returns:

dict: A dictionary with all the parameters and their values.

def matchtoDefaults(parameter, defaultsDict, sections):
43def matchtoDefaults(parameter, defaultsDict, sections):
44    """Returns the section of the defaults file where the parameter is located.
45
46    Args:
47        parameter (str): The parameter to be searched for.
48        defaultsDict (dict): A dictionary with all the parameters and their values.
49        sections (list): A list with the sections of the defaults file.
50
51    Raises:
52        KeyError: If the parameter does not exist in the defaults files.
53
54    Returns:
55        str: The section of the defaults file where the parameter is located.
56    """    
57    for section in sections:
58        if parameter in defaultsDict[section]:
59            return section, toPythonType(defaultsDict[section][parameter]),\
60                     type(toPythonType(defaultsDict[section][parameter]))
61    else:
62        raise KeyError(f"Parameter {parameter} does not exist in the defaults files.")

Returns the section of the defaults file where the parameter is located.

Arguments:
  • parameter (str): The parameter to be searched for.
  • defaultsDict (dict): A dictionary with all the parameters and their values.
  • sections (list): A list with the sections of the defaults file.
Raises:
  • KeyError: If the parameter does not exist in the defaults files.
Returns:

str: The section of the defaults file where the parameter is located.

def getFilename(astero, binary, default_section, inlist_filenames):
64def getFilename(astero, binary, default_section, inlist_filenames):
65        if not binary:
66            if default_section in ["star_job", "controls"]:
67                filename = "inlist_project"
68            elif default_section == "pgstar":
69                filename = "inlist_pgstar"
70        if astero:
71            if default_section == "astero_search_controls" or default_section == "astero_pgstar_controls":
72                filename = "inlist_astero_search_controls"
73        else:
74            filename = inlist_filenames[0]
75        return filename
def toPythonType(data):
 78def toPythonType(data):
 79    """Returns the 'Python' type of the value.
 80
 81    Args:
 82        data (str): The value to be checked.
 83
 84    Raises:
 85        AttributeError: If the value cannot be converted to a known type.
 86
 87    Returns:
 88        type: The type of the value.
 89    """
 90    regex_floatingValue = r"([-\d\.\d]+)[deDE]([\+\-\d]*)" # regex for floating point values
 91    if data[0] == "." and data[-1] == ".": # return boolean
 92        return True if data[1:-1] == "true" else False
 93    elif data[0] == "'": # return string
 94        return data[1:-1]
 95    elif re.compile(regex_floatingValue).match(data) is not None:
 96        matches = re.compile(regex_floatingValue).findall(data)
 97        if matches[0][1] == "":
 98            power = 0
 99        else:
100            power = float(matches[0][1])
101        return float(matches[0][0])*pow(10, power)
102    elif "." in data:
103        try:
104            return float(data)
105        except:
106            return str(data)
107    else:
108        try:
109            return int(data)
110        except:
111            raise AttributeError(f"Cannot convert {data} to known type!")

Returns the 'Python' type of the value.

Arguments:
  • data (str): The value to be checked.
Raises:
  • AttributeError: If the value cannot be converted to a known type.
Returns:

type: The type of the value.

def toFortranType(data):
114def toFortranType(data):
115    """Converts the value to a 'Fortran' type.
116
117    Args:
118        data (str): The value to be converted.
119
120    Raises:
121        AttributeError: If the value cannot be converted to a known type.
122
123    Returns:
124        str: The value converted to a 'Fortran' type.
125    """    
126    if isinstance(data, bool):
127        return "." + ("true" if data else "false") + "."
128    elif isinstance(data, str):
129        return "'"+data+"'"
130    elif isinstance(data, float):
131        if "e" in str(data):
132            return str(data).replace("e", "d")
133        elif "E" in str(data):
134            return str(data).replace("E", "d")
135        else:
136            return str(data)
137    elif isinstance(data, int):
138        return str(data)
139    else:
140        raise AttributeError(f"Cannot convert type {str(type(data))} to known type")

Converts the value to a 'Fortran' type.

Arguments:
  • data (str): The value to be converted.
Raises:
  • AttributeError: If the value cannot be converted to a known type.
Returns:

str: The value converted to a 'Fortran' type.

def matchTypes(inputType, defaultType):
143def matchTypes(inputType, defaultType):
144    """Checks if the input type is the same as the default type.
145
146    Args:
147        inputType (type): The type of the input value.
148        defaultType (type): The type of the default value.
149
150    Raises:
151        TypeError: If the input type is not the same as the default type.
152
153    Returns:
154        bool: True if the types match, False otherwise.
155    """    
156    if inputType == defaultType:
157        return True
158    elif inputType == float and defaultType == int or inputType == int and defaultType == float:
159        return True
160    else:
161        return False

Checks if the input type is the same as the default type.

Arguments:
  • inputType (type): The type of the input value.
  • defaultType (type): The type of the default value.
Raises:
  • TypeError: If the input type is not the same as the default type.
Returns:

bool: True if the types match, False otherwise.

def matchtoFile(parameter, inlistDict, sections, default_section):
164def matchtoFile(parameter, inlistDict, sections, default_section):
165    """Returns the section of the inlist file where the parameter is located.
166
167    Args:
168        parameter (str): The parameter to be searched for.
169        inlistDict (dict): A dictionary with all the parameters and their values.
170        sections (list): A list with the sections of the inlist file.
171
172    Returns:
173        bool, str: A tuple with a boolean indicating if the parameter exists in the inlist file 
174                    and the section of the inlist file where the parameter is located.
175    """    
176    for section in sections:
177        if parameter in inlistDict[section] and section == default_section:
178            return True, toPythonType(inlistDict[section][parameter])
179    else:
180        return False, None

Returns the section of the inlist file where the parameter is located.

Arguments:
  • parameter (str): The parameter to be searched for.
  • inlistDict (dict): A dictionary with all the parameters and their values.
  • sections (list): A list with the sections of the inlist file.
Returns:

bool, str: A tuple with a boolean indicating if the parameter exists in the inlist file and the section of the inlist file where the parameter is located.

def readFile(inlist, projectDir):
184def readFile(inlist, projectDir):
185    """Reads the inlist file and returns a dictionary with all the parameters and their values.
186
187    Args:
188        inlist (str): The path to the inlist file.
189
190    Raises:
191        FileNotFoundError: If the inlist file does not exist.
192
193    Returns:
194        dict : A dictionary with all the parameters and their values.
195    """    
196    with cwd(projectDir):
197        if not os.path.exists(inlist):
198            raise FileNotFoundError(f"Inlist {inlist} does not exist.")
199        else:
200            inlistParameters = {}
201            inlistSections = []
202            section = ""
203            with open(inlist) as file:
204                for line in file:
205                    line = line.strip().replace(" ", "")
206                    if line.startswith("&"):
207                        section = line.split("&")[1].split()[0]
208                        inlistParameters[section] = {}
209                        inlistSections.append(section)
210                    elif not line.startswith("!") and not line.startswith("/") and line != "":
211                        line = line.replace(" ", "")
212                        if "!" in line:
213                            line = line.split("!")[0]
214                        name, _, value = line.partition("=")
215                        if section != "":
216                            inlistParameters[section][name] = value
217                        else:
218                            print("Something went wrong, section not found!")
219        # pprint(inlistParameters)
220        return inlistSections, inlistParameters

Reads the inlist file and returns a dictionary with all the parameters and their values.

Arguments:
  • inlist (str): The path to the inlist file.
Raises:
  • FileNotFoundError: If the inlist file does not exist.
Returns:

dict : A dictionary with all the parameters and their values.

def writetoFile( projectDir, filename, parameter, value, exists, default_section, delete=False):
225def writetoFile(projectDir, filename, parameter, value, exists, default_section, delete=False):
226    """Writes the parameter and its value to the inlist file.
227
228    Args:
229        projectDir (str): The path to the project directory.
230        filename (str): The name of the inlist file.
231        parameter (str): The parameter to be written to the inlist file.
232        value (str): The value of the parameter to be written to the inlist file.
233        exists (bool): A boolean indicating if the parameter exists in the inlist file.
234        default_section (str): The default section of the inlist file.
235        delete (bool, optional): A boolean indicating if the parameter should be deleted from the inlist file. Defaults to False.
236    """    
237    value = toFortranType(value)
238    this_section = False
239    with cwd(projectDir):
240        with open(filename, "r") as file:
241            lines = file.readlines()
242        with open(filename, "w+") as f:
243            indent = "    "
244            for line in lines:
245                if line.startswith("&"):
246                    if '&' + default_section in line:
247                        this_section = True
248                        # print("Writing to section: " + default_section)
249                    else:
250                        this_section = False
251                        # print("skip section: " + line.split("&")[1].split()[0])
252                if this_section:
253                    if exists and parameter in line:
254                        if parameter == line.split("=")[0].strip():
255                            if not delete:
256                                f.write(line.replace(line.split("=")[1], f" {value}    ! Changed\n"))
257                            else:
258                                f.write(indent)
259                                f.write(f"! {parameter} = {value}    ! Removed\n")
260                    elif not exists and line.startswith("/"):
261                        f.write(indent)
262                        f.write(f"{parameter} = {value}    ! Added\n")
263                        f.write("/\n")
264                        this_section = False
265                    else:
266                        f.write(line)
267                else:
268                    f.write(line)

Writes the parameter and its value to the inlist file.

Arguments:
  • projectDir (str): The path to the project directory.
  • filename (str): The name of the inlist file.
  • parameter (str): The parameter to be written to the inlist file.
  • value (str): The value of the parameter to be written to the inlist file.
  • exists (bool): A boolean indicating if the parameter exists in the inlist file.
  • default_section (str): The default section of the inlist file.
  • delete (bool, optional): A boolean indicating if the parameter should be deleted from the inlist file. Defaults to False.