コード例 #1
0
class Arias(IMT):
    """Class defining steps and invalid imts, for arias intensity."""

    # making invalid IMCs a class variable because
    # 1) it doesn't change with instances
    # 2) information can now be retrieved without
    #    instantiating first
    imts, imcs = gather_pgms()
    _invalid_imcs = ['gmrotd', 'rotd']

    def __init__(self, imt, imc, period=None):
        """
        Args:
            imt (string):
                Intensity measurement type.
            imc (string):
                Intensity measurement component.
            period (float):
                Period for fourier amplitude spectra and spectral amplitudes.
                Default is None. Not used by Arias.
        """
        super().__init__(imt, imc, period=None)
        self._steps = {
            'Transform2': 'null_transform',
            'Transform3': 'null_transform',
            'Combination1': 'null_combination',
            'Reduction': 'arias',
        }
コード例 #2
0
    def fromMetricXML(cls, xmlstr):
        imtlist = gather_pgms()[0]
        root = etree.fromstring(xmlstr)
        pgms = {}
        station_code = None
        damping = None
        for element in root.iter():
            etag = element.tag
            if etag == 'waveform_metrics':
                station_code = element.attrib['station_code']
                continue
            elif etag in imtlist:
                tdict = {}
                if etag in ['sa', 'fas']:
                    period = element.attrib['period']
                    if 'damping' in element.attrib:
                        damping = float(element.attrib['damping'])
                    imt = '%s(%s)' % (etag.upper(), period)
                else:
                    imt = etag.upper()
                for imc_element in element.getchildren():
                    imc = imc_element.tag.upper()
                    value = float(imc_element.text)
                    tdict[imc] = value

                pgms[imt] = tdict
        station = cls.from_pgms(station_code, pgms)
        station._damping = damping
        return station
コード例 #3
0
class Duration(IMT):
    """Class defining steps and invalid imts, for duration."""

    # making invalid IMCs a class variable because
    # 1) it doesn't change with instances
    # 2) information can now be retrieved without
    #    instantiating first
    imts, imcs = gather_pgms()

    # Until we redesign the metrics controller to allow for two
    # different reduction steps, we can't support the percentile-baesd
    # IMCs. See notes in gmprocess.metrics.execute_steps
    _invalid_imcs = ['gmrotd', 'rotd']

    def __init__(self, imt, imc, period=None):
        """
        Args:
            imt (string):
                Intensity measurement type.
            imc (string):
                Intensity measurement component.
            period (float):
                Period for fourier amplitude spectra and spectral amplitudes.
                Default is None. Not used by Arias.
        """
        super().__init__(imt, imc, period=None)
        self._steps = {
            'Transform2': 'null_transform',
            'Transform3': 'null_transform',
            'Combination1': 'null_combination',
            'Reduction': 'duration',
        }
コード例 #4
0
def test_gather():
    target_imts = [
        "pga", "pgv", "sa", "fas", "arias", "duration", "sorted_duration"
    ]
    target_imcs = [
        "CHANNELS",
        "GMROTD",
        "ROTD",
        "RADIAL_TRANSVERSE",
        "GREATER_OF_TWO_HORIZONTALS",
        "ARITHMETIC_MEAN",
        "GEOMETRIC_MEAN",
        "QUADRATIC_MEAN",
    ]
    target_imcs = [
        "channels",
        "gmrotd",
        "rotd",
        "radial_transverse",
        "greater_of_two_horizontals",
        "arithmetic_mean",
        "geometric_mean",
        "quadratic_mean",
    ]
    imts, imcs = gather_pgms()
    assert len(imts) == len(target_imts)
    assert len(imcs) == len(target_imcs)
    np.testing.assert_array_equal(np.sort(imts), np.sort(target_imts))
    np.testing.assert_array_equal(np.sort(imcs), np.sort(target_imcs))
