Make Uniform Hazard Spectra curves for each location.

    :param hmap:
        array of shape (N, M, P)
    :param info:
        a dictionary with keys poes, imtls, uhs_dt
    :returns:
        a composite array containing uniform hazard spectra
439044
def make_uhs(hmap, info):
    
    uhs = numpy.zeros(len(hmap), info['uhs_dt'])
    for p, poe in enumerate(info['poes']):
        for m, imt in enumerate(info['imtls']):
            if imt.startswith(('PGA', 'SA')):
                uhs[str(poe)][imt] = hmap[:, m, p]
    return uhs
749042
def initialize_plot(self, ranges=None):
        
        # Get element key and ranges for frame
        return self.generate_plot(list(self.hmap.data.keys())[0], ranges)
256418
def _parse_spectra(self, line):
        
        if line in ['\n', '\r\n', '//\n', '//\r\n', '', '//']:
            self.start_spectra = False
            self.current_id_meta += 1
            self.collect_meta = True
            return

        splist = line.split()

        if len(splist) > 2 and not self.ignore_additional_spectra_info:
            additional_info = ''.join(map(str, splist[2:len(splist)]))
        else:
            additional_info = ''

        srow = (
            self.current_id_spectra, float(splist[0]), float(splist[1]), additional_info,
            self.current_id_meta)

        self.spectra_all.append(srow)

        self.current_id_spectra += 1
1073092
def _process_infohash_list(infohash_list):
        
        if isinstance(infohash_list, list):
            data = {'hashes': '|'.join([h.lower() for h in infohash_list])}
        else:
            data = {'hashes': infohash_list.lower()}
        return data
217564
def _build_information(self):
        
        lag_time = float(self.lag_time)

        # only the "active set" of variables not at the bounds of the
        # feasible set.
        inds = np.where(self.theta_ != 0)[0]

        hessian = _ratematrix.hessian(
            self.theta_, self.countsmat_, t=lag_time, inds=inds)

        self.information_ = np.zeros((len(self.theta_), len(self.theta_)))
        self.information_[np.ix_(inds, inds)] = scipy.linalg.pinv(-hessian)
850863
def export_curves_stats(self, aids, key):
        
        oq = self.dstore['oqparam']
        stats = oq.hazard_stats().items()  # pair (name, func)
        stat2idx = {stat[0]: s for s, stat in enumerate(stats)}
        if 'loss_curves-stats' in self.dstore:  # classical_risk
            dset = self.dstore['loss_curves-stats']
            data = dset[aids]  # shape (A, S)
            if key == 'stats':
                return {stat[0]: data[:, s] for s, stat in enumerate(stats)}
            else:  # a specific statistics
                return {key: data[:, stat2idx[key]]}
        elif 'curves-stats' in self.dstore:  # event_based_risk
            dset = self.dstore['curves-stats']
            data = dset[aids]
            if key == 'stats':
                return {stat[0]: data[:, s] for s, stat in enumerate(stats)}
            else:  # a specific statistics
                return {key: data[:, stat2idx[key]]}
        else:
            raise KeyError('no loss curves in %s' % self.dstore)
268957
def combine(pmaps):
    
    shape = get_shape(pmaps)
    res = ProbabilityMap(shape[1], shape[2])
    for pmap in pmaps:
        res |= pmap
    return res
783709
def smoothed_hazard_confidence_intervals_(self, bandwidth, hazard_=None):
        
        if hazard_ is None:
            hazard_ = self.smoothed_hazard_(bandwidth).values[:, 0]

        timeline = self.timeline
        z = inv_normal_cdf(1 - self.alpha / 2)
        self._cumulative_sq.iloc[0] = 0
        var_hazard_ = self._cumulative_sq.diff().fillna(self._cumulative_sq.iloc[0])
        C = var_hazard_.values != 0.0  # only consider the points with jumps
        std_hazard_ = np.sqrt(
            1.0
            / (bandwidth ** 2)
            * np.dot(
                epanechnikov_kernel(timeline[:, None], timeline[C][None, :], bandwidth) ** 2, var_hazard_.values[C]
            )
        )
        values = {
            self.ci_labels[0]: hazard_ * np.exp(z * std_hazard_ / hazard_),
            self.ci_labels[1]: hazard_ * np.exp(-z * std_hazard_ / hazard_),
        }
        return pd.DataFrame(values, index=timeline)
548989
def hmap_dt(self):  # used for CSV export
        
        return numpy.dtype([('%s-%s' % (imt, poe), F32)
                            for imt in self.imtls for poe in self.poes])
1049809
def smoothed_hazard_(self, bandwidth):
        
        timeline = self.timeline
        cumulative_hazard_name = self.cumulative_hazard_.columns[0]
        hazard_name = "differenced-" + cumulative_hazard_name
        hazard_ = self.cumulative_hazard_.diff().fillna(self.cumulative_hazard_.iloc[0])
        C = (hazard_[cumulative_hazard_name] != 0.0).values
        return pd.DataFrame(
            1.0
            / bandwidth
            * np.dot(epanechnikov_kernel(timeline[:, None], timeline[C][None, :], bandwidth), hazard_.values[C, :]),
            columns=[hazard_name],
            index=timeline,
        )
