:param dstore: datastore for an event based risk calculation
    :returns: a LossCurvesMapsBuilder instance
506657
def get_loss_builder(dstore, return_periods=None, loss_dt=None):
    
    oq = dstore['oqparam']
    weights = dstore['weights'][:, 0]
    eff_time = oq.investigation_time * oq.ses_per_logic_tree_path
    num_events = countby(dstore['events'].value, 'rlz')
    periods = return_periods or oq.return_periods or scientific.return_periods(
        eff_time, max(num_events.values()))
    return scientific.LossCurvesMapsBuilder(
        oq.conditional_loss_poes, numpy.array(periods),
        loss_dt or oq.loss_dt(), weights, num_events,
        eff_time, oq.risk_investigation_time)
1099298
def get_assets(dstore):
    
    assetcol = dstore['assetcol']
    tagnames = sorted(assetcol.tagnames)
    tag = {t: getattr(assetcol.tagcol, t) for t in tagnames}
    dtlist = [('asset_ref', (bytes, 100))]
    for tagname in tagnames:
        dtlist.append((tagname, (bytes, 100)))
    dtlist.extend([('lon', F32), ('lat', F32)])
    asset_data = []
    for aref, a in zip(assetcol.asset_refs, assetcol.array):
        tup = tuple(b'"%s"' % tag[t][a[t]].encode('utf-8') for t in tagnames)
        asset_data.append((aref,) + tup + (a['lon'], a['lat']))
    return numpy.array(asset_data, dtlist)
