Пример #1
0
    def test_buffer(self):
        "Testing buffer()."
        for bg in self.geometries.buffer_geoms:
            g = fromstr(bg.wkt)

            # The buffer we expect
            exp_buf = fromstr(bg.buffer_wkt)
            quadsegs = bg.quadsegs
            width = bg.width

            # Can't use a floating-point for the number of quadsegs.
            self.assertRaises(ctypes.ArgumentError, g.buffer, width, float(quadsegs))

            # Constructing our buffer
            buf = g.buffer(width, quadsegs)
            self.assertEqual(exp_buf.num_coords, buf.num_coords)
            self.assertEqual(len(exp_buf), len(buf))

            # Now assuring that each point in the buffer is almost equal
            for j in xrange(len(exp_buf)):
                exp_ring = exp_buf[j]
                buf_ring = buf[j]
                self.assertEqual(len(exp_ring), len(buf_ring))
                for k in xrange(len(exp_ring)):
                    # Asserting the X, Y of each point are almost equal (due to floating point imprecision)
                    self.assertAlmostEqual(exp_ring[k][0], buf_ring[k][0], 9)
                    self.assertAlmostEqual(exp_ring[k][1], buf_ring[k][1], 9)
Пример #2
0
    def __init__(self, *args, **kwargs):
        """
        Initializes on the given sequence -- may take lists, tuples, NumPy arrays
        of X,Y pairs, or Point objects.  If Point objects are used, ownership is
        _not_ transferred to the LineString object.

        Examples:
         ls = LineString((1, 1), (2, 2))
         ls = LineString([(1, 1), (2, 2)])
         ls = LineString(array([(1, 1), (2, 2)]))
         ls = LineString(Point(1, 1), Point(2, 2))
        """
        # If only one argument provided, set the coords array appropriately
        if len(args) == 1: coords = args[0]
        else: coords = args

        if isinstance(coords, (tuple, list)):
            # Getting the number of coords and the number of dimensions -- which
            #  must stay the same, e.g., no LineString((1, 2), (1, 2, 3)).
            ncoords = len(coords)
            if coords: ndim = len(coords[0])
            else: raise TypeError('Cannot initialize on empty sequence.')
            self._checkdim(ndim)
            # Incrementing through each of the coordinates and verifying
            for i in xrange(1, ncoords):
                if not isinstance(coords[i], (tuple, list, Point)):
                    raise TypeError('each coordinate should be a sequence (list or tuple)')
                if len(coords[i]) != ndim: raise TypeError('Dimension mismatch.')
            numpy_coords = False
        elif numpy and isinstance(coords, numpy.ndarray):
            shape = coords.shape # Using numpy's shape.
            if len(shape) != 2: raise TypeError('Too many dimensions.')
            self._checkdim(shape[1])
            ncoords = shape[0]
            ndim = shape[1]
            numpy_coords = True
        else:
            raise TypeError('Invalid initialization input for LineStrings.')

        # Creating a coordinate sequence object because it is easier to
        # set the points using GEOSCoordSeq.__setitem__().
        cs = GEOSCoordSeq(capi.create_cs(ncoords, ndim), z=bool(ndim==3))

        for i in xrange(ncoords):
            if numpy_coords: cs[i] = coords[i,:]
            elif isinstance(coords[i], Point): cs[i] = coords[i].tuple
            else: cs[i] = coords[i]

        # If SRID was passed in with the keyword arguments
        srid = kwargs.get('srid', None)

        # Calling the base geometry initialization with the returned pointer
        #  from the function.
        super(LineString, self).__init__(self._init_func(cs.ptr), srid=srid)
