Esempio n. 1
0
    def __call__(self, loss_type, assets, hazard, _eps=None, _eids=None):
        """
        :param loss_type: the loss type
        :param assets: a list of N assets of the same taxonomy
        :param hazard: an hazard curve
        :param _eps: dummy parameter, unused
        :param _eids: dummy parameter, unused
        :returns: a list of triples (eal_orig, eal_retro, bcr_result)
        """
        n = len(assets)
        self.assets = assets
        vf = self.risk_functions[loss_type]
        imls = self.hazard_imtls[vf.imt]
        vf_retro = self.retro_functions[loss_type]
        curves_orig = functools.partial(scientific.classical, vf, imls,
                                        steps=self.lrem_steps_per_interval)
        curves_retro = functools.partial(scientific.classical, vf_retro, imls,
                                         steps=self.lrem_steps_per_interval)
        original_loss_curves = utils.numpy_map(curves_orig, [hazard] * n)
        retrofitted_loss_curves = utils.numpy_map(curves_retro, [hazard] * n)

        eal_original = utils.numpy_map(
            scientific.average_loss, original_loss_curves)

        eal_retrofitted = utils.numpy_map(
            scientific.average_loss, retrofitted_loss_curves)

        bcr_results = [
            scientific.bcr(
                eal_original[i], eal_retrofitted[i],
                self.interest_rate, self.asset_life_expectancy,
                asset.value(loss_type), asset.retrofitted(loss_type))
            for i, asset in enumerate(assets)]

        return list(zip(eal_original, eal_retrofitted, bcr_results))
Esempio n. 2
0
def do_classical_bcr(loss_type, units, containers, params, profile):
    for unit_orig, unit_retro in utils.pairwise(units):
        with profile('getting hazard'):
            assets, hazard_curves = unit_orig.getter()
            _, hazard_curves_retrofitted = unit_retro.getter()

        with profile('computing bcr'):
            original_loss_curves = unit_orig.calc(hazard_curves)
            retrofitted_loss_curves = unit_retro.calc(
                hazard_curves_retrofitted)

            eal_original = [
                scientific.average_loss(losses, poes)
                for losses, poes in original_loss_curves]

            eal_retrofitted = [
                scientific.average_loss(losses, poes)
                for losses, poes in retrofitted_loss_curves]

            bcr_results = [
                scientific.bcr(
                    eal_original[i], eal_retrofitted[i],
                    params.interest_rate, params.asset_life_expectancy,
                    asset.value(loss_type), asset.retrofitted(loss_type))
                for i, asset in enumerate(assets)]

        with logs.tracing('writing results'):
            containers.write(
                assets, zip(eal_original, eal_retrofitted, bcr_results),
                output_type="bcr_distribution",
                loss_type=loss_type,
                hazard_output_id=unit_orig.getter.hazard_output.id)
Esempio n. 3
0
    def __call__(self, loss_type, assets, gmfs, epsilons, event_ids):
        self.assets = assets

        original_loss_curves = utils.numpy_map(
            self.curves, self.vf_orig[loss_type].apply_to(gmfs, epsilons))
        retrofitted_loss_curves = utils.numpy_map(
            self.curves, self.vf_retro[loss_type].apply_to(gmfs, epsilons))

        eal_original = utils.numpy_map(scientific.average_loss,
                                       original_loss_curves)
        eal_retrofitted = utils.numpy_map(scientific.average_loss,
                                          retrofitted_loss_curves)

        bcr_results = [
            scientific.bcr(eal_original[i], eal_retrofitted[i],
                           self.interest_rate, self.asset_life_expectancy,
                           asset.value(loss_type),
                           asset.retrofitted(loss_type))
            for i, asset in enumerate(assets)
        ]

        return scientific.Output(assets,
                                 loss_type,
                                 data=list(
                                     zip(eal_original, eal_retrofitted,
                                         bcr_results)))
