output = []
    if log:
        print("Started point2shape process...")
    for row in range(0, points.shape[1]):
        for col in range(0, points.shape[0]):
            if points[row][col] > 0:
                output.append(Point(row, col))
    return output


if __name__ == "__main__":
    # execute only if run as a script
    #Example case
    plot = True

    p1 = Polygon([(2, 4), (2, 6), (4, 6), (4, 4)])
    p2 = Polygon([(10, 10), (10, 11), (11, 11), (11, 10)])
    obstacles = [Point(5, 5), Point(15, 15)]
    b = [20, 20]
    coords = [(0, 0), (2, 0), (0, 2)]
    point = Point(5, 5)
    d1 = f(coords)
    d1.rotate(-90)
    z = create_config_space(d1, obstacles, b)

    if plot:

        x = []
        y = []
        for tmp in range(0, b[1]):
            y.append(tmp)
示例#2
0
import unittest
from shapely.geometry.polygon import Polygon
from collections import OrderedDict
from ocgis.test.misc import gen_descriptor_classes
from ocgis.api.interp.interpreter import Interpreter
import numpy as np
import datetime
from types import NoneType
import make_simple_01
import os.path


NC_PATH = os.path.join(os.path.split(__file__)[0],make_simple_01.OUTNAME)
TGEOMS = [{'id':1,'geom':Polygon(((-105.5,40.5),(-103.5,40.5),(-103.5,38.5),(-105.5,38.5)))},
          {'id':2,'geom':Polygon(((-103.5,40.5),(-101.5,40.5),(-101.5,38.5),(-103.5,38.5)))},
          {'id':3,'geom':Polygon(((-105.5,38.5),(-103.5,38.5),(-103.5,36.5),(-105.5,36.5)))},
          {'id':4,'geom':Polygon(((-103.5,38.5),(-101.5,38.5),(-101.5,36.5),(-103.5,36.5)))},]
MGEOM = [{'id':100,'geom':Polygon(((-104.5,39.5),(-102.5,39.5),(-102.5,37.5),(-104.5,37.5)))}]
TINY = [{'id':2000,'geom':Polygon(((-103.75,38.75),(-103.25,38.75),(-103.25,38.25),(-103.75,38.25)))}]
META = {'uri':NC_PATH,
        'variable':'foo'}
META2 = {'uri':NC_PATH,
         'variable':'foo2'}