Пример #3
0
    def test_mutable_geometries(self):
        "Testing the mutability of Polygons and Geometry Collections."
        ### Testing the mutability of Polygons ###
        for p in self.geometries.polygons:
            poly = fromstr(p.wkt)

            # Should only be able to use __setitem__ with LinearRing geometries.
            self.assertRaises(TypeError, poly.__setitem__, 0, LineString((1, 1), (2, 2)))

            # Constructing the new shell by adding 500 to every point in the old shell.
            shell_tup = poly.shell.tuple
            new_coords = []
            for point in shell_tup: new_coords.append((point[0] + 500., point[1] + 500.))
            new_shell = LinearRing(*tuple(new_coords))

            # Assigning polygon's exterior ring w/the new shell
            poly.exterior_ring = new_shell
            s = str(new_shell) # new shell is still accessible
            self.assertEqual(poly.exterior_ring, new_shell)
            self.assertEqual(poly[0], new_shell)

        ### Testing the mutability of Geometry Collections
        for tg in self.geometries.multipoints:
            mp = fromstr(tg.wkt)
            for i in range(len(mp)):
                # Creating a random point.
                pnt = mp[i]
                new = Point(random.randint(1, 100), random.randint(1, 100))
                # Testing the assignment
                mp[i] = new
                s = str(new) # what was used for the assignment is still accessible
                self.assertEqual(mp[i], new)
                self.assertEqual(mp[i].wkt, new.wkt)
                self.assertNotEqual(pnt, mp[i])

        # MultiPolygons involve much more memory management because each
        # Polygon w/in the collection has its own rings.
        for tg in self.geometries.multipolygons:
            mpoly = fromstr(tg.wkt)
            for i in xrange(len(mpoly)):
                poly = mpoly[i]
                old_poly = mpoly[i]
                # Offsetting the each ring in the polygon by 500.
                for j in xrange(len(poly)):
                    r = poly[j]
                    for k in xrange(len(r)): r[k] = (r[k][0] + 500., r[k][1] + 500.)
                    poly[j] = r

                self.assertNotEqual(mpoly[i], poly)
                # Testing the assignment
                mpoly[i] = poly
                s = str(poly) # Still accessible
                self.assertEqual(mpoly[i], poly)
                self.assertNotEqual(mpoly[i], old_poly)
Пример #4
0
 def fields(self):
     """
     Returns a list of string names corresponding to each of the Fields
     available in this Layer.
     """
     return [capi.get_field_name(capi.get_field_defn(self._ldefn, i))
             for i in xrange(self.num_fields) ]
Пример #5
0
    def __init__(self, num_zoom=19, tilesize=256):
        "Initializes the Google Zoom object."
        # Google's tilesize is 256x256, square tiles are assumed.
        self._tilesize = tilesize

        # The number of zoom levels
        self._nzoom = num_zoom

        # Initializing arrays to hold the parameters for each one of the
        # zoom levels.
        self._degpp = [] # Degrees per pixel
        self._radpp = [] # Radians per pixel
        self._npix  = [] # 1/2 the number of pixels for a tile at the given zoom level

        # Incrementing through the zoom levels and populating the parameter arrays.
        z = tilesize # The number of pixels per zoom level.
        for i in xrange(num_zoom):
            # Getting the degrees and radians per pixel, and the 1/2 the number of
            # for every zoom level.
            self._degpp.append(z / 360.) # degrees per pixel
            self._radpp.append(z / (2 * pi)) # radians per pixel
            self._npix.append(z / 2) # number of pixels to center of tile

            # Multiplying `z` by 2 for the next iteration.
            z *= 2
Пример #6
0
    def get_zoom(self, geom):
        "Returns the optimal Zoom level for the given geometry."
        # Checking the input type.
        if not isinstance(geom, GEOSGeometry) or geom.srid != 4326:
            raise TypeError('get_zoom() expects a GEOS Geometry with an SRID of 4326.')

        # Getting the envelope for the geometry, and its associated width, height
        # and centroid.
        env = geom.envelope
        env_w, env_h = self.get_width_height(env.extent)
        center = env.centroid

        for z in xrange(self._nzoom):
            # Getting the tile at the zoom level.
            tile_w, tile_h = self.get_width_height(self.tile(center, z).extent)

            # When we span more than one tile, this is an approximately good
            # zoom level.
            if (env_w > tile_w) or (env_h > tile_h):
                if z == 0:
                    raise GoogleMapException('Geometry width and height should not exceed that of the Earth.')
                return z-1

        # Otherwise, we've zoomed in to the max.
        return self._nzoom-1