Esempio n. 4
0
    def __call__(self, loss_type, assets, hazard, _eps=None, _tags=None):
        self.assets = assets

        original_loss_curves = utils.numpy_map(self.curves_orig[loss_type],
                                               hazard)
        retrofitted_loss_curves = utils.numpy_map(self.curves_retro[loss_type],
                                                  hazard)

        eal_original = utils.numpy_map(scientific.average_loss,
                                       original_loss_curves)

        eal_retrofitted = utils.numpy_map(scientific.average_loss,
                                          retrofitted_loss_curves)

        bcr_results = [
            scientific.bcr(eal_original[i], eal_retrofitted[i],
                           self.interest_rate, self.asset_life_expectancy,
                           asset.value(loss_type),
                           asset.retrofitted(loss_type))
            for i, asset in enumerate(assets)
        ]

        return scientific.Output(assets,
                                 loss_type,
                                 data=list(
                                     zip(eal_original, eal_retrofitted,
                                         bcr_results)))
Esempio n. 5
0
    def test_bcr_classical(self):
        vulnerability_function_rm = (
            scientific.VulnerabilityFunction(
                'PGA',
                [0.1, 0.2, 0.3, 0.45, 0.6],
                [0.05, 0.1, 0.2, 0.4, 0.8],
                [0.5, 0.4, 0.3, 0.2, 0.1], "LN"))

        vulnerability_function_rf = (
            scientific.VulnerabilityFunction(
                'PGA',
                [0.1, 0.2, 0.3, 0.45, 0.6],
                [0.035, 0.07, 0.14, 0.28, 0.56],
                [0.5, 0.4, 0.3, 0.2, 0.1], "LN"))

        asset_value = 2.
        retrofitting_cost = .1
        interest_rate = 0.05
        asset_life_expectancy = 40

        hazard = [
            (0.001, 0.0398612669790014), (0.01, 0.0398612669790014),
            (0.05, 0.0397287574802989), (0.1, 0.0296134266256125),
            (0.15, 0.0198273287564916), (0.2, 0.0130622701614519),
            (0.25, 0.00865538795000043), (0.3, 0.00589852059368967),
            (0.35, 0.00406169858951178), (0.4, 0.00281172717952682),
            (0.45, 0.00199511741777669), (0.5, 0.00135870597284571),
            (0.55, 0.000989667841573727), (0.6, 0.000757544444296432),
            (0.7, 0.000272824002045979), (0.8, 0.0),
            (0.9, 0.0), (1.0, 0.0)]

        original_loss_ratio_curve = scientific.classical(
            vulnerability_function_rm,
            hazard,
            steps=5)
        retrofitted_loss_ratio_curve = scientific.classical(
            vulnerability_function_rf,
            hazard,
            steps=5)

        eal_original = scientific.average_loss(*original_loss_ratio_curve)
        eal_retrofitted = scientific.average_loss(
            *retrofitted_loss_ratio_curve)

        bcr = scientific.bcr(
            eal_original, eal_retrofitted,
            interest_rate,
            asset_life_expectancy,
            asset_value,
            retrofitting_cost)

        self.assertAlmostEqual(0.009379,
                               eal_original * asset_value,
                               delta=0.0009)

        self.assertAlmostEqual(0.006586,
                               eal_retrofitted * asset_value,
                               delta=0.0009)

        self.assertAlmostEqual(0.483091, bcr, delta=0.009)
    def test_compute_bcr(self):
        # numbers are proven to be correct
        eal_orig = 0.00838
        eal_retrofitted = 0.00587
        retrofitting_cost = 0.1
        interest = 0.05
        life_expectancy = 40
        expected_result = 0.43405

        result = scientific.bcr(eal_orig, eal_retrofitted, interest, life_expectancy, 1, retrofitting_cost)
        self.assertAlmostEqual(result, expected_result, delta=2e-5)
    def test_compute_bcr(self):
        # numbers are proven to be correct
        eal_orig = 0.00838
        eal_retrofitted = 0.00587
        retrofitting_cost = 0.1
        interest = 0.05
        life_expectancy = 40
        expected_result = 0.43405

        result = scientific.bcr(eal_orig, eal_retrofitted, interest,
                                life_expectancy, 1, retrofitting_cost)
        self.assertAlmostEqual(result, expected_result, delta=2e-5)
