Exemplo n.º 1
0
def test_start():
    m = minuit(fn, x, y, start=[1,2,3,4,5])
    assert_equal(m.values['e'], 5, 'minuit start assignment named')
    
    m = minuit(fn2, x, y, start=[1,2,3,4,5])
    assert_equal(m.values['x4'], 5, 'minuit start assignment unnamed')
    
    m = minuit(fn, x, y, e=5)
    assert_equal(m.values['e'], 5, 'minuit start assignment single named')
    
    m = minuit(fn, x, y)
    assert_equal(m.values['e'], 1, 'minuit start default param named')
Exemplo n.º 2
0
def test_limit_broadcast():
    m = minuit(fn, x, y, limit=[0,5])
    limits_all = [m.limits[k][1] == 5 for k in 'abcde']
    assert_equal(all(limits_all), True, 'minuit limits broadcasting')    
    
    limits_all = [m.limits[k][0] == 0 for k in 'abcde']
    assert_equal(all(limits_all), True, 'minuit limits broadcasting')    
Exemplo n.º 3
0
def _fit_single_minuit(fn, x, y, dy, fixed, do_minos=True, **kwargs):
    """
        Fit data with minuit minimizer
    """
    
    # set up minuit inputs
    bounds = np.array(kwargs['bounds']).T
    
    kwargs_minuit = {'start':kwargs['p0'], 
                     'limit':bounds, 
                     'fix':fixed, 
                     'print_level':kwargs.get('print_level', 0), 
                     }
    
    name = kwargs.get('name', None)
    if name is None:    
        name = inspect.getfullargspec(fn).args
        if 'self' in name:                  name.remove('self')
        if len(name) == len(kwargs['p0']):  kwargs_minuit['name'] = name
    else:
        kwargs_minuit['name'] = name
    
    m = minuit(fn, x, y, dy, **kwargs_minuit)
    m.migrad()
    
    # get errors
    if do_minos:
        try:
            m.minos()
            names = list(m.mname)
            mlower = np.abs(m.mlower)
            mupper = m.mupper
            
            # insert errors of zero for fixed parameters
            lower = [mlower[names.index(p)] if not m.fixed[p] else 0 for p in m.parameters]
            upper = [mupper[names.index(p)] if not m.fixed[p] else 0 for p in m.parameters]
            
            
        except RuntimeError as errmsg: # migrad did not converge
            print(errmsg)
            err = m.errors
            lower, upper = (err, err)
    else:
        m.hesse()
        err = m.errors
        lower, upper = (err, err)
    
    # get parameters
    par = m.values
    
    try:
        cov = m.covariance
    except RuntimeError:
        cov = None
    
    dof = len(y) - len(kwargs['p0'])
    chi = m.fval/dof
    
    return (par, cov, lower, upper, chi, m)
Exemplo n.º 4
0
def test_limit_named_and_list_assign():
    m = minuit(fn, x, y, limit_e=[1,2], limit=[0,5])
    
    assert_equal(m.limits['e'][0], 1, 'minuit limits 0 list and named assignment')
    assert_equal(m.limits['e'][1], 2, 'minuit limits 1 list and named assignment')
    
    others = [m.limits[k][0]==0 for k in 'abcd']
    assert_equal(all(others), True, 'minuit limits 0 list and named assignment')
    
    others = [m.limits[k][1]==5 for k in 'abcd']
    assert_equal(all(others), True, 'minuit limits 1 list and named assignment')
Exemplo n.º 5
0
def test_limit_named_assign():
    m = minuit(fn, x, y, limit_e=[0,5])
    assert_equal(m.limits['e'][0], 0, 'minuit limits 0 named assignment')
    assert_equal(m.limits['e'][1], 5, 'minuit limits 1 named assignment')
Exemplo n.º 6
0
 def _do_fit(self, text):
     
     # save model text
     self.text= text[-1]
     
     # get fit data
     xstr = self.xaxis.get()
     ystr = self.yaxis.get()
     
     # Make model
     parnames = self.output_par_text.get('1.0', END).split('\n')[:-1]
     parstr = ', '.join(parnames)
     eqn = text[-1].split('=')[-1]
     model = 'lambda x, %s : %s' % (parstr, eqn)
     
     self.logger.info('Fitting model %s for x="%s", y="%s"', model, xstr, ystr)
     self.model_fn = eval(model)
     npar = len(parnames)
     
     # set up p0, bounds
     p0 = self.new_par['p0'].values
     blo = self.new_par['blo'].values
     bhi = self.new_par['bhi'].values
     
     p0 = list(map(float, p0))
     blo = list(map(float, blo))
     bhi = list(map(float, bhi))
                 
     # get data to fit
     xvals, xerrs_l, xerrs_h = self._get_data(xstr)
     yvals, yerrs_l, yerrs_h = self._get_data(ystr)
     
     # minimize
     m = minuit(self.model_fn, xvals, yvals, 
               dy = yerrs_h, 
               dx = xerrs_h, 
               dy_low = yerrs_l, 
               dx_low = xerrs_l,
               name = parnames,
               print_level = 0,
               limit = np.array([blo, bhi]).T,
               start = p0,
               )
     
     m.migrad()
     m.hesse()
     m.minos()
     
     # print fitting quality
     try:
         print(m.fmin)
         print(m.params)
         print(m.merrors)
     except UnicodeEncodeError:
         pass
     
     # get results
     par = m.values
     self.par = par
     n = len(m.merrors)
     
     if npar == 1:
         std_l = np.array([m.merrors[i].lower for i in range(n)])
         std_h = np.array([std_l])
     else:
         std_l = np.array([m.merrors[i].lower for i in range(n)])
         std_h = np.array([m.merrors[i].upper for i in range(n)])
         
     # chi2
     chi = m.chi2
     self.chi_label['text'] = 'ChiSq: %.2f' % np.around(chi, 2)
     self.chi = chi
     
     self.logger.info('Fit model results: %s, Errors-: %s, Errors+: %s', 
                     str(par), str(std_l), str(std_h))
     
     self.bfit.plt.figure('param')
     self.draw_data()
     self.draw_model()    
     
     return (par, std_l, std_h)
