Python scipy.constants.g() Examples

The following are 19 code examples of scipy.constants.g(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module scipy.constants , or try the search function .
Example #1
Source File: met_data_processing.py    From OpenOA with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def pressure_vertical_extrapolation(p0, temp_avg, z0, z1):
    """
    Extrapolate pressure from height z0 to height z1 given the average temperature in the layer.
    The hydostatic equation is used to peform the extrapolation.

    Args:
        p0(:obj:`pandas.Series`): pressure at height z0; units of Pascals
        temp_avg(:obj:`pandas.Series`): mean temperature between z0 and z1; units of Kelvin
        z0(:obj:`pandas.Series`): height above surface; units of meters
        z1(:obj:`pandas.Series`): extrapolation height; units of meters

    Returns:
        :obj:`pandas.Series`: p1, extrapolated pressure at z1; units of Pascals
    """
    # Send exception if any negative data found
    if (p0[p0 < 0].size > 0) | (temp_avg[temp_avg < 0].size > 0):
        raise Exception('Some of your temperature of pressure data is negative. Check your data')

    R_const = 287.058  # Gas constant for dry air, units of J/kg/K
    p1 = p0 * np.exp(-const.g * (z1 - z0) / R_const / temp_avg)  # Pressure at z1

    return p1 
Example #2
Source File: sm_table_parsers.py    From gmpe-smtk with GNU Affero General Public License v3.0 6 votes vote down vote up
def get_sa_columns(cls, csv_fieldnames):
        """This method is intended to be overridden by subclasses (by default
        it raises :class:`NotImplementedError`) to return a `dict` of SA
        column names (string), mapped to a numeric value representing the SA
        period. This class will then sort and save SA periods accordingly.

        You can also implement here operations which should be executed once
        at the beginning of the flatfile parsing, such as e.g.
        creating objects and storing them as class attributes later accessible
        in :method:`parse_row`

        :param csv_fieldnames: an iterable of strings representing the
            header of the persed csv file
        """
        # return just the U component. V and W will be handled in `parse_row`:
        return OrderedDict([(k, float(k[3:].replace('_', '.'))) for k in
                            ['U_T0_010', 'U_T0_025', 'U_T0_040', 'U_T0_050',
                             'U_T0_070', 'U_T0_100', 'U_T0_150', 'U_T0_200',
                             'U_T0_250', 'U_T0_300', 'U_T0_350', 'U_T0_400',
                             'U_T0_450', 'U_T0_500', 'U_T0_600', 'U_T0_700',
                             'U_T0_750', 'U_T0_800', 'U_T0_900', 'U_T1_000',
                             'U_T1_200', 'U_T1_400', 'U_T1_600', 'U_T1_800',
                             'U_T2_000', 'U_T2_500', 'U_T3_000', 'U_T3_500',
                             'U_T4_000', 'U_T4_500', 'U_T5_000', 'U_T6_000',
                             'U_T7_000', 'U_T8_000', 'U_T9_000', 'U_T10_000']]) 
Example #3
Source File: adimensional.py    From pychemqt with GNU General Public License v3.0 6 votes vote down vote up
def Bo(rhol, rhog, sigma, L):
    r"""Calculates Bond number, `Bo` also known as Eotvos number.

    .. math::
        Bo = \frac{g(\rho_l-\rho_g)L^2}{\sigma}

    Parameters
    ----------
    rhol : float
        Density of liquid, [kg/m³]
    rhog : float
        Density of gas, [kg/m³]
    sigma : float
        Surface tension, [N/m]
    L : float
        Characteristic length, [m]

    Returns
    -------
    Bo : float
        Bond number, [-]
    """
    return (g*(rhol-rhog)*L**2/sigma) 
Example #4
Source File: sm_utils_test.py    From gmpe-smtk with GNU Affero General Public License v3.0 6 votes vote down vote up
def convert_accel_units_old(acceleration, units):
    """
    Converts acceleration from different units into cm/s^2

    :param units: string in "g", "m/s/s", "m/s**2", "m/s^2",
        "cm/s/s", "cm/s**2" or "cm/s^2" (in the last three cases, this
        function simply returns `acceleration`)

    :return: acceleration converted to the given units
    """
    if units == "g":
        return (100 * g) * acceleration
    if units in ("m/s/s", "m/s**2", "m/s^2"):
        return 100. * acceleration
    if units in ("cm/s/s", "cm/s**2", "cm/s^2"):
        return acceleration

    raise ValueError("Unrecognised time history units. "
                     "Should take either ''g'', ''m/s/s'' or ''cm/s/s''") 
Example #5
Source File: gas_solid.py    From pychemqt with GNU General Public License v3.0 6 votes vote down vote up
def calcularRendimientos_parciales(self, L):
        """Calculate the efficiency of separation process for each diameter of
        solid fraction"""
        entrada = self.kwargs["entrada"]
        rhoS = entrada.solido.rho
        rhoG = entrada.Gas.rho
        muG = entrada.Gas.mu
        rendimientos = []
        for d in entrada.solido.diametros:
            Ar = d**3*rhoG*(rhoS-rhoG)*g/muG**2
            Vt = muG/d*rhoG*((14.42+1.827*Ar**0.5)**0.5-3.798)**2
            if self.kwargs["modelo"] == 0:
                r = Vt*L/self.Vgas/self.H
            else:
                r = 1-exp(-Vt*L/self.Vgas/self.H)
            if r > 1:
                rendimientos.append(1)
            else:
                rendimientos.append(r)
        return rendimientos 
Example #6
Source File: unidades.py    From pychemqt with GNU General Public License v3.0 6 votes vote down vote up
def _getBaseValue(cls, data, unit, magnitud):
        if data is None:
            data = 0
        if not magnitud:
            magnitud = cls.__name__

        if unit == "conf":
            Config = getMainWindowConfig()
            unit = cls.__units__[Config.getint('Units', magnitud)]
        elif not unit:
            unit = "Pa"

        if unit == "barg":
            data = data*k.bar+k.atm
        elif unit == "psig":
            data = data*k.psi+k.atm
        elif unit == "kgcm2g":
            data = data*k.g/k.centi**2+k.atm
        elif unit in cls.rates:
            data = data * cls.rates[unit]
        else:
            raise ValueError(
                QApplication.translate("pychemqt", "Wrong input code"))

        return data 
Example #7
Source File: adimensional.py    From pychemqt with GNU General Public License v3.0 5 votes vote down vote up
def Ga(L, rho=None, mu=None, nu=None, g=g):
    r"""Calculates Galilei number `Ga`.

    .. math::
        Ar=\frac{gL^3}{v^2}

    Inputs either of any of the following sets:

    * L and kinematic viscosity `nu`
    * L, density `rho` and dynamic viscosity `mu`

    Parameters
    ----------
    L : float
        Characteristic length [m]
    rho : float, optional
        Density of bulk phase [kg/m³]
    mu : float, optional
        Dynamic viscosity, [Pa*s]
    nu : float, optional
        Kinematic viscosity, [m^2/s]
    g : float, optional
        Acceleration due to gravity, [m/s^2]

    Returns
    -------
    Ga : float
        Galilei number, [-]

    Examples
    --------
    >>> print("%0.3f" % Ga(5e-4, nu=48.09e-6))
    0.530
    """
    if rho and mu:
        nu = mu/rho
    elif not nu:
        raise Exception("undefined")
    return Dimensionless(g*L**3/nu**2) 
Example #8
Source File: adimensional.py    From pychemqt with GNU General Public License v3.0 5 votes vote down vote up
def Fr(V, L, g=g):
    r"""Calculates Froude number `Fr` for velocity `V` and geometric length
    `L`. If desired, gravity can be specified as well. Normally the function
    returns the result of the equation below.

    .. math::
        Fr = \frac{V}{\sqrt{gL}}

    Parameters
    ----------
    V : float
        Velocity of the particle or fluid, [m/s]
    L : float
        Characteristic length, no typical definition [m]
    g : float, optional
        Acceleration due to gravity, [m/s^2]

    Returns
    -------
    Fr : float
        Froude number, [-]

    Notes
    -----
    Can be seen as a ratio of inertial force and gravity.

    .. math::
        Fr = \frac{\text{Inertial Force}}{\text{Gravity Force}}

    Appears in problems of forced motion when gravity has same influence,
    example in free liquid surfaces or multiphase flow.

    Examples
    --------
    >>> print("%0.0f" % Fr(5, L=0.025))
    102
    """
    return Dimensionless(V**2/(L*g)) 
Example #9
Source File: sm_utils.py    From gmpe-smtk with GNU Affero General Public License v3.0 5 votes vote down vote up
def convert_accel_units(acceleration, from_, to_='cm/s/s'):  # pylint: disable=too-many-return-statements
    """
    Converts acceleration from/to different units

    :param acceleration: the acceleration (numeric or numpy array)
    :param from_: unit of `acceleration`: string in "g", "m/s/s", "m/s**2",
        "m/s^2", "cm/s/s", "cm/s**2" or "cm/s^2"
    :param to_: new unit of `acceleration`: string in "g", "m/s/s", "m/s**2",
        "m/s^2", "cm/s/s", "cm/s**2" or "cm/s^2". When missing, it defaults
        to "cm/s/s"

    :return: acceleration converted to the given units (by default, 'cm/s/s')
    """
    m_sec_square = ("m/s/s", "m/s**2", "m/s^2")
    cm_sec_square = ("cm/s/s", "cm/s**2", "cm/s^2")
    acceleration = np.asarray(acceleration)
    if from_ == 'g':
        if to_ == 'g':
            return acceleration
        if to_ in m_sec_square:
            return acceleration * g
        if to_ in cm_sec_square:
            return acceleration * (100 * g)
    elif from_ in m_sec_square:
        if to_ == 'g':
            return acceleration / g
        if to_ in m_sec_square:
            return acceleration
        if to_ in cm_sec_square:
            return acceleration * 100
    elif from_ in cm_sec_square:
        if to_ == 'g':
            return acceleration / (100 * g)
        if to_ in m_sec_square:
            return acceleration / 100
        if to_ in cm_sec_square:
            return acceleration

    raise ValueError("Unrecognised time history units. "
                     "Should take either ''g'', ''m/s/s'' or ''cm/s/s''") 
Example #10
Source File: constraintanalysis.py    From ADRpy with GNU General Public License v3.0 5 votes vote down vote up
def bank2turnradius(self, bankangle_deg):
        """Calculates the turn radius in m, given the turn TAS and the bank angle"""

        bankangle_rad = math.radians(bankangle_deg)
        v_mps = co.kts2mps(self.turnspeed_ktas)

        r_m = (v_mps ** 2) / (constants.g * math.tan(bankangle_rad))

        return r_m 
Example #11
Source File: heatExchanger.py    From pychemqt with GNU General Public License v3.0 5 votes vote down vote up
def h_tubeside_laminar_condensation_Kern(self):
        return 0.815*(k**3*rho_l*(rho_l-rho_g)*g*l/(pi*mu_l*Do*(T-Tw)))**0.25 
Example #12
Source File: heatExchanger.py    From pychemqt with GNU General Public License v3.0 5 votes vote down vote up
def h_tubeside_laminar_condensation_Nusselt(self):
        return 0.72*eg**0.75*(k**3*rho_l*(rho_l-rho_g)*g*hlg/(mu_l*Do*(T-Tw)))**0.25 
Example #13
Source File: pump.py    From pychemqt with GNU General Public License v3.0 4 votes vote down vote up
def calculo(self):
        entrada = self.kwargs["entrada"]
        self.rendimientoCalculado = Dimensionless(self.kwargs["rendimiento"])

        if self.kwargs["Pout"]:
            DeltaP = Pressure(self.kwargs["Pout"]-entrada.P)
        elif self.kwargs["deltaP"]:
            DeltaP = Pressure(self.kwargs["deltaP"])
        elif self.kwargs["Carga"]:
            DeltaP = Pressure(self.kwargs["Carga"]*entrada.Liquido.rho*g)
        else:
            DeltaP = Pressure(0)

        if self.kwargs["usarCurva"]:
            b1 = self.kwargs["diametro"] != self.kwargs["curvaCaracteristica"][0]  # noqa
            b2 = self.kwargs["velocidad"] != self.kwargs["curvaCaracteristica"][1]  # noqa
            if b1 or b2:
                self.curvaActual = self.calcularCurvaActual()
            else:
                self.curvaActual = self.kwargs["curvaCaracteristica"]
            self.Ajustar_Curvas_Caracteristicas()

        if not self.kwargs["usarCurva"]:
            head = Length(DeltaP/g/entrada.Liquido.rho)
            power = Power(head*g*entrada.Liquido.rho*entrada.Q /
                          self.rendimientoCalculado)
            P_freno = Power(power*self.rendimientoCalculado)
        elif not self.kwargs["incognita"]:
            head = Length(polyval(self.CurvaHQ, entrada.Q))
            DeltaP = Pressure(head*g*entrada.Liquido.rho)
            power = Power(entrada.Q*DeltaP)
            P_freno = Power(polyval(self.CurvaPotQ, entrada.Q))
            self.rendimientoCalculado = Dimensionless(power/P_freno)
        else:
            head = Length(self.DeltaP/g/entrada.Liquido.rho)
            poli = [self.CurvaHQ[0], self.CurvaHQ[1], self.CurvaHQ[2]-head]
            Q = roots(poli)[0]
            power = Power(Q*self.DeltaP)
            entrada = entrada.clone(split=Q/entrada.Q)
            P_freno = Power(polyval(self.CurvaPotQ, Q))
            self.rendimientoCalculado = Dimensionless(power/P_freno)

        self.deltaP = DeltaP
        self.headCalculada = head
        self.power = power
        self.P_freno = P_freno
        self.salida = [entrada.clone(P=entrada.P+DeltaP)]
        self.Pin = entrada.P
        self.PoutCalculada = self.salida[0].P
        self.volflow = entrada.Q
        self.cp_cv = entrada.Liquido.cp_cv 
Example #14
Source File: adimensional.py    From pychemqt with GNU General Public License v3.0 4 votes vote down vote up
def Ar(L, rho_p, rho, mu=None, nu=None, g=g):
    r"""Calculates Archimedes number `Ar` for two phases densities, a
    geometric length `L` or any viscosity definition.

    .. math::
        Ar=\frac{gL^3\delta\rho}{\rho v^2}

    Inputs either of any of the following sets:

    * L, density of both phases (rho_p, rho) and kinematic viscosity `nu`
    * L, density of both phases (rho_p, rho) and dynamic viscosity `mu`

    Parameters
    ------------
    L : float
        Characteristic length [m]
    rho_p : float
        Density of particle phase [kg/m³]
    rho : float
        Density of bulk phase [kg/m³]
    mu : float, optional
        Dynamic viscosity, [Pa*s]
    nu : float, optional
        Kinematic viscosity, [m²/s]
    g : float, optional
        Acceleration due to gravity, [m/s²]

    Returns
    -------
    Ar : float
        Archimedes number, [-]

    Notes
    -----
    It may be seen as a ratio of weight minus bouyancy and the inertial forces
    It is often used in equations describing the motion of particles (solid
    particles, drop, bubbles) in other fluid phase.

    Examples
    --------
    >>> print("%0.0f" % Ar(5e-4, 2610, 0.6072, nu=48.09e-6))
    2278
    """
    if rho and mu:
        nu = mu/rho
    elif not nu:
        raise Exception("undefined")
    deltarho = abs(rho_p-rho)
    return Dimensionless(g*L**3*deltarho/(rho*nu**2)) 
Example #15
Source File: pipe.py    From pychemqt with GNU General Public License v3.0 4 votes vote down vote up
def calculo(self):
        self.L = unidades.Length(self.kwargs["l"])

        if self.kwargs["entrada"].x == 0:
            self.rho = self.kwargs["entrada"].Liquido.rho
            self.mu = self.kwargs["entrada"].Liquido.mu
        else:
            self.rho = self.kwargs["entrada"].Gas.rho
            self.mu = self.kwargs["entrada"].Gas.mu

        self.material = self.kwargs["material"][0] + " " + \
            self.kwargs["material"][1]
        self.Dn = self.kwargs["material"][3]
        self.rugosidad = unidades.Length(self.kwargs["material"][2], "mm")
        self.De = unidades.Length(self.kwargs["material"][6], "mm")
        self.w = unidades.Length(self.kwargs["material"][5], "mm")
        self.Di = unidades.Length((self.De-2*self.w))
        self.eD = unidades.Dimensionless(self.rugosidad/self.Di)
        self.seccion = unidades.Area(pi/4*self.Di**2)
        self.A = unidades.Area(pi*self.De*self.L)
        self.V = unidades.Speed(self.kwargs["entrada"].Q/self.seccion)
        self.Re = Re(self.Di, self.V, self.rho, self.mu)
        K = 0
        for accesorio in self.kwargs["accesorios"]:
            K += accesorio[2]*accesorio[3]
        self.K = unidades.Dimensionless(K)
        self.DeltaP_h = unidades.Pressure(g*self.kwargs["h"]*self.rho)
        self.DeltaP_ac = unidades.Pressure(self.K*self.V**2/2*self.rho)

        self.f = f_friccion(self.Re, self.eD)
        self.DeltaP_f = self.__DeltaP_friccion()
        # TODO:
        self.DeltaP_v = unidades.Pressure(0)

        self.DeltaP = unidades.Pressure(self.DeltaP_h + self.DeltaP_ac +
                                        self.DeltaP_f + self.DeltaP_v)
        self.DeltaP_100ft = self.DeltaP*100/self.L.ft
        self.Pout = unidades.Pressure(self.kwargs["entrada"].P-self.DeltaP)

        if self.kwargs["thermal"] == 0:
            self.Tout = self.kwargs["entrada"].T
            self.Heat = unidades.Power(0)
        else:
            ch = Heat_Exchanger()
            ch(entrada=self.kwargs["entrada"], modo=self.kwargs["thermal"],
               Heat=self.kwargs["Q"], deltaP=self.DeltaP, A=self.A,
               U=self.kwargs["U"], Text=self.kwargs["Text"])
            self.Tout = ch.salida[0].T
            self.Heat = ch.Heat

        self.salida = [self.kwargs["entrada"].clone(T=self.Tout, P=self.Pout)]
        self.Pin = self.kwargs["entrada"].P
        self.Pout = self.salida[0].P 
Example #16
Source File: constraintanalysis.py    From ADRpy with GNU General Public License v3.0 4 votes vote down vote up
def thrusttoweight_takeoff(self, wingloading_pa):
        """The thrust to weight ratio required for take-off. This function is an
        implementation of the following simple, analytical model:

        .. math::

            \\frac{\\overline{T}}{W} = 1.21\\frac{W/S}{\\rho C_\\mathrm{Lmax}^\\mathrm{TO}gd_
            \\mathrm{G}}+\\frac{1}{2}\\frac{C_\\mathrm{D}^\\mathrm{TO}}{C_\\mathrm{L}^\\mathrm{TO}}
            +\\frac{1}{2}\\mu_\\mathrm{R}

        where :math:`\\overline{T}` is the average thrust during the take-off run,
        :math:`W/S` is the wing loading, :math:`d_\\mathrm{G}` is the required ground
        roll, :math:`C_\\mathrm{D}^\\mathrm{TO}` and :math:`C_\\mathrm{L}^\\mathrm{TO}`
        are the 'all wheels on the runway' drag and lift coefficient respectively
        in the take-off configuration, :math:`C_\\mathrm{Lmax}^\\mathrm{TO}` is the maximum
        lift coefficient achieved during the take-off run (during rotation), :math:`\\rho`
        is the ambient density and :math:`\\mu_\\mathrm{R}` is the coefficient of rolling
        resistance on the wheels.

        This is a function exposed to the user for clarity and added flexibility.
        If you need to calculate the thrust to weight ratio required for take-off, use
        ``twrequired_to``. This corrects the output of this function to account for the
        environmental conditions (including their impact on engine performance) and includes
        a mapping to static thrust. ``thrusttoweight_takeoff`` should only be used if you
        would like to perform these corrections in a different way than implemented in
        ``twrequired_to``.

        If a full constraint analysis is required, ``twrequired`` should be used.
        A similar 'full constraint set' function is available for calculating the
        power demanded of the engine or electric motor of a propeller-driven aircraft
        (to satisfy the constraint set) - this is called ``powerrequired``.
        """

        groundrun_m = self.groundrun_m

        # Assuming that the lift-off speed is equal to VR, which we estimate at 1.1VS1(T/O)
        density_kgpm3 = self.designatm.airdens_kgpm3(self.rwyelevation_m)

        vs1to_mps = np.sqrt((2 * wingloading_pa) / (density_kgpm3 * self.clmaxto))

        liftoffspeed_mpstas = 1.1 * vs1to_mps

        thrusttoweightreqd = (liftoffspeed_mpstas ** 2) / (2 * constants.g * groundrun_m) + \
        0.5 * self.cdto / self.clto + \
        0.5 * self.mu_r

        return thrusttoweightreqd, liftoffspeed_mpstas 
Example #17
Source File: sm_table_parsers.py    From gmpe-smtk with GNU Affero General Public License v3.0 4 votes vote down vote up
def parse_row(cls, rowdict, sa_colnames):
        '''This method is intended to be overridden by subclasses (by default
        is no-op) to perform any further operation on the given csv row
        `rowdict` before writing it to the GM databse file. Please note that:

        1. This method should process `rowdict` in place, the returned value is
           ignored. Any exception raised here is hanlded in the caller method.
        2. `rowdict` keys might not be the same as the csv
           field names (first csv row). See `mappings` class attribute
        3. The values of `rowdict` are all strings and they will be casted
           later according to the column type. However, if a cast is needed
           here for some custom operation, in order to convert strings to
           floats or timestamps (floats denoting date-times) you can use the
           static methods `timestamp` and `float`. Both methods accept also
           lists or tuples to convert arrays and silenttly coerce unparsable
           values to nan (Note that nan represents a missing value for any
           numeric or timestamp column).
        4. the `rowdict` keys 'event_id', 'station_id' and 'record_id' are
           reserved and their values will be overridden anyway

        :param rowdict: a row of the csv flatfile, as Python dict

        :param sa_colnames: a list of strings of the column
            names denoting the SA values. The list is sorted ascending
            according to the relative numeric period defined in
            :method:`get_sa_periods`
        '''
        # replace non lower case keys with their lower case counterpart:
        for key in cls._non_lcase_fieldnames:
            rowdict[key.lower()] = rowdict.pop(key)

        # assign values (sa, event time, pga):
        tofloat = cls.float
        sa_ = tofloat([rowdict[p] for p in sa_colnames])
        sa_unit = rowdict[cls._acc_unit_col] if cls._acc_unit_col else 'g'
        sa_ = convert_accel_units(sa_, sa_unit)
        rowdict['sa'] = sa_

        # assign event time:
        evtime_fieldnames = cls._evtime_fieldnames
        dtime = ""
        if len(evtime_fieldnames) == 6:
            # use zfill to account for '934' formatted as '0934' for years,
            # and '5' formatted as '05' for all other fields:
            dtime = "{}-{}-{}T{}:{}:{}".\
                format(*(rowdict[c].zfill(4 if i == 0 else 2)
                       for i, c in enumerate(evtime_fieldnames)))
        else:
            dtime = rowdict[evtime_fieldnames[0]]
        rowdict['event_time'] = cls.timestamp(dtime)

        # assign pga:
        pga_col, pga_unit = cls._pga_col, cls._pga_unit
        if not pga_unit:
            pga_unit = cls._acc_unit_col if cls._acc_unit_col else 'g'
        rowdict['pga'] = \
            convert_accel_units(tofloat(rowdict[pga_col]), pga_unit) 
Example #18
Source File: sm_table_parsers.py    From gmpe-smtk with GNU Affero General Public License v3.0 4 votes vote down vote up
def get_sa_columns(cls, csv_fieldnames):
        """This method is intended to be overridden by subclasses (by default
        it raises :class:`NotImplementedError`) to return a `dict` of SA
        column names (string), mapped to a numeric value representing the SA
        period. This class will then sort and save SA periods accordingly.

        You can also implement here operations which should be executed once
        at the beginning of the flatfile parsing, such as e.g.
        creating objects and storing them as class attributes later accessible
        in :method:`parse_row`

        :param csv_fieldnames: an iterable of strings representing the
            header of the persed csv file
        """
        # convert to lower case:
        csv_fieldnames_lc = tuple(_.lower() for _ in csv_fieldnames)
        csv_fieldnames_lc_set = set(csv_fieldnames_lc)

        # this method is run once per parse action, setup here the
        # needed class attributes we will need inside parse_row (maybe could be
        # better implemented):
        try:
            cls._evtime_fieldnames = \
                cls._get_event_time_columns(csv_fieldnames_lc_set)
        except Exception as exc:
            raise ValueError('Unable to parse event '
                             'time column(s): %s' % str(exc))

        # get pga fieldname and units:
        try:
            cls._pga_col, cls._pga_unit, cls._acc_unit_col = \
                cls._get_pga_column_and_acc_units(csv_fieldnames_lc_set)
        except Exception as exc:
            raise ValueError('Unable to parse PGA column: %s' % str(exc))

        # set non-lowercase fields, so that we replace these later:
        cls._non_lcase_fieldnames = \
            set(csv_fieldnames) - csv_fieldnames_lc_set

        # extract the sa columns:
        periods_names = []
        reg = cls._sa_periods_re
        for fname in csv_fieldnames_lc:
            match = reg.match(fname)
            if match:
                periods_names.append((fname, float(match.group(1))))

        periods_names.sort(key=lambda item: item[1])
        return OrderedDict(periods_names) 
Example #19
Source File: sm_utils_test.py    From gmpe-smtk with GNU Affero General Public License v3.0 4 votes vote down vote up
def test_accel_units(self):
        '''test acceleration units function'''
        func = convert_accel_units
        for acc in [np.nan, 0, 100, -g*5, g*6.5,
                    np.array([np.nan, 0, 100, g*5, g*6.5])]:

            # check that cm_sec and m_sec produce the same result:
            _1, _2 = func(acc, 'g', 'cm/s/s'), func(acc, 'cm/s/s', 'g')
            for cmsec in ('cm/s^2', 'cm/s**2'):
                self.assertNEqual(_1, func(acc, 'g', cmsec))
                self.assertNEqual(_2, func(acc, cmsec, 'g'))

            _1, _2 = func(acc, 'g', 'm/s/s'), func(acc, 'm/s/s', 'g')
            for msec in ('m/s^2', 'm/s**2'):
                self.assertNEqual(_1, func(acc, 'g', msec))
                self.assertNEqual(_2, func(acc, msec, 'g'))

            # assert same label is no-op:
            self.assertNEqual(func(acc, 'g', 'g'), acc)
            self.assertNEqual(func(acc, 'cm/s/s', 'cm/s/s'), acc)
            self.assertNEqual(func(acc, 'm/s/s', 'm/s/s'), acc)

            # assume input in g:
            # to cm/s/s
            expected = acc * (100 * g)
            self.assertNEqual(func(acc, 'g', 'cm/s/s'), expected)
            self.assertNEqual(func(acc, 'g', 'cm/s/s'),
                              convert_accel_units_old(acc, 'g'))
            # to m/s/s:
            expected /= 100
            self.assertNEqual(func(acc, 'g', 'm/s/s'), expected)
            self.assertNEqual(func(acc, 'g', 'm/s/s'),
                              convert_accel_units_old(acc, 'g')/100)

            # check that the old calls to convert_accel_units:
            # are the same as the actual:
            for unit in ['g', 'cm/s/s', 'm/s/s']:
                self.assertNEqual(convert_accel_units_old(acc, unit),
                                  func(acc, unit))

            with self.assertRaises(ValueError):  # invalid units 'a':
                func(acc, 'a')