Example #1
0
    def open(self):

        if self.opened:
            return True

        try:
            datfile = open(self.csvfile, 'r', encoding='utf-8')
        except TypeError:
            datfile = open(self.csvfile, 'rb')

        reader = csv.reader(datfile)

        if self._has_header:
            next(reader)

        try:
            for line in reader:
                A = int(line[0])
                Z = int(line[1])
                energy = ufloat_fromstr(line[2])
                sigma = ufloat_fromstr(line[3])
                k0 = ufloat_fromstr(line[4])
                gamma = PGAAGamma(Nuclides(Z, A)[0],
                                  energy,
                                  sigma=sigma,
                                  k0=k0,
                                  k0_comp=self.k0_comp)
                self.append(gamma)
        except csv.Error as e:
            hdtv.ui.error('file %s, line %d: %s' %
                          (self.csvfile, reader.line_num, e))
        else:
            self.opened = True
        finally:
            datfile.close()
def renyi_sse_add(swap, for_each='L', **kwargs):
    if 'inc_range' not in kwargs:
        kwargs['inc_range'] = []

    values = defaultdict(dict)   

    for dset in swap:        
        if 'special' in kwargs:
            if kwargs['special'] == 'left_half':
                kwargs['inc_range'] = range(0, len(dset.x)/2);
            elif kwargs['special'] == 'right_half':
                kwargs['inc_range'] = range(len(dset.x)/2, len(dset.x));

        inc_range = kwargs['inc_range']

        if dset.props[for_each] in values.keys():
            pass
        else:
            values[dset.props[for_each]] = uncertainties.ufloat(0, 0)

        for x, y in zip(dset.x, dset.y):            
            if int(x) not in inc_range:
                continue

            u = uncertainties.ufloat_fromstr(str(y))                
            if u.nominal_value < 1e-12:
                print >> sys.stderr, "Plottery: Warning - entry", j, "is zero"
                continue
            values[dset.props[for_each]] += -uncertainties.umath.log(u/(uncertainties.ufloat_fromstr("1 +/- 0") -u))

    x_values = values.keys()
    y_values = [v.nominal_value for k, v in values.items()]
    y_errors = [v.std_dev for k, v in values.items()]

    return x_values, y_values, y_errors
Example #3
0
def countRR(orig_df, mu_df, **kwargs):
    """
    Assumption: One does not measure an isotope after 10 half-lives.
    Therefore we calculate delta_t and compare it with half-lives.
    If delta_t < 10HL => select df[Half-life] > 0.1 delta_t
    """
    AVOGADRO = float(6.02214076e+23)

    orig_df["Half-life [s]"] = orig_df[["Half-life [s]", "sigm_Half-life [s]"
                                        ]].apply(uncert_series, axis=1)
    orig_df["sigm_Area"] = 0.01 * orig_df["Area"] * orig_df["%err"]
    orig_df["Area"] = orig_df[["Area", "sigm_Area"]].apply(uncert_series,
                                                           axis=1)
    orig_df["Ig"] = orig_df[["Ig", "sigm_Ig"]].apply(uncert_series, axis=1)

    irr_start = pd.to_datetime(kwargs["irradiation_start"], dayfirst=True)
    t_irr = parse_time_unc(kwargs["irradiation_time"])
    acq_started = pd.to_datetime(orig_df["Acquisition Started"][0],
                                 dayfirst=True)
    delta_t = (acq_started - irr_start).total_seconds() - t_irr
    T_LOW = 0.1 * delta_t
    T_HIGH = 6e+6

    df = orig_df[(orig_df["Half-life [s]"] > T_LOW)
                 & (orig_df["Half-life [s]"] < T_HIGH)]
    lines_df = orig_df[orig_df["E_tab"].isna()]
    df_high = orig_df[(orig_df["Half-life [s]"] >= T_HIGH)]

    mu = get_mu_col(df["Energy"], mu_df)
    mu = mu.astype(np.float64)

    rho = ufloat_fromstr(kwargs['foil_material_rho'])
    d = ufloat_fromstr(kwargs['foil_thickness'])
    k = (mu * rho * d) / (1 - unp.exp(-mu * rho * d))

    lam = np.log(2) / df["Half-life [s]"]

    mass = ufloat_fromstr(kwargs['foil_mass'])
    molar_mass = ufloat_fromstr(kwargs['foil_material_molar_mass'])

    N = mass * AVOGADRO / molar_mass

    real_time = lines_df['Real Time'][0]
    live_time = lines_df['Live Time'][0]

    nom = ((real_time / live_time) * k * lam * df["Area"])
    denom = (N * (1 - unp.exp(-lam * t_irr)) * unp.exp(-lam * delta_t) *
             (1 - unp.exp(-lam * real_time)) * df["eps"] * df["Ig"])

    df["RR"] = nom / denom

    df["RR_fiss_prod"] = (2 / df["fiss_yield"]) * df["RR"]
    print("Reaction rates counted successfully.")
    df = df.append(lines_df)

    df = df.append(df_high)
    df = df.sort_values(by=["Energy", "Channel", "Ig [%]"],
                        ascending=[True, True, False])
    return df
Example #4
0
    def clean(self, value):
        """ Convert attribute value into the appropriate type

        Args:
            value (:obj:`object`): value of attribute to clean

        Returns:
            :obj:`tuple` of :obj:`str`, :obj:`core.InvalidAttribute` or :obj:`None`:
                tuple of cleaned value and cleaning error
        """
        error = None
        if isinstance(value, uncertainties.core.Variable):
            pass
        elif value is None or value == '':
            value = self.get_default_cleaned_value()
        elif isinstance(value, str):
            try:
                value = uncertainties.ufloat_fromstr(value)
            except ValueError:
                error = core.InvalidAttribute(
                    self, ['Invalid uncertain float {}'.format(value)])
        else:
            error = core.InvalidAttribute(
                self, ['Invalid uncertain float {}'.format(value)])
        return (value, error)
