id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
12,338
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple The provided code snippet includes necessary dependencies for implementing the `num_round` function. Write a Python function `def num_round(num, decimal=2)` to solve the following problem: Rounds a number to a specified number of decimal places. Args: num (float): The number to round. decimal (int, optional): The number of decimal places to round. Defaults to 2. Returns: float: The number with the specified decimal places rounded. Here is the function: def num_round(num, decimal=2): """Rounds a number to a specified number of decimal places. Args: num (float): The number to round. decimal (int, optional): The number of decimal places to round. Defaults to 2. Returns: float: The number with the specified decimal places rounded. """ return round(num, decimal)
Rounds a number to a specified number of decimal places. Args: num (float): The number to round. decimal (int, optional): The number of decimal places to round. Defaults to 2. Returns: float: The number with the specified decimal places rounded.
12,339
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple The provided code snippet includes necessary dependencies for implementing the `jpg_to_gif` function. Write a Python function `def jpg_to_gif(in_dir, out_gif, fps=10, loop=0)` to solve the following problem: Convert a list of jpg images to gif. Args: in_dir (str): The input directory containing jpg images. out_gif (str): The output file path to the gif. fps (int, optional): Frames per second. Defaults to 10. loop (bool, optional): controls how many times the animation repeats. 1 means that the animation will play once and then stop (displaying the last frame). A value of 0 means that the animation will repeat forever. Defaults to 0. Raises: FileNotFoundError: No jpg images could be found. Here is the function: def jpg_to_gif(in_dir, out_gif, fps=10, loop=0): """Convert a list of jpg images to gif. Args: in_dir (str): The input directory containing jpg images. out_gif (str): The output file path to the gif. fps (int, optional): Frames per second. Defaults to 10. loop (bool, optional): controls how many times the animation repeats. 1 means that the animation will play once and then stop (displaying the last frame). A value of 0 means that the animation will repeat forever. Defaults to 0. Raises: FileNotFoundError: No jpg images could be found. """ import glob from PIL import Image if not out_gif.endswith(".gif"): raise ValueError("The out_gif must be a gif file.") out_gif = os.path.abspath(out_gif) out_dir = os.path.dirname(out_gif) if not os.path.exists(out_dir): os.makedirs(out_dir) # Create the frames frames = [] imgs = list(glob.glob(os.path.join(in_dir, "*.jpg"))) imgs.sort() if len(imgs) == 0: raise FileNotFoundError(f"No jpg could be found in {in_dir}.") for i in imgs: new_frame = Image.open(i) frames.append(new_frame) # Save into a GIF file that loops forever frames[0].save( out_gif, format="GIF", append_images=frames[1:], save_all=True, duration=1000 / fps, loop=loop, )
Convert a list of jpg images to gif. Args: in_dir (str): The input directory containing jpg images. out_gif (str): The output file path to the gif. fps (int, optional): Frames per second. Defaults to 10. loop (bool, optional): controls how many times the animation repeats. 1 means that the animation will play once and then stop (displaying the last frame). A value of 0 means that the animation will repeat forever. Defaults to 0. Raises: FileNotFoundError: No jpg images could be found.
12,340
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple The provided code snippet includes necessary dependencies for implementing the `geometry_type` function. Write a Python function `def geometry_type(ee_object)` to solve the following problem: Get geometry type of an Earth Engine object. Args: ee_object (object): An Earth Engine object. Returns: str: Returns geometry type. One of Point, MultiPoint, LineString, LinearRing, MultiLineString, BBox, Rectangle, Polygon, MultiPolygon. Here is the function: def geometry_type(ee_object): """Get geometry type of an Earth Engine object. Args: ee_object (object): An Earth Engine object. Returns: str: Returns geometry type. One of Point, MultiPoint, LineString, LinearRing, MultiLineString, BBox, Rectangle, Polygon, MultiPolygon. """ if isinstance(ee_object, ee.Geometry): return ee_object.type().getInfo() elif isinstance(ee_object, ee.Feature): return ee_object.geometry().type().getInfo() elif isinstance(ee_object, ee.FeatureCollection): return ee.Feature(ee_object.first()).geometry().type().getInfo() else: raise TypeError( "The ee_object must be one of ee.Geometry, ee.Feature, ee.FeatureCollection." )
Get geometry type of an Earth Engine object. Args: ee_object (object): An Earth Engine object. Returns: str: Returns geometry type. One of Point, MultiPoint, LineString, LinearRing, MultiLineString, BBox, Rectangle, Polygon, MultiPolygon.
12,341
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple The provided code snippet includes necessary dependencies for implementing the `vector_styling` function. Write a Python function `def vector_styling( ee_object, column, palette, color="000000", colorOpacity=1.0, pointSize=3, pointShape="circle", width=1, lineType="solid", fillColorOpacity=0.66, )` to solve the following problem: Add a new property to each feature containing a stylying dictionary. Args: ee_object (object): An ee.FeatureCollection. column (str): The column name to use for styling. palette (list | dict): The palette (e.g., list of colors or a dict containing label and color pairs) to use for styling. color (str, optional): A default color (CSS 3.0 color value e.g. 'FF0000' or 'red') to use for drawing the features. Defaults to "black". colorOpacity (float, optional): Opacity between 0-1 of the features. Defaults to 1 pointSize (int, optional): The default size in pixels of the point markers. Defaults to 3. pointShape (str, optional): The default shape of the marker to draw at each point location. One of: circle, square, diamond, cross, plus, pentagram, hexagram, triangle, triangle_up, triangle_down, triangle_left, triangle_right, pentagon, hexagon, star5, star6. This argument also supports the following Matlab marker abbreviations: o, s, d, x, +, p, h, ^, v, <, >. Defaults to "circle". width (int, optional): The default line width for lines and outlines for polygons and point shapes. Defaults to 1. lineType (str, optional): The default line style for lines and outlines of polygons and point shapes. Defaults to 'solid'. One of: solid, dotted, dashed. Defaults to "solid". fillColorOpacity (float, optional): Opacity between 0-1 of the fill. Defaults to 0.66. Color of the fill is based on the column name or index in the palette. Raises: ValueError: The provided column name is invalid. TypeError: The provided palette is invalid. TypeError: The provided ee_object is not an ee.FeatureCollection. Returns: object: An ee.FeatureCollection containing the styling attribute. Here is the function: def vector_styling( ee_object, column, palette, color="000000", colorOpacity=1.0, pointSize=3, pointShape="circle", width=1, lineType="solid", fillColorOpacity=0.66, ): """Add a new property to each feature containing a stylying dictionary. Args: ee_object (object): An ee.FeatureCollection. column (str): The column name to use for styling. palette (list | dict): The palette (e.g., list of colors or a dict containing label and color pairs) to use for styling. color (str, optional): A default color (CSS 3.0 color value e.g. 'FF0000' or 'red') to use for drawing the features. Defaults to "black". colorOpacity (float, optional): Opacity between 0-1 of the features. Defaults to 1 pointSize (int, optional): The default size in pixels of the point markers. Defaults to 3. pointShape (str, optional): The default shape of the marker to draw at each point location. One of: circle, square, diamond, cross, plus, pentagram, hexagram, triangle, triangle_up, triangle_down, triangle_left, triangle_right, pentagon, hexagon, star5, star6. This argument also supports the following Matlab marker abbreviations: o, s, d, x, +, p, h, ^, v, <, >. Defaults to "circle". width (int, optional): The default line width for lines and outlines for polygons and point shapes. Defaults to 1. lineType (str, optional): The default line style for lines and outlines of polygons and point shapes. Defaults to 'solid'. One of: solid, dotted, dashed. Defaults to "solid". fillColorOpacity (float, optional): Opacity between 0-1 of the fill. Defaults to 0.66. Color of the fill is based on the column name or index in the palette. Raises: ValueError: The provided column name is invalid. TypeError: The provided palette is invalid. TypeError: The provided ee_object is not an ee.FeatureCollection. Returns: object: An ee.FeatureCollection containing the styling attribute. """ from box import Box if isinstance(ee_object, ee.FeatureCollection): prop_names = ee.Feature(ee_object.first()).propertyNames().getInfo() arr = ee_object.aggregate_array(column).distinct().sort() if column not in prop_names: raise ValueError(f"The column name must of one of {', '.join(prop_names)}") if isinstance(palette, Box): try: palette = list(palette["default"]) except Exception as e: print("The provided palette is invalid.") raise Exception(e) elif isinstance(palette, tuple): palette = list(palette) elif isinstance(palette, dict): values = list(arr.getInfo()) labels = list(palette.keys()) if not all(elem in values for elem in labels): raise ValueError( f"The keys of the palette must contain the following elements: {', '.join(values)}" ) else: colors = [palette[value] for value in values] palette = colors if not isinstance(palette, list): raise TypeError("The palette must be a list.") colors = ee.List( [ color.strip() + str(hex(int(fillColorOpacity * 255)))[2:].zfill(2) for color in palette ] ) fc = ee_object.map(lambda f: f.set({"styleIndex": arr.indexOf(f.get(column))})) step = arr.size().divide(colors.size()).ceil() fc = fc.map( lambda f: f.set( { "style": { "color": color + str(hex(int(colorOpacity * 255)))[2:].zfill(2), "pointSize": pointSize, "pointShape": pointShape, "width": width, "lineType": lineType, "fillColor": colors.get( ee.Number( ee.Number(f.get("styleIndex")).divide(step) ).floor() ), } } ) ) return fc else: raise TypeError("The ee_object must be an ee.FeatureCollection.")
Add a new property to each feature containing a stylying dictionary. Args: ee_object (object): An ee.FeatureCollection. column (str): The column name to use for styling. palette (list | dict): The palette (e.g., list of colors or a dict containing label and color pairs) to use for styling. color (str, optional): A default color (CSS 3.0 color value e.g. 'FF0000' or 'red') to use for drawing the features. Defaults to "black". colorOpacity (float, optional): Opacity between 0-1 of the features. Defaults to 1 pointSize (int, optional): The default size in pixels of the point markers. Defaults to 3. pointShape (str, optional): The default shape of the marker to draw at each point location. One of: circle, square, diamond, cross, plus, pentagram, hexagram, triangle, triangle_up, triangle_down, triangle_left, triangle_right, pentagon, hexagon, star5, star6. This argument also supports the following Matlab marker abbreviations: o, s, d, x, +, p, h, ^, v, <, >. Defaults to "circle". width (int, optional): The default line width for lines and outlines for polygons and point shapes. Defaults to 1. lineType (str, optional): The default line style for lines and outlines of polygons and point shapes. Defaults to 'solid'. One of: solid, dotted, dashed. Defaults to "solid". fillColorOpacity (float, optional): Opacity between 0-1 of the fill. Defaults to 0.66. Color of the fill is based on the column name or index in the palette. Raises: ValueError: The provided column name is invalid. TypeError: The provided palette is invalid. TypeError: The provided ee_object is not an ee.FeatureCollection. Returns: object: An ee.FeatureCollection containing the styling attribute.
12,342
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple def check_package(name, URL=""): try: __import__(name.lower()) except Exception: raise ImportError( f"{name} is not installed. Please install it before proceeding. {URL}" ) The provided code snippet includes necessary dependencies for implementing the `kml_to_shp` function. Write a Python function `def kml_to_shp(in_kml, out_shp, **kwargs)` to solve the following problem: Converts a KML to shapefile. Args: in_kml (str): The file path to the input KML. out_shp (str): The file path to the output shapefile. Raises: FileNotFoundError: The input KML could not be found. TypeError: The output must be a shapefile. Here is the function: def kml_to_shp(in_kml, out_shp, **kwargs): """Converts a KML to shapefile. Args: in_kml (str): The file path to the input KML. out_shp (str): The file path to the output shapefile. Raises: FileNotFoundError: The input KML could not be found. TypeError: The output must be a shapefile. """ warnings.filterwarnings("ignore") in_kml = os.path.abspath(in_kml) if not os.path.exists(in_kml): raise FileNotFoundError("The input KML could not be found.") out_shp = os.path.abspath(out_shp) if not out_shp.endswith(".shp"): raise TypeError("The output must be a shapefile.") out_dir = os.path.dirname(out_shp) if not os.path.exists(out_dir): os.makedirs(out_dir) check_package(name="geopandas", URL="https://geopandas.org") import geopandas as gpd import fiona # import fiona # print(fiona.supported_drivers) fiona.drvsupport.supported_drivers["KML"] = "rw" df = gpd.read_file(in_kml, driver="KML", **kwargs) df.to_file(out_shp, **kwargs)
Converts a KML to shapefile. Args: in_kml (str): The file path to the input KML. out_shp (str): The file path to the output shapefile. Raises: FileNotFoundError: The input KML could not be found. TypeError: The output must be a shapefile.
12,343
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple def kml_to_ee(in_kml, **kwargs): """Converts a KML to ee.FeatureCollection. Args: in_kml (str): The file path to the input KML. Raises: FileNotFoundError: The input KML could not be found. Returns: object: ee.FeatureCollection """ warnings.filterwarnings("ignore") in_kml = os.path.abspath(in_kml) if not os.path.exists(in_kml): raise FileNotFoundError("The input KML could not be found.") out_json = os.path.join(os.getcwd(), "tmp.geojson") check_package(name="geopandas", URL="https://geopandas.org") kml_to_geojson(in_kml, out_json, **kwargs) ee_object = geojson_to_ee(out_json) os.remove(out_json) return ee_object The provided code snippet includes necessary dependencies for implementing the `kmz_to_ee` function. Write a Python function `def kmz_to_ee(in_kmz, **kwargs)` to solve the following problem: Converts a KMZ to ee.FeatureCollection. Args: in_kmz (str): The file path to the input KMZ. Raises: FileNotFoundError: The input KMZ could not be found. Returns: object: ee.FeatureCollection Here is the function: def kmz_to_ee(in_kmz, **kwargs): """Converts a KMZ to ee.FeatureCollection. Args: in_kmz (str): The file path to the input KMZ. Raises: FileNotFoundError: The input KMZ could not be found. Returns: object: ee.FeatureCollection """ in_kmz = os.path.abspath(in_kmz) if not os.path.exists(in_kmz): raise FileNotFoundError("The input KMZ could not be found.") out_dir = os.path.dirname(in_kmz) out_kml = os.path.join(out_dir, "doc.kml") with zipfile.ZipFile(in_kmz, "r") as zip_ref: zip_ref.extractall(out_dir) fc = kml_to_ee(out_kml, **kwargs) os.remove(out_kml) return fc
Converts a KMZ to ee.FeatureCollection. Args: in_kmz (str): The file path to the input KMZ. Raises: FileNotFoundError: The input KMZ could not be found. Returns: object: ee.FeatureCollection
12,344
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple def github_raw_url(url): """Get the raw URL for a GitHub file. Args: url (str): The GitHub URL. Returns: str: The raw URL. """ if isinstance(url, str) and url.startswith("https://github.com/") and "blob" in url: url = url.replace("github.com", "raw.githubusercontent.com").replace( "blob/", "", 1 ) return url The provided code snippet includes necessary dependencies for implementing the `csv_to_df` function. Write a Python function `def csv_to_df(in_csv, **kwargs)` to solve the following problem: Converts a CSV file to pandas dataframe. Args: in_csv (str): File path to the input CSV. Returns: pd.DataFrame: pandas DataFrame Here is the function: def csv_to_df(in_csv, **kwargs): """Converts a CSV file to pandas dataframe. Args: in_csv (str): File path to the input CSV. Returns: pd.DataFrame: pandas DataFrame """ import pandas as pd in_csv = github_raw_url(in_csv) try: return pd.read_csv(in_csv, **kwargs) except Exception as e: raise Exception(e)
Converts a CSV file to pandas dataframe. Args: in_csv (str): File path to the input CSV. Returns: pd.DataFrame: pandas DataFrame
12,345
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple def check_package(name, URL=""): try: __import__(name.lower()) except Exception: raise ImportError( f"{name} is not installed. Please install it before proceeding. {URL}" ) The provided code snippet includes necessary dependencies for implementing the `shp_to_gdf` function. Write a Python function `def shp_to_gdf(in_shp, **kwargs)` to solve the following problem: Converts a shapefile to Geopandas dataframe. Args: in_shp (str): File path to the input shapefile. Raises: FileNotFoundError: The provided shp could not be found. Returns: gpd.GeoDataFrame: geopandas.GeoDataFrame Here is the function: def shp_to_gdf(in_shp, **kwargs): """Converts a shapefile to Geopandas dataframe. Args: in_shp (str): File path to the input shapefile. Raises: FileNotFoundError: The provided shp could not be found. Returns: gpd.GeoDataFrame: geopandas.GeoDataFrame """ warnings.filterwarnings("ignore") in_shp = os.path.abspath(in_shp) if not os.path.exists(in_shp): raise FileNotFoundError("The provided shp could not be found.") check_package(name="geopandas", URL="https://geopandas.org") import geopandas as gpd try: return gpd.read_file(in_shp, **kwargs) except Exception as e: raise Exception(e)
Converts a shapefile to Geopandas dataframe. Args: in_shp (str): File path to the input shapefile. Raises: FileNotFoundError: The provided shp could not be found. Returns: gpd.GeoDataFrame: geopandas.GeoDataFrame
12,346
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple The provided code snippet includes necessary dependencies for implementing the `delete_shp` function. Write a Python function `def delete_shp(in_shp, verbose=False)` to solve the following problem: Deletes a shapefile. Args: in_shp (str): The input shapefile to delete. verbose (bool, optional): Whether to print out descriptive text. Defaults to False. Here is the function: def delete_shp(in_shp, verbose=False): """Deletes a shapefile. Args: in_shp (str): The input shapefile to delete. verbose (bool, optional): Whether to print out descriptive text. Defaults to False. """ from pathlib import Path in_shp = os.path.abspath(in_shp) in_dir = os.path.dirname(in_shp) basename = os.path.basename(in_shp).replace(".shp", "") files = Path(in_dir).rglob(basename + ".*") for file in files: filepath = os.path.join(in_dir, str(file)) try: os.remove(filepath) if verbose: print(f"Deleted {filepath}") except Exception as e: if verbose: print(e)
Deletes a shapefile. Args: in_shp (str): The input shapefile to delete. verbose (bool, optional): Whether to print out descriptive text. Defaults to False.
12,347
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple def df_to_geojson( df, out_geojson=None, latitude="latitude", longitude="longitude", encoding="utf-8", ): """Creates points for a Pandas DataFrame and exports data as a GeoJSON. Args: df (pandas.DataFrame): The input Pandas DataFrame. out_geojson (str): The file path to the exported GeoJSON. Default to None. latitude (str, optional): The name of the column containing latitude coordinates. Defaults to "latitude". longitude (str, optional): The name of the column containing longitude coordinates. Defaults to "longitude". encoding (str, optional): The encoding of characters. Defaults to "utf-8". """ from geojson import Feature, FeatureCollection, Point if out_geojson is not None: out_dir = os.path.dirname(os.path.abspath(out_geojson)) if not os.path.exists(out_dir): os.makedirs(out_dir) features = df.apply( lambda row: Feature( geometry=Point((float(row[longitude]), float(row[latitude]))), properties=dict(row), ), axis=1, ).tolist() geojson = FeatureCollection(features=features) if out_geojson is None: return geojson else: with open(out_geojson, "w", encoding=encoding) as f: f.write(json.dumps(geojson)) def geojson_to_ee(geo_json, geodesic=False, encoding="utf-8"): """Converts a geojson to ee.Geometry() Args: geo_json (dict): A geojson geometry dictionary or file path. geodesic (bool, optional): Whether line segments should be interpreted as spherical geodesics. If false, indicates that line segments should be interpreted as planar lines in the specified CRS. If absent, defaults to true if the CRS is geographic (including the default EPSG:4326), or to false if the CRS is projected. Defaults to False. encoding (str, optional): The encoding of characters. Defaults to "utf-8". Returns: ee_object: An ee.Geometry object """ try: if isinstance(geo_json, str): if geo_json.startswith("http") and geo_json.endswith(".geojson"): geo_json = github_raw_url(geo_json) out_geojson = temp_file_path(extension=".geojson") download_file(geo_json, out_geojson) with open(out_geojson, "r", encoding=encoding) as f: geo_json = json.loads(f.read()) os.remove(out_geojson) elif os.path.isfile(geo_json): with open(os.path.abspath(geo_json), encoding=encoding) as f: geo_json = json.load(f) # geo_json["geodesic"] = geodesic if geo_json["type"] == "FeatureCollection": for feature in geo_json["features"]: if feature["geometry"]["type"] != "Point": feature["geometry"]["geodesic"] = geodesic features = ee.FeatureCollection(geo_json) return features elif geo_json["type"] == "Feature": geom = None if "style" in geo_json["properties"]: keys = geo_json["properties"]["style"].keys() if "radius" in keys: # Checks whether it is a circle geom = ee.Geometry(geo_json["geometry"]) radius = geo_json["properties"]["style"]["radius"] geom = geom.buffer(radius) elif geo_json["geometry"]["type"] == "Point": geom = ee.Geometry(geo_json["geometry"]) else: geom = ee.Geometry(geo_json["geometry"], "", geodesic) elif ( geo_json["geometry"]["type"] == "Point" ): # Checks whether it is a point coordinates = geo_json["geometry"]["coordinates"] longitude = coordinates[0] latitude = coordinates[1] geom = ee.Geometry.Point(longitude, latitude) else: geom = ee.Geometry(geo_json["geometry"], "", geodesic) return geom else: raise Exception("Could not convert the geojson to ee.Geometry()") except Exception as e: print("Could not convert the geojson to ee.Geometry()") raise Exception(e) The provided code snippet includes necessary dependencies for implementing the `df_to_ee` function. Write a Python function `def df_to_ee(df, latitude="latitude", longitude="longitude", **kwargs)` to solve the following problem: Converts a pandas DataFrame to ee.FeatureCollection. Args: df (pandas.DataFrame): An input pandas.DataFrame. latitude (str, optional): Column name for the latitude column. Defaults to 'latitude'. longitude (str, optional): Column name for the longitude column. Defaults to 'longitude'. Raises: TypeError: The input data type must be pandas.DataFrame. Returns: ee.FeatureCollection: The ee.FeatureCollection converted from the input pandas DataFrame. Here is the function: def df_to_ee(df, latitude="latitude", longitude="longitude", **kwargs): """Converts a pandas DataFrame to ee.FeatureCollection. Args: df (pandas.DataFrame): An input pandas.DataFrame. latitude (str, optional): Column name for the latitude column. Defaults to 'latitude'. longitude (str, optional): Column name for the longitude column. Defaults to 'longitude'. Raises: TypeError: The input data type must be pandas.DataFrame. Returns: ee.FeatureCollection: The ee.FeatureCollection converted from the input pandas DataFrame. """ import pandas as pd if not isinstance(df, pd.DataFrame): raise TypeError("The input data type must be pandas.DataFrame.") geojson = df_to_geojson(df, latitude=latitude, longitude=longitude) fc = geojson_to_ee(geojson) return fc
Converts a pandas DataFrame to ee.FeatureCollection. Args: df (pandas.DataFrame): An input pandas.DataFrame. latitude (str, optional): Column name for the latitude column. Defaults to 'latitude'. longitude (str, optional): Column name for the longitude column. Defaults to 'longitude'. Raises: TypeError: The input data type must be pandas.DataFrame. Returns: ee.FeatureCollection: The ee.FeatureCollection converted from the input pandas DataFrame.
12,348
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple The provided code snippet includes necessary dependencies for implementing the `extract_pixel_values` function. Write a Python function `def extract_pixel_values( ee_object, region, scale=None, projection=None, tileScale=1, getInfo=False )` to solve the following problem: Samples the pixels of an image, returning them as a ee.Dictionary. Args: ee_object (ee.Image | ee.ImageCollection): The ee.Image or ee.ImageCollection to sample. region (ee.Geometry): The region to sample from. If unspecified, uses the image's whole footprint. scale (float, optional): A nominal scale in meters of the projection to sample in. Defaults to None. projection (str, optional): The projection in which to sample. If unspecified, the projection of the image's first band is used. If specified in addition to scale, rescaled to the specified scale. Defaults to None. tileScale (int, optional): A scaling factor used to reduce aggregation tile size; using a larger tileScale (e.g. 2 or 4) may enable computations that run out of memory with the default. Defaults to 1. getInfo (bool, optional): Whether to use getInfo with the results, i.e., returning the values a list. Default to False. Raises: TypeError: The image must be an instance of ee.Image. TypeError: Region must be an instance of ee.Geometry. Returns: ee.Dictionary: The dictionary containing band names and pixel values. Here is the function: def extract_pixel_values( ee_object, region, scale=None, projection=None, tileScale=1, getInfo=False ): """Samples the pixels of an image, returning them as a ee.Dictionary. Args: ee_object (ee.Image | ee.ImageCollection): The ee.Image or ee.ImageCollection to sample. region (ee.Geometry): The region to sample from. If unspecified, uses the image's whole footprint. scale (float, optional): A nominal scale in meters of the projection to sample in. Defaults to None. projection (str, optional): The projection in which to sample. If unspecified, the projection of the image's first band is used. If specified in addition to scale, rescaled to the specified scale. Defaults to None. tileScale (int, optional): A scaling factor used to reduce aggregation tile size; using a larger tileScale (e.g. 2 or 4) may enable computations that run out of memory with the default. Defaults to 1. getInfo (bool, optional): Whether to use getInfo with the results, i.e., returning the values a list. Default to False. Raises: TypeError: The image must be an instance of ee.Image. TypeError: Region must be an instance of ee.Geometry. Returns: ee.Dictionary: The dictionary containing band names and pixel values. """ if isinstance(ee_object, ee.ImageCollection): ee_object = ee_object.toBands() if not isinstance(ee_object, ee.Image): raise TypeError("The image must be an instance of ee.Image.") if not isinstance(region, ee.Geometry): raise TypeError("Region must be an instance of ee.Geometry.") dict_values = ( ee_object.sample(region, scale, projection, tileScale=tileScale) .first() .toDictionary() ) if getInfo: band_names = ee_object.bandNames().getInfo() values_tmp = dict_values.getInfo() values = [values_tmp[i] for i in band_names] return dict(zip(band_names, values)) else: return dict_values
Samples the pixels of an image, returning them as a ee.Dictionary. Args: ee_object (ee.Image | ee.ImageCollection): The ee.Image or ee.ImageCollection to sample. region (ee.Geometry): The region to sample from. If unspecified, uses the image's whole footprint. scale (float, optional): A nominal scale in meters of the projection to sample in. Defaults to None. projection (str, optional): The projection in which to sample. If unspecified, the projection of the image's first band is used. If specified in addition to scale, rescaled to the specified scale. Defaults to None. tileScale (int, optional): A scaling factor used to reduce aggregation tile size; using a larger tileScale (e.g. 2 or 4) may enable computations that run out of memory with the default. Defaults to 1. getInfo (bool, optional): Whether to use getInfo with the results, i.e., returning the values a list. Default to False. Raises: TypeError: The image must be an instance of ee.Image. TypeError: Region must be an instance of ee.Geometry. Returns: ee.Dictionary: The dictionary containing band names and pixel values.
12,349
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple The provided code snippet includes necessary dependencies for implementing the `list_vars` function. Write a Python function `def list_vars(var_type=None)` to solve the following problem: Lists all defined avariables. Args: var_type (object, optional): The object type of variables to list. Defaults to None. Returns: list: A list of all defined variables. Here is the function: def list_vars(var_type=None): """Lists all defined avariables. Args: var_type (object, optional): The object type of variables to list. Defaults to None. Returns: list: A list of all defined variables. """ result = [] for var in globals(): reserved_vars = [ "In", "Out", "get_ipython", "exit", "quit", "json", "getsizeof", "NamespaceMagics", "np", "var_dic_list", "list_vars", "ee", "geemap", ] if (not var.startswith("_")) and (var not in reserved_vars): if var_type is not None and isinstance(eval(var), var_type): result.append(var) elif var_type is None: result.append(var) return result
Lists all defined avariables. Args: var_type (object, optional): The object type of variables to list. Defaults to None. Returns: list: A list of all defined variables.
12,350
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple def ee_to_df( ee_object, columns=None, remove_geom=True, sort_columns=False, **kwargs, ): """Converts an ee.FeatureCollection to pandas dataframe. Args: ee_object (ee.FeatureCollection): ee.FeatureCollection. columns (list): List of column names. Defaults to None. remove_geom (bool): Whether to remove the geometry column. Defaults to True. sort_columns (bool): Whether to sort the column names. Defaults to False. kwargs: Additional arguments passed to ee.data.computeFeature. Raises: TypeError: ee_object must be an ee.FeatureCollection Returns: pd.DataFrame: pandas DataFrame """ if isinstance(ee_object, ee.Feature): ee_object = ee.FeatureCollection([ee_object]) if not isinstance(ee_object, ee.FeatureCollection): raise TypeError("ee_object must be an ee.FeatureCollection") try: property_names = ee_object.first().propertyNames().sort().getInfo() if remove_geom: data = ee_object.map( lambda f: ee.Feature(None, f.toDictionary(property_names)) ) else: data = ee_object kwargs["expression"] = data kwargs["fileFormat"] = "PANDAS_DATAFRAME" df = ee.data.computeFeatures(kwargs) if isinstance(columns, list): df = df[columns] if remove_geom and ("geo" in df.columns): df = df.drop(columns=["geo"], axis=1) if sort_columns: df = df.reindex(sorted(df.columns), axis=1) return df except Exception as e: raise Exception(e) The provided code snippet includes necessary dependencies for implementing the `random_sampling` function. Write a Python function `def random_sampling( image, region=None, scale=None, projection=None, factor=None, numPixels=None, seed=0, dropNulls=True, tileScale=1.0, geometries=True, to_pandas=False, )` to solve the following problem: Samples the pixels of an image, returning them as a FeatureCollection. Each feature will have 1 property per band in the input image. Note that the default behavior is to drop features that intersect masked pixels, which result in null-valued properties (see dropNulls argument). Args: image (ee.Image): The image to sample. region (ee.Geometry, optional): The region to sample from. If unspecified, uses the image's whole footprint. Defaults to None. scale (float, optional): A nominal scale in meters of the projection to sample in.. Defaults to None. projection (ee.Projection, optional): The projection in which to sample. If unspecified, the projection of the image's first band is used. If specified in addition to scale, rescaled to the specified scale.. Defaults to None. factor (float, optional): A subsampling factor, within (0, 1]. If specified, 'numPixels' must not be specified. Defaults to no subsampling. Defaults to None. numPixels (int, optional): The approximate number of pixels to sample. If specified, 'factor' must not be specified. Defaults to None. seed (int, optional): A randomization seed to use for subsampling. Defaults to True. Defaults to 0. dropNulls (bool, optional): Post filter the result to drop features that have null-valued properties. Defaults to True. tileScale (float, optional): Post filter the result to drop features that have null-valued properties. Defaults to 1. geometries (bool, optional): If true, adds the center of the sampled pixel as the geometry property of the output feature. Otherwise, geometries will be omitted (saving memory). Defaults to True. to_pandas (bool, optional): Whether to return the result as a pandas dataframe. Defaults to False. Raises: TypeError: If the input image is not an ee.Image. Returns: ee.FeatureCollection: Random sampled points. Here is the function: def random_sampling( image, region=None, scale=None, projection=None, factor=None, numPixels=None, seed=0, dropNulls=True, tileScale=1.0, geometries=True, to_pandas=False, ): """Samples the pixels of an image, returning them as a FeatureCollection. Each feature will have 1 property per band in the input image. Note that the default behavior is to drop features that intersect masked pixels, which result in null-valued properties (see dropNulls argument). Args: image (ee.Image): The image to sample. region (ee.Geometry, optional): The region to sample from. If unspecified, uses the image's whole footprint. Defaults to None. scale (float, optional): A nominal scale in meters of the projection to sample in.. Defaults to None. projection (ee.Projection, optional): The projection in which to sample. If unspecified, the projection of the image's first band is used. If specified in addition to scale, rescaled to the specified scale.. Defaults to None. factor (float, optional): A subsampling factor, within (0, 1]. If specified, 'numPixels' must not be specified. Defaults to no subsampling. Defaults to None. numPixels (int, optional): The approximate number of pixels to sample. If specified, 'factor' must not be specified. Defaults to None. seed (int, optional): A randomization seed to use for subsampling. Defaults to True. Defaults to 0. dropNulls (bool, optional): Post filter the result to drop features that have null-valued properties. Defaults to True. tileScale (float, optional): Post filter the result to drop features that have null-valued properties. Defaults to 1. geometries (bool, optional): If true, adds the center of the sampled pixel as the geometry property of the output feature. Otherwise, geometries will be omitted (saving memory). Defaults to True. to_pandas (bool, optional): Whether to return the result as a pandas dataframe. Defaults to False. Raises: TypeError: If the input image is not an ee.Image. Returns: ee.FeatureCollection: Random sampled points. """ if not isinstance(image, ee.Image): raise TypeError("The image must be ee.Image") points = image.sample( **{ "region": region, "scale": scale, "projection": projection, "factor": factor, "numPixels": numPixels, "seed": seed, "dropNulls": dropNulls, "tileScale": tileScale, "geometries": geometries, } ) if to_pandas: return ee_to_df(points) else: return points
Samples the pixels of an image, returning them as a FeatureCollection. Each feature will have 1 property per band in the input image. Note that the default behavior is to drop features that intersect masked pixels, which result in null-valued properties (see dropNulls argument). Args: image (ee.Image): The image to sample. region (ee.Geometry, optional): The region to sample from. If unspecified, uses the image's whole footprint. Defaults to None. scale (float, optional): A nominal scale in meters of the projection to sample in.. Defaults to None. projection (ee.Projection, optional): The projection in which to sample. If unspecified, the projection of the image's first band is used. If specified in addition to scale, rescaled to the specified scale.. Defaults to None. factor (float, optional): A subsampling factor, within (0, 1]. If specified, 'numPixels' must not be specified. Defaults to no subsampling. Defaults to None. numPixels (int, optional): The approximate number of pixels to sample. If specified, 'factor' must not be specified. Defaults to None. seed (int, optional): A randomization seed to use for subsampling. Defaults to True. Defaults to 0. dropNulls (bool, optional): Post filter the result to drop features that have null-valued properties. Defaults to True. tileScale (float, optional): Post filter the result to drop features that have null-valued properties. Defaults to 1. geometries (bool, optional): If true, adds the center of the sampled pixel as the geometry property of the output feature. Otherwise, geometries will be omitted (saving memory). Defaults to True. to_pandas (bool, optional): Whether to return the result as a pandas dataframe. Defaults to False. Raises: TypeError: If the input image is not an ee.Image. Returns: ee.FeatureCollection: Random sampled points.
12,351
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple def gdf_to_ee(gdf, geodesic=True, date=None, date_format="YYYY-MM-dd"): """Converts a GeoPandas GeoDataFrame to ee.FeatureCollection. Args: gdf (geopandas.GeoDataFrame): The input geopandas.GeoDataFrame to be converted ee.FeatureCollection. geodesic (bool, optional): Whether line segments should be interpreted as spherical geodesics. If false, indicates that line segments should be interpreted as planar lines in the specified CRS. If absent, defaults to true if the CRS is geographic (including the default EPSG:4326), or to false if the CRS is projected. Defaults to True. date (str, optional): Column name for the date column. Defaults to None. date_format (str, optional): Date format. A pattern, as described at http://joda-time.sourceforge.net/apidocs/org/joda/time/format/DateTimeFormat.html. Defaults to 'YYYY-MM-dd'. Raises: TypeError: The input data type must be geopandas.GeoDataFrame. Returns: ee.FeatureCollection: The output ee.FeatureCollection converted from the input geopandas.GeoDataFrame. """ check_package(name="geopandas", URL="https://geopandas.org") import geopandas as gpd if not isinstance(gdf, gpd.GeoDataFrame): raise TypeError("The input data type must be geopandas.GeoDataFrame.") out_json = os.path.join(os.getcwd(), random_string(6) + ".geojson") gdf = gdf.to_crs(4326) gdf.to_file(out_json, driver="GeoJSON") fc = geojson_to_ee(out_json, geodesic=geodesic) if date is not None: try: fc = fc.map( lambda x: x.set( "system:time_start", ee.Date.parse(date_format, x.get(date)).millis(), ) ) except Exception as e: raise Exception(e) os.remove(out_json) return fc def osm_to_gdf( query, which_result=None, by_osmid=False, buffer_dist=None, ): """Retrieves place(s) by name or ID from the Nominatim API as a GeoDataFrame. Args: query (str | dict | list): Query string(s) or structured dict(s) to geocode. which_result (INT, optional): Which geocoding result to use. if None, auto-select the first (Multi)Polygon or raise an error if OSM doesn't return one. to get the top match regardless of geometry type, set which_result=1. Defaults to None. by_osmid (bool, optional): If True, handle query as an OSM ID for lookup rather than text search. Defaults to False. buffer_dist (float, optional): Distance to buffer around the place geometry, in meters. Defaults to None. Returns: GeoDataFrame: A GeoPandas GeoDataFrame. """ check_package( "geopandas", "https://geopandas.org/getting_started.html#installation" ) check_package("osmnx", "https://osmnx.readthedocs.io/en/stable/") try: import osmnx as ox gdf = ox.geocode_to_gdf(query, which_result, by_osmid, buffer_dist) return gdf except Exception as e: raise Exception(e) The provided code snippet includes necessary dependencies for implementing the `osm_to_ee` function. Write a Python function `def osm_to_ee( query, which_result=None, by_osmid=False, buffer_dist=None, geodesic=True )` to solve the following problem: Retrieves place(s) by name or ID from the Nominatim API as an ee.FeatureCollection. Args: query (str | dict | list): Query string(s) or structured dict(s) to geocode. which_result (INT, optional): Which geocoding result to use. if None, auto-select the first (Multi)Polygon or raise an error if OSM doesn't return one. to get the top match regardless of geometry type, set which_result=1. Defaults to None. by_osmid (bool, optional): If True, handle query as an OSM ID for lookup rather than text search. Defaults to False. buffer_dist (float, optional): Distance to buffer around the place geometry, in meters. Defaults to None. geodesic (bool, optional): Whether line segments should be interpreted as spherical geodesics. If false, indicates that line segments should be interpreted as planar lines in the specified CRS. If absent, defaults to true if the CRS is geographic (including the default EPSG:4326), or to false if the CRS is projected. Returns: ee.FeatureCollection: An Earth Engine FeatureCollection. Here is the function: def osm_to_ee( query, which_result=None, by_osmid=False, buffer_dist=None, geodesic=True ): """Retrieves place(s) by name or ID from the Nominatim API as an ee.FeatureCollection. Args: query (str | dict | list): Query string(s) or structured dict(s) to geocode. which_result (INT, optional): Which geocoding result to use. if None, auto-select the first (Multi)Polygon or raise an error if OSM doesn't return one. to get the top match regardless of geometry type, set which_result=1. Defaults to None. by_osmid (bool, optional): If True, handle query as an OSM ID for lookup rather than text search. Defaults to False. buffer_dist (float, optional): Distance to buffer around the place geometry, in meters. Defaults to None. geodesic (bool, optional): Whether line segments should be interpreted as spherical geodesics. If false, indicates that line segments should be interpreted as planar lines in the specified CRS. If absent, defaults to true if the CRS is geographic (including the default EPSG:4326), or to false if the CRS is projected. Returns: ee.FeatureCollection: An Earth Engine FeatureCollection. """ gdf = osm_to_gdf(query, which_result, by_osmid, buffer_dist) fc = gdf_to_ee(gdf, geodesic) return fc
Retrieves place(s) by name or ID from the Nominatim API as an ee.FeatureCollection. Args: query (str | dict | list): Query string(s) or structured dict(s) to geocode. which_result (INT, optional): Which geocoding result to use. if None, auto-select the first (Multi)Polygon or raise an error if OSM doesn't return one. to get the top match regardless of geometry type, set which_result=1. Defaults to None. by_osmid (bool, optional): If True, handle query as an OSM ID for lookup rather than text search. Defaults to False. buffer_dist (float, optional): Distance to buffer around the place geometry, in meters. Defaults to None. geodesic (bool, optional): Whether line segments should be interpreted as spherical geodesics. If false, indicates that line segments should be interpreted as planar lines in the specified CRS. If absent, defaults to true if the CRS is geographic (including the default EPSG:4326), or to false if the CRS is projected. Returns: ee.FeatureCollection: An Earth Engine FeatureCollection.
12,352
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple def osm_to_gdf( query, which_result=None, by_osmid=False, buffer_dist=None, ): """Retrieves place(s) by name or ID from the Nominatim API as a GeoDataFrame. Args: query (str | dict | list): Query string(s) or structured dict(s) to geocode. which_result (INT, optional): Which geocoding result to use. if None, auto-select the first (Multi)Polygon or raise an error if OSM doesn't return one. to get the top match regardless of geometry type, set which_result=1. Defaults to None. by_osmid (bool, optional): If True, handle query as an OSM ID for lookup rather than text search. Defaults to False. buffer_dist (float, optional): Distance to buffer around the place geometry, in meters. Defaults to None. Returns: GeoDataFrame: A GeoPandas GeoDataFrame. """ check_package( "geopandas", "https://geopandas.org/getting_started.html#installation" ) check_package("osmnx", "https://osmnx.readthedocs.io/en/stable/") try: import osmnx as ox gdf = ox.geocode_to_gdf(query, which_result, by_osmid, buffer_dist) return gdf except Exception as e: raise Exception(e) The provided code snippet includes necessary dependencies for implementing the `osm_to_geojson` function. Write a Python function `def osm_to_geojson(query, which_result=None, by_osmid=False, buffer_dist=None)` to solve the following problem: Retrieves place(s) by name or ID from the Nominatim API as an ee.FeatureCollection. Args: query (str | dict | list): Query string(s) or structured dict(s) to geocode. which_result (INT, optional): Which geocoding result to use. if None, auto-select the first (Multi)Polygon or raise an error if OSM doesn't return one. to get the top match regardless of geometry type, set which_result=1. Defaults to None. by_osmid (bool, optional): If True, handle query as an OSM ID for lookup rather than text search. Defaults to False. buffer_dist (float, optional): Distance to buffer around the place geometry, in meters. Defaults to None. Returns: ee.FeatureCollection: An Earth Engine FeatureCollection. Here is the function: def osm_to_geojson(query, which_result=None, by_osmid=False, buffer_dist=None): """Retrieves place(s) by name or ID from the Nominatim API as an ee.FeatureCollection. Args: query (str | dict | list): Query string(s) or structured dict(s) to geocode. which_result (INT, optional): Which geocoding result to use. if None, auto-select the first (Multi)Polygon or raise an error if OSM doesn't return one. to get the top match regardless of geometry type, set which_result=1. Defaults to None. by_osmid (bool, optional): If True, handle query as an OSM ID for lookup rather than text search. Defaults to False. buffer_dist (float, optional): Distance to buffer around the place geometry, in meters. Defaults to None. Returns: ee.FeatureCollection: An Earth Engine FeatureCollection. """ gdf = osm_to_gdf(query, which_result, by_osmid, buffer_dist) return gdf.__geo_interface__
Retrieves place(s) by name or ID from the Nominatim API as an ee.FeatureCollection. Args: query (str | dict | list): Query string(s) or structured dict(s) to geocode. which_result (INT, optional): Which geocoding result to use. if None, auto-select the first (Multi)Polygon or raise an error if OSM doesn't return one. to get the top match regardless of geometry type, set which_result=1. Defaults to None. by_osmid (bool, optional): If True, handle query as an OSM ID for lookup rather than text search. Defaults to False. buffer_dist (float, optional): Distance to buffer around the place geometry, in meters. Defaults to None. Returns: ee.FeatureCollection: An Earth Engine FeatureCollection.
12,353
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple The provided code snippet includes necessary dependencies for implementing the `get_api_key` function. Write a Python function `def get_api_key(token_name, m=None)` to solve the following problem: Retrieves an API key based on a system environmen variable. Args: token_name (str): The token name. m (ipyleaflet.Map | folium.Map, optional): A Map instance. Defaults to None. Returns: str: The API key. Here is the function: def get_api_key(token_name, m=None): """Retrieves an API key based on a system environmen variable. Args: token_name (str): The token name. m (ipyleaflet.Map | folium.Map, optional): A Map instance. Defaults to None. Returns: str: The API key. """ api_key = os.environ.get(token_name) if m is not None and token_name in m.api_keys: api_key = m.api_keys[token_name] return api_key
Retrieves an API key based on a system environmen variable. Args: token_name (str): The token name. m (ipyleaflet.Map | folium.Map, optional): A Map instance. Defaults to None. Returns: str: The API key.
12,354
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple def planet_monthly_tropical(api_key=None, token_name="PLANET_API_KEY"): """Generates Planet monthly imagery URLs based on an API key. See https://assets.planet.com/docs/NICFI_UserGuidesFAQ.pdf Args: api_key (str, optional): The Planet API key. Defaults to None. token_name (str, optional): The environment variable name of the API key. Defaults to "PLANET_API_KEY". Raises: ValueError: If the API key could not be found. Returns: list: A list of tile URLs. """ # from datetime import date if api_key is None: api_key = os.environ.get(token_name) if api_key is None: raise ValueError("The Planet API Key must be provided.") today = datetime.date.today() year_now = int(today.strftime("%Y")) month_now = int(today.strftime("%m")) links = [] prefix = "https://tiles.planet.com/basemaps/v1/planet-tiles/planet_medres_normalized_analytic_" subfix = "_mosaic/gmap/{z}/{x}/{y}.png?api_key=" for year in range(2020, year_now + 1): for month in range(1, 13): m_str = str(year) + "-" + str(month).zfill(2) if year == 2020 and month < 9: continue if year == year_now and month >= month_now: break url = f"{prefix}{m_str}{subfix}{api_key}" links.append(url) return links def planet_biannual_tropical(api_key=None, token_name="PLANET_API_KEY"): """Generates Planet bi-annual imagery URLs based on an API key. See https://assets.planet.com/docs/NICFI_UserGuidesFAQ.pdf Args: api_key (str, optional): The Planet API key. Defaults to None. token_name (str, optional): The environment variable name of the API key. Defaults to "PLANET_API_KEY". Raises: ValueError: If the API key could not be found. Returns: list: A list of tile URLs. """ if api_key is None: api_key = os.environ.get(token_name) if api_key is None: raise ValueError("The Planet API Key must be provided.") dates = [ "2015-12_2016-05", "2016-06_2016-11", "2016-12_2017-05", "2017-06_2017-11", "2017-12_2018-05", "2018-06_2018-11", "2018-12_2019-05", "2019-06_2019-11", "2019-12_2020-05", "2020-06_2020-08", ] link = [] prefix = "https://tiles.planet.com/basemaps/v1/planet-tiles/planet_medres_normalized_analytic_" subfix = "_mosaic/gmap/{z}/{x}/{y}.png?api_key=" for d in dates: url = f"{prefix}{d}{subfix}{api_key}" link.append(url) return link The provided code snippet includes necessary dependencies for implementing the `planet_catalog_tropical` function. Write a Python function `def planet_catalog_tropical(api_key=None, token_name="PLANET_API_KEY")` to solve the following problem: Generates Planet bi-annual and monthly imagery URLs based on an API key. See https://assets.planet.com/docs/NICFI_UserGuidesFAQ.pdf Args: api_key (str, optional): The Planet API key. Defaults to None. token_name (str, optional): The environment variable name of the API key. Defaults to "PLANET_API_KEY". Returns: list: A list of tile URLs. Here is the function: def planet_catalog_tropical(api_key=None, token_name="PLANET_API_KEY"): """Generates Planet bi-annual and monthly imagery URLs based on an API key. See https://assets.planet.com/docs/NICFI_UserGuidesFAQ.pdf Args: api_key (str, optional): The Planet API key. Defaults to None. token_name (str, optional): The environment variable name of the API key. Defaults to "PLANET_API_KEY". Returns: list: A list of tile URLs. """ biannual = planet_biannual_tropical(api_key, token_name) monthly = planet_monthly_tropical(api_key, token_name) return biannual + monthly
Generates Planet bi-annual and monthly imagery URLs based on an API key. See https://assets.planet.com/docs/NICFI_UserGuidesFAQ.pdf Args: api_key (str, optional): The Planet API key. Defaults to None. token_name (str, optional): The environment variable name of the API key. Defaults to "PLANET_API_KEY". Returns: list: A list of tile URLs.
12,355
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple def planet_monthly_tiles_tropical( api_key=None, token_name="PLANET_API_KEY", tile_format="ipyleaflet" ): """Generates Planet monthly imagery TileLayer based on an API key. See https://assets.planet.com/docs/NICFI_UserGuidesFAQ.pdf Args: api_key (str, optional): The Planet API key. Defaults to None. token_name (str, optional): The environment variable name of the API key. Defaults to "PLANET_API_KEY". tile_format (str, optional): The TileLayer format, can be either ipyleaflet or folium. Defaults to "ipyleaflet". Raises: ValueError: If the tile layer format is invalid. Returns: dict: A dictionary of TileLayer. """ import folium import ipyleaflet if tile_format not in ["ipyleaflet", "folium"]: raise ValueError("The tile format must be either ipyleaflet or folium.") tiles = {} link = planet_monthly_tropical(api_key, token_name) for url in link: index = url.find("20") name = "Planet_" + url[index : index + 7] if tile_format == "ipyleaflet": tile = ipyleaflet.TileLayer(url=url, attribution="Planet", name=name) else: tile = folium.TileLayer( tiles=url, attr="Planet", name=name, overlay=True, control=True, ) tiles[name] = tile return tiles def planet_biannual_tiles_tropical( api_key=None, token_name="PLANET_API_KEY", tile_format="ipyleaflet" ): """Generates Planet bi-annual imagery TileLayer based on an API key. See https://assets.planet.com/docs/NICFI_UserGuidesFAQ.pdf Args: api_key (str, optional): The Planet API key. Defaults to None. token_name (str, optional): The environment variable name of the API key. Defaults to "PLANET_API_KEY". tile_format (str, optional): The TileLayer format, can be either ipyleaflet or folium. Defaults to "ipyleaflet". Raises: ValueError: If the tile layer format is invalid. Returns: dict: A dictionary of TileLayer. """ import folium import ipyleaflet if tile_format not in ["ipyleaflet", "folium"]: raise ValueError("The tile format must be either ipyleaflet or folium.") tiles = {} link = planet_biannual_tropical(api_key, token_name) for url in link: index = url.find("20") name = "Planet_" + url[index : index + 15] if tile_format == "ipyleaflet": tile = ipyleaflet.TileLayer(url=url, attribution="Planet", name=name) else: tile = folium.TileLayer( tiles=url, attr="Planet", name=name, overlay=True, control=True, ) tiles[name] = tile return tiles The provided code snippet includes necessary dependencies for implementing the `planet_tiles_tropical` function. Write a Python function `def planet_tiles_tropical( api_key=None, token_name="PLANET_API_KEY", tile_format="ipyleaflet" )` to solve the following problem: Generates Planet monthly imagery TileLayer based on an API key. See https://assets.planet.com/docs/NICFI_UserGuidesFAQ.pdf Args: api_key (str, optional): The Planet API key. Defaults to None. token_name (str, optional): The environment variable name of the API key. Defaults to "PLANET_API_KEY". tile_format (str, optional): The TileLayer format, can be either ipyleaflet or folium. Defaults to "ipyleaflet". Raises: ValueError: If the tile layer format is invalid. Returns: dict: A dictionary of TileLayer. Here is the function: def planet_tiles_tropical( api_key=None, token_name="PLANET_API_KEY", tile_format="ipyleaflet" ): """Generates Planet monthly imagery TileLayer based on an API key. See https://assets.planet.com/docs/NICFI_UserGuidesFAQ.pdf Args: api_key (str, optional): The Planet API key. Defaults to None. token_name (str, optional): The environment variable name of the API key. Defaults to "PLANET_API_KEY". tile_format (str, optional): The TileLayer format, can be either ipyleaflet or folium. Defaults to "ipyleaflet". Raises: ValueError: If the tile layer format is invalid. Returns: dict: A dictionary of TileLayer. """ catalog = {} biannul = planet_biannual_tiles_tropical(api_key, token_name, tile_format) monthly = planet_monthly_tiles_tropical(api_key, token_name, tile_format) for key in biannul: catalog[key] = biannul[key] for key in monthly: catalog[key] = monthly[key] return catalog
Generates Planet monthly imagery TileLayer based on an API key. See https://assets.planet.com/docs/NICFI_UserGuidesFAQ.pdf Args: api_key (str, optional): The Planet API key. Defaults to None. token_name (str, optional): The environment variable name of the API key. Defaults to "PLANET_API_KEY". tile_format (str, optional): The TileLayer format, can be either ipyleaflet or folium. Defaults to "ipyleaflet". Raises: ValueError: If the tile layer format is invalid. Returns: dict: A dictionary of TileLayer.
12,356
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple def planet_monthly(api_key=None, token_name="PLANET_API_KEY"): """Generates Planet monthly imagery URLs based on an API key. To get a Planet API key, see https://developers.planet.com/quickstart/apis/ Args: api_key (str, optional): The Planet API key. Defaults to None. token_name (str, optional): The environment variable name of the API key. Defaults to "PLANET_API_KEY". Raises: ValueError: If the API key could not be found. Returns: list: A list of tile URLs. """ # from datetime import date if api_key is None: api_key = os.environ.get(token_name) if api_key is None: raise ValueError("The Planet API Key must be provided.") today = datetime.date.today() year_now = int(today.strftime("%Y")) month_now = int(today.strftime("%m")) link = [] prefix = "https://tiles.planet.com/basemaps/v1/planet-tiles/global_monthly_" subfix = "_mosaic/gmap/{z}/{x}/{y}.png?api_key=" for year in range(2016, year_now + 1): for month in range(1, 13): m_str = str(year) + "_" + str(month).zfill(2) if year == year_now and month >= month_now: break url = f"{prefix}{m_str}{subfix}{api_key}" link.append(url) return link def planet_quarterly(api_key=None, token_name="PLANET_API_KEY"): """Generates Planet quarterly imagery URLs based on an API key. To get a Planet API key, see https://developers.planet.com/quickstart/apis/ Args: api_key (str, optional): The Planet API key. Defaults to None. token_name (str, optional): The environment variable name of the API key. Defaults to "PLANET_API_KEY". Raises: ValueError: If the API key could not be found. Returns: list: A list of tile URLs. """ # from datetime import date if api_key is None: api_key = os.environ.get(token_name) if api_key is None: raise ValueError("The Planet API Key must be provided.") today = datetime.date.today() year_now = int(today.strftime("%Y")) month_now = int(today.strftime("%m")) quarter_now = (month_now - 1) // 3 + 1 link = [] prefix = "https://tiles.planet.com/basemaps/v1/planet-tiles/global_quarterly_" subfix = "_mosaic/gmap/{z}/{x}/{y}.png?api_key=" for year in range(2016, year_now + 1): for quarter in range(1, 5): m_str = str(year) + "q" + str(quarter) if year == year_now and quarter >= quarter_now: break url = f"{prefix}{m_str}{subfix}{api_key}" link.append(url) return link The provided code snippet includes necessary dependencies for implementing the `planet_catalog` function. Write a Python function `def planet_catalog(api_key=None, token_name="PLANET_API_KEY")` to solve the following problem: Generates Planet bi-annual and monthly imagery URLs based on an API key. See https://assets.planet.com/docs/NICFI_UserGuidesFAQ.pdf Args: api_key (str, optional): The Planet API key. Defaults to None. token_name (str, optional): The environment variable name of the API key. Defaults to "PLANET_API_KEY". Returns: list: A list of tile URLs. Here is the function: def planet_catalog(api_key=None, token_name="PLANET_API_KEY"): """Generates Planet bi-annual and monthly imagery URLs based on an API key. See https://assets.planet.com/docs/NICFI_UserGuidesFAQ.pdf Args: api_key (str, optional): The Planet API key. Defaults to None. token_name (str, optional): The environment variable name of the API key. Defaults to "PLANET_API_KEY". Returns: list: A list of tile URLs. """ quarterly = planet_quarterly(api_key, token_name) monthly = planet_monthly(api_key, token_name) return quarterly + monthly
Generates Planet bi-annual and monthly imagery URLs based on an API key. See https://assets.planet.com/docs/NICFI_UserGuidesFAQ.pdf Args: api_key (str, optional): The Planet API key. Defaults to None. token_name (str, optional): The environment variable name of the API key. Defaults to "PLANET_API_KEY". Returns: list: A list of tile URLs.
12,357
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple def planet_by_quarter( year=2016, quarter=1, api_key=None, token_name="PLANET_API_KEY", ): """Gets Planet global mosaic tile url by quarter. To get a Planet API key, see https://developers.planet.com/quickstart/apis/ Args: year (int, optional): The year of Planet global mosaic, must be >=2016. Defaults to 2016. quarter (int, optional): The quarter of Planet global mosaic, must be 1-4. Defaults to 1. api_key (str, optional): The Planet API key. Defaults to None. token_name (str, optional): The environment variable name of the API key. Defaults to "PLANET_API_KEY". Raises: ValueError: The Planet API key is not provided. ValueError: The year is invalid. ValueError: The quarter is invalid. ValueError: The quarter is invalid. Returns: str: A Planet global mosaic tile url. """ # from datetime import date if api_key is None: api_key = os.environ.get(token_name) if api_key is None: raise ValueError("The Planet API Key must be provided.") today = datetime.date.today() year_now = int(today.strftime("%Y")) month_now = int(today.strftime("%m")) quarter_now = (month_now - 1) // 3 + 1 if year > year_now: raise ValueError(f"Year must be between 2016 and {year_now}.") elif year == year_now and quarter >= quarter_now: raise ValueError(f"Quarter must be less than {quarter_now} for year {year_now}") if quarter < 1 or quarter > 4: raise ValueError("Quarter must be between 1 and 4.") prefix = "https://tiles.planet.com/basemaps/v1/planet-tiles/global_quarterly_" subfix = "_mosaic/gmap/{z}/{x}/{y}.png?api_key=" m_str = str(year) + "q" + str(quarter) url = f"{prefix}{m_str}{subfix}{api_key}" return url The provided code snippet includes necessary dependencies for implementing the `planet_tile_by_quarter` function. Write a Python function `def planet_tile_by_quarter( year=2016, quarter=1, name=None, api_key=None, token_name="PLANET_API_KEY", tile_format="ipyleaflet", )` to solve the following problem: Generates Planet quarterly imagery TileLayer based on an API key. To get a Planet API key, see https://developers.planet.com/quickstart/apis Args: year (int, optional): The year of Planet global mosaic, must be >=2016. Defaults to 2016. quarter (int, optional): The quarter of Planet global mosaic, must be 1-4. Defaults to 1. name (str, optional): The layer name to use. Defaults to None. api_key (str, optional): The Planet API key. Defaults to None. token_name (str, optional): The environment variable name of the API key. Defaults to "PLANET_API_KEY". tile_format (str, optional): The TileLayer format, can be either ipyleaflet or folium. Defaults to "ipyleaflet". Raises: ValueError: If the tile layer format is invalid. Returns: dict: A dictionary of TileLayer. Here is the function: def planet_tile_by_quarter( year=2016, quarter=1, name=None, api_key=None, token_name="PLANET_API_KEY", tile_format="ipyleaflet", ): """Generates Planet quarterly imagery TileLayer based on an API key. To get a Planet API key, see https://developers.planet.com/quickstart/apis Args: year (int, optional): The year of Planet global mosaic, must be >=2016. Defaults to 2016. quarter (int, optional): The quarter of Planet global mosaic, must be 1-4. Defaults to 1. name (str, optional): The layer name to use. Defaults to None. api_key (str, optional): The Planet API key. Defaults to None. token_name (str, optional): The environment variable name of the API key. Defaults to "PLANET_API_KEY". tile_format (str, optional): The TileLayer format, can be either ipyleaflet or folium. Defaults to "ipyleaflet". Raises: ValueError: If the tile layer format is invalid. Returns: dict: A dictionary of TileLayer. """ import folium import ipyleaflet if tile_format not in ["ipyleaflet", "folium"]: raise ValueError("The tile format must be either ipyleaflet or folium.") url = planet_by_quarter(year, quarter, api_key, token_name) if name is None: name = "Planet_" + str(year) + "_q" + str(quarter) if tile_format == "ipyleaflet": tile = ipyleaflet.TileLayer(url=url, attribution="Planet", name=name) else: tile = folium.TileLayer( tiles=url, attr="Planet", name=name, overlay=True, control=True, ) return tile
Generates Planet quarterly imagery TileLayer based on an API key. To get a Planet API key, see https://developers.planet.com/quickstart/apis Args: year (int, optional): The year of Planet global mosaic, must be >=2016. Defaults to 2016. quarter (int, optional): The quarter of Planet global mosaic, must be 1-4. Defaults to 1. name (str, optional): The layer name to use. Defaults to None. api_key (str, optional): The Planet API key. Defaults to None. token_name (str, optional): The environment variable name of the API key. Defaults to "PLANET_API_KEY". tile_format (str, optional): The TileLayer format, can be either ipyleaflet or folium. Defaults to "ipyleaflet". Raises: ValueError: If the tile layer format is invalid. Returns: dict: A dictionary of TileLayer.
12,358
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple def planet_by_month( year=2016, month=1, api_key=None, token_name="PLANET_API_KEY", ): """Gets Planet global mosaic tile url by month. To get a Planet API key, see https://developers.planet.com/quickstart/apis/ Args: year (int, optional): The year of Planet global mosaic, must be >=2016. Defaults to 2016. month (int, optional): The month of Planet global mosaic, must be 1-12. Defaults to 1. api_key (str, optional): The Planet API key. Defaults to None. token_name (str, optional): The environment variable name of the API key. Defaults to "PLANET_API_KEY". Raises: ValueError: The Planet API key is not provided. ValueError: The year is invalid. ValueError: The month is invalid. ValueError: The month is invalid. Returns: str: A Planet global mosaic tile url. """ # from datetime import date if api_key is None: api_key = os.environ.get(token_name) if api_key is None: raise ValueError("The Planet API Key must be provided.") today = datetime.date.today() year_now = int(today.strftime("%Y")) month_now = int(today.strftime("%m")) # quarter_now = (month_now - 1) // 3 + 1 if year > year_now: raise ValueError(f"Year must be between 2016 and {year_now}.") elif year == year_now and month >= month_now: raise ValueError(f"Month must be less than {month_now} for year {year_now}") if month < 1 or month > 12: raise ValueError("Month must be between 1 and 12.") prefix = "https://tiles.planet.com/basemaps/v1/planet-tiles/global_monthly_" subfix = "_mosaic/gmap/{z}/{x}/{y}.png?api_key=" m_str = str(year) + "_" + str(month).zfill(2) url = f"{prefix}{m_str}{subfix}{api_key}" return url The provided code snippet includes necessary dependencies for implementing the `planet_tile_by_month` function. Write a Python function `def planet_tile_by_month( year=2016, month=1, name=None, api_key=None, token_name="PLANET_API_KEY", tile_format="ipyleaflet", )` to solve the following problem: Generates Planet monthly imagery TileLayer based on an API key. To get a Planet API key, see https://developers.planet.com/quickstart/apis Args: year (int, optional): The year of Planet global mosaic, must be >=2016. Defaults to 2016. month (int, optional): The month of Planet global mosaic, must be 1-12. Defaults to 1. name (str, optional): The layer name to use. Defaults to None. api_key (str, optional): The Planet API key. Defaults to None. token_name (str, optional): The environment variable name of the API key. Defaults to "PLANET_API_KEY". tile_format (str, optional): The TileLayer format, can be either ipyleaflet or folium. Defaults to "ipyleaflet". Raises: ValueError: If the tile layer format is invalid. Returns: dict: A dictionary of TileLayer. Here is the function: def planet_tile_by_month( year=2016, month=1, name=None, api_key=None, token_name="PLANET_API_KEY", tile_format="ipyleaflet", ): """Generates Planet monthly imagery TileLayer based on an API key. To get a Planet API key, see https://developers.planet.com/quickstart/apis Args: year (int, optional): The year of Planet global mosaic, must be >=2016. Defaults to 2016. month (int, optional): The month of Planet global mosaic, must be 1-12. Defaults to 1. name (str, optional): The layer name to use. Defaults to None. api_key (str, optional): The Planet API key. Defaults to None. token_name (str, optional): The environment variable name of the API key. Defaults to "PLANET_API_KEY". tile_format (str, optional): The TileLayer format, can be either ipyleaflet or folium. Defaults to "ipyleaflet". Raises: ValueError: If the tile layer format is invalid. Returns: dict: A dictionary of TileLayer. """ import folium import ipyleaflet if tile_format not in ["ipyleaflet", "folium"]: raise ValueError("The tile format must be either ipyleaflet or folium.") url = planet_by_month(year, month, api_key, token_name) if name is None: name = "Planet_" + str(year) + "_" + str(month).zfill(2) if tile_format == "ipyleaflet": tile = ipyleaflet.TileLayer(url=url, attribution="Planet", name=name) else: tile = folium.TileLayer( tiles=url, attr="Planet", name=name, overlay=True, control=True, ) return tile
Generates Planet monthly imagery TileLayer based on an API key. To get a Planet API key, see https://developers.planet.com/quickstart/apis Args: year (int, optional): The year of Planet global mosaic, must be >=2016. Defaults to 2016. month (int, optional): The month of Planet global mosaic, must be 1-12. Defaults to 1. name (str, optional): The layer name to use. Defaults to None. api_key (str, optional): The Planet API key. Defaults to None. token_name (str, optional): The environment variable name of the API key. Defaults to "PLANET_API_KEY". tile_format (str, optional): The TileLayer format, can be either ipyleaflet or folium. Defaults to "ipyleaflet". Raises: ValueError: If the tile layer format is invalid. Returns: dict: A dictionary of TileLayer.
12,359
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple The provided code snippet includes necessary dependencies for implementing the `get_current_latlon` function. Write a Python function `def get_current_latlon()` to solve the following problem: Get the current latitude and longitude based on the user's location. Here is the function: def get_current_latlon(): """Get the current latitude and longitude based on the user's location.""" import geocoder g = geocoder.ip("me") props = g.geojson["features"][0]["properties"] lat = props["lat"] lon = props["lng"] return lat, lon
Get the current latitude and longitude based on the user's location.
12,360
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple The provided code snippet includes necessary dependencies for implementing the `get_census_dict` function. Write a Python function `def get_census_dict(reset=False)` to solve the following problem: Returns a dictionary of Census data. Args: reset (bool, optional): Reset the dictionary. Defaults to False. Returns: dict: A dictionary of Census data. Here is the function: def get_census_dict(reset=False): """Returns a dictionary of Census data. Args: reset (bool, optional): Reset the dictionary. Defaults to False. Returns: dict: A dictionary of Census data. """ import pkg_resources pkg_dir = os.path.dirname(pkg_resources.resource_filename("geemap", "geemap.py")) census_data = os.path.join(pkg_dir, "data/census_data.json") if reset: try: from owslib.wms import WebMapService except ImportError: raise ImportError( 'The owslib package must be installed to use this function. Install with "pip install owslib"' ) census_dict = {} names = [ "Current", "ACS 2021", "ACS 2019", "ACS 2018", "ACS 2017", "ACS 2016", "ACS 2015", "ACS 2014", "ACS 2013", "ACS 2012", "ECON 2012", "Census 2020", "Census 2010", "Physical Features", "Decennial Census 2020", "Decennial Census 2010", "Decennial Census 2000", "Decennial Physical Features", ] links = {} print("Retrieving data. Please wait ...") for name in names: if "Decennial" not in name: links[name] = ( f"https://tigerweb.geo.census.gov/arcgis/services/TIGERweb/tigerWMS_{name.replace(' ', '')}/MapServer/WMSServer" ) else: links[name] = ( f"https://tigerweb.geo.census.gov/arcgis/services/Census2020/tigerWMS_{name.replace('Decennial', '').replace(' ', '')}/MapServer/WMSServer" ) wms = WebMapService(links[name], timeout=300) layers = list(wms.contents) layers.sort() census_dict[name] = { "url": links[name], "layers": layers, # "title": wms.identification.title, # "abstract": wms.identification.abstract, } with open(census_data, "w") as f: json.dump(census_dict, f, indent=4) else: with open(census_data, "r") as f: census_dict = json.load(f) return census_dict
Returns a dictionary of Census data. Args: reset (bool, optional): Reset the dictionary. Defaults to False. Returns: dict: A dictionary of Census data.
12,361
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple The provided code snippet includes necessary dependencies for implementing the `get_wms_layers` function. Write a Python function `def get_wms_layers(url, return_titles=False)` to solve the following problem: Returns a list of WMS layers from a WMS service. Args: url (str): The URL of the WMS service. return_titles (bool, optional): If True, the titles of the layers will be returned. Defaults to False. Returns: list: A list of WMS layers. Here is the function: def get_wms_layers(url, return_titles=False): """Returns a list of WMS layers from a WMS service. Args: url (str): The URL of the WMS service. return_titles (bool, optional): If True, the titles of the layers will be returned. Defaults to False. Returns: list: A list of WMS layers. """ from owslib.wms import WebMapService wms = WebMapService(url) layers = list(wms.contents) layers.sort() if return_titles: return layers, [wms[layer].title for layer in layers] else: return layers
Returns a list of WMS layers from a WMS service. Args: url (str): The URL of the WMS service. return_titles (bool, optional): If True, the titles of the layers will be returned. Defaults to False. Returns: list: A list of WMS layers.
12,362
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple The provided code snippet includes necessary dependencies for implementing the `read_file_from_url` function. Write a Python function `def read_file_from_url(url, return_type="list", encoding="utf-8")` to solve the following problem: Reads a file from a URL. Args: url (str): The URL of the file. return_type (str, optional): The return type, can either be string or list. Defaults to "list". encoding (str, optional): The encoding of the file. Defaults to "utf-8". Raises: ValueError: The return type must be either list or string. Returns: str | list: The contents of the file. Here is the function: def read_file_from_url(url, return_type="list", encoding="utf-8"): """Reads a file from a URL. Args: url (str): The URL of the file. return_type (str, optional): The return type, can either be string or list. Defaults to "list". encoding (str, optional): The encoding of the file. Defaults to "utf-8". Raises: ValueError: The return type must be either list or string. Returns: str | list: The contents of the file. """ from urllib.request import urlopen if return_type == "list": return [line.decode(encoding).rstrip() for line in urlopen(url).readlines()] elif return_type == "string": return urlopen(url).read().decode(encoding) else: raise ValueError("The return type must be either list or string.")
Reads a file from a URL. Args: url (str): The URL of the file. return_type (str, optional): The return type, can either be string or list. Defaults to "list". encoding (str, optional): The encoding of the file. Defaults to "utf-8". Raises: ValueError: The return type must be either list or string. Returns: str | list: The contents of the file.
12,363
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple The provided code snippet includes necessary dependencies for implementing the `create_download_button` function. Write a Python function `def create_download_button( label, data, file_name=None, mime=None, key=None, help=None, on_click=None, args=None, **kwargs, )` to solve the following problem: Streamlit function to create a download button. Args: label (str): A short label explaining to the user what this button is for.. data (str | list): The contents of the file to be downloaded. See example below for caching techniques to avoid recomputing this data unnecessarily. file_name (str, optional): An optional string to use as the name of the file to be downloaded, such as 'my_file.csv'. If not specified, the name will be automatically generated. Defaults to None. mime (str, optional): The MIME type of the data. If None, defaults to "text/plain" (if data is of type str or is a textual file) or "application/octet-stream" (if data is of type bytes or is a binary file). Defaults to None. key (str, optional): An optional string or integer to use as the unique key for the widget. If this is omitted, a key will be generated for the widget based on its content. Multiple widgets of the same type may not share the same key. Defaults to None. help (str, optional): An optional tooltip that gets displayed when the button is hovered over. Defaults to None. on_click (str, optional): An optional callback invoked when this button is clicked. Defaults to None. args (list, optional): An optional tuple of args to pass to the callback. Defaults to None. kwargs (dict, optional): An optional tuple of args to pass to the callback. Here is the function: def create_download_button( label, data, file_name=None, mime=None, key=None, help=None, on_click=None, args=None, **kwargs, ): """Streamlit function to create a download button. Args: label (str): A short label explaining to the user what this button is for.. data (str | list): The contents of the file to be downloaded. See example below for caching techniques to avoid recomputing this data unnecessarily. file_name (str, optional): An optional string to use as the name of the file to be downloaded, such as 'my_file.csv'. If not specified, the name will be automatically generated. Defaults to None. mime (str, optional): The MIME type of the data. If None, defaults to "text/plain" (if data is of type str or is a textual file) or "application/octet-stream" (if data is of type bytes or is a binary file). Defaults to None. key (str, optional): An optional string or integer to use as the unique key for the widget. If this is omitted, a key will be generated for the widget based on its content. Multiple widgets of the same type may not share the same key. Defaults to None. help (str, optional): An optional tooltip that gets displayed when the button is hovered over. Defaults to None. on_click (str, optional): An optional callback invoked when this button is clicked. Defaults to None. args (list, optional): An optional tuple of args to pass to the callback. Defaults to None. kwargs (dict, optional): An optional tuple of args to pass to the callback. """ try: import streamlit as st import pandas as pd if isinstance(data, str): if file_name is None: file_name = data.split("/")[-1] if data.endswith(".csv"): data = pd.read_csv(data).to_csv() if mime is None: mime = "text/csv" return st.download_button( label, data, file_name, mime, key, help, on_click, args, **kwargs ) elif ( data.endswith(".gif") or data.endswith(".png") or data.endswith(".jpg") ): if mime is None: mime = f"image/{os.path.splitext(data)[1][1:]}" with open(data, "rb") as file: return st.download_button( label, file, file_name, mime, key, help, on_click, args, **kwargs, ) else: return st.download_button( label, label, data, file_name, mime, key, help, on_click, args, **kwargs, ) except ImportError: print("Streamlit is not installed. Please run 'pip install streamlit'.") return except Exception as e: raise Exception(e)
Streamlit function to create a download button. Args: label (str): A short label explaining to the user what this button is for.. data (str | list): The contents of the file to be downloaded. See example below for caching techniques to avoid recomputing this data unnecessarily. file_name (str, optional): An optional string to use as the name of the file to be downloaded, such as 'my_file.csv'. If not specified, the name will be automatically generated. Defaults to None. mime (str, optional): The MIME type of the data. If None, defaults to "text/plain" (if data is of type str or is a textual file) or "application/octet-stream" (if data is of type bytes or is a binary file). Defaults to None. key (str, optional): An optional string or integer to use as the unique key for the widget. If this is omitted, a key will be generated for the widget based on its content. Multiple widgets of the same type may not share the same key. Defaults to None. help (str, optional): An optional tooltip that gets displayed when the button is hovered over. Defaults to None. on_click (str, optional): An optional callback invoked when this button is clicked. Defaults to None. args (list, optional): An optional tuple of args to pass to the callback. Defaults to None. kwargs (dict, optional): An optional tuple of args to pass to the callback.
12,364
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple def check_package(name, URL=""): try: __import__(name.lower()) except Exception: raise ImportError( f"{name} is not installed. Please install it before proceeding. {URL}" ) The provided code snippet includes necessary dependencies for implementing the `gdf_to_geojson` function. Write a Python function `def gdf_to_geojson(gdf, out_geojson=None, epsg=None)` to solve the following problem: Converts a GeoDataFame to GeoJSON. Args: gdf (GeoDataFrame): A GeoPandas GeoDataFrame. out_geojson (str, optional): File path to he output GeoJSON. Defaults to None. epsg (str, optional): An EPSG string, e.g., "4326". Defaults to None. Raises: TypeError: When the output file extension is incorrect. Exception: When the conversion fails. Returns: dict: When the out_json is None returns a dict. Here is the function: def gdf_to_geojson(gdf, out_geojson=None, epsg=None): """Converts a GeoDataFame to GeoJSON. Args: gdf (GeoDataFrame): A GeoPandas GeoDataFrame. out_geojson (str, optional): File path to he output GeoJSON. Defaults to None. epsg (str, optional): An EPSG string, e.g., "4326". Defaults to None. Raises: TypeError: When the output file extension is incorrect. Exception: When the conversion fails. Returns: dict: When the out_json is None returns a dict. """ check_package(name="geopandas", URL="https://geopandas.org") try: if epsg is not None: gdf = gdf.to_crs(epsg=epsg) geojson = gdf.__geo_interface__ if out_geojson is None: return geojson else: ext = os.path.splitext(out_geojson)[1] if ext.lower() not in [".json", ".geojson"]: raise TypeError( "The output file extension must be either .json or .geojson" ) out_dir = os.path.dirname(out_geojson) if not os.path.exists(out_dir): os.makedirs(out_dir) gdf.to_file(out_geojson, driver="GeoJSON") except Exception as e: raise Exception(e)
Converts a GeoDataFame to GeoJSON. Args: gdf (GeoDataFrame): A GeoPandas GeoDataFrame. out_geojson (str, optional): File path to he output GeoJSON. Defaults to None. epsg (str, optional): An EPSG string, e.g., "4326". Defaults to None. Raises: TypeError: When the output file extension is incorrect. Exception: When the conversion fails. Returns: dict: When the out_json is None returns a dict.
12,365
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple def mosaic(images, output, merge_args={}, verbose=True, **kwargs): """Mosaics a list of images into a single image. Inspired by https://bit.ly/3A6roDK. Args: images (str | list): An input directory containing images or a list of images. output (str): The output image filepath. merge_args (dict, optional): A dictionary of arguments to pass to the rasterio.merge function. Defaults to {}. verbose (bool, optional): Whether to print progress. Defaults to True. """ from rasterio.merge import merge import rasterio as rio from pathlib import Path output = os.path.abspath(output) if isinstance(images, str): path = Path(images) raster_files = list(path.iterdir()) elif isinstance(images, list): raster_files = images else: raise ValueError("images must be a list of raster files.") raster_to_mosiac = [] if not os.path.exists(os.path.dirname(output)): os.makedirs(os.path.dirname(output)) for index, p in enumerate(raster_files): if verbose: print(f"Reading {index+1}/{len(raster_files)}: {os.path.basename(p)}") raster = rio.open(p, **kwargs) raster_to_mosiac.append(raster) if verbose: print("Merging rasters...") arr, transform = merge(raster_to_mosiac, **merge_args) output_meta = raster.meta.copy() output_meta.update( { "driver": "GTiff", "height": arr.shape[1], "width": arr.shape[2], "transform": transform, } ) with rio.open(output, "w", **output_meta) as m: m.write(arr) The provided code snippet includes necessary dependencies for implementing the `create_contours` function. Write a Python function `def create_contours( image, min_value, max_value, interval, kernel=None, region=None, values=None )` to solve the following problem: Creates contours from an image. Code adapted from https://mygeoblog.com/2017/01/28/contour-lines-in-gee. Credits to MyGeoBlog. Args: image (ee.Image): An image to create contours. min_value (float): The minimum value of contours. max_value (float): The maximum value of contours. interval (float): The interval between contours. kernel (ee.Kernel, optional): The kernel to use for smoothing image. Defaults to None. region (ee.Geometry | ee.FeatureCollection, optional): The region of interest. Defaults to None. values (list, optional): A list of values to create contours for. Defaults to None. Raises: TypeError: The image must be an ee.Image. TypeError: The region must be an ee.Geometry or ee.FeatureCollection. Returns: ee.Image: The image containing contours. Here is the function: def create_contours( image, min_value, max_value, interval, kernel=None, region=None, values=None ): """Creates contours from an image. Code adapted from https://mygeoblog.com/2017/01/28/contour-lines-in-gee. Credits to MyGeoBlog. Args: image (ee.Image): An image to create contours. min_value (float): The minimum value of contours. max_value (float): The maximum value of contours. interval (float): The interval between contours. kernel (ee.Kernel, optional): The kernel to use for smoothing image. Defaults to None. region (ee.Geometry | ee.FeatureCollection, optional): The region of interest. Defaults to None. values (list, optional): A list of values to create contours for. Defaults to None. Raises: TypeError: The image must be an ee.Image. TypeError: The region must be an ee.Geometry or ee.FeatureCollection. Returns: ee.Image: The image containing contours. """ if not isinstance(image, ee.Image): raise TypeError("The image must be an ee.Image.") if region is not None: if isinstance(region, ee.FeatureCollection) or isinstance(region, ee.Geometry): pass else: raise TypeError( "The region must be an ee.Geometry or ee.FeatureCollection." ) if kernel is None: kernel = ee.Kernel.gaussian(5, 3) if isinstance(values, list): values = ee.List(values) elif isinstance(values, ee.List): pass if values is None: values = ee.List.sequence(min_value, max_value, interval) def contouring(value): mycountour = ( image.convolve(kernel) .subtract(ee.Image.constant(value)) .zeroCrossing() .multiply(ee.Image.constant(value).toFloat()) ) return mycountour.mask(mycountour) contours = values.map(contouring) if region is not None: if isinstance(region, ee.FeatureCollection): return ee.ImageCollection(contours).mosaic().clipToCollection(region) elif isinstance(region, ee.Geometry): return ee.ImageCollection(contours).mosaic().clip(region) else: return ee.ImageCollection(contours).mosaic()
Creates contours from an image. Code adapted from https://mygeoblog.com/2017/01/28/contour-lines-in-gee. Credits to MyGeoBlog. Args: image (ee.Image): An image to create contours. min_value (float): The minimum value of contours. max_value (float): The maximum value of contours. interval (float): The interval between contours. kernel (ee.Kernel, optional): The kernel to use for smoothing image. Defaults to None. region (ee.Geometry | ee.FeatureCollection, optional): The region of interest. Defaults to None. values (list, optional): A list of values to create contours for. Defaults to None. Raises: TypeError: The image must be an ee.Image. TypeError: The region must be an ee.Geometry or ee.FeatureCollection. Returns: ee.Image: The image containing contours.
12,366
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple palettes = Box(_palette_dict, frozen_box=True) The provided code snippet includes necessary dependencies for implementing the `get_palettable` function. Write a Python function `def get_palettable(types=None)` to solve the following problem: Get a list of palettable color palettes. Args: types (list, optional): A list of palettable types to return, e.g., types=['matplotlib', 'cartocolors']. Defaults to None. Returns: list: A list of palettable color palettes. Here is the function: def get_palettable(types=None): """Get a list of palettable color palettes. Args: types (list, optional): A list of palettable types to return, e.g., types=['matplotlib', 'cartocolors']. Defaults to None. Returns: list: A list of palettable color palettes. """ try: import palettable except ImportError: raise ImportError( "The palettable package is not installed. Please install it with `pip install palettable`." ) if types is not None and (not isinstance(types, list)): raise ValueError("The types must be a list.") allowed_palettes = [ "cartocolors", "cmocean", "colorbrewer", "cubehelix", "lightbartlein", "matplotlib", "mycarta", "scientific", "tableau", "wesanderson", ] if types is None: types = allowed_palettes[:] if all(x in allowed_palettes for x in types): pass else: raise ValueError( "The types must be one of the following: " + ", ".join(allowed_palettes) ) palettes = [] if "cartocolors" in types: cartocolors_diverging = [ f"cartocolors.diverging.{c}" for c in dir(palettable.cartocolors.diverging)[:-19] ] cartocolors_qualitative = [ f"cartocolors.qualitative.{c}" for c in dir(palettable.cartocolors.qualitative)[:-19] ] cartocolors_sequential = [ f"cartocolors.sequential.{c}" for c in dir(palettable.cartocolors.sequential)[:-41] ] palettes = ( palettes + cartocolors_diverging + cartocolors_qualitative + cartocolors_sequential ) if "cmocean" in types: cmocean_diverging = [ f"cmocean.diverging.{c}" for c in dir(palettable.cmocean.diverging)[:-19] ] cmocean_sequential = [ f"cmocean.sequential.{c}" for c in dir(palettable.cmocean.sequential)[:-19] ] palettes = palettes + cmocean_diverging + cmocean_sequential if "colorbrewer" in types: colorbrewer_diverging = [ f"colorbrewer.diverging.{c}" for c in dir(palettable.colorbrewer.diverging)[:-19] ] colorbrewer_qualitative = [ f"colorbrewer.qualitative.{c}" for c in dir(palettable.colorbrewer.qualitative)[:-19] ] colorbrewer_sequential = [ f"colorbrewer.sequential.{c}" for c in dir(palettable.colorbrewer.sequential)[:-41] ] palettes = ( palettes + colorbrewer_diverging + colorbrewer_qualitative + colorbrewer_sequential ) if "cubehelix" in types: cubehelix = [ "classic_16", "cubehelix1_16", "cubehelix2_16", "cubehelix3_16", "jim_special_16", "perceptual_rainbow_16", "purple_16", "red_16", ] cubehelix = [f"cubehelix.{c}" for c in cubehelix] palettes = palettes + cubehelix if "lightbartlein" in types: lightbartlein_diverging = [ f"lightbartlein.diverging.{c}" for c in dir(palettable.lightbartlein.diverging)[:-19] ] lightbartlein_sequential = [ f"lightbartlein.sequential.{c}" for c in dir(palettable.lightbartlein.sequential)[:-19] ] palettes = palettes + lightbartlein_diverging + lightbartlein_sequential if "matplotlib" in types: matplotlib_colors = [ f"matplotlib.{c}" for c in dir(palettable.matplotlib)[:-16] ] palettes = palettes + matplotlib_colors if "mycarta" in types: mycarta = [f"mycarta.{c}" for c in dir(palettable.mycarta)[:-16]] palettes = palettes + mycarta if "scientific" in types: scientific_diverging = [ f"scientific.diverging.{c}" for c in dir(palettable.scientific.diverging)[:-19] ] scientific_sequential = [ f"scientific.sequential.{c}" for c in dir(palettable.scientific.sequential)[:-19] ] palettes = palettes + scientific_diverging + scientific_sequential if "tableau" in types: tableau = [f"tableau.{c}" for c in dir(palettable.tableau)[:-14]] palettes = palettes + tableau return palettes
Get a list of palettable color palettes. Args: types (list, optional): A list of palettable types to return, e.g., types=['matplotlib', 'cartocolors']. Defaults to None. Returns: list: A list of palettable color palettes.
12,367
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple def check_package(name, URL=""): try: __import__(name.lower()) except Exception: raise ImportError( f"{name} is not installed. Please install it before proceeding. {URL}" ) The provided code snippet includes necessary dependencies for implementing the `connect_postgis` function. Write a Python function `def connect_postgis( database, host="localhost", user=None, password=None, port=5432, use_env_var=False )` to solve the following problem: Connects to a PostGIS database. Args: database (str): Name of the database host (str, optional): Hosting server for the database. Defaults to "localhost". user (str, optional): User name to access the database. Defaults to None. password (str, optional): Password to access the database. Defaults to None. port (int, optional): Port number to connect to at the server host. Defaults to 5432. use_env_var (bool, optional): Whether to use environment variables. It set to True, user and password are treated as an environment variables with default values user="SQL_USER" and password="SQL_PASSWORD". Defaults to False. Raises: ValueError: If user is not specified. ValueError: If password is not specified. Returns: [type]: [description] Here is the function: def connect_postgis( database, host="localhost", user=None, password=None, port=5432, use_env_var=False ): """Connects to a PostGIS database. Args: database (str): Name of the database host (str, optional): Hosting server for the database. Defaults to "localhost". user (str, optional): User name to access the database. Defaults to None. password (str, optional): Password to access the database. Defaults to None. port (int, optional): Port number to connect to at the server host. Defaults to 5432. use_env_var (bool, optional): Whether to use environment variables. It set to True, user and password are treated as an environment variables with default values user="SQL_USER" and password="SQL_PASSWORD". Defaults to False. Raises: ValueError: If user is not specified. ValueError: If password is not specified. Returns: [type]: [description] """ check_package(name="geopandas", URL="https://geopandas.org") check_package( name="sqlalchemy", URL="https://docs.sqlalchemy.org/en/14/intro.html#installation", ) from sqlalchemy import create_engine if use_env_var: if user is not None: user = os.getenv(user) else: user = os.getenv("SQL_USER") if password is not None: password = os.getenv(password) else: password = os.getenv("SQL_PASSWORD") if user is None: raise ValueError("user is not specified.") if password is None: raise ValueError("password is not specified.") connection_string = f"postgresql://{user}:{password}@{host}:{port}/{database}" engine = create_engine(connection_string) return engine
Connects to a PostGIS database. Args: database (str): Name of the database host (str, optional): Hosting server for the database. Defaults to "localhost". user (str, optional): User name to access the database. Defaults to None. password (str, optional): Password to access the database. Defaults to None. port (int, optional): Port number to connect to at the server host. Defaults to 5432. use_env_var (bool, optional): Whether to use environment variables. It set to True, user and password are treated as an environment variables with default values user="SQL_USER" and password="SQL_PASSWORD". Defaults to False. Raises: ValueError: If user is not specified. ValueError: If password is not specified. Returns: [type]: [description]
12,368
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple def check_package(name, URL=""): try: __import__(name.lower()) except Exception: raise ImportError( f"{name} is not installed. Please install it before proceeding. {URL}" ) def gdf_to_ee(gdf, geodesic=True, date=None, date_format="YYYY-MM-dd"): """Converts a GeoPandas GeoDataFrame to ee.FeatureCollection. Args: gdf (geopandas.GeoDataFrame): The input geopandas.GeoDataFrame to be converted ee.FeatureCollection. geodesic (bool, optional): Whether line segments should be interpreted as spherical geodesics. If false, indicates that line segments should be interpreted as planar lines in the specified CRS. If absent, defaults to true if the CRS is geographic (including the default EPSG:4326), or to false if the CRS is projected. Defaults to True. date (str, optional): Column name for the date column. Defaults to None. date_format (str, optional): Date format. A pattern, as described at http://joda-time.sourceforge.net/apidocs/org/joda/time/format/DateTimeFormat.html. Defaults to 'YYYY-MM-dd'. Raises: TypeError: The input data type must be geopandas.GeoDataFrame. Returns: ee.FeatureCollection: The output ee.FeatureCollection converted from the input geopandas.GeoDataFrame. """ check_package(name="geopandas", URL="https://geopandas.org") import geopandas as gpd if not isinstance(gdf, gpd.GeoDataFrame): raise TypeError("The input data type must be geopandas.GeoDataFrame.") out_json = os.path.join(os.getcwd(), random_string(6) + ".geojson") gdf = gdf.to_crs(4326) gdf.to_file(out_json, driver="GeoJSON") fc = geojson_to_ee(out_json, geodesic=geodesic) if date is not None: try: fc = fc.map( lambda x: x.set( "system:time_start", ee.Date.parse(date_format, x.get(date)).millis(), ) ) except Exception as e: raise Exception(e) os.remove(out_json) return fc def read_postgis(sql, con, geom_col="geom", crs=None, **kwargs): """Reads data from a PostGIS database and returns a GeoDataFrame. Args: sql (str): SQL query to execute in selecting entries from database, or name of the table to read from the database. con (sqlalchemy.engine.Engine): Active connection to the database to query. geom_col (str, optional): Column name to convert to shapely geometries. Defaults to "geom". crs (str | dict, optional): CRS to use for the returned GeoDataFrame; if not set, tries to determine CRS from the SRID associated with the first geometry in the database, and assigns that to all geometries. Defaults to None. Returns: [type]: [description] """ check_package(name="geopandas", URL="https://geopandas.org") import geopandas as gpd gdf = gpd.read_postgis(sql, con, geom_col, crs, **kwargs) return gdf The provided code snippet includes necessary dependencies for implementing the `postgis_to_ee` function. Write a Python function `def postgis_to_ee(sql, con, geom_col="geom", crs=None, geodestic=False, **kwargs)` to solve the following problem: Reads data from a PostGIS database and returns a GeoDataFrame. Args: sql (str): SQL query to execute in selecting entries from database, or name of the table to read from the database. con (sqlalchemy.engine.Engine): Active connection to the database to query. geom_col (str, optional): Column name to convert to shapely geometries. Defaults to "geom". crs (str | dict, optional): CRS to use for the returned GeoDataFrame; if not set, tries to determine CRS from the SRID associated with the first geometry in the database, and assigns that to all geometries. Defaults to None. geodestic (bool, optional): Whether to use geodestic coordinates. Defaults to False. Returns: [type]: [description] Here is the function: def postgis_to_ee(sql, con, geom_col="geom", crs=None, geodestic=False, **kwargs): """Reads data from a PostGIS database and returns a GeoDataFrame. Args: sql (str): SQL query to execute in selecting entries from database, or name of the table to read from the database. con (sqlalchemy.engine.Engine): Active connection to the database to query. geom_col (str, optional): Column name to convert to shapely geometries. Defaults to "geom". crs (str | dict, optional): CRS to use for the returned GeoDataFrame; if not set, tries to determine CRS from the SRID associated with the first geometry in the database, and assigns that to all geometries. Defaults to None. geodestic (bool, optional): Whether to use geodestic coordinates. Defaults to False. Returns: [type]: [description] """ check_package(name="geopandas", URL="https://geopandas.org") gdf = read_postgis(sql, con, geom_col, crs=crs, **kwargs) fc = gdf_to_ee(gdf, geodesic=geodestic) return fc
Reads data from a PostGIS database and returns a GeoDataFrame. Args: sql (str): SQL query to execute in selecting entries from database, or name of the table to read from the database. con (sqlalchemy.engine.Engine): Active connection to the database to query. geom_col (str, optional): Column name to convert to shapely geometries. Defaults to "geom". crs (str | dict, optional): CRS to use for the returned GeoDataFrame; if not set, tries to determine CRS from the SRID associated with the first geometry in the database, and assigns that to all geometries. Defaults to None. geodestic (bool, optional): Whether to use geodestic coordinates. Defaults to False. Returns: [type]: [description]
12,369
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple def check_package(name, URL=""): try: __import__(name.lower()) except Exception: raise ImportError( f"{name} is not installed. Please install it before proceeding. {URL}" ) def github_raw_url(url): """Get the raw URL for a GitHub file. Args: url (str): The GitHub URL. Returns: str: The raw URL. """ if isinstance(url, str) and url.startswith("https://github.com/") and "blob" in url: url = url.replace("github.com", "raw.githubusercontent.com").replace( "blob/", "", 1 ) return url The provided code snippet includes necessary dependencies for implementing the `points_from_xy` function. Write a Python function `def points_from_xy(data, x="longitude", y="latitude", z=None, crs=None, **kwargs)` to solve the following problem: Create a GeoPandas GeoDataFrame from a csv or Pandas DataFrame containing x, y, z values. Args: data (str | pd.DataFrame): A csv or Pandas DataFrame containing x, y, z values. x (str, optional): The column name for the x values. Defaults to "longitude". y (str, optional): The column name for the y values. Defaults to "latitude". z (str, optional): The column name for the z values. Defaults to None. crs (str | int, optional): The coordinate reference system for the GeoDataFrame. Defaults to None. Returns: geopandas.GeoDataFrame: A GeoPandas GeoDataFrame containing x, y, z values. Here is the function: def points_from_xy(data, x="longitude", y="latitude", z=None, crs=None, **kwargs): """Create a GeoPandas GeoDataFrame from a csv or Pandas DataFrame containing x, y, z values. Args: data (str | pd.DataFrame): A csv or Pandas DataFrame containing x, y, z values. x (str, optional): The column name for the x values. Defaults to "longitude". y (str, optional): The column name for the y values. Defaults to "latitude". z (str, optional): The column name for the z values. Defaults to None. crs (str | int, optional): The coordinate reference system for the GeoDataFrame. Defaults to None. Returns: geopandas.GeoDataFrame: A GeoPandas GeoDataFrame containing x, y, z values. """ check_package(name="geopandas", URL="https://geopandas.org") import geopandas as gpd import pandas as pd if crs is None: crs = "epsg:4326" data = github_raw_url(data) if isinstance(data, pd.DataFrame): df = data elif isinstance(data, str): if not data.startswith("http") and (not os.path.exists(data)): raise FileNotFoundError("The specified input csv does not exist.") else: df = pd.read_csv(data, **kwargs) else: raise TypeError("The data must be a pandas DataFrame or a csv file path.") gdf = gpd.GeoDataFrame(df, geometry=gpd.points_from_xy(df[x], df[y], z=z, crs=crs)) return gdf
Create a GeoPandas GeoDataFrame from a csv or Pandas DataFrame containing x, y, z values. Args: data (str | pd.DataFrame): A csv or Pandas DataFrame containing x, y, z values. x (str, optional): The column name for the x values. Defaults to "longitude". y (str, optional): The column name for the y values. Defaults to "latitude". z (str, optional): The column name for the z values. Defaults to None. crs (str | int, optional): The coordinate reference system for the GeoDataFrame. Defaults to None. Returns: geopandas.GeoDataFrame: A GeoPandas GeoDataFrame containing x, y, z values.
12,370
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple The provided code snippet includes necessary dependencies for implementing the `vector_centroids` function. Write a Python function `def vector_centroids(ee_object)` to solve the following problem: Returns the centroids of an ee.FeatureCollection. Args: ee_object (ee.FeatureCollection): The ee.FeatureCollection to get the centroids of. Raises: TypeError: If the ee_object is not an ee.FeatureCollection. Returns: ee.FeatureCollection: The centroids of the ee_object. Here is the function: def vector_centroids(ee_object): """Returns the centroids of an ee.FeatureCollection. Args: ee_object (ee.FeatureCollection): The ee.FeatureCollection to get the centroids of. Raises: TypeError: If the ee_object is not an ee.FeatureCollection. Returns: ee.FeatureCollection: The centroids of the ee_object. """ if not isinstance(ee_object, ee.FeatureCollection): raise TypeError("The input must be an Earth Engine FeatureCollection.") centroids = ee_object.map( lambda f: ee.Feature(f.geometry().centroid(0.001), f.toDictionary()) ) centroids = centroids.map( lambda f: f.set( { "longitude": f.geometry().coordinates().get(0), "latitude": f.geometry().coordinates().get(1), } ) ) return centroids
Returns the centroids of an ee.FeatureCollection. Args: ee_object (ee.FeatureCollection): The ee.FeatureCollection to get the centroids of. Raises: TypeError: If the ee_object is not an ee.FeatureCollection. Returns: ee.FeatureCollection: The centroids of the ee_object.
12,371
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple def cog_info(url, titiler_endpoint=None, return_geojson=False, timeout=300): """Get band statistics of a Cloud Optimized GeoTIFF (COG). Args: url (str): HTTP URL to a COG, e.g., https://opendata.digitalglobe.com/events/mauritius-oil-spill/post-event/2020-08-12/105001001F1B5B00/105001001F1B5B00.tif titiler_endpoint (str, optional): Titiler endpoint. Defaults to "https://titiler.xyz". timeout (int, optional): Timeout in seconds. Defaults to 300. Returns: list: A dictionary of band info. """ titiler_endpoint = check_titiler_endpoint(titiler_endpoint) url = get_direct_url(url) info = "info" if return_geojson: info = "info.geojson" r = requests.get( f"{titiler_endpoint}/cog/{info}", params={ "url": url, }, timeout=timeout, ).json() return r def check_file_path(file_path, make_dirs=True): """Gets the absolute file path. Args: file_path ([str): The path to the file. make_dirs (bool, optional): Whether to create the directory if it does not exist. Defaults to True. Raises: FileNotFoundError: If the directory could not be found. TypeError: If the input directory path is not a string. Returns: str: The absolute path to the file. """ if isinstance(file_path, str): if file_path.startswith("~"): file_path = os.path.expanduser(file_path) else: file_path = os.path.abspath(file_path) file_dir = os.path.dirname(file_path) if not os.path.exists(file_dir) and make_dirs: os.makedirs(file_dir) return file_path else: raise TypeError("The provided file path must be a string.") The provided code snippet includes necessary dependencies for implementing the `cog_validate` function. Write a Python function `def cog_validate(source, verbose=False)` to solve the following problem: Validate Cloud Optimized Geotiff. Args: source (str): A dataset path or URL. Will be opened in "r" mode. verbose (bool, optional): Whether to print the output of the validation. Defaults to False. Raises: ImportError: If the rio-cogeo package is not installed. FileNotFoundError: If the provided file could not be found. Returns: tuple: A tuple containing the validation results (True is src_path is a valid COG, List of validation errors, and a list of validation warnings). Here is the function: def cog_validate(source, verbose=False): """Validate Cloud Optimized Geotiff. Args: source (str): A dataset path or URL. Will be opened in "r" mode. verbose (bool, optional): Whether to print the output of the validation. Defaults to False. Raises: ImportError: If the rio-cogeo package is not installed. FileNotFoundError: If the provided file could not be found. Returns: tuple: A tuple containing the validation results (True is src_path is a valid COG, List of validation errors, and a list of validation warnings). """ try: from rio_cogeo.cogeo import cog_validate, cog_info except ImportError: raise ImportError( "The rio-cogeo package is not installed. Please install it with `pip install rio-cogeo` or `conda install rio-cogeo -c conda-forge`." ) if not source.startswith("http"): source = check_file_path(source) if not os.path.exists(source): raise FileNotFoundError("The provided input file could not be found.") if verbose: return cog_info(source) else: return cog_validate(source)
Validate Cloud Optimized Geotiff. Args: source (str): A dataset path or URL. Will be opened in "r" mode. verbose (bool, optional): Whether to print the output of the validation. Defaults to False. Raises: ImportError: If the rio-cogeo package is not installed. FileNotFoundError: If the provided file could not be found. Returns: tuple: A tuple containing the validation results (True is src_path is a valid COG, List of validation errors, and a list of validation warnings).
12,372
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple def gdf_to_df(gdf, drop_geom=True): """Converts a GeoDataFrame to a pandas DataFrame. Args: gdf (gpd.GeoDataFrame): A GeoDataFrame. drop_geom (bool, optional): Whether to drop the geometry column. Defaults to True. Returns: pd.DataFrame: A pandas DataFrame containing the GeoDataFrame. """ import pandas as pd if drop_geom: df = pd.DataFrame(gdf.drop(columns=["geometry"])) else: df = pd.DataFrame(gdf) return df def geojson_to_df(in_geojson, encoding="utf-8", drop_geometry=True): """Converts a GeoJSON object to a pandas DataFrame. Args: in_geojson (str | dict): The input GeoJSON file or dict. encoding (str, optional): The encoding of the GeoJSON object. Defaults to "utf-8". drop_geometry (bool, optional): Whether to drop the geometry column. Defaults to True. Raises: FileNotFoundError: If the input GeoJSON file could not be found. Returns: pd.DataFrame: A pandas DataFrame containing the GeoJSON object. """ import pandas as pd from urllib.request import urlopen if isinstance(in_geojson, str): if in_geojson.startswith("http"): in_geojson = github_raw_url(in_geojson) with urlopen(in_geojson) as f: data = json.load(f) else: in_geojson = os.path.abspath(in_geojson) if not os.path.exists(in_geojson): raise FileNotFoundError("The provided GeoJSON file could not be found.") with open(in_geojson, encoding=encoding) as f: data = json.load(f) elif isinstance(in_geojson, dict): data = in_geojson df = pd.json_normalize(data["features"]) df.columns = [col.replace("properties.", "") for col in df.columns] if drop_geometry: df = df[df.columns.drop(list(df.filter(regex="geometry")))] return df def github_raw_url(url): """Get the raw URL for a GitHub file. Args: url (str): The GitHub URL. Returns: str: The raw URL. """ if isinstance(url, str) and url.startswith("https://github.com/") and "blob" in url: url = url.replace("github.com", "raw.githubusercontent.com").replace( "blob/", "", 1 ) return url The provided code snippet includes necessary dependencies for implementing the `ee_join_table` function. Write a Python function `def ee_join_table(ee_object, data, src_key, dst_key=None)` to solve the following problem: Join a table to an ee.FeatureCollection attribute table. Args: ee_object (ee.FeatureCollection): The ee.FeatureCollection to be joined by a table. data (str | pd.DataFraem | gpd.GeoDataFrame): The table to join to the ee.FeatureCollection. src_key (str): The key of ee.FeatureCollection attribute table to join. dst_key (str, optional): The key of the table to be joined to the ee.FeatureCollection. Defaults to None. Returns: ee.FeatureCollection: The joined ee.FeatureCollection. Here is the function: def ee_join_table(ee_object, data, src_key, dst_key=None): """Join a table to an ee.FeatureCollection attribute table. Args: ee_object (ee.FeatureCollection): The ee.FeatureCollection to be joined by a table. data (str | pd.DataFraem | gpd.GeoDataFrame): The table to join to the ee.FeatureCollection. src_key (str): The key of ee.FeatureCollection attribute table to join. dst_key (str, optional): The key of the table to be joined to the ee.FeatureCollection. Defaults to None. Returns: ee.FeatureCollection: The joined ee.FeatureCollection. """ import pandas as pd if not isinstance(ee_object, ee.FeatureCollection): raise TypeError("The input ee_object must be of type ee.FeatureCollection.") if not isinstance(src_key, str): raise TypeError("The input src_key must be of type str.") if dst_key is None: dst_key = src_key if isinstance(data, str): data = github_raw_url(data) if data.endswith(".csv"): df = pd.read_csv(data) elif data.endswith(".geojson"): df = geojson_to_df(data) else: import geopandas as gpd gdf = gpd.read_file(data) df = gdf_to_df(gdf) elif isinstance(data, pd.DataFrame): if "geometry" in data.columns: df = data.drop(columns=["geometry"]) elif "geom" in data.columns: df = data.drop(columns=["geom"]) else: df = data else: raise TypeError("The input data must be of type str or pandas.DataFrame.") df[dst_key] = df[dst_key].astype(str) df.set_index(dst_key, inplace=True) df = df[~df.index.duplicated(keep="first")] table = ee.Dictionary(df.to_dict("index")) fc = ee_object.map(lambda f: f.set(table.get(f.get(src_key), ee.Dictionary()))) return fc
Join a table to an ee.FeatureCollection attribute table. Args: ee_object (ee.FeatureCollection): The ee.FeatureCollection to be joined by a table. data (str | pd.DataFraem | gpd.GeoDataFrame): The table to join to the ee.FeatureCollection. src_key (str): The key of ee.FeatureCollection attribute table to join. dst_key (str, optional): The key of the table to be joined to the ee.FeatureCollection. Defaults to None. Returns: ee.FeatureCollection: The joined ee.FeatureCollection.
12,373
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple def gdf_bounds(gdf, return_geom=False): """Returns the bounding box of a GeoDataFrame. Args: gdf (gpd.GeoDataFrame): A GeoDataFrame. return_geom (bool, optional): Whether to return the bounding box as a GeoDataFrame. Defaults to False. Returns: list | gpd.GeoDataFrame: A bounding box in the form of a list (minx, miny, maxx, maxy) or GeoDataFrame. """ bounds = gdf.total_bounds if return_geom: return bbox_to_gdf(bbox=bounds) else: return bounds The provided code snippet includes necessary dependencies for implementing the `gdf_centroid` function. Write a Python function `def gdf_centroid(gdf, return_geom=False)` to solve the following problem: Returns the centroid of a GeoDataFrame. Args: gdf (gpd.GeoDataFrame): A GeoDataFrame. return_geom (bool, optional): Whether to return the bounding box as a GeoDataFrame. Defaults to False. Returns: list | gpd.GeoDataFrame: A bounding box in the form of a list (lon, lat) or GeoDataFrame. Here is the function: def gdf_centroid(gdf, return_geom=False): """Returns the centroid of a GeoDataFrame. Args: gdf (gpd.GeoDataFrame): A GeoDataFrame. return_geom (bool, optional): Whether to return the bounding box as a GeoDataFrame. Defaults to False. Returns: list | gpd.GeoDataFrame: A bounding box in the form of a list (lon, lat) or GeoDataFrame. """ warnings.filterwarnings("ignore") centroid = gdf_bounds(gdf, return_geom=True).centroid if return_geom: return centroid else: return centroid.x[0], centroid.y[0]
Returns the centroid of a GeoDataFrame. Args: gdf (gpd.GeoDataFrame): A GeoDataFrame. return_geom (bool, optional): Whether to return the bounding box as a GeoDataFrame. Defaults to False. Returns: list | gpd.GeoDataFrame: A bounding box in the form of a list (lon, lat) or GeoDataFrame.
12,374
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple The provided code snippet includes necessary dependencies for implementing the `gdf_geom_type` function. Write a Python function `def gdf_geom_type(gdf, first_only=True)` to solve the following problem: Returns the geometry type of a GeoDataFrame. Args: gdf (gpd.GeoDataFrame): A GeoDataFrame. first_only (bool, optional): Whether to return the geometry type of the first feature in the GeoDataFrame. Defaults to True. Returns: str: The geometry type of the GeoDataFrame. Here is the function: def gdf_geom_type(gdf, first_only=True): """Returns the geometry type of a GeoDataFrame. Args: gdf (gpd.GeoDataFrame): A GeoDataFrame. first_only (bool, optional): Whether to return the geometry type of the first feature in the GeoDataFrame. Defaults to True. Returns: str: The geometry type of the GeoDataFrame. """ if first_only: return gdf.geometry.type[0] else: return gdf.geometry.type
Returns the geometry type of a GeoDataFrame. Args: gdf (gpd.GeoDataFrame): A GeoDataFrame. first_only (bool, optional): Whether to return the geometry type of the first feature in the GeoDataFrame. Defaults to True. Returns: str: The geometry type of the GeoDataFrame.
12,375
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple The provided code snippet includes necessary dependencies for implementing the `image_to_numpy` function. Write a Python function `def image_to_numpy(image)` to solve the following problem: Converts an image to a numpy array. Args: image (str): A dataset path, URL or rasterio.io.DatasetReader object. Raises: FileNotFoundError: If the provided file could not be found. Returns: np.array: A numpy array. Here is the function: def image_to_numpy(image): """Converts an image to a numpy array. Args: image (str): A dataset path, URL or rasterio.io.DatasetReader object. Raises: FileNotFoundError: If the provided file could not be found. Returns: np.array: A numpy array. """ import rasterio from osgeo import gdal gdal.UseExceptions() gdal.PushErrorHandler("CPLQuietErrorHandler") if not os.path.exists(image): raise FileNotFoundError("The provided input file could not be found.") with rasterio.open(image, "r") as ds: arr = ds.read() # read all raster values return arr
Converts an image to a numpy array. Args: image (str): A dataset path, URL or rasterio.io.DatasetReader object. Raises: FileNotFoundError: If the provided file could not be found. Returns: np.array: A numpy array.
12,376
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple def check_dir(dir_path, make_dirs=True): """Checks if a directory exists and creates it if it does not. Args: dir_path ([str): The path to the directory. make_dirs (bool, optional): Whether to create the directory if it does not exist. Defaults to True. Raises: FileNotFoundError: If the directory could not be found. TypeError: If the input directory path is not a string. Returns: str: The path to the directory. """ if isinstance(dir_path, str): if dir_path.startswith("~"): dir_path = os.path.expanduser(dir_path) else: dir_path = os.path.abspath(dir_path) if not os.path.exists(dir_path) and make_dirs: os.makedirs(dir_path) if os.path.exists(dir_path): return dir_path else: raise FileNotFoundError("The provided directory could not be found.") else: raise TypeError("The provided directory path must be a string.") The provided code snippet includes necessary dependencies for implementing the `numpy_to_cog` function. Write a Python function `def numpy_to_cog( np_array, out_cog, bounds=None, profile=None, dtype=None, crs="epsg:4326" )` to solve the following problem: Converts a numpy array to a COG file. Args: np_array (np.array): A numpy array representing the image. out_cog (str): The output COG file path. bounds (tuple, optional): The bounds of the image in the format of (minx, miny, maxx, maxy). Defaults to None. profile (str | dict, optional): File path to an existing COG file or a dictionary representing the profile. Defaults to None. dtype (str, optional): The data type of the output COG file. Defaults to None. crs (str, optional): The coordinate reference system of the output COG file. Defaults to "epsg:4326". Here is the function: def numpy_to_cog( np_array, out_cog, bounds=None, profile=None, dtype=None, crs="epsg:4326" ): """Converts a numpy array to a COG file. Args: np_array (np.array): A numpy array representing the image. out_cog (str): The output COG file path. bounds (tuple, optional): The bounds of the image in the format of (minx, miny, maxx, maxy). Defaults to None. profile (str | dict, optional): File path to an existing COG file or a dictionary representing the profile. Defaults to None. dtype (str, optional): The data type of the output COG file. Defaults to None. crs (str, optional): The coordinate reference system of the output COG file. Defaults to "epsg:4326". """ import numpy as np import rasterio from rasterio.io import MemoryFile from rasterio.transform import from_bounds from rio_cogeo.cogeo import cog_translate from rio_cogeo.profiles import cog_profiles warnings.filterwarnings("ignore") if not isinstance(np_array, np.ndarray): raise TypeError("The input array must be a numpy array.") out_dir = os.path.dirname(out_cog) check_dir(out_dir) if profile is not None: if isinstance(profile, str): if not os.path.exists(profile): raise FileNotFoundError("The provided file could not be found.") with rasterio.open(profile) as ds: bounds = ds.bounds elif isinstance(profile, rasterio.profiles.Profile): profile = dict(profile) elif not isinstance(profile, dict): raise TypeError("The provided profile must be a file path or a dictionary.") if bounds is None: bounds = (-180.0, -85.0511287798066, 180.0, 85.0511287798066) if not isinstance(bounds, tuple) and len(bounds) != 4: raise TypeError("The provided bounds must be a tuple of length 4.") # Rasterio uses numpy array of shape of `(bands, height, width)` if len(np_array.shape) == 3: nbands = np_array.shape[0] height = np_array.shape[1] width = np_array.shape[2] elif len(np_array.shape) == 2: nbands = 1 height = np_array.shape[0] width = np_array.shape[1] np_array = np_array.reshape((1, height, width)) else: raise ValueError("The input array must be a 2D or 3D numpy array.") src_transform = from_bounds(*bounds, width=width, height=height) if dtype is None: dtype = str(np_array.dtype) if isinstance(profile, dict): src_profile = profile src_profile["count"] = nbands else: src_profile = dict( driver="GTiff", dtype=dtype, count=nbands, height=height, width=width, crs=crs, transform=src_transform, ) with MemoryFile() as memfile: with memfile.open(**src_profile) as mem: # Populate the input file with numpy array mem.write(np_array) dst_profile = cog_profiles.get("deflate") cog_translate( mem, out_cog, dst_profile, in_memory=True, quiet=True, )
Converts a numpy array to a COG file. Args: np_array (np.array): A numpy array representing the image. out_cog (str): The output COG file path. bounds (tuple, optional): The bounds of the image in the format of (minx, miny, maxx, maxy). Defaults to None. profile (str | dict, optional): File path to an existing COG file or a dictionary representing the profile. Defaults to None. dtype (str, optional): The data type of the output COG file. Defaults to None. crs (str, optional): The coordinate reference system of the output COG file. Defaults to "epsg:4326".
12,377
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple def in_colab_shell(): """Tests if the code is being executed within Google Colab.""" import sys if "google.colab" in sys.modules: return True else: return False The provided code snippet includes necessary dependencies for implementing the `view_lidar` function. Write a Python function `def view_lidar(filename, cmap="terrain", backend="pyvista", background=None, **kwargs)` to solve the following problem: View LiDAR data in 3D. Args: filename (str): The filepath to the LiDAR data. cmap (str, optional): The colormap to use. Defaults to "terrain". cmap currently does not work for the open3d backend. backend (str, optional): The plotting backend to use, can be pyvista, ipygany, panel, and open3d. Defaults to "pyvista". background (str, optional): The background color to use. Defaults to None. Raises: FileNotFoundError: If the file does not exist. ValueError: If the backend is not supported. Here is the function: def view_lidar(filename, cmap="terrain", backend="pyvista", background=None, **kwargs): """View LiDAR data in 3D. Args: filename (str): The filepath to the LiDAR data. cmap (str, optional): The colormap to use. Defaults to "terrain". cmap currently does not work for the open3d backend. backend (str, optional): The plotting backend to use, can be pyvista, ipygany, panel, and open3d. Defaults to "pyvista". background (str, optional): The background color to use. Defaults to None. Raises: FileNotFoundError: If the file does not exist. ValueError: If the backend is not supported. """ if in_colab_shell(): print("The view_lidar() function is not supported in Colab.") return warnings.filterwarnings("ignore") filename = os.path.abspath(filename) if not os.path.exists(filename): raise FileNotFoundError(f"{filename} does not exist.") backend = backend.lower() if backend in ["pyvista", "ipygany", "panel"]: try: import pyntcloud except ImportError: print( "The pyvista and pyntcloud packages are required for this function. Use pip install geemap[lidar] to install them." ) return try: if backend == "pyvista": backend = None if backend == "ipygany": cmap = None data = pyntcloud.PyntCloud.from_file(filename) mesh = data.to_instance("pyvista", mesh=False) mesh = mesh.elevation() mesh.plot( scalars="Elevation", cmap=cmap, jupyter_backend=backend, background=background, **kwargs, ) except Exception as e: print("Something went wrong.") print(e) return elif backend == "open3d": try: import laspy import open3d as o3d import numpy as np except ImportError: print( "The laspy and open3d packages are required for this function. Use pip install laspy open3d to install them." ) return try: las = laspy.read(filename) point_data = np.stack([las.X, las.Y, las.Z], axis=0).transpose((1, 0)) geom = o3d.geometry.PointCloud() geom.points = o3d.utility.Vector3dVector(point_data) # geom.colors = o3d.utility.Vector3dVector(colors) # need to add colors. A list in the form of [[r,g,b], [r,g,b]] with value range 0-1. https://github.com/isl-org/Open3D/issues/614 o3d.visualization.draw_geometries([geom], **kwargs) except Exception as e: print("Something went wrong.") print(e) return else: raise ValueError(f"{backend} is not a valid backend.")
View LiDAR data in 3D. Args: filename (str): The filepath to the LiDAR data. cmap (str, optional): The colormap to use. Defaults to "terrain". cmap currently does not work for the open3d backend. backend (str, optional): The plotting backend to use, can be pyvista, ipygany, panel, and open3d. Defaults to "pyvista". background (str, optional): The background color to use. Defaults to None. Raises: FileNotFoundError: If the file does not exist. ValueError: If the backend is not supported.
12,378
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple def check_file_path(file_path, make_dirs=True): """Gets the absolute file path. Args: file_path ([str): The path to the file. make_dirs (bool, optional): Whether to create the directory if it does not exist. Defaults to True. Raises: FileNotFoundError: If the directory could not be found. TypeError: If the input directory path is not a string. Returns: str: The absolute path to the file. """ if isinstance(file_path, str): if file_path.startswith("~"): file_path = os.path.expanduser(file_path) else: file_path = os.path.abspath(file_path) file_dir = os.path.dirname(file_path) if not os.path.exists(file_dir) and make_dirs: os.makedirs(file_dir) return file_path else: raise TypeError("The provided file path must be a string.") def read_lidar(filename, **kwargs): """Read a LAS file. Args: filename (str): A local file path or HTTP URL to a LAS file. Returns: LasData: The LasData object return by laspy.read. """ try: import laspy except ImportError: print( "The laspy package is required for this function. Use `pip install laspy[lazrs,laszip]` to install it." ) return if ( isinstance(filename, str) and filename.startswith("http") and (filename.endswith(".las") or filename.endswith(".laz")) ): filename = github_raw_url(filename) filename = download_file(filename) return laspy.read(filename, **kwargs) def write_lidar(source, destination, do_compress=None, laz_backend=None): """Writes to a stream or file. Args: source (str | laspy.lasdatas.base.LasBase): The source data to be written. destination (str): The destination filepath. do_compress (bool, optional): Flags to indicate if you want to compress the data. Defaults to None. laz_backend (str, optional): The laz backend to use. Defaults to None. """ try: import laspy except ImportError: print( "The laspy package is required for this function. Use `pip install laspy[lazrs,laszip]` to install it." ) return if isinstance(source, str): source = read_lidar(source) source.write(destination, do_compress=do_compress, laz_backend=laz_backend) The provided code snippet includes necessary dependencies for implementing the `convert_lidar` function. Write a Python function `def convert_lidar( source, destination=None, point_format_id=None, file_version=None, **kwargs )` to solve the following problem: Converts a Las from one point format to another Automatically upgrades the file version if source file version is not compatible with the new point_format_id Args: source (str | laspy.lasdatas.base.LasBase): The source data to be converted. destination (str, optional): The destination file path. Defaults to None. point_format_id (int, optional): The new point format id (the default is None, which won't change the source format id). file_version (str, optional): The new file version. None by default which means that the file_version may be upgraded for compatibility with the new point_format. The file version will not be downgraded. Returns: aspy.lasdatas.base.LasBase: The converted LasData object. Here is the function: def convert_lidar( source, destination=None, point_format_id=None, file_version=None, **kwargs ): """Converts a Las from one point format to another Automatically upgrades the file version if source file version is not compatible with the new point_format_id Args: source (str | laspy.lasdatas.base.LasBase): The source data to be converted. destination (str, optional): The destination file path. Defaults to None. point_format_id (int, optional): The new point format id (the default is None, which won't change the source format id). file_version (str, optional): The new file version. None by default which means that the file_version may be upgraded for compatibility with the new point_format. The file version will not be downgraded. Returns: aspy.lasdatas.base.LasBase: The converted LasData object. """ try: import laspy except ImportError: print( "The laspy package is required for this function. Use `pip install laspy[lazrs,laszip]` to install it." ) return if isinstance(source, str): source = read_lidar(source) las = laspy.convert( source, point_format_id=point_format_id, file_version=file_version ) if destination is None: return las else: destination = check_file_path(destination) write_lidar(las, destination, **kwargs) return destination
Converts a Las from one point format to another Automatically upgrades the file version if source file version is not compatible with the new point_format_id Args: source (str | laspy.lasdatas.base.LasBase): The source data to be converted. destination (str, optional): The destination file path. Defaults to None. point_format_id (int, optional): The new point format id (the default is None, which won't change the source format id). file_version (str, optional): The new file version. None by default which means that the file_version may be upgraded for compatibility with the new point_format. The file version will not be downgraded. Returns: aspy.lasdatas.base.LasBase: The converted LasData object.
12,379
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple The provided code snippet includes necessary dependencies for implementing the `download_folder` function. Write a Python function `def download_folder( url=None, id=None, output=None, quiet=False, proxy=None, speed=None, use_cookies=True, remaining_ok=False, )` to solve the following problem: Downloads the entire folder from URL. Args: url (str, optional): URL of the Google Drive folder. Must be of the format 'https://drive.google.com/drive/folders/{url}'. Defaults to None. id (str, optional): Google Drive's folder ID. Defaults to None. output (str, optional): String containing the path of the output folder. Defaults to current working directory. quiet (bool, optional): Suppress terminal output. Defaults to False. proxy (str, optional): Proxy. Defaults to None. speed (float, optional): Download byte size per second (e.g., 256KB/s = 256 * 1024). Defaults to None. use_cookies (bool, optional): Flag to use cookies. Defaults to True. resume (bool, optional): Resume the download from existing tmp file if possible. Defaults to False. Returns: list: List of files downloaded, or None if failed. Here is the function: def download_folder( url=None, id=None, output=None, quiet=False, proxy=None, speed=None, use_cookies=True, remaining_ok=False, ): """Downloads the entire folder from URL. Args: url (str, optional): URL of the Google Drive folder. Must be of the format 'https://drive.google.com/drive/folders/{url}'. Defaults to None. id (str, optional): Google Drive's folder ID. Defaults to None. output (str, optional): String containing the path of the output folder. Defaults to current working directory. quiet (bool, optional): Suppress terminal output. Defaults to False. proxy (str, optional): Proxy. Defaults to None. speed (float, optional): Download byte size per second (e.g., 256KB/s = 256 * 1024). Defaults to None. use_cookies (bool, optional): Flag to use cookies. Defaults to True. resume (bool, optional): Resume the download from existing tmp file if possible. Defaults to False. Returns: list: List of files downloaded, or None if failed. """ import gdown files = gdown.download_folder( url, id, output, quiet, proxy, speed, use_cookies, remaining_ok ) return files
Downloads the entire folder from URL. Args: url (str, optional): URL of the Google Drive folder. Must be of the format 'https://drive.google.com/drive/folders/{url}'. Defaults to None. id (str, optional): Google Drive's folder ID. Defaults to None. output (str, optional): String containing the path of the output folder. Defaults to current working directory. quiet (bool, optional): Suppress terminal output. Defaults to False. proxy (str, optional): Proxy. Defaults to None. speed (float, optional): Download byte size per second (e.g., 256KB/s = 256 * 1024). Defaults to None. use_cookies (bool, optional): Flag to use cookies. Defaults to True. resume (bool, optional): Resume the download from existing tmp file if possible. Defaults to False. Returns: list: List of files downloaded, or None if failed.
12,380
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple def temp_file_path(extension): """Returns a temporary file path. Args: extension (str): The file extension. Returns: str: The temporary file path. """ import tempfile import uuid if not extension.startswith("."): extension = "." + extension file_id = str(uuid.uuid4()) file_path = os.path.join(tempfile.gettempdir(), f"{file_id}{extension}") return file_path def check_file_path(file_path, make_dirs=True): """Gets the absolute file path. Args: file_path ([str): The path to the file. make_dirs (bool, optional): Whether to create the directory if it does not exist. Defaults to True. Raises: FileNotFoundError: If the directory could not be found. TypeError: If the input directory path is not a string. Returns: str: The absolute path to the file. """ if isinstance(file_path, str): if file_path.startswith("~"): file_path = os.path.expanduser(file_path) else: file_path = os.path.abspath(file_path) file_dir = os.path.dirname(file_path) if not os.path.exists(file_dir) and make_dirs: os.makedirs(file_dir) return file_path else: raise TypeError("The provided file path must be a string.") def download_file( url=None, output=None, quiet=False, proxy=None, speed=None, use_cookies=True, verify=True, id=None, fuzzy=False, resume=False, unzip=True, overwrite=False, ): """Download a file from URL, including Google Drive shared URL. Args: url (str, optional): Google Drive URL is also supported. Defaults to None. output (str, optional): Output filename. Default is basename of URL. quiet (bool, optional): Suppress terminal output. Default is False. proxy (str, optional): Proxy. Defaults to None. speed (float, optional): Download byte size per second (e.g., 256KB/s = 256 * 1024). Defaults to None. use_cookies (bool, optional): Flag to use cookies. Defaults to True. verify (bool | str, optional): Either a bool, in which case it controls whether the server's TLS certificate is verified, or a string, in which case it must be a path to a CA bundle to use. Default is True.. Defaults to True. id (str, optional): Google Drive's file ID. Defaults to None. fuzzy (bool, optional): Fuzzy extraction of Google Drive's file Id. Defaults to False. resume (bool, optional): Resume the download from existing tmp file if possible. Defaults to False. unzip (bool, optional): Unzip the file. Defaults to True. overwrite (bool, optional): Overwrite the file if it already exists. Defaults to False. Returns: str: The output file path. """ import gdown if output is None: if isinstance(url, str) and url.startswith("http"): output = os.path.basename(url) if isinstance(url, str): if os.path.exists(os.path.abspath(output)) and (not overwrite): print( f"{output} already exists. Skip downloading. Set overwrite=True to overwrite." ) return os.path.abspath(output) else: url = github_raw_url(url) if "https://drive.google.com/file/d/" in url: fuzzy = True output = gdown.download( url, output, quiet, proxy, speed, use_cookies, verify, id, fuzzy, resume ) if unzip and output.endswith(".zip"): with zipfile.ZipFile(output, "r") as zip_ref: if not quiet: print("Extracting files...") zip_ref.extractall(os.path.dirname(output)) return os.path.abspath(output) The provided code snippet includes necessary dependencies for implementing the `clip_image` function. Write a Python function `def clip_image(image, mask, output)` to solve the following problem: Clip an image by mask. Args: image (str): Path to the image file in GeoTIFF format. mask (str | list | dict): The mask used to extract the image. It can be a path to vector datasets (e.g., GeoJSON, Shapefile), a list of coordinates, or m.user_roi. output (str): Path to the output file. Raises: ImportError: If the fiona or rasterio package is not installed. FileNotFoundError: If the image is not found. ValueError: If the mask is not a valid GeoJSON or raster file. FileNotFoundError: If the mask file is not found. Here is the function: def clip_image(image, mask, output): """Clip an image by mask. Args: image (str): Path to the image file in GeoTIFF format. mask (str | list | dict): The mask used to extract the image. It can be a path to vector datasets (e.g., GeoJSON, Shapefile), a list of coordinates, or m.user_roi. output (str): Path to the output file. Raises: ImportError: If the fiona or rasterio package is not installed. FileNotFoundError: If the image is not found. ValueError: If the mask is not a valid GeoJSON or raster file. FileNotFoundError: If the mask file is not found. """ try: import fiona import rasterio import rasterio.mask except ImportError as e: raise ImportError(e) if not os.path.exists(image): raise FileNotFoundError(f"{image} does not exist.") if not output.endswith(".tif"): raise ValueError("Output must be a tif file.") output = check_file_path(output) if isinstance(mask, ee.Geometry): mask = mask.coordinates().getInfo()[0] if isinstance(mask, str): if mask.startswith("http"): mask = download_file(mask, output) if not os.path.exists(mask): raise FileNotFoundError(f"{mask} does not exist.") elif isinstance(mask, list) or isinstance(mask, dict): if isinstance(mask, list): geojson = { "type": "FeatureCollection", "features": [ { "type": "Feature", "properties": {}, "geometry": {"type": "Polygon", "coordinates": [mask]}, } ], } else: geojson = { "type": "FeatureCollection", "features": [mask], } mask = temp_file_path(".geojson") with open(mask, "w") as f: json.dump(geojson, f) with fiona.open(mask, "r") as shapefile: shapes = [feature["geometry"] for feature in shapefile] with rasterio.open(image) as src: out_image, out_transform = rasterio.mask.mask(src, shapes, crop=True) out_meta = src.meta out_meta.update( { "driver": "GTiff", "height": out_image.shape[1], "width": out_image.shape[2], "transform": out_transform, } ) with rasterio.open(output, "w", **out_meta) as dest: dest.write(out_image)
Clip an image by mask. Args: image (str): Path to the image file in GeoTIFF format. mask (str | list | dict): The mask used to extract the image. It can be a path to vector datasets (e.g., GeoJSON, Shapefile), a list of coordinates, or m.user_roi. output (str): Path to the output file. Raises: ImportError: If the fiona or rasterio package is not installed. FileNotFoundError: If the image is not found. ValueError: If the mask is not a valid GeoJSON or raster file. FileNotFoundError: If the mask file is not found.
12,381
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple def check_file_path(file_path, make_dirs=True): """Gets the absolute file path. Args: file_path ([str): The path to the file. make_dirs (bool, optional): Whether to create the directory if it does not exist. Defaults to True. Raises: FileNotFoundError: If the directory could not be found. TypeError: If the input directory path is not a string. Returns: str: The absolute path to the file. """ if isinstance(file_path, str): if file_path.startswith("~"): file_path = os.path.expanduser(file_path) else: file_path = os.path.abspath(file_path) file_dir = os.path.dirname(file_path) if not os.path.exists(file_dir) and make_dirs: os.makedirs(file_dir) return file_path else: raise TypeError("The provided file path must be a string.") def download_file( url=None, output=None, quiet=False, proxy=None, speed=None, use_cookies=True, verify=True, id=None, fuzzy=False, resume=False, unzip=True, overwrite=False, ): """Download a file from URL, including Google Drive shared URL. Args: url (str, optional): Google Drive URL is also supported. Defaults to None. output (str, optional): Output filename. Default is basename of URL. quiet (bool, optional): Suppress terminal output. Default is False. proxy (str, optional): Proxy. Defaults to None. speed (float, optional): Download byte size per second (e.g., 256KB/s = 256 * 1024). Defaults to None. use_cookies (bool, optional): Flag to use cookies. Defaults to True. verify (bool | str, optional): Either a bool, in which case it controls whether the server's TLS certificate is verified, or a string, in which case it must be a path to a CA bundle to use. Default is True.. Defaults to True. id (str, optional): Google Drive's file ID. Defaults to None. fuzzy (bool, optional): Fuzzy extraction of Google Drive's file Id. Defaults to False. resume (bool, optional): Resume the download from existing tmp file if possible. Defaults to False. unzip (bool, optional): Unzip the file. Defaults to True. overwrite (bool, optional): Overwrite the file if it already exists. Defaults to False. Returns: str: The output file path. """ import gdown if output is None: if isinstance(url, str) and url.startswith("http"): output = os.path.basename(url) if isinstance(url, str): if os.path.exists(os.path.abspath(output)) and (not overwrite): print( f"{output} already exists. Skip downloading. Set overwrite=True to overwrite." ) return os.path.abspath(output) else: url = github_raw_url(url) if "https://drive.google.com/file/d/" in url: fuzzy = True output = gdown.download( url, output, quiet, proxy, speed, use_cookies, verify, id, fuzzy, resume ) if unzip and output.endswith(".zip"): with zipfile.ZipFile(output, "r") as zip_ref: if not quiet: print("Extracting files...") zip_ref.extractall(os.path.dirname(output)) return os.path.abspath(output) The provided code snippet includes necessary dependencies for implementing the `netcdf_to_tif` function. Write a Python function `def netcdf_to_tif( filename, output=None, variables=None, shift_lon=True, lat="lat", lon="lon", return_vars=False, **kwargs, )` to solve the following problem: Convert a netcdf file to a GeoTIFF file. Args: filename (str): Path to the netcdf file. output (str, optional): Path to the output GeoTIFF file. Defaults to None. If None, the output file will be the same as the input file with the extension changed to .tif. variables (str | list, optional): Name of the variable or a list of variables to extract. Defaults to None. If None, all variables will be extracted. shift_lon (bool, optional): Flag to shift longitude values from [0, 360] to the range [-180, 180]. Defaults to True. lat (str, optional): Name of the latitude variable. Defaults to 'lat'. lon (str, optional): Name of the longitude variable. Defaults to 'lon'. return_vars (bool, optional): Flag to return all variables. Defaults to False. Raises: ImportError: If the xarray or rioxarray package is not installed. FileNotFoundError: If the netcdf file is not found. ValueError: If the variable is not found in the netcdf file. Here is the function: def netcdf_to_tif( filename, output=None, variables=None, shift_lon=True, lat="lat", lon="lon", return_vars=False, **kwargs, ): """Convert a netcdf file to a GeoTIFF file. Args: filename (str): Path to the netcdf file. output (str, optional): Path to the output GeoTIFF file. Defaults to None. If None, the output file will be the same as the input file with the extension changed to .tif. variables (str | list, optional): Name of the variable or a list of variables to extract. Defaults to None. If None, all variables will be extracted. shift_lon (bool, optional): Flag to shift longitude values from [0, 360] to the range [-180, 180]. Defaults to True. lat (str, optional): Name of the latitude variable. Defaults to 'lat'. lon (str, optional): Name of the longitude variable. Defaults to 'lon'. return_vars (bool, optional): Flag to return all variables. Defaults to False. Raises: ImportError: If the xarray or rioxarray package is not installed. FileNotFoundError: If the netcdf file is not found. ValueError: If the variable is not found in the netcdf file. """ try: import xarray as xr except ImportError as e: raise ImportError(e) if filename.startswith("http"): filename = download_file(filename) if not os.path.exists(filename): raise FileNotFoundError(f"{filename} does not exist.") if output is None: output = filename.replace(".nc", ".tif") else: output = check_file_path(output) xds = xr.open_dataset(filename, **kwargs) if shift_lon: xds.coords[lon] = (xds.coords[lon] + 180) % 360 - 180 xds = xds.sortby(xds.lon) allowed_vars = list(xds.data_vars.keys()) if isinstance(variables, str): if variables not in allowed_vars: raise ValueError(f"{variables} is not a valid variable.") variables = [variables] if variables is not None and (not set(variables).issubset(allowed_vars)): raise ValueError(f"{variables} must be a subset of {allowed_vars}.") if variables is None: xds.rio.set_spatial_dims(x_dim=lon, y_dim=lat).rio.to_raster(output) else: xds[variables].rio.set_spatial_dims(x_dim=lon, y_dim=lat).rio.to_raster(output) if return_vars: return output, allowed_vars else: return output
Convert a netcdf file to a GeoTIFF file. Args: filename (str): Path to the netcdf file. output (str, optional): Path to the output GeoTIFF file. Defaults to None. If None, the output file will be the same as the input file with the extension changed to .tif. variables (str | list, optional): Name of the variable or a list of variables to extract. Defaults to None. If None, all variables will be extracted. shift_lon (bool, optional): Flag to shift longitude values from [0, 360] to the range [-180, 180]. Defaults to True. lat (str, optional): Name of the latitude variable. Defaults to 'lat'. lon (str, optional): Name of the longitude variable. Defaults to 'lon'. return_vars (bool, optional): Flag to return all variables. Defaults to False. Raises: ImportError: If the xarray or rioxarray package is not installed. FileNotFoundError: If the netcdf file is not found. ValueError: If the variable is not found in the netcdf file.
12,382
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple def download_file( url=None, output=None, quiet=False, proxy=None, speed=None, use_cookies=True, verify=True, id=None, fuzzy=False, resume=False, unzip=True, overwrite=False, ): """Download a file from URL, including Google Drive shared URL. Args: url (str, optional): Google Drive URL is also supported. Defaults to None. output (str, optional): Output filename. Default is basename of URL. quiet (bool, optional): Suppress terminal output. Default is False. proxy (str, optional): Proxy. Defaults to None. speed (float, optional): Download byte size per second (e.g., 256KB/s = 256 * 1024). Defaults to None. use_cookies (bool, optional): Flag to use cookies. Defaults to True. verify (bool | str, optional): Either a bool, in which case it controls whether the server's TLS certificate is verified, or a string, in which case it must be a path to a CA bundle to use. Default is True.. Defaults to True. id (str, optional): Google Drive's file ID. Defaults to None. fuzzy (bool, optional): Fuzzy extraction of Google Drive's file Id. Defaults to False. resume (bool, optional): Resume the download from existing tmp file if possible. Defaults to False. unzip (bool, optional): Unzip the file. Defaults to True. overwrite (bool, optional): Overwrite the file if it already exists. Defaults to False. Returns: str: The output file path. """ import gdown if output is None: if isinstance(url, str) and url.startswith("http"): output = os.path.basename(url) if isinstance(url, str): if os.path.exists(os.path.abspath(output)) and (not overwrite): print( f"{output} already exists. Skip downloading. Set overwrite=True to overwrite." ) return os.path.abspath(output) else: url = github_raw_url(url) if "https://drive.google.com/file/d/" in url: fuzzy = True output = gdown.download( url, output, quiet, proxy, speed, use_cookies, verify, id, fuzzy, resume ) if unzip and output.endswith(".zip"): with zipfile.ZipFile(output, "r") as zip_ref: if not quiet: print("Extracting files...") zip_ref.extractall(os.path.dirname(output)) return os.path.abspath(output) The provided code snippet includes necessary dependencies for implementing the `read_netcdf` function. Write a Python function `def read_netcdf(filename, **kwargs)` to solve the following problem: Read a netcdf file. Args: filename (str): File path or HTTP URL to the netcdf file. Raises: ImportError: If the xarray or rioxarray package is not installed. FileNotFoundError: If the netcdf file is not found. Returns: xarray.Dataset: The netcdf file as an xarray dataset. Here is the function: def read_netcdf(filename, **kwargs): """Read a netcdf file. Args: filename (str): File path or HTTP URL to the netcdf file. Raises: ImportError: If the xarray or rioxarray package is not installed. FileNotFoundError: If the netcdf file is not found. Returns: xarray.Dataset: The netcdf file as an xarray dataset. """ try: import xarray as xr except ImportError as e: raise ImportError(e) if filename.startswith("http"): filename = download_file(filename) if not os.path.exists(filename): raise FileNotFoundError(f"{filename} does not exist.") xds = xr.open_dataset(filename, **kwargs) return xds
Read a netcdf file. Args: filename (str): File path or HTTP URL to the netcdf file. Raises: ImportError: If the xarray or rioxarray package is not installed. FileNotFoundError: If the netcdf file is not found. Returns: xarray.Dataset: The netcdf file as an xarray dataset.
12,383
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple def check_package(name, URL=""): try: __import__(name.lower()) except Exception: raise ImportError( f"{name} is not installed. Please install it before proceeding. {URL}" ) def get_local_tile_layer( source, port="default", debug=False, indexes=None, colormap=None, vmin=None, vmax=None, nodata=None, attribution=None, tile_format="ipyleaflet", layer_name="Local COG", return_client=False, quiet=False, **kwargs, ): """Generate an ipyleaflet/folium TileLayer from a local raster dataset or remote Cloud Optimized GeoTIFF (COG). If you are using this function in JupyterHub on a remote server and the raster does not render properly, try running the following two lines before calling this function: import os os.environ['LOCALTILESERVER_CLIENT_PREFIX'] = 'proxy/{port}' Args: source (str): The path to the GeoTIFF file or the URL of the Cloud Optimized GeoTIFF. port (str, optional): The port to use for the server. Defaults to "default". debug (bool, optional): If True, the server will be started in debug mode. Defaults to False. indexes (int, optional): The band(s) to use. Band indexing starts at 1. Defaults to None. colormap (str, optional): The name of the colormap from `matplotlib` to use when plotting a single band. See https://matplotlib.org/stable/gallery/color/colormap_reference.html. Default is greyscale. vmin (float, optional): The minimum value to use when colormapping the colormap when plotting a single band. Defaults to None. vmax (float, optional): The maximum value to use when colormapping the colormap when plotting a single band. Defaults to None. nodata (float, optional): The value from the band to use to interpret as not valid data. Defaults to None. attribution (str, optional): Attribution for the source raster. This defaults to a message about it being a local file.. Defaults to None. tile_format (str, optional): The tile layer format. Can be either ipyleaflet or folium. Defaults to "ipyleaflet". layer_name (str, optional): The layer name to use. Defaults to None. return_client (bool, optional): If True, the tile client will be returned. Defaults to False. quiet (bool, optional): If True, the error messages will be suppressed. Defaults to False. Returns: ipyleaflet.TileLayer | folium.TileLayer: An ipyleaflet.TileLayer or folium.TileLayer. """ import rasterio check_package( "localtileserver", URL="https://github.com/banesullivan/localtileserver" ) # Handle legacy localtileserver kwargs if "cmap" in kwargs: warnings.warn( "`cmap` is a deprecated keyword argument for get_local_tile_layer. Please use `colormap`." ) if "palette" in kwargs: warnings.warn( "`palette` is a deprecated keyword argument for get_local_tile_layer. Please use `colormap`." ) if "band" in kwargs or "bands" in kwargs: warnings.warn( "`band` and `bands` are deprecated keyword arguments for get_local_tile_layer. Please use `indexes`." ) if "projection" in kwargs: warnings.warn( "`projection` is a deprecated keyword argument for get_local_tile_layer and will be ignored." ) if "style" in kwargs: warnings.warn( "`style` is a deprecated keyword argument for get_local_tile_layer and will be ignored." ) if "max_zoom" not in kwargs: kwargs["max_zoom"] = 30 if "max_native_zoom" not in kwargs: kwargs["max_native_zoom"] = 30 if "cmap" in kwargs: colormap = kwargs.pop("cmap") if "palette" in kwargs: colormap = kwargs.pop("palette") if "band" in kwargs: indexes = kwargs.pop("band") if "bands" in kwargs: indexes = kwargs.pop("bands") # Make it compatible with binder and JupyterHub if os.environ.get("JUPYTERHUB_SERVICE_PREFIX") is not None: os.environ["LOCALTILESERVER_CLIENT_PREFIX"] = ( f"{os.environ['JUPYTERHUB_SERVICE_PREFIX'].lstrip('/')}/proxy/{{port}}" ) if is_studio_lab(): os.environ["LOCALTILESERVER_CLIENT_PREFIX"] = ( f"studiolab/default/jupyter/proxy/{{port}}" ) elif is_on_aws(): os.environ["LOCALTILESERVER_CLIENT_PREFIX"] = "proxy/{port}" elif "prefix" in kwargs: os.environ["LOCALTILESERVER_CLIENT_PREFIX"] = kwargs["prefix"] kwargs.pop("prefix") from localtileserver import ( get_leaflet_tile_layer, get_folium_tile_layer, TileClient, ) # if "show_loading" not in kwargs: # kwargs["show_loading"] = False if isinstance(source, str): if not source.startswith("http"): if source.startswith("~"): source = os.path.expanduser(source) # else: # source = os.path.abspath(source) # if not os.path.exists(source): # raise ValueError("The source path does not exist.") else: source = github_raw_url(source) elif isinstance(source, TileClient) or isinstance( source, rasterio.io.DatasetReader ): pass else: raise ValueError("The source must either be a string or TileClient") if tile_format not in ["ipyleaflet", "folium"]: raise ValueError("The tile format must be either ipyleaflet or folium.") if layer_name is None: if source.startswith("http"): layer_name = "RemoteTile_" + random_string(3) else: layer_name = "LocalTile_" + random_string(3) if isinstance(source, str) or isinstance(source, rasterio.io.DatasetReader): tile_client = TileClient(source, port=port, debug=debug) else: tile_client = source if quiet: output = widgets.Output() with output: if tile_format == "ipyleaflet": tile_layer = get_leaflet_tile_layer( tile_client, port=port, debug=debug, indexes=indexes, colormap=colormap, vmin=vmin, vmax=vmax, nodata=nodata, attribution=attribution, name=layer_name, **kwargs, ) else: tile_layer = get_folium_tile_layer( tile_client, port=port, debug=debug, indexes=indexes, colormap=colormap, vmin=vmin, vmax=vmax, nodata=nodata, attr=attribution, overlay=True, name=layer_name, **kwargs, ) else: if tile_format == "ipyleaflet": tile_layer = get_leaflet_tile_layer( tile_client, port=port, debug=debug, indexes=indexes, colormap=colormap, vmin=vmin, vmax=vmax, nodata=nodata, attribution=attribution, name=layer_name, **kwargs, ) else: tile_layer = get_folium_tile_layer( tile_client, port=port, debug=debug, indexes=indexes, colormap=colormap, vmin=vmin, vmax=vmax, nodata=nodata, attr=attribution, overlay=True, name=layer_name, **kwargs, ) if return_client: return tile_layer, tile_client else: return tile_layer # center = tile_client.center() # bounds = tile_client.bounds() # [ymin, ymax, xmin, xmax] # bounds = (bounds[2], bounds[0], bounds[3], bounds[1]) # [minx, miny, maxx, maxy] # if get_center and get_bounds: # return tile_layer, center, bounds # elif get_center: # return tile_layer, center # elif get_bounds: # return tile_layer, bounds # else: # return tile_layer def download_file( url=None, output=None, quiet=False, proxy=None, speed=None, use_cookies=True, verify=True, id=None, fuzzy=False, resume=False, unzip=True, overwrite=False, ): """Download a file from URL, including Google Drive shared URL. Args: url (str, optional): Google Drive URL is also supported. Defaults to None. output (str, optional): Output filename. Default is basename of URL. quiet (bool, optional): Suppress terminal output. Default is False. proxy (str, optional): Proxy. Defaults to None. speed (float, optional): Download byte size per second (e.g., 256KB/s = 256 * 1024). Defaults to None. use_cookies (bool, optional): Flag to use cookies. Defaults to True. verify (bool | str, optional): Either a bool, in which case it controls whether the server's TLS certificate is verified, or a string, in which case it must be a path to a CA bundle to use. Default is True.. Defaults to True. id (str, optional): Google Drive's file ID. Defaults to None. fuzzy (bool, optional): Fuzzy extraction of Google Drive's file Id. Defaults to False. resume (bool, optional): Resume the download from existing tmp file if possible. Defaults to False. unzip (bool, optional): Unzip the file. Defaults to True. overwrite (bool, optional): Overwrite the file if it already exists. Defaults to False. Returns: str: The output file path. """ import gdown if output is None: if isinstance(url, str) and url.startswith("http"): output = os.path.basename(url) if isinstance(url, str): if os.path.exists(os.path.abspath(output)) and (not overwrite): print( f"{output} already exists. Skip downloading. Set overwrite=True to overwrite." ) return os.path.abspath(output) else: url = github_raw_url(url) if "https://drive.google.com/file/d/" in url: fuzzy = True output = gdown.download( url, output, quiet, proxy, speed, use_cookies, verify, id, fuzzy, resume ) if unzip and output.endswith(".zip"): with zipfile.ZipFile(output, "r") as zip_ref: if not quiet: print("Extracting files...") zip_ref.extractall(os.path.dirname(output)) return os.path.abspath(output) The provided code snippet includes necessary dependencies for implementing the `netcdf_tile_layer` function. Write a Python function `def netcdf_tile_layer( filename, variables=None, colormap=None, vmin=None, vmax=None, nodata=None, port="default", debug=False, attribution=None, tile_format="ipyleaflet", layer_name="NetCDF layer", return_client=False, shift_lon=True, lat="lat", lon="lon", **kwargs, )` to solve the following problem: Generate an ipyleaflet/folium TileLayer from a netCDF file. If you are using this function in JupyterHub on a remote server (e.g., Binder, Microsoft Planetary Computer), try adding to following two lines to the beginning of the notebook if the raster does not render properly. import os os.environ['LOCALTILESERVER_CLIENT_PREFIX'] = f'{os.environ['JUPYTERHUB_SERVICE_PREFIX'].lstrip('/')}/proxy/{{port}}' Args: filename (str): File path or HTTP URL to the netCDF file. variables (int, optional): The variable/band names to extract data from the netCDF file. Defaults to None. If None, all variables will be extracted. port (str, optional): The port to use for the server. Defaults to "default". colormap (str, optional): The name of the colormap from `matplotlib` to use when plotting a single band. See https://matplotlib.org/stable/gallery/color/colormap_reference.html. Default is greyscale. vmin (float, optional): The minimum value to use when colormapping the colormap when plotting a single band. Defaults to None. vmax (float, optional): The maximum value to use when colormapping the colormap when plotting a single band. Defaults to None. nodata (float, optional): The value from the band to use to interpret as not valid data. Defaults to None. debug (bool, optional): If True, the server will be started in debug mode. Defaults to False. projection (str, optional): The projection of the GeoTIFF. Defaults to "EPSG:3857". attribution (str, optional): Attribution for the source raster. This defaults to a message about it being a local file.. Defaults to None. tile_format (str, optional): The tile layer format. Can be either ipyleaflet or folium. Defaults to "ipyleaflet". layer_name (str, optional): The layer name to use. Defaults to "NetCDF layer". return_client (bool, optional): If True, the tile client will be returned. Defaults to False. shift_lon (bool, optional): Flag to shift longitude values from [0, 360] to the range [-180, 180]. Defaults to True. lat (str, optional): Name of the latitude variable. Defaults to 'lat'. lon (str, optional): Name of the longitude variable. Defaults to 'lon'. Returns: ipyleaflet.TileLayer | folium.TileLayer: An ipyleaflet.TileLayer or folium.TileLayer. Here is the function: def netcdf_tile_layer( filename, variables=None, colormap=None, vmin=None, vmax=None, nodata=None, port="default", debug=False, attribution=None, tile_format="ipyleaflet", layer_name="NetCDF layer", return_client=False, shift_lon=True, lat="lat", lon="lon", **kwargs, ): """Generate an ipyleaflet/folium TileLayer from a netCDF file. If you are using this function in JupyterHub on a remote server (e.g., Binder, Microsoft Planetary Computer), try adding to following two lines to the beginning of the notebook if the raster does not render properly. import os os.environ['LOCALTILESERVER_CLIENT_PREFIX'] = f'{os.environ['JUPYTERHUB_SERVICE_PREFIX'].lstrip('/')}/proxy/{{port}}' Args: filename (str): File path or HTTP URL to the netCDF file. variables (int, optional): The variable/band names to extract data from the netCDF file. Defaults to None. If None, all variables will be extracted. port (str, optional): The port to use for the server. Defaults to "default". colormap (str, optional): The name of the colormap from `matplotlib` to use when plotting a single band. See https://matplotlib.org/stable/gallery/color/colormap_reference.html. Default is greyscale. vmin (float, optional): The minimum value to use when colormapping the colormap when plotting a single band. Defaults to None. vmax (float, optional): The maximum value to use when colormapping the colormap when plotting a single band. Defaults to None. nodata (float, optional): The value from the band to use to interpret as not valid data. Defaults to None. debug (bool, optional): If True, the server will be started in debug mode. Defaults to False. projection (str, optional): The projection of the GeoTIFF. Defaults to "EPSG:3857". attribution (str, optional): Attribution for the source raster. This defaults to a message about it being a local file.. Defaults to None. tile_format (str, optional): The tile layer format. Can be either ipyleaflet or folium. Defaults to "ipyleaflet". layer_name (str, optional): The layer name to use. Defaults to "NetCDF layer". return_client (bool, optional): If True, the tile client will be returned. Defaults to False. shift_lon (bool, optional): Flag to shift longitude values from [0, 360] to the range [-180, 180]. Defaults to True. lat (str, optional): Name of the latitude variable. Defaults to 'lat'. lon (str, optional): Name of the longitude variable. Defaults to 'lon'. Returns: ipyleaflet.TileLayer | folium.TileLayer: An ipyleaflet.TileLayer or folium.TileLayer. """ check_package( "localtileserver", URL="https://github.com/banesullivan/localtileserver" ) try: import xarray as xr except ImportError as e: raise ImportError(e) if filename.startswith("http"): filename = download_file(filename) if not os.path.exists(filename): raise FileNotFoundError(f"{filename} does not exist.") output = filename.replace(".nc", ".tif") xds = xr.open_dataset(filename, **kwargs) if shift_lon: xds.coords[lon] = (xds.coords[lon] + 180) % 360 - 180 xds = xds.sortby(xds.lon) allowed_vars = list(xds.data_vars.keys()) if isinstance(variables, str): if variables not in allowed_vars: raise ValueError(f"{variables} is not a subset of {allowed_vars}.") variables = [variables] if variables is not None and len(variables) > 3: raise ValueError("Only 3 variables can be plotted at a time.") if variables is not None and (not set(variables).issubset(allowed_vars)): raise ValueError(f"{variables} must be a subset of {allowed_vars}.") xds.rio.set_spatial_dims(x_dim=lon, y_dim=lat).rio.to_raster(output) if variables is None: if len(allowed_vars) >= 3: band_idx = [1, 2, 3] else: band_idx = [1] else: band_idx = [allowed_vars.index(var) + 1 for var in variables] tile_layer = get_local_tile_layer( output, port=port, debug=debug, indexes=band_idx, colormap=colormap, vmin=vmin, vmax=vmax, nodata=nodata, attribution=attribution, tile_format=tile_format, layer_name=layer_name, return_client=return_client, ) return tile_layer
Generate an ipyleaflet/folium TileLayer from a netCDF file. If you are using this function in JupyterHub on a remote server (e.g., Binder, Microsoft Planetary Computer), try adding to following two lines to the beginning of the notebook if the raster does not render properly. import os os.environ['LOCALTILESERVER_CLIENT_PREFIX'] = f'{os.environ['JUPYTERHUB_SERVICE_PREFIX'].lstrip('/')}/proxy/{{port}}' Args: filename (str): File path or HTTP URL to the netCDF file. variables (int, optional): The variable/band names to extract data from the netCDF file. Defaults to None. If None, all variables will be extracted. port (str, optional): The port to use for the server. Defaults to "default". colormap (str, optional): The name of the colormap from `matplotlib` to use when plotting a single band. See https://matplotlib.org/stable/gallery/color/colormap_reference.html. Default is greyscale. vmin (float, optional): The minimum value to use when colormapping the colormap when plotting a single band. Defaults to None. vmax (float, optional): The maximum value to use when colormapping the colormap when plotting a single band. Defaults to None. nodata (float, optional): The value from the band to use to interpret as not valid data. Defaults to None. debug (bool, optional): If True, the server will be started in debug mode. Defaults to False. projection (str, optional): The projection of the GeoTIFF. Defaults to "EPSG:3857". attribution (str, optional): Attribution for the source raster. This defaults to a message about it being a local file.. Defaults to None. tile_format (str, optional): The tile layer format. Can be either ipyleaflet or folium. Defaults to "ipyleaflet". layer_name (str, optional): The layer name to use. Defaults to "NetCDF layer". return_client (bool, optional): If True, the tile client will be returned. Defaults to False. shift_lon (bool, optional): Flag to shift longitude values from [0, 360] to the range [-180, 180]. Defaults to True. lat (str, optional): Name of the latitude variable. Defaults to 'lat'. lon (str, optional): Name of the longitude variable. Defaults to 'lon'. Returns: ipyleaflet.TileLayer | folium.TileLayer: An ipyleaflet.TileLayer or folium.TileLayer.
12,384
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple def check_color(in_color): """Checks the input color and returns the corresponding hex color code. Args: in_color (str or tuple): It can be a string (e.g., 'red', '#ffff00', 'ffff00', 'ff0') or RGB tuple (e.g., (255, 127, 0)). Returns: str: A hex color code. """ import colour out_color = "#000000" # default black color if isinstance(in_color, tuple) and len(in_color) == 3: # rescale color if necessary if all(isinstance(item, int) for item in in_color): in_color = [c / 255.0 for c in in_color] return colour.Color(rgb=tuple(in_color)).hex_l else: # try to guess the color system try: return colour.Color(in_color).hex_l except Exception as e: pass # try again by adding an extra # (GEE handle hex codes without #) try: return colour.Color(f"#{in_color}").hex_l except Exception as e: print( f"The provided color ({in_color}) is invalid. Using the default black color." ) print(e) return out_color The provided code snippet includes necessary dependencies for implementing the `classify` function. Write a Python function `def classify( data, column, cmap=None, colors=None, labels=None, scheme="Quantiles", k=5, legend_kwds=None, classification_kwds=None, )` to solve the following problem: Classify a dataframe column using a variety of classification schemes. Args: data (str | pd.DataFrame | gpd.GeoDataFrame): The data to classify. It can be a filepath to a vector dataset, a pandas dataframe, or a geopandas geodataframe. column (str): The column to classify. cmap (str, optional): The name of a colormap recognized by matplotlib. Defaults to None. colors (list, optional): A list of colors to use for the classification. Defaults to None. labels (list, optional): A list of labels to use for the legend. Defaults to None. scheme (str, optional): Name of a choropleth classification scheme (requires mapclassify). Name of a choropleth classification scheme (requires mapclassify). A mapclassify.MapClassifier object will be used under the hood. Supported are all schemes provided by mapclassify (e.g. 'BoxPlot', 'EqualInterval', 'FisherJenks', 'FisherJenksSampled', 'HeadTailBreaks', 'JenksCaspall', 'JenksCaspallForced', 'JenksCaspallSampled', 'MaxP', 'MaximumBreaks', 'NaturalBreaks', 'Quantiles', 'Percentiles', 'StdMean', 'UserDefined'). Arguments can be passed in classification_kwds. k (int, optional): Number of classes (ignored if scheme is None or if column is categorical). Default to 5. legend_kwds (dict, optional): Keyword arguments to pass to :func:`matplotlib.pyplot.legend` or `matplotlib.pyplot.colorbar`. Defaults to None. Keyword arguments to pass to :func:`matplotlib.pyplot.legend` or Additional accepted keywords when `scheme` is specified: fmt : string A formatting specification for the bin edges of the classes in the legend. For example, to have no decimals: ``{"fmt": "{:.0f}"}``. labels : list-like A list of legend labels to override the auto-generated labblels. Needs to have the same number of elements as the number of classes (`k`). interval : boolean (default False) An option to control brackets from mapclassify legend. If True, open/closed interval brackets are shown in the legend. classification_kwds (dict, optional): Keyword arguments to pass to mapclassify. Defaults to None. Returns: pd.DataFrame, dict: A pandas dataframe with the classification applied and a legend dictionary. Here is the function: def classify( data, column, cmap=None, colors=None, labels=None, scheme="Quantiles", k=5, legend_kwds=None, classification_kwds=None, ): """Classify a dataframe column using a variety of classification schemes. Args: data (str | pd.DataFrame | gpd.GeoDataFrame): The data to classify. It can be a filepath to a vector dataset, a pandas dataframe, or a geopandas geodataframe. column (str): The column to classify. cmap (str, optional): The name of a colormap recognized by matplotlib. Defaults to None. colors (list, optional): A list of colors to use for the classification. Defaults to None. labels (list, optional): A list of labels to use for the legend. Defaults to None. scheme (str, optional): Name of a choropleth classification scheme (requires mapclassify). Name of a choropleth classification scheme (requires mapclassify). A mapclassify.MapClassifier object will be used under the hood. Supported are all schemes provided by mapclassify (e.g. 'BoxPlot', 'EqualInterval', 'FisherJenks', 'FisherJenksSampled', 'HeadTailBreaks', 'JenksCaspall', 'JenksCaspallForced', 'JenksCaspallSampled', 'MaxP', 'MaximumBreaks', 'NaturalBreaks', 'Quantiles', 'Percentiles', 'StdMean', 'UserDefined'). Arguments can be passed in classification_kwds. k (int, optional): Number of classes (ignored if scheme is None or if column is categorical). Default to 5. legend_kwds (dict, optional): Keyword arguments to pass to :func:`matplotlib.pyplot.legend` or `matplotlib.pyplot.colorbar`. Defaults to None. Keyword arguments to pass to :func:`matplotlib.pyplot.legend` or Additional accepted keywords when `scheme` is specified: fmt : string A formatting specification for the bin edges of the classes in the legend. For example, to have no decimals: ``{"fmt": "{:.0f}"}``. labels : list-like A list of legend labels to override the auto-generated labblels. Needs to have the same number of elements as the number of classes (`k`). interval : boolean (default False) An option to control brackets from mapclassify legend. If True, open/closed interval brackets are shown in the legend. classification_kwds (dict, optional): Keyword arguments to pass to mapclassify. Defaults to None. Returns: pd.DataFrame, dict: A pandas dataframe with the classification applied and a legend dictionary. """ import numpy as np import pandas as pd import geopandas as gpd import matplotlib as mpl import matplotlib.pyplot as plt try: import mapclassify except ImportError: raise ImportError( 'mapclassify is required for this function. Install with "pip install mapclassify".' ) if isinstance(data, gpd.GeoDataFrame) or isinstance(data, pd.DataFrame): df = data else: try: df = gpd.read_file(data) except Exception: raise TypeError( "Data must be a GeoDataFrame or a path to a file that can be read by geopandas.read_file()." ) if df.empty: warnings.warn( "The GeoDataFrame you are attempting to plot is " "empty. Nothing has been displayed.", UserWarning, ) return columns = df.columns.values.tolist() if column not in columns: raise ValueError( f"{column} is not a column in the GeoDataFrame. It must be one of {columns}." ) # Convert categorical data to numeric init_column = None value_list = None if np.issubdtype(df[column].dtype, np.object0): value_list = df[column].unique().tolist() value_list.sort() df["category"] = df[column].replace(value_list, range(0, len(value_list))) init_column = column column = "category" k = len(value_list) if legend_kwds is not None: legend_kwds = legend_kwds.copy() # To accept pd.Series and np.arrays as column if isinstance(column, (np.ndarray, pd.Series)): if column.shape[0] != df.shape[0]: raise ValueError( "The dataframe and given column have different number of rows." ) else: values = column # Make sure index of a Series matches index of df if isinstance(values, pd.Series): values = values.reindex(df.index) else: values = df[column] values = df[column] nan_idx = np.asarray(pd.isna(values), dtype="bool") if cmap is None: cmap = "Blues" cmap = plt.cm.get_cmap(cmap, k) if colors is None: colors = [mpl.colors.rgb2hex(cmap(i))[1:] for i in range(cmap.N)] colors = ["#" + i for i in colors] elif isinstance(colors, list): colors = [check_color(i) for i in colors] elif isinstance(colors, str): colors = [check_color(colors)] * k allowed_schemes = [ "BoxPlot", "EqualInterval", "FisherJenks", "FisherJenksSampled", "HeadTailBreaks", "JenksCaspall", "JenksCaspallForced", "JenksCaspallSampled", "MaxP", "MaximumBreaks", "NaturalBreaks", "Quantiles", "Percentiles", "StdMean", "UserDefined", ] if scheme.lower() not in [s.lower() for s in allowed_schemes]: raise ValueError( f"{scheme} is not a valid scheme. It must be one of {allowed_schemes}." ) if classification_kwds is None: classification_kwds = {} if "k" not in classification_kwds: classification_kwds["k"] = k binning = mapclassify.classify( np.asarray(values[~nan_idx]), scheme, **classification_kwds ) df["category"] = binning.yb df["color"] = [colors[i] for i in df["category"]] if legend_kwds is None: legend_kwds = {} if "interval" not in legend_kwds: legend_kwds["interval"] = True if "fmt" not in legend_kwds: if np.issubdtype(df[column].dtype, np.floating): legend_kwds["fmt"] = "{:.2f}" else: legend_kwds["fmt"] = "{:.0f}" if labels is None: # set categorical to True for creating the legend if legend_kwds is not None and "labels" in legend_kwds: if len(legend_kwds["labels"]) != binning.k: raise ValueError( "Number of labels must match number of bins, " "received {} labels for {} bins".format( len(legend_kwds["labels"]), binning.k ) ) else: labels = list(legend_kwds.pop("labels")) else: # fmt = "{:.2f}" if legend_kwds is not None and "fmt" in legend_kwds: fmt = legend_kwds.pop("fmt") labels = binning.get_legend_classes(fmt) if legend_kwds is not None: show_interval = legend_kwds.pop("interval", False) else: show_interval = False if not show_interval: labels = [c[1:-1] for c in labels] if init_column is not None: labels = value_list elif isinstance(labels, list): if len(labels) != len(colors): raise ValueError("The number of labels must match the number of colors.") else: raise ValueError("labels must be a list or None.") legend_dict = dict(zip(labels, colors)) df["category"] = df["category"] + 1 return df, legend_dict
Classify a dataframe column using a variety of classification schemes. Args: data (str | pd.DataFrame | gpd.GeoDataFrame): The data to classify. It can be a filepath to a vector dataset, a pandas dataframe, or a geopandas geodataframe. column (str): The column to classify. cmap (str, optional): The name of a colormap recognized by matplotlib. Defaults to None. colors (list, optional): A list of colors to use for the classification. Defaults to None. labels (list, optional): A list of labels to use for the legend. Defaults to None. scheme (str, optional): Name of a choropleth classification scheme (requires mapclassify). Name of a choropleth classification scheme (requires mapclassify). A mapclassify.MapClassifier object will be used under the hood. Supported are all schemes provided by mapclassify (e.g. 'BoxPlot', 'EqualInterval', 'FisherJenks', 'FisherJenksSampled', 'HeadTailBreaks', 'JenksCaspall', 'JenksCaspallForced', 'JenksCaspallSampled', 'MaxP', 'MaximumBreaks', 'NaturalBreaks', 'Quantiles', 'Percentiles', 'StdMean', 'UserDefined'). Arguments can be passed in classification_kwds. k (int, optional): Number of classes (ignored if scheme is None or if column is categorical). Default to 5. legend_kwds (dict, optional): Keyword arguments to pass to :func:`matplotlib.pyplot.legend` or `matplotlib.pyplot.colorbar`. Defaults to None. Keyword arguments to pass to :func:`matplotlib.pyplot.legend` or Additional accepted keywords when `scheme` is specified: fmt : string A formatting specification for the bin edges of the classes in the legend. For example, to have no decimals: ``{"fmt": "{:.0f}"}``. labels : list-like A list of legend labels to override the auto-generated labblels. Needs to have the same number of elements as the number of classes (`k`). interval : boolean (default False) An option to control brackets from mapclassify legend. If True, open/closed interval brackets are shown in the legend. classification_kwds (dict, optional): Keyword arguments to pass to mapclassify. Defaults to None. Returns: pd.DataFrame, dict: A pandas dataframe with the classification applied and a legend dictionary.
12,385
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple The provided code snippet includes necessary dependencies for implementing the `image_count` function. Write a Python function `def image_count( collection, region=None, band=None, start_date=None, end_date=None, clip=False )` to solve the following problem: Create an image with the number of available images for a specific region. Args: collection (ee.ImageCollection): The collection to be queried. region (ee.Geometry | ee.FeatureCollection, optional): The region to be queried. start_date (str | ee.Date, optional): The start date of the query. band (str, optional): The band to be queried. end_date (str | ee.Date, optional): The end date of the query. clip (bool, optional): Whether to clip the image to the region. Returns: ee.Image: The image with each pixel value representing the number of available images. Here is the function: def image_count( collection, region=None, band=None, start_date=None, end_date=None, clip=False ): """Create an image with the number of available images for a specific region. Args: collection (ee.ImageCollection): The collection to be queried. region (ee.Geometry | ee.FeatureCollection, optional): The region to be queried. start_date (str | ee.Date, optional): The start date of the query. band (str, optional): The band to be queried. end_date (str | ee.Date, optional): The end date of the query. clip (bool, optional): Whether to clip the image to the region. Returns: ee.Image: The image with each pixel value representing the number of available images. """ if not isinstance(collection, ee.ImageCollection): raise TypeError("collection must be an ee.ImageCollection.") if region is not None: if isinstance(region, ee.Geometry) or isinstance(region, ee.FeatureCollection): pass else: raise TypeError("region must be an ee.Geometry or ee.FeatureCollection.") if (start_date is not None) and (end_date is not None): pass elif (start_date is None) and (end_date is None): pass else: raise ValueError("start_date and end_date must be provided.") if band is None: first_image = collection.first() band = first_image.bandNames().get(0) if region is not None: collection = collection.filterBounds(region) if start_date is not None and end_date is not None: collection = collection.filterDate(start_date, end_date) image = ( collection.filter(ee.Filter.listContains("system:band_names", band)) .select([band]) .reduce(ee.Reducer.count()) ) if clip: image = image.clip(region) return image
Create an image with the number of available images for a specific region. Args: collection (ee.ImageCollection): The collection to be queried. region (ee.Geometry | ee.FeatureCollection, optional): The region to be queried. start_date (str | ee.Date, optional): The start date of the query. band (str, optional): The band to be queried. end_date (str | ee.Date, optional): The end date of the query. clip (bool, optional): Whether to clip the image to the region. Returns: ee.Image: The image with each pixel value representing the number of available images.
12,386
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple The provided code snippet includes necessary dependencies for implementing the `dynamic_world` function. Write a Python function `def dynamic_world( region=None, start_date="2020-01-01", end_date="2021-01-01", clip=False, reducer=None, projection="EPSG:3857", scale=10, return_type="hillshade", )` to solve the following problem: Create 10-m land cover composite based on Dynamic World. The source code is adapted from the following tutorial by Spatial Thoughts: https://developers.google.com/earth-engine/tutorials/community/introduction-to-dynamic-world-pt-1 Args: region (ee.Geometry | ee.FeatureCollection): The region of interest. start_date (str | ee.Date): The start date of the query. Default to "2020-01-01". end_date (str | ee.Date): The end date of the query. Default to "2021-01-01". clip (bool, optional): Whether to clip the image to the region. Default to False. reducer (ee.Reducer, optional): The reducer to be used. Default to None. projection (str, optional): The projection to be used for creating hillshade. Default to "EPSG:3857". scale (int, optional): The scale to be used for creating hillshade. Default to 10. return_type (str, optional): The type of image to be returned. Can be one of 'hillshade', 'visualize', 'class', or 'probability'. Default to "hillshade". Returns: ee.Image: The image with the specified return_type. Here is the function: def dynamic_world( region=None, start_date="2020-01-01", end_date="2021-01-01", clip=False, reducer=None, projection="EPSG:3857", scale=10, return_type="hillshade", ): """Create 10-m land cover composite based on Dynamic World. The source code is adapted from the following tutorial by Spatial Thoughts: https://developers.google.com/earth-engine/tutorials/community/introduction-to-dynamic-world-pt-1 Args: region (ee.Geometry | ee.FeatureCollection): The region of interest. start_date (str | ee.Date): The start date of the query. Default to "2020-01-01". end_date (str | ee.Date): The end date of the query. Default to "2021-01-01". clip (bool, optional): Whether to clip the image to the region. Default to False. reducer (ee.Reducer, optional): The reducer to be used. Default to None. projection (str, optional): The projection to be used for creating hillshade. Default to "EPSG:3857". scale (int, optional): The scale to be used for creating hillshade. Default to 10. return_type (str, optional): The type of image to be returned. Can be one of 'hillshade', 'visualize', 'class', or 'probability'. Default to "hillshade". Returns: ee.Image: The image with the specified return_type. """ if return_type not in ["hillshade", "visualize", "class", "probability"]: raise ValueError( f"{return_type} must be one of 'hillshade', 'visualize', 'class', or 'probability'." ) if reducer is None: reducer = ee.Reducer.mode() dw = ee.ImageCollection("GOOGLE/DYNAMICWORLD/V1").filter( ee.Filter.date(start_date, end_date) ) if isinstance(region, ee.FeatureCollection) or isinstance(region, ee.Geometry): dw = dw.filterBounds(region) else: raise ValueError("region must be an ee.FeatureCollection or ee.Geometry.") # Create a Mode Composite classification = dw.select("label") dwComposite = classification.reduce(reducer) if clip and (region is not None): if isinstance(region, ee.Geometry): dwComposite = dwComposite.clip(region) elif isinstance(region, ee.FeatureCollection): dwComposite = dwComposite.clipToCollection(region) elif isinstance(region, ee.Feature): dwComposite = dwComposite.clip(region.geometry()) dwVisParams = { "min": 0, "max": 8, "palette": [ "#419BDF", "#397D49", "#88B053", "#7A87C6", "#E49635", "#DFC35A", "#C4281B", "#A59B8F", "#B39FE1", ], } if return_type == "class": return dwComposite elif return_type == "visualize": return dwComposite.visualize(**dwVisParams) else: # Create a Top-1 Probability Hillshade Visualization probabilityBands = [ "water", "trees", "grass", "flooded_vegetation", "crops", "shrub_and_scrub", "built", "bare", "snow_and_ice", ] # Select probability bands probabilityCol = dw.select(probabilityBands) # Create a multi-band image with the average pixel-wise probability # for each band across the time-period meanProbability = probabilityCol.reduce(ee.Reducer.mean()) # Composites have a default projection that is not suitable # for hillshade computation. # Set a EPSG:3857 projection with 10m scale proj = ee.Projection(projection).atScale(scale) meanProbability = meanProbability.setDefaultProjection(proj) # Create the Top1 Probability Hillshade top1Probability = meanProbability.reduce(ee.Reducer.max()) if clip and (region is not None): if isinstance(region, ee.Geometry): top1Probability = top1Probability.clip(region) elif isinstance(region, ee.FeatureCollection): top1Probability = top1Probability.clipToCollection(region) elif isinstance(region, ee.Feature): top1Probability = top1Probability.clip(region.geometry()) if return_type == "probability": return top1Probability else: top1Confidence = top1Probability.multiply(100).int() hillshade = ee.Terrain.hillshade(top1Confidence).divide(255) rgbImage = dwComposite.visualize(**dwVisParams).divide(255) probabilityHillshade = rgbImage.multiply(hillshade) return probabilityHillshade
Create 10-m land cover composite based on Dynamic World. The source code is adapted from the following tutorial by Spatial Thoughts: https://developers.google.com/earth-engine/tutorials/community/introduction-to-dynamic-world-pt-1 Args: region (ee.Geometry | ee.FeatureCollection): The region of interest. start_date (str | ee.Date): The start date of the query. Default to "2020-01-01". end_date (str | ee.Date): The end date of the query. Default to "2021-01-01". clip (bool, optional): Whether to clip the image to the region. Default to False. reducer (ee.Reducer, optional): The reducer to be used. Default to None. projection (str, optional): The projection to be used for creating hillshade. Default to "EPSG:3857". scale (int, optional): The scale to be used for creating hillshade. Default to 10. return_type (str, optional): The type of image to be returned. Can be one of 'hillshade', 'visualize', 'class', or 'probability'. Default to "hillshade". Returns: ee.Image: The image with the specified return_type.
12,387
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple The provided code snippet includes necessary dependencies for implementing the `dynamic_world_s2` function. Write a Python function `def dynamic_world_s2( region=None, start_date="2020-01-01", end_date="2021-01-01", clip=False, cloud_pct=0.35, reducer=None, )` to solve the following problem: Create Sentinel-2 composite for the Dynamic World Land Cover product. Args: region (ee.Geometry | ee.FeatureCollection): The region of interest. Default to None. start_date (str | ee.Date): The start date of the query. Default to "2020-01-01". end_date (str | ee.Date): The end date of the query. Default to "2021-01-01". clip (bool, optional): Whether to clip the image to the region. Default to False. cloud_pct (float, optional): The percentage of cloud cover to be used for filtering. Default to 0.35. reducer (ee.Reducer, optional): The reducer to be used for creating image composite. Default to None. Returns: ee.Image: The Sentinel-2 composite. Here is the function: def dynamic_world_s2( region=None, start_date="2020-01-01", end_date="2021-01-01", clip=False, cloud_pct=0.35, reducer=None, ): """Create Sentinel-2 composite for the Dynamic World Land Cover product. Args: region (ee.Geometry | ee.FeatureCollection): The region of interest. Default to None. start_date (str | ee.Date): The start date of the query. Default to "2020-01-01". end_date (str | ee.Date): The end date of the query. Default to "2021-01-01". clip (bool, optional): Whether to clip the image to the region. Default to False. cloud_pct (float, optional): The percentage of cloud cover to be used for filtering. Default to 0.35. reducer (ee.Reducer, optional): The reducer to be used for creating image composite. Default to None. Returns: ee.Image: The Sentinel-2 composite. """ s2 = ( ee.ImageCollection("COPERNICUS/S2_HARMONIZED") .filterDate(start_date, end_date) .filter(ee.Filter.lt("CLOUDY_PIXEL_PERCENTAGE", cloud_pct * 100)) ) if isinstance(region, ee.FeatureCollection) or isinstance(region, ee.Geometry): s2 = s2.filterBounds(region) else: raise ValueError("region must be an ee.FeatureCollection or ee.Geometry.") if reducer is None: reducer = ee.Reducer.median() image = s2.reduce(reducer).rename(s2.first().bandNames()) if clip and (region is not None): if isinstance(region, ee.Geometry): image = image.clip(region) elif isinstance(region, ee.FeatureCollection): image = image.clipToCollection(region) return image
Create Sentinel-2 composite for the Dynamic World Land Cover product. Args: region (ee.Geometry | ee.FeatureCollection): The region of interest. Default to None. start_date (str | ee.Date): The start date of the query. Default to "2020-01-01". end_date (str | ee.Date): The end date of the query. Default to "2021-01-01". clip (bool, optional): Whether to clip the image to the region. Default to False. cloud_pct (float, optional): The percentage of cloud cover to be used for filtering. Default to 0.35. reducer (ee.Reducer, optional): The reducer to be used for creating image composite. Default to None. Returns: ee.Image: The Sentinel-2 composite.
12,388
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple def download_ee_image( image, filename, region=None, crs=None, crs_transform=None, scale=None, resampling="near", dtype=None, overwrite=True, num_threads=None, max_tile_size=None, max_tile_dim=None, shape=None, scale_offset=False, unmask_value=None, **kwargs, ): """Download an Earth Engine Image as a GeoTIFF. Images larger than the `Earth Engine size limit are split and downloaded as separate tiles, then re-assembled into a single GeoTIFF. See https://github.com/dugalh/geedim/blob/main/geedim/download.py#L574 Args: image (ee.Image): The image to be downloaded. filename (str): Name of the destination file. region (ee.Geometry, optional): Region defined by geojson polygon in WGS84. Defaults to the entire image granule. crs (str, optional): Reproject image(s) to this EPSG or WKT CRS. Where image bands have different CRSs, all are re-projected to this CRS. Defaults to the CRS of the minimum scale band. crs_transform (list, optional): tuple of float, list of float, rio.Affine, optional List of 6 numbers specifying an affine transform in the specified CRS. In row-major order: [xScale, xShearing, xTranslation, yShearing, yScale, yTranslation]. All bands are re-projected to this transform. scale (float, optional): Resample image(s) to this pixel scale (size) (m). Where image bands have different scales, all are resampled to this scale. Defaults to the minimum scale of image bands. resampling (ResamplingMethod, optional): Resampling method, can be 'near', 'bilinear', 'bicubic', or 'average'. Defaults to None. dtype (str, optional): Convert to this data type (`uint8`, `int8`, `uint16`, `int16`, `uint32`, `int32`, `float32` or `float64`). Defaults to auto select a minimum size type that can represent the range of pixel values. overwrite (bool, optional): Overwrite the destination file if it exists. Defaults to True. num_threads (int, optional): Number of tiles to download concurrently. Defaults to a sensible auto value. max_tile_size: int, optional Maximum tile size (MB). If None, defaults to the Earth Engine download size limit (32 MB). max_tile_dim: int, optional Maximum tile width/height (pixels). If None, defaults to Earth Engine download limit (10000). shape: tuple of int, optional (height, width) dimensions to export (pixels). scale_offset: bool, optional Whether to apply any EE band scales and offsets to the image. unmask_value (float, optional): The value to use for pixels that are masked in the input image. If the exported image contains zero values, you should set the unmask value to a non-zero value so that the zero values are not treated as missing data. Defaults to None. """ if os.environ.get("USE_MKDOCS") is not None: return try: import geedim as gd except ImportError: raise ImportError( "Please install geedim using `pip install geedim` or `conda install -c conda-forge geedim`" ) if not isinstance(image, ee.Image): raise ValueError("image must be an ee.Image.") if unmask_value is not None: image = image.selfMask().unmask(unmask_value) if isinstance(region, ee.Geometry): image = image.clip(region) elif isinstance(region, ee.FeatureCollection): image = image.clipToCollection(region) if region is not None: kwargs["region"] = region if crs is not None: kwargs["crs"] = crs if crs_transform is not None: kwargs["crs_transform"] = crs_transform if scale is not None: kwargs["scale"] = scale if resampling is not None: kwargs["resampling"] = resampling if dtype is not None: kwargs["dtype"] = dtype if max_tile_size is not None: kwargs["max_tile_size"] = max_tile_size if max_tile_dim is not None: kwargs["max_tile_dim"] = max_tile_dim if shape is not None: kwargs["shape"] = shape if scale_offset: kwargs["scale_offset"] = scale_offset img = gd.download.BaseImage(image) img.download(filename, overwrite=overwrite, num_threads=num_threads, **kwargs) The provided code snippet includes necessary dependencies for implementing the `download_ee_image_tiles` function. Write a Python function `def download_ee_image_tiles( image, features, out_dir=None, prefix=None, crs=None, crs_transform=None, scale=None, resampling="near", dtype=None, overwrite=True, num_threads=None, max_tile_size=None, max_tile_dim=None, shape=None, scale_offset=False, unmask_value=None, column=None, **kwargs, )` to solve the following problem: Download an Earth Engine Image as small tiles based on ee.FeatureCollection. Images larger than the `Earth Engine size limit are split and downloaded as separate tiles, then re-assembled into a single GeoTIFF. See https://github.com/dugalh/geedim/blob/main/geedim/download.py#L574 Args: image (ee.Image): The image to be downloaded. features (ee.FeatureCollection): The features to loop through to download image. out_dir (str, optional): The output directory. Defaults to None. prefix (str, optional): The prefix for the output file. Defaults to None. crs (str, optional): Reproject image(s) to this EPSG or WKT CRS. Where image bands have different CRSs, all are re-projected to this CRS. Defaults to the CRS of the minimum scale band. crs_transform (list, optional): tuple of float, list of float, rio.Affine, optional List of 6 numbers specifying an affine transform in the specified CRS. In row-major order: [xScale, xShearing, xTranslation, yShearing, yScale, yTranslation]. All bands are re-projected to this transform. scale (float, optional): Resample image(s) to this pixel scale (size) (m). Where image bands have different scales, all are resampled to this scale. Defaults to the minimum scale of image bands. resampling (ResamplingMethod, optional): Resampling method, can be 'near', 'bilinear', 'bicubic', or 'average'. Defaults to None. dtype (str, optional): Convert to this data type (`uint8`, `int8`, `uint16`, `int16`, `uint32`, `int32`, `float32` or `float64`). Defaults to auto select a minimum size type that can represent the range of pixel values. overwrite (bool, optional): Overwrite the destination file if it exists. Defaults to True. num_threads (int, optional): Number of tiles to download concurrently. Defaults to a sensible auto value. max_tile_size: int, optional Maximum tile size (MB). If None, defaults to the Earth Engine download size limit (32 MB). max_tile_dim: int, optional Maximum tile width/height (pixels). If None, defaults to Earth Engine download limit (10000). shape: tuple of int, optional (height, width) dimensions to export (pixels). scale_offset: bool, optional Whether to apply any EE band scales and offsets to the image. unmask_value (float, optional): The value to use for pixels that are masked in the input image. If the exported image contains zero values, you should set the unmask value to a non-zero value so that the zero values are not treated as missing data. Defaults to None. column (str, optional): The column name to use for the filename. Defaults to None. Here is the function: def download_ee_image_tiles( image, features, out_dir=None, prefix=None, crs=None, crs_transform=None, scale=None, resampling="near", dtype=None, overwrite=True, num_threads=None, max_tile_size=None, max_tile_dim=None, shape=None, scale_offset=False, unmask_value=None, column=None, **kwargs, ): """Download an Earth Engine Image as small tiles based on ee.FeatureCollection. Images larger than the `Earth Engine size limit are split and downloaded as separate tiles, then re-assembled into a single GeoTIFF. See https://github.com/dugalh/geedim/blob/main/geedim/download.py#L574 Args: image (ee.Image): The image to be downloaded. features (ee.FeatureCollection): The features to loop through to download image. out_dir (str, optional): The output directory. Defaults to None. prefix (str, optional): The prefix for the output file. Defaults to None. crs (str, optional): Reproject image(s) to this EPSG or WKT CRS. Where image bands have different CRSs, all are re-projected to this CRS. Defaults to the CRS of the minimum scale band. crs_transform (list, optional): tuple of float, list of float, rio.Affine, optional List of 6 numbers specifying an affine transform in the specified CRS. In row-major order: [xScale, xShearing, xTranslation, yShearing, yScale, yTranslation]. All bands are re-projected to this transform. scale (float, optional): Resample image(s) to this pixel scale (size) (m). Where image bands have different scales, all are resampled to this scale. Defaults to the minimum scale of image bands. resampling (ResamplingMethod, optional): Resampling method, can be 'near', 'bilinear', 'bicubic', or 'average'. Defaults to None. dtype (str, optional): Convert to this data type (`uint8`, `int8`, `uint16`, `int16`, `uint32`, `int32`, `float32` or `float64`). Defaults to auto select a minimum size type that can represent the range of pixel values. overwrite (bool, optional): Overwrite the destination file if it exists. Defaults to True. num_threads (int, optional): Number of tiles to download concurrently. Defaults to a sensible auto value. max_tile_size: int, optional Maximum tile size (MB). If None, defaults to the Earth Engine download size limit (32 MB). max_tile_dim: int, optional Maximum tile width/height (pixels). If None, defaults to Earth Engine download limit (10000). shape: tuple of int, optional (height, width) dimensions to export (pixels). scale_offset: bool, optional Whether to apply any EE band scales and offsets to the image. unmask_value (float, optional): The value to use for pixels that are masked in the input image. If the exported image contains zero values, you should set the unmask value to a non-zero value so that the zero values are not treated as missing data. Defaults to None. column (str, optional): The column name to use for the filename. Defaults to None. """ import time start = time.time() if os.environ.get("USE_MKDOCS") is not None: return if not isinstance(features, ee.FeatureCollection): raise ValueError("features must be an ee.FeatureCollection.") if out_dir is None: out_dir = os.getcwd() if not os.path.exists(out_dir): os.makedirs(out_dir) if prefix is None: prefix = "" count = features.size().getInfo() collection = features.toList(count) if column is not None: names = features.aggregate_array(column).getInfo() else: names = [str(i + 1).zfill(len(str(count))) for i in range(count)] for i in range(count): region = ee.Feature(collection.get(i)).geometry() filename = os.path.join( out_dir, "{}{}.tif".format(prefix, names[i].replace("/", "_")) ) print(f"Downloading {i + 1}/{count}: {filename}") download_ee_image( image, filename, region, crs, crs_transform, scale, resampling, dtype, overwrite, num_threads, max_tile_size, max_tile_dim, shape, scale_offset, unmask_value, **kwargs, ) print(f"Downloaded {count} tiles in {time.time() - start} seconds.")
Download an Earth Engine Image as small tiles based on ee.FeatureCollection. Images larger than the `Earth Engine size limit are split and downloaded as separate tiles, then re-assembled into a single GeoTIFF. See https://github.com/dugalh/geedim/blob/main/geedim/download.py#L574 Args: image (ee.Image): The image to be downloaded. features (ee.FeatureCollection): The features to loop through to download image. out_dir (str, optional): The output directory. Defaults to None. prefix (str, optional): The prefix for the output file. Defaults to None. crs (str, optional): Reproject image(s) to this EPSG or WKT CRS. Where image bands have different CRSs, all are re-projected to this CRS. Defaults to the CRS of the minimum scale band. crs_transform (list, optional): tuple of float, list of float, rio.Affine, optional List of 6 numbers specifying an affine transform in the specified CRS. In row-major order: [xScale, xShearing, xTranslation, yShearing, yScale, yTranslation]. All bands are re-projected to this transform. scale (float, optional): Resample image(s) to this pixel scale (size) (m). Where image bands have different scales, all are resampled to this scale. Defaults to the minimum scale of image bands. resampling (ResamplingMethod, optional): Resampling method, can be 'near', 'bilinear', 'bicubic', or 'average'. Defaults to None. dtype (str, optional): Convert to this data type (`uint8`, `int8`, `uint16`, `int16`, `uint32`, `int32`, `float32` or `float64`). Defaults to auto select a minimum size type that can represent the range of pixel values. overwrite (bool, optional): Overwrite the destination file if it exists. Defaults to True. num_threads (int, optional): Number of tiles to download concurrently. Defaults to a sensible auto value. max_tile_size: int, optional Maximum tile size (MB). If None, defaults to the Earth Engine download size limit (32 MB). max_tile_dim: int, optional Maximum tile width/height (pixels). If None, defaults to Earth Engine download limit (10000). shape: tuple of int, optional (height, width) dimensions to export (pixels). scale_offset: bool, optional Whether to apply any EE band scales and offsets to the image. unmask_value (float, optional): The value to use for pixels that are masked in the input image. If the exported image contains zero values, you should set the unmask value to a non-zero value so that the zero values are not treated as missing data. Defaults to None. column (str, optional): The column name to use for the filename. Defaults to None.
12,389
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple def ee_initialize( token_name="EARTHENGINE_TOKEN", auth_mode=None, service_account=False, auth_args={}, user_agent_prefix="geemap", **kwargs, ): """Authenticates Earth Engine and initialize an Earth Engine session Args: token_name (str, optional): The name of the Earth Engine token. Defaults to "EARTHENGINE_TOKEN". In Colab, you can also set a secret named "EE_PROJECT_ID" to initialize Earth Engine. auth_mode (str, optional): The authentication mode, can be one of colab, notebook, localhost, or gcloud. See https://developers.google.com/earth-engine/guides/auth for more details. Defaults to None. service_account (bool, optional): If True, use a service account. Defaults to False. auth_args (dict, optional): Additional authentication parameters for aa.Authenticate(). Defaults to {}. user_agent_prefix (str, optional): If set, the prefix (version-less) value used for setting the user-agent string. Defaults to "geemap". kwargs (dict, optional): Additional parameters for ee.Initialize(). For example, opt_url='https://earthengine-highvolume.googleapis.com' to use the Earth Engine High-Volume platform. Defaults to {}. """ import httplib2 from .__init__ import __version__ user_agent = f"{user_agent_prefix}/{__version__}" if "http_transport" not in kwargs: kwargs["http_transport"] = httplib2.Http() if auth_mode is None: if in_colab_shell(): from google.colab import userdata try: project_id = userdata.get("EE_PROJECT_ID") auth_mode = "colab" kwargs["project"] = project_id except Exception: auth_mode = "notebook" else: auth_mode = "notebook" auth_args["auth_mode"] = auth_mode if ee.data._credentials is None: ee_token = os.environ.get(token_name) if in_colab_shell(): from google.colab import userdata try: ee_token = userdata.get(token_name) except Exception: pass if service_account: try: credential_file_path = os.path.expanduser( "~/.config/earthengine/private-key.json" ) if os.path.exists(credential_file_path): with open(credential_file_path) as f: token_dict = json.load(f) else: token_name = "EARTHENGINE_TOKEN" ee_token = os.environ.get(token_name) token_dict = json.loads(ee_token, strict=False) service_account = token_dict["client_email"] private_key = token_dict["private_key"] credentials = ee.ServiceAccountCredentials( service_account, key_data=private_key ) ee.Initialize(credentials, **kwargs) except Exception as e: raise Exception(e) else: try: if ee_token is not None: credential_file_path = os.path.expanduser( "~/.config/earthengine/credentials" ) if not os.path.exists(credential_file_path): os.makedirs( os.path.dirname(credential_file_path), exist_ok=True ) if ee_token.startswith("{") and ee_token.endswith( "}" ): # deals with token generated by new auth method (earthengine-api>=0.1.304). token_dict = json.loads(ee_token) with open(credential_file_path, "w") as f: f.write(json.dumps(token_dict)) else: credential = ( '{"refresh_token":"%s"}' % ee_token ) # deals with token generated by old auth method. with open(credential_file_path, "w") as f: f.write(credential) ee.Initialize(**kwargs) except Exception: ee.Authenticate(**auth_args) ee.Initialize(**kwargs) ee.data.setUserAgent(user_agent) def download_ee_image( image, filename, region=None, crs=None, crs_transform=None, scale=None, resampling="near", dtype=None, overwrite=True, num_threads=None, max_tile_size=None, max_tile_dim=None, shape=None, scale_offset=False, unmask_value=None, **kwargs, ): """Download an Earth Engine Image as a GeoTIFF. Images larger than the `Earth Engine size limit are split and downloaded as separate tiles, then re-assembled into a single GeoTIFF. See https://github.com/dugalh/geedim/blob/main/geedim/download.py#L574 Args: image (ee.Image): The image to be downloaded. filename (str): Name of the destination file. region (ee.Geometry, optional): Region defined by geojson polygon in WGS84. Defaults to the entire image granule. crs (str, optional): Reproject image(s) to this EPSG or WKT CRS. Where image bands have different CRSs, all are re-projected to this CRS. Defaults to the CRS of the minimum scale band. crs_transform (list, optional): tuple of float, list of float, rio.Affine, optional List of 6 numbers specifying an affine transform in the specified CRS. In row-major order: [xScale, xShearing, xTranslation, yShearing, yScale, yTranslation]. All bands are re-projected to this transform. scale (float, optional): Resample image(s) to this pixel scale (size) (m). Where image bands have different scales, all are resampled to this scale. Defaults to the minimum scale of image bands. resampling (ResamplingMethod, optional): Resampling method, can be 'near', 'bilinear', 'bicubic', or 'average'. Defaults to None. dtype (str, optional): Convert to this data type (`uint8`, `int8`, `uint16`, `int16`, `uint32`, `int32`, `float32` or `float64`). Defaults to auto select a minimum size type that can represent the range of pixel values. overwrite (bool, optional): Overwrite the destination file if it exists. Defaults to True. num_threads (int, optional): Number of tiles to download concurrently. Defaults to a sensible auto value. max_tile_size: int, optional Maximum tile size (MB). If None, defaults to the Earth Engine download size limit (32 MB). max_tile_dim: int, optional Maximum tile width/height (pixels). If None, defaults to Earth Engine download limit (10000). shape: tuple of int, optional (height, width) dimensions to export (pixels). scale_offset: bool, optional Whether to apply any EE band scales and offsets to the image. unmask_value (float, optional): The value to use for pixels that are masked in the input image. If the exported image contains zero values, you should set the unmask value to a non-zero value so that the zero values are not treated as missing data. Defaults to None. """ if os.environ.get("USE_MKDOCS") is not None: return try: import geedim as gd except ImportError: raise ImportError( "Please install geedim using `pip install geedim` or `conda install -c conda-forge geedim`" ) if not isinstance(image, ee.Image): raise ValueError("image must be an ee.Image.") if unmask_value is not None: image = image.selfMask().unmask(unmask_value) if isinstance(region, ee.Geometry): image = image.clip(region) elif isinstance(region, ee.FeatureCollection): image = image.clipToCollection(region) if region is not None: kwargs["region"] = region if crs is not None: kwargs["crs"] = crs if crs_transform is not None: kwargs["crs_transform"] = crs_transform if scale is not None: kwargs["scale"] = scale if resampling is not None: kwargs["resampling"] = resampling if dtype is not None: kwargs["dtype"] = dtype if max_tile_size is not None: kwargs["max_tile_size"] = max_tile_size if max_tile_dim is not None: kwargs["max_tile_dim"] = max_tile_dim if shape is not None: kwargs["shape"] = shape if scale_offset: kwargs["scale_offset"] = scale_offset img = gd.download.BaseImage(image) img.download(filename, overwrite=overwrite, num_threads=num_threads, **kwargs) The provided code snippet includes necessary dependencies for implementing the `download_ee_image_tiles_parallel` function. Write a Python function `def download_ee_image_tiles_parallel( image, features, out_dir=None, prefix=None, crs=None, crs_transform=None, scale=None, resampling="near", dtype=None, overwrite=True, num_threads=None, max_tile_size=None, max_tile_dim=None, shape=None, scale_offset=False, unmask_value=None, column=None, job_args={"n_jobs": -1}, **kwargs, )` to solve the following problem: Download an Earth Engine Image as small tiles based on ee.FeatureCollection. Images larger than the `Earth Engine size limit are split and downloaded as separate tiles, then re-assembled into a single GeoTIFF. See https://github.com/dugalh/geedim/blob/main/geedim/download.py#L574 Args: image (ee.Image): The image to be downloaded. features (ee.FeatureCollection): The features to loop through to download image. out_dir (str, optional): The output directory. Defaults to None. prefix (str, optional): The prefix for the output file. Defaults to None. crs (str, optional): Reproject image(s) to this EPSG or WKT CRS. Where image bands have different CRSs, all are re-projected to this CRS. Defaults to the CRS of the minimum scale band. crs_transform (list, optional): tuple of float, list of float, rio.Affine, optional List of 6 numbers specifying an affine transform in the specified CRS. In row-major order: [xScale, xShearing, xTranslation, yShearing, yScale, yTranslation]. All bands are re-projected to this transform. scale (float, optional): Resample image(s) to this pixel scale (size) (m). Where image bands have different scales, all are resampled to this scale. Defaults to the minimum scale of image bands. resampling (ResamplingMethod, optional): Resampling method, can be 'near', 'bilinear', 'bicubic', or 'average'. Defaults to None. dtype (str, optional): Convert to this data type (`uint8`, `int8`, `uint16`, `int16`, `uint32`, `int32`, `float32` or `float64`). Defaults to auto select a minimum size type that can represent the range of pixel values. overwrite (bool, optional): Overwrite the destination file if it exists. Defaults to True. num_threads (int, optional): Number of tiles to download concurrently. Defaults to a sensible auto value. max_tile_size: int, optional Maximum tile size (MB). If None, defaults to the Earth Engine download size limit (32 MB). max_tile_dim: int, optional Maximum tile width/height (pixels). If None, defaults to Earth Engine download limit (10000). shape: tuple of int, optional (height, width) dimensions to export (pixels). scale_offset: bool, optional Whether to apply any EE band scales and offsets to the image. unmask_value (float, optional): The value to use for pixels that are masked in the input image. If the exported image contains zero values, you should set the unmask value to a non-zero value so that the zero values are not treated as missing data. Defaults to None. column (str, optional): The column name in the feature collection to use as the filename. Defaults to None. job_args (dict, optional): The arguments to pass to joblib.Parallel. Defaults to {"n_jobs": -1}. Here is the function: def download_ee_image_tiles_parallel( image, features, out_dir=None, prefix=None, crs=None, crs_transform=None, scale=None, resampling="near", dtype=None, overwrite=True, num_threads=None, max_tile_size=None, max_tile_dim=None, shape=None, scale_offset=False, unmask_value=None, column=None, job_args={"n_jobs": -1}, **kwargs, ): """Download an Earth Engine Image as small tiles based on ee.FeatureCollection. Images larger than the `Earth Engine size limit are split and downloaded as separate tiles, then re-assembled into a single GeoTIFF. See https://github.com/dugalh/geedim/blob/main/geedim/download.py#L574 Args: image (ee.Image): The image to be downloaded. features (ee.FeatureCollection): The features to loop through to download image. out_dir (str, optional): The output directory. Defaults to None. prefix (str, optional): The prefix for the output file. Defaults to None. crs (str, optional): Reproject image(s) to this EPSG or WKT CRS. Where image bands have different CRSs, all are re-projected to this CRS. Defaults to the CRS of the minimum scale band. crs_transform (list, optional): tuple of float, list of float, rio.Affine, optional List of 6 numbers specifying an affine transform in the specified CRS. In row-major order: [xScale, xShearing, xTranslation, yShearing, yScale, yTranslation]. All bands are re-projected to this transform. scale (float, optional): Resample image(s) to this pixel scale (size) (m). Where image bands have different scales, all are resampled to this scale. Defaults to the minimum scale of image bands. resampling (ResamplingMethod, optional): Resampling method, can be 'near', 'bilinear', 'bicubic', or 'average'. Defaults to None. dtype (str, optional): Convert to this data type (`uint8`, `int8`, `uint16`, `int16`, `uint32`, `int32`, `float32` or `float64`). Defaults to auto select a minimum size type that can represent the range of pixel values. overwrite (bool, optional): Overwrite the destination file if it exists. Defaults to True. num_threads (int, optional): Number of tiles to download concurrently. Defaults to a sensible auto value. max_tile_size: int, optional Maximum tile size (MB). If None, defaults to the Earth Engine download size limit (32 MB). max_tile_dim: int, optional Maximum tile width/height (pixels). If None, defaults to Earth Engine download limit (10000). shape: tuple of int, optional (height, width) dimensions to export (pixels). scale_offset: bool, optional Whether to apply any EE band scales and offsets to the image. unmask_value (float, optional): The value to use for pixels that are masked in the input image. If the exported image contains zero values, you should set the unmask value to a non-zero value so that the zero values are not treated as missing data. Defaults to None. column (str, optional): The column name in the feature collection to use as the filename. Defaults to None. job_args (dict, optional): The arguments to pass to joblib.Parallel. Defaults to {"n_jobs": -1}. """ import joblib import time start = time.time() if os.environ.get("USE_MKDOCS") is not None: return if not isinstance(features, ee.FeatureCollection): raise ValueError("features must be an ee.FeatureCollection.") if out_dir is None: out_dir = os.getcwd() if not os.path.exists(out_dir): os.makedirs(out_dir) if prefix is None: prefix = "" count = features.size().getInfo() if column is not None: names = features.aggregate_array(column).getInfo() else: names = [str(i + 1).zfill(len(str(count))) for i in range(count)] collection = features.toList(count) def download_data(index): ee_initialize(opt_url="https://earthengine-highvolume.googleapis.com") region = ee.Feature(collection.get(index)).geometry() filename = os.path.join( out_dir, "{}{}.tif".format(prefix, names[index].replace("/", "_")) ) print(f"Downloading {index + 1}/{count}: {filename}") download_ee_image( image, filename, region, crs, crs_transform, scale, resampling, dtype, overwrite, num_threads, max_tile_size, max_tile_dim, shape, scale_offset, unmask_value, **kwargs, ) with joblib.Parallel(**job_args) as parallel: parallel(joblib.delayed(download_data)(index) for index in range(count)) end = time.time() print(f"Finished in {end - start} seconds.")
Download an Earth Engine Image as small tiles based on ee.FeatureCollection. Images larger than the `Earth Engine size limit are split and downloaded as separate tiles, then re-assembled into a single GeoTIFF. See https://github.com/dugalh/geedim/blob/main/geedim/download.py#L574 Args: image (ee.Image): The image to be downloaded. features (ee.FeatureCollection): The features to loop through to download image. out_dir (str, optional): The output directory. Defaults to None. prefix (str, optional): The prefix for the output file. Defaults to None. crs (str, optional): Reproject image(s) to this EPSG or WKT CRS. Where image bands have different CRSs, all are re-projected to this CRS. Defaults to the CRS of the minimum scale band. crs_transform (list, optional): tuple of float, list of float, rio.Affine, optional List of 6 numbers specifying an affine transform in the specified CRS. In row-major order: [xScale, xShearing, xTranslation, yShearing, yScale, yTranslation]. All bands are re-projected to this transform. scale (float, optional): Resample image(s) to this pixel scale (size) (m). Where image bands have different scales, all are resampled to this scale. Defaults to the minimum scale of image bands. resampling (ResamplingMethod, optional): Resampling method, can be 'near', 'bilinear', 'bicubic', or 'average'. Defaults to None. dtype (str, optional): Convert to this data type (`uint8`, `int8`, `uint16`, `int16`, `uint32`, `int32`, `float32` or `float64`). Defaults to auto select a minimum size type that can represent the range of pixel values. overwrite (bool, optional): Overwrite the destination file if it exists. Defaults to True. num_threads (int, optional): Number of tiles to download concurrently. Defaults to a sensible auto value. max_tile_size: int, optional Maximum tile size (MB). If None, defaults to the Earth Engine download size limit (32 MB). max_tile_dim: int, optional Maximum tile width/height (pixels). If None, defaults to Earth Engine download limit (10000). shape: tuple of int, optional (height, width) dimensions to export (pixels). scale_offset: bool, optional Whether to apply any EE band scales and offsets to the image. unmask_value (float, optional): The value to use for pixels that are masked in the input image. If the exported image contains zero values, you should set the unmask value to a non-zero value so that the zero values are not treated as missing data. Defaults to None. column (str, optional): The column name in the feature collection to use as the filename. Defaults to None. job_args (dict, optional): The arguments to pass to joblib.Parallel. Defaults to {"n_jobs": -1}.
12,390
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple def download_ee_image( image, filename, region=None, crs=None, crs_transform=None, scale=None, resampling="near", dtype=None, overwrite=True, num_threads=None, max_tile_size=None, max_tile_dim=None, shape=None, scale_offset=False, unmask_value=None, **kwargs, ): """Download an Earth Engine Image as a GeoTIFF. Images larger than the `Earth Engine size limit are split and downloaded as separate tiles, then re-assembled into a single GeoTIFF. See https://github.com/dugalh/geedim/blob/main/geedim/download.py#L574 Args: image (ee.Image): The image to be downloaded. filename (str): Name of the destination file. region (ee.Geometry, optional): Region defined by geojson polygon in WGS84. Defaults to the entire image granule. crs (str, optional): Reproject image(s) to this EPSG or WKT CRS. Where image bands have different CRSs, all are re-projected to this CRS. Defaults to the CRS of the minimum scale band. crs_transform (list, optional): tuple of float, list of float, rio.Affine, optional List of 6 numbers specifying an affine transform in the specified CRS. In row-major order: [xScale, xShearing, xTranslation, yShearing, yScale, yTranslation]. All bands are re-projected to this transform. scale (float, optional): Resample image(s) to this pixel scale (size) (m). Where image bands have different scales, all are resampled to this scale. Defaults to the minimum scale of image bands. resampling (ResamplingMethod, optional): Resampling method, can be 'near', 'bilinear', 'bicubic', or 'average'. Defaults to None. dtype (str, optional): Convert to this data type (`uint8`, `int8`, `uint16`, `int16`, `uint32`, `int32`, `float32` or `float64`). Defaults to auto select a minimum size type that can represent the range of pixel values. overwrite (bool, optional): Overwrite the destination file if it exists. Defaults to True. num_threads (int, optional): Number of tiles to download concurrently. Defaults to a sensible auto value. max_tile_size: int, optional Maximum tile size (MB). If None, defaults to the Earth Engine download size limit (32 MB). max_tile_dim: int, optional Maximum tile width/height (pixels). If None, defaults to Earth Engine download limit (10000). shape: tuple of int, optional (height, width) dimensions to export (pixels). scale_offset: bool, optional Whether to apply any EE band scales and offsets to the image. unmask_value (float, optional): The value to use for pixels that are masked in the input image. If the exported image contains zero values, you should set the unmask value to a non-zero value so that the zero values are not treated as missing data. Defaults to None. """ if os.environ.get("USE_MKDOCS") is not None: return try: import geedim as gd except ImportError: raise ImportError( "Please install geedim using `pip install geedim` or `conda install -c conda-forge geedim`" ) if not isinstance(image, ee.Image): raise ValueError("image must be an ee.Image.") if unmask_value is not None: image = image.selfMask().unmask(unmask_value) if isinstance(region, ee.Geometry): image = image.clip(region) elif isinstance(region, ee.FeatureCollection): image = image.clipToCollection(region) if region is not None: kwargs["region"] = region if crs is not None: kwargs["crs"] = crs if crs_transform is not None: kwargs["crs_transform"] = crs_transform if scale is not None: kwargs["scale"] = scale if resampling is not None: kwargs["resampling"] = resampling if dtype is not None: kwargs["dtype"] = dtype if max_tile_size is not None: kwargs["max_tile_size"] = max_tile_size if max_tile_dim is not None: kwargs["max_tile_dim"] = max_tile_dim if shape is not None: kwargs["shape"] = shape if scale_offset: kwargs["scale_offset"] = scale_offset img = gd.download.BaseImage(image) img.download(filename, overwrite=overwrite, num_threads=num_threads, **kwargs) The provided code snippet includes necessary dependencies for implementing the `download_ee_image_collection` function. Write a Python function `def download_ee_image_collection( collection, out_dir=None, filenames=None, region=None, crs=None, crs_transform=None, scale=None, resampling="near", dtype=None, overwrite=True, num_threads=None, max_tile_size=None, max_tile_dim=None, shape=None, scale_offset=False, unmask_value=None, **kwargs, )` to solve the following problem: Download an Earth Engine ImageCollection as GeoTIFFs. Images larger than the `Earth Engine size limit are split and downloaded as separate tiles, then re-assembled into a single GeoTIFF. See https://github.com/dugalh/geedim/blob/main/geedim/download.py#L574 Args: collection (ee.ImageCollection): The image collection to be downloaded. out_dir (str, optional): The directory to save the downloaded images. Defaults to the current directory. filenames (list, optional): A list of filenames to use for the downloaded images. Defaults to the image ID. region (ee.Geometry, optional): Region defined by geojson polygon in WGS84. Defaults to the entire image granule. crs (str, optional): Reproject image(s) to this EPSG or WKT CRS. Where image bands have different CRSs, all are re-projected to this CRS. Defaults to the CRS of the minimum scale band. crs_transform (list, optional): tuple of float, list of float, rio.Affine, optional List of 6 numbers specifying an affine transform in the specified CRS. In row-major order: [xScale, xShearing, xTranslation, yShearing, yScale, yTranslation]. All bands are re-projected to this transform. scale (float, optional): Resample image(s) to this pixel scale (size) (m). Where image bands have different scales, all are resampled to this scale. Defaults to the minimum scale of image bands. resampling (ResamplingMethod, optional): Resampling method, can be 'near', 'bilinear', 'bicubic', or 'average'. Defaults to None. dtype (str, optional): Convert to this data type (`uint8`, `int8`, `uint16`, `int16`, `uint32`, `int32`, `float32` or `float64`). Defaults to auto select a minimum size type that can represent the range of pixel values. overwrite (bool, optional): Overwrite the destination file if it exists. Defaults to True. num_threads (int, optional): Number of tiles to download concurrently. Defaults to a sensible auto value. max_tile_size: int, optional Maximum tile size (MB). If None, defaults to the Earth Engine download size limit (32 MB). max_tile_dim: int, optional Maximum tile width/height (pixels). If None, defaults to Earth Engine download limit (10000). shape: tuple of int, optional (height, width) dimensions to export (pixels). scale_offset: bool, optional Whether to apply any EE band scales and offsets to the image. unmask_value (float, optional): The value to use for pixels that are masked in the input image. If the exported image contains zero values, you should set the unmask value to a non-zero value so that the zero values are not treated as missing data. Defaults to None. Here is the function: def download_ee_image_collection( collection, out_dir=None, filenames=None, region=None, crs=None, crs_transform=None, scale=None, resampling="near", dtype=None, overwrite=True, num_threads=None, max_tile_size=None, max_tile_dim=None, shape=None, scale_offset=False, unmask_value=None, **kwargs, ): """Download an Earth Engine ImageCollection as GeoTIFFs. Images larger than the `Earth Engine size limit are split and downloaded as separate tiles, then re-assembled into a single GeoTIFF. See https://github.com/dugalh/geedim/blob/main/geedim/download.py#L574 Args: collection (ee.ImageCollection): The image collection to be downloaded. out_dir (str, optional): The directory to save the downloaded images. Defaults to the current directory. filenames (list, optional): A list of filenames to use for the downloaded images. Defaults to the image ID. region (ee.Geometry, optional): Region defined by geojson polygon in WGS84. Defaults to the entire image granule. crs (str, optional): Reproject image(s) to this EPSG or WKT CRS. Where image bands have different CRSs, all are re-projected to this CRS. Defaults to the CRS of the minimum scale band. crs_transform (list, optional): tuple of float, list of float, rio.Affine, optional List of 6 numbers specifying an affine transform in the specified CRS. In row-major order: [xScale, xShearing, xTranslation, yShearing, yScale, yTranslation]. All bands are re-projected to this transform. scale (float, optional): Resample image(s) to this pixel scale (size) (m). Where image bands have different scales, all are resampled to this scale. Defaults to the minimum scale of image bands. resampling (ResamplingMethod, optional): Resampling method, can be 'near', 'bilinear', 'bicubic', or 'average'. Defaults to None. dtype (str, optional): Convert to this data type (`uint8`, `int8`, `uint16`, `int16`, `uint32`, `int32`, `float32` or `float64`). Defaults to auto select a minimum size type that can represent the range of pixel values. overwrite (bool, optional): Overwrite the destination file if it exists. Defaults to True. num_threads (int, optional): Number of tiles to download concurrently. Defaults to a sensible auto value. max_tile_size: int, optional Maximum tile size (MB). If None, defaults to the Earth Engine download size limit (32 MB). max_tile_dim: int, optional Maximum tile width/height (pixels). If None, defaults to Earth Engine download limit (10000). shape: tuple of int, optional (height, width) dimensions to export (pixels). scale_offset: bool, optional Whether to apply any EE band scales and offsets to the image. unmask_value (float, optional): The value to use for pixels that are masked in the input image. If the exported image contains zero values, you should set the unmask value to a non-zero value so that the zero values are not treated as missing data. Defaults to None. """ if not isinstance(collection, ee.ImageCollection): raise ValueError("ee_object must be an ee.ImageCollection.") if out_dir is None: out_dir = os.getcwd() if not os.path.exists(out_dir): os.makedirs(out_dir) try: count = int(collection.size().getInfo()) print(f"Total number of images: {count}\n") if filenames is not None: if len(filenames) != count: raise ValueError( f"The number of filenames must match the number of image: {count}" ) for i in range(0, count): image = ee.Image(collection.toList(count).get(i)) if filenames is not None: name = filenames[i] if not name.endswith(".tif"): name = name + ".tif" else: name = image.get("system:index").getInfo() + ".tif" filename = os.path.join(os.path.abspath(out_dir), name) print(f"Downloading {i + 1}/{count}: {name}") download_ee_image( image, filename, region, crs, crs_transform, scale, resampling, dtype, overwrite, num_threads, max_tile_size, max_tile_dim, shape, scale_offset, unmask_value, **kwargs, ) except Exception as e: raise Exception(f"Error downloading image collection: {e}")
Download an Earth Engine ImageCollection as GeoTIFFs. Images larger than the `Earth Engine size limit are split and downloaded as separate tiles, then re-assembled into a single GeoTIFF. See https://github.com/dugalh/geedim/blob/main/geedim/download.py#L574 Args: collection (ee.ImageCollection): The image collection to be downloaded. out_dir (str, optional): The directory to save the downloaded images. Defaults to the current directory. filenames (list, optional): A list of filenames to use for the downloaded images. Defaults to the image ID. region (ee.Geometry, optional): Region defined by geojson polygon in WGS84. Defaults to the entire image granule. crs (str, optional): Reproject image(s) to this EPSG or WKT CRS. Where image bands have different CRSs, all are re-projected to this CRS. Defaults to the CRS of the minimum scale band. crs_transform (list, optional): tuple of float, list of float, rio.Affine, optional List of 6 numbers specifying an affine transform in the specified CRS. In row-major order: [xScale, xShearing, xTranslation, yShearing, yScale, yTranslation]. All bands are re-projected to this transform. scale (float, optional): Resample image(s) to this pixel scale (size) (m). Where image bands have different scales, all are resampled to this scale. Defaults to the minimum scale of image bands. resampling (ResamplingMethod, optional): Resampling method, can be 'near', 'bilinear', 'bicubic', or 'average'. Defaults to None. dtype (str, optional): Convert to this data type (`uint8`, `int8`, `uint16`, `int16`, `uint32`, `int32`, `float32` or `float64`). Defaults to auto select a minimum size type that can represent the range of pixel values. overwrite (bool, optional): Overwrite the destination file if it exists. Defaults to True. num_threads (int, optional): Number of tiles to download concurrently. Defaults to a sensible auto value. max_tile_size: int, optional Maximum tile size (MB). If None, defaults to the Earth Engine download size limit (32 MB). max_tile_dim: int, optional Maximum tile width/height (pixels). If None, defaults to Earth Engine download limit (10000). shape: tuple of int, optional (height, width) dimensions to export (pixels). scale_offset: bool, optional Whether to apply any EE band scales and offsets to the image. unmask_value (float, optional): The value to use for pixels that are masked in the input image. If the exported image contains zero values, you should set the unmask value to a non-zero value so that the zero values are not treated as missing data. Defaults to None.
12,391
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple The provided code snippet includes necessary dependencies for implementing the `get_palette_colors` function. Write a Python function `def get_palette_colors(cmap_name=None, n_class=None, hashtag=False)` to solve the following problem: Get a palette from a matplotlib colormap. See the list of colormaps at https://matplotlib.org/stable/tutorials/colors/colormaps.html. Args: cmap_name (str, optional): The name of the matplotlib colormap. Defaults to None. n_class (int, optional): The number of colors. Defaults to None. hashtag (bool, optional): Whether to return a list of hex colors. Defaults to False. Returns: list: A list of hex colors. Here is the function: def get_palette_colors(cmap_name=None, n_class=None, hashtag=False): """Get a palette from a matplotlib colormap. See the list of colormaps at https://matplotlib.org/stable/tutorials/colors/colormaps.html. Args: cmap_name (str, optional): The name of the matplotlib colormap. Defaults to None. n_class (int, optional): The number of colors. Defaults to None. hashtag (bool, optional): Whether to return a list of hex colors. Defaults to False. Returns: list: A list of hex colors. """ import matplotlib as mpl import matplotlib.pyplot as plt cmap = plt.cm.get_cmap(cmap_name, n_class) colors = [mpl.colors.rgb2hex(cmap(i))[1:] for i in range(cmap.N)] if hashtag: colors = ["#" + i for i in colors] return colors
Get a palette from a matplotlib colormap. See the list of colormaps at https://matplotlib.org/stable/tutorials/colors/colormaps.html. Args: cmap_name (str, optional): The name of the matplotlib colormap. Defaults to None. n_class (int, optional): The number of colors. Defaults to None. hashtag (bool, optional): Whether to return a list of hex colors. Defaults to False. Returns: list: A list of hex colors.
12,392
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple def in_colab_shell(): """Tests if the code is being executed within Google Colab.""" import sys if "google.colab" in sys.modules: return True else: return False def reproject(image, output, dst_crs="EPSG:4326", resampling="nearest", **kwargs): """Reprojects an image. Args: image (str): The input image filepath. output (str): The output image filepath. dst_crs (str, optional): The destination CRS. Defaults to "EPSG:4326". resampling (Resampling, optional): The resampling method. Defaults to "nearest". **kwargs: Additional keyword arguments to pass to rasterio.open. """ import rasterio as rio from rasterio.warp import calculate_default_transform, reproject, Resampling if isinstance(resampling, str): resampling = getattr(Resampling, resampling) image = os.path.abspath(image) output = os.path.abspath(output) if not os.path.exists(os.path.dirname(output)): os.makedirs(os.path.dirname(output)) with rio.open(image, **kwargs) as src: transform, width, height = calculate_default_transform( src.crs, dst_crs, src.width, src.height, *src.bounds ) kwargs = src.meta.copy() kwargs.update( { "crs": dst_crs, "transform": transform, "width": width, "height": height, } ) with rio.open(output, "w", **kwargs) as dst: for i in range(1, src.count + 1): reproject( source=rio.band(src, i), destination=rio.band(dst, i), src_transform=src.transform, src_crs=src.crs, dst_transform=transform, dst_crs=dst_crs, resampling=resampling, **kwargs, ) The provided code snippet includes necessary dependencies for implementing the `plot_raster` function. Write a Python function `def plot_raster( image, band=None, cmap="terrain", proj="EPSG:3857", figsize=None, open_kwargs={}, **kwargs, )` to solve the following problem: Plot a raster image. Args: image (str | xarray.DataArray ): The input raster image, can be a file path, HTTP URL, or xarray.DataArray. band (int, optional): The band index, starting from zero. Defaults to None. cmap (str, optional): The matplotlib colormap to use. Defaults to "terrain". proj (str, optional): The EPSG projection code. Defaults to "EPSG:3857". figsize (tuple, optional): The figure size as a tuple, such as (10, 8). Defaults to None. open_kwargs (dict, optional): The keyword arguments to pass to rioxarray.open_rasterio. Defaults to {}. **kwargs: Additional keyword arguments to pass to xarray.DataArray.plot(). Here is the function: def plot_raster( image, band=None, cmap="terrain", proj="EPSG:3857", figsize=None, open_kwargs={}, **kwargs, ): """Plot a raster image. Args: image (str | xarray.DataArray ): The input raster image, can be a file path, HTTP URL, or xarray.DataArray. band (int, optional): The band index, starting from zero. Defaults to None. cmap (str, optional): The matplotlib colormap to use. Defaults to "terrain". proj (str, optional): The EPSG projection code. Defaults to "EPSG:3857". figsize (tuple, optional): The figure size as a tuple, such as (10, 8). Defaults to None. open_kwargs (dict, optional): The keyword arguments to pass to rioxarray.open_rasterio. Defaults to {}. **kwargs: Additional keyword arguments to pass to xarray.DataArray.plot(). """ if os.environ.get("USE_MKDOCS") is not None: return if in_colab_shell(): print("The plot_raster() function is not supported in Colab.") return try: import pvxarray import rioxarray import xarray except ImportError: raise ImportError( "pyxarray and rioxarray are required for plotting. Please install them using 'pip install rioxarray pyvista-xarray'." ) if isinstance(image, str): da = rioxarray.open_rasterio(image, **open_kwargs) elif isinstance(image, xarray.DataArray): da = image else: raise ValueError("image must be a string or xarray.Dataset.") if band is not None: da = da[dict(band=band)] da = da.rio.reproject(proj) kwargs["cmap"] = cmap kwargs["figsize"] = figsize da.plot(**kwargs)
Plot a raster image. Args: image (str | xarray.DataArray ): The input raster image, can be a file path, HTTP URL, or xarray.DataArray. band (int, optional): The band index, starting from zero. Defaults to None. cmap (str, optional): The matplotlib colormap to use. Defaults to "terrain". proj (str, optional): The EPSG projection code. Defaults to "EPSG:3857". figsize (tuple, optional): The figure size as a tuple, such as (10, 8). Defaults to None. open_kwargs (dict, optional): The keyword arguments to pass to rioxarray.open_rasterio. Defaults to {}. **kwargs: Additional keyword arguments to pass to xarray.DataArray.plot().
12,393
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple def in_colab_shell(): """Tests if the code is being executed within Google Colab.""" import sys if "google.colab" in sys.modules: return True else: return False def reproject(image, output, dst_crs="EPSG:4326", resampling="nearest", **kwargs): """Reprojects an image. Args: image (str): The input image filepath. output (str): The output image filepath. dst_crs (str, optional): The destination CRS. Defaults to "EPSG:4326". resampling (Resampling, optional): The resampling method. Defaults to "nearest". **kwargs: Additional keyword arguments to pass to rasterio.open. """ import rasterio as rio from rasterio.warp import calculate_default_transform, reproject, Resampling if isinstance(resampling, str): resampling = getattr(Resampling, resampling) image = os.path.abspath(image) output = os.path.abspath(output) if not os.path.exists(os.path.dirname(output)): os.makedirs(os.path.dirname(output)) with rio.open(image, **kwargs) as src: transform, width, height = calculate_default_transform( src.crs, dst_crs, src.width, src.height, *src.bounds ) kwargs = src.meta.copy() kwargs.update( { "crs": dst_crs, "transform": transform, "width": width, "height": height, } ) with rio.open(output, "w", **kwargs) as dst: for i in range(1, src.count + 1): reproject( source=rio.band(src, i), destination=rio.band(dst, i), src_transform=src.transform, src_crs=src.crs, dst_transform=transform, dst_crs=dst_crs, resampling=resampling, **kwargs, ) The provided code snippet includes necessary dependencies for implementing the `plot_raster_3d` function. Write a Python function `def plot_raster_3d( image, band=None, cmap="terrain", factor=1.0, proj="EPSG:3857", background=None, x=None, y=None, z=None, order=None, component=None, open_kwargs={}, mesh_kwargs={}, **kwargs, )` to solve the following problem: Plot a raster image in 3D. Args: image (str | xarray.DataArray): The input raster image, can be a file path, HTTP URL, or xarray.DataArray. band (int, optional): The band index, starting from zero. Defaults to None. cmap (str, optional): The matplotlib colormap to use. Defaults to "terrain". factor (float, optional): The scaling factor for the raster. Defaults to 1.0. proj (str, optional): The EPSG projection code. Defaults to "EPSG:3857". background (str, optional): The background color. Defaults to None. x (str, optional): The x coordinate. Defaults to None. y (str, optional): The y coordinate. Defaults to None. z (str, optional): The z coordinate. Defaults to None. order (str, optional): The order of the coordinates. Defaults to None. component (str, optional): The component of the coordinates. Defaults to None. open_kwargs (dict, optional): The keyword arguments to pass to rioxarray.open_rasterio. Defaults to {}. mesh_kwargs (dict, optional): The keyword arguments to pass to pyvista.mesh.warp_by_scalar(). Defaults to {}. **kwargs: Additional keyword arguments to pass to xarray.DataArray.plot(). Here is the function: def plot_raster_3d( image, band=None, cmap="terrain", factor=1.0, proj="EPSG:3857", background=None, x=None, y=None, z=None, order=None, component=None, open_kwargs={}, mesh_kwargs={}, **kwargs, ): """Plot a raster image in 3D. Args: image (str | xarray.DataArray): The input raster image, can be a file path, HTTP URL, or xarray.DataArray. band (int, optional): The band index, starting from zero. Defaults to None. cmap (str, optional): The matplotlib colormap to use. Defaults to "terrain". factor (float, optional): The scaling factor for the raster. Defaults to 1.0. proj (str, optional): The EPSG projection code. Defaults to "EPSG:3857". background (str, optional): The background color. Defaults to None. x (str, optional): The x coordinate. Defaults to None. y (str, optional): The y coordinate. Defaults to None. z (str, optional): The z coordinate. Defaults to None. order (str, optional): The order of the coordinates. Defaults to None. component (str, optional): The component of the coordinates. Defaults to None. open_kwargs (dict, optional): The keyword arguments to pass to rioxarray.open_rasterio. Defaults to {}. mesh_kwargs (dict, optional): The keyword arguments to pass to pyvista.mesh.warp_by_scalar(). Defaults to {}. **kwargs: Additional keyword arguments to pass to xarray.DataArray.plot(). """ if os.environ.get("USE_MKDOCS") is not None: return if in_colab_shell(): print("The plot_raster_3d() function is not supported in Colab.") return try: import pvxarray import pyvista import rioxarray import xarray except ImportError: raise ImportError( "pyxarray and rioxarray are required for plotting. Please install them using 'pip install rioxarray pyvista-xarray'." ) if isinstance(background, str): pyvista.global_theme.background = background if isinstance(image, str): da = rioxarray.open_rasterio(image, **open_kwargs) elif isinstance(image, xarray.DataArray): da = image else: raise ValueError("image must be a string or xarray.Dataset.") if band is not None: da = da[dict(band=band)] da = da.rio.reproject(proj) mesh_kwargs["factor"] = factor kwargs["cmap"] = cmap coords = list(da.coords) if x is None: if "x" in coords: x = "x" elif "lon" in coords: x = "lon" if y is None: if "y" in coords: y = "y" elif "lat" in coords: y = "lat" if z is None: if "z" in coords: z = "z" elif "elevation" in coords: z = "elevation" elif "band" in coords: z = "band" # Grab the mesh object for use with PyVista mesh = da.pyvista.mesh(x=x, y=y, z=z, order=order, component=component) # Warp top and plot in 3D mesh.warp_by_scalar(**mesh_kwargs).plot(**kwargs)
Plot a raster image in 3D. Args: image (str | xarray.DataArray): The input raster image, can be a file path, HTTP URL, or xarray.DataArray. band (int, optional): The band index, starting from zero. Defaults to None. cmap (str, optional): The matplotlib colormap to use. Defaults to "terrain". factor (float, optional): The scaling factor for the raster. Defaults to 1.0. proj (str, optional): The EPSG projection code. Defaults to "EPSG:3857". background (str, optional): The background color. Defaults to None. x (str, optional): The x coordinate. Defaults to None. y (str, optional): The y coordinate. Defaults to None. z (str, optional): The z coordinate. Defaults to None. order (str, optional): The order of the coordinates. Defaults to None. component (str, optional): The component of the coordinates. Defaults to None. open_kwargs (dict, optional): The keyword arguments to pass to rioxarray.open_rasterio. Defaults to {}. mesh_kwargs (dict, optional): The keyword arguments to pass to pyvista.mesh.warp_by_scalar(). Defaults to {}. **kwargs: Additional keyword arguments to pass to xarray.DataArray.plot().
12,394
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple The provided code snippet includes necessary dependencies for implementing the `display_html` function. Write a Python function `def display_html(src, width=950, height=600)` to solve the following problem: Display an HTML file in a Jupyter Notebook. Args src (str): File path to HTML file. width (int, optional): Width of the map. Defaults to 950. height (int, optional): Height of the map. Defaults to 600. Here is the function: def display_html(src, width=950, height=600): """Display an HTML file in a Jupyter Notebook. Args src (str): File path to HTML file. width (int, optional): Width of the map. Defaults to 950. height (int, optional): Height of the map. Defaults to 600. """ if not os.path.isfile(src): raise ValueError(f"{src} is not a valid file path.") display(IFrame(src=src, width=width, height=height))
Display an HTML file in a Jupyter Notebook. Args src (str): File path to HTML file. width (int, optional): Width of the map. Defaults to 950. height (int, optional): Height of the map. Defaults to 600.
12,395
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple The provided code snippet includes necessary dependencies for implementing the `bbox_coords` function. Write a Python function `def bbox_coords(geometry, decimals=4)` to solve the following problem: Get the bounding box coordinates of a geometry. Args: geometry (ee.Geometry | ee.FeatureCollection): The input geometry. decimals (int, optional): The number of decimals to round to. Defaults to 4. Returns: list: The bounding box coordinates in the form [west, south, east, north]. Here is the function: def bbox_coords(geometry, decimals=4): """Get the bounding box coordinates of a geometry. Args: geometry (ee.Geometry | ee.FeatureCollection): The input geometry. decimals (int, optional): The number of decimals to round to. Defaults to 4. Returns: list: The bounding box coordinates in the form [west, south, east, north]. """ if isinstance(geometry, ee.FeatureCollection): geometry = geometry.geometry() if geometry is not None: if not isinstance(geometry, ee.Geometry): raise ValueError("geometry must be an ee.Geometry.") coords = geometry.bounds().coordinates().getInfo()[0] x = [p[0] for p in coords] y = [p[1] for p in coords] west = round(min(x), decimals) east = round(max(x), decimals) south = round(min(y), decimals) north = round(max(y), decimals) return [west, south, east, north] else: return None
Get the bounding box coordinates of a geometry. Args: geometry (ee.Geometry | ee.FeatureCollection): The input geometry. decimals (int, optional): The number of decimals to round to. Defaults to 4. Returns: list: The bounding box coordinates in the form [west, south, east, north].
12,396
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple def ee_initialize( token_name="EARTHENGINE_TOKEN", auth_mode=None, service_account=False, auth_args={}, user_agent_prefix="geemap", **kwargs, ): """Authenticates Earth Engine and initialize an Earth Engine session Args: token_name (str, optional): The name of the Earth Engine token. Defaults to "EARTHENGINE_TOKEN". In Colab, you can also set a secret named "EE_PROJECT_ID" to initialize Earth Engine. auth_mode (str, optional): The authentication mode, can be one of colab, notebook, localhost, or gcloud. See https://developers.google.com/earth-engine/guides/auth for more details. Defaults to None. service_account (bool, optional): If True, use a service account. Defaults to False. auth_args (dict, optional): Additional authentication parameters for aa.Authenticate(). Defaults to {}. user_agent_prefix (str, optional): If set, the prefix (version-less) value used for setting the user-agent string. Defaults to "geemap". kwargs (dict, optional): Additional parameters for ee.Initialize(). For example, opt_url='https://earthengine-highvolume.googleapis.com' to use the Earth Engine High-Volume platform. Defaults to {}. """ import httplib2 from .__init__ import __version__ user_agent = f"{user_agent_prefix}/{__version__}" if "http_transport" not in kwargs: kwargs["http_transport"] = httplib2.Http() if auth_mode is None: if in_colab_shell(): from google.colab import userdata try: project_id = userdata.get("EE_PROJECT_ID") auth_mode = "colab" kwargs["project"] = project_id except Exception: auth_mode = "notebook" else: auth_mode = "notebook" auth_args["auth_mode"] = auth_mode if ee.data._credentials is None: ee_token = os.environ.get(token_name) if in_colab_shell(): from google.colab import userdata try: ee_token = userdata.get(token_name) except Exception: pass if service_account: try: credential_file_path = os.path.expanduser( "~/.config/earthengine/private-key.json" ) if os.path.exists(credential_file_path): with open(credential_file_path) as f: token_dict = json.load(f) else: token_name = "EARTHENGINE_TOKEN" ee_token = os.environ.get(token_name) token_dict = json.loads(ee_token, strict=False) service_account = token_dict["client_email"] private_key = token_dict["private_key"] credentials = ee.ServiceAccountCredentials( service_account, key_data=private_key ) ee.Initialize(credentials, **kwargs) except Exception as e: raise Exception(e) else: try: if ee_token is not None: credential_file_path = os.path.expanduser( "~/.config/earthengine/credentials" ) if not os.path.exists(credential_file_path): os.makedirs( os.path.dirname(credential_file_path), exist_ok=True ) if ee_token.startswith("{") and ee_token.endswith( "}" ): # deals with token generated by new auth method (earthengine-api>=0.1.304). token_dict = json.loads(ee_token) with open(credential_file_path, "w") as f: f.write(json.dumps(token_dict)) else: credential = ( '{"refresh_token":"%s"}' % ee_token ) # deals with token generated by old auth method. with open(credential_file_path, "w") as f: f.write(credential) ee.Initialize(**kwargs) except Exception: ee.Authenticate(**auth_args) ee.Initialize(**kwargs) ee.data.setUserAgent(user_agent) def change_require(lib_path): if not isinstance(lib_path, str): raise ValueError("lib_path must be a string.") if lib_path.startswith("http"): if lib_path.startswith("https://github.com") and "blob" in lib_path: lib_path = lib_path.replace("blob", "raw") basename = os.path.basename(lib_path) r = requests.get(lib_path, allow_redirects=True) open(basename, "wb").write(r.content) lib_path = basename elif ( lib_path.startswith("user") or lib_path.startswith("projects") ) and ":" in lib_path: repo = f'https://earthengine.googlesource.com/{lib_path.split(":")[0]}' start_index = lib_path.index("/", lib_path.index("/") + 1) + 1 lib_path = lib_path[start_index:].replace(":", "/") if not os.path.exists(lib_path): cmd = f"git clone {repo}" os.system(cmd) if not os.path.exists(lib_path): raise ValueError(f"{lib_path} does not exist.") output = [] with open(lib_path, "r") as f: lines = f.readlines() for line in lines: if "require(" in line and ":" in line and (not line.strip().startswith("//")): new_line = "// " + line output.append(new_line) if "users/" in line: start_index = line.index("users/") end_index = line.index("/", start_index + 6) elif "projects" in line: start_index = line.index("projects/") end_index = line.index("/", start_index + 9) header = line[start_index:end_index] new_line = line.replace(header, os.getcwd()).replace(":", "/") output.append(new_line) else: output.append(line) with open(lib_path, "w") as f: f.writelines(output) return lib_path def get_direct_url(url): """Get the direct URL for a given URL. Args: url (str): The URL to get the direct URL for. Returns: str: The direct URL. """ if not isinstance(url, str): raise ValueError("url must be a string.") if not url.startswith("http"): raise ValueError("url must start with http.") r = requests.head(url, allow_redirects=True) return r.url The provided code snippet includes necessary dependencies for implementing the `requireJS` function. Write a Python function `def requireJS(lib_path=None, Map=None)` to solve the following problem: Import Earth Engine JavaScript libraries. Based on the Open Earth Engine Library (OEEL). For more info, visit https://www.open-geocomputing.org/OpenEarthEngineLibrary. Args: lib_path (str, optional): A local file path or HTTP URL to a JavaScript library. It can also be in a format like 'users/gena/packages:grid'. Defaults to None. Map (geemap.Map, optional): An geemap.Map object. Defaults to None. Returns: object: oeel object. Here is the function: def requireJS(lib_path=None, Map=None): """Import Earth Engine JavaScript libraries. Based on the Open Earth Engine Library (OEEL). For more info, visit https://www.open-geocomputing.org/OpenEarthEngineLibrary. Args: lib_path (str, optional): A local file path or HTTP URL to a JavaScript library. It can also be in a format like 'users/gena/packages:grid'. Defaults to None. Map (geemap.Map, optional): An geemap.Map object. Defaults to None. Returns: object: oeel object. """ try: from oeel import oeel except ImportError: raise ImportError( "oeel is required for requireJS. Please install it using 'pip install oeel'." ) ee_initialize() if lib_path is None: if Map is not None: oeel.setMap(Map) return oeel elif isinstance(lib_path, str): if lib_path.startswith("http"): lib_path = get_direct_url(lib_path) lib_path = change_require(lib_path) if Map is not None: oeel.setMap(Map) return oeel.requireJS(lib_path) else: raise ValueError("lib_path must be a string.")
Import Earth Engine JavaScript libraries. Based on the Open Earth Engine Library (OEEL). For more info, visit https://www.open-geocomputing.org/OpenEarthEngineLibrary. Args: lib_path (str, optional): A local file path or HTTP URL to a JavaScript library. It can also be in a format like 'users/gena/packages:grid'. Defaults to None. Map (geemap.Map, optional): An geemap.Map object. Defaults to None. Returns: object: oeel object.
12,397
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple The provided code snippet includes necessary dependencies for implementing the `setupJS` function. Write a Python function `def setupJS()` to solve the following problem: Install npm packages for Earth Engine JavaScript libraries. Based on the Open Earth Engine Library (OEEL). Here is the function: def setupJS(): """Install npm packages for Earth Engine JavaScript libraries. Based on the Open Earth Engine Library (OEEL).""" try: os.system("npm install @google/earthengine") os.system("npm install zeromq@6.0.0-beta.6") os.system("npm install request") except Exception as e: raise Exception( f"Error installing npm packages: {e}. Make sure that you have installed nodejs. See https://nodejs.org/" )
Install npm packages for Earth Engine JavaScript libraries. Based on the Open Earth Engine Library (OEEL).
12,398
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple The provided code snippet includes necessary dependencies for implementing the `ee_vector_style` function. Write a Python function `def ee_vector_style( collection, column, labels=None, color="black", pointSize=3, pointShape="circle", width=2, fillColor=None, lineType="solid", neighborhood=5, return_fc=False, )` to solve the following problem: Create a vector style for a feature collection. Args: collection (ee.FeatureCollection): The input feature collection. column (str): The name of the column to use for styling. labels (list, optional): A list of labels to use for styling. Defaults to None. color (str | list, optional): A default color (CSS 3.0 color value e.g. 'FF0000' or 'red') to use for drawing the features. Supports opacity (e.g.: 'FF000088' for 50% transparent red). Defaults to "black". pointSize (int | list, optional): The default size in pixels of the point markers. Defaults to 3. pointShape (str | list, optional): The default shape of the marker to draw at each point location. One of: circle, square, diamond, cross, plus, pentagram, hexagram, triangle, triangle_up, triangle_down, triangle_left, triangle_right, pentagon, hexagon, star5, star6. This argument also supports the following Matlab marker abbreviations: o, s, d, x, +, p, h, ^, v, <, >. Defaults to "circle". width (int | list, optional): The default line width for lines and outlines for polygons and point shapes. Defaults to 2. fillColor (str | list, optional): The color for filling polygons and point shapes. Defaults to 'color' at 0.66 opacity. Defaults to None. lineType (str | list, optional): The default line style for lines and outlines of polygons and point shapes. Defaults to 'solid'. One of: solid, dotted, dashed. Defaults to "solid". neighborhood (int, optional): If styleProperty is used and any feature has a pointSize or width larger than the defaults, tiling artifacts can occur. Specifies the maximum neighborhood (pointSize + width) needed for any feature. Defaults to 5. return_fc (bool, optional): If True, return an ee.FeatureCollection with a style property. Otherwise, return a styled ee.Image. Defaults to False. Returns: ee.FeatureCollection | ee.Image: The styled Earth Engine FeatureCollection or Image. Here is the function: def ee_vector_style( collection, column, labels=None, color="black", pointSize=3, pointShape="circle", width=2, fillColor=None, lineType="solid", neighborhood=5, return_fc=False, ): """Create a vector style for a feature collection. Args: collection (ee.FeatureCollection): The input feature collection. column (str): The name of the column to use for styling. labels (list, optional): A list of labels to use for styling. Defaults to None. color (str | list, optional): A default color (CSS 3.0 color value e.g. 'FF0000' or 'red') to use for drawing the features. Supports opacity (e.g.: 'FF000088' for 50% transparent red). Defaults to "black". pointSize (int | list, optional): The default size in pixels of the point markers. Defaults to 3. pointShape (str | list, optional): The default shape of the marker to draw at each point location. One of: circle, square, diamond, cross, plus, pentagram, hexagram, triangle, triangle_up, triangle_down, triangle_left, triangle_right, pentagon, hexagon, star5, star6. This argument also supports the following Matlab marker abbreviations: o, s, d, x, +, p, h, ^, v, <, >. Defaults to "circle". width (int | list, optional): The default line width for lines and outlines for polygons and point shapes. Defaults to 2. fillColor (str | list, optional): The color for filling polygons and point shapes. Defaults to 'color' at 0.66 opacity. Defaults to None. lineType (str | list, optional): The default line style for lines and outlines of polygons and point shapes. Defaults to 'solid'. One of: solid, dotted, dashed. Defaults to "solid". neighborhood (int, optional): If styleProperty is used and any feature has a pointSize or width larger than the defaults, tiling artifacts can occur. Specifies the maximum neighborhood (pointSize + width) needed for any feature. Defaults to 5. return_fc (bool, optional): If True, return an ee.FeatureCollection with a style property. Otherwise, return a styled ee.Image. Defaults to False. Returns: ee.FeatureCollection | ee.Image: The styled Earth Engine FeatureCollection or Image. """ if not isinstance(collection, ee.FeatureCollection): raise ValueError("collection must be an ee.FeatureCollection.") if not isinstance(column, str): raise ValueError("column must be a string.") prop_names = ee.Feature(collection.first()).propertyNames().getInfo() if column not in prop_names: raise ValueError( f"{column} is not a property name of the collection. It must be one of {','.join(prop_names)}." ) if labels is None: labels = collection.aggregate_array(column).distinct().sort().getInfo() elif isinstance(labels, list): collection = collection.filter(ee.Filter.inList(column, labels)) elif not isinstance(labels, list): raise ValueError("labels must be a list.") size = len(labels) if isinstance(color, str): color = [color] * size elif size != len(color): raise ValueError("labels and color must be the same length.") elif not isinstance(color, list): raise ValueError("color must be a string or a list.") if isinstance(pointSize, int): pointSize = [pointSize] * size elif not isinstance(pointSize, list): raise ValueError("pointSize must be an integer or a list.") if isinstance(pointShape, str): pointShape = [pointShape] * size elif not isinstance(pointShape, list): raise ValueError("pointShape must be a string or a list.") if isinstance(width, int): width = [width] * size elif not isinstance(width, list): raise ValueError("width must be an integer or a list.") if fillColor is None: fillColor = color elif isinstance(fillColor, str): fillColor = [fillColor] * size elif not isinstance(fillColor, list): raise ValueError("fillColor must be a list.") if not isinstance(neighborhood, int): raise ValueError("neighborhood must be an integer.") if isinstance(lineType, str): lineType = [lineType] * size elif not isinstance(lineType, list): raise ValueError("lineType must be a string or list.") style_dict = {} for i, label in enumerate(labels): style_dict[label] = { "color": color[i], "pointSize": pointSize[i], "pointShape": pointShape[i], "width": width[i], "fillColor": fillColor[i], "lineType": lineType[i], } style = ee.Dictionary(style_dict) result = collection.map(lambda f: f.set("style", style.get(f.get(column)))) if return_fc: return result else: return result.style(**{"styleProperty": "style", "neighborhood": neighborhood})
Create a vector style for a feature collection. Args: collection (ee.FeatureCollection): The input feature collection. column (str): The name of the column to use for styling. labels (list, optional): A list of labels to use for styling. Defaults to None. color (str | list, optional): A default color (CSS 3.0 color value e.g. 'FF0000' or 'red') to use for drawing the features. Supports opacity (e.g.: 'FF000088' for 50% transparent red). Defaults to "black". pointSize (int | list, optional): The default size in pixels of the point markers. Defaults to 3. pointShape (str | list, optional): The default shape of the marker to draw at each point location. One of: circle, square, diamond, cross, plus, pentagram, hexagram, triangle, triangle_up, triangle_down, triangle_left, triangle_right, pentagon, hexagon, star5, star6. This argument also supports the following Matlab marker abbreviations: o, s, d, x, +, p, h, ^, v, <, >. Defaults to "circle". width (int | list, optional): The default line width for lines and outlines for polygons and point shapes. Defaults to 2. fillColor (str | list, optional): The color for filling polygons and point shapes. Defaults to 'color' at 0.66 opacity. Defaults to None. lineType (str | list, optional): The default line style for lines and outlines of polygons and point shapes. Defaults to 'solid'. One of: solid, dotted, dashed. Defaults to "solid". neighborhood (int, optional): If styleProperty is used and any feature has a pointSize or width larger than the defaults, tiling artifacts can occur. Specifies the maximum neighborhood (pointSize + width) needed for any feature. Defaults to 5. return_fc (bool, optional): If True, return an ee.FeatureCollection with a style property. Otherwise, return a styled ee.Image. Defaults to False. Returns: ee.FeatureCollection | ee.Image: The styled Earth Engine FeatureCollection or Image.
12,399
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple The provided code snippet includes necessary dependencies for implementing the `add_crs` function. Write a Python function `def add_crs(filename, epsg)` to solve the following problem: Add a CRS to a raster dataset. Args: filename (str): The filename of the raster dataset. epsg (int | str): The EPSG code of the CRS. Here is the function: def add_crs(filename, epsg): """Add a CRS to a raster dataset. Args: filename (str): The filename of the raster dataset. epsg (int | str): The EPSG code of the CRS. """ try: import rasterio except ImportError: raise ImportError( "rasterio is required for adding a CRS to a raster. Please install it using 'pip install rasterio'." ) if not os.path.exists(filename): raise ValueError("filename must exist.") if isinstance(epsg, int): epsg = f"EPSG:{epsg}" elif isinstance(epsg, str): epsg = "EPSG:" + epsg else: raise ValueError("epsg must be an integer or string.") crs = rasterio.crs.CRS({"init": epsg}) with rasterio.open(filename, mode="r+") as src: src.crs = crs
Add a CRS to a raster dataset. Args: filename (str): The filename of the raster dataset. epsg (int | str): The EPSG code of the CRS.
12,400
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple The provided code snippet includes necessary dependencies for implementing the `jrc_hist_monthly_history` function. Write a Python function `def jrc_hist_monthly_history( collection=None, region=None, start_date="1984-03-16", end_date=None, start_month=1, end_month=12, scale=None, frequency="year", reducer="mean", denominator=1e4, x_label=None, y_label=None, title=None, width=None, height=None, layout_args={}, return_df=False, **kwargs, )` to solve the following problem: Create a JRC monthly history plot. Args: collection (ee.ImageCollection, optional): The image collection of JRC surface water monthly history. Default to ee.ImageCollection('JRC/GSW1_4/MonthlyHistory') region (ee.Geometry | ee.FeatureCollection, optional): The region to plot. Default to None. start_date (str, optional): The start date of the plot. Default to '1984-03-16'. end_date (str, optional): The end date of the plot. Default to the current date. start_month (int, optional): The start month of the plot. Default to 1. end_month (int, optional): The end month of the plot. Default to 12. scale (float, optional): The scale to compute the statistics. Default to None. frequency (str, optional): The frequency of the plot. Can be either 'year' or 'month', Default to 'year'. reducer (str, optional): The reducer to compute the statistics. Can be either 'mean', 'min', 'max', 'median', etc. Default to 'mean'. denominator (int, optional): The denominator to convert area from square meters to other units. Default to 1e4, converting to hectares. x_label (str, optional): Label for the x axis. Defaults to None. y_label (str, optional): Label for the y axis. Defaults to None. title (str, optional): Title for the plot. Defaults to None. width (int, optional): Width of the plot in pixels. Defaults to None. height (int, optional): Height of the plot in pixels. Defaults to 500. layout_args (dict, optional): Layout arguments for the plot to be passed to fig.update_layout(), return_df (bool, optional): Whether to return the dataframe of the plot. Defaults to False. Returns: pd.DataFrame: Pandas dataframe of the plot. Here is the function: def jrc_hist_monthly_history( collection=None, region=None, start_date="1984-03-16", end_date=None, start_month=1, end_month=12, scale=None, frequency="year", reducer="mean", denominator=1e4, x_label=None, y_label=None, title=None, width=None, height=None, layout_args={}, return_df=False, **kwargs, ): """Create a JRC monthly history plot. Args: collection (ee.ImageCollection, optional): The image collection of JRC surface water monthly history. Default to ee.ImageCollection('JRC/GSW1_4/MonthlyHistory') region (ee.Geometry | ee.FeatureCollection, optional): The region to plot. Default to None. start_date (str, optional): The start date of the plot. Default to '1984-03-16'. end_date (str, optional): The end date of the plot. Default to the current date. start_month (int, optional): The start month of the plot. Default to 1. end_month (int, optional): The end month of the plot. Default to 12. scale (float, optional): The scale to compute the statistics. Default to None. frequency (str, optional): The frequency of the plot. Can be either 'year' or 'month', Default to 'year'. reducer (str, optional): The reducer to compute the statistics. Can be either 'mean', 'min', 'max', 'median', etc. Default to 'mean'. denominator (int, optional): The denominator to convert area from square meters to other units. Default to 1e4, converting to hectares. x_label (str, optional): Label for the x axis. Defaults to None. y_label (str, optional): Label for the y axis. Defaults to None. title (str, optional): Title for the plot. Defaults to None. width (int, optional): Width of the plot in pixels. Defaults to None. height (int, optional): Height of the plot in pixels. Defaults to 500. layout_args (dict, optional): Layout arguments for the plot to be passed to fig.update_layout(), return_df (bool, optional): Whether to return the dataframe of the plot. Defaults to False. Returns: pd.DataFrame: Pandas dataframe of the plot. """ from datetime import date import pandas as pd import plotly.express as px if end_date is None: end_date = date.today().strftime("%Y-%m-%d") if collection is None: collection = ee.ImageCollection("JRC/GSW1_4/MonthlyHistory") if frequency not in ["year", "month"]: raise ValueError("frequency must be 'year' or 'month'.") images = ( collection.filterDate(start_date, end_date) .filter(ee.Filter.calendarRange(start_month, end_month, "month")) .map(lambda img: img.eq(2).selfMask()) ) def cal_area(img): pixel_area = img.multiply(ee.Image.pixelArea()).divide(denominator) img_area = pixel_area.reduceRegion( **{ "geometry": region, "reducer": ee.Reducer.sum(), "scale": scale, "maxPixels": 1e12, "bestEffort": True, } ) return img.set({"area": img_area}) areas = images.map(cal_area) stats = areas.aggregate_array("area").getInfo() values = [item["water"] for item in stats] labels = areas.aggregate_array("system:index").getInfo() months = [label.split("_")[1] for label in labels] if frequency == "month": area_df = pd.DataFrame({"Month": labels, "Area": values, "month": months}) else: dates = [d[:4] for d in labels] data_dict = {"Date": labels, "Year": dates, "Area": values} df = pd.DataFrame(data_dict) result = df.groupby("Year").agg(reducer) area_df = pd.DataFrame({"Year": result.index, "Area": result["Area"]}) area_df = area_df.reset_index(drop=True) if return_df: return area_df else: labels = {} if x_label is not None: labels[frequency.title()] = x_label if y_label is not None: labels["Area"] = y_label fig = px.bar( area_df, x=frequency.title(), y="Area", labels=labels, title=title, width=width, height=height, **kwargs, ) fig.update_layout(**layout_args) return fig
Create a JRC monthly history plot. Args: collection (ee.ImageCollection, optional): The image collection of JRC surface water monthly history. Default to ee.ImageCollection('JRC/GSW1_4/MonthlyHistory') region (ee.Geometry | ee.FeatureCollection, optional): The region to plot. Default to None. start_date (str, optional): The start date of the plot. Default to '1984-03-16'. end_date (str, optional): The end date of the plot. Default to the current date. start_month (int, optional): The start month of the plot. Default to 1. end_month (int, optional): The end month of the plot. Default to 12. scale (float, optional): The scale to compute the statistics. Default to None. frequency (str, optional): The frequency of the plot. Can be either 'year' or 'month', Default to 'year'. reducer (str, optional): The reducer to compute the statistics. Can be either 'mean', 'min', 'max', 'median', etc. Default to 'mean'. denominator (int, optional): The denominator to convert area from square meters to other units. Default to 1e4, converting to hectares. x_label (str, optional): Label for the x axis. Defaults to None. y_label (str, optional): Label for the y axis. Defaults to None. title (str, optional): Title for the plot. Defaults to None. width (int, optional): Width of the plot in pixels. Defaults to None. height (int, optional): Height of the plot in pixels. Defaults to 500. layout_args (dict, optional): Layout arguments for the plot to be passed to fig.update_layout(), return_df (bool, optional): Whether to return the dataframe of the plot. Defaults to False. Returns: pd.DataFrame: Pandas dataframe of the plot.
12,401
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple The provided code snippet includes necessary dependencies for implementing the `html_to_streamlit` function. Write a Python function `def html_to_streamlit( filename, width=None, height=None, scrolling=False, replace_dict={} )` to solve the following problem: Renders an HTML file as a Streamlit component. Args: filename (str): The filename of the HTML file. width (int, optional): Width of the map. Defaults to None. height (int, optional): Height of the map. Defaults to 600. scrolling (bool, optional): Whether to allow the map to scroll. Defaults to False. replace_dict (dict, optional): A dictionary of strings to replace in the HTML file. Defaults to {}. Raises: ValueError: If the filename does not exist. Returns: streamlit.components: components.html object. Here is the function: def html_to_streamlit( filename, width=None, height=None, scrolling=False, replace_dict={} ): """Renders an HTML file as a Streamlit component. Args: filename (str): The filename of the HTML file. width (int, optional): Width of the map. Defaults to None. height (int, optional): Height of the map. Defaults to 600. scrolling (bool, optional): Whether to allow the map to scroll. Defaults to False. replace_dict (dict, optional): A dictionary of strings to replace in the HTML file. Defaults to {}. Raises: ValueError: If the filename does not exist. Returns: streamlit.components: components.html object. """ import streamlit.components.v1 as components if not os.path.exists(filename): raise ValueError("filename must exist.") f = open(filename, "r") html = f.read() for key, value in replace_dict.items(): html = html.replace(key, value) f.close() return components.html(html, width=width, height=height, scrolling=scrolling)
Renders an HTML file as a Streamlit component. Args: filename (str): The filename of the HTML file. width (int, optional): Width of the map. Defaults to None. height (int, optional): Height of the map. Defaults to 600. scrolling (bool, optional): Whether to allow the map to scroll. Defaults to False. replace_dict (dict, optional): A dictionary of strings to replace in the HTML file. Defaults to {}. Raises: ValueError: If the filename does not exist. Returns: streamlit.components: components.html object.
12,402
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple def mosaic(images, output, merge_args={}, verbose=True, **kwargs): """Mosaics a list of images into a single image. Inspired by https://bit.ly/3A6roDK. Args: images (str | list): An input directory containing images or a list of images. output (str): The output image filepath. merge_args (dict, optional): A dictionary of arguments to pass to the rasterio.merge function. Defaults to {}. verbose (bool, optional): Whether to print progress. Defaults to True. """ from rasterio.merge import merge import rasterio as rio from pathlib import Path output = os.path.abspath(output) if isinstance(images, str): path = Path(images) raster_files = list(path.iterdir()) elif isinstance(images, list): raster_files = images else: raise ValueError("images must be a list of raster files.") raster_to_mosiac = [] if not os.path.exists(os.path.dirname(output)): os.makedirs(os.path.dirname(output)) for index, p in enumerate(raster_files): if verbose: print(f"Reading {index+1}/{len(raster_files)}: {os.path.basename(p)}") raster = rio.open(p, **kwargs) raster_to_mosiac.append(raster) if verbose: print("Merging rasters...") arr, transform = merge(raster_to_mosiac, **merge_args) output_meta = raster.meta.copy() output_meta.update( { "driver": "GTiff", "height": arr.shape[1], "width": arr.shape[2], "transform": transform, } ) with rio.open(output, "w", **output_meta) as m: m.write(arr) The provided code snippet includes necessary dependencies for implementing the `image_convolution` function. Write a Python function `def image_convolution( image, kernel=None, resample=None, projection="EPSG:3857", **kwargs )` to solve the following problem: Performs a convolution on an image. Args: image (ee.Image | ee.ImageCollection): The image to convolve. kernel (ee.Kernel, optional): The kernel to convolve with. Defaults to None, a 7x7 gaussian kernel. resample (str, optional): The resample method to use. It can be either 'bilinear' or 'bicubic'". Defaults to None, which uses the image's resample method. projection (str, optional): The projection to use. Defaults to 'EPSG:3857'. Returns: ee.Image: The convolved image. Here is the function: def image_convolution( image, kernel=None, resample=None, projection="EPSG:3857", **kwargs ): """Performs a convolution on an image. Args: image (ee.Image | ee.ImageCollection): The image to convolve. kernel (ee.Kernel, optional): The kernel to convolve with. Defaults to None, a 7x7 gaussian kernel. resample (str, optional): The resample method to use. It can be either 'bilinear' or 'bicubic'". Defaults to None, which uses the image's resample method. projection (str, optional): The projection to use. Defaults to 'EPSG:3857'. Returns: ee.Image: The convolved image. """ if isinstance(image, ee.ImageCollection): image = image.mosaic() elif not isinstance(image, ee.Image): raise ValueError("image must be an ee.Image or ee.ImageCollection.") if kernel is None: kernel = ee.Kernel.gaussian(radius=3, sigma=2, units="pixels", normalize=True) elif not isinstance(kernel, ee.Kernel): raise ValueError("kernel must be an ee.Kernel.") if resample is not None: if resample not in ["bilinear", "bicubic"]: raise ValueError("resample must be one of 'bilinear' or 'bicubic'") result = image.convolve(kernel) if resample is not None: result = result.resample(resample) return result.setDefaultProjection(projection)
Performs a convolution on an image. Args: image (ee.Image | ee.ImageCollection): The image to convolve. kernel (ee.Kernel, optional): The kernel to convolve with. Defaults to None, a 7x7 gaussian kernel. resample (str, optional): The resample method to use. It can be either 'bilinear' or 'bicubic'". Defaults to None, which uses the image's resample method. projection (str, optional): The projection to use. Defaults to 'EPSG:3857'. Returns: ee.Image: The convolved image.
12,403
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple def download_file( url=None, output=None, quiet=False, proxy=None, speed=None, use_cookies=True, verify=True, id=None, fuzzy=False, resume=False, unzip=True, overwrite=False, ): """Download a file from URL, including Google Drive shared URL. Args: url (str, optional): Google Drive URL is also supported. Defaults to None. output (str, optional): Output filename. Default is basename of URL. quiet (bool, optional): Suppress terminal output. Default is False. proxy (str, optional): Proxy. Defaults to None. speed (float, optional): Download byte size per second (e.g., 256KB/s = 256 * 1024). Defaults to None. use_cookies (bool, optional): Flag to use cookies. Defaults to True. verify (bool | str, optional): Either a bool, in which case it controls whether the server's TLS certificate is verified, or a string, in which case it must be a path to a CA bundle to use. Default is True.. Defaults to True. id (str, optional): Google Drive's file ID. Defaults to None. fuzzy (bool, optional): Fuzzy extraction of Google Drive's file Id. Defaults to False. resume (bool, optional): Resume the download from existing tmp file if possible. Defaults to False. unzip (bool, optional): Unzip the file. Defaults to True. overwrite (bool, optional): Overwrite the file if it already exists. Defaults to False. Returns: str: The output file path. """ import gdown if output is None: if isinstance(url, str) and url.startswith("http"): output = os.path.basename(url) if isinstance(url, str): if os.path.exists(os.path.abspath(output)) and (not overwrite): print( f"{output} already exists. Skip downloading. Set overwrite=True to overwrite." ) return os.path.abspath(output) else: url = github_raw_url(url) if "https://drive.google.com/file/d/" in url: fuzzy = True output = gdown.download( url, output, quiet, proxy, speed, use_cookies, verify, id, fuzzy, resume ) if unzip and output.endswith(".zip"): with zipfile.ZipFile(output, "r") as zip_ref: if not quiet: print("Extracting files...") zip_ref.extractall(os.path.dirname(output)) return os.path.abspath(output) def github_raw_url(url): """Get the raw URL for a GitHub file. Args: url (str): The GitHub URL. Returns: str: The raw URL. """ if isinstance(url, str) and url.startswith("https://github.com/") and "blob" in url: url = url.replace("github.com", "raw.githubusercontent.com").replace( "blob/", "", 1 ) return url The provided code snippet includes necessary dependencies for implementing the `download_ned` function. Write a Python function `def download_ned(region, out_dir=None, return_url=False, download_args={}, **kwargs)` to solve the following problem: Download the US National Elevation Datasets (NED) for a region. Args: region (str | list): A filepath to a vector dataset or a list of bounds in the form of [minx, miny, maxx, maxy]. out_dir (str, optional): The directory to download the files to. Defaults to None, which uses the current working directory. return_url (bool, optional): Whether to return the download URLs of the files. Defaults to False. download_args (dict, optional): A dictionary of arguments to pass to the download_file function. Defaults to {}. Returns: list: A list of the download URLs of the files if return_url is True. Here is the function: def download_ned(region, out_dir=None, return_url=False, download_args={}, **kwargs): """Download the US National Elevation Datasets (NED) for a region. Args: region (str | list): A filepath to a vector dataset or a list of bounds in the form of [minx, miny, maxx, maxy]. out_dir (str, optional): The directory to download the files to. Defaults to None, which uses the current working directory. return_url (bool, optional): Whether to return the download URLs of the files. Defaults to False. download_args (dict, optional): A dictionary of arguments to pass to the download_file function. Defaults to {}. Returns: list: A list of the download URLs of the files if return_url is True. """ import geopandas as gpd if out_dir is None: out_dir = os.getcwd() else: out_dir = os.path.abspath(out_dir) if isinstance(region, str): if region.startswith("http"): region = github_raw_url(region) region = download_file(region) elif not os.path.exists(region): raise ValueError("region must be a path or a URL to a vector dataset.") roi = gpd.read_file(region, **kwargs) roi = roi.to_crs(epsg=4326) bounds = roi.total_bounds elif isinstance(region, list): bounds = region else: raise ValueError( "region must be a filepath or a list of bounds in the form of [minx, miny, maxx, maxy]." ) minx, miny, maxx, maxy = [float(x) for x in bounds] tiles = [] left = abs(math.floor(minx)) right = abs(math.floor(maxx)) - 1 upper = math.ceil(maxy) bottom = math.ceil(miny) - 1 for y in range(upper, bottom, -1): for x in range(left, right, -1): tile_id = "n{}w{}".format(str(y).zfill(2), str(x).zfill(3)) tiles.append(tile_id) links = [] filepaths = [] for index, tile in enumerate(tiles): tif_url = f"https://prd-tnm.s3.amazonaws.com/StagedProducts/Elevation/13/TIFF/current/{tile}/USGS_13_{tile}.tif" r = requests.head(tif_url) if r.status_code == 200: tif = os.path.join(out_dir, os.path.basename(tif_url)) links.append(tif_url) filepaths.append(tif) else: print(f"{tif_url} does not exist.") if return_url: return links else: for index, link in enumerate(links): print(f"Downloading {index + 1} of {len(links)}: {os.path.basename(link)}") download_file(link, filepaths[index], **download_args)
Download the US National Elevation Datasets (NED) for a region. Args: region (str | list): A filepath to a vector dataset or a list of bounds in the form of [minx, miny, maxx, maxy]. out_dir (str, optional): The directory to download the files to. Defaults to None, which uses the current working directory. return_url (bool, optional): Whether to return the download URLs of the files. Defaults to False. download_args (dict, optional): A dictionary of arguments to pass to the download_file function. Defaults to {}. Returns: list: A list of the download URLs of the files if return_url is True.
12,404
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple The provided code snippet includes necessary dependencies for implementing the `get_info` function. Write a Python function `def get_info(ee_object, layer_name="", opened=False, return_node=False)` to solve the following problem: Print out the information for an Earth Engine object using a tree structure. The source code was adapted from https://github.com/google/earthengine-jupyter. Credits to Tyler Erickson. Args: ee_object (object): The Earth Engine object. layer_name (str, optional): The name of the layer. Defaults to "". opened (bool, optional): Whether to expand the tree. Defaults to False. return_node (bool, optional): Whether to return the widget as ipytree.Node. If False, returns the widget as ipytree.Tree. Defaults to False. Here is the function: def get_info(ee_object, layer_name="", opened=False, return_node=False): """Print out the information for an Earth Engine object using a tree structure. The source code was adapted from https://github.com/google/earthengine-jupyter. Credits to Tyler Erickson. Args: ee_object (object): The Earth Engine object. layer_name (str, optional): The name of the layer. Defaults to "". opened (bool, optional): Whether to expand the tree. Defaults to False. return_node (bool, optional): Whether to return the widget as ipytree.Node. If False, returns the widget as ipytree.Tree. Defaults to False. """ def _order_items(item_dict, ordering_list): """Orders dictionary items in a specified order. Adapted from https://github.com/google/earthengine-jupyter. """ list_of_tuples = [ (key, item_dict[key]) for key in [x for x in ordering_list if x in item_dict.keys()] ] return dict(list_of_tuples) def _process_info(info): node_list = [] if isinstance(info, list): for count, item in enumerate(info): if isinstance(item, (list, dict)): if "id" in item: count = f"{count}: \"{item['id']}\"" if "data_type" in item: count = f"{count}, {item['data_type']['precision']}" if "crs" in item: count = f"{count}, {item['crs']}" if "dimensions" in item: dimensions = item["dimensions"] count = f"{count}, {dimensions[0]}x{dimensions[1]} px" node_list.append( Node(f"{count}", nodes=_process_info(item), opened=opened) ) else: node_list.append(Node(f"{count}: {item}", icon="file")) elif isinstance(info, dict): for k, v in info.items(): if isinstance(v, (list, dict)): if k == "properties": k = f"properties: Object ({len(v)} properties)" elif k == "bands": k = f"bands: List ({len(v)} elements)" node_list.append( Node(f"{k}", nodes=_process_info(v), opened=opened) ) else: node_list.append(Node(f"{k}: {v}", icon="file")) else: node_list.append(Node(f"{info}", icon="file")) return node_list if isinstance(ee_object, ee.FeatureCollection): ee_object = ee_object.map(lambda f: ee.Feature(None, f.toDictionary())) layer_info = ee_object.getInfo() if not layer_info: return None props = layer_info.get("properties", {}) layer_info["properties"] = dict(sorted(props.items())) ordering_list = [] if "type" in layer_info: ordering_list.append("type") ee_type = layer_info["type"] else: ee_type = "" if "id" in layer_info: ordering_list.append("id") ee_id = layer_info["id"] else: ee_id = "" ordering_list.append("version") ordering_list.append("bands") ordering_list.append("properties") layer_info = _order_items(layer_info, ordering_list) nodes = _process_info(layer_info) if len(layer_name) > 0: layer_name = f"{layer_name}: " if "bands" in layer_info: band_info = f' ({len(layer_info["bands"])} bands)' else: band_info = "" root_node = Node(f"{layer_name}{ee_type} {band_info}", nodes=nodes, opened=opened) # root_node.open_icon = "plus-square" # root_node.open_icon_style = "success" # root_node.close_icon = "minus-square" # root_node.close_icon_style = "info" if return_node: return root_node else: tree = Tree() tree.add_node(root_node) return tree
Print out the information for an Earth Engine object using a tree structure. The source code was adapted from https://github.com/google/earthengine-jupyter. Credits to Tyler Erickson. Args: ee_object (object): The Earth Engine object. layer_name (str, optional): The name of the layer. Defaults to "". opened (bool, optional): Whether to expand the tree. Defaults to False. return_node (bool, optional): Whether to return the widget as ipytree.Node. If False, returns the widget as ipytree.Tree. Defaults to False.
12,405
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple def download_ee_image( image, filename, region=None, crs=None, crs_transform=None, scale=None, resampling="near", dtype=None, overwrite=True, num_threads=None, max_tile_size=None, max_tile_dim=None, shape=None, scale_offset=False, unmask_value=None, **kwargs, ): def mosaic(images, output, merge_args={}, verbose=True, **kwargs): def download_3dep_lidar(region, filename, scale=1.0, crs="EPSG:3857"): dataset = ee.ImageCollection("USGS/3DEP/1m") if isinstance(region, ee.Geometry) or isinstance(region, ee.Feature): region = ee.FeatureCollection([region]) if isinstance(region, ee.FeatureCollection): image = dataset.filterBounds(region).mosaic().clipToCollection(region) download_ee_image(image, filename, region=region.geometry(), scale=scale, crs=crs)
null
12,406
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple The provided code snippet includes necessary dependencies for implementing the `use_mkdocs` function. Write a Python function `def use_mkdocs()` to solve the following problem: Test if the current notebook is running in mkdocs. Returns: bool: True if the notebook is running in mkdocs. Here is the function: def use_mkdocs(): """Test if the current notebook is running in mkdocs. Returns: bool: True if the notebook is running in mkdocs. """ if os.environ.get("USE_MKDOCS") is not None: return True else: return False
Test if the current notebook is running in mkdocs. Returns: bool: True if the notebook is running in mkdocs.
12,407
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple def rgb_to_hex(rgb=(255, 255, 255)): """Converts RGB to hex color. In RGB color R stands for Red, G stands for Green, and B stands for Blue, and it ranges from the decimal value of 0 – 255. Args: rgb (tuple, optional): RGB color code as a tuple of (red, green, blue). Defaults to (255, 255, 255). Returns: str: hex color code """ return "%02x%02x%02x" % rgb def check_color(in_color): """Checks the input color and returns the corresponding hex color code. Args: in_color (str or tuple): It can be a string (e.g., 'red', '#ffff00', 'ffff00', 'ff0') or RGB tuple (e.g., (255, 127, 0)). Returns: str: A hex color code. """ import colour out_color = "#000000" # default black color if isinstance(in_color, tuple) and len(in_color) == 3: # rescale color if necessary if all(isinstance(item, int) for item in in_color): in_color = [c / 255.0 for c in in_color] return colour.Color(rgb=tuple(in_color)).hex_l else: # try to guess the color system try: return colour.Color(in_color).hex_l except Exception as e: pass # try again by adding an extra # (GEE handle hex codes without #) try: return colour.Color(f"#{in_color}").hex_l except Exception as e: print( f"The provided color ({in_color}) is invalid. Using the default black color." ) print(e) return out_color builtin_legends = { # National Land Cover Database 2016 (NLCD2016) Legend https://www.mrlc.gov/data/legends/national-land-cover-database-2016-nlcd2016-legend "NLCD": { "11 Open Water": "466b9f", "12 Perennial Ice/Snow": "d1def8", "21 Developed, Open Space": "dec5c5", "22 Developed, Low Intensity": "d99282", "23 Developed, Medium Intensity": "eb0000", "24 Developed, High Intensity": "ab0000", "31 Barren Land (Rock/Sand/Clay)": "b3ac9f", "41 Deciduous Forest": "68ab5f", "42 Evergreen Forest": "1c5f2c", "43 Mixed Forest": "b5c58f", "51 Dwarf Scrub": "af963c", "52 Shrub/Scrub": "ccb879", "71 Grassland/Herbaceous": "dfdfc2", "72 Sedge/Herbaceous": "d1d182", "73 Lichens": "a3cc51", "74 Moss": "82ba9e", "81 Pasture/Hay": "dcd939", "82 Cultivated Crops": "ab6c28", "90 Woody Wetlands": "b8d9eb", "95 Emergent Herbaceous Wetlands": "6c9fb8", }, # https://developers.google.com/earth-engine/datasets/catalog/ESA_WorldCover_v100 "ESA_WorldCover": { "10 Trees": "006400", "20 Shrubland": "ffbb22", "30 Grassland": "ffff4c", "40 Cropland": "f096ff", "50 Built-up": "fa0000", "60 Barren / sparse vegetation": "b4b4b4", "70 Snow and ice": "f0f0f0", "80 Open water": "0064c8", "90 Herbaceous wetland": "0096a0", "95 Mangroves": "00cf75", "100 Moss and lichen": "fae6a0", }, # https://samapriya.github.io/awesome-gee-community-datasets/projects/esrilc2020/ "ESRI_LandCover": { "1 Water": "1A5BAB", "2 Trees": "358221", "3 Grass": "A7D282", "4 Flooded Vegetation": "87D19E", "5 Crops": "FFDB5C", "6 Shrub & Scrub": "EECFA8", "7 Built Area": "ED022A", "8 Bare Ground": "EDE9E4", "9 Snow/Ice": "F2FAFF", "10 Clouds": "C8C8C8", }, # https://samapriya.github.io/awesome-gee-community-datasets/projects/S2TSLULC/ "ESRI_LandCover_TS": { "1 Water": "1A5BAB", "2 Trees": "358221", "4 Flooded Vegetation": "87D19E", "5 Crops": "FFDB5C", "7 Built Area": "ED022A", "8 Bare Ground": "EDE9E4", "9 Snow/Ice": "F2FAFF", "10 Clouds": "C8C8C8", "11 Rangeland": "C6AD8D", }, "Dynamic_World": { "0 Water": "419BDF", "1 Trees": "397D49", "2 Grass": "88B053", "3 Flooded vegetation": "7A87C6", "4 Crops": "E49635", "5 Shrub & Scrub": "DFC35A", "6 Built-up area": "C4281B", "7 Bare ground": "A59B8F", "8 Snow & Ice": "B39FE1", }, # National Wetlands Inventory Legend: https://www.fws.gov/wetlands/data/Mapper-Wetlands-Legend.html "NWI": { "Freshwater- Forested and Shrub wetland": (0, 136, 55), "Freshwater Emergent wetland": (127, 195, 28), "Freshwater pond": (104, 140, 192), "Estuarine and Marine wetland": (102, 194, 165), "Riverine": (1, 144, 191), "Lakes": (19, 0, 124), "Estuarine and Marine Deepwater": (0, 124, 136), "Other Freshwater wetland": (178, 134, 86), }, # MCD12Q1.051 Land Cover Type Yearly Global 500m https://developers.google.com/earth-engine/datasets/catalog/MODIS_051_MCD12Q1 "MODIS/051/MCD12Q1": { "0 Water": "1c0dff", "1 Evergreen needleleaf forest": "05450a", "2 Evergreen broadleaf forest": "086a10", "3 Deciduous needleleaf forest": "54a708", "4 Deciduous broadleaf forest": "78d203", "5 Mixed forest": "009900", "6 Closed shrublands": "c6b044", "7 Open shrublands": "dcd159", "8 Woody savannas": "dade48", "9 Savannas": "fbff13", "10 Grasslands": "b6ff05", "11 Permanent wetlands": "27ff87", "12 Croplands": "c24f44", "13 Urban and built-up": "a5a5a5", "14 Cropland/natural vegetation mosaic": "ff6d4c", "15 Snow and ice": "69fff8", "16 Barren or sparsely vegetated": "f9ffa4", "254 Unclassified": "ffffff", }, # MCD12Q1.006 Land Cover Type Yearly Global 500m https://developers.google.com/earth-engine/datasets/catalog/MODIS_006_MCD12Q1 "MODIS/006/MCD12Q1": { "1 Evergreen needleleaf forest": "05450a", "2 Evergreen broadleaf forest": "086a10", "3 Deciduous needleleaf forest": "54a708", "4 Deciduous broadleaf forest": "78d203", "5 Mixed forest": "009900", "6 Closed shrublands": "c6b044", "7 Open shrublands": "dcd159", "8 Woody savannas": "dade48", "9 Savannas": "fbff13", "10 Grasslands": "b6ff05", "11 Permanent wetlands": "27ff87", "12 Croplands": "c24f44", "13 Urban and built-up": "a5a5a5", "14 Cropland/natural vegetation mosaic": "ff6d4c", "15 Snow and ice": "69fff8", "16 Barren or sparsely vegetated": "f9ffa4", "17 Water bodies": "1c0dff", }, # GlobCover: Global Land Cover Map https://developers.google.com/earth-engine/datasets/catalog/ESA_GLOBCOVER_L4_200901_200912_V2_3 "GLOBCOVER": { "11 Post-flooding or irrigated croplands": "aaefef", "14 Rainfed croplands": "ffff63", "20 Mosaic cropland (50-70%) / vegetation (grassland, shrubland, forest) (20-50%)": "dcef63", "30 Mosaic vegetation (grassland, shrubland, forest) (50-70%) / cropland (20-50%)": "cdcd64", "40 Closed to open (>15%) broadleaved evergreen and/or semi-deciduous forest (>5m)": "006300", "50 Closed (>40%) broadleaved deciduous forest (>5m)": "009f00", "60 Open (15-40%) broadleaved deciduous forest (>5m)": "aac700", "70 Closed (>40%) needleleaved evergreen forest (>5m)": "003b00", "90 Open (15-40%) needleleaved deciduous or evergreen forest (>5m)": "286300", "100 Closed to open (>15%) mixed broadleaved and needleleaved forest (>5m)": "788300", "110 Mosaic forest-shrubland (50-70%) / grassland (20-50%)": "8d9f00", "120 Mosaic grassland (50-70%) / forest-shrubland (20-50%)": "bd9500", "130 Closed to open (>15%) shrubland (<5m)": "956300", "140 Closed to open (>15%) grassland": "ffb431", "150 Sparse (>15%) vegetation (woody vegetation, shrubs, grassland)": "ffebae", "160 Closed (>40%) broadleaved forest regularly flooded - Fresh water": "00785a", "170 Closed (>40%) broadleaved semi-deciduous and/or evergreen forest regularly flooded - saline water": "009578", "180 Closed to open (>15%) vegetation (grassland, shrubland, woody vegetation) on regularly flooded or waterlogged soil - fresh, brackish or saline water": "00dc83", "190 Artificial surfaces and associated areas (urban areas >50%) GLOBCOVER 2009": "c31300", "200 Bare areas": "fff5d6", "210 Water bodies": "0046c7", "220 Permanent snow and ice": "ffffff", "230 Unclassified": "743411", }, # Global PALSAR-2/PALSAR Forest/Non-Forest Map https://developers.google.com/earth-engine/datasets/catalog/JAXA_ALOS_PALSAR_YEARLY_FNF "JAXA/PALSAR": { "1 Forest": "006400", "2 Non-Forest": "FEFF99", "3 Water": "0000FF", }, # Oxford MAP: Malaria Atlas Project Fractional International Geosphere-Biosphere Programme Landcover https://developers.google.com/earth-engine/datasets/catalog/Oxford_MAP_IGBP_Fractional_Landcover_5km_Annual "Oxford": { "0 Water": "032f7e", "1 Evergreen_Needleleaf_Fores": "02740b", "2 Evergreen_Broadleaf_Forest": "02740b", "3 Deciduous_Needleleaf_Forest": "8cf502", "4 Deciduous_Broadleaf_Forest": "8cf502", "5 Mixed_Forest": "a4da01", "6 Closed_Shrublands": "ffbd05", "7 Open_Shrublands": "ffbd05", "8 Woody_Savannas": "7a5a02", "9 Savannas": "f0ff0f", "10 Grasslands": "869b36", "11 Permanent_Wetlands": "6091b4", "12 Croplands": "ff4e4e", "13 Urban_and_Built-up": "999999", "14 Cropland_Natural_Vegetation_Mosaic": "ff4e4e", "15 Snow_and_Ice": "ffffff", "16 Barren_Or_Sparsely_Vegetated": "feffc0", "17 Unclassified": "020202", }, # Canada AAFC Annual Crop Inventory https://developers.google.com/earth-engine/datasets/catalog/AAFC_ACI "AAFC/ACI": { "10 Cloud": "000000", "20 Water": "3333ff", "30 Exposed Land and Barren": "996666", "34 Urban and Developed": "cc6699", "35 Greenhouses": "e1e1e1", "50 Shrubland": "ffff00", "80 Wetland": "993399", "110 Grassland": "cccc00", "120 Agriculture (undifferentiated)": "cc6600", "122 Pasture and Forages": "ffcc33", "130 Too Wet to be Seeded": "7899f6", "131 Fallow": "ff9900", "132 Cereals": "660000", "133 Barley": "dae31d", "134 Other Grains": "d6cc00", "135 Millet": "d2db25", "136 Oats": "d1d52b", "137 Rye": "cace32", "138 Spelt": "c3c63a", "139 Triticale": "b9bc44", "140 Wheat": "a7b34d", "141 Switchgrass": "b9c64e", "142 Sorghum": "999900", "145 Winter Wheat": "92a55b", "146 Spring Wheat": "809769", "147 Corn": "ffff99", "148 Tobacco": "98887c", "149 Ginseng": "799b93", "150 Oilseeds": "5ea263", "151 Borage": "52ae77", "152 Camelina": "41bf7a", "153 Canola and Rapeseed": "d6ff70", "154 Flaxseed": "8c8cff", "155 Mustard": "d6cc00", "156 Safflower": "ff7f00", "157 Sunflower": "315491", "158 Soybeans": "cc9933", "160 Pulses": "896e43", "162 Peas": "8f6c3d", "167 Beans": "82654a", "174 Lentils": "b85900", "175 Vegetables": "b74b15", "176 Tomatoes": "ff8a8a", "177 Potatoes": "ffcccc", "178 Sugarbeets": "6f55ca", "179 Other Vegetables": "ffccff", "180 Fruits": "dc5424", "181 Berries": "d05a30", "182 Blueberry": "d20000", "183 Cranberry": "cc0000", "185 Other Berry": "dc3200", "188 Orchards": "ff6666", "189 Other Fruits": "c5453b", "190 Vineyards": "7442bd", "191 Hops": "ffcccc", "192 Sod": "b5fb05", "193 Herbs": "ccff05", "194 Nursery": "07f98c", "195 Buckwheat": "00ffcc", "196 Canaryseed": "cc33cc", "197 Hemp": "8e7672", "198 Vetch": "b1954f", "199 Other Crops": "749a66", "200 Forest (undifferentiated)": "009900", "210 Coniferous": "006600", "220 Broadleaf": "00cc00", "230 Mixedwood": "cc9900", }, # Copernicus CORINE Land Cover https://developers.google.com/earth-engine/datasets/catalog/COPERNICUS_CORINE_V20_100m "COPERNICUS/CORINE/V20/100m": { "111 Artificial surfaces > Urban fabric > Continuous urban fabric": "E6004D", "112 Artificial surfaces > Urban fabric > Discontinuous urban fabric": "FF0000", "121 Artificial surfaces > Industrial, commercial, and transport units > Industrial or commercial units": "CC4DF2", "122 Artificial surfaces > Industrial, commercial, and transport units > Road and rail networks and associated land": "CC0000", "123 Artificial surfaces > Industrial, commercial, and transport units > Port areas": "E6CCCC", "124 Artificial surfaces > Industrial, commercial, and transport units > Airports": "E6CCE6", "131 Artificial surfaces > Mine, dump, and construction sites > Mineral extraction sites": "A600CC", "132 Artificial surfaces > Mine, dump, and construction sites > Dump sites": "A64DCC", "133 Artificial surfaces > Mine, dump, and construction sites > Construction sites": "FF4DFF", "141 Artificial surfaces > Artificial, non-agricultural vegetated areas > Green urban areas": "FFA6FF", "142 Artificial surfaces > Artificial, non-agricultural vegetated areas > Sport and leisure facilities": "FFE6FF", "211 Agricultural areas > Arable land > Non-irrigated arable land": "FFFFA8", "212 Agricultural areas > Arable land > Permanently irrigated land": "FFFF00", "213 Agricultural areas > Arable land > Rice fields": "E6E600", "221 Agricultural areas > Permanent crops > Vineyards": "E68000", "222 Agricultural areas > Permanent crops > Fruit trees and berry plantations": "F2A64D", "223 Agricultural areas > Permanent crops > Olive groves": "E6A600", "231 Agricultural areas > Pastures > Pastures": "E6E64D", "241 Agricultural areas > Heterogeneous agricultural areas > Annual crops associated with permanent crops": "FFE6A6", "242 Agricultural areas > Heterogeneous agricultural areas > Complex cultivation patterns": "FFE64D", "243 Agricultural areas > Heterogeneous agricultural areas > Land principally occupied by agriculture, with significant areas of natural vegetation": "E6CC4D", "244 Agricultural areas > Heterogeneous agricultural areas > Agro-forestry areas": "F2CCA6", "311 Forest and semi natural areas > Forests > Broad-leaved forest": "80FF00", "312 Forest and semi natural areas > Forests > Coniferous forest": "00A600", "313 Forest and semi natural areas > Forests > Mixed forest": "4DFF00", "321 Forest and semi natural areas > Scrub and/or herbaceous vegetation associations > Natural grasslands": "CCF24D", "322 Forest and semi natural areas > Scrub and/or herbaceous vegetation associations > Moors and heathland": "A6FF80", "323 Forest and semi natural areas > Scrub and/or herbaceous vegetation associations > Sclerophyllous vegetation": "A6E64D", "324 Forest and semi natural areas > Scrub and/or herbaceous vegetation associations > Transitional woodland-shrub": "A6F200", "331 Forest and semi natural areas > Open spaces with little or no vegetation > Beaches, dunes, sands": "E6E6E6", "332 Forest and semi natural areas > Open spaces with little or no vegetation > Bare rocks": "CCCCCC", "333 Forest and semi natural areas > Open spaces with little or no vegetation > Sparsely vegetated areas": "CCFFCC", "334 Forest and semi natural areas > Open spaces with little or no vegetation > Burnt areas": "000000", "335 Forest and semi natural areas > Open spaces with little or no vegetation > Glaciers and perpetual snow": "A6E6CC", "411 Wetlands > Inland wetlands > Inland marshes": "A6A6FF", "412 Wetlands > Inland wetlands > Peat bogs": "4D4DFF", "421 Wetlands > Maritime wetlands > Salt marshes": "CCCCFF", "422 Wetlands > Maritime wetlands > Salines": "E6E6FF", "423 Wetlands > Maritime wetlands > Intertidal flats": "A6A6E6", "511 Water bodies > Inland waters > Water courses": "00CCF2", "512 Water bodies > Inland waters > Water bodies": "80F2E6", "521 Water bodies > Marine waters > Coastal lagoons": "00FFA6", "522 Water bodies > Marine waters > Estuaries": "A6FFE6", "523 Water bodies > Marine waters > Sea and ocean": "E6F2FF", }, # Copernicus Global Land Cover Layers: CGLS-LC100 collection 2 https://developers.google.com/earth-engine/datasets/catalog/COPERNICUS_Landcover_100m_Proba-V_Global "COPERNICUS/Landcover/100m/Proba-V/Global": { "0 Unknown": "282828", "20 Shrubs. Woody perennial plants with persistent and woody stems and without any defined main stem being less than 5 m tall. The shrub foliage can be either evergreen or deciduous.": "FFBB22", "30 Herbaceous vegetation. Plants without persistent stem or shoots above ground and lacking definite firm structure. Tree and shrub cover is less than 10 %.": "FFFF4C", "40 Cultivated and managed vegetation / agriculture. Lands covered with temporary crops followed by harvest and a bare soil period (e.g., single and multiple cropping systems). Note that perennial woody crops will be classified as the appropriate forest or shrub land cover type.": "F096FF", "50 Urban / built up. Land covered by buildings and other man-made structures.": "FA0000", "60 Bare / sparse vegetation. Lands with exposed soil, sand, or rocks and never has more than 10 % vegetated cover during any time of the year.": "B4B4B4", "70 Snow and ice. Lands under snow or ice cover throughout the year.": "F0F0F0", "80 Permanent water bodies. Lakes, reservoirs, and rivers. Can be either fresh or salt-water bodies.": "0032C8", "90 Herbaceous wetland. Lands with a permanent mixture of water and herbaceous or woody vegetation. The vegetation can be present in either salt, brackish, or fresh water.": "0096A0", "100 Moss and lichen.": "FAE6A0", "111 Closed forest, evergreen needle leaf. Tree canopy >70 %, almost all needle leaf trees remain green all year. Canopy is never without green foliage.": "58481F", "112 Closed forest, evergreen broad leaf. Tree canopy >70 %, almost all broadleaf trees remain green year round. Canopy is never without green foliage.": "009900", "113 Closed forest, deciduous needle leaf. Tree canopy >70 %, consists of seasonal needle leaf tree communities with an annual cycle of leaf-on and leaf-off periods.": "70663E", "114 Closed forest, deciduous broad leaf. Tree canopy >70 %, consists of seasonal broadleaf tree communities with an annual cycle of leaf-on and leaf-off periods.": "00CC00", "115 Closed forest, mixed.": "4E751F", "116 Closed forest, not matching any of the other definitions.": "007800", "121 Open forest, evergreen needle leaf. Top layer- trees 15-70 % and second layer- mixed of shrubs and grassland, almost all needle leaf trees remain green all year. Canopy is never without green foliage.": "666000", "122 Open forest, evergreen broad leaf. Top layer- trees 15-70 % and second layer- mixed of shrubs and grassland, almost all broadleaf trees remain green year round. Canopy is never without green foliage.": "8DB400", "123 Open forest, deciduous needle leaf. Top layer- trees 15-70 % and second layer- mixed of shrubs and grassland, consists of seasonal needle leaf tree communities with an annual cycle of leaf-on and leaf-off periods.": "8D7400", "124 Open forest, deciduous broad leaf. Top layer- trees 15-70 % and second layer- mixed of shrubs and grassland, consists of seasonal broadleaf tree communities with an annual cycle of leaf-on and leaf-off periods.": "A0DC00", "125 Open forest, mixed.": "929900", "126 Open forest, not matching any of the other definitions.": "648C00", "200 Oceans, seas. Can be either fresh or salt-water bodies.": "000080", }, # USDA NASS Cropland Data Layers https://developers.google.com/earth-engine/datasets/catalog/USDA_NASS_CDL "USDA/NASS/CDL": { "1 Corn": "ffd300", "2 Cotton": "ff2626", "3 Rice": "00a8e2", "4 Sorghum": "ff9e0a", "5 Soybeans": "267000", "6 Sunflower": "ffff00", "10 Peanuts": "70a500", "11 Tobacco": "00af49", "12 Sweet Corn": "dda50a", "13 Pop or Orn Corn": "dda50a", "14 Mint": "7cd3ff", "21 Barley": "e2007c", "22 Durum Wheat": "896054", "23 Spring Wheat": "d8b56b", "24 Winter Wheat": "a57000", "25 Other Small Grains": "d69ebc", "26 Dbl Crop WinWht/Soybeans": "707000", "27 Rye": "aa007c", "28 Oats": "a05989", "29 Millet": "700049", "30 Speltz": "d69ebc", "31 Canola": "d1ff00", "32 Flaxseed": "7c99ff", "33 Safflower": "d6d600", "34 Rape Seed": "d1ff00", "35 Mustard": "00af49", "36 Alfalfa": "ffa5e2", "37 Other Hay/Non Alfalfa": "a5f28c", "38 Camelina": "00af49", "39 Buckwheat": "d69ebc", "41 Sugarbeets": "a800e2", "42 Dry Beans": "a50000", "43 Potatoes": "702600", "44 Other Crops": "00af49", "45 Sugarcane": "af7cff", "46 Sweet Potatoes": "702600", "47 Misc Vegs & Fruits": "ff6666", "48 Watermelons": "ff6666", "49 Onions": "ffcc66", "50 Cucumbers": "ff6666", "51 Chick Peas": "00af49", "52 Lentils": "00ddaf", "53 Peas": "54ff00", "54 Tomatoes": "f2a377", "55 Caneberries": "ff6666", "56 Hops": "00af49", "57 Herbs": "7cd3ff", "58 Clover/Wildflowers": "e8bfff", "59 Sod/Grass Seed": "afffdd", "60 Switchgrass": "00af49", "61 Fallow/Idle Cropland": "bfbf77", "63 Forest": "93cc93", "64 Shrubland": "c6d69e", "65 Barren": "ccbfa3", "66 Cherries": "ff00ff", "67 Peaches": "ff8eaa", "68 Apples": "ba004f", "69 Grapes": "704489", "70 Christmas Trees": "007777", "71 Other Tree Crops": "af9970", "72 Citrus": "ffff7c", "74 Pecans": "b5705b", "75 Almonds": "00a582", "76 Walnuts": "e8d6af", "77 Pears": "af9970", "81 Clouds/No Data": "f2f2f2", "82 Developed": "999999", "83 Water": "4970a3", "87 Wetlands": "7cafaf", "88 Nonag/Undefined": "e8ffbf", "92 Aquaculture": "00ffff", "111 Open Water": "4970a3", "112 Perennial Ice/Snow": "d3e2f9", "121 Developed/Open Space": "999999", "122 Developed/Low Intensity": "999999", "123 Developed/Med Intensity": "999999", "124 Developed/High Intensity": "999999", "131 Barren": "ccbfa3", "141 Deciduous Forest": "93cc93", "142 Evergreen Forest": "93cc93", "143 Mixed Forest": "93cc93", "152 Shrubland": "c6d69e", "176 Grassland/Pasture": "e8ffbf", "190 Woody Wetlands": "7cafaf", "195 Herbaceous Wetlands": "7cafaf", "204 Pistachios": "00ff8c", "205 Triticale": "d69ebc", "206 Carrots": "ff6666", "207 Asparagus": "ff6666", "208 Garlic": "ff6666", "209 Cantaloupes": "ff6666", "210 Prunes": "ff8eaa", "211 Olives": "334933", "212 Oranges": "e27026", "213 Honeydew Melons": "ff6666", "214 Broccoli": "ff6666", "216 Peppers": "ff6666", "217 Pomegranates": "af9970", "218 Nectarines": "ff8eaa", "219 Greens": "ff6666", "220 Plums": "ff8eaa", "221 Strawberries": "ff6666", "222 Squash": "ff6666", "223 Apricots": "ff8eaa", "224 Vetch": "00af49", "225 Dbl Crop WinWht/Corn": "ffd300", "226 Dbl Crop Oats/Corn": "ffd300", "227 Lettuce": "ff6666", "229 Pumpkins": "ff6666", "230 Dbl Crop Lettuce/Durum Wht": "896054", "231 Dbl Crop Lettuce/Cantaloupe": "ff6666", "232 Dbl Crop Lettuce/Cotton": "ff2626", "233 Dbl Crop Lettuce/Barley": "e2007c", "234 Dbl Crop Durum Wht/Sorghum": "ff9e0a", "235 Dbl Crop Barley/Sorghum": "ff9e0a", "236 Dbl Crop WinWht/Sorghum": "a57000", "237 Dbl Crop Barley/Corn": "ffd300", "238 Dbl Crop WinWht/Cotton": "a57000", "239 Dbl Crop Soybeans/Cotton": "267000", "240 Dbl Crop Soybeans/Oats": "267000", "241 Dbl Crop Corn/Soybeans": "ffd300", "242 Blueberries": "000099", "243 Cabbage": "ff6666", "244 Cauliflower": "ff6666", "245 Celery": "ff6666", "246 Radishes": "ff6666", "247 Turnips": "ff6666", "248 Eggplants": "ff6666", "249 Gourds": "ff6666", "250 Cranberries": "ff6666", "254 Dbl Crop Barley/Soybeans": "267000", }, "ALOS_landforms": { "11 Peak/ridge (warm)": "141414", "12 Peak/ridge": "383838", "13 Peak/ridge (cool)": "808080", "14 Mountain/divide": "EBEB8F", "15 Cliff": "F7D311", "21 Upper slope (warm)": "AA0000", "22 Upper slope": "D89382", "23 Upper slope (cool)": "DDC9C9", "24 Upper slope (flat)": "DCCDCE", "31 Lower slope (warm)": "1C6330", "32 Lower slope": "68AA63", "33 Lower slope (cool)": "B5C98E", "34 Lower slope (flat)": "E1F0E5", "41 Valley": "a975ba", "42 Valley (narrow)": "6f198c", }, } The provided code snippet includes necessary dependencies for implementing the `create_legend` function. Write a Python function `def create_legend( title="Legend", labels=None, colors=None, legend_dict=None, builtin_legend=None, opacity=1.0, position="bottomright", draggable=True, output=None, style={}, )` to solve the following problem: Create a legend in HTML format. Reference: https://bit.ly/3oV6vnH Args: title (str, optional): Title of the legend. Defaults to 'Legend'. Defaults to "Legend". colors (list, optional): A list of legend colors. Defaults to None. labels (list, optional): A list of legend labels. Defaults to None. legend_dict (dict, optional): A dictionary containing legend items as keys and color as values. If provided, legend_keys and legend_colors will be ignored. Defaults to None. builtin_legend (str, optional): Name of the builtin legend to add to the map. Defaults to None. opacity (float, optional): The opacity of the legend. Defaults to 1.0. position (str, optional): The position of the legend, can be one of the following: "topleft", "topright", "bottomleft", "bottomright". Defaults to "bottomright". draggable (bool, optional): If True, the legend can be dragged to a new position. Defaults to True. output (str, optional): The output file path (*.html) to save the legend. Defaults to None. style: Additional keyword arguments to style the legend, such as position, bottom, right, z-index, border, background-color, border-radius, padding, font-size, etc. The default style is: style = { 'position': 'fixed', 'z-index': '9999', 'border': '2px solid grey', 'background-color': 'rgba(255, 255, 255, 0.8)', 'border-radius': '5px', 'padding': '10px', 'font-size': '14px', 'bottom': '20px', 'right': '5px' } Returns: str: The HTML code of the legend. Here is the function: def create_legend( title="Legend", labels=None, colors=None, legend_dict=None, builtin_legend=None, opacity=1.0, position="bottomright", draggable=True, output=None, style={}, ): """Create a legend in HTML format. Reference: https://bit.ly/3oV6vnH Args: title (str, optional): Title of the legend. Defaults to 'Legend'. Defaults to "Legend". colors (list, optional): A list of legend colors. Defaults to None. labels (list, optional): A list of legend labels. Defaults to None. legend_dict (dict, optional): A dictionary containing legend items as keys and color as values. If provided, legend_keys and legend_colors will be ignored. Defaults to None. builtin_legend (str, optional): Name of the builtin legend to add to the map. Defaults to None. opacity (float, optional): The opacity of the legend. Defaults to 1.0. position (str, optional): The position of the legend, can be one of the following: "topleft", "topright", "bottomleft", "bottomright". Defaults to "bottomright". draggable (bool, optional): If True, the legend can be dragged to a new position. Defaults to True. output (str, optional): The output file path (*.html) to save the legend. Defaults to None. style: Additional keyword arguments to style the legend, such as position, bottom, right, z-index, border, background-color, border-radius, padding, font-size, etc. The default style is: style = { 'position': 'fixed', 'z-index': '9999', 'border': '2px solid grey', 'background-color': 'rgba(255, 255, 255, 0.8)', 'border-radius': '5px', 'padding': '10px', 'font-size': '14px', 'bottom': '20px', 'right': '5px' } Returns: str: The HTML code of the legend. """ import pkg_resources from .legends import builtin_legends pkg_dir = os.path.dirname(pkg_resources.resource_filename("geemap", "geemap.py")) legend_template = os.path.join(pkg_dir, "data/template/legend_style.html") if draggable: legend_template = os.path.join(pkg_dir, "data/template/legend.txt") if not os.path.exists(legend_template): raise FileNotFoundError("The legend template does not exist.") if labels is not None: if not isinstance(labels, list): print("The legend keys must be a list.") return else: labels = ["One", "Two", "Three", "Four", "etc"] if colors is not None: if not isinstance(colors, list): print("The legend colors must be a list.") return elif all(isinstance(item, tuple) for item in colors): try: colors = [rgb_to_hex(x) for x in colors] except Exception as e: print(e) elif all((item.startswith("#") and len(item) == 7) for item in colors): pass elif all((len(item) == 6) for item in colors): pass else: print("The legend colors must be a list of tuples.") return else: colors = [ "#8DD3C7", "#FFFFB3", "#BEBADA", "#FB8072", "#80B1D3", ] if len(labels) != len(colors): print("The legend keys and values must be the same length.") return allowed_builtin_legends = builtin_legends.keys() if builtin_legend is not None: if builtin_legend not in allowed_builtin_legends: print( "The builtin legend must be one of the following: {}".format( ", ".join(allowed_builtin_legends) ) ) return else: legend_dict = builtin_legends[builtin_legend] labels = list(legend_dict.keys()) colors = list(legend_dict.values()) if legend_dict is not None: if not isinstance(legend_dict, dict): print("The legend dict must be a dictionary.") return else: labels = list(legend_dict.keys()) colors = list(legend_dict.values()) if all(isinstance(item, tuple) for item in colors): try: colors = [rgb_to_hex(x) for x in colors] except Exception as e: print(e) allowed_positions = [ "topleft", "topright", "bottomleft", "bottomright", ] if position not in allowed_positions: raise ValueError( "The position must be one of the following: {}".format( ", ".join(allowed_positions) ) ) if position == "bottomright": if "bottom" not in style: style["bottom"] = "20px" if "right" not in style: style["right"] = "5px" if "left" in style: del style["left"] if "top" in style: del style["top"] elif position == "bottomleft": if "bottom" not in style: style["bottom"] = "5px" if "left" not in style: style["left"] = "5px" if "right" in style: del style["right"] if "top" in style: del style["top"] elif position == "topright": if "top" not in style: style["top"] = "5px" if "right" not in style: style["right"] = "5px" if "left" in style: del style["left"] if "bottom" in style: del style["bottom"] elif position == "topleft": if "top" not in style: style["top"] = "5px" if "left" not in style: style["left"] = "5px" if "right" in style: del style["right"] if "bottom" in style: del style["bottom"] if "position" not in style: style["position"] = "fixed" if "z-index" not in style: style["z-index"] = "9999" if "background-color" not in style: style["background-color"] = "rgba(255, 255, 255, 0.8)" if "padding" not in style: style["padding"] = "10px" if "border-radius" not in style: style["border-radius"] = "5px" if "font-size" not in style: style["font-size"] = "14px" content = [] with open(legend_template) as f: lines = f.readlines() if draggable: for index, line in enumerate(lines): if index < 36: content.append(line) elif index == 36: line = lines[index].replace("Legend", title) content.append(line) elif index < 39: content.append(line) elif index == 39: for i, color in enumerate(colors): item = f" <li><span style='background:{check_color(color)};opacity:{opacity};'></span>{labels[i]}</li>\n" content.append(item) elif index > 41: content.append(line) content = content[3:-1] else: for index, line in enumerate(lines): if index < 8: content.append(line) elif index == 8: for key, value in style.items(): content.append( " {}: {};\n".format(key.replace("_", "-"), value) ) elif index < 17: pass elif index < 19: content.append(line) elif index == 19: content.append(line.replace("Legend", title)) elif index < 22: content.append(line) elif index == 22: for index, key in enumerate(labels): color = colors[index] if not color.startswith("#"): color = "#" + color item = " <li><span style='background:{};opacity:{};'></span>{}</li>\n".format( color, opacity, key ) content.append(item) elif index < 33: pass else: content.append(line) legend_text = "".join(content) if output is not None: with open(output, "w") as f: f.write(legend_text) else: return legend_text
Create a legend in HTML format. Reference: https://bit.ly/3oV6vnH Args: title (str, optional): Title of the legend. Defaults to 'Legend'. Defaults to "Legend". colors (list, optional): A list of legend colors. Defaults to None. labels (list, optional): A list of legend labels. Defaults to None. legend_dict (dict, optional): A dictionary containing legend items as keys and color as values. If provided, legend_keys and legend_colors will be ignored. Defaults to None. builtin_legend (str, optional): Name of the builtin legend to add to the map. Defaults to None. opacity (float, optional): The opacity of the legend. Defaults to 1.0. position (str, optional): The position of the legend, can be one of the following: "topleft", "topright", "bottomleft", "bottomright". Defaults to "bottomright". draggable (bool, optional): If True, the legend can be dragged to a new position. Defaults to True. output (str, optional): The output file path (*.html) to save the legend. Defaults to None. style: Additional keyword arguments to style the legend, such as position, bottom, right, z-index, border, background-color, border-radius, padding, font-size, etc. The default style is: style = { 'position': 'fixed', 'z-index': '9999', 'border': '2px solid grey', 'background-color': 'rgba(255, 255, 255, 0.8)', 'border-radius': '5px', 'padding': '10px', 'font-size': '14px', 'bottom': '20px', 'right': '5px' } Returns: str: The HTML code of the legend.
12,408
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple def is_arcpy(): """Check if arcpy is available. Returns: book: True if arcpy is available, False otherwise. """ import sys if "arcpy" in sys.modules: return True else: return False def arc_active_map(): """Get the active map in ArcGIS Pro. Returns: arcpy.Map: The active map in ArcGIS Pro. """ if is_arcpy(): import arcpy aprx = arcpy.mp.ArcGISProject("CURRENT") m = aprx.activeMap return m else: return None The provided code snippet includes necessary dependencies for implementing the `arc_add_layer` function. Write a Python function `def arc_add_layer(url, name=None, shown=True, opacity=1.0)` to solve the following problem: Add a layer to the active map in ArcGIS Pro. Args: url (str): The URL of the tile layer to add. name (str, optional): The name of the layer. Defaults to None. shown (bool, optional): Whether the layer is shown. Defaults to True. opacity (float, optional): The opacity of the layer. Defaults to 1.0. Here is the function: def arc_add_layer(url, name=None, shown=True, opacity=1.0): """Add a layer to the active map in ArcGIS Pro. Args: url (str): The URL of the tile layer to add. name (str, optional): The name of the layer. Defaults to None. shown (bool, optional): Whether the layer is shown. Defaults to True. opacity (float, optional): The opacity of the layer. Defaults to 1.0. """ if is_arcpy(): m = arc_active_map() if m is not None: m.addDataFromPath(url) if isinstance(name, str): layers = m.listLayers("Tiled service layer") if len(layers) > 0: layer = layers[0] layer.name = name layer.visible = shown layer.transparency = 100 - (opacity * 100)
Add a layer to the active map in ArcGIS Pro. Args: url (str): The URL of the tile layer to add. name (str, optional): The name of the layer. Defaults to None. shown (bool, optional): Whether the layer is shown. Defaults to True. opacity (float, optional): The opacity of the layer. Defaults to 1.0.
12,409
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple def is_arcpy(): """Check if arcpy is available. Returns: book: True if arcpy is available, False otherwise. """ import sys if "arcpy" in sys.modules: return True else: return False def arc_active_view(): """Get the active view in ArcGIS Pro. Returns: arcpy.MapView: The active view in ArcGIS Pro. """ if is_arcpy(): import arcpy aprx = arcpy.mp.ArcGISProject("CURRENT") view = aprx.activeView return view else: return None The provided code snippet includes necessary dependencies for implementing the `arc_zoom_to_extent` function. Write a Python function `def arc_zoom_to_extent(xmin, ymin, xmax, ymax)` to solve the following problem: Zoom to an extent in ArcGIS Pro. Args: xmin (float): The minimum x value of the extent. ymin (float): The minimum y value of the extent. xmax (float): The maximum x value of the extent. ymax (float): The maximum y value of the extent. Here is the function: def arc_zoom_to_extent(xmin, ymin, xmax, ymax): """Zoom to an extent in ArcGIS Pro. Args: xmin (float): The minimum x value of the extent. ymin (float): The minimum y value of the extent. xmax (float): The maximum x value of the extent. ymax (float): The maximum y value of the extent. """ if is_arcpy(): import arcpy view = arc_active_view() if view is not None: view.camera.setExtent( arcpy.Extent( xmin, ymin, xmax, ymax, spatial_reference=arcpy.SpatialReference(4326), ) ) # if isinstance(zoom, int): # scale = 156543.04 * math.cos(0) / math.pow(2, zoom) # view.camera.scale = scale # Not working properly
Zoom to an extent in ArcGIS Pro. Args: xmin (float): The minimum x value of the extent. ymin (float): The minimum y value of the extent. xmax (float): The maximum x value of the extent. ymax (float): The maximum y value of the extent.
12,410
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple The provided code snippet includes necessary dependencies for implementing the `html_to_gradio` function. Write a Python function `def html_to_gradio(html, width="100%", height="500px", **kwargs)` to solve the following problem: Converts the map to an HTML string that can be used in Gradio. Removes unsupported elements, such as attribution and any code blocks containing functions. See https://github.com/gradio-app/gradio/issues/3190 Args: width (str, optional): The width of the map. Defaults to '100%'. height (str, optional): The height of the map. Defaults to '500px'. Returns: str: The HTML string to use in Gradio. Here is the function: def html_to_gradio(html, width="100%", height="500px", **kwargs): """Converts the map to an HTML string that can be used in Gradio. Removes unsupported elements, such as attribution and any code blocks containing functions. See https://github.com/gradio-app/gradio/issues/3190 Args: width (str, optional): The width of the map. Defaults to '100%'. height (str, optional): The height of the map. Defaults to '500px'. Returns: str: The HTML string to use in Gradio. """ if isinstance(width, int): width = f"{width}px" if isinstance(height, int): height = f"{height}px" if isinstance(html, str): with open(html, "r") as f: lines = f.readlines() elif isinstance(html, list): lines = html else: raise TypeError("html must be a file path or a list of strings") output = [] skipped_lines = [] for index, line in enumerate(lines): if index in skipped_lines: continue if line.lstrip().startswith('{"attribution":'): continue elif "on(L.Draw.Event.CREATED, function(e)" in line: for i in range(14): skipped_lines.append(index + i) elif "L.Control.geocoder" in line: for i in range(5): skipped_lines.append(index + i) elif "function(e)" in line: print( f"Warning: The folium plotting backend does not support functions in code blocks. Please delete line {index + 1}." ) else: output.append(line + "\n") return f"""<iframe style="width: {width}; height: {height}" name="result" allow="midi; geolocation; microphone; camera; display-capture; encrypted-media;" sandbox="allow-modals allow-forms allow-scripts allow-same-origin allow-popups allow-top-navigation-by-user-activation allow-downloads" allowfullscreen="" allowpaymentrequest="" frameborder="0" srcdoc='{"".join(output)}'></iframe>"""
Converts the map to an HTML string that can be used in Gradio. Removes unsupported elements, such as attribution and any code blocks containing functions. See https://github.com/gradio-app/gradio/issues/3190 Args: width (str, optional): The width of the map. Defaults to '100%'. height (str, optional): The height of the map. Defaults to '500px'. Returns: str: The HTML string to use in Gradio.
12,411
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple def get_local_tile_layer( source, port="default", debug=False, indexes=None, colormap=None, vmin=None, vmax=None, nodata=None, attribution=None, tile_format="ipyleaflet", layer_name="Local COG", return_client=False, quiet=False, **kwargs, ): """Generate an ipyleaflet/folium TileLayer from a local raster dataset or remote Cloud Optimized GeoTIFF (COG). If you are using this function in JupyterHub on a remote server and the raster does not render properly, try running the following two lines before calling this function: import os os.environ['LOCALTILESERVER_CLIENT_PREFIX'] = 'proxy/{port}' Args: source (str): The path to the GeoTIFF file or the URL of the Cloud Optimized GeoTIFF. port (str, optional): The port to use for the server. Defaults to "default". debug (bool, optional): If True, the server will be started in debug mode. Defaults to False. indexes (int, optional): The band(s) to use. Band indexing starts at 1. Defaults to None. colormap (str, optional): The name of the colormap from `matplotlib` to use when plotting a single band. See https://matplotlib.org/stable/gallery/color/colormap_reference.html. Default is greyscale. vmin (float, optional): The minimum value to use when colormapping the colormap when plotting a single band. Defaults to None. vmax (float, optional): The maximum value to use when colormapping the colormap when plotting a single band. Defaults to None. nodata (float, optional): The value from the band to use to interpret as not valid data. Defaults to None. attribution (str, optional): Attribution for the source raster. This defaults to a message about it being a local file.. Defaults to None. tile_format (str, optional): The tile layer format. Can be either ipyleaflet or folium. Defaults to "ipyleaflet". layer_name (str, optional): The layer name to use. Defaults to None. return_client (bool, optional): If True, the tile client will be returned. Defaults to False. quiet (bool, optional): If True, the error messages will be suppressed. Defaults to False. Returns: ipyleaflet.TileLayer | folium.TileLayer: An ipyleaflet.TileLayer or folium.TileLayer. """ import rasterio check_package( "localtileserver", URL="https://github.com/banesullivan/localtileserver" ) # Handle legacy localtileserver kwargs if "cmap" in kwargs: warnings.warn( "`cmap` is a deprecated keyword argument for get_local_tile_layer. Please use `colormap`." ) if "palette" in kwargs: warnings.warn( "`palette` is a deprecated keyword argument for get_local_tile_layer. Please use `colormap`." ) if "band" in kwargs or "bands" in kwargs: warnings.warn( "`band` and `bands` are deprecated keyword arguments for get_local_tile_layer. Please use `indexes`." ) if "projection" in kwargs: warnings.warn( "`projection` is a deprecated keyword argument for get_local_tile_layer and will be ignored." ) if "style" in kwargs: warnings.warn( "`style` is a deprecated keyword argument for get_local_tile_layer and will be ignored." ) if "max_zoom" not in kwargs: kwargs["max_zoom"] = 30 if "max_native_zoom" not in kwargs: kwargs["max_native_zoom"] = 30 if "cmap" in kwargs: colormap = kwargs.pop("cmap") if "palette" in kwargs: colormap = kwargs.pop("palette") if "band" in kwargs: indexes = kwargs.pop("band") if "bands" in kwargs: indexes = kwargs.pop("bands") # Make it compatible with binder and JupyterHub if os.environ.get("JUPYTERHUB_SERVICE_PREFIX") is not None: os.environ["LOCALTILESERVER_CLIENT_PREFIX"] = ( f"{os.environ['JUPYTERHUB_SERVICE_PREFIX'].lstrip('/')}/proxy/{{port}}" ) if is_studio_lab(): os.environ["LOCALTILESERVER_CLIENT_PREFIX"] = ( f"studiolab/default/jupyter/proxy/{{port}}" ) elif is_on_aws(): os.environ["LOCALTILESERVER_CLIENT_PREFIX"] = "proxy/{port}" elif "prefix" in kwargs: os.environ["LOCALTILESERVER_CLIENT_PREFIX"] = kwargs["prefix"] kwargs.pop("prefix") from localtileserver import ( get_leaflet_tile_layer, get_folium_tile_layer, TileClient, ) # if "show_loading" not in kwargs: # kwargs["show_loading"] = False if isinstance(source, str): if not source.startswith("http"): if source.startswith("~"): source = os.path.expanduser(source) # else: # source = os.path.abspath(source) # if not os.path.exists(source): # raise ValueError("The source path does not exist.") else: source = github_raw_url(source) elif isinstance(source, TileClient) or isinstance( source, rasterio.io.DatasetReader ): pass else: raise ValueError("The source must either be a string or TileClient") if tile_format not in ["ipyleaflet", "folium"]: raise ValueError("The tile format must be either ipyleaflet or folium.") if layer_name is None: if source.startswith("http"): layer_name = "RemoteTile_" + random_string(3) else: layer_name = "LocalTile_" + random_string(3) if isinstance(source, str) or isinstance(source, rasterio.io.DatasetReader): tile_client = TileClient(source, port=port, debug=debug) else: tile_client = source if quiet: output = widgets.Output() with output: if tile_format == "ipyleaflet": tile_layer = get_leaflet_tile_layer( tile_client, port=port, debug=debug, indexes=indexes, colormap=colormap, vmin=vmin, vmax=vmax, nodata=nodata, attribution=attribution, name=layer_name, **kwargs, ) else: tile_layer = get_folium_tile_layer( tile_client, port=port, debug=debug, indexes=indexes, colormap=colormap, vmin=vmin, vmax=vmax, nodata=nodata, attr=attribution, overlay=True, name=layer_name, **kwargs, ) else: if tile_format == "ipyleaflet": tile_layer = get_leaflet_tile_layer( tile_client, port=port, debug=debug, indexes=indexes, colormap=colormap, vmin=vmin, vmax=vmax, nodata=nodata, attribution=attribution, name=layer_name, **kwargs, ) else: tile_layer = get_folium_tile_layer( tile_client, port=port, debug=debug, indexes=indexes, colormap=colormap, vmin=vmin, vmax=vmax, nodata=nodata, attr=attribution, overlay=True, name=layer_name, **kwargs, ) if return_client: return tile_layer, tile_client else: return tile_layer # center = tile_client.center() # bounds = tile_client.bounds() # [ymin, ymax, xmin, xmax] # bounds = (bounds[2], bounds[0], bounds[3], bounds[1]) # [minx, miny, maxx, maxy] # if get_center and get_bounds: # return tile_layer, center, bounds # elif get_center: # return tile_layer, center # elif get_bounds: # return tile_layer, bounds # else: # return tile_layer def image_check(image): from localtileserver import TileClient if isinstance(image, str): if image.startswith("http") or os.path.exists(image): pass else: raise ValueError("image must be a URL or filepath.") elif isinstance(image, TileClient): pass else: raise ValueError("image must be a URL or filepath.") The provided code snippet includes necessary dependencies for implementing the `image_client` function. Write a Python function `def image_client(image, **kwargs)` to solve the following problem: Get a LocalTileserver TileClient from an image. Args: image (str): The input image filepath or URL. Returns: TileClient: A LocalTileserver TileClient. Here is the function: def image_client(image, **kwargs): """Get a LocalTileserver TileClient from an image. Args: image (str): The input image filepath or URL. Returns: TileClient: A LocalTileserver TileClient. """ image_check(image) _, client = get_local_tile_layer(image, return_client=True, **kwargs) return client
Get a LocalTileserver TileClient from an image. Args: image (str): The input image filepath or URL. Returns: TileClient: A LocalTileserver TileClient.
12,412
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple def get_local_tile_layer( source, port="default", debug=False, indexes=None, colormap=None, vmin=None, vmax=None, nodata=None, attribution=None, tile_format="ipyleaflet", layer_name="Local COG", return_client=False, quiet=False, **kwargs, ): """Generate an ipyleaflet/folium TileLayer from a local raster dataset or remote Cloud Optimized GeoTIFF (COG). If you are using this function in JupyterHub on a remote server and the raster does not render properly, try running the following two lines before calling this function: import os os.environ['LOCALTILESERVER_CLIENT_PREFIX'] = 'proxy/{port}' Args: source (str): The path to the GeoTIFF file or the URL of the Cloud Optimized GeoTIFF. port (str, optional): The port to use for the server. Defaults to "default". debug (bool, optional): If True, the server will be started in debug mode. Defaults to False. indexes (int, optional): The band(s) to use. Band indexing starts at 1. Defaults to None. colormap (str, optional): The name of the colormap from `matplotlib` to use when plotting a single band. See https://matplotlib.org/stable/gallery/color/colormap_reference.html. Default is greyscale. vmin (float, optional): The minimum value to use when colormapping the colormap when plotting a single band. Defaults to None. vmax (float, optional): The maximum value to use when colormapping the colormap when plotting a single band. Defaults to None. nodata (float, optional): The value from the band to use to interpret as not valid data. Defaults to None. attribution (str, optional): Attribution for the source raster. This defaults to a message about it being a local file.. Defaults to None. tile_format (str, optional): The tile layer format. Can be either ipyleaflet or folium. Defaults to "ipyleaflet". layer_name (str, optional): The layer name to use. Defaults to None. return_client (bool, optional): If True, the tile client will be returned. Defaults to False. quiet (bool, optional): If True, the error messages will be suppressed. Defaults to False. Returns: ipyleaflet.TileLayer | folium.TileLayer: An ipyleaflet.TileLayer or folium.TileLayer. """ import rasterio check_package( "localtileserver", URL="https://github.com/banesullivan/localtileserver" ) # Handle legacy localtileserver kwargs if "cmap" in kwargs: warnings.warn( "`cmap` is a deprecated keyword argument for get_local_tile_layer. Please use `colormap`." ) if "palette" in kwargs: warnings.warn( "`palette` is a deprecated keyword argument for get_local_tile_layer. Please use `colormap`." ) if "band" in kwargs or "bands" in kwargs: warnings.warn( "`band` and `bands` are deprecated keyword arguments for get_local_tile_layer. Please use `indexes`." ) if "projection" in kwargs: warnings.warn( "`projection` is a deprecated keyword argument for get_local_tile_layer and will be ignored." ) if "style" in kwargs: warnings.warn( "`style` is a deprecated keyword argument for get_local_tile_layer and will be ignored." ) if "max_zoom" not in kwargs: kwargs["max_zoom"] = 30 if "max_native_zoom" not in kwargs: kwargs["max_native_zoom"] = 30 if "cmap" in kwargs: colormap = kwargs.pop("cmap") if "palette" in kwargs: colormap = kwargs.pop("palette") if "band" in kwargs: indexes = kwargs.pop("band") if "bands" in kwargs: indexes = kwargs.pop("bands") # Make it compatible with binder and JupyterHub if os.environ.get("JUPYTERHUB_SERVICE_PREFIX") is not None: os.environ["LOCALTILESERVER_CLIENT_PREFIX"] = ( f"{os.environ['JUPYTERHUB_SERVICE_PREFIX'].lstrip('/')}/proxy/{{port}}" ) if is_studio_lab(): os.environ["LOCALTILESERVER_CLIENT_PREFIX"] = ( f"studiolab/default/jupyter/proxy/{{port}}" ) elif is_on_aws(): os.environ["LOCALTILESERVER_CLIENT_PREFIX"] = "proxy/{port}" elif "prefix" in kwargs: os.environ["LOCALTILESERVER_CLIENT_PREFIX"] = kwargs["prefix"] kwargs.pop("prefix") from localtileserver import ( get_leaflet_tile_layer, get_folium_tile_layer, TileClient, ) # if "show_loading" not in kwargs: # kwargs["show_loading"] = False if isinstance(source, str): if not source.startswith("http"): if source.startswith("~"): source = os.path.expanduser(source) # else: # source = os.path.abspath(source) # if not os.path.exists(source): # raise ValueError("The source path does not exist.") else: source = github_raw_url(source) elif isinstance(source, TileClient) or isinstance( source, rasterio.io.DatasetReader ): pass else: raise ValueError("The source must either be a string or TileClient") if tile_format not in ["ipyleaflet", "folium"]: raise ValueError("The tile format must be either ipyleaflet or folium.") if layer_name is None: if source.startswith("http"): layer_name = "RemoteTile_" + random_string(3) else: layer_name = "LocalTile_" + random_string(3) if isinstance(source, str) or isinstance(source, rasterio.io.DatasetReader): tile_client = TileClient(source, port=port, debug=debug) else: tile_client = source if quiet: output = widgets.Output() with output: if tile_format == "ipyleaflet": tile_layer = get_leaflet_tile_layer( tile_client, port=port, debug=debug, indexes=indexes, colormap=colormap, vmin=vmin, vmax=vmax, nodata=nodata, attribution=attribution, name=layer_name, **kwargs, ) else: tile_layer = get_folium_tile_layer( tile_client, port=port, debug=debug, indexes=indexes, colormap=colormap, vmin=vmin, vmax=vmax, nodata=nodata, attr=attribution, overlay=True, name=layer_name, **kwargs, ) else: if tile_format == "ipyleaflet": tile_layer = get_leaflet_tile_layer( tile_client, port=port, debug=debug, indexes=indexes, colormap=colormap, vmin=vmin, vmax=vmax, nodata=nodata, attribution=attribution, name=layer_name, **kwargs, ) else: tile_layer = get_folium_tile_layer( tile_client, port=port, debug=debug, indexes=indexes, colormap=colormap, vmin=vmin, vmax=vmax, nodata=nodata, attr=attribution, overlay=True, name=layer_name, **kwargs, ) if return_client: return tile_layer, tile_client else: return tile_layer # center = tile_client.center() # bounds = tile_client.bounds() # [ymin, ymax, xmin, xmax] # bounds = (bounds[2], bounds[0], bounds[3], bounds[1]) # [minx, miny, maxx, maxy] # if get_center and get_bounds: # return tile_layer, center, bounds # elif get_center: # return tile_layer, center # elif get_bounds: # return tile_layer, bounds # else: # return tile_layer def image_check(image): from localtileserver import TileClient if isinstance(image, str): if image.startswith("http") or os.path.exists(image): pass else: raise ValueError("image must be a URL or filepath.") elif isinstance(image, TileClient): pass else: raise ValueError("image must be a URL or filepath.") The provided code snippet includes necessary dependencies for implementing the `image_center` function. Write a Python function `def image_center(image, **kwargs)` to solve the following problem: Get the center of an image. Args: image (str): The input image filepath or URL. Returns: tuple: A tuple of (latitude, longitude). Here is the function: def image_center(image, **kwargs): """Get the center of an image. Args: image (str): The input image filepath or URL. Returns: tuple: A tuple of (latitude, longitude). """ image_check(image) if isinstance(image, str): _, client = get_local_tile_layer(image, return_client=True, **kwargs) else: client = image return client.center()
Get the center of an image. Args: image (str): The input image filepath or URL. Returns: tuple: A tuple of (latitude, longitude).
12,413
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple def get_local_tile_layer( source, port="default", debug=False, indexes=None, colormap=None, vmin=None, vmax=None, nodata=None, attribution=None, tile_format="ipyleaflet", layer_name="Local COG", return_client=False, quiet=False, **kwargs, ): """Generate an ipyleaflet/folium TileLayer from a local raster dataset or remote Cloud Optimized GeoTIFF (COG). If you are using this function in JupyterHub on a remote server and the raster does not render properly, try running the following two lines before calling this function: import os os.environ['LOCALTILESERVER_CLIENT_PREFIX'] = 'proxy/{port}' Args: source (str): The path to the GeoTIFF file or the URL of the Cloud Optimized GeoTIFF. port (str, optional): The port to use for the server. Defaults to "default". debug (bool, optional): If True, the server will be started in debug mode. Defaults to False. indexes (int, optional): The band(s) to use. Band indexing starts at 1. Defaults to None. colormap (str, optional): The name of the colormap from `matplotlib` to use when plotting a single band. See https://matplotlib.org/stable/gallery/color/colormap_reference.html. Default is greyscale. vmin (float, optional): The minimum value to use when colormapping the colormap when plotting a single band. Defaults to None. vmax (float, optional): The maximum value to use when colormapping the colormap when plotting a single band. Defaults to None. nodata (float, optional): The value from the band to use to interpret as not valid data. Defaults to None. attribution (str, optional): Attribution for the source raster. This defaults to a message about it being a local file.. Defaults to None. tile_format (str, optional): The tile layer format. Can be either ipyleaflet or folium. Defaults to "ipyleaflet". layer_name (str, optional): The layer name to use. Defaults to None. return_client (bool, optional): If True, the tile client will be returned. Defaults to False. quiet (bool, optional): If True, the error messages will be suppressed. Defaults to False. Returns: ipyleaflet.TileLayer | folium.TileLayer: An ipyleaflet.TileLayer or folium.TileLayer. """ import rasterio check_package( "localtileserver", URL="https://github.com/banesullivan/localtileserver" ) # Handle legacy localtileserver kwargs if "cmap" in kwargs: warnings.warn( "`cmap` is a deprecated keyword argument for get_local_tile_layer. Please use `colormap`." ) if "palette" in kwargs: warnings.warn( "`palette` is a deprecated keyword argument for get_local_tile_layer. Please use `colormap`." ) if "band" in kwargs or "bands" in kwargs: warnings.warn( "`band` and `bands` are deprecated keyword arguments for get_local_tile_layer. Please use `indexes`." ) if "projection" in kwargs: warnings.warn( "`projection` is a deprecated keyword argument for get_local_tile_layer and will be ignored." ) if "style" in kwargs: warnings.warn( "`style` is a deprecated keyword argument for get_local_tile_layer and will be ignored." ) if "max_zoom" not in kwargs: kwargs["max_zoom"] = 30 if "max_native_zoom" not in kwargs: kwargs["max_native_zoom"] = 30 if "cmap" in kwargs: colormap = kwargs.pop("cmap") if "palette" in kwargs: colormap = kwargs.pop("palette") if "band" in kwargs: indexes = kwargs.pop("band") if "bands" in kwargs: indexes = kwargs.pop("bands") # Make it compatible with binder and JupyterHub if os.environ.get("JUPYTERHUB_SERVICE_PREFIX") is not None: os.environ["LOCALTILESERVER_CLIENT_PREFIX"] = ( f"{os.environ['JUPYTERHUB_SERVICE_PREFIX'].lstrip('/')}/proxy/{{port}}" ) if is_studio_lab(): os.environ["LOCALTILESERVER_CLIENT_PREFIX"] = ( f"studiolab/default/jupyter/proxy/{{port}}" ) elif is_on_aws(): os.environ["LOCALTILESERVER_CLIENT_PREFIX"] = "proxy/{port}" elif "prefix" in kwargs: os.environ["LOCALTILESERVER_CLIENT_PREFIX"] = kwargs["prefix"] kwargs.pop("prefix") from localtileserver import ( get_leaflet_tile_layer, get_folium_tile_layer, TileClient, ) # if "show_loading" not in kwargs: # kwargs["show_loading"] = False if isinstance(source, str): if not source.startswith("http"): if source.startswith("~"): source = os.path.expanduser(source) # else: # source = os.path.abspath(source) # if not os.path.exists(source): # raise ValueError("The source path does not exist.") else: source = github_raw_url(source) elif isinstance(source, TileClient) or isinstance( source, rasterio.io.DatasetReader ): pass else: raise ValueError("The source must either be a string or TileClient") if tile_format not in ["ipyleaflet", "folium"]: raise ValueError("The tile format must be either ipyleaflet or folium.") if layer_name is None: if source.startswith("http"): layer_name = "RemoteTile_" + random_string(3) else: layer_name = "LocalTile_" + random_string(3) if isinstance(source, str) or isinstance(source, rasterio.io.DatasetReader): tile_client = TileClient(source, port=port, debug=debug) else: tile_client = source if quiet: output = widgets.Output() with output: if tile_format == "ipyleaflet": tile_layer = get_leaflet_tile_layer( tile_client, port=port, debug=debug, indexes=indexes, colormap=colormap, vmin=vmin, vmax=vmax, nodata=nodata, attribution=attribution, name=layer_name, **kwargs, ) else: tile_layer = get_folium_tile_layer( tile_client, port=port, debug=debug, indexes=indexes, colormap=colormap, vmin=vmin, vmax=vmax, nodata=nodata, attr=attribution, overlay=True, name=layer_name, **kwargs, ) else: if tile_format == "ipyleaflet": tile_layer = get_leaflet_tile_layer( tile_client, port=port, debug=debug, indexes=indexes, colormap=colormap, vmin=vmin, vmax=vmax, nodata=nodata, attribution=attribution, name=layer_name, **kwargs, ) else: tile_layer = get_folium_tile_layer( tile_client, port=port, debug=debug, indexes=indexes, colormap=colormap, vmin=vmin, vmax=vmax, nodata=nodata, attr=attribution, overlay=True, name=layer_name, **kwargs, ) if return_client: return tile_layer, tile_client else: return tile_layer # center = tile_client.center() # bounds = tile_client.bounds() # [ymin, ymax, xmin, xmax] # bounds = (bounds[2], bounds[0], bounds[3], bounds[1]) # [minx, miny, maxx, maxy] # if get_center and get_bounds: # return tile_layer, center, bounds # elif get_center: # return tile_layer, center # elif get_bounds: # return tile_layer, bounds # else: # return tile_layer def image_check(image): from localtileserver import TileClient if isinstance(image, str): if image.startswith("http") or os.path.exists(image): pass else: raise ValueError("image must be a URL or filepath.") elif isinstance(image, TileClient): pass else: raise ValueError("image must be a URL or filepath.") The provided code snippet includes necessary dependencies for implementing the `image_bounds` function. Write a Python function `def image_bounds(image, **kwargs)` to solve the following problem: Get the bounds of an image. Args: image (str): The input image filepath or URL. Returns: list: A list of bounds in the form of [(south, west), (north, east)]. Here is the function: def image_bounds(image, **kwargs): """Get the bounds of an image. Args: image (str): The input image filepath or URL. Returns: list: A list of bounds in the form of [(south, west), (north, east)]. """ image_check(image) if isinstance(image, str): _, client = get_local_tile_layer(image, return_client=True, **kwargs) else: client = image bounds = client.bounds() return [(bounds[0], bounds[2]), (bounds[1], bounds[3])]
Get the bounds of an image. Args: image (str): The input image filepath or URL. Returns: list: A list of bounds in the form of [(south, west), (north, east)].
12,414
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple def get_local_tile_layer( source, port="default", debug=False, indexes=None, colormap=None, vmin=None, vmax=None, nodata=None, attribution=None, tile_format="ipyleaflet", layer_name="Local COG", return_client=False, quiet=False, **kwargs, ): """Generate an ipyleaflet/folium TileLayer from a local raster dataset or remote Cloud Optimized GeoTIFF (COG). If you are using this function in JupyterHub on a remote server and the raster does not render properly, try running the following two lines before calling this function: import os os.environ['LOCALTILESERVER_CLIENT_PREFIX'] = 'proxy/{port}' Args: source (str): The path to the GeoTIFF file or the URL of the Cloud Optimized GeoTIFF. port (str, optional): The port to use for the server. Defaults to "default". debug (bool, optional): If True, the server will be started in debug mode. Defaults to False. indexes (int, optional): The band(s) to use. Band indexing starts at 1. Defaults to None. colormap (str, optional): The name of the colormap from `matplotlib` to use when plotting a single band. See https://matplotlib.org/stable/gallery/color/colormap_reference.html. Default is greyscale. vmin (float, optional): The minimum value to use when colormapping the colormap when plotting a single band. Defaults to None. vmax (float, optional): The maximum value to use when colormapping the colormap when plotting a single band. Defaults to None. nodata (float, optional): The value from the band to use to interpret as not valid data. Defaults to None. attribution (str, optional): Attribution for the source raster. This defaults to a message about it being a local file.. Defaults to None. tile_format (str, optional): The tile layer format. Can be either ipyleaflet or folium. Defaults to "ipyleaflet". layer_name (str, optional): The layer name to use. Defaults to None. return_client (bool, optional): If True, the tile client will be returned. Defaults to False. quiet (bool, optional): If True, the error messages will be suppressed. Defaults to False. Returns: ipyleaflet.TileLayer | folium.TileLayer: An ipyleaflet.TileLayer or folium.TileLayer. """ import rasterio check_package( "localtileserver", URL="https://github.com/banesullivan/localtileserver" ) # Handle legacy localtileserver kwargs if "cmap" in kwargs: warnings.warn( "`cmap` is a deprecated keyword argument for get_local_tile_layer. Please use `colormap`." ) if "palette" in kwargs: warnings.warn( "`palette` is a deprecated keyword argument for get_local_tile_layer. Please use `colormap`." ) if "band" in kwargs or "bands" in kwargs: warnings.warn( "`band` and `bands` are deprecated keyword arguments for get_local_tile_layer. Please use `indexes`." ) if "projection" in kwargs: warnings.warn( "`projection` is a deprecated keyword argument for get_local_tile_layer and will be ignored." ) if "style" in kwargs: warnings.warn( "`style` is a deprecated keyword argument for get_local_tile_layer and will be ignored." ) if "max_zoom" not in kwargs: kwargs["max_zoom"] = 30 if "max_native_zoom" not in kwargs: kwargs["max_native_zoom"] = 30 if "cmap" in kwargs: colormap = kwargs.pop("cmap") if "palette" in kwargs: colormap = kwargs.pop("palette") if "band" in kwargs: indexes = kwargs.pop("band") if "bands" in kwargs: indexes = kwargs.pop("bands") # Make it compatible with binder and JupyterHub if os.environ.get("JUPYTERHUB_SERVICE_PREFIX") is not None: os.environ["LOCALTILESERVER_CLIENT_PREFIX"] = ( f"{os.environ['JUPYTERHUB_SERVICE_PREFIX'].lstrip('/')}/proxy/{{port}}" ) if is_studio_lab(): os.environ["LOCALTILESERVER_CLIENT_PREFIX"] = ( f"studiolab/default/jupyter/proxy/{{port}}" ) elif is_on_aws(): os.environ["LOCALTILESERVER_CLIENT_PREFIX"] = "proxy/{port}" elif "prefix" in kwargs: os.environ["LOCALTILESERVER_CLIENT_PREFIX"] = kwargs["prefix"] kwargs.pop("prefix") from localtileserver import ( get_leaflet_tile_layer, get_folium_tile_layer, TileClient, ) # if "show_loading" not in kwargs: # kwargs["show_loading"] = False if isinstance(source, str): if not source.startswith("http"): if source.startswith("~"): source = os.path.expanduser(source) # else: # source = os.path.abspath(source) # if not os.path.exists(source): # raise ValueError("The source path does not exist.") else: source = github_raw_url(source) elif isinstance(source, TileClient) or isinstance( source, rasterio.io.DatasetReader ): pass else: raise ValueError("The source must either be a string or TileClient") if tile_format not in ["ipyleaflet", "folium"]: raise ValueError("The tile format must be either ipyleaflet or folium.") if layer_name is None: if source.startswith("http"): layer_name = "RemoteTile_" + random_string(3) else: layer_name = "LocalTile_" + random_string(3) if isinstance(source, str) or isinstance(source, rasterio.io.DatasetReader): tile_client = TileClient(source, port=port, debug=debug) else: tile_client = source if quiet: output = widgets.Output() with output: if tile_format == "ipyleaflet": tile_layer = get_leaflet_tile_layer( tile_client, port=port, debug=debug, indexes=indexes, colormap=colormap, vmin=vmin, vmax=vmax, nodata=nodata, attribution=attribution, name=layer_name, **kwargs, ) else: tile_layer = get_folium_tile_layer( tile_client, port=port, debug=debug, indexes=indexes, colormap=colormap, vmin=vmin, vmax=vmax, nodata=nodata, attr=attribution, overlay=True, name=layer_name, **kwargs, ) else: if tile_format == "ipyleaflet": tile_layer = get_leaflet_tile_layer( tile_client, port=port, debug=debug, indexes=indexes, colormap=colormap, vmin=vmin, vmax=vmax, nodata=nodata, attribution=attribution, name=layer_name, **kwargs, ) else: tile_layer = get_folium_tile_layer( tile_client, port=port, debug=debug, indexes=indexes, colormap=colormap, vmin=vmin, vmax=vmax, nodata=nodata, attr=attribution, overlay=True, name=layer_name, **kwargs, ) if return_client: return tile_layer, tile_client else: return tile_layer # center = tile_client.center() # bounds = tile_client.bounds() # [ymin, ymax, xmin, xmax] # bounds = (bounds[2], bounds[0], bounds[3], bounds[1]) # [minx, miny, maxx, maxy] # if get_center and get_bounds: # return tile_layer, center, bounds # elif get_center: # return tile_layer, center # elif get_bounds: # return tile_layer, bounds # else: # return tile_layer def image_check(image): from localtileserver import TileClient if isinstance(image, str): if image.startswith("http") or os.path.exists(image): pass else: raise ValueError("image must be a URL or filepath.") elif isinstance(image, TileClient): pass else: raise ValueError("image must be a URL or filepath.") The provided code snippet includes necessary dependencies for implementing the `image_metadata` function. Write a Python function `def image_metadata(image, **kwargs)` to solve the following problem: Get the metadata of an image. Args: image (str): The input image filepath or URL. Returns: dict: A dictionary of image metadata. Here is the function: def image_metadata(image, **kwargs): """Get the metadata of an image. Args: image (str): The input image filepath or URL. Returns: dict: A dictionary of image metadata. """ image_check(image) if isinstance(image, str): _, client = get_local_tile_layer(image, return_client=True, **kwargs) else: client = image return client.metadata()
Get the metadata of an image. Args: image (str): The input image filepath or URL. Returns: dict: A dictionary of image metadata.
12,415
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple def get_local_tile_layer( source, port="default", debug=False, indexes=None, colormap=None, vmin=None, vmax=None, nodata=None, attribution=None, tile_format="ipyleaflet", layer_name="Local COG", return_client=False, quiet=False, **kwargs, ): """Generate an ipyleaflet/folium TileLayer from a local raster dataset or remote Cloud Optimized GeoTIFF (COG). If you are using this function in JupyterHub on a remote server and the raster does not render properly, try running the following two lines before calling this function: import os os.environ['LOCALTILESERVER_CLIENT_PREFIX'] = 'proxy/{port}' Args: source (str): The path to the GeoTIFF file or the URL of the Cloud Optimized GeoTIFF. port (str, optional): The port to use for the server. Defaults to "default". debug (bool, optional): If True, the server will be started in debug mode. Defaults to False. indexes (int, optional): The band(s) to use. Band indexing starts at 1. Defaults to None. colormap (str, optional): The name of the colormap from `matplotlib` to use when plotting a single band. See https://matplotlib.org/stable/gallery/color/colormap_reference.html. Default is greyscale. vmin (float, optional): The minimum value to use when colormapping the colormap when plotting a single band. Defaults to None. vmax (float, optional): The maximum value to use when colormapping the colormap when plotting a single band. Defaults to None. nodata (float, optional): The value from the band to use to interpret as not valid data. Defaults to None. attribution (str, optional): Attribution for the source raster. This defaults to a message about it being a local file.. Defaults to None. tile_format (str, optional): The tile layer format. Can be either ipyleaflet or folium. Defaults to "ipyleaflet". layer_name (str, optional): The layer name to use. Defaults to None. return_client (bool, optional): If True, the tile client will be returned. Defaults to False. quiet (bool, optional): If True, the error messages will be suppressed. Defaults to False. Returns: ipyleaflet.TileLayer | folium.TileLayer: An ipyleaflet.TileLayer or folium.TileLayer. """ import rasterio check_package( "localtileserver", URL="https://github.com/banesullivan/localtileserver" ) # Handle legacy localtileserver kwargs if "cmap" in kwargs: warnings.warn( "`cmap` is a deprecated keyword argument for get_local_tile_layer. Please use `colormap`." ) if "palette" in kwargs: warnings.warn( "`palette` is a deprecated keyword argument for get_local_tile_layer. Please use `colormap`." ) if "band" in kwargs or "bands" in kwargs: warnings.warn( "`band` and `bands` are deprecated keyword arguments for get_local_tile_layer. Please use `indexes`." ) if "projection" in kwargs: warnings.warn( "`projection` is a deprecated keyword argument for get_local_tile_layer and will be ignored." ) if "style" in kwargs: warnings.warn( "`style` is a deprecated keyword argument for get_local_tile_layer and will be ignored." ) if "max_zoom" not in kwargs: kwargs["max_zoom"] = 30 if "max_native_zoom" not in kwargs: kwargs["max_native_zoom"] = 30 if "cmap" in kwargs: colormap = kwargs.pop("cmap") if "palette" in kwargs: colormap = kwargs.pop("palette") if "band" in kwargs: indexes = kwargs.pop("band") if "bands" in kwargs: indexes = kwargs.pop("bands") # Make it compatible with binder and JupyterHub if os.environ.get("JUPYTERHUB_SERVICE_PREFIX") is not None: os.environ["LOCALTILESERVER_CLIENT_PREFIX"] = ( f"{os.environ['JUPYTERHUB_SERVICE_PREFIX'].lstrip('/')}/proxy/{{port}}" ) if is_studio_lab(): os.environ["LOCALTILESERVER_CLIENT_PREFIX"] = ( f"studiolab/default/jupyter/proxy/{{port}}" ) elif is_on_aws(): os.environ["LOCALTILESERVER_CLIENT_PREFIX"] = "proxy/{port}" elif "prefix" in kwargs: os.environ["LOCALTILESERVER_CLIENT_PREFIX"] = kwargs["prefix"] kwargs.pop("prefix") from localtileserver import ( get_leaflet_tile_layer, get_folium_tile_layer, TileClient, ) # if "show_loading" not in kwargs: # kwargs["show_loading"] = False if isinstance(source, str): if not source.startswith("http"): if source.startswith("~"): source = os.path.expanduser(source) # else: # source = os.path.abspath(source) # if not os.path.exists(source): # raise ValueError("The source path does not exist.") else: source = github_raw_url(source) elif isinstance(source, TileClient) or isinstance( source, rasterio.io.DatasetReader ): pass else: raise ValueError("The source must either be a string or TileClient") if tile_format not in ["ipyleaflet", "folium"]: raise ValueError("The tile format must be either ipyleaflet or folium.") if layer_name is None: if source.startswith("http"): layer_name = "RemoteTile_" + random_string(3) else: layer_name = "LocalTile_" + random_string(3) if isinstance(source, str) or isinstance(source, rasterio.io.DatasetReader): tile_client = TileClient(source, port=port, debug=debug) else: tile_client = source if quiet: output = widgets.Output() with output: if tile_format == "ipyleaflet": tile_layer = get_leaflet_tile_layer( tile_client, port=port, debug=debug, indexes=indexes, colormap=colormap, vmin=vmin, vmax=vmax, nodata=nodata, attribution=attribution, name=layer_name, **kwargs, ) else: tile_layer = get_folium_tile_layer( tile_client, port=port, debug=debug, indexes=indexes, colormap=colormap, vmin=vmin, vmax=vmax, nodata=nodata, attr=attribution, overlay=True, name=layer_name, **kwargs, ) else: if tile_format == "ipyleaflet": tile_layer = get_leaflet_tile_layer( tile_client, port=port, debug=debug, indexes=indexes, colormap=colormap, vmin=vmin, vmax=vmax, nodata=nodata, attribution=attribution, name=layer_name, **kwargs, ) else: tile_layer = get_folium_tile_layer( tile_client, port=port, debug=debug, indexes=indexes, colormap=colormap, vmin=vmin, vmax=vmax, nodata=nodata, attr=attribution, overlay=True, name=layer_name, **kwargs, ) if return_client: return tile_layer, tile_client else: return tile_layer # center = tile_client.center() # bounds = tile_client.bounds() # [ymin, ymax, xmin, xmax] # bounds = (bounds[2], bounds[0], bounds[3], bounds[1]) # [minx, miny, maxx, maxy] # if get_center and get_bounds: # return tile_layer, center, bounds # elif get_center: # return tile_layer, center # elif get_bounds: # return tile_layer, bounds # else: # return tile_layer def image_check(image): from localtileserver import TileClient if isinstance(image, str): if image.startswith("http") or os.path.exists(image): pass else: raise ValueError("image must be a URL or filepath.") elif isinstance(image, TileClient): pass else: raise ValueError("image must be a URL or filepath.") The provided code snippet includes necessary dependencies for implementing the `image_bandcount` function. Write a Python function `def image_bandcount(image, **kwargs)` to solve the following problem: Get the number of bands in an image. Args: image (str): The input image filepath or URL. Returns: int: The number of bands in the image. Here is the function: def image_bandcount(image, **kwargs): """Get the number of bands in an image. Args: image (str): The input image filepath or URL. Returns: int: The number of bands in the image. """ image_check(image) if isinstance(image, str): _, client = get_local_tile_layer(image, return_client=True, **kwargs) else: client = image return len(client.metadata()["bands"])
Get the number of bands in an image. Args: image (str): The input image filepath or URL. Returns: int: The number of bands in the image.
12,416
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple def get_local_tile_layer( source, port="default", debug=False, indexes=None, colormap=None, vmin=None, vmax=None, nodata=None, attribution=None, tile_format="ipyleaflet", layer_name="Local COG", return_client=False, quiet=False, **kwargs, ): """Generate an ipyleaflet/folium TileLayer from a local raster dataset or remote Cloud Optimized GeoTIFF (COG). If you are using this function in JupyterHub on a remote server and the raster does not render properly, try running the following two lines before calling this function: import os os.environ['LOCALTILESERVER_CLIENT_PREFIX'] = 'proxy/{port}' Args: source (str): The path to the GeoTIFF file or the URL of the Cloud Optimized GeoTIFF. port (str, optional): The port to use for the server. Defaults to "default". debug (bool, optional): If True, the server will be started in debug mode. Defaults to False. indexes (int, optional): The band(s) to use. Band indexing starts at 1. Defaults to None. colormap (str, optional): The name of the colormap from `matplotlib` to use when plotting a single band. See https://matplotlib.org/stable/gallery/color/colormap_reference.html. Default is greyscale. vmin (float, optional): The minimum value to use when colormapping the colormap when plotting a single band. Defaults to None. vmax (float, optional): The maximum value to use when colormapping the colormap when plotting a single band. Defaults to None. nodata (float, optional): The value from the band to use to interpret as not valid data. Defaults to None. attribution (str, optional): Attribution for the source raster. This defaults to a message about it being a local file.. Defaults to None. tile_format (str, optional): The tile layer format. Can be either ipyleaflet or folium. Defaults to "ipyleaflet". layer_name (str, optional): The layer name to use. Defaults to None. return_client (bool, optional): If True, the tile client will be returned. Defaults to False. quiet (bool, optional): If True, the error messages will be suppressed. Defaults to False. Returns: ipyleaflet.TileLayer | folium.TileLayer: An ipyleaflet.TileLayer or folium.TileLayer. """ import rasterio check_package( "localtileserver", URL="https://github.com/banesullivan/localtileserver" ) # Handle legacy localtileserver kwargs if "cmap" in kwargs: warnings.warn( "`cmap` is a deprecated keyword argument for get_local_tile_layer. Please use `colormap`." ) if "palette" in kwargs: warnings.warn( "`palette` is a deprecated keyword argument for get_local_tile_layer. Please use `colormap`." ) if "band" in kwargs or "bands" in kwargs: warnings.warn( "`band` and `bands` are deprecated keyword arguments for get_local_tile_layer. Please use `indexes`." ) if "projection" in kwargs: warnings.warn( "`projection` is a deprecated keyword argument for get_local_tile_layer and will be ignored." ) if "style" in kwargs: warnings.warn( "`style` is a deprecated keyword argument for get_local_tile_layer and will be ignored." ) if "max_zoom" not in kwargs: kwargs["max_zoom"] = 30 if "max_native_zoom" not in kwargs: kwargs["max_native_zoom"] = 30 if "cmap" in kwargs: colormap = kwargs.pop("cmap") if "palette" in kwargs: colormap = kwargs.pop("palette") if "band" in kwargs: indexes = kwargs.pop("band") if "bands" in kwargs: indexes = kwargs.pop("bands") # Make it compatible with binder and JupyterHub if os.environ.get("JUPYTERHUB_SERVICE_PREFIX") is not None: os.environ["LOCALTILESERVER_CLIENT_PREFIX"] = ( f"{os.environ['JUPYTERHUB_SERVICE_PREFIX'].lstrip('/')}/proxy/{{port}}" ) if is_studio_lab(): os.environ["LOCALTILESERVER_CLIENT_PREFIX"] = ( f"studiolab/default/jupyter/proxy/{{port}}" ) elif is_on_aws(): os.environ["LOCALTILESERVER_CLIENT_PREFIX"] = "proxy/{port}" elif "prefix" in kwargs: os.environ["LOCALTILESERVER_CLIENT_PREFIX"] = kwargs["prefix"] kwargs.pop("prefix") from localtileserver import ( get_leaflet_tile_layer, get_folium_tile_layer, TileClient, ) # if "show_loading" not in kwargs: # kwargs["show_loading"] = False if isinstance(source, str): if not source.startswith("http"): if source.startswith("~"): source = os.path.expanduser(source) # else: # source = os.path.abspath(source) # if not os.path.exists(source): # raise ValueError("The source path does not exist.") else: source = github_raw_url(source) elif isinstance(source, TileClient) or isinstance( source, rasterio.io.DatasetReader ): pass else: raise ValueError("The source must either be a string or TileClient") if tile_format not in ["ipyleaflet", "folium"]: raise ValueError("The tile format must be either ipyleaflet or folium.") if layer_name is None: if source.startswith("http"): layer_name = "RemoteTile_" + random_string(3) else: layer_name = "LocalTile_" + random_string(3) if isinstance(source, str) or isinstance(source, rasterio.io.DatasetReader): tile_client = TileClient(source, port=port, debug=debug) else: tile_client = source if quiet: output = widgets.Output() with output: if tile_format == "ipyleaflet": tile_layer = get_leaflet_tile_layer( tile_client, port=port, debug=debug, indexes=indexes, colormap=colormap, vmin=vmin, vmax=vmax, nodata=nodata, attribution=attribution, name=layer_name, **kwargs, ) else: tile_layer = get_folium_tile_layer( tile_client, port=port, debug=debug, indexes=indexes, colormap=colormap, vmin=vmin, vmax=vmax, nodata=nodata, attr=attribution, overlay=True, name=layer_name, **kwargs, ) else: if tile_format == "ipyleaflet": tile_layer = get_leaflet_tile_layer( tile_client, port=port, debug=debug, indexes=indexes, colormap=colormap, vmin=vmin, vmax=vmax, nodata=nodata, attribution=attribution, name=layer_name, **kwargs, ) else: tile_layer = get_folium_tile_layer( tile_client, port=port, debug=debug, indexes=indexes, colormap=colormap, vmin=vmin, vmax=vmax, nodata=nodata, attr=attribution, overlay=True, name=layer_name, **kwargs, ) if return_client: return tile_layer, tile_client else: return tile_layer # center = tile_client.center() # bounds = tile_client.bounds() # [ymin, ymax, xmin, xmax] # bounds = (bounds[2], bounds[0], bounds[3], bounds[1]) # [minx, miny, maxx, maxy] # if get_center and get_bounds: # return tile_layer, center, bounds # elif get_center: # return tile_layer, center # elif get_bounds: # return tile_layer, bounds # else: # return tile_layer def image_check(image): from localtileserver import TileClient if isinstance(image, str): if image.startswith("http") or os.path.exists(image): pass else: raise ValueError("image must be a URL or filepath.") elif isinstance(image, TileClient): pass else: raise ValueError("image must be a URL or filepath.") The provided code snippet includes necessary dependencies for implementing the `image_size` function. Write a Python function `def image_size(image, **kwargs)` to solve the following problem: Get the size (width, height) of an image. Args: image (str): The input image filepath or URL. Returns: tuple: A tuple of (width, height). Here is the function: def image_size(image, **kwargs): """Get the size (width, height) of an image. Args: image (str): The input image filepath or URL. Returns: tuple: A tuple of (width, height). """ image_check(image) if isinstance(image, str): _, client = get_local_tile_layer(image, return_client=True, **kwargs) else: client = image metadata = client.metadata() return metadata["sourceSizeX"], metadata["sourceSizeY"]
Get the size (width, height) of an image. Args: image (str): The input image filepath or URL. Returns: tuple: A tuple of (width, height).
12,417
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple def get_local_tile_layer( source, port="default", debug=False, indexes=None, colormap=None, vmin=None, vmax=None, nodata=None, attribution=None, tile_format="ipyleaflet", layer_name="Local COG", return_client=False, quiet=False, **kwargs, ): """Generate an ipyleaflet/folium TileLayer from a local raster dataset or remote Cloud Optimized GeoTIFF (COG). If you are using this function in JupyterHub on a remote server and the raster does not render properly, try running the following two lines before calling this function: import os os.environ['LOCALTILESERVER_CLIENT_PREFIX'] = 'proxy/{port}' Args: source (str): The path to the GeoTIFF file or the URL of the Cloud Optimized GeoTIFF. port (str, optional): The port to use for the server. Defaults to "default". debug (bool, optional): If True, the server will be started in debug mode. Defaults to False. indexes (int, optional): The band(s) to use. Band indexing starts at 1. Defaults to None. colormap (str, optional): The name of the colormap from `matplotlib` to use when plotting a single band. See https://matplotlib.org/stable/gallery/color/colormap_reference.html. Default is greyscale. vmin (float, optional): The minimum value to use when colormapping the colormap when plotting a single band. Defaults to None. vmax (float, optional): The maximum value to use when colormapping the colormap when plotting a single band. Defaults to None. nodata (float, optional): The value from the band to use to interpret as not valid data. Defaults to None. attribution (str, optional): Attribution for the source raster. This defaults to a message about it being a local file.. Defaults to None. tile_format (str, optional): The tile layer format. Can be either ipyleaflet or folium. Defaults to "ipyleaflet". layer_name (str, optional): The layer name to use. Defaults to None. return_client (bool, optional): If True, the tile client will be returned. Defaults to False. quiet (bool, optional): If True, the error messages will be suppressed. Defaults to False. Returns: ipyleaflet.TileLayer | folium.TileLayer: An ipyleaflet.TileLayer or folium.TileLayer. """ import rasterio check_package( "localtileserver", URL="https://github.com/banesullivan/localtileserver" ) # Handle legacy localtileserver kwargs if "cmap" in kwargs: warnings.warn( "`cmap` is a deprecated keyword argument for get_local_tile_layer. Please use `colormap`." ) if "palette" in kwargs: warnings.warn( "`palette` is a deprecated keyword argument for get_local_tile_layer. Please use `colormap`." ) if "band" in kwargs or "bands" in kwargs: warnings.warn( "`band` and `bands` are deprecated keyword arguments for get_local_tile_layer. Please use `indexes`." ) if "projection" in kwargs: warnings.warn( "`projection` is a deprecated keyword argument for get_local_tile_layer and will be ignored." ) if "style" in kwargs: warnings.warn( "`style` is a deprecated keyword argument for get_local_tile_layer and will be ignored." ) if "max_zoom" not in kwargs: kwargs["max_zoom"] = 30 if "max_native_zoom" not in kwargs: kwargs["max_native_zoom"] = 30 if "cmap" in kwargs: colormap = kwargs.pop("cmap") if "palette" in kwargs: colormap = kwargs.pop("palette") if "band" in kwargs: indexes = kwargs.pop("band") if "bands" in kwargs: indexes = kwargs.pop("bands") # Make it compatible with binder and JupyterHub if os.environ.get("JUPYTERHUB_SERVICE_PREFIX") is not None: os.environ["LOCALTILESERVER_CLIENT_PREFIX"] = ( f"{os.environ['JUPYTERHUB_SERVICE_PREFIX'].lstrip('/')}/proxy/{{port}}" ) if is_studio_lab(): os.environ["LOCALTILESERVER_CLIENT_PREFIX"] = ( f"studiolab/default/jupyter/proxy/{{port}}" ) elif is_on_aws(): os.environ["LOCALTILESERVER_CLIENT_PREFIX"] = "proxy/{port}" elif "prefix" in kwargs: os.environ["LOCALTILESERVER_CLIENT_PREFIX"] = kwargs["prefix"] kwargs.pop("prefix") from localtileserver import ( get_leaflet_tile_layer, get_folium_tile_layer, TileClient, ) # if "show_loading" not in kwargs: # kwargs["show_loading"] = False if isinstance(source, str): if not source.startswith("http"): if source.startswith("~"): source = os.path.expanduser(source) # else: # source = os.path.abspath(source) # if not os.path.exists(source): # raise ValueError("The source path does not exist.") else: source = github_raw_url(source) elif isinstance(source, TileClient) or isinstance( source, rasterio.io.DatasetReader ): pass else: raise ValueError("The source must either be a string or TileClient") if tile_format not in ["ipyleaflet", "folium"]: raise ValueError("The tile format must be either ipyleaflet or folium.") if layer_name is None: if source.startswith("http"): layer_name = "RemoteTile_" + random_string(3) else: layer_name = "LocalTile_" + random_string(3) if isinstance(source, str) or isinstance(source, rasterio.io.DatasetReader): tile_client = TileClient(source, port=port, debug=debug) else: tile_client = source if quiet: output = widgets.Output() with output: if tile_format == "ipyleaflet": tile_layer = get_leaflet_tile_layer( tile_client, port=port, debug=debug, indexes=indexes, colormap=colormap, vmin=vmin, vmax=vmax, nodata=nodata, attribution=attribution, name=layer_name, **kwargs, ) else: tile_layer = get_folium_tile_layer( tile_client, port=port, debug=debug, indexes=indexes, colormap=colormap, vmin=vmin, vmax=vmax, nodata=nodata, attr=attribution, overlay=True, name=layer_name, **kwargs, ) else: if tile_format == "ipyleaflet": tile_layer = get_leaflet_tile_layer( tile_client, port=port, debug=debug, indexes=indexes, colormap=colormap, vmin=vmin, vmax=vmax, nodata=nodata, attribution=attribution, name=layer_name, **kwargs, ) else: tile_layer = get_folium_tile_layer( tile_client, port=port, debug=debug, indexes=indexes, colormap=colormap, vmin=vmin, vmax=vmax, nodata=nodata, attr=attribution, overlay=True, name=layer_name, **kwargs, ) if return_client: return tile_layer, tile_client else: return tile_layer # center = tile_client.center() # bounds = tile_client.bounds() # [ymin, ymax, xmin, xmax] # bounds = (bounds[2], bounds[0], bounds[3], bounds[1]) # [minx, miny, maxx, maxy] # if get_center and get_bounds: # return tile_layer, center, bounds # elif get_center: # return tile_layer, center # elif get_bounds: # return tile_layer, bounds # else: # return tile_layer def image_check(image): from localtileserver import TileClient if isinstance(image, str): if image.startswith("http") or os.path.exists(image): pass else: raise ValueError("image must be a URL or filepath.") elif isinstance(image, TileClient): pass else: raise ValueError("image must be a URL or filepath.") The provided code snippet includes necessary dependencies for implementing the `image_projection` function. Write a Python function `def image_projection(image, **kwargs)` to solve the following problem: Get the projection of an image. Args: image (str): The input image filepath or URL. Returns: str: The projection of the image. Here is the function: def image_projection(image, **kwargs): """Get the projection of an image. Args: image (str): The input image filepath or URL. Returns: str: The projection of the image. """ image_check(image) if isinstance(image, str): _, client = get_local_tile_layer(image, return_client=True, **kwargs) else: client = image return client.metadata()["Projection"]
Get the projection of an image. Args: image (str): The input image filepath or URL. Returns: str: The projection of the image.
12,418
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple The provided code snippet includes necessary dependencies for implementing the `image_set_crs` function. Write a Python function `def image_set_crs(image, epsg)` to solve the following problem: Define the CRS of an image. Args: image (str): The input image filepath epsg (int): The EPSG code of the CRS to set. Here is the function: def image_set_crs(image, epsg): """Define the CRS of an image. Args: image (str): The input image filepath epsg (int): The EPSG code of the CRS to set. """ from rasterio.crs import CRS import rasterio with rasterio.open(image, "r+") as rds: rds.crs = CRS.from_epsg(epsg)
Define the CRS of an image. Args: image (str): The input image filepath epsg (int): The EPSG code of the CRS to set.
12,419
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple def get_local_tile_layer( source, port="default", debug=False, indexes=None, colormap=None, vmin=None, vmax=None, nodata=None, attribution=None, tile_format="ipyleaflet", layer_name="Local COG", return_client=False, quiet=False, **kwargs, ): """Generate an ipyleaflet/folium TileLayer from a local raster dataset or remote Cloud Optimized GeoTIFF (COG). If you are using this function in JupyterHub on a remote server and the raster does not render properly, try running the following two lines before calling this function: import os os.environ['LOCALTILESERVER_CLIENT_PREFIX'] = 'proxy/{port}' Args: source (str): The path to the GeoTIFF file or the URL of the Cloud Optimized GeoTIFF. port (str, optional): The port to use for the server. Defaults to "default". debug (bool, optional): If True, the server will be started in debug mode. Defaults to False. indexes (int, optional): The band(s) to use. Band indexing starts at 1. Defaults to None. colormap (str, optional): The name of the colormap from `matplotlib` to use when plotting a single band. See https://matplotlib.org/stable/gallery/color/colormap_reference.html. Default is greyscale. vmin (float, optional): The minimum value to use when colormapping the colormap when plotting a single band. Defaults to None. vmax (float, optional): The maximum value to use when colormapping the colormap when plotting a single band. Defaults to None. nodata (float, optional): The value from the band to use to interpret as not valid data. Defaults to None. attribution (str, optional): Attribution for the source raster. This defaults to a message about it being a local file.. Defaults to None. tile_format (str, optional): The tile layer format. Can be either ipyleaflet or folium. Defaults to "ipyleaflet". layer_name (str, optional): The layer name to use. Defaults to None. return_client (bool, optional): If True, the tile client will be returned. Defaults to False. quiet (bool, optional): If True, the error messages will be suppressed. Defaults to False. Returns: ipyleaflet.TileLayer | folium.TileLayer: An ipyleaflet.TileLayer or folium.TileLayer. """ import rasterio check_package( "localtileserver", URL="https://github.com/banesullivan/localtileserver" ) # Handle legacy localtileserver kwargs if "cmap" in kwargs: warnings.warn( "`cmap` is a deprecated keyword argument for get_local_tile_layer. Please use `colormap`." ) if "palette" in kwargs: warnings.warn( "`palette` is a deprecated keyword argument for get_local_tile_layer. Please use `colormap`." ) if "band" in kwargs or "bands" in kwargs: warnings.warn( "`band` and `bands` are deprecated keyword arguments for get_local_tile_layer. Please use `indexes`." ) if "projection" in kwargs: warnings.warn( "`projection` is a deprecated keyword argument for get_local_tile_layer and will be ignored." ) if "style" in kwargs: warnings.warn( "`style` is a deprecated keyword argument for get_local_tile_layer and will be ignored." ) if "max_zoom" not in kwargs: kwargs["max_zoom"] = 30 if "max_native_zoom" not in kwargs: kwargs["max_native_zoom"] = 30 if "cmap" in kwargs: colormap = kwargs.pop("cmap") if "palette" in kwargs: colormap = kwargs.pop("palette") if "band" in kwargs: indexes = kwargs.pop("band") if "bands" in kwargs: indexes = kwargs.pop("bands") # Make it compatible with binder and JupyterHub if os.environ.get("JUPYTERHUB_SERVICE_PREFIX") is not None: os.environ["LOCALTILESERVER_CLIENT_PREFIX"] = ( f"{os.environ['JUPYTERHUB_SERVICE_PREFIX'].lstrip('/')}/proxy/{{port}}" ) if is_studio_lab(): os.environ["LOCALTILESERVER_CLIENT_PREFIX"] = ( f"studiolab/default/jupyter/proxy/{{port}}" ) elif is_on_aws(): os.environ["LOCALTILESERVER_CLIENT_PREFIX"] = "proxy/{port}" elif "prefix" in kwargs: os.environ["LOCALTILESERVER_CLIENT_PREFIX"] = kwargs["prefix"] kwargs.pop("prefix") from localtileserver import ( get_leaflet_tile_layer, get_folium_tile_layer, TileClient, ) # if "show_loading" not in kwargs: # kwargs["show_loading"] = False if isinstance(source, str): if not source.startswith("http"): if source.startswith("~"): source = os.path.expanduser(source) # else: # source = os.path.abspath(source) # if not os.path.exists(source): # raise ValueError("The source path does not exist.") else: source = github_raw_url(source) elif isinstance(source, TileClient) or isinstance( source, rasterio.io.DatasetReader ): pass else: raise ValueError("The source must either be a string or TileClient") if tile_format not in ["ipyleaflet", "folium"]: raise ValueError("The tile format must be either ipyleaflet or folium.") if layer_name is None: if source.startswith("http"): layer_name = "RemoteTile_" + random_string(3) else: layer_name = "LocalTile_" + random_string(3) if isinstance(source, str) or isinstance(source, rasterio.io.DatasetReader): tile_client = TileClient(source, port=port, debug=debug) else: tile_client = source if quiet: output = widgets.Output() with output: if tile_format == "ipyleaflet": tile_layer = get_leaflet_tile_layer( tile_client, port=port, debug=debug, indexes=indexes, colormap=colormap, vmin=vmin, vmax=vmax, nodata=nodata, attribution=attribution, name=layer_name, **kwargs, ) else: tile_layer = get_folium_tile_layer( tile_client, port=port, debug=debug, indexes=indexes, colormap=colormap, vmin=vmin, vmax=vmax, nodata=nodata, attr=attribution, overlay=True, name=layer_name, **kwargs, ) else: if tile_format == "ipyleaflet": tile_layer = get_leaflet_tile_layer( tile_client, port=port, debug=debug, indexes=indexes, colormap=colormap, vmin=vmin, vmax=vmax, nodata=nodata, attribution=attribution, name=layer_name, **kwargs, ) else: tile_layer = get_folium_tile_layer( tile_client, port=port, debug=debug, indexes=indexes, colormap=colormap, vmin=vmin, vmax=vmax, nodata=nodata, attr=attribution, overlay=True, name=layer_name, **kwargs, ) if return_client: return tile_layer, tile_client else: return tile_layer # center = tile_client.center() # bounds = tile_client.bounds() # [ymin, ymax, xmin, xmax] # bounds = (bounds[2], bounds[0], bounds[3], bounds[1]) # [minx, miny, maxx, maxy] # if get_center and get_bounds: # return tile_layer, center, bounds # elif get_center: # return tile_layer, center # elif get_bounds: # return tile_layer, bounds # else: # return tile_layer def image_check(image): from localtileserver import TileClient if isinstance(image, str): if image.startswith("http") or os.path.exists(image): pass else: raise ValueError("image must be a URL or filepath.") elif isinstance(image, TileClient): pass else: raise ValueError("image must be a URL or filepath.") The provided code snippet includes necessary dependencies for implementing the `image_geotransform` function. Write a Python function `def image_geotransform(image, **kwargs)` to solve the following problem: Get the geotransform of an image. Args: image (str): The input image filepath or URL. Returns: list: A list of geotransform values. Here is the function: def image_geotransform(image, **kwargs): """Get the geotransform of an image. Args: image (str): The input image filepath or URL. Returns: list: A list of geotransform values. """ image_check(image) if isinstance(image, str): _, client = get_local_tile_layer(image, return_client=True, **kwargs) else: client = image return client.metadata()["GeoTransform"]
Get the geotransform of an image. Args: image (str): The input image filepath or URL. Returns: list: A list of geotransform values.
12,420
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple def get_local_tile_layer( source, port="default", debug=False, indexes=None, colormap=None, vmin=None, vmax=None, nodata=None, attribution=None, tile_format="ipyleaflet", layer_name="Local COG", return_client=False, quiet=False, **kwargs, ): """Generate an ipyleaflet/folium TileLayer from a local raster dataset or remote Cloud Optimized GeoTIFF (COG). If you are using this function in JupyterHub on a remote server and the raster does not render properly, try running the following two lines before calling this function: import os os.environ['LOCALTILESERVER_CLIENT_PREFIX'] = 'proxy/{port}' Args: source (str): The path to the GeoTIFF file or the URL of the Cloud Optimized GeoTIFF. port (str, optional): The port to use for the server. Defaults to "default". debug (bool, optional): If True, the server will be started in debug mode. Defaults to False. indexes (int, optional): The band(s) to use. Band indexing starts at 1. Defaults to None. colormap (str, optional): The name of the colormap from `matplotlib` to use when plotting a single band. See https://matplotlib.org/stable/gallery/color/colormap_reference.html. Default is greyscale. vmin (float, optional): The minimum value to use when colormapping the colormap when plotting a single band. Defaults to None. vmax (float, optional): The maximum value to use when colormapping the colormap when plotting a single band. Defaults to None. nodata (float, optional): The value from the band to use to interpret as not valid data. Defaults to None. attribution (str, optional): Attribution for the source raster. This defaults to a message about it being a local file.. Defaults to None. tile_format (str, optional): The tile layer format. Can be either ipyleaflet or folium. Defaults to "ipyleaflet". layer_name (str, optional): The layer name to use. Defaults to None. return_client (bool, optional): If True, the tile client will be returned. Defaults to False. quiet (bool, optional): If True, the error messages will be suppressed. Defaults to False. Returns: ipyleaflet.TileLayer | folium.TileLayer: An ipyleaflet.TileLayer or folium.TileLayer. """ import rasterio check_package( "localtileserver", URL="https://github.com/banesullivan/localtileserver" ) # Handle legacy localtileserver kwargs if "cmap" in kwargs: warnings.warn( "`cmap` is a deprecated keyword argument for get_local_tile_layer. Please use `colormap`." ) if "palette" in kwargs: warnings.warn( "`palette` is a deprecated keyword argument for get_local_tile_layer. Please use `colormap`." ) if "band" in kwargs or "bands" in kwargs: warnings.warn( "`band` and `bands` are deprecated keyword arguments for get_local_tile_layer. Please use `indexes`." ) if "projection" in kwargs: warnings.warn( "`projection` is a deprecated keyword argument for get_local_tile_layer and will be ignored." ) if "style" in kwargs: warnings.warn( "`style` is a deprecated keyword argument for get_local_tile_layer and will be ignored." ) if "max_zoom" not in kwargs: kwargs["max_zoom"] = 30 if "max_native_zoom" not in kwargs: kwargs["max_native_zoom"] = 30 if "cmap" in kwargs: colormap = kwargs.pop("cmap") if "palette" in kwargs: colormap = kwargs.pop("palette") if "band" in kwargs: indexes = kwargs.pop("band") if "bands" in kwargs: indexes = kwargs.pop("bands") # Make it compatible with binder and JupyterHub if os.environ.get("JUPYTERHUB_SERVICE_PREFIX") is not None: os.environ["LOCALTILESERVER_CLIENT_PREFIX"] = ( f"{os.environ['JUPYTERHUB_SERVICE_PREFIX'].lstrip('/')}/proxy/{{port}}" ) if is_studio_lab(): os.environ["LOCALTILESERVER_CLIENT_PREFIX"] = ( f"studiolab/default/jupyter/proxy/{{port}}" ) elif is_on_aws(): os.environ["LOCALTILESERVER_CLIENT_PREFIX"] = "proxy/{port}" elif "prefix" in kwargs: os.environ["LOCALTILESERVER_CLIENT_PREFIX"] = kwargs["prefix"] kwargs.pop("prefix") from localtileserver import ( get_leaflet_tile_layer, get_folium_tile_layer, TileClient, ) # if "show_loading" not in kwargs: # kwargs["show_loading"] = False if isinstance(source, str): if not source.startswith("http"): if source.startswith("~"): source = os.path.expanduser(source) # else: # source = os.path.abspath(source) # if not os.path.exists(source): # raise ValueError("The source path does not exist.") else: source = github_raw_url(source) elif isinstance(source, TileClient) or isinstance( source, rasterio.io.DatasetReader ): pass else: raise ValueError("The source must either be a string or TileClient") if tile_format not in ["ipyleaflet", "folium"]: raise ValueError("The tile format must be either ipyleaflet or folium.") if layer_name is None: if source.startswith("http"): layer_name = "RemoteTile_" + random_string(3) else: layer_name = "LocalTile_" + random_string(3) if isinstance(source, str) or isinstance(source, rasterio.io.DatasetReader): tile_client = TileClient(source, port=port, debug=debug) else: tile_client = source if quiet: output = widgets.Output() with output: if tile_format == "ipyleaflet": tile_layer = get_leaflet_tile_layer( tile_client, port=port, debug=debug, indexes=indexes, colormap=colormap, vmin=vmin, vmax=vmax, nodata=nodata, attribution=attribution, name=layer_name, **kwargs, ) else: tile_layer = get_folium_tile_layer( tile_client, port=port, debug=debug, indexes=indexes, colormap=colormap, vmin=vmin, vmax=vmax, nodata=nodata, attr=attribution, overlay=True, name=layer_name, **kwargs, ) else: if tile_format == "ipyleaflet": tile_layer = get_leaflet_tile_layer( tile_client, port=port, debug=debug, indexes=indexes, colormap=colormap, vmin=vmin, vmax=vmax, nodata=nodata, attribution=attribution, name=layer_name, **kwargs, ) else: tile_layer = get_folium_tile_layer( tile_client, port=port, debug=debug, indexes=indexes, colormap=colormap, vmin=vmin, vmax=vmax, nodata=nodata, attr=attribution, overlay=True, name=layer_name, **kwargs, ) if return_client: return tile_layer, tile_client else: return tile_layer # center = tile_client.center() # bounds = tile_client.bounds() # [ymin, ymax, xmin, xmax] # bounds = (bounds[2], bounds[0], bounds[3], bounds[1]) # [minx, miny, maxx, maxy] # if get_center and get_bounds: # return tile_layer, center, bounds # elif get_center: # return tile_layer, center # elif get_bounds: # return tile_layer, bounds # else: # return tile_layer def image_check(image): from localtileserver import TileClient if isinstance(image, str): if image.startswith("http") or os.path.exists(image): pass else: raise ValueError("image must be a URL or filepath.") elif isinstance(image, TileClient): pass else: raise ValueError("image must be a URL or filepath.") The provided code snippet includes necessary dependencies for implementing the `image_resolution` function. Write a Python function `def image_resolution(image, **kwargs)` to solve the following problem: Get the resolution of an image. Args: image (str): The input image filepath or URL. Returns: float: The resolution of the image. Here is the function: def image_resolution(image, **kwargs): """Get the resolution of an image. Args: image (str): The input image filepath or URL. Returns: float: The resolution of the image. """ image_check(image) if isinstance(image, str): _, client = get_local_tile_layer(image, return_client=True, **kwargs) else: client = image return client.metadata()["GeoTransform"][1]
Get the resolution of an image. Args: image (str): The input image filepath or URL. Returns: float: The resolution of the image.
12,421
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple The provided code snippet includes necessary dependencies for implementing the `find_files` function. Write a Python function `def find_files(input_dir, ext=None, fullpath=True, recursive=True)` to solve the following problem: Find files in a directory. Args: input_dir (str): The input directory. ext (str, optional): The file extension to match. Defaults to None. fullpath (bool, optional): Whether to return the full path. Defaults to True. recursive (bool, optional): Whether to search recursively. Defaults to True. Returns: list: A list of matching files. Here is the function: def find_files(input_dir, ext=None, fullpath=True, recursive=True): """Find files in a directory. Args: input_dir (str): The input directory. ext (str, optional): The file extension to match. Defaults to None. fullpath (bool, optional): Whether to return the full path. Defaults to True. recursive (bool, optional): Whether to search recursively. Defaults to True. Returns: list: A list of matching files. """ from pathlib import Path files = [] if ext is None: ext = "*" else: ext = ext.replace(".", "") ext = f"*.{ext}" if recursive: if fullpath: files = [str(path.joinpath()) for path in Path(input_dir).rglob(ext)] else: files = [str(path.name) for path in Path(input_dir).rglob(ext)] else: if fullpath: files = [str(path.joinpath()) for path in Path(input_dir).glob(ext)] else: files = [path.name for path in Path(input_dir).glob(ext)] return files
Find files in a directory. Args: input_dir (str): The input directory. ext (str, optional): The file extension to match. Defaults to None. fullpath (bool, optional): Whether to return the full path. Defaults to True. recursive (bool, optional): Whether to search recursively. Defaults to True. Returns: list: A list of matching files.
12,422
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple The provided code snippet includes necessary dependencies for implementing the `zoom_level_resolution` function. Write a Python function `def zoom_level_resolution(zoom, latitude=0)` to solve the following problem: Returns the approximate pixel scale based on zoom level and latutude. See https://blogs.bing.com/maps/2006/02/25/map-control-zoom-levels-gt-resolution Args: zoom (int): The zoom level. latitude (float, optional): The latitude. Defaults to 0. Returns: float: Map resolution in meters. Here is the function: def zoom_level_resolution(zoom, latitude=0): """Returns the approximate pixel scale based on zoom level and latutude. See https://blogs.bing.com/maps/2006/02/25/map-control-zoom-levels-gt-resolution Args: zoom (int): The zoom level. latitude (float, optional): The latitude. Defaults to 0. Returns: float: Map resolution in meters. """ import math resolution = 156543.04 * math.cos(latitude) / math.pow(2, zoom) return abs(resolution)
Returns the approximate pixel scale based on zoom level and latutude. See https://blogs.bing.com/maps/2006/02/25/map-control-zoom-levels-gt-resolution Args: zoom (int): The zoom level. latitude (float, optional): The latitude. Defaults to 0. Returns: float: Map resolution in meters.
12,423
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple The provided code snippet includes necessary dependencies for implementing the `meters_to_lnglat` function. Write a Python function `def meters_to_lnglat(x, y)` to solve the following problem: coordinate conversion between web mercator to lat/lon in decimal degrees Args: x (float): The x coordinate. y (float): The y coordinate. Returns: tuple: A tuple of (longitude, latitude) in decimal degrees. Here is the function: def meters_to_lnglat(x, y): """coordinate conversion between web mercator to lat/lon in decimal degrees Args: x (float): The x coordinate. y (float): The y coordinate. Returns: tuple: A tuple of (longitude, latitude) in decimal degrees. """ import numpy as np origin_shift = np.pi * 6378137 longitude = (x / origin_shift) * 180.0 latitude = (y / origin_shift) * 180.0 latitude = ( 180 / np.pi * (2 * np.arctan(np.exp(latitude * np.pi / 180.0)) - np.pi / 2.0) ) return (longitude, latitude)
coordinate conversion between web mercator to lat/lon in decimal degrees Args: x (float): The x coordinate. y (float): The y coordinate. Returns: tuple: A tuple of (longitude, latitude) in decimal degrees.
12,424
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple def lnglat_to_meters(longitude, latitude): """coordinate conversion between lat/lon in decimal degrees to web mercator Args: longitude (float): The longitude. latitude (float): The latitude. Returns: tuple: A tuple of (x, y) in meters. """ import numpy as np origin_shift = np.pi * 6378137 easting = longitude * origin_shift / 180.0 northing = np.log(np.tan((90 + latitude) * np.pi / 360.0)) * origin_shift / np.pi if np.isnan(easting): if longitude > 0: easting = 20026376 else: easting = -20026376 if np.isnan(northing): if latitude > 0: northing = 20048966 else: northing = -20048966 return (easting, northing) The provided code snippet includes necessary dependencies for implementing the `bounds_to_xy_range` function. Write a Python function `def bounds_to_xy_range(bounds)` to solve the following problem: Convert bounds to x and y range to be used as input to bokeh map. Args: bounds (list): A list of bounds in the form [(south, west), (north, east)] or [xmin, ymin, xmax, ymax]. Returns: tuple: A tuple of (x_range, y_range). Here is the function: def bounds_to_xy_range(bounds): """Convert bounds to x and y range to be used as input to bokeh map. Args: bounds (list): A list of bounds in the form [(south, west), (north, east)] or [xmin, ymin, xmax, ymax]. Returns: tuple: A tuple of (x_range, y_range). """ if isinstance(bounds, tuple): bounds = list(bounds) elif not isinstance(bounds, list): raise TypeError("bounds must be a list") if len(bounds) == 4: west, south, east, north = bounds elif len(bounds) == 2: south, west = bounds[0] north, east = bounds[1] xmin, ymin = lnglat_to_meters(west, south) xmax, ymax = lnglat_to_meters(east, north) x_range = (xmin, xmax) y_range = (ymin, ymax) return x_range, y_range
Convert bounds to x and y range to be used as input to bokeh map. Args: bounds (list): A list of bounds in the form [(south, west), (north, east)] or [xmin, ymin, xmax, ymax]. Returns: tuple: A tuple of (x_range, y_range).
12,425
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple def lnglat_to_meters(longitude, latitude): """coordinate conversion between lat/lon in decimal degrees to web mercator Args: longitude (float): The longitude. latitude (float): The latitude. Returns: tuple: A tuple of (x, y) in meters. """ import numpy as np origin_shift = np.pi * 6378137 easting = longitude * origin_shift / 180.0 northing = np.log(np.tan((90 + latitude) * np.pi / 360.0)) * origin_shift / np.pi if np.isnan(easting): if longitude > 0: easting = 20026376 else: easting = -20026376 if np.isnan(northing): if latitude > 0: northing = 20048966 else: northing = -20048966 return (easting, northing) The provided code snippet includes necessary dependencies for implementing the `center_zoom_to_xy_range` function. Write a Python function `def center_zoom_to_xy_range(center, zoom)` to solve the following problem: Convert center and zoom to x and y range to be used as input to bokeh map. Args: center (tuple): A tuple of (latitude, longitude). zoom (int): The zoom level. Returns: tuple: A tuple of (x_range, y_range). Here is the function: def center_zoom_to_xy_range(center, zoom): """Convert center and zoom to x and y range to be used as input to bokeh map. Args: center (tuple): A tuple of (latitude, longitude). zoom (int): The zoom level. Returns: tuple: A tuple of (x_range, y_range). """ if isinstance(center, tuple) or isinstance(center, list): pass else: raise TypeError("center must be a tuple or list") if not isinstance(zoom, int): raise TypeError("zoom must be an integer") latitude, longitude = center x_range = (-179, 179) y_range = (-70, 70) x_full_length = x_range[1] - x_range[0] y_full_length = y_range[1] - y_range[0] x_length = x_full_length / 2 ** (zoom - 2) y_length = y_full_length / 2 ** (zoom - 2) south = latitude - y_length / 2 north = latitude + y_length / 2 west = longitude - x_length / 2 east = longitude + x_length / 2 xmin, ymin = lnglat_to_meters(west, south) xmax, ymax = lnglat_to_meters(east, north) x_range = (xmin, xmax) y_range = (ymin, ymax) return x_range, y_range
Convert center and zoom to x and y range to be used as input to bokeh map. Args: center (tuple): A tuple of (latitude, longitude). zoom (int): The zoom level. Returns: tuple: A tuple of (x_range, y_range).
12,426
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple def lnglat_to_meters(longitude, latitude): """coordinate conversion between lat/lon in decimal degrees to web mercator Args: longitude (float): The longitude. latitude (float): The latitude. Returns: tuple: A tuple of (x, y) in meters. """ import numpy as np origin_shift = np.pi * 6378137 easting = longitude * origin_shift / 180.0 northing = np.log(np.tan((90 + latitude) * np.pi / 360.0)) * origin_shift / np.pi if np.isnan(easting): if longitude > 0: easting = 20026376 else: easting = -20026376 if np.isnan(northing): if latitude > 0: northing = 20048966 else: northing = -20048966 return (easting, northing) The provided code snippet includes necessary dependencies for implementing the `get_geometry_coords` function. Write a Python function `def get_geometry_coords(row, geom, coord_type, shape_type, mercator=False)` to solve the following problem: Returns the coordinates ('x' or 'y') of edges of a Polygon exterior. :param: (GeoPandas Series) row : The row of each of the GeoPandas DataFrame. :param: (str) geom : The column name. :param: (str) coord_type : Whether it's 'x' or 'y' coordinate. :param: (str) shape_type Here is the function: def get_geometry_coords(row, geom, coord_type, shape_type, mercator=False): """ Returns the coordinates ('x' or 'y') of edges of a Polygon exterior. :param: (GeoPandas Series) row : The row of each of the GeoPandas DataFrame. :param: (str) geom : The column name. :param: (str) coord_type : Whether it's 'x' or 'y' coordinate. :param: (str) shape_type """ # Parse the exterior of the coordinate if shape_type.lower() in ["polygon", "multipolygon"]: exterior = row[geom].geoms[0].exterior if coord_type == "x": # Get the x coordinates of the exterior coords = list(exterior.coords.xy[0]) if mercator: coords = [lnglat_to_meters(x, 0)[0] for x in coords] return coords elif coord_type == "y": # Get the y coordinates of the exterior coords = list(exterior.coords.xy[1]) if mercator: coords = [lnglat_to_meters(0, y)[1] for y in coords] return coords elif shape_type.lower() in ["linestring", "multilinestring"]: if coord_type == "x": coords = list(row[geom].coords.xy[0]) if mercator: coords = [lnglat_to_meters(x, 0)[0] for x in coords] return coords elif coord_type == "y": coords = list(row[geom].coords.xy[1]) if mercator: coords = [lnglat_to_meters(0, y)[1] for y in coords] return coords elif shape_type.lower() in ["point", "multipoint"]: exterior = row[geom] if coord_type == "x": # Get the x coordinates of the exterior coords = exterior.coords.xy[0][0] if mercator: coords = lnglat_to_meters(coords, 0)[0] return coords elif coord_type == "y": # Get the y coordinates of the exterior coords = exterior.coords.xy[1][0] if mercator: coords = lnglat_to_meters(0, coords)[1] return coords
Returns the coordinates ('x' or 'y') of edges of a Polygon exterior. :param: (GeoPandas Series) row : The row of each of the GeoPandas DataFrame. :param: (str) geom : The column name. :param: (str) coord_type : Whether it's 'x' or 'y' coordinate. :param: (str) shape_type
12,427
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple The provided code snippet includes necessary dependencies for implementing the `landsat_scaling` function. Write a Python function `def landsat_scaling(image, thermal_bands=True, apply_fmask=False)` to solve the following problem: Apply scaling factors to a Landsat image. See an example at https://developers.google.com/earth-engine/datasets/catalog/LANDSAT_LC09_C02_T1_L2 Args: image (ee.Image): The input Landsat image. thermal_bands (bool, optional): Whether to apply scaling to thermal bands. Defaults to True. apply_fmask (bool, optional): Whether to apply Fmask cloud mask. Defaults to False. Returns: ee.Image: The scaled Landsat image. Here is the function: def landsat_scaling(image, thermal_bands=True, apply_fmask=False): """Apply scaling factors to a Landsat image. See an example at https://developers.google.com/earth-engine/datasets/catalog/LANDSAT_LC09_C02_T1_L2 Args: image (ee.Image): The input Landsat image. thermal_bands (bool, optional): Whether to apply scaling to thermal bands. Defaults to True. apply_fmask (bool, optional): Whether to apply Fmask cloud mask. Defaults to False. Returns: ee.Image: The scaled Landsat image. """ # Apply the scaling factors to the appropriate bands. opticalBands = image.select("SR_B.").multiply(0.0000275).add(-0.2) if thermal_bands: thermalBands = image.select("ST_B.*").multiply(0.00341802).add(149) if apply_fmask: # Replace the original bands with the scaled ones and apply the masks. # Bit 0 - Fill # Bit 1 - Dilated Cloud # Bit 2 - Cirrus # Bit 3 - Cloud # Bit 4 - Cloud Shadow qaMask = image.select("QA_PIXEL").bitwiseAnd(int("11111", 2)).eq(0) if thermal_bands: return ( image.addBands(thermalBands, None, True) .addBands(opticalBands, None, True) .updateMask(qaMask) ) else: return image.addBands(opticalBands, None, True).updateMask(qaMask) else: if thermal_bands: return image.addBands(thermalBands, None, True).addBands( opticalBands, None, True ) else: return image.addBands(opticalBands, None, True)
Apply scaling factors to a Landsat image. See an example at https://developers.google.com/earth-engine/datasets/catalog/LANDSAT_LC09_C02_T1_L2 Args: image (ee.Image): The input Landsat image. thermal_bands (bool, optional): Whether to apply scaling to thermal bands. Defaults to True. apply_fmask (bool, optional): Whether to apply Fmask cloud mask. Defaults to False. Returns: ee.Image: The scaled Landsat image.
12,428
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple The provided code snippet includes necessary dependencies for implementing the `tif_to_jp2` function. Write a Python function `def tif_to_jp2(filename, output, creationOptions=None)` to solve the following problem: Converts a GeoTIFF to JPEG2000. Args: filename (str): The path to the GeoTIFF file. output (str): The path to the output JPEG2000 file. creationOptions (list): A list of creation options for the JPEG2000 file. See https://gdal.org/drivers/raster/jp2openjpeg.html. For example, to specify the compression ratio, use ``["QUALITY=20"]``. A value of 20 means the file will be 20% of the size in comparison to uncompressed data. Here is the function: def tif_to_jp2(filename, output, creationOptions=None): """Converts a GeoTIFF to JPEG2000. Args: filename (str): The path to the GeoTIFF file. output (str): The path to the output JPEG2000 file. creationOptions (list): A list of creation options for the JPEG2000 file. See https://gdal.org/drivers/raster/jp2openjpeg.html. For example, to specify the compression ratio, use ``["QUALITY=20"]``. A value of 20 means the file will be 20% of the size in comparison to uncompressed data. """ from osgeo import gdal gdal.UseExceptions() if not os.path.exists(filename): raise Exception(f"File {filename} does not exist") if not output.endswith(".jp2"): output += ".jp2" in_ds = gdal.Open(filename) gdal.Translate(output, in_ds, format="JP2OpenJPEG", creationOptions=creationOptions) in_ds = None
Converts a GeoTIFF to JPEG2000. Args: filename (str): The path to the GeoTIFF file. output (str): The path to the output JPEG2000 file. creationOptions (list): A list of creation options for the JPEG2000 file. See https://gdal.org/drivers/raster/jp2openjpeg.html. For example, to specify the compression ratio, use ``["QUALITY=20"]``. A value of 20 means the file will be 20% of the size in comparison to uncompressed data.
12,429
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple def ee_to_bbox(ee_object): """Get the bounding box of an Earth Engine object as a list in the format [xmin, ymin, xmax, ymax]. Args: ee_object (ee.Image | ee.Geometry | ee.Feature | ee.FeatureCollection): The input Earth Engine object. Returns: list: The bounding box of the Earth Engine object in the format [xmin, ymin, xmax, ymax]. """ if ( isinstance(ee_object, ee.Image) or isinstance(ee_object, ee.Feature) or isinstance(ee_object, ee.FeatureCollection) ): geometry = ee_object.geometry() elif isinstance(ee_object, ee.Geometry): geometry = ee_object else: raise Exception( "The ee_object must be an ee.Image, ee.Feature, ee.FeatureCollection or ee.Geometry object." ) bounds = geometry.bounds().getInfo()["coordinates"][0] xmin = bounds[0][0] ymin = bounds[0][1] xmax = bounds[1][0] ymax = bounds[2][1] bbox = [xmin, ymin, xmax, ymax] return bbox def blend( top_layer, bottom_layer=None, top_vis=None, bottom_vis=None, hillshade=True, expression="a*b", **kwargs, ): """Create a blended image that is a combination of two images, e.g., DEM and hillshade. This function was inspired by Jesse Anderson. See https://github.com/jessjaco/gee-blend. Args: top_layer (ee.Image): The top layer image, e.g., ee.Image("CGIAR/SRTM90_V4") bottom_layer (ee.Image, optional): The bottom layer image. If not specified, it will use the top layer image. top_vis (dict, optional): The top layer image vis parameters as a dictionary. Defaults to None. bottom_vis (dict, optional): The bottom layer image vis parameters as a dictionary. Defaults to None. hillshade (bool, optional): Flag to use hillshade. Defaults to True. expression (str, optional): The expression to use for the blend. Defaults to 'a*b'. Returns: ee.Image: The blended image. """ from box import Box if not isinstance(top_layer, ee.Image): raise ValueError("top_layer must be an ee.Image.") if bottom_layer is None: bottom_layer = top_layer if not isinstance(bottom_layer, ee.Image): raise ValueError("bottom_layer must be an ee.Image.") if top_vis is not None: if not isinstance(top_vis, dict): raise ValueError("top_vis must be a dictionary.") elif "palette" in top_vis and isinstance(top_vis["palette"], Box): try: top_vis["palette"] = top_vis["palette"]["default"] except Exception as e: print("The provided palette is invalid.") raise Exception(e) if bottom_vis is not None: if not isinstance(bottom_vis, dict): raise ValueError("top_vis must be a dictionary.") elif "palette" in bottom_vis and isinstance(bottom_vis["palette"], Box): try: bottom_vis["palette"] = bottom_vis["palette"]["default"] except Exception as e: print("The provided palette is invalid.") raise Exception(e) if top_vis is None: top_bands = top_layer.bandNames().getInfo() top_vis = {"bands": top_bands} if hillshade: top_vis["palette"] = ["006633", "E5FFCC", "662A00", "D8D8D8", "F5F5F5"] top_vis["min"] = 0 top_vis["max"] = 6000 if bottom_vis is None: bottom_bands = bottom_layer.bandNames().getInfo() bottom_vis = {"bands": bottom_bands} if hillshade: bottom_vis["bands"] = ["hillshade"] top = top_layer.visualize(**top_vis).divide(255) if hillshade: bottom = ee.Terrain.hillshade(bottom_layer).visualize(**bottom_vis).divide(255) else: bottom = bottom_layer.visualize(**bottom_vis).divide(255) if "a" not in expression or ("b" not in expression): raise ValueError("expression must contain 'a' and 'b'.") result = ee.Image().expression(expression, {"a": top, "b": bottom}) return result def check_cmap(cmap): """Check the colormap and return a list of colors. Args: cmap (str | list | Box): The colormap to check. Returns: list: A list of colors. """ from box import Box from .colormaps import get_palette if isinstance(cmap, str): try: palette = get_palette(cmap) if isinstance(palette, dict): palette = palette["default"] return palette except Exception as e: try: return check_color(cmap) except Exception as e: raise Exception(f"{cmap} is not a valid colormap.") elif isinstance(cmap, Box): return list(cmap["default"]) elif isinstance(cmap, list) or isinstance(cmap, tuple): return cmap else: raise Exception(f"{cmap} is not a valid colormap.") def mosaic(images, output, merge_args={}, verbose=True, **kwargs): """Mosaics a list of images into a single image. Inspired by https://bit.ly/3A6roDK. Args: images (str | list): An input directory containing images or a list of images. output (str): The output image filepath. merge_args (dict, optional): A dictionary of arguments to pass to the rasterio.merge function. Defaults to {}. verbose (bool, optional): Whether to print progress. Defaults to True. """ from rasterio.merge import merge import rasterio as rio from pathlib import Path output = os.path.abspath(output) if isinstance(images, str): path = Path(images) raster_files = list(path.iterdir()) elif isinstance(images, list): raster_files = images else: raise ValueError("images must be a list of raster files.") raster_to_mosiac = [] if not os.path.exists(os.path.dirname(output)): os.makedirs(os.path.dirname(output)) for index, p in enumerate(raster_files): if verbose: print(f"Reading {index+1}/{len(raster_files)}: {os.path.basename(p)}") raster = rio.open(p, **kwargs) raster_to_mosiac.append(raster) if verbose: print("Merging rasters...") arr, transform = merge(raster_to_mosiac, **merge_args) output_meta = raster.meta.copy() output_meta.update( { "driver": "GTiff", "height": arr.shape[1], "width": arr.shape[2], "transform": transform, } ) with rio.open(output, "w", **output_meta) as m: m.write(arr) def tms_to_geotiff( output, bbox, zoom=None, resolution=None, source="OpenStreetMap", crs="EPSG:3857", to_cog=False, quiet=False, **kwargs, ): """Download TMS tiles and convert them to a GeoTIFF. The source is adapted from https://github.com/gumblex/tms2geotiff. Credits to the GitHub user @gumblex. Args: output (str): The output GeoTIFF file. bbox (list): The bounding box [minx, miny, maxx, maxy], e.g., [-122.5216, 37.733, -122.3661, 37.8095] zoom (int, optional): The map zoom level. Defaults to None. resolution (float, optional): The resolution in meters. Defaults to None. source (str, optional): The tile source. It can be one of the following: "OPENSTREETMAP", "ROADMAP", "SATELLITE", "TERRAIN", "HYBRID", or an HTTP URL. Defaults to "OpenStreetMap". crs (str, optional): The coordinate reference system. Defaults to "EPSG:3857". to_cog (bool, optional): Convert to Cloud Optimized GeoTIFF. Defaults to False. quiet (bool, optional): Suppress output. Defaults to False. **kwargs: Additional arguments to pass to gdal.GetDriverByName("GTiff").Create(). """ import io import math import itertools import concurrent.futures import numpy from PIL import Image from osgeo import gdal, osr gdal.UseExceptions() try: import httpx SESSION = httpx.Client() except ImportError: import requests SESSION = requests.Session() xyz_tiles = { "OpenStreetMap": { "url": "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", "attribution": "OpenStreetMap", "name": "OpenStreetMap", }, "ROADMAP": { "url": "https://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/tile/{z}/{y}/{x}", "attribution": "Esri", "name": "Esri.WorldStreetMap", }, "SATELLITE": { "url": "https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}", "attribution": "Esri", "name": "Esri.WorldImagery", }, "TERRAIN": { "url": "https://server.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer/tile/{z}/{y}/{x}", "attribution": "Esri", "name": "Esri.WorldTopoMap", }, "HYBRID": { "url": "https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}", "attribution": "Esri", "name": "Esri.WorldImagery", }, } if isinstance(source, str) and source.upper() in xyz_tiles: source = xyz_tiles[source.upper()]["url"] elif isinstance(source, str) and source.startswith("http"): pass else: raise ValueError( 'source must be one of "OpenStreetMap", "ROADMAP", "SATELLITE", "TERRAIN", "HYBRID", or a URL' ) def resolution_to_zoom_level(resolution): """ Convert map resolution in meters to zoom level for Web Mercator (EPSG:3857) tiles. """ # Web Mercator tile size in meters at zoom level 0 initial_resolution = 156543.03392804097 # Calculate the zoom level zoom_level = math.log2(initial_resolution / resolution) return int(zoom_level) if isinstance(bbox, list) and len(bbox) == 4: west, south, east, north = bbox else: raise ValueError( "bbox must be a list of 4 coordinates in the format of [xmin, ymin, xmax, ymax]" ) if zoom is None and resolution is None: raise ValueError("Either zoom or resolution must be provided") elif zoom is not None and resolution is not None: raise ValueError("Only one of zoom or resolution can be provided") if resolution is not None: zoom = resolution_to_zoom_level(resolution) EARTH_EQUATORIAL_RADIUS = 6378137.0 Image.MAX_IMAGE_PIXELS = None web_mercator = osr.SpatialReference() web_mercator.ImportFromEPSG(3857) WKT_3857 = web_mercator.ExportToWkt() def from4326_to3857(lat, lon): xtile = math.radians(lon) * EARTH_EQUATORIAL_RADIUS ytile = ( math.log(math.tan(math.radians(45 + lat / 2.0))) * EARTH_EQUATORIAL_RADIUS ) return (xtile, ytile) def deg2num(lat, lon, zoom): lat_r = math.radians(lat) n = 2**zoom xtile = (lon + 180) / 360 * n ytile = (1 - math.log(math.tan(lat_r) + 1 / math.cos(lat_r)) / math.pi) / 2 * n return (xtile, ytile) def is_empty(im): extrema = im.getextrema() if len(extrema) >= 3: if len(extrema) > 3 and extrema[-1] == (0, 0): return True for ext in extrema[:3]: if ext != (0, 0): return False return True else: return extrema[0] == (0, 0) def paste_tile(bigim, base_size, tile, corner_xy, bbox): if tile is None: return bigim im = Image.open(io.BytesIO(tile)) mode = "RGB" if im.mode == "RGB" else "RGBA" size = im.size if bigim is None: base_size[0] = size[0] base_size[1] = size[1] newim = Image.new( mode, (size[0] * (bbox[2] - bbox[0]), size[1] * (bbox[3] - bbox[1])) ) else: newim = bigim dx = abs(corner_xy[0] - bbox[0]) dy = abs(corner_xy[1] - bbox[1]) xy0 = (size[0] * dx, size[1] * dy) if mode == "RGB": newim.paste(im, xy0) else: if im.mode != mode: im = im.convert(mode) if not is_empty(im): newim.paste(im, xy0) im.close() return newim def finish_picture(bigim, base_size, bbox, x0, y0, x1, y1): xfrac = x0 - bbox[0] yfrac = y0 - bbox[1] x2 = round(base_size[0] * xfrac) y2 = round(base_size[1] * yfrac) imgw = round(base_size[0] * (x1 - x0)) imgh = round(base_size[1] * (y1 - y0)) retim = bigim.crop((x2, y2, x2 + imgw, y2 + imgh)) if retim.mode == "RGBA" and retim.getextrema()[3] == (255, 255): retim = retim.convert("RGB") bigim.close() return retim def get_tile(url): retry = 3 while 1: try: r = SESSION.get(url, timeout=60) break except Exception: retry -= 1 if not retry: raise if r.status_code == 404: return None elif not r.content: return None r.raise_for_status() return r.content def draw_tile( source, lat0, lon0, lat1, lon1, zoom, filename, quiet=False, **kwargs ): x0, y0 = deg2num(lat0, lon0, zoom) x1, y1 = deg2num(lat1, lon1, zoom) x0, x1 = sorted([x0, x1]) y0, y1 = sorted([y0, y1]) corners = tuple( itertools.product( range(math.floor(x0), math.ceil(x1)), range(math.floor(y0), math.ceil(y1)), ) ) totalnum = len(corners) futures = [] with concurrent.futures.ThreadPoolExecutor(5) as executor: for x, y in corners: futures.append( executor.submit(get_tile, source.format(z=zoom, x=x, y=y)) ) bbox = (math.floor(x0), math.floor(y0), math.ceil(x1), math.ceil(y1)) bigim = None base_size = [256, 256] for k, (fut, corner_xy) in enumerate(zip(futures, corners), 1): bigim = paste_tile(bigim, base_size, fut.result(), corner_xy, bbox) if not quiet: print("Downloaded image %d/%d" % (k, totalnum)) if not quiet: print("Saving GeoTIFF. Please wait...") img = finish_picture(bigim, base_size, bbox, x0, y0, x1, y1) imgbands = len(img.getbands()) driver = gdal.GetDriverByName("GTiff") if "options" not in kwargs: kwargs["options"] = [ "COMPRESS=DEFLATE", "PREDICTOR=2", "ZLEVEL=9", "TILED=YES", ] gtiff = driver.Create( filename, img.size[0], img.size[1], imgbands, gdal.GDT_Byte, **kwargs, ) xp0, yp0 = from4326_to3857(lat0, lon0) xp1, yp1 = from4326_to3857(lat1, lon1) pwidth = abs(xp1 - xp0) / img.size[0] pheight = abs(yp1 - yp0) / img.size[1] gtiff.SetGeoTransform((min(xp0, xp1), pwidth, 0, max(yp0, yp1), 0, -pheight)) gtiff.SetProjection(WKT_3857) for band in range(imgbands): array = numpy.array(img.getdata(band), dtype="u8") array = array.reshape((img.size[1], img.size[0])) band = gtiff.GetRasterBand(band + 1) band.WriteArray(array) gtiff.FlushCache() if not quiet: print(f"Image saved to {filename}") return img try: draw_tile(source, south, west, north, east, zoom, output, quiet, **kwargs) if crs.upper() != "EPSG:3857": reproject(output, output, crs, to_cog=to_cog) elif to_cog: image_to_cog(output, output) except Exception as e: raise Exception(e) The provided code snippet includes necessary dependencies for implementing the `ee_to_geotiff` function. Write a Python function `def ee_to_geotiff( ee_object, output, bbox=None, vis_params={}, zoom=None, resolution=None, crs="EPSG:3857", to_cog=False, quiet=False, **kwargs, )` to solve the following problem: Downloads an Earth Engine object as GeoTIFF. Args: ee_object (ee.Image | ee.FeatureCollection): The Earth Engine object to download. output (str): The output path for the GeoTIFF. bbox (str, optional): The bounding box in the format [xmin, ymin, xmax, ymax]. Defaults to None, which is the bounding box of the Earth Engine object. vis_params (dict, optional): Visualization parameters. Defaults to {}. zoom (int, optional): The zoom level to download the image at. Defaults to None. resolution (float, optional): The resolution in meters to download the image at. Defaults to None. crs (str, optional): The CRS of the output image. Defaults to "EPSG:3857". to_cog (bool, optional): Whether to convert the image to Cloud Optimized GeoTIFF. Defaults to False. quiet (bool, optional): Whether to hide the download progress bar. Defaults to False. Here is the function: def ee_to_geotiff( ee_object, output, bbox=None, vis_params={}, zoom=None, resolution=None, crs="EPSG:3857", to_cog=False, quiet=False, **kwargs, ): """Downloads an Earth Engine object as GeoTIFF. Args: ee_object (ee.Image | ee.FeatureCollection): The Earth Engine object to download. output (str): The output path for the GeoTIFF. bbox (str, optional): The bounding box in the format [xmin, ymin, xmax, ymax]. Defaults to None, which is the bounding box of the Earth Engine object. vis_params (dict, optional): Visualization parameters. Defaults to {}. zoom (int, optional): The zoom level to download the image at. Defaults to None. resolution (float, optional): The resolution in meters to download the image at. Defaults to None. crs (str, optional): The CRS of the output image. Defaults to "EPSG:3857". to_cog (bool, optional): Whether to convert the image to Cloud Optimized GeoTIFF. Defaults to False. quiet (bool, optional): Whether to hide the download progress bar. Defaults to False. """ from box import Box image = None if ( not isinstance(ee_object, ee.Image) and not isinstance(ee_object, ee.ImageCollection) and not isinstance(ee_object, ee.FeatureCollection) and not isinstance(ee_object, ee.Feature) and not isinstance(ee_object, ee.Geometry) ): err_str = "\n\nThe image argument in 'addLayer' function must be an instance of one of ee.Image, ee.Geometry, ee.Feature or ee.FeatureCollection." raise AttributeError(err_str) if ( isinstance(ee_object, ee.geometry.Geometry) or isinstance(ee_object, ee.feature.Feature) or isinstance(ee_object, ee.featurecollection.FeatureCollection) ): features = ee.FeatureCollection(ee_object) width = 2 if "width" in vis_params: width = vis_params["width"] color = "000000" if "color" in vis_params: color = vis_params["color"] image_fill = features.style(**{"fillColor": color}).updateMask( ee.Image.constant(0.5) ) image_outline = features.style( **{"color": color, "fillColor": "00000000", "width": width} ) image = image_fill.blend(image_outline) elif isinstance(ee_object, ee.image.Image): image = ee_object elif isinstance(ee_object, ee.imagecollection.ImageCollection): image = ee_object.mosaic() if "palette" in vis_params: if isinstance(vis_params["palette"], Box): try: vis_params["palette"] = vis_params["palette"]["default"] except Exception as e: print("The provided palette is invalid.") raise Exception(e) elif isinstance(vis_params["palette"], str): vis_params["palette"] = check_cmap(vis_params["palette"]) elif not isinstance(vis_params["palette"], list): raise ValueError( "The palette must be a list of colors or a string or a Box object." ) map_id_dict = ee.Image(image).getMapId(vis_params) url = map_id_dict["tile_fetcher"].url_format if bbox is None: bbox = ee_to_bbox(image) if zoom is None and resolution is None: raise ValueError("Either zoom level or resolution must be specified.") tms_to_geotiff(output, bbox, zoom, resolution, url, crs, to_cog, quiet, **kwargs)
Downloads an Earth Engine object as GeoTIFF. Args: ee_object (ee.Image | ee.FeatureCollection): The Earth Engine object to download. output (str): The output path for the GeoTIFF. bbox (str, optional): The bounding box in the format [xmin, ymin, xmax, ymax]. Defaults to None, which is the bounding box of the Earth Engine object. vis_params (dict, optional): Visualization parameters. Defaults to {}. zoom (int, optional): The zoom level to download the image at. Defaults to None. resolution (float, optional): The resolution in meters to download the image at. Defaults to None. crs (str, optional): The CRS of the output image. Defaults to "EPSG:3857". to_cog (bool, optional): Whether to convert the image to Cloud Optimized GeoTIFF. Defaults to False. quiet (bool, optional): Whether to hide the download progress bar. Defaults to False.
12,430
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple The provided code snippet includes necessary dependencies for implementing the `create_grid` function. Write a Python function `def create_grid(ee_object, scale, proj=None)` to solve the following problem: Create a grid covering an Earth Engine object. Args: ee_object (ee.Image | ee.Geometry | ee.FeatureCollection): The Earth Engine object. scale (float): The grid cell size. proj (str, optional): The projection. Defaults to None. Returns: ee.FeatureCollection: The grid as a feature collection. Here is the function: def create_grid(ee_object, scale, proj=None): """Create a grid covering an Earth Engine object. Args: ee_object (ee.Image | ee.Geometry | ee.FeatureCollection): The Earth Engine object. scale (float): The grid cell size. proj (str, optional): The projection. Defaults to None. Returns: ee.FeatureCollection: The grid as a feature collection. """ if isinstance(ee_object, ee.FeatureCollection) or isinstance(ee_object, ee.Image): geometry = ee_object.geometry() elif isinstance(ee_object, ee.Geometry): geometry = ee_object else: raise ValueError( "ee_object must be an ee.FeatureCollection, ee.Image, or ee.Geometry" ) if proj is None: proj = geometry.projection() grid = geometry.coveringGrid(proj, scale) return grid
Create a grid covering an Earth Engine object. Args: ee_object (ee.Image | ee.Geometry | ee.FeatureCollection): The Earth Engine object. scale (float): The grid cell size. proj (str, optional): The projection. Defaults to None. Returns: ee.FeatureCollection: The grid as a feature collection.
12,431
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple The provided code snippet includes necessary dependencies for implementing the `check_basemap` function. Write a Python function `def check_basemap(basemap)` to solve the following problem: Check Google basemaps Args: basemap (str): The basemap name. Returns: str: The basemap name. Here is the function: def check_basemap(basemap): """Check Google basemaps Args: basemap (str): The basemap name. Returns: str: The basemap name. """ if isinstance(basemap, str): map_dict = { "ROADMAP": "Google Maps", "SATELLITE": "Google Satellite", "TERRAIN": "Google Terrain", "HYBRID": "Google Hybrid", } if basemap.upper() in map_dict.keys(): return map_dict[basemap.upper()] else: return basemap else: return basemap
Check Google basemaps Args: basemap (str): The basemap name. Returns: str: The basemap name.
12,432
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple The provided code snippet includes necessary dependencies for implementing the `get_ee_token` function. Write a Python function `def get_ee_token()` to solve the following problem: Get Earth Engine token. Returns: dict: The Earth Engine token. Here is the function: def get_ee_token(): """Get Earth Engine token. Returns: dict: The Earth Engine token. """ credential_file_path = os.path.expanduser("~/.config/earthengine/credentials") if os.path.exists(credential_file_path): with open(credential_file_path, "r") as f: credentials = json.load(f) return credentials else: print("Earth Engine credentials not found. Please run ee.Authenticate()") return None
Get Earth Engine token. Returns: dict: The Earth Engine token.
12,433
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple def random_string(string_length=3): """Generates a random string of fixed length. Args: string_length (int, optional): Fixed length. Defaults to 3. Returns: str: A random string """ import random import string # random.seed(1001) letters = string.ascii_lowercase return "".join(random.choice(letters) for i in range(string_length)) The provided code snippet includes necessary dependencies for implementing the `widget_template` function. Write a Python function `def widget_template( widget=None, opened=True, show_close_button=True, widget_icon="gear", close_button_icon="times", widget_args={}, close_button_args={}, display_widget=None, m=None, position="topright", )` to solve the following problem: Create a widget template. Args: widget (ipywidgets.Widget, optional): The widget to be displayed. Defaults to None. opened (bool, optional): Whether to open the toolbar. Defaults to True. show_close_button (bool, optional): Whether to show the close button. Defaults to True. widget_icon (str, optional): The icon name for the toolbar button. Defaults to 'gear'. close_button_icon (str, optional): The icon name for the close button. Defaults to "times". widget_args (dict, optional): Additional arguments to pass to the toolbar button. Defaults to {}. close_button_args (dict, optional): Additional arguments to pass to the close button. Defaults to {}. display_widget (ipywidgets.Widget, optional): The widget to be displayed when the toolbar is clicked. m (geemap.Map, optional): The geemap.Map instance. Defaults to None. position (str, optional): The position of the toolbar. Defaults to "topright". Here is the function: def widget_template( widget=None, opened=True, show_close_button=True, widget_icon="gear", close_button_icon="times", widget_args={}, close_button_args={}, display_widget=None, m=None, position="topright", ): """Create a widget template. Args: widget (ipywidgets.Widget, optional): The widget to be displayed. Defaults to None. opened (bool, optional): Whether to open the toolbar. Defaults to True. show_close_button (bool, optional): Whether to show the close button. Defaults to True. widget_icon (str, optional): The icon name for the toolbar button. Defaults to 'gear'. close_button_icon (str, optional): The icon name for the close button. Defaults to "times". widget_args (dict, optional): Additional arguments to pass to the toolbar button. Defaults to {}. close_button_args (dict, optional): Additional arguments to pass to the close button. Defaults to {}. display_widget (ipywidgets.Widget, optional): The widget to be displayed when the toolbar is clicked. m (geemap.Map, optional): The geemap.Map instance. Defaults to None. position (str, optional): The position of the toolbar. Defaults to "topright". """ name = "_" + random_string() # a random attribute name if "value" not in widget_args: widget_args["value"] = False if "tooltip" not in widget_args: widget_args["tooltip"] = "Toolbar" if "layout" not in widget_args: widget_args["layout"] = widgets.Layout( width="28px", height="28px", padding="0px 0px 0px 4px" ) widget_args["icon"] = widget_icon if "value" not in close_button_args: close_button_args["value"] = False if "tooltip" not in close_button_args: close_button_args["tooltip"] = "Close the tool" if "button_style" not in close_button_args: close_button_args["button_style"] = "primary" if "layout" not in close_button_args: close_button_args["layout"] = widgets.Layout( height="28px", width="28px", padding="0px 0px 0px 4px" ) close_button_args["icon"] = close_button_icon toolbar_button = widgets.ToggleButton(**widget_args) close_button = widgets.ToggleButton(**close_button_args) toolbar_widget = widgets.VBox() toolbar_widget.children = [toolbar_button] toolbar_header = widgets.HBox() if show_close_button: toolbar_header.children = [close_button, toolbar_button] else: toolbar_header.children = [toolbar_button] toolbar_footer = widgets.VBox() if widget is not None: toolbar_footer.children = [ widget, ] else: toolbar_footer.children = [] def toolbar_btn_click(change): if change["new"]: close_button.value = False toolbar_widget.children = [toolbar_header, toolbar_footer] if display_widget is not None: widget.outputs = () with widget: display(display_widget) else: toolbar_widget.children = [toolbar_button] toolbar_button.observe(toolbar_btn_click, "value") def close_btn_click(change): if change["new"]: toolbar_button.value = False if m is not None: control = getattr(m, name) if control is not None and control in m.controls: m.remove_control(control) delattr(m, name) toolbar_widget.close() close_button.observe(close_btn_click, "value") toolbar_button.value = opened if m is not None: import ipyleaflet toolbar_control = ipyleaflet.WidgetControl( widget=toolbar_widget, position=position ) if toolbar_control not in m.controls: m.add_control(toolbar_control) setattr(m, name, toolbar_control) else: return toolbar_widget
Create a widget template. Args: widget (ipywidgets.Widget, optional): The widget to be displayed. Defaults to None. opened (bool, optional): Whether to open the toolbar. Defaults to True. show_close_button (bool, optional): Whether to show the close button. Defaults to True. widget_icon (str, optional): The icon name for the toolbar button. Defaults to 'gear'. close_button_icon (str, optional): The icon name for the close button. Defaults to "times". widget_args (dict, optional): Additional arguments to pass to the toolbar button. Defaults to {}. close_button_args (dict, optional): Additional arguments to pass to the close button. Defaults to {}. display_widget (ipywidgets.Widget, optional): The widget to be displayed when the toolbar is clicked. m (geemap.Map, optional): The geemap.Map instance. Defaults to None. position (str, optional): The position of the toolbar. Defaults to "topright".
12,434
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple The provided code snippet includes necessary dependencies for implementing the `geotiff_to_image` function. Write a Python function `def geotiff_to_image(image: str, output: str) -> None` to solve the following problem: Converts a GeoTIFF file to a JPEG/PNG image. Args: image (str): The path to the input GeoTIFF file. output (str): The path to save the output JPEG/PNG file. Returns: None Here is the function: def geotiff_to_image(image: str, output: str) -> None: """ Converts a GeoTIFF file to a JPEG/PNG image. Args: image (str): The path to the input GeoTIFF file. output (str): The path to save the output JPEG/PNG file. Returns: None """ import rasterio from PIL import Image # Open the GeoTIFF file with rasterio.open(image) as dataset: # Read the image data data = dataset.read() # Convert the image data to 8-bit format (assuming it's not already) if dataset.dtypes[0] != "uint8": data = (data / data.max() * 255).astype("uint8") # Convert the image data to RGB format if it's a single band image if dataset.count == 1: data = data.squeeze() data = data.reshape((1, data.shape[0], data.shape[1])) data = data.repeat(3, axis=0) # Create a PIL Image object from the image data image = Image.fromarray(data.transpose(1, 2, 0)) # Save the image as a JPEG file image.save(output)
Converts a GeoTIFF file to a JPEG/PNG image. Args: image (str): The path to the input GeoTIFF file. output (str): The path to save the output JPEG/PNG file. Returns: None
12,435
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple def install_package(package): """Install a Python package. Args: package (str | list): The package name or a GitHub URL or a list of package names or GitHub URLs. """ import subprocess if isinstance(package, str): packages = [package] for package in packages: if package.startswith("https"): package = f"git+{package}" # Execute pip install command and show output in real-time command = f"pip install {package}" process = subprocess.Popen(command.split(), stdout=subprocess.PIPE) # Print output in real-time while True: output = process.stdout.readline() if output == b"" and process.poll() is not None: break if output: print(output.decode("utf-8").strip()) # Wait for process to complete process.wait() The provided code snippet includes necessary dependencies for implementing the `xee_to_image` function. Write a Python function `def xee_to_image( xds, filenames: Optional[Union[str, List[str]]] = None, out_dir: Optional[str] = None, crs: Optional[str] = None, nodata: Optional[float] = None, driver: str = "COG", time_unit: str = "D", quiet: bool = False, **kwargs, ) -> None` to solve the following problem: Convert xarray Dataset to georeferenced images. Args: xds (xr.Dataset): The xarray Dataset to convert to images. filenames (Union[str, List[str]], optional): Output filenames for the images. If a single string is provided, it will be used as the filename for all images. If a list of strings is provided, the filenames will be used in order. Defaults to None. out_dir (str, optional): Output directory for the images. Defaults to current working directory. crs (str, optional): Coordinate reference system (CRS) of the output images. If not provided, the CRS is inferred from the Dataset's attributes ('crs' attribute) or set to 'EPSG:4326'. nodata (float, optional): The nodata value used for the output images. Defaults to None. driver (str, optional): Driver used for writing the output images, such as 'GTiff'. Defaults to "COG". time_unit (str, optional): Time unit used for generating default filenames. Defaults to 'D'. quiet (bool, optional): If True, suppresses progress messages. Defaults to False. **kwargs: Additional keyword arguments passed to rioxarray's `rio.to_raster()` function. Returns: None Raises: ValueError: If the number of filenames doesn't match the number of time steps in the Dataset. Here is the function: def xee_to_image( xds, filenames: Optional[Union[str, List[str]]] = None, out_dir: Optional[str] = None, crs: Optional[str] = None, nodata: Optional[float] = None, driver: str = "COG", time_unit: str = "D", quiet: bool = False, **kwargs, ) -> None: """ Convert xarray Dataset to georeferenced images. Args: xds (xr.Dataset): The xarray Dataset to convert to images. filenames (Union[str, List[str]], optional): Output filenames for the images. If a single string is provided, it will be used as the filename for all images. If a list of strings is provided, the filenames will be used in order. Defaults to None. out_dir (str, optional): Output directory for the images. Defaults to current working directory. crs (str, optional): Coordinate reference system (CRS) of the output images. If not provided, the CRS is inferred from the Dataset's attributes ('crs' attribute) or set to 'EPSG:4326'. nodata (float, optional): The nodata value used for the output images. Defaults to None. driver (str, optional): Driver used for writing the output images, such as 'GTiff'. Defaults to "COG". time_unit (str, optional): Time unit used for generating default filenames. Defaults to 'D'. quiet (bool, optional): If True, suppresses progress messages. Defaults to False. **kwargs: Additional keyword arguments passed to rioxarray's `rio.to_raster()` function. Returns: None Raises: ValueError: If the number of filenames doesn't match the number of time steps in the Dataset. """ import numpy as np try: import rioxarray except ImportError: install_package("rioxarray") import rioxarray if crs is None and "crs" in xds.attrs: crs = xds.attrs["crs"] if crs is None: crs = "EPSG:4326" if out_dir is None: out_dir = os.getcwd() if not os.path.exists(out_dir): os.makedirs(out_dir) if isinstance(filenames, str): filenames = [filenames] if isinstance(filenames, list): if len(filenames) != len(xds.time): raise ValueError( "The number of filenames must match the number of time steps" ) coords = [coord for coord in xds.coords] x_dim = coords[1] y_dim = coords[2] for index, time in enumerate(xds.time.values): if nodata is not None: # Create a Boolean mask where all three variables are zero (nodata) mask = (xds == nodata).all(dim="time") # Set nodata values based on the mask for all variables xds = xds.where(~mask, other=np.nan) if not quiet: print(f"Processing {index + 1}/{len(xds.time.values)}: {time}") image = xds.sel(time=time) # transform the image to suit rioxarray format image = ( image.rename({y_dim: "y", x_dim: "x"}) .transpose("y", "x") .rio.write_crs(crs) ) if filenames is None: date = np.datetime_as_string(time, unit=time_unit) filename = f"{date}.tif" else: filename = filenames.pop() output_path = os.path.join(out_dir, filename) image.rio.to_raster(output_path, driver=driver, **kwargs)
Convert xarray Dataset to georeferenced images. Args: xds (xr.Dataset): The xarray Dataset to convert to images. filenames (Union[str, List[str]], optional): Output filenames for the images. If a single string is provided, it will be used as the filename for all images. If a list of strings is provided, the filenames will be used in order. Defaults to None. out_dir (str, optional): Output directory for the images. Defaults to current working directory. crs (str, optional): Coordinate reference system (CRS) of the output images. If not provided, the CRS is inferred from the Dataset's attributes ('crs' attribute) or set to 'EPSG:4326'. nodata (float, optional): The nodata value used for the output images. Defaults to None. driver (str, optional): Driver used for writing the output images, such as 'GTiff'. Defaults to "COG". time_unit (str, optional): Time unit used for generating default filenames. Defaults to 'D'. quiet (bool, optional): If True, suppresses progress messages. Defaults to False. **kwargs: Additional keyword arguments passed to rioxarray's `rio.to_raster()` function. Returns: None Raises: ValueError: If the number of filenames doesn't match the number of time steps in the Dataset.
12,436
import csv import datetime import io import json import math import os import requests import shutil import tarfile import urllib.request import warnings import zipfile import ee import ipywidgets as widgets from ipytree import Node, Tree from typing import Union, List, Dict, Optional, Tuple def array_to_memory_file( array, source: str = None, dtype: str = None, compress: str = "deflate", transpose: bool = True, cellsize: float = None, crs: str = None, transform: tuple = None, driver="COG", **kwargs, ): """Convert a NumPy array to a memory file. Args: array (numpy.ndarray): The input NumPy array. source (str, optional): Path to the source file to extract metadata from. Defaults to None. dtype (str, optional): The desired data type of the array. Defaults to None. compress (str, optional): The compression method for the output file. Defaults to "deflate". transpose (bool, optional): Whether to transpose the array from (bands, rows, columns) to (rows, columns, bands). Defaults to True. cellsize (float, optional): The cell size of the array if source is not provided. Defaults to None. crs (str, optional): The coordinate reference system of the array if source is not provided. Defaults to None. transform (tuple, optional): The affine transformation matrix if source is not provided. Defaults to None. driver (str, optional): The driver to use for creating the output file, such as 'GTiff'. Defaults to "COG". **kwargs: Additional keyword arguments to be passed to the rasterio.open() function. Returns: rasterio.DatasetReader: The rasterio dataset reader object for the converted array. """ import rasterio import numpy as np import xarray as xr if isinstance(array, xr.DataArray): coords = [coord for coord in array.coords] if coords[0] == "time": x_dim = coords[1] y_dim = coords[2] if array.dims[0] == "time": array = array.isel(time=0) array = array.rename({y_dim: "y", x_dim: "x"}).transpose("y", "x") array = array.values if array.ndim == 3 and transpose: array = np.transpose(array, (1, 2, 0)) if source is not None: with rasterio.open(source) as src: crs = src.crs transform = src.transform if compress is None: compress = src.compression else: if cellsize is None: raise ValueError("cellsize must be provided if source is not provided") if crs is None: raise ValueError( "crs must be provided if source is not provided, such as EPSG:3857" ) if "transform" not in kwargs: # Define the geotransformation parameters xmin, ymin, xmax, ymax = ( 0, 0, cellsize * array.shape[1], cellsize * array.shape[0], ) # (west, south, east, north, width, height) transform = rasterio.transform.from_bounds( xmin, ymin, xmax, ymax, array.shape[1], array.shape[0] ) else: transform = kwargs["transform"] if dtype is None: # Determine the minimum and maximum values in the array min_value = np.min(array) max_value = np.max(array) # Determine the best dtype for the array if min_value >= 0 and max_value <= 1: dtype = np.float32 elif min_value >= 0 and max_value <= 255: dtype = np.uint8 elif min_value >= -128 and max_value <= 127: dtype = np.int8 elif min_value >= 0 and max_value <= 65535: dtype = np.uint16 elif min_value >= -32768 and max_value <= 32767: dtype = np.int16 else: dtype = np.float64 # Convert the array to the best dtype array = array.astype(dtype) # Define the GeoTIFF metadata metadata = { "driver": driver, "height": array.shape[0], "width": array.shape[1], "dtype": array.dtype, "crs": crs, "transform": transform, } if array.ndim == 2: metadata["count"] = 1 elif array.ndim == 3: metadata["count"] = array.shape[2] if compress is not None: metadata["compress"] = compress metadata.update(**kwargs) # Create a new memory file and write the array to it memory_file = rasterio.MemoryFile() dst = memory_file.open(**metadata) if array.ndim == 2: dst.write(array, 1) elif array.ndim == 3: for i in range(array.shape[2]): dst.write(array[:, :, i], i + 1) dst.close() # Read the dataset from memory dataset_reader = rasterio.open(dst.name, mode="r") return dataset_reader The provided code snippet includes necessary dependencies for implementing the `array_to_image` function. Write a Python function `def array_to_image( array, output: str = None, source: str = None, dtype: str = None, compress: str = "deflate", transpose: bool = True, cellsize: float = None, crs: str = None, driver: str = "COG", **kwargs, ) -> str` to solve the following problem: Save a NumPy array as a GeoTIFF using the projection information from an existing GeoTIFF file. Args: array (np.ndarray): The NumPy array to be saved as a GeoTIFF. output (str): The path to the output image. If None, a temporary file will be created. Defaults to None. source (str, optional): The path to an existing GeoTIFF file with map projection information. Defaults to None. dtype (np.dtype, optional): The data type of the output array. Defaults to None. compress (str, optional): The compression method. Can be one of the following: "deflate", "lzw", "packbits", "jpeg". Defaults to "deflate". transpose (bool, optional): Whether to transpose the array from (bands, rows, columns) to (rows, columns, bands). Defaults to True. cellsize (float, optional): The resolution of the output image in meters. Defaults to None. crs (str, optional): The CRS of the output image. Defaults to None. driver (str, optional): The driver to use for creating the output file, such as 'GTiff'. Defaults to "COG". **kwargs: Additional keyword arguments to be passed to the rasterio.open() function. Here is the function: def array_to_image( array, output: str = None, source: str = None, dtype: str = None, compress: str = "deflate", transpose: bool = True, cellsize: float = None, crs: str = None, driver: str = "COG", **kwargs, ) -> str: """Save a NumPy array as a GeoTIFF using the projection information from an existing GeoTIFF file. Args: array (np.ndarray): The NumPy array to be saved as a GeoTIFF. output (str): The path to the output image. If None, a temporary file will be created. Defaults to None. source (str, optional): The path to an existing GeoTIFF file with map projection information. Defaults to None. dtype (np.dtype, optional): The data type of the output array. Defaults to None. compress (str, optional): The compression method. Can be one of the following: "deflate", "lzw", "packbits", "jpeg". Defaults to "deflate". transpose (bool, optional): Whether to transpose the array from (bands, rows, columns) to (rows, columns, bands). Defaults to True. cellsize (float, optional): The resolution of the output image in meters. Defaults to None. crs (str, optional): The CRS of the output image. Defaults to None. driver (str, optional): The driver to use for creating the output file, such as 'GTiff'. Defaults to "COG". **kwargs: Additional keyword arguments to be passed to the rasterio.open() function. """ import numpy as np import rasterio import xarray as xr if output is None: return array_to_memory_file( array, source, dtype, compress, transpose, cellsize, crs, driver, **kwargs ) if isinstance(array, xr.DataArray): coords = [coord for coord in array.coords] if coords[0] == "time": x_dim = coords[1] y_dim = coords[2] if array.dims[0] == "time": array = array.isel(time=0) array = array.rename({y_dim: "y", x_dim: "x"}).transpose("y", "x") array = array.values if array.ndim == 3 and transpose: array = np.transpose(array, (1, 2, 0)) out_dir = os.path.dirname(os.path.abspath(output)) if not os.path.exists(out_dir): os.makedirs(out_dir) if not output.endswith(".tif"): output += ".tif" if source is not None: with rasterio.open(source) as src: crs = src.crs transform = src.transform if compress is None: compress = src.compression else: if cellsize is None: raise ValueError("resolution must be provided if source is not provided") if crs is None: raise ValueError( "crs must be provided if source is not provided, such as EPSG:3857" ) if "transform" not in kwargs: # Define the geotransformation parameters xmin, ymin, xmax, ymax = ( 0, 0, cellsize * array.shape[1], cellsize * array.shape[0], ) transform = rasterio.transform.from_bounds( xmin, ymin, xmax, ymax, array.shape[1], array.shape[0] ) else: transform = kwargs["transform"] if dtype is None: # Determine the minimum and maximum values in the array min_value = np.min(array) max_value = np.max(array) # Determine the best dtype for the array if min_value >= 0 and max_value <= 1: dtype = np.float32 elif min_value >= 0 and max_value <= 255: dtype = np.uint8 elif min_value >= -128 and max_value <= 127: dtype = np.int8 elif min_value >= 0 and max_value <= 65535: dtype = np.uint16 elif min_value >= -32768 and max_value <= 32767: dtype = np.int16 else: dtype = np.float64 # Convert the array to the best dtype array = array.astype(dtype) # Define the GeoTIFF metadata metadata = { "driver": driver, "height": array.shape[0], "width": array.shape[1], "dtype": array.dtype, "crs": crs, "transform": transform, } if array.ndim == 2: metadata["count"] = 1 elif array.ndim == 3: metadata["count"] = array.shape[2] if compress is not None: metadata["compress"] = compress metadata.update(**kwargs) # Create a new GeoTIFF file and write the array to it with rasterio.open(output, "w", **metadata) as dst: if array.ndim == 2: dst.write(array, 1) elif array.ndim == 3: for i in range(array.shape[2]): dst.write(array[:, :, i], i + 1)
Save a NumPy array as a GeoTIFF using the projection information from an existing GeoTIFF file. Args: array (np.ndarray): The NumPy array to be saved as a GeoTIFF. output (str): The path to the output image. If None, a temporary file will be created. Defaults to None. source (str, optional): The path to an existing GeoTIFF file with map projection information. Defaults to None. dtype (np.dtype, optional): The data type of the output array. Defaults to None. compress (str, optional): The compression method. Can be one of the following: "deflate", "lzw", "packbits", "jpeg". Defaults to "deflate". transpose (bool, optional): Whether to transpose the array from (bands, rows, columns) to (rows, columns, bands). Defaults to True. cellsize (float, optional): The resolution of the output image in meters. Defaults to None. crs (str, optional): The CRS of the output image. Defaults to None. driver (str, optional): The driver to use for creating the output file, such as 'GTiff'. Defaults to "COG". **kwargs: Additional keyword arguments to be passed to the rasterio.open() function.
12,437
import os import warnings from typing import Optional, Any, Dict import ee import ipyleaflet import ipywidgets as widgets from box import Box from bqplot import pyplot as plt from IPython.display import display from .basemaps import get_xyz_dict, xyz_to_leaflet from .common import * from .conversion import * from .ee_tile_layers import * from . import core from . import map_widgets from . import toolbar from .plot import * from .timelapse import * from .legends import builtin_legends from . import examples class EELeafletTileLayer(ipyleaflet.TileLayer): """An ipyleaflet TileLayer that shows an EE object.""" EE_TYPES = ( ee.Geometry, ee.Feature, ee.FeatureCollection, ee.Image, ee.ImageCollection, ) def __init__( self, ee_object, vis_params=None, name="Layer untitled", shown=True, opacity=1.0, **kwargs, ): """Initialize the ipyleaflet tile layer. Args: ee_object (Collection|Feature|Image|MapId): The object to add to the map. vis_params (dict, optional): The visualization parameters. Defaults to None. name (str, optional): The name of the layer. Defaults to 'Layer untitled'. shown (bool, optional): A flag indicating whether the layer should be on by default. Defaults to True. opacity (float, optional): The layer's opacity represented as a number between 0 and 1. Defaults to 1. """ self._ee_object = ee_object self.url_format = _get_tile_url_format( ee_object, _validate_vis_params(vis_params) ) super().__init__( url=self.url_format, attribution="Google Earth Engine", name=name, opacity=opacity, visible=shown, max_zoom=24, **kwargs, ) def _calculate_vis_stats(self, *, bounds, bands): """Calculate stats used for visualization parameters. Stats are calculated consistently with the Code Editor visualization parameters, and are cached to avoid recomputing for the same bounds and bands. Args: bounds (ee.Geometry|ee.Feature|ee.FeatureCollection): The bounds to sample. bands (tuple): The bands to sample. Returns: tuple: The minimum, maximum, standard deviation, and mean values across the specified bands. """ stat_reducer = ( ee.Reducer.minMax() .combine(ee.Reducer.mean().unweighted(), sharedInputs=True) .combine(ee.Reducer.stdDev(), sharedInputs=True) ) stats = ( self._ee_object.select(bands) .reduceRegion( reducer=stat_reducer, geometry=bounds, bestEffort=True, maxPixels=10_000, crs="SR-ORG:6627", scale=1, ) .getInfo() ) mins, maxs, stds, means = [ {v for k, v in stats.items() if k.endswith(stat) and v is not None} for stat in ("_min", "_max", "_stdDev", "_mean") ] if any(len(vals) == 0 for vals in (mins, maxs, stds, means)): raise ValueError("No unmasked pixels were sampled.") min_val = min(mins) max_val = max(maxs) std_dev = sum(stds) / len(stds) mean = sum(means) / len(means) return (min_val, max_val, std_dev, mean) def calculate_vis_minmax(self, *, bounds, bands=None, percent=None, sigma=None): """Calculate the min and max clip values for visualization. Args: bounds (ee.Geometry|ee.Feature|ee.FeatureCollection): The bounds to sample. bands (list, optional): The bands to sample. If None, all bands are used. percent (float, optional): The percent to use when stretching. sigma (float, optional): The number of standard deviations to use when stretching. Returns: tuple: The minimum and maximum values to clip to. """ bands = self._ee_object.bandNames() if bands is None else tuple(bands) try: min_val, max_val, std, mean = self._calculate_vis_stats( bounds=bounds, bands=bands ) except ValueError: return (0, 0) if sigma is not None: stretch_min = mean - sigma * std stretch_max = mean + sigma * std elif percent is not None: x = (max_val - min_val) * (1 - percent) stretch_min = min_val + x stretch_max = max_val - x else: stretch_min = min_val stretch_max = max_val return (stretch_min, stretch_max) The provided code snippet includes necessary dependencies for implementing the `ee_tile_layer` function. Write a Python function `def ee_tile_layer( ee_object, vis_params={}, name="Layer untitled", shown=True, opacity=1.0 )` to solve the following problem: Converts and Earth Engine layer to ipyleaflet TileLayer. Args: ee_object (Collection|Feature|Image|MapId): The object to add to the map. vis_params (dict, optional): The visualization parameters. Defaults to {}. name (str, optional): The name of the layer. Defaults to 'Layer untitled'. shown (bool, optional): A flag indicating whether the layer should be on by default. Defaults to True. opacity (float, optional): The layer's opacity represented as a number between 0 and 1. Defaults to 1. Here is the function: def ee_tile_layer( ee_object, vis_params={}, name="Layer untitled", shown=True, opacity=1.0 ): """Converts and Earth Engine layer to ipyleaflet TileLayer. Args: ee_object (Collection|Feature|Image|MapId): The object to add to the map. vis_params (dict, optional): The visualization parameters. Defaults to {}. name (str, optional): The name of the layer. Defaults to 'Layer untitled'. shown (bool, optional): A flag indicating whether the layer should be on by default. Defaults to True. opacity (float, optional): The layer's opacity represented as a number between 0 and 1. Defaults to 1. """ return EELeafletTileLayer(ee_object, vis_params, name, shown, opacity)
Converts and Earth Engine layer to ipyleaflet TileLayer. Args: ee_object (Collection|Feature|Image|MapId): The object to add to the map. vis_params (dict, optional): The visualization parameters. Defaults to {}. name (str, optional): The name of the layer. Defaults to 'Layer untitled'. shown (bool, optional): A flag indicating whether the layer should be on by default. Defaults to True. opacity (float, optional): The layer's opacity represented as a number between 0 and 1. Defaults to 1.