Esempio n. 8
0
    def test_bcr_classical(self):
        vulnerability_function_rm = (
            scientific.VulnerabilityFunction(
                'RM', 'PGA',
                [0.1, 0.2, 0.3, 0.45, 0.6],
                [0.05, 0.1, 0.2, 0.4, 0.8],
                [0.5, 0.4, 0.3, 0.2, 0.1], "LN"))

        vulnerability_function_rf = (
            scientific.VulnerabilityFunction(
                'RF', 'PGA',
                [0.1, 0.2, 0.3, 0.45, 0.6],
                [0.035, 0.07, 0.14, 0.28, 0.56],
                [0.5, 0.4, 0.3, 0.2, 0.1], "LN"))

        asset_value = 2.
        retrofitting_cost = .1
        interest_rate = 0.05
        asset_life_expectancy = 40

        hazard_imls = [0.001, 0.01, 0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4,
                       0.45, 0.5, 0.55, 0.6, 0.7, 0.8, 0.9, 1.0]
        poes = [0.039861266979, 0.039861266979, 0.0397287574803,
                0.0296134266256, 0.0198273287565, 0.0130622701615,
                0.00865538795, 0.00589852059369, 0.00406169858951,
                0.00281172717953, 0.00199511741778, 0.00135870597285,
                0.000989667841574, 0.000757544444296, 0.000272824002046,
                0.0, 0.0, 0.]

        original_loss_ratio_curve = scientific.classical(
            vulnerability_function_rm, hazard_imls, poes, steps=5)
        retrofitted_loss_ratio_curve = scientific.classical(
            vulnerability_function_rf, hazard_imls, poes, steps=5)

        eal_original = scientific.average_loss(original_loss_ratio_curve)
        eal_retrofitted = scientific.average_loss(retrofitted_loss_ratio_curve)

        bcr = scientific.bcr(
            eal_original, eal_retrofitted,
            interest_rate,
            asset_life_expectancy,
            asset_value,
            retrofitting_cost)

        self.assertAlmostEqual(0.009379,
                               eal_original * asset_value,
                               delta=0.0009)

        self.assertAlmostEqual(0.006586,
                               eal_retrofitted * asset_value,
                               delta=0.0009)

        self.assertAlmostEqual(0.483091, bcr, delta=0.009)
Esempio n. 9
0
    def test_bcr_classical(self):
        vulnerability_function_rm = (scientific.VulnerabilityFunction(
            'RM', 'PGA', [0.1, 0.2, 0.3, 0.45, 0.6],
            [0.05, 0.1, 0.2, 0.4, 0.8], [0.5, 0.4, 0.3, 0.2, 0.1], "LN"))

        vulnerability_function_rf = (scientific.VulnerabilityFunction(
            'RF', 'PGA', [0.1, 0.2, 0.3, 0.45, 0.6],
            [0.035, 0.07, 0.14, 0.28, 0.56], [0.5, 0.4, 0.3, 0.2, 0.1], "LN"))

        asset_value = 2.
        retrofitting_cost = .1
        interest_rate = 0.05
        asset_life_expectancy = 40

        hazard_imls = [
            0.001, 0.01, 0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5,
            0.55, 0.6, 0.7, 0.8, 0.9, 1.0
        ]
        poes = [
            0.039861266979, 0.039861266979, 0.0397287574803, 0.0296134266256,
            0.0198273287565, 0.0130622701615, 0.00865538795, 0.00589852059369,
            0.00406169858951, 0.00281172717953, 0.00199511741778,
            0.00135870597285, 0.000989667841574, 0.000757544444296,
            0.000272824002046, 0.0, 0.0, 0.
        ]

        original_loss_ratio_curve = scientific.classical(
            vulnerability_function_rm, hazard_imls, poes, steps=5)
        retrofitted_loss_ratio_curve = scientific.classical(
            vulnerability_function_rf, hazard_imls, poes, steps=5)

        eal_original = scientific.average_loss(original_loss_ratio_curve)
        eal_retrofitted = scientific.average_loss(retrofitted_loss_ratio_curve)

        bcr = scientific.bcr(eal_original, eal_retrofitted, interest_rate,
                             asset_life_expectancy, asset_value,
                             retrofitting_cost)

        self.assertAlmostEqual(0.009379,
                               eal_original * asset_value,
                               delta=0.0009)

        self.assertAlmostEqual(0.006586,
                               eal_retrofitted * asset_value,
                               delta=0.0009)

        self.assertAlmostEqual(0.483091, bcr, delta=0.009)
