def isInsidePolygon(point, polyPoints): # adapted from http://stackoverflow.com/questions/36399381/whats-the-fastest-way-of-checking-if-a-point-is-inside-a-polygon-in-python shapelyPoint = Point(point['lat'], point['lon']) shapelyPolygon = Polygon(polyPoints) isInside = shapelyPolygon.contains(shapelyPoint) #print(isInside) return isInside
def isInsideAnyOfPolygons(point, polys): for poly in polys: shapelyPoint = Point(point['lat'], point['lon']) shapelyPolygon = Polygon(poly) isInside = shapelyPolygon.contains(shapelyPoint) if isInside: return True return False
def is_clicked(self, click, handles): from shapely.geometry import Point from shapely.geometry.polygon import Polygon point = Point(*click) polygon = Polygon([handles["1BL"].position, handles["2TL"].position, handles["3TR"].position, handles["4BR"].position]) return polygon.contains(point)
def decoderSTSC(self, date_ini, polygon, anima): '''Filter the data from STSC inside an specific polygon''' stsc_data = self.redemet.get_produto_stsc(date_ini, anima) if stsc_data != None: stsc_points = stsc_data['stsc'][0] polygon_shp = Polygon(polygon) for _pnt in stsc_points: point = (float(_pnt['la']), float(_pnt['lo'])) point_shp = Point(point) if polygon_shp.contains(point_shp): self.point_list.append(point) else: print('Error DecoderSTSC!')
def find_tiles_inside(param, domain, oceanonly=True): """Determine which tiles are inside `domain` The function uses `corners` the list of corners for each tile """ p = Polygon(domain) tileslist = [] for tile, c in param.corners.items(): if (not oceanonly) or (not param.missing[tile]): q = Polygon(c) if p.overlaps(q) or p.contains(q): tileslist += [tile] return tileslist
def find_point_in_polygon_p(cells=None,point=None): ''' loop all the cells and find the polygon that contains the point,with printing the center ''' for i in cells: polygon=SPolygon(i['vertices']) if polygon.contains(point): #print("find") axes=plt.gca() axes.add_patch(Polygon(i['vertices'],closed=True,\ facecolor='b',alpha=0.2)) print(i)
def filter_polygons_points_intersection(polygon_contours, center_coords): """https://github.com/huyhoang17/machine-learning-snippets/blob/master/filter_polygons_points_intersection.py """ # checking if polygon contains point final_cons = [] for con in polygon_contours: polygon = Polygon(zip(con[::2], con[1::2])) for center in center_coords: point = Point(center[1], center[0]) if polygon.contains(point): final_cons.append(con) break return final_cons
def list_all_points_inside_polyg(polyg_choords, vision_radius=0.5): polygon = Polygon(polyg_choords) inside_points = [] xmin, ymin, xmax, ymax = polygon.bounds try: for i in range(int(ymin), int(ymax) + 1, int(vision_radius * 2)): for j in range(int(xmin), int(xmax) + 1, int(vision_radius * 2)): if polygon.contains(Point((j, i))): inside_points.append((j, i)) except ValueError: print( "Please, choose a 'vision_radius' multiple of 0.5 (where 0.5 is the minimum value)" ) return inside_points
def check_suburb(coordinate): # return the name of suburb that contains the coordinate name = '' for feature in suburb_info_json['features']: lat_lon_list = feature['geometry']['coordinates'][0][ 0] # the coordinates of a suburb suburb_name = feature['properties']['name'] # the name of the suburb polygon = Polygon(lat_lon_list) point = Point(coordinate[0], coordinate[1]) if polygon.contains(point): name = suburb_name return name
class Region: """ class for managing particular regions. """ def __init__(self, region_kml): self.name = region_kml.name s = str(region_kml.MultiGeometry.Polygon.outerBoundaryIs.LinearRing.coordinates) self.coords = [map(float, l.split(',')) for l in s.strip().split('\n')] self.polygon = Polygon(self.coords) def contains(self, lat, lon): """ does this region contain the point at (lat, lon)? """ p = Point(lon, lat) return self.polygon.contains(p)
def build_prm(obstacles,start,goal,n,k,ax): #prm algo v = set() e = set() while len(v) < n: x = random.randint(0,600) y = random.randint(0,600) point = Point(x,y) #delect collisions no_collisions = [] for obstacle in obstacles: polygon = Polygon(obstacle) if not polygon.contains(point): no_collisions.append(True) else: no_collisions.append(False) if all(no_collisions): v.add((x,y)) #find neighbors V_2d = [list(coord) for coord in v] for q in v: n_q = kNeighbors(q,V_2d,k) for q_prime in n_q: if (q,q_prime) not in e and hasCollision([q,q_prime],obstacles)==False: e.add((q,q_prime)) #connect start and goal points to nearest q in v closest_to_start = kNeighbors(start,V_2d,len(V_2d)) closest_to_goal = kNeighbors(goal,V_2d,len(V_2d)) for q in closest_to_start: if hasCollision([q,start],obstacles)==False: e.add((q,start)) break for q in closest_to_goal: if hasCollision([q,goal],obstacles)==False: e.add((q,goal)) break #draw the graph for edge in e: (line_xs,line_ys) = zip(*edge) ax.add_line(lines.Line2D(line_xs,line_ys,linewidth=1,color='red')) #find shortest path and highlight it shortest_path = get_shortest_path(v,e,start,goal) for edge in shortest_path: (line_xs,line_ys) = zip(*edge) ax.add_line(lines.Line2D(line_xs,line_ys,linewidth=3,color='blue')) return v,e
def is_in_square_table(table_coor, point): # table_coor, 按照顺时针方向的桌子顶点 # point, 待计算点坐标 例,Point(Neck[0], Neck[1]) # 调用实例 # table_back = [(ellipse_cali_info['back_top_left'][0], ellipse_cali_info['back_top_left'][1]), (ellipse_cali_info['back_top_right'][0], ellipse_cali_info['back_top_right'][1]), # check_1 = is_in_square_table(table_back, Point(Neck[0], Neck[1])) polygon = Polygon(table_coor) inout = polygon.contains(point) if inout: return True else: return False
def find_sections_Mmax(f_for_sherifs, zones_json): # Find the max length for each section nb_sections = len(f_for_sherifs) for si in range(nb_sections): f_for_sherifs[si]["max_possible_length"] = 10000. f_for_sherifs[si]["max_possible_Mmax"] = 11. # Load the zones with open(zones_json) as f: gj = geojson.load(f) zones_length = gj['features'] # Loop on the zone to find the sections within for zone_i in zones_length: poly = [] for pt in zone_i["geometry"]["coordinates"][0][0]: poly.append((pt[0], pt[1])) polygon = Polygon(poly) max_i = zone_i["properties"]["max_length"] Mmax_i = zone_i["properties"]["max_possible_Mmax"] for si in range(nb_sections): if f_for_sherifs[si]["max_possible_length"] > max_i: lons_si = f_for_sherifs[si]['lons'] lats_si = f_for_sherifs[si]['lats'] for lon_i, lat_i in zip(lons_si, lats_si): if polygon.contains(Point(lon_i, lat_i)): f_for_sherifs[si]["max_possible_length"] = max_i for si in range(nb_sections): if f_for_sherifs[si]["max_possible_Mmax"] > Mmax_i: lons_si = f_for_sherifs[si]['lons'] lats_si = f_for_sherifs[si]['lats'] for lon_i, lat_i in zip(lons_si, lats_si): if polygon.contains(Point(lon_i, lat_i)): f_for_sherifs[si]["max_possible_Mmax"] = Mmax_i return f_for_sherifs
def addBackProjectRegion(self, bgLayer, origPointsLayer, border, srcArea): newPointsLayer = pointslayer.PointsLayer(isPointSelect=True) origPts = origPointsLayer.getPoints() borderPoly = Polygon(border) for i in origPts: pt = origPts[i] xy = pt["xy"] self.originalImagePlanePositions[i] = { "xy": [xy[0], xy[1]], "label": pt["label"], "timedelay": pt["timedelay"] } if borderPoly.contains(Point(*xy)): bpXY = ( self.traceThetaApproximately(np.array(xy) * ANGLE_ARCSEC) / ANGLE_ARCSEC).tolist() newPointsLayer.setPoint(i, bpXY, pt["label"]) origLayerId = origPointsLayer.getUuid() if not origLayerId in self.originalPointInfo: self.originalPointInfo[origLayerId] = {} self.originalPointInfo[origLayerId][ i] = newPointsLayer.getPoint( i) # Use this to check what to update newScene = scenes.PointsSingleLayerScene(newPointsLayer, bgLayer) newScene.setAllowTriangulation(False) layerItem, _ = newScene.getCurrentItemAndLayer() layerItem.updatePoints() newView = base.GraphicsView(newScene, parent=self.ui.tabWidget) self.ui.tabWidget.addTab(newView, bgLayer.getName()) self.bpViews[newView] = { "scene": newScene, "newlayer": newPointsLayer, "origlayer": origPointsLayer, "srcarea": srcArea, "border": border } isPixels = self.ui.m_pointPixelsBox.isChecked() newScene.setPointSizePixelSize(self.ui.m_pointPixelSize.value( )) if isPixels else newScene.setPointSizeSceneSize( self.ui.m_pointArcsecSize.value()) newScene.setPointSizeFixed(self.ui.m_pointPixelsBox.isChecked()) self._setViewRange(newView, srcArea[0], srcArea[1])
def main(): cwd = os.getcwd() # !!! INIT PHASE !!! Took too long, that's why we saved our results # start_time = time.time() # df = create_commit_df(cwd) # df.to_hdf('100_days_commits.h5', key='commit') # print("--- %s seconds ---" % (time.time() - start_time)) for stdin in sys.stdin: file = str.strip(stdin) with open(os.path.join(cwd, file)) as f: source_code = f.read() sc_tokens = tokenize_sc(source_code) df = pd.read_hdf('./100_days_commits.h5') # load data from init phase vocab = create_vocab(df.tokens, top=256) df = df.groupby('author.name', as_index=False).agg({'tokens': sum}) author_bow_df = create_bow_df(df, vocab) vecs = [ np.array(list(bow.values())) for bow in author_bow_df.bow.values ] sc_bow = create_bow(sc_tokens, vocab) sc_vec = [np.array(list(sc_bow.values()))] tsne = TSNE(n_components=2, random_state=128) vecs_2d = tsne.fit_transform(vecs + sc_vec) vor = Voronoi(vecs_2d[:-1]) regions, vertices = voronoi_finite_polygons_2d(vor) offset = 10 point = Point(np.array(vecs_2d[-1])) voronoi_plot_2d(vor) for i, region in enumerate(regions): polygon_points = vertices[region] polygon = Polygon(polygon_points) if polygon.contains(point): print(author_bow_df.iloc[i]['author.name']) plt.fill(*zip(*polygon_points), alpha=0.4) break plt.plot(vecs_2d[:-1, 0], vecs_2d[:-1, 1], 'ko') plt.xlim(vor.min_bound[0] - offset, vor.max_bound[0] + offset) plt.ylim(vor.min_bound[1] - offset, vor.max_bound[1] + offset) plt.plot(point.x, point.y, 'rs') plt.show()
def parse_geo_result(plat, plong): ppoint = Point(float(plong), float(plat)) #geo-result.json file downloaded from https://maps.elastic.co with open(basedirectory + "/geo-result.json") as f: docket_content = f.read() datann = json.loads(docket_content) pResult = 0 mygss = '' myiso = '' myregname = '' pcount = 0 #i = (len(datann['features'])) for dtt in datann['features']: mycoords = dtt['geometry'] if dtt['geometry']['type'] == 'Polygon': polygon = Polygon(dtt['geometry']['coordinates'][0]) if polygon.contains(ppoint): pcount = pcount + 1 mygss = dtt['properties']['gss'] myiso = dtt['properties']['iso_3166_2'] myregname = dtt['properties']['label_en'] if pcount == 2: return mygss, myiso, myregname #return dtt['properties']['gss'], dtt['properties']['iso_3166_2'], dtt['properties']['label_en'] else: for drr in dtt['geometry']['coordinates'][0]: polygon = Polygon(drr) if polygon.contains(ppoint): pcount = pcount + 1 mygss = dtt['properties']['gss'] myiso = dtt['properties']['iso_3166_2'] myregname = dtt['properties']['label_en'] if pcount == 2: return mygss, myiso, myregname #return dtt['properties']['gss'], dtt['properties']['iso_3166_2'], dtt['properties']['label_en'] return mygss, myiso, myregname
def calculate_suns_position(self, day): """ This method will be responsible for creating a polygon with all the galaxy's planets and determining whether the sun is inside of it If the sun is inside, also returns the polygons perimeter """ positions = [] for p in self.planets: positions.append(p.calculate_planet_position(day)) poly = Polygon(positions) if poly.contains(Point(0, 0)): return (PlanetsPosition.SUN_INSIDE_POLYGON, poly.length) return (PlanetsPosition.SUN_NOT_INSIDE_POLYGON, poly.length)
def water_mass_id(T, S): """Returns the water mass associated to the given T-S properties. """ wm = water_masses_def() point = Point(S, T) wm_id = '' for name in wm.keys(): polygon = Polygon(wm.get(name)) if polygon.contains(point): wm_id = name return wm_id
def checkIfObjectInArea(objectPos: Point, field: Field): """Checks if object in area of map. Args: field: polygon defining the area objectPos (list): object x and y coordinates Returns: bool: True if object in area """ point = SPoint(objectPos.reprTuple()) (topLeft, topRight, bottomLeft, bottomRight) = field.reprTuple() polygon = SPolygon((bottomLeft, topLeft, topRight, bottomRight)) return polygon.contains(point)
def check_gv_word_in_azure(gv_info, azure_info): poly_coordinates = [ tuple(azure_info["boundingBox"]["p1"]), (azure_info["boundingBox"]["p3"][0], azure_info["boundingBox"]["p1"][1]), tuple(azure_info["boundingBox"]["p3"]), (azure_info["boundingBox"]["p1"][0], azure_info["boundingBox"]["p3"][1]) ] point_coordinates = (int( (gv_info[0] + gv_info[2]) / 2), int((gv_info[1] + gv_info[5]) / 2)) point = Point(point_coordinates) polygon = Polygon(poly_coordinates) # print(polygon.contains(point)) return polygon.contains(point)
def remove_fully_contained_signs(squares): signs_do_not_contain = [] for first_sign in squares: contains = False s1 = Polygon(first_sign) for second_sign in squares: if (first_sign == second_sign).all(): continue s2 = Polygon(second_sign) contains = s1.contains(s2) if contains: break if not contains: signs_do_not_contain.append(first_sign) return signs_do_not_contain
def CoordsInBoundingbox(coordinate_list, boundingbox): result_list = [] if not isinstance(boundingbox[0], tuple): for coord in coordinate_list: if coord[0] > float(boundingbox[0]) and coord[0] < float( boundingbox[1]): if coord[1] > float(boundingbox[2]) and coord[1] < float( boundingbox[3]): result_list.append(coord) else: polygon = Polygon(boundingbox) for coord in coordinate_list: if polygon.contains(Point(coord[0], coord[1])): result_list.append(coord) return result_list
def Homography(tgtCorners, srcCorners, affArray, changeElements, image, srcImage, final, poly): residual = 0 newLocation = [] for i in range(0, len(tgtCorners)): cordMat = [[srcCorners[i][0]], [srcCorners[i][1]], [1]] h20 = changeElements[6][0] h21 = changeElements[7][0] D = h20 * srcCorners[i][0] + h21 * srcCorners[i][1] + 1 tgtCod = np.floor(np.matmul(affArray, cordMat)) # print(tgtLoc) x = int(tgtCod[0][0] / D) y = int(tgtCod[1][0] / D) residual += np.linalg.norm([[tgtCorners[i][0] - x], [tgtCorners[i][1] - y]]) newLocation.append([x, y]) if final == True: #print(srcCorners) polygon = Polygon(poly) for i in range(0, len(image)): for j in range(0, len(image[0])): point = Point(i, j) if polygon.contains(point): cordMat = [[i], [j], [1]] tgtLoc = np.floor(np.matmul(affArray, cordMat)) h20 = changeElements[6][0] h21 = changeElements[7][0] D = h20 * i + h21 * j + 1 x = int(round(tgtLoc[0][0] / D)) y = int(round(tgtLoc[1][0] / D)) if x < len(srcImage) and y < len( srcImage[0]) and x >= 0 and y >= 0: image[i][j][0] = srcImage[x][y][0] image[i][j][1] = srcImage[x][y][1] image[i][j][2] = srcImage[x][y][2] return (residual, newLocation)
def detect(self, image, tVal=25): # compute the absolute difference between the background model # and the image passed in, then threshold the delta image delta = cv2.absdiff(self.bg.astype("uint8"), image) thresh = cv2.threshold(delta, tVal, 255, cv2.THRESH_BINARY)[1] # perform a series of erosions and dilations to remove small # blobs thresh = cv2.erode(thresh, None, iterations=2) thresh = cv2.dilate(thresh, None, iterations=2) # find contours in the thresholded image and initialize the # minimum and maximum bounding box regions for motion cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) cnts = imutils.grab_contours(cnts) (minX, minY) = (np.inf, np.inf) (maxX, maxY) = (-np.inf, -np.inf) # if no contours were found, return None # if len(cnts) == 0: # return None # otherwise, loop over the contours rect = [] for c in cnts: # compute the bounding box of the contour and use it to # update the minimum and maximum bounding box regions if cv2.contourArea(c) < 300: continue (x, y, w, h) = cv2.boundingRect(c) # (minX, minY) = (min(minX, x), min(minY, y)) # (maxX, maxY) = (max(maxX, x + w), max(maxY, y + h)) mid_point_x = (x + x + w) / 2 mid_point_y = (y + y + h) / 2 point = Point(mid_point_x, mid_point_y) for pts in self.region: polygon = Polygon(pts) if polygon.contains(point) == False: continue rect.append({'x': x, 'y': y, 'w': w, 'h': h}) if len(rect) == 0: return None # otherwise, return a tuple of the thresholded image along # with bounding box return (thresh, rect)
def write_correlation_catalog(City_Latitude, City_Longitude, Circle_Radius, earthquake_depth, MagLo, completeness_mag): input_file = open("USGS_WorldWide.catalog", "r") output_file = open("EQ_Correlation.catalog", "w") # Compute vertices that define the circle around the city lng_circle_dg, lat_circle_dg = MCUtilities.createCircleAroundWithRadius( City_Latitude, City_Longitude, Circle_Radius) number_polygon_vertices = len(lng_circle_dg) point_list = [] for i in range(number_polygon_vertices): point_list.append((float(lat_circle_dg[i]), float(lng_circle_dg[i]))) polygon = Polygon(point_list) # print point_list # for line in input_file: items = line.strip().split() dep = items[6] mag = items[5] eq_lat = items[4] eq_lng = items[3] point = Point((float(eq_lat), float(eq_lng))) if (float(dep) <= float(earthquake_depth) and float(mag) >= float(completeness_mag) and polygon.contains(point) == True): print(items[0], items[1], items[2], items[3], items[4], items[5], items[6], file=output_file) output_file.close() input_file.close() return
def check_update_tables_conf(final_json, cord, conf, style): update = True p = Point(cord) for i in range(len(final_json['tables'])): # CURRENTLY ONLY 4 SIDED TABLES # str table number********* when saved p1, p3 = final_json['table_coordinates'][i + 1][:2], \ final_json['table_coordinates'][i + 1][2:] p2 = [p3[0], p1[1]] p4 = [p1[0], p3[1]] polygon_coordinates_list = [p1, p2, p3, p4] temp_polygon = Polygon(polygon_coordinates_list) if temp_polygon.contains(p): for cell in final_json['tables'][i + 1]: bb = final_json['tables'][i + 1][cell]['boundingBox'] if cord[0] in range(bb['p1'][0], bb['p3'][0]) and cord[1] in range( bb['p1'][1], bb['p3'][1]): words_bb = final_json['tables'][i + 1][cell]['words'] for j, bb in enumerate( [el['boundingBox'] for el in words_bb]): if cord[0] in range(min(bb['p1'][0], bb['p3'][0]), max(bb['p1'][0], bb['p3'][0])) and \ cord[1] in range(min(bb['p1'][1], bb['p3'][1]), max(bb['p1'][1], bb['p3'][1])): final_json['tables'][ i + 1][cell]['words'][j]['azure_conf'] = conf final_json['tables'][ i + 1][cell]['words'][j]['style'] = style update = True # return True, final_json else: pass else: pass else: pass if not update: return False, final_json else: return True, final_json
def isStateValid(state): global newPoseX global newPoseY point = Point(state.getX(), state.getY()) TrueList = [] for i in range(len(newPoseX)): polygon = Polygon([ (newPoseX[i][0], newPoseY[i][0]),\ (newPoseX[i][1], newPoseY[i][1]),\ (newPoseX[i][2], newPoseY[i][2]),\ (newPoseX[i][3], newPoseY[i][3]) ]) if (polygon.contains(point)): TrueList.append(0) else: TrueList.append(1) return not any(x is 0 for x in TrueList)
def env_viewed(xhist, yhist,zhist, square): viewed = {(x,y):'unviewed' for x in range(int(square[0][0]),int(square[1][0])+10,10) for y in range(int(square[0][1]),int(square[2][1])+10,10)} for i,x in enumerate(xhist[1:len(xhist)]): w,h,d = viewable_area(zhist[i+1]) viewed_area = rect(xhist[i],yhist[i],xhist[i+1],yhist[i+1], w+5,h+5) if abs(xhist[i]-xhist[i+1]) + abs(yhist[i]-yhist[i+1]) > 0.1 and w >0.01: polygon=Polygon(viewed_area) #plt.plot(*polygon.exterior.xy) (displays area to debug code) #plt.plot([xhist[i],xhist[i+1]],[yhist[i],yhist[i+1]]) if not polygon.is_valid: print('invalid points') for spot in viewed: if polygon.contains(Point(spot)): viewed[spot]=d return viewed
def clearance(self, state): global newPoseX global newPoseY point = Point(state[0], state[1]) TrueList = [] for i in range(len(newPoseX)): polygon = Polygon([ (newPoseX[i][0], newPoseY[i][0]),\ (newPoseX[i][1], newPoseY[i][1]),\ (newPoseX[i][2], newPoseY[i][2]),\ (newPoseX[i][3], newPoseY[i][3]) ]) if (polygon.contains(point)): TrueList.append(0) else: TrueList.append(1) return not any(x is 0 for x in TrueList)
def mark_outdoor_points(self, triangulation): hull_points = list() for p_idx in self.convex_hull.vertices: hull_points.append( (self.usr_points[p_idx][0], self.usr_points[p_idx][1])) poly = Polygon(hull_points) outdoor = [False] * len(triangulation[VERTICES]) for i in range(len(outdoor)): outdoor[i] = not (triangulation[SRC_POINT_MARKERS][i] or poly.contains(Point(triangulation[VERTICES][i]))) return [ outdoor[i] and all([ outdoor[v] or triangulation[SRC_POINT_MARKERS][v] for v in triangulation[GRAPH][i] ]) for i in range(len(outdoor)) ]
def group_in_range(group_id, range_id): if group_id in cdi.active_players_by_group_id.keys(): pos = cdi.active_players_by_group_id[group_id].unit_pos # pos = db.env_group_dict[group_id].lead_pos # print(pos) group_point = Point(pos['x'], pos['z']) range_boundary_point = range_polygon[range_id] poly = Polygon(range_boundary_point) if poly.contains(group_point): return True else: return False else: return False
def look_for_ice(planes, icebergs, k): """Retrieve, for each plane, the visible ice.""" for p in planes: if p.active(k): fov = Polygon(p.fov) p.findings = [ i for i in range(icebergs.positions.shape[1]) if fov.contains( Point(icebergs.positions[0, i], icebergs.positions[1, i])) ] p.scan = lmb.Scan( lmb.sensors.SquareSensor(p.fov, p.p_detect, p.lambdaB), [ lmb.GaussianReport( np.random.multivariate_normal(icebergs.positions[:, i], Pz_true), p.Pz, i) for i in p.findings ])
def calcTimeToStayInPosition(centroidPath, footprint): polygon = Polygon(footprint) cPath = centroidPath.copy() # First centroid assumed to be in footprint: increment by update interval time_s = deltaTT_s centroidContained = True while (centroidContained == True and len(cPath) > 0): nextCentroid = cPath.pop(0) point = Point(nextCentroid) # Check if the next centroid is in footprint if (polygon.contains(point)): # Since it is, increment by update interval time_s = time_s + deltaTT_s else: centroidContained = False return time_s
class VoronoiData: def __init__(self, hydrants): self.vor = Voronoi(hydrants, incremental=True) self.poly = Polygon([(float(x.split(', ')[0]), float(x.split(', ')[1])) for x in open('coords.txt').read().split('\n')[:-1]]) def polygons(self): l={} for point_index, region_index in enumerate(self.vor.point_region): region = self.vor.regions[region_index] if region == [] or -1 in region: continue points = self.vor.vertices[region] l[tuple(self.vor.points[point_index])] = points return l def valid(self, candidate): #lat, long = candidate #return (lat <= 41.861571 and lat >= 41.772414) and (long <= -71.369694 and long >= -71.472667) return self.poly.contains(Point(*candidate)) def most_vulnerable_point(self): l = self.polygons() candidates = [] for center, points in l.items(): farthest = None farthestDistance = 0.0 for p in points: dist = (p[0] - center[0])**2 + (p[1] - center[1])**2 if dist > farthestDistance: farthestDistance = dist farthest = p candidates.append((farthestDistance, farthest)) candidates = sorted(candidates, reverse=True) for candidate in candidates: if self.valid(candidate[1]): return candidate raise Exception("vulnerable point not found") def add_hydrant(self, p): self.vor.add_points([p[1]])
def h__getEccentricityAndOrientation(x_mc,y_mc,xRange_all,yRange_all,gridAspectRatio_all,N_GRID_POINTS,eccentricity,orientation,run_mask): # h__getEccentricityAndOrientation for iFrame in np.nditer(utils.find(run_mask)): cur_aspect_ratio = gridAspectRatio_all[iFrame] # x_range = xRange_all[iFrame] #y_range = yRange_all[iFrame] #------------------------------------------------------ cur_cx = x_mc[:, iFrame] cur_cy = y_mc[:, iFrame] poly = Polygon(zip(cur_cx, cur_cy)) if cur_aspect_ratio > 1: # x size is larger so scale down the number of grid points in # the y direction n1 = N_GRID_POINTS n2 = np.round(N_GRID_POINTS / cur_aspect_ratio) else: # y size is larger so scale down the number of grid points in # the x direction n1 = np.round(N_GRID_POINTS * cur_aspect_ratio) n2 = N_GRID_POINTS wtf1 = np.linspace(np.min(x_mc[:, iFrame]), np.max(x_mc[:, iFrame]), num=n1) wtf2 = np.linspace(np.min(y_mc[:, iFrame]), np.max(y_mc[:, iFrame]), num=n2) m, n = np.meshgrid(wtf1, wtf2) n_points = m.size m_lin = m.reshape(n_points) n_lin = n.reshape(n_points) in_worm = np.zeros(n_points, dtype=np.bool) for i in range(n_points): p = Point(m_lin[i], n_lin[i]) # try: in_worm[i] = poly.contains(p) # except ValueError: # import pdb # pdb.set_trace() x = m_lin[in_worm] y = n_lin[in_worm] eccentricity[iFrame],orientation[iFrame] = h__calculateSingleValues(x,y) # First eccentricity value should be: 0.9743 """ TODO: Finish this plot(xOutline_mc(:,iFrame),yOutline_mc(:,iFrame),'g-o') hold on scatter(x,y,'r') hold off axis equal title(sprintf('%d',iFrame)) pause """ return (eccentricity,orientation)
def coords_to_ccg(lng, lat): """ takes coordinates and returns ccg name and code """ import json import operator import ast from shapely.geometry import Point from shapely.geometry.polygon import Polygon fd = open("ccg_kml_dicts") sd = fd.read() fd.close() ldData = ast.literal_eval(sd) lNames = [ldData[i]['CCG'] for i in range(len(ldData))] lCodes = [ldData[i]['CCG Code'] for i in range(len(ldData))] lBoundaries = [ldData[i]['boundary'] for i in range(len(ldData))] ldUnsorted = [] #clean up boundaries for i in range(len(lBoundaries)): lBoundaries[i] = lBoundaries[i].split("\n") lx = [] ly = [] for j in range(len(lBoundaries[i])): lBoundaries[i][j] = lBoundaries[i][j].strip() lx.append(float(lBoundaries[i][j].split(",")[0])) lx.append(float(lBoundaries[i][j].split(",")[0])) ly.append(float(lBoundaries[i][j].split(",")[1])) ly.append(float(lBoundaries[i][j].split(",")[1])) lBoundaries[i][j] = (float(lBoundaries[i][j].split(",")[0]), float(lBoundaries[i][j].split(",")[1])) fXmid = ((min(lx))+(max(lx)))/2 fYmid = ((min(ly))+(max(ly)))/2 ldUnsorted.append({ "ccg_name": lNames[i], "dist": ((fXmid - lat)**2 + (fYmid - lng)**2)**0.5, "boundary": lBoundaries[i], "ccg_code": lCodes[i] }) #order all boundaries by how close they are to the lat lng ldSorted = sorted(ldUnsorted, key=lambda t:t['dist']) lNamesSorted = [ldSorted[i]["ccg_name"] for i in range(len(ldSorted))] lCodesSorted = [ldSorted[i]["ccg_code"] for i in range(len(ldSorted))] lBoundariesSorted = [ldSorted[i]["boundary"] for i in range(len(ldSorted))] for iB in range(len(lBoundariesSorted)): coordPoint = Point(lat, lng) coordPolygon = Polygon(lBoundariesSorted[iB]) if coordPolygon.contains(coordPoint): sName = lNamesSorted[iB] sCode = lCodesSorted[iB] return sName,sCode return None,None
polygon_bottom_exclude2 = Polygon(lines_bottom_exclude2) x = 0.0 y = 0.0 for x in range(int((board_width + x_offset * 2) / spacing)): x *= spacing x += x_offset for y in range(int((board_height + y_offset * 2) / spacing)): y *= spacing y += y_offset tp = Point(x, y) make_via = True if not polygon_top.contains(tp): make_via = False if not polygon_bottom.contains(tp): make_via = False if polygon_top_exclude.contains(tp): make_via = False if polygon_top_exclude2.contains(tp): make_via = False if polygon_bottom_exclude.contains(tp): make_via = False if polygon_bottom_exclude2.contains(tp): make_via = False # x y thickness clearance mask drillholedia name number flags if make_via: print ('Via[%fmm %fmm 0.7000mm 20.00mil 0.0000 0.3000mm "" "thermal(0S,5S)"]' % (x, y))
def create_initial_positions3(xdivide=10, ydivide=10,lon0=55.,lon1=56.,lat0=-21.5, lat1=-20.5 ,start=1, zdivide=10, k0=56., k1=60., crop=False, outfile='initial_positions.txt', domain_dir='/Users/agn/Data/NEMO0083'): lons = np.linspace(lon0, lon1, xdivide+1) lats = np.linspace(lat0, lat1, ydivide+1) kdepths = np.linspace(k0, k1, zdivide+1) path = pjoin(domain_dir,'mask.nc') print('path for mask file', path) with Dataset(path) as f: Ndlat = f.variables['nav_lat'] meridional = Ndlat[:,0] jeq = meridional.searchsorted(0.) Ndlon = f.variables['nav_lon'] zonal = Ndlon[jeq,:] ibreak = np.argmax(zonal) + 1 if lon0 > zonal[0] and lon1 < zonal[ibreak-1]: zonal_part = zonal[:ibreak] iadd = 0 elif lon0 > zonal[ibreak] and lon1 < zonal[-1]: zonal_part = zonal[ibreak:] iadd = ibreak else: sys.exit('lon0 and lon1 bracket dateline; not implemented yet') i0 = zonal_part.searchsorted(lon0) - 1 + iadd i1 = zonal_part.searchsorted(lon1) + 1 + iadd imid = (i0 + i1)//2 meridional = Ndlat[:,imid] j0 = meridional.searchsorted(lat0) - 1 j1 = meridional.searchsorted(lat1) + 1 jmid = (j0 + j1)//2 zonal = Ndlon[jmid,:] dlon = np.diff(zonal) ibreak = np.argmin(dlon) ri = np.interp(lons, zonal[i0:i1], np.arange(i0,i1,dtype=zonal.dtype)) rj = np.interp(lats, meridional[j0:j1], np.arange(j0,j1,dtype=meridional.dtype)) print('specified longitudes are','\n',lons) print('i values are','\n',ri + 1. -.5) print('specified latitudes are','\n',lats) print('j values are','\n',rj + 1. -.5) print('k values are','\n',kdepths) i00, i11 = i0 - 1, i1 + 1 j00, j11 = j0 - 1, j1 + 1 tmask = ~(f.variables['tmask'][0,:,j00:j11,i00:i11].astype(np.bool)) uvmask = tmask[:,1:-1,1:-1] + tmask[:,:-2,1:-1] + tmask[:,2:,1:-1] \ + tmask[:,1:-1,:-2] + tmask[:,1:-1,2:] if crop: inner_circle, outer_circle, fuel_circle, box = get_circles() polygon = Polygon( zip(*box) ) npoints = 0 with open(outfile, 'w') as f: for kdepth in kdepths: for y, lat in zip(rj, lats): for x, lon in zip(ri, lons): if (not crop) or (crop and polygon.contains(Point(lon, lat))): i, j, k = int(x), int(y), int(kdepth) if not uvmask[k-1,j-j0, i-i0]: # ri and rj are c-indices relative to T-cells # subtract .5 to produce u v indices as required by ariane # ... and add 1 to convert from C to fortran numbering f.write('%10g%10g%10g%10g%5g\n' %(x + 1. -.5, y + 1. -.5 , kdepth, start, 1)) npoints +=1 print('# of sea points started is %g out of %g' % (npoints, len(rj)*len(ri)*len(kdepths)))
def calculate_erection_operation_time(project_specs, project_data, construct_duration, operational_construction_time): """ Calculates operation time required for each type of equipment included in project data. :param project_specs: data frame with project details (from project input file) :param project_data: dictionary of data frames for each of the csv files loaded for the project :param construct_duration: duration of construction (in months) :param operational_construction_time: operational hours of construction :return: list of possible cranes that could be used to erect tower and turbine """ erection_construction_time = 1/3 * construct_duration print('Calculating operation time for erection...') # group project data by project ID project = project_specs # for components in component list determine if base or topping project_data['components']['Operation'] = project_data['components']['Lift height m'] > (float(project['Hub height m'] * project['Breakpoint between base and topping (percent)'])) boolean_dictionary = {True: 'Top', False: 'Base'} project_data['components']['Operation'] = project_data['components']['Operation'].map(boolean_dictionary) # create groups for operations top_v_base = project_data['components'].groupby(['Operation']) # group crane data by boom system and crane name to get distinct cranes crane_grouped = project_data['crane_specs'].groupby(['Equipment name', 'Crane name', 'Boom system', 'Crane capacity tonne']) crane_poly = pd.DataFrame(columns=['Equipment name', 'Crane name', 'Boom system', 'Crane capacity tonne', 'Crane poly']) for name, crane in crane_grouped: crane = crane.reset_index(drop=True) x = crane['Max capacity tonne'] y = crane['Hub height m'] wind_speed = min(crane['Max wind speed m per s']) hoist_speed = min(crane['Hoist speed m per min']) travel_speed = min(crane['Speed of travel km per hr']) setup_time = max(crane['Setup time hr']) crew_type = crane['Crew type ID'][0] #todo: fix this so it's not a hack... need to rethink data structure - right now just picking first crew type - this is correct because same for all crane/boom combinations but we should come up with a better way to do it polygon = Polygon([(0, 0), (0, max(y)), (min(x), max(y)), (max(x), min(y)), (max(x), 0)]) df = pd.DataFrame([[name[0], name[1], name[2], name[3], wind_speed, setup_time, hoist_speed, travel_speed, crew_type, polygon]], columns=['Equipment name', 'Crane name', 'Boom system', 'Crane capacity tonne', 'Max wind speed m per s', 'Setup time hr', 'Hoist speed m per min', 'Speed of travel km per hr', 'Crew type ID', 'Crane poly']) crane_poly = crane_poly.append(df, sort=True) # loop through operation type (topping vs. base) rownew = pd.Series() component_max_speed = pd.DataFrame() crane_poly_new = crane_poly for name_operation, component_group in top_v_base: # calculate polygon for crane capacity and check if component can be lifted by each crane without wind loading for idx, crane in crane_poly.iterrows(): polygon = crane['Crane poly'] for component in component_group['Component']: # get weight and height of component in each component group component_only = component_group.where(component_group['Component'] == component).dropna(thresh=1) point = Point(component_only['Mass tonne'], component_only['Lift height m']) crane['Lift boolean {component}'.format(component=component)] = polygon.contains(point) rownew = rownew.append(crane) bool_list = list() for component in component_group['Component']: if crane['Lift boolean {component}'.format(component=component)] is False: crane_bool = False else: crane_bool = True bool_list.append(crane_bool) # calculate max permissible wind speed # equation for calculating permissible wind speed: # vmax = max_TAB * sqrt(1.2 * mh / aw), where # mh = hoist load # aw = area exposed to wind = surface area * coeff drag # 1.2 = constant in m^2 / t # vmax_tab = maximum load speed per load chart # source: pg. 33 of Liebherr mh = component_group['Mass tonne'] aw = component_group['Surface area sq m'] * component_group['Coeff drag'] vmax_tab = crane['Max wind speed m per s'] vmax_calc = vmax_tab * sqrt(1.2 * mh / aw) # if vmax_calc is less than vmax_tab then vmax_calc, otherwise vmax_tab (based on pg. 33 of Liebherr) # todo: check vmax - should it be set to calculated value rather than vmax_tab if greater? component_group_new = pd.DataFrame(component_group, columns=list(component_group.columns.values) + ['vmax', 'Crane name', 'Boom system', 'crane_bool']) component_group_new['vmax'] = list((min(vmax_tab, x) for x in vmax_calc)) component_group_new['Crane name'] = crane['Crane name'] component_group_new['Boom system'] = crane['Boom system'] component_group_new['crane_bool'] = bool_list component_max_speed = component_max_speed.append(component_group_new, sort=True) crane_poly_new['Crane bool {operation}'.format(operation=name_operation)] = min(bool_list) crane_poly = crane_poly_new # join crane polygon to crane specs crane_component = pd.merge(crane_poly, component_max_speed, on=['Crane name', 'Boom system']) # select only cranes that could lift the component possible_cranes = crane_component.where(crane_component['crane_bool'] == True).dropna(thresh=1).reset_index(drop=True) # calculate travel time per cycle turbine_spacing = float(project['Turbine spacing (times rotor diameter)'] * project['Rotor diameter m'] * km_per_m) turbine_num = float(project['Number of turbines']) possible_cranes['Travel time hr'] = turbine_spacing / possible_cranes['Speed of travel km per hr'] * turbine_num # calculate erection time possible_cranes['Operation time hr'] = ((possible_cranes['Lift height m'] / possible_cranes['Hoist speed m per min'] * hr_per_min) + (possible_cranes['Cycle time installation hrs']) ) * turbine_num # store setup time possible_cranes['Setup time hr'] = possible_cranes['Setup time hr'] * turbine_num erection_time = possible_cranes.groupby(['Crane name', 'Equipment name', 'Crane capacity tonne', 'Crew type ID', 'Boom system', 'Operation'])['Operation time hr'].sum() travel_time = possible_cranes.groupby(['Crane name', 'Equipment name', 'Crane capacity tonne', 'Crew type ID', 'Boom system', 'Operation'])['Travel time hr'].max() setup_time = possible_cranes.groupby(['Crane name', 'Equipment name', 'Crane capacity tonne', 'Crew type ID', 'Boom system', 'Operation'])['Setup time hr'].max() rental_time_without_weather = erection_time + travel_time + setup_time operation_time = rental_time_without_weather.reset_index() operation_time = operation_time.rename(columns={0: 'Operation time all turbines hrs'}) operation_time['Operational construct days'] = (operation_time['Operation time all turbines hrs'] / operational_construction_time) # if more than one crew needed to complete within construction duration then assume that all construction happens # within that window and use that time frame for weather delays; if not, use the number of days calculated operation_time['time_construct_bool'] = (operation_time['Operational construct days'] > erection_construction_time * 30) boolean_dictionary = {True: erection_construction_time * 30, False: np.NAN} operation_time['time_construct_bool'] = operation_time['time_construct_bool'].map(boolean_dictionary) operation_time['Time construct days'] = operation_time[['time_construct_bool', 'Operational construct days']].min(axis=1) #print(possible_cranes[['Crane name', 'Component', 'Operation time hr', 'Operation']]) for operation, component_group in top_v_base: unique_component_crane = possible_cranes.loc[possible_cranes['Operation'] == operation]['Component'].unique() for component in component_group['Component']: if component not in unique_component_crane: error = 1 sys.exit('Error: Unable to find installation crane for {} operation and {} component'.format(operation, component)) else: error = 0 if error == 0: print('Crane(s) found for all components for {} installation'.format(operation)) return possible_cranes, operation_time, error
def get_eccentricity_and_orientation(contour_x, contour_y): """ get_eccentricity [eccentricity, orientation] = seg_worm.feature_helpers.posture.getEccentricity(xOutline, yOutline, gridSize) Given x and y coordinates of the outline of a region of interest, fill the outline with a grid of evenly spaced points and use these points in a center of mass calculation to calculate the eccentricity and orientation of the equivalent ellipse. Placing points in the contour is a well known computer science problem known as the Point-in-Polygon problem. http://en.wikipedia.org/wiki/Point_in_polygon This function became a lot more complicated in an attempt to make it go much faster. The complication comes from the simplication that can be made when the worm doesn't bend back on itself at all. OldName: getEccentricity.m Inputs: ======================================================================= xOutline : [96 x num_frames] The x coordinates of the contour. In particular the contour starts at the head and goes to the tail and then back to the head (although no points are redundant) yOutline : [96 x num_frames] The y coordinates of the contour " " N_ECCENTRICITY (a constant from config.py): (scalar) The # of points to place in the long dimension. More points gives a more accurate estimate of the ellipse but increases the calculation time. Outputs: a namedtuple containing: ======================================================================= eccentricity - [1 x num_frames] The eccentricity of the equivalent ellipse orientation - [1 x num_frames] The orientation angle of the equivalent ellipse Nature Methods Description ======================================================================= Eccentricity. ------------------ The eccentricity of the worm’s posture is measured using the eccentricity of an equivalent ellipse to the worm’s filled contour. The orientation of the major axis for the equivalent ellipse is used in computing the amplitude, wavelength, and track length (described below). Status ======================================================================= The code below is finished although I want to break it up into smaller functions. I also need to submit a bug report for the inpoly FEX code. Translation of: SegwormMatlabClasses / +seg_worm / +feature_helpers / +posture / getEccentricity.m """ t_obj = time.time() N_GRID_POINTS = 50 #TODO: Get from config ... x_range_all = np.ptp(contour_x,axis=0) y_range_all = np.ptp(contour_y,axis=0) x_mc = contour_x - np.mean(contour_x,axis=0) #mc - mean centered y_mc = contour_y - np.mean(contour_y,axis=0) grid_aspect_ratio = x_range_all/y_range_all #run_mask = np.logical_not(np.isnan(grid_aspect_ratio)) n_frames = len(x_range_all) eccentricity = np.empty(n_frames) eccentricity[:] = np.NAN orientation = np.empty(n_frames) orientation[:] = np.NAN #h__getEccentricityAndOrientation for iFrame in range(n_frames): cur_aspect_ratio = grid_aspect_ratio[iFrame] #------------------------------------------------------ if not np.isnan(cur_aspect_ratio): cur_cx = x_mc[:,iFrame] cur_cy = y_mc[:,iFrame] poly = Polygon(zip(cur_cx,cur_cy)) if cur_aspect_ratio > 1: #x size is larger so scale down the number of grid points in the y direction n1 = N_GRID_POINTS n2 = np.round(N_GRID_POINTS / cur_aspect_ratio) else: #y size is larger so scale down the number of grid points in the x direction n1 = np.round(N_GRID_POINTS * cur_aspect_ratio) n2 = N_GRID_POINTS wtf1 = np.linspace(np.min(x_mc[:,iFrame]), np.max(x_mc[:,iFrame]), num=n1); wtf2 = np.linspace(np.min(y_mc[:,iFrame]), np.max(y_mc[:,iFrame]), num=n2); m,n = np.meshgrid( wtf1 , wtf2 ); n_points = m.size m_lin = m.reshape(n_points) n_lin = n.reshape(n_points) in_worm = np.zeros(n_points,dtype=np.bool) for i in range(n_points): p = Point(m_lin[i],n_lin[i]) # try: in_worm[i] = poly.contains(p) # except ValueError: # import pdb # pdb.set_trace() x = m_lin[in_worm] y = n_lin[in_worm] """ TODO: Finish this plot(xOutline_mc(:,iFrame),yOutline_mc(:,iFrame),'g-o') hold on scatter(x,y,'r') hold off axis equal title(sprintf('%d',iFrame)) pause """ #First eccentricity value should be: 0.9743 #h__calculateSingleValues N = float(len(x)) # Calculate normalized second central moments for the region. uxx = np.sum(x*x)/N uyy = np.sum(y*y)/N uxy = np.sum(x*y)/N # Calculate major axis length, minor axis length, and eccentricity. common = np.sqrt((uxx - uyy)**2 + 4*(uxy**2)) majorAxisLength = 2*np.sqrt(2)*np.sqrt(uxx + uyy + common) minorAxisLength = 2*np.sqrt(2)*np.sqrt(uxx + uyy - common) eccentricity[iFrame] = 2*np.sqrt((majorAxisLength/2)**2 - (minorAxisLength/2)**2) / majorAxisLength # Calculate orientation. if (uyy > uxx): num = uyy - uxx + np.sqrt((uyy - uxx)**2 + 4*uxy**2) den = 2*uxy else: num = 2*uxy den = uxx - uyy + np.sqrt((uxx - uyy)**2 + 4*uxy**2) orientation[iFrame] = (180/np.pi) * np.arctan(num/den) #[eccentricity(iFrame),orientation(iFrame)] = h__calculateSingleValues(x,y); elapsed_time = time.time() - t_obj print('Elapsed time in seconds for eccentricity: %d' % elapsed_time) return (eccentricity,orientation)