Exemplo n.º 7
0
    def _do_migrad(self, master_fn, master_fnprime, do_minos, p0_first,
                   **fitargs):

        # set args
        limit = fitargs.get('bounds', None)
        if limit is not None:
            limit = np.array(limit).T

        kwargs_minuit = {
            'start': p0_first,
            'limit': limit,
            'print_level': fitargs.get('print_level', 1),
        }

        # get minuit obj
        m = minuit(master_fn,
                   self.xcat,
                   self.ycat,
                   dy=self.dycat,
                   dx=self.dxcat,
                   dy_low=self.dycat_low,
                   dx_low=self.dxcat_low,
                   fn_prime=master_fnprime,
                   **kwargs_minuit)

        self.ls = m.ls
        self.minuit = m

        # minimize
        try:
            m.migrad()
        except UnicodeEncodeError:  # can't print on older machines
            pass

        # check minimum
        if not m.fmin.is_valid:
            raise RuntimeError('Minuit failed to converge to a valid minimum')

        # get errors
        if do_minos:
            try:
                m.minos()
            except UnicodeEncodeError:  # can't print on older machines
                pass

            lower = np.abs(m.mlower)
            upper = m.mupper
        else:
            try:
                m.hesse()
            except UnicodeEncodeError:  # can't print on older machines
                pass

            lower = m.errors
            upper = lower

        # get output
        par = m.values
        cov = m.covariance

        return (par, lower, upper, cov)
Exemplo n.º 8
0
def test_fix_named_and_list_assign():
    m = minuit(fn, x, y, fix_e=False, fix=True)
    assert_equal(m.fixed['e'], False, 'minuit fixed list and named assignment')
    
    others = [m.fixed[k] for k in 'abcd']
    assert_equal(all(others), True, 'minuit fixed list and named assignment')
Exemplo n.º 9
0
def test_fix_named_assign():
    m = minuit(fn, x, y, fix_e=True)
    assert_equal(m.fixed['e'], True, 'minuit fixed named assignment')
    
    fixed_other = [m.fixed[k] for k in 'abcd']
    assert_equal(any(fixed_other), False, 'minuit fixed named assignment, other')
Exemplo n.º 10
0
def test_fix_broadcast():
    m = minuit(fn, x, y, fix=True)
    assert_equal(m.fixed['e'], True, 'minuit fixed broadcasting')
Exemplo n.º 11
0
def test_fix_assign():
    m = minuit(fn, x, y, fix=[True, True, True, True, True])
    assert_equal(m.fixed['e'], True, 'minuit fixed assignment')
Exemplo n.º 12
0
def test_name_default():
    m = minuit(fn2, x, y, name=['a', 'b', 'c', 'd', 'e'])    
    assert_equal(m.values['e'], 1, 'minuit start default param unnamed')
Exemplo n.º 13
0
def test_name_assign():
    m = minuit(fn2, x, y, name=['a', 'b', 'c', 'd', 'e'])
    assert m.values['e'], 'minuit name assignment'
Exemplo n.º 14
0
def test_limit_assign():
    m = minuit(fn, x, y, limit=[[0,1],[0,2],[0,3],[0,4],[0,5]])
    assert_equal(m.limits['e'][1], 5, 'minuit limits assignment')    
Exemplo n.º 15
0
def test_error_named_and_list_assign():
    m = minuit(fn, x, y, error_e=5, error=1)
    assert_equal(m.errors['e'], 5, 'minuit errors list and named assignment')
    
    others = [m.errors[k]==1 for k in 'abcd']
    assert_equal(all(others), True, 'minuit errors list and named assignment')
Exemplo n.º 16
0
def test_error_named_assign():
    m = minuit(fn, x, y, error_e=5)
    assert_equal(m.errors['e'], 5, 'minuit errors named assignment')
Exemplo n.º 17
0
def test_error_broadcast():    
    m = minuit(fn, x, y, error=5)
    errors_all = [m.errors[k] == 5 for k in 'abcde']
    assert_equal(all(errors_all), True, 'minuit errors broadcasting')
Exemplo n.º 18
0
def test_error_assign():
    m = minuit(fn, x, y, error=[1,2,3,4,5])
    assert_equal(m.errors['e'], 5, 'minuit errors assignment')