Display the global hazard curves for the calculation. They are
    used for debugging purposes when comparing the results of two
    calculations. They are the mean over the sites of the mean hazard
    curves.
173999
def view_global_hcurves(token, dstore):
    
    oq = dstore['oqparam']
    nsites = len(dstore['sitecol'])
    rlzs_assoc = dstore['csm_info'].get_rlzs_assoc()
    mean = getters.PmapGetter(dstore, rlzs_assoc).get_mean()
    array = calc.convert_to_array(mean, nsites, oq.imtls)
    res = numpy.zeros(1, array.dtype)
    for name in array.dtype.names:
        res[name] = array[name].mean()
    return rst_table(res)
378070
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
        
        C = self.COEFFS[imt]
        # Get the mean
        mean = self.get_mean(C, rup, sites, dists)
        if imt.name == "PGV":
            # Convert from log10 m/s to ln cm/s
            mean = np.log((10.0 ** mean) * 100.)
        else:
            # convert from log10 m/s/s to ln g
            mean = np.log((10.0 ** mean) / g)

        # Get the standard deviations
        stddevs = self.get_stddevs(C, mean.shape, stddev_types)
        return mean, stddevs
272444
def hazard_preparation(self):
        """"""
        LOGGER.info('ANALYSIS : Hazard preparation')

        use_same_projection = (
            self.hazard.crs().authid() == self._crs.authid())
        self.set_state_info(
            'hazard',
            'use_same_projection_as_aggregation',
            use_same_projection)

        if is_raster_layer(self.hazard):

            extent = self._analysis_impacted.extent()
            if not use_same_projection:
                transform = QgsCoordinateTransform(
                    self._crs, self.hazard.crs(), QgsProject.instance())
                extent = transform.transform(extent)

            self.set_state_process(
                'hazard', 'Clip raster by analysis bounding box')
            # noinspection PyTypeChecker
            self.hazard = clip_by_extent(self.hazard, extent)
            self.debug_layer(self.hazard)

            if self.hazard.keywords.get('layer_mode') == 'continuous':
                self.set_state_process(
                    'hazard', 'Classify continuous raster hazard')
                # noinspection PyTypeChecker
                self.hazard = reclassify_raster(
                    self.hazard, self.exposure.keywords['exposure'])
                self.debug_layer(self.hazard)

            self.set_state_process(
                'hazard', 'Polygonize classified raster hazard')
            # noinspection PyTypeChecker
            self.hazard = polygonize(self.hazard)
            self.debug_layer(self.hazard)

        if not use_same_projection:
            self.set_state_process(
                'hazard',
                'Reproject hazard layer to aggregation CRS')
            # noinspection PyTypeChecker
            self.hazard = reproject(self.hazard, self._crs)
            self.debug_layer(self.hazard, check_fields=False)

        self.set_state_process(
            'hazard',
            'Clip and mask hazard polygons with the analysis layer')
        self.hazard = clip(self.hazard, self._analysis_impacted)
        self.debug_layer(self.hazard, check_fields=False)

        self.set_state_process(
            'hazard',
            'Cleaning the vector hazard attribute table')
        # noinspection PyTypeChecker
        self.hazard = prepare_vector_layer(self.hazard)
        self.debug_layer(self.hazard)

        if self.hazard.keywords.get('layer_mode') == 'continuous':
            # If the layer is continuous, we update the original data to the
            # inasafe hazard class.
            self.set_state_process(
                'hazard',
                'Classify continuous hazard and assign class names')
            self.hazard = reclassify_vector(
                self.hazard, self.exposure.keywords['exposure'])
            self.debug_layer(self.hazard)
        else:
            # However, if it's a classified dataset, we only transpose the
            # value map using inasafe hazard classes.
            self.set_state_process(
                'hazard', 'Assign classes based on value map')
            self.hazard = update_value_map(
                self.hazard, self.exposure.keywords['exposure'])
            self.debug_layer(self.hazard)
