コード例 #1
0
ファイル: fitstate.py プロジェクト: opendatafit/sasview
 def make_fitproblem(self):
     # type: () -> FitProblem
     """
     Build collection of bumps fitness calculators and return the FitProblem.
     """
     # TODO: batch info not stored with project/analysis file (ticket #907)
     models = [make_fitness(state) for state in self.fits]
     if not models:
         raise RuntimeError("Nothing to fit")
     fit_problem = FitProblem(models)
     fit_problem.setp_hook = ParameterExpressions(models)
     return fit_problem
コード例 #2
0
ファイル: bumps.py プロジェクト: arm61/easyCore
    def fit(self, x: np.ndarray, y: np.ndarray, weights: Union[np.ndarray, noneType] = None,
            model=None, parameters=None, xtol=1e-6, ftol=1e-8, **kwargs) -> FitResults:
        """
        Perform a fit using the lmfit engine.

        :param x: points to be calculated at
        :type x: np.ndarray
        :param y: measured points
        :type y: np.ndarray
        :param weights: Weights for supplied measured points * Not really optional*
        :type weights: np.ndarray
        :param model: Optional Model which is being fitted to
        :type model: lmModel
        :param parameters: Optional parameters for the fit
        :type parameters: List[bumpsParameter]
        :param kwargs: Additional arguments for the fitting function.
        :return: Fit results
        :rtype: ModelResult
        """

        if weights is None:
            weights = np.sqrt(x)

        if model is None:
            model = self.make_model(pars=parameters)
            model = model(x, y, weights)
        self._cached_model = model
        problem = FitProblem(model)
        # Why do we do this? Because a fitting template has to have borg instantiated outside pre-runtime
        from easyCore import borg
        borg.stack.beginMacro('Fitting routine')
        model_results = bumps_fit(problem, **kwargs)
        self._set_parameter_fit_result(model_results)
        borg.stack.endMacro()
        return self._gen_fit_results(model_results)
コード例 #3
0
ファイル: compare.py プロジェクト: robertdfrench/sasmodels
def explore(opts):
    # type: (Dict[str, Any]) -> None
    """
    explore the model using the bumps gui.
    """
    import wx  # type: ignore
    from bumps.names import FitProblem  # type: ignore
    from bumps.gui.app_frame import AppFrame  # type: ignore
    from bumps.gui import signal

    is_mac = "cocoa" in wx.version()
    # Create an app if not running embedded
    app = wx.App() if wx.GetApp() is None else None
    model = Explore(opts)
    problem = FitProblem(model)
    frame = AppFrame(parent=None, title="explore", size=(1000, 700))
    if not is_mac: frame.Show()
    frame.panel.set_model(model=problem)
    frame.panel.Layout()
    frame.panel.aui.Split(0, wx.TOP)

    def reset_parameters(event):
        model.revert_values()
        signal.update_parameters(problem)

    frame.Bind(wx.EVT_TOOL, reset_parameters, frame.ToolBar.GetToolByPos(1))
    if is_mac: frame.Show()
    # If running withing an app, start the main loop
    if app: app.MainLoop()
コード例 #4
0
    def setup(self):
        """
        Setup problem ready to run with SasView.

        Creates a Sasview FitProblem for calling in fit()
        """
        # Bumps fails with the *args notation
        param_name_str = ', '.join(self._param_names)
        wrapper = "def fitFunction(x, {}):\n".format(param_name_str)
        wrapper += "    return func(x, {})".format(param_name_str)

        exec_dict = {'func': self.functions[self.function_id][0]}
        exec(wrapper, exec_dict)

        model = exec_dict['fitFunction']

        # Remove any function attribute. BinWidth is the only attribute in all
        # FitBenchmark (Mantid) problems.
        param_dict = {
            name: value
            for name, value in zip(self._param_names, self.initial_params)
        }

        # Create a Function Wrapper for the problem function. The type of the
        # Function Wrapper is acceptable by Bumps.
        func_wrapper = Curve(fn=model,
                             x=self.data_x,
                             y=self.data_y,
                             dy=self.data_e,
                             **param_dict)

        # Set a range for each parameter
        val_ranges = self.problem.value_ranges
        for name in self._param_names:
            min_val = -np.inf
            max_val = np.inf
            if val_ranges is not None and name in val_ranges:
                min_val = val_ranges[name][0]
                max_val = val_ranges[name][1]
            func_wrapper.__dict__[name].range(min_val, max_val)

        # Create a Problem Wrapper. The type of the Problem Wrapper is
        # acceptable by Bumps fitting.
        self._func_wrapper = func_wrapper
        self._fit_problem = FitProblem(func_wrapper)
        if self.minimizer == "lm-bumps":
            self.minimizer = "lm"
