Пример #1
0
def fitRingSizeHalf(t, r, rErr=None):
    '''
    Fits ring size data to the ringSizeFunc (above)
    Returns: minimizer object defined by lmfit class. To access the parameters use res.best_values['r0'].
    '''
    
    if rErr==None: rErr = np.ones_like(r)
    if r[0]<0.5 or r.size<=3: return None
    params = Parameters()
    params.add('tau', (t[-1]-t[0])/3., vary=True, min = 0, max=max(t))
    params.add('t0', t[np.argmin(np.abs(r-0.5))], vary=True)
    params.add('r0', 1.1, vary=False, min=0.)
    mod = Model(ringSizeFuncHalf)
    ind=np.where(r>0.2)[0]
    if ind.size<3: ind = np.where(r>0.)
    w = 1./rErr**2
    res=mod.fit(r[ind],x=t[ind],weights = w[ind], params=params)
    if False:
        fig = myFigure()
        print(fit_report(res))
        fig.plot(t, r, 'r')
        delta = (max(t)-min(t))
        x=np.arange(min(t)-0.2*delta,max(t)+0.2*delta,delta/100.)
        fig.plot(x, ringSizeFuncHalf(x,res.best_values['r0'], res.best_values['tau'],res.best_values['t0']),'k')
        fig.show()
    return res
Пример #2
0
    def onSaveFit(self, evt=None):
        "Save Fit and Compoents to Data File"
        print("save fit and components")
        nfit = self.current_fit
        dgroup = self.datagroup
        nfits = int(self.wids['plot_nchoice'].GetStringSelection())

        deffile = "%s_LinearFit%i.dat" % (dgroup.filename, nfit + 1)
        wcards = 'Data Files (*.dat)|*.dat|All files (*.*)|*.*'

        path = FileSave(self,
                        'Save Fit and Components to File',
                        default_file=deffile,
                        wildcard=wcards)
        if path is None:
            return

        form = self.form
        label = [' energy         ', ' data           ', ' best_fit       ']
        result = dgroup.lcf_result[nfit]

        header = [
            'Fit #%2.2d' % (nfit + 1),
            'Fit arrayname: %s' % form['arrayname'],
            'E0:  %f ' % form['e0'],
            'Energy fit range: [%f, %f]' % (form['elo'], form['ehi']),
            'Components: '
        ]
        for key, val in result.weights.items():
            header.append('  %s: %f' % (key, val))

        report = fit_report(result.result).split('\n')
        header.extend(report)

        out = [result.xdata, result.ydata, result.yfit]
        for compname, compdata in result.ycomps.items():
            label.append(' %s' % (compname + ' ' *
                                  (max(1, 15 - len(compname)))))
            out.append(compdata)

        label = ' '.join(label)
        _larch = self.parent.controller.larch
        write_ascii(path, header=header, label=label, _larch=_larch, *out)
Пример #3
0
    def onSaveFit(self, evt=None):
        "Save Fit and Compoents to Data File"
        nfit = self.current_fit
        dgroup = self.datagroup
        nfits = int(self.wids['plot_nchoice'].GetStringSelection())

        deffile = "%s_LinearFit%i.dat" % (dgroup.filename, nfit+1)
        wcards  = 'Data Files (*.dat)|*.dat|All files (*.*)|*.*'
        path = FileSave(self, 'Save Fit and Components to File',
                        default_file=deffile, wildcard=wcards)
        if path is None:
            return

        form  = self.form
        label = [' energy         ',
                 ' data           ',
                 ' best_fit       ']
        result = dgroup.lcf_result[nfit]

        header = ['Larch Linear Fit Result for Fit: #%2.2d' % (nfit+1),
                  'Dataset filename: %s ' % dgroup.filename,
                  'Larch group: %s ' % dgroup.groupname,
                  'Array name: %s' %  form['arrayname'],
                  'E0:  %f '  % form['e0'],
                  'Energy fit range: [%f, %f]' % (form['elo'], form['ehi']),
                  'Components: ']
        for key, val in result.weights.items():
            header.append('  %s: %f' % (key, val))

        report = fit_report(result.result).split('\n')
        header.extend(report)

        out = [result.xdata, result.ydata, result.yfit]
        for compname, compdata in result.ycomps.items():
            label.append(' %s' % (compname + ' '*(max(1, 15-len(compname)))))
            out.append(compdata)

        label = ' '.join(label)
        _larch = self.parent.controller.larch
        write_ascii(path, header=header, label=label, _larch=_larch, *out)
Пример #4
0
 def generate_fit_report(self):
     report_header = f'\n\n{"="*10}\nFIT REPORT\n{"="*10}\n\n'
     return report_header + fit_report(self.result.params)
