コード例 #1
0
 def transform(self, srid_dest: int = None) -> BaseGeometry:
     crs_orig = pyproj.CRS(f'EPSG:{self.__class__.srid()}')
     crs_dest = pyproj.CRS(f'EPSG:{srid_dest}')
     project = pyproj.Transformer.from_crs(crs_orig,
                                           crs_dest,
                                           always_xy=True).transform
     return transform(project, self.get_base_geom())
コード例 #2
0
    def get_distance_to_closest_road(self, lat, lon):
        '''
        Returns the distance in metres from the nearest road  - 1km radius
         i.e. closest road type, closest distance, 
        '''
        try:

            G = ox.graph_from_point((lat, lon),
                                    dist=1000,
                                    network_type='drive')
            gdf = ox.graph_to_gdfs(G, nodes=False, fill_edge_geometry=True)
            gdf.to_crs(epsg=3310, inplace=True)
            gdf = gdf.reset_index(
            )  ## to ensure the values of u & v are in the columns
            # convert point to utm in order to get distance in metres
            wgs84_pt = Point(lon, lat)
            wgs84 = pyproj.CRS('EPSG:4326')
            utm = pyproj.CRS('EPSG:3310')
            project = pyproj.Transformer.from_crs(wgs84, utm,
                                                  always_xy=True).transform
            utm_point = transform(project, wgs84_pt)
            roads = gdf[['geometry', 'u', 'v', 'highway']].values.tolist()
            roads_with_distances = [(road, utm_point.distance(road[0]))
                                    for road in roads]
            roads_with_distances = sorted(roads_with_distances,
                                          key=lambda x: x[1])
            closest_road = roads_with_distances[0]
            closest_distance = round(closest_road[1], 2)

        except Exception as ex:
            #closest_road_type = None
            closest_distance = None
            print(ex)

        return closest_distance
コード例 #3
0
def convert_crs_point(point_x, point_y, in_proj, out_proj):
    """
    Change the coordinate system of a lat, lon point.

    Parameters
    ----------
    point_x : int
        Longitude coordinate.
    point_y : int
        Latitude coordinate.
    in_proj : str
        Coordinate system to transform from.
    out_proj : str
        Coordinate system to transform to.

    Returns
    ----------
    AoI_point : shapely Point
        Lat, lon point in new coordinate system.
    """
    in_pt = Point(point_x, point_y)
    in_proj = pyproj.CRS(in_proj)
    out_proj = pyproj.CRS(out_proj)
    project = pyproj.Transformer.from_crs(in_proj, out_proj,
                                          always_xy=True).transform
    AoI_point = transform(project, in_pt)
    return AoI_point
コード例 #4
0
def count_bus_stops(mlon, mlat, bus_dict):
    '''
        Делаем подсчет автобусных остановок в радиусе 500м от метро
        На вход берем координаты стани=ции метро и словарь с координатами автобусных остановок
        В функции сначала преобразовываем координаты (в градусах) из СК WGS84 (EPSG:4326) в СК World Mercator (EPSG:3395) в метрах
        Затем ищем расстояние между точками. Если расстояние <=500м, то увеличиваем счетчик станций
        Вывод - количество автобусных остановок около метро
    '''
    count_bus = 0
    # Точка метро, преобразовываем в геометрический объект
    wgs84_metro = Point(mlat, mlon)

    wgs84 = pyproj.CRS('EPSG:4326')  # параметры СК WGS84
    mercmetr = pyproj.CRS('EPSG:3395')  # параметры СК World Mercator

    project = pyproj.Transformer.from_crs(
        wgs84, mercmetr, always_xy=True
    ).transform  # параметры трансформации СК из WGS84 в World Mercator
    # Трансформируем координаты метро
    metro_merc_proj = transform(project, wgs84_metro)

    #Начинаме обход словаря со всеми остановками
    for bbuss in list(bus_dict.keys()):
        wgs84_bus = Point(bus_dict[bbuss]['lat'], bus_dict[bbuss]['lon'])
        # Трансформируем координаты автобусной остановки
        bus_merc_proj = transform(project, wgs84_bus)

        # Ищем расстояние между точками метро и автобусной остановкой, если <=500м, то мы увеличивает счетчик остановок на 1
        if metro_merc_proj.distance(bus_merc_proj) <= 500.0:
            count_bus += 1
    return count_bus