Esempio n. 10
0
    def classical_bcr(self, loss_type, assets, hazard, eids=None, eps=None):
        """
        :param loss_type: the loss type
        :param assets: a list of N assets of the same taxonomy
        :param hazard: an hazard curve
        :param _eps: dummy parameter, unused
        :param _eids: dummy parameter, unused
        :returns: a list of triples (eal_orig, eal_retro, bcr_result)
        """
        if loss_type != 'structural':
            raise NotImplementedError('retrofitted is not defined for ' +
                                      loss_type)
        n = len(assets)
        self.assets = assets
        vf = self.risk_functions[loss_type, 'vulnerability']
        imls = self.hazard_imtls[vf.imt]
        vf_retro = self.risk_functions[loss_type, 'vulnerability_retrofitted']
        curves_orig = functools.partial(
            scientific.classical,
            vf,
            imls,
            loss_ratios=self.loss_ratios_orig[loss_type])
        curves_retro = functools.partial(
            scientific.classical,
            vf_retro,
            imls,
            loss_ratios=self.loss_ratios_retro[loss_type])
        original_loss_curves = numpy.array([curves_orig(hazard)] * n)
        retrofitted_loss_curves = numpy.array([curves_retro(hazard)] * n)

        eal_original = numpy.array(
            [scientific.average_loss(lc) for lc in original_loss_curves])

        eal_retrofitted = numpy.array(
            [scientific.average_loss(lc) for lc in retrofitted_loss_curves])

        bcr_results = [
            scientific.bcr(eal_original[i], eal_retrofitted[i],
                           self.interest_rate, self.asset_life_expectancy,
                           asset['value-' + loss_type], asset['retrofitted'])
            for i, asset in enumerate(assets)
        ]
        return list(zip(eal_original, eal_retrofitted, bcr_results))
Esempio n. 11
0
def do_event_based_bcr(loss_type, units, containers, params, profile):
    """
    See `event_based_bcr` for docstring
    """
    for unit_orig, unit_retro in utils.pairwise(units):

        with profile("getting hazard"):
            assets, (gmvs, _) = unit_orig.getter()
            if len(assets) == 0:
                logs.LOG.info("Exit from task as no asset could be processed")
                return

            _, (gmvs_retro, _) = unit_retro.getter()

        with profile("computing bcr"):
            _, original_loss_curves = unit_orig.calc(gmvs)
            _, retrofitted_loss_curves = unit_retro.calc(gmvs_retro)

            eal_original = [scientific.average_loss(losses, poes) for losses, poes in original_loss_curves]

            eal_retrofitted = [scientific.average_loss(losses, poes) for losses, poes in retrofitted_loss_curves]

            bcr_results = [
                scientific.bcr(
                    eal_original[i],
                    eal_retrofitted[i],
                    params.interest_rate,
                    params.asset_life_expectancy,
                    asset.value(loss_type),
                    asset.retrofitted(loss_type),
                )
                for i, asset in enumerate(assets)
            ]

        with profile("writing results"):
            containers.write(
                assets,
                zip(eal_original, eal_retrofitted, bcr_results),
                output_type="bcr_distribution",
                loss_type=loss_type,
                hazard_output_id=unit_orig.getter.hazard_output.id,
            )
Esempio n. 12
0
    def __call__(self, loss_type, assets, hazard):
        self.assets = assets

        original_loss_curves = self.curves_orig[loss_type](hazard)
        retrofitted_loss_curves = self.curves_retro[loss_type](hazard)

        eal_original = [
            scientific.average_loss(losses, poes)
            for losses, poes in original_loss_curves]

        eal_retrofitted = [
            scientific.average_loss(losses, poes)
            for losses, poes in retrofitted_loss_curves]

        bcr_results = [
            scientific.bcr(
                eal_original[i], eal_retrofitted[i],
                self.interest_rate, self.asset_life_expectancy,
                asset.value(loss_type), asset.retrofitted(loss_type))
            for i, asset in enumerate(assets)]

        return zip(eal_original, eal_retrofitted, bcr_results)
