Esempio n. 1
0
def map_to_polygon(shape,origin,position,rotation,size):
    geom_obj=Polygon(shape)
    geom_obj=affinity.translate(geom_obj, -origin[0],-origin[1],0)
    geom_obj=affinity.scale(geom_obj,size[0],size[1],origin=(0,0))
    geom_obj=affinity.rotate(geom_obj,int(rotation*360),origin=(0,0))
    geom_obj=affinity.translate(geom_obj, position[0],position[1],0)
    return geom_obj
def main(infile, outfile, driver):

    with fio.open(infile) as src:
        meta = src.meta
        meta['driver'] = driver

    with fio.open(infile) as src, fio.open(outfile, 'w', **meta) as dst:
        with click.progressbar(src) as features:
            for feat in features:

                east = deepcopy(feat)
                west = deepcopy(feat)

                east_geom = shape(east['geometry'])
                west_geom = shape(west['geometry'])

                # if 'Point' not in asShape(feat['geometry']).type:
                #     east_geom = east_geom.simplify(0.0001).buffer(0)
                #     west_geom = west_geom.simplify(0.0001).buffer(0)

                east_geom = translate(east_geom, xoff=180)
                west_geom = translate(west_geom, xoff=-180)

                if not east_geom.is_empty:
                    east['geometry'] = mapping(east_geom)
                    dst.write(east)

                if not west_geom.is_empty:
                    west['geometry'] = mapping(west_geom)
                    dst.write(west)
    def _refine_predug(self, candidate):
        """ uses the color information directly to specify the predug """
        # determine a bounding rectangle
        region = candidate.bounds
        size = max(region.width, region.height)
        region.buffer(0.5 * size)  # < increase by 50% in each direction

        # extract the region from the image
        slice_x, slice_y = region.slices
        img = self.image[slice_y, slice_x].astype(np.uint8, copy=True)

        # build the estimate polygon
        poly_p = affinity.translate(candidate.polygon, -region.x, -region.y)
        poly_s = affinity.translate(self.ground.get_sky_polygon(), -region.x, -region.y)

        def fill_mask(color, margin=0):
            """ fills the mask with the buffered regions """
            for poly in (poly_p, poly_s):
                pts = np.array(poly.buffer(margin).boundary.coords, np.int32)
                cv2.fillPoly(mask, [pts], color)

        # prepare the mask for the grabCut algorithm
        burrow_width = self.params["burrows/width"]
        mask = np.full_like(img, cv2.GC_BGD, dtype=np.uint8)  # < sure background
        fill_mask(cv2.GC_PR_BGD, 0.25 * burrow_width)  # < possible background
        fill_mask(cv2.GC_PR_FGD, 0)  # < possible foreground
        fill_mask(cv2.GC_FGD, -0.25 * burrow_width)  # < sure foreground

        # run GrabCut algorithm
        img = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB)
        bgdmodel = np.zeros((1, 65), np.float64)
        fgdmodel = np.zeros((1, 65), np.float64)
        try:
            cv2.grabCut(img, mask, (0, 0, 1, 1), bgdmodel, fgdmodel, 2, cv2.GC_INIT_WITH_MASK)
        except:
            # any error in the GrabCut algorithm makes the whole function useless
            logging.warn("GrabCut algorithm failed for predug")
            return candidate

        # turn the sky into background
        pts = np.array(poly_s.boundary.coords, np.int32)
        cv2.fillPoly(mask, [pts], cv2.GC_BGD)

        # extract a binary mask determining the predug
        predug_mask = (mask == cv2.GC_FGD) | (mask == cv2.GC_PR_FGD)
        predug_mask = predug_mask.astype(np.uint8)

        # simplify the mask using binary operations
        w = int(0.5 * burrow_width)
        kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (w, w))
        predug_mask = cv2.morphologyEx(predug_mask, cv2.MORPH_OPEN, kernel)

        # extract the outline of the predug
        contour = regions.get_contour_from_largest_region(predug_mask)

        # translate curves back into global coordinate system
        contour = curves.translate_points(contour, region.x, region.y)

        return shapes.Polygon(contour)
def crop_line(line,pts_array):
    line_start,line_end=list(line.coords)
    line_start=Point(line_start); line_end=Point(line_end)
    x=(line_start.x-line_end.x)/line.length
    y=(line_start.y-line_end.y)/line.length
    center=line.centroid
    pts=pts_array-np.array([center.x,center.y])
    pts=pts[:,0]*x+pts[:,1]*y
    return pts2line([translate(center,xoff=(np.min(pts)*x), yoff=np.min(pts)*y),translate(center,xoff=(np.max(pts)*x), yoff=np.max(pts)*y)])
Esempio n. 5
0
def fit_shape(shape, width, height, padding=0):
    width -= padding * 2
    height -= padding * 2
    x1, y1, x2, y2 = shape.bounds
    w, h = x2 - x1, y2 - y1
    s = min(width / w, height / h)
    shape = translate(shape, -x1, -y1)
    shape = scale(shape, s, s, origin=(0, 0, 0))
    shape = translate(shape, padding, padding)
    return shape
Esempio n. 6
0
def findIntersect( ):
    time, max_area, max_time = 0.0, 0.0, 0.0
    while time < 5:
        time+=.001
        temp = asteroid1.asteroid.intersection(asteroid2.asteroid).area
        if temp > max_area:
            max_area = temp
            max_time = time
        asteroid1.asteroid = translate(asteroid1.asteroid, asteroid1.velocity[0]*.001, asteroid1.velocity[1]*.001)
        asteroid2.asteroid = translate(asteroid2.asteroid, asteroid2.velocity[0]*.001, asteroid2.velocity[1]*.001)
    return max_time