Example #5
0
    def FitPosAssign(self, args):
        """
        Assign a nominal value for the positon of peaks

        Peaks are specified by their id and the peak number within the fit.
        Syntax: id.number
        If no number is given, the first peak in the fit is used.
        """
        if self.spectra.activeID is None:
            hdtv.ui.warning("No active spectrum, no action taken.")
            return False
        spec = self.spectra.GetActiveObject()
        if len(args.args) % 2 != 0:
            raise hdtv.cmdline.HDTVCommandError(
                "Number of arguments must be even")
        else:
            for i in range(0, len(args.args), 2):
                en = ufloat_fromstr(args.args[i + 1])
                try:
                    ids = hdtv.util.ID.ParseIds(args.args[i],
                                                spec,
                                                only_existent=False)
                    pid = ids[0].minor
                    if pid is None:
                        pid = 0
                    fid = ids[0]
                    fid.minor = None
                    spec.dict[fid].peaks[pid].extras["pos_lit"] = en
                except ValueError:
                    continue
                except (KeyError, IndexError):
                    hdtv.ui.warning("no peak with id %s" % args.args[i])
Example #6
0
def importMatrix(file):
    num_cols = 2
    converters = dict.fromkeys(
        range(num_cols),
        lambda col_bytes: u.ufloat_fromstr(col_bytes.decode("latin1")))
    arr = np.loadtxt(file, converters=converters, dtype=object)
    return arr.reshape((64, 64, 2))
Example #7
0
    def FitPosMap(self, args):
        """
        Read a list of energies from file and map to the fitted peaks.

        The spectrum must be roughly calibrated for this to work.
        """
        f = hdtv.util.TxtFile(args.filename)
        f.read()
        energies = list()
        for line in f.lines:
            energies.append(ufloat_fromstr(line.split(",")[0]))
        if self.spectra.activeID is None:
            hdtv.ui.warning("No active spectrum, no action taken.")
            return False
        if len(energies) == 0:
            hdtv.ui.warning("No energies found in file {}.".format(
                args.filename))
            return False
        spec = self.spectra.GetActiveObject()
        count = 0
        for fit in spec.dict.values():
            for peak in fit.peaks:
                if args.overwrite:
                    peak.extras.pop("pos_lit", None)
                # pick best match within a certain tolerance (if it exists)
                tol = args.tolerance
                enlit = [
                    e for e in energies if abs(peak.pos_cal.std_score(e)) < tol
                ]
                if len(enlit) > 0:
                    peak.extras["pos_lit"] = min(
                        enlit, key=lambda e: abs(peak.pos_cal.std_score(e)))
                    count += 1
        # give a feetback to the user
        hdtv.ui.msg("Mapped %s energies to peaks" % count)
Example #8
0
    def _draw_plot_data(self, ax: Axes, **kwargs):
        """
        Hook into the BasePlot plot processing to enable this type to draw to the plot Axes
        """
        delta_ts = np.append(np.arange(0.1, 2.0, 0.1),
                             np.arange(2.0, self.max_delta_t, 0.5))

        # Could be fit set and/or lightcurve data
        for data_set in [kwargs["fit_sets"], kwargs["lightcurves"]]:

            # we are interested in the B and V band fits data.  May be more than one of each.
            if data_set is not None and len(data_set):
                b_sets = ColorMagnitudePlot._values_with_key_ends_with(
                    data_set, "B-band")
                v_sets = ColorMagnitudePlot._values_with_key_ends_with(
                    data_set, "V-band")

                for b_set, v_set in zip(b_sets, v_sets):
                    e_b_v = ufloat_fromstr(
                        b_set.metadata.get_or_default("E(B-V)", None))
                    mu = ufloat_fromstr(
                        b_set.metadata.get_or_default("mu", None))
                    marker = b_set.metadata.get_or_default("marker", "D")

                    if isinstance(b_set, FitSet):
                        dt, b_v_int, b_v_int_err, abs_mag, abs_mag_err = \
                            self.__class__._calculate_color_magnitudes_from_fit_sets(b_set, v_set, delta_ts,
                                                                                     e_b_v, mu)
                    else:
                        dt, b_v_int, b_v_int_err, abs_mag, abs_mag_err = \
                            self.__class__._calculate_color_magnitudes_from_lightcurves(b_set, v_set, delta_ts,
                                                                                        e_b_v, mu)

                    label = b_set.metadata.get_or_default(
                        "label",
                        f"E(B-V)={e_b_v.nominal_value:.2f}\n$\\mu$={mu.nominal_value:.2f}"
                    )
                    self._draw_color_magnitude_plot(ax,
                                                    dt,
                                                    b_v_int,
                                                    b_v_int_err,
                                                    abs_mag,
                                                    abs_mag_err,
                                                    label=label,
                                                    marker=marker)

        return
Example #9
0
def get_val(dictionary: dict, key: str, default_value=None):
    if key in dictionary.keys():
        try:
            return ufloat_fromstr(dictionary[key])
        except (ValueError, AttributeError) as e:
            return dictionary[key]
    else:
        return default_value
