Beispiel #1
0
    def init_boundary_guard(
        file,
        param_limits,
        bg_lim,
        invalid_llh,
        prior=False,
        Tprior=None,
        custom_objects=None,
    ):
        if custom_objects == None:
            model = tf.keras.models.load_model(file)
        else:
            model = tf.keras.models.load_model(file,
                                               custom_objects=custom_objects)
        param_limits = tf.constant(param_limits, tf.float32)
        bg_lim = tf.constant(bg_lim, tf.float32)
        invalid_llh = tf.constant(invalid_llh, tf.float32)
        prior = tf.constant(prior, tf.bool)
        if Tprior is not None:
            with open(Tprior, "rb") as F:
                Tprior = pickle.load(F)
            Tprior = UnivariateSpline._from_tck(Tprior)
            Tprior.ext = 1

        return dict(
            model=model,
            param_limits=param_limits,
            bg_lim=bg_lim,
            invalid_llh=invalid_llh,
            prior=prior,
            Tprior=Tprior,
        )
Beispiel #2
0
    def _spline_dirichlet(self, x, y, k, s, w=None):
        """

        Parameters
        ----------
        x : array_like
            Input x coordinate values.
        y : array_like
            Input y coordinate values.
        k : int
            Degree of Spline polynomial.
        s : float (between 0 and 1)
            Sensitivity parameter  (0 is for interpolating, 1 is for maximal smoothing).
        w : array_like, optional
            Predefined weights.

        Returns
        -------
        spline: UnivariateSpline
            Returns Spline which best suits given minimization problem.

        """
        t, c0, k = self._guess(x, y, k, s, w=w)
        con = {
            'type': 'eq',
            'fun': lambda c: splev(0, (t, c, k), der=0) - 1,
        }
        opt = minimize(self._err, c0, (x, y, t, k, w), constraints=con)
        copt = opt.x
        return UnivariateSpline._from_tck((t, copt, k))
def optimized_spline(x, y, k=3, s=0, w=None):
    t, c0, k = splrep(x, y, w, k=k, s=s)
    x0 = x[0]
    constraint = {}
    constraint['type'] = 'eq'
    constraint['fun'] = lambda c: splev(x0, (t, c, k), der=1)
    constraints = [constraint]
    res = minimize(error_function, c0, (x, y, t, k, w), constraints=constraints)
    return UnivariateSpline._from_tck((t, res.x, k))
Beispiel #4
0
def load_splines(dye='BPB', file=None):
    """
    Load saved splines for 
    """
    splines = load_spline_tcks(file)[dye]

    return {
        k: UnivariateSpline._from_tck(tck_2_array(tck))
        for k, tck in splines.items()
    }
Beispiel #5
0
def optimized_spline(x, y, k=3, s=0, w=None):
    t, c0, k = splrep(x, y, w, k=k, s=s)
    x0 = x[0]
    constraint = {}
    constraint['type'] = 'eq'
    constraint['fun'] = lambda c: splev(x0, (t, c, k), der=1)
    constraints = [constraint]
    res = minimize(error_function,
                   c0, (x, y, t, k, w),
                   constraints=constraints)
    return UnivariateSpline._from_tck((t, res.x, k))
Beispiel #6
0
    def _load_pion_function(self):
        """Returns the universal function on a fixed energy range
        """
        from pickle import load as pickle_load
        from scipy.interpolate import UnivariateSpline

        uf_file = join(global_path, 'data/pion_spline.pkl')
        with open(uf_file, 'r') as f:
            tck = pickle_load(f)

        self.pion_spl = UnivariateSpline._from_tck(tck)
Beispiel #7
0
    def _load_pion_function(self):
        """Returns the universal function on a fixed energy range
        """
        from pickle import load as pickle_load
        from scipy.interpolate import UnivariateSpline

        uf_file = join(config.data_dir, 'pion_spline.pkl')
        with open(uf_file, 'rb') as f:
            tck = pickle_load(f, encoding='latin1')

        self.pion_spl = UnivariateSpline._from_tck(tck)