コード例 #5
0
    def fromMetricXML(cls, xmlstr):
        imtlist = gather_pgms()[0]
        root = etree.fromstring(xmlstr)
        pgms = {}
        station_code = None
        damping = None
        for element in root.iter():
            etag = element.tag
            if etag == 'waveform_metrics':
                station_code = element.attrib['station_code']
                continue
            elif etag in imtlist:
                tdict = {}
                if etag in ['sa', 'fas']:
                    period = element.attrib['period']
                    if 'damping' in element.attrib:
                        damping = float(element.attrib['damping'])
                    imt = '%s(%s)' % (etag.upper(), period)
                else:
                    imt = etag.upper()
                for imc_element in element.getchildren():
                    imc = imc_element.tag.upper()
                    value = float(imc_element.text)
                    tdict[imc] = value

                pgms[imt] = tdict
        station = cls.from_pgms(station_code, pgms)
        station._damping = damping
        return station
コード例 #6
0
    def available_imts(self):
        """
        Helper method for getting a list of measurement types.

        Returns:
            list: List of available measurement types (str).
        """
        return [x for x in gather_pgms()[0]]
コード例 #7
0
    def available_imcs(self):
        """
        Helper method for getting a list of components.

        Returns:
            list: List of available components (str).
        """
        return [x for x in gather_pgms()[1]]
コード例 #8
0
    def available_imts(self):
        """
        Helper method for getting a list of measurement types.

        Returns:
            list: List of available measurement types (str).
        """
        return [x for x in gather_pgms()[0]]
コード例 #9
0
    def available_imcs(self):
        """
        Helper method for getting a list of components.

        Returns:
            list: List of available components (str).
        """
        return [x for x in gather_pgms()[1]]
コード例 #10
0
 def __init__(self,
              imts,
              imcs,
              timeseries,
              bandwidth=None,
              damping=None,
              event=None,
              smooth_type=None):
     """
     Args:
         imts (list):
             Intensity measurement types (string) to calculate.
         imcs (list):
             Intensity measurement components (string) to
             calculate. timeseries (StationStream): Stream of the
             timeseries data.
         event (ScalarEvent):
             Defines the focal time, geographic location, and magnitude of
             an earthquake hypocenter. Default is None.
         damping (float):
             Damping for the oscillator calculation.
         bandwidth (float):
             Bandwidth for the smoothing calculation.
         smoothing (string):
             Currently not used, as konno_ohmachi is the only smoothing
             type.
     """
     if not isinstance(imts, (list, np.ndarray)):
         imts = [imts]
     if not isinstance(imcs, (list, np.ndarray)):
         imcs = [imcs]
     self.imts = set(np.sort([imt.lower() for imt in imts]))
     self.imcs = set(np.sort([imc.lower() for imc in imcs]))
     if 'radial_transverse' in self.imcs and event is None:
         raise PGMException('MetricsController: Event is required for '
                            'radial_transverse imc')
     self.timeseries = timeseries
     self.validate_stream()
     self.event = event
     self.config = get_config()
     self.damping = damping
     self.smooth_type = smooth_type
     self.bandwidth = bandwidth
     if damping is None:
         self.damping = self.config['metrics']['sa']['damping']
     if smooth_type is None:
         self.smooth_type = self.config['metrics']['fas']['smoothing']
     if bandwidth is None:
         self.bandwidth = self.config['metrics']['fas']['bandwidth']
     self._available_imts, self._available_imcs = gather_pgms()
     self._step_sets = self.get_steps()
     imtstr = '_'.join(imts)
     if '_sa' in imtstr or imtstr.startswith('sa'):
         self._times = self._get_horizontal_time()
     else:
         self._times = None
     self.pgms = self.execute_steps()
コード例 #11
0
def test_gather():
    target_imts = ['pga', 'pgv', 'sa', 'fas', 'arias']
    target_imcs = ['CHANNELS', 'GMROTD', 'ROTD', 'RADIAL_TRANSVERSE',
            'GREATER_OF_TWO_HORIZONTALS', 'ARITHMETIC_MEAN', 'GEOMETRIC_MEAN',
            'QUADRATIC_MEAN']
    target_imcs = ['channels', 'gmrotd', 'rotd', 'radial_transverse',
            'greater_of_two_horizontals', 'arithmetic_mean', 'geometric_mean',
            'quadratic_mean']
    imts, imcs = gather_pgms()
    assert len(imts) == len(target_imts)
    assert len(imcs) == len(target_imcs)
    np.testing.assert_array_equal(np.sort(imts), np.sort(target_imts))
    np.testing.assert_array_equal(np.sort(imcs), np.sort(target_imcs))
