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

Refactored ModelProperty. #914

Merged
merged 14 commits into from
Nov 29, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
38 changes: 21 additions & 17 deletions glotaran/builtin/io/yml/test/test_model_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ def test_dataset(model):
assert dataset.megacomplex == ["cmplx1"]
assert dataset.initial_concentration == "inputD1"
assert dataset.irf == "irf1"
assert dataset.scale == 1
assert dataset.scale.full_label == "1"

assert "dataset2" in model.dataset
dataset = model.dataset["dataset2"]
Expand All @@ -55,7 +55,7 @@ def test_dataset(model):
assert dataset.megacomplex == ["cmplx2"]
assert dataset.initial_concentration == "inputD2"
assert dataset.irf == "irf2"
assert dataset.scale == 2
assert dataset.scale.full_label == "2"
assert dataset.spectral_axis_scale == 1e7
assert dataset.spectral_axis_inverted

Expand Down Expand Up @@ -83,7 +83,7 @@ def test_penalties(model):
assert eac.source_intervals == [[670, 810]]
assert eac.target == "s2"
assert eac.target_intervals == [[670, 810]]
assert eac.parameter == 55
assert eac.parameter.full_label == "55"
assert eac.weight == 0.0016


Expand All @@ -108,7 +108,7 @@ def test_initial_concentration(model):
assert initial_concentration.compartments == ["s1", "s2", "s3"]
assert isinstance(initial_concentration, InitialConcentration)
assert initial_concentration.label == label
assert initial_concentration.parameters == [1, 2, 3]
assert [p.full_label for p in initial_concentration.parameters] == ["1", "2", "3"]


def test_irf(model):
Expand All @@ -120,17 +120,18 @@ def test_irf(model):
irf = model.irf[label]
assert isinstance(irf, IrfMultiGaussian)
assert irf.label == label
want = [1] if i == 1 else [1, 2]
assert irf.center == want
want = [2] if i == 1 else [3, 4]
assert irf.width == want
want = [3] if i == 1 else [5, 6]
want = ["1"] if i == 1 else ["1", "2"]
assert [p.full_label for p in irf.center] == want
want = ["2"] if i == 1 else ["3", "4"]
assert [p.full_label for p in irf.width] == want

if i == 2:
assert irf.center_dispersion_coefficients == want
want = [7, 8]
assert irf.width_dispersion_coefficients == want
want = [9]
assert irf.scale == want
want = ["3"] if i == 1 else ["5", "6"]
assert [p.full_label for p in irf.center_dispersion_coefficients] == want
want = ["7", "8"]
assert [p.full_label for p in irf.width_dispersion_coefficients] == want
want = ["9"]
assert [p.full_label for p in irf.scale] == want
assert irf.normalize == (i == 1)

if i == 2:
Expand All @@ -144,10 +145,13 @@ def test_irf(model):
def test_k_matrices(model):
assert "km1" in model.k_matrix
parameter = ParameterGroup.from_list([1, 2, 3, 4, 5, 6, 7])
print(model.k_matrix["km1"].fill(model, parameter).matrix)
reduced = model.k_matrix["km1"].fill(model, parameter).reduced(["s1", "s2", "s3", "s4"])
assert np.array_equal(
reduced, np.asarray([[1, 3, 5, 7], [2, 0, 0, 0], [4, 0, 0, 0], [6, 0, 0, 0]])
)
print(parameter)
print(reduced)
wanted = np.asarray([[1, 3, 5, 7], [2, 0, 0, 0], [4, 0, 0, 0], [6, 0, 0, 0]])
print(wanted)
assert np.array_equal(reduced, wanted)


def test_weight(model):
Expand Down
4 changes: 2 additions & 2 deletions glotaran/builtin/io/yml/test/test_model_spec.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,11 @@ dataset:

irf:
irf1:
type: gaussian
type: multi-gaussian
center: [1]
width: [2]
irf2:
type: spectral-gaussian
type: spectral-multi-gaussian
center: [1, 2]
width: [3, 4]
scale: [9]
Expand Down
88 changes: 32 additions & 56 deletions glotaran/model/item.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,15 @@
from __future__ import annotations

import copy
from textwrap import indent
from typing import TYPE_CHECKING
from typing import Callable
from typing import List
from typing import Type

from glotaran.model.property import ModelProperty
from glotaran.model.util import wrap_func_as_method
from glotaran.parameter import Parameter
from glotaran.utils.ipython import MarkdownStr

if TYPE_CHECKING:
from typing import Any
Expand Down Expand Up @@ -126,12 +127,12 @@ def decorator(cls):

fill = _create_fill_func(cls)
setattr(cls, "fill", fill)

get_parameters = _create_get_parameters(cls)
setattr(cls, "get_parameters", get_parameters)
#
# get_parameters = _create_get_parameters(cls)
# setattr(cls, "get_parameters", get_parameters)