Beispiel #8
0
def spline_neumann(x, y, k=3, s=0, w=None):
    t, c0, k = guess(x, y, k, s, w=w)
    x0 = x[0]  # point at which zero slope is required
    con = {
        'type': 'eq',
        'fun': lambda c: splev(x0, (t, c, k), der=1),
        #'jac': lambda c: splev(x0, (t, c, k), der=2) # doesn't help, dunno why
    }
    opt = minimize(err, c0, (x, y, t, k, w), constraints=con)
    copt = opt.x
    return UnivariateSpline._from_tck((t, copt, k))
Beispiel #9
0
        def alphapi(energies):
            """Returnes the scaling coefficient for pions as a function of energy
            
            Arguments
            ---------
            energies -- {array, float} energies where to evaluate, in GeV
            """
            tp1 = 10**(-.18)
            tp2 = 10**(.55)
            he_alphapi = UnivariateSpline._from_tck(tck, ext=3)  # ext='const'
            api = 2./3 * np.ones_like(energies)
            api[(tp1 < energies) * (energies < tp2)] = sigm(
                np.log10(energies[(tp1 < energies) * (energies < tp2)]), .2, .25, 8, .65, True) 
            api[tp2 <= energies] = he_alphapi(np.log10(energies[tp2 <= energies]))

            return api
Beispiel #10
0
    def function(self, x, *coefs):
        # Order of polynomial
        k = self.k

        # Number of coefficients
        n = k + 1

        # Knot positions
        t_arr = np.zeros(n * 2, dtype=float)
        t_arr[:n] = min(x)
        t_arr[n:] = max(x)

        # Coefficients
        c_arr = np.zeros(n * 2, dtype=float)
        c_arr[:n] = coefs

        # Build Spline function
        tck = [t_arr, c_arr, k]
        model = UnivariateSpline._from_tck(tck)

        # Return predicted function
        return model(x)
