コード例 #1
0
def get_exposure(oqparam):
    """
    Read the full exposure in memory and build a list of
    :class:`openquake.risklib.riskmodels.Asset` instances.

    :param oqparam:
        an :class:`openquake.commonlib.oqvalidation.OqParam` instance
    :returns:
        an :class:`Exposure` instance
    """
    out_of_region = 0
    if oqparam.region_constraint:
        region = wkt.loads(oqparam.region_constraint)
    else:
        region = None
    all_cost_types = set(oqparam.all_cost_types)
    fname = oqparam.inputs['exposure']
    exposure, assets_node = _get_exposure(fname, all_cost_types)
    relevant_cost_types = all_cost_types - set(['occupants'])
    asset_refs = set()
    ignore_missing_costs = set(oqparam.ignore_missing_costs)

    for idx, asset in enumerate(assets_node):
        values = {}
        deductibles = {}
        insurance_limits = {}
        retrofitteds = {}
        with context(fname, asset):
            asset_id = asset['id'].encode('utf8')
            if asset_id in asset_refs:
                raise read_nrml.DuplicatedID(asset_id)
            asset_refs.add(asset_id)
            exposure.asset_refs.append(asset_id)
            taxonomy = asset['taxonomy']
            if 'damage' in oqparam.calculation_mode:
                # calculators of 'damage' kind require the 'number'
                # if it is missing a KeyError is raised
                number = asset.attrib['number']
            else:
                # some calculators ignore the 'number' attribute;
                # if it is missing it is considered 1, since we are going
                # to multiply by it
                try:
                    number = asset['number']
                except KeyError:
                    number = 1
                else:
                    if 'occupants' in all_cost_types:
                        values['occupants_None'] = number
            location = asset.location['lon'], asset.location['lat']
            if region and not geometry.Point(*location).within(region):
                out_of_region += 1
                continue
            tagnode = getattr(asset, 'tags', None)
            if tagnode is not None:
                for item in tagnode.attrib.items():
                    valid.simple_id(item[0])  # name
                    valid.nice_string(item[1])  # value
                    exposure.assets_by_tag['%s-%s' % item].append(idx)
            exposure.assets_by_tag['taxonomy-' + taxonomy].append(idx)
        try:
            costs = asset.costs
        except AttributeError:
            costs = Node('costs', [])
        try:
            occupancies = asset.occupancies
        except AttributeError:
            occupancies = Node('occupancies', [])
        for cost in costs:
            with context(fname, cost):
                cost_type = cost['type']
                if cost_type in relevant_cost_types:
                    values[cost_type] = cost['value']
                    retrovalue = cost.attrib.get('retrofitted')
                    if retrovalue is not None:
                        retrofitteds[cost_type] = retrovalue
                    if oqparam.insured_losses:
                        deductibles[cost_type] = cost['deductible']
                        insurance_limits[cost_type] = cost['insuranceLimit']

        # check we are not missing a cost type
        missing = relevant_cost_types - set(values)
        if missing and missing <= ignore_missing_costs:
            logging.warn(
                'Ignoring asset %s, missing cost type(s): %s',
                asset_id, ', '.join(missing))
            for cost_type in missing:
                values[cost_type] = None
        elif missing and 'damage' not in oqparam.calculation_mode:
            # missing the costs is okay for damage calculators
            with context(fname, asset):
                raise ValueError("Invalid Exposure. "
                                 "Missing cost %s for asset %s" % (
                                     missing, asset_id))
        tot_occupants = 0
        for occupancy in occupancies:
            with context(fname, occupancy):
                exposure.time_events.add(occupancy['period'])
                occupants = 'occupants_%s' % occupancy['period']
                values[occupants] = occupancy['occupants']
                tot_occupants += values[occupants]
        if occupancies:  # store average occupants
            values['occupants_None'] = tot_occupants / len(occupancies)
        area = float(asset.attrib.get('area', 1))
        ass = riskmodels.Asset(
            idx, taxonomy, number, location, values, area,
            deductibles, insurance_limits, retrofitteds,
            exposure.cost_calculator)
        exposure.assets.append(ass)
    if region:
        logging.info('Read %d assets within the region_constraint '
                     'and discarded %d assets outside the region',
                     len(exposure.assets), out_of_region)
        if len(exposure.assets) == 0:
            raise RuntimeError('Could not find any asset within the region!')

    # sanity checks
    values = any(len(ass.values) + ass.number for ass in exposure.assets)
    assert values, 'Could not find any value??'
    return exposure
コード例 #2
0
ファイル: valid_test.py プロジェクト: oneconcern/oq-engine
 def test_simple_id(self):
     self.assertEqual(valid.simple_id('0'), '0')
     self.assertEqual(valid.simple_id('1-0'), '1-0')
     self.assertEqual(valid.simple_id('a_x'), 'a_x')
     with self.assertRaises(ValueError) as ctx:
         valid.simple_id('a x')
     self.assertEqual(
         str(ctx.exception),
         "Invalid ID 'a x': the only accepted chars are a-zA-Z0-9_-")
     with self.assertRaises(ValueError):
         valid.simple_id('0|1')
     with self.assertRaises(ValueError):
         valid.simple_id('à')
     with self.assertRaises(ValueError):
         valid.simple_id('\t')
     with self.assertRaises(ValueError):
         valid.simple_id('a' * 101)
コード例 #3
0
ファイル: valid_test.py プロジェクト: gem/oq-hazardlib
 def test_simple_id(self):
     self.assertEqual(valid.simple_id('0'), '0')
     self.assertEqual(valid.simple_id('1-0'), '1-0')
     self.assertEqual(valid.simple_id('a_x'), 'a_x')
     with self.assertRaises(ValueError) as ctx:
         valid.simple_id('a x')
     self.assertEqual(
         str(ctx.exception),
         "Invalid ID 'a x': the only accepted chars are a-zA-Z0-9_-")
     with self.assertRaises(ValueError):
         valid.simple_id('0|1')
     with self.assertRaises(ValueError):
         valid.simple_id('à')
     with self.assertRaises(ValueError):
         valid.simple_id('\t')
     with self.assertRaises(ValueError):
         valid.simple_id('a' * 101)