Example #10
0
    def test_data(self):
        """
        Do we have the correct weight, abundance, and half-life for select nuclides?
        """
        nuclides = [ (1,1), (19, 49), (63, 148), (96, 240) ]
        weights  = [ unc.ufloat_fromstr("1.00782503207(10)"),
                     unc.ufloat_fromstr("48.967450(80)"),
                     unc.ufloat_fromstr("147.918086(11)"),
                     unc.ufloat_fromstr("240.0555295(25)"), ]
        abundances  = [ unc.ufloat_fromstr("0.999885(70)"), 0., 0., 0. ]
        half_lifes = [ np.inf, 1.26E+00, 4.71E+06, 2.33E+06]
        stable = [True, False, False, False]

        for i in range(len(nuclides)):
            d = nuclide_data.nuc(*nuclides[i])

            assert self.ufloat_equiv(d['weight'], weights[i])
            assert self.ufloat_equiv(d['abundance'], abundances[i])
            assert d['half-life'] == half_lifes[i]
            assert d['stable'] == stable[i]
Example #11
0
def test_data():
    """
    Do we have the correct weight, abundance, and half-life for select nuclides?
    """
    nuclides = [ (1,1), (19, 49), (63, 148), (96, 240) ]
    weights  = [ unc.ufloat_fromstr("1.00782503207(10)"),
                 unc.ufloat_fromstr("48.967450(80)"),
                 unc.ufloat_fromstr("147.918086(11)"),
                 unc.ufloat_fromstr("240.0555295(25)"), ]
    abundances  = [ unc.ufloat_fromstr("0.999885(70)"), 0., 0., 0. ]
    half_lifes = [ 0., 1.26E+00, 4.71E+06, 2.33E+06]
    stable = [True, False, False, False]

    for i in range(len(nuclides)):
        d = nuclide_data.nuc(*nuclides[i])

        assert ufloat_equiv(d['weight'], weights[i])
        assert ufloat_equiv(d['abundance'], abundances[i])
        assert d['half-life'] == half_lifes[i]
        assert d['stable'] == stable[i]
Example #12
0
def is_bayes_factor_good(kwargs):
    try:
        result_full = BackgroundResults(kwargs, runID="Oscillation")
        result_noise = BackgroundResults(kwargs, runID="Noise")
    except:
        return True

    _, factor = bayes_factor(
        result_full.evidence._evidence["Skillings log with Error"],
        result_noise.evidence._evidence["Skillings log with Error"])

    return ufloat_fromstr(factor) > np.log10(5)
Example #13
0
File: common.py Project: op3/hdtv
    def __init__(self, csvfile=os.path.join(hdtv.datadir, "nuclides.dat")):

        self._storage = dict()
        try:
            try:
                datfile = open(csvfile, "r", encoding="utf-8")
            except TypeError:
                datfile = open(csvfile, "rb")
            reader = csv.reader(datfile)
            next(reader)  # Skip header

            for line in reader:
                Z = int(line[0].strip())
                element = Elements(Z)
                A = int(line[1].strip())
                if line[2].strip():
                    abd = ufloat_fromstr(line[2].strip()) / 100.0
                else:
                    abd = None
                if line[3].strip():
                    M = ufloat_fromstr(line[3].strip())
                else:
                    M = None
                if line[4].strip():
                    sigma = ufloat_fromstr(line[4].strip())
                else:
                    sigma = None

                if Z not in self._storage:
                    self._storage[Z] = dict()
                self._storage[Z][A] = _Nuclide(element,
                                               A,
                                               abundance=abd,
                                               sigma=sigma,
                                               M=M)
        except csv.Error as e:
            hdtv.ui.error("file %s, line %d: %s" %
                          (csvfile, reader.line_num, e))
        finally:
            datfile.close()
Example #14
0
def get_quantity(s):
    # 5, 5 eV, 5+/-1 eV, 5(1) eV
    # set uncertainty to nan if not provided
    parts = s.split()
    parts += [None] * (2 - len(parts))
    if isfloat(parts[0]):
        parts[0] += "+/-nan"

    try:
        parts[0] = ufloat_fromstr(parts[0])
        return ureg.Measurement(*parts)
    except ValueError:
        return None
Example #15
0
def load_parameter_text_file(pathToFile):
    """
    Returns a dictionary of float and/or ufloat parameters from a parameter file.

    Parameters
    ----------
    pathToFile : string
        The path to the text file with the parameters listed in the specified
        format.

    Returns
    -------
    parameters : dictionary
        A dictionary of the values stored in the text files.

    For example::

        c = 0.08 +/- 0.01
        d=0.314+/-0.002
        t = 0.1+/-0.01, 0.12+/-0.02
        whb = 0.5

    The first item on the line must be the variable name and the second is an
    equals sign. The values to the right of the equal sign much may or may not
    contain an uncertainty designated by `+/-`. Multiple comma seperated values
    will be averaged.

    """

    parameters = {}
    # parse the text file
    with open(pathToFile, 'r') as f:
        for line in f:
            # ignore lines that start with a hash
            if line[0] != '#':
                # remove any whitespace characters and comments at the end of
                # the line, then split the right and left side of the equality
                equality = line.strip().split('#')[0].split('=')
                # ['a ', ' 0.1 +/- 0.05 , 0.09 +/- 0.05']
                valList = equality[1].strip().split(',')
                # ['0.1 +/- 0.05 ', ' 0.09 +/- 0.05']
                if '+/-' in equality[1]:
                    values = [ufloat_fromstr(x) for x in valList]
                else:
                    values = [float(x) for x in valList]
                # store in dictionary
                parameters[equality[0].strip()] = np.mean(values)

    return parameters