Пример #7
0
    def test_coord_seq(self):
        "Testing Coordinate Sequence objects."
        for p in self.geometries.polygons:
            if p.ext_ring_cs:
                # Constructing the polygon and getting the coordinate sequence
                poly = fromstr(p.wkt)
                cs = poly.exterior_ring.coord_seq

                self.assertEqual(p.ext_ring_cs, cs.tuple) # done in the Polygon test too.
                self.assertEqual(len(p.ext_ring_cs), len(cs)) # Making sure __len__ works

                # Checks __getitem__ and __setitem__
                for i in xrange(len(p.ext_ring_cs)):
                    c1 = p.ext_ring_cs[i] # Expected value
                    c2 = cs[i] # Value from coordseq
                    self.assertEqual(c1, c2)

                    # Constructing the test value to set the coordinate sequence with
                    if len(c1) == 2: tset = (5, 23)
                    else: tset = (5, 23, 8)
                    cs[i] = tset

                    # Making sure every set point matches what we expect
                    for j in range(len(tset)):
                        cs[i] = tset
                        self.assertEqual(tset[j], cs[i][j])
Пример #8
0
    def disconnect(self, receiver=None, sender=None, weak=True, dispatch_uid=None):
        """
        Disconnect receiver from sender for signal.

        If weak references are used, disconnect need not be called. The receiver
        will be remove from dispatch automatically.

        Arguments:

            receiver
                The registered receiver to disconnect. May be none if
                dispatch_uid is specified.

            sender
                The registered sender to disconnect

            weak
                The weakref state to disconnect

            dispatch_uid
                the unique identifier of the receiver to disconnect
        """
        if dispatch_uid:
            lookup_key = (dispatch_uid, _make_id(sender))
        else:
            lookup_key = (_make_id(receiver), _make_id(sender))

        with self.lock:
            for index in xrange(len(self.receivers)):
                (r_key, _) = self.receivers[index]
                if r_key == lookup_key:
                    del self.receivers[index]
                    break
Пример #9
0
    def __init__(self, *args, **kwargs):
        """
        A class for generating sets of Google Maps that will be shown on the
        same page together.

        Example:
         gmapset = GoogleMapSet( GoogleMap( ... ), GoogleMap( ... ) )
         gmapset = GoogleMapSet( [ gmap1, gmap2] )
        """
        # The `google-multi.js` template is used instead of `google-single.js`
        # by default.
        template = kwargs.pop('template', 'gis/google/google-multi.js')

        # This is the template used to generate the GMap load JavaScript for
        # each map in the set.
        self.map_template = kwargs.pop('map_template', 'gis/google/google-single.js')

        # Running GoogleMap.__init__(), and resetting the template
        # value with default obtained above.
        super(GoogleMapSet, self).__init__(**kwargs)
        self.template = template

        # If a tuple/list passed in as first element of args, then assume
        if isinstance(args[0], (tuple, list)):
            self.maps = args[0]
        else:
            self.maps = args

        # Generating DOM ids for each of the maps in the set.
        self.dom_ids = ['map%d' % i for i in xrange(len(self.maps))]
Пример #10
0
 def __getitem__(self, index):
     "Get the item(s) at the specified index/slice."
     if isinstance(index, slice):
         return [self._get_single_external(i) for i in xrange(*index.indices(len(self)))]
     else:
         index = self._checkindex(index)
         return self._get_single_external(index)
Пример #11
0
 def _listarr(self, func):
     """
     Internal routine that returns a sequence (list) corresponding with
     the given function.  Will return a numpy array if possible.
     """
     lst = [func(i) for i in xrange(len(self))]
     if numpy: return numpy.array(lst) # ARRRR!
     else: return lst
Пример #12
0
 def kml(self):
     "Returns the KML representation for the coordinates."
     # Getting the substitution string depending on whether the coordinates have
     #  a Z dimension.
     if self.hasz: substr = '%s,%s,%s '
     else: substr = '%s,%s,0 '
     return '<coordinates>%s</coordinates>' % \
         ''.join([substr % self[i] for i in xrange(len(self))]).strip()
Пример #13
0
 def field_types(self):
     """
     Returns a list of the types of fields in this Layer.  For example,
     the list [OFTInteger, OFTReal, OFTString] would be returned for
     an OGR layer that had an integer, a floating-point, and string
     fields.
     """
     return [OGRFieldTypes[capi.get_field_type(capi.get_field_defn(self._ldefn, i))]
             for i in xrange(self.num_fields)]