コード例 #5
0
def edge_detection(tiffs, refgeoms):
    logger = logging.getLogger('root')
    wgs84 = pyproj.CRS('EPSG:4326')
    utm = pyproj.CRS('EPSG:32724')
    utm2wgs84 = pyproj.Transformer.from_crs(utm, wgs84,
                                            always_xy=True).transform
    for abs_path in tiffs:
        tif_filename = os.path.split(abs_path)[-1]
        productName = '_'.join(tif_filename[:-4].split('_')[:9])
        if os.path.exists(
                os.path.join(edgeOut, productName, tif_filename[:-4] +
                             '_projected_edges.finished')) | os.path.exists(
                                 os.path.join(
                                     edgeOut, productName,
                                     tif_filename[:-4] + '_NA_SAR.finished')):
            continue
        id = edge_classification(tif_filename)
        if id == -1:
            open(
                os.path.join(edgeOut, productName,
                             tif_filename[:-4] + '_NA_SAR.finished'),
                'w').close()
            continue
        skeleton, out_transform = morphological_transformations(
            tif_filename, refgeoms[int(id)], utm2wgs84)
        geojson_file_name = save_edge_coordinates(skeleton, tif_filename,
                                                  out_transform)
        open(
            os.path.join(edgeOut, productName,
                         tif_filename[:-4] + '_projected_edges.finished'),
            'w').close()
コード例 #6
0
def transform_coordinates(x, y, epsg_in, epsg_out):
    """
    Transform between any coordinate system.

    **Requires `pyproj`** - install using pip.

    Args:
        x : float / 1D array
            x coordinates (may be in degrees or metres/eastings)
        y : float / 1D array
            y coordinates (may be in degrees or metres/northings)
        epsg_in : int
            CRS of x and y coordinates
        epsg_out : int
            CRS of output

    Returns:
        x_out : float / list of floats
            x coordinates projected in `epsg_out`
        y_out : float / list of floats
            y coordinates projected in `epsg_out`
    """
    import pyproj

    proj_in = pyproj.CRS("EPSG:" + str(epsg_in))
    proj_out = pyproj.CRS("EPSG:" + str(epsg_out))
    transformer = pyproj.Transformer.from_crs(proj_in,
                                              proj_out,
                                              always_xy=True)
    return transformer.transform(x, y)
コード例 #7
0
    def get_distance_to_closest_trunk(self, lat, lon):
        '''
        Returns the distance in metres from the nearest trunk road - 10km radius
        '''
        try:
            G = ox.graph_from_point((lat, lon),
                                    dist=30000,
                                    network_type='drive')
            gdf = ox.graph_to_gdfs(G, nodes=False, fill_edge_geometry=True)
            gdf.to_crs(epsg=3310, inplace=True)
            new_gdf = gdf[gdf['highway'] == 'trunk']

            if new_gdf.shape[0] == 0:
                closest_distance = None
            else:
                wgs84_pt = Point(lon, lat)
                wgs84 = pyproj.CRS('EPSG:4326')
                utm = pyproj.CRS('EPSG:3310')
                project = pyproj.Transformer.from_crs(wgs84,
                                                      utm,
                                                      always_xy=True).transform
                utm_point = transform(project, wgs84_pt)

                roads = new_gdf[['geometry', 'u', 'v']].values.tolist()
                roads_with_distances = [(road, utm_point.distance(road[0]))
                                        for road in roads]
                roads_with_distances = sorted(roads_with_distances,
                                              key=lambda x: x[1])
                closest_road = roads_with_distances[0]
                closest_distance = round(closest_road[1], 2)
        except:
            closest_distance = None
        return closest_distance
