Validares a node representation of a planar fault geometry
772262
def _validate_planar_fault_geometry(self, node, _float_re):
        
        valid_spacing = node["spacing"]
        for key in ["topLeft", "topRight", "bottomLeft", "bottomRight"]:
            lon = getattr(node, key)["lon"]
            lat = getattr(node, key)["lat"]
            depth = getattr(node, key)["depth"]
            valid_lon = (lon >= -180.0) and (lon <= 180.0)
            valid_lat = (lat >= -90.0) and (lat <= 90.0)
            valid_depth = (depth >= 0.0)
            is_valid = valid_lon and valid_lat and valid_depth
            if not is_valid or not valid_spacing:
                raise LogicTreeError(
                    node, self.filename,
                    "'planarFaultGeometry' node is not valid")
988603
def is_valid_geometry(self):
        
        has_sites = (self.sites is not None or 'sites' in self.inputs
                     or 'site_model' in self.inputs)
        if not has_sites and not self.ground_motion_fields:
            # when generating only the ruptures you do not need the sites
            return True
        if ('gmfs' in self.inputs and not has_sites and
                not self.inputs['gmfs'].endswith('.xml')):
            raise ValueError('Missing sites or sites_csv in the .ini file')
        elif ('risk' in self.calculation_mode or
                'damage' in self.calculation_mode or
                'bcr' in self.calculation_mode):
            return True  # no check on the sites for risk
        flags = dict(
            sites=bool(self.sites),
            sites_csv=self.inputs.get('sites', 0),
            hazard_curves_csv=self.inputs.get('hazard_curves', 0),
            gmfs_csv=self.inputs.get('gmfs', 0),
            region=bool(self.region and self.region_grid_spacing))
        # NB: below we check that all the flags
        # are mutually exclusive
        return sum(bool(v) for v in flags.values()) == 1 or self.inputs.get(
            'exposure') or self.inputs.get('site_model')
1202191
function ( inPolygonData ) {
		// positional slots for neighboring trapezoid-diagonals
		var DIAG_UL = 0, DIAG_UM = 1, DIAG_ULR = 2, DIAG_UR = 3;
		var DIAG_DR = 4, DIAG_DM = 5, DIAG_DLR = 6, DIAG_DL = 7;

		var i, j;
		var nbVertices = inPolygonData.nbVertices();

		// initialize arrays for neighboring trapezoid-diagonals and vertices
		var myVisibleDiagonals	= new Array(nbVertices);
		for ( i = 0; i < nbVertices; i++ ) {
			myVisibleDiagonals[i] = new Array(DIAG_DL+1);
		}
		// create the list of neighboring trapezoid-diagonals
		//	put into their positional slots
		var myExternalNeighbors = new Array(nbVertices);
		for ( i = 0, j = this.trapArray.length; i < j; i++ ) {
			var curTrap = this.trapArray[i];
			var highPos = curTrap.uL ?
						( curTrap.uR ? DIAG_DM : DIAG_DL ) :
						( curTrap.uR ? DIAG_DR : DIAG_DLR );
			var lowPos = curTrap.dL ?
						( curTrap.dR ? DIAG_UM : DIAG_UL ) :
						( curTrap.dR ? DIAG_UR : DIAG_ULR );

			if ( ( curTrap.depth % 2 ) == 1 ) {		// inside ?
				if ( ( highPos == DIAG_DM ) || ( lowPos == DIAG_UM ) ||
					 ( ( highPos == DIAG_DL ) && ( lowPos == DIAG_UR ) ) ||
					 ( ( highPos == DIAG_DR ) && ( lowPos == DIAG_UL ) ) ) {
					var lhDiag = inPolygonData.appendDiagonalsEntry( {
									vFrom: curTrap.vLow, vTo: curTrap.vHigh,
									mprev: null, mnext: null, marked: false } );
					var hlDiag = inPolygonData.appendDiagonalsEntry( {
									vFrom: curTrap.vHigh, vTo: curTrap.vLow, revDiag: lhDiag,
									mprev: null, mnext: null, marked: false } );
					lhDiag.revDiag = hlDiag;
					myVisibleDiagonals[ curTrap.vLow.id][ lowPos] = lhDiag;
					myVisibleDiagonals[curTrap.vHigh.id][highPos] = hlDiag;
				}
			} else {		// outside, hole
				if ( curTrap.vHigh.id !== null )	myExternalNeighbors[curTrap.vHigh.id] = highPos;
				if ( curTrap.vLow.id  !== null )	myExternalNeighbors[ curTrap.vLow.id] = lowPos;
			}
		}
		// create the list of outgoing diagonals in the right order (CW)
		//	from the ordered list of neighboring trapezoid-diagonals
		//	- starting from an external one
		// and connect those incoming to
		var curDiag, curDiags, firstElem, fromVertex, lastIncoming;
		for ( i = 0; i < nbVertices; i++ ) {
			curDiags  = myVisibleDiagonals[i];
			firstElem = myExternalNeighbors[i];
			if ( firstElem == null )	continue;		// eg. skipped vertices (zero length, co-linear		// NOT: === !
			j = firstElem;
			lastIncoming = null;
			do {
				if ( j++ > DIAG_DL )			j = DIAG_UL;	// circular positional list
				if ( curDiag = curDiags[j] ) {
					if ( lastIncoming ) {
						curDiag.mprev = lastIncoming;
						lastIncoming.mnext = curDiag;
					} else {
						fromVertex = curDiag.vFrom;
						fromVertex.firstOutDiag = curDiag;
					}
					lastIncoming = curDiag.revDiag;
				}
			} while ( j != firstElem );
			if ( lastIncoming )		fromVertex.lastInDiag = lastIncoming;
		}
	}