コード例 #12
0
ファイル: imt.py プロジェクト: norfordb/groundmotion
 def __init__(self, imt, imc, period=None):
     """
     Args:
         imc (string): Intensity measurement component.
         imt (string): Intensity measurement type.
         period (float): Period for fourier amplitude spectra and
                 spectral amplitudes.  Default is None.
     """
     self.imt = imt.lower()
     self.imc = imc.lower()
     self.period = period
     imts, imcs = gather_pgms()
     self._available_imcs = imcs
コード例 #13
0
def get_combinations():
    imts, imcs = gather_pgms()
    dataframe = pd.DataFrame(columns=imts + ['imc'])
    checks = ['Y'] * len(imts)
    for imc in imcs:
        imc_class = get_class(imc, 'imc')
        invalid_imts = imc_class._invalid_imts
        row = dict(zip(imts, checks))
        for iimt in invalid_imts:
            row[iimt.lower()] = 'N'
        row['imc'] = imc
        dataframe = dataframe.append(row, ignore_index=True)

    dataframe = dataframe.set_index('imc')
    return dataframe
コード例 #14
0
 def __init__(self, imc, imt, percentile=None, period=None):
     """
     Args:
         imc (string): Intensity measurement component.
         imt (string): Intensity measurement type.
         percentile (float): Percentile for rotations. Default is None.
                 Not used by AM.
         period (float): Period for fourier amplitude spectra and
                 spectral amplitudes.  Default is None. Not used by AM.
     """
     self.imc = imc.lower()
     self.imt = imt.lower()
     self.period = period
     self.percentile = percentile
     imts, imcs = gather_pgms()
     self._available_imts = imts
コード例 #15
0
ファイル: gather_test.py プロジェクト: norfordb/groundmotion
def test_gather():
    target_imts = ['pga', 'pgv', 'sa', 'fas', 'arias']
    target_imcs = [
        'CHANNELS', 'GMROTD', 'ROTD', 'RADIAL_TRANSVERSE',
        'GREATER_OF_TWO_HORIZONTALS', 'ARITHMETIC_MEAN', 'GEOMETRIC_MEAN',
        'QUADRATIC_MEAN'
    ]
    target_imcs = [
        'channels', 'gmrotd', 'rotd', 'radial_transverse',
        'greater_of_two_horizontals', 'arithmetic_mean', 'geometric_mean',
        'quadratic_mean'
    ]
    imts, imcs = gather_pgms()
    assert len(imts) == len(target_imts)
    assert len(imcs) == len(target_imcs)
    np.testing.assert_array_equal(np.sort(imts), np.sort(target_imts))
    np.testing.assert_array_equal(np.sort(imcs), np.sort(target_imcs))
コード例 #16
0
 def __init__(self, imt, imc, period):
     """
     Args:
         imt (string): Intensity measurement type.
         imc (string): Intensity measurement component.
         period (float): Period for fourier amplitude spectra and
                 spectral amplitudes.
     """
     super().__init__(imt, imc, period=None)
     self._steps = {
         'Transform2': 'null_transform',
         'Transform3': 'fft',
         'Reduction': 'smooth_select',
     }
     imts, imcs = gather_pgms()
     valid_imcs = ['geometric_mean', 'arithmetic_mean', 'quadratic_mean']
     self._invalid_imcs = [imc for imc in imcs if imc not in valid_imcs]
コード例 #17
0
 def __init__(self, imt, imc, period=None):
     """
     Args:
         imt (string): Intensity measurement type.
         imc (string): Intensity measurement component.
         period (float): Period for fourier amplitude spectra and
                 spectral amplitudes. Default is None. Not used by Arias.
     """
     super().__init__(imt, imc, period=None)
     self._steps = {
             'Transform2': 'null_transform',
             'Transform3': 'null_transform',
             'Combination1': 'null_combination',
             'Reduction': 'arias',
     }
     imts, imcs = gather_pgms()
     self._invalid_imcs = [imc for imc in imcs if imc != 'arithmetic_mean']
