Пример #1
0
def get_poly_cb(f_fiducial_poly, f_target_poly, opts):
    # Get board
    ps_b = get_ps_b(opts)
    poly_cb = Polygon(ps_b[[0, 2, 3, 1], :])

    # Subtract fiducial markers
    s_f = opts['size_fiducial']
    ps_fp = get_ps_fp(opts)
    for idx, p_fp in enumerate(ps_fp):
        fiducial_poly = f_fiducial_poly(idx + 1)
        poly_cb = poly_cb.difference(
            affine_poly(fiducial_poly,
                        [[s_f, 0, p_fp[0]], [0, s_f, p_fp[1]], [0, 0, 1]]))

    # Subtract targets
    sz_t, num_t_w, num_t_h = opts['size_target'], opts[
        'num_targets_width'], opts['num_targets_height']
    ps_t = get_ps_t(opts)
    for idx, p_t in enumerate(ps_t):
        target_poly = f_target_poly(*np.unravel_index(idx, (num_t_h, num_t_w)))
        poly_cb = poly_cb.difference(
            affine_poly(target_poly,
                        [[sz_t, 0, p_t[0]], [0, sz_t, p_t[1]], [0, 0, 1]]))

    return poly_cb
Пример #2
0
def calculate_errors(image,path,groups,groups_edges, err_name):
	df = pd.DataFrame(columns=["image","path","radius",err_name])

	for grp in groups.keys():
		#edges
		if grp not in groups_edges.keys():
			edge_err = 1.0

		else:
			a = Polygon(groups_edges[grp])
			b = Polygon(groups[grp])

			if not (a.is_valid and b.is_valid):
				edge_err = 1.0

			else:

				Adiff1 = a.difference(b).area
				Adiff2 = b.difference(a).area
				Adiff = Adiff1+Adiff2
				Aunion = a.union(b).area
				edge_err = Adiff/Aunion

		b = Polygon(groups[grp])

		df = df.append({
			"image": image,
			"path": path,
			"group":grp,
			"radius": sqrt(b.area/pi),
			err_name: edge_err
			}, ignore_index=True)

	return df
Пример #3
0
    def placePoly(self,index):
        '''
        放置某一个index的形状进去
        '''
        adjoin=self.polygons[index]
        ifp=self.getInnerFitRectangle(self.polygons[index])
        differ_region=Polygon(ifp)
        multi=True
        if multi==True:
            if self.choose_nfp==True and index>8:
                target_polygon=self.polygons[index-8:index]
                bottom_height=self.getMinTop(target_polygon)+300
                differ_region=differ_region.difference(Polygon([[0,0],[self.width,0],[self.width,bottom_height],[0,bottom_height]]))
            else:
                target_polygon=self.polygons[0:index]
            tasks=[(main,adjoin) for main in target_polygon]
            res=pool.starmap(NFP,tasks)
            for item in res:
                nfp=item.nfp
                differ_region=differ_region.difference(Polygon(nfp))
        else:
            for main_index in range(0,index):
                main=self.polygons[main_index]
                nfp=NFP(main,adjoin).nfp
                differ_region=differ_region.difference(Polygon(nfp))

        # print(differ_region)
        differ=GeoFunc.polyToArr(differ_region)

        differ_index=self.getBottomLeft(differ)
        refer_pt_index=GeoFunc.checkTop(adjoin)
        GeoFunc.slideToPoint(self.polygons[index],adjoin[refer_pt_index],differ[differ_index])        
Пример #4
0
def mask_china_region(ax, facecolor='white', include_sea=False):
    china_shapefile_path = f'{os.path.dirname(os.path.realpath(__file__))}/../shapefiles/china_without_islands.shp'

    extent = ax.get_extent()
    frame = Polygon([(extent[0], extent[2]), (extent[1], extent[2]),
                     (extent[1], extent[3]), (extent[0], extent[3]),
                     (extent[0], extent[2])])

    shapes = cascaded_union(
        list(ShapeReader(china_shapefile_path).geometries()))

    if include_sea:
        for polygon in shapes:
            if polygon.area > 900:
                china_mainland = polygon
                break
        mask_polygon = frame.difference(
            china_mainland.union(get_china_territorial_sea_polygon()))
        if type(mask_polygon) != MultiPolygon:
            mask_polygon = MultiPolygon([mask_polygon])
    else:
        mask_polygon = MultiPolygon([frame.difference(shapes)])

    mask = ShapelyFeature(mask_polygon,
                          ccrs.PlateCarree(),
                          edgecolor='none',
                          facecolor=facecolor)
    ax.add_feature(mask)
Пример #5
0
    def test_polygon_topojson(self):
        '''
        Create a polygon to cover the world and make sure it is "similar" (clip on)
        '''

        self.defineGeometry('POLYGON')

        geom = Polygon([(-180, -85.0511), (180, -85.0511), (180, 85.0511),
                        (-180, 85.0511), (-180, -85.0511)])

        self.insertTestRow(geom.wkt)

        tile_mimetype, tile_content = utils.request(self.config_file_content,
                                                    "vectile_test", "topojson",
                                                    0, 0, 0)
        self.assertTrue(tile_mimetype.endswith('/json'))
        topojson_result = json.loads(tile_content.decode('utf8'))
        topojson_xform = get_topo_transform(topojson_result)

        parts = [
            topojson_result['arcs'][arc[0]] for arc in
            topojson_result['objects']['vectile']['geometries'][0]['arcs']
        ]
        parts = [
            list(map(topojson_xform, topojson_dediff(part))) for part in parts
        ]

        result_geom = Polygon(*parts)
        expected_geom = Polygon([(-180, -85.0511), (180, -85.0511),
                                 (180, 85.0511), (-180, 85.0511),
                                 (-180, -85.0511)])

        # What is going on here is a bit unorthodox, but let me explain. The clipping
        # code inside TileStache relies on GEOS Intersection alongside some TileStache code
        # that creates a clipping geometry based on the tile perimeter. The tile perimeter
        # is made out of 17 (x,y) coordinates and not a box. Hence, the GEOS::Intersection
        # os that perimeter with the geometry of the vector we get back from the data provider
        # can end with extra vertices. Although it is the right shape, we cannot do a straight
        # comparisson because the expected geometry and the returned geometry *may* have extra
        # vertices. Simplify() will not do much because the distance of the vertices can clearly
        # be bigger than the tolerance.
        #
        # To add to this, because of double precision, the vertices may not be exact.
        # An optional way to find out if two shapes are close enough, is to buffer the two features
        # by just a little bit and then subtract each other like so:
        #
        #             geometry1.difference(geometry2) == empty set?
        #             geometry2.difference(geometry1) == empty set?
        #
        # If both geometries are empty, then they are similar. Hence what you see below

        # Close enough?
        self.assertTrue(
            result_geom.difference(expected_geom.buffer(1)).is_empty)
        self.assertTrue(
            expected_geom.difference(result_geom.buffer(1)).is_empty)
Пример #6
0
def place_tiles_into_gaps(polygons, filler_chains, half_tile, A0, plot=[]):
    # fill spaces which are still empty after the main construction step
    t0 = time.time()
    counter = 0
    for chain in filler_chains:
        # Speed up:
        chain_as_line = LineString(np.array(chain)[:, ::-1]).buffer(
            2.1 * half_tile)  # ::-1 weil x und y vertauscht werden muss
        preselected_nearby_polygons = [
            poly for poly in polygons if poly.intersects(chain_as_line)
        ]
        # Sicherstellen, dass am Ende der Kette nichts verschenkt wird
        index_list = list(range(0, len(chain), half_tile * 2))
        last_i = len(chain) - 1
        min_delta = 3
        if index_list[-1] != last_i and last_i - index_list[-1] >= min_delta:
            index_list += [last_i]
        for i in index_list:
            y, x = chain[i]
            p = Polygon([[x - half_tile, y + half_tile],
                         [x + half_tile, y + half_tile],
                         [x + half_tile, y - half_tile],
                         [x - half_tile, y - half_tile]])
            # fit in polygon (concave ones are okay for now)
            p_buff = p.buffer(0.1)
            nearby_polygons = [
                poly for poly in preselected_nearby_polygons
                if p_buff.intersects(poly)
            ]
            for p_vorhanden in nearby_polygons:
                try:
                    p = p.difference(p_vorhanden)  # => remove overlap
                except:
                    p = p.difference(
                        p_vorhanden.buffer(0.1))  # => remove overlap
            # keep only largest fragment if more than one exists
            if p.geom_type == 'MultiPolygon':
                i_largest = np.argmax([p_i.area for p_i in p])
                p = p[i_largest]
            if p.area >= 0.05 * A0 and p.geom_type == 'Polygon':  # sort out very small tiles
                polygons += [p]
                preselected_nearby_polygons += [p]
                counter += 1
    if 'polygons_filler' in plot:
        plotting.draw_tiles(polygons,
                            None,
                            h=0,
                            w=0,
                            background_brightness=0.2,
                            return_svg=False,
                            chains=filler_chains,
                            axis_off=True)
    print(f'Added {counter} tiles into gaps:', f'{time.time()-t0:.1f}s')
    return polygons
Пример #7
0
def calcCurveErr(workspace,poly,mean,sigma,level):
    # see: http://toblerity.org/shapely/manual.html
    boundaryestimate = getLevelSet (workspace, mean, level)
    # GroundTruth = np.vstack((poly,poly[0]))
    GroundTruth=Polygon(GroundTruth)
    boundaryestimate=Polygon(boundaryestimate)

    mislabeled=boundaryestimate.symmetric_difference(GroundTruth) # mislabeled data ()
    boundaryestimate.difference(GroundTruth) #mislabeled as tumor--extra that would be removed
    GroundTruth.difference(boundaryestimate) # mislbaled as not-tumor--would be missed and should be cut out
    correct=boundaryestimate.intersection(GroundTruth) #correctly labeled as tumor
    return correct.area, mislabeled.area
