Beispiel #1
0
def get_rlzs_assoc(oqparam):
    """
    Extract the GSIM realizations from the gsim_logic_tree file, if present,
    or build a single realization from the gsim attribute. It is only defined
    for the scenario calculators.

    :param oqparam:
        an :class:`openquake.commonlib.oqvalidation.OqParam` instance
    """
    if 'gsim_logic_tree' in oqparam.inputs:
        gsim_lt = get_gsim_lt(oqparam, [])
        if len(gsim_lt.values) != 1:
            gsim_file = os.path.join(oqparam.base_path,
                                     oqparam.inputs['gsim_logic_tree'])
            raise InvalidFile(
                'The gsim logic tree file %s must contain a single tectonic '
                'region type, found %s instead ' %
                (gsim_file, list(gsim_lt.values)))
        trt = gsim_lt.values
        rlzs = sorted(get_gsim_lt(oqparam, trt))
    else:
        rlzs = [
            logictree.Realization(value=(str(oqparam.gsim), ),
                                  weight=1,
                                  lt_path=('', ),
                                  ordinal=0,
                                  lt_uid=('@', ))
        ]
    return logictree.RlzsAssoc(rlzs)
Beispiel #2
0
    def pre_execute(self):
        """
        Read the curves and build the riskinputs.
        """
        super(ClassicalDamageCalculator, self).pre_execute()

        logging.info('Reading hazard curves from CSV')
        sites, hcurves_by_imt = readinput.get_sitecol_hcurves(self.oqparam)

        with self.monitor('assoc_assets_sites'):
            sitecol, assets_by_site = self.assoc_assets_sites(sites)
        num_assets = sum(len(assets) for assets in assets_by_site)
        num_sites = len(sitecol)
        logging.info('Associated %d assets to %d sites', num_assets, num_sites)

        logging.info('Preparing the risk input')
        self.riskinputs = self.build_riskinputs({
            (0, 'FromFile'): hcurves_by_imt
        })
        fake_rlz = logictree.Realization(value=('FromFile', ),
                                         weight=1,
                                         lt_path=('', ),
                                         ordinal=0,
                                         lt_uid=('*', ))
        self.rlzs_assoc = logictree.RlzsAssoc([fake_rlz])
Beispiel #3
0
 def __fromh5__(self, dic, attrs):
     # TODO: this is called more times than needed, maybe we should cache it
     sm_data = dic['sm_data']
     vars(self).update(attrs)
     self.source_model_lt = dic['source_model_lt']
     self.gsim_lt = dic['gsim_lt']
     self.sm_rlzs = []
     for sm_id, rec in enumerate(sm_data):
         path = tuple(str(decode(rec['path'])).split('_'))
         sm = logictree.Realization(rec['name'], rec['weight'], sm_id, path,
                                    rec['samples'], rec['offset'])
         self.sm_rlzs.append(sm)