コード例 #18
0
 def __init__(self, imts, imcs, timeseries, bandwidth=None, damping=None,
              event=None, smooth_type=None):
     """
     Args:
         imts (list): Intensity measurement types (string) to calculate.
         imcs (list): Intensity measurement components (string) to calculate.
         timeseries (StationStream): Stream of the timeseries data.
         event (ScalarEvent): Defines the focal time, 
                 geographic location, and magnitude of an earthquake hypocenter.
                 Default is None.
         damping (float): Damping for the oscillator calculation.
         bandwidth (float): Bandwidth for the smoothing calculation.
         smoothing (string): Currently not used, as konno_ohmachi is the
                 only smoothing type.
     """
     if not isinstance(imts, (list, np.ndarray)):
         imts = [imts]
     if not isinstance(imcs, (list, np.ndarray)):
         imcs = [imcs]
     self.imts = set(np.sort([imt.lower() for imt in imts]))
     self.imcs = set(np.sort([imc.lower() for imc in imcs]))
     if 'radial_transverse' in self.imcs and event is None:
         raise PGMException('MetricsController: Event is required for '
                            'radial_transverse imc')
     self.timeseries = timeseries
     self.validate_stream()
     self.event = event
     self.config = get_config()
     self.damping = damping
     self.smooth_type = smooth_type
     self.bandwidth = bandwidth
     if damping is None:
         self.damping = self.config['metrics']['sa']['damping']
     if smooth_type is None:
         self.smooth_type = self.config['metrics']['fas']['smoothing']
     if bandwidth is None:
         self.bandwidth = self.config['metrics']['fas']['bandwidth']
     self._available_imts, self._available_imcs = gather_pgms()
     self._step_sets = self.get_steps()
     imtstr = '_'.join(imts)
     if '_sa' in imtstr or imtstr.startswith('sa'):
         self._times = self._get_horizontal_time()
     else:
         self._times = None
     self.pgms = self.execute_steps()
コード例 #19
0
# Local imports
from gmprocess.metrics.gather import gather_pgms
from gmprocess.metrics.imt.imt import IMT

imts, imcs = gather_pgms()
valid_imcs = ['geometric_mean', 'arithmetic_mean', 'quadratic_mean']


class FAS(IMT):
    """Class defining steps and invalid imts, for fourier amplitude spectra."""

    # making invalid IMCs a class variable because
    # 1) it doesn't change with instances
    # 2) information can now be retrieved without
    #    instantiating first
    _invalid_imcs = [imc for imc in imcs if imc not in valid_imcs]

    def __init__(self, imt, imc, period):
        """
        Args:
            imt (string): Intensity measurement type.
            imc (string): Intensity measurement component.
            period (float): Period for fourier amplitude spectra and
                    spectral amplitudes.
        """
        super().__init__(imt, imc, period=None)
        self._steps = {
            'Transform2': 'null_transform',
            'Transform3': 'fft',
            'Reduction': 'smooth_select',
        }
コード例 #20
0
    def from_xml(cls, xml_stream, xml_station):
        """Instantiate a StationSummary from metrics XML stored in ASDF file.

        <waveform_metrics>
            <rot_d50>
                <pga units="m/s**2">0.45</pga>
                <sa percent_damping="5.0" units="g">
                <value period="2.0">0.2</value>
            </rot_d50>
            <maximum_component>
            </maximum_component>
        </waveform_metrics>

        <station_metrics>
            <distances>
            <hypocentral units="km">100</hypocentral>
            <epicentral units="km">120</epicentral>
            </distances>
        </station_metrics>

        Args:
            xml_stream (str):
                Stream metrics XML string in format above.
            xml_station (str):
                Station metrics XML string in format above.

        Returns:
            object: StationSummary Object summarizing all station metrics.

        """
        imtlist = gather_pgms()[0]
        root = etree.fromstring(xml_stream)
        pgms = {}
        channel_dict = {}
        damping = None
        for element in root.iter():
            etag = element.tag
            if etag == "waveform_metrics":
                station_code = element.attrib["station_code"]
                continue
            elif etag in imtlist:
                tdict = {}
                if etag in ["sa", "fas"]:
                    period = element.attrib["period"]
                    if "damping" in element.attrib:
                        damping = float(element.attrib["damping"])
                    imt = f"{etag.upper()}({period})"
                elif etag == "duration":
                    interval = element.attrib["interval"]
                    imt = f"{etag.upper()}{interval}"
                else:
                    imt = etag.upper()
                for imc_element in element.getchildren():
                    imc = imc_element.tag.upper()
                    if imc in ["H1", "H2", "Z"]:
                        if "original_channel" in imc_element.attrib:
                            channel_dict[imc] = imc_element.attrib[
                                "original_channel"]
                    value = float(imc_element.text)
                    tdict[imc] = value

                pgms[imt] = tdict
        station = cls.from_pgms(station_code, pgms)
        station._damping = damping
        station.channel_dict = channel_dict.copy()
        # extract info from station metrics, fill in metadata
        root = etree.fromstring(xml_station)  # station metrics element
        for element in root.iterchildren():
            if element.tag == "distances":
                for dist_type in element.iterchildren():
                    station._distances[dist_type.tag] = float(dist_type.text)
            if element.tag == "vs30":
                for vs30_type in element.iterchildren():
                    station._vs30[vs30_type.tag] = {
                        "value": float(vs30_type.text),
                        "column_header": vs30_type.attrib["column_header"],
                        "readme_entry": vs30_type.attrib["readme_entry"],
                        "units": vs30_type.attrib["units"],
                    }
            if element.tag == "back_azimuth":
                station._back_azimuth = float(element.text)

        return station