Пример #14
0
 def setUp(self):
     ts = []
     ss = []
     for x in xrange(5000):
         t = Test1()
         ts.append(t)
         s = safeRef(t.x, self._closure)
         ss.append(s)
     ts.append(test2)
     ss.append(safeRef(test2, self._closure))
     for x in xrange(30):
         t = Test2()
         ts.append(t)
         s = safeRef(t, self._closure)
         ss.append(s)
     self.ts = ts
     self.ss = ss
     self.closureCount = 0
Пример #15
0
        def newItems():
            for i in xrange(origLen + 1):
                if i == start:
                    for val in valueList:
                        yield val

                if i < origLen:
                    if i < start or i >= stop:
                        yield self._get_single_internal(i)
Пример #16
0
 def test13_union(self):
     "Testing union()."
     for i in xrange(len(self.geometries.topology_geoms)):
         a = OGRGeometry(self.geometries.topology_geoms[i].wkt_a)
         b = OGRGeometry(self.geometries.topology_geoms[i].wkt_b)
         u1 = OGRGeometry(self.geometries.union_geoms[i].wkt)
         u2 = a.union(b)
         self.assertEqual(u1, u2)
         self.assertEqual(u1, a | b)  # __or__ is union operator
         a |= b  # testing __ior__
         self.assertEqual(u1, a)
Пример #17
0
 def test_long_string(self):
     # If the backend is Oracle, test that we can save a text longer
     # than 4000 chars and read it properly
     c = connection.cursor()
     c.execute('CREATE TABLE ltext ("TEXT" NCLOB)')
     long_str = "".join([six.text_type(x) for x in xrange(4000)])
     c.execute("INSERT INTO ltext VALUES (%s)", [long_str])
     c.execute("SELECT text FROM ltext")
     row = c.fetchone()
     self.assertEqual(long_str, row[0].read())
     c.execute("DROP TABLE ltext")
Пример #18
0
 def test12_symdifference(self):
     "Testing sym_difference()."
     for i in xrange(len(self.geometries.topology_geoms)):
         a = OGRGeometry(self.geometries.topology_geoms[i].wkt_a)
         b = OGRGeometry(self.geometries.topology_geoms[i].wkt_b)
         d1 = OGRGeometry(self.geometries.sdiff_geoms[i].wkt)
         d2 = a.sym_difference(b)
         self.assertEqual(d1, d2)
         self.assertEqual(d1, a ^ b)  # __xor__ is symmetric difference operator
         a ^= b  # testing __ixor__
         self.assertEqual(d1, a)
Пример #19
0
 def test10_difference(self):
     "Testing difference()."
     for i in xrange(len(self.geometries.topology_geoms)):
         a = OGRGeometry(self.geometries.topology_geoms[i].wkt_a)
         b = OGRGeometry(self.geometries.topology_geoms[i].wkt_b)
         d1 = OGRGeometry(self.geometries.diff_geoms[i].wkt)
         d2 = a.difference(b)
         self.assertEqual(d1, d2)
         self.assertEqual(d1, a - b)  # __sub__ is difference operator
         a -= b  # testing __isub__
         self.assertEqual(d1, a)
Пример #20
0
def dbl_from_geom(func, num_geom=1):
    """
    Argument is a Geometry, return type is double that is passed
    in by reference as the last argument.
    """
    argtypes = [GEOM_PTR for i in xrange(num_geom)]
    argtypes += [POINTER(c_double)]
    func.argtypes = argtypes
    func.restype = c_int # Status code returned
    func.errcheck = check_dbl
    return func
Пример #21
0
 def test_bulk(self):
     from djangocg.db.models.sql.constants import GET_ITERATOR_CHUNK_SIZE
     s = S.objects.create(r=R.objects.create())
     for i in xrange(2*GET_ITERATOR_CHUNK_SIZE):
         T.objects.create(s=s)
     #   1 (select related `T` instances)
     # + 1 (select related `U` instances)
     # + 2 (delete `T` instances in batches)
     # + 1 (delete `s`)
     self.assertNumQueries(5, s.delete)
     self.assertFalse(S.objects.exists())
