Skip to content
Snippets Groups Projects
Commit 9c1d88b4 authored by Marek Wiesner's avatar Marek Wiesner
Browse files

Refactor reading of pcomp model

parent a4c58373
No related branches found
No related tags found
No related merge requests found
......@@ -8,79 +8,7 @@ from loggingUtility import set_log_level, add_log_level_to_argument_parser
from src.read_dataset import read_datasets_from_directory
from src.Dataset import ModelType, Dataset
from dataclasses import dataclass
@dataclass
class PCOMPModel:
variables: list[str]
functions: list[str]
def remove_comments(modelFileContent: str) -> str:
modelFileLines = modelFileContent.splitlines()
modelFileLinesWithoutComments = [line for line in modelFileLines if not line.startswith(("c", "C"))]
return '\n'.join(modelFileLinesWithoutComments)
def get_new_pcomp_special_line_pattern() -> re.Pattern:
return re.compile(r"^\*", flags=re.IGNORECASE|re.MULTILINE)
def read_pcomp_block(modelFileContent: str, blockStartIndex: int) -> str:
findNewSpecialLinePattern = get_new_pcomp_special_line_pattern()
blockEndMatch = findNewSpecialLinePattern.search(modelFileContent[blockStartIndex + 1:])
if blockEndMatch:
blockEndIndex = blockStartIndex + blockEndMatch.end()
else:
blockEndIndex = -1
return modelFileContent[blockStartIndex:blockEndIndex]
def read_pcomp_model_infos(modelFile: Path) -> PCOMPModel:
modelFileContent = modelFile.read_text()
modelFileContent = remove_comments(modelFileContent)
variables: list[str] = []
functions: list[str] = []
indexSets: list[tuple[str, str]] = []
findNewSpecialLinePattern = get_new_pcomp_special_line_pattern()
findNewSetOfIndicesPattern = re.compile(r"^(\*\s*SET OF INDICES)", flags=re.IGNORECASE|re.MULTILINE)
findNewVariablePattern = re.compile(r"^(\*\s*VARIABLE)", flags=re.IGNORECASE|re.MULTILINE)
findNewFunctionPattern = re.compile(r"^(\*\s*FUNCTION)", flags=re.IGNORECASE|re.MULTILINE)
for specialLineStartMatch in findNewSpecialLinePattern.finditer(modelFileContent):
if findNewSetOfIndicesPattern.match(modelFileContent[specialLineStartMatch.start():]):
indexSetBlock = read_pcomp_block(modelFileContent, specialLineStartMatch.start())
indexSetBlock = findNewSetOfIndicesPattern.sub("", indexSetBlock)
indexSetBlock = indexSetBlock.strip()
indexSetBlock = indexSetBlock.strip('\n')
indexSetBlock = indexSetBlock.strip()
for line in indexSetBlock.splitlines():
splitIndexSet = line.split('=', maxsplit=1)
assert len(splitIndexSet) == 2
indexSets.append((splitIndexSet[0].strip(), splitIndexSet[1].strip()))
continue
if findNewFunctionPattern.match(modelFileContent[specialLineStartMatch.start():]):
functions.append(read_pcomp_block(modelFileContent, specialLineStartMatch.start()))
continue
if findNewVariablePattern.match(modelFileContent[specialLineStartMatch.start():]):
variablesBlock = read_pcomp_block(modelFileContent, specialLineStartMatch.start())
variablesBlock = findNewVariablePattern.sub("", variablesBlock)
for line in variablesBlock.splitlines():
if any([indexSet[0] in line for indexSet in indexSets]):
variables.append(line.strip())
else:
variables.extend([var for var in line.replace(' ', '').split(',') if var])
return PCOMPModel(variables, functions)
from src.read_pcomp_model import read_pcomp_model
def find_whole_word(targetString: str, sourceString: str, ignoreCase: bool = True) -> bool:
......@@ -100,7 +28,7 @@ def any_function_contains_parameter(functions: list[str], parameterName: str) ->
def get_indices_of_model_parameters_in_ode(modelFileName: Path, dataset: Dataset) -> list[tuple[int, str]]:
pcompModelInfos = read_pcomp_model_infos(modelFileName)
pcompModelInfos = read_pcomp_model(modelFileName)
numberOfTimeVariables = 1
numberOfConcentrationVariables = 1 if dataset.numberOfConcentrations > 0 else 0
......@@ -110,13 +38,12 @@ def get_indices_of_model_parameters_in_ode(modelFileName: Path, dataset: Dataset
if len(pcompModelInfos.functions) != expectedNumberOfFunctions:
logging.warning(f"{dataset.name}: wrong number of functions detected, expected: {expectedNumberOfFunctions}, observed: {len(pcompModelInfos.functions)}. Return no detected parameters.")
modelParametersInOde: list[tuple[int, str]] = []
return []
elif len(pcompModelInfos.variables) != expectedNumberOfVariables:
logging.warning(f"{dataset.name}: wrong number of variables detected, expected: {expectedNumberOfVariables}, observed: {len(pcompModelInfos.variables)}. Return no detected parameters")
return []
else:
if len(pcompModelInfos.variables) == expectedNumberOfVariables:
modelParameterNames = pcompModelInfos.variables[0:dataset.numberOfModelParameters]
else:
logging.warning(f"{dataset.name}: wrong number of variables detected, expected: {expectedNumberOfVariables}, observed: {len(pcompModelInfos.variables)}. Use model parameter names from dataset.")
modelParameterNames = [info.name for info in dataset.modelParameterInfos]
modelParameterNames = pcompModelInfos.variables[0:dataset.numberOfModelParameters]
odeFunctions = pcompModelInfos.functions[0:dataset.numberOfOdes]
modelParametersInOde = [(index, parameter) for index, parameter in enumerate(modelParameterNames)
......
from dataclasses import dataclass
from pathlib import Path
import re
@dataclass
class PCOMPModel:
variables: list[str]
functions: list[str]
def remove_comments(modelFileContent: str) -> str:
modelFileLines = modelFileContent.splitlines()
modelFileLinesWithoutComments = [line for line in modelFileLines if not line.startswith(("c", "C"))]
return '\n'.join(modelFileLinesWithoutComments)
def get_new_pcomp_special_line_pattern() -> re.Pattern:
return re.compile(r"^\*", flags=re.IGNORECASE|re.MULTILINE)
def read_pcomp_block(modelFileContent: str, blockStartIndex: int) -> str:
findNewSpecialLinePattern = get_new_pcomp_special_line_pattern()
blockEndMatch = findNewSpecialLinePattern.search(modelFileContent[blockStartIndex + 1:])
if blockEndMatch:
blockEndIndex = blockStartIndex + blockEndMatch.end()
else:
blockEndIndex = -1
return modelFileContent[blockStartIndex:blockEndIndex]
def read_pcomp_model(modelFile: Path) -> PCOMPModel:
modelFileContent = modelFile.read_text()
modelFileContent = remove_comments(modelFileContent)
variables: list[str] = []
functions: list[str] = []
indexSets: list[tuple[str, str]] = []
findNewSpecialLinePattern = get_new_pcomp_special_line_pattern()
findNewSetOfIndicesPattern = re.compile(r"^(\*\s*SET OF INDICES)", flags=re.IGNORECASE|re.MULTILINE)
findNewVariablePattern = re.compile(r"^(\*\s*VARIABLE)", flags=re.IGNORECASE|re.MULTILINE)
findNewFunctionPattern = re.compile(r"^(\*\s*FUNCTION)", flags=re.IGNORECASE|re.MULTILINE)
for specialLineStartMatch in findNewSpecialLinePattern.finditer(modelFileContent):
if findNewSetOfIndicesPattern.match(modelFileContent[specialLineStartMatch.start():]):
indexSetBlock = read_pcomp_block(modelFileContent, specialLineStartMatch.start())
indexSetBlock = findNewSetOfIndicesPattern.sub("", indexSetBlock)
indexSetBlock = indexSetBlock.strip()
indexSetBlock = indexSetBlock.strip('\n')
indexSetBlock = indexSetBlock.strip()
for line in indexSetBlock.splitlines():
splitIndexSet = line.split('=', maxsplit=1)
assert len(splitIndexSet) == 2
indexSets.append((splitIndexSet[0].strip(), splitIndexSet[1].strip()))
continue
if findNewFunctionPattern.match(modelFileContent[specialLineStartMatch.start():]):
functions.append(read_pcomp_block(modelFileContent, specialLineStartMatch.start()))
continue
if findNewVariablePattern.match(modelFileContent[specialLineStartMatch.start():]):
variablesBlock = read_pcomp_block(modelFileContent, specialLineStartMatch.start())
variablesBlock = findNewVariablePattern.sub("", variablesBlock)
for line in variablesBlock.splitlines():
if any([indexSet[0] in line for indexSet in indexSets]):
variables.append(line.strip())
else:
variables.extend([var for var in line.replace(' ', '').split(',') if var])
return PCOMPModel(variables, functions)
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment