Coverage for pydelica/options/simulation.py: 84%

1 import collections.abc

2 import os.path

3 import enum

4 import pathlib

5 from typing import Any, Iterable

6

7 import defusedxml.ElementTree as ET

8 from pydelica.exception import UnknownOptionError

9

10

11 class Solver(str, enum.Enum):

12 """[Deprecated]"""

13 DASSL = "dassl"

14 EULER = "euler"

15 RUNGE_KUTTA = "rungekutta"

16

17

18 class OutputFormat(str, enum.Enum):

19 """[Deprecated]"""

20 CSV = "csv"

21 MAT = "mat"

22 PLT = "plt"

23

24

25 class SimulationOptions(collections.abc.MutableMapping):

26 """

27 Simulation Options

28 ------------------

29

30 Object contains configuration settings for simulation within Modelica

31 """

32

33 def __init__(self, xml_model_file: pathlib.Path) -> None:

34 """Create a configuration object from a given model XML file

35

36 Parameters

37 ----------

38 xml_model_file : pathlib.Path

39 file containing the parameters and configurations from a model

40 after compilation

41

42 Raises

43 ------

44 FileNotFoundError

45 if the specified XML file does not exist

46 """

47 self._model_xml = xml_model_file

48

49 if not os.path.exists(xml_model_file):

50 raise FileNotFoundError(

51 "Could not extract simulation options, "

52 f"no such file '{xml_model_file}"

53 )

54

55 _xml_obj = ET.parse(xml_model_file)

56

57 self._opts = list(_xml_obj.iterfind("DefaultExperiment"))[0].attrib

58

59 def _write_opts(self) -> None:

60 _xml_obj = ET.parse(self._model_xml)

61

62 for opt in _xml_obj.findall("DefaultExperiment")[0].attrib:

63 _xml_obj.findall("DefaultExperiment")[0].attrib[opt] = str(self._opts[opt])

64

65 _xml_obj.write(self._model_xml)

66

67 def __setitem__(self, key: str, value: Any) -> None:

68 self._opts[key] = value

69 self._write_opts()

70

71 def __getitem__(self, key: str) -> Any:

72 return self._opts[key]

73

74 def __delitem__(self, key: str) -> None:

75 del self._opts[key]

76

77 def set_option(self, option_name: str, value: Any) -> None:

78 """Set the value of an option

79

80 Parameters

81 ----------

82 option_name : str

83 name of option to update

84 value : Any

85 new value for option

86

87 Raises

88 ------

89 UnknownOptionError

90 if the option does not exist

91 """

92 if option_name not in self._opts:

93 raise UnknownOptionError(option_name)

94 _opt = [i for i in self._opts.keys() if i.lower() == option_name.lower()][0]

95 self._opts[_opt] = value

96 self._write_opts()

97

98 def __len__(self) -> int:

99 return len(self._opts)

100

101 def __iter__(self) -> Iterable:

102 return iter(self._opts)