Пример #22
0
 def test11_intersection(self):
     "Testing intersects() and intersection()."
     for i in xrange(len(self.geometries.topology_geoms)):
         a = OGRGeometry(self.geometries.topology_geoms[i].wkt_a)
         b = OGRGeometry(self.geometries.topology_geoms[i].wkt_b)
         i1 = OGRGeometry(self.geometries.intersect_geoms[i].wkt)
         self.assertEqual(True, a.intersects(b))
         i2 = a.intersection(b)
         self.assertEqual(i1, i2)
         self.assertEqual(i1, a & b)  # __and__ is intersection operator
         a &= b  # testing __iand__
         self.assertEqual(i1, a)
Пример #23
0
 def __getitem__(self, index):
     "Gets the Feature at the specified index."
     if isinstance(index, six.integer_types):
         # An integer index was given -- we cannot do a check based on the
         # number of features because the beginning and ending feature IDs
         # are not guaranteed to be 0 and len(layer)-1, respectively.
         if index < 0: raise OGRIndexError('Negative indices are not allowed on OGR Layers.')
         return self._make_feature(index)
     elif isinstance(index, slice):
         # A slice was given
         start, stop, stride = index.indices(self.num_feat)
         return [self._make_feature(fid) for fid in xrange(start, stop, stride)]
     else:
         raise TypeError('Integers and slices may only be used when indexing OGR Layers.')
Пример #24
0
 def create(self):
     # Because a cache can fail silently (e.g. memcache), we don't know if
     # we are failing to create a new session because of a key collision or
     # because the cache is missing. So we try for a (large) number of times
     # and then raise an exception. That's the risk you shoulder if using
     # cache backing.
     for i in xrange(10000):
         self._session_key = self._get_new_session_key()
         try:
             self.save(must_create=True)
         except CreateError:
             continue
         self.modified = True
         return
     raise RuntimeError("Unable to create a new session key.")
Пример #25
0
    def __delitem__(self, index):
        "Delete the item(s) at the specified index/slice."
        if not isinstance(index, six.integer_types + (slice,)):
            raise TypeError("%s is not a legal index" % index)

        # calculate new length and dimensions
        origLen     = len(self)
        if isinstance(index, six.integer_types):
            index = self._checkindex(index)
            indexRange  = [index]
        else:
            indexRange  = range(*index.indices(origLen))

        newLen      = origLen - len(indexRange)
        newItems    = ( self._get_single_internal(i)
                        for i in xrange(origLen)
                        if i not in indexRange )

        self._rebuild(newLen, newItems)
Пример #26
0
def _explode_shorthand_ip_string(ip_str):
    """
    Expand a shortened IPv6 address.

    Args:
        ip_str: A string, the IPv6 address.

    Returns:
        A string, the expanded IPv6 address.

    """
    if not _is_shorthand_ip(ip_str):
        # We've already got a longhand ip_str.
        return ip_str

    new_ip = []
    hextet = ip_str.split('::')

    # If there is a ::, we need to expand it with zeroes
    # to get to 8 hextets - unless there is a dot in the last hextet,
    # meaning we're doing v4-mapping
    if '.' in ip_str.split(':')[-1]:
        fill_to = 7
    else:
        fill_to = 8

    if len(hextet) > 1:
        sep = len(hextet[0].split(':')) + len(hextet[1].split(':'))
        new_ip = hextet[0].split(':')

        for _ in xrange(fill_to - sep):
            new_ip.append('0000')
        new_ip += hextet[1].split(':')

    else:
        new_ip = ip_str.split(':')

    # Now need to make sure every hextet is 4 lower case characters.
    # If a hextet is < 4 characters, we've got missing leading 0's.
    ret_ip = []
    for hextet in new_ip:
        ret_ip.append(('0' * (4 - len(hextet)) + hextet).lower())
    return ':'.join(ret_ip)
Пример #27
0
 def fields(self):
     "Returns a list of fields in the Feature."
     return [capi.get_field_name(capi.get_field_defn(self._fdefn, i))
             for i in xrange(self.num_fields)]
Пример #28
0
 def __iter__(self):
     "Allows for iteration over the layers in a data source."
     for i in xrange(self.layer_count):
         yield self[i]
Пример #29
0
 def __iter__(self):
     "Allows iteration over this LineString."
     for i in xrange(len(self)):
         yield self[i]
Пример #30
0
 def _construct_forms(self):
     # instantiate all the forms and put them in self.forms
     self.forms = []
     for i in xrange(self.total_form_count()):
         self.forms.append(self._construct_form(i))