Note: The default ITS GitLab runner is a shared resource and is subject to slowdowns during heavy usage.
You can run your own GitLab runner that is dedicated just to your group if you need to avoid processing delays.

Commit f9f3b691 authored by Qusai Al Shidi's avatar Qusai Al Shidi 💬
Browse files

Improved paramin functions

parent 113cbec1
"""Tools to manipulate or create param.in files """
PARAM.in Tools PARAM.in Tools
-------------- --------------
...@@ -7,27 +6,31 @@ These tools are to help script the editing of PARAM.in files. ...@@ -7,27 +6,31 @@ These tools are to help script the editing of PARAM.in files.
""" """
__all__ = [ __all__ = [
'read_command', 'read_command',
'replace_command' 'replace_command',
'get_command'
] ]
__author__ = 'Qusai Al Shidi' __author__ = 'Qusai Al Shidi'
__email__ = 'qusai@umich.edu' __email__ = 'qusai@umich.edu'
import logging import logging
def get_command(line): def get_command(line):
"""Returns the '#COMMAND' if on line. """Returns the '#COMMAND' if on line.
Args: Args:
line (str): The line in the PARAM.in file. line (str, list, tuple): The line in the PARAM.in file.
Returns: Returns:
(str): '#COMMAND' if found and None if not. (str): '#COMMAND' if found and None if not.
""" """
to_check = line.split() if isinstance(line, (str, list, tuple)): # Raises type error otherwise
if isinstance(to_check, (str, tuple, list)): if isinstance(line, str):
if isinstance(to_check, str) and to_check.startswitch('#'): to_check = line.split()
return to_check if to_check and to_check[0].startswith('#'):
return get_command(to_check[0]) return to_check[0]
return None
return get_command(line[0])
return None return None
...@@ -46,6 +49,9 @@ def replace_command(parameters, input_file, output_file='PARAM.in'): ...@@ -46,6 +49,9 @@ def replace_command(parameters, input_file, output_file='PARAM.in'):
Returns: Returns:
A list of lines of the PARAM.in file that would be outputted. A list of lines of the PARAM.in file that would be outputted.
Raises:
TypeError: If a value given couldn't be converted to string.
Examples: Examples:
``` ```
change['#SOLARWINDFILE'] = [['T', 'UseSolarWindFile'], change['#SOLARWINDFILE'] = [['T', 'UseSolarWindFile'],
...@@ -57,37 +63,25 @@ def replace_command(parameters, input_file, output_file='PARAM.in'): ...@@ -57,37 +63,25 @@ def replace_command(parameters, input_file, output_file='PARAM.in'):
# Author: Qusai Al Shidi # Author: Qusai Al Shidi
# Email: qusai@umich.edu # Email: qusai@umich.edu
# TODO This will replace all for repeat commands.
logger = logging.getLogger() # For debugging logger = logging.getLogger() # For debugging
# Read and replace paramin file by making a temp list # Read and replace paramin file by making a temp list
with open(input_file, 'rt') as paramin: with open(input_file, 'rt') as paramin:
command = None # Current command
# Compile lines in a list before editing/writing it # Compile lines in a list before editing/writing it
lines = list(paramin) lines = list(paramin)
for line_num, line in enumerate(lines): for line_num, line in enumerate(lines):
words = line.split()
# If the current command is what we want # If the current command is what we want
if words and words[0] in parameters.keys(): command = get_command(line)
command = words[0] if command in parameters.keys():
# Replace code
for param, value in enumerate(parameters[command]): for param, value in enumerate(parameters[command]):
newline = '' newline = _make_line(value)
# Allow additions of comments if list(str) logger.info('Replacing: %s\n with: %s\n',
if isinstance(value, list): line, newline)
for text in value: # Lines will be replaced in order
newline += text + '\t\t\t' lines[line_num+param+1] = newline + '\n'
logger.info('Replacing: %s\n with: %s\n',
line, newline)
# Lines will be replaced in order
lines[line_num+param+1] = newline + '\n'
# Else just make a line
elif isinstance(value, str):
logger.info('Replacing: %s\n with: %s\n', line, value)
# Lines will be replaced in order
lines[line_num+param+1] = value + '\n'
# Write the PARAM.in file # Write the PARAM.in file
if output_file is None: if output_file is None:
...@@ -136,25 +130,24 @@ def read_command(command, paramin_file='PARAM.in', **kwargs): ...@@ -136,25 +130,24 @@ def read_command(command, paramin_file='PARAM.in', **kwargs):
with open(paramin_file) as paramin: with open(paramin_file) as paramin:
return_values = [] return_values = []
found_command = False # to know if worked command_found = False # to know if worked
at_command = False # when after command needed in_command = False # when after command needed
for line in paramin: for line in paramin:
words = line.split() if get_command(line) == command:
if words and words[0] == command:
logger.info('Found command: %s', command) logger.info('Found command: %s', command)
found_command = True command_found = True
at_command = True in_command = True
return_values.append(command) return_values.append(command)
elif words and words[0][0] == '#': elif in_command and get_command(line): # Make sure not out of cmd
at_command = False in_command = False
elif words and at_command: elif line.split() and in_command:
value = words[0] value = line.split()[0]
logger.info('Value added: %s', value) logger.info('Value added: %s', value)
return_values.append(value) return_values.append(value)
# Error handling # Error handling
# Unable to find #COMMAND # Unable to find #COMMAND
if not found_command: if not command_found:
raise ValueError(command + ' not found.') raise ValueError(command + ' not found.')
# To ignore additional lines # To ignore additional lines
...@@ -163,3 +156,12 @@ def read_command(command, paramin_file='PARAM.in', **kwargs): ...@@ -163,3 +156,12 @@ def read_command(command, paramin_file='PARAM.in', **kwargs):
return_values = return_values[:value_limit+1] return_values = return_values[:value_limit+1]
return return_values # empty list might mean command not found return return_values # empty list might mean command not found
def _make_line(value):
"""Makes the paramin line based on value type recursively"""
if isinstance(value, str):
return value
elif isinstance(value, list):
return '\t\t\t'.join([_make_line(v) for v in value])
return str(value)
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment