def finger_print_characteristic_collector(self):
        collected_characteristics_vector = self.collected_burst
        collected_labels = self.collected_labels

        for key in self.converted_characteristic.keys():

            self.converted_characteristic[key] = array(
                self.converted_characteristic[key])
            if size(self.converted_characteristic[key]) > 1:
                self.converted_characteristic[key] = reshape(
                    self.converted_characteristic[key],
                    [size(self.converted_characteristic[key], 0), 1])

            collected_characteristics_vector = row_stack(
                (collected_characteristics_vector,
                 self.converted_characteristic[key]))

            if size(collected_labels) == 0:
                collected_labels = {
                    self.output_label_index: self.output_labels[key]
                }
                self.output_label_index += 1

            else:
                collected_labels[
                    self.output_label_index] = self.output_labels[key]
                self.output_label_index += 1

        return collected_characteristics_vector, collected_labels
    def postProcessor_burst_collector(self):
        # saving the whole burst in the data-bank
        self.collected_burst = self.collected_burst[1:]
        self.collected_burst = reshape(self.collected_burst,
                                       size(self.collected_burst), 1)
        if size(self.data_collection) == 0:
            self.data_collection = self.collected_burst
        else:
            self.data_collection = column_stack(
                (self.data_collection, self.collected_burst))

        self.label_vector = column_stack(
            (self.label_vector, self.device_label))
        self.collected_burst = 0
    def finger_print_burst_collector(self):
        # saving the whole burst in the data-bank
        self.collected_burst = self.collected_burst[1:]
        self.collected_burst = reshape(self.collected_burst,
                                       [size(self.collected_burst, 0), 1])
        if size(self.data_collection) == 0:
            self.data_collection = self.collected_burst
        else:
            self.data_collection = column_stack(
                (self.data_collection, self.collected_burst))

        self.label_vector = column_stack(
            (self.label_vector, self.device_label))
        self.collected_burst = 0
Example #4
0
def power_mean_inner(p, mat, axis=0, dtype=None):
    mat_cmplx = mat.astype(np.complex64 if dtype ==
                           np.float32 else np.complex128)
    result_cmplx = np.power(
        (np.power(mat_cmplx, p)).sum(axis=axis) / size(mat_cmplx, axis=axis),
        1 / p)
    return result_cmplx.real.astype(dtype)
Example #5
0
 def __init__(self, **parameters):
     # TODO : check extra parameters dimensions consistancy if enumerates (must match layer height)
     # initialize weights
     weights = parameters.get(WeightParameters.WEIGHTS.value, None)
     # randomize weights if necessary
     if weights is None:
         currentHeight = parameters.get(
             WeightParameters.CURRENT_HEIGHT.value)
         previousHeight = parameters.get(
             WeightParameters.PREVIOUS_HEIGHT.value)
         weightLimit = parameters.get(WeightParameters.WEIGHT_LIMIT.value)
         # TODO : compute with spark 'weights'
         weights = (rand(currentHeight, previousHeight) -
                    .5) * 2 * weightLimit
     self.weights = weights
     height = size(self.weights, 0)
     # initialize meta parameters
     metaParameters = MetaParameters.defaultValues()
     # initialize meta parameters
     for name in MetaParameters.enumerate():
         value = parameters[name] if name in parameters else metaParameters[
             name]
         if not isinstance(value, Iterable):
             value = [value] * height
         metaParameters[name] = value
     # set meta parameters has enumerates
     for name, value in metaParameters.items():
         setattr(self, name, value)
Example #6
0
def variance(signal, special_parameters):
    # TODO: this 'special_parameters' maybe be useful
    signal = signal - mean(signal)
    squared_signal = power(signal, 2)
    summation = sum(squared_signal)
    statistic = (1 / size(signal)) * summation

    added_label = "var"

    return statistic, added_label
Example #7
0
def _pfromz_MA(z, lapse_rate, P_bott, T_bott, z_bott):
    """Pressure given altitude in a constant lapse rate layer.

    The dry gas constant is used in calculations requiring the gas
    constant.  See the docstring for press2alt for references.

    Input Arguments:
    * z:  Geopotential altitude [m].
    * lapse_rate:  -dT/dz [K/m] over the layer.
    * P_bott:  Pressure [hPa] at the base of the layer.
    * T_bott:  Temperature [K] at the base of the layer.
    * z_bott:  Geopotential altitude [m] of the base of the layer.

    Output:
    * Pressure [hPa] for each element given in the input arguments.

    All input arguments can be either a scalar or an MA array.  All 
    arguments that are MA arrays, however, are of the same size and 
    shape.  If every input argument is a scalar, the output is a scalar.  
    If any of the input arguments is an MA array, the output is an MA 
    array of the same size and shape.
    """
    #jfp was import Numeric as N
    import numpy as N
    #jfp was import MA
    import numpy.ma as MA
    from atmconst import AtmConst

    const = AtmConst()

    if MA.size(lapse_rate) == 1:
        #jfp was if MA.array(lapse_rate)[0] == 0.0:
        if MA.array(lapse_rate) == 0.0:
            return P_bott * \
                   MA.exp( -const.g / (const.R_d*T_bott) * (z-z_bott) )
        else:
            exponent = const.g / (const.R_d * lapse_rate)
            return P_bott * \
                   ( (1.0 - (lapse_rate * (z-z_bott) / T_bott))**exponent )
    else:
        exponent = const.g / (const.R_d * lapse_rate)
        P = P_bott * \
            ( (1.0 - (lapse_rate * (z-z_bott) / T_bott))**exponent )
        P_at_0 = P_bott * \
                 MA.exp( -const.g / (const.R_d*T_bott) * (z-z_bott) )

        zero_lapse_mask = MA.filled(MA.where(lapse_rate == 0., 1, 0), 0)
        zero_lapse_mask_indices_flat = N.nonzero(N.ravel(zero_lapse_mask))
        P_flat = MA.ravel(P)
        MA.put( P_flat, zero_lapse_mask_indices_flat \
              , MA.take(MA.ravel(P_at_0), zero_lapse_mask_indices_flat) )
        return MA.reshape(P_flat, P.shape)
Example #8
0
def _pfromz_MA(z, lapse_rate, P_bott, T_bott, z_bott):
    """Pressure given altitude in a constant lapse rate layer.

    The dry gas constant is used in calculations requiring the gas
    constant.  See the docstring for press2alt for references.

    Input Arguments:
    * z:  Geopotential altitude [m].
    * lapse_rate:  -dT/dz [K/m] over the layer.
    * P_bott:  Pressure [hPa] at the base of the layer.
    * T_bott:  Temperature [K] at the base of the layer.
    * z_bott:  Geopotential altitude [m] of the base of the layer.

    Output:
    * Pressure [hPa] for each element given in the input arguments.

    All input arguments can be either a scalar or an MA array.  All 
    arguments that are MA arrays, however, are of the same size and 
    shape.  If every input argument is a scalar, the output is a scalar.  
    If any of the input arguments is an MA array, the output is an MA 
    array of the same size and shape.
    """
    #jfp was import Numeric as N
    import numpy as N
    #jfp was import MA
    import numpy.ma as MA
    from atmconst import AtmConst

    const = AtmConst()

    if MA.size(lapse_rate) == 1:
        #jfp was if MA.array(lapse_rate)[0] == 0.0:
        if MA.array(lapse_rate) == 0.0:
            return P_bott * \
                   MA.exp( -const.g / (const.R_d*T_bott) * (z-z_bott) )
        else:
            exponent = const.g / (const.R_d * lapse_rate)
            return P_bott * \
                   ( (1.0 - (lapse_rate * (z-z_bott) / T_bott))**exponent )
    else:
        exponent = const.g / (const.R_d * lapse_rate)
        P = P_bott * \
            ( (1.0 - (lapse_rate * (z-z_bott) / T_bott))**exponent )
        P_at_0 = P_bott * \
                 MA.exp( -const.g / (const.R_d*T_bott) * (z-z_bott) )

        zero_lapse_mask = MA.filled(MA.where(lapse_rate == 0., 1, 0), 0)
        zero_lapse_mask_indices_flat = N.nonzero(N.ravel(zero_lapse_mask))
        P_flat = MA.ravel(P)
        MA.put( P_flat, zero_lapse_mask_indices_flat \
              , MA.take(MA.ravel(P_at_0), zero_lapse_mask_indices_flat) )
        return MA.reshape(P_flat, P.shape)
Example #9
0
def normalizer(data_bank, special_input, data_bank_structure):
    # TODO: do sth with special_input

    # data_bank: dimensions are in 'Rows'

    for row_index in range(size(data_bank, 0) - 1):
        current_dimension = data_bank[row_index, :]
        current_dimension = (current_dimension - mean(current_dimension)) / \
                                                                         (amax(current_dimension) - amin(current_dimension))

        data_bank[row_index, :] = current_dimension

    return data_bank
Example #10
0
def _zfromp_MA(P, lapse_rate, P_bott, T_bott, z_bott):
    """Altitude given pressure in a constant lapse rate layer.

    The dry gas constant is used in calculations requiring the gas
    constant.  See the docstring for press2alt for references.

    Input Arguments:
    * P:  Pressure [hPa].
    * lapse_rate:  -dT/dz [K/m] over the layer.
    * P_bott:  Pressure [hPa] at the base of the layer.
    * T_bott:  Temperature [K] at the base of the layer.
    * z_bott:  Geopotential altitude [m] of the base of the layer.

    Output:
    * Altitude [m] for each element given in the input arguments.

    All input arguments can be either a scalar or an MA array.  All 
    arguments that are MA arrays, however, are of the same size and 
    shape.  If every input argument is a scalar, the output is a scalar.
    If any of the input arguments is an MA array, the output is an MA 
    array of the same size and shape.
    """
    import numpy as N
    #jfp was import Numeric as N
    import numpy.ma as MA
    #jfp was import MA
    from atmconst import AtmConst

    const = AtmConst()

    if MA.size(lapse_rate) == 1:
        if MA.array(lapse_rate)[0] == 0.0:
            return ( (-const.R_d * T_bott / const.g) * MA.log(P/P_bott) ) + \
                   z_bott
        else:
            exponent = (const.R_d * lapse_rate) / const.g
            return ((T_bott / lapse_rate) * (1. - (P/P_bott)**exponent)) + \
                   z_bott
    else:
        exponent = (const.R_d * lapse_rate) / const.g
        z = ((T_bott / lapse_rate) * (1. - (P / P_bott)**exponent)) + z_bott
        z_at_0 = ( (-const.R_d * T_bott / const.g) * MA.log(P/P_bott) ) + \
                 z_bott

        zero_lapse_mask = MA.filled(MA.where(lapse_rate == 0., 1, 0), 0)
        zero_lapse_mask_indices_flat = N.nonzero(N.ravel(zero_lapse_mask))
        z_flat = MA.ravel(z)
        MA.put( z_flat, zero_lapse_mask_indices_flat \
              , MA.take(MA.ravel(z_at_0), zero_lapse_mask_indices_flat) )
        return MA.reshape(z_flat, z.shape)
Example #11
0
def _zfromp_MA(P, lapse_rate, P_bott, T_bott, z_bott):
    """Altitude given pressure in a constant lapse rate layer.

    The dry gas constant is used in calculations requiring the gas
    constant.  See the docstring for press2alt for references.

    Input Arguments:
    * P:  Pressure [hPa].
    * lapse_rate:  -dT/dz [K/m] over the layer.
    * P_bott:  Pressure [hPa] at the base of the layer.
    * T_bott:  Temperature [K] at the base of the layer.
    * z_bott:  Geopotential altitude [m] of the base of the layer.

    Output:
    * Altitude [m] for each element given in the input arguments.

    All input arguments can be either a scalar or an MA array.  All 
    arguments that are MA arrays, however, are of the same size and 
    shape.  If every input argument is a scalar, the output is a scalar.
    If any of the input arguments is an MA array, the output is an MA 
    array of the same size and shape.
    """
    import numpy as N
    #jfp was import Numeric as N
    import numpy.ma as MA
    #jfp was import MA
    from atmconst import AtmConst

    const = AtmConst()

    if MA.size(lapse_rate) == 1:
        if MA.array(lapse_rate)[0] == 0.0:
            return ( (-const.R_d * T_bott / const.g) * MA.log(P/P_bott) ) + \
                   z_bott
        else:
            exponent = (const.R_d * lapse_rate) / const.g
            return ((T_bott / lapse_rate) * (1. - (P/P_bott)**exponent)) + \
                   z_bott
    else:
        exponent = (const.R_d * lapse_rate) / const.g
        z = ((T_bott / lapse_rate) * (1. - (P/P_bott)**exponent)) + z_bott
        z_at_0 = ( (-const.R_d * T_bott / const.g) * MA.log(P/P_bott) ) + \
                 z_bott

        zero_lapse_mask = MA.filled(MA.where(lapse_rate == 0., 1, 0), 0)
        zero_lapse_mask_indices_flat = N.nonzero(N.ravel(zero_lapse_mask))
        z_flat = MA.ravel(z)
        MA.put( z_flat, zero_lapse_mask_indices_flat \
              , MA.take(MA.ravel(z_at_0), zero_lapse_mask_indices_flat) )
        return MA.reshape(z_flat, z.shape)
    def preProcessor_device_collector(self):
        if size(self.data_collection) == 0:
            self.data_collection = {}

        self.data_collection[self.device_key] = self.device_collection
Example #13
0
def press2alt(arg, P0=None, T0=None, missing=1e+20, invert=0):
    """Calculate elevation given pressure (or vice versa).

    Calculations are made assuming that the temperature distribution
    follows the 1976 Standard Atmosphere.  Technically the standard
    atmosphere defines temperature distribution as a function of
    geopotential altitude, and this routine actually calculates geo-
    potential altitude rather than geometric altitude.


    Method Positional Argument:
    * arg:  Numeric floating point vector of any shape and size, or a
      Numeric floating point scalar.  If invert=0 (the default), arg 
      is air pressure [hPa].  If invert=1, arg is elevation [m].


    Method Keyword Arguments:
    * P0:  Pressure [hPa] at the surface (altitude equals 0).  Numeric 
      floating point vector of same size and shape as arg or a scalar.
      Default of keyword is set to None, in which case the routine 
      uses the value of instance attribute sea_level_press (converted
      to hPa) from the AtmConst class.  Keyword value is used if the 
      keyword is set in the function call.  This keyword cannot have 
      any missing values.

    * T0:  Temperature [K] at the surface (altitude equals 0).  Numeric 
      floating point vector of same size and shape as arg or a scalar.  
      Default of keyword is set to None, in which case the routine uses 
      the value of instance attribute sea_level_temp from the AtmConst
      class.  Keyword value is used if the keyword is set in the func-
      tion call.  This keyword cannot have any missing values.

    * missing:  If arg has missing values, this is the missing value 
      value.  Floating point scalar.  Default is 1e+20.

    * invert:  If set to 1, function calculates pressure [hPa] from 
      altitude [m].  In that case, positional input variable arg is 
      altitude [m] and the output is pressure [hPa].  Default value of 
      invert=0, which means the function calculates altitude given 
      pressure.


    Output:
    * If invert=0 (the default), output is elevation [m] at each 
      element of arg, relative to the surface.  If invert=1, output
      is the air pressure [hPa].  Numeric floating point array of 
      the same size and shape as arg.

      If there are any missing values in output, those values are set 
      to the value in argument missing from the input.  If there are 
      missing values in the output due to math errors and missing is 
      set to None, output will fill those missing values with the MA 
      default value of 1e+20.


    References:
    * Carmichael, Ralph (2003):  "Definition of the 1976 Standard Atmo-
      sphere to 86 km," Public Domain Aeronautical Software (PDAS).
      URL:  http://www.pdas.com/coesa.htm.

    * Wallace, J. M., and P. V. Hobbs (1977): Atmospheric Science:
      An Introductory Survey.  San Diego, CA:  Academic Press, ISBN
      0-12-732950-1, pp. 60-61.


    Examples:

    (1) Calculating altitude given pressure:

    >>> from press2alt import press2alt
    >>> import Numeric as N
    >>> press = N.array([200., 350., 850., 1e+20, 50.])
    >>> alt = press2alt(press, missing=1e+20)
    >>> ['%.7g' % alt[i] for i in range(5)]
    ['11783.94', '8117.19', '1457.285', '1e+20', '20575.96']

    (2) Calculating pressure given altitude:

    >>> alt = N.array([0., 10000., 15000., 20000., 50000.])
    >>> press = press2alt(alt, missing=1e+20, invert=1)
    >>> ['%.7g' % press[i] for i in range(5)]
    ['1013.25', '264.3589', '120.443', '54.74718', '0.7593892']

    (3) Input is a Numeric floating point scalar, and using a keyword
        set surface pressure to a different scalar:

    >>> alt = press2alt(N.array(850.), P0=1000.)
    >>> ['%.7g' % alt[0]]
    ['1349.778']
    """
    import numpy.ma as MA
    import numpy as N
    from atmconst import AtmConst
    #from is_numeric_float import is_numeric_float

    #- Check input is of the correct type:

    #if is_numeric_float(arg) != 1:
    #    raise TypeError, "press2alt:  Arg not Numeric floating"

    #- Import general constants and set additional constants.  h1_std
    #  is the lower limit of the Standard Atmosphere layer geopoten-
    #  tial altitude [m], h2_std is the upper limit [m] of the layer,
    #  and dT/dh is the temperature gradient (i.e. negative of the
    #  lapse rate) [K/m]:

    const = AtmConst()

    h1_std = N.array([0., 11., 20., 32., 47., 51., 71.]) * 1000.
    h2_std = N.array(MA.concatenate([h1_std[1:], [84.852 * 1000.]]))
    dTdh_std = N.array([-6.5, 0.0, 1.0, 2.8, 0.0, -2.8, -2.0]) / 1000.

    #- Prep arrays for masked array calculation and set conditions
    #  at sea-level.  Pressures are in hPa and temperatures in K.
    #  Sea-level conditions arrays are same shape/size as P_or_z.
    #  If input argument is a scalar, make the local variable used
    #  for calculations a 1-element vector:

    if missing == None: P_or_z = MA.masked_array(arg)
    else: P_or_z = MA.masked_values(arg, missing, copy=0)

    if P_or_z.shape == ():
        P_or_z = MA.reshape(P_or_z, (1, ))

    if P0 == None:
        P0_use = MA.zeros(P_or_z.shape) \
               + (const.sea_level_press / 100.)
    else:
        P0_use = MA.zeros(P_or_z.shape) \
               + MA.masked_array(P0)

    if T0 == None:
        T0_use = MA.zeros(P_or_z.shape) \
               + const.sea_level_temp
    else:
        T0_use = MA.zeros(P_or_z.shape) \
               + MA.masked_array(T0)

    #- Calculate P and T for the boundaries of the 7 layers of the
    #  Standard Atmosphere for the given P0 and T0 (layer 0 goes from
    #  P0 to P1, layer 1 from P1 to P2, etc.).  These are given as
    #  8 element dictionaries P_std and T_std where the key is the
    #  location (P_std[0] is at the bottom of layer 0, P_std[1] is the
    #  top of layer 0 and bottom of layer 1, ... and P_std[7] is the
    #  top of layer 6).  Remember P_std and T_std are dictionaries but
    #  dTdh_std, h1_std, and h2_std are vectors:

    P_std = {0: P0_use}
    T_std = {0: T0_use}

    for i in range(len(h1_std)):
        P_std[i+1] = _pfromz_MA( h2_std[i], -dTdh_std[i] \
                               , P_std[i], T_std[i], h1_std[i] )
        T_std[i + 1] = T_std[i] + (dTdh_std[i] * (h2_std[i] - h1_std[i]))

    #- Test input is within Standard Atmosphere limits:

    if invert == 0:
        tmp = MA.where(P_or_z < P_std[len(h1_std)], 1, 0)
        if MA.sum(MA.ravel(tmp)) > 0:
            raise ValueError, "press2alt:  Pressure out-of-range"
    else:
        tmp = MA.where(P_or_z > MA.maximum(h2_std), 1, 0)
        if MA.sum(MA.ravel(tmp)) > 0:
            raise ValueError, "press2alt:  Altitude out-of-range"

    #- What layer number is each element of P_or_z in?

    P_or_z_layer = 0  #MA.zeros(P_or_z.shape)

    #if invert == 0:
    #    for i in range(len(h1_std)):
    #        tmp = MA.where( MA.logical_and( (P_or_z <= P_std[i]) \
    #                                      , (P_or_z >  P_std[i+1]) ) \
    #                      , i, 0 )
    #        P_or_z_layer += tmp
    #else:
    #    for i in range(len(h1_std)):
    #        tmp = MA.where( MA.logical_and( (P_or_z >= h1_std[i]) \
    #                                      , (P_or_z <  h2_std[i]) ) \
    #                      , i, 0 )
    #        P_or_z_layer += tmp

    #- Fill in the bottom-of-the-layer variables and the lapse rate
    #  for the layers that the levels are in.  The *_actual variables
    #  are the values of dTdh, P_bott, etc. for each element in the
    #  P_or_z_flat array:

    P_or_z_flat = MA.ravel(P_or_z)
    if P_or_z_flat.mask() == None:
        P_or_z_flat_mask = MA.make_mask_none(P_or_z_flat.shape)
    else:
        P_or_z_flat_mask = P_or_z_flat.mask()

    P_or_z_layer_flat = MA.ravel(P_or_z_layer)
    dTdh_actual = MA.zeros(P_or_z_flat.shape)
    P_bott_actual = MA.zeros(P_or_z_flat.shape)
    T_bott_actual = MA.zeros(P_or_z_flat.shape)
    z_bott_actual = MA.zeros(P_or_z_flat.shape)

    for i in xrange(MA.size(P_or_z_flat)):
        if P_or_z_flat_mask[i] != 1:
            layer_number = P_or_z_layer_flat[i]
            dTdh_actual[i] = dTdh_std[layer_number]
            P_bott_actual[i] = MA.ravel(P_std[layer_number])[i]
            T_bott_actual[i] = MA.ravel(T_std[layer_number])[i]
            z_bott_actual[i] = h1_std[layer_number]
        else:
            dTdh_actual[i] = MA.masked
            P_bott_actual[i] = MA.masked
            T_bott_actual[i] = MA.masked
            z_bott_actual[i] = MA.masked

    #- Calculate pressure/altitude from altitude/pressure (output is
    #  a flat array):

    if invert == 0:
        output = _zfromp_MA( P_or_z_flat, -dTdh_actual \
                           , P_bott_actual, T_bott_actual, z_bott_actual )
    else:
        output = _pfromz_MA( P_or_z_flat, -dTdh_actual \
                           , P_bott_actual, T_bott_actual, z_bott_actual )

    #- Return output as same shape as input positional argument:

    return MA.filled(MA.reshape(output, arg.shape), missing)
