def test_graham_scan_t(self): # test the implementation of Graham scan res_1 = graham_scan([(4, 4), (5, 4), (4, 5), (5, 5), (5, 6), (6, 6), (5, 7), (6, 7), (6, 2), (7, 2), (6, 3), (7, 3)]) ans_1 = [(6, 2), (7, 2), (7, 3), (6, 7), (5, 7), (4, 5), (4, 4)] res_2 = graham_scan([(1, 2), (2, 2), (1, 3), (2, 3), (1, 5), (2, 5), (1, 6), (2, 6), (2, 6), (3, 6), (2, 7), (3, 7), (3, 3), (4, 3), (3, 4), (4, 4)]) ans_2 = [(1, 2), (2, 2), (4, 3), (4, 4), (3, 7), (2, 7), (1, 6)]
def test_graham_scan(self): points = generate_points() actual_hull = ch.graham_scan(points) expected_hull = get_expected_hull() self.assertEqual(actual_hull, expected_hull)
def _fill_mountain_1(self, h, h_coordinates): hull_verts = graham_scan(get_all_vertices( h_coordinates[h])) # all vertices of the convex hull mask = interpolate(self.m, self.n, hull_verts, use_wn=True) for r in range(self.m): for c in range(self.n): if mask[r][c] and self.terrain[r][c] != 2: self.terrain[r][c] = h
def getVectorRepresentation(filePath): ''' extracts coordinates from geojson File (for vector representation) \n input "filePath": type string, file path to geojson File \n returns extracted coordinates of content: type list, list of lists with length = 2 ''' #type list, contains all coordinates as tuples coordinates = [] #type list, contains everything extracted extracted = [] def extractAfterKeyword(searchParam, gjsonContent): ''' searches for the value fo the dict entry with keyword which is given as input \n input "searchParam": type string, keyword for which is searched in the dict \n input "gjsonContent": type dict, Content of geojson File ''' if type(gjsonContent) == dict: for keyContent, valueContent in gjsonContent.items(): if keyContent == searchParam: extracted.append(valueContent) if type(valueContent) == dict or type(valueContent) == list: extractAfterKeyword(searchParam, valueContent) if type(gjsonContent) == list: for element in gjsonContent: extractAfterKeyword(searchParam, element) def extractCoordinates(coordsList): ''' extract coordinates as tuples out of a some more lists (e.g. with Multipolygons) \n input "coordsList": type list, value of dict entry with key "coordinates" ''' if type(coordsList) == list and len(coordsList) == 2 and (type( coordsList[0]) == float or type( coordsList[0]) == int) and (type(coordsList[1]) == float or type(coordsList[1]) == int): coordinates.append(coordsList) elif type(coordsList) == list and len(coordsList) != 0: for value in coordsList: extractCoordinates(value) gjsonContent = convert3dto2d(filePath) extracted = [] extractAfterKeyword("coordinates", gjsonContent) extractCoordinates(extracted) if not coordinates: raise Exception( "No coordinates found in File. Vector Representation could not be extracted." ) #convex hull is formed out of coordinates coordinates = convex_hull.graham_scan(coordinates) return coordinates
def getVectorRepresentation(path): ''' abstract the geometry of the file with a polygon first: collects all the points of the file then: call the function that computes the polygon of it \n input "path": type string, file path to shapefile \n returns extracted coordinates of content from shapefiletype list, list of lists with length = 2, ''' try: if not '.shp' in path: shpPath = path[:path.rfind(".")+1] shpPath += "shp" if not hf.exists(shpPath): raise FileNotFoundError("Related shp-file could not be found!") else: path = shpPath with fiona.open(path) as datasetFiona: if datasetFiona is not None: coordinates = "" for x in datasetFiona: if 'geometry' in x: if 'coordinates' in x["geometry"]: if len(x["geometry"]["coordinates"]) > 0: coors = str(x["geometry"]["coordinates"][0]) coordinatesASString = coors[coors.find("(") : coors.rfind(")") + 1] if len(coordinatesASString) < 3 and len(x["geometry"]["coordinates"]) == 2: coordinates += "(" + str(x["geometry"]["coordinates"][0]) + ", " + str(x["geometry"]["coordinates"][1]) + ")" coordinates += coordinatesASString + ", " coordinates = coordinates[: len(coordinates) - 4] coordinates = coordinates.split("), (") for index, value in enumerate(coordinates): coordinates[index] = str(value).split(", ") for index, value in enumerate(coordinates): if len(value) != 2: print("Error: Coordinate does not have two values") try: coordinates[index][0] = float(value[0].replace("(", "").replace(")", "")) coordinates[index][1] = float(value[1].replace("(", "").replace(")", "")) except: print("Error: Value cannot be converted into float" + value[0]) coordinates = convex_hull.graham_scan(coordinates) return coordinates except Exception as e: pathWithoutEnding = path[:len(path)-4] if not (hf.exists(pathWithoutEnding + ".dbf") and hf.exists(pathWithoutEnding + ".shp") and \ hf.exists(pathWithoutEnding + ".shx")): raise Exception("One of the required files with the following ending are missing: .dbf, .shp or .shx") else: raise e raise Exception("The vector representaton could not be extracted from the file")
def getVectorRepFromFolder(mult_vec_rep): ''' computes vector representation from multiple vector representations stored in the array 'mult_vec_rep' (uses helpfunction) \n input "mult_vec_rep": type list, all vector representations from the files in the folder \n returns the vector representation of the files in the folder: type list, one vector representation of the files from folder ''' print( str(len(mult_vec_rep)) + " of " + str(len(fullPaths) - filesSkiped) + " supported Files have a vector representation.") if type(mult_vec_rep) == list: if len(mult_vec_rep) > 0: return convex_hull.graham_scan(mult_vec_rep) return None
def getVectorRepresentation(path): ''' abstracts the geometry of the file with a polygon first: collects all the points of the file then: call the function that computes the polygon of it \n input "path": type string, path to file which shall be extracted \n returns extracted coordinates of content: type list, list of lists with length = 2: type list ''' file = xarray.open_dataset(path) if file is not None: if 'coords' in file.to_dict(): if all(x in file.to_dict()["coords"] for x in ['lat', 'lon']): if 'data' in file.to_dict()["coords"][ "lat"] and 'data' in file.to_dict()["coords"]["lon"]: lats = file.to_dict()["coords"]["lat"]["data"] lons = file.to_dict()["coords"]["lon"]["data"] if not ('lats' in locals() and 'lons' in locals()): ncDataset = NCDataset(path) if 'latitude' in ncDataset.variables: latitudes = ncDataset.variables["latitude"][:] lats = [] for x in latitudes: lats.append(x) if 'longitude' in ncDataset.variables: longitudes = ncDataset.variables["longitude"][:] lons = [] for x in longitudes: lons.append(x) if 'lats' in locals() and 'lons' in locals(): coordinates = {'lat': lats, 'lon': lons} if len(lats) == len(lons): referenced_coordinates = [] for index, val in enumerate(lats): referenced_coordinates.append([lons[index], val]) coordinates = convex_hull.graham_scan(coordinates) else: raise Exception( "The numer auf lat-points and lon-points is not equal, thus a vector representation cannot be computed." ) return coordinates raise Exception( "The vector representaton could not be extracted from the file")
from convex_hull import graham_scan import matplotlib.pyplot as plt # Original points. points = [(4.4, 14), (6.7, 15.25), (6.9, 12.8), (2.1, 11.1), (9.5, 14.9), (13.2, 11.9), (10.3, 12.3), (6.8, 9.5), (3.3, 7.7), (0.6, 5.1), (5.3, 2.4), (8.45, 4.7), (11.5, 9.6), (13.8, 7.3), (12.9, 3.1), (11, 1.1)] convex_hull = graham_scan(points) x_values = [] y_values = [] for i in range(0, len(convex_hull)): x_values.append(convex_hull[i][0]) y_values.append(convex_hull[i][1]) x_values.append(convex_hull[0][0]) y_values.append(convex_hull[0][1]) plt.plot(x_values, y_values, '-d', color='c', markersize=8, markerfacecolor='m', markeredgecolor='m', label='Path of the convex hull') x_values = []
def test_graham_scan(self): for points, expected in zip(self.points, self.expected): result = graham_scan(points) print 'result: {}\nexpected: {}'.format(result, expected)
def getVectorRepresentation(path): ''' abstract the geometry of the file with a polygon first: collects all the points of the file then: call the function that computes the polygon of it \n input "path": type string, file path to geopackage file \n returns extracted coordinates of content: type list, list of lists with length = 2 ''' coordinates = [] with fiona.open(path) as datasetFiona: for shapeElement in datasetFiona: if 'geometry' in shapeElement: if shapeElement["geometry"] is not None: if 'coordinates' in shapeElement["geometry"]: element = shapeElement["geometry"]["coordinates"] def getCoordinatesFromArray(element): if len(element) == 1: if type(element[0]) == list: if type(element[0][0]) == list: for y in element[0][0]: coordinates.append([y[0], y[1]]) elif type(element[0][0]) == tuple: coordinates.append([ element[0][0][0], element[0][0][1] ]) else: raise Exception( "Filetype could not be handled") if len(element) == 2: if type(element[0]) == list: if type(element[0][0]) == list: for y in element[0][0]: coordinates.append([y[0], y[1]]) elif type(element[0][0]) == tuple: coordinates.append([ element[0][0][0], element[0][0][1] ]) else: raise Exception( "Filetype could not be handled") if type(element[1]) == list: if type(element[0][0]) == list: for y in element[0][0]: coordinates.append([y[0], y[1]]) elif type(element[0][0]) == tuple: coordinates.append([ element[0][0][0], element[0][0][1] ]) else: raise Exception( "Filetype could not be handled") if type(element[0]) == float and type( element[1]) == float: coordinates.append( [element[0], element[1]]) getCoordinatesFromArray(element) if len(coordinates) > 0: # pop the last dimension in case the coordinates are 3D for index, points in enumerate(coordinates): if type(points) == list: if len(points) == 3: coordinates[index] = [points[0], points[1]] coordinates = convex_hull.graham_scan(coordinates) return coordinates else: raise Exception( "The vector representaton could not be extracted from the file")
def test_graham_scan(self): for points, expected in zip(self.points, self.expected): result = graham_scan(points) print 'result: {}\nexpected: {}'.format(result, expected)