198065
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
        

        # Distance term
        R = np.sqrt(dists.rjb ** 2 + 11.29 ** 2)

        # Magnitude term
        M = rup.mag - 6

        # Site term only distinguishes between lava and ash;
        # since ash sites have Vs30 in the range 60-200m/s,
        # we use this upper value as class separator
        S = np.zeros(R.shape)
        S[sites.vs30 <= 200] = 1

        # Mean ground motion (log10)
        mean = (0.518 + 0.387*M - np.log10(R) - 0.00256*R + 0.335*S)

        # Converting to natural log
        mean /= np.log10(np.e)

        # Check for standard deviation type
        assert all(stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES
                   for stddev_type in stddev_types)

        # Constant (total) standard deviation
        stddevs = [0.237/np.log10(np.e) + np.zeros(R.shape)]

        return mean, stddevs
1191979
def compare_mean_curves(calc_ref, calc, nsigma=3):
    
    dstore_ref = datastore.read(calc_ref)
    dstore = datastore.read(calc)
    imtls = dstore_ref['oqparam'].imtls
    if dstore['oqparam'].imtls != imtls:
        raise RuntimeError('The IMTs and levels are different between '
                           'calculation %d and %d' % (calc_ref, calc))
    sitecol_ref = dstore_ref['sitecol']
    sitecol = dstore['sitecol']
    site_id_ref = {(lon, lat): sid for sid, lon, lat in zip(
        sitecol_ref.sids, sitecol_ref.lons, sitecol_ref.lats)}
    site_id = {(lon, lat): sid for sid, lon, lat in zip(
        sitecol.sids, sitecol.lons, sitecol.lats)}
    common = set(site_id_ref) & set(site_id)
    if not common:
        raise RuntimeError('There are no common sites between calculation '
                           '%d and %d' % (calc_ref, calc))
    pmap_ref = PmapGetter(dstore_ref, sids=[site_id_ref[lonlat]
                                            for lonlat in common]).get_mean()
    pmap = PmapGetter(dstore, sids=[site_id[lonlat]
                                    for lonlat in common]).get_mean()
    for lonlat in common:
        mean, std = pmap[site_id[lonlat]].array.T  # shape (2, N)
        mean_ref, std_ref = pmap_ref[site_id_ref[lonlat]].array.T
        err = numpy.sqrt(std**2 + std_ref**2)
        for imt in imtls:
            sl = imtls(imt)
            ok = (numpy.abs(mean[sl] - mean_ref[sl]) < nsigma * err[sl]).all()
            if not ok:
                md = (numpy.abs(mean[sl] - mean_ref[sl])).max()
                plt.title('point=%s, imt=%s, maxdiff=%.2e' % (lonlat, imt, md))
                plt.loglog(imtls[imt], mean_ref[sl] + std_ref[sl],
                           label=str(calc_ref), color='black')
                plt.loglog(imtls[imt], mean_ref[sl] - std_ref[sl],
                           color='black')
                plt.loglog(imtls[imt], mean[sl] + std[sl], label=str(calc),
                           color='red')
                plt.loglog(imtls[imt], mean[sl] - std[sl], color='red')
                plt.legend()
                plt.show()
670889
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
        
        # extracting dictionary of coefficients specific to required
        # intensity measure type.
        C = self.COEFFS[imt]
        # Implements mean model (equation 12)
        mean = (self._compute_magnitude(rup, C) +
                self._compute_distance(dists, C) +
                self._get_site_amplification(sites, rup, C) +
                self._get_mechanism(rup, C))

        stddevs = self._get_stddevs(rup, np.exp(mean), stddev_types, sites)

        return mean, stddevs
576679
def mean
      w = @comparators.collect { |comparator| comparator.weight || 1 }
      @score_set.open_for_reading
      @score_set.each_pair do |id_1, id_2, scores|
        sum = 0
        scores.each do |key, value|
          sum += value * w[key-1]
        end
        mean = sum / @comparators.length.to_f
        if mean >= @threshold
          changed
          notify_observers(id_1, id_2, mean)
        end
      end
      @score_set.close
    end