コード例 #21
0
    def from_xml(cls, xml_stream, xml_station):
        """Instantiate a StationSummary from metrics XML stored in ASDF file.

        <waveform_metrics>
            <rot_d50>
                <pga units="m/s**2">0.45</pga>
                <sa percent_damping="5.0" units="g">
                <value period="2.0">0.2</value>
            </rot_d50>
            <maximum_component>
            </maximum_component>
        </waveform_metrics>

        <station_metrics>
            <distances>
            <hypocentral units="km">100</hypocentral>
            <epicentral units="km">120</epicentral>
            </distances>
        </station_metrics>

        Args:
            xml_stream (str): Stream metrics XML string in format above.
            xml_station (str): Station metrics XML string in format above.
        Returns:
            StationSummary: Object summarizing all station metrics.

        """
        imtlist = gather_pgms()[0]
        root = etree.fromstring(xml_stream)
        pgms = {}
        channel_dict = {}
        damping = None
        for element in root.iter():
            etag = element.tag
            if etag == 'waveform_metrics':
                station_code = element.attrib['station_code']
                continue
            elif etag in imtlist:
                tdict = {}
                if etag in ['sa', 'fas']:
                    period = element.attrib['period']
                    if 'damping' in element.attrib:
                        damping = float(element.attrib['damping'])
                    imt = '%s(%s)' % (etag.upper(), period)
                else:
                    imt = etag.upper()
                for imc_element in element.getchildren():
                    imc = imc_element.tag.upper()
                    if imc in ['H1', 'H2', 'Z']:
                        if 'original_channel' in imc_element.attrib:
                            channel_dict[imc] = imc_element.attrib[
                                'original_channel']
                    value = float(imc_element.text)
                    tdict[imc] = value

                pgms[imt] = tdict
        station = cls.from_pgms(station_code, pgms)
        station._damping = damping
        station.channel_dict = channel_dict.copy()
        # extract info from station metrics, fill in metadata
        root = etree.fromstring(xml_station)  # station metrics element
        for element in root.iterchildren():
            if element.tag == 'distances':
                for dist_type in element.iterchildren():
                    station._distances[dist_type.tag] = float(dist_type.text)
            if element.tag == 'vs30':
                for vs30_type in element.iterchildren():
                    station._vs30[vs30_type.tag] = {
                        'value': float(vs30_type.text),
                        'column_header': vs30_type.attrib['column_header'],
                        'readme_entry': vs30_type.attrib['readme_entry'],
                        'units': vs30_type.attrib['units']
                    }
            if element.tag == 'back_azimuth':
                station._back_azimuth = float(element.text)

        return station