148618
def is_valid_complex_fault_mesh_spacing(self):
        
        rms = getattr(self, 'rupture_mesh_spacing', None)
        if rms and not getattr(self, 'complex_fault_mesh_spacing', None):
            self.complex_fault_mesh_spacing = self.rupture_mesh_spacing
        return True
1181603
void constructLinearSystem(List<DMatrixRMaj> homographies,
							   List<List<PointIndex2D_F64>> observations) {
		// parameters are encoded points first then the
		int startView = totalFeatures*3;

		A.reshape(numEquations,numUnknown);

		DMatrixRMaj H = new DMatrixRMaj(3,3);
		Point2D_F64 p = new Point2D_F64();

		int row = 0;
		for (int viewIdx = 0; viewIdx < homographies.size(); viewIdx++) {
			N.apply(homographies.get(viewIdx),H);

			int colView = startView + viewIdx*3;

			List<PointIndex2D_F64> obs = observations.get(viewIdx);
			for (int i = 0; i < obs.size(); i++) {
				PointIndex2D_F64 p_pixel = obs.get(i);

				N.apply(p_pixel,p);

				// column this feature is at
				int col = p_pixel.index*3;

				// x component of pixel
				// A(row,colView) =  ...
				A.data[row*A.numCols + col    ] = p.x*H.get(2,0) - H.get(0,0);
				A.data[row*A.numCols + col + 1] = p.x*H.get(2,1) - H.get(0,1);
				A.data[row*A.numCols + col + 2] = p.x*H.get(2,2) - H.get(0,2);

				A.data[row*A.numCols + colView     ] = -1;
				A.data[row*A.numCols + colView + 1 ] = 0;
				A.data[row*A.numCols + colView + 2 ] = p.x;

				// y component of pixel
				row += 1;
				A.data[row*A.numCols + col    ] = p.y*H.get(2,0) - H.get(1,0);
				A.data[row*A.numCols + col + 1] = p.y*H.get(2,1) - H.get(1,1);
				A.data[row*A.numCols + col + 2] = p.y*H.get(2,2) - H.get(1,2);

				A.data[row*A.numCols + colView     ] = 0;
				A.data[row*A.numCols + colView + 1 ] = -1;
				A.data[row*A.numCols + colView + 2 ] = p.y;

				row += 1;
			}
		}
	}