Пример #5
0
def main(argv):
    parser = ArgumentParser(usage=__doc__.lstrip())
    parser.add_argument("global_pilot_file",
                        help="The name of the global pilot file")
    parser.add_argument("--walkers", "-w", type=int, default=100,
                        help="How many MCMC walkers? Default=100")
    parser.add_argument("--steps", "-s", type=int, default=2000,
                        help="How many MCMC steps? Default=2000")
    parser.add_argument("--ntemps", '-T', type=int, default=1,
                        help="How many parallel tempering temperatures? "
                             "Default=1")
    parser.add_argument("--burn", "-b", type=int, default=500,
                        help="How many initial MCMC steps do you want to "
                             "burn? Default=500")
    parser.add_argument("--thin", "-t", type=int, default=20,
                        help="Thins the chain by accepting 1 in every 'thin'. "
                             "Default=20")
    parser.add_argument("--resample", "-r", default=False, action='store_true',
                        help="Don't do Markov Chain Monte Carlo, do resampling "
                             "MC instead. All MCMC parameters are ignored if "
                             "this option is specified.")
    parser.add_argument("--qres", "-q", type=float, default=5.0,
                        help="Constant dq/q resolution. Default=5")
    parser.add_argument("--pointqres", "-p", action="store_true",
                        default=False,
                        help="Use point by point resolution smearing. "
                             "Default=False")
    parser.add_argument("--chain_input", "-i", type=str,
                        help="Initialise/restart emcee with this RAW chain. "
                             "This file is a numpy array (.npy) that would've "
                             "originally been saved by the --chain_output "
                             "option.")
    parser.add_argument("--chain_output", "-c", default='raw_chain.npy',
                        type=str,
                        help="Specify filename for unthinned, unburnt RAW "
                             "chain. The file is saved as a numpy (.npy) "
                             "array. You can use this file if you'd like to do "
                             "the burn/thin procedure yourself. You can also"
                             " use this file to restart the sampling. The array"
                             " has shape (walkers, steps, dims), where dims "
                             "represents the number of parameters you are "
                             "varying. If ntemps is > 1 then the array has "
                             "shape (ntemps, walkers, steps, dims). "
                             "Default=raw_chain.npy")
    parser.add_argument("--output", "-o", type=str, default='iterations',
                        help="Output file for burnt and thinned MCMC chain. "
                             "This is only written once the sampling has "
                             "finished")
    parser.add_argument("--nprocesses", "-n", type=int, default=1,
                        help="How many processes for parallelisation? Default=1")

    args = parser.parse_args(argv)

    # set up global fitting
    if args.pointqres:
        dqvals = None
    else:
        dqvals = args.qres

    if args.nprocesses < 1:
        args.nprocesses = 1

    global_fitter = global_fitter_setup(args.global_pilot_file,
                                        dqvals=dqvals)

    # do the Monte Carlo
    if not args.resample:
        # By Markov Chain Monte Carlo
        if args.thin < 1:
            sys.stdout.write("Can't have thin < 1, setting 'thin' to 1.\n")
            args.thin = 1
        if (args.burn < 0) or (args.burn > args.steps):
            sys.stdout.write("Can't burn < 0 or burn > steps, setting 'burn' to 1.\n")
            args.burn = 1

        res = _mcmc(args, global_fitter)
    else:
        # By resampling
        res = _resample_mc(args, global_fitter)

    # write the iterations.
    _write_results(args.output, res)

    sys.stdout.write("\nFinished MCMC\n")
    sys.stdout.write("-------------\n")
    sys.stdout.write(fit_report(res.params))
    sys.stdout.write("\n-----------------------------------------------------\n")
Пример #6
0
t = reflect.Transform('logY').transform
ydata, dydata = t(xdata, ydata, dydata)
kwds = {'dqvals': dxdata, 'transform': t}

# create the fit instance
fitter = reflect.ReflectivityFitFunction(parameters, xdata, ydata, edata=dydata,
                                    kwds=kwds)

#do the fit
if USE_DIFFERENTIAL_EVOLUTION:
    fitter.fit(method='differential_evolution')

fitter.fit()

print('-------------------------------------------------------------------')
print(DATASET_NAME)
print(fit_report(fitter))

fig = figure()
ax = fig.add_subplot(2, 1, 1)
ax.scatter(xdata, ydata, label=DATASET_NAME)
ax.plot(xdata, fitter.model(parameters), label='fit')
ylim(min(np.min(ydata), np.min(fitter.model(parameters))),
     max(np.max(ydata), np.max(fitter.model(parameters))))
xlim(np.min(xdata), np.max(xdata))
xlabel('Q')
ylabel('logR')
legend()
ax2 = fig.add_subplot(2, 1, 2)
z, rho_z = fitter.sld_profile(parameters)
ax2.plot(z, rho_z)