コード例 #22
0
    def __init__(self,
                 imts,
                 imcs,
                 timeseries,
                 bandwidth=None,
                 damping=None,
                 event=None,
                 smooth_type=None,
                 allow_nans=None):
        """Initialize MetricsController class.

        Args:
            imts (list):
                Intensity measurement types (string) to calculate.
            imcs (list):
                Intensity measurement components (string) to
                calculate.
            timeseries (StationStream):
                Stream of the timeseries data.
            bandwidth (float):
                Bandwidth for the smoothing calculation.
            damping (float):
                Damping for the oscillator calculation.
            event (ScalarEvent):
                Defines the focal time, geographic location, and magnitude of
                an earthquake hypocenter. Default is None.
            smooth_type (string):
                Currently not used, as konno_ohmachi is the only smoothing
                type.
            allow_nans (bool):
                Should nans be allowed in the smoothed spectra. If False, then
                the number of points in the FFT will be computed to ensure
                that nans will not result in the smoothed spectra.

        Raises:
            PGMException: Requires an event for radial_transfer imcs.
        """
        if not isinstance(imts, (list, np.ndarray)):
            imts = [imts]
        if not isinstance(imcs, (list, np.ndarray)):
            imcs = [imcs]
        self.imts = set(np.sort([imt.lower() for imt in imts]))
        self.clean_imts()
        self.imcs = set(np.sort([imc.lower() for imc in imcs]))
        if 'radial_transverse' in self.imcs and event is None:
            raise PGMException('MetricsController: Event is required for '
                               'radial_transverse imc')

        self.channel_dict = {}  # dictionary to serve as translator between
        self.timeseries = timeseries
        self.validate_stream()
        self.event = event
        self.config = get_config()
        self.damping = damping
        self.smooth_type = smooth_type
        self.bandwidth = bandwidth
        self.allow_nans = allow_nans
        if damping is None:
            self.damping = self.config['metrics']['sa']['damping']
        if smooth_type is None:
            self.smooth_type = self.config['metrics']['fas']['smoothing']
        if bandwidth is None:
            self.bandwidth = self.config['metrics']['fas']['bandwidth']
        if allow_nans is None:
            self.allow_nans = self.config['metrics']['fas']['allow_nans']
        self._available_imts, self._available_imcs = gather_pgms()
        self._step_sets = self.get_steps()
        imtstr = '_'.join(imts)
        if '_sa' in imtstr or imtstr.startswith('sa'):
            self._times = self._get_horizontal_time()
        else:
            self._times = None
        self.max_period = self._get_max_period()
        self.pgms = self.execute_steps()
コード例 #23
0
    def from_xml(cls, xml_stream, xml_station):
        """Instantiate a StationSummary from metrics XML stored in ASDF file.

        <waveform_metrics>
            <rot_d50>
                <pga units="m/s**2">0.45</pga>
                <sa percent_damping="5.0" units="g">
                <value period="2.0">0.2</value>
            </rot_d50>
            <maximum_component>
            </maximum_component>
        </waveform_metrics>

        <station_metrics>
            <hypocentral_distance units="km">100</hypocentral_distance>
            <epicentral_distance units="km">120</epicentral_distance>
        </station_metrics>

        Args:
            xml_stream (str): Stream metrics XML string in format above.
            xml_station (str): Station metrics XML string in format above.
        Returns:
            StationSummary: Object summarizing all station metrics.

        """
        imtlist = gather_pgms()[0]
        root = etree.fromstring(xml_stream)
        pgms = {}
        damping = None
        for element in root.iter():
            etag = element.tag
            if etag == 'waveform_metrics':
                station_code = element.attrib['station_code']
                continue
            elif etag in imtlist:
                tdict = {}
                if etag in ['sa', 'fas']:
                    period = element.attrib['period']
                    if 'damping' in element.attrib:
                        damping = float(element.attrib['damping'])
                    imt = '%s(%s)' % (etag.upper(), period)
                else:
                    imt = etag.upper()
                for imc_element in element.getchildren():
                    imc = imc_element.tag.upper()
                    value = float(imc_element.text)
                    tdict[imc] = value

                pgms[imt] = tdict
        station = cls.from_pgms(station_code, pgms)
        station._damping = damping
        # extract info from station metrics, fill in metadata
        root = etree.fromstring(xml_station)  # station metrics element
        for element in root.iter():
            etag = element.tag
            if etag == 'epicentral_distance':
                station._epicentral_distance = float(element.text)
            if etag == 'hypocentral_distance':
                station._hypocentral_distance = float(element.text)

        return station