Esempio n. 7
0
def clip_geometry_to_srs_bounds(geometry, pyramid, multipart=False):
    """
    Clip input geometry to SRS bounds of given TilePyramid.

    If geometry passes the antimeridian, it will be split up in a multipart
    geometry and shifted to within the SRS boundaries.
    Note: geometry SRS must be the TilePyramid SRS!

    - geometry: any shapely geometry
    - pyramid: a TilePyramid object
    - multipart: return list of geometries instead of a GeometryCollection
    """
    try:
        assert geometry.is_valid
    except AssertionError:
        raise ValueError("invalid geometry given")
    try:
        assert isinstance(pyramid, TilePyramid or MetaTilePyramid)
    except AssertionError:
        raise ValueError("not a TilePyramid object")
    pyramid_bbox = box(
        pyramid.left, pyramid.bottom, pyramid.right, pyramid.top)

    # Special case for global tile pyramids if geometry extends over tile
    # pyramid boundaries (such as the antimeridian).
    if pyramid.is_global and not geometry.within(pyramid_bbox):
        inside_geom = geometry.intersection(pyramid_bbox)
        outside_geom = geometry.difference(pyramid_bbox)
        # shift outside geometry so it lies within SRS bounds
        if isinstance(outside_geom, Polygon):
            outside_geom = [outside_geom]
        all_geoms = [inside_geom]
        for geom in outside_geom:
            geom_left = geom.bounds[0]
            geom_right = geom.bounds[2]
            if geom_left < pyramid.left:
                geom = translate(geom, xoff=2*pyramid.right)
            elif geom_right > pyramid.right:
                geom = translate(geom, xoff=-2*pyramid.right)
            all_geoms.append(geom)
        if multipart:
            return all_geoms
        else:
            return GeometryCollection(all_geoms)

    else:
        if multipart:
            return [geometry]
        else:
            return geometry
Esempio n. 8
0
 def wrap_americas(self, wrapping_point=-50):
     new_mp = []
     try:
         for i, p in enumerate(self.patch):
             if min(p.envelope.exterior.xy[0]) < wrapping_point or\
                     max(p.envelope.exterior.xy[0]) < wrapping_point:
                 new_mp.append(translate(p, xoff=360.))
             else:
                 new_mp.append(p)
         self.patch = MultiPolygon(new_mp)
     except TypeError:
         if self.get_maxx() < wrapping_point or\
                 self.get_minx() < wrapping_point:
             self.patch = translate(self.patch, xoff=360.)
Esempio n. 9
0
def load_letters(letters):
    x = 0.0
    s = 1.82748538
    p = 0.125
    polygons = []
    for letter in letters:
        polygon = load_letter(letter)
        polygon = scale(polygon, s, s)
        x1, y1, x2, y2 = polygon.bounds
        polygon = translate(polygon, -x1, -y1)
        polygon = translate(polygon, x)
        x += (x2 - x1) + p
        polygons.append(polygon)
        print polygon.bounds
    return MultiPolygon(polygons)
Esempio n. 10
0
 def move(self, x3_offset, alt_layer=False):
     """Translate a layer in the vertical (x3) direction."""
     # translate the polygon
     self.polygon = translate(self.polygon, yoff=x3_offset)
     # translate the corners
     for i in range(len(self.corners)):
         new_corner = translate(self.corners[i], yoff=x3_offset)
         self.corners[i] = new_corner
     if not alt_layer:
         # in a regular layer, update the left, right, top, and bottom edges
         #   so they will be translated too
         self.get_and_save_edges()
     else:
         # in an alt layer, translate the edges
         for edge in self.edges:
             edge[:,1] += x3_offset
Esempio n. 11
0
File: map.py Progetto: aleaf/Figures
    def _load_shapefile(self, shp, index_field, convert_coordinates, remove_offset, simplify):

        df = shp2df(shp)

        if index_field is not None:
            df.index = df[index_field]

        proj4 = get_proj4(shp)

        if proj4 != self.proj4:
            df['geometry'] = projectdf(df, proj4, self.proj4)

        # convert projected coordinate units and/or get rid z values if the shapefile has them
        if convert_coordinates != 1 or df.iloc[0]['geometry'].has_z:
            df['geometry'] = [transform(lambda x, y, z=None: (x * convert_coordinates,
                                                              y * convert_coordinates), g)
                              for g in df.geometry]

        # remove model offset from projected coordinates (llcorner = 0,0)
        if remove_offset:
            df['geometry'] = [translate(g,
                                        -1 * self.extent_proj[0],
                                        -1 * self.extent_proj[1]) for g in df.geometry]

        if simplify > 0:
            df['geometry'] = [g.simplify(simplify) for g in df.geometry]
        return df
Esempio n. 12
0
    def tile(self, tile_builder, offset, max_width, max_height, polygon_mask=None):
        """Extract a tile from the image

        Parameters
        ----------
        tile_builder: TileBuilder
            A tile builder for constructing the Tile object
        offset: (int, int)
            The (x, y) coordinates of the pixel at the origin point of the tile in the parent image
        max_width: int
            The maximum width of the tile
        max_height: int
            The maximum height of the tile
        polygon_mask: Polygon (optional, default: None)
            The polygon representing the alpha mask to apply to the image window. The polygon must be referenced
            to the full image top-left pixel.

        Returns
        -------
        tile: Tile
            The extracted tile

        Raises
        ------
        IndexError: if the offset is not inside the image
        TileExtractionException: if the tile cannot be extracted
        """
        if not self._check_tile_offset(offset):
            raise IndexError("Offset {} is out of the image.".format(offset))
        width = min(max_width, self.width - offset[0])
        height = min(max_height, self.height - offset[1])
        translated_polygon = translate(polygon_mask, -offset[0], -offset[1]) if polygon_mask is not None else None
        return tile_builder.build(self, offset, width, height, polygon_mask=translated_polygon)
Esempio n. 13
0
def module_third(wafer_size, ncells, module_center=Point((0,0)), module_id=0, triggercell_size=1):
    # Compute the cell grid length for 1/3 of a module
    grid_size = int(math.sqrt(ncells/3))
    # This geometry is of the rotated type
    # The wafer size below is the vertex to vertex distance
    # The cell size is the edge to edge distance
    cell_size = wafer_size/grid_size/2.
    # Create grid of cells along the usual hexagon axes (60deg rotated axes)
    grid_generator = GridGenerator('diamond', grid_size)
    reference_position = translate(module_center,
            xoff=-cell_size*(grid_size-1), 
            yoff=cell_size*tan30)
    cell_centers = grid_generator(reference_position, cell_size)
    # Create cells corresponding to 1/3 of a module
    hex_generator = HexagonGenerator(cell_size*tan30)
    cell_transform = CellTransform(cell_size, grid_size)
    cell_vertices = [cell_transform(i)(hex_generator(point)) for i,point in enumerate(cell_centers)]
    # Merge cells in trigger cells if requested
    if triggercell_size>1:
        cell_vertices = trigger_cells(cell_vertices, size=triggercell_size)
        cell_centers = [c.centroid for c in cell_vertices]
    cells = []
    for i,(vertices,center) in enumerate(zip(cell_vertices,cell_centers)):
        cells.append(Cell(
            id=compute_id(module=module_id, third=0, cell=i),
            layer=1,
            zside=1,
            subdet=3,
            module=module_id,
            center=center,
            vertices=vertices
            ))
    return cells
