From c601e77cec18d230be4769bc8901493de7a2396b Mon Sep 17 00:00:00 2001 From: Dominik Demuth Date: Sun, 30 Jul 2023 19:34:59 +0200 Subject: [PATCH] fit with expression works with single fit --- src/nmreval/fit/parameter.py | 13 ++++++++++--- src/nmreval/models/spectrum.py | 2 +- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/src/nmreval/fit/parameter.py b/src/nmreval/fit/parameter.py index a7800a3..4090574 100644 --- a/src/nmreval/fit/parameter.py +++ b/src/nmreval/fit/parameter.py @@ -2,6 +2,7 @@ from __future__ import annotations from numbers import Number from itertools import count +from re import sub import numpy as np @@ -69,6 +70,9 @@ class Parameters(dict): name = par.name else: par = Parameter(name=name, value=value, var=var, lb=lb, ub=ub) + + name = _prepare_namespace_string(name) + self[name] = par par.eval_allowed = False self._namespace[name] = par.value @@ -114,6 +118,7 @@ class Parameter: self._expr = None if isinstance(value, str): + value = _prepare_namespace_string(value) self._expr = value self.var = False @@ -171,9 +176,7 @@ class Parameter: @property def value(self) -> float: if self._expr is not None and self.eval_allowed: - print(self._expr, self.namespace) - print(eval(self._expr, self.namespace)) - return eval(self._expr, self.namespace) + return eval(self._expr, {}, self.namespace) elif self._value is not None: return self._value @@ -216,3 +219,7 @@ class Parameter: para_copy = Parameter(name=self.name, value=val, var=self.var, lb=self.lb, ub=self.ub) return para_copy + + +def _prepare_namespace_string(expr: str) -> str: + return sub('[\(\)\{.\}\\\]', '_', expr) diff --git a/src/nmreval/models/spectrum.py b/src/nmreval/models/spectrum.py index 2a59aee..1c78de2 100644 --- a/src/nmreval/models/spectrum.py +++ b/src/nmreval/models/spectrum.py @@ -56,7 +56,7 @@ class Lorentzian: off (float): baseline """ - print('Lorentzian', a, mu, sigma, off) + # print('Lorentzian', a, mu, sigma, off) return (a/np.pi) * 2*sigma / (4*(x-mu)**2 + sigma**2) + off