-
Notifications
You must be signed in to change notification settings - Fork 1
fix(dap): lmfit1d can pass any parameters with kwargs #707
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
Open
wyzula-jan
wants to merge
2
commits into
main
Choose a base branch
from
fix/dap-lmfit
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -41,6 +41,7 @@ def __init__(self, model: str, *args, continuous: bool = False, **kwargs): | |
| self.device_y = None | ||
| self.signal_y = None | ||
| self.parameters = None | ||
| self._parameter_override_names = [] | ||
| self.current_scan_item = None | ||
| self.finished_id = None | ||
| self.model = getattr(lmfit.models, model)() | ||
|
|
@@ -169,6 +170,7 @@ def configure( | |
| data_y: np.ndarray = None, | ||
| x_min: float = None, | ||
| x_max: float = None, | ||
| parameters: dict | None = None, | ||
| amplitude: lmfit.Parameter = None, | ||
| center: lmfit.Parameter = None, | ||
| sigma: lmfit.Parameter = None, | ||
|
|
@@ -195,15 +197,59 @@ def configure( | |
|
|
||
| self.oversample = oversample | ||
|
|
||
| self.parameters = {} | ||
| raw_parameters: dict = {} | ||
| if parameters: | ||
| if isinstance(parameters, lmfit.Parameters): | ||
| raw_parameters.update({name: param for name, param in parameters.items()}) | ||
| elif isinstance(parameters, dict): | ||
| raw_parameters.update(parameters) | ||
| else: | ||
| raise DAPError( | ||
| f"Invalid parameters type {type(parameters)}. Expected dict or lmfit.Parameters." | ||
| ) | ||
wyzula-jan marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| if amplitude: | ||
| self.parameters["amplitude"] = amplitude | ||
| raw_parameters["amplitude"] = amplitude | ||
| if center: | ||
| self.parameters["center"] = center | ||
| raw_parameters["center"] = center | ||
| if sigma: | ||
| self.parameters["sigma"] = sigma | ||
|
|
||
| self.parameters = deserialize_param_object(self.parameters) | ||
| raw_parameters["sigma"] = sigma | ||
|
|
||
| override_params = deserialize_param_object(raw_parameters) | ||
| if len(override_params) > 0: | ||
| valid_names = set(getattr(self.model, "param_names", [])) | ||
| if valid_names: | ||
| invalid_names = set(override_params.keys()) - valid_names | ||
| for name in invalid_names: | ||
| logger.warning( | ||
| f"Ignoring unknown lmfit parameter '{name}' for model '{self.model.__class__.__name__}'." | ||
| ) | ||
| override_params.pop(name, None) | ||
|
|
||
| self._parameter_override_names = list(override_params.keys()) | ||
| if len(override_params) > 0: | ||
| # If `params=` is provided to lmfit, it must contain ALL parameters. | ||
| # Start from model defaults and apply overrides on top. | ||
| full_params = self.model.make_params() | ||
| for name, override in override_params.items(): | ||
| full_params[name].set( | ||
| value=override.value, | ||
| vary=override.vary, | ||
| min=override.min, | ||
| max=override.max, | ||
| expr=override.expr, | ||
| brute_step=getattr(override, "brute_step", None), | ||
| ) | ||
| self.parameters = full_params | ||
| logger.info( | ||
| f"Configured lmfit model={self.model.__class__.__name__} with override_params={serialize_lmfit_params(override_params)}" | ||
| ) | ||
| else: | ||
| self.parameters = None | ||
| if parameters or amplitude or center or sigma: | ||
| logger.info( | ||
| f"No usable lmfit parameter overrides after validation for model={self.model.__class__.__name__} " | ||
| f"(input_keys={list(raw_parameters.keys())})" | ||
| ) | ||
|
|
||
| if data_x is not None and data_y is not None: | ||
| self.data = { | ||
|
|
@@ -342,9 +388,12 @@ def get_data_from_current_scan( | |
| "scan_data": True, | ||
| } | ||
|
|
||
| def process(self) -> tuple[dict, dict]: | ||
| def process(self) -> tuple[dict, dict] | None: | ||
| """ | ||
| Process data and return the result. | ||
|
|
||
| Returns: | ||
| tuple[dict, dict]: Processed data and metadata if successful, None otherwise. | ||
| """ | ||
| # get the data | ||
| if not self.data: | ||
|
|
@@ -354,10 +403,31 @@ def process(self) -> tuple[dict, dict]: | |
| y = self.data["y"] | ||
|
|
||
| # fit the data | ||
| model_name = self.model.__class__.__name__ | ||
| if self.parameters: | ||
| result = self.model.fit(y, x=x, params=self.parameters) | ||
| logger.info( | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. these logs could be potentially very verbose. Maybe put them on debug? |
||
| f"Running lmfit fit: model={model_name} points={len(x)} fixed/override_params={self._parameter_override_names}" | ||
| ) | ||
| else: | ||
| result = self.model.fit(y, x=x) | ||
| logger.info(f"Running lmfit fit: model={model_name} points={len(x)} params=<default>") | ||
|
|
||
| try: | ||
| if self.parameters: | ||
| result = self.model.fit(y, x=x, params=self.parameters) | ||
| else: | ||
| result = self.model.fit(y, x=x) | ||
| except Exception as exc: # pylint: disable=broad-except | ||
| if self.parameters is not None: | ||
| try: | ||
| params_str = serialize_lmfit_params(self.parameters) | ||
| except Exception as ser_exc: | ||
| params_str = f"<serialization failed: {ser_exc}>" | ||
| else: | ||
| params_str = "<None>" | ||
| logger.warning( | ||
| f"lmfit fit failed: model={model_name} points={len(x)} parameters={params_str} error={exc}" | ||
| ) | ||
| return | ||
|
|
||
| # if the fit was only on a subset of the data, add the original x values to the output | ||
| if self.data["x_lim"] or self.oversample != 1: | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I guess the type hint could benefit from the additional dict description
same in the doc string