Beispiel #4
0
def get_gmfs(calc):
    """
    :param calc: a ScenarioDamage or ScenarioRisk calculator
    :returns: a dictionary of gmfs
    """
    if 'gmfs' in calc.oqparam.inputs:  # from file
        logging.info('Reading gmfs from file')
        sitecol, calc.tags, gmfs_by_imt = readinput.get_gmfs(calc.oqparam)
        calc.save_params()  # save number_of_ground_motion_fields and sites

        # reduce the gmfs matrices to the filtered sites
        for imt in calc.oqparam.imtls:
            gmfs_by_imt[imt] = gmfs_by_imt[imt][sitecol.indices]

        logging.info('Preparing the risk input')
        fake_rlz = logictree.Realization(
            value=('FromFile',), weight=1, lt_path=('',),
            ordinal=0, lt_uid=('*',))
        calc.rlzs_assoc = logictree.RlzsAssoc([fake_rlz])
        return sitecol, {(0, 'FromFile'): gmfs_by_imt}

    # else from rupture
    gmf = calc.datastore['gmfs/col00'].value
    # NB: if the hazard site collection has N sites, the hazard
    # filtered site collection for the nonzero GMFs has N' <= N sites
    # whereas the risk site collection associated to the assets
    # has N'' <= N' sites
    if calc.datastore.parent:
        haz_sitecol = calc.datastore.parent['sitecol']  # N' values
    else:
        haz_sitecol = calc.sitecol
    risk_indices = set(calc.sitecol.indices)  # N'' values
    N = len(haz_sitecol.complete)
    imt_dt = numpy.dtype([(imt, float) for imt in calc.oqparam.imtls])
    gmf_by_idx = general.groupby(gmf, lambda row: row['idx'])
    R = len(gmf_by_idx)
    # build a matrix N x R for each GSIM realization
    gmfs = {(trt_id, gsim): numpy.zeros((N, R), imt_dt)
            for trt_id, gsim in calc.rlzs_assoc}
    for rupid, rows in sorted(gmf_by_idx.items()):
        assert len(haz_sitecol.indices) == len(rows), (
            len(haz_sitecol.indices), len(rows))
        for sid, gmv in zip(haz_sitecol.indices, rows):
            if sid in risk_indices:
                for trt_id, gsim in gmfs:
                    gmfs[trt_id, gsim][sid, rupid] = gmv[gsim]
    return haz_sitecol, gmfs
Beispiel #5
0
 def fake(cls, gsimlt=None):
     """
     :returns:
         a fake `FullLogicTree` instance with the given gsim logic tree
         object; if None, builds automatically a fake gsim logic tree
     """
     gsim_lt = gsimlt or logictree.GsimLogicTree.from_('[FromFile]')
     fakeSM = logictree.Realization('scenario',
                                    weight=1,
                                    ordinal=0,
                                    lt_path='b1',
                                    samples=1)
     info = object.__new__(cls)
     info.source_model_lt = logictree.SourceModelLogicTree.fake()
     info.gsim_lt = gsim_lt
     info.sm_rlzs = [fakeSM]
     return info
Beispiel #6
0
def read_gmfs_from_csv(calc):
    """
    :param calc: a ScenarioDamage or ScenarioRisk calculator
    :returns: riskinputs
    """
    logging.info('Reading hazard curves from CSV')
    gmfs_by_imt = readinput.get_gmfs(calc.oqparam, calc.sitecol.complete)

    # reduce the gmfs matrices to the filtered sites
    for imt in calc.oqparam.imtls:
        gmfs_by_imt[imt] = gmfs_by_imt[imt][calc.sitecol.indices]

    num_assets = calc.count_assets()
    num_sites = len(calc.sitecol)
    logging.info('Associated %d assets to %d sites', num_assets, num_sites)

    logging.info('Preparing the risk input')
    fake_rlz = logictree.Realization(value=('FromCsv', ),
                                     weight=1,
                                     lt_path=('', ),
                                     ordinal=0,
                                     lt_uid=('*', ))
    calc.rlzs_assoc = logictree.RlzsAssoc([fake_rlz])
    return {(0, 'FromCsv'): gmfs_by_imt}
Beispiel #7
0
def read_gmfs_from_file(calc):
    """
    :param calc: a ScenarioDamage or ScenarioRisk calculator
    :returns: riskinputs
    """
    logging.info('Reading gmfs from file')
    try:
        sitecol = calc.sitecol.complete
    except KeyError:
        sitecol = None
    calc.sitecol, calc.tags, gmfs_by_imt = readinput.get_gmfs(
        calc.oqparam, sitecol)
    calc.save_params()  # save number_of_ground_motion_fields and sites

    # reduce the gmfs matrices to the filtered sites
    for imt in calc.oqparam.imtls:
        gmfs_by_imt[imt] = gmfs_by_imt[imt][calc.sitecol.indices]

    logging.info('Preparing the risk input')
    fake_rlz = logictree.Realization(
        value=('FromFile',), weight=1, lt_path=('',),
        ordinal=0, lt_uid=('*',))
    calc.rlzs_assoc = logictree.RlzsAssoc([fake_rlz])
    return {(0, 'FromFile'): gmfs_by_imt}