mprint = _create_mprint_func(cls)
setattr(cls, "mprint", mprint)
setattr(cls, "markdown", mprint)

return cls

Expand Down Expand Up @@ -241,13 +242,13 @@ def from_dict(ncls, values: dict) -> cls:
if name in values:
value = values[name]
prop = getattr(item.__class__, name)
if prop.property_type == float:
if prop.glotaran_property_type == float:
value = float(value)
elif prop.property_type == int:
elif prop.glotaran_property_type == int:
value = int(value)
setattr(item, name, value)

elif not getattr(ncls, name).allow_none and getattr(item, name) is None:
elif not getattr(ncls, name).glotaran_allow_none and getattr(item, name) is None:
raise ValueError(f"Missing Property '{name}' For Item '{ncls.__name__}'")
return item

Expand All @@ -273,7 +274,7 @@ def validate(self, model: Model, parameters: ParameterGroup | None = None) -> li
for name in self._glotaran_properties:
prop = getattr(self.__class__, name)
value = getattr(self, name)
problems += prop.validate(value, model, parameters)
problems += prop.glotaran_validate(value, model, parameters)
for validator, need_parameter in self._glotaran_validators.items():
if need_parameter:
if parameters is not None:
Expand All @@ -290,7 +291,9 @@ def _create_as_dict_func(cls):
@wrap_func_as_method(cls)
def as_dict(self) -> dict:
return {
name: getattr(self.__class__, name).as_dict_value(getattr(self, name))
name: getattr(self.__class__, name).glotaran_replace_parameter_with_labels(
getattr(self, name)
)
for name in self._glotaran_properties
if name != "label" and getattr(self, name) is not None
}
Expand All @@ -315,7 +318,7 @@ def fill(self, model: Model, parameters: ParameterGroup) -> cls:
for name in self._glotaran_properties:
prop = getattr(self.__class__, name)
value = getattr(self, name)
value = prop.fill(value, model, parameters)
value = prop.glotaran_fill(value, model, parameters)
setattr(item, name, value)
return item

Expand Down Expand Up @@ -354,62 +357,35 @@ def set_state(self, state) -> cls:


def _create_mprint_func(cls):
@wrap_func_as_method(cls, name="mprint")
@wrap_func_as_method(cls, name="markdown")
def mprint_item(
self, parameters: ParameterGroup = None, initial_parameters: ParameterGroup = None
) -> str:
self, all_parameters: ParameterGroup = None, initial_parameters: ParameterGroup = None
) -> MarkdownStr:
f"""Returns a string with the {cls.__name__} formatted in markdown."""

s = "\n"
md = "\n"
if self._glotaran_has_label:
s = f"**{self.label}**"

md = f"**{self.label}**"
if hasattr(self, "type"):
s += f" ({self.type})"
s += ":\n"
md += f" ({self.type})"
md += ":\n"

elif hasattr(self, "type"):
s = f"**{self.type}**:\n"
md = f"**{self.type}**:\n"

attrs = []
for name in self._glotaran_properties:
prop = getattr(self.__class__, name)
value = getattr(self, name)
if value is None:
continue
a = f"* *{name.replace('_', ' ').title()}*: "
property_md = indent(
f"* *{name.replace('_', ' ').title()}*: "
f"{prop.glotaran_value_as_markdown(value,all_parameters, initial_parameters)}\n",
" ",
)

def format_parameter(param):
s = f"{param.full_label}"
if parameters is not None:
p = parameters.get(param.full_label)
s += f": **{p.value:.5e}**"
if p.vary:
err = p.standard_error or 0
s += f" *(StdErr: {err:.0e}"
if initial_parameters is not None:
i = initial_parameters.get(param.full_label)
s += f" ,initial: {i.value:.5e}"
s += ")*"
else:
s += " *(fixed)*"
return s

if isinstance(value, Parameter):
a += format_parameter(value)
elif isinstance(value, list) and all([isinstance(v, Parameter) for v in value]):
a += f"[{', '.join([format_parameter(v) for v in value])}]"
elif isinstance(value, dict):
a += "\n"
for k, v in value.items():
a += f" * *{k}*: "
if isinstance(v, Parameter):
a += format_parameter(v)
else:
a += f"{v}"
a += "\n"
else:
a += f"{value}"
attrs.append(a)
s += "\n".join(attrs)
return s
md += property_md

return MarkdownStr(md)

return mprint_item
4 changes: 2 additions & 2 deletions glotaran/model/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -445,8 +445,8 @@ def markdown(
if isinstance(items, dict):
items = items.values()
for item in items:
item_str = item.mprint(
parameters=parameters, initial_parameters=initial_parameters
item_str = item.markdown(
all_parameters=parameters, initial_parameters=initial_parameters
).split("\n")
string += f"* {item_str[0]}\n"
for s in item_str[1:]:
Expand Down
Loading