Esempio n. 14
0
    def valid_edge(self, state, primitive, plot = True):

        bounding_poly = affinity.rotate(primitive.bounding_poly, state[2], origin = (0.0, 0.0), use_radians = True)
        bounding_poly = affinity.translate(bounding_poly, state[0], state[1])

        #Drawing Primitive-TAKE OUT TODO
        if plot:
            if bounding_poly.intersects(self.world_polys):
                color = 'r'
            else:
                color = 'b'

            fig = plt.figure(2)
            fig.clear()
            plt.ion()
            ax = fig.add_subplot(111, aspect = 'equal')
            for poly in self.world_polys:
                P = PolygonPatch(poly, fc = 'k', zorder = 2)
                ax.add_patch(P)
            P = PolygonPatch(bounding_poly, fc = color, ec = '#999999', alpha = 1, zorder = 1)
            polyPatch = ax.add_patch(P)
            ax.set_xlim(0,50)
            ax.set_ylim(0,50)
            fig.show()
            plt.pause(0.1)
            #pdb.set_trace()
        
        if bounding_poly.intersects(self.world_polys):

            return False
        return True
Esempio n. 15
0
    def window(self, offset, max_width, max_height, polygon_mask=None):
        """Build an image object representing a window of the image

        Parameters
        ----------
        offset: (int, int)
            The (x, y) coordinates of the pixel at the origin point of the window in the parent image
        max_width: int
            The maximum width of the window
        max_height: int
            The maximum height of the window
        polygon_mask: Polygon (optional, default: None)
            The polygon representing the alpha mask to apply to the image window. The polygon must be referenced
            to the full image top-left pixel.

        Returns
        -------
        window: ImageWindow
            The resulting image window
        """
        # width are bound to the current window size, not the parent one
        width = min(max_width, self.width - offset[0])
        height = min(max_height, self.height - offset[1])
        translated_polygon = translate(polygon_mask, -offset[0], -offset[1]) if polygon_mask is not None else None
        return ImageWindow(self, offset, width, height, polygon_mask=translated_polygon)
Esempio n. 16
0
 def test_translate(self):
     ls = load_wkt('LINESTRING(240 400 10, 240 300 30, 300 300 20)')
     # test default offset of 0.0
     tls = affinity.translate(ls)
     self.assertTrue(tls.equals(ls))
     # test all offsets
     tls = affinity.translate(ls, 100, 400, -10)
     els = load_wkt('LINESTRING(340 800 0, 340 700 20, 400 700 10)')
     self.assertTrue(tls.equals(els))
     # Do explicit 3D check of coordinate values
     for a, b in zip(tls.coords, els.coords):
         for ap, bp in zip(a, b):
             self.assertEqual(ap, bp)
     # retest with named parameters for the same result
     tls = affinity.translate(geom=ls, xoff=100, yoff=400, zoff=-10)
     self.assertTrue(tls.equals(els))
Esempio n. 17
0
 def make(self):
     # Create new geometry
     dx = self.destination[0] - self.origin[0]
     dy = self.destination[1] - self.origin[1]
     self.geometry = [DrawToolShape(affinity.translate(geom.geo, xoff=dx, yoff=dy))
                      for geom in self.draw_app.get_selected()]
     self.complete = True
Esempio n. 18
0
def gen_feature(feature_name, model_number, image_path, shape, transl, scaling, scn):
    print("Called gen_feature @ %s" % feature_name)
    # let's first translate our feature.
    ip = Polygon(list(shape))  # map(lambda x: (x[0], 4x[1]), shape)))
    p = translate(ip, xoff=transl[0], yoff=transl[1])
    if(feature_name == "Mountain"):
        center_z = 0
        center_pos = p.centroid.coords[0]
        rd = int((max([dist(x, center_pos) for x in p.exterior.coords]) / 2) ** 0.5)
        print("Radius = %d" % rd)
        print("Center = %d, %d" % (center_pos[0], center_pos[1]))
        return Mountain(rd, center_z, center_pos)
    elif(feature_name == "MountainImg"):
        center_z = 0
        center_pos = p.bounds[0:2]
        print("Center = %d, %d" % (center_pos[0], center_pos[1]))
        return MountainImg(p, center=center_pos)
    elif(feature_name == "Roads"):
        pass
    elif(feature_name == "Image"):
        f = ImageFeature(image_path)
        f.shape = p
        return f
    elif(feature_name == "Vegetation"):
        for a in p.exterior.coords:
            print(a)
        return Vegetation(p, model=AbstractModel(scn["model_path"], 0.02, (0, 0)), tree_number=model_number)
    elif(feature_name == "Urban"):
        pass
    elif(feature_name == "WaterArea"):
        pass
    elif(feature_name == "River"):
        pass
