Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

5804 Simplify the configparser usage to get parsed attributes easily #5813

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/source/bundle.rst
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ Model Bundle
---------------
.. autoclass:: ConfigParser
:members:
:special-members:
wyli marked this conversation as resolved.
Show resolved Hide resolved

`Scripts`
---------
Expand Down
13 changes: 13 additions & 0 deletions monai/bundle/config_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,19 @@ def __init__(
def __repr__(self):
return f"{self.config}"

def __getattr__(self, id):
"""
Get the parsed result of ``ConfigItem`` with the specified ``id``
with default arguments (e.g. ``lazy=True``, ``instantiate=True`` and ``eval_expr=True``).

Args:
id: id of the ``ConfigItem``.

See also:
:py:meth:`get_parsed_content`
"""
return self.get_parsed_content(id)

def __getitem__(self, id: Union[str, int]):
"""
Get the config by id.
Expand Down
2 changes: 1 addition & 1 deletion tests/test_auto3dseg_ensemble.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ def test_ensemble(self) -> None:
builder = AlgoEnsembleBuilder(history, data_src_cfg)
builder.set_ensemble_method(AlgoEnsembleBestN(n_best=1))
ensemble = builder.get_ensemble()
pred_param["network#init_filter"] = 8 # segresnet
pred_param["network#init_filters"] = 8 # segresnet
preds = ensemble(pred_param)
self.assertTupleEqual(preds[0].shape, (2, 24, 24, 24))

Expand Down
16 changes: 16 additions & 0 deletions tests/test_config_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -256,6 +256,22 @@ def test_pdb(self):
with self.assertRaisesRegex(RuntimeError, ".*bdb.BdbQuit.*"):
case_pdb()

def test_get_via_attributes(self):
config = {
"A": {"B": {"C": 1}},
"my_dims": 2,
"dims_1": "$@my_dims + 1",
"patch_size": [8, 8],
"transform": {"_target_": "Lambda", "func": "$lambda x: x.reshape((1, *@patch_size))"},
}
parser = ConfigParser(config=config)
self.assertEqual(parser.A, {"B": {"C": 1}})
self.assertEqual(parser.dims_1, 3)

trans = parser.transform
result = trans(np.ones(64))
self.assertTupleEqual(result.shape, (1, 8, 8))


if __name__ == "__main__":
unittest.main()