Example #14
0
def press2alt(arg, P0=None, T0=None, missing=1e+20, invert=0):
    """Calculate elevation given pressure (or vice versa).

    Calculations are made assuming that the temperature distribution
    follows the 1976 Standard Atmosphere.  Technically the standard
    atmosphere defines temperature distribution as a function of
    geopotential altitude, and this routine actually calculates geo-
    potential altitude rather than geometric altitude.


    Method Positional Argument:
    * arg:  Numeric floating point vector of any shape and size, or a
      Numeric floating point scalar.  If invert=0 (the default), arg 
      is air pressure [hPa].  If invert=1, arg is elevation [m].


    Method Keyword Arguments:
    * P0:  Pressure [hPa] at the surface (altitude equals 0).  Numeric 
      floating point vector of same size and shape as arg or a scalar.
      Default of keyword is set to None, in which case the routine 
      uses the value of instance attribute sea_level_press (converted
      to hPa) from the AtmConst class.  Keyword value is used if the 
      keyword is set in the function call.  This keyword cannot have 
      any missing values.

    * T0:  Temperature [K] at the surface (altitude equals 0).  Numeric 
      floating point vector of same size and shape as arg or a scalar.  
      Default of keyword is set to None, in which case the routine uses 
      the value of instance attribute sea_level_temp from the AtmConst
      class.  Keyword value is used if the keyword is set in the func-
      tion call.  This keyword cannot have any missing values.

    * missing:  If arg has missing values, this is the missing value 
      value.  Floating point scalar.  Default is 1e+20.

    * invert:  If set to 1, function calculates pressure [hPa] from 
      altitude [m].  In that case, positional input variable arg is 
      altitude [m] and the output is pressure [hPa].  Default value of 
      invert=0, which means the function calculates altitude given 
      pressure.


    Output:
    * If invert=0 (the default), output is elevation [m] at each 
      element of arg, relative to the surface.  If invert=1, output
      is the air pressure [hPa].  Numeric floating point array of 
      the same size and shape as arg.

      If there are any missing values in output, those values are set 
      to the value in argument missing from the input.  If there are 
      missing values in the output due to math errors and missing is 
      set to None, output will fill those missing values with the MA 
      default value of 1e+20.


    References:
    * Carmichael, Ralph (2003):  "Definition of the 1976 Standard Atmo-
      sphere to 86 km," Public Domain Aeronautical Software (PDAS).
      URL:  http://www.pdas.com/coesa.htm.

    * Wallace, J. M., and P. V. Hobbs (1977): Atmospheric Science:
      An Introductory Survey.  San Diego, CA:  Academic Press, ISBN
      0-12-732950-1, pp. 60-61.


    Examples:

    (1) Calculating altitude given pressure:

    >>> from press2alt import press2alt
    >>> import Numeric as N
    >>> press = N.array([200., 350., 850., 1e+20, 50.])
    >>> alt = press2alt(press, missing=1e+20)
    >>> ['%.7g' % alt[i] for i in range(5)]
    ['11783.94', '8117.19', '1457.285', '1e+20', '20575.96']

    (2) Calculating pressure given altitude:

    >>> alt = N.array([0., 10000., 15000., 20000., 50000.])
    >>> press = press2alt(alt, missing=1e+20, invert=1)
    >>> ['%.7g' % press[i] for i in range(5)]
    ['1013.25', '264.3589', '120.443', '54.74718', '0.7593892']

    (3) Input is a Numeric floating point scalar, and using a keyword
        set surface pressure to a different scalar:

    >>> alt = press2alt(N.array(850.), P0=1000.)
    >>> ['%.7g' % alt[0]]
    ['1349.778']
    """
    import numpy as N
    import numpy.ma as MA
    #jfp was import MA
    #jfp was import Numeric as N
    from atmconst import AtmConst
    from is_numeric_float import is_numeric_float


    #- Check input is of the correct type:

    if is_numeric_float(arg) != 1:
        raise TypeError, "press2alt:  Arg not Numeric floating"


    #- Import general constants and set additional constants.  h1_std
    #  is the lower limit of the Standard Atmosphere layer geopoten-
    #  tial altitude [m], h2_std is the upper limit [m] of the layer,
    #  and dT/dh is the temperature gradient (i.e. negative of the
    #  lapse rate) [K/m]:

    const = AtmConst()

    h1_std   = N.array([0., 11., 20., 32., 47., 51., 71.]) * 1000.
    h2_std   = N.array( MA.concatenate([h1_std[1:], [84.852*1000.]]) )
    dTdh_std = N.array([-6.5, 0.0, 1.0, 2.8, 0.0, -2.8, -2.0]) / 1000.


    #- Prep arrays for masked array calculation and set conditions
    #  at sea-level.  Pressures are in hPa and temperatures in K.
    #  Sea-level conditions arrays are same shape/size as P_or_z.
    #  If input argument is a scalar, make the local variable used
    #  for calculations a 1-element vector:

    if missing == None: P_or_z = MA.masked_array(arg)
    else:               P_or_z = MA.masked_values(arg, missing, copy=0)

    if P_or_z.shape == ():
        P_or_z = MA.reshape(P_or_z, (1,))

    if P0 == None:
        #jfp was P0_use = MA.zeros(P_or_z.shape, typecode=MA.Float) \
        P0_use = MA.zeros(P_or_z.shape) \
               + (const.sea_level_press / 100.)
    else:
        #jfp was P0_use = MA.zeros(P_or_z.shape, typecode=MA.Float) \
        P0_use = MA.zeros(P_or_z.shape) \
               + MA.masked_array(P0)

    if T0 == None:
        #jfp was T0_use = MA.zeros(P_or_z.shape, typecode=MA.Float) \
        T0_use = MA.zeros(P_or_z.shape) \
               + const.sea_level_temp
    else:
        #jfp was T0_use = MA.zeros(P_or_z.shape, typecode=MA.Float) \
        T0_use = MA.zeros(P_or_z.shape) \
               + MA.masked_array(T0)


    #- Calculate P and T for the boundaries of the 7 layers of the
    #  Standard Atmosphere for the given P0 and T0 (layer 0 goes from
    #  P0 to P1, layer 1 from P1 to P2, etc.).  These are given as
    #  8 element dictionaries P_std and T_std where the key is the
    #  location (P_std[0] is at the bottom of layer 0, P_std[1] is the
    #  top of layer 0 and bottom of layer 1, ... and P_std[7] is the
    #  top of layer 6).  Remember P_std and T_std are dictionaries but
    #  dTdh_std, h1_std, and h2_std are vectors:

    P_std = {0:P0_use}
    T_std = {0:T0_use}

    for i in range(len(h1_std)):
        P_std[i+1] = _pfromz_MA( h2_std[i], -dTdh_std[i] \
                               , P_std[i], T_std[i], h1_std[i] )
        T_std[i+1] = T_std[i] + ( dTdh_std[i] * (h2_std[i]-h1_std[i]) )

    #- Test input is within Standard Atmosphere limits:

    if invert == 0:
        tmp = MA.where(P_or_z < P_std[len(h1_std)], 1, 0)
        if MA.sum(MA.ravel(tmp)) > 0:
            raise ValueError, "press2alt:  Pressure out-of-range"
    else:
        tmp = MA.where(P_or_z > MA.maximum(h2_std), 1, 0)
        if MA.sum(MA.ravel(tmp)) > 0:
            raise ValueError, "press2alt:  Altitude out-of-range"


    #- What layer number is each element of P_or_z in?

    P_or_z_layer = MA.zeros(P_or_z.shape)

    if invert == 0:
        for i in range(len(h1_std)):
            tmp = MA.where( MA.logical_and( (P_or_z <= P_std[i]) \
                                          , (P_or_z >  P_std[i+1]) ) \
                          , i, 0 )
            P_or_z_layer += tmp
    else:
        for i in range(len(h1_std)):
            tmp = MA.where( MA.logical_and( (P_or_z >= h1_std[i]) \
                                          , (P_or_z <  h2_std[i]) ) \
                          , i, 0 )
            P_or_z_layer += tmp


    #- Fill in the bottom-of-the-layer variables and the lapse rate
    #  for the layers that the levels are in.  The *_actual variables 
    #  are the values of dTdh, P_bott, etc. for each element in the
    #  P_or_z_flat array:

    P_or_z_flat = MA.ravel(P_or_z)
    P_or_z_flat_mask = P_or_z_flat.mask
    if P_or_z_flat.mask==False:
        P_or_z_flat_mask = MA.make_mask_none(P_or_z_flat.shape)
    #jfp was:
    #if P_or_z_flat.mask() == None:
    #    P_or_z_flat_mask = MA.make_mask_none(P_or_z_flat.shape)
    #else:
    #    P_or_z_flat_mask = P_or_z_flat.mask()

    P_or_z_layer_flat = MA.ravel(P_or_z_layer)
    #jfp was dTdh_actual       = MA.zeros(P_or_z_flat.shape, typecode=MA.Float)
    #jfp was P_bott_actual     = MA.zeros(P_or_z_flat.shape, typecode=MA.Float)
    #jfp was T_bott_actual     = MA.zeros(P_or_z_flat.shape, typecode=MA.Float)
    #jfp was z_bott_actual     = MA.zeros(P_or_z_flat.shape, typecode=MA.Float)
    dTdh_actual       = MA.zeros(P_or_z_flat.shape)
    P_bott_actual     = MA.zeros(P_or_z_flat.shape)
    T_bott_actual     = MA.zeros(P_or_z_flat.shape)
    z_bott_actual     = MA.zeros(P_or_z_flat.shape)

    for i in xrange(MA.size(P_or_z_flat)):
        if P_or_z_flat_mask[i] != 1:
            layer_number     = P_or_z_layer_flat[i]
            dTdh_actual[i]   = dTdh_std[layer_number]
            P_bott_actual[i] = MA.ravel(P_std[layer_number])[i]
            T_bott_actual[i] = MA.ravel(T_std[layer_number])[i]
            z_bott_actual[i] = h1_std[layer_number]
        else:
            dTdh_actual[i]   = MA.masked
            P_bott_actual[i] = MA.masked
            T_bott_actual[i] = MA.masked
            z_bott_actual[i] = MA.masked


    #- Calculate pressure/altitude from altitude/pressure (output is
    #  a flat array):
    
    if invert == 0:
        output = _zfromp_MA( P_or_z_flat, -dTdh_actual \
                           , P_bott_actual, T_bott_actual, z_bott_actual )
    else:
        output = _pfromz_MA( P_or_z_flat, -dTdh_actual \
                           , P_bott_actual, T_bott_actual, z_bott_actual )


    #- Return output as same shape as input positional argument:

    return MA.filled( MA.reshape(output, arg.shape), missing )