854650
def build_maps(self, losses, clp, stats=()):
        
        shp = losses.shape[:2] + (len(clp), len(losses.dtype))  # (A, R, C, LI)
        array = numpy.zeros(shp, F32)
        for lti, lt in enumerate(losses.dtype.names):
            for a, losses_ in enumerate(losses[lt]):
                for r, ls in enumerate(losses_):
                    for c, poe in enumerate(clp):
                        clratio = conditional_loss_ratio(ls, self.poes, poe)
                        array[a, r, c, lti] = clratio
        return self.pair(array, stats)
750037
def transform(self, x, warn=True):
        
        # 1. split across last dimension
        # 2. re-use ranges
        # 3. Merge
        array_list = [encodeSplines(x[..., i].reshape((-1, 1)),
                                    n_bases=self.n_bases,
                                    spline_order=self.degree,
                                    warn=warn,
                                    start=self.data_min_[i],
                                    end=self.data_max_[i]).reshape(x[..., i].shape + (self.n_bases,))
                      for i in range(x.shape[-1])]
        return np.stack(array_list, axis=-2)
3101
def make_iml4(R, iml_disagg, imtls=None, poes_disagg=(None,), curves=()):
    
    if imtls is None:
        imtls = {imt: [iml] for imt, iml in iml_disagg.items()}
    N = len(curves) or 1
    M = len(imtls)
    P = len(poes_disagg)
    arr = numpy.zeros((N, R, M, P))
    imts = [from_string(imt) for imt in imtls]
    for m, imt in enumerate(imtls):
        imls = imtls[imt]
        for p, poe in enumerate(poes_disagg):
            for r in range(R):
                arr[:, r, m, p] = _imls(curves, poe, imt, imls, r)
    return ArrayWrapper(arr, dict(poes_disagg=poes_disagg, imts=imts))
1345045
def default_classification_value_maps(classification):
    
    value_maps = {}
    for hazard_class in classification['classes']:
        value_maps[hazard_class['key']] = hazard_class.get(
            'string_defaults', [])

    return value_maps
482720
def data(self, profile_data):
        
        default_profile = generate_default_profile()
        self.clear()
        for hazard in sorted(default_profile.keys()):
            classifications = default_profile[hazard]
            hazard_widget_item = QTreeWidgetItem()
            hazard_widget_item.setData(0, Qt.UserRole, hazard)
            hazard_widget_item.setText(0, get_name(hazard))
            for classification in sorted(classifications.keys()):
                # Filter out classification that doesn't support population.
                # TODO(IS): This is not the best place to put the filtering.
                # It's more suitable in the generate_default_profile method
                # in safe/definitions/utilities.
                classification_definition = definition(classification)
                supported_exposures = classification_definition.get(
                    'exposures', [])
                # Empty list means support all exposure
                if supported_exposures != []:
                    if exposure_population not in supported_exposures:
                        continue
                classes = classifications[classification]
                classification_widget_item = QTreeWidgetItem()
                classification_widget_item.setData(
                    0, Qt.UserRole, classification)
                classification_widget_item.setText(0, get_name(classification))
                hazard_widget_item.addChild(classification_widget_item)
                for the_class, the_value in list(classes.items()):
                    the_class_widget_item = QTreeWidgetItem()
                    the_class_widget_item.setData(0, Qt.UserRole, the_class)
                    the_class_widget_item.setText(
                        0, get_class_name(the_class, classification))
                    classification_widget_item.addChild(the_class_widget_item)
                    # Adding widget must be happened after addChild
                    affected_check_box = QCheckBox(self)
                    # Set from profile_data if exist, else get default
                    profile_value = profile_data.get(
                        hazard, {}).get(classification, {}).get(
                        the_class, the_value)

                    affected_check_box.setChecked(profile_value['affected'])
                    self.setItemWidget(
                        the_class_widget_item, 1, affected_check_box)
                    displacement_rate_spinbox = PercentageSpinBox(self)
                    displacement_rate_spinbox.setValue(
                        profile_value['displacement_rate'])
                    displacement_rate_spinbox.setEnabled(
                        profile_value['affected'])
                    self.setItemWidget(
                        the_class_widget_item, 2, displacement_rate_spinbox)
                    # Behaviour when the check box is checked
                    # noinspection PyUnresolvedReferences
                    affected_check_box.stateChanged.connect(
                        displacement_rate_spinbox.setEnabled)
            if hazard_widget_item.childCount() > 0:
                self.widget_items.append(hazard_widget_item)

        self.addTopLevelItems(self.widget_items)

        self.expandAll()
661972
def spectra(
            self):
        
        specResultsList = []
        specResultsList[:] = [dict(l) for l in self.specResultsList]
        return specResultsList