348233
def display_breakdown(scores, outfile=None):
    
    total = 0
    outfile = open(outfile, 'w') if outfile else sys.stdout

    format.print_line('-')
    print('Point breakdown', file=outfile)
    for name, (score, max_score) in scores.items():
        print('    {}: {}/{}'.format(name, score, max_score), file=outfile)
        total += score
    print(file=outfile)

    print('Score:', file=outfile)
    print('    Total: {}'.format(total), file=outfile)
    return {'Total': total}
245561
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
        
        assert all(stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES
                   for stddev_type in stddev_types)

        # extract dictionaries of coefficients specific to required
        # intensity measure type
        C = self.COEFFS[imt]

        # Deltas for Tectonic Region Type and rake angles
        delta_R, delta_S, delta_V, delta_I = self._get_deltas(rup.rake)

        mean = self._compute_mean(C, rup.mag, dists.rrup, rup.hypo_depth,
                                  delta_R, delta_S, delta_V, delta_I,
                                  sites.vs30)

        stddevs = self._get_stddevs(C, stddev_types, sites.vs30.size)

        return mean, stddevs
759235
def get_hazard(self, data=None):
        
        if data is None:
            data = self.get_gmfdata()
        return general.group_array(data, 'sid')
1290912
def add_hazard_curves(self, root, metadata, data):
        
        hazard_curves = et.SubElement(root, 'hazardCurves')

        _set_metadata(hazard_curves, metadata, _ATTR_MAP)

        imls_elem = et.SubElement(hazard_curves, 'IMLs')
        imls_elem.text = ' '.join(map(scientificformat, metadata['imls']))
        gml_ns = nrml.SERIALIZE_NS_MAP['gml']

        for hc in data:
            hc_elem = et.SubElement(hazard_curves, 'hazardCurve')
            gml_point = et.SubElement(hc_elem, '{%s}Point' % gml_ns)
            gml_pos = et.SubElement(gml_point, '{%s}pos' % gml_ns)
            gml_pos.text = '%s %s' % (hc.location.x, hc.location.y)
            poes_elem = et.SubElement(hc_elem, 'poEs')
            poes_elem.text = ' '.join(map(scientificformat, hc.poes))
1030233
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
        
        C = self.COEFFS[imt]

        mean = (self._compute_magnitude_term(C, rup.mag) +
                self._compute_distance_term(C, dists.rhypo, rup.mag))
        stddevs = self._get_stddevs(C, dists.rhypo, stddev_types)
        return mean, stddevs
638223
function () {
		var chartOptions = this.chartOptions,
			getValueCount = function (type) {
				return (Highcharts.seriesTypes[type || 'line'].prototype.pointArrayMap || [0]).length;
			},
			globalType = chartOptions && chartOptions.chart && chartOptions.chart.type,
			individualCounts = [];

		each((chartOptions && chartOptions.series) || [], function (series) {
			individualCounts.push(getValueCount(series.type || globalType));
		});

		this.valueCount = {
			global: getValueCount(globalType),
			individual: individualCounts
		};
	}
