Parses a planar geometry surface
193535
def _parse_planar_geometry_surface(self, node):
        
        nodes = []
        for key in ["topLeft", "topRight", "bottomRight", "bottomLeft"]:
            nodes.append(geo.Point(getattr(node, key)["lon"],
                                   getattr(node, key)["lat"],
                                   getattr(node, key)["depth"]))
        top_left, top_right, bottom_right, bottom_left = tuple(nodes)
        return geo.PlanarSurface.from_corner_points(
            top_left, top_right, bottom_right, bottom_left)
978702
def parse_planar_fault_geometry(node):
    
    assert "planarSurface" in node.tag
    geometry = {"strike": node.attrib["strike"],
                "dip": node.attrib["dip"]}
    upper_depth = numpy.inf
    lower_depth = 0.0
    tags = get_taglist(node)
    corner_points = []
    for locn in ["topLeft", "topRight", "bottomRight", "bottomLeft"]:
        plane = node.nodes[tags.index(locn)]
        upper_depth = plane["depth"] if plane["depth"] < upper_depth else\
            upper_depth
        lower_depth = plane["depth"] if plane["depth"] > lower_depth else\
            lower_depth
        corner_points.append([plane["lon"], plane["lat"], plane["depth"]])
    geometry["upperSeismoDepth"] = upper_depth
    geometry["lowerSeismoDepth"] = lower_depth
    geometry["corners"] = numpy.array(corner_points)
    return geometry
136059
function(collection) {
            var len = collection.components.length;
            var array = new Array(len);
            for(var i=0; i<len; ++i) {
                array[i] = this.extract.geometry.apply(
                    this, [collection.components[i]]
                );
            }
            return array;
        }
619813
def __geometryToDict(self, geom):
        """"""
        if isinstance(geom, dict):
            return geom
        elif isinstance(geom, Point):
            pt = geom.asDictionary
            return {"geometry": {"x" : pt['x'], "y" : pt['y']}}
        elif isinstance(geom, Polygon):
            poly = geom.asDictionary
            return {
                "geometry" : {
                    "rings" : poly['rings'],
                    'spatialReference' : poly['spatialReference']
                }
            }
        elif isinstance(geom, list):
            return [self.__geometryToDict(g) for g in geom]
346569
def parseGeometry(self, geometry):
        

        

        self.coordinates = []
        self.index = []
        self.position = 0
        self.lastX = 0 
        self.lastY = 0
        self.isPoly = False
        self.isPoint = True;
        self.dropped = 0;
        self.first = True
        # Used for exception strings
        self._current_string = geometry
        
        reader = _ExtendedUnPacker(geometry)
                
        # Start the parsing
        self._dispatchNextType(reader)
1156295
function parsePolygonGeometry(coordinates) {
		var polygonWkt = [];
		for (var i = 0; i < coordinates.length; i++) {
			polygonWkt.push('(' + parseLineGeometry(coordinates[i]) + ')');
		}
		return polygonWkt.join(', ');
	}
521163
function parseLineGeometry (coordinates) {
		var lineWkt = [];
		for (var i = 0; i < coordinates.length; i++) {
			lineWkt.push(parsePointGeometry(coordinates[i]));
		}
		return lineWkt.join(', ');
	}