Esempio n. 19
0
def pack(items):
    shifted = [ ]
    for i, item in enumerate(items):
        shifted.append(
            affinity.translate(item, (i%6)*15, (i//6)*15)
            )
    return ops.cascaded_union(shifted)
def main(opts):
    pattern = loads(open(opts.input, "r").read())
    extent = loads(open(opts.extent, "r").read())

    if not contains.matches(extent.relate(pattern)):
        print "ERROR: pattern must be contained within the extent"
        return

    c = pattern.centroid
    (xs, ys) = extent.boundary.xy
    (minx, maxx, miny, maxy) = (min(xs) - c.x, max(xs) - c.x, min(ys) - c.y, max(ys) - c.y)

    outputFile = open(opts.output, "w")

    geoms = []

    while len(geoms) < opts.number:
        dx = random.uniform(minx, maxx)
        dy = random.uniform(miny, maxy)

        geom = translate(pattern, xoff=dx, yoff=dy)

        if contains.matches(extent.relate(geom)):
            # Check that it is within the extent
            overlap = False
            for g in geoms:
                if intersects.matches(g.relate(geom)):
                    overlap = True
            if overlap == False:
                geoms.append(geom)

    for geom in geoms:
        outputFile.write(dumps(geom) + "\n")
    outputFile.close()
Esempio n. 21
0
def saveR(rectangles, A, cc, n):
    zona = takeZona(n)
    polis =[]
    for r in rectangles:
        polis.append(r[0])

    union = affinity.rotate(cascaded_union(polis), -A, origin=cc)
    dx = union.centroid.x-cc.x
    dy = union.centroid.y-cc.y
    print 'translate : ',dx, dy
    data2save=()
    for r in rectangles:
        rotated=affinity.rotate(r[0], -A, origin=cc)
        translated = affinity.translate(rotated, -dx, -dy)
        #verificar si interseca
        print zona.intersects(translated)
        if zona.intersects(translated):
            data = (n, A, r[1], r[2], "SRID=25831;"+str(translated))
            data2save += (data,)
        #print data
    conn = db.connect(rootData)
    c = conn.cursor()
    c.executemany('''insert into elementsdiv ( name, ang, x, y, geometry ) values ( ?, ?, ?,?, GeomFromEWKT( ? ) )''', data2save )
    conn.commit()
    conn.close()

    return
Esempio n. 22
0
 def move_obs(self, index, displacement):
     for i in range(0,index):
         self.obs_config[i][index-1] = translate(self.obs_config[i][index-1], 
                                                    xoff = displacement[0], 
                                                    yoff = displacement[1])
     for i in range(index+1, len(self.poly)):
         self.obs_config[i][index] = translate(self.obs_config[i][index], 
                                                xoff = displacement[0], 
                                                yoff = displacement[1])
     self.config_poly[index] = translate(self.config_poly[index], 
                                        xoff = displacement[0], 
                                        yoff = displacement[1])
     self.config_objects = unary_union(self.config_poly)
     self.poly[index] = translate(self.poly[index], 
                                    xoff = displacement[0], 
                                    yoff = displacement[1])
     self.objects = unary_union(self.poly)
Esempio n. 23
0
    def get_shapely_object(self):
        # Start with the "rays"
        # noinspection PyTypeChecker
        ray_angles = np.linspace(0, np.pi / 2, 8) + np.pi / 2
        outer_ray_positions = (np.array(
            [np.cos(ray_angles), np.sin(ray_angles)]) *
                               self.height).T + (self.height, 0)
        inner_ray_positions = (np.array(
            [np.cos(ray_angles), np.sin(ray_angles)]) * self.height *
                               self.min_radius_fraction).T + (self.height, 0)

        polygons = list()
        for outer, inner in zip(outer_ray_positions.reshape(-1, 2, 2),
                                inner_ray_positions.reshape(-1, 2, 2)):
            polygons.append(Polygon([outer[0], outer[1], inner[1], inner[0]]))
            pass

        # Draw the letters
        d = self.height * 0.077

        k_upper_branch = rotate(box(0, -d,
                                    sqrt(2) * self.height / 2 + sqrt(2) * d,
                                    d),
                                45,
                                origin=(0, 0))
        k_lower_branch = scale(k_upper_branch, yfact=-1., origin=(0, 0))
        k_uncut = k_upper_branch.union(k_lower_branch)
        k_unscaled = k_uncut.intersection(
            box(0, -self.height / 2., self.height / 2. + sqrt(2) * d,
                self.height / 2.))
        k = scale(k_unscaled, 0.8, origin=(0, 0))
        polygons.append(translate(k, self.height * 1.05, self.height / 2.))

        i = box(0, 0, 2 * d, self.height)
        polygons.append(translate(i, self.height * 1.6))

        t_overlap = 2
        t = box(-d, 0, d, self.height).union(
            box(-d * (1 + t_overlap), self.height - 2 * d, d * (1 + t_overlap),
                self.height))
        polygons.append(translate(t, self.height * 2.05))

        logo = unary_union(polygons)

        return translate(logo, *self.origin)
Esempio n. 24
0
    def get_kml(self):
        '''
        Render the Site as KML
        '''
        k = kml.KML()
        ns = '{http://www.opengis.net/kml/2.2}'
        ls = LineStyle(color="ffffff00", width=0.5)
        s1 = Style(id="thin_border", styles=[ls])
        d = kml.Document(ns,
                         self.site.name,
                         self.site.name,
                         "Site plan for %s" % (self.site.name),
                         styles=[s1])
        k.append(d)
        # nf = kml.Folder(ns, 'B1', 'building 1', 'Building one')
        # d.append(nf)

        # render the site reference mark as a KML Placemark
        p = kml.Placemark(ns, 'ref_mark', self.site.name,
                          'Reference survey mark')
        p.geometry = self.site.ref_mark
        d.append(p)

        # compute the UTM coords of the Site reference point

        crs = get_epsg(self.site.ref_mark)
        site_UTM = get_UTM_from_long_lat(self.site.ref_mark)
        project_UTM_to_WGS84 = partial(pyproj.transform, pyproj.Proj(init=crs),
                                       pyproj.Proj(init='epsg:4326'))

        folder = kml.Folder(ns, 'Structures', 'Structures',
                            'Structures on the site')
        d.append(folder)

        # render each Structure

        for s in self.site.structures:
            name = s.name
            # work with the outline of the structure
            outline = s.geometry.buffer(0)
            # move outline into UTM coordinates for the site
            outline = translate(outline, xoff=site_UTM.x, yoff=site_UTM.y)
            # and transform to WGS84
            outline = transform(project_UTM_to_WGS84, outline)

            # place the outline in Structures folder
            p = kml.Placemark(ns,
                              name,
                              name,
                              s.description,
                              styleUrl="#thin_border")
            p.geometry = outline
            folder.append(p)

        # return the KML

        return k.to_string(prettyprint=True)
Esempio n. 25
0
 def __init__(self):
     self.centre = [400, 500]
     self.centredLineString = LineString([(-playerHalfSize,-playerHalfSize),
                                          (-playerHalfSize,playerHalfSize),
                                          (playerHalfSize,playerHalfSize),
                                          (playerHalfSize,-playerHalfSize)])
     self.lineString = translate(self.centredLineString, self.centre[0], self.centre[1])
     self.speedY = 0
     self.jumping = False
Esempio n. 26
0
 def transform_patch(p, s=2):
     corrected_patch = scale(
         translate(p, xoff=-data.shape[1]/2, yoff=-data.shape[0]/2),
         xfact=0.396,
         yfact=0.396,
         origin=(0, 0),
     )
     # display patch at s*Re
     return scale(corrected_patch, s, s)
Esempio n. 27
0
def get_geojson():
    with open('us_states_simplified_albers.geojson') as us_states_file:
        geojson = json.loads(us_states_file.read())
        for f in geojson['features']:
            if f['properties']['NAME'] == 'Alaska':
                geom = affinity.translate(shape(f['geometry']),
                                          xoff=1.2e6,
                                          yoff=-4.8e6)
                geom = affinity.scale(geom, .4, .4)
                geom = affinity.rotate(geom, 30)
                f['geometry'] = mapping(geom)
            elif f['properties']['NAME'] == 'Hawaii':
                geom = affinity.translate(shape(f['geometry']),
                                          xoff=4.6e6,
                                          yoff=-1.1e6)
                geom = affinity.rotate(geom, 30)
                f['geometry'] = mapping(geom)
    return json.dumps(geojson)
Esempio n. 28
0
 def __call__(self, point, rotation=0):
     panels = []
     for panel in self._panels:
         p = translate(panel, xoff=point.x, yoff=point.y)
         if rotation!=0:
             # Rotate around the origin
             p = rotate(p, rotation, origin=(0,0))
         panels.append(p)
     return panels
Esempio n. 29
0
 def __init__(self, hexagon_size, module_list=[]):
     self._vertices = []
     for module in module_list:
         column = module[0]
         row = module[1]
         point0 = Point((0,0))
         point0 = translate(point0, xoff=-hexagon_size*math.sqrt(3)/2.*column, yoff=hexagon_size/2.*column)
         self._vertices.append((point0.x, point0.y+hexagon_size*row))
     self._vertices.append((self._vertices[0][0]-hexagon_size/10, self._vertices[0][1]))
Esempio n. 30
0
def rect_polygon(x, y, width, height, angle):
    """Return a shapely Polygon describing the rectangle with centre at
    (x, y) and the given width and height, rotated by angle quarter-turns.
    code from: https://codereview.stackexchange.com/questions/204017/intersection-over-union-for-rotated-rectangles
    """
    w = width / 2
    h = height / 2
    p = Polygon([(-w, -h), (w, -h), (w, h), (-w, h)])
    return translate(rotate(p, angle, use_radians=True), x, y)
Esempio n. 31
0
 def _channel(self):
     channel_object = self._bezier_guide_channel(
         0, self._outer_channel_width, self._inner_channel_width,
         self._channel_length, self._channel_point_2, self._channel_point_3)
     x_offset = (self._gate_length + self._gate_choke_length +
                 self._choke_length_2 + self._choke_length_3)
     y_offset = (1 - self._channel_position) * self._channel_length
     return translate(rotate(channel_object, -np.pi / 2, (0, 0), True),
                      x_offset, y_offset, 0)
Esempio n. 32
0
    def __rotate_box(box, angle, image_size, rotated_image_size):
        """
        Поворот многоугольника
        """
        rotated_box = []
        for i in range(len(box) // 2):
            pt = Point(box[2 * i], box[2 * i + 1])
            pt = affinity.translate(pt, -image_size[0] / 2, -image_size[1] / 2)
            rotated_pt = affinity.rotate(pt,
                                         angle,
                                         origin=[0, 0],
                                         use_radians=False)
            rotated_pt = affinity.translate(rotated_pt,
                                            rotated_image_size[0] / 2,
                                            rotated_image_size[1] / 2)
            rotated_box.extend([rotated_pt.x, rotated_pt.y])

        return rotated_box
Esempio n. 33
0
def _connect_points(row):
    pt0 = row['prev_pt']
    pt1 = row['geometry']
    if type(pt0) != Point:
        return None
    if pt0 == pt1:
        # to avoid intersection issues with zero length lines
        pt1 = translate(pt1, 0.00000001, 0.00000001)
    return LineString(list(pt0.coords) + list(pt1.coords))
Esempio n. 34
0
def add_letter_to_axis(ax, let, x, y, height):
    """Add 'let' with position x,y and height height to matplotlib axis 'ax'.
    """
    for polygon, color in zip(letters_polygons[let], colors[let]):
        new_polygon = affinity.scale(polygon, yfact=height, origin=(0, 0, 0))
        new_polygon = affinity.translate(new_polygon, xoff=x, yoff=y)
        patch = PolygonPatch(new_polygon, edgecolor=color, facecolor=color)
        ax.add_patch(patch)
    return
Esempio n. 35
0
    def __init__(self, shape, num_particles, map_size):
        super().__init__(map_size)
        self.shape = af.translate(shape, -shape.centroid.xy[0].tolist()[0], -shape.centroid.xy[1].tolist()[0]) # shape of object
        self.particles = [Particle() for i in range(num_particles)]
        self.reset_particles()

        self.XY_TRANSITION_SIGMA = 0.1
        self.THETA_TRANSITION_SIGMA = np.pi / 24
        self.OBS_ACCURACY = 0.99
Esempio n. 36
0
    def to_minimise(optimiser_input):
        rotated = aff.rotate(ellipse, optimiser_input[2], origin='centroid')
        translated = aff.translate(rotated,
                                   xoff=optimiser_input[0],
                                   yoff=optimiser_input[1])

        disjoint_area = (translated.difference(cutout).area +
                         cutout.difference(ellipse).area)
        return disjoint_area
Esempio n. 37
0
 def __init__(self, centreX, centreY):
     self.centre = [centreX, centreY]
     self.centredLineString = LineString([(-enemyHalfSize, -enemyHalfSize),
                                          (-enemyHalfSize, enemyHalfSize),
                                          (enemyHalfSize, enemyHalfSize),
                                          (enemyHalfSize, -enemyHalfSize)])
     self.lineString = translate(self.centredLineString, self.centre[0],
                                 self.centre[1])
     self.speedX = enemyLateralSpeed
Esempio n. 38
0
 def __call__(self, point, rotation=0):
     panels = []
     for panel in self._panels:
         p = translate(panel, xoff=point.x, yoff=point.y)
         if rotation != 0:
             # Rotate around the origin
             p = rotate(p, rotation, origin=(0, 0))
         panels.append(p)
     return panels
Esempio n. 39
0
def coffin(Rint,wmid,Rmid,lmid,wtop,htop,Rtop):
    ltot = lmid+Rint
    L = math.sqrt((ltot-Rmid)*(ltot-Rmid)-Rmid*Rmid)
    alpha = math.atan(Rmid/L)
    tri = Polygon([[0,0],[math.cos(alpha)*L, -math.sin(alpha)*L],[math.cos(alpha)*L, math.sin(alpha)*L]])
    c = circle(lmid+Rint-Rmid,0,Rmid)
    union = tri.union(c)
    trans = 2*Rmid-wmid
    union2 = translate(union,0,-trans/2)
    union3 = translate(union, 0,trans/2)
    inter = union3.intersection(union2)
    cint = circle(O,Rint)
    inter = inter.difference(cint)    
    c1 = circle(ltot,0,Rtop)
    c2 = translate(c1,0,-Rtop+wtop/2)
    c3 = translate(c1,0,Rtop-wtop/2)
    eye = c2.intersection(c3)
    return eye.union(inter)
Esempio n. 40
0
    def minimising_function(optimiser_input):
        x_shift, y_shift, rotation_angle = optimiser_input
        rotated = aff.rotate(initial_ellipse, rotation_angle, use_radians=True)
        translated = aff.translate(rotated, xoff=x_shift, yoff=y_shift)

        disjoint_area = (translated.difference(insert).area +
                         insert.difference(translated).area)

        return disjoint_area / 400
Esempio n. 41
0
 def make(self):
     # Create new geometry
     dx = self.destination[0] - self.origin[0]
     dy = self.destination[1] - self.origin[1]
     self.geometry = [
         DrawToolShape(affinity.translate(geom.geo, xoff=dx, yoff=dy))
         for geom in self.draw_app.get_selected()
     ]
     self.complete = True
Esempio n. 42
0
 def transition_fnc(self, p):
     """ Makes a new particle, moved by a random amount. """
     new_p = Particle()
     new_p.x = np.random.normal(loc=p.x, scale=self.XY_TRANSITION_SIGMA)
     new_p.y = np.random.normal(loc=p.y, scale=self.XY_TRANSITION_SIGMA)
     new_p.theta = np.random.normal(loc=p.theta, scale=self.THETA_TRANSITION_SIGMA) % (2 * np.pi)
     new_p.shape = af.translate(af.rotate(self.shape, new_p.theta, use_radians=True,
                                          origin=(0, 0)), new_p.x, new_p.y)
     return new_p
Esempio n. 43
0
def importSVGroute(IDT_group):
    IDT_group_dir = IDT_group['IDT_group_dir']
    Tk().withdraw(
    )  # we don't want a full GUI, so keep the root window from appearing
    svg_filename = tkFileDialog.askopenfilename(title='Wafer routing filename',
                                                defaultextension='svg',
                                                initialdir=IDT_group_dir)
    all_points = SVGT.read_colored_path_from_svg(svg_filename)
    route = [[], []]
    for points in all_points['red']:
        polygon = shapely_geom.Polygon(points.T)
        polygon_validity = explain_validity(polygon)
        if polygon_validity == 'Valid Geometry':
            route[0].append(polygon)
        else:
            tkMessageBox.showwarning('Error in svg import', polygon_validity)
    for points in all_points['blue']:
        polygon = shapely_geom.Polygon(points.T)
        polygon_validity = explain_validity(polygon)
        if polygon_validity == 'Valid Geometry':
            route[1].append(polygon)
        else:
            tkMessageBox.showwarning('Error in svg import', polygon_validity)
    route[0] = shapely_geom.MultiPolygon(route[0])
    route[1] = shapely_geom.MultiPolygon(route[1])
    #outbox = route[0].bounds
    #dx = outbox[2]-outbox[0]
    #dy = outbox[3]-outbox[1]
    #x0 = outbox[0]+dx/2
    #y0 = outbox[1]+dy/2
    x0 = 4000
    y0 = 4000
    factor = 1e-5
    route[0] = shapely_affinity.translate(route[0], xoff=-x0, yoff=-y0)
    route[0] = shapely_affinity.scale(route[0],
                                      xfact=factor,
                                      yfact=factor,
                                      origin=(0, 0, 0))
    route[1] = shapely_affinity.translate(route[1], xoff=-x0, yoff=-y0)
    route[1] = shapely_affinity.scale(route[1],
                                      xfact=factor,
                                      yfact=factor,
                                      origin=(0, 0, 0))
    IDT_group['route'] = route
Esempio n. 44
0
    def getNFPForHole(self, hole):
        shape_hash = self.getShapeHash()
        try: # try to get cached NFP
            if _debug: print("hole ", hole.wkt, " has cached nfp")
            return hole.shape_nfps[shape_hash]
        except KeyError: # it does not exist
            shapepoints = list(orient(self.shape_rotated).exterior.coords)
            if self.convex_hull:
                shapepoints = list(orient(self.shape_rotated.convex_hull).exterior.coords)
            holepoints = list(orient(hole.simplify(1)).exterior.coords)
            holepoints = roundCoords(holepoints)
            trans = [- shapepoints[0][0], - shapepoints[0][1]]
            holepoints[0] = [holepoints[0][0]+1,holepoints[0][1]+1] #hacky hack
            holepoints[-1] = holepoints[0]
            try:
                nfps = genNFP(holepoints, shapepoints)
            except RuntimeError as err:
                self.logger.log("WTF?: " + str(err), self.logger.logLevel.DEBUG, self.log_type)
                holepoints = roundCoords(holepoints)
                try:
                    nfps = genNFP(holepoints, shapepoints)
                except Exception as ee:
                    self.logger.log("WTF!!!" + str(ee), self.logger.logLevel.DEBUG, self.log_type)
                    holepoints = intCoords(holepoints)
                    shapepoints = intCoords(shapepoints)
                    try:
                        nfps = genNFP(holepoints, shapepoints)
                    except Exception as ee:
                        self.logger.log("WTF??????????" + str(ee), self.logger.logLevel.DEBUG, self.log_type)
                        holepoints[0] = [holepoints[0][0]-1,holepoints[0][1]-1] #unhacky unhack
                        holepoints[-1] = holepoints[0]
                        try:
                            nfps = genNFP(holepoints, shapepoints)
                        except Exception as ee:
                            self.logger.log("Falling back to circle" + str(ee), self.logger.logLevel.DEBUG, self.log_type)
                            return None
            except:
                print("Fatal error")
            if _debug: print("storing new NFP for hole ", hole.wkt)

            try:
                npolys = Polygon(nfps[0], nfps[1:])
            except:
                # one of NFPS has less than 3 points -> ignote it #FIXME: do not ignore it somehow

                # hack to create polygons out of 1- and 2-point NFPS by appending
                # copies of the last point so that there are at least 3
                #nfps[1:] = [[*x, *[x[-1]]*(3-len(x))] if len(x) < 3 else x for x in nfps[1:]]

                npolys = Polygon(nfps[0], [x for x in nfps[1:] if len(x) >= 3])
                self.logger.log("OHSHIT!", logger.logLevel.WARNING, self.log_type)
            
            npolys = npolys.buffer(self.hole_offset, resolution=2)
            npolys = affinity.translate(npolys, trans[0], trans[1])            
            hole.shape_nfps[shape_hash] = npolys # store the NFP in cache
            return npolys
Esempio n. 45
0
    def __update(self, eps=0.001):
        if len(list(self.__parcels)) == 0:
            raise Warning('Empty Block')

        self.parcels = self.__parcels
        self.polygon = self.__polygon
        for trans_type, params in self.__transform_list:
            if trans_type == 'rotation':
                theta, origin = params
                self.parcels = rotate(self.parcels, theta, origin=origin)
                self.polygon = rotate(self.polygon, theta, origin=origin)
            elif trans_type == 'translation':
                x_offset, y_offset = params
                self.parcels = translate(self.parcels, x_offset, y_offset)
                self.polygon = translate(self.polygon, x_offset, y_offset)
            elif trans_type == 'scaling':
                xfact, yfact, origin = params
                self.parcels = scale(self.parcels, xfact, yfact, origin=origin)
                self.polygon = scale(self.polygon, xfact, yfact, origin=origin)
Esempio n. 46
0
def get_polygons(shape, scale):
    result = []
    parts = list(shape.parts) + [len(shape.points)]
    for i1, i2 in zip(parts, parts[1:]):
        points = [mercator(y, x, scale) for x, y in shape.points[i1:i2]]
        polygon = Polygon(points)
        bounds = polygon.bounds
        polygon = translate(polygon, -bounds[0], -bounds[1])
        result.append(polygon)
    return result
Esempio n. 47
0
def _example():
    from gdshelpers.geometry.chip import Cell

    kit_logo = KITLogo([0, 0], 1)
    wwu_logo = WWULogo([0, 0], 1, 1)

    cell = Cell('LOGOS')
    cell.add_to_layer(1, kit_logo)
    cell.add_to_layer(1, translate(wwu_logo.get_shapely_object(), 2.5))
    cell.show()
Esempio n. 48
0
 def get_polygon(self, idx, FoR='local'):
     """Get polygon in the appropriate Frame-of-Reference.
     By default, returns in the local frame to avoid translation.
     """
     if FoR == 'global':
         return translate(self._polygons[idx], *self.centers[idx])
     elif FoR == 'local':
         return self._polygons[idx]
     else:
         raise Exception('invalid frame of reference (FoR)')
Esempio n. 49
0
 def draw_aperture(self, x, y):
     (name, mods) = self.apertures[self.aperture]
     if name == 'R':
         (w,h) = mods
         p = sa.translate(sg.box(-w / 2, -h / 2, w / 2, h / 2), x, y)
         self.polys.append(p)
     elif name == 'C':
         (r, ) = mods
         self.polys.append(sg.Point(x, y).buffer(r))
         assert 0
Esempio n. 50
0
 def get_base_shape(self):
     """
     Get the base shape of this ship, in board coordinates
     return: Polygon representing this ship
     """
     bx = self.base_size[0] / 2
     by = self.base_size[1] / 2
     base_shape = box(-bx, -by, bx, by)
     base_shape = rotate(base_shape, self.orientation)
     return translate(base_shape, self.position[0], self.position[1])
Esempio n. 51
0
 def add_paper(self, width, height):
     """paper width and height are assumed to be in scalar units
         (inches by default)
     """
     geom = box(minx=0, miny=0, maxx=width, maxy=height)
     self.paper = translate(geom,
                            xoff=self.paper_origin.x,
                            yoff=self.paper_origin.y)
     self.paper_center = self.paper.centroid
     return self.paper
Esempio n. 52
0
 def __init__(self, corners, parcel_borders=[], x=0, y=0, theta=0):
     self.__polygon = translate(Polygon(corners), x, y)
     merged = linemerge([self.__polygon.boundary] +
                        [LineString(_) for _ in parcel_borders])
     borders = unary_union(merged)
     self.__parcels = MultiPolygon(list(polygonize(borders)))
     self.polygon = self.__polygon
     self.parcels = self.__parcels
     self.__transform_list = []
     self.rotate(theta)
Esempio n. 53
0
 def get_shapely_object(self):
     shapely_object = geometric_union([
         self._gate(),
         self._choke_channel(),
         self._choke_left(),
         self._choke_right(),
         self._channel()
     ])
     rotated_object = rotate(shapely_object, self._angle, (0, 0), True)
     return translate(rotated_object, self._origin[0], self._origin[1], 0)
Esempio n. 54
0
def get_polygon(t):
    pos = t.position()
    vert = t.get_shapepoly()
    heading = t.heading()
    print('vert {}'.format(vert))
    p = Polygon(vert)
    p = translate(p, xoff=pos[0], yoff=pos[1])
    p = rotate(p, 90 + heading)
    print('polygon {}'.format(p))
    return p
Esempio n. 55
0
 def move(self, east_metres=0.0, north_metres=0.0):
     '''
     Move the Structure by the specified distance 
     To move south specify a negative value for north_metres. Same for west
     '''
     self.geometry = translate(self.geometry,
                               xoff=east_metres,
                               yoff=north_metres,
                               zoff=0.0)
     return self
Esempio n. 56
0
        def _transform(geom):
            centroid = geom.centroid

            # Bring back to origin
            geom = translate(geom, xoff=-centroid.x, yoff=-centroid.y)
            geom = rotate(geom,
                          -self._bubble_heading,
                          "centroid",
                          use_radians=True)

            # Now apply new transformation in "vehicle coordinate space"
            geom = translate(
                geom,
                xoff=self._bubble.follow_offset[0],
                yoff=self._bubble.follow_offset[1],
            )
            geom = rotate(geom, vehicle.heading, (0, 0), use_radians=True)
            geom = translate(geom, xoff=x, yoff=y)
            return geom
Esempio n. 57
0
    def handle(self, *args, **options):
        minx = options['minx']
        miny = options['miny']
        maxx = options['maxx']
        maxy = options['maxy']

        if minx >= maxx:
            raise CommandError(_('minx has to be lower than maxx'))
        if miny >= maxy:
            raise CommandError(_('miny has to be lower than maxy'))

        width = maxx-minx
        height = maxy-miny

        model = {'areas': Area, 'obstacles': Obstacle}[options['type']]

        namespaces = {'svg': 'http://www.w3.org/2000/svg'}

        svg = ElementTree.fromstring(options['svgfile'].read())
        svg_width = float(svg.attrib['width'])
        svg_height = float(svg.attrib['height'])

        for element in svg.findall('.//svg:clipPath/..', namespaces):
            for clippath in element.findall('./svg:clipPath', namespaces):
                element.remove(clippath)

        for element in svg.findall('.//svg:symbol/..', namespaces):
            for clippath in element.findall('./svg:symbol', namespaces):
                element.remove(clippath)

        if svg.findall('.//*[@transform]'):
            raise CommandError(_('svg contains transform attributes. Use inkscape apply transforms.'))

        if model.objects.filter(space=options['space'], import_tag=options['name']).exists():
            raise CommandError(_('objects with this import tag already exist in this space.'))

        with MapUpdate.lock():
            changed_geometries.reset()
            for path in svg.findall('.//svg:path', namespaces):
                for polygon in self.parse_svg_data(path.attrib['d']):
                    if len(polygon) < 3:
                        continue
                    polygon = Polygon(polygon)
                    polygon = scale(polygon, xfact=1, yfact=-1, origin=(0, svg_height/2))
                    polygon = scale(polygon, xfact=width / svg_width, yfact=height / svg_height, origin=(0, 0))
                    polygon = translate(polygon, xoff=minx, yoff=miny)
                    obj = model(geometry=polygon, space=options['space'], import_tag=options['name'])
                    obj.save()
            MapUpdate.objects.create(type='importsvg')

        logger = logging.getLogger('c3nav')
        logger.info('Imported, map update created.')
        logger.info('Next step: go into the shell and edit them using '
                    '%s.objects.filter(space_id=%r, import_tag=%r)' %
                    (model.__name__, options['space'].pk, options['name']))
Esempio n. 58
0
def splitworlds_shape(shape, seam_longitude):
    """Returns three MultiPolygons: western old world, eastern old world, and new world."""

    # Construct MultiPolygon to perform intersections
    multi = geoshapes.shape2multi(shape).buffer(0)
    multi = multi.intersection(geometry.box(multi.bounds[0], -30, multi.bounds[2], 30))

    # Drop the drop boxes
    for region in DROP_REGIONS:
        multi = multi.difference(region)

    # Pull out the list, in case it wasn't a list
    geoms = [poly for poly in geoshapes.polygons(multi)]

    in_newworlds = []
    for geom in geoms:
        minnew = in_newworld(*geom.bounds[:2])
        maxnew = in_newworld(*geom.bounds[2:])
        assert minnew == maxnew
        in_newworlds.append(minnew)

    newworld = geometry.MultiPolygon([geoms[ii] for ii in range(len(geoms)) if in_newworlds[ii]])
    if np.all(in_newworlds):
        return geometry.MultiPolygon(), geometry.MultiPolygon(), newworld

    # If some old world, construct unions and re-seam
    oldworld = []
    for ii in range(len(geoms)):
        if in_newworlds[ii]:
            continue

        # Move everything west of new world to the far east
        if geoms[ii].bounds[0] < -65:
            oldworld.append(affinity.translate(geoms[ii], 360))
        else:
            oldworld.append(geoms[ii])

    oldworld = ops.cascaded_union(geometry.MultiPolygon(oldworld))
    rightoldworld = oldworld.intersection(geometry.box(-65, -30, seam_longitude, 30))
    leftoldworld = affinity.translate(oldworld.intersection(geometry.box(seam_longitude, -30, oldworld.bounds[2], 30)), -360)

    return rightoldworld, leftoldworld, newworld
Esempio n. 59
0
    def to_minimise(optimiser_input):
        rotated = aff.rotate(
            ellipse, optimiser_input[2], origin='centroid')
        translated = aff.translate(
            rotated, xoff=optimiser_input[0], yoff=optimiser_input[1])

        disjoint_area = (
            translated.difference(cutout).area +
            cutout.difference(ellipse).area
        )
        return disjoint_area
Esempio n. 60
0
	def affine_trans(self,header):
		for elmt in header.elements:
			if elmt.element.is_empty:
				continue
			if elmt.active:
				if self.mirror:
					elmt.element=affinity.scale(elmt.element, xfact=1, yfact=-1,origin=self.center)
				if abs(self.rot_ang) > self.tiny_ang:
					elmt.element=affinity.rotate(elmt.element, self.rot_ang,origin=self.center)
				if abs(self.xoff) > 0.0 or abs(self.yoff) > 0.0:
					elmt.element=affinity.translate(elmt.element, xoff=self.xoff, yoff=self.yoff)