コード例 #5
0
ファイル: compare.py プロジェクト: lamstephanie/sasmodels
def explore(opts):
    """
    Explore the model using the Bumps GUI.
    """
    import wx
    from bumps.names import FitProblem
    from bumps.gui.app_frame import AppFrame

    problem = FitProblem(Explore(opts))
    is_mac = "cocoa" in wx.version()
    app = wx.App()
    frame = AppFrame(parent=None, title="explore")
    if not is_mac: frame.Show()
    frame.panel.set_model(model=problem)
    frame.panel.Layout()
    frame.panel.aui.Split(0, wx.TOP)
    if is_mac: frame.Show()
    app.MainLoop()
コード例 #6
0
ファイル: compare.py プロジェクト: willend/sasmodels
def explore(opts):
    # type: (Dict[str, Any]) -> None
    """
    explore the model using the bumps gui.
    """
    import wx  # type: ignore
    from bumps.names import FitProblem  # type: ignore
    from bumps.gui.app_frame import AppFrame  # type: ignore

    is_mac = "cocoa" in wx.version()
    # Create an app if not running embedded
    app = wx.App() if wx.GetApp() is None else None
    problem = FitProblem(Explore(opts))
    frame = AppFrame(parent=None, title="explore", size=(1000,700))
    if not is_mac: frame.Show()
    frame.panel.set_model(model=problem)
    frame.panel.Layout()
    frame.panel.aui.Split(0, wx.TOP)
    if is_mac: frame.Show()
    # If running withing an app, start the main loop
    if app: app.MainLoop()
コード例 #7
0
ファイル: Pmodel.py プロジェクト: scottwedge/dataflow
def build_problem(mydirectory, myfilebase, myend, cost="poisson"):

    monitor_efficiency = 0.1
    resolution = 0.001
    scale = resolution**2 / monitor_efficiency
    scale = 1e-6
    M = Peaks(
        [
            Gaussian(name="G1-"),
            Gaussian(name="G2-"),
            #Gaussian(name="G3-"),
            #Gaussian(name="G4-"),
            Background()
        ],
        scale,
        data=read_data(mydirectory, myfilebase, myend),
        #cost='poisson',
        cost=cost,
    )

    # Peak intensity and background
    background = 1
    M.parts[-1].C.value = background
    M.parts[-1].C.range(0, 1000)
    for peak in M.parts[:-1]:
        peak.A.value = 1. / (len(M.parts) - 1)  # Equal size peaks
        peak.A.range(0, 1)

    peak1 = M.parts[0]
    if 0:
        # Peak centers are independent
        for peak in M.parts[:-1]:
            peak.xc.range(0.45, 0.55)
            peak.yc.range(-0.55, -0.4)
    else:
        # Peak centers lie on a line
        alpha = Parameter(45.0, name="alpha")
        alpha.range(-90., 90.)
        peak1.xc.range(0.40, 0.55)
        peak1.yc.range(0.40, 0.55)
        #peak1.yc.range(-0.55,-0.4)
        for i, peak in enumerate(M.parts[1:-1]):
            delta = Parameter(.0045, name="delta-%d" % (i + 1))
            delta.range(0.00, 0.03)
            peak.xc = peak1.xc + delta * pmath.cosd(alpha)
            peak.yc = peak1.yc + delta * pmath.sind(alpha)

        # Initial values
        cx, cy = 0.4996 - 0.4957, -0.4849 + 0.4917
        alpha.value = np.degrees(np.arctan2(cy, cx))
        delta.value = np.sqrt(cx**2 + cy**2)
        peak1.xc.value, peak1.yc.value = 0.4957, 0.4917

    # Peak location and shape
    dx, dy = 0.4997 - 0.4903, -0.4969 + 0.4851
    dxm, dym = 0.4951 - 0.4960, -0.4941 + 0.4879
    peak1.s1.value = np.sqrt(dx**2 + dy**2) / 2.35 / 2
    peak1.s2.value = np.sqrt(dxm**2 + dym**2) / 2.35 / 2
    peak1.theta.value = np.degrees(np.arctan2(dy, dx))

    # Peak shape is the same across all peaks
    peak1.s1.range(0.001, 0.010)
    peak1.s2.range(0.001, 0.010)
    peak1.theta.range(-90, 90)
    for peak in M.parts[1:-1]:
        peak.s1 = peak1.s1
        peak.s2 = peak1.s2
        peak.theta = peak1.theta

    if 1:
        print "shape", peak1.s1.value, peak1.s2.value, peak1.theta.value
        print "centers alpha,delta", alpha.value, delta.value
        print "centers",(peak1.xc.value,peak1.yc.value),\
            (M.parts[1].xc.value,M.parts[1].yc.value)
    return FitProblem(M)