1264084
def build_rupture_node(rupt, probs_occur):
    
    s = sum(probs_occur)
    if abs(s - 1) > pmf.PRECISION:
        raise ValueError('The sum of %s is not 1: %s' % (probs_occur, s))
    h = rupt.hypocenter
    hp_dict = dict(lon=h.longitude, lat=h.latitude, depth=h.depth)
    rupt_nodes = [Node('magnitude', {}, rupt.mag),
                  Node('rake', {}, rupt.rake),
                  Node('hypocenter', hp_dict)]
    rupt_nodes.extend(rupt.surface.surface_nodes)
    geom = rupt.surface.surface_nodes[0].tag
    if len(rupt.surface.surface_nodes) > 1:
        name = 'multiPlanesRupture'
    elif geom == 'planarSurface':
        name = 'singlePlaneRupture'
    elif geom == 'simpleFaultGeometry':
        name = 'simpleFaultRupture'
    elif geom == 'complexFaultGeometry':
        name = 'complexFaultRupture'
    elif geom == 'griddedSurface':
        name = 'griddedRupture'
    return Node(name, {'probs_occur': probs_occur}, nodes=rupt_nodes)
750377
function constrainedMDSLayout(areas, params) {
        params = params || {};
        var restarts = params.restarts || 10;

        // bidirectionally map sets to a rowid  (so we can create a matrix)
        var sets = [],
            setids = {},
            i;
        for (i = 0; i < areas.length; ++i) {
            var area = areas[i];
            if (area.sets.length == 1) {
                setids[area.sets[0]] = sets.length;
                sets.push(area);
            }
        }

        var matrices = getDistanceMatrices(areas, sets, setids),
            distances = matrices.distances,
            constraints = matrices.constraints;

        // keep distances bounded, things get messed up otherwise.
        // TODO: proper preconditioner?
        var norm = norm2(distances.map(norm2)) / distances.length;
        distances = distances.map(function (row) {
            return row.map(function (value) {
                return value / norm;
            });
        });

        var obj = function obj(x, fxprime) {
            return constrainedMDSGradient(x, fxprime, distances, constraints);
        };

        var best, current;
        for (i = 0; i < restarts; ++i) {
            var initial = zeros(distances.length * 2).map(Math.random);

            current = conjugateGradient(obj, initial, params);
            if (!best || current.fx < best.fx) {
                best = current;
            }
        }
        var positions = best.x;

        // translate rows back to (x,y,radius) coordinates
        var circles = {};
        for (i = 0; i < sets.length; ++i) {
            var set = sets[i];
            circles[set.sets[0]] = {
                x: positions[2 * i] * norm,
                y: positions[2 * i + 1] * norm,
                radius: Math.sqrt(set.size / Math.PI)
            };
        }

        if (params.history) {
            for (i = 0; i < params.history.length; ++i) {
                scale(params.history[i].x, norm);
            }
        }
        return circles;
    }
