Ejemplo n.º 1
0
    def serialize(self, data):
        """
        Write a sequence of uniform hazard spectra to the specified file.

        :param data:
            Iterable of UHS data. Each datum must be an object with the
            following attributes:

            * imls: A sequence of Itensity Measure Levels
            * location: An object representing the location of the curve; must
              have `x` and `y` to represent lon and lat, respectively.
        """
        gml_ns = nrml.SERIALIZE_NS_MAP['gml']

        with nrml.NRMLFile(self.dest, 'w') as fh:
            root = et.Element('nrml')

            uh_spectra = et.SubElement(root, 'uniformHazardSpectra')

            _set_metadata(uh_spectra, self.metadata, _ATTR_MAP)

            periods_elem = et.SubElement(uh_spectra, 'periods')
            periods_elem.text = ' '.join(
                [str(x) for x in self.metadata['periods']])

            for uhs in data:
                uhs_elem = et.SubElement(uh_spectra, 'uhs')
                gml_point = et.SubElement(uhs_elem, '{%s}Point' % gml_ns)
                gml_pos = et.SubElement(gml_point, '{%s}pos' % gml_ns)
                gml_pos.text = '%s %s' % (uhs.location.x, uhs.location.y)
                imls_elem = et.SubElement(uhs_elem, 'IMLs')
                imls_elem.text = ' '.join([str(x) for x in uhs.imls])

            nrml.write(list(root), fh)
Ejemplo n.º 2
0
    def serialize(self, data):
        """
        :param data:

            A sequence of data where each datum has the following attributes:

            * matrix: N-dimensional numpy array containing the disaggregation
              histogram.
            * dim_labels: A list of strings which label the dimensions of a
              given histogram. For example, for a Magnitude-Distance-Epsilon
              histogram, we would expect `dim_labels` to be
              ``['Mag', 'Dist', 'Eps']``.
            * poe: The disaggregation Probability of Exceedance level for which
              these results were produced.
            * iml: Intensity measure level, interpolated from the source hazard
              curve at the given ``poe``.
        """

        with nrml.NRMLFile(self.dest, 'w') as fh:
            root = et.Element('nrml')

            diss_matrices = et.SubElement(root, 'disaggMatrices')

            _set_metadata(diss_matrices, self.metadata, _ATTR_MAP)

            transform = lambda val: ', '.join(map(scientificformat, val))
            _set_metadata(diss_matrices,
                          self.metadata,
                          self.BIN_EDGE_ATTR_MAP,
                          transform=transform)

            for result in data:
                diss_matrix = et.SubElement(diss_matrices, 'disaggMatrix')

                # Check that we have bin edges defined for each dimension label
                # (mag, dist, lon, lat, eps, TRT)
                for label in result.dim_labels:
                    bin_edge_attr = self.DIM_LABEL_TO_BIN_EDGE_MAP.get(label)
                    assert self.metadata.get(bin_edge_attr) is not None, (
                        "Writer is missing '%s' metadata" % bin_edge_attr)

                result_type = ','.join(result.dim_labels)
                diss_matrix.set('type', result_type)

                dims = ','.join(str(x) for x in result.matrix.shape)
                diss_matrix.set('dims', dims)

                diss_matrix.set('poE', scientificformat(result.poe))
                diss_matrix.set('iml', scientificformat(result.iml))

                for idxs, value in numpy.ndenumerate(result.matrix):
                    prob = et.SubElement(diss_matrix, 'prob')

                    index = ','.join([str(x) for x in idxs])
                    prob.set('index', index)
                    prob.set('value', scientificformat(value))

            nrml.write(list(root), fh)
Ejemplo n.º 3
0
    def serialize(self, data):
        """
        Write the hazard curves to the given as GeoJSON. The GeoJSON format
        is customized to contain various bits of metadata.

        See :meth:`HazardCurveXMLWriter.serialize` for expected input.
        """
        oqmetadata = {}
        for key, value in self.metadata.items():
            if key == 'imls':
                oqmetadata['IMLs'] = value
            if value is not None:
                if key == 'imls':
                    oqmetadata['IMLs'] = value
                else:
                    oqmetadata[_ATTR_MAP.get(key)] = scientificformat(value)

        features = []
        feature_coll = {
            'type': 'FeatureCollection',
            'features': features,
            'oqtype': 'HazardCurve',
            'oqnrmlversion': '0.4',
            'oqmetadata': oqmetadata,
        }
        for hc in data:
            poes = list(hc.poes)
            lon = hc.location.x
            lat = hc.location.y

            feature = {
                'type': 'Feature',
                'geometry': {
                    'type': 'Point',
                    'coordinates': [float(lon), float(lat)],
                },
                'properties': {
                    'poEs': list(poes)
                },
            }
            features.append(feature)

        with nrml.NRMLFile(self.dest, 'w') as fh:
            json.dump(feature_coll,
                      fh,
                      sort_keys=True,
                      indent=4,
                      separators=(',', ': '))
Ejemplo n.º 4
0
    def serialize(self, curve_set):
        """
        Write a set of sequence of hazard curves to the specified file.
        :param curve_set:

           Iterable over sequence of curves. Each element returned by
           the iterable is an iterable suitable to be used by the
           :meth:`serialize` of the class
           :class:`openquake.commonlib.hazard_writers.HazardCurveXMLWriter`
        """
        with nrml.NRMLFile(self.dest, 'w') as fh:
            root = et.Element('nrml')
            for metadata, curve_data in zip(self.metadata_set, curve_set):
                writer = HazardCurveXMLWriter(self.dest, **metadata)
                writer.add_hazard_curves(root, metadata, curve_data)
            nrml.write(list(root), fh)
Ejemplo n.º 5
0
    def serialize(self, data):
        """
        Write a sequence of hazard curves to the specified file.

        :param data:
            Iterable of hazard curve data. Each datum must be an object with
            the following attributes:

            * poes: A list of probability of exceedence values (floats).
            * location: An object representing the location of the curve; must
              have `x` and `y` to represent lon and lat, respectively.
        """
        with nrml.NRMLFile(self.dest, 'w') as fh:
            root = et.Element('nrml')
            self.add_hazard_curves(root, self.metadata, data)
            nrml.write(list(root), fh)
Ejemplo n.º 6
0
    def serialize(self, data):
        """
        Serialize hazard map data to XML.

        See :meth:`HazardMapWriter.serialize` for details about the expected
        input.
        """
        with nrml.NRMLFile(self.dest, 'w') as fh:
            root = et.Element('nrml')
            hazard_map = et.SubElement(root, 'hazardMap')
            _set_metadata(hazard_map, self.metadata, _ATTR_MAP)

            for lon, lat, iml in data:
                node = et.SubElement(hazard_map, 'node')
                node.set('lon', str(lon))
                node.set('lat', str(lat))
                node.set('iml', str(iml))

            nrml.write(list(root), fh)
Ejemplo n.º 7
0
    def serialize(self, data):
        """
        Serialize hazard map data to GeoJSON.

        See :meth:`HazardMapWriter.serialize` for details about the expected
        input.
        """
        oqmetadata = {}
        for key, value in self.metadata.items():
            if value is not None:
                oqmetadata[_ATTR_MAP.get(key)] = str(value)

        features = []
        feature_coll = {
            'type': 'FeatureCollection',
            'features': features,
            'oqtype': 'HazardMap',
            'oqnrmlversion': '0.4',
            'oqmetadata': oqmetadata,
        }

        for lon, lat, iml in data:
            feature = {
                'type': 'Feature',
                'geometry': {
                    'type': 'Point',
                    'coordinates': [float(lon), float(lat)],
                },
                'properties': {
                    'iml': float(iml)
                },
            }
            features.append(feature)

        with nrml.NRMLFile(self.dest, 'w') as fh:
            json.dump(feature_coll,
                      fh,
                      sort_keys=True,
                      indent=4,
                      separators=(',', ': '))
Ejemplo n.º 8
0
    def serialize(self, data):
        """
        Serialize a collection of stochastic event sets to XML.

        :param data:
            An iterable of "SES" ("Stochastic Event Set") objects.
            Each "SES" object should:

            * have an `investigation_time` attribute
            * have an `ordinal` attribute
            * be iterable, yielding a sequence of "rupture" objects

            Each rupture" should have the following attributes:
            * `tag`
            * `magnitude`
            * `strike`
            * `dip`
            * `rake`
            * `tectonic_region_type`
            * `is_from_fault_source` (a `bool`)
            * `is_multi_surface` (a `bool`)
            * `lons`
            * `lats`
            * `depths`

            If `is_from_fault_source` is `True`, the rupture originated from a
            simple or complex fault sources. In this case, `lons`, `lats`, and
            `depths` should all be 2D arrays (of uniform shape). These
            coordinate triples represent nodes of the rupture mesh.

            If `is_from_fault_source` is `False`, the rupture originated from a
            point or area source. In this case, the rupture is represented by a
            quadrilateral planar surface. This planar surface is defined by 3D
            vertices. In this case, the rupture should have the following
            attributes:

            * `top_left_corner`
            * `top_right_corner`
            * `bottom_right_corner`
            * `bottom_left_corner`

            Each of these should be a triple of `lon`, `lat`, `depth`.

            If `is_multi_surface` is `True`, the rupture originated from a
            multi-surface source. In this case, `lons`, `lats`, and `depths`
            should have uniform length. The length should be a multiple of 4,
            where each segment of 4 represents the corner points of a planar
            surface in the following order:

            * top left
            * top right
            * bottom left
            * bottom right

            Each of these should be a triple of `lon`, `lat`, `depth`.
        """
        with nrml.NRMLFile(self.dest, 'w') as fh:
            root = et.Element('nrml')
            ses_container = et.SubElement(root, 'stochasticEventSetCollection')
            ses_container.set(SM_TREE_PATH, self.sm_lt_path)
            for ses in data:
                ruptures = list(ses)
                if not ruptures:  # empty SES, don't export it
                    continue
                ses_elem = et.SubElement(ses_container, 'stochasticEventSet')
                ses_elem.set('id', str(ses.ordinal or 1))
                ses_elem.set('investigationTime', str(ses.investigation_time))
                for rupture in ruptures:
                    rupture_to_element(rupture, ses_elem)

            nrml.write(list(root), fh)