コード例 #8
0
    def fit(
        self,
        x: np.ndarray,
        y: np.ndarray,
        weights: Optional[np.ndarray] = None,
        model: Optional = None,
        parameters: Optional = None,
        method: Optional[str] = None,
        minimizer_kwargs: Optional[dict] = None,
        engine_kwargs: Optional[dict] = None,
        **kwargs,
    ) -> FitResults:
        """
        Perform a fit using the lmfit engine.

        :param x: points to be calculated at
        :type x: np.ndarray
        :param y: measured points
        :type y: np.ndarray
        :param weights: Weights for supplied measured points * Not really optional*
        :type weights: np.ndarray
        :param model: Optional Model which is being fitted to
        :type model: lmModel
        :param parameters: Optional parameters for the fit
        :type parameters: List[bumpsParameter]
        :param kwargs: Additional arguments for the fitting function.
        :param method: Method for minimization
        :type method: str
        :return: Fit results
        :rtype: ModelResult
        """

        default_method = {}
        if method is not None and method in self.available_methods():
            default_method["method"] = method

        if weights is None:
            weights = np.sqrt(np.abs(y))

        if engine_kwargs is None:
            engine_kwargs = {}

        if minimizer_kwargs is None:
            minimizer_kwargs = {}
        # else:
        #     minimizer_kwargs = {"fit_kws": minimizer_kwargs}
        minimizer_kwargs.update(engine_kwargs)

        if model is None:
            model = self.make_model(pars=parameters)
            model = model(x, y, weights)
        self._cached_model = model
        self.p_0 = {
            f"p{key}": self._cached_pars[key].raw_value
            for key in self._cached_pars.keys()
        }
        problem = FitProblem(model)
        # Why do we do this? Because a fitting template has to have borg instantiated outside pre-runtime
        from easyCore import borg

        borg.stack.beginMacro("Fitting routine")
        try:
            model_results = bumps_fit(problem, **default_method,
                                      **minimizer_kwargs, **kwargs)
            self._set_parameter_fit_result(model_results)
            results = self._gen_fit_results(model_results)
        except Exception as e:
            raise FitError(e)
        finally:
            borg.stack.endMacro()
        return results
コード例 #9
0
ファイル: mesh_bumps.py プロジェクト: scottwedge/dataflow
def build_problem(mydirectory, myfilebase, myend):

    M = Peaks(
        [
            Gaussian(name="G1-"),
            Gaussian(name="G2-"),
            #Gaussian(name="G3-"),
            #Gaussian(name="G4-"),
            Background()
        ],
        *read_data(mydirectory, myfilebase, myend))
    background = np.min(M.data)
    background += np.sqrt(background)
    signal = np.sum(M.data) - M.data.size * background
    M.parts[-1].C.value = background
    M.parts[-1].C.range(0, 200)
    peak1 = M.parts[0]

    if 0:
        # Peak centers are independent
        for peak in M.parts[:-1]:
            peak.xc.range(0.45, 0.55)
            peak.yc.range(-0.55, -0.4)
    else:
        # Peak centers lie on a line
        alpha = Parameter(45.0, name="alpha")
        alpha.range(-90., 90.)
        peak1.xc.range(0.40, 0.55)
        peak1.yc.range(0.40, 0.55)
        #peak1.yc.range(-0.55,-0.4)
        for i, peak in enumerate(M.parts[1:-1]):
            delta = Parameter(.0045, name="delta-%d" % (i + 1))
            delta.range(0.00, 0.03)
            peak.xc = peak1.xc + delta * pmath.cosd(alpha)
            peak.yc = peak1.yc + delta * pmath.sind(alpha)

        # Initial values
        cx, cy = 0.4996 - 0.4957, -0.4849 + 0.4917
        alpha.value = np.degrees(np.arctan2(cy, cx))
        delta.value = np.sqrt(cx**2 + cy**2)
        peak1.xc.value, peak1.yc.value = 0.4957, -0.4917

    # Initial values
    for peak in M.parts[:-1]:
        peak.A.value = signal / (len(M.parts) - 1)  # Equal size peaks
    dx, dy = 0.4997 - 0.4903, -0.4969 + 0.4851
    dxm, dym = 0.4951 - 0.4960, -0.4941 + 0.4879
    peak1.s1.value = np.sqrt(dx**2 + dy**2) / 2.35 / 2
    peak1.s2.value = np.sqrt(dxm**2 + dym**2) / 2.35 / 2
    peak1.theta.value = np.degrees(np.arctan2(dy, dx))

    # Peak intensity varies
    for peak in M.parts[:-1]:
        peak.A.range(0.10 * signal, 1.1 * signal)

    # Peak shape is the same across all peaks
    peak1.s1.range(0.001, 0.010)
    peak1.s2.range(0.001, 0.004)
    peak1.theta.range(0, 90)
    for peak in M.parts[1:-1]:
        peak.s1 = peak1.s1
        peak.s2 = peak1.s2
        peak.theta = peak1.theta

    if 1:
        print "shape", peak1.s1.value, peak1.s2.value, peak1.theta.value
        print "centers alpha,delta", alpha.value, delta.value
        print "centers",(peak1.xc.value,peak1.yc.value),\
            (M.parts[1].xc.value,M.parts[1].yc.value)
    return FitProblem(M)