OPTS = OrderedDict({
    'meta':[[META],[META,META2]],
    'backend':['ocg'],
    'time_range':[[datetime.datetime(2000,1,1),
                   datetime.datetime(2000,1,1)],
                  None],
    'level_range':[None,[1]],
    'geom':[None,TGEOMS,MGEOM,TINY],
示例#3
0
def TestPP():
    print(__file__ + " start!!")

    # start and goal position
    sx = 300.0  # [mm]
    sy = 450.0  # [mm]
    gx = 1300.0  # [mm]
    gy = 450.0  # [mm]
    grid_size = 70  # [mm] #précision du A*
    robot_size = 150  # [mm] #distance de sécurité avec les obstacles i.e. taille du robot/2

    ox, oy = create_map()
    obstacle = [Point(600,1500),Point(700,1500),Point(800,1500),Point(900,1500)]
    add_obstacles(ox, oy, obstacle)
    
    print("map ok1")
    '''
    for i in range(60):
        ox.append(i)
        oy.append(0.0)
    for i in range(60):
        ox.append(60.0)
        oy.append(i)
    for i in range(61):
        ox.append(i)
        oy.append(60.0)
    for i in range(61):
        ox.append(0.0)
        oy.append(i)
    for i in range(40):
        ox.append(20.0)
        oy.append(i)
    for i in range(40):
        ox.append(40.0)
        oy.append(60.0 - i)
    '''
    
    if show_animation:  # pragma: no cover
        plt.plot(ox, oy, ".k")
        plt.plot(sx, sy, "xr")
        plt.plot(gx, gy, "xb")
        plt.grid(True)
        plt.axis("equal")

    rx, ry = a_star_planning(sx, sy, gx, gy, ox, oy, grid_size, robot_size)


    print (rx,ry)
    control_points = [Point(rx[i],ry[i]) for i in range(len(rx)-1,-1,-1)]
    
    poly = Polygon(InterieurDeMap())    
    #on repère les points critique où il faudra passer nécessairement (points proche des murs)
    #puis on calcul les chemins avec Bezier entre ces différents points
    AllPath = []
    newPath = []
    
    for i,point in enumerate(control_points) :
        newPath.append(point)
        if (not point.within(poly) and len(newPath)>3) or i== len(control_points)-1:
            AllPath.append(newPath)
            newPath = [point]
            
    BezierPaths = [Bezier.calc_bezier_path(discrete_control_points, n_points=100*len(discrete_control_points)) for discrete_control_points in AllPath ]

    
    return BezierPaths
def draw_grid():
    global edges
    global grid_accord
    total_line_segment=[]
    for i in total_line:
        for j in range(int(len(i)/2)-1):
            total_line_segment.append(((float(i[j*2]),float(i[j*2+1])),(float(i[j*2+2]),float(i[j*2+3]))))


    start_x = int(MIN_X)
    end_x = int(MAX_X)
    start_y = int(MIN_Y)
    end_y = int(MAX_Y)
    interval = 8
    grid_line = []
    for i in range(start_x,end_x,interval):
        for k in range(start_y,end_y,interval):
            CONTAIN=False
            for key, value in cellspace_accord.items():
                point = Point(i,k)
                polygon = Polygon(value)
                if polygon.contains(point) == True:
                    CONTAIN=True
                    break
            if CONTAIN==False : continue
            if i > end_x or i < 0 or k > end_y or k < 0: continue
            grid_accord[str(int(i))+"-"+str(int(k))]=(i,k)
            grid_line.append(LineString([(i, k), (i - interval, k + interval)]))
            grid_line.append(LineString([(i, k), (i + interval, k)]))
            grid_line.append(LineString([(i, k), (i, k + interval)]))
            # canvas.create_oval(i, k, i,  k, width=3, fill="#ff0000")
            # print(i , k)


    for i in grid_line :
        WALL_Bool_intersect=False
        DOOR_Bool_intersect=False
        Start_grid=str(int(list(i.coords)[0][0]))+"-"+str(int(list(i.coords)[0][1]))
        End_grid=str(int(list(i.coords)[1][0]))+"-"+ str(int(list(i.coords)[1][1]))
        EDGE=(Start_grid,End_grid,euclidean_distance((list(i.coords)[0][0], list(i.coords)[0][1]),(list(i.coords)[1][0], list(i.coords)[1][1])))

        # print(list(i.coords)[0][0], list(i.coords)[0][1], list(i.coords)[1][0], list(i.coords)[1][1])
        # print(EDGE)
        for k in total_line_segment:
            WALL_LINE=LineString([(k[0][0],k[0][1]),(k[1][0],k[1][1])])
            intersect_Point=i.intersection(WALL_LINE)
            if intersect_Point.type=='Point':
                WALL_Bool_intersect=True
                break

        if WALL_Bool_intersect==False:
            canvas.create_line(list(i.coords)[0][0], list(i.coords)[0][1], list(i.coords)[1][0], list(i.coords)[1][1],width=1, fill="blue")
            edges.append(EDGE)

        for k in door_line:
            intersect_Point = i.intersection(k)
            if intersect_Point.type == 'Point':
                DOOR_Bool_intersect = True
                break

        if DOOR_Bool_intersect == True:
            canvas.create_line(list(i.coords)[0][0], list(i.coords)[0][1], list(i.coords)[1][0], list(i.coords)[1][1],width=1, fill="blue")
            edges.append(EDGE)


            # print (i)
    # for i in grid_line:
    #     print (list(i.coords)[0][0])

    window.mainloop()
    def possibleFlightArea(self, area_length, uav0, uavh_others, static_kozs):
        theta_ref = math.radians(self.thetaRef)
        theta_possible = math.radians(self.thetaPossible)

        side_decision = 0

        points = [list(self.position)]

        if self.staticAreaLength:
            area_length = self.staticAreaLength
            side_decision = self.__weightedSideDecision(
                uav0, uavh_others,
                static_kozs)  # stub uav_others and koz lists for now

            if side_decision < 0:
                points[-1][0] = self.position[0] + (
                    3 * area_length * math.cos(theta_ref -
                                               (theta_possible / 2)))
                points[-1][1] = self.position[1] + (
                    3 * area_length * math.sin(theta_ref -
                                               (theta_possible / 2)))

        for div in range(-2, -5, -1):
            pt_x = self.position[0] + (area_length *
                                       math.cos(theta_ref +
                                                (theta_possible / div)))
            pt_y = self.position[1] + (area_length *
                                       math.sin(theta_ref +
                                                (theta_possible / div)))
            points.append([pt_x, pt_y])

        # +-0
        pt_x = self.position[0] + (area_length * math.cos(theta_ref))
        pt_y = self.position[1] + (area_length * math.sin(theta_ref))
        points.append([pt_x, pt_y])

        for div in range(4, 1, -1):
            pt_x = self.position[0] + (area_length *
                                       math.cos(theta_ref +
                                                (theta_possible / div)))
            pt_y = self.position[1] + (area_length *
                                       math.sin(theta_ref +
                                                (theta_possible / div)))
            points.append([pt_x, pt_y])

        if self.staticAreaLength and side_decision > 0:
            points[-1][0] = self.position[0] + (2 * area_length *
                                                math.cos(theta_ref +
                                                         (theta_possible / 2)))
            points[-1][1] = self.position[1] + (2 * area_length *
                                                math.sin(theta_ref +
                                                         (theta_possible / 2)))

        points.append(list(self.position))

        # if uav0 is in possible flight area, recalculate with length/2
        pt = Point(uav0.position[0], uav0.position[1])
        koz_polygon = Polygon(points)
        if koz_polygon.contains(pt):
            print(TC.FAIL +
                  '[HOTFIX - Line 152 | Area Length for Head-On Collision]' +
                  TC.ENDC)
            if self.staticAreaLength:
                self.staticAreaLength = self.staticAreaLength / 2
            else:
                self.staticAreaLength = area_length / 4
            points = self.possibleFlightArea(area_length, uav0, uavh_others,
                                             static_kozs)

        return points
示例#6
0
 def client_contains_area(self, partner, client):        
     point = Point(client)
     polygon = Polygon(partner)
     
     return polygon.contains(point)
示例#7
0
def findNearestBuildings(resultPoints, fig, numberOfK):
	# Rakennusdata samaan tiedostoon ja koordinaattisysteemiin
	crs0={'init': 'epsg:3067'}
	rakVan=gpd.read_file("vanRak.json", crs=crs0,encoding="utf-8")
	rakVan = rakVan.rename(columns={rakVan.columns[4]: "kayttotarkoitus_koodi" })

	rakVan = rakVan.rename(columns={"käyttötarkoitus_koodi": "kayttotarkoitus_koodi"})
	rakEsp=gpd.read_file("espRak.json", crs=crs0,encoding="utf-8")
	rakHel=gpd.GeoDataFrame.from_file(r"rakennukset2012/rakennukset_Helsinki_wgs84/rakennukset_Helsinki_06_2012_wgs84.TAB", crs=crs0,encoding="utf-8")
	rakVan=rakVan.to_crs({'init': 'epsg:3067'})
	rakHel=rakHel.to_crs({'init': 'epsg:3067'})
	rakEsp=rakEsp.to_crs({'init': 'epsg:3067'})

# Parsitaan Espoolle ja Vantaalle kirjainkoodit
	kayttoluokitus0=pd.read_table('kayttotarkoitusluokitus.txt', index_col=False, sep='\t', skiprows=1, header=None)
	kayttoluokitus0.columns=['koodi', 'selite']
	kaytto, selite = '', ''
	kayttoluokitus=pd.DataFrame(columns=['koodi', 'selite','koodiPitka','selitePitka', 'koodiPitkaNum'], dtype=str)
	for index, row in kayttoluokitus0.iterrows():
		if row['koodi'].isalpha():
			koodi=row['koodi']
			selite=row['selite']
		else:
			koodiPitka=row['koodi']
			selitePitka=row['selite']
			kayttoluokitus.loc[index, 'koodi']=koodi
			kayttoluokitus.loc[index, 'selite']=selite
			kayttoluokitus.loc[index, 'koodiPitka']=koodiPitka
			kayttoluokitus.loc[index, 'selitePitka']=selitePitka
			kayttoluokitus.loc[index, 'koodiPitkaNum']=int(koodiPitka)
			kayttoluokitus.drop_duplicates('koodiPitkaNum', inplace=True)

	# Espoo
	rakEsp=pd.merge(rakEsp, kayttoluokitus[['koodi', 'koodiPitkaNum']], left_on='kayttotarkoitusnumero', right_on='koodiPitkaNum')
	rakEsp['osoite']=rakEsp.katunimi + ' ' +rakEsp.osoitenumero + ' Espoo'
	rakEsp1=rakEsp[['koodi','osoite','geometry']]
	rakEsp1.columns=['koodi','osoite','building']
	# Vantaa
	rakVan=pd.merge(rakVan, kayttoluokitus[["koodi", "koodiPitka"]], left_on="kayttotarkoitus_koodi", right_on="koodiPitka")
	rakVan['osoite']=rakVan.katuosoite_suomeksi + ' Vantaa'
	rakVan1=rakVan[['koodi', 'osoite', 'geometry']]
	rakVan1.columns=['koodi','osoite','building']
	#  HElsinki
	rakHel1=rakHel[["kayttotark_t1koodi", "Osoite", "geometry"]]
	rakHel1.columns=['koodi', 'osoite', 'building']
	rak=pd.concat((rakEsp1, rakVan1,rakHel1))
	rak=rak.set_geometry('building')
	print("Rakennusten geometriasarake: ", rak.geometry.name)
#rak['geometry2']=rak.centroid
	#Geometrian vaihto, jos tarpeen käyttää rakennusten keskipisteitä
	#rak=rak.set_geometry('geometry2')
	
	#A Asuinrakennukset B Vapaa-ajan asuinrakennukset C Liikerakennukset D Toimistorakennukset
	#E Liikenteen rakennukset F Hoitoalan rakennukset G Kokoontumisrakennukset H Opetusrakennukset
	#J Teollisuusrakennukset K Varastorakennukset L Palo- ja pelastustoimen rakennukset 
	#M Maatalousrakennukset N Muut rakennukset

	rakennusTyyppi='D'
	retVal=placeSuggestions(resultPoints, rak[(rak['koodi']==rakennusTyyppi) | (rak['koodi']=='F') | (rak['koodi']=='C')])
	#rak=rak[['koodi', 'osoite', 'building']]
	#test0=pd.DataFrame(rak)
	#test0['test']=0
	#print(rak.columns)
	#print(test0.columns)	
	# plot 5 nearest locations
	buildingSuggestions=gpd.GeoDataFrame(retVal[['pointIndex','building','osoite']], geometry='building', crs=crs0)
	points=gpd.GeoDataFrame(retVal[['pointIndex','point']], geometry='point', crs=crs0)
	print(retVal.head())
	print(buildingSuggestions.crs)
	print(len(rak))
	i=0
	
	while i <= max(points["pointIndex"]):
		print(buildingSuggestions.geometry, buildingSuggestions.crs)
		fig = plt.figure(i+2)
		buildingPlot = fig.add_subplot(111, aspect='equal', adjustable='box-forced')
		buildingPlot.set_title(i+1)
		buildingsOfIndex = buildingSuggestions[buildingSuggestions["pointIndex"] == i]
		df_road = gpd.read_file("metropolitan/metropolitan_helsinki_roads_gen1.geojson")
		df_road = df_road.to_crs(epsg=3067)
		df_road.plot(ax=buildingPlot, color="rebeccapurple", alpha=1, zorder=0)
		axisX = max(buildingsOfIndex["building"].centroid.x)
		axisX0 = min(buildingsOfIndex["building"].centroid.x)
		axisY = max(buildingsOfIndex["building"].centroid.y)
		axisY0 = min(buildingsOfIndex["building"].centroid.y)
		poly = Polygon([[axisX0,axisY0],[axisX0,axisY],[axisX,axisY],[axisX,axisY0]])
		for building in rak["building"]:
			if poly.contains(building):
				patch = PolygonPatch(building , alpha=0.75, zorder=-1, fc="red")
				buildingPlot.add_patch(patch)
		
		if (axisX - axisX0) < 250:
			paddingX = 250
		else:
			paddingX = (axisX - axisX0)*0.2
		if(axisY-axisY0) < 250:
			paddingY = 250
		else:
			paddingY = (axisY - axisY0)*0.2
			

		buildingPlot.axis([axisX0 - paddingX,axisX+paddingX,axisY0-paddingY,axisY+paddingY])
		buildingPlot.axes.get_xaxis().set_visible(False)
		buildingPlot.axes.get_yaxis().set_visible(False)
		buildingSuggestions[buildingSuggestions["pointIndex"]==i].plot(ax=buildingPlot)
		j = 0
		for j in range(len(buildingSuggestions[buildingSuggestions["pointIndex"]==i])):
			#print(buildingSuggestions[buildingSuggestions["pointIndex"]==i]["osoite"].iloc[j])
			print(buildingSuggestions[buildingSuggestions["pointIndex"]==i]["building"].iloc[j].centroid.x)
			print(buildingSuggestions[buildingSuggestions["pointIndex"]==i]["building"].iloc[j].centroid.y)

			buildingPlot.annotate(buildingSuggestions[buildingSuggestions["pointIndex"]==i]["osoite"].iloc[j], xy=(buildingSuggestions[buildingSuggestions["pointIndex"]==i]["building"].iloc[j].centroid.x, buildingSuggestions[buildingSuggestions["pointIndex"]==i]["building"].iloc[j].centroid.y))
			j = j + 1 
		
		points[points['pointIndex']==i].plot(ax=buildingPlot)
		i = i + 1
	
	print(buildingSuggestions, points)
def parse_slide_annotations_into_tables(slide_annotations,
                                        cropping_bounds=None,
                                        cropping_polygon_vertices=None,
                                        use_shapely=False):
    """Given a slide annotation list, parse into convenient tabular format.

    If the annotation is a point, then it is just treated as if it is a
    rectangle with zero area (i.e. xmin=xmax). Rotated rectangles are treated
    as polygons for simplicity.

    Parameters
    -----------
    slide_annotations : list of dicts
        response from server request

    cropping_bounds : dict or None
        if given, must have keys XMIN, XMAX, YMIN, YMAX. These are the
        bounds to which the polygons may be cropped using shapely,
        if the param use_shapely is True. Otherwise, the polygon
        coordinates are just shifted relative to these bounds without
        actually cropping.

    cropping_polygon_vertices : nd array or None
        if given, is an (m, 2) nd array of vertices to crop bounds.
        if the param use_shapely is True. Otherwise, the polygon
        coordinates are just shifted relative to these bounds without
        actually cropping.

    use_shapely : bool
        see cropping_bounds description.

    Returns
    ---------
    Pandas DataFrame
        Summary of key properties of the annotation documents. It has the
        following columns:
        - annotation_girder_id
        - _modelType
        - _version
        - itemId
        - created
        - creatorId
        - public
        - updated
        - updatedId
        - groups
        - element_count
        - element_details

    Pandas DataFrame

        The individual annotation elements (polygons, points, rectangles).
        The columns annidx and elementidx encode the dict index of annotation
        document and element, respectively, in the original slide_annotations
        list of dictionaries. It has the following columns:

        - annidx
        - annotation_girder_id
        - elementidx
        - element_girder_id
        - type
        - group
        - label
        - color
        - xmin
        - xmax
        - ymin
        - ymax
        - bbox_area
        - coords_x
        - coords_y

    """

    # we use this object to pass params to split method into sub-methods
    # and avoid annoying linting ("method too complex") issue
    class Cfg:
        def __init__(self):
            pass

    cfg = Cfg()
    cfg.cropping_bounds = cropping_bounds
    cfg.cropping_polygon_vertices = cropping_polygon_vertices
    cfg.use_shapely = use_shapely

    cfg.annotation_infos = DataFrame(columns=[
        'annotation_girder_id',
        '_modelType',
        '_version',
        'itemId',
        'created',
        'creatorId',
        'public',
        'updated',
        'updatedId',
        'groups',
        'element_count',
        'element_details',
    ])

    cfg.element_infos = DataFrame(columns=[
        'annidx', 'annotation_girder_id', 'elementidx', 'element_girder_id',
        'type', 'group', 'label', 'color', 'xmin', 'xmax', 'ymin', 'ymax',
        'bbox_area', 'coords_x', 'coords_y'
    ])

    if cfg.cropping_bounds is not None:
        assert cfg.cropping_polygon_vertices is None, \
            "either give cropping bouns or vertices, not both"
        xmin, xmax, ymin, ymax = (cfg.cropping_bounds['XMIN'],
                                  cfg.cropping_bounds['XMAX'],
                                  cfg.cropping_bounds['YMIN'],
                                  cfg.cropping_bounds['YMAX'])
        bounds_polygon = Polygon(
            np.array([
                (xmin, ymin),
                (xmax, ymin),
                (xmax, ymax),
                (xmin, ymax),
                (xmin, ymin),
            ],
                     dtype='int32'))
        cfg.x_shift = xmin
        cfg.y_shift = ymin

    elif cfg.cropping_polygon_vertices is not None:
        bounds_polygon = Polygon(np.int32(cfg.cropping_polygon_vertices))
        cfg.x_shift, cfg.y_shift = np.min(cfg.cropping_polygon_vertices, 0)

    # go through annotation elements and add as needed
    for cfg.annidx, cfg.ann in enumerate(slide_annotations):

        annno = cfg.annotation_infos.shape[0]

        # Add annotation document info to annotations dataframe

        cfg.annotation_infos.loc[annno,
                                 'annotation_girder_id'] = cfg.ann['_id']

        for key in [
                '_modelType',
                '_version',
                'itemId',
                'created',
                'creatorId',
                'public',
                'updated',
                'updatedId',
        ]:
            cfg.annotation_infos.loc[annno, key] = cfg.ann[key]

        cfg.annotation_infos.loc[annno, 'groups'] = str(cfg.ann['groups'])
        cfg.annotation_infos.loc[
            annno, 'element_count'] = cfg.ann['_elementQuery']['count']
        cfg.annotation_infos.loc[
            annno, 'element_details'] = cfg.ann['_elementQuery']['details']

        for cfg.elementidx, cfg.element in enumerate(
                cfg.ann['annotation']['elements']):

            coords = _get_coords_from_element(copy.deepcopy(cfg.element))

            # crop using shapely to desired bounds if needed
            # IMPORTANT: everything till this point needs to be
            # relative to the whole slide image
            if ((cfg.cropping_bounds is None) and
                    (cfg.cropping_polygon_vertices is None)) \
                    or (cfg.element['type'] == 'point') \
                    or (not use_shapely):
                all_coords = [
                    coords,
                ]
            else:
                all_coords = _maybe_crop_polygon(coords, bounds_polygon)

            # now add polygons one by one
            for vertices in all_coords:
                _add_element_to_final_df(vertices, cfg=cfg)

    return cfg.annotation_infos, cfg.element_infos
import xlrd
import json
from collections import Counter
import re

from tqdm import tqdm
from geopandas import GeoDataFrame
from shapely.geometry import Point
from shapely.geometry.polygon import Polygon
import geopandas as gpd
from geopandas import sjoin
from fast_pt_in_poly import contains_cy_insee

import helpers_locs_to_home as help_loc

france=Polygon([[-4.9658203125,42.3585439175],[8.4375,42.3585439175],[8.4375,51.2344073516],[-4.9658203125,51.2344073516],[-4.9658203125,42.3585439175]])

""" Extract excel data while ignoring first data rows"""
def extract_xls_file(path,sheet_name,offset):
    workbook = xlrd.open_workbook(path)
    worksheet = workbook.sheet_by_name(sheet_name)
    rows = []
    for i, row in tqdm(enumerate(range(worksheet.nrows))):
        if i <= offset:  # (Optionally) skip headers
            continue
        r = []
        for j, col in enumerate(range(worksheet.ncols)):
            r.append(worksheet.cell_value(i, j))
        rows.append(r)
    return(pd.DataFrame(rows[1:],columns=rows[0]))
    def onclick(self, event):
        print('button=%d, x=%d, y=%d, xdata=%f, ydata=%f' %
              (event.button, event.x, event.y, event.xdata, event.ydata))
        if event.button == 3:
            if str(self.rClicktype.currentText()) == 'Add cell':
                squaresize = self.cropsize
                #print(len(self.THEblobs))
                self.THEblobs = np.array(
                    self.THEblobs.tolist() +
                    [[int(event.ydata),
                      int(event.xdata), self.cropsize]])
                #print(len(self.THEblobs))
                #self.table.setHorizontalHeaderLabels(['index', 'auto class', 'manual class'])
                #rowPosition = self.table.rowCount()
                #self.table.insertRow(rowPosition)

                self.nMarkedCells.setText(
                    str(int(self.nMarkedCells.text()) + 1))
                self.ImgAddPatches()
            if str(self.rClicktype.currentText()) == 'Add 1st box corner':
                self.guidePoints['TR'] = [int(event.ydata), int(event.xdata)]
                self.rClicktype.setCurrentIndex == 'Add 2nd box corner'

                if 0 not in self.guidePoints.values():
                    self.polygonList = []
                    self.innergridRight = [
                        (array(self.guidePoints['TR']) * i +
                         array(self.guidePoints['BR']) *
                         (int(self.numLayers.text()) - i)) /
                        int(self.numLayers.text())
                        for i in range(0,
                                       int(self.numLayers.text()) + 1)
                    ]
                    self.innergridLeft = [
                        (array(self.guidePoints['TL']) * i +
                         array(self.guidePoints['BL']) *
                         (int(self.numLayers.text()) - i)) /
                        int(self.numLayers.text())
                        for i in range(0,
                                       int(self.numLayers.text()) + 1)
                    ]
                    #print(self.innergridLeft, self.innergridRight)
                    self.bigpoligon = Polygon([
                        self.guidePoints['TR'], self.guidePoints['TL'],
                        self.guidePoints['BL'], self.guidePoints['BR']
                    ])
                    for i in range(len(self.innergridLeft) - 1):
                        self.polygonList += [
                            Polygon([
                                self.innergridRight[i], self.innergridLeft[i],
                                self.innergridLeft[i + 1],
                                self.innergridRight[i + 1]
                            ])
                        ]
                self.ImgAddPatches()

            if str(self.rClicktype.currentText()) == 'Add 2nd box corner':
                self.guidePoints['TL'] = [int(event.ydata), int(event.xdata)]
                self.rClicktype.setCurrentIndex == 'Add 3rd box corner'

                if 0 not in self.guidePoints.values():
                    self.polygonList = []
                    self.innergridRight = [
                        (array(self.guidePoints['TR']) * i +
                         array(self.guidePoints['BR']) *
                         (int(self.numLayers.text()) - i)) /
                        int(self.numLayers.text())
                        for i in range(0,
                                       int(self.numLayers.text()) + 1)
                    ]
                    self.innergridLeft = [
                        (array(self.guidePoints['TL']) * i +
                         array(self.guidePoints['BL']) *
                         (int(self.numLayers.text()) - i)) /
                        int(self.numLayers.text())
                        for i in range(0,
                                       int(self.numLayers.text()) + 1)
                    ]
                    #print(self.innergridLeft, self.innergridRight)
                    self.bigpoligon = Polygon([
                        self.guidePoints['TR'], self.guidePoints['TL'],
                        self.guidePoints['BL'], self.guidePoints['BR']
                    ])
                    for i in range(len(self.innergridLeft) - 1):
                        self.polygonList += [
                            Polygon([
                                self.innergridRight[i], self.innergridLeft[i],
                                self.innergridLeft[i + 1],
                                self.innergridRight[i + 1]
                            ])
                        ]
                self.ImgAddPatches()

            if str(self.rClicktype.currentText()) == 'Add 3rd box corner':
                self.guidePoints['BL'] = [int(event.ydata), int(event.xdata)]
                self.rClicktype.setCurrentIndex == 'Add 4th box corner'

                if 0 not in self.guidePoints.values():
                    self.polygonList = []
                    self.innergridRight = [
                        (array(self.guidePoints['TR']) * i +
                         array(self.guidePoints['BR']) *
                         (int(self.numLayers.text()) - i)) /
                        int(self.numLayers.text())
                        for i in range(0,
                                       int(self.numLayers.text()) + 1)
                    ]
                    self.innergridLeft = [
                        (array(self.guidePoints['TL']) * i +
                         array(self.guidePoints['BL']) *
                         (int(self.numLayers.text()) - i)) /
                        int(self.numLayers.text())
                        for i in range(0,
                                       int(self.numLayers.text()) + 1)
                    ]
                    #print(self.innergridLeft, self.innergridRight)
                    self.bigpoligon = Polygon([
                        self.guidePoints['TR'], self.guidePoints['TL'],
                        self.guidePoints['BL'], self.guidePoints['BR']
                    ])
                    for i in range(len(self.innergridLeft) - 1):
                        self.polygonList += [
                            Polygon([
                                self.innergridRight[i], self.innergridLeft[i],
                                self.innergridLeft[i + 1],
                                self.innergridRight[i + 1]
                            ])
                        ]
                self.ImgAddPatches()

            if str(self.rClicktype.currentText()) == 'Add 4th box corner':
                self.guidePoints['BR'] = [int(event.ydata), int(event.xdata)]
                if 0 not in self.guidePoints.values():
                    self.polygonList = []
                    self.innergridRight = [
                        (array(self.guidePoints['TR']) * i +
                         array(self.guidePoints['BR']) *
                         (int(self.numLayers.text()) - i)) /
                        int(self.numLayers.text())
                        for i in range(0,
                                       int(self.numLayers.text()) + 1)
                    ]
                    self.innergridLeft = [
                        (array(self.guidePoints['TL']) * i +
                         array(self.guidePoints['BL']) *
                         (int(self.numLayers.text()) - i)) /
                        int(self.numLayers.text())
                        for i in range(0,
                                       int(self.numLayers.text()) + 1)
                    ]
                    #print(self.innergridLeft, self.innergridRight)
                    self.bigpoligon = Polygon([
                        self.guidePoints['TR'], self.guidePoints['TL'],
                        self.guidePoints['BL'], self.guidePoints['BR']
                    ])
                    #print(self.bigpoligon)
                    for i in range(len(self.innergridLeft) - 1):
                        self.polygonList += [
                            Polygon([
                                self.innergridRight[i], self.innergridLeft[i],
                                self.innergridLeft[i + 1],
                                self.innergridRight[i + 1]
                            ])
                        ]
                self.ImgAddPatches()
            if str(self.rClicktype.currentText()) == 'Remove cell':
                dist = np.sum(
                    (self.THEblobs[:, 0:2] - [event.ydata, event.xdata])**2, 1)
                if min(dist) < 800:
                    line = dist.tolist().index(min(dist))
                    #print(line)
                    self.removeCell(line)
                    self.nMarkedCells.setText(
                        str(int(self.nMarkedCells.text()) - 1))
                #self.ImgAddPatches()

        elif event.button == 2:
            #print(self.THEblobs[:,0:2])
            dist = np.sum(
                (self.THEblobs[:, 0:2] - [event.ydata, event.xdata])**2, 1)
            if min(dist) < 800:
                line = dist.tolist().index(min(dist))
                #print(line)
                self.removeCell(line)
                self.nMarkedCells.setText(
                    str(int(self.nMarkedCells.text()) - 1))
示例#11
0
 def point_inside(self, x, y):
     polygon = Polygon(self.nodes)
     return polygon.intersects(Point(x, y))
    def openMainFig(self):
        if self.THEimage.any() == True:
            self.rmmpl()
            self.THEimage = np.array([])
            self.BLUEimage = 0
            while self.table.rowCount() < int(self.numLayers.text()) + 2:
                self.table.insertRow(0)
            while self.table.rowCount() > int(self.numLayers.text()) + 2:
                self.table.removeRow(0)
            for num, layer in enumerate(
                [str(x + 1) for x in range(int(self.numLayers.text()))] +
                ['Total selected reg', 'Total image']):
                self.table.setItem(num, 0, QtWidgets.QTableWidgetItem(layer))
                self.table.setItem(num, 1, QtWidgets.QTableWidgetItem("0"))
                self.table.setItem(num, 2, QtWidgets.QTableWidgetItem("0"))
                self.table.setItem(num, 3, QtWidgets.QTableWidgetItem("0"))
                self.table.setItem(num, 4, QtWidgets.QTableWidgetItem("0"))
                self.table.setItem(num, 5, QtWidgets.QTableWidgetItem("0"))
            self.directory = 'singleCells/'
            self.guidePoints = {'TR': 0, 'TL': 0, 'BL': 0, 'BR': 0}
            self.innergridRight = [
                (self.guidePoints['TR'] * i + self.guidePoints['BR'] *
                 (int(self.numLayers.text()) - i)) / int(self.numLayers.text())
                for i in range(1,
                               int(self.numLayers.text()) + 1)
            ]
            self.innergridLeft = [
                (self.guidePoints['TL'] * i + self.guidePoints['BL'] *
                 (int(self.numLayers.text()) - i)) / int(self.numLayers.text())
                for i in range(1,
                               int(self.numLayers.text()) + 1)
            ]
            self.polygonList = []
            self.bigpoligon = 0
            self.nMarkedCells.setText(str(0))
            self.THEblobs = np.array([])

        name = QtWidgets.QFileDialog.getOpenFileName(
            self, 'Single File', '~/Desktop/',
            "Image files (*.jpg *.png *.tif)")
        self.figname = str(name[0])
        image = imageio.imread(self.figname)
        #self.saveNames.setText(str(name).split("/")[-1][:-4] + 'i')
        self.THEimage = image
        self.imgPolygon = Polygon([[0, 0], [0, image.shape[1]],
                                   [image.shape[0], image.shape[1]],
                                   [image.shape[0], 0]])
        self.BLUEimage = image[:, :, 2]
        #self.BLUEblobs = blob_log(self.BLUEimage[self.cropsize:-self.cropsize,self.cropsize:-self.cropsize],  max_sigma=int(self.maxSigSpin.text()), num_sigma=10, min_sigma = int(self.minSigSpin.text()),overlap = float(self.log_overlap.text()) ,threshold=float(self.thresholdSpin.text()))
        self.REDimage = image[:, :, 0]
        self.GREENimage = image[:, :, 1]
        baseimage = self.fig.add_subplot(111)
        #baseimage.axis('off', frameon=False)
        #baseimage.grid(False)
        #baseimage.imshow(image)
        #axis('off')
        #subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=0, hspace=0)

        self.fig, ax = subplots(1, 1)
        ax.imshow(self.THEimage)
        ax.axis('off')
        subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=0, hspace=0)

        self.canvas = FigureCanvas(self.fig)
        self.mplvl.addWidget(self.canvas)
        self.canvas.draw()
        self.toolbar = NavigationToolbar(self.canvas,
                                         self.widget,
                                         coordinates=True)
        self.mplvl.addWidget(self.toolbar)
        cid = self.fig.canvas.mpl_connect('button_press_event', self.onclick)
示例#13
0
def getSA3(lon, lat, polygon):  #149.57900670400008, -35.5
    polygon = Polygon(polygon)  # create polygon
    point = Point(lon, lat)  # create point
    return (point.within(polygon))
示例#14
0
def polygon_from_points(points):
    if Polygon is None:
        raise ValueError('shapely is not installed, please install it')
    return Polygon(points)
示例#15
0
def isIn(x, y, X, Y):
    point = Point(x, y)
    points = [(x, y) for x, y in zip(X, Y)]
    polygon = Polygon(points)
    return polygon.contains(point)
def get_skyline_vs2(poi_awal, query_awal, rating=0):
    data_poi = poi_awal[poi_awal['rating'] >= float(rating)]
    if len(data_poi) < 2:
        return data_poi
    else:
        poi = data_poi[['latitude', 'longitude']].values.tolist()
        poi = np.array(poi)

        query = query_awal[['latitude', 'longitude']].values.tolist()
        query = np.array(query)

        skyline = []
        minheap = []
        visited = []
        extracted = []

        vor = Voronoi(poi)
        regions, vertices = voronoi_finite_polygons_2d(vor)

        if len(query_awal) == 2:
            vor = Voronoi(poi)
            hull_vertices = [que for que in query]

        else:
            hull = ConvexHull(query)
            hull_vertices = [query[i] for i in hull.vertices]
            ch = Polygon(hull_vertices)

        dist_poi = distance.cdist(poi, hull_vertices, 'euclidean')
        nn = np.where(dist_poi[:, 0] == min(dist_poi[:, 0]))[0][0]

        mindist_nn = mindist(nn, dist_poi)
        heapq.heappush(minheap, (mindist_nn, nn))
        visited.append(nn)

        MBR_nn = MBR(nn, dist_poi, hull_vertices)
        B = MBR_nn
        vor_neighbors = voronoi_neighbors(vor)

        vor_ver = []
        for region in regions:
            vor_ver.append(vertices[region])

        while minheap:
            key, p = minheap[0]
            a = np.array(minheap)
            if p in extracted:
                heapq.heappop(minheap)
                p_is_dominated_by_skyline = is_dominated(
                    p, dist_poi, hull_vertices, skyline)
                if len(query_awal) == 2:
                    if p_is_dominated_by_skyline == 'no':
                        skyline.append(p)
                else:
                    if Point(poi[p]).within(
                            ch) or p_is_dominated_by_skyline == 'no':
                        skyline.append(p)
            else:
                extracted.append(p)
                vorn_p = vor_neighbors[p]
                vorn_p_in_skyline = vorn_in_skyline(vorn_p, skyline)
                if not skyline or vorn_p_in_skyline == 'yes':
                    for p_ in vorn_p:
                        if p_ in visited:
                            continue
                        elif Point(poi[p_]).within(B) or Polygon(
                                vor_ver[p_]).intersects(B):
                            visited.append(p_)
                            mindist_p_ = mindist(p_, dist_poi)
                            heapq.heappush(minheap, (mindist_p_, p_))
                            MBR_p_ = MBR(p_, dist_poi, hull_vertices)
                            B = B.intersection(MBR_p_)

        return data_poi.iloc[skyline].sort_index()
示例#17
0
    def on_pick(self, event):
        """
        mouse has been clicked on the canvas
        """
        box_points = (event.xdata, event.ydata)
        print "coords:"
        print box_points
        print self.axes.get_xlim()
        print self.axes.get_ylim()
        print self.stack.shape

        if event.inaxes == self.axes:
            if (self.proi_mode == True) and (self.pcollect_roi == True):
                # This is CRUCIAL:
                # coordinate system of imshow:
                #  0
                #  |
                #  |
                # y|
                #  |
                #  |
                #  v 0-------->
                #        x
                # the box points I get from on_pick perfectly follow this convention.
                # When I plot (e.g. using plot) these points on the imshow figure, they appear a the right location
                # Hence the coordinate system of imshow, extracted points and replotting points on it
                # are consistent.
                # However, the matrix arrangement (according to numpy) is the following:
                #
                #  0
                #  |
                #  |
                # x|
                #  |
                #  |
                #  v 0-------->
                #        y
                # Assume imshow shows matrix M and I have according to  imshow the coordinates (x, y). To get
                # the cooresponding element from the matrix, I have to type M(y, x). This is because
                # y corresponds to the rows (which come first) and x to the columns. So,
                # if I want to save the ROI coordinates according to the numpy matrix convention, I
                # should save x as y and y as x:
                # Again, I save the coordinates according to the way I access a matrix element: rows first, then columns
                self.curr_roi_x.append(box_points[1])
                self.curr_roi_y.append(box_points[0])

                self.draw_figure()

            if self.proi_mode == True and self.proi_delete == True:
                self.proi_delete = False
                # NOTE: change of coordinate system
                (py, px) = (box_points[0], box_points[1])
                point = Point(px, py)
                i = 0
                for r in self.ROIs:
                    (x0, y0) = (r[0][0], r[1][0])
                    polyg = Polygon(zip(r[0], r[1]) + [(x0, y0)])
                    if polyg.contains(point):
                        # delete this point
                        self.ROIs.pop(i)
                        self.draw_figure()
                    i = i + 1
示例#18
0
 print('Panel Coords', panel_coords[0][0][0])
 # Extract coordinates
 if panel_coords[0][0][0]:
     nw_x = int(panel_coords[0][0][0])
     nw_y = int(panel_coords[0][0][1])
     sw_x = int(panel_coords[1][0][0])
     sw_y = int(panel_coords[1][0][1])
     se_x = int(panel_coords[2][0][0])
     se_y = int(panel_coords[2][0][1])
     ne_x = int(panel_coords[3][0][0])
     ne_y = int(panel_coords[3][0][1])
     x_min = numpy.min([nw_x, sw_x, ne_x, se_x])
     x_max = numpy.max([nw_x, sw_x, ne_x, se_x])
     y_min = numpy.min([nw_y, sw_y, ne_y, se_y])
     y_max = numpy.max([nw_y, sw_y, ne_y, se_y])
     panelPolygon = Polygon([(sw_x, sw_y), (nw_x, nw_y), (ne_x, ne_y),
                             (se_x, se_y)])
     numPixel = 0
     sumRadiance = 0
     for x in range(x_min, x_max):
         for y in range(y_min, y_max):
             if panelPolygon.contains(Point(x, y)):
                 numPixel += 1
                 sumRadiance = sumRadiance + radianceImage[y, x]
     meanRadiance = sumRadiance / numPixel
     if bandName == 'Blue':
         sbr_B = sbr_B + meanRadiance
         nbr_B += 1
     elif bandName == 'Green':
         sbr_G = sbr_G + meanRadiance
         nbr_G += 1
     elif bandName == 'Red':
示例#19
0
lon_0 = -50
lat_0 = 50
dataFile = '/home/cyrf0006/data/GEBCO/GEBCO_2014_1D.nc'

lonLims = [4, 18]  # Khanh boxes
latLims = [58, 71]
lonLims = [2, 21]  # Khanh boxes 2
latLims = [55, 72]
# Box 1
lat1 = [58.23, 59.23]
lon1 = [4, 5]
x1 = lon1[0]
x2 = lon1[1]
y1 = lat1[0]
y2 = lat1[1]
polygon1 = Polygon([[x1, y1], [x1, y2], [x2, y2], [x2, y1]])
# Box2
lat2 = [69.78, 70.5]
lon2 = [17.5, 18]
xx1 = lon2[0]
xx2 = lon2[1]
yy1 = lat2[0]
yy2 = lat2[1]
polygon2 = Polygon([[xx1, yy1], [xx1, yy2], [xx2, yy2], [xx2, yy1]])

## ---- Load NAFO divisions ---- ##

decim_scale = 4
fig_name = 'map_sst_capelin.png'
v = np.linspace(100, 5000, 10)
vtext = np.linspace(1000, 5000, 5)
示例#20
0
    def Exist1(self, existingPoints, addedPoints):

        self.currP = existingPoints[0]
        self.tempPoints = list(self.AllPoints)

        goOnX = True
        if addedPoints[-1] == self.currP:
            if addedPoints[-1][0] == addedPoints[-2][0]:
                goOnX = False
        else:
            if addedPoints[0][0] == addedPoints[1][0]:
                goOnX = False

        if not goOnX:

            self.tempPoints = list(self.AllPoints)
            self.newShape1.append(self.currP)

            while len(self.tempPoints) > 0 and not self.stop:
                self.isFound = False
                if not self.searchRight(self.newShape1):
                    self.searchLeft(self.newShape1)

                if self.isFound:
                    if self.currP == self.newShape1[0]:
                        break
                    else:
                        self.newShape1.append(self.currP)
                        self.tempPoints.remove(self.currP)

                self.isFound = False
                if len(self.tempPoints) > 0:
                    if not self.searchDown(self.newShape1):
                        self.searchUp(self.newShape1)

                    if self.isFound:
                        if self.currP == self.newShape1[0]:
                            break
                        else:
                            self.newShape1.append(self.currP)
                            self.tempPoints.remove(self.currP)

            self.tempPoints = list(self.AllPoints)
            self.tempPoints.remove(existingPoints[0])

            if existingPoints[0] == addedPoints[0]:
                self.currP = addedPoints[-1]
            else:
                self.currP = addedPoints[0]

            self.newShape2.append(self.currP)

            while len(self.tempPoints) > 0 and not self.stop:
                self.isFound = False
                if not self.searchLeft(self.newShape2):
                    self.searchRight(self.newShape2)

                if self.isFound:
                    if self.currP == self.newShape2[0]:
                        break
                    else:
                        self.newShape2.append(self.currP)
                        self.tempPoints.remove(self.currP)
                else:

                    if len(self.newShape2) > 1:
                        if self.newShape2[-1] in self.tempPoints:
                            self.tempPoints.remove(self.newShape2[-1])
                        self.newShape2.remove(self.newShape2[-1])

                    self.currP = self.newShape2[-1]

                self.isFound = False
                if len(self.tempPoints) > 0:
                    if not self.searchDown(self.newShape2):
                        self.searchUp(self.newShape2)

                    if self.isFound:
                        if self.currP == self.newShape2[0]:
                            break
                        else:
                            self.newShape2.append(self.currP)
                            self.tempPoints.remove(self.currP)
                    else:
                        if len(self.newShape2) > 1:
                            if self.newShape2[-1] in self.tempPoints:
                                self.tempPoints.remove(self.newShape2[-1])
                            self.newShape2.remove(self.newShape2[-1])

                        self.currP = self.newShape2[-1]

        else:  # Search up and then down

            self.tempPoints = list(self.AllPoints)
            self.newShape1.append(self.currP)

            while len(self.tempPoints) > 0 and not self.stop:
                self.isFound = False
                if not self.searchUp(self.newShape1):
                    self.searchDown(self.newShape1)

                if self.isFound:
                    if self.currP == self.newShape1[0]:
                        break
                    else:
                        self.newShape1.append(self.currP)
                        self.tempPoints.remove(self.currP)

                self.isFound = False
                if len(self.tempPoints) > 0:
                    if not self.searchRight(self.newShape1):
                        self.searchLeft(self.newShape1)

                    if self.isFound:
                        if self.currP == self.newShape1[0]:
                            break
                        else:
                            self.newShape1.append(self.currP)
                            self.tempPoints.remove(self.currP)

            self.tempPoints = list(self.AllPoints)
            self.tempPoints.remove(existingPoints[0])
            if existingPoints[0] == addedPoints[0]:
                self.currP = addedPoints[-1]
            else:
                self.currP = addedPoints[0]

            self.newShape2.append(self.currP)

            while len(self.tempPoints) > 0 and not self.stop:
                self.isFound = False
                if not self.searchDown(self.newShape2):
                    self.searchUp(self.newShape2)

                if self.isFound:
                    if self.currP == self.newShape2[0]:
                        break
                    else:
                        self.newShape2.append(self.currP)
                        self.tempPoints.remove(self.currP)
                else:
                    if len(self.newShape2) > 1:
                        counter = 0
                        for tp in self.tempPoints:
                            if tp == self.newShape2[-1]:
                                self.tempPoints[counter] = (tp[0], tp[1],
                                                            False)
                            counter = counter + 1
                        self.tempPoints.append((self.newShape2[-1][0],
                                                self.newShape2[-1][1], False))
                        self.newShape2.remove(self.newShape2[-1])

                    self.currP = self.newShape2[-1]

                self.isFound = False
                if len(self.tempPoints) > 0:

                    if not self.searchRight(self.newShape2):
                        self.searchLeft(self.newShape2)

                    if self.isFound:
                        if self.currP == self.newShape2[0]:
                            break
                        else:
                            self.newShape2.append(self.currP)
                            self.tempPoints.remove(self.currP)
                    else:
                        if len(self.newShape2) > 1:
                            counter = 0
                            for tp in self.tempPoints:
                                if tp == self.newShape2[-1]:
                                    self.tempPoints[counter] = (tp[0], tp[1],
                                                                False)
                                counter = counter + 1
                            self.tempPoints.append(
                                (self.newShape2[-1][0], self.newShape2[-1][1],
                                 False))
                            self.newShape2.remove(self.newShape2[-1])
                        self.currP = self.newShape2[-1]

        tempShape = list(self.newShape1)

        pointNm = Point(self.GB.Enm.EnemyX + 8, self.GB.Enm.EnemyY + 8)
        polygon = Polygon(tempShape)

        if polygon.contains(pointNm):
            self.finishShape(self.newShape1)
            self.OldShape = list(self.newShape1)
            self.GB.ShapeArea = int(polygon.area)

            return self.newShape1
        else:
            polygon = Polygon(self.newShape2)
            self.GB.ShapeArea = int(polygon.area)

            self.finishShape(self.newShape2)
            self.OldShape = list(self.newShape2)
            return self.newShape2
def GeoFence(location, zone):
    polygon = Polygon(zone)
    lat = float(location.split(',')[0])
    long = float(location.split(',')[1])
    point = polygon.contains(Point(lat, long))
    return point
示例#22
0
    def Exist0(self):
        counter = 0
        self.currP = self.tempPoints[-1]
        goOnX = True

        for ln in self.GB.LinesPropertiesX:
            if ln[1] == self.currP[1]:
                if ln[2] < self.currP[0] < ln[3]:
                    goOnX = False

        if not goOnX:
            self.tempPoints = list(self.AllPoints)

            self.newShape1.append(self.currP)

            while len(self.tempPoints) > 0 and not self.stop:
                self.isFound = False
                if not self.searchRight(self.newShape1):
                    self.searchLeft(self.newShape1)

                if self.isFound:
                    if self.currP == self.newShape1[0]:
                        break
                    else:
                        self.newShape1.append(self.currP)
                        self.tempPoints.remove(self.currP)

                self.isFound = False
                if len(self.tempPoints) > 0:
                    if not self.searchDown(self.newShape1):
                        self.searchUp(self.newShape1)

                    if self.isFound:
                        if self.currP == self.newShape1[0]:
                            break
                        else:
                            self.newShape1.append(self.currP)
                            self.tempPoints.remove(self.currP)

            self.tempPoints = list(self.AllPoints)
            self.currP = self.tempPoints[-1]

            self.newShape2.append(self.currP)

            while len(self.tempPoints) > 0 and not self.stop:
                self.isFound = False
                if not self.searchLeft(self.newShape2):
                    self.searchRight(self.newShape2)

                if self.isFound:
                    if self.currP == self.newShape2[0]:
                        break
                    else:
                        self.newShape2.append(self.currP)
                        self.tempPoints.remove(self.currP)

                self.isFound = False
                if len(self.tempPoints) > 0:
                    if not self.searchDown(self.newShape2):
                        self.searchUp(self.newShape2)

                    if self.isFound:
                        if self.currP == self.newShape2[0]:
                            break
                        else:
                            self.newShape2.append(self.currP)
                            self.tempPoints.remove(self.currP)

        else:  # Search up and then down

            self.tempPoints = list(self.AllPoints)
            self.newShape1.append(self.currP)

            while len(self.tempPoints) > 0 and not self.stop:
                self.isFound = False
                if not self.searchUp(self.newShape1):
                    self.searchDown(self.newShape1)

                if self.isFound:
                    if self.currP == self.newShape1[0]:
                        break
                    else:
                        self.newShape1.append(self.currP)
                        self.tempPoints.remove(self.currP)

                self.isFound = False
                if len(self.tempPoints) > 0:

                    if not self.searchRight(self.newShape1):
                        self.searchLeft(self.newShape1)

                    if self.isFound:
                        if self.currP == self.newShape1[0]:
                            break
                        else:
                            self.newShape1.append(self.currP)
                            self.tempPoints.remove(self.currP)

            self.tempPoints = list(self.AllPoints)
            self.currP = self.tempPoints[-1]
            self.newShape2.append(self.currP)

            while len(self.tempPoints) > 0 and not self.stop:
                self.isFound = False
                if not self.searchDown(self.newShape2):
                    self.searchUp(self.newShape2)

                if self.isFound:
                    if self.currP == self.newShape1[0]:
                        break
                    else:
                        self.newShape2.append(self.currP)
                        self.tempPoints.remove(self.currP)

                self.isFound = False
                if len(self.tempPoints) > 0:

                    if not self.searchRight(self.newShape2):
                        self.searchLeft(self.newShape2)

                    if self.isFound:
                        if self.currP == self.newShape1[0]:
                            break
                        else:
                            self.newShape2.append(self.currP)
                            self.tempPoints.remove(self.currP)

        tempShape = list(self.newShape1)
        pointNm = Point(self.GB.Enm.EnemyX + 8, self.GB.Enm.EnemyY + 8)
        polygon = Polygon(tempShape)

        if polygon.contains(pointNm):
            self.finishShape(self.newShape1)
            self.GB.ShapeArea = int(polygon.area)

            self.OldShape = list(self.newShape1)
            return self.newShape1
        else:
            polygon = Polygon(self.newShape2)
            self.GB.ShapeArea = int(polygon.area)

            self.finishShape(self.newShape2)
            self.OldShape = list(self.newShape2)

            return self.newShape2
示例#23
0
def collide_pt(p):
    for poly in POLY_LIST:
        polygoly = Polygon([list(elem) for elem in poly])
        if polygoly.intersects(p):
            return True
    return False
示例#24
0
 def spriteinside(self,spritex,spritey):
     point = Point(spritex, spritey)
     points = self.getpoints()
     polygon = Polygon([points[0], points[1], points[2]])
     return polygon.contains(point)
示例#25
0
def ubungTest(request):

    t = get_template("ubung.html")
    if request.path == "/ubung/":
        q = Question.objects.get(my_order=1)
    else:
        q = Question.objects.get(uberschrift=request.path.split("/")[2])

    active = str(q.kapitel)
    kapitelliste = []
    linkliste = []
    for ubung in Question.objects.all():
        if str(ubung.kapitel) not in kapitelliste:
            kapitelliste.append(str(ubung.kapitel))
            linkliste.append("/ubung/" + str(ubung.uberschrift))

    c = {
        "question": q,
        "kapitelliste": zip(kapitelliste, linkliste),
        "active": active,
    }
    try:
        naechst = Question.objects.get(my_order=q.my_order + 1).uberschrift
        c["naechst"] = "/ubung/" + naechst
    except:
        pass
    try:
        zuruck = Question.objects.get(my_order=q.my_order - 1).uberschrift
        c["zuruck"] = "/ubung/" + zuruck
    except:
        pass

    gleich = q.uberschrift
    c["gleich"] = gleich
    if len(q.answer_set.all()) != 0:
        answers = {}
        answernumm = []
        i = 0
        for answer in q.answer_set.all():
            i = i + 1
            answers[str(answer.answer)] = answer.richtig
            answernumm.append(i)

        answerlist = answers.keys()
        if len(q.answer_set.filter(richtig=True)) < 2:
            c["singlechoice"] = "singlechoice"
        c["answerlist"] = answerlist
    elif q.coordinates != "":
        if request.method == "GET":
            if bool(request.GET.dict()):
                x, y = request.META["QUERY_STRING"].split(",")
                point = Point(int(x), int(y))
                polygonstr = q.coordinates
                polylist = []
                for coord in polygonstr.split(";"):
                    polylist.append(
                        (int(coord.split(",")[0]), int(coord.split(",")[1])))
                poly = Polygon(polylist)
                print(point)
                clicked = True
                clickrichtig = poly.contains(point)

                context["clicked"] = clicked
                context["clickrichtig"] = clickrichtig

        bildTestPath = "ubung/" + q.image
        c["bildTestPath"] = bildTestPath
    if request.user.is_authenticated():
        c["logged_in"] = True
    print(request.GET.getlist("choice"))
    try:
        givennum = []
        givenanswer = request.GET.getlist("choice")
        print(givenanswer)
        if givenanswer != []:
            richtigListe = []
            print(list(answers.values()))
            for i in range(len(list(answers.values()))):
                if list(answers.values()
                        )[i] == True and "choice" + str(i + 1) in givenanswer:
                    richtigListe.append(True)
                elif list(answers.values(
                ))[i] == False and "choice" + str(i + 1) not in givenanswer:
                    richtigListe.append(True)
                else:
                    richtigListe.append(False)

            print(richtigListe)
            c["richtig"] = not False in richtigListe
            c["falsch"] = False in richtigListe
        else:
            print("emppy")
            pass

    except:
        print("not woriking")
        pass
        # class UserForm(forms.Form):
        #     widget = forms.RadioSelect(answerneu)
        # form = UserForm
        # context["form"] = form
    html = t.render(c)
    return HttpResponse(html)
示例#26
0
    if linear_ring.is_ccw:
        print(f"{polygon} is already ccw")
        return polygon
    else:
        print(f"{polygon} was made ccw")
        return Polygon(list(linear_ring.coords)[::-1])


def y_monotonize(polygon):
    pass


# patch = Point(0.0, 0.0).buffer(10.0)
# print(patch.area)

poly = Polygon([(0, 0), (0, 2), (1, 1), (2, 2), (2, 0), (1, 0.8), (0, 0)])
poly = make_ccw(poly)
print(poly)

monotone_poly = Polygon([(0, 2), (1.5, 6), (3, 4), (1.5, 0), (1, 1)])
poly = make_ccw(monotone_poly)
print(monotone_poly)

myPoint = Point(1, 2)

#my_edges = get_edges(monotone_poly)
# plt.plot()
# plt.savefig("edges_poly.png")
# plt.close()
#print(is_y_monotone(monotone_poly))
示例#27
0
    def _get_merge_pairs(self, edgepair, group, monitorPrefix=""):
        """Get nest dfs and indices of which ones to merge (Internal)."""
        def _get_nests_slice(ridx=1):
            Nests = self.edge_contours[edgepair['roi%d-name' % ridx]]
            edgevar = "touches_edge-%s" % (edgepair['roi%d-edge' % ridx])
            Nests = Nests.loc[Nests.loc[:, edgevar] == 1, :]
            Nests = Nests.loc[Nests.loc[:, 'group'] == group, :]
            return Nests

        # Nests of the same label. The nest IDs are using the index of the
        # roi dataframe from the edge_nests dictionary
        Nests1 = _get_nests_slice(1)
        Nests2 = _get_nests_slice(2)

        # to avoid redoing things, keep all polygons in a list
        polygons1 = []
        nno1 = 0
        nno1Max = Nests1.shape[0]
        for nid1, nest1 in Nests1.iterrows():
            nno1 += 1
            self._print2("%s: edge1-nest %d of %d" % (
                monitorPrefix, nno1, nno1Max))
            try:
                coords = np.array(_parse_annot_coords(nest1))
                coords[:, 0] = coords[:, 0] + self.roiinfos[
                    edgepair['roi1-name']]['left']
                coords[:, 1] = coords[:, 1] + self.roiinfos[
                    edgepair['roi1-name']]['top']
                polygons1.append((nid1, Polygon(coords)))
            except Exception as e:
                self._print2(
                    "%s: edge1-nest %d of %d: Shapely Error (below)" % (
                        monitorPrefix, nno1, nno1Max))
                self._print2(e)

        # go through the "other" polygons to get merge list
        to_merge = DataFrame(columns=[
            'nest1-roiname', 'nest1-nid', 'nest2-roiname', 'nest2-nid'])
        nno2 = 0
        nno2Max = Nests2.shape[0]
        for nid2, nest2 in Nests2.iterrows():
            nno2 += 1
            try:
                coords = np.array(_parse_annot_coords(nest2))
                coords[:, 0] = coords[:, 0] + self.roiinfos[
                    edgepair['roi2-name']]['left']
                coords[:, 1] = coords[:, 1] + self.roiinfos[
                    edgepair['roi2-name']]['top']
                polygon2 = Polygon(coords)
            except Exception as e:
                self._print2(
                    "%s: edge2-nest %d of %d: Shapely Error (below)" % (
                        monitorPrefix, nno2, nno2Max))
                self._print2(e)
                continue

            nno1Max = len(polygons1)-1
            for nno1, poly1 in enumerate(polygons1):
                self._print2(
                    "%s: edge2-nest %d of %d: vs. edge1-nest %d of %d" % (
                        monitorPrefix, nno2, nno2Max, nno1+1, nno1Max+1))
                nid1, polygon1 = poly1
                if polygon1.distance(polygon2) < self.merge_thresh:
                    idx = to_merge.shape[0]
                    to_merge.loc[idx, 'nest1-roiname'] = edgepair['roi1-name']
                    to_merge.loc[idx, 'nest1-nid'] = nid1
                    to_merge.loc[idx, 'nest2-roiname'] = edgepair['roi2-name']
                    to_merge.loc[idx, 'nest2-nid'] = nid2

        return to_merge
示例#28
0
# yx_river = np.asarray([np.nan] * (ny * nx)).reshape(ny, nx) # initialize ny*nx array with nan value
# for icell in river_cells:
#     yx_river[grids[icell, 1], grids[icell, 0]] = 1

# material_h5.close()

# ## import river geometry

# In[10]:

river_geo = pd.read_csv(fname_river_geo)

# river_geo['x'] = (river_geo['x'] - model_origin[0])/1000
# river_geo['y'] = (river_geo['y'] - model_origin[1])/1000

polygon = Polygon(river_geo.loc[:, ["x", "y"]].values)
river_x, river_y = polygon.exterior.xy

# In[44]:

# sf = shp.Reader(fname_hf_shp)

# plt.figure()
# for shape in sf.shapeRecords():
#     x = [i[0] for i in shape.shape.points[:]]
#     y = [i[1] for i in shape.shape.points[:]]
#     plt.plot(x,y)

# # plot tracer contour

# In[22]:
示例#29
0
            idx_closest = np.argmin(np.abs(bottom_depth - z[idx_good]))
        else:
            continue

        if np.abs([idx_closest] - bottom_depth) <= 20:
            Sbot[j, i] = temp_vec[idx_good[idx_closest]]
        elif np.abs(z[idx_closest] - bottom_depth) <= 50:
            #print('used data located [30,50]m from bottom')
            Sbot[j, i] = temp_vec[idx_good[idx_closest]]

print(' -> Done!')

# Mask data outside Nafo div.
print('Mask according to NAFO division for ' + season)
# Polygons
polygon3K = Polygon(zip(nafo_div['3K']['lon'], nafo_div['3K']['lat']))
polygon3L = Polygon(zip(nafo_div['3L']['lon'], nafo_div['3L']['lat']))
polygon3N = Polygon(zip(nafo_div['3N']['lon'], nafo_div['3N']['lat']))
polygon3O = Polygon(zip(nafo_div['3O']['lon'], nafo_div['3O']['lat']))
polygon3Ps = Polygon(zip(nafo_div['3Ps']['lon'], nafo_div['3Ps']['lat']))
polygon2J = Polygon(zip(nafo_div['2J']['lon'], nafo_div['2J']['lat']))

# Contour of data to mask
contour_mask = np.load(
    '/home/cyrf0006/AZMP/state_reports/bottomT/100m_contour_labrador.npy')
polygon_mask = Polygon(contour_mask)

## if season == 'spring':
##     for i, xx in enumerate(lon_reg):
##         for j,yy in enumerate(lat_reg):
##             point = Point(lon_reg[i], lat_reg[j])
示例#30
0
count = -1
for i in range(np.shape(metaData)[0]):
    if os.path.exists("data/segmentationMasks/" +
                      metaData['SlideID - Cycle 2'][i] + '_CTX.yml'):
        with open(
                "data/segmentationMasks/" + metaData['SlideID - Cycle 2'][i] +
                '_CTX.yml', 'r') as stream:
            segmentationMasks = yaml.safe_load(stream)
        sectionNumber = metaData['Section Number'][i]
        if len(nested_lookup('wm', segmentationMasks)) > 0:
            count += 1
            positions = nested_lookup('position', segmentationMasks)
            firstSplit = str.split(positions[(2 * sectionNumber) - 2][0], ';')
            areaData['LeftCortex'][count] = Polygon(
                np.asarray([
                    str.split(firstSplit[i], ' ')
                    for i in range(len(firstSplit))
                ]).astype(np.float)).area
            firstSplit = str.split(positions[(2 * sectionNumber) - 1][0], ';')
            areaData['RightCortex'][count] = Polygon(
                np.asarray([
                    str.split(firstSplit[i], ' ')
                    for i in range(len(firstSplit))
                ]).astype(np.float)).area
            areaData['Index'][count] = i
            areaData['Genotype'][count] = metaData['Genotype'][i]
            areaData['MouseID'][count] = metaData['MouseID'][i]
            areaData['z-coordinate'][count] = metaData[
                'Figure Number - By Eye'][i]

# Plot size of Kptn and WT cortex segmentation masks area as function of z coordinate: