def test_xml(self): # can read and write a .xml file converted into a Node object xmlfile = io.StringIO(u"""\ <root> <general> <a>1</a> <b>2</b> </general> <section1 param="xxx" /> <section2 param="yyy" /> </root> """) node = n.node_from_xml(xmlfile) outfile = io.BytesIO() n.node_to_xml(node, outfile) self.assertEqual(outfile.getvalue(), """\ <?xml version="1.0" encoding="utf-8"?> <root> <general> <a> 1 </a> <b> 2 </b> </general> <section1 param="xxx"/> <section2 param="yyy"/> </root> """)
def test_node_factory(self): class ValidNode(n.LiteralNode): "ValidNode test implementation. " validators = dict(a=float, b=int) self.assertEqual(ValidNode.__doc__, '''\ ValidNode test implementation. Known validators: a: `float` b: `int`''') xmlfile = io.StringIO(u"""\ <root> <general> <a>1</a> <b>2</b> </general> <section1 param="xxx" /> <section2 param="yyy" /> </root> """) node = n.node_from_xml(xmlfile, ValidNode) self.assertEqual(~node.general.a, 1.0) self.assertEqual(~node.general.b, 2) self.assertEqual(node.section1['param'], 'xxx') self.assertEqual( n.to_literal(node), ( 'root', {}, None, [('general', {}, None, [('a', {}, 1.0, []), ('b', {}, 2, [])]), ('section1', {'param': 'xxx'}, None, []), ('section2', {'param': 'yyy'}, None, [])]) )
def _parse_lt(self): # do the parsing, called at instantiation time to populate .values fkeys = [] nrml = node_from_xml(self.fname) for branching_level in nrml.logicTree: if len(branching_level) > 1: raise InvalidLogicTree( 'Branching level %s has multiple branchsets' % branching_level['branchingLevelID']) for branchset in branching_level: if branchset['uncertaintyType'] != 'gmpeModel': raise InvalidLogicTree( 'only uncertainties of type ' '"gmpeModel" are allowed in gmpe logic tree') fkey = branchset.attrib.get(self.branchset_filter) if fkey: fkeys.append(fkey) if fkey in self.filter_keys: weights = [] for branch in branchset: weight = Decimal(branch.uncertaintyWeight.text) weights.append(weight) branch_id = branch['branchID'] uncertainty = branch.uncertaintyModel.text.strip() self.validate_gsim(uncertainty) self.values[fkey].append(uncertainty) yield BranchTuple( branchset, branch_id, uncertainty, weight) assert sum(weights) == 1, weights if len(fkeys) > len(set(fkeys)): raise InvalidLogicTree('Found duplicated %s=%s' % ( self.branchset_filter, fkeys))
def test_node_factory(self): class ValidNode(n.LiteralNode): "ValidNode test implementation. " validators = dict(a=float, b=int) self.assertEqual( ValidNode.__doc__, '''\ ValidNode test implementation. Known validators: a: `float` b: `int`''') xmlfile = io.StringIO(u"""\ <root> <general> <a>1</a> <b>2</b> </general> <section1 param="xxx" /> <section2 param="yyy" /> </root> """) node = n.node_from_xml(xmlfile, ValidNode) self.assertEqual(~node.general.a, 1.0) self.assertEqual(~node.general.b, 2) self.assertEqual(node.section1['param'], 'xxx') self.assertEqual( n.to_literal(node), ('root', {}, None, [('general', {}, None, [('a', {}, 1.0, []), ('b', {}, 2, [])]), ('section1', { 'param': 'xxx' }, None, []), ('section2', { 'param': 'yyy' }, None, [])]))
def test_xml(self): # can read and write a .xml file converted into a Node object xmlfile = io.StringIO(u"""\ <root> <general> <a>1</a> <b>2</b> </general> <section1 param="xxx" /> <section2 param="yyy" /> </root> """) node = n.node_from_xml(xmlfile) outfile = io.BytesIO() n.node_to_xml(node, outfile) self.assertEqual( outfile.getvalue(), """\ <?xml version="1.0" encoding="utf-8"?> <root> <general> <a> 1 </a> <b> 2 </b> </general> <section1 param="xxx"/> <section2 param="yyy"/> </root> """)
def read_file(self, identifier, mfd_spacing=0.1, simple_mesh_spacing=1.0, complex_mesh_spacing=4.0, area_discretization=10.): """ Reads in the source model in returns an instance of the :class: hmtk.sourcs.source_model.mtkSourceModel """ node_set = node_from_xml(self.input_file)[0] source_model = mtkSourceModel(identifier, name=node_set.attrib["name"]) for node in node_set: if "pointSource" in node.tag: source_model.sources.append( parse_point_source_node(node, mfd_spacing)) elif "areaSource" in node.tag: source_model.sources.append( parse_area_source_node(node, mfd_spacing)) elif "simpleFaultSource" in node.tag: source_model.sources.append( parse_simple_fault_node(node, mfd_spacing, simple_mesh_spacing)) elif "complexFaultSource" in node.tag: source_model.sources.append( parse_complex_fault_node(node, mfd_spacing, complex_mesh_spacing)) else: print "Source typology %s not recognised - skipping!" % node.tag return source_model
def __init__(self, fname, tectonic_region_types, ltnode=None): self.fname = fname self.tectonic_region_types = sorted(tectonic_region_types) trts = self.tectonic_region_types if len(trts) > len(set(trts)): raise ValueError( 'The given tectonic region types are not distinct: %s' % ','.join(self.tectonic_region_types)) self.values = collections.defaultdict(list) # {trt: gsims} self._ltnode = ltnode or node_from_xml(fname).logicTree self.all_trts, self.branches = self._build_trts_branches() if tectonic_region_types and not self.branches: raise InvalidLogicTree('Could not find branches with attribute ' "'applyToTectonicRegionType' in %s" % set(tectonic_region_types))
def __init__(self, fname, tectonic_region_types, ltnode=None): self.fname = fname self.tectonic_region_types = sorted(tectonic_region_types) trts = self.tectonic_region_types if len(trts) > len(set(trts)): raise ValueError( 'The given tectonic region types are not distinct: %s' % ','.join(self.tectonic_region_types)) self.values = collections.defaultdict(list) # {trt: gsims} self._ltnode = ltnode or node_from_xml(fname).logicTree self.all_trts, self.branches = self._build_trts_branches() if tectonic_region_types and not self.branches: raise InvalidLogicTree( 'Could not find branches with attribute ' "'applyToTectonicRegionType' in %s" % set(tectonic_region_types))
def fix_source_node(node): if node.tag.endswith('complexFaultSource'): geom = node.complexFaultGeometry top = geom.faultTopEdge intermediate = [edge for edge in geom.getnodes('intermediateEdge')] bottom = geom.faultBottomEdge edges = map(make_edge, [top] + intermediate + [bottom]) try: ComplexFaultSurface.from_fault_data(edges, mesh_spacing=4.) except ValueError as excp: if AKI_RICH_ERR_MSG in str(excp): print str(excp) print 'Reverting edges ...' reverse(geom.faultTopEdge) reverse(geom.faultBottomEdge) elif WRONG_ORDER_ERR_MSG in str(excp): print str(excp) print 'reverting bottom edge ...' reverse(geom.faultBottomEdge) else: raise if __name__ == '__main__': fname = sys.argv[1] src_model = node_from_xml(fname).sourceModel for node in src_model: fix_source_node(node) with open(fname, 'w') as f: nrml.write([src_model], f)
def from_nrml(cls, nrmlfile): """ Return a specialized Converter instance from a file or filename """ [node] = node_from_xml(nrmlfile) return cls.from_node(node)