Skip to content

Commit 2eea27c

Browse files
peterhollenderebrahimebrahim
authored andcommitted
Soften SimSetup.from_dict on mismatched attributes
For better backwards compatibility with protocols prior to #364
1 parent c298ae7 commit 2eea27c

1 file changed

Lines changed: 25 additions & 1 deletion

File tree

src/openlifu/sim/sim_setup.py

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
import logging
44
from dataclasses import dataclass, field
5-
from typing import Annotated, Tuple
5+
from typing import Annotated, Literal, Tuple
66

77
import numpy as np
88
import pandas as pd
@@ -204,3 +204,27 @@ def to_table(self) -> pd.DataFrame:
204204
{"Name": "CFL", "Value": self.cfl, "Unit": ""},
205205
]
206206
return pd.DataFrame.from_records(records)
207+
208+
@staticmethod
209+
def from_dict(d: dict, on_keyword_mismatch: Literal['warn', 'raise', 'ignore'] = 'warn') -> SimSetup:
210+
"""Create a SimSetup instance from a dictionary."""
211+
if not isinstance(d, dict):
212+
raise TypeError("Input must be a dictionary.")
213+
214+
expected_keywords = [
215+
'spacing', 'units', 'x_extent', 'y_extent', 'z_extent',
216+
'dt', 't_end', 'c0', 'cfl', 'options'
217+
]
218+
219+
input_args = {
220+
k: v for k, v in d.items() if k in expected_keywords
221+
}
222+
unexpected_keywords = [k for k in d if k not in expected_keywords]
223+
224+
if unexpected_keywords:
225+
if on_keyword_mismatch == 'raise':
226+
raise TypeError(f"Unexpected keyword arguments for SimSetup: {unexpected_keywords}")
227+
elif on_keyword_mismatch == 'warn':
228+
logging.warning(f"Ignoring unexpected keyword arguments for SimSetup: {unexpected_keywords}")
229+
230+
return SimSetup(**input_args)

0 commit comments

Comments
 (0)