def serialize(self, rm):
        """
        Serialize rupture model to NRML file
        """
        srcm = SourceModelXMLWriter(None)
        with NRMLFile(self.dest, 'w') as fh:
            root = etree.Element(
                'nrml', nsmap=SERIALIZE_NS_MAP
            )

            if isinstance(rm, ComplexFaultRuptureModel):
                rm_elem = etree.SubElement(root, 'complexFaultRupture')
                mag = etree.SubElement(rm_elem, 'magnitude')
                mag.text = str(rm.magnitude)
                rake = etree.SubElement(rm_elem, 'rake')
                rake.text = str(rm.rake)
                hypocenter = etree.SubElement(rm_elem, 'hypocenter',
                    attrib={'lon': rm.hypocenter[0], 'lat': rm.hypocenter[1],
                    'depth': rm.hypocenter[2]})
                srcm._append_complex_fault_geom(rm_elem, rm.geometry)
            elif isinstance(rm, SimpleFaultRuptureModel):
                rm_elem = etree.SubElement(root, 'simpleFaultRupture')
                mag = etree.SubElement(rm_elem, 'magnitude')
                mag.text = str(rm.magnitude)
                rake = etree.SubElement(rm_elem, 'rake')
                rake.text = str(rm.rake)
                hypocenter = etree.SubElement(rm_elem, 'hypocenter',
                    attrib={'lon': rm.hypocenter[0], 'lat': rm.hypocenter[1],
                    'depth': rm.hypocenter[2]})
                srcm._append_simple_fault_geom(rm_elem, rm.geometry)
            else:
                raise ValueError('Rupture model %s not recognized' % rm.__class__)

            fh.write(etree.tostring(root, pretty_print=True,
                xml_declaration=True, encoding='UTF-8'))
Esempio n. 2
0
def convert(sourceFileName, targetFileName, sourceType, nameMappings):
    deserializedShp = convertShapeFileToNrml(sourceFileName, targetFileName, nameMappings, sourceType)

    writer = SourceModelXMLWriter(targetFileName)
    writer.serialize(deserializedShp)

    target_path = os.path.join(os.path.dirname(targetFileName), 'source_model_logic_tree.xml')
    writeSourceModelTree(target_path, os.path.basename(targetFileName))
Esempio n. 3
0
    def write_to_nrml(self,
                      output_filename,
                      mmin,
                      upper_depth=0.,
                      lower_depth=50.,
                      source_model_name="POINT SOURCE MODEL",
                      trt=DEFAULT_TRT,
                      msr=DEFAULT_MSR,
                      aspect=ASPECT_RATIO,
                      hdd=None):
        """
        Converts the smoothed seismicity data to a set of oq-nrml point
        sources and writes to the output file
        """
        writer = SourceModelXMLWriter(output_filename)
        source_model = models.SourceModel(source_model_name)
        source_model.sources = []

        print 'Building source model ...'
        for iloc, row in enumerate(self.data):
            # Geometry
            #trt =(row[18])

            geom = models.PointGeometry(
                "POINT (%9.4f %9.4f)" % (row[0], row[1]), upper_depth,
                lower_depth)
            if hdd:
                src_hdd = []
                #each tuple with probality and depth
                for d in hdd:
                    src_hdd.append(models.HypocentralDepth(d[1], d[0]))
            else:
                src_hdd = [models.HypocentralDepth(Decimal("1.0"), row[2])]

            npd = [models.NodalPlane(1, 0, 90, 0)]
            #if row[5]==1:
            #    npd = [models.NodalPlane(row[6], row[7], row[9], row[8])]
            #elif row[5] ==2:
            #    npd = [models.NodalPlane(row[6], row[7], row[9], row[8]), models.NodalPlane(row[10], row[11], row[13], row[12])]
            #else:
            #    npd =  [models.NodalPlane(row[6], row[7], row[9], row[8]), models.NodalPlane(row[10], row[11], row[13], row[12]), models.NodalPlane(row[14], row[15], row[17], row[16])]

            source_model.sources.append(
                models.PointSource(str(iloc), "PNT_%s" % str(iloc), trt,
                                   geom, msr, aspect,
                                   self.get_mfd(iloc, row,
                                                mmin), npd, src_hdd))
        print 'done!'
        print 'Writing to file ...'
        writer.serialize(source_model)
        print 'done!'