1060327
function splatND(out, points, weights, radius) {
  var n = points.shape[0]
  var d = points.shape[1]
  var lo = new Array(d)
  var hi = new Array(d)
  var bounds = out.shape
  var coord = new Array(d+1)
  var w = 1.0
  function splatRec(k) {
    if(k < 0) {
      coord[d] = out.get.apply(out, coord) + w
      out.set.apply(out, coord)
      return
    }
    var wprev = w
    var x = points.get(i, k)
    for(coord[k]=lo[k]; coord[k]<hi[k]; ++coord[k]) {
      w = wprev * dirichlet(bounds[k], coord[k] - x)
      splatRec(k-1)
    }
    w = wprev
  }

  for(var i=0; i<=d; ++i) {
    coord[i] = 0
  }

  for(var i=0; i<n; ++i) {
    for(var j=0; j<d; ++j) {
      var x = points.get(i,j)
      lo[j] = Math.max(x-radius, 0)
      hi[j] = Math.min(x+radius, bounds[j]-1)
    }
    w = weights.get(i)
    splatRec(d-1)
  }
}
1367309
def get_ucerf_rupture(self, iloc, src_filter):
        
        trt = self.tectonic_region_type
        ridx = self.get_ridx(iloc)
        mag = self.orig.mags[iloc]
        surface_set = []
        indices = src_filter.get_indices(self, ridx, mag)
        if len(indices) == 0:
            return None
        for trace, plane in self.gen_trace_planes(ridx):
            # build simple fault surface
            for jloc in range(0, plane.shape[2]):
                top_left = Point(
                    plane[0, 0, jloc], plane[0, 1, jloc], plane[0, 2, jloc])
                top_right = Point(
                    plane[1, 0, jloc], plane[1, 1, jloc], plane[1, 2, jloc])
                bottom_right = Point(
                    plane[2, 0, jloc], plane[2, 1, jloc], plane[2, 2, jloc])
                bottom_left = Point(
                    plane[3, 0, jloc], plane[3, 1, jloc], plane[3, 2, jloc])
                try:
                    surface_set.append(
                        ImperfectPlanarSurface.from_corner_points(
                            top_left, top_right, bottom_right, bottom_left))
                except ValueError as err:
                    raise ValueError(err, trace, top_left, top_right,
                                     bottom_right, bottom_left)

        rupture = ParametricProbabilisticRupture(
            mag, self.orig.rake[iloc], trt,
            surface_set[len(surface_set) // 2].get_middle_point(),
            MultiSurface(surface_set), self.orig.rate[iloc], self.tom)

        return rupture
1048294
def build_area_source_geometry(area_source):
    
    geom = []
    for lon_lat in zip(area_source.polygon.lons, area_source.polygon.lats):
        geom.extend(lon_lat)
    poslist_node = Node("gml:posList", text=geom)
    linear_ring_node = Node("gml:LinearRing", nodes=[poslist_node])
    exterior_node = Node("gml:exterior", nodes=[linear_ring_node])
    polygon_node = Node("gml:Polygon", nodes=[exterior_node])
    upper_depth_node = Node(
        "upperSeismoDepth", text=area_source.upper_seismogenic_depth)
    lower_depth_node = Node(
        "lowerSeismoDepth", text=area_source.lower_seismogenic_depth)
    return Node(
        "areaGeometry", {'discretization': area_source.area_discretization},
        nodes=[polygon_node, upper_depth_node, lower_depth_node])
1192829
def export(self, mesh, rlzs_by_gsim, num_ses):
        
        rupture = self.rupture
        events = self.get_events(rlzs_by_gsim)
        events_by_ses = self.get_events_by_ses(events, num_ses)
        new = ExportedRupture(self.serial, events_by_ses)
        new.mesh = mesh[()]
        if isinstance(rupture.surface, geo.ComplexFaultSurface):
            new.typology = 'complexFaultsurface'
        elif isinstance(rupture.surface, geo.SimpleFaultSurface):
            new.typology = 'simpleFaultsurface'
        elif isinstance(rupture.surface, geo.GriddedSurface):
            new.typology = 'griddedRupture'
        elif isinstance(rupture.surface, geo.MultiSurface):
            new.typology = 'multiPlanesRupture'
        else:
            new.typology = 'singlePlaneRupture'
        new.is_from_fault_source = iffs = isinstance(
            rupture.surface, (geo.ComplexFaultSurface,
                              geo.SimpleFaultSurface))
        new.is_gridded_surface = igs = isinstance(
            rupture.surface, geo.GriddedSurface)
        new.is_multi_surface = ims = isinstance(
            rupture.surface, geo.MultiSurface)
        new.lons, new.lats, new.depths = get_geom(
            rupture.surface, iffs, ims, igs)
        new.surface = rupture.surface
        new.strike = rupture.surface.get_strike()
        new.dip = rupture.surface.get_dip()
        new.rake = rupture.rake
        new.hypocenter = rupture.hypocenter
        new.tectonic_region_type = rupture.tectonic_region_type
        new.magnitude = new.mag = rupture.mag
        new.top_left_corner = None if iffs or ims or igs else (
            new.lons[0], new.lats[0], new.depths[0])
        new.top_right_corner = None if iffs or ims or igs else (
            new.lons[1], new.lats[1], new.depths[1])
        new.bottom_left_corner = None if iffs or ims or igs else (
            new.lons[2], new.lats[2], new.depths[2])
        new.bottom_right_corner = None if iffs or ims or igs else (
            new.lons[3], new.lats[3], new.depths[3])
        return new
95671
def parse_uncertainty_value(self, node, branchset):
        
        if branchset.uncertainty_type == 'sourceModel':
            return node.text.strip()
        elif branchset.uncertainty_type == 'abGRAbsolute':
            [a, b] = node.text.strip().split()
            return float(a), float(b)
        elif branchset.uncertainty_type == 'incrementalMFDAbsolute':
            min_mag, bin_width = (node.incrementalMFD["minMag"],
                                  node.incrementalMFD["binWidth"])
            return min_mag,  bin_width, ~node.incrementalMFD.occurRates
        elif branchset.uncertainty_type == 'simpleFaultGeometryAbsolute':
            return self._parse_simple_fault_geometry_surface(
                node.simpleFaultGeometry)
        elif branchset.uncertainty_type == 'complexFaultGeometryAbsolute':
            return self._parse_complex_fault_geometry_surface(
                node.complexFaultGeometry)
        elif branchset.uncertainty_type ==\
                'characteristicFaultGeometryAbsolute':
            surfaces = []
            for geom_node in node.surface:
                if "simpleFaultGeometry" in geom_node.tag:
                    trace, usd, lsd, dip, spacing =\
                        self._parse_simple_fault_geometry_surface(geom_node)
                    surfaces.append(geo.SimpleFaultSurface.from_fault_data(
                        trace, usd, lsd, dip, spacing))
                elif "complexFaultGeometry" in geom_node.tag:
                    edges, spacing =\
                        self._parse_complex_fault_geometry_surface(geom_node)
                    surfaces.append(geo.ComplexFaultSurface.from_fault_data(
                        edges, spacing))
                elif "planarSurface" in geom_node.tag:
                    surfaces.append(
                        self._parse_planar_geometry_surface(geom_node))
                else:
                    pass
            if len(surfaces) > 1:
                return geo.MultiSurface(surfaces)
            else:
                return surfaces[0]
        else:
            return float(node.text.strip())
1071103
function ( relationships, geoNode, deformers ) {

			switch ( geoNode.attrType ) {

				case 'Mesh':
					return this.parseMeshGeometry( relationships, geoNode, deformers );
					break;

				case 'NurbsCurve':
					return this.parseNurbsGeometry( geoNode );
					break;

			}

		}
931164
def _compute_pga_rock(self, C, dc1, sites, rup, dists):
        
        mean = (self._compute_magnitude_term(C, dc1, rup.mag) +
                self._compute_distance_term(C, rup.mag, dists) +
                self._compute_focal_depth_term(C, rup) +
                self._compute_forearc_backarc_term(C, sites, dists))
        # Apply linear site term
        site_response = ((C['theta12'] + C['b'] * self.CONSTS['n']) *
                         np.log(1000. / C['vlin']))
        return mean + site_response
1355711
def set_simple_fault_geometry(w, src):
    
    assert "simpleFaultSource" in src.tag
    geometry_node = src.nodes[get_taglist(src).index("simpleFaultGeometry")]
    fault_attrs = parse_simple_fault_geometry(geometry_node)
    w.line(parts=[fault_attrs["trace"].tolist()])
978381
def convert_nonParametricSeismicSource(self, node):
        
        trt = node.attrib.get('tectonicRegion')
        rup_pmf_data = []
        rups_weights = None
        if 'rup_weights' in node.attrib:
            tmp = node.attrib.get('rup_weights')
            rups_weights = numpy.array([float(s) for s in tmp.split()])
        for i, rupnode in enumerate(node):
            probs = pmf.PMF(valid.pmf(rupnode['probs_occur']))
            rup = RuptureConverter.convert_node(self, rupnode)
            rup.tectonic_region_type = trt
            rup.weight = None if rups_weights is None else rups_weights[i]
            rup_pmf_data.append((rup, probs))
        nps = source.NonParametricSeismicSource(
            node['id'], node['name'], trt, rup_pmf_data)
        nps.splittable = 'rup_weights' not in node.attrib
        return nps
1363003
def build_multi_point_source_node(multi_point_source):
    
    # parse geometry
    pos = []
    for p in multi_point_source.mesh:
        pos.append(p.x)
        pos.append(p.y)
    mesh_node = Node('gml:posList', text=pos)
    upper_depth_node = Node(
        "upperSeismoDepth", text=multi_point_source.upper_seismogenic_depth)
    lower_depth_node = Node(
        "lowerSeismoDepth", text=multi_point_source.lower_seismogenic_depth)
    source_nodes = [Node(
        "multiPointGeometry",
        nodes=[mesh_node, upper_depth_node, lower_depth_node])]
    # parse common distributed attributes
    source_nodes.extend(get_distributed_seismicity_source_nodes(
        multi_point_source))
    return Node("multiPointSource",
                get_source_attributes(multi_point_source),
                nodes=source_nodes)