Beispiel #11
0
def qeModel(ext):
    """
    This function returns a callable object that returns the QE of a CCD
    (relative to CCD2) as a function of wavelength(s) in nm. The QE data is
    provided as a dict, keyed by the array_name() descriptor of the CCD.
    The value is either a list (interpreted as polynomial coefficients) or a
    dict describing a spline.

    NB. Spline objects defined in the dict return the decimal logarithm of
    the relative QE, while polynomials simply return the relative QE.

    In addition, if the model changes, the value can be a dict keyed by the
    earliest UT date at which each model should be applied.

    Parameters
    ----------
    ext: single-slice AstroData object
        the extension to calculate the QE coefficients for

    Returns
    -------
    callable: a function to convert wavelengths in nm to relative QE
    """
    # All coefficients are for nm (not AA as in G-IRAF)
    qeData = {
        # GMOS-N EEV CCD1 and 3
        "EEV_9273-16-03": [9.883090E-1, -1.390254E-5,  5.282149E-7, -6.847360E-10],
        "EEV_9273-20-03": [9.699E-1, 1.330E-4, -2.082E-7, 1.206E-10],
        # GMOS-N Hamamatsu CCD1 and 3
        "BI13-20-4k-1": {"order": 3,
                         "knots": [366.5, 413.500044, 435.500048, 465.000052, 478.500054,
                                   507.500058, 693.000014, 1062.000039],
                         "coeffs": [1.20848283, 1.59132929, 1.58317142, 1.25123198, 1.14410563,
                                    0.98095206, 0.83416436, 1.03247587, 1.15355675, 1.10176507]},
        "BI13-18-4k-2": {"order": 3,
                         "knots": [341.750054, 389.500062, 414.000067, 447.500006, 493.000079,
                                   592.000013, 694.500021, 1057.000048],
                         "coeffs": [0.90570141, 0.99834392, 1.6311227 , 1.47271364, 1.13843214,
                                    0.91170917, 0.88454097, 1.06456595, 1.16684561, 1.10476059]},
        # IRAF coefficients
        #"BI13-20-4k-1": [-2.45481760e+03, 3.24130657e+01, -1.87380500e-01,
        #                 6.23494400e-04, -1.31713482e-06, 1.83308885e-09,
        #                 -1.68145852e-12, 9.80603592e-16, -3.30016761e-19,
        #                 4.88466076e-23],
        #"BI13-18-4k-2": [3.48333720e+03, -5.27904605e+01, 3.48210500e-01,
        #                 -1.31286828e-03, 3.12154994e-06, -4.85949692e-09,
        #                 4.95886638e-12, -3.20198283e-15, 1.18833302e-18,
        #                 -1.93303639e-22],
        # GMOS-S EEV CCD1 and 3
        "EEV_2037-06-03": {"1900-01-01": [2.8197, -8.101e-3, 1.147e-5, -5.270e-9],
                           "2006-08-31": [2.225037, -4.441856E-3, 5.216792E-6, -1.977506E-9]},
        "EEV_8261-07-04": {"1900-01-01": [1.3771, -1.863e-3, 2.559e-6, -1.0289e-9],
                           "2006-08-31": [8.694583E-1, 1.021462E-3, -2.396927E-6, 1.670948E-9]},
        # GMOS-S Hamamatsu CCD1 and 3
        "BI5-36-4k-2": [-6.00810046e+02,  6.74834788e+00, -3.26251680e-02,
                        8.87677395e-05, -1.48699188e-07, 1.57120033e-10,
                        -1.02326999e-13, 3.75794380e-17, -5.96238257e-21],
        "BI12-34-4k-1": [7.44793105e+02, -1.22941630e+01, 8.83657074e-02,
                         -3.62949805e-04, 9.40246850e-07, -1.59549327e-09,
                         1.77557909e-12, -1.25086490e-15, 5.06582071e-19,
                         -8.99166534e-23]
     }

    array_name = ext.array_name().split(',')[0]
    try:
        data = qeData[array_name]
    except KeyError:
        return None

    # Deal with date-dependent changes
    if isinstance(data, dict) and 'knots' not in data:
        obs_date = ext.ut_date()
        for k in sorted(data):
            if obs_date >= datetime.strptime(k, "%Y-%m-%d"):
                use_data = data[k]
        data = use_data

    # data is either a dict defining a spline that defines QE
    # or a list of polynomial coefficients that define QE
    if 'knots' in data:
        # Duplicate the knots at either end for the correct format
        order = data["order"]
        knots = data["knots"]
        knots[0:0] = [knots[0]] * order
        knots.extend(knots[-1:] * order)
        coeffs = data["coeffs"] + [0] * (order+1)
        spline = UnivariateSpline._from_tck((knots, coeffs, order))
        return spline
    else:
        model_params = {'c{}'.format(i): c for i, c in enumerate(data)}
        model = models.Polynomial1D(degree=len(data)-1, **model_params)
        return model