Esempio n. 13
0
    def classical_bcr(self, loss_type, assets, hazard, eids=None, eps=None):
        """
        :param loss_type: the loss type
        :param assets: a list of N assets of the same taxonomy
        :param hazard: an hazard curve
        :param _eps: dummy parameter, unused
        :param _eids: dummy parameter, unused
        :returns: a list of triples (eal_orig, eal_retro, bcr_result)
        """
        if loss_type != 'structural':
            raise NotImplemented('retrofitted is not defined for ' + loss_type)
        n = len(assets)
        self.assets = assets
        vf = self.risk_functions[loss_type, 'vulnerability']
        imls = self.hazard_imtls[vf.imt]
        vf_retro = self.risk_functions[loss_type, 'vulnerability_retrofitted']
        curves_orig = functools.partial(
            scientific.classical, vf, imls,
            loss_ratios=self.loss_ratios_orig[loss_type])
        curves_retro = functools.partial(
            scientific.classical, vf_retro, imls,
            loss_ratios=self.loss_ratios_retro[loss_type])
        original_loss_curves = numpy.array([curves_orig(hazard)] * n)
        retrofitted_loss_curves = numpy.array([curves_retro(hazard)] * n)

        eal_original = numpy.array([scientific.average_loss(lc)
                                    for lc in original_loss_curves])

        eal_retrofitted = numpy.array([scientific.average_loss(lc)
                                       for lc in retrofitted_loss_curves])

        bcr_results = [
            scientific.bcr(
                eal_original[i], eal_retrofitted[i],
                self.interest_rate, self.asset_life_expectancy,
                asset['value-' + loss_type], asset['retrofitted'])
            for i, asset in enumerate(assets)]
        return list(zip(eal_original, eal_retrofitted, bcr_results))
Esempio n. 14
0
    def __call__(self, loss_type, assets, gmfs, epsilons, event_ids):
        self.assets = assets

        original_loss_curves = utils.numpy_map(
            self.curves, self.vf_orig[loss_type].apply_to(gmfs, epsilons))
        retrofitted_loss_curves = utils.numpy_map(
            self.curves, self.vf_retro[loss_type].apply_to(gmfs, epsilons))

        eal_original = utils.numpy_map(
            scientific.average_loss, original_loss_curves)
        eal_retrofitted = utils.numpy_map(
            scientific.average_loss, retrofitted_loss_curves)

        bcr_results = [
            scientific.bcr(
                eal_original[i], eal_retrofitted[i],
                self.interest_rate, self.asset_life_expectancy,
                asset.value(loss_type), asset.retrofitted(loss_type))
            for i, asset in enumerate(assets)]

        return scientific.Output(
            assets, loss_type,
            data=list(zip(eal_original, eal_retrofitted, bcr_results)))
Esempio n. 15
0
    def __call__(self, loss_type, assets, gmfs, epsilons, event_ids):
        self.assets = assets
        original_loss_curves = self.curves(
            self.vf_orig[loss_type].apply_to(gmfs, epsilons))
        retrofitted_loss_curves = self.curves(
            self.vf_retro[loss_type].apply_to(gmfs, epsilons))

        eal_original = [
            scientific.average_loss(losses, poes)
            for losses, poes in original_loss_curves]

        eal_retrofitted = [
            scientific.average_loss(losses, poes)
            for losses, poes in retrofitted_loss_curves]

        bcr_results = [
            scientific.bcr(
                eal_original[i], eal_retrofitted[i],
                self.interest_rate, self.asset_life_expectancy,
                asset.value(loss_type), asset.retrofitted(loss_type))
            for i, asset in enumerate(assets)]

        return zip(eal_original, eal_retrofitted, bcr_results)