Example #16
0
def load_parameter_text_file(pathToFile):
    """
    Returns a dictionary of float and/or ufloat parameters from a parameter file.

    Parameters
    ----------
    pathToFile : string
        The path to the text file with the parameters listed in the specified
        format.

    Returns
    -------
    parameters : dictionary
        A dictionary of the values stored in the text files.

    For example::

        c = 0.08 +/- 0.01
        d=0.314+/-0.002
        t = 0.1+/-0.01, 0.12+/-0.02
        whb = 0.5

    The first item on the line must be the variable name and the second is an
    equals sign. The values to the right of the equal sign much may or may not
    contain an uncertainty designated by `+/-`. Multiple comma seperated values
    will be averaged.

    """

    parameters = {}
    # parse the text file
    with open(pathToFile, 'r') as f:
        for line in f:
            # ignore lines that start with a hash
            if line[0] != '#':
                # remove any whitespace characters and comments at the end of
                # the line, then split the right and left side of the equality
                equality = line.strip().split('#')[0].split('=')
                # ['a ', ' 0.1 +/- 0.05 , 0.09 +/- 0.05']
                valList = equality[1].strip().split(',')
                # ['0.1 +/- 0.05 ', ' 0.09 +/- 0.05']
                if '+/-' in equality[1]:
                    values = [ufloat_fromstr(x) for x in valList]
                else:
                    values = [float(x) for x in valList]
                # store in dictionary
                parameters[equality[0].strip()] = np.mean(values)

    return parameters
def convert_alps_dataset_unc(dset):
    """ Converts an ALPS dataset to a numpy array for X, and an uncertainties array for Y +/- Yerr 

    Parameters
    ----------
    dset       : ALPS dataset

    Returns
    ---------
    X       : numpy array
    Y, Yerr : uncertainties array
    """
    X=dset.x
    Y = map(lambda x: unc.ufloat_fromstr(str(x)), dset.y)
    return X,Y
Example #18
0
def parse_one_chunk(chunk):
    d = {}
    for line in chunk:
        k,v = split_line(line)
        if v.find('.') >= 0:
            if v.endswith('#'):
                v = v[:-1]
            d[k] = unc.ufloat_fromstr(v)
        else:
            try:
                d[k] = int(v)
            except ValueError:
                d[k] = v

    return d
Example #19
0
def parse_one_chunk(chunk):
    d = {}
    for line in chunk:
        k,v = split_line(line)
        if v.find('.') >= 0:
            if v.endswith('#'):
                v = v[:-1]
            d[k] = unc.ufloat_fromstr(v)
        else:
            try:
                d[k] = int(v)
            except ValueError:
                d[k] = v

    return d
Example #20
0
def mixedfromstr(string):
    try:
        return nb.Mixed(int(string))
    except:
        try:
            return nb.Mixed(float(string))
        except:
            try:
                return nb.Mixed(fr.Fraction(string))
            except ValueError:
                try:
                    return nb.Mixed(uc.ufloat_fromstr(string))
                except ValueError:
                    raise(Exception("The following string looks like a number, "
                                    "but I can't convert it: %s" % (string)))
Example #21
0
def conv_ufloat(matrix,  coeficients, return_matrix = False):
    if not len(matrix[0]) == len(coeficients):
        raise RuntimeError(str("False length of coef. : " + str(len(matrix[0])) + " vs. " + str(len(coeficients))))
    matrix_res = np.array([np.array([ufloat_fromstr("-1(0)") for j in range(len(coeficients)/2)]) for i in matrix])
    for i in range(0,  len(coeficients),  2):
        for j,  line in enumerate(matrix):
            x= line[i]*coeficients[i]
            error = line[i+1]*coeficients[i+1]
            #print matrix_res
            #print x,  error,  j,  i
            matrix_res[j][i/2] = ufloat(x,  error)
    if return_matrix:
        return matrix_res
    else:
        return np.transpose(matrix_res) #1: ufloat, $2 ufloat,..
Example #22
0
def mixedfromstr(string):
    try:
        return nb.Mixed(int(string))
    except:
        try:
            return nb.Mixed(float(string))
        except:
            try:
                return nb.Mixed(fr.Fraction(string))
            except ValueError:
                try:
                    return nb.Mixed(uc.ufloat_fromstr(string))
                except ValueError:
                    raise (Exception(
                        "The following string looks like a number, "
                        "but I can't convert it: %s" % (string)))
Example #23
0
 def parse_ioniz_energy_str(row):
     ioniz_energy_str = row['ionization_energy_str']
     if ioniz_energy_str == '':
         return None
     if ioniz_energy_str.startswith('('):
         method = 'theor' # theoretical
         ioniz_energy_str = ioniz_energy_str.strip('()')
         #.replace('))', ')') - not clear why that exists
     elif ioniz_energy_str.startswith('['):
         method = 'intrpl' # interpolated
         ioniz_energy_str = ioniz_energy_str.strip('[]')
     else:
         method = 'meas'  # measured
     # ToDo: Some value are given without uncertainty. How to be with them?
     ioniz_energy = ufloat_fromstr(ioniz_energy_str)
     return pd.Series([ioniz_energy.nominal_value, ioniz_energy.std_dev, method])
Example #24
0
 def parse_ioniz_energy_str(row):
     ioniz_energy_str = row['ionization_energy_str']
     if ioniz_energy_str == '':
         return None
     if ioniz_energy_str.startswith('('):
         method = 'theor' # theoretical
         ioniz_energy_str = ioniz_energy_str[1:-1]  # .strip('()') wasn't working for '(217.7185766(10))'
         #.replace('))', ')') - not clear why that exists
     elif ioniz_energy_str.startswith('['):
         method = 'intrpl' # interpolated
         ioniz_energy_str = ioniz_energy_str.strip('[]')
     else:
         method = 'meas'  # measured
     # ToDo: Some value are given without uncertainty. How to be with them?
     ioniz_energy = ufloat_fromstr(ioniz_energy_str)
     return pd.Series([ioniz_energy.nominal_value, ioniz_energy.std_dev, method])