コード例 #8
0
    def post(self):
        """
        Return the area of a polygon in m²
        """

        try:
            # projection = partial(
            #     pyproj.transform,
            #     pyproj.Proj('epsg:4269'),
            #     pyproj.Proj('epsg:5070')
            # )

            projection = pyproj.Transformer.from_crs(pyproj.CRS("epsg:4326"),
                                                     pyproj.CRS("epsg:5070"),
                                                     always_xy=True).transform

            return transform(projection,
                             Polygon(
                                 request.json["geometry"]["coordinates"])).area
        except Exception as err:
            abort(
                HTTPStatus.UNPROCESSABLE_ENTITY,
                message="The GeoJSON polygon couldn't be processed.",
                error=err,
            )
コード例 #9
0
def calib_params_closest_point(multipoint, selected_rows, lat_lon_file,
                               calib_file, outfile):
    """
    calib_params_closest_point finds the closest calibration points to the lat,lon
    test points in the area of interest.
    :param multipoint: shapely multipoint object of the calibrated points
    :param selected_rows: row numbers of calibrated points (based on input csv file)
    :param lat_lon_file: csv file with the point geometry objects of the test points in
    the area of interest
    :param calib_file: csv file with the parameters for each calibrated point
    :param outfile: name of csv file with the parameters of the closest calibration points
    to the test points
    """
    points_df = pd.read_csv(lat_lon_file, index_col=None)

    full_calibration_df = pd.read_csv(calib_file, index_col=None)

    closest_points_df = pd.DataFrame(columns=full_calibration_df.columns[1:])
    # add extra lat lon columns
    closest_points_df['lat_test'] = ""
    closest_points_df['lon_test'] = ""
    closest_points_df['lat_calib'] = ""
    closest_points_df['lon_calib'] = ""
    points_df['geometry'] = points_df['geometry'].apply(wkt.loads)
    points_gdf = gpd.GeoDataFrame(points_df, crs='epsg:4326')

    for i in range(len(points_df)):
        #point = Point(515854, 4.551284e+06)
        wgs84_pt = points_gdf['geometry'][i]
        # reproject point
        AoI_proj = pyproj.CRS('EPSG:32633')
        wgs84 = pyproj.CRS('EPSG:4326')
        project = pyproj.Transformer.from_crs(wgs84, AoI_proj,
                                              always_xy=True).transform
        AoI_point = transform(project, wgs84_pt)

        # this prints out the point closest to our list of points
        closest_cal_point = nearest_points(multipoint, AoI_point)[0]

        # note that Z is not the altitude but the row number in the initial dataframe... need to figure out a better way to factor this in.
        calibration_params_index = list(selected_rows[
            selected_rows['X'] == closest_cal_point.x].index.values)
        calibration_parameters_selection = int(
            selected_rows['Z'][calibration_params_index])

        calibration_parameters = full_calibration_df.iloc[[
            calibration_parameters_selection
        ]]

        # save the parameters to a new file with only the point we want
        calibration_parameters = calibration_parameters.drop(
            calibration_parameters.columns[[0]], axis=1)

        closest_points_df.loc[i] = calibration_parameters.iloc[0]
        closest_points_df['lat_test'].loc[i] = AoI_point.y
        closest_points_df['lon_test'].loc[i] = AoI_point.x
        closest_points_df['lat_calib'].loc[i] = closest_cal_point.y
        closest_points_df['lon_calib'].loc[i] = closest_cal_point.x
    closest_points_df.to_csv(outfile, index=False)
コード例 #10
0
def wgs2laea(p):
    wgs84 = pyproj.CRS('EPSG:4326')
    rd = pyproj.CRS(
        '+proj=laea +lat_0=51 +lon_0=9.5 +x_0=0 +y_0=0 +ellps=GRS80 +units=m +no_defs'
    )
    project = pyproj.Transformer.from_crs(wgs84, rd, always_xy=True)
    p = transform(project.transform, p)
    return (p)
コード例 #11
0
def convert_coordinates(lon, lat):
    # Define the Rijksdriehoek projection system (EPSG 28992)
    wgs84=pyproj.CRS(source_epsg) # LatLon with WGS84 datum used by GPS units and Google Earth 
    utm_12N=pyproj.CRS(dest_epsg) # UK Ordnance Survey, 1936 datum 

    lon, lat = pyproj.transform(wgs84, utm_12N, lat, lon)
    
    return lon, lat