コード例 #10
0
ファイル: model.py プロジェクト: perezrathke/bumps
def build_problem():

    M = Peaks(
        [
            Gaussian(name="G1-"),
            Gaussian(name="G2-"),
            #Gaussian(name="G3-"),
            #Gaussian(name="G4-"),
            Background()
        ],
        *read_data())
    background = np.min(M.data)
    background += np.sqrt(background)
    signal = np.sum(M.data) - M.data.size * background
    M.parts[-1].C.value = background
    peak1 = M.parts[0]

    peak1.xc.range(0.45, 0.55)
    peak1.yc.range(-0.55, -0.4)
    peak1.xc.value = 0.500
    peak1.yc.value = -0.485

    if 0:
        # Peak centers are independent
        for peak in M.parts[1:-1]:
            peak.xc.range(0.45, 0.55)
            peak.yc.range(-0.55, -0.4)
        M.parts[1].xc.value = 0.495
        M.parts[1].yc.value = -0.495
    else:
        # Peak centers lie on a line
        theta = Parameter(45, name="theta")
        theta.range(0, 90)
        for i, peak in enumerate(M.parts[1:-1]):
            delta = Parameter(0.0045, name="delta-%d" % (i + 1))
            delta.range(0.0, 0.015)
            peak.xc = peak1.xc + delta * cosd(theta)
            peak.yc = peak1.yc + delta * sind(theta)

        # Initial values
        cx, cy = 0.4996 - 0.4957, -0.4849 + 0.4917
        theta.value = np.degrees(np.arctan2(cy, cx))
        delta.value = np.sqrt(cx**2 + cy**2)

    # Initial values
    for peak in M.parts[:-1]:
        peak.A.value = signal / (len(M.parts) - 1)  # Equal size peaks
    dx, dy = 0.4997 - 0.4903, -0.4969 + 0.4851
    dxm, dym = 0.4951 - 0.4960, -0.4941 + 0.4879
    peak1.s1.value = np.sqrt(dx**2 + dy**2) / 2.35 / 2
    peak1.s2.value = np.sqrt(dxm**2 + dym**2) / 2.35 / 2
    peak1.theta.value = np.degrees(np.arctan2(dy, dx))

    # Peak intensity varies
    for peak in M.parts[:-1]:
        peak.A.range(0.1 * signal, 1.1 * signal)

    peak1.s1.range(0.002, 0.02)
    peak1.s2.range(0.001, 0.02)
    peak1.theta.range(-90, -0)

    if 1:
        # Peak shape is the same across all peaks
        for peak in M.parts[1:-1]:
            peak.s1 = peak1.s1
            peak.s2 = peak1.s2
            peak.theta = peak1.theta
    else:
        for peak in M.parts[1:-1]:
            peak.s1.range(*peak1.s1.bounds.limits)
            peak.s2.range(*peak1.s2.bounds.limits)
            peak.theta.range(*peak1.theta.bounds.limits)

    if 1:
        M.parts[-1].C.pmp(100.0)

    if 1:
        for peak in M.parts[:-1]:
            peak.s1.value = 0.006
            peak.s2.value = 0.002
            peak.theta.value = -60.0
            peak.A.value = signal / 2

    if 0:
        print("shape", peak1.s1.value, peak1.s2.value, peak1.theta.value)
        print("centers theta,delta", theta.value, delta.value)
        print("centers", (peak1.xc.value, peak1.yc.value),
              (M.parts[1].xc.value, M.parts[1].yc.value))
    return FitProblem(M)