Esempio n. 16
0
    def __call__(self, loss_type, assets, hazard, _eps=None, _eids=None):
        """
        :param loss_type: the loss type
        :param assets: a list of N assets of the same taxonomy
        :param hazard: an hazard curve
        :param _eps: dummy parameter, unused
        :param _eids: dummy parameter, unused
        :returns: a :class:`openquake.risklib.scientific.Output` instance
        """
        n = len(assets)
        self.assets = assets
        vf = self.risk_functions[loss_type]
        imls = self.hazard_imtls[vf.imt]
        vf_retro = self.retro_functions[loss_type]
        curves_orig = functools.partial(scientific.classical, vf, imls,
                                        steps=self.lrem_steps_per_interval)
        curves_retro = functools.partial(scientific.classical, vf_retro, imls,
                                         steps=self.lrem_steps_per_interval)
        original_loss_curves = utils.numpy_map(curves_orig, [hazard] * n)
        retrofitted_loss_curves = utils.numpy_map(curves_retro, [hazard] * n)

        eal_original = utils.numpy_map(
            scientific.average_loss, original_loss_curves)

        eal_retrofitted = utils.numpy_map(
            scientific.average_loss, retrofitted_loss_curves)

        bcr_results = [
            scientific.bcr(
                eal_original[i], eal_retrofitted[i],
                self.interest_rate, self.asset_life_expectancy,
                asset.value(loss_type), asset.retrofitted(loss_type))
            for i, asset in enumerate(assets)]

        return scientific.Output(
            assets, loss_type,
            data=list(zip(eal_original, eal_retrofitted, bcr_results)))
Esempio n. 17
0
    def __call__(self, loss_type, assets, hazard):
        self.assets = assets

        original_loss_curves = utils.numpy_map(
            self.curves_orig[loss_type], hazard)
        retrofitted_loss_curves = utils.numpy_map(
            self.curves_retro[loss_type], hazard)

        eal_original = utils.numpy_map(
            scientific.average_loss, original_loss_curves)

        eal_retrofitted = utils.numpy_map(
            scientific.average_loss, retrofitted_loss_curves)

        bcr_results = [
            scientific.bcr(
                eal_original[i], eal_retrofitted[i],
                self.interest_rate, self.asset_life_expectancy,
                asset.value(loss_type), asset.retrofitted(loss_type))
            for i, asset in enumerate(assets)]

        return scientific.Output(
            assets, loss_type,
            data=zip(eal_original, eal_retrofitted, bcr_results))
Esempio n. 18
0
def event_based_bcr(job_id, hazard, seed,
                    vulnerability_function, vulnerability_function_retrofitted,
                    output_containers, time_span, tses,
                    loss_curve_resolution, asset_correlation,
                    asset_life_expectancy, interest_rate):
    """
    Celery task for the BCR risk calculator based on the event based
    calculator.

    Instantiates risklib calculators, computes bcr
    and stores results to db in a single transaction.

    :param int job_id:
        ID of the currently running job.
    :param dict hazard:
      A dictionary mapping IDs of
      :class:`openquake.engine.db.models.Output` (with output_type set
      to 'gmf_collection') to a tuple where the first element is a list
      of list (one for each asset) with the ground motion values used by the
      calculation, and the second element is the corresponding weight.
    :param output_containers: A dictionary mapping hazard Output ID to
      a tuple with only the ID of the
      :class:`openquake.engine.db.models.BCRDistribution` output container
      used to store the computed bcr distribution
    :param float time_span:
        Time Span of the hazard calculation.
    :param float tses:
        Time of the Stochastic Event Set.
    :param int loss_curve_resolution:
        Resolution of the computed loss curves (number of points).
    :param int seed:
        Seed used to generate random values.
    :param float asset_correlation:
        asset correlation (0 uncorrelated, 1 perfectly correlated).
    :param float interest_rate
        The interest rate used in the Cost Benefit Analysis.
    :param float asset_life_expectancy
        The life expectancy used for every asset.
    """

    for hazard_output_id, hazard_data in hazard.items():
        hazard_getter, _ = hazard_data
        (bcr_distribution_id,) = output_containers[hazard_output_id]

        # FIXME(lp). We should not pass the exact same seed for
        # different hazard
        calc_original = api.ProbabilisticEventBased(
            vulnerability_function, curve_resolution=loss_curve_resolution,
            time_span=time_span, tses=tses,
            seed=seed, correlation=asset_correlation)

        calc_retrofitted = api.ProbabilisticEventBased(
            vulnerability_function_retrofitted,
            curve_resolution=loss_curve_resolution,
            time_span=time_span, tses=tses,
            seed=seed, correlation=asset_correlation)

        with logs.tracing('getting hazard'):
            assets, gmvs_ruptures, missings = hazard_getter()
            if len(assets):
                ground_motion_values = numpy.array(gmvs_ruptures)[:, 0]
            else:
                # we are relying on the fact that if all the
                # hazard_getter in this task will either return some
                # results or they all return an empty result set.
                logs.LOG.info("Exit from task as no asset could be processed")
                base.signal_task_complete(job_id=job_id,
                                          num_items=len(missings))
                return

        with logs.tracing('computing risk'):
            _, original_loss_curves = calc_original(ground_motion_values)
            _, retrofitted_loss_curves = calc_retrofitted(ground_motion_values)

            eal_original = [
                scientific.mean_loss(*original_loss_curves[i].xy)
                for i in range(len(assets))]

            eal_retrofitted = [
                scientific.mean_loss(*retrofitted_loss_curves[i].xy)
                for i in range(len(assets))]

            bcr_results = [
                scientific.bcr(
                    eal_original[i], eal_retrofitted[i],
                    interest_rate, asset_life_expectancy,
                    asset.value, asset.retrofitting_cost)
                for i, asset in enumerate(assets)]

        with logs.tracing('writing results'):
            with transaction.commit_on_success(using='reslt_writer'):
                for i, asset in enumerate(assets):
                    general.write_bcr_distribution(
                        bcr_distribution_id, asset,
                        eal_original[i], eal_retrofitted[i], bcr_results[i])

    base.signal_task_complete(job_id=job_id,
                              num_items=len(assets) + len(missings))