def qeModel(ext):
    """
    This function returns a callable object that returns the QE of a CCD
    (relative to CCD2) as a function of wavelength(s) in nm. The QE data is
    provided as a dict, keyed by the array_name() descriptor of the CCD.
    The value is either a list (interpreted as polynomial coefficients) or a
    dict describing a spline.

    NB. Spline objects defined in the dict return the decimal logarithm of
    the relative QE, while polynomials simply return the relative QE.

    In addition, if the model changes, the value can be a dict keyed by the
    earliest UT date at which each model should be applied.

    Parameters
    ----------
    ext: single-slice AstroData object
        the extension to calculate the QE coefficients for

    Returns
    -------
    callable: a function to convert wavelengths in nm to relative QE
    """
    # All coefficients are for nm (not AA as in G-IRAF)
    qeData = {
        # GMOS-N EEV CCD1 and 3
        "EEV_9273-16-03":
        [9.883090E-1, -1.390254E-5, 5.282149E-7, -6.847360E-10],
        "EEV_9273-20-03": [9.699E-1, 1.330E-4, -2.082E-7, 1.206E-10],
        # GMOS-N Hamamatsu CCD1 and 3
        "BI13-20-4k-1": {
            "order":
            3,
            "knots": [
                358.0, 380.0, 428.0, 468.0, 576.0, 648.0, 798.0, 932.0, 966.0,
                994.0, 1010.0, 1028.0, 1044.0, 1076.0
            ],
            "coeffs": [
                0.014629039930259876, 0.10133317072093591, 0.2384728514854233,
                0.0778544705196136, -0.06232251896695778, -0.0671226704286497,
                0.0017962888751030116, 0.02399802448657926,
                0.06062000896013293, 0.04661836594286457, 0.05694058456700794,
                0.020108979328507717, 0.00719658389760285,
                0.029938578274652766, 0.05265151968369216, 0.04654560999567498
            ]
        },
        "BI13-18-4k-2": {
            "order":
            3,
            "knots": [
                358.0, 432.0, 476.0, 520.0, 602.0, 640.0, 678.0, 752.0, 914.0,
                1002.0, 1040.0, 1076.0
            ],
            "coeffs": [
                0.02206208508099143, 0.2834094598715138, 0.07132646057310524,
                -0.01980030661665999, -0.05201598712929662,
                -0.06777120754328926, -0.012413172958416104,
                -0.015591358664326838, 0.03433933272643748,
                0.04127142803163095, 0.06235368833554948,
                -0.008691968589858072, 0.06049075935311075, 0.0484080146014316
            ]
        },
        # GMOS-S EEV CCD1 and 3
        "EEV_2037-06-03": {
            "1900-01-01": [2.8197, -8.101e-3, 1.147e-5, -5.270e-9],
            "2006-08-31": [2.225037, -4.441856E-3, 5.216792E-6, -1.977506E-9]
        },
        "EEV_8261-07-04": {
            "1900-01-01": [1.3771, -1.863e-3, 2.559e-6, -1.0289e-9],
            "2006-08-31":
            [8.694583E-1, 1.021462E-3, -2.396927E-6, 1.670948E-9]
        },
        # GMOS-S Hamamatsu CCD1 and 3
        "BI5-36-4k-2": [
            -6.00810046e+02, 6.74834788e+00, -3.26251680e-02, 8.87677395e-05,
            -1.48699188e-07, 1.57120033e-10, -1.02326999e-13, 3.75794380e-17,
            -5.96238257e-21
        ],
        "BI12-34-4k-1": [
            7.44793105e+02, -1.22941630e+01, 8.83657074e-02, -3.62949805e-04,
            9.40246850e-07, -1.59549327e-09, 1.77557909e-12, -1.25086490e-15,
            5.06582071e-19, -8.99166534e-23
        ]
    }

    array_name = ext.array_name().split(',')[0]
    try:
        data = qeData[array_name]
    except KeyError:
        return None

    # Deal with date-dependent changes
    if isinstance(data, dict) and 'knots' not in data:
        obs_date = ext.ut_date()
        for k in sorted(data):
            if obs_date >= datetime.strptime(k, "%Y-%m-%d"):
                use_data = data[k]
        data = use_data

    # data is either a dict defining a spline that defines log10(QE)
    # or a list of polynomial coefficients that define QE
    if 'knots' in data:
        # Duplicate the knots at either end for the correct format
        order = data["order"]
        knots = data["knots"]
        knots[0:0] = [knots[0]] * order
        knots.extend(knots[-1:] * order)
        coeffs = data["coeffs"] + [0] * (order + 1)
        spline = UnivariateSpline._from_tck((knots, coeffs, order))
        return lambda x: 10**spline(x)
    else:
        model_params = {'c{}'.format(i): c for i, c in enumerate(data)}
        model = models.Polynomial1D(degree=len(data) - 1, **model_params)
        return model