Example #25
0
def get_input(num):
    """ Asks user for value and uncertainty
    Input = # of values to collect
    Output = Array of values formatted for uncertainty library
    """

    input_value = []
    for i in range(1, num + 1):
        print('')
        user_input_value = input('Input value ' + str(i) +
                                 '                 >>> ')
        user_input_uncertainty = input('Input uncertainty value ' + str(i) +
                                       '     >>> +/-  ')
        print('')
        input_value.append(
            ufloat_fromstr(user_input_value + '+/-' + user_input_uncertainty))
    return input_value
Example #26
0
def parse_quantity(string):
    """Parse a string into a pint/uncertainty quantity.

    Parameters
    ----------
    string : string

    Returns
    -------
    value : pint.quantity of uncertainties.core.AffineScalarFunc

    Examples
    --------
    >>> quant = parse_quantity('1.2 +/- 0.7 * units.meter')
    >>> print str(quant)
    1.2+/-0.7 meter
    >>> print '{:~}'.format(quant)
    1.2+/-0.7 m
    >>> print quant.magnitude
    1.2+/-0.7
    >>> print quant.units
    meter
    >>> print quant.nominal_value
    1.2
    >>> print quant.std_dev
    0.7

    Also note that spaces and the "*" are optional:

    >>> print parse_quantity('1+/-1units.GeV')
    1.0+/-1.0 gigaelectron_volt

    """
    value = string.replace(' ', '')
    if 'units.' in value:
        value, unit = value.split('units.')
    else:
        unit = None
    value = value.rstrip('*')
    if '+/-' in value:
        value = ufloat_fromstr(value)
    else:
        value = ufloat(float(value), 0)
    value *= ureg(unit)
    return value
Example #27
0
def uncertainty_parser(unc_raw_str, split_unc_symbol='%'):
    unc_raw_str = unc_raw_str.lower()

    value_unc_pair = [
        item.strip() for item in unc_raw_str.split(split_unc_symbol)
    ]

    if len(value_unc_pair) == 1:  # if no uncertainty given
        return float(value_unc_pair[0]), np.nan
    else:
        value, unc = value_unc_pair[:2]  # limit to two
    if unc == "" or unc == "?":  # if uncertainty_str is empty or unknown
        unc = np.nan
    if "e" in value:
        exp_pos = value.find("e")
        unc_str = value[:exp_pos] + f"({unc})" + value[exp_pos:]
    else:
        unc_str = value + f"({unc})"
    parsed_uncertainty = ufloat_fromstr(unc_str)
    return parsed_uncertainty.nominal_value, parsed_uncertainty.std_dev
Example #28
0
    def __init__(self, n, d={0: 0}, name='g', analytic=None):
        """
        Example:
        `z2 = Series(3, {0: ufloat(-1, 0.4), 1: ufloat(-2, .004), 2: ufloat(999, .1)})`
        will give:
        Z₂(g) = -1.0(4) - 2.000(4) g + 999.00(10) g²

        :param n: number of the "known" orders, `int`
        :param d: dictionary with k=powers, v=`ufloat`s
        :param name: name of the series variable, arbitrary character, default is `'g'`
        :param analytic: boolean
        """
        self.n = n
        self.gSeries = d
        self.name = name
        for k, v in d.items():
            if isinstance(v, AffineScalarFunc):
                self.gSeries[k] = v
            elif isinstance(v, (list, tuple)):
                self.gSeries[k] = ufloat(v[0], v[1])
            elif isinstance(v, str):
                self.gSeries[k] = ufloat_fromstr(v)
            elif isinstance(v, int):
                self.gSeries[k] = v
                self.analytic = True
            else:
                raise TypeError(
                    "Series constructor warning: Type(v)={}".format(type(v)))
        if analytic is not None:
            # XXX: if defined explicitly:
            self.analytic = bool(analytic)
        else:
            # XXX: if all values are ints assume analytic
            self.analytic = all(map(lambda x: type(x) == int, d.values()))
        for i in range(0, n):
            if i not in d.keys():
                if self.analytic:
                    self.gSeries[i] = 0
                else:
                    self.gSeries[i] = ufloat(0, 0)
Example #29
0
File: common.py Project: op3/hdtv
    def __init__(self, csvfile=os.path.join(hdtv.datadir, "elements.dat")):

        super(_Elements, self).__init__()

        tmp = list()

        try:
            try:
                datfile = open(csvfile, "r", encoding="utf-8")
            except TypeError:
                datfile = open(csvfile, "rb")
            reader = csv.reader(datfile)
            next(reader)  # Skip header

            for line in reader:
                Z = int(line[0])
                Symbol = line[1].strip()
                Name = line[2].strip()
                try:
                    Mass = ufloat_fromstr(line[3].strip())
                except ValueError:
                    Mass = None
                element = _Element(Z, Symbol, Name, Mass)
                tmp.append(element)
        except csv.Error as err:
            hdtv.ui.error("file %s, line %d: %s" %
                          (csvfile, reader.line_num, err))
        finally:
            datfile.close()

        # Now store elements finally
        maxZ = max(tmp, key=lambda x: x.z)  # Get highest Z
        for i in range(maxZ.z):
            self.append(None)

        for e in tmp:
            self[e.z] = e