Esempio n. 19
0
File: core.py Progetto: 4x/oq-engine
def classical_bcr(
    job_id,
    hazard,
    vulnerability_function,
    vulnerability_function_retrofitted,
    output_containers,
    lrem_steps_per_interval,
    asset_life_expectancy,
    interest_rate,
):
    """
    Celery task for the BCR risk calculator based on the classical
    calculator.

    Instantiates risklib calculators, computes BCR and stores the
    results to db in a single transaction.

    :param int job_id:
      ID of the currently running job
    :param dict hazard:
      A dictionary mapping IDs of
      :class:`openquake.engine.db.models.Output` (with output_type set
      to 'hazard_curve') to a tuple where the first element is an instance of
      :class:`..hazard_getters.HazardCurveGetter, and the second element is the
      corresponding weight.
    :param output_containers: A dictionary mapping hazard Output ID to
      a tuple with only the ID of the
      :class:`openquake.engine.db.models.BCRDistribution` output container
      used to store the computed bcr distribution
    :param int lrem_steps_per_interval
      Steps per interval used to compute the Loss Ratio Exceedance matrix
    :param float interest_rate
      The interest rate used in the Cost Benefit Analysis
    :param float asset_life_expectancy
      The life expectancy used for every asset
    """

    calc_original = api.Classical(vulnerability_function, lrem_steps_per_interval)
    calc_retrofitted = api.Classical(vulnerability_function_retrofitted, lrem_steps_per_interval)

    for hazard_output_id, hazard_data in hazard.items():
        hazard_getter, _ = hazard_data
        (bcr_distribution_id,) = output_containers[hazard_output_id]

        with logs.tracing("getting hazard"):
            assets, hazard_curves, missings = hazard_getter()

        with logs.tracing("computing original losses"):
            original_loss_curves = calc_original(hazard_curves)
            retrofitted_loss_curves = calc_retrofitted(hazard_curves)

            eal_original = [scientific.mean_loss(*original_loss_curves[i].xy) for i in range(len(assets))]

            eal_retrofitted = [scientific.mean_loss(*retrofitted_loss_curves[i].xy) for i in range(len(assets))]

            bcr_results = [
                scientific.bcr(
                    eal_original[i],
                    eal_retrofitted[i],
                    interest_rate,
                    asset_life_expectancy,
                    asset.value,
                    asset.retrofitting_cost,
                )
                for i, asset in enumerate(assets)
            ]

        with logs.tracing("writing results"):
            with transaction.commit_on_success(using="reslt_writer"):
                for i, asset in enumerate(assets):
                    general.write_bcr_distribution(
                        bcr_distribution_id, asset, eal_original[i], eal_retrofitted[i], bcr_results[i]
                    )

    base.signal_task_complete(job_id=job_id, num_items=len(assets) + len(missings))