664765
def build_loss_tables(dstore):
    
    oq = dstore['oqparam']
    L = len(oq.loss_dt().names)
    R = dstore['csm_info'].get_num_rlzs()
    serials = dstore['ruptures']['serial']
    idx_by_ser = dict(zip(serials, range(len(serials))))
    tbl = numpy.zeros((len(serials), L), F32)
    lbr = numpy.zeros((R, L), F32)  # losses by rlz
    for rec in dstore['losses_by_event'].value:  # call .value for speed
        idx = idx_by_ser[rec['eid'] // TWO32]
        tbl[idx] += rec['loss']
        lbr[rec['rlzi']] += rec['loss']
    return tbl, lbr
252205
def extract_src_loss_table(dstore, loss_type):
    
    oq = dstore['oqparam']
    li = oq.lti[loss_type]
    source_ids = dstore['source_info']['source_id']
    idxs = dstore['ruptures'].value[['srcidx', 'grp_id']]
    losses = dstore['rup_loss_table'][:, li]
    slt = numpy.zeros(len(source_ids), [('grp_id', U32), (loss_type, F32)])
    for loss, (srcidx, grp_id) in zip(losses, idxs):
        slt[srcidx][loss_type] += loss
        slt[srcidx]['grp_id'] = grp_id
    slt = util.compose_arrays(source_ids, slt, 'source_id')
    slt.sort(order=loss_type)
    return slt[::-1]
989281
def extract_exposure_metadata(dstore, what):
    
    dic = {}
    dic1, dic2 = dstore['assetcol/tagcol'].__toh5__()
    dic.update(dic1)
    dic.update(dic2)
    if 'asset_risk' in dstore:
        dic['multi_risk'] = sorted(
            set(dstore['asset_risk'].dtype.names) -
            set(dstore['assetcol/array'].dtype.names))
    names = [name for name in dstore['assetcol/array'].dtype.names
             if name.startswith(('value-', 'number', 'occupants_'))
             and not name.endswith('_None')]
    return ArrayWrapper(numpy.array(names), dic)
793357
def zinterstore(self, dest, keys, aggregate=None):
        
        return self._zaggregate('ZINTERSTORE', dest, keys, aggregate)
285469
def extract_hcurves(dstore, what):
    
    info = get_info(dstore)
    if what == '':  # npz exports for QGIS
        sitecol = dstore['sitecol']
        mesh = get_mesh(sitecol, complete=False)
        dic = _get_dict(dstore, 'hcurves-stats', info['imtls'], info['stats'])
        yield from hazard_items(
            dic, mesh, investigation_time=info['investigation_time'])
        return
    params = parse(what, info)
    if 'imt' in params:
        [imt] = params['imt']
        slc = info['imtls'](imt)
    else:
        slc = ALL
    sids = params.get('site_id', ALL)
    if params['rlzs']:
        dset = dstore['hcurves-rlzs']
        for k in params['k']:
            yield 'rlz-%03d' % k, hdf5.extract(dset, sids, k, slc)[:, 0]
    else:
        dset = dstore['hcurves-stats']
        stats = list(info['stats'])
        for k in params['k']:
            yield stats[k], hdf5.extract(dset, sids, k, slc)[:, 0]
    yield from params.items()
1333487
def export_gmf(ekey, dstore):
    
    oq = dstore['oqparam']
    if not oq.calculation_mode.startswith('scenario'):
        return []
    sitecol = dstore['sitecol']
    investigation_time = (None if oq.calculation_mode == 'scenario'
                          else oq.investigation_time)
    fmt = ekey[-1]
    gmf_data = dstore['gmf_data']
    nbytes = gmf_data.attrs['nbytes']
    logging.info('Internal size of the GMFs: %s', humansize(nbytes))
    if nbytes > GMF_MAX_SIZE:
        logging.warning(GMF_WARNING, dstore.filename)
    data = gmf_data['data'].value
    ses_idx = 1  # for scenario only
    events = []
    for eid, gmfa in group_array(data, 'eid').items():
        rup = Event(eid, ses_idx, sorted(set(gmfa['sid'])), gmfa)
        events.append(rup)
    fname = dstore.build_fname('gmf', 'scenario', fmt)
    writer = hazard_writers.EventBasedGMFXMLWriter(
        fname, sm_lt_path='', gsim_lt_path='')
    writer.serialize(
        GmfCollection(sitecol, oq.imtls, events, investigation_time))
    return [fname]
211248
def avglosses_data_transfer(token, dstore):
    
    oq = dstore['oqparam']
    N = len(dstore['assetcol'])
    R = dstore['csm_info'].get_num_rlzs()
    L = len(dstore.get_attr('risk_model', 'loss_types'))
    ct = oq.concurrent_tasks
    size_bytes = N * R * L * 8 * ct  # 8 byte floats
    return (
        '%d asset(s) x %d realization(s) x %d loss type(s) losses x '
        '8 bytes x %d tasks = %s' % (N, R, L, ct, humansize(size_bytes)))
986207
def export_hcurves_csv(ekey, dstore):
    
    oq = dstore['oqparam']
    info = get_info(dstore)
    rlzs_assoc = dstore['csm_info'].get_rlzs_assoc()
    R = len(rlzs_assoc.realizations)
    sitecol = dstore['sitecol']
    sitemesh = get_mesh(sitecol)
    key, kind, fmt = get_kkf(ekey)
    fnames = []
    checksum = dstore.get_attr('/', 'checksum32')
    hmap_dt = oq.hmap_dt()
    for kind in oq.get_kinds(kind, R):
        fname = hazard_curve_name(dstore, (key, fmt), kind, rlzs_assoc)
        comment = _comment(rlzs_assoc, kind, oq.investigation_time)
        if (key in ('hmaps', 'uhs') and oq.uniform_hazard_spectra or
                oq.hazard_maps):
            hmap = extract(dstore, 'hmaps?kind=' + kind)[kind]
        if key == 'uhs' and oq.poes and oq.uniform_hazard_spectra:
            uhs_curves = calc.make_uhs(hmap, info)
            writers.write_csv(
                fname, util.compose_arrays(sitemesh, uhs_curves),
                comment=comment + ', checksum=%d' % checksum)
            fnames.append(fname)
        elif key == 'hmaps' and oq.poes and oq.hazard_maps:
            fnames.extend(
                export_hmaps_csv(ekey, fname, sitemesh,
                                 hmap.flatten().view(hmap_dt),
                                 comment + ', checksum=%d' % checksum))
        elif key == 'hcurves':
            hcurves = extract(dstore, 'hcurves?kind=' + kind)[kind]
            fnames.extend(
                export_hcurves_by_imt_csv(
                    ekey, kind, rlzs_assoc, fname, sitecol, hcurves, oq,
                    checksum))
    return sorted(fnames)
1089436
def export_curves_rlzs(self, aids, key):
        
        if 'loss_curves-stats' in self.dstore:  # classical_risk
            if self.R == 1:
                data = self.dstore['loss_curves-stats'][aids]  # shape (A, 1)
            else:
                data = self.dstore['loss_curves-rlzs'][aids]  # shape (A, R)
            if key.startswith('rlz-'):
                rlzi = int(key[4:])
                return {key: data[:, rlzi]}
            # else key == 'rlzs', returns all data
            return {'rlz-%03d' % rlzi: data[:, rlzi] for rlzi in range(self.R)}

        # otherwise event_based
        curves = self.dstore['curves-rlzs'][aids]  # shape (A, R, P)
        if key.startswith('rlz-'):
            rlzi = int(key[4:])
            return {'rlz-%03d' % rlzi: curves[:, rlzi]}
        else:  # key is 'rlzs', return a dictionary will all realizations
            # this may be disabled in the future unless an asset is specified
            dic = {}
            for rlzi in range(self.R):
                dic['rlz-%03d' % rlzi] = curves[:, rlzi]
            return dic
1209090
def set(self, key, value):
        
        return DatastoreLegacy.store[self.domain].set(key, value)
359674
def export_csv(ekey, dstore):
    
    name = ekey[0] + '.csv'
    try:
        array = dstore[ekey[0]].value
    except AttributeError:
        # this happens if the key correspond to a HDF5 group
        return []  # write a custom exporter in this case
    if len(array.shape) == 1:  # vector
        array = array.reshape((len(array), 1))
    return [write_csv(dstore.export_path(name), array)]
1167544
def appendDatastore(self, store):
    ''''''
    if not isinstance(store, Datastore):
      raise TypeError("stores must be of type %s" % Datastore)

    self._stores.append(store)
1030987
def export_agg_losses(ekey, dstore):
    
    dskey = ekey[0]
    oq = dstore['oqparam']
    dt = oq.loss_dt()
    name, value, tags = _get_data(dstore, dskey, oq.hazard_stats().items())
    writer = writers.CsvWriter(fmt=writers.FIVEDIGITS)
    expvalue = dstore['exposed_value'].value  # shape (T1, T2, ..., L)
    tagcol = dstore['assetcol/tagcol']
    tagnames = tuple(dstore['oqparam'].aggregate_by)
    header = ('loss_type',) + tagnames + (
        'loss_value', 'exposed_value', 'loss_ratio')
    for r, tag in enumerate(tags):
        rows = []
        for multi_idx, loss in numpy.ndenumerate(value[:, r]):
            l, *tagidxs = multi_idx
            evalue = expvalue[tuple(tagidxs) + (l,)]
            row = tagcol.get_tagvalues(tagnames, tagidxs) + (
                loss, evalue, loss / evalue)
            rows.append((dt.names[l],) + row)
        dest = dstore.build_fname(name, tag, 'csv')
        writer.save(rows, dest, header)
    return writer.getsaved()
576728
def view_global_hmaps(token, dstore):
    
    oq = dstore['oqparam']
    dt = numpy.dtype([('%s-%s' % (imt, poe), F32)
                      for imt in oq.imtls for poe in oq.poes])
    array = dstore['hmaps/mean'].value.view(dt)[:, 0]
    res = numpy.zeros(1, array.dtype)
    for name in array.dtype.names:
        res[name] = array[name].mean()
    return rst_table(res)
1028866
def get_maxloss_rupture(dstore, loss_type):
    
    lti = dstore['oqparam'].lti[loss_type]
    ridx = dstore.get_attr('rup_loss_table', 'ridx')[lti]
    [rgetter] = gen_rupture_getters(dstore, slice(ridx, ridx + 1))
    [ebr] = rgetter.get_ruptures()
    return ebr