Example #30
0
    def CalPosAssign(self, args):
        """
        Calibrate the active spectrum by assigning energies to fitted peaks

        Peaks are specified by their id and the peak number within the fit.
        Syntax: id.number
        If no number is given, the first peak in the fit is used.
        """
        if self.spectra.activeID is None:
            hdtv.ui.warning("No active spectrum, no action taken.")
            return False
        spec = self.spectra.GetActiveObject()
        # parsing of command
        if len(args.args) % 2 != 0:
            raise hdtv.cmdline.HDTVCommandError("Number of arguments must be even")
        else:
            pairs = hdtv.util.Pairs()
            for peak_id, energy in zip(*[iter(args.args)]*2):
                ID = hdtv.util.ID.ParseIds(
                    peak_id, spec, only_existent=False)[0]
                value = ufloat_fromstr(energy)
                pairs.add(ID, value)
        sids = hdtv.util.ID.ParseIds(args.spectrum, self.spectra)
        if not sids:
            sids = [self.spectra.activeID]
        degree = int(args.degree)
        # do the work
        cal = self.EnergyCalIf.CalFromFits(
            spec.dict,
            pairs,
            degree,
            table=args.show_table,
            fit=args.show_fit,
            residual=args.show_residual,
            ignore_errors=args.ignore_errors)
        self.spectra.ApplyCalibration(sids, cal)
        return True
def to_nom_value_and_std_dev(tokens):
    u = ufloat_fromstr("".join(tokens))
    tokens['nominal_value'] = u.nominal_value
    tokens['std_dev'] = u.std_dev
    return tokens
Example #32
0
def nndc_abun(string, delimiter):
    a, b = string.split(delimiter)
    unc_string = "{0}({1})".format(float(a), int(b))
    return unc.ufloat_fromstr(unc_string)
Example #33
0
mpl.rcParams['text.usetex']=True
mpl.rcParams['text.latex.unicode']=True
mpl.rcParams["ps.usedistiller"]="xpdf"
mpl.rcParams["axes.labelsize"]=12
mpl.rcParams["font.size"]=12
mpl.rcParams["legend.fontsize"]=10
mpl.rcParams["xtick.labelsize"]=10
mpl.rcParams["ytick.labelsize"]=10
mpl.rcParams["text.usetex"]=True
mpl.rcParams["figure.figsize"]=fig_size
mpl.rc('font',**
       {'family':'serif','serif':['Computer Modern Roman']})


g = ufloat_fromstr("9.81")


def fitfunc(x,  a,  b):
    return x*b + a

def fitfunc2(x,  a,  b):
    return np.sqrt(b*x + a)

def fitfunc3(x,  a, c):

    return a*np.sqrt(x)+c
def fitfunc4(x, D, h):
    print D
    return 0.5*(1-special.erf((x[1]+h)/(np.sqrt(4*np.abs(D)*(x[0])))))
Example #34
0
cl = {}

# Exact definitions

c_light = uncertainties.ufloat(299792458,0)
cl['c_light'] = [c_light,'m s^{-1}','Speed of light in vacuum','Definition']

au = uncertainties.ufloat(149597870700,0)
cl['au'] = [au,'m','Astronomical unit','Definition']

yr = uncertainties.ufloat(31557600,0)
cl['yr'] = [yr,'s','Julian year','Definition']

# Fundamental measured constants

G_Newton = uncertainties.ufloat_fromstr('6.67384(80)e-11')
cl['G_Newton'] = [G_Newton,'m^{3} s^{-2} kg^{-1}','Newton gravitational constant','NIST']

k_Boltzmann = uncertainties.ufloat_fromstr('1.3806488(13)e-23')
cl['k_Boltzmann'] = [k_Boltzmann,'J K^{-1}','Boltzmann constant','NIST']

uamu =  uncertainties.ufloat_fromstr('1.660538921(73)e-27')
cl['uamu'] = [uamu,'kg','Unified atomic mass unit','NIST']

m_proton = uncertainties.ufloat_fromstr('1.672621777(74)e-27')
cl['m_proton'] = [m_proton,'kg','Proton mass','NIST']

m_neutron = uncertainties.ufloat_fromstr('1.674927351(74)e-27')
cl['m_neutron'] = [m_neutron,'kg','Neutron mass','NIST']

m_electron = uncertainties.ufloat_fromstr('9.10938291(40)e-31')
Example #35
0
 def parse_ionization_string(ionization_string):
     if ionization_string == '':
         return None
     return ufloat_fromstr(ionization_string.strip('(').replace('))', ')')
                           .strip('[]'))