868671
function createUniformWrapper(gl, program, uniforms, locations) {

  function makeGetter(index) {
    var proc = new Function('gl', 'prog', 'locations', 
      'return function(){return gl.getUniform(prog,locations[' + index + '])}') 
    return proc(gl, program, locations)
  }

  function makePropSetter(path, index, type) {
    switch(type) {
      case 'bool':
      case 'int':
      case 'sampler2D':
      case 'samplerCube':
        return 'gl.uniform1i(locations[' + index + '],obj' + path + ')'
      case 'float':
        return 'gl.uniform1f(locations[' + index + '],obj' + path + ')'
      default:
        var vidx = type.indexOf('vec')
        if(0 <= vidx && vidx <= 1 && type.length === 4 + vidx) {
          var d = type.charCodeAt(type.length-1) - 48
          if(d < 2 || d > 4) {
            throw new Error('gl-shader: Invalid data type')
          }
          switch(type.charAt(0)) {
            case 'b':
            case 'i':
              return 'gl.uniform' + d + 'iv(locations[' + index + '],obj' + path + ')'
            case 'v':
              return 'gl.uniform' + d + 'fv(locations[' + index + '],obj' + path + ')'
            default:
              throw new Error('gl-shader: Unrecognized data type for vector ' + name + ': ' + type)
          }
        } else if(type.indexOf('mat') === 0 && type.length === 4) {
          var d = type.charCodeAt(type.length-1) - 48
          if(d < 2 || d > 4) {
            throw new Error('gl-shader: Invalid uniform dimension type for matrix ' + name + ': ' + type)
          }
          return 'gl.uniformMatrix' + d + 'fv(locations[' + index + '],false,obj' + path + ')'
        } else {
          throw new Error('gl-shader: Unknown uniform data type for ' + name + ': ' + type)
        }
      break
    }
  }

  function enumerateIndices(prefix, type) {
    if(typeof type !== 'object') {
      return [ [prefix, type] ]
    }
    var indices = []
    for(var id in type) {
      var prop = type[id]
      var tprefix = prefix
      if(parseInt(id) + '' === id) {
        tprefix += '[' + id + ']'
      } else {
        tprefix += '.' + id
      }
      if(typeof prop === 'object') {
        indices.push.apply(indices, enumerateIndices(tprefix, prop))
      } else {
        indices.push([tprefix, prop])
      }
    }
    return indices
  }

  function makeSetter(type) {
    var code = [ 'return function updateProperty(obj){' ]
    var indices = enumerateIndices('', type)
    for(var i=0; i<indices.length; ++i) {
      var item = indices[i]
      var path = item[0]
      var idx  = item[1]
      if(locations[idx]) {
        code.push(makePropSetter(path, idx, uniforms[idx].type))
      }
    }
    code.push('return obj}')
    var proc = new Function('gl', 'prog', 'locations', code.join('\n'))
    return proc(gl, program, locations)
  }

  function defaultValue(type) {
    switch(type) {
      case 'bool':
        return false
      case 'int':
      case 'sampler2D':
      case 'samplerCube':
        return 0
      case 'float':
        return 0.0
      default:
        var vidx = type.indexOf('vec')
        if(0 <= vidx && vidx <= 1 && type.length === 4 + vidx) {
          var d = type.charCodeAt(type.length-1) - 48
          if(d < 2 || d > 4) {
            throw new Error('gl-shader: Invalid data type')
          }
          if(type.charAt(0) === 'b') {
            return dup(d, false)
          }
          return dup(d)
        } else if(type.indexOf('mat') === 0 && type.length === 4) {
          var d = type.charCodeAt(type.length-1) - 48
          if(d < 2 || d > 4) {
            throw new Error('gl-shader: Invalid uniform dimension type for matrix ' + name + ': ' + type)
          }
          return dup([d,d])
        } else {
          throw new Error('gl-shader: Unknown uniform data type for ' + name + ': ' + type)
        }
      break
    }
  }

  function storeProperty(obj, prop, type) {
    if(typeof type === 'object') {
      var child = processObject(type)
      Object.defineProperty(obj, prop, {
        get: identity(child),
        set: makeSetter(type),
        enumerable: true,
        configurable: false
      })
    } else {
      if(locations[type]) {
        Object.defineProperty(obj, prop, {
          get: makeGetter(type),
          set: makeSetter(type),
          enumerable: true,
          configurable: false
        })
      } else {
        obj[prop] = defaultValue(uniforms[type].type)
      }
    }
  }

  function processObject(obj) {
    var result
    if(Array.isArray(obj)) {
      result = new Array(obj.length)
      for(var i=0; i<obj.length; ++i) {
        storeProperty(result, i, obj[i])
      }
    } else {
      result = {}
      for(var id in obj) {
        storeProperty(result, id, obj[id])
      }
    }
    return result
  }

  //Return data
  var coallesced = coallesceUniforms(uniforms, true)
  return {
    get: identity(processObject(coallesced)),
    set: makeSetter(coallesced),
    enumerable: true,
    configurable: true
  }
}