973673
def render(self, **kwargs):
        
        # Calling parent function
        super(VisCurve2D, self).render(**kwargs)

        # Initialize variables
        legend_proxy = []
        legend_names = []

        # Draw control points polygon and the curve
        fig = plt.figure(figsize=self.vconf.figure_size, dpi=self.vconf.figure_dpi)
        ax = fig.gca()

        # Start plotting
        for plot in self._plots:
            pts = np.array(plot['ptsarr'], dtype=self.vconf.dtype)
            # Plot control points
            if plot['type'] == 'ctrlpts' and self.vconf.display_ctrlpts:
                cpplot, = plt.plot(pts[:, 0], pts[:, 1], color=plot['color'], linestyle='-.', marker='o')
                legend_proxy.append(cpplot)
                legend_names.append(plot['name'])

            # Plot evaluated points
            if plot['type'] == 'evalpts' and self.vconf.display_evalpts:
                curveplt, = plt.plot(pts[:, 0], pts[:, 1], color=plot['color'], linestyle='-', alpha=self.vconf.alpha)
                legend_proxy.append(curveplt)
                legend_names.append(plot['name'])
                # Debugging for curve directions
                if self.vconf.debug_mode:
                    plt.quiver(pts[0, 0], pts[0, 1], pts[-1, 0] - pts[0, 0], pts[-1, 1] - pts[0, 1],
                               color='k', angles='xy', scale_units='xy', scale=1, width=0.003)

            # Plot bounding box
            if plot['type'] == 'bbox' and self.vconf.display_bbox:
                bboxplt, = plt.plot(pts[:, 0], pts[:, 1], color=plot['color'], linestyle='--')
                legend_proxy.append(bboxplt)
                legend_names.append(plot['name'])

            # Plot extras
            if plot['type'] == 'extras':
                extrasplt, = plt.plot(pts[:, 0], pts[:, 1],
                                      color=plot['color'][0], linestyle='-', linewidth=plot['color'][1])
                legend_proxy.append(extrasplt)
                legend_names.append(plot['name'])

        # Add legend
        if self.vconf.display_legend:
            plt.legend(legend_proxy, legend_names)

        # Remove axes
        if not self.vconf.display_axes:
            plt.axis('off')

        # Set aspect ratio
        if self.vconf.axes_equal:
            ax.set_aspect('equal')

        # Axis labels
        if self.vconf.display_labels:
            ax.set_xlabel('x')
            ax.set_ylabel('y')

        # Process keyword arguments
        fig_filename = kwargs.get('fig_save_as', None)
        fig_display = kwargs.get('display_plot', True)

        # Display the plot
        if fig_display:
            plt.show()
        else:
            fig_filename = self.vconf.figure_image_filename if fig_filename is None else fig_filename

        # Save the figure
        self.vconf.save_figure_as(fig, fig_filename)
359357
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
        
        # extract faulting style  and rock adjustment coefficients for the
        # given imt
        C_ADJ = self.COEFFS_FS_ROCK[imt]

        mean, stddevs = super().get_mean_and_stddevs(
            sites, rup, dists, imt, stddev_types)

        # apply faulting style and rock adjustment factor for mean and std
        mean = np.log(np.exp(mean) *
                      _compute_faulting_style_term(C_ADJ['Frss'],
                                                   self.CONSTS_FS['pR'],
                                                   self.CONSTS_FS['Fnss'],
                                                   self.CONSTS_FS['pN'],
                                                   rup.rake) * C_ADJ['AFrock'])
        stddevs = np.array(stddevs)

        return mean, stddevs
896477
def summary_calculation(self):
        
        LOGGER.info('ANALYSIS : Summary calculation')
        if is_vector_layer(self._exposure_summary):
            # With continuous exposure, we don't have an exposure summary layer
            self.set_state_process(
                'impact function',
                'Aggregate the impact summary')
            self._aggregate_hazard_impacted = aggregate_hazard_summary(
                self.exposure_summary, self._aggregate_hazard_impacted)
            self.debug_layer(self._exposure_summary, add_to_datastore=False)

        self.set_state_process(
            'impact function', 'Aggregate the aggregation summary')
        self._aggregation_summary = aggregation_summary(
            self._aggregate_hazard_impacted, self.aggregation)
        self.debug_layer(
            self._aggregation_summary, add_to_datastore=False)

        self.set_state_process(
            'impact function', 'Aggregate the analysis summary')
        self._analysis_impacted = analysis_summary(
            self._aggregate_hazard_impacted, self._analysis_impacted)
        self.debug_layer(self._analysis_impacted)

        if self._exposure.keywords.get('classification'):
            self.set_state_process(
                'impact function', 'Build the exposure summary table')
            self._exposure_summary_table = exposure_summary_table(
                self._aggregate_hazard_impacted, self._exposure_summary)
            self.debug_layer(
                self._exposure_summary_table, add_to_datastore=False)
615885
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
        
        mean, stddevs = super().get_mean_and_stddevs(
            sites, rup, dists, imt, stddev_types)

        # this is the firm ground adjustment
        mean += np.log(1.162)

        return mean, stddevs