Example #36
0
def compose_results(priors: List[List[float]], nu_max: float, params: Dict,
                    data: np.ndarray,
                    kwargs: Dict) -> Tuple[od, np.ndarray, List[str], str]:
    result_full = BackgroundResults(kwargs, runID="Oscillation")
    result_noise = BackgroundResults(kwargs, runID="Noise")

    create_parameter_trend_plot(result_full, kwargs)
    create_parameter_trend_plot(result_noise, kwargs)

    create_marginal_distributions_plot(result_full, kwargs)
    create_marginal_distributions_plot(result_noise, kwargs)

    err = []
    exception_text = None

    if result_full._summary is None:
        err.append("Cannot find summary file for oscillation model")
        exception_text = "Cannot find summary file for standard run"

    if result_noise._summary is None:
        err.append("Cannot find summary file for noise model")
        exception_text = "Cannot find summary file for noise run"

    full_res_set = od()

    full_res_set["Priors Oscillation model"] = get_priors(priors, result_full)
    full_res_set["Priors Noise only"] = get_priors(priors, result_noise)

    full_res_set["Prior centroid values"] = params

    try:
        full_res_set["Oscillation model result"] = get_resulting_values(
            result_full)
        full_res_set["Noise model result"] = get_resulting_values(result_noise)

        full_res_set[
            "Evidence Oscillation model"] = f"{result_full.evidence._evidence['Skillings log with Error']}"
        full_res_set[
            "Evidence Noise model"] = f"{result_noise.evidence._evidence['Skillings log with Error']}"

        conc, factor = bayes_factor(
            result_full.evidence._evidence["Skillings log with Error"],
            result_noise.evidence._evidence["Skillings log with Error"])
        full_res_set["Bayes factor"] = factor
        full_res_set["Conclusion"] = conc
    except:
        err.append("Cannot find read evidence file")
        if exception_text is None:
            exception_text = "Failed to read evidence values"

    full_res_set["Nu max guess"] = nu_max

    if internal_literature_value in kwargs.keys():
        full_res_set[
            internal_literature_value] = f"{kwargs[internal_literature_value]}"

    if internal_delta_nu in kwargs.keys():
        full_res_set[internal_delta_nu] = f"{kwargs[internal_delta_nu]}"

    psd = result_full.powerSpectralDensity

    try:
        plot_f_space(psd.T,
                     kwargs,
                     bg_model=result_full.createBackgroundModel(),
                     add_smoothing=True)
        plot_f_space(psd.T,
                     kwargs,
                     bg_model=result_noise.createBackgroundModel(),
                     add_smoothing=True)
    except:
        err.append("Failed to plot model")
        if exception_text is None:
            exception_text = "Failed to plot model"

    try:
        delta_nu = get_delta_nu(data, result_full, kwargs)
    except:
        delta_nu = None
    full_res_set["Delta nu"] = f"{delta_nu}"

    scaling = ScalingRelations(
        ufloat_fromstr(full_res_set["Oscillation model result"]['nu_max']),
        delta_nu, kwargs[internal_teff])
    full_res_set["log(g)"] = f'{scaling.log_g()}'
    full_res_set["Radius"] = f'{scaling.radius()}'
    full_res_set["Mass"] = f'{scaling.mass()}'

    if err == [] and exception_text is None:
        full_res_set[internal_flag_worked] = True
    else:
        full_res_set[internal_flag_worked] = False

    return full_res_set, psd, err, exception_text
Example #37
0
def nndc_abun(string, delimiter):
    a, b = string.split(delimiter)
    unc_string = "{0}({1})".format(float(a), int(b))
    return unc.ufloat_fromstr(unc_string)
Example #38
0
def get_nom(dG):
    dG_m = np.array([uc.ufloat_fromstr(s) for s in dG])
    dG_m = unp.nominal_values(dG_m)
    dG_m = invsec_to_nat * dG_m

    return dG_m
Example #39
0
def to_nom_value_and_std_dev(tokens):
    u = ufloat_fromstr("".join(tokens))
    tokens['nominal_value'] = u.nominal_value
    tokens['std_dev'] = u.std_dev
    return tokens
Example #40
0
mpl.rcParams['text.usetex']=True
mpl.rcParams['text.latex.unicode']=True
mpl.rcParams["ps.usedistiller"]="xpdf"
mpl.rcParams["axes.labelsize"]=12
mpl.rcParams["font.size"]=12
mpl.rcParams["legend.fontsize"]=10
mpl.rcParams["xtick.labelsize"]=10
mpl.rcParams["ytick.labelsize"]=10
mpl.rcParams["text.usetex"]=True
mpl.rcParams["figure.figsize"]=fig_size
mpl.rc('font',**
       {'family':'serif','serif':['Computer Modern Roman']})


g = ufloat_fromstr("9.81")
A = ufloat_fromstr("3.9083(0)e-3")
B = ufloat_fromstr("-5.775(0)e-7")
R_0 = ufloat_fromstr("1000.0(0)")
R = ufloat_fromstr("8.314462(0)")
A = 3.9083e-3
B = -5.775e-7
R_0 = 1000.0

def fitfunc(x,  a,  b):
    return x*b + a
    
def fitfunc2(x,  a,  b):
    return np.sqrt(b*x + a)

def fitfunc3(x,  a, c):
Example #41
0
def unorm(x):
    # for counting experiments: define ufloat with poisson uncertainty
    return unc.ufloat(x, np.sqrt(abs(x)))

# data['zDelBB'] = data['zDelBB'].apply(lambda x: unc.ufloat_fromstr(x))
# data['zDelBE'] = data['zDelBE'].apply(lambda x: unc.ufloat_fromstr(x))
# data['zDelEE'] = data['zDelEE'].apply(lambda x: unc.ufloat_fromstr(x))
# data['zDelBB_mc'] = data['zDelBB_mc'].apply(lambda x: unc.ufloat_fromstr(x))
# data['zDelBE_mc'] = data['zDelBE_mc'].apply(lambda x: unc.ufloat_fromstr(x))
# data['zDelEE_mc'] = data['zDelEE_mc'].apply(lambda x: unc.ufloat_fromstr(x))

data['yieldBB'] = data['yieldBB'].apply(lambda x: unorm(x))
data['yieldBE'] = data['yieldBE'].apply(lambda x: unorm(x))
data['yieldEE'] = data['yieldEE'].apply(lambda x: unorm(x))

data['ZBBeff_mc'] = data['ZBBeff_mc'].apply(lambda x: unc.ufloat_fromstr(x))
data['ZBEeff_mc'] = data['ZBEeff_mc'].apply(lambda x: unc.ufloat_fromstr(x))
data['ZEEeff_mc'] = data['ZEEeff_mc'].apply(lambda x: unc.ufloat_fromstr(x))