979496
def _parse_coords(coord_lines):
        
        paras = {}
        var_pattern = re.compile(r"^([A-Za-z]+\S*)[\s=,]+([\d\-\.]+)$")
        for l in coord_lines:
            m = var_pattern.match(l.strip())
            if m:
                paras[m.group(1).strip("=")] = float(m.group(2))

        species = []
        coords = []
        # Stores whether a Zmatrix format is detected. Once a zmatrix format
        # is detected, it is assumed for the remaining of the parsing.
        zmode = False
        for l in coord_lines:
            l = l.strip()
            if not l:
                break
            if (not zmode) and GaussianInput._xyz_patt.match(l):
                m = GaussianInput._xyz_patt.match(l)
                species.append(m.group(1))
                toks = re.split(r"[,\s]+", l.strip())
                if len(toks) > 4:
                    coords.append([float(i) for i in toks[2:5]])
                else:
                    coords.append([float(i) for i in toks[1:4]])
            elif GaussianInput._zmat_patt.match(l):
                zmode = True
                toks = re.split(r"[,\s]+", l.strip())
                species.append(toks[0])
                toks.pop(0)
                if len(toks) == 0:
                    coords.append(np.array([0, 0, 0]))
                else:
                    nn = []
                    parameters = []
                    while len(toks) > 1:
                        ind = toks.pop(0)
                        data = toks.pop(0)
                        try:
                            nn.append(int(ind))
                        except ValueError:
                            nn.append(species.index(ind) + 1)
                        try:
                            val = float(data)
                            parameters.append(val)
                        except ValueError:
                            if data.startswith("-"):
                                parameters.append(-paras[data[1:]])
                            else:
                                parameters.append(paras[data])
                    if len(nn) == 1:
                        coords.append(np.array([0, 0, parameters[0]]))
                    elif len(nn) == 2:
                        coords1 = coords[nn[0] - 1]
                        coords2 = coords[nn[1] - 1]
                        bl = parameters[0]
                        angle = parameters[1]
                        axis = [0, 1, 0]
                        op = SymmOp.from_origin_axis_angle(coords1, axis,
                                                           angle, False)
                        coord = op.operate(coords2)
                        vec = coord - coords1
                        coord = vec * bl / np.linalg.norm(vec) + coords1
                        coords.append(coord)
                    elif len(nn) == 3:
                        coords1 = coords[nn[0] - 1]
                        coords2 = coords[nn[1] - 1]
                        coords3 = coords[nn[2] - 1]
                        bl = parameters[0]
                        angle = parameters[1]
                        dih = parameters[2]
                        v1 = coords3 - coords2
                        v2 = coords1 - coords2
                        axis = np.cross(v1, v2)
                        op = SymmOp.from_origin_axis_angle(
                            coords1, axis, angle, False)
                        coord = op.operate(coords2)
                        v1 = coord - coords1
                        v2 = coords1 - coords2
                        v3 = np.cross(v1, v2)
                        adj = get_angle(v3, axis)
                        axis = coords1 - coords2
                        op = SymmOp.from_origin_axis_angle(
                            coords1, axis, dih - adj, False)
                        coord = op.operate(coord)
                        vec = coord - coords1
                        coord = vec * bl / np.linalg.norm(vec) + coords1
                        coords.append(coord)

        def _parse_species(sp_str):
            """
            The species specification can take many forms. E.g.,
            simple integers representing atomic numbers ("8"),
            actual species string ("C") or a labelled species ("C1").
            Sometimes, the species string is also not properly capitalized,
            e.g, ("c1"). This method should take care of these known formats.
            """
            try:
                return int(sp_str)
            except ValueError:
                sp = re.sub(r"\d", "", sp_str)
                return sp.capitalize()

        species = [_parse_species(sp) for sp in species]

        return Molecule(species, coords)
881701
def extract_geometry(dataset):
        
        alg = vtk.vtkGeometryFilter()
        alg.SetInputDataObject(dataset)
        alg.Update()
        return _get_output(alg)
899778
private void parseGeometryMetadata(JsonParser jp, String geometryType) throws IOException, SQLException {        
        if (geometryType.equalsIgnoreCase(GeoJsonField.POINT)) {
             parsePointMetadata(jp);
             finalGeometryTypes.add(GeoJsonField.POINT);
        } else if (geometryType.equalsIgnoreCase(GeoJsonField.MULTIPOINT)) {
             parseMultiPointMetadata(jp);
             finalGeometryTypes.add(GeoJsonField.MULTIPOINT);
        } else if (geometryType.equalsIgnoreCase(GeoJsonField.LINESTRING)) {
             parseLinestringMetadata(jp);
             finalGeometryTypes.add(GeoJsonField.LINESTRING);
        } else if (geometryType.equalsIgnoreCase(GeoJsonField.MULTILINESTRING)) {
            parseMultiLinestringMetadata(jp);
            finalGeometryTypes.add(GeoJsonField.MULTILINESTRING);
        } else if (geometryType.equalsIgnoreCase(GeoJsonField.POLYGON)) {
             parsePolygonMetadata(jp);
             finalGeometryTypes.add(GeoJsonField.POLYGON);
        } else if (geometryType.equalsIgnoreCase(GeoJsonField.MULTIPOLYGON)) {
             parseMultiPolygonMetadata(jp);
             finalGeometryTypes.add(GeoJsonField.MULTIPOLYGON);
        } else if (geometryType.equalsIgnoreCase(GeoJsonField.GEOMETRYCOLLECTION)) {
             parseGeometryCollectionMetadata(jp);
             finalGeometryTypes.add(GeoJsonField.GEOMETRYCOLLECTION);
        } else {
            throw new SQLException("Unsupported geometry : " + geometryType);
        }
    }
986765
def get_surface(shifts, orig_text, item, text):
    """"""
    span = item.span()
    logging.debug(u'\tInitial span: %s ("%s")', span, text[span[0]:span[1]])

    real_span = (span[0] - shifts[span[0]], span[1] - shifts[span[1] - 1])
    surface = orig_text[real_span[0]:real_span[1]]
    logging.debug(u'\tShifted span: %s ("%s")', real_span, surface)

    while any(surface.endswith(i) for i in [' ', '-']):
        surface = surface[:-1]
        real_span = (real_span[0], real_span[1] - 1)

    while surface.startswith(' '):
        surface = surface[1:]
        real_span = (real_span[0] + 1, real_span[1])

    logging.debug(u'\tFinal span: %s ("%s")', real_span, surface)
    return surface, real_span
41626
private void computeMatrixTopoGraphHalfEdges_(int geometry_a, int geometry_b) {
		boolean bRelationKnown = false;

		int id_a = m_topo_graph.getGeometryID(geometry_a);
		int id_b = m_topo_graph.getGeometryID(geometry_b);

		m_visited_index = m_topo_graph.createUserIndexForHalfEdges();

		for (int cluster = m_topo_graph.getFirstCluster(); cluster != -1; cluster = m_topo_graph
				.getNextCluster(cluster)) {
			int first_half_edge = m_topo_graph.getClusterHalfEdge(cluster);
            if (first_half_edge == -1)
            {
                if (m_predicates_cluster != -1)
                {
                    // Treat cluster as an interior point
                    switch (m_predicates_cluster)
                    {
                        case Predicates.AreaPointPredicates:
                            bRelationKnown = areaPointPredicates_(cluster, id_a, id_b);
                            break;
                        case Predicates.LinePointPredicates:
                            bRelationKnown = linePointPredicates_(cluster, id_a, id_b);
                            break;
                        default:
                            throw GeometryException.GeometryInternalError();
                    }
                }

                continue;
            }

			int next_half_edge = first_half_edge;

			do {
				int half_edge = next_half_edge;
				int visited = m_topo_graph.getHalfEdgeUserIndex(half_edge,
						m_visited_index);

				if (visited != 1) {
					do {
						// Invoke relational predicates
						switch (m_predicates_half_edge) {
						case Predicates.AreaAreaPredicates:
							bRelationKnown = areaAreaPredicates_(half_edge,
									id_a, id_b);
							break;
						case Predicates.AreaLinePredicates:
							bRelationKnown = areaLinePredicates_(half_edge,
									id_a, id_b);
							break;
						case Predicates.LineLinePredicates:
							bRelationKnown = lineLinePredicates_(half_edge,
									id_a, id_b);
							break;
						default:
							throw GeometryException.GeometryInternalError();
						}

						if (bRelationKnown)
							break;

						m_topo_graph.setHalfEdgeUserIndex(half_edge,
								m_visited_index, 1);
						half_edge = m_topo_graph.getHalfEdgeNext(half_edge);
					} while (half_edge != next_half_edge && !bRelationKnown);
				}

				if (bRelationKnown)
					break;

				next_half_edge = m_topo_graph.getHalfEdgeNext(m_topo_graph
						.getHalfEdgeTwin(half_edge));
			} while (next_half_edge != first_half_edge);

			if (bRelationKnown)
				break;
		}

		if (!bRelationKnown)
			setRemainingPredicatesToFalse_();

		m_topo_graph.deleteUserIndexForHalfEdges(m_visited_index);
	}
119591
def geo_planar(self, surface):
        
        with context(self.fname, surface):
            tl = surface.topLeft
            top_left = geo.Point(tl['lon'], tl['lat'], tl['depth'])
            tr = surface.topRight
            top_right = geo.Point(tr['lon'], tr['lat'], tr['depth'])
            bl = surface.bottomLeft
            bottom_left = geo.Point(bl['lon'], bl['lat'], bl['depth'])
            br = surface.bottomRight
            bottom_right = geo.Point(br['lon'], br['lat'], br['depth'])
        return geo.PlanarSurface.from_corner_points(
            top_left, top_right, bottom_right, bottom_left)
1157963
function parse (input) {
  var parts = input.split(';');
  var _ = parts.pop();
  var srid = (parts.shift() || '').split('=').pop();

  var i = 0;

  function $ (re) {
    var match = _.substring(i).match(re);
    if (!match) return null;
    else {
      i += match[0].length;
      return match[0];
    }
  }

  function crs (obj) {
    if (obj && srid.match(/\d+/)) {
      obj.crs = {
        type: 'name',
        properties: {
          name: 'urn:ogc:def:crs:EPSG::' + srid
        }
      };
    }

    return obj;
  }

  function white () { $(/^\s*/); }

  function multicoords () {
    white();
    var depth = 0;
    var rings = [];
    var stack = [rings];
    var pointer = rings;
    var elem;

    while (elem =
           $(/^(\()/) ||
             $(/^(\))/) ||
               $(/^(,)/) ||
                 $(tuples)) {
      if (elem === '(') {
        stack.push(pointer);
        pointer = [];
        stack[stack.length - 1].push(pointer);
        depth++;
      } else if (elem === ')') {
        // For the case: Polygon(), ...
        if (pointer.length === 0) return null;

        pointer = stack.pop();
        // the stack was empty, input was malformed
        if (!pointer) return null;
        depth--;
        if (depth === 0) break;
      } else if (elem === ',') {
        pointer = [];
        stack[stack.length - 1].push(pointer);
      } else if (!elem.split(/\s/g).some(isNaN)) {
        Array.prototype.push.apply(pointer, elem.split(/\s/g).map(parseFloat));
      } else {
        return null;
      }
      white();
    }

    if (depth !== 0) return null;

    return rings;
  }

  function coords () {
    var list = [];
    var item;
    var pt;
    while (pt =
           $(tuples) ||
             $(/^(,)/)) {
      if (pt === ',') {
        list.push(item);
        item = [];
      } else if (!pt.split(/\s/g).some(isNaN)) {
        if (!item) item = [];
        Array.prototype.push.apply(item, pt.split(/\s/g).map(parseFloat));
      }
      white();
    }

    if (item) list.push(item);
    else return null;

    return list.length ? list : null;
  }

  function point () {
    if (!$(/^(point(\sz)?)/i)) return null;
    white();
    if (!$(/^(\()/)) return null;
    var c = coords();
    if (!c) return null;
    white();
    if (!$(/^(\))/)) return null;
    return {
      type: 'Point',
      coordinates: c[0]
    };
  }

  function multipoint () {
    if (!$(/^(multipoint)/i)) return null;
    white();
    var newCoordsFormat = _
      .substring(_.indexOf('(') + 1, _.length - 1)
      .replace(/\(/g, '')
      .replace(/\)/g, '');
    _ = 'MULTIPOINT (' + newCoordsFormat + ')';
    var c = multicoords();
    if (!c) return null;
    white();
    return {
      type: 'MultiPoint',
      coordinates: c
    };
  }

  function multilinestring () {
    if (!$(/^(multilinestring)/i)) return null;
    white();
    var c = multicoords();
    if (!c) return null;
    white();
    return {
      type: 'MultiLineString',
      coordinates: c
    };
  }

  function linestring () {
    if (!$(/^(linestring(\sz)?)/i)) return null;
    white();
    if (!$(/^(\()/)) return null;
    var c = coords();
    if (!c) return null;
    if (!$(/^(\))/)) return null;
    return {
      type: 'LineString',
      coordinates: c
    };
  }

  function polygon () {
    if (!$(/^(polygon(\sz)?)/i)) return null;
    white();
    var c = multicoords();
    if (!c) return null;
    return {
      type: 'Polygon',
      coordinates: c
    };
  }

  function multipolygon () {
    if (!$(/^(multipolygon)/i)) return null;
    white();
    var c = multicoords();
    if (!c) return null;
    return {
      type: 'MultiPolygon',
      coordinates: c
    };
  }

  function geometrycollection () {
    var geometries = [];
    var geometry;

    if (!$(/^(geometrycollection)/i)) return null;
    white();

    if (!$(/^(\()/)) return null;
    while (geometry = root()) {
      geometries.push(geometry);
      white();
      $(/^(,)/);
      white();
    }
    if (!$(/^(\))/)) return null;

    return {
      type: 'GeometryCollection',
      geometries: geometries
    };
  }

  function root () {
    return point() ||
      linestring() ||
      polygon() ||
      multipoint() ||
      multilinestring() ||
      multipolygon() ||
      geometrycollection();
  }

  return crs(root());
}
771827
function parse_PtgArea3d(blob, length, opts) {
	var type = (blob[blob.l++] & 0x60) >> 5;
	var ixti = blob.read_shift(2, 'i');
	var w = 8;
	if(opts) switch(opts.biff) {
		case 5: blob.l += 12; w = 6; break;
		case 12: w = 12; break;
	}
	var area = parse_RgceArea(blob, w, opts);
	return [type, ixti, area];
}
897868
def extract_line(geom, dem, **kwargs):
    
    kwargs.setdefault('masked', True)

    coords_in = coords_array(geom)

    # Transform geometry into pixels
    f = lambda *x: ~dem.transform * x
    px = transform(f,geom)

    # Subdivide geometry segments if option is given
    interval = kwargs.pop('subdivide', 1)
    if interval is not None:
        px = subdivide(px, interval=interval)

    # Transform pixels back to geometry
    # to capture subdivisions
    f = lambda *x: dem.transform * (x[0],x[1])
    geom = transform(f,px)

    # Get min and max coords for windowing
    # Does not deal with edge cases where points
    # are outside of footprint of DEM

    coords_px = coords_array(px)
    mins = N.floor(coords_px.min(axis=0))
    maxs = N.ceil(coords_px.max(axis=0))

    window = tuple((int(mn),int(mx))
        for mn,mx in zip(mins[::-1],maxs[::-1]))

    aff = Affine.translation(*(-mins))

    f = lambda *x: aff * x
    px_to_extract = transform(f,px)

    band = dem.read(1, window=window, **kwargs)
    extracted = bilinear(band, px_to_extract)
    coords = coords_array(extracted)

    coords[:,:2] = coords_array(geom)
    return coords
1150479
def surface_to_array(surface):
    
    if hasattr(surface, 'surfaces'):  # multiplanar surfaces
        n = len(surface.surfaces)
        arr = numpy.zeros((3, n, 4), F32)
        for i, surf in enumerate(surface.surfaces):
            arr[:, i] = surf.mesh.array
        return arr
    mesh = surface.mesh
    if len(mesh.lons.shape) == 1:  # 1D mesh
        shp = (3, 1) + mesh.lons.shape
    else:  # 2D mesh
        shp = (3,) + mesh.lons.shape
    return mesh.array.reshape(shp)