示例#1
0
def test_save_filter_data1d(tmp_path, clean_ui):
    """Check save_filter [Data1D]"""

    x = np.arange(1, 11, dtype=np.int16)
    ui.load_arrays(1, x, x)

    ui.notice(2, 4)
    ui.notice(6, 8)

    outfile = tmp_path / "filter.dat"
    ui.save_filter(str(outfile))

    expected = [0, 1, 1, 1, 0, 1, 1, 1, 0, 0]

    d = ui.unpack_data(str(outfile), colkeys=['X', 'FILTER'])
    assert isinstance(d, ui.Data1D)
    assert d.x == pytest.approx(x)
    assert d.y == pytest.approx(expected)
    assert d.staterror is None
    assert d.syserror is None
示例#2
0
def mwl_fit_high_level():
    """Use high-level Sherpa API.

    High-level = session and convenience functions

    Example: http://cxc.harvard.edu/sherpa/threads/simultaneous/
    Example: http://python4astronomers.github.io/fitting/spectrum.html
    """
    import sherpa.ui as ui

    fermi_data = FermiData()
    ui.load_arrays(fermi_data.name, fermi_data.x, fermi_data.y,
                   fermi_data.staterror)

    ui.load_user_stat('fermi_stat', FermiStat.calc_stat,
                      FermiStat.calc_staterror)
    # TODO: is there a good way to get the stat??
    # ui.get_stat('fermi_stat')
    # fermi_stat = ui._session._get_stat_by_name('fermi_stat')
    ui.set_stat(fermi_stat)
    # IPython.embed()

    iact_data = IACTData()
    ui.load_arrays(iact_data.name, iact_data.x, iact_data.y,
                   iact_data.staterror)

    spec_model = ui.logparabola.spec_model
    spec_model.c1 = 0.5
    spec_model.c2 = 0.2
    spec_model.ampl = 5e-11

    ui.set_source(fermi_data.name, spec_model)
    ui.set_source(iact_data.name, spec_model)

    ui.notice(lo=1e-3, hi=None)

    # IPython.embed()
    ui.fit()

    return dict(results=ui.get_fit_results(), model=spec_model)
示例#3
0
def mwl_fit_high_level():
    """Use high-level Sherpa API.

    High-level = session and convenience functions

    Example: http://cxc.harvard.edu/sherpa/threads/simultaneous/
    Example: http://python4astronomers.github.io/fitting/spectrum.html
    """
    import sherpa.ui as ui

    fermi_data = FermiData()
    ui.load_arrays(fermi_data.name, fermi_data.x, fermi_data.y, fermi_data.staterror)

    ui.load_user_stat('fermi_stat', FermiStat.calc_stat, FermiStat.calc_staterror)
    # TODO: is there a good way to get the stat??
    # ui.get_stat('fermi_stat')
    # fermi_stat = ui._session._get_stat_by_name('fermi_stat')
    ui.set_stat(fermi_stat)
    # IPython.embed()


    iact_data = IACTData()
    ui.load_arrays(iact_data.name, iact_data.x, iact_data.y, iact_data.staterror)

    spec_model = ui.logparabola.spec_model
    spec_model.c1 = 0.5
    spec_model.c2 = 0.2
    spec_model.ampl = 5e-11

    ui.set_source(fermi_data.name, spec_model)
    ui.set_source(iact_data.name, spec_model)

    ui.notice(lo=1e-3, hi=None)

    # IPython.embed()
    ui.fit()

    return Bunch(results=ui.get_fit_results(), model=spec_model)
示例#4
0
    rates = asciitable.read(filename)

    data_id = fail_types[ftype]

    ui.set_method('simplex')
    ui.load_arrays(data_id,
                   rates['time'],
                   rates['rate'])
    ui.set_staterror(data_id,
                     rates['err'])

    ftype_poly = ui.polynom1d(ftype)
    ui.set_model(data_id, ftype_poly)
    ui.thaw(ftype_poly.c0)
    ui.thaw(ftype_poly.c1)
    ui.notice(DateTime(trend_date_start).frac_year)
    ui.fit(data_id)
    ui.notice()
    myfit = ui.get_fit_results()
    axplot = ui.get_model_plot(data_id)
    if myfit.succeeded:
        b = ftype_poly.c1.val * DateTime(trend_date_start).frac_year + ftype_poly.c0.val
        m = ftype_poly.c1.val
        rep_file = open('%s_fitfile.json' % ftype, 'w')
        rep_file.write(json.dumps(dict(time0=DateTime(trend_date_start).frac_year,
                                       datestart=trend_date_start,
                                       datestop=data_stop,
                                       bin=trend_type,
                                       m=m,
                                       b=b,
                                       comment="mx+b with b at time0 and m = (delta rate)/year"),
示例#5
0
def fit_evol(dateglob='20?????', rootdir='darkhist_peaknorm', outroot='', xmin=25.0, xmax=4000,
             conf=True, gauss=False):
    results = {}
    fileglob = os.path.join(rootdir, '{}.dat'.format(dateglob))

    for i, filename in enumerate(glob(fileglob)):
        filedate = re.search(r'(\d{7})', filename).group(1)
        print "\n\n*************** {} *****************".format(filename)
        plt.figure(1)
        ui.load_data(1, filename, 2)
        data = ui.get_data()
        ui.ignore(None, xmin)
        ui.ignore(xmax, None)

        dark_models.xall = data.x
        # dark_models.imin = np.where(xall > xmin)[0][0]
        # dark_models.imax = np.where(xall > xmax)[0][0]

        sbp.gamma1 = 0.05
        sbp.gamma2 = 3.15
        sbp.gamma2.min = 2.
        sbp.gamma2.max = 4.
        sbp.x_b = 130.
        sbp.x_b.min = 100.
        sbp.x_b.max = 160.
        sbp.x_r = 50.
        ok = (data.x > 40) & (data.x < 60)
        sbp.ampl1 = np.mean(data.y[ok])

        if gauss:
            fit_gauss_sbp()
        else:
            fit_sbp()

        pars = (sbp.gamma1.val, sbp.gamma2.val, sbp.x_b.val, sbp.x_r.val, sbp.ampl1.val)
        fit_y = dark_models.smooth_broken_pow(pars, data.x)

        if conf:
            ui.set_conf_opt('numcores', 1)
            ui.conf()
            res = ui.get_conf_results()
            result = dict((x, getattr(res, x))
                          for x in ('parnames', 'parmins', 'parvals', 'parmaxes'))
            result['x'] = data.x
            result['y'] = data.y
            result['y_fit'] = fit_y
            results[filedate] = result

        if outroot is not None:
            ui.notice(0, xmax)
            ui.set_xlog()
            ui.set_ylog()
            ui.plot_fit()
            plt.xlim(1, 1e4)
            plt.ylim(0.5, 1e5)
            plt.grid(True)
            plt.xlabel('Dark current (e-/sec)')
            outfile = os.path.join(rootdir, '{}{}.png'.format(outroot, filedate))
            print 'Writing', outfile
            plt.savefig(outfile)

            if conf:
                outfile = os.path.join(rootdir, '{}{}.pkl'.format(outroot, filedate))
                print 'Writing', outfile
                pickle.dump(result, open(outfile, 'w'), protocol=-1)

    if outroot is not None:
        outfile = os.path.join(rootdir, '{}fits.pkl'.format(outroot))
        print 'Writing', outfile
        pickle.dump(results, open(outfile, 'w'), protocol=-1)

    return results