data['zYieldBB_purity'] = data['zYieldBB_purity'].apply(lambda x: unc.ufloat_fromstr(x))
data['zYieldBE_purity'] = data['zYieldBE_purity'].apply(lambda x: unc.ufloat_fromstr(x))
data['zYieldEE_purity'] = data['zYieldEE_purity'].apply(lambda x: unc.ufloat_fromstr(x))

# delivered Z rate without applying purity
data['delBB_mc'] = data['yieldBB'] / data['ZBBeff_mc']
data['delBE_mc'] = data['yieldBE'] / data['ZBEeff_mc']
data['delEE_mc'] = data['yieldEE'] / data['ZEEeff_mc']

data['del_mc'] = data['delBB_mc'] + data['delBE_mc'] + data['delEE_mc']

# delivered Z rate with applying purity
##### loop over Fills and produce fill specific plots
for fill in fills:
    dFill = data.loc[data['fill'] == fill]

    subDir = outDir + "/PlotsFill_" + str(fill)
    if plotsPerFill:
        if not os.path.isdir(subDir):
            os.mkdir(subDir)

    ### Efficiency ###
    for eff, name, ymin, ymax, err in features:
        # if err not in dFill.keys():
        #     dFill[err] = np.zeros(len( dFill[eff].values))

        yyUnc = dFill[eff].apply(lambda x: unc.ufloat_fromstr(x))

        yy = dFill[eff].apply(
            lambda x: unc.ufloat_fromstr(x).nominal_value).values
        yyErr = dFill[eff].apply(
            lambda x: unc.ufloat_fromstr(x).std_dev).values

        if plotsPerFill:
            graph_Zeff = ROOT.TGraphErrors(len(dFill), dFill['tdate'].values,
                                           yy, np.zeros(len(dFill['tdate'])),
                                           yyErr)
            graph_Zeff.SetName("graph_Zeff")
            graph_Zeff.SetMarkerStyle(26)
            graph_Zeff.SetMarkerColor(ROOT.kOrange + 8)
            graph_Zeff.SetFillStyle(0)
            graph_Zeff.SetFillColor(0)
Example #43
0
File: mod.py Project: dfb159/expKP
def smart_out(fn, x):
    '''TODO'''
    out_si(fn, x)
    '''if isinstance(x,list):
        out_si_tab(fn,x)
    elif isinstance(x,types.FunctionType):
        out(fn,inspect.getsourcelines(x)[0])
    else:
        out_si(fn,x)
    '''


# usage zB:
# pfit, perr = fit_curvefit(unv(xdata), unv(ydata), gerade, yerr = usd(ydata), p0 = [1, 0])
# fuer eine gerade mit anfangswerten m = 1, b = 0

# weitere Werte, Konstanten
# Werte von https://physics.nist.gov/cuu/Constants/index.html[0]

c = 299792458  # m/s
k_B = unc.ufloat_fromstr("1.38064852(79)e-23")  # J K-1 [0]
h = unc.ufloat_fromstr("4.135667662(25)e-15")  # eV s [0]
h_bar = h / (2 * np.pi)  # J/s
r_e = unc.ufloat_fromstr("2.8179403227(19)e-15")  # m [0]
R = unc.ufloat_fromstr("8.3144598(48)")  # J mol-1 K-1 [0]
K = 273.15  # kelvin
g = 9.81  # m/s^2
rad = 360 / 2 / np.pi
grad = 1 / rad
Example #44
0
 def _to_ufloat(cls, value):
     if value.startswith('>'):
         return ufloat(float("NaN"), 0)
     else:
         return ufloat_fromstr(value.replace("+or-", "+/-"))
Example #45
0
def get_uc_array(dG):
    dG_m = np.array([uc.ufloat_fromstr(s) for s in dG])
    dG_m = invsec_to_nat * dG_m

    return dG_m
Example #46
0
# pdb.set_trace()

########## Data Acquisition ##########

# --- z luminosity
data = pd.read_csv(str(args.rates), sep=',',low_memory=False) #, skiprows=[1,2,3,4,5])
if args.fill != 0:
    data = data.loc[data['fill'] == args.fill]

data = data.sort_values(['fill','tdate_begin','tdate_end'])

data['time'] = data['tdate_begin'] + (data['tdate_end'] - data['tdate_begin'])/2
data['timeE'] = (data['tdate_end'] - data['tdate_begin'])/2

data['ZBBeff'] = data['ZBBeff'].apply(lambda x: unc.ufloat_fromstr(x))
data['ZBEeff'] = data['ZBEeff'].apply(lambda x: unc.ufloat_fromstr(x))
data['ZEEeff'] = data['ZEEeff'].apply(lambda x: unc.ufloat_fromstr(x))

if args.mcCorrections:
    print("Get MC corrections from file: "+args.mcCorrections)
    corr = getMCCorrection(args.mcCorrections)
    data['ZBBeff_mc'] = 1. / corr['effBB'](data['pileUp']) * data['ZBBeff']
    data['ZBEeff_mc'] = 1. / corr['effBE'](data['pileUp']) * data['ZBEeff']
    data['ZEEeff_mc'] = 1. / corr['effEE'](data['pileUp']) * data['ZEEeff']
else:
    data['ZBBeff_mc'] = data['ZBBeff_mc'].apply(lambda x: unc.ufloat_fromstr(x))
    data['ZBEeff_mc'] = data['ZBEeff_mc'].apply(lambda x: unc.ufloat_fromstr(x))
    data['ZEEeff_mc'] = data['ZEEeff_mc'].apply(lambda x: unc.ufloat_fromstr(x))

# seconds to hours