Пример #8
0
def remove_overlapping_areas(polygons):

    for i in range(len(polygons)):
        for j in range(i+1, len(polygons)):
            p1 = Polygon(polygons[i])
            p2 = Polygon(polygons[j])

            if p1.intersects(p2):
                intersection = p1.intersection(p2)

                print(p1.difference(intersection))

                subtracted = str(p1.difference(intersection)).split("((")[1].split("))")[0].split(", ")
                '''
    def test_polygon_topojson(self):
        '''
        Create a polygon to cover the world and make sure it is "similar" (clip on)
        '''
        
        self.defineGeometry('POLYGON')

        geom = Polygon( [(-180, -85.0511),
                         ( 180, -85.0511),
                         ( 180, 85.0511), 
                         (-180, 85.0511), 
                         (-180, -85.0511)])

        self.insertTestRow(geom.wkt)
        
        tile_mimetype, tile_content = utils.request(self.config_file_content, "vectile_test", "topojson", 0, 0, 0)
        self.assertTrue(tile_mimetype.endswith('/json'))
        topojson_result = json.loads(tile_content)
        topojson_xform = get_topo_transform(topojson_result)
        
        parts = [topojson_result['arcs'][arc[0]] for arc in topojson_result['objects']['vectile']['geometries'][0]['arcs']]
        parts = [map(topojson_xform, topojson_dediff(part)) for part in parts]
        
        result_geom = Polygon(*parts)
        expected_geom = Polygon( [(-180, -85.0511), (180, -85.0511), (180, 85.0511), (-180, 85.0511), (-180, -85.0511)])

        # What is going on here is a bit unorthodox, but let me explain. The clipping
        # code inside TileStache relies on GEOS Intersection alongside some TileStache code
        # that creates a clipping geometry based on the tile perimeter. The tile perimeter
        # is made out of 17 (x,y) coordinates and not a box. Hence, the GEOS::Intersection
        # os that perimeter with the geometry of the vector we get back from the data provider
        # can end with extra vertices. Although it is the right shape, we cannot do a straight
        # comparisson because the expected geometry and the returned geometry *may* have extra
        # vertices. Simplify() will not do much because the distance of the vertices can clearly
        # be bigger than the tolerance. 
        #
        # To add to this, because of double precision, the vertices may not be exact.
        # An optional way to find out if two shapes are close enough, is to buffer the two features
        # by just a little bit and then subtract each other like so:
        #
        #             geometry1.difference(geometry2) == empty set?
        #             geometry2.difference(geometry1) == empty set?
        # 
        # If both geometries are empty, then they are similar. Hence what you see below
        
        # Close enough?
        self.assertTrue(result_geom.difference(expected_geom.buffer(1)).is_empty)
        self.assertTrue(expected_geom.difference(result_geom.buffer(1)).is_empty)
Пример #10
0
    def __init__(self):

        super(ConcaveDecomp, self).__init__()
        self.segment_count = segment_count
        self.body_size = body_size
        self.density = 1
        self.friction = 1
        ground = self.world.CreateBody(shapes=b2EdgeShape(
            vertices=[(-40, 40), (-4000, -10), (4000, -10), (40, 40)]))

        boxV = [(0, 1), (1, 1), (1, 0), (0, 0)]
        boxS = [(1, 2), (2, 3), (3, 4), (4, 1)]
        boxPath = self.makeClosedPath(boxV)
        #self.plotPatch(boxPath)
        POC = (0, .5)
        r = .25
        N = 20
        circV, circS = self.makeALD(POC, r, N)
        a = Polygon(boxV)
        b = Polygon(circV)

        newPoly = a.difference(b)
        x, y = self.verts2XY(newPoly.exterior.coords)
        print 'yay'
        plt.plot(x, y)
        plt.show()
        newPolyS = self.XY2Verts_Segs(newPoly.exterior.coords)
Пример #11
0
class PaintConnectTest2(PaintTestCase):
    """
    Boundary with an internal cutout.
    """

    def setUp(self):
        self.boundary = Polygon([[0, 0], [0, 5], [5, 5], [5, 0]])
        self.boundary = self.boundary.difference(
            Polygon([[2, 1], [3, 1], [3, 4], [2, 4]])
        )

    def test_no_jump3(self):
        print "TEST: No jump expected"
        paths = [
            LineString([[0.5, 1], [1.5, 3]]),
            LineString([[4, 1], [4, 4]])
        ]
        for p in paths:
            print p

        tooldia = 1.0

        print "--"
        result = Geometry.paint_connect(mkstorage(deepcopy(paths)), self.boundary, tooldia)

        result = list(result.get_objects())
        for r in result:
            print r

        self.assertEqual(len(result), len(paths))
Пример #12
0
def reshapePatron(offset, shape, patron):
    if not (patron):
        return []
    localShape = Polygon(offsetShape(
        shape, offset))  # object polygon needed to use the function difference
    localPatron = Polygon(patron)
    try:
        localPatron = localPatron.difference(
            localShape)  # to create the new patron
    except:
        return [[0, 0]]
    if localPatron.geom_type == 'MultiPolygon':
        localPatronTabFloat = []
        for i in range(len(localPatron)):
            localPatronTabFloat += localPatron[i].exterior.coords[:]
        if (localPatronTabFloat[0] == localPatronTabFloat[-1]):
            localPatronTabFloat.pop(
            )  # to delete the last value which is also the first (avoiding double detection)
        # print("local patron_mmulti")
        # print(localPatron)
        # print("local patron float_mmulti")
        # print(localPatronTabFloat)
    else:
        localPatronTabFloat = localPatron.exterior.coords[:]  # to convert the object polygon into a tab of float
        if localPatronTabFloat:  # at the end the result is an empty list and so you can't substract anything
            localPatronTabFloat.pop(
            )  # to delete the last value which is also the first (avoiding double detection)
    localPatronTabInt = []
    for i in reversed(range(len(
            localPatronTabFloat))):  # a certain order is needed to detect fits
        localPatronTabInt.append(
            [int(localPatronTabFloat[i][0]),
             int(localPatronTabFloat[i][1])])
    # print(localPatronTabInt)
    return localPatronTabInt
Пример #13
0
    def common(self, z):

        Frame = Polygon(self.argv['frame'])
        polygons = self.argv['polygons']

        polypores = []
        for poly in polygons:
            thin = Polygon(poly).intersection(Frame)
            if isinstance(thin, shapely.geometry.multipolygon.MultiPolygon):
                tmp = list(thin)
                for t in tmp:
                    polypores.append(t)
            else:
                polypores.append(thin)
        MP = MultiPolygon(polypores)
        bulk = Frame.difference(cascaded_union(MP))
        if not (isinstance(bulk, shapely.geometry.multipolygon.MultiPolygon)):
            bulk = [bulk]

        loop_start = len(self.loops)
        for region in bulk:
            pp = list(region.exterior.coords)[:-1]
            self.create_lines_and_loop_from_points(pp, z)

            #From pores
            for interior in region.interiors:
                pp = list(interior.coords)[:-1]
                self.create_lines_and_loop_from_points(pp, z)
        loop_end = len(self.loops)

        self.surfaces.append(range(loop_start, loop_end))
Пример #14
0
    def get_aoi(uid):
        """
        给定UID,采集AOI和bound,转换坐标系
        :param uid:
        :return:  AOI列表
        """
        content = Spider.__request_url(aoi_str % uid).get(
            'content').get('geo')
        if content:
            wgs84_aois = []
            aois, bound = gis.parseGeo(content)  # 解析墨卡托坐标系
            # 围栏  坐标系转换:墨卡托-->百度-->wgs84
            for mocator in aois:
                bd_coord_aois = [list(gis.transform_func(*gis.convert_MCT_2_BD09(mct_x, mct_y))) for
                                 mct_x, mct_y in
                                 mocator]
                bd_coord_aois = [[round(lon, 6), round(lat, 6)] for lon, lat in bd_coord_aois]
                wgs84_aois.append(bd_coord_aois)

            if len(wgs84_aois) == 1:
                # 几乎100%是只有一个aoi,所以无需再套一层列表
                final_polygon = wgs84_aois[0]
            else:
                final_polygon = Polygon(wgs84_aois[0])
                for wgs84_aoi in wgs84_aois[1:]:
                    cur_polygon = Polygon(wgs84_aoi)
                    if cur_polygon.intersects(final_polygon):
                        final_polygon = final_polygon.difference(cur_polygon)
                    else:
                        final_polygon = final_polygon.union(cur_polygon)

            return Polygon(final_polygon).wkt
        return
Пример #15
0
 def import_hydro(self):
     print('Importing hydro...')
     poly_list = []
     outer = None
     for s in self.imported_hydro.shapeRecords():
         coords = s.__geo_interface__['geometry']['coordinates']
         print(s.__geo_interface__['geometry']['type'])
         if len(coords) == 1 and type(coords[0]) is tuple:
             coords = coords[0]
             try:
                 s_p = Polygon(coords)
                 poly_list.append(s_p)
             except AssertionError:
                 for p in coords:
                     s_p = Polygon(p)
                     poly_list.append(s_p)
         else:
             outer = Polygon(coords[0])
             for i, g in enumerate(coords[1:]):
                 s_p = Polygon(g)
                 poly_list.append(s_p)
     if outer is None:
         self.hydro_as_poly = unary_union(poly_list)
     else:
         subtraction = unary_union(poly_list)
         self.hydro_as_poly = outer.difference(subtraction)
         self.donut_hydro = True
     self.hydro_area = self.hydro_as_poly.area
Пример #16
0
    def divide_polygon_for_intersection(self, segments):
        """ Generates multiple polygons based on cutting the 
        fracture faces by line segments. 
        """
        R = self.build_rotation_matrix()
        fracture_poly_list = []
        # face_poly_list = []

        for point in self.points:
            rot_point = np.linalg.solve(R, point - self.center)
            fracture_poly_list.append(rot_point[:2])

        seg_rot = []
        for seg in segments:
            p1 = seg[0]
            p2 = seg[1]

            vec = p2 - p1
            p1 = p1 - 100.0 * vec
            p2 = p2 + 100.0 * vec

            p1_rot = np.linalg.solve(R, p1 - self.center)
            p2_rot = np.linalg.solve(R, p2 - self.center)

            line = LineString((p1_rot[:2], p2_rot[:2]))
            dilated = line.buffer(1.0e-10)
            seg_rot.append(dilated)

        fracture_poly = Polygon(fracture_poly_list)

        divided_polygons = fracture_poly.difference(seg_rot[0])

        return (divided_polygons, fracture_poly)
Пример #17
0
def _update3(itr,D,x,soln,t,ax,time):
  N = 100
  #ax.clear()
  buff = 200.0
  minx = np.min(x[:,0])
  maxx = np.max(x[:,0])
  miny = np.min(x[:,1])
  maxy = np.max(x[:,1])
  ax.set_xlim((minx-buff/2,maxx+buff/2))
  ax.set_ylim((miny-buff/2,maxy+buff/2))
  square = Polygon([(minx-buff,miny-buff),
                    (minx-buff,maxy+buff),
                    (maxx+buff,maxy+buff),
                    (maxx+buff,miny-buff),
                    (minx-buff,miny-buff)])
  ax.add_artist(PolygonPatch(square.difference(D),alpha=1.0,color='k',zorder=1))
  xitp = np.linspace(minx,maxx,N)
  yitp = np.linspace(miny,maxy,N)
  xgrid,ygrid = np.meshgrid(xitp,yitp)
  xflat = xgrid.flatten()
  yflat = ygrid.flatten()
  ax.images = []
  im =NonUniformImage(ax,interpolation='bilinear',
                         cmap='cubehelix',
                         extent=(minx,maxx,miny,maxy))
  val = soln[itr](zip(xflat,yflat))
  val = np.sqrt(np.sum(val**2,1))
  im.set_data(xitp,yitp,np.reshape(val,(N,N)))  
  ax.images.append(im)
  t.set_text('t: %s s' % time[itr])
  return ax,t
Пример #18
0
class PaintConnectTest2(PaintTestCase):
    """
    Boundary with an internal cutout.
    """
    def setUp(self):
        self.boundary = Polygon([[0, 0], [0, 5], [5, 5], [5, 0]])
        self.boundary = self.boundary.difference(
            Polygon([[2, 1], [3, 1], [3, 4], [2, 4]]))

    def test_no_jump3(self):
        print("TEST: No jump expected")
        paths = [
            LineString([[0.5, 1], [1.5, 3]]),
            LineString([[4, 1], [4, 4]])
        ]
        for p in paths:
            print(p)

        tooldia = 1.0

        print("--")
        result = Geometry.paint_connect(mkstorage(deepcopy(paths)),
                                        self.boundary, tooldia)

        result = list(result.get_objects())
        for r in result:
            print(r)

        self.assertEqual(len(result), len(paths))
Пример #19
0
def poly(polygon_, bm=None, name="Polygon"):
    """
    flattens polygons with holes to a mesh with only faces
    """
    # bmesh management
    nolink = False
    if bm == None:
        bm = bmesh.new()
    else:
        nolink = True
        
    if len(polygon_.interiors) > 0:
        # find area between inner rings
        inner = polygon_.interiors[0]
        for i in range(1, len(polygon_.interiors)):
            inner = MultiPolygon([Polygon(inner),Polygon(polygon_.interiors[i])])
            ch = inner.convex_hull
            bridge = ch.difference(inner)
            coords(bridge.exterior.coords, "FACE", bm)
            inner = ch.exterior
        
        # create two sides around all the interiors
        pb = polygon_.bounds
        triangle = Polygon((pb[:2],pb[2:],(pb[0],pb[3])))
        donut = Polygon(polygon_.exterior.coords, [inner.coords])
        half1 = donut.intersection(triangle)
        half2 = donut.difference(triangle)
        coords(half1.exterior.coords, "FACE", bm)
        coords(half2.exterior.coords, "FACE", bm)
    else:
        coords(polygon_.exterior.coords, "FACE", bm)
        
    if not nolink:
        link(bm, name)
Пример #20
0
def _build_polygon(value):
    scaling_ratio = CONFIG.DISPLAY_BOARD_SIZE[0] / CONFIG.DARTBOARD_IMAGE_DIMENSIONS[0]
    outter_radius = CONFIG.DIAMETERS[-1] * scaling_ratio

    # start with getting the swept angle based on the target point value
    value_list = [6, 13, 4, 18, 1, 20, 5, 12, 9, 14, 11, 8, 16, 7, 19, 3, 17, 2, 15, 10]

    # special case, return a circle
    if 25 not in POLYGONS:
        POLYGONS[25] = Point(0, 0).buffer(CONFIG.DIAMETERS[1] * scaling_ratio)

    if value == 25:
        return POLYGONS[25]

    bulls = POLYGONS[25]

    wedge_exterior_pts = []
    wedge_exterior_pts.append([0,0])

    theta1_deg = (value_list.index(value) * (18))-9
    theta2_deg = theta1_deg+18

    t1 = deg2rad(theta1_deg)
    t2 = deg2rad(theta2_deg)
    for theta in np.linspace(t1, t2, 32):
        x,y = pol2cart(outter_radius, theta)
        wedge_exterior_pts.append([x,y])

    # Generate a full slice of pie between center point and outter radius
    pie = Polygon(wedge_exterior_pts)

    # Chop off the interior bit that overlaps with the bullseye
    ret = pie.difference(bulls)
    return ret
Пример #21
0
def get_point_new_coverage(x,y,game_state, rotation,camera_field_of_view,obstacles):
    #rotation = (rotation - 45)%360
    rotation_rad = rotation / 180 * math.pi
    fov_checker = FieldOfView([x,y,rotation_rad],camera_field_of_view/180.0*math.pi, obstacles)

    checkPoly = fov_checker.getFoVPolygon(17)

    intersection_free_points = [[],[]]

    for x,y in zip(checkPoly.x_list,checkPoly.y_list) :
        if len(intersection_free_points[0]) != 0:
            if not ( abs(x - intersection_free_points[0][-1]) < 0.001 and abs(y-intersection_free_points[1][-1]) < 0.001):
                intersection_free_points[0].append(x)
                intersection_free_points[1].append(y)
        else :
            intersection_free_points[0].append(x)
            intersection_free_points[1].append(y)

    #newPoly = Polygon(zip(checkPoly.x_list, checkPoly.y_list))
    try :
        newPoly = Polygon(zip(intersection_free_points[0], intersection_free_points[1]))
        newPoly = newPoly.difference(game_state.world_poly.buffer(0))
    except:
        return 0

    world = game_state.world_poly

    show_animation = False

    if show_animation:
        plt.cla()
        plt.plot(x, y, "or")
        # plt.plot(gx, gy, "ob")
        # poly.plot("-r")

        if world.geom_type == 'MultiPolygon':
            for i in range(len(world)):
                pts = world[i].exterior.coords
                plt.fill([p[0] for p in pts], [p[1] for p in pts], "-b")
        else:
            pts = world.exterior.coords
            plt.fill([p[0] for p in pts], [p[1] for p in pts], "-b")

        if newPoly.geom_type == 'MultiPolygon':
            for i in range(len(newPoly)):
                pts = newPoly[i].exterior.coords
                plt.fill([p[0] for p in pts], [p[1] for p in pts], "-g")
        else:
            pts = newPoly.exterior.coords
            plt.fill([p[0] for p in pts], [p[1] for p in pts], "-g")

        #for i in range(len(obstacles)):
        #    obstacles[i].plot("-k")
        for obstacle in obstacles:
            obstacle.plot("-g")

        plt.axis("equal")
        plt.pause(1)

    return newPoly.area
Пример #22
0
    def placePoly(self, index):
        adjoin = self.polygons[index]
        # 是否垂直
        if self.vertical == True:
            ifr = packing.PackingUtil.getInnerFitRectangle(
                self.polygons[index], self.width, self.length)
        else:
            ifr = packing.PackingUtil.getInnerFitRectangle(
                self.polygons[index], self.length, self.width)
        differ_region = Polygon(ifr)

        for main_index in range(0, index):
            main = self.polygons[main_index]
            if self.NFPAssistant == None:
                nfp = NFP(main, adjoin, rectangle=self.rectangle).nfp
            else:
                nfp = self.NFPAssistant.getDirectNFP(main, adjoin)
            nfp_poly = Polygon(nfp)
            try:
                differ_region = differ_region.difference(nfp_poly)
            except:
                print('NFP failure, polys and nfp are:')
                print([main, adjoin])
                print(nfp)
                self.showAll()
                self.showPolys([main] + [adjoin] + [nfp])
                print('NFP loaded from: ', self.NFPAssistant.history_path)

        differ = GeoFunc.polyToArr(differ_region)
        differ_index = self.getBottomLeft(differ)
        refer_pt_index = GeoFunc.checkTop(adjoin)
        GeoFunc.slideToPoint(self.polygons[index], adjoin[refer_pt_index],
                             differ[differ_index])
Пример #23
0
def doPolygonize():
  blocks = polygonize(lines)
  writeBlocks(blocks, args[0] + '-blocks.geojson')

  blocks = polygonize(lines)
  bounds = Polygon([
    [minlng, minlat],
    [minlng, maxlat],
    [maxlng, maxlat],
    [maxlng, minlat],
    [minlng, minlat]
  ])
  # Geometry transform function based on pyproj.transform
  project = partial(
    pyproj.transform,
    pyproj.Proj(init='EPSG:3785'),
    pyproj.Proj(init='EPSG:4326'))
  print bounds
  print transform(project, bounds)

  print 'finding holes'
  for index, block in enumerate(blocks):
    if index % 1000 == 0:
      print "diff'd  %s" % (index)
    if not block.is_valid:
      print explain_validity(block)
      print transform(project, block)
    else:
      bounds = bounds.difference(block)
  print bounds
Пример #24
0
    def divide_polygon_for_intersection(self, segments):
        """ Generates multiple polygons based on cutting the 
        fracture faces by line segments. 
        """
        R = self.build_rotation_matrix()
        fracture_poly_list = []
        #face_poly_list = []

        for point in self.points:
            rot_point = np.linalg.solve(R, point - self.center)
            fracture_poly_list.append(rot_point[:2])

        seg_rot = []
        for seg in segments:
            p1 = seg[0]
            p2 = seg[1]

            vec = p2 - p1
            p1 = p1 - 100. * vec
            p2 = p2 + 100. * vec

            p1_rot = np.linalg.solve(R, p1 - self.center)
            p2_rot = np.linalg.solve(R, p2 - self.center)

            line = LineString((p1_rot[:2], p2_rot[:2]))
            dilated = line.buffer(1.e-10)
            seg_rot.append(dilated)

        fracture_poly = Polygon(fracture_poly_list)

        divided_polygons = fracture_poly.difference(seg_rot[0])

        return (divided_polygons, fracture_poly)
Пример #25
0
def showPoly(threshold):
    #this outputs blue and white polygon
    polygons = []
    tempx = []
    tempy = []
    for i in roomListLocal:
        tempx.append(i[0])
        tempy.append(i[1])
        polygon = Polygon(i)
        polygon = polygon.buffer(threshold, resolution=16, cap_style=2, join_style=3, mitre_limit=0.1)
        polygons.append(polygon)
    u = cascaded_union(polygons)
    polygon = Polygon(building_metre_polygon)
    global newPoly
    newPoly = polygon.difference(u)
    newPoly = newPoly.buffer(threshold, resolution=16, cap_style=2, join_style=3, mitre_limit=0.1)
    fig = plt.figure(1, figsize=5000, dpi=1000)
    ax = fig.add_subplot(111)
    print(newPoly)
    #plot_coords(ax, newPoly.exterior)
    patch = PolygonPatch(newPoly, facecolor=v_color(newPoly), edgecolor=v_color(newPoly), alpha=0.5, zorder=2)
    xrange = [-10, np.max(tempx) + 10]
    yrange = [-10, np.max(tempy) + 10]
    ax.set_xlim(*xrange)
    ax.set_ylim(*yrange)
    ax.set_aspect(1)
    ax.add_patch(patch)
    ax.set_aspect(1)
    plt.show()
def checkSupport(rule, dd, belowLayer, aboveLayer):
    objs = aboveLayer.objs
    for id2, o2 in objs.items():
        ## Support posts are supported -- you don't have to check
        bbox = o2.shape.bounds
        cumulative = Polygon(o2.shape)
        o2_supported = False
        ## things below that might support the object
        candidates = belowLayer.index.intersection(bbox)
        for cind in candidates:
            if not cind in dd.layers[DesignDict.POST].objs:
                o1 = belowLayer.objs[cind]
                if supported(o1, o2):
                    o2_supported = True
                    break
                else:
                    cumulative = cumulative.difference(o1.shape)
        ## we didn't leave the inner loop with a return.
        ## the above object isn't supported.
        if not o2_supported:
            wit = []
            if isinstance(cumulative, Polygon):
                wit.append(Witness(Witness.REGION, cumulative))
            elif isinstance(cumulative, MultiPolygon):
                for r in cumulative:
                    wit.append(Witness(Witness.REGION, r))
            else:
                raise "Unrecognized type"
            dd.violations.add(Violation.ofRule(rule, [o2], wit))
Пример #27
0
def get_lanes(egolane_clusters, other_lanes_clusters):
    """ 
      Method used to transform the hulls into polygons.
      The first thing to do is to select which of the clusters of the egolane is actually the egolane. 
      This is done selecting the cluster with the biggest area.
      Then, we subtract the intersections with the other lanes to avoid that one pixel is associated to both the egolane
      and another lane.
      Finally, we split the other lanes in left ones and right ones, basing the assumption on the centroid position.
      The biggest cluster on the right will be the right lane, the biggest on the left the left lane.

      args:
          egolane_clusters: set of points that represents the convex hull of the egolane. Can be more than one
          other_lanes_clusters: set of points that represents the convex hull of the other lanes. Can be more than one
  """
    ### Selecting the egolane
    egolane_polygons = [Polygon(x) for x in egolane_clusters]
    egolane = max(egolane_polygons, key=lambda p: p.area)

    egolane = Polygon(egolane)
    other_lanes_polygons = []

    ### Subtracting the intersecting pixels
    # note that this code gives priority to the detection of the other lanes; in this way we can minimize the risk of
    # getting on another lane
    for elem in other_lanes_clusters:
        elem = Polygon(elem)
        other_lanes_polygons.append(elem)
        egolane = egolane.difference(egolane.intersection(elem))

    ### Egolane refinement
    # The deletion of the intersecting regions can cause a split in the egolane in more polygons. In this case,
    # the biggest polygon is selected as the new egolane
    if isinstance(egolane, MultiPolygon):
        polygons = list(egolane)
        egolane = max(polygons, key=lambda p: p.area)

    ### Splitting the other lanes in left and right ones
    left_lanes = [
        lane for lane in other_lanes_polygons
        if lane.centroid.x < egolane.centroid.x
    ]
    right_lanes = [
        lane for lane in other_lanes_polygons
        if lane.centroid.x >= egolane.centroid.x
    ]

    ### Selecting the right and the left lane
    left_lane = None if len(left_lanes) == 0 else max(left_lanes,
                                                      key=lambda p: p.area)
    right_lane = None if len(right_lanes) == 0 else max(right_lanes,
                                                        key=lambda p: p.area)

    ### Numpy conversion
    if egolane is not None: egolane = np.asarray(egolane.exterior.coords.xy).T
    if left_lane is not None:
        left_lane = np.asarray(left_lane.exterior.coords.xy).T
    if right_lane is not None:
        right_lane = np.asarray(right_lane.exterior.coords.xy).T

    return egolane, left_lane, right_lane
Пример #28
0
def _trim_polygon(crs: CRS, polygon: Polygon) -> Polygon:
    """
    Remove coordinates from the polygon can cannot be interpolated easily but
    simply cutting out a box between the coordinates.

    :param crs: The coordinate reference system to verify.
    :param polygon: The polygon to cut.
    :return: A new polygon.
    """
    wgs84_to_proj = Transformer.from_proj(CRS.from_epsg(4326), crs)
    new_polygon = Polygon(polygon)
    for i in range(len(polygon.exterior.coords) - 1):
        a = polygon.exterior.coords[i]
        b = polygon.exterior.coords[i + 1]
        if a[0] == b[0] or a[1] == b[1]:
            continue

        # We want to preserve diagonals as much as possible, so we only cut off
        # pieces if the mid-point for two coordinates cannot be projected. But
        # this is known to produce false positives! So this might be removed.
        mid_point = (a[0] + b[0]) / 2, (a[1] + b[1]) / 2
        if wgs84_to_proj.transform(*mid_point)[0] != float('inf'):
            continue

        boxed_coordinates = _box_coordinates(a, b)
        new_polygon = new_polygon.difference(boxed_coordinates)
    return new_polygon
Пример #29
0
def normalize_footprint(footprint: List[Tuple[float, float]]) -> MultiPolygon:
    """Split footprints which cross the anti-meridian

    Most applications, including RasterFoundry, cannot handle a single polygon representation
    of anti-meridian crossing footprint.
    Normalizing footprints by splitting them over the anti-meridian fixes cases where
    scenes appear to span all longitudes outside their actual footprint.
    If a footprint covers the anti-meridian, the shape is shifted 360 degrees, split,
    then the split section is moved back.
    """
    intersects = intersects_antimeridian(footprint)
    if not intersects:
        return MultiPolygon([Polygon(footprint)])
    else:
        shifted_footprint = Polygon([shift_point(p, 0, Side.RIGHT, False, 360) for p in footprint])
        left_hemisphere_mask = Polygon([(0, -90), (180, -90), (180, 90), (0, 90), (0, -90)])
        left_split = shifted_footprint.intersection(left_hemisphere_mask)
        right_split = Polygon([
            shift_point((x, y), 180, Side.LEFT, True, -360)
            for x, y
            in shifted_footprint.difference(left_hemisphere_mask).exterior.coords
        ])
        if left_split.area > 0 and right_split.area > 0:
            return MultiPolygon([left_split, right_split])
        elif left_split.area > 0:
            return MultiPolygon([left_split])
        elif right_split.area > 0:
            return MultiPolygon([right_split])
        else:
            return MultiPolygon([])
Пример #30
0
def boundary_list(platforms,dist_to_platform):
    boundaries_in = []
    boundaries_out = []

    for i in range(len(platforms)):
        #bl = platforms[i].parallel_offset(distance=dist_to_platform,side="left")
        #br = platforms[i].parallel_offset(distance=dist_to_platform,side="right")
        #bl = platforms[i].difference(bl)
        #br = platforms[i].difference(br)
        #plt.plot(*Polygon(br).exterior.xy)
        #plt.show()
        bl = platforms[i].parallel_offset(distance=dist_to_platform,side="left")
        br = platforms[i].parallel_offset(distance=dist_to_platform,side="right")
        #boundaries_in.append(bl)
        #boundaries_out.append(br)

        bl = Polygon(bl)
        br = Polygon(br)

        outer_band = bl.difference(platforms[i])
        inner_band = platforms[i].difference(br)

        boundaries_in.append(inner_band)
        boundaries_out.append(outer_band)

    return boundaries_in, boundaries_out
Пример #31
0
def checkMaxWidth(rule, dd, layerID, threshold):
    layer = dd.layers[layerID]

    ## Set up the dicitionary of things above and belowme.
    aboveID = layerID + 1
    belowID = SU81
    aboveLayer = None
    belowLayer = None
    if aboveID in PHYSICAL_LAYERS:
        aboveLayer = dd.layers[aboveID]
    if belowID != layerID:
        belowLayer = dd.layers[belowID]

    objs = layer.objs
    for ident, obj in objs.items():
        if obj.type == Object.FEATURE and obj.diameter > threshold:
            ## Object is large enough to test
            bbox = obj.shape.bounds
            cumulative = Polygon(obj.shape)

            ## Add in everything supporing you, so you get the width of the
            ## whole structure to this point
            if belowLayer:
                candidates = belowLayer.index.intersection(bbox)
                for cind in candidates:
                    if not cind in dd.layers[DesignDict.POST].objs:
                        below = belowLayer.objs[cind]
                        if below.shape.contains(cumulative):
                            cumulative = cumulative.union(below.shape)
            ## Subtract out the layer above you, so you're considering only the
            ## portions of the structure that stop at this layer.  Layers that
            ## go deeper / higher will be considered in their own pass.
            if aboveLayer:
                candidates = aboveLayer.index.intersection(bbox)
                for cind in candidates:
                    if not cind in dd.layers[DesignDict.POST].objs:
                        above = aboveLayer.objs[cind]
                        if cumulative.contains(above.shape):
                            cumulative = cumulative.difference(above.shape)

            polygons = []
            if isinstance(cumulative, Polygon):
                polygons = [cumulative]
            else:
                for r in cumulative:
                    polygons.append(r)

            ## Polygons now represent the features on this layer which must be checked
            for shape in polygons:
                (point, dist) = maxMinDistance(
                    shape,
                    dd)  ## dist here is a radius of the inscribed circle
                ## so in this line we need to double it.
                if dist * 2 > threshold:
                    logger.debug("Violated max width:" + str(dist) + " > " +
                                 str(threshold) + "\n\tWitness centered at:" +
                                 str(point))
                    wit = Witness(Witness.POINT_RADIUS, (point, dist))
                    dd.violations.add(Violation.ofRule(rule, [obj], [wit]))
Пример #32
0
def resample_Polygon(polygon, *args, **kwargs):
    exterior = Polygon(_resample_Polygon(polygon.exterior, *args, **kwargs))
    interiors = [
        Polygon(_resample_Polygon(interior, *args, **kwargs))
        for interior in polygon.interiors
    ]
    interiors = cascaded_union(interiors)
    return exterior.difference(interiors)
Пример #33
0
def handle_coords(polygon, sys_par):

    # Set the history-clip shapefile path
    pth = sys_par[0] + 'Clips\\clips.shp'

    # Get all previous clipping history as a merged Polygon geometry
    try:
        with fiona.open(pth) as c:
            multi_old = shape(c[0]['geometry'])

            # Increase the clipping counter by one more
            fname = str(int(c[0]['properties']['id'])+1)
    except:
        # There is no previous polygon in the history.. So build an empty one to begin with.
        multi_old = Polygon()
        fname = str(1)

    # Clean the user's input of coordinates
    geom = [(float(p1[0]), float(p1[1])) for p1 in [p0.split(", ") for p0 in polygon[1:-1].split(")(")]]

    # If the user's polygon is not valid, reduce-correct it.
    poly = Polygon(geom).buffer(0)

    # Remove from it, all previously used clipping areas
    fin_polygon = poly.difference(multi_old)
    multi_new = poly.union(multi_old)

    if not fin_polygon.is_empty:

        clip_path = "Tools/LAS_Tools/clipping_polygon.shp"

        # Write a new Shapefile to be used as the new single clip polygon
        with fiona.open(sys_par[0]+clip_path, 'w', 'ESRI Shapefile',
                        {'geometry': 'Polygon', 'properties': {'id': 'int'}}) as c:
            c.write({'geometry': mapping(fin_polygon), 'properties': {'id': 0}})

        # Get the boundaries of the new (clean) clipping area
        bb = poly.bounds

        coordinate_list = {"max": [bb[2], bb[3]], "min": [bb[0], bb[1]]}

        # Continue with the point cloud preparation.
        new_diffs = prepare_pointclouds.init_pc_preparation(coordinate_list, fname, sys_par)

        # Get the centroid of the area
        cent = fin_polygon.centroid

        if new_diffs:
            return str(cent.x), str(cent.y), str(0), (multi_new, sys_par[0]+'Clips/clips.shp', fname)  #, str("Change-detection process has started.")
        else:
            return str(cent.x), str(cent.y), str(0), False

    # The requested differences have probably been already calculated
    else:
        # Get the centroid of the area
        cent = poly.centroid

        return str(cent.x), str(cent.y), str(0), False
Пример #34
0
    def from_json(cls, obj, z, x, y):
        tile = cls(z, x, y)

        if "roads" in obj:
            for road in obj["roads"].get("features", []):
                tile.ways["roads"] += Road.from_obj(road)

        water_polys = []
        if "water" in obj:
            for water in obj["water"]["features"]:
                geometry = water["geometry"]
                if geometry["type"] == "Polygon":
                    coords = []
                    for c in geometry["coordinates"][0]:
                        coords.append((c[1], c[0]))
                    water_polys.append(Polygon(coords))
                elif geometry["type"] in ("MultiPolygon",):
                    for uclist in geometry["coordinates"]:
                        for clist in uclist:
                            coords = [(c[1], c[0]) for c in clist]
                            water_polys.append(Polygon(coords))

        if "earth" in obj:
            for earth in obj["earth"]["features"]:
                geometry = earth["geometry"]
                if geometry["type"] == "Polygon":
                    poly = Polygon([(c[1], c[0]) for c in geometry["coordinates"][0]])
                    for water in water_polys:
                        poly = poly.difference(water)

                    polys = poly.geoms if poly.geom_type == "MultiPolygon" else [poly]
                    for p in polys:
                        tile.ways["earth"].append(list(p.exterior.coords))
                elif geometry["type"] == "MultiPolygon":
                    for uclist in geometry["coordinates"]:
                        for clist in uclist:
                            poly = Polygon([(c[1], c[0]) for c in clist])
                            for water in water_polys:
                                poly = poly.difference(water)

                            polys = poly.geoms if poly.geom_type in ("MultiPolygon", "GeometryCollection") else [poly]
                            for p in polys:
                                tile.ways["earth"].append(list(p.exterior.coords))

        return tile
Пример #35
0
    def difference(self, l):
        coords = self.unclose().coords
        p = Polygon(coords)
        try:
            lp = l.linestring()
        except:
            lp = l

        return p.difference(Polygon(lp))
Пример #36
0
def polygonize(conts, withholes = False):
    for i in conts:i[:,[0,1]] = i[:,[1,0]]
    polygon = Polygon(conts[0]).buffer(0)
    if not withholes:return polygon
    holes = []
    for i in conts[1:]:
        if len(i)<4:continue
        holes.append(Polygon(i).buffer(0))
    hole = cascaded_union(holes)
    return polygon.difference(hole)
Пример #37
0
    def reset_boundarygrid(self,
                           n_turbines,
                           parameters: WindBoundaryGridParameters,
                           exclusions: Polygon = None):
        """

        """
        self._get_system_config()

        wind_shape = Polygon(self.site.polygon.exterior)
        if exclusions:
            wind_shape = wind_shape.difference(
                exclusions)  # compute valid wind layout shape

        # place border turbines
        turbine_positions: [Point] = []
        if not isinstance(wind_shape, MultiPolygon):
            wind_shape = MultiPolygon([
                wind_shape,
            ])

        border_spacing = (parameters.border_spacing + 1) * self.min_spacing
        for bounding_shape in wind_shape:
            turbine_positions.extend(
                get_evenly_spaced_points_along_border(
                    bounding_shape.exterior,
                    border_spacing,
                    parameters.border_offset,
                    n_turbines - len(turbine_positions),
                ))

        valid_wind_shape = subtract_turbine_exclusion_zone(
            self.min_spacing, wind_shape, turbine_positions)

        # place interior grid turbines
        max_num_interior_turbines = n_turbines - len(turbine_positions)
        grid_aspect = np.exp(parameters.grid_aspect_power)
        intrarow_spacing, grid_sites = get_best_grid(
            valid_wind_shape,
            wind_shape.centroid,
            parameters.grid_angle,
            grid_aspect,
            parameters.row_phase_offset,
            self.min_spacing * 10000,
            self.min_spacing,
            max_num_interior_turbines,
        )
        turbine_positions.extend(grid_sites)
        xcoords, ycoords = [], []
        for p in turbine_positions:
            xcoords.append(p.x)
            ycoords.append(p.y)

        self.turb_pos_x, self.turb_pos_y = xcoords, ycoords
        self._set_system_layout()
Пример #38
0
def get_tile_geometry(path, origin_espg, tolerance=500):
    """ Calculate the data and tile geometry for sentinel-2 tiles """

    with rasterio.open(path) as src:

        # Get tile geometry
        b = src.bounds
        tile_shape = Polygon([(b[0], b[1]), (b[2], b[1]), (b[2], b[3]),
                              (b[0], b[3]), (b[0], b[1])])
        tile_geojson = mapping(tile_shape)

        # read first band of the image
        image = src.read(1)

        # create a mask of zero values
        mask = image == 0.

        # generate shapes of the mask
        novalue_shape = shapes(image, mask=mask, transform=src.affine)

        # generate polygons using shapely
        novalue_shape = [
            Polygon(s['coordinates'][0]) for (s, v) in novalue_shape
        ]

        if novalue_shape:

            # Make sure polygons are united
            # also simplify the resulting polygon
            union = cascaded_union(novalue_shape)

            # generates a geojson
            data_shape = tile_shape.difference(union)

            # If there are multipolygons, select the largest one
            if data_shape.geom_type == 'MultiPolygon':
                areas = {p.area: i for i, p in enumerate(data_shape)}
                largest = max(areas.keys())
                data_shape = data_shape[areas[largest]]

            # if the polygon has interior rings, remove them
            if list(data_shape.interiors):
                data_shape = Polygon(data_shape.exterior.coords)

            data_shape = data_shape.simplify(tolerance,
                                             preserve_topology=False)
            data_geojson = mapping(data_shape)

        else:
            data_geojson = tile_geojson

        # convert cooridnates to degrees
        return (to_latlon(tile_geojson,
                          origin_espg), to_latlon(data_geojson, origin_espg))
Пример #39
0
def cutting_box_mk2(sLine1, sLine2, inCircle):
    minX, minY, maxX, maxY = inCircle.bounds
    boundingBox = Polygon([(minX, minY), (minX, maxY), (maxX, maxY), (maxX, minY)])
    cutting_box = []
    if sLine1.interLine == "maxXLine":
        if sLine2.interLine == "maxXLine":
            cutting_box = Polygon([sLine1.fromNode, sLine1.interPts, sLine2.interPts, sLine2.fromNode])
        elif sLine2.interLine == "minYLine":
            cutting_box = Polygon([sLine1.fromNode, sLine1.interPts, (maxX, minY), sLine2.interPts, sLine2.fromNode])
        elif sLine2.interLine == "minXLine":
            cutting_box = Polygon(
                [sLine1.fromNode, sLine1.interPts, (maxX, minY), (minX, minY), sLine2.interPts, sLine2.fromNode]
            )
        elif sLine2.interLine == "maxYLine":
            cutting_box = Polygon([sLine1.fromNode, sLine1.interPts, (maxX, maxY), sLine2.interPts, sLine2.fromNode])
    elif sLine1.interLine == "minYLine":
        if sLine2.interLine == "minYLine":
            cutting_box = Polygon([sLine1.fromNode, sLine1.interPts, sLine2.interPts, sLine2.fromNode])
        elif sLine2.interLine == "minXLine":
            cutting_box = Polygon([sLine1.fromNode, sLine1.interPts, (minX, minY), sLine2.interPts, sLine2.fromNode])
        elif sLine2.interLine == "maxYLine":
            cutting_box = Polygon(
                [sLine1.fromNode, sLine1.interPts, (minX, minY), (minX, maxY), sLine2.interPts, sLine2.fromNode]
            )
        elif sLine2.interLine == "maxXLine":
            cutting_box = Polygon([sLine1.fromNode, sLine1.interPts, (maxX, minY), sLine2.interPts, sLine2.fromNode])
    elif sLine1.interLine == "minXLine":
        if sLine2.interLine == "minXLine":
            cutting_box = Polygon([sLine1.fromNode, sLine1.interPts, sLine2.interPts, sLine2.fromNode])
        elif sLine2.interLine == "maxYLine":
            cutting_box = Polygon([sLine1.fromNode, sLine1.interPts, (minX, maxY), sLine2.interPts, sLine2.fromNode])
        elif sLine2.interLine == "maxXLine":
            cutting_box = Polygon(
                [sLine1.fromNode, sLine1.interPts, (minX, maxY), (maxX, maxY), sLine2.interPts, sLine2.fromNode]
            )
        elif sLine2.interLine == "minYLine":
            cutting_box = Polygon([sLine1.fromNode, sLine1.interPts, (minX, minY), sLine2.interPts, sLine2.fromNode])
    elif sLine1.interLine == "maxYLine":
        if sLine2.interLine == "maxYLine":
            cutting_box = Polygon([sLine1.fromNode, sLine1.interPts, sLine2.interPts, sLine2.fromNode])
        elif sLine2.interLine == "maxXLine":
            cutting_box = Polygon([sLine1.fromNode, sLine1.interPts, (maxX, maxY), sLine2.interPts, sLine2.fromNode])
        elif sLine2.interLine == "minYLine":
            cutting_box = Polygon(
                [sLine1.fromNode, sLine1.interPts, (maxX, maxY), (maxX, minY), sLine2.interPts, sLine2.fromNode]
            )
        elif sLine2.interLine == "minXLine":
            cutting_box = Polygon([sLine1.fromNode, sLine1.interPts, (minX, maxY), sLine2.interPts, sLine2.fromNode])

    cutting_box_2 = boundingBox.difference(cutting_box)
    return cutting_box, cutting_box_2
Пример #40
0
def init_cuuting_box(sLine1, sLine2, inCircle):
    minX, minY, maxX, maxY = inCircle.bounds
    boundingBox = Polygon([(minX, minY), (minX, maxY), (maxX, maxY), (maxX, minY)])
    cutting_box = []
    if sLine1.interLine == "maxXLine":
        if sLine2.interLine == "maxXLine":
            cutting_box = Polygon([sLine1.toNode, sLine1.interPts, sLine2.interPts, sLine2.toNode])
        elif sLine2.interLine == "minYLine":
            cutting_box = Polygon([sLine1.toNode, sLine1.interPts, (maxX, minY), sLine2.interPts, sLine2.toNode])
        elif sLine2.interLine == "minXLine":
            cutting_box = Polygon(
                [sLine1.toNode, sLine1.interPts, (maxX, minY), (minX, minY), sLine2.interPts, sLine2.toNode]
            )
        elif sLine2.interLine == "maxYLine":
            cutting_box = Polygon([sLine1.toNode, sLine1.interPts, (maxX, maxY), sLine2.interPts, sLine2.toNode])
    elif sLine1.interLine == "minYLine":
        if sLine2.interLine == "minYLine":
            cutting_box = Polygon([sLine1.toNode, sLine1.interPts, sLine2.interPts, sLine2.toNode])
        elif sLine2.interLine == "minXLine":
            cutting_box = Polygon([sLine1.toNode, sLine1.interPts, (minX, minY), sLine2.interPts, sLine2.toNode])
        elif sLine2.interLine == "maxYLine":
            cutting_box = Polygon(
                [sLine1.toNode, sLine1.interPts, (minX, minY), (minX, maxY), sLine2.interPts, sLine2.toNode]
            )
        elif sLine2.interLine == "maxXLine":
            cutting_box = Polygon([sLine1.toNode, sLine1.interPts, (maxX, minY), sLine2.interPts, sLine2.toNode])
    elif sLine1.interLine == "minXLine":
        if sLine2.interLine == "minXLine":
            cutting_box = Polygon([sLine1.toNode, sLine1.interPts, sLine2.interPts, sLine2.toNode])
        elif sLine2.interLine == "maxYLine":
            cutting_box = Polygon([sLine1.toNode, sLine1.interPts, (minX, maxY), sLine2.interPts, sLine2.toNode])
        elif sLine2.interLine == "maxXLine":
            cutting_box = Polygon(
                [sLine1.toNode, sLine1.interPts, (minX, maxY), (maxX, maxY), sLine2.interPts, sLine2.toNode]
            )
        elif sLine2.interLine == "minYLine":
            cutting_box = Polygon([sLine1.toNode, sLine1.interPts, (minX, minY), sLine2.interPts, sLine2.toNode])
    elif sLine1.interLine == "maxYLine":
        if sLine2.interLine == "maxYLine":
            cutting_box = Polygon([sLine1.toNode, sLine1.interPts, sLine2.interPts, sLine2.toNode])
        elif sLine2.interLine == "maxXLine":
            cutting_box = Polygon([sLine1.toNode, sLine1.interPts, (maxX, maxY), sLine2.interPts, sLine2.toNode])
        elif sLine2.interLine == "minYLine":
            cutting_box = Polygon(
                [sLine1.toNode, sLine1.interPts, (maxX, maxY), (maxX, minY), sLine2.interPts, sLine2.toNode]
            )
        elif sLine2.interLine == "minXLine":
            cutting_box = Polygon([sLine1.toNode, sLine1.interPts, (minX, maxY), sLine2.interPts, sLine2.toNode])
    writeShp([cutting_box], "cutting_box.shp")
    cutting_box_2 = boundingBox.difference(cutting_box)
    return cutting_box, cutting_box_2
def all_CCD_check(com, ra, dec):
    sima = Polygon([(com[0], com[1]), (com[2], com[3]), (com[4], com[5]), (com[6], com[7])])
    # simp = PolygonPatch(sima, facecolor='k',zorder=0)
    # plt.gca().add_patch(simp)
    alpha = np.arctan(np.divide((np.subtract(com[6], com[0])), np.subtract(com[7], com[1])))
    # print alpha

    xt = com[0]
    yt = com[1]

    jonest = np.matrix([[np.cos(alpha), -np.sin(alpha), xt], [np.sin(alpha), np.cos(alpha), yt], [0, 0, 1.0]])
    # print jonest

    good_area = []

    xl_scale = abs(com[0] - com[2]) / ((2048 * 1.01) / 3600)
    xr_scale = abs(com[4] - com[6]) / ((2048 * 1.01) / 3600)

    yu_scale = abs(com[3] - com[5]) / ((4096 * 1.01) / 3600)

    yl_scale = abs(com[1] - com[7]) / ((4096 * 1.01) / 3600)

    for i in [
        (75.0 * xl_scale, 75.0),
        (2048.0 * xl_scale, 75.0),
        (2048.0 * xr_scale, 4000.0),
        (75.0 * xr_scale, 4000.0),
    ]:
        x = i[0] * (1.01 / 3600)
        y = i[1] * (1.01 / 3600)
        pixel_coords = np.matrix([[x], [y], [1.0]])
        # print 'Pixel:', pixel_coords
        cords = np.dot(jonest, pixel_coords)
        # print 'New Coordinates:', cords
        # print cords.item(0)
        good_area.append((cords.item(0), yt - (cords.item(1) - yt)))

    garea = [
        good_area[0],
        (good_area[1][0], com[3] - ((75.0 * 1.01 / 3600) * yu_scale)),
        (good_area[2][0], com[5] + ((96.0 * 1.01 / 3600) * yu_scale)),
        good_area[3],
    ]
    # print good_area
    # print [(com[0],com[1]),(com[2],com[3]),(com[4],com[5]),(com[6],com[7])]
    simg1 = Polygon(garea)
    if com[8] == 0:
        simb0 = ccd0_defect(com, alpha)
        simg1 = simg1.difference(simb0)
    return simg1.contains(Point(ra, dec))
Пример #42
0
def get_tile_geometry(path, origin_espg, tolerance=500):
    """ Calculate the data and tile geometry for sentinel-2 tiles """

    with rasterio.open(path) as src:

        # Get tile geometry
        b = src.bounds
        tile_shape = Polygon([(b[0], b[1]), (b[2], b[1]), (b[2], b[3]), (b[0], b[3]), (b[0], b[1])])
        tile_geojson = mapping(tile_shape)

        # read first band of the image
        image = src.read(1)

        # create a mask of zero values
        mask = image == 0.

        # generate shapes of the mask
        novalue_shape = shapes(image, mask=mask, transform=src.affine)

        # generate polygons using shapely
        novalue_shape = [Polygon(s['coordinates'][0]) for (s, v) in novalue_shape]

        if novalue_shape:

            # Make sure polygons are united
            # also simplify the resulting polygon
            union = cascaded_union(novalue_shape)

            # generates a geojson
            data_shape = tile_shape.difference(union)

            # If there are multipolygons, select the largest one
            if data_shape.geom_type == 'MultiPolygon':
                areas = {p.area: i for i, p in enumerate(data_shape)}
                largest = max(areas.keys())
                data_shape = data_shape[areas[largest]]

            # if the polygon has interior rings, remove them
            if list(data_shape.interiors):
                data_shape = Polygon(data_shape.exterior.coords)

            data_shape = data_shape.simplify(tolerance, preserve_topology=False)
            data_geojson = mapping(data_shape)

        else:
            data_geojson = tile_geojson

        # convert cooridnates to degrees
        return (to_latlon(tile_geojson, origin_espg), to_latlon(data_geojson, origin_espg))
Пример #43
0
 def calc_resp(self, projector_shadows):
 
     shadow_union = [ShpPolygon()]*self.num_proj
     for shadow in projector_shadows:
         proj_idx = self.proj_id_2idx[shadow.projector_id]
         
         poly = []
         for point in shadow.polygon.points:
             poly.append([point.y, point.x])
             
         shadow_union[proj_idx] = shadow_union[proj_idx].union(ShpPolygon(poly))
         
         
     new_resp = [None]*self.num_proj
     prev_coverage = ShpPolygon()
     
     for i in range(self.num_proj):
         curr_poly = ShpPolygon(self.proj_coord[i])
         curr_poly = curr_poly.difference(shadow_union[i])
         new_coverage = curr_poly.difference(prev_coverage)
         new_resp[i] = new_coverage
         prev_coverage.union(curr_poly)
         
     self.resp = new_resp
Пример #44
0
def plot_interpolant(D,interp,x,title='',dim=1,ax=None,scatter=False):
  if ax is None:  
    fig,ax = plt.subplots()
    plt.gca().set_aspect('equal', adjustable='box')
    ax.set_title(title)

  
  buff = 400.0
  N = 150
  minx = np.min(x[:,0])
  maxx = np.max(x[:,0])
  miny = np.min(x[:,1])
  maxy = np.max(x[:,1])
  square = Polygon([(minx-buff,miny-buff),
                    (minx-buff,maxy+buff),
                    (maxx+buff,maxy+buff),
                    (maxx+buff,miny-buff),
                    (minx-buff,miny-buff)])
  ax.add_artist(PolygonPatch(square.difference(D),alpha=1.0,color='k',zorder=1))
  ax.set_xlim((minx-buff,maxx+buff))
  ax.set_ylim((miny-buff,maxy+buff))

  if dim == 1:
    xitp = np.linspace(minx,maxx,N)
    yitp = np.linspace(miny,maxy,N)
    xgrid,ygrid = np.meshgrid(xitp,yitp)
    xflat = xgrid.flatten()
    yflat = ygrid.flatten()
    points = np.zeros((len(xflat),2))
    points[:,0] = xflat
    points[:,1] = yflat
    val = interp(points)
    #val[(np.sqrt(xflat**2+yflat**2) > 6371),:] = 0.0

    im =NonUniformImage(ax,interpolation='bilinear',cmap='cubehelix_r',extent=(minx,maxx,miny,maxy))
    im.set_data(xitp,yitp,np.reshape(val,(N,N)))

    ax.images.append(im)
    if scatter == True:
      p = ax.scatter(x[:,0],
                     x[:,1],
                     c='gray',edgecolor='none',zorder=2,s=10)
    cbar = plt.colorbar(im)

  if dim == 2:
    ax.quiver(x[::3,0],x[::3,1],interp(x)[::3,0],interp(x)[::3,1],color='gray',scale=4000.0,zorder=20)

  return ax
Пример #45
0
def plot_interpolant(D,interp,x,title='figure'):
  buff = 100.0
  fig,ax = plt.subplots()
  plt.gca().set_aspect('equal', adjustable='box')

  plt.title(title,fontsize=16)

  N = 200
  minx = np.min(x[:,0])
  maxx = np.max(x[:,0])
  miny = np.min(x[:,1])
  maxy = np.max(x[:,1])
  xitp = np.linspace(minx,maxx,N)
  yitp = np.linspace(miny,maxy,N)
  xgrid,ygrid = np.meshgrid(xitp,yitp)
  xflat = xgrid.flatten()
  yflat = ygrid.flatten()
  points = np.zeros((len(xflat),2))
  points[:,0] = xflat
  points[:,1] = yflat
  val = interp(points)
  val[(np.sqrt(xflat**2+yflat**2) > 6371),:] = 0.0

  square = Polygon([(minx-buff,miny-buff),
                    (minx-buff,maxy+buff),
                    (maxx+buff,maxy+buff),
                    (maxx+buff,miny-buff),
                    (minx-buff,miny-buff)])

  #help(D)
  im =NonUniformImage(ax,interpolation='bilinear',cmap='cubehelix',extent=(minx,maxx,miny,maxy))
  im.set_data(xitp,yitp,np.reshape(val,(N,N)))
  
  ax.images.append(im)
  ax.add_artist(PolygonPatch(square.difference(D),alpha=1.0,color='k',zorder=1))
  p = ax.scatter(x[:,0],
                 x[:,1],
                 c='gray',edgecolor='none',zorder=2,s=10)
  cbar = plt.colorbar(im)
  cbar.ax.set_ylabel(title)
  ax.set_xlim((minx-buff,maxx+buff))
  ax.set_ylim((miny-buff,maxy+buff))
  #fig.colorbar(p)
  return fig
Пример #46
0
    def test_polygon_pbf(self):
        '''
        Create a polygon to cover the world and make sure it is "similar" (clip on) (pbf)
        '''
        self.defineGeometry('POLYGON')

        geom = Polygon([(-180, -85.05),
                        (180, -85.05),
                        (180, 85.05),
                        (-180, 85.05),
                        (-180, -85.05)])

        self.insertTestRow(geom.wkt)

        tile_mimetype, tile_content = utils.request(self.config_file_content, "vectile_test", "pbf", 0, 0, 0)
        self.assertTrue(tile_mimetype.endswith('/x-protobuf'))
        pbf_result = mapbox_vector_tile.decode(tile_content)
        layer_result = pbf_result['vectile_test']

        extent = tile_bounds_mercator(0, 0, 0)

        result_geom = decoded_pbf_asshape(layer_result['features'][0], extent)
        expected_geom = Polygon([(-180, -85.05), (180, -85.05), (180, 85.05), (-180, 85.05), (-180, -85.05)])

        # What is going on here is a bit unorthodox, but let me explain. The clipping
        # code inside TileStache relies on GEOS Intersection alongside some TileStache code
        # that creates a clipping geometry based on the tile perimeter. The tile perimeter
        # is made out of 17 (x,y) coordinates and not a box. Hence, the GEOS::Intersection
        # os that perimeter with the geometry of the vector we get back from the data provider
        # can end with extra vertices. Although it is the right shape, we cannot do a straight
        # comparisson because the expected geometry and the returned geometry *may* have extra
        # vertices. Simplify() will not do much because the distance of the vertices can clearly
        # be bigger than the tolerance. 
        #
        # To add to this, because of double precision, the vertices may not be exact.
        # An optional way to find out if two shapes are close enough, is to buffer the two features
        # by just a little bit and then subtract each other like so:
        #
        #             geometry1.difference(geometry2) == empty set?
        #             geometry2.difference(geometry1) == empty set?
        # 
        # If both geometries are empty, then they are similar. Hence what you see below
        self.assertTrue(result_geom.difference(expected_geom.buffer(0.01)).is_empty)
        self.assertTrue(expected_geom.difference(result_geom.buffer(0.01)).is_empty)
Пример #47
0
    def get_fracture_intersection_diff(self, fracture, face):

        R = fracture.build_rotation_matrix()

        fracture_poly_list = []
        face_poly_list = []
        for point in fracture.points:
            rot_point = np.linalg.solve(R, point - fracture.center)
            fracture_poly_list.append(rot_point[:2])

        for point_index in face:
            point = self.get_point(point_index)
            rot_point = np.linalg.solve(R, point - fracture.center)
            face_poly_list.append(rot_point[:2])

        face_poly = Polygon(face_poly_list)
        fracture_poly = Polygon(fracture_poly_list)

        if not face_poly.intersects(fracture_poly) or fracture_poly.contains(face_poly):
            return (False, None, None)

        else:
            poly1 = fracture_poly.intersection(face_poly)
            poly1_ret = []
            for point in list(poly1.exterior.coords)[:-1]:
                rot_point = R.dot(np.array(list(point) + [0.0])) + fracture.center
                poly1_ret.append(rot_point)

            poly2 = face_poly.difference(fracture_poly)
            poly2_ret = []
            if type(poly2) == type(MultiPolygon()):
                for poly in poly2:
                    poly2_ret.append([])
                    for point in list(poly.exterior.coords)[:-1]:
                        rot_point = R.dot(np.array(list(point) + [0.0])) + fracture.center
                        poly2_ret[-1].append(rot_point)

            else:
                poly2_ret.append([])
                for point in list(poly2.exterior.coords)[:-1]:
                    rot_point = R.dot(np.array(list(point) + [0.0])) + fracture.center
                    poly2_ret[-1].append(rot_point)

            return (True, [poly1_ret], poly2_ret)
Пример #48
0
    def get_fracture_intersection_diff_w_segs(self, fracture, segs, face):

        (divided_polygons, full_frac_poly) = fracture.divide_polygon_for_intersection(segs)

        R = fracture.build_rotation_matrix()

        face_poly_list = []
        for point_index in face:
            point = self.get_point(point_index)
            rot_point = np.linalg.solve(R, point - fracture.center)
            face_poly_list.append(rot_point[:2])

        face_poly = Polygon(face_poly_list)

        if not face_poly.intersects(divided_polygons) or full_frac_poly.contains(face_poly):
            return (False, None, None)

        else:
            new_faces = []
            for poly in divided_polygons:
                poly1 = poly.intersection(face_poly)
                poly1_ret = []
                if not poly1.is_empty:
                    for point in list(poly1.exterior.coords)[:-1]:
                        rot_point = R.dot(np.array(list(point) + [0.0])) + fracture.center
                        poly1_ret.append(rot_point)
                    new_faces.append(poly1_ret)

            poly2 = face_poly.difference(full_frac_poly)
            poly2_ret = []
            if type(poly2) == type(MultiPolygon()):
                for poly in poly2:
                    poly2_ret.append([])
                    for point in list(poly.exterior.coords)[:-1]:
                        rot_point = R.dot(np.array(list(point) + [0.0])) + fracture.center
                        poly2_ret[-1].append(rot_point)

            else:
                poly2_ret.append([])
                for point in list(poly2.exterior.coords)[:-1]:
                    rot_point = R.dot(np.array(list(point) + [0.0])) + fracture.center
                    poly2_ret[-1].append(rot_point)

            return (True, new_faces, poly2_ret)
Пример #49
0
	yl_scale=abs(m[1]-m[7])/((4096*1.01)/3600)

	for i in [(75.*xl_scale,75.), (2048.*xl_scale,75.),(2048.*xr_scale,4000.),(75.*xr_scale,4000.)]:
		x=i[0]*(1.01/3600)
		y=i[1]*(1.01/3600)
		pixel_coords=np.matrix([[x],[y],[1.]])
		#print 'Pixel:', pixel_coords
		cords=np.dot(jonest,pixel_coords)
		#print 'New Coordinates:', cords
		#print cords.item(0)
		good_area.append((cords.item(0),yt-(cords.item(1)-yt)))
	
	garea=[good_area[0], (good_area[1][0],m[3]-((75.*1.01/3600)*yu_scale)), (good_area[2][0],m[5]+((96.*1.01/3600)*yu_scale)),good_area[3]]
	#print good_area
	#print [(m[0],m[1]),(m[2],m[3]),(m[4],m[5]),(m[6],m[7])]
	simg1=Polygon(garea)
	if m[8]==0:
		simb0=ccd0_defect(m, alpha)
		simg1=simg1.difference(simb0)
	simg2 = PolygonPatch(simg1, facecolor='blue',zorder=5)
	plt.gca().add_patch(simg2)
plt.xlim(120,360)
plt.ylim(-20,85)
plt.xlabel('Ra')
plt.ylabel('Dec')
plt.show()
'''
fig = matplotlib.pyplot.gcf()
fig.set_size_inches(30,15)
plt.savefig('CCD_Areas.png', bbox_inches='tight', dpi=300)
'''
Пример #50
0
def main(args):
  # setup logger
  name = args.name
  os.makedirs('output/%s' % name)

  # Define Topology
  # ---------------
  # Keep track of the total number of nodes
  node_count = 0
  total_nodes = np.zeros((0,2))

  # initiate a Halton sequence 
  H = Halton(dim=3)

  # define boundary nodes
  p = np.linspace(0,1,args.boundary_nodes+1)[:-1]
  surface_nodes = boundary(p)
  surface_idx = range(node_count,len(surface_nodes)+node_count)
  total_nodes = np.vstack((total_nodes,surface_nodes))
  node_count += len(surface_nodes)  

  # find the normal vectors for each surface node, this is used for 
  # applying the boundary conditions
  dp = 1e-6
  surface_nodes_plus_dp = boundary(p+dp)
  surface_tangents = surface_nodes_plus_dp - surface_nodes
  surface_normals = np.zeros((args.boundary_nodes,2))
  surface_normals[:,0] = surface_tangents[:,1]
  surface_normals[:,1] = -surface_tangents[:,0]
  normal_lengths = np.sqrt(np.sum(surface_normals**2,1))
  surface_normals = surface_normals/normal_lengths[:,None]
  # Define polygon based on boundary nodes
  D = Polygon(surface_nodes)

  # Add a buffer so that the polygon is slightly smaller than what is 
  # defined by the boundary nodes. This is needed for a stable 
  # solution.  The buffer is the minimum of the distances between 
  # adjacent surface nodes
  nearest_surface_node = nearest(surface_nodes)[0]
  for p,n in zip(surface_nodes,nearest_surface_node):
    pbuff = Point(p).buffer(n)
    D = D.difference(pbuff)

  assert D.is_valid

  # Find interior nodes that are within the domain and adhere to the
  # user specified node density
  interior_nodes = pick_nodes(H,D,node_density,args.nodes-node_count)
  interior_idx = range(node_count,len(interior_nodes)+node_count)
  total_nodes = np.vstack((total_nodes,interior_nodes))
  node_count += len(interior_nodes)

  # Material Properties
  # -------------------
  # load P-wave and S-wave velocities from PREM table
  prem_table = np.loadtxt(args.material_file,skiprows=1)
  depth = prem_table[:,0]*1000 # m
  P_vel = prem_table[:,1] # m/s
  S_vel = prem_table[:,2] # m/s
  rho = prem_table[:,3] # kg/m**3

  # lame parameters
  mu = (S_vel**2*rho) # kg/m*s**2
  lam = (P_vel**2*rho - 2*mu) # kg/m*s**2

  # create interpolants. The interpolants are 1D with respect to 
  # depth
  eps = args.epsilon/nearest(depth)[0]
  lam_itp = RBFInterpolant(depth,eps,value=lam)  
  mu_itp = RBFInterpolant(depth,eps,value=mu)  
  rho_itp = RBFInterpolant(depth,eps,value=rho)  
  
  # Convert the 1D interpolants to 2D cartesian interpolants
  r = np.sqrt(np.sum(total_nodes**2,1))
  eps = args.epsilon/nearest(total_nodes)[0]
  lam_itp = RBFInterpolant(total_nodes,eps,value=lam_itp(r))
  mu_itp = RBFInterpolant(total_nodes,eps,value=mu_itp(r))
  rho_itp = RBFInterpolant(total_nodes,eps,value=rho_itp(r))

  # Build Problem Matrices
  # ----------------------
  # calculate shape parameter
  eps = args.epsilon/nearest(total_nodes)[0]

  # Form interpolation, acceleration, and boundary condition matrix
  G = interpolation_matrix(total_nodes,total_nodes,eps)
  A = acceleration_matrix(total_nodes,total_nodes,eps,
                          lam_itp,mu_itp,rho_itp)
  B = traction_matrix(surface_nodes,surface_normals,total_nodes,eps,
                      lam_itp,mu_itp)/1e8
  G[surface_idx,:,:,:] = B

  # Print Run Information
  # ---------------------
  min_dist = np.min(nearest(total_nodes)[0])
  max_speed = np.max(np.concatenate((P_vel,S_vel)))

  # Time Stepping
  # -------------  
  time_steps = np.arange(0.0,args.max_time,args.time_step)
  total_steps = len(time_steps)

  initial_save(name,
               total_nodes,
               surface_idx,
               interior_idx,
               eps,
               mu_itp(total_nodes),
               lam_itp(total_nodes),
               rho_itp(total_nodes),
               time_steps)

  last_save = 0
  alpha_list = []
  for itr,t in enumerate(time_steps):
    if itr == 0:
      # compute initial velocity and displacement
      u,v = initial_conditions(total_nodes) 
      # compute acceleration due to source term 
      f = source(total_nodes,
                 np.asarray(args.epicenter),
                 t,
                 np.asarray(args.moment_tensor),
                 args.couple_distance)
      f = f/rho_itp(total_nodes)
      # compute acceleration and the spectral coefficients
      a,alpha = F(u,G,A,f,surface_idx,0.0)
      alpha_list += [alpha]
      u = np.einsum('ijkl,kl',G,alpha)

    else:
      # compute acceleration due to source term 
      f = source(total_nodes,
                 np.asarray(args.epicenter),
                 t,
                 np.asarray(args.moment_tensor),
                 args.couple_distance)
      f = f/rho_itp(total_nodes)
      # compute next step from leapfrom iteration
      u,v,a,alpha = leapfrog(F,u,v,a,args.time_step,
                             F_args=(G,A,f,surface_idx,0.0))
      alpha_list += [alpha]

    if ((itr+1)%args.save_interval==0) | ((itr+1) == len(time_steps)): 
      update_save(name,range(last_save,itr+1),alpha_list)
      last_save = itr+1
      alpha_list = []
Пример #51
0
shapely_line_strings = [LineString(x) for x in snap_lines]

# add bounding lines needed by polygonize (it's easy to do per pixel. TODO refactor to create only necessary lines)
#for i in xrange(sz):
#  pair_lines.append(((0,i),(0,i+1)))
#  pair_lines.append(((sz,i),(sz,i+1)))
#  pair_lines.append(((i,0),(i+1,0)))
#  pair_lines.append(((i,sz),(i+1,sz)))

#ps = list(polygonize(shapely_line_strings))

# simple polygonize doesn't work. it is a trick (see http://gis.stackexchange.com/questions/58245/generate-polygons-from-a-set-of-intersecting-lines)
M = MultiLineString(shapely_line_strings)
MB = M.buffer(0.001)
P = Polygon([(0, 0), (0, sz), (sz, sz), (sz, 0)])
pso = P.difference(MB)

# round vertices coords
ps = []
for p in pso:
  pb = p.buffer(0.001)
  pbt = transform(lambda x, y, z=None: (int(round(x)), int(round(y))), pb)
  ps.append(pbt)

# associate LineString_s with Polygon_s
pt_polygon_index = dict();

for p in ps:
  for pt in p.exterior.coords:
    if (pt_polygon_index.get(pt) == None): pt_polygon_index[pt] = set()
    pt_polygon_index[pt].add(p)
Пример #52
0
def main():

    # Convert to SQL as soon as possible!
    datafile = 'routesSFlandsEnd.dat'
    shapefile = 'regionSFlandsEnd.dat'

#     # Bounding box in geographic coordinates
#     lng0 = -122.517
#     lng1 = -122.355
#     lat0 = 37.707
#     lat1 = 37.834

    # Land's End
    lng0 = -122.521
    lng1 = -122.484
    lat0 = 37.778
    lat1 = 37.793

    # Initialize Basemap object
    # Get shapefile data
    shape_file = 'sf_data/planning_neighborhoods_geo.shp'

    # Plot locations on a map of SF neighborhoods
    shp = fiona.open(shape_file)
    crs_data = shp.crs
    bds = shp.bounds
    shp.close()
    ll = (bds[0], bds[1])
    ur = (bds[2], bds[3])
    coords = list(chain(ll, ur))
    w, h = coords[2] - coords[0], coords[3] - coords[1]

    # Create a Basemap instance, and open the shapefile
    m = Basemap(
        projection='tmerc',
        lon_0 = -122.0,
        lat_0 = 37.0,
        ellps = 'WGS84',
        llcrnrlon = coords[0],
        llcrnrlat = coords[1],
        urcrnrlon = coords[2],
        urcrnrlat = coords[3],
        lat_ts=0,
        resolution='i',
        suppress_ticks=True)

    # Use get_mmf_token.py to get a new authorization if necessary
    url = 'https://api.ua.com/v7.0/route/'
    headers = {'Api-Key': 'nsnxf9ptznw33fzh59wrdezt2rm3fnkt',
               'Authorization': 'Bearer 0b8a90cbd6f83a724f3467c9f6e49cda644d94e2',
               'Content-Type': 'application/json'}

    # Initialize Polygon to keep track of space that has definitively
    # been accounted for.  The intersection of this and the bounding
    # box can be compared with the box itself to know when I am done.
    #
    # Can use a Basemap object to convert to map-projection
    # coordinates
    bbox = Polygon([m(lng0, lat0), m(lng1, lat0), m(lng1, lat1), m(lng0, lat1)])
    region_covered = Polygon()
    # fid = open(shapefile, 'r')
    # region_covered = shapely.wkt.loads(fid.read())
    # fid.close()

    # Loop until the whole bbox has been covered
    done = False
    # while done == False:
    for n in range(500):

        # Use shapely.object.representative_point() to get a point
        # from the remaining area in the bbox
        lng, lat = m(bbox.difference(region_covered).representative_point().x,
                     bbox.difference(region_covered).representative_point().y, inverse=True)

        # Call the mapmyrun API for a lat,long and get some route start points
        payload = {'close_to_location': ('%.6f,%.6f' % (lat, lng)),
                   'limit': '40'}
        r = requests.get(url, params=payload, headers=headers)

        route_coords =  np.array([ route['starting_location']['coordinates']
                                   for route in r.json()['_embedded']['routes'] ]).astype('float')
        route_IDs =  np.array([ route['_links']['self'][0]['id']
                                for route in r.json()['_embedded']['routes'] ]).astype('int')

        # Append coordinates list to file
        fid = open(datafile, 'a')
        for c in range(route_coords.shape[0]):
            fid.write(('%d %f %f\n' % (route_IDs[c], route_coords[c,0],
                                        route_coords[c,1])))
        fid.close()

        # Adjust the region_covered representation by adding a circle
        # around the query point
        search_point = Point(m(lng, lat))
        route_points = [ Point(m(r_lng, r_lat)) for r_lng, r_lat in
                         route_coords ]
        route_search_radii = np.array([ search_point.distance(r_point) for
                                        r_point in route_points ])
        new_region_covered = search_point.buffer(route_search_radii.max())
        region_covered = shapely.ops.unary_union([region_covered, new_region_covered])

        # Save shapely representation region_covered
        fid = open(shapefile, 'w')
        fid.write(region_covered.wkt)

        # # Wait for a random time between 1 and 5 seconds
        # time.sleep(1)

        # Print percent remaining
        print('%3d %f' % (n, bbox.difference(region_covered).area / bbox.area))

        # done = True

    # plot_sf(route_coords, m, bbox.difference(region_covered))

    return
Пример #53
0
def cutting_box_old(sLine1, sLine2, inCircle, circleCenter):
    minX, minY, maxX, maxY = inCircle.bounds
    maxXLine = LineString([[maxX, maxY], [maxX, minY]])
    maxYLine = LineString([[minX, maxY], [maxX, maxY]])
    minXLine = LineString([[minX, maxY], [minX, minY]])
    minYLine = LineString([[minX, minY], [maxX, minY]])
    boundingBox = Polygon([(minX, minY), (minX, maxY), (maxX, maxY), (maxX, minY)])
    if sLine1.octa == "I":
        sLin1_interPoint = sLine1.intersectPoint(maxXLine)
    elif sLine1.octa == "II":
        sLin1_interPoint = sLine1.intersectPoint(maxYLine)
    elif sLine1.octa == "III":
        sLin1_interPoint = sLine1.intersectPoint(maxYLine)
    elif sLine1.octa == "IV":
        sLin1_interPoint = sLine1.intersectPoint(minXLine)
    elif sLine1.octa == "V":
        sLin1_interPoint = sLine1.intersectPoint(minXLine)
    elif sLine1.octa == "VI":
        sLin1_interPoint = sLine1.intersectPoint(minYLine)
    elif sLine1.octa == "VII":
        sLin1_interPoint = sLine1.intersectPoint(minYLine)
    elif sLine1.octa == "VIII":
        sLin1_interPoint = sLine1.intersectPoint(maxXLine)

    if sLine2.octa == "I":
        sLine2_interPoint = sLine2.intersectPoint(maxXLine)
    elif sLine2.octa == "II":
        sLine2_interPoint = sLine2.intersectPoint(maxYLine)
    elif sLine2.octa == "III":
        sLine2_interPoint = sLine2.intersectPoint(maxYLine)
    elif sLine2.octa == "IV":
        sLine2_interPoint = sLine2.intersectPoint(minXLine)
    elif sLine2.octa == "V":
        sLine2_interPoint = sLine2.intersectPoint(minXLine)
    elif sLine2.octa == "VI":
        sLine2_interPoint = sLine2.intersectPoint(minYLine)
    elif sLine2.octa == "VII":
        sLine2_interPoint = sLine2.intersectPoint(minYLine)
    elif sLine2.octa == "VIII":
        sLine2_interPoint = sLine2.intersectPoint(maxXLine)

    # cutting box
    # coordinates should be in order
    # determine whether two split lines interset same MBR boundary segment
    cutting_box_1 = []
    cutting_box_2 = []
    try:
        if sLine1.MBR == "N":
            if sLine2.MBR == "E":
                cutting_box_1 = Polygon([circleCenter, sLin1_interPoint, (maxX, maxY), sLine2_interPoint])
                cutting_box_2 = boundingBox.difference(cutting_box_1)
            elif sLine2.MBR == "S":
                cutting_box_1 = Polygon([circleCenter, sLin1_interPoint, (maxX, maxY), (maxX, minY), sLine2_interPoint])
                cutting_box_2 = boundingBox.difference(cutting_box_1)
            elif sLine2.MBR == "W":
                cutting_box_1 = Polygon([circleCenter, sLin1_interPoint, (minX, maxY), sLine2_interPoint])
                cutting_box_2 = boundingBox.difference(cutting_box_1)
            elif sLine2.MBR == "N":
                cutting_box_1 = Polygon([circleCenter, sLin1_interPoint, sLine2_interPoint])
                cutting_box_2 = boundingBox.difference(cutting_box_1)
        if sLine1.MBR == "E":
            if sLine2.MBR == "S":
                cutting_box_1 = Polygon([circleCenter, sLin1_interPoint, (maxX, minY), sLine2_interPoint])
                cutting_box_2 = boundingBox.difference(cutting_box_1)
            elif sLine2.MBR == "W":
                cutting_box_1 = Polygon([circleCenter, sLin1_interPoint, (maxX, minY), (minX, minY), sLine2_interPoint])
                cutting_box_2 = boundingBox.difference(cutting_box_1)
            elif sLine2.MBR == "N":
                cutting_box_1 = Polygon([circleCenter, sLin1_interPoint, (maxX, maxY), sLine2_interPoint])
                cutting_box_2 = boundingBox.difference(cutting_box_1)
            elif sLine2.MBR == "E":
                cutting_box_1 = Polygon([circleCenter, sLin1_interPoint, sLine2_interPoint])
                cutting_box_2 = boundingBox.difference(cutting_box_1)
        if sLine1.MBR == "S":
            if sLine2.MBR == "W":
                cutting_box_1 = Polygon([circleCenter, sLin1_interPoint, (minX, minY), sLine2_interPoint])
                cutting_box_2 = boundingBox.difference(cutting_box_1)
            elif sLine2.MBR == "N":
                cutting_box_1 = Polygon([circleCenter, sLin1_interPoint, (minX, minY), (minX, maxY), sLine2_interPoint])
                cutting_box_2 = boundingBox.difference(cutting_box_1)
            elif sLine2.MBR == "E":
                cutting_box_1 = Polygon([circleCenter, sLin1_interPoint, (maxX, minY), sLine2_interPoint])
                cutting_box_2 = boundingBox.difference(cutting_box_1)
            elif sLine2.MBR == "S":
                cutting_box_1 = Polygon([circleCenter, sLin1_interPoint, sLine2_interPoint])
                cutting_box_2 = boundingBox.difference(cutting_box_1)
        if sLine1.MBR == "W":
            if sLine2.MBR == "N":
                cutting_box_1 = Polygon([circleCenter, sLin1_interPoint, (minX, maxY), sLine2_interPoint])
                cutting_box_2 = boundingBox.difference(cutting_box_1)
            elif sLine2.MBR == "E":
                cutting_box_1 = Polygon([circleCenter, sLin1_interPoint, (minX, maxY), (maxX, maxY), sLine2_interPoint])
                cutting_box_2 = boundingBox.difference(cutting_box_1)
            elif sLine2.MBR == "S":
                cutting_box_1 = Polygon([circleCenter, sLin1_interPoint, (minX, minY), sLine2_interPoint])
                cutting_box_2 = boundingBox.difference(cutting_box_1)
            elif sLine2.MBR == "W":
                cutting_box_1 = Polygon([circleCenter, sLin1_interPoint, sLine2_interPoint])
                cutting_box_2 = boundingBox.difference(cutting_box_1)
    except:
        writeShp([cutting_box_1], "cutting_box_1.shp")
        raise Exception
    return cutting_box_1, cutting_box_2
Пример #54
0
def fun(x, hull):
    coords = x.reshape(4,2)
    p = Polygon(coords)
    area = p.difference(hull).area + hull.difference(p).area
    return(area)
Пример #55
0
				else:
					a = Polygon(groups_edges[adir][surf][grp])
					b = Polygon(groups[adir][surf][grp])

					if not (a.is_valid and b.is_valid):
						edge_total_errs.append(1.0)

						df = df.append({"image" : adir,
							"surface":surf,
							"group" :grp,
							"error":1.0,
							"type":'edge'}, ignore_index=True)
					else:

						Adiff1 = a.difference(b).area
						Adiff2 = b.difference(a).area
						Adiff = Adiff1+Adiff2
						Aunion = a.union(b).area
						err = Adiff/Aunion
						edge_total_errs.append(err)

						df = df.append({"image":adir,
							"surface":surf,
							"group" :grp,
							"error":err,
							"type":'edge'}, ignore_index=True)

				#images
				if grp not in groups_images[adir][surf].keys():
					img_total_errs.append(1.0)