def convert(sourceFileName, targetFileName, sourceType,
            nameMappings={'A': 'aGRval', 'B': 'bGRval', 'ID': 'EMME_IDAS', 'NAME': 'CODE'}):
    deserializedShps = convertShapeFileToNrml(sourceFileName, targetFileName, nameMappings, sourceType)

    fileName, ext = os.path.splitext(targetFileName)
    sourceModels = list()
    for i in xrange(len(deserializedShps)):
        deserializedShp = deserializedShps[i][0]
        shapeFileName = fileName + '_' + str(i) + ext
        writer = SourceModelXMLWriter(shapeFileName)
        writer.serialize(deserializedShp)
        sourceModels.append((os.path.basename(shapeFileName), deserializedShps[i][1]))

    writeSourceModelTree(os.path.join(os.path.dirname(targetFileName), 'source_model_logic_tree.xml'), sourceModels)
def shp2nrml(source_models, output_file):
    """
    Convert source model ESRI shapefiles to NRML.
    """
    srcs = []
    for source_model in source_models:
        sf = shapefile.Reader(source_model)

        for shape, record in zip(sf.shapes(), sf.records()):
            srcs.append(create_nrml_source(shape, record, sf.fields))

    srcm = SourceModel(sources=srcs)

    smw = SourceModelXMLWriter('%s.xml' % output_file)
    smw.serialize(srcm)
Esempio n. 6
0
    def serialise_to_nrml(self, filename, use_defaults=False):
        """
        Writes the source model to a nrml source model file given by the
        filename

        :param str filename:
            Path to output file

        :param bool use_defaults:
            Boolean to indicate whether to use default values (True) or not.
            If set to False, ValueErrors will be raised when an essential
            attribute is missing.
        """
        output_model = models.SourceModel(name=self.name, sources=[])

        for source in self.sources:
            output_model.sources.append(source.create_oqnrml_source(use_defaults))

        writer = SourceModelXMLWriter(filename)
        writer.serialize(output_model)
Esempio n. 7
0
    def serialise_to_nrml(self, filename, use_defaults=False):
        '''
        Writes the source model to a nrml source model file given by the 
        filename

        :param str filename:
            Path to output file

        :param bool use_defaults:
            Boolean to indicate whether to use default values (True) or not.
            If set to False, ValueErrors will be raised when an essential
            attribute is missing.
        '''
        output_model = models.SourceModel(name=self.name, sources=[])

        for source in self.sources:
            output_model.sources.append(
                source.create_oqnrml_source(use_defaults))

        writer = SourceModelXMLWriter(filename)
        writer.serialize(output_model)
    converter = NrmlHazardlibConverter(
        investigation_time=50, rupture_mesh_spacing=4,
        width_of_mfd_bin=0.2, area_source_discretization=10)

    srcm = SourceModelParser(sys.argv[1]).parse()

    srcs = []
    for src in srcm:
        if isinstance(src, ComplexFaultSource):
            try:
                hazlib_src = converter(src)
            except ValueError, excp:
                print str(excp)
                print 'Reverting edges ...'
                top_edge = _revert_edge(src.geometry.top_edge_wkt)
                bottom_edge = _revert_edge(src.geometry.bottom_edge_wkt)

                # replace old edges with reverted edges
                src.geometry.top_edge_wkt = top_edge
                src.geometry.bottom_edge_wkt = bottom_edge
            finally:
                srcs.append(src)
        else:
            srcs.append(src)

    new_srcm = SourceModel(srcm.name, srcs)

    w = SourceModelXMLWriter(sys.argv[1])
    w.serialize(new_srcm)