コード例 #12
0
def handleNearestOSMWays(lat, lon, type):
    """

    @param lat:
    @param lon:
    @param type:
    @return:
    """
    # see: https://gis.stackexchange.com/a/80898
    # Doc: https://github.com/mvexel/overpass-api-python-wrapper
    # Create overpass API connection, with a timeout time
    api = overpass.API(timeout=15)

    # see: https://shapely.readthedocs.io/en/stable/manual.html#other-transformations
    # Set GCS and projection to be applied: EPSG:3310 NAD83 / California Albers, units are meters
    wgs84 = pyproj.CRS('EPSG:4326')
    calAlb = pyproj.CRS('EPSG:3310')
    # Create transformation object
    project = pyproj.Transformer.from_crs(wgs84, calAlb, always_xy=True).transform

    # transform input coord to PCS, shapely takes coords in X,Y
    inputCoord = transform(project, Point(float(lon), float(lat)))
    # Dict that holds results
    resDict = {}
    # radius list, meters
    radList = (10, 100, 1000, 5000, 10000, 100000)
    for rad in radList:
        # print(f"trying search radius: {rad}")
        # around query
        # req expression : https://gis.stackexchange.com/questions/341746/what-is-a-correct-overpass-turbo-query-for-getting-all-streets-in-a-city

        # Get nearest road, result will always be used:
        roadQ = api.get(f'way["tiger:cfcc"]["name"][!"cycleway"](around:{rad},{lat},{lon})', verbosity='geom')
        # print(f"Len is: {len(roadQ.features)}")
        # Check if a road was found, if not go to the next radius, always want a road result
        if len(roadQ.features) > 0:
            # print("Populating Dict!")
            resDict = {}
            nearestRoad = getNearestWay(roadQ, project, inputCoord)
            resDict["Road"] = nearestRoad
            # print(nearestRoad)
            if type == "Road_Cycling":
                # Same as road query but can include cycling ways, bike paths, etc
                cycleQ = api.get(f'way["highway"]["name"](around:{rad},{lat},{lon})', verbosity='geom')
                nearestRoute = getNearestWay(cycleQ, project, inputCoord)
                resDict["Route"] = nearestRoute
            # elif type in ("MTB", "Walk", "Hike", "Trail"):
            elif type in ['Toro Park','Fort Ord', 'UCSC Trails', 'Soquel Demo','Kern Canyon']:
                # same as road query but can catch all types of named ways
                trailQ = api.get(f'way["name"](around:{rad},{lat},{lon})', verbosity='geom')
                nearestTrail = getNearestWay(trailQ, project, inputCoord)
                resDict["Route"] = nearestTrail
            else:
                resDict["Route"] = [None,None]
            return resDict
    return ["No Nearby Road!", "999999"]
コード例 #13
0
ファイル: match.py プロジェクト: llsshh1985/geonumpy
def mp2pm(boxs, m1, prj1, prj2, m2, t1=lambda x: x, t2=lambda x: x):
    p1 = osr.SpatialReference()
    p1.ImportFromProj4(pyproj.CRS(prj1).to_proj4())
    p2 = osr.SpatialReference()
    p2.ImportFromProj4(pyproj.CRS(prj2).to_proj4())
    box = t1(np.dot(m1[:, 1:], np.array(boxs).T) + m1[:, :1])
    ct = osr.CoordinateTransformation(p1, p2)
    box = t2(np.array(ct.TransformPoints(box.T)).T)
    return np.dot(inv(m2[:, 1:]), box[:2] - m2[:, :1]).T
    '''
コード例 #14
0
    def setup_method(self):
        self.osgb = pyproj.CRS(27700)
        self.wgs = pyproj.CRS(4326)

        self.geoms = [Point(0, 0), Point(1, 1)]
        self.polys = [
            Polygon([(random.random(), random.random()) for i in range(3)])
            for _ in range(10)
        ]
        self.arr = from_shapely(self.polys, crs=27700)
コード例 #15
0
def draw_ruler(raster, left, top, right, bot, step, crs, font, color, w, dh): 

    img = Image.fromarray(raster)
    d = ImageDraw.Draw(img)
    def f(x, dir=0):
        v = raster.shape[1-dir]
        if x<0: return v+x
        if isinstance(x, int): return x
        if isinstance(x, float): return int(v*x)
    
    left, top, right, bot = f(left), f(top,1), f(right), f(bot,1)
    d.rectangle([left, top, right, bot], outline=color, width=w)
    pts = np.array([(left,top),(right,top),(right,bot),(left,bot)])
    prj1, prj2 = pyproj.CRS(raster.crs), pyproj.CRS(crs)
    ct = pyproj.Transformer.from_crs(prj1, prj2, always_xy=True)
    pts = np.dot(raster.mat[:,1:], pts.T) + raster.mat[:,:1]
    xs, ys = ct.transform(*pts)

    a, b = int(xs[0]//step), int(xs[1]//step)
    tab = [i*step for i in range(a+1, b+1)]
    nps = ct.transform(tab, np.linspace(ys[0], ys[1], len(tab)), direction='INVERSE')
    nps = np.dot(np.linalg.inv(raster.mat[:,1:]), nps - raster.mat[:,:1])
    font = ImageFont.truetype(*font)
    for x,e in zip(nps[0],tab):
        d.line([int(x), top, int(x), top-dh], color, w)
        tw, th = d.textsize('%d°E'%e, font)
        d.text((int(x-tw//2), top-dh-th*1.2), '%d°E'%e, font=font, fill=color)

    a, b = int(xs[3]//step), int(xs[2]//step)
    tab = [i*step for i in range(a+1, b+1)]
    nps = ct.transform(tab, np.linspace(ys[3], ys[2], len(tab)), direction='INVERSE')
    nps = np.dot(np.linalg.inv(raster.mat[:,1:]), nps - raster.mat[:,:1])
    for x,e in zip(nps[0],tab):
        d.line([int(x), bot, int(x), bot+dh], color, w)
        tw, th = d.textsize('%d°E'%e, font)
        d.text((int(x-tw//2), bot+dh+th*0.0), '%d°E'%e, font=font, fill=color)

    a, b = int(ys[3]//step), int(ys[0]//step)
    tab = [i*step for i in range(a+1, b+1)]
    nps = ct.transform(np.linspace(xs[3], xs[0], len(tab)), tab, direction='INVERSE')
    nps = np.dot(np.linalg.inv(raster.mat[:,1:]), nps - raster.mat[:,:1])
    for y,n in zip(nps[1],tab):
        d.line([left, int(y), left-dh, int(y)], color, w)
        tw, th = d.textsize('%d°N'%n, font)
        d.text((left-dh-tw-th*0.2, int(y-th*3/5)), '%d°N'%n, font=font, fill=color)

    a, b = int(ys[2]//step), int(ys[1]//step)
    tab = [i*step for i in range(a+1, b+1)]
    nps = ct.transform(np.linspace(xs[2], xs[1], len(tab)), tab, direction='INVERSE')
    nps = np.dot(np.linalg.inv(raster.mat[:,1:]), nps - raster.mat[:,:1])
    for y,n in zip(nps[1],tab):
        d.line([right, int(y), right+dh, int(y)], color, w)
        tw, th = d.textsize('%d°N'%n, font)
        d.text((right+dh+th*0.2, int(y-th*3/5)), '%d°N'%n, font=font, fill=color)
    raster[:] = np.array(img)
コード例 #16
0
    def _read_geojson_crs(geojson: Dict) -> pyproj.CRS:
        #so actually geojson has no crs, it's always lat lon, need to check what gdal does...
        crs = geojson.get('crs', {}).get("properties", {}).get("name")

        # TODO: what's the deal with this deprecated "init"?
        if crs == None:
            return pyproj.CRS({'init': 'epsg:4326'})
        elif crs.startswith("urn:ogc:"):
            return pyproj.CRS(crs)
        else:
            return pyproj.CRS({'init': crs})
コード例 #17
0
ファイル: services.py プロジェクト: ArtesiaWater/UGW
def set_crs(gdf, crs='epsg:28992'):
    if gdf.crs == None:
        gdf.crs = crs
    else:
        if hasattr(pyproj, 'CRS'):
            update_crs = not pyproj.CRS(gdf.crs).equals(pyproj.CRS(crs))
        else:
            update_crs = pyproj.Proj(gdf.crs).srs != pyproj.Proj(crs).srs
        if update_crs:
            gdf = gdf.to_crs(crs)

    return gdf
コード例 #18
0
def set_crs(gdf, crs=sources['default_crs']):
    if gdf.crs == None:
        gdf.crs = crs
    else:
        if hasattr(pyproj, 'CRS'):
            update_crs = not pyproj.CRS(gdf.crs).equals(pyproj.CRS(crs))
        else:
            update_crs = pyproj.Proj(gdf.crs).srs != pyproj.Proj(init=crs).srs
        if update_crs:
            gdf = gdf.to_crs(crs)

    return gdf
コード例 #19
0
    def tile_generator(self, polygon, zoom=14):
        wgs84 = pyproj.CRS('EPSG:4326')
        webMarcator = pyproj.CRS('EPSG:3857')
        project = pyproj.Transformer.from_crs(wgs84,
                                              webMarcator,
                                              always_xy=True).transform
        polygon = transform(project, polygon)

        tiler = tileschemes.WebMercator()
        for t in tilecover.cover_geometry(tiler, polygon, zoom):
            # Keep tiles between Noth of Iceland and South of Americas
            if t.y > 4085 and t.y < 11200:
                yield [t.z, t.x, t.y]
コード例 #20
0
def test_to_bng():
    crs_4326 = pyproj.CRS("epsg:4326")
    bng = pyproj.Proj(init="epsg:27700")
    wgs84 = pyproj.Proj(init="epsg:4326")    
    def project(lon, lat):
        return pyproj.transform(wgs84, bng, lon, lat)

    bng_new = pyproj.CRS("epsg:27700")
    project2 = pyproj.Transformer.from_crs(crs_4326, bng_new).transform

    assert( project(-1.55532, 53.80474) == project2(53.80474, -1.55532) )
    assert( project(-5.71808, 50.06942) == project2(50.06942, -5.71808) )
    assert( project(-3.02516, 58.64389) == project2(58.64389, -3.02516) )
コード例 #21
0
def set_crs(gdf, crs=sources['default_crs']):
    '''sets the coordinate reference system to a gdf if not specified'''

    if gdf.crs == None:
        gdf.crs = crs
    else:
        if hasattr(pyproj, 'CRS'):
            update_crs = not pyproj.CRS(gdf.crs).equals(pyproj.CRS(crs))
        else:
            update_crs = pyproj.Proj(gdf.crs).srs != pyproj.Proj(crs).srs
        if update_crs:
            gdf = gdf.to_crs(crs)

    return gdf
コード例 #22
0
    def transform_crs(shp, from_crs):
        if from_crs == "WGS84" or from_crs == "" or from_crs is None:
            from_crs = "EPSG:4326"

        if from_crs != "EPSG:4326":
            wgs84 = pyproj.CRS("EPSG:4326")
            original_crs = pyproj.CRS(from_crs)

            project = pyproj.Transformer.from_crs(original_crs,
                                                  wgs84,
                                                  always_xy=True).transform
            return transform(project, shp)
        else:
            return shp
コード例 #23
0
async def test_calculate_isochrone_single_scenario(
    client: AsyncClient, superuser_token_headers: Dict[str, str], db: AsyncSession
) -> None:
    superuser = await crud.user.get_by_key(db, key="email", value=settings.FIRST_SUPERUSER_EMAIL)
    obj_scenario = models.Scenario(
        scenario_name=random_lower_string(),
        user_id=superuser[0].id,
        study_area_id=superuser[0].active_study_area_id,
    )
    scenario = await crud.scenario.create(db=db, obj_in=obj_scenario)

    scenario_ways_modified_features = []
    for feature in isochrone_scenario_new_bridge["features"]:
        scenario_ways_modified_features.append(ScenarioWaysModifiedCreate(**feature))
    await crud.scenario.create_scenario_features(
        db,
        superuser[0],
        scenario.id,
        ScenarioLayerFeatureEnum.way_modified,
        ScenarioFeatureCreate(
            features=scenario_ways_modified_features,
        ),
    )
    isochrone_scenario_comparision["scenario_id"] = scenario.id
    r = await client.post(
        f"{settings.API_V1_STR}/isochrones/single",
        headers=superuser_token_headers,
        json=isochrone_scenario_comparision,
    )
    response = r.json()
    assert 200 <= r.status_code < 300
    assert len(response["features"]) > 0
    assert len(response["features"][0]["geometry"]["coordinates"][0][0]) > 3
    # Scenario geometry area should be greater than default geometry area when new feature is added
    project = pyproj.Transformer.from_crs(
        pyproj.CRS("EPSG:4326"), pyproj.CRS("EPSG:3857"), always_xy=True
    ).transform
    groups = defaultdict(list)
    for obj in response["features"]:
        obj["properties"]["area"] = transform(project, shape(obj["geometry"])).area
        groups[obj["properties"]["step"]].append(obj)
    for group, features in groups.items():
        default_area = 0
        scenario_area = 0
        for feature in features:
            if feature["properties"]["modus"] == "default":
                default_area = feature["properties"]["area"]
            else:
                scenario_area = feature["properties"]["area"]
        assert scenario_area > default_area
コード例 #24
0
ファイル: geometry.py プロジェクト: brazil-data-cube/stac2odc
def _transform_crs(crs_src: str, crs_dest: str, geom: BaseGeometry) -> BaseGeometry:
    """Reproject geometry

    Args:
        crs_src (str): Actual geometry CRS
        crs_dest (str): Destiny geometry CRS
        geom (shapely.geometry.base.BaseGeometry): Shapely Geometry
    Returns:
        shapely.geometry.base.BaseGeometry: Shapely Geometry reprojected
    """
    crs_src = pyproj.CRS(crs_src)
    crs_dest = pyproj.CRS(crs_dest)

    transform_fnc = pyproj.Transformer.from_crs(crs_src, crs_dest).transform
    return transform(transform_fnc, geom)
コード例 #25
0
def get_proj(prj_code):
    """
      Helper method for handling projection codes that are unknown to pyproj

      Args:
          prj_code (str): an epsg proj code

      Returns:
          projection: a pyproj projection
    """
    if prj_code in CUSTOM_PRJ:
        proj = pyproj.CRS(CUSTOM_PRJ[prj_code])
    else:
        proj = pyproj.CRS(prj_code)
    return proj
コード例 #26
0
def shp_to_vtk(
    shp_fn, vtk_fn, final_epsg, model_center, model_depth=0, x="latitude", y="longitude"
):
    model_east, model_north = project_points(
        model_center[0],
        model_center[1],
        pyproj.CRS("EPSG:4326"),
        pyproj.CRS(f"EPSG:{final_epsg}"),
    )

    x, y, z = shape_to_points(
        shp_fn, final_epsg, model_east, model_north, model_depth=model_depth, x=x, y=y
    )

    pointsToVTK(vtk_fn, y, x, z)
コード例 #27
0
def get_flowgrid(catchment_geom, transformToRaster, transformToWGS84):
    """Use a 90 meter buffer of the local catchment to clip NHD Plus v2 flow direction raster"""

    print('start clip raster')
    with rasterio.open(IN_FDR_COG, 'r') as ds:

        # get raster crs
        dest_crs = ds.crs

        # create wgs84 crs
        wgs84 = pyproj.CRS('EPSG:4326')

        # check to see if raster is already wgs84
        latlon = dest_crs == wgs84

        # transform catchment geometry to use for clip
        projected_catchment_geom = transform_geom(transformToRaster,
                                                  catchment_geom)

        # buffer catchment geometry by 90m before clipping flow direction raster
        buffer_projected_catchment_geom = GeometryCollection(
            [projected_catchment_geom.buffer(90)])

        # clip input fd
        flwdir, flwdir_transform = rasterio.mask.mask(
            ds, buffer_projected_catchment_geom, crop=True)
        print('finish clip raster')

    # import clipped fdr into pyflwdir
    flw = pyflwdir.from_array(flwdir[0],
                              ftype='d8',
                              transform=flwdir_transform,
                              latlon=latlon)

    return flw, flwdir_transform
コード例 #28
0
def write_crs_cf(ds, crs=None, grid_mapping_name="crs"):
    crs = pyproj.CRS(crs if crs is not None else ds.rio.crs.to_wkt())
    crs_cf = crs.to_cf()
    with suppress(KeyError):
        del ds.coords["spatial_ref"]
    ds.rio.write_crs(crs, grid_mapping_name=grid_mapping_name, inplace=True)
    ds[grid_mapping_name].attrs = crs_cf
    if crs.is_geographic:
        if "x" in ds:
            ds = ds.rename({"x": "longitude"})
        if "y" in ds:
            ds = ds.rename({"y": "latitude"})

        ds["longitude"].attrs.update(standard_name="longitude",
                                     units="degree_east")
        ds["latitude"].attrs.update(standard_name="latitude",
                                    units="degree_north")
    elif crs.is_projected:
        ds["x"].attrs.update(standard_name="projection_x_coordinate",
                             long_name="Easting",
                             units="m")
        ds["y"].attrs.update(standard_name="projection_x_coordinate",
                             long_name="Northing",
                             units="m")
    else:
        logger.warning(
            "CRS not geographic nor geocentric. Cannot set dim info")
    return ds
コード例 #29
0
    def get_coordinates(self):
        """{get_coordinates}

        The default implementation tries to find the lat/lon coordinates based on dataset.affine.
        It cannot determine the alt or time dimensions, so child classes may
        have to overload this method.
        """

        # check to see if the coordinates are rotated used affine
        affine = self.dataset.transform

        if self.crs is not None:
            crs = self.crs
        elif isinstance(self.dataset.crs,
                        rasterio.crs.CRS) and "init" in self.dataset.crs:
            crs = self.dataset.crs["init"].upper()
        elif isinstance(self.dataset.crs, dict) and "init" in self.dataset.crs:
            crs = self.dataset.crs["init"].upper()
        else:
            try:
                crs = pyproj.CRS(self.dataset.crs).to_wkt()
            except pyproj.exceptions.CRSError:
                raise RuntimeError("Unexpected rasterio crs '%s'" %
                                   self.dataset.crs)

        return Coordinates.from_geotransform(affine.to_gdal(),
                                             self.dataset.shape, crs)
コード例 #30
0
    def __init__(self, polygon_file,proj4_str = '+proj=lonlat +ellps=WGS84'):

        self.proj4 = proj4_str 
        self.crs = pyproj.CRS(self.proj4)

        super(Reader, self).__init__()
        shore = np.loadtxt(
            polygon_file)  # nan-delimited closed polygons for land and islands

        # Depth
        self.z = None
        self.xmin, self.ymin = np.nanmin(shore[:, 0]), np.nanmin(shore[:, 1])
        self.xmax, self.ymax = np.nanmax(shore[:, 0]), np.nanmax(shore[:, 1])
        # convert to xy
        self.xmin, self.ymin = self.lonlat2xy(self.xmin, self.ymin)
        self.xmax, self.ymax = self.lonlat2xy(self.xmax, self.ymax)

        # Loop through polygon to build MultiPolygon object
        #
        # make sure that start and end lines are [nan,nan] as well
        if not np.isnan(shore[0, 0]):
            shore = np.vstack(([np.nan, np.nan], shore))
        if not np.isnan(shore[-1, 0]):
            shore = np.vstack((shore, [np.nan, np.nan]))
        id_nans = np.where(np.isnan(shore[:, 0]))[0]
        poly = []
        for cnt, _id_i in enumerate(id_nans[:-1]):
            # The shapely.geometry.asShape() family of functions can be used to wrap Numpy coordinate arrays
            # https://shapely.readthedocs.io/en/latest/manual.html
            poly.append(
                asPolygon(shore[id_nans[cnt] + 1:id_nans[cnt + 1] - 1, :]))
        # We can pass multiple Polygon -objects into our MultiPolygon as a list
        self.mask = MultiPolygon(poly)
        self.mask = shapely.prepared.prep(self.mask)