Check and parse coordinates as either a single coordinate list [[r,c],[r,c]] or a
    list of coordinates for multiple regions [[[r0,c0],[r0,c0]], [[r1,c1],[r1,c1]]]
170990
def check_coordinates(co, xy=None):
    
    if isinstance(co, ndarray):
        co = co.tolist()
    if not (isinstance(co[0][0], list) or isinstance(co[0][0], tuple)):
        co = [co]
    if xy is not True:
        co = map(lambda p: asarray(p)[:, ::-1].tolist(), co)
    return co
399730
def _parse_coords(self,opts):
        
        # The coordinates are mutually exclusive, so
        # shouldn't have to worry about over-writing them.
        if 'coords' in vars(opts): return
        radius = vars(opts).get('radius',0)
        gal = None
        if vars(opts).get('gal') is not None: 
            gal = opts.gal
        elif vars(opts).get('cel') is not None: 
            gal = cel2gal(*opts.cel)
        elif vars(opts).get('hpx') is not None: 
            gal = pix2ang(*opts.hpx)

        if gal is not None:
            opts.coords = [(gal[0],gal[1],radius)]
            opts.names = [vars(opts).get('name','')]
        else:
            opts.coords = None
            opts.names = None

        if vars(opts).get('targets') is not None:
            opts.names,opts.coords = self.parse_targets(opts.targets)
            if vars(opts).get('radius') is not None:
                opts.coords['radius'] = vars(opts).get('radius')
1368615
def pointlist(points, sr):
    """"""
    assert all(isinstance(pt, Point) or len(pt) == 2 
               for pt in points), "Point(s) not in [x, y] form"
    return [coord if isinstance(coord, Point) 
                  else Point(coord[0], coord[1], sr)
            for coord in points]
266462
def __reorganize_coordinates(self):
        
        try:
            l = self.noaa_data_sorted["Site_Information"]['geometry']['coordinates']
            locations = ["Northernmost_Latitude", "Southernmost_Latitude", "Easternmost_Longitude",
                         "Westernmost_Longitude", "Elevation"]
            logger_lpd_noaa.info("coordinates: {} coordinates found".format(len(l)))

            # Amount of coordinates in the list
            _len_coords = len(l)

            # Odd number of coordinates. Elevation value exists
            if _len_coords % 2 == 1:
                # Store the elevation, which is always the last value in the list
                self.noaa_geo["Elevation"] = l[-1]
                # If elevation, then subtract one from the length
                _len_coords -= 1

            # Start compiling the lat lon coordinates

            # 0 coordinate values. fill in locations with empty values
            if _len_coords == 0:
                for location in locations:
                    self.noaa_geo[location] = ' '
            # 2 coordinates values. duplicate to fill 4 location slots.
            elif _len_coords == 2:
                self.noaa_geo[locations[0]] = l[1]
                self.noaa_geo[locations[1]] = l[1]
                self.noaa_geo[locations[2]] = l[0]
                self.noaa_geo[locations[3]] = l[0]

            # 4 coordinate values. put each in its correct location slot.
            elif _len_coords == 4:
                for index, location in enumerate(locations):
                    self.noaa_geo[locations[index]] = l[index]
            else:
                logger_lpd_noaa.info("coordinates: too many coordinates given")
        except KeyError:
            logger_lpd_noaa.info("lpd_noaa: coordinates: no coordinate information")
        except Exception:
            logger_lpd_noaa.error("lpd_noaa: coordinates: unknown exception")

        return
904944
def get_aligned_adjacent_coords(x, y):
    '''
    
    '''
    return [(x-1, y), (x-1, y-1), (x, y-1), (x+1, y-1), (x+1, y), (x+1, y+1), (x, y+1), (x-1, y+1)]
13127
def parseListOfPoints(s):
    
    i = 0

    # (wsp)? comma-or-wsp-separated coordinate pairs (wsp)?
    # coordinate-pair = coordinate comma-or-wsp coordinate
    # coordinate = sign? integer
    # comma-wsp: (wsp+ comma? wsp*) | (comma wsp*)
    ws_nums = re.split(r"\s*[\s,]\s*", s.strip())
    nums = []

    # also, if 100-100 is found, split it into two also
    #  <polygon points="100,-100,100-100,100-100-100,-100-100" />
    for i in range(len(ws_nums)):
        negcoords = ws_nums[i].split("-")

        # this string didn't have any negative coordinates
        if len(negcoords) == 1:
            nums.append(negcoords[0])
        # we got negative coords
        else:
            for j in range(len(negcoords)):
                # first number could be positive
                if j == 0:
                    if negcoords[0] != '':
                        nums.append(negcoords[0])
                # otherwise all other strings will be negative
                else:
                    # unless we accidentally split a number that was in scientific notation
                    # and had a negative exponent (500.00e-1)
                    prev = ""
                    if len(nums):
                        prev = nums[len(nums) - 1]
                    if prev and prev[len(prev) - 1] in ['e', 'E']:
                        nums[len(nums) - 1] = prev + '-' + negcoords[j]
                    else:
                        nums.append('-' + negcoords[j])

    # if we have an odd number of points, return empty
    if len(nums) % 2 != 0:
        return []

    # now resolve into Decimal values
    i = 0
    while i < len(nums):
        try:
            nums[i] = getcontext().create_decimal(nums[i])
            nums[i + 1] = getcontext().create_decimal(nums[i + 1])
        except InvalidOperation:  # one of the lengths had a unit or is an invalid number
            return []

        i += 2

    return nums
1184992
private List<Coordinate> getPossibleCoordinates(Coordinate coordinate) {
		int xMin = Collections.binarySearch(sortedX, new Coordinate(coordinate.getX() - ruleDistance, 0),
				new XComparator());
		int xMax = Collections.binarySearch(sortedX, new Coordinate(coordinate.getX() + ruleDistance, 0),
				new XComparator());
		int yMin = Collections.binarySearch(sortedY, new Coordinate(0, coordinate.getY() - ruleDistance),
				new YComparator());
		int yMax = Collections.binarySearch(sortedY, new Coordinate(0, coordinate.getY() + ruleDistance),
				new YComparator());
		if (xMin < 0) {
			xMin = Math.abs(xMin) - 1;
		}
		if (xMax < 0) {
			xMax = Math.abs(xMax) - 1;
		}
		if (yMin < 0) {
			yMin = Math.abs(yMin) - 1;
		}
		if (yMax < 0) {
			yMax = Math.abs(yMax) - 1;
		}

		List<Coordinate> coordinates = new ArrayList<Coordinate>();
		for (int i = xMin; i < xMax; i++) {
			coordinates.add(sortedX.get(i));
		}
		for (int i = yMin; i < yMax; i++) {
			coordinates.add(sortedY.get(i));
		}

		return coordinates;
	}
161987
function parseMultiPolygonGeometry(coordinates) {
		var multiPolygonWkt = [];
		for (var i = 0; i < coordinates.length; i++) {
			multiPolygonWkt.push('(' + parsePolygonGeometry(coordinates[i]) + ')');
		}
		return multiPolygonWkt.join(', ');
	}
413196
def check_geo(geo):
    
    geo = copy.copy(geo)

    def fix_item(item):
        if isinstance(item, six.binary_type):
            return item.decode()
        return item

    def fix_list(lst):
        return [fix_item(i) for i in lst]
    if isinstance(geo.reduce, six.binary_type):
        geo.reduce = geo.reduce.decode()
    for key in geo.kwargs.keys():
        if geo.kwargs[key] is not None:
            if isinstance(geo.kwargs[key], (list, np.ndarray)):
                geo.kwargs[key] = fix_list(geo.kwargs[key])
            elif isinstance(geo.kwargs[key], six.binary_type):
                geo.kwargs[key] = fix_item(geo.kwargs[key])
    return geo
146355
def coords(obj):
    
    # Handle recursive case first
    if 'features' in obj:
        for f in obj['features']:
            # For Python 2 compatibility
            # See https://www.reddit.com/r/learnpython/comments/4rc15s/yield_from_and_python_27/ # noqa: E501
            for c in coords(f):
                yield c
    else:
        if isinstance(obj, (tuple, list)):
            coordinates = obj
        elif 'geometry' in obj:
            coordinates = obj['geometry']['coordinates']
        else:
            coordinates = obj.get('coordinates', obj)
        for e in coordinates:
            if isinstance(e, (float, int)):
                yield tuple(coordinates)
                break
            for f in coords(e):
                yield f
131992
def coordinates?
      text.is_a?(Array) or (
        text.is_a?(String) and
        !!text.to_s.match(/\A-?[0-9\.]+, *-?[0-9\.]+\z/)
      )
    end
526044
def _split_regions(chrom, start, end):
    
    window_size = 1e5
    if end - start < window_size * 5:
        return [(chrom, start, end)]
    else:
        out = []
        for r in pybedtools.BedTool().window_maker(w=window_size,
                                                   b=pybedtools.BedTool("%s\t%s\t%s" % (chrom, start, end),
                                                                        from_string=True)):
            out.append((r.chrom, r.start, r.end))
        return out
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)
642540
def parse_coordinate(string_rep, unit):
        
        # explicit radian ('r') value
        if string_rep[-1] == 'r':
            return coordinates.Angle(string_rep[:-1], unit=u.rad)
        # explicit image ('i') and physical ('p') pixels
        elif string_rep[-1] in ['i', 'p']:
            return u.Quantity(string_rep[:-1]) - 1
        # Any ds9 coordinate representation (sexagesimal or degrees)
        elif 'd' in string_rep or 'h' in string_rep:
            return coordinates.Angle(string_rep)
        elif unit is 'hour_or_deg':
            if ':' in string_rep:
                spl = tuple([float(x) for x in string_rep.split(":")])
                return coordinates.Angle(spl, u.hourangle)
            else:
                ang = float(string_rep)
                return coordinates.Angle(ang, u.deg)
        elif unit.is_equivalent(u.deg):
            # return coordinates.Angle(string_rep, unit=unit)
            if ':' in string_rep:
                ang = tuple([float(x) for x in string_rep.split(":")])
            else:
                ang = float(string_rep)
            return coordinates.Angle(ang, u.deg)
        elif unit.is_equivalent(u.dimensionless_unscaled):
            return u.Quantity(float(string_rep), unit) - 1
        else:
            return u.Quantity(float(string_rep), unit)
381833
def read_coordinates(self, where=None, start=None, stop=None, **kwargs):
        

        # validate the version
        self.validate_version(where)

        # infer the data kind
        if not self.infer_axes():
            return False

        # create the selection
        self.selection = Selection(
            self, where=where, start=start, stop=stop, **kwargs)
        coords = self.selection.select_coords()
        if self.selection.filter is not None:
            for field, op, filt in self.selection.filter.format():
                data = self.read_column(
                    field, start=coords.min(), stop=coords.max() + 1)
                coords = coords[
                    op(data.iloc[coords - coords.min()], filt).values]

        return Index(coords)
966799
def closest(self, coords=[], **kwargs):
        
        if kwargs and coords:
            raise ValueError("Specify coordinate using as either a list "
                             "keyword arguments not both")
        if kwargs:
            coords = []
            getter = []
            for k, v in kwargs.items():
                idx = self.get_dimension_index(k)
                if np.isscalar(v):
                    coords.append((0, v) if idx else (v, 0))
                else:
                    if isinstance(v, list):
                        coords = [(0, c) if idx else (c, 0) for c in v]
                    if len(coords) not in [0, len(v)]:
                        raise ValueError("Length of samples must match")
                    elif len(coords):
                        coords = [(t[abs(idx-1)], c) if idx else (c, t[abs(idx-1)])
                                  for c, t in zip(v, coords)]
                getter.append(idx)
        else:
            getter = [0, 1]
        getter = itemgetter(*sorted(getter))
        if len(coords) == 1:
            coords = coords[0]
        if isinstance(coords, tuple):
            return getter(self.closest_cell_center(*coords))
        else:
            return [getter(self.closest_cell_center(*el)) for el in coords]
146775
def convert_coordinates(self):
        
        coord_list_str = regex_coordinate.findall(self.reg_str) + regex_length.findall(self.reg_str)
        coord_list = []

        if self.region_type == 'poly':
            if len(coord_list_str) < 4:
                self._raise_error('Not in proper format: {} polygon should have > 4 coordinates'.format(self.reg_str))
            if coord_list_str[0] != coord_list_str[-1]:
                self._raise_error("Not in proper format: '{0}', "
                                  "In polygon, the last and first coordinates should be same".format(self.reg_str))
        else:
            if len(coord_list_str) != len(self.language_spec[self.region_type]):
                self._raise_error("Not in proper format: '{0}', "
                                  "Does not contain expected number of parameters for the region '{1}'"
                                  .format(self.reg_str, self.region_type))

        for attr_spec, val_str in zip(self.language_spec[self.region_type], coord_list_str):

            if attr_spec == 'c':
                if len(val_str) == 2 and val_str[1] != '':
                    coord_list.append(CoordinateParser.parse_coordinate(val_str[0]))
                    coord_list.append(CoordinateParser.parse_coordinate(val_str[1]))
                else:
                    self._raise_error("Not in proper format: {0} should be a coordinate".format(val_str))
            if attr_spec == 'pl':
                if len(val_str) == 2 and val_str[1] != '':
                    coord_list.append(CoordinateParser.parse_angular_length_quantity(val_str[0]))
                    coord_list.append(CoordinateParser.parse_angular_length_quantity(val_str[1]))
                else:
                    self._raise_error("Not in proper format: {0} should be a pair of length".format(val_str))
            if attr_spec == 'l':
                if isinstance(val_str, six.string_types):
                    coord_list.append(CoordinateParser.parse_angular_length_quantity(val_str))
                else:
                    self._raise_error("Not in proper format: {0} should be a single length".format(val_str))
            if attr_spec == 's':
                if self.region_type == 'symbol':
                    if val_str in valid_symbols:
                        self.meta['symbol'] = val_str
                    else:
                        self._raise_error("Not in proper format: '{0}' should be a symbol".format(val_str))
                elif self.region_type == 'text':
                    self.meta['text'] = val_str[1:-1]

        self.coord = coord_list