Details¶
geeViz.geeView¶
View GEE objects using Python
geeViz.geeView is the core module for managing GEE objects on the geeViz mapper object. geeViz instantiates an instance of the mapper class as Map by default. Layers can be added to the map using Map.addLayer or Map.addTimeLapse and then viewed using the Map.view method.
- geeViz.geeView.baseDomain(url)[source]¶
Get root domain for a given url
- Parameters:
url (str) – URL to find the base domain of
- Returns:
domain of given URL
- Return type:
str
- geeViz.geeView.cleanAccessToken(accessToken)[source]¶
Remove trailing ‘….’ in generated access token
- Parameters:
accessToken (str) – Raw access token
- Returns:
Given access token without trailing ‘….’
- Return type:
str
- geeViz.geeView.color_dict_maker(gradient: list[list[int]]) dict [source]¶
Takes in a list of RGB sub-lists and returns dictionary of colors in RGB and hex form for use in a graphing function defined later on
- geeViz.geeView.get_poly_gradient_ct(palette: list[str], min: int, max: int) list[str] [source]¶
Take a palette and a set of min and max stretch values to get a 1:1 value to color hex list
- Parameters:
palette (list) – A list of hex code colors that will be interpolated
min (int) – The min value for the stretch
max (int) – The max value for the stretch
- Returns:
A list of linearly interpolated hex codes where there is 1:1 color to value from min-max (inclusive)
- Return type:
list
>>> import geeViz.geeView as gv >>> viz = {"palette": ["#FFFF00", "00F", "0FF", "FF0000"], "min": 1, "max": 20} >>> color_ramp = gv.get_poly_gradient_ct(viz["palette"], viz["min"], viz["max"]) >>> print("Color ramp:", color_ramp)
- geeViz.geeView.hex_to_rgb(value: str) tuple [source]¶
Return (red, green, blue) for the color given as #rrggbb.
- geeViz.geeView.isPortActive(port: int = 8001)[source]¶
See if a given port number is currently active
- Parameters:
port (int) – Port number to check status of
- Returns:
Whether or not the port is already active
- Return type:
bool
- geeViz.geeView.is_notebook()[source]¶
Check if inside Jupyter shell
- Returns:
Whether inside Jupyter shell or not
- Return type:
bool
- geeViz.geeView.linear_gradient(start_hex: str, finish_hex: str = '#FFFFFF', n: int = 10) dict [source]¶
returns a gradient list of (n) colors between two hex colors. start_hex and finish_hex should be the full six-digit color string, inlcuding the number sign (“#FFFFFF”)
- class geeViz.geeView.mapper(port: int = 8001)[source]¶
Primary geeViz map setup and manipulation object
Map object that is used to manage layers, activated user input methods, and launching the map viewer user interface
- Parameters:
port (int, default 8001) – Which port to user for web server. Sometimes a port will become “stuck,” so this will need set to some other number than what it was set at in previous runs of a given session.
- port¶
Which port to user for web server. Sometimes a port will become “stuck,” so this will need set to some other number than what it was set at in previous runs of a given session.
- Type:
int, default 8001
- proxy_url¶
The proxy url the web server runs through for either Google Colab or Vertex AI Workbench. This is automatically specified in Google Colab, but in Vertex AI Workbench, the Map.proxy_url must be specified as the current URL Workbench Notebook is running from (e.g. https://code-dot-region.notebooks.googleusercontent.com/).
- Type:
str, default None
- refreshTokenPath¶
Refresh token credentials file path
- Type:
str, default ee.oauth.get_credentials_path()
- serviceKeyPath¶
Location of a service account key json. If provided, this will be used for authentication inside geeView instead of the refresh token
- Type:
str, default None
- project¶
Can override which project geeView will use for authentication. While geeViz will try to find a project if ee.data._cloud_api_user_project isn’t already set (usually by ee.Initialize(project=”someProjectID”)) by prompting the user to enter one, in some builds, this does not work. Set this attribute manually if the URL say project=None when launching geeView using Map.view().
- Type:
str, default ee.data._cloud_api_user_project
- turnOffLayersWhenTimeLapseIsOn¶
Whether all other layers should be turned off when a time lapse is turned on. This is set to True by default to avoid confusing layer order rendering that can occur when time lapses and non-time lapses are visible at the same time. Often this confusion is fine and visualizing time lapses and other layers is desired. Set Map.turnOffLayersWhenTimeLapseIsOn to False in this instance.
- Type:
bool, default True
- addAreaChartLayer(image: Image | ImageCollection, params: dict = {}, name: str | None = None, shouldChart: bool = True)[source]¶
Use this method to add a layer for area charting that you do not want as a map layer as well. Once you add all area chart layers to the map, you can turn them on using the Map.populateAreaChartLayerSelect method. This will create a selection menu inside the Area Tools -> Area Tools Parameters menu. You can then turn layers to include in any area charts on and off from that menu.
- Parameters:
image (ImageCollection, Image) – ee Image or ImageCollection to add to include in area charting.
params (dict) –
Primary set of parameters for charting setup (colors, chart types, etc), charting, etc. The accepted keys are:
{
“reducer” (Reducer, default ee.Reducer.mean() if no bandName_class_values, bandName_class_names, bandName_class_palette properties are available. ee.Reducer.frequencyHistogram if those are available or thematic:True (see below)): The reducer used to compute zonal summary statistics.,
”crs” (str, default “EPSG:5070”): the coordinate reference system string to use for are chart zonal stats,
”transform” (list, default [30, 0, -2361915, 0, -30, 3177735]): the transform to snap to for zonal stats,
”scale” (int, default None): The spatial resolution to use for zonal stats. Only specify if transform : None.
”line” (bool, default True): Whether to create a line chart,
”sankey” (bool, default False): Whether to create Sankey charts - only available for thematic (discrete) inputs that have a system:time_start property set for each image,
”chartLabelMaxWidth” (int, default 40): The maximum number of characters, including spaces, allowed in a single line of a chart class label. The class name will be broken at this number of characters, including spaces, to go to the next line,
”chartLabelMaxLength” (int, default 100): The maximum number of characters, including spaces, allowed in a chart class label. Any class name with more characters, including spaces, than this number will be cut off at this number of characters,
”sankeyTransitionPeriods” (list of lists, default None): The years to use as transition periods for sankey charts (e.g. [[1985,1987],[2000,2002],[2020,2022]]). If not provided, users can enter years in the map user interface under Area Tools -> Transition Charting Periods. These will automatically be used for any layers where no sankeyTransitionPeriods were provided. If years are provided, the years in the user interface will not be used for that layer,
”sankeyMinPercentage” (float, default 0.5): The minimum percentage a given class has to be to be shown in the sankey chart,
”thematic” (bool): Whether input has discrete values or not. If True, it forces the reducer to ee.Reducer.frequencyHistogram() even if not specified and even if bandName_class_values, bandName_class_names, bandName_class_palette properties are not available,
”palette” (list, or comma-separated strings): List of hex codes for colors for charts. This is especially useful when bandName_class_values, bandName_class_names, bandName_class_palette properties are not available, but there is a desired set of colors for each band to have on the chart,
”showGrid” (bool, default True): Whether to show the grid lines on the line or bar graph,
”rangeSlider” (bool,default False): Whether to include the x-axis range selector on the bottom of each graph (https://plotly.com/javascript/range-slider/>),
”barChartMaxClasses” (int, default 20): The maximum number of classes to show for image bar charts. Will automatically only show the top bartChartMaxClasses in any image bar chart. Any downloaded csv table will still have all of the class counts,
”minZoomSpecifiedScale” (int, default 11): The map zoom level where any lower zoom level, not including this zoom level, will multiply the spatial resolution used for the zonal stats by 2 for each lower zoom level. E.g. if the minZoomSpecifiedScale is 9 and the scale is 30, any zoom level >= 9 will compute zonal stats at 30m spatial resolution. Then, at zoom level 8, it will be 60m. Zoom level 7 will be 120m, etc,
”chartPrecision” (int, default 3): Used to override the default global precision settings for a specific area charting layer. See setQueryPrecision for setting the global charting precision. When specified, for this specific area charting layer, will show the larger of chartPrecision decimal places or ceiling(chartDecimalProportion * total decimal places). E.g. if the number is 1.12345678, 0.25 of 8 decimal places is 2, so 3 will be used and yield 1.123,
”chartDecimalProportion” (float, default 0.25): Used to override the default global precision settings for a specific area charting layer. See setQueryPrecision for setting the global charting precision. When specified, for this specific area charting layer, will show the larger of chartPrecision decimal places or chartDecimalProportion * total decimal places. E.g. if the number is 1.1234567891234, ceiling(0.25 of 13) decimal places is 4, so 4 will be used and yield 1.1235,
”hovermode” (str, default “closest”): The mode to show hover text in area summary charts. Options include “closest”, “x”, “y”, “x unified”, and “y unified”,
”yAxisLabel” (str, default an appropriate label based on whether data are thematic or continuous): The Y axis label that will be included in charts. Defaults to a unit of % area for thematic and mean for continuous data,
”chartType” (str, default “line” for ee.ImageCollection and “bar” for ee.Image objects): The type of chart to show. Options include “line”, “bar”, “stacked-line”, and “stacked-bar”. This is only used for ee.ImageCollection objects. For ee.Image objects, the chartType is always “bar”.
}
name (str) – Descriptive name for map layer that will be shown on the map UI
shouldChart (bool, optional) – Whether layer should be charted when map UI loads
>>> import geeViz.geeView as gv >>> Map = gv.Map >>> ee = gv.ee >>> lcms = ee.ImageCollection("USFS/GTAC/LCMS/v2023-9").filter('study_area=="CONUS"') >>> Map.addLayer(lcms.select(["Change_Raw_Probability.*"]), {"reducer": ee.Reducer.stdDev(), "min": 0, "max": 10}, "LCMS Change Prob") >>> Map.addAreaChartLayer(lcms, {"line": True, "layerType": "ImageCollection"}, "LCMS All Thematic Classes Line", True) >>> Map.addAreaChartLayer(lcms, {"sankey": True}, "LCMS All Thematic Classes Sankey", True) >>> Map.populateAreaChartLayerSelect() >>> Map.turnOnAutoAreaCharting() >>> Map.view()
- addLayer(image: Image | ImageCollection | Geometry | Feature | FeatureCollection, viz: dict = {}, name: str | None = None, visible: bool = True)[source]¶
Adds GEE object to the mapper object that will then be added to the map user interface with a view call.
- Parameters:
image (ImageCollection, Image, Feature, FeatureCollection, Geometry) – ee object to add to the map UI.
viz (dict) –
Primary set of parameters for map visualization, querying, charting, etc. In addition to the parameters supported by the addLayer function in the GEE Code Editor, there are several additional parameters available to help facilitate legend generation, querying, and area summaries. The accepted keys are:
- {
“min” (int, list, or comma-separated numbers): One numeric value or one per band to map onto 00.,
”max” (int, list, or comma-separated numbers): One numeric value or one per band to map onto FF,
”gain” (int, list, or comma-separated numbers): One numeric value or one per band to map onto 00-FF.,
”bias” (int, list, or comma-separated numbers): One numeric value or one per band to map onto 00-FF.,
”gamma” (int, list, or comma-separated numbers): Gamma correction factor. One numeric value or one per band.,
”palette” (str, list, or comma-separated strings): List of CSS-style color strings (single-band previews only).,
”opacity” (float): a number between 0 and 1 for initially set opacity.,
”layerType” (str, one of geeImage, geeImageCollection, geeVector, geeVectorImage, geoJSONVector): Optional parameter. For vector data (“featureCollection”, “feature”, or “geometry”), you can spcify “geeVector” if you would like to force the vector to be an actual vector object on the client. This can be slow if the ee object is large and/or complex. Otherwise, any “featureCollection”, “feature”, or “geometry” will default to “geeVectorImage” where the vector is rasterized on-the-fly for map rendering. Any querying of the vector will query the underlying vector data though. To add a geojson vector as json, just add the json as the image parameter.,
”reducer” (Reducer, default ‘ee.Reducer.lastNonNull()’): If an ImageCollection is provided, how to reduce it to create the layer that is shown on the map. Defaults to ee.Reducer.lastNonNull(),
”autoViz” (bool): Whether to take image bandName_class_values, bandName_class_names, bandName_class_palette properties to visualize, create a legend (populates classLegendDict), and apply class names to any query functions (populates queryDict),
”includeClassValues” (bool, default True): Whether to include the numeric value of each class in the legend when “autoViz”:True.
”canQuery” (bool, default True): Whether a layer can be queried when visible.,
”addToLegend” (bool, default True): Whether geeViz should try to create a legend for this layer. Sometimes setting it to False is useful for continuous multi-band inputs.,
”classLegendDict” (dict): A dictionary with a key:value of the name:color(hex) to include in legend. This is auto-populated when autoViz : True,
”queryDict” (dict): A dictionary with a key:value of the queried number:label to include if queried numeric values have corresponding label names. This is auto-populated when autoViz : True,
”queryParams” (dict, optional): Dictionary of additional parameters for querying visible map layers:
- {
“palette” (list, or comma-separated strings): List of hex codes for colors for charts. This is especially useful when bandName_class_values, bandName_class_names, bandName_class_palette properties are not available, but there is a desired set of colors for each band to have on the chart.,
”yLabel” (str, optional): Y axis label for query charts. This is useful when bandName_class_values, bandName_class_names, bandName_class_palette properties are not available, but there is a desired label for the Y axis.
}
”legendLabelLeftBefore” (str) : Label for continuous legend on the left before the numeric component,
”legendLabelLeftAfter” (str) : Label for continuous legend on the left after the numeric component,
”legendLabelRightBefore” (str) : Label for continuous legend on the right before the numeric component,
”legendLabelRightAfter” (str) : Label for continuous legend on the right after the numeric component,
”canAreaChart” (bool): whether to include this layer for area charting. If the layer is complex, area charting can be quite slow,
”areaChartParams” (dict, optional): Dictionary of additional parameters for area charting:
- {
“reducer” (Reducer, default ee.Reducer.mean() if no bandName_class_values, bandName_class_names, bandName_class_palette properties are available. ee.Reducer.frequencyHistogram if those are available or thematic:True (see below)): The reducer used to compute zonal summary statistics.,
”crs” (str, default “EPSG:5070”): the coordinate reference system string to use for are chart zonal stats,
”transform” (list, default [30, 0, -2361915, 0, -30, 3177735]): the transform to snap to for zonal stats,
”scale” (int, default None): The spatial resolution to use for zonal stats. Only specify if transform : None.
”line” (bool, default True): Whether to create a line chart,
”sankey” (bool, default False): Whether to create Sankey charts - only available for thematic (discrete) inputs that have a system:time_start property set for each image,
”chartLabelMaxWidth” (int, default 40): The maximum number of characters, including spaces, allowed in a single line of a chart class label. The class name will be broken at this number of characters, including spaces, to go to the next line,
”chartLabelMaxLength” (int, default 100): The maximum number of characters, including spaces, allowed in a chart class label. Any class name with more characters, including spaces, than this number will be cut off at this number of characters,
”sankeyTransitionPeriods” (list of lists, default None): The years to use as transition periods for sankey charts (e.g. [[1985,1987],[2000,2002],[2020,2022]]). If not provided, users can enter years in the map user interface under Area Tools -> Transition Charting Periods. These will automatically be used for any layers where no sankeyTransitionPeriods were provided. If years are provided, the years in the user interface will not be used for that layer,
”sankeyMinPercentage” (float, default 0.5): The minimum percentage a given class has to be to be shown in the sankey chart,
”thematic” (bool): Whether input has discrete values or not. If True, it forces the reducer to ee.Reducer.frequencyHistogram() even if not specified and even if bandName_class_values, bandName_class_names, bandName_class_palette properties are not available,
”palette” (list, or comma-separated strings): List of hex codes for colors for charts. This is especially useful when bandName_class_values, bandName_class_names, bandName_class_palette properties are not available, but there is a desired set of colors for each band to have on the chart,
”showGrid” (bool, default True): Whether to show the grid lines on the line or bar graph,
”rangeSlider” (bool,default False): Whether to include the x-axis range selector on the bottom of each graph (https://plotly.com/javascript/range-slider/>),
”barChartMaxClasses” (int, default 20): The maximum number of classes to show for image bar charts. Will automatically only show the top bartChartMaxClasses in any image bar chart. Any downloaded csv table will still have all of the class counts,
”minZoomSpecifiedScale” (int, default 11): The map zoom level where any lower zoom level, not including this zoom level, will multiply the spatial resolution used for the zonal stats by 2 for each lower zoom level. E.g. if the minZoomSpecifiedScale is 9 and the scale is 30, any zoom level >= 9 will compute zonal stats at 30m spatial resolution. Then, at zoom level 8, it will be 60m. Zoom level 7 will be 120m, etc,
”chartPrecision” (int, default 3): Used to override the default global precision settings for a specific area charting layer. See setQueryPrecision for setting the global charting precision. When specified, for this specific area charting layer, will show the larger of chartPrecision decimal places or ceiling(chartDecimalProportion * total decimal places). E.g. if the number is 1.12345678, 0.25 of 8 decimal places is 2, so 3 will be used and yield 1.123,
”chartDecimalProportion” (float, default 0.25): Used to override the default global precision settings for a specific area charting layer. See setQueryPrecision for setting the global charting precision. When specified, for this specific area charting layer, will show the larger of chartPrecision decimal places or chartDecimalProportion * total decimal places. E.g. if the number is 1.1234567891234, ceiling(0.25 of 13) decimal places is 4, so 4 will be used and yield 1.1235,
”hovermode” (str, default “closest”): The mode to show hover text in area summary charts. Options include “closest”, “x”, “y”, “x unified”, and “y unified”,
”yAxisLabel” (str, default an appropriate label based on whether data are thematic or continuous): The Y axis label that will be included in charts. Defaults to a unit of % area for thematic and mean for continuous data,
”chartType” (str, default “line” for ee.ImageCollection and “bar” for ee.Image objects): The type of chart to show. Options include “line”, “bar”, “stacked-line”, and “stacked-bar”. This is only used for ee.ImageCollection objects. For ee.Image objects, the chartType is always “bar”.
}
}
name (str) – Descriptive name for map layer that will be shown on the map UI
visible (bool, default True) – Whether layer should be visible when map UI loads
>>> import geeViz.geeView as gv >>> Map = gv.Map >>> ee = gv.ee >>> nlcd = ee.ImageCollection("USGS/NLCD_RELEASES/2021_REL/NLCD").select(['landcover']) >>> Map.addLayer(nlcd, {"autoViz": True}, "NLCD Land Cover / Land Use 2021") >>> Map.turnOnInspector() >>> Map.view()
- addSelectLayer(featureCollection: FeatureCollection, viz: dict = {}, name: str | None = None)[source]¶
Adds GEE featureCollection to the mapper object that will then be added as an interactive selection layer in the map user interface with a view call. This layer will be availble for selecting areas to include in area summary charts.
- Parameters:
featureCollection (FeatureCollection) – ee FeatureCollecion object to add to the map UI as a selectable layer, where each feature is selectable by clicking on it.
viz (dict, optional) –
Primary set of parameters for map visualization and specifying which feature attribute to use as the feature name (selectLayerNameProperty), etc. In addition to the parameters supported by the addLayer function in the GEE Code Editor, there are several additional parameters available to help facilitate legend generation, querying, and area summaries. The accepted keys are:
- {
“strokeColor” (str, default random color): The color of the selection layer on the map,
”strokeWeight” (int, default 3): The thickness of the polygon outlines,
”selectLayerNameProperty” (str, default first feature attribute with “name” in it or “system:index”): The attribute name to show when a user selects a feature.
}
name (str, default None) – Descriptive name for map layer that will be shown on the map UI. Will be auto-populated with Layer N if not specified
>>> import geeViz.geeView as gv >>> Map = gv.Map >>> ee = gv.ee >>> lcms = ee.ImageCollection("USFS/GTAC/LCMS/v2023-9").filter('study_area=="CONUS"') >>> Map.addLayer(lcms, {"autoViz": True, "canAreaChart": True, "areaChartParams": {"line": True, "sankey": True}}, "LCMS") >>> mtbsBoundaries = ee.FeatureCollection("USFS/GTAC/MTBS/burned_area_boundaries/v1") >>> mtbsBoundaries = mtbsBoundaries.map(lambda f: f.set("system:time_start", f.get("Ig_Date"))) >>> Map.addSelectLayer(mtbsBoundaries, {"strokeColor": "00F", "selectLayerNameProperty": "Incid_Name"}, "MTBS Fire Boundaries") >>> Map.turnOnSelectionAreaCharting() >>> Map.view()
- addTimeLapse(image: ImageCollection, viz: dict = {}, name: str | None = None, visible: bool = True)[source]¶
Adds GEE ImageCollection object to the mapper object that will then be added as an interactive time lapse in the map user interface with a view call.
- Parameters:
image (ImageCollection) – ee ImageCollecion object to add to the map UI.
viz (dict) –
Primary set of parameters for map visualization, querying, charting, etc. These are largely the same as the addLayer function. Keys unique to addTimeLapse are provided here first. In addition to the parameters supported by the addLayer function in the GEE Code Editor, there are several additional parameters available to help facilitate legend generation, querying, and area summaries. The accepted keys are:
- {
“mosaic” (bool, default False): If an ImageCollection with multiple images per time step is provided, how to reduce it to create the layer that is shown on the map. Uses ee.Reducer.lastNonNull() if True or ee.Reducer.first() if False,
”dateFormat” (str, default “YYYY”): The format of the date to show in the slider. E.g. if your data is annual, generally “YYYY” is best. If it’s monthly, generally “YYYYMM” is best. Daily, generally “YYYYMMdd”…etc.,
”advanceInterval” (str, default ‘year’): How much to advance each frame when creating each individual mosaic. One of ‘year’, ‘month’ ‘week’, ‘day’, ‘hour’, ‘minute’, or ‘second’.
”min” (int, list, or comma-separated numbers): One numeric value or one per band to map onto 00.,
”max” (int, list, or comma-separated numbers): One numeric value or one per band to map onto FF,
”gain” (int, list, or comma-separated numbers): One numeric value or one per band to map onto 00-FF.,
”bias” (int, list, or comma-separated numbers): One numeric value or one per band to map onto 00-FF.,
”gamma” (int, list, or comma-separated numbers): Gamma correction factor. One numeric value or one per band.,
”palette” (str, list, or comma-separated strings): List of CSS-style color strings (single-band previews only).,
”opacity” (float): a number between 0 and 1 for initially set opacity.,
”autoViz” (bool): Whether to take image bandName_class_values, bandName_class_names, bandName_class_palette properties to visualize, create a legend (populates classLegendDict), and apply class names to any query functions (populates queryDict),
”includeClassValues” (bool, default True): Whether to include the numeric value of each class in the legend when “autoViz”:True.
”canQuery” (bool, default True): Whether a layer can be queried when visible.,
”addToLegend” (bool, default True): Whether geeViz should try to create a legend for this layer. Sometimes setting it to False is useful for continuous multi-band inputs.,
”classLegendDict” (dict): A dictionary with a key:value of the name:color(hex) to include in legend. This is auto-populated when autoViz : True,
”queryDict” (dict): A dictionary with a key:value of the queried number:label to include if queried numeric values have corresponding label names. This is auto-populated when autoViz : True,
”queryParams” (dict, optional): Dictionary of additional parameters for querying visible map layers:
- {
“palette” (list, or comma-separated strings): List of hex codes for colors for charts. This is especially useful when bandName_class_values, bandName_class_names, bandName_class_palette properties are not available, but there is a desired set of colors for each band to have on the chart.,
”yLabel” (str, optional): Y axis label for query charts. This is useful when bandName_class_values, bandName_class_names, bandName_class_palette properties are not available, but there is a desired label for the Y axis.
}
”legendLabelLeftBefore” (str) : Label for continuous legend on the left before the numeric component,
”legendLabelLeftAfter” (str) : Label for continuous legend on the left after the numeric component,
”legendLabelRightBefore” (str) : Label for continuous legend on the right before the numeric component,
”legendLabelRightAfter” (str) : Label for continuous legend on the right after the numeric component,
”canAreaChart” (bool): whether to include this layer for area charting. If the layer is complex, area charting can be quite slow,
”areaChartParams” (dict, optional): Dictionary of additional parameters for area charting:
- {
“reducer” (Reducer, default ee.Reducer.mean() if no bandName_class_values, bandName_class_names, bandName_class_palette properties are available. ee.Reducer.frequencyHistogram if those are available or thematic:True (see below)): The reducer used to compute zonal summary statistics.,
”crs” (str, default “EPSG:5070”): the coordinate reference system string to use for are chart zonal stats,
”transform” (list, default [30, 0, -2361915, 0, -30, 3177735]): the transform to snap to for zonal stats,
”scale” (int, default None): The spatial resolution to use for zonal stats. Only specify if transform : None.
”line” (bool, default True): Whether to create a line chart,
”sankey” (bool, default False): Whether to create Sankey charts - only available for thematic (discrete) inputs that have a system:time_start property set for each image,
”chartLabelMaxWidth” (int, default 40): The maximum number of characters, including spaces, allowed in a single line of a chart class label. The class name will be broken at this number of characters, including spaces, to go to the next line,
”chartLabelMaxLength” (int, default 100): The maximum number of characters, including spaces, allowed in a chart class label. Any class name with more characters, including spaces, than this number will be cut off at this number of characters,
”sankeyTransitionPeriods” (list of lists, default None): The years to use as transition periods for sankey charts (e.g. [[1985,1987],[2000,2002],[2020,2022]]). If not provided, users can enter years in the map user interface under Area Tools -> Transition Charting Periods. These will automatically be used for any layers where no sankeyTransitionPeriods were provided. If years are provided, the years in the user interface will not be used for that layer,
”sankeyMinPercentage” (float, default 0.5): The minimum percentage a given class has to be to be shown in the sankey chart,
”thematic” (bool): Whether input has discrete values or not. If True, it forces the reducer to ee.Reducer.frequencyHistogram() even if not specified and even if bandName_class_values, bandName_class_names, bandName_class_palette properties are not available,
”palette” (list, or comma-separated strings): List of hex codes for colors for charts. This is especially useful when bandName_class_values, bandName_class_names, bandName_class_palette properties are not available, but there is a desired set of colors for each band to have on the chart,
”showGrid” (bool, default True): Whether to show the grid lines on the line or bar graph,
”rangeSlider” (bool,default False): Whether to include the x-axis range selector on the bottom of each graph (https://plotly.com/javascript/range-slider/>),
”barChartMaxClasses” (int, default 20): The maximum number of classes to show for image bar charts. Will automatically only show the top bartChartMaxClasses in any image bar chart. Any downloaded csv table will still have all of the class counts,
”minZoomSpecifiedScale” (int, default 11): The map zoom level where any lower zoom level, not including this zoom level, will multiply the spatial resolution used for the zonal stats by 2 for each lower zoom level. E.g. if the minZoomSpecifiedScale is 9 and the scale is 30, any zoom level >= 9 will compute zonal stats at 30m spatial resolution. Then, at zoom level 8, it will be 60m. Zoom level 7 will be 120m, etc,
”chartPrecision” (int, default 3): Used to override the default global precision settings for a specific area charting layer. See setQueryPrecision for setting the global charting precision. When specified, for this specific area charting layer, will show the larger of chartPrecision decimal places or ceiling(chartDecimalProportion * total decimal places). E.g. if the number is 1.12345678, 0.25 of 8 decimal places is 2, so 3 will be used and yield 1.123,
”chartDecimalProportion” (float, default 0.25): Used to override the default global precision settings for a specific area charting layer. See setQueryPrecision for setting the global charting precision. When specified, for this specific area charting layer, will show the larger of chartPrecision decimal places or chartDecimalProportion * total decimal places. E.g. if the number is 1.1234567891234, ceiling(0.25 of 13) decimal places is 4, so 4 will be used and yield 1.1235,
”hovermode” (str, default “closest”): The mode to show hover text in area summary charts. Options include “closest”, “x”, “y”, “x unified”, and “y unified”,
”yAxisLabel” (str, default an appropriate label based on whether data are thematic or continuous): The Y axis label that will be included in charts. Defaults to a unit of % area for thematic and mean for continuous data,
”chartType” (str, default “line” for ee.ImageCollection and “bar” for ee.Image objects): The type of chart to show. Options include “line”, “bar”, “stacked-line”, and “stacked-bar”. This is only used for ee.ImageCollection objects. For ee.Image objects, the chartType is always “bar”.
}
}
name (str) – Descriptive name for map layer that will be shown on the map UI
visible (bool, default True) – Whether layer should be visible when map UI loads
>>> import geeViz.geeView as gv >>> Map = gv.Map >>> ee = gv.ee >>> lcms = ee.ImageCollection("USFS/GTAC/LCMS/v2023-9").filter(ee.Filter.calendarRange(2010, 2023, "year")) >>> Map.addTimeLapse(lcms.select(["Land_Cover"]), {"autoViz": True, "mosaic": True}, "LCMS Land Cover Time Lapse") >>> Map.addTimeLapse(lcms.select(["Change"]), {"autoViz": True, "mosaic": True}, "LCMS Change Time Lapse") >>> Map.addTimeLapse(lcms.select(["Land_Use"]), {"autoViz": True, "mosaic": True}, "LCMS Land Use Time Lapse") >>> Map.turnOnInspector() >>> Map.view()
- centerObject(feature: Geometry | Feature | FeatureCollection | Image, zoom: int | None = None)[source]¶
Center the map on an object on loading
- Parameters:
feature (Feature, FeatureCollection, or Geometry) – The object to center the map on
zoom (int, optional) – If provided, will force the map to zoom to this level after centering it on the object. If not provided, the highest zoom level that allows the feature to be viewed fully will be used.
>>> from geeViz.geeView import * >>> pt = ee.Geometry.Point([-111, 41]) >>> Map.addLayer(pt.buffer(10), {}, "Plot") >>> Map.centerObject(pt) >>> Map.view()
- clearMap()[source]¶
Removes all map layers and commands - useful if running geeViz in a notebook and don’t want layers/commands from a prior code block to still be included.
>>> from geeViz.geeView import * >>> lcms = ee.ImageCollection("USFS/GTAC/LCMS/v2023-9").filter('study_area=="CONUS"') >>> Map.addLayer(lcms, {"autoViz": True}, "LCMS") # Layer >>> Map.turnOnInspector() # Command >>> Map.clearMap() # Clear map layer and commands >>> Map.view()
- clearMapCommands()[source]¶
Removes all map commands - useful if running geeViz in a notebook and don’t want commands from a prior code block to still be included, but want layers to remain.
>>> from geeViz.geeView import * >>> lcms = ee.ImageCollection("USFS/GTAC/LCMS/v2023-9").filter('study_area=="CONUS"') >>> Map.addLayer(lcms, {"autoViz": True}, "LCMS") # Layer >>> Map.turnOnInspector() # Command - this will be removed >>> Map.clearMapCommands() # Clear map comands only and leave layers >>> Map.view()
- clearMapLayers()[source]¶
Removes all map layers - useful if running geeViz in a notebook and don’t want layers from a prior code block to still be included, but want commands to remain.
>>> from geeViz.geeView import * >>> lcms = ee.ImageCollection("USFS/GTAC/LCMS/v2023-9").filter('study_area=="CONUS"') >>> Map.addLayer(lcms, {"autoViz": True}, "LCMS") # Layer - this will be removed >>> Map.turnOnInspector() # Command - this will remain (even though there will be no layers to query) >>> Map.clearMapLayers() # Clear map layer only and leave commands >>> Map.view()
- populateAreaChartLayerSelect()[source]¶
Once you add all area chart layers to the map, you can turn them on using this method- Map.populateAreaChartLayerSelect. This will create a selection menu inside the Area Tools -> Area Tools Parameters menu. You can then turn layers to include in any area charts on and off from that menu.
>>> import geeViz.geeView as gv >>> Map = gv.Map >>> ee = gv.ee >>> lcms = ee.ImageCollection("USFS/GTAC/LCMS/v2023-9").filter('study_area=="CONUS"') >>> Map.addLayer(lcms.select(["Change_Raw_Probability.*"]), {"reducer": ee.Reducer.stdDev(), "min": 0, "max": 10}, "LCMS Change Prob") >>> Map.addAreaChartLayer(lcms, {"line": True, "layerType": "ImageCollection"}, "LCMS All Thematic Classes Line", True) >>> Map.addAreaChartLayer(lcms, {"sankey": True}, "LCMS All Thematic Classes Sankey", True) >>> Map.populateAreaChartLayerSelect() >>> Map.turnOnAutoAreaCharting() >>> Map.view()
- setCanReorderLayers(canReorderLayers: bool)[source]¶
Set whether layers can be reordered by dragging layer user interface objects. By default all non timelapse and non geojson layers can be reordereed by dragging.
- Parameters:
canReorderLayers (bool, default True) – Set whether layers can be reordered by dragging layer user interface objects. By default all non timelapse and non geojson layers can be reordereed by dragging.
>>> from geeViz.geeView import * >>> lcms = ee.ImageCollection("USFS/GTAC/LCMS/v2023-9").filter('study_area=="CONUS"') >>> Map.addLayer(lcms.select([2]), {"autoViz": True}, "LCMS Land Use") >>> Map.addLayer(lcms.select([1]), {"autoViz": True}, "LCMS Land Cover") >>> Map.addLayer(lcms.select([0]), {"autoViz": True}, "LCMS Change") >>> Map.turnOnInspector() >>> Map.setCanReorderLayers(False) # Notice you cannot drag and reorder layers. Change to True and rerun and notice you now can drag layers to reorder >>> Map.setCenter(-109.446, 43.620, 12) >>> Map.view()
- setCenter(lng: float, lat: float, zoom: int | None = None)[source]¶
Center the map on a specified point and optional zoom on loading
- Parameters:
lng (int or float) – The longitude to center the map on
lat (int or float) – The latitude to center the map on
zoom (int, optional) – If provided, will force the map to zoom to this level after centering it on the provided coordinates. If not provided, the current zoom level will be used.
>>> from geeViz.geeView import * >>> Map.setCenter(-111,41,10) >>> Map.view()
- setMapTitle(title)[source]¶
Set the title that appears in the left sidebar header and the page title
- Parameters:
title (str, default geeViz Data Explorer) – The title to appear in the header on the left sidebar as well as the title of the viewer webpage.
>>> from geeViz.geeView import * >>> lcms = ee.ImageCollection("USFS/GTAC/LCMS/v2023-9").filter('study_area=="CONUS"') >>> Map.addLayer(lcms, {"autoViz": True}, "LCMS") >>> Map.turnOnInspector() >>> Map.setMapTitle("<h2>A Custom Title!!!</h2>") # Set custom map title >>> Map.view()
- setQueryBoxColor(color: str)[source]¶
Set the color of the query box to something other than yellow
- Parameters:
color (str, default "FFFF00") – Set the default query box color shown on the map by providing a hex color.
>>> from geeViz.geeView import * >>> lcms = ee.ImageCollection("USFS/GTAC/LCMS/v2023-9").filter('study_area=="CONUS"') >>> Map.addLayer(lcms.select([1]), {"autoViz": True}, "LCMS Land Cover") >>> Map.turnOnInspector() >>> Map.setQueryBoxColor("0FF") >>> Map.view()
- setQueryCRS(crs: str)[source]¶
The coordinate reference system string to query layers with
- Parameters:
(str (crs) – 5070”): Which projection (CRS) to use for querying map layers.
"EPSG (default) – 5070”): Which projection (CRS) to use for querying map layers.
>>> import geeViz.getImagesLib as gil >>> from geeViz.geeView import * >>> crs = gil.common_projections["NLCD_AK"]["crs"] >>> transform = gil.common_projections["NLCD_AK"]["transform"] >>> lcms = ee.ImageCollection("USFS/GTAC/LCMS/v2023-9").filter('study_area=="SEAK"') >>> Map.addLayer(lcms, {"autoViz": True}, "LCMS") >>> Map.turnOnInspector() >>> Map.setQueryCRS(crs) >>> Map.setQueryTransform(transform) >>> Map.setCenter(-144.36390353, 60.20479529215, 8) >>> Map.view()
- setQueryDateFormat(defaultQueryDateFormat: str = 'YYYY-MM-dd')[source]¶
Set the date format to be used for any dates when querying.
- Parameters:
defaultQueryDateFormat (str, default "YYYY-MM-dd") – The date format string to use for query outputs with dates. To simplify date outputs, “YYYY” is often used instead of the default.
>>> from geeViz.geeView import * >>> lcms = ee.ImageCollection("USFS/GTAC/LCMS/v2023-9").filter('study_area=="CONUS"') >>> Map.addLayer(lcms.select([1]), {"autoViz": True}, "LCMS Land Cover") >>> Map.addLayer(lcms.select([0]), {"autoViz": True}, "LCMS Change") >>> Map.turnOnInspector() >>> Map.setQueryDateFormat("YYYY") >>> Map.view()
- setQueryPrecision(chartPrecision: int = 3, chartDecimalProportion: float = 0.25)[source]¶
What level of precision to show for queried layers. This avoids showing too many digits after the decimal.
- Parameters:
chartPrecision (int, default 3) – Will show the larger of chartPrecision decimal places or ceiling(chartDecimalProportion * total decimal places). E.g. if the number is 1.12345678, 0.25 of 8 decimal places is 2, so 3 will be used and yield 1.123.
chartDecimalProportion (float, default 0.25) – Will show the larger of chartPrecision decimal places or chartDecimalProportion * total decimal places. E.g. if the number is 1.1234567891234, ceiling(0.25 of 13) decimal places is 4, so 4 will be used and yield 1.1235.
>>> import geeViz.getImagesLib as gil >>> from geeViz.geeView import * >>> s2s = gil.superSimpleGetS2(ee.Geometry.Point([-107.61, 37.85]), "2024-01-01", "2024-12-31", 190, 250).select(["blue", "green", "red", "nir", "swir1", "swir2"]) >>> projection = s2s.first().select(["nir"]).projection().getInfo() >>> s2s = s2s.map(lambda img: ee.Image(img).divide(10000).set("system:time_start",img.date().millis())) >>> Map.addLayer(s2s, gil.vizParamsFalse, "Sentinel-2 Images") >>> Map.addLayer(s2s.median(), gil.vizParamsFalse, "Sentinel-2 Composite") >>> Map.turnOnInspector() >>> Map.setQueryCRS(projection["crs"]) >>> Map.setQueryTransform(projection["transform"]) >>> Map.setQueryPrecision(chartPrecision=2, chartDecimalProportion=0.1) >>> Map.centerObject(s2s.first()) >>> Map.view()
- setQueryScale(scale: int)[source]¶
What scale to query map layers with. Will also update the size of the box drawn on the map query layers are queried.
- Parameters:
scale (int, default None) – The spatial resolution to use for querying map layers in meters. If set, the query transform will be set to None in the map viewer.
>>> import geeViz.getImagesLib as gil >>> from geeViz.geeView import * >>> s2s = gil.superSimpleGetS2(ee.Geometry.Point([-107.61, 37.85]), "2024-01-01", "2024-12-31", 190, 250) >>> projection = s2s.first().select(["nir"]).projection().getInfo() >>> Map.addLayer(s2s.median(), gil.vizParamsFalse10k, "Sentinel-2 Composite") >>> Map.turnOnInspector() >>> Map.setQueryCRS(projection["crs"]) >>> Map.setQueryScale(projection["transform"][0]) >>> Map.centerObject(s2s.first()) >>> Map.view()
- setQueryToInfoWindow()[source]¶
Set the location of query outputs to an info window popup over the map
>>> from geeViz.geeView import * >>> lcms = ee.ImageCollection("USFS/GTAC/LCMS/v2023-9").filter('study_area=="CONUS"') >>> Map.addLayer(lcms.select([1]), {"autoViz": True}, "LCMS Land Cover") >>> Map.turnOnInspector() >>> Map.setQueryToInfoWindow() >>> Map.view()
- setQueryToSidePane()[source]¶
Set the location of query outputs to the right sidebar above the legend
>>> from geeViz.geeView import * >>> lcms = ee.ImageCollection("USFS/GTAC/LCMS/v2023-9").filter('study_area=="CONUS"') >>> Map.addLayer(lcms.select([1]), {"autoViz": True}, "LCMS Land Cover") >>> Map.turnOnInspector() >>> Map.setQueryToSidePane() >>> Map.view()
- setQueryTransform(transform: list[int])[source]¶
What transform to query map layers with. Will also update the size of the box drawn on the map query layers are queried.
- Parameters:
transform (list, default [30, 0, -2361915, 0, -30, 3177735]) – The snap to grid to use for querying layers on the map. If set, the query scale will be set to None in the map viewer.
>>> import geeViz.getImagesLib as gil >>> from geeViz.geeView import * >>> s2s = gil.superSimpleGetS2(ee.Geometry.Point([-107.61, 37.85]), "2024-01-01", "2024-12-31", 190, 250) >>> projection = s2s.first().select(["nir"]).projection().getInfo() >>> Map.addLayer(s2s.median(), gil.vizParamsFalse10k, "Sentinel-2 Composite") >>> Map.turnOnInspector() >>> Map.setQueryCRS(projection["crs"]) >>> Map.setQueryTransform(projection["transform"]) >>> Map.centerObject(s2s.first()) >>> Map.view()
- setTitle(title)[source]¶
Redundant function for setMapTitle. Set the title that appears in the left sidebar header and the page title
- Parameters:
title (str, default geeViz Data Explorer) – The title to appear in the header on the left sidebar as well as the title of the viewer webpage.
>>> from geeViz.geeView import * >>> lcms = ee.ImageCollection("USFS/GTAC/LCMS/v2023-9").filter('study_area=="CONUS"') >>> Map.addLayer(lcms, {"autoViz": True}, "LCMS") >>> Map.turnOnInspector() >>> Map.setMapTitle("<h2>A Custom Title!!!</h2>") # Set custom map title >>> Map.view()
- setYLabelBreakLength(maxLength: int)[source]¶
Set the maximum length per line a Y axis label can have in charts
- Parameters:
maxLength (int, default 10) – Maximum number of characters in each line of a Y axis label. Will break total characters (setYLabelMaxLength) until maxLines (setYLabelMaxLines) is reached
>>> from geeViz.geeView import * >>> lcms = ee.ImageCollection("USFS/GTAC/LCMS/v2023-9").filter('study_area=="CONUS"') >>> Map.addLayer(lcms.select([1]), {"autoViz": True}, "LCMS Land Cover") >>> Map.setYLabelBreakLength(5) # Double-click on map to inspect area. Change to a larger number and rerun to see how Y labels are impacted >>> Map.turnOnInspector() >>> Map.setCenter(-109.446, 43.620, 12) >>> Map.view()
- setYLabelFontSize(fontSize: int)[source]¶
Set the size of the font on the y-axis labels. Useful when y-axis labels are too large to fit on the chart.
- Parameters:
fontSize (int, default 10) – The font size used on the y-axis labels for query charting.
>>> from geeViz.geeView import * >>> lcms = ee.ImageCollection("USFS/GTAC/LCMS/v2023-9").filter('study_area=="CONUS"') >>> Map.addLayer(lcms.select([1]), {"autoViz": True}, "LCMS Land Cover") >>> Map.setYLabelFontSize(8) # Double-click on map to inspect area. Change to a different number and rerun to see how Y labels are impacted >>> Map.turnOnInspector() >>> Map.setCenter(-109.446, 43.620, 12) >>> Map.view()
- setYLabelMaxLength(maxLength: int)[source]¶
Set the maximum length a Y axis label can have in charts
- Parameters:
maxLength (int, default 30) – Maximum number of characters in a Y axis label.
>>> from geeViz.geeView import * >>> lcms = ee.ImageCollection("USFS/GTAC/LCMS/v2023-9").filter('study_area=="CONUS"') >>> Map.addLayer(lcms.select([1]), {"autoViz": True}, "LCMS Land Cover") >>> Map.setYLabelMaxLength(10) # Double-click on map to inspect area. Change to a larger number and rerun to see how Y labels are impacted >>> Map.turnOnInspector() >>> Map.setCenter(-109.446, 43.620, 12) >>> Map.view()
- setYLabelMaxLines(maxLines)[source]¶
Set the max number of lines each y-axis label can have.
- Parameters:
maxLines (int, default 5) – The maximum number of lines each y-axis label can have. Will simply exclude any remaining lines.
>>> from geeViz.geeView import * >>> lcms = ee.ImageCollection("USFS/GTAC/LCMS/v2023-9").filter('study_area=="CONUS"') >>> Map.addLayer(lcms.select([1]), {"autoViz": True}, "LCMS Land Cover") >>> Map.setYLabelMaxLines(3) # Double-click on map to inspect area. Change to a larger number and rerun to see how Y labels are impacted >>> Map.turnOnInspector() >>> Map.setCenter(-109.446, 43.620, 12) >>> Map.view()
- setZoom(zoom: int)[source]¶
Set the map zoom level
- Parameters:
zoom (int) – The zoom level to set the map to on loading.
>>> from geeViz.geeView import * >>> Map.setZoom(10) >>> Map.view()
- turnOffAllLayers()[source]¶
Turn off all layers added to the mapper object. Typically used in notebooks or iPython when you want to allow existing layers to remain, but want to turn them all off.
>>> #%% >>> from geeViz.geeView import * >>> lcms = ee.ImageCollection("USFS/GTAC/LCMS/v2023-9").filter('study_area=="CONUS"') >>> Map.addLayer(lcms.select([2]), {"autoViz": True}, "LCMS Land Use") >>> Map.addLayer(lcms.select([1]), {"autoViz": True}, "LCMS Land Cover") >>> Map.turnOnInspector() >>> Map.setCenter(-109.446, 43.620, 5) >>> Map.view() >>> #%% >>> Map.turnOffAllLayers() >>> Map.addLayer(lcms.select([0]), {"autoViz": True}, "LCMS Change") >>> Map.view()
- turnOnAllLayers()[source]¶
Turn on all layers added to the mapper object
>>> #%% >>> from geeViz.geeView import * >>> lcms = ee.ImageCollection("USFS/GTAC/LCMS/v2023-9").filter('study_area=="CONUS"') >>> Map.addLayer(lcms.select([2]), {"autoViz": True}, "LCMS Land Use",False) >>> Map.addLayer(lcms.select([1]), {"autoViz": True}, "LCMS Land Cover",False) >>> Map.turnOnInspector() >>> Map.setCenter(-109.446, 43.620, 5) >>> Map.view() >>> #%% >>> Map.turnOnAllLayers() >>> Map.addLayer(lcms.select([0]), {"autoViz": True}, "LCMS Change") >>> Map.view()
- turnOnAutoAreaCharting()[source]¶
Turn on automatic area charting upon map loading. This will automatically update charts by summarizing any visible layers with “canAreaChart” : True any time the map finishes panning or zooming.
>>> from geeViz.geeView import * >>> lcms = ee.ImageCollection("USFS/GTAC/LCMS/v2023-9").filter('study_area=="CONUS"') >>> Map.addLayer(lcms.select([1]), {"autoViz": True,'canAreaChart':True}, "LCMS Land Cover") >>> Map.turnOnAutoAreaCharting() >>> Map.view()
- turnOnInspector()[source]¶
Turn on the query inspector tool upon map loading. This is used frequently so map layers can be queried as soon as the map viewer loads.
>>> from geeViz.geeView import * >>> lcms = ee.ImageCollection("USFS/GTAC/LCMS/v2023-9").filter('study_area=="CONUS"') >>> Map.addLayer(lcms.select([1]), {"autoViz": True}, "LCMS Land Cover") >>> Map.turnOnInspector() >>> Map.view()
- turnOnSelectionAreaCharting()[source]¶
Turn on area charting by a user selected area upon map loading. This will update charts by summarizing any visible layers with “canAreaChart” : True when the user selects selection areas to summarize and hits the Chart Selected Areas button in the user interface under Area Tools -> Select an Area on Map.
>>> from geeViz.geeView import * >>> lcms = ee.ImageCollection("USFS/GTAC/LCMS/v2023-9").filter('study_area=="CONUS"') >>> Map.addLayer(lcms.select([1]), {"autoViz": True,'canAreaChart':True}, "LCMS Land Cover") >>> mtbsBoundaries = ee.FeatureCollection("USFS/GTAC/MTBS/burned_area_boundaries/v1") >>> mtbsBoundaries = mtbsBoundaries.map(lambda f: f.set("system:time_start", f.get("Ig_Date"))) >>> Map.addSelectLayer(mtbsBoundaries, {"strokeColor": "00F", "selectLayerNameProperty": "Incid_Name"}, "MTBS Fire Boundaries") >>> Map.turnOnSelectionAreaCharting() >>> Map.view()
- turnOnUserDefinedAreaCharting()[source]¶
Turn on area charting by a user defined area upon map loading. This will update charts by summarizing any visible layers with “canAreaChart” : True when the user draws an area to summarize and hits the Chart Selected Areas button in the user interface under Area Tools -> User-Defined Area.
>>> from geeViz.geeView import * >>> lcms = ee.ImageCollection("USFS/GTAC/LCMS/v2023-9").filter('study_area=="CONUS"') >>> Map.addLayer(lcms.select([1]), {"autoViz": True,'canAreaChart':True}, "LCMS Land Cover") >>> Map.turnOnUserDefinedAreaCharting() >>> Map.view()
- view(open_browser: bool | None = None, open_iframe: bool | None = None, iframe_height: int = 525)[source]¶
Compiles all map objects and commands and starts the map server
- Parameters:
open_browser (bool) – Whether or not to open the browser. If unspecified, will automatically be selected depending on whether geeViz is being used in a notebook (False) or not (True).
open_iframe (bool) – Whether or not to open an iframe. If unspecified, will automatically be selected depending on whether geeViz is being used in a notebook (True) or not (False).
iframe_height (int, default 525) – The height of the iframe shown if running inside a notebook
>>> from geeViz.geeView import * >>> lcms = ee.ImageCollection("USFS/GTAC/LCMS/v2023-9").filter('study_area=="CONUS"') >>> Map.addLayer(lcms, {"autoViz": True, "canAreaChart": True, "areaChartParams": {"line": True, "sankey": True}}, "LCMS") >>> Map.turnOnInspector() >>> Map.view()
- geeViz.geeView.polylinear_gradient(colors: list[str], n: int)[source]¶
returns a list of colors forming linear gradients between all sequential pairs of colors. “n” specifies the total number of desired output colors
- geeViz.geeView.refreshToken()[source]¶
Get a refresh token from currently authenticated ee instance
- Returns:
temporary access token
- Return type:
str
- geeViz.geeView.robustInitializer(verbose: bool = False)[source]¶
A method that tries to authenticate and/or initialize GEE if it isn’t already successfully initialized. This method tries to handle many different scenarios, but often fails. It is best to authenticate and initialize to a project prior to importing geeViz
- geeViz.geeView.run_local_server(port: int = 8001)[source]¶
Start a local webserver using the Python http.server
- Parameters:
port (int) – Port number to run local server at
- geeViz.geeView.serviceAccountToken(service_key_file_path)[source]¶
Get a refresh token from service account key file credentials
- Returns:
temporary access token
- Return type:
str
geeViz.getImagesLib¶
Get images and organize them so they are easier to work with
geeViz.getImagesLib is the core module for setting up various imageCollections from GEE. Notably, it facilitates Landsat, Sentinel-2, and MODIS data organization. This module helps avoid many common mistakes in GEE. Most functions ease matching band names, ensuring resampling methods are properly set, date wrapping, and helping with cloud and cloud shadow masking.
- geeViz.getImagesLib.HoCalcAlgorithm2(image: Image) Image [source]¶
Applies an algal detection algorithm based on: Matthews, M. (2011) A current review of empirical procedures of remote sensing in inland and near-coastal transitional waters, International Journal of Remote Sensing, 32:21, 6855-6899, DOI: 10.1080/01431161.2010.512947.
- Parameters:
image – The input Earth Engine image.
- Returns:
The image with added bloom2 and NDGI bands.
- geeViz.getImagesLib.RefinedLee(img: Image) Image [source]¶
Applies the Refined Lee speckle filter to a Sentinel-1 image.
- Parameters:
img – The input Sentinel-1 image in natural units.
- Returns:
The speckle filtered image.
- geeViz.getImagesLib.addDateBand(img: Image, maskTime: bool = False) Image [source]¶
Adds a date band to an image.
- Parameters:
img – The input Earth Engine image.
maskTime – Whether to mask the date band based on the image mask.
- Returns:
The input image with an added date band.
- geeViz.getImagesLib.addFullYearJulianDayBand(img: Image) Image [source]¶
Adds a full year Julian day band to an image.
- Parameters:
img – The input Earth Engine image.
- Returns:
The input image with an added full year Julian day band.
- geeViz.getImagesLib.addIndices(img: Image) Image [source]¶
Adds various spectral indices to an image.
- Parameters:
img – The input Earth Engine image.
- Returns:
The image with added spectral indices.
- geeViz.getImagesLib.addJulianDayBand(img: Image) Image [source]¶
Adds a Julian day band to an image.
- Parameters:
img – The input Earth Engine image.
- Returns:
The input image with an added Julian day band.
- geeViz.getImagesLib.addSAVIandEVI(img: Image) Image [source]¶
Adds SAVI and EVI indices to an image.
- Parameters:
img – The input Earth Engine image.
- Returns:
The image with added SAVI and EVI indices.
- geeViz.getImagesLib.addSensorBand(img: Image, whichProgram: str, toaOrSR: str) Image [source]¶
Adds a sensor band to an image.
- Parameters:
img – The input Earth Engine image.
whichProgram – The program (e.g., ‘C1_landsat’, “C2_landsat”, ‘sentinel2’).
toaOrSR – Whether the image is TOA or SR.
- Returns:
The input image with an added sensor band.
- geeViz.getImagesLib.addSoilIndices(img: Image) Image [source]¶
Adds soil-related indices to an image.
- Parameters:
img – The input Earth Engine image.
- Returns:
The image with added soil indices.
- geeViz.getImagesLib.addTCAngles(image: Image) Image [source]¶
Adds Tasseled Cap angles and distances to an image. Assumes image has bands: ‘brightness’, ‘greenness’, and ‘wetness’.
- Parameters:
image – The input Earth Engine image with brightness, greenness, and wetness bands.
- Returns:
The image with added Tasseled Cap angles and distances.
- geeViz.getImagesLib.addYearBand(img: Image) Image [source]¶
Adds a year band to an image.
- Parameters:
img – The input Earth Engine image.
- Returns:
The input image with an added year band.
- geeViz.getImagesLib.addYearFractionBand(img: Image) Image [source]¶
Adds a year fraction band to an image.
- Parameters:
img – The input Earth Engine image.
- Returns:
The input image with an added year fraction band.
- geeViz.getImagesLib.addYearJulianDayBand(img: Image) Image [source]¶
Adds a year and Julian day band to an image.
- Parameters:
img – The input Earth Engine image.
- Returns:
The input image with an added year and Julian day band.
- geeViz.getImagesLib.addYearYearFractionBand(img: Image) Image [source]¶
Adds a year and year fraction band to an image.
- Parameters:
img – The input Earth Engine image.
- Returns:
The input image with an added year and year fraction band.
- geeViz.getImagesLib.addZenithAzimuth(img: Image, toaOrSR: str, zenithDict: dict = {'SR': 'SOLAR_ZENITH_ANGLE', 'TOA': 'SUN_ELEVATION'}, azimuthDict: dict = {'SR': 'SOLAR_AZIMUTH_ANGLE', 'TOA': 'SUN_AZIMUTH'})[source]¶
Adds solar zenith and azimuth angles in radians to an image.
- Parameters:
img – The input Earth Engine image.
toaOrSR – Whether the image is TOA or SR.
zenithDict – A dictionary mapping toaOrSR to the zenith band name.
azimuthDict – A dictionary mapping toaOrSR to the azimuth band name.
- Returns:
The image with added zenith and azimuth bands.
- geeViz.getImagesLib.applyBitMask(img: Image, bit: int, bitMaskBandName: str = 'QA_PIXEL') Image [source]¶
Applies a bitmask to an image.
- Parameters:
img – The input image.
bit – The bit position to mask.
bitMaskBandName – The name of the QA band (default: “QA_PIXEL”).
- Returns:
The masked image.
- geeViz.getImagesLib.applyCloudScoreAlgorithm(collection: ImageCollection, cloudScoreFunction: function, cloudScoreThresh: float = 20, cloudScorePctl: float = 10, contractPixels: float = 1.5, dilatePixels: float = 3.5, performCloudScoreOffset: bool = True, preComputedCloudScoreOffset: Image = None) ImageCollection [source]¶
Applies a cloud score algorithm to an image collection.
- Parameters:
collection – The input Earth Engine image collection.
cloudScoreFunction – A function to calculate the cloud score for an image.
cloudScoreThresh – The cloud score threshold for masking (default: 20).
cloudScorePctl – The percentile for computing the cloud score offset (default: 10).
contractPixels – The contraction kernel size (default: 1.5).
dilatePixels – The dilation kernel size (default: 3.5).
performCloudScoreOffset – Whether to perform cloud score offsetting (default: True).
preComputedCloudScoreOffset – A pre-computed cloud score offset image (optional).
- Returns:
The image collection with cloud masks applied.
- geeViz.getImagesLib.cFmask(img: Image, fmaskClass: str, bitMaskBandName: str = 'QA_PIXEL') Image [source]¶
Applies the CFMask algorithm to a Landsat image.
- Parameters:
img – The input Landsat image.
fmaskClass – The CFMask class to apply (e.g., ‘cloud’, ‘shadow’, ‘snow’).
bitMaskBandName – The name of the QA band (default: “QA_PIXEL”).
- Returns:
The cloud-masked image.
- geeViz.getImagesLib.cFmaskCloud(img: Image, landsatCollectionVersion: str, bitMaskBandName: str = 'QA_PIXEL') Image [source]¶
Applies the CFMask cloud mask to a Landsat image.
- Parameters:
img – The input Landsat image.
landsatCollectionVersion – The Landsat collection version (e.g., ‘C1’, ‘C2’).
bitMaskBandName – The name of the QA band (default: “QA_PIXEL”).
- Returns:
The cloud-masked image.
- geeViz.getImagesLib.cFmaskCloudShadow(img: Image, landsatCollectionVersion: str, bitMaskBandName: str = 'QA_PIXEL') Image [source]¶
Applies the CFMask cloud shadow mask to a Landsat image.
- Parameters:
img – The input Landsat image.
landsatCollectionVersion – The Landsat collection version (e.g., ‘C1’, ‘C2’).
bitMaskBandName – The name of the QA band (default: “QA_PIXEL”).
- Returns:
The cloud shadow masked image.
- geeViz.getImagesLib.collectionToImage(collection: ImageCollection) Image [source]¶
Deprecated - use .toBands(). Converts an image collection to a multiband image.
- Parameters:
collection – The input Earth Engine image collection.
- Returns:
A multiband Earth Engine image.
- geeViz.getImagesLib.compositeDates(images: ImageCollection, composite: Image, bandNames: list = None) Image [source]¶
Finds the dates corresponding to bands in a composite image.
- Parameters:
images – The original image collection.
composite – The composite image.
bandNames – Optional list of band names to consider.
- Returns:
An Earth Engine image with date information for each band.
- geeViz.getImagesLib.compositeTimeSeries(ls: ImageCollection, startYear: int, endYear: int, startJulian: int, endJulian: int, timebuffer: int = 0, weights: list = [1], compositingMethod: str | None = None, compositingReducer: Reducer | None = None) ImageCollection [source]¶
Creates composites for each year within a specified date range.
This function generates annual composites from an image collection, allowing for time buffering and weighted averaging.
- Parameters:
ls – The input Earth Engine image collection.
startYear – The start year of the composite period.
endYear – The end year of the composite period.
startJulian – The start Julian day of the composite period.
endJulian – The end Julian day of the composite period.
timebuffer – The number of years to include in the composite (default: 0).
weights – The weights for the composite (default: [1]).
compositingMethod – The compositing method (e.g., ‘median’, ‘medoid’) (optional).
compositingReducer – A custom compositing reducer (optional).
- Returns:
An Earth Engine image collection containing the composites.
- geeViz.getImagesLib.dailyMosaics(imgs: ImageCollection) ImageCollection [source]¶
Creates daily mosaics from an image collection.
- Parameters:
imgs – The input Earth Engine image collection.
- Returns:
An Earth Engine image collection containing daily mosaics.
- geeViz.getImagesLib.defringeLandsat(img: Image) Image [source]¶
Defringes a Landsat 7 image.
- Parameters:
img – The input Landsat 7 image.
- Returns:
The defringed Landsat 7 image.
- geeViz.getImagesLib.exportToAssetWrapper(imageForExport: Image, assetName: str, assetPath: str, pyramidingPolicyObject: dict | None = None, roi: Geometry | None = None, scale: float | None = None, crs: str | None = None, transform: list | None = None, overwrite: bool = False)[source]¶
Exports an image to an Earth Engine asset.
This function provides a wrapper for exporting images to Earth Engine assets with additional features like handling existing assets and setting the pyramiding policy.
- Parameters:
imageForExport – The Earth Engine Image to export.
assetName – The desired name for the asset.
assetPath – The full path for the asset in the Earth Engine asset tree.
pyramidingPolicyObject – An optional dictionary specifying the pyramiding policy for the exported asset.
roi – An optional Earth Engine Geometry defining the region of interest for export.
scale – The desired export scale in meters.
crs – The desired coordinate reference system for the export.
transform – The desired transform for the export.
overwrite – A boolean indicating whether to overwrite an existing asset.
- Returns:
None. The function starts the export task.
- geeViz.getImagesLib.exportToCloudStorageWrapper(imageForExport: Image, outputName: str, bucketName: str, roi: Geometry, scale: float | None = None, crs: str | None = None, transform: list | None = None, outputNoData: int = -32768, fileFormat: str = 'GeoTIFF', formatOptions: dict = {'cloudOptimized': True}, overwrite: bool = False)[source]¶
Exports an image to Google Cloud Storage.
This function exports an Earth Engine Image to a specified Google Cloud Storage bucket.
- Parameters:
imageForExport – The Earth Engine Image to export.
outputName – The desired name for the exported file.
bucketName – The name of the Google Cloud Storage bucket.
roi – The Earth Engine Geometry defining the region of interest.
scale – The desired export scale in meters.
crs – The desired coordinate reference system for the export.
transform – The desired transform for the export.
outputNoData – The no data value to use for the export.
fileFormat – The desired output file format (e.g., “GeoTIFF”, “TFRecord”).
formatOptions – Additional format options for the export.
overwrite – A boolean indicating whether to overwrite an existing file.
- Returns:
None. The function starts the export task.
- geeViz.getImagesLib.exportToDriveWrapper(imageForExport: Image, outputName: str, driveFolderName: str, roi: Geometry, scale: float | None = None, crs: str | None = None, transform: list | None = None, outputNoData: int = -32768)[source]¶
Exports an image to Google Drive.
This function exports an Earth Engine Image to a specified Google Drive folder.
- Parameters:
imageForExport – The Earth Engine Image to export.
outputName – The desired name for the exported file.
driveFolderName – The name of the Google Drive folder to export to.
roi – The Earth Engine Geometry defining the region of interest.
scale – The desired export scale in meters.
crs – The desired coordinate reference system for the export.
transform – The desired transform for the export.
outputNoData – The no data value to use for the export.
- Returns:
None. The function starts the export task.
- geeViz.getImagesLib.fillEmptyCollections(inCollection: ImageCollection, dummyImage: Image) ImageCollection [source]¶
Fills empty image collections with a dummy image. This handles empty collections that will cause subsequent processes to fail.
- Parameters:
inCollection – The input Earth Engine image collection.
dummyImage – A dummy Earth Engine image.
- Returns:
The input image collection or a collection containing the dummy image if empty.
- geeViz.getImagesLib.formatArgs(args: dict) dict [source]¶
Formats arguments as strings for setting as image properties.
- Parameters:
args – A dictionary of arguments.
- Returns:
A dictionary of formatted arguments.
- geeViz.getImagesLib.getClimateWrapper(collectionName: str, studyArea: Geometry | Feature | FeatureCollection, startYear: int, endYear: int, startJulian: int, endJulian: int, timebuffer: int = 0, weights: List | list | None = None, compositingReducer: Reducer | None = None, exportComposites: bool = False, exportPathRoot: str | None = None, crs: str | None = None, transform: list[int] | None = None, scale: int | None = None, exportBands: List | list | None = None, exportNamePrefix: str = '', exportToAssets: bool = False, exportToCloud: bool = False, bucket: str = '') ImageCollection [source]¶
Wrapper function to retrieve and process climate data from various Earth Engine collections.
This function supports retrieving climate data from collections like NASA/ORNL/DAYMET_V3, NASA/ORNL/DAYMET_V4, UCSB-CHG/CHIRPS/DAILY (precipitation only), and potentially others. It allows filtering by date, study area, and Julian day, specifying a compositing reducer, and optionally exporting the resulting time series.
- Parameters:
collectionName (str) – Name of the Earth Engine collection containing climate data.
studyArea (ee.Geometry | ee.Feature | ee.FeatureCollection) – The geographic area of interest (study area) as an Earth Engine geometry object.
startYear (int) – The starting year for the data collection.
endYear (int) – The ending year for the data collection.
startJulian (int) – The starting Julian day of year for the data collection (1-365).
endJulian (int) – The ending Julian day of year for the data collection (1-365).
timebuffer (int, optional) – Number of years to buffer around each year. Defaults to 0.
weights (ee.List | list| None, optional) – List of weights for weighted compositing (if applicable to the chosen collection). Defaults to None (equal weights).
compositingReducer (ee.Reducer | None, optional) – Earth Engine reducer used for compositing daily data into the desired temporal resolution. Defaults to None (may require a reducer depending on the collection).
exportComposites (bool, optional) – Flag indicating whether to export the resulting time series. Defaults to False.
exportPathRoot (str | None, optional) – Root path for exporting the composites (if exportComposites is True). Defaults to None (no export).
crs (str | None, optional) – Earth Engine projection object for the exported composites (if exportComposites is True). Defaults to None (uses the source collection’s projection).
transform (list[int] | None, optional) – Earth Engine transform object for the exported composites (if exportComposites is True). Defaults to None (uses the source collection’s transform).
scale (int | None, optional) – Scale in meters for the exported composites (if exportComposites is True). Defaults to None (uses the source collection’s scale).
exportBands (ee.List | list | None, optional) – List of band names to export from the composites (if exportComposites is True). Defaults to None (all bands from the first image in the collection).
exportNamePrefix (str, optional) – Name to place before default name of exported image. Defaults to ‘’.
exportToAssets (bool, optional) – Set to True to export images to earth engine assets. Defaults to False.
exportToCloud (bool, optional) – Set to True to export images to Google Cloud Storage. Defaults to False.
bucket (str, optional) – If exportToCloud is True, images are exported to this Google Cloud storage bucket. Defaults to ‘’, but will need to be provided if exportToCloud is True.
- Returns:
The time series collection of processed climate data.
- Return type:
ee.ImageCollection
>>> import geeViz.getImagesLib as gil >>> Map = gil.Map >>> ee = gil.ee >>> studyArea = gil.testAreas["CO"] >>> startJulian = 274 >>> endJulian = 273 >>> startYear = 2016 >>> endYear = 2023 >>> timebuffer = 0 >>> weights = [1] >>> compositingReducer = ee.Reducer.mean() >>> collectionName = "NASA/ORNL/DAYMET_V4" >>> exportComposites = False >>> exportPathRoot = "users/username/someCollection" >>> exportBands = ["prcp.*", "tmax.*", "tmin.*"] >>> exportNamePrefix = 'Colorado_Test_Area_' >>> crs = "EPSG:5070" >>> transform = [1000, 0, -2361915.0, 0, -1000, 3177735.0] >>> scale = None >>> climateComposites = gil.getClimateWrapper(collectionName, studyArea, startYear, endYear, startJulian, endJulian, timebuffer, weights, compositingReducer, exportComposites, exportPathRoot, crs, transform, scale, exportBands, exportNamePrefix,exportToAssets,exportToCloud,bucket) >>> Map.addTimeLapse(climateComposites.select(exportBands), {}, "Climate Composite Time Lapse") >>> Map.addLayer(studyArea, {"strokeColor": "0000FF", "canQuery": False}, "Study Area", True) >>> Map.centerObject(studyArea) >>> Map.turnOnInspector() >>> Map.view()
- geeViz.getImagesLib.getImageCollection(studyArea: Geometry | Feature | FeatureCollection, startDate: Date | datetime | str, endDate: Date | datetime | str, startJulian: int = 1, endJulian: int = 365, toaOrSR: str = 'SR', includeSLCOffL7: bool = False, defringeL5: bool = False, addPixelQA: bool = False, resampleMethod: str = 'near', landsatCollectionVersion: str = 'C2')¶
Retrieves Landsat imagery for a specified study area and date range.
- Parameters:
studyArea (ee.Geometry, ee.Feature, or ee.FeatureCollection) – The geographic area of interest.
startDate (ee.Date, datetime.datetime, or str) – The start date of the desired image range.
endDate (ee.Date, datetime.datetime, or str) – The end date of the desired image range.
startJulian (int, optional) – The start Julian day of the desired image range. Defaults to 1.
endJulian (int, optional) – The end Julian day of the desired image range. Defaults to 365.
toaOrSR (str, optional) – Whether to retrieve TOA or SR data. Defaults to “SR”.
includeSLCOffL7 (bool, optional) – Whether to include SLC-off L7 data. Defaults to False.
defringeL5 (bool, optional) – Whether to defringe L5 data. Defaults to False.
addPixelQA (bool, optional) – Whether to add pixel QA band. Defaults to False.
resampleMethod (str, optional) – Resampling method. Options are “near”, “bilinear”, or “bicubic”. Defaults to “near”.
landsatCollectionVersion (str, optional) – Landsat collection version. Options are “C1” or “C2”. Defaults to “C2”.
- Returns:
A collection of Landsat images meeting the specified criteria.
- Return type:
ee.ImageCollection
>>> import geeViz.getImagesLib as gil >>> Map = gil.Map >>> ee = gil.ee >>> studyArea = gil.testAreas["CA"] >>> composite = gil.getLandsat(studyArea, "2024-01-01", "2024-12-31", 190, 250).median() >>> Map.addLayer(composite, gil.vizParamsFalse, "Landsat Composite") >>> Map.addLayer(studyArea, {"canQuery": False}, "Study Area") >>> Map.centerObject(studyArea) >>> Map.turnOnInspector() >>> Map.view()
- geeViz.getImagesLib.getLandsat(studyArea: Geometry | Feature | FeatureCollection, startDate: Date | datetime | str, endDate: Date | datetime | str, startJulian: int = 1, endJulian: int = 365, toaOrSR: str = 'SR', includeSLCOffL7: bool = False, defringeL5: bool = False, addPixelQA: bool = False, resampleMethod: str = 'near', landsatCollectionVersion: str = 'C2')[source]¶
Retrieves Landsat imagery for a specified study area and date range.
- Parameters:
studyArea (ee.Geometry, ee.Feature, or ee.FeatureCollection) – The geographic area of interest.
startDate (ee.Date, datetime.datetime, or str) – The start date of the desired image range.
endDate (ee.Date, datetime.datetime, or str) – The end date of the desired image range.
startJulian (int, optional) – The start Julian day of the desired image range. Defaults to 1.
endJulian (int, optional) – The end Julian day of the desired image range. Defaults to 365.
toaOrSR (str, optional) – Whether to retrieve TOA or SR data. Defaults to “SR”.
includeSLCOffL7 (bool, optional) – Whether to include SLC-off L7 data. Defaults to False.
defringeL5 (bool, optional) – Whether to defringe L5 data. Defaults to False.
addPixelQA (bool, optional) – Whether to add pixel QA band. Defaults to False.
resampleMethod (str, optional) – Resampling method. Options are “near”, “bilinear”, or “bicubic”. Defaults to “near”.
landsatCollectionVersion (str, optional) – Landsat collection version. Options are “C1” or “C2”. Defaults to “C2”.
- Returns:
A collection of Landsat images meeting the specified criteria.
- Return type:
ee.ImageCollection
>>> import geeViz.getImagesLib as gil >>> Map = gil.Map >>> ee = gil.ee >>> studyArea = gil.testAreas["CA"] >>> composite = gil.getLandsat(studyArea, "2024-01-01", "2024-12-31", 190, 250).median() >>> Map.addLayer(composite, gil.vizParamsFalse, "Landsat Composite") >>> Map.addLayer(studyArea, {"canQuery": False}, "Study Area") >>> Map.centerObject(studyArea) >>> Map.turnOnInspector() >>> Map.view()
- geeViz.getImagesLib.getModisData(startYear: int, endYear: int, startJulian: int, endJulian: int, daily: bool = False, maskWQA: bool = False, zenithThresh: int = 90, useTempInCloudMask: bool = True, addLookAngleBands: bool = False, resampleMethod: str = 'near')[source]¶
Retrieves MODIS imagery from Earth Engine for a specified period. Handles joining all MODIS collections for Terra and Aqua and aligning band names
- Parameters:
startYear (int) – The starting year for the data collection.
endYear (int) – The ending year for the data collection.
startJulian (int) – The starting Julian day of year for the data collection (1-366).
endJulian (int) – The ending Julian day of year for the data collection (1-366).
daily (bool, optional) – Determines whether to retrieve daily or 8-day composite data. Defaults to False (8-day composite).
maskWQA (bool, optional) – Controls whether to mask pixels based on the Quality Assurance (QA) band. Only applicable for daily data (daily=True). Defaults to False.
zenithThresh (float, optional) – Sets the threshold for solar zenith angle in degrees. Pixels with zenith angle exceeding this threshold will be masked out. Defaults to 90.
useTempInCloudMask (bool, optional) – Determines whether to use the thermal band for cloud masking. Defaults to True.
addLookAngleBands (bool, optional) – Controls whether to include view angle bands in the output. Defaults to False.
resampleMethod (str, optional) – Specifies the resampling method to apply to the imagery. Valid options include “near”, “bilinear”, and “bicubic”. Defaults to “near” (nearest neighbor).
- Returns:
A collection of MODIS imagery for the specified criteria.
- Return type:
ee.ImageCollection
>>> import geeViz.getImagesLib as gil >>> Map = gil.Map >>> ee = gil.ee >>> crs = gil.common_projections["NLCD_CONUS"]["crs"] >>> transform = gil.common_projections["NLCD_CONUS"]["transform"] >>> scale = 240 >>> transform[0] = scale >>> transform[4] = -scale >>> composite = gil.getModisData(2024, 2024, 190, 250, resampleMethod="bicubic").median().reproject(crs, transform) >>> Map.addLayer(composite, gil.vizParamsFalse, "MODIS Composite") >>> Map.setCenter(-111, 41, 7) >>> Map.turnOnInspector() >>> Map.view()
- geeViz.getImagesLib.getProcessedLandsatScenes(studyArea: Geometry | Feature | FeatureCollection, startYear: int, endYear: int, startJulian: int, endJulian: int, toaOrSR: str = 'SR', includeSLCOffL7: bool = False, defringeL5: bool = False, applyCloudScore: bool = False, applyFmaskCloudMask: bool = True, applyTDOM: bool = False, applyFmaskCloudShadowMask: bool = True, applyFmaskSnowMask: bool = False, cloudScoreThresh: int = 10, performCloudScoreOffset: bool = True, cloudScorePctl: int = 10, zScoreThresh: float = -1, shadowSumThresh: float = 0.35, contractPixels: float = 1.5, dilatePixels: float = 3.5, shadowSumBands: list[str] = ['nir', 'swir1'], resampleMethod: str = 'near', harmonizeOLI: bool = False, preComputedCloudScoreOffset: Image | None = None, preComputedTDOMIRMean: Image | None = None, preComputedTDOMIRStdDev: Image | None = None, landsatCollectionVersion: str = 'C2', verbose: bool = False) ImageCollection [source]¶
Retrieves, processes, and filters Landsat scenes for a specified area and time period.
This function retrieves Landsat scenes from Earth Engine, applies various cloud, cloud shadow, and snow masking techniques, calculates common indices, and returns a collection of processed images.
- Parameters:
studyArea (ee.Geometry) – The geographic area of interest (study area) as an Earth Engine geometry, Feature, or FeatureCollection object.
startYear (int) – The starting year for the data collection.
endYear (int) – The ending year for the data collection.
startJulian (int) – The starting Julian day of year for the data collection (1-365).
endJulian (int) – The ending Julian day of year for the data collection (1-365).
toaOrSR (str, optional) – Flag indicating desired reflectance type: “TOA” (Top Of Atmosphere) or “SR” (Surface Reflectance). Defaults to “SR”.
includeSLCOffL7 (bool, optional) – Determines whether to include Landsat 7 SLC-off scenes. Defaults to False.
defringeL5 (bool, optional) – Determines whether to defringe Landsat 5 scenes. Defaults to False.
applyCloudScore (bool, optional) – Determines whether to apply cloud masking based on the CloudScore simple algorithm. Defaults to False.
applyFmaskCloudMask (bool, optional) – Determines whether to apply the Fmask cloud mask. Defaults to True.
applyTDOM (bool, optional) – Determines whether to apply the TDOM (Temporal Dark Outlier Mask) technique for cloud shadow masking. Defaults to False.
applyFmaskCloudShadowMask (bool, optional) – Determines whether to apply the Fmask cloud shadow mask. Defaults to True.
applyFmaskSnowMask (bool, optional) – Determines whether to apply the Fmask snow mask. Defaults to False.
cloudScoreThresh (int, optional) – Threshold for the CloudScore simple algorithm to classify a pixel as cloudy. Lower number masks out more. Defaults to 10.
performCloudScoreOffset (bool, optional) – Controls whether to perform an offset correction on the Cloud Score data over bright surfaces. Only use this if bright areas are being masked as clouds. Do not use this in persistently cloud areas. Defaults to True.
cloudScorePctl (int, optional) – Percentile of the Cloud Score product to use for the offset correction. Defaults to 10.
zScoreThresh (float, optional) – Threshold for the z-score used in TDOM cloud shadow masking. Pixels with z-scores below this threshold are masked. Defaults to -1.
shadowSumThresh (float, optional) – Threshold for the sum of reflectance in shadow bands used in TDOM cloud shadow masking. Pixels below this threshold and the zScoreThresh are masked as dark outliers (likely cloud shadows). Defaults to 0.35.
contractPixels (float, optional) – Number of pixels to contract cloud and shadow masks by. Defaults to 1.5.
dilatePixels (float, optional) – Number of pixels to dilate cloud and shadow masks by. Defaults to 3.5.
shadowSumBands (list[str], optional) – List of band names to use for calculating the sum of reflectance in TDOM cloud shadow masking. Defaults to [“nir”, “swir1”].
resampleMethod (str, optional) – Specifies the resampling method to apply to the imagery. Valid options include “near”, “bilinear”, and “bicubic”. Defaults to “near”.
harmonizeOLI (bool, optional) – Determines whether to harmonize OLI data to match TM/ETM+ spectral response. Defaults to False.
preComputedCloudScoreOffset (float | None, optional) – Pre-computed Cloud Score offset value to avoid redundant calculations. Defaults to None (automatic calculation).
preComputedTDOMIRMean (float | None, optional) – Pre-computed mean of the IR band used in TDOM cloud shadow masking to avoid redundant calculations. Defaults to None (automatic calculation).
preComputedTDOMIRStdDev (float | None, optional) – Pre-computed standard deviation of the IR band used in TDOM cloud shadow masking to avoid redundant calculations. Defaults to None (automatic calculation).
landsatCollectionVersion (str, optional) – Specifies the Landsat collection version to use (e.g., “C1”, “C2”). Defaults to “C2”.
verbose (bool, optional) – Controls whether to print additional information during processing. Defaults to False.
- Returns:
A collection of analysis ready, cloud and cloud shadow asked Landsat scenes with common band names.
- Return type:
ee.ImageCollection
>>> import geeViz.getImagesLib as gil >>> Map = gil.Map >>> ee = gil.ee >>> studyArea = gil.testAreas["CO"] >>> composite = gil.getProcessedLandsatScenes(studyArea, 2023, 2023, 190, 250).median() >>> Map.addLayer(composite, gil.vizParamsFalse, "Landsat Composite") >>> Map.addLayer(studyArea, {"canQuery": False}, "Study Area") >>> Map.centerObject(studyArea) >>> Map.turnOnInspector() >>> Map.view()
- geeViz.getImagesLib.getProcessedModis(startYear: int, endYear: int, startJulian: int, endJulian: int, zenithThresh: float = 90, addLookAngleBands: bool = True, applyCloudScore: bool = True, applyTDOM: bool = True, useTempInCloudMask: bool = True, cloudScoreThresh: int = 20, performCloudScoreOffset: bool = True, cloudScorePctl: int = 10, zScoreThresh: float = -1, shadowSumThresh: float = 0.35, contractPixels: int = 0, dilatePixels: float = 2.5, shadowSumBands: list[str] = ['nir', 'swir2'], resampleMethod: str = 'bicubic', preComputedCloudScoreOffset: Image | None = None, preComputedTDOMIRMean: Image | None = None, preComputedTDOMIRStdDev: Image | None = None, addToMap: bool = False, crs: str = 'EPSG:4326', scale: int | None = 250, transform: list[int] | None = None)[source]¶
Retrieves, processes, and filters MODIS imagery for a specified period.
This function retrieves daily MODIS imagery from Earth Engine, applies various cloud and cloud shadow masking techniques, and returns a collection of processed images.
- Parameters:
startYear (int) – The starting year for the data collection.
endYear (int) – The ending year for the data collection.
startJulian (int) – The starting Julian day of year for the data collection (1-366).
endJulian (int) – The ending Julian day of year for the data collection (1-366).
zenithThresh (float, optional) – Sets the threshold for solar zenith angle in degrees. Pixels with zenith angle exceeding this threshold will be masked out. Defaults to 90.
addLookAngleBands (bool, optional) – Controls whether to include view angle bands in the output. Defaults to True.
applyCloudScore (bool, optional) – Determines whether to apply cloud masking based on the CloudScore simple algorithm adapted to MODIS. Defaults to True.
applyTDOM (bool, optional) – Determines whether to apply the TDOM (Temporal Dark Outlier Mask)
True. (technique for cloud shadow masking. Defaults to)
useTempInCloudMask (bool, optional) – Determines whether to use the thermal band for cloud masking during MODIS data retrieval. Defaults to True.
cloudScoreThresh (int, optional) – Threshold for the CloudScore simple algorithm to classify a pixel as cloudy. Lower number masks out more. Defaults to 20.
performCloudScoreOffset (bool, optional) – Controls whether to perform an offset correction on the Cloud Score data over bright surfaces. Only use this if bright areas are being masked as clouds. Do not use this in persistently cloud areas. Defaults to True.
cloudScorePctl (int, optional) – Percentile of the Cloud Score product to use for the offset correction. Defaults to 10.
zScoreThresh (float, optional) – Threshold for the z-score used in TDOM cloud shadow masking. Pixels with z-scores below this threshold are masked. Defaults to -1.
shadowSumThresh (float, optional) – Threshold for the sum of reflectance in shadow bands used in TDOM cloud shadow masking. Pixels below this threshold and the zScoreThresh are masked as dark outliers (likely cloud shadows). Defaults to 0.35.
contractPixels (int, optional) – Number of pixels to contract cloud and shadow masks by. Defaults to 0.
dilatePixels (float, optional) – Number of pixels to dilate cloud and shadow masks by. Defaults to 2.5.
shadowSumBands (list[str], optional) – List of band names to use for calculating the sum of reflectance in TDOM cloud shadow masking. Defaults to [“nir”, “swir2”].
resampleMethod (str, optional) – Specifies the resampling method to apply to the imagery. Valid options include “near”, “bilinear”, and “bicubic”. Defaults to “bicubic”.
preComputedCloudScoreOffset (float | None, optional) – Pre-computed Cloud Score offset value to avoid redundant calculations. Defaults to None (automatic calculation).
preComputedTDOMIRMean (float | None, optional) – Pre-computed mean of the IR band used in TDOM cloud shadow masking to avoid redundant calculations. Defaults to None (automatic calculation).
preComputedTDOMIRStdDev (float | None, optional) – Pre-computed standard deviation of the IR band used in TDOM cloud shadow masking to avoid redundant calculations. Defaults to None (automatic calculation).
addToMap (bool, optional) – Controls whether to add intermediate processing steps (masked medians) to the Earth Engine map for visualization purposes. Defaults to False.
crs (str, optional) – Only used if addToMap is True. Coordinate Reference System (CRS) for the output imagery. Defaults to “EPSG:4326”.
scale (int | None, optional) – Only used if addToMap is True. Scale (resolution) of the output imagery in meters. Defaults to 250.
transform (list | None, optional) – Only used if addToMap is True. Optional transformation matrix to apply to the output imagery. Defaults to None.
>>> import geeViz.getImagesLib as gil >>> Map = gil.Map >>> ee = gil.ee >>> crs = gil.common_projections["NLCD_CONUS"]["crs"] >>> transform = gil.common_projections["NLCD_CONUS"]["transform"] >>> scale = 240 >>> transform[0] = scale >>> transform[4] = -scale >>> composite = gil.getProcessedModis(2024, 2024, 190, 250).median().reproject(crs, transform) >>> Map.addLayer(composite, gil.vizParamsFalse, "MODIS Composite") >>> Map.setCenter(-111, 41, 7) >>> Map.turnOnInspector() >>> Map.view()
- geeViz.getImagesLib.getQABits(image: Image, start: int, end: int, name: str) Image [source]¶
Extracts specific bits from a QA band.
This function extracts a range of bits from a QA band and creates a new band.
- Parameters:
image – The input Earth Engine Image with a QA band.
start – The starting bit position (0-based).
end – The ending bit position.
name – The name for the output band.
- Returns:
The Earth Engine Image with the extracted bits.
- geeViz.getImagesLib.getS1(studyArea: Geometry | Feature | FeatureCollection, startYear: int, endYear: int, startJulian: int, endJulian: int, polarization: str = 'VV', pass_direction: str = 'ASCENDING') ImageCollection [source]¶
Loads Sentinel-1 GRD data for a given area and time period.
- Parameters:
studyArea – The geographic area of interest.
startYear – The start year of the desired data.
endYear – The end year of the desired data.
startJulian – The start Julian day of the desired data.
endJulian – The end Julian day of the desired data.
polarization – The desired polarization (default: “VV”).
pass_direction – The desired pass direction (default: “ASCENDING”).
- Returns:
An Earth Engine ImageCollection containing the loaded Sentinel-1 data.
- geeViz.getImagesLib.getS2(studyArea: Geometry | Feature | FeatureCollection, startDate: Date | datetime | str, endDate: Date | datetime | str, startJulian: int = 1, endJulian: int = 365, resampleMethod: str = 'nearest', toaOrSR: str = 'TOA', convertToDailyMosaics: bool = True, addCloudProbability: bool = False, addCloudScorePlus: bool = True, cloudScorePlusScore: str = 'cs') ImageCollection [source]¶
Loads Sentinel-2 data for a given area and time period and joins cloud score information. Partially deprecated in favor of the simpler superSimpleGetS2.
- Parameters:
studyArea – The geographic area of interest.
startDate – The start date of the desired data. Can be an ee.Date object, datetime object, or date string.
endDate – The end date of the desired data. Can be an ee.Date object, datetime object, or date string.
startJulian – The start Julian day of the desired data.
endJulian – The end Julian day of the desired data.
resampleMethod – The resampling method (default: “nearest”).
toaOrSR – Whether to load TOA or SR data (default: “TOA”).
convertToDailyMosaics – Whether to convert the data to daily mosaics (default: True).
addCloudProbability – Whether to add cloud probability data (default: False).
addCloudScorePlus – Whether to add cloud score plus data (default: True).
cloudScorePlusScore – The band name for cloud score plus (default: “cs”).
- Returns:
A collection of Sentinel-2 satellite images filtered by the specified criteria.
- Return type:
ee.ImageCollection
>>> import geeViz.getImagesLib as gil >>> Map = gil.Map >>> ee = gil.ee >>> studyArea = gil.testAreas["CA"] >>> composite = gil.getS2(studyArea, "2024-01-01", "2024-12-31", 190, 250).median() >>> Map.addLayer(composite, gil.vizParamsFalse, "Sentinel-2 Composite") >>> Map.addLayer(studyArea, {"canQuery": False}, "Study Area") >>> Map.centerObject(studyArea) >>> Map.turnOnInspector() >>> Map.view()
- geeViz.getImagesLib.getSentinel2(studyArea: Geometry | Feature | FeatureCollection, startDate: Date | datetime | str, endDate: Date | datetime | str, startJulian: int = 1, endJulian: int = 365, resampleMethod: str = 'nearest', toaOrSR: str = 'TOA', convertToDailyMosaics: bool = True, addCloudProbability: bool = False, addCloudScorePlus: bool = True, cloudScorePlusScore: str = 'cs') ImageCollection ¶
Loads Sentinel-2 data for a given area and time period and joins cloud score information. Partially deprecated in favor of the simpler superSimpleGetS2.
- Parameters:
studyArea – The geographic area of interest.
startDate – The start date of the desired data. Can be an ee.Date object, datetime object, or date string.
endDate – The end date of the desired data. Can be an ee.Date object, datetime object, or date string.
startJulian – The start Julian day of the desired data.
endJulian – The end Julian day of the desired data.
resampleMethod – The resampling method (default: “nearest”).
toaOrSR – Whether to load TOA or SR data (default: “TOA”).
convertToDailyMosaics – Whether to convert the data to daily mosaics (default: True).
addCloudProbability – Whether to add cloud probability data (default: False).
addCloudScorePlus – Whether to add cloud score plus data (default: True).
cloudScorePlusScore – The band name for cloud score plus (default: “cs”).
- Returns:
A collection of Sentinel-2 satellite images filtered by the specified criteria.
- Return type:
ee.ImageCollection
>>> import geeViz.getImagesLib as gil >>> Map = gil.Map >>> ee = gil.ee >>> studyArea = gil.testAreas["CA"] >>> composite = gil.getS2(studyArea, "2024-01-01", "2024-12-31", 190, 250).median() >>> Map.addLayer(composite, gil.vizParamsFalse, "Sentinel-2 Composite") >>> Map.addLayer(studyArea, {"canQuery": False}, "Study Area") >>> Map.centerObject(studyArea) >>> Map.turnOnInspector() >>> Map.view()
- geeViz.getImagesLib.getTasseledCap(image: Image) Image [source]¶
Computes the Tasseled Cap transformation for an image using the Crist 1985 coefficients.
- Parameters:
image – The input Earth Engine image.
- Returns:
The image with added Tasseled Cap components.
- geeViz.getImagesLib.harmonizationChastain(img: Image, fromSensor: str, toSensor: str) Image [source]¶
Harmonizes Landsat images using Chastain et al. (2018) coefficients.
- Parameters:
img – The input Landsat image.
fromSensor – The sensor of the input image (e.g., ‘OLI’, ‘ETM+’).
toSensor – The target sensor for harmonization (e.g., ‘OLI’, ‘ETM+’).
- Returns:
A harmonized Landsat image.
- geeViz.getImagesLib.harmonizationRoy(oli: Image) Image [source]¶
Harmonizes Landsat 8 OLI to Landsat 7 ETM+ using Roy et al. (2016) coefficients.
- Parameters:
oli – A Landsat 8 OLI image.
- Returns:
A harmonized Landsat 8 OLI image.
- geeViz.getImagesLib.landsatCloudScore(img: Image) Image [source]¶
Computes a cloud score for a Landsat image and adds a band that represents the cloud mask. This expects the input image to have the common band names: [“red”, “blue”, etc], so it can work across sensors.
- Parameters:
img – The input Landsat image.
- Returns:
An image with a cloud score band.
- geeViz.getImagesLib.maskEmptyPixels(image: Image) Image [source]¶
Masks pixels without observations in an image.
This function masks pixels where the number of observations is zero.
- Parameters:
image – The input Earth Engine Image with a “num_observations_1km” band.
- Returns:
The masked Earth Engine Image.
- geeViz.getImagesLib.maskS2clouds(image: Image) Image [source]¶
Masks clouds in a Sentinel-2 image using the QA60 band.
- Parameters:
image – The input Sentinel-2 image.
- Returns:
The cloud-masked image.
- geeViz.getImagesLib.medoidMosaicMSD(inCollection: ImageCollection, medoidIncludeBands: List | None = None) Image [source]¶
Creates a medoid mosaic using the Mean Squared Difference (MSD) (euclidean distance) method.
This function calculates the medoid image from an image collection based on minimizing the sum of squared differences between pixel values.
- Parameters:
inCollection – The input Earth Engine ImageCollection to create the mosaic from.
medoidIncludeBands – A list of band names to include in the MSD calculation. If None, all bands are used.
- Returns:
An Earth Engine Image representing the medoid mosaic.
Note
As the data are not normalized in this method, ensuring the medoidIncludeBands have roughly comparable ranges of values helps the function work properly. For example, if temperature is included, it will account for most of the variance thus resulting in a medoid mosaic that will more or less choose values closest to the median temperature only, rather than all the bands
The function assumes that the image collection has consistent band names and data types.
>>> import geeViz.getImagesLib as gil >>> Map = gil.Map >>> ee = gil.ee >>> studyArea = gil.testAreas["CO"] >>> s2s = gil.superSimpleGetS2(studyArea, "2024-01-01", "2024-12-31", 190, 250) >>> median_composite = s2s.median() >>> medoid_composite = gil.medoidMosaicMSD(s2s, ["green", "red", "nir", "swir1", "swir2"]) >>> Map.addLayer(median_composite, gil.vizParamsFalse10k, "Sentinel-2 Median Composite") >>> Map.addLayer(medoid_composite, gil.vizParamsFalse10k, "Sentinel-2 Medoid Composite") >>> Map.addLayer(studyArea, {"canQuery": False}, "Study Area") >>> Map.centerObject(studyArea) >>> Map.turnOnInspector() >>> Map.view()
- geeViz.getImagesLib.offsetImageDate(img: Image, n: int, unit: str) Image [source]¶
Offsets the date of an image.
- Parameters:
img – The input Earth Engine image.
n – The number of units to offset.
unit – The unit of the offset (e.g., ‘year’, ‘month’, ‘day’).
- Returns:
The image with an offset date.
- geeViz.getImagesLib.rescale(img: Image, thresholds: tuple) Image [source]¶
Rescales pixel values in an image using a min-max normalization.
- Parameters:
img – The input Earth Engine image.
thresholds – A tuple containing the minimum and maximum values for rescaling.
- Returns:
A rescaled Earth Engine image.
- geeViz.getImagesLib.setNoData(image: Image, noDataValue: float) Image [source]¶
Sets null values for an image.
- Parameters:
image – The input Earth Engine image.
noDataValue – The value to assign to null pixels.
- Returns:
An Earth Engine image with null pixels set to the specified noDataValue.
- geeViz.getImagesLib.sieve(image: Image, mmu: float) Image [source]¶
Performs clumping and elimination on an image.
- Parameters:
image – The input Earth Engine image.
mmu – The minimum mapping unit.
- Returns:
An Earth Engine image with clumping and elimination applied.
- geeViz.getImagesLib.simpleAddIndices(in_image: Image) Image [source]¶
Adds common spectral indices to an image.
- Parameters:
in_image – The input Earth Engine image.
- Returns:
The image with added NDVI, NBR, NDMI, and NDSI indices.
- geeViz.getImagesLib.simpleAddTCAngles(image: Image) Image [source]¶
Adds the Tasseled Cap brightness-greenness angle to an image as in Powell et al 2009. Assumes image has bands: ‘brightness’, ‘greenness’, and ‘wetness’.
- Parameters:
image – The input Earth Engine image with brightness and greenness bands.
- Returns:
The image with added brightness-greenness angle.
- geeViz.getImagesLib.simpleGetTasseledCap(image: Image) Image [source]¶
Computes the Tasseled Cap transformation for an image, including only brightness, greenness, and wetness using the Crist 1985 coefficients.
- Parameters:
image – The input Earth Engine image.
- Returns:
The image with added brightness, greenness, and wetness bands.
- geeViz.getImagesLib.simpleTDOM2(collection: ImageCollection, zScoreThresh: float = -1, shadowSumThresh: float = 0.35, contractPixels: float = 1.5, dilatePixels: float = 3.5, shadowSumBands: list = ['nir', 'swir1'], preComputedTDOMIRMean: Image | None = None, preComputedTDOMIRStdDev: Image | None = None) ImageCollection [source]¶
Applies a simple temporal dark object differencing (TDOM) algorithm to an image collection. Adds a band that is a mask of pixels that are dark, and dark outliers.
- Parameters:
collection – The input Earth Engine image collection.
zScoreThresh – The z-score threshold for dark outliers (default: -1).
shadowSumThresh – The shadow sum threshold (default: 0.35).
contractPixels – The contraction kernel size (default: 1.5).
dilatePixels – The dilation kernel size (default: 3.5).
shadowSumBands – The bands used for shadow sum calculation (default: [“nir”, “swir1”]).
preComputedTDOMIRMean – Precomputed mean of the shadow sum bands (optional).
preComputedTDOMIRStdDev – Precomputed standard deviation of the shadow sum bands (optional).
- Returns:
The image collection with dark outliers masked.
- geeViz.getImagesLib.simpleWaterMask(img: Image, contractPixels: int = 0, slope_thresh: float = 10, elevationImagePath: str | Image | ImageCollection = 'USGS/3DEP/10m', elevationFocalMeanRadius: float = 5.5) Image [source]¶
Performs a basic on-the-fly water masking for TOA reflectance imagery.
This function creates a water mask based on thresholds applied to Tasseled Cap angles, brightness, and slope. It’s designed for time-sensitive analysis and works well when wet snow is absent. However, wet snow in flat areas can lead to false positives. SR data might cause false negatives (omissions).
- Parameters:
img (ee.Image) – The input Earth Engine image (TOA reflectance data recommended) with Tasseled Cap transformation bands added. You may need to run getTasseledCap to add these bands.
contractPixels (int, optional) – Number of pixels to contract the water mask by for morphological closing. Defaults to 0 (no contraction).
slope_thresh (float, optional) – Threshold for slope (degrees) to identify flat areas suitable for water masking. Defaults to 10.
elevationImagePath (str or ee.Image or ee.ImageCollection, optional) – Path to the Earth Engine image or Earth Engine image or imageCollection object containing elevation data. Defaults to “USGS/3DEP/10m” (10m DEM from USGS 3D Elevation Program).
elevationFocalMeanRadius (float, optional) – Radius (in pixels) for the focal mean filter applied to the elevation data before calculating slope. Defaults to 5.5.
- Returns:
The water mask image with a single band named “waterMask”.
- Return type:
ee.Image
>>> import geeViz.getImagesLib as gil >>> Map = gil.Map >>> ee = gil.ee >>> studyArea = gil.testAreas["CO"] >>> s2s = gil.superSimpleGetS2(studyArea, "2024-01-01", "2024-12-31", 190, 250).map(lambda img: gil.getTasseledCap(img.resample("bicubic").divide(10000))) >>> median_composite = s2s.median() >>> water = gil.simpleWaterMask(median_composite).rename("Water") >>> water = water.selfMask().set({"Water_class_values": [1], "Water_class_names": ["Water"], "Water_class_palette": ["0000DD"]}) >>> Map.addLayer(median_composite.reproject("EPSG:32613", None, 10), gil.vizParamsFalse, "Sentinel-2 Median Composite") >>> Map.addLayer(water.reproject("EPSG:32613", None, 10), {"autoViz": True}, "Water Mask") >>> Map.addLayer(studyArea, {"canQuery": False}, "Study Area") >>> Map.centerObject(studyArea, 12) >>> Map.turnOnInspector() >>> Map.view()
- geeViz.getImagesLib.superSimpleGetS2(studyArea: Geometry | Feature | FeatureCollection | None, startDate: Date | datetime | str, endDate: Date | datetime | str, startJulian: int = 1, endJulian: int = 365, toaOrSR: str = 'TOA', applyCloudScorePlus: bool = True, cloudScorePlusThresh: float = 0.6, cloudScorePlusScore: str = 'cs') ImageCollection [source]¶
This function retrieves Sentinel-2 satellite imagery from Earth Engine for a specified study area and date range. It applies the cloudScore+ algorithm unless told otherwise.
- Parameters:
studyArea (ee.Geometry, ee.Feature, ee.FeatureCollection, or None, optional) – An Earth Engine geometry object representing the area of interest. If set to None, startJulian and endJulian cannot be used. Doing so will cause the image to never render.
startDate (ee.Date, datetime.datetime, or str) – The start date for the image collection in YYYY-MM-DD format.
endDate (ee.Date, datetime.datetime, or str) – The end date for the image collection in YYYY-MM-DD format.
startJulian (int, optional) – The start Julian day of the desired data. Defaults to 1.
endJulian (int, optional) – The end Julian day of the desired data. Defaults to 365.
toaOrSR (str, optional) – Specifies whether to retrieve data in Top-Of-Atmosphere (TOA) reflectance or Surface Reflectance (SR). Defaults to “TOA”.
applyCloudScorePlus (bool, optional) – Determines whether to apply cloud filtering based on the Cloud Score Plus product. Defaults to True.
cloudScorePlusThresh (float, optional) – Sets the threshold for cloud cover percentage based on Cloud Score Plus. Images with cloud cover exceeding this threshold will be masked out if applyCloudScorePlus is True. A higher value will mask out more pixels (call them cloud/cloud-shadow). Defaults to 0.6.
cloudScorePlusScore (str, optional) – One of “cs” - Tends to mask out more. Commits ephemeral water, but doesn’t omit cloud shadows as much or “cs_cdf” - Tends to mask out less, notably fewer water bodies and shadows. This can result in omitting cloud shadows, but not committing ephemeral water as a cloud shadow. Specifies the band name within the Cloud Score Plus product containing the cloud cover information. Defaults to “cs”.
- Returns:
A collection of cloud and cloud-shadow-free Sentinel-2 satellite images filtered by the specified criteria.
- Return type:
ee.ImageCollection
>>> import geeViz.getImagesLib as gil >>> Map = gil.Map >>> ee = gil.ee >>> studyArea = gil.testAreas["CA"] >>> composite = gil.superSimpleGetS2(studyArea, "2024-01-01", "2024-12-31", 190, 250).median() >>> Map.addLayer(composite, gil.vizParamsFalse10k, "Sentinel-2 Composite") >>> Map.addLayer(studyArea, {"canQuery": False}, "Study Area") >>> Map.centerObject(studyArea) >>> Map.turnOnInspector() >>> Map.view()
- geeViz.getImagesLib.toDB(img: Image) Image [source]¶
Converts a Sentinel-1 image from natural units to dB.
- Parameters:
img – The input Sentinel-1 image in natural units.
- Returns:
The converted image in dB.
- geeViz.getImagesLib.toNatural(img: Image) Image [source]¶
Converts a Sentinel-1 image from dB to natural units.
- Parameters:
img – The input Sentinel-1 image in dB.
- Returns:
The converted image in natural units.
- geeViz.getImagesLib.uniqueValues(collection: ImageCollection, field: str) List [source]¶
Finds unique values of a field in an image collection.
- Parameters:
collection – The input Earth Engine image collection.
field – The field to extract unique values from.
- Returns:
A list of unique values.
- geeViz.getImagesLib.wrapDates(startJulian: int, endJulian: int) list [source]¶
Wraps dates when the startJulian is greater than the endJulian.
This function handles cases where the start Julian day is later in the year than the end Julian day.
- Parameters:
startJulian – The start Julian day.
endJulian – The end Julian day.
- Returns:
A list containing the wrap offset and the year with the majority of days.
geeViz.changeDetectionLib¶
Apply change detection methods usin GEE
geeViz.changeDetectionLib is the core module for setting up various change detection algorithms within GEE. Notably, it facilitates the use of LandTrendr and CCDC data preparation, application, and output formatting, compression, and decompression.
- geeViz.changeDetectionLib.batchFeatherCCDCImgs(ccdcAnnualizedCol1: ImageCollection, ccdcAnnualizedCol2: ImageCollection, featherStartYr: int, featherEndYr: int) ImageCollection [source]¶
Wrapper function to join annualized CCDC images from two different CCDC collections, and iterate across images and apply featherCCDCImgs function The feather years are the overlapping years between the two CCDC collections that are used in weighting
- geeViz.changeDetectionLib.ccdcChangeDetection(ccdcImg: list[Image, Image] | Image, bandName: str, startYear: None | int = None, endYear: None | int = None) dict [source]¶
Function for getting change years and magnitudes for a specified band from CCDC outputs Only change from the breaks is extracted. As of now, if a segment has a high slope value, this method will not extract that. If combining two CCDC raw outputs provide them as a list of two images for the ccdcImg parameter.
- Parameters:
ccdcImg (list[ee.Image, ee.Image] | ee.Image) – A raw CCDC ee.Image array or list of two raw CCDC ee.Image arrays. If a list of 2 images is provided, they will automatically be combined.
bandName (str) – The band name to use for magnitude of change.
startYear (None | int) – The start of the time window. If left as None, all years in the input CCDC images will be included. Defaults to None.
endYear (None | int) – The end of the time window (inclusive). If left as None, all years in the input CCDC images will be included. Defaults to None.
- Returns:
A dictionary of various CCDC change metrics.
- Return type:
dict
>>> import geeViz.changeDetectionLib as cdl >>> Map = cdl.Map >>> ee = cdl.ee >>> changeDetectionBandName = "NDVI" >>> ccdcChangeBandNames = ["tBreak", "changeProb", f"{changeDetectionBandName}.*"] >>> sortingMethod = "mostRecent" >>> ccdcImg1 = ee.ImageCollection("projects/lcms-292214/assets/CONUS-LCMS/Base-Learners/CCDC-Collection-1984-2022").select(ccdcChangeBandNames).mosaic() >>> ccdcImg2 = ee.ImageCollection("projects/lcms-292214/assets/CONUS-LCMS/Base-Learners/CCDC-Feathered-Collection").select(ccdcChangeBandNames).mosaic() >>> changeObjCombined = cdl.ccdcChangeDetection([ccdcImg1, ccdcImg2], changeDetectionBandName) >>> Map.addLayer(changeObjCombined[sortingMethod]["loss"]["year"], {"min": 1984, "max": 2024, "palette": cdl.lossYearPalette}, "Loss Year") >>> Map.addLayer(changeObjCombined[sortingMethod]["loss"]["mag"], {"min": -0.5, "max": -0.1, "palette": cdl.lossMagPalette}, "Loss Mag", False) >>> Map.addLayer(changeObjCombined[sortingMethod]["gain"]["year"], {"min": 1984, "max": 2024, "palette": cdl.gainYearPalette}, "Gain Year") >>> Map.addLayer(changeObjCombined[sortingMethod]["gain"]["mag"], {"min": 0.05, "max": 0.2, "palette": cdl.gainMagPalette}, "Gain Mag", False) >>> Map.turnOnInspector() >>> Map.setCenter(-88, 36, 12) >>> Map.view()
- geeViz.changeDetectionLib.featherCCDCImgs(joinedCCDCImg: Image, ccdcBnds: list | List, coeffs1_bns: list | List, coeffs2_bns: list | List, featherStartYr: int, featherEndYr: int) Image [source]¶
Function to feather two CCDC collections together based on overlapping data time periods and weights The feather years are the overlapping years between the two CCDC collections that are used in weighting
- geeViz.changeDetectionLib.predictCCDC(ccdcImg: list[Image, Image] | Image, timeImgs: ImageCollection, fillGaps: bool = True, whichHarmonics: list[int] = [1, 2, 3], featherStartYr: int = 2015, featherEndYr: int = 2021) ImageCollection [source]¶
Takes one or two raw CCDC ee.Image array outputs, an ee.ImageCollection of time images, and returns a time-series ee.ImageCollection with harmonic coefficients and fitted values
- Parameters:
ccdcImg (list[ee.Image, ee.Image] | ee.Image) – A raw CCDC ee.Image array or list of two raw CCDC ee.Image arrays. If a list of 2 images is provided, feathering will automatically be performed. Note that any pixel that is null in either CCDC image will result in a null value in the predicted output.
timeImgs (ee.ImageCollection) – An ee.ImageCollection of time images usually from functions such as simpleGetTimeImageCollection.
fillGaps (bool, optional) – Whether to fill gaps between segments. If false, outputs can have blank values mid time-series. Defaults to True.
whichHarmonics (list[int], optional) – Which harmonics to include in fitted outputs forreturned time-series. Defaults to [1,2,3].
featherStartYear (int, optional) – If a list of 2 images is provided as ccdcImg, this is the first year of the window used for feathering the two time-series together. Defaults to 2015.
featherEndYear (int, optional) – If a list of 2 images is provided as ccdcImg, this is the last year (inclusive) of the window used for feathering the two time-series together. Defaults to 2021.
- Returns:
A collection of CCDC coefficients and fitted values.
- Return type:
ee.ImageCollection
>>> import geeViz.changeDetectionLib as cdl >>> Map = cdl.Map >>> ee = cdl.ee >>> ccdcBandNames = ["tStart", "tEnd", "tBreak", "changeProb", "swir1.*", "NDVI.*"] >>> timeImgs = cdl.simpleGetTimeImageCollection(startYear=1984, endYear=2024, startJulian=1, endJulian=365, step=0.1) >>> ccdcImg1 = ee.ImageCollection("projects/lcms-292214/assets/CONUS-LCMS/Base-Learners/CCDC-Collection-1984-2022").select(ccdcBandNames).mosaic() >>> ccdcImg2 = ee.ImageCollection("projects/lcms-292214/assets/CONUS-LCMS/Base-Learners/CCDC-Feathered-Collection").select(ccdcBandNames).mosaic() >>> fittedFeathered = cdl.predictCCDC(ccdcImg=[ccdcImg1, ccdcImg2], timeImgs=timeImgs, fillGaps=True, whichHarmonics=[1, 2, 3], featherStartYr=2015, featherEndYr=2021) >>> Map.addLayer(fittedFeathered.select([".*_CCDC_fitted"]), {"reducer": ee.Reducer.mean(), "min": 0.3, "max": 0.8}, "Combined CCDC", True) >>> Map.turnOnInspector() >>> Map.setCenter(-88, 36, 12) >>> Map.view()
- geeViz.changeDetectionLib.simpleGetTimeImageCollection(startYear: int, endYear: int, startJulian: int = 1, endJulian: int = 365, step: float = 0.1)[source]¶
Provides a time series of year and decimal days ee.ImageCollection. This is useful for CCDC predictions
- Parameters:
startYear (int) – The starting year for returned time-series.
endYear (int) – The ending year for the returned time-series.
startJulian (int) – The starting Julian day of year for returned time-series (1-365).
endJulian (int) – The ending Julian day of year for returned time-series (1-365).
step (float, optional) – Fraction of a year for each output in returned time-series (~0.01-1). Defaults to 0.1.
- Returns:
A collection of time images.
- Return type:
ee.ImageCollection
>>> import geeViz.changeDetectionLib as cdl >>> Map = cdl.Map >>> ee = cdl.ee >>> timeImgs = cdl.simpleGetTimeImageCollection(startYear = 1984, endYear = 2024, startJulian = 1, endJulian = 365, step = 0.1) >>> Map.addLayer(timeImgs, {}, "Time Images", True) >>> Map.turnOnInspector() >>> Map.view()
- geeViz.changeDetectionLib.simpleLANDTRENDR(ts, startYear, endYear, indexName='NBR', run_params=None, lossMagThresh=-0.15, lossSlopeThresh=-0.1, gainMagThresh=0.1, gainSlopeThresh=0.1, slowLossDurationThresh=3, chooseWhichLoss='largest', chooseWhichGain='largest', addToMap=True, howManyToPull=2, multBy=10000)[source]¶
Takes annual time series input data, properly sets it up for LandTrendr, runs LandTrendr, and provides both a compressed vertex-only format output as well as a basic change detection output.
geeViz.taskManagerLib¶
Monitor and manage tasks programatically
geeViz.taskManagerLib facilitates the monitoring and deleting of GEE export tasks.
- geeViz.taskManagerLib.batchCancel()[source]¶
Cancel all tasks that are either ready or running.
Example
>>> batchCancel() Cancelling: ExportImage READY: ExportImage ...
- geeViz.taskManagerLib.cancelByName(nameIdentifier)[source]¶
Cancel all tasks whose description contains the given identifier.
- Parameters:
nameIdentifier (str) – Substring to search for in task descriptions.
Example
>>> cancelByName('ExportImage') Cancelling ExportImage ...
- geeViz.taskManagerLib.failedTasks()[source]¶
Print all failed tasks and their run times.
Example
>>> failedTasks() Failed names: {'id': 'ABCD', 'state': 'FAILED', ...} ...
- geeViz.taskManagerLib.getEECUS(output_table_name, nameFind=None, overwrite=False)[source]¶
Create a CSV table of successful exports, including run time, EECU usage, and output size.
- Parameters:
output_table_name (str) – Path to output CSV file.
nameFind (str, optional) – Substring to filter task descriptions.
overwrite (bool, optional) – Overwrite existing file if True.
Example
>>> getEECUS('output.csv', nameFind='ExportImage', overwrite=True) Only output extension allowed is .csv. Changing extension to .csv ...
- geeViz.taskManagerLib.getTasks(id_list=None)[source]¶
Get a dictionary of tasks grouped by their state.
- Parameters:
id_list (list, optional) – List of task descriptions to filter.
- Returns:
Dictionary with keys ‘ready’, ‘running’, ‘failed’, ‘completed’.
- Return type:
dict
Example
>>> getTasks() {'ready': ['ExportImage'], 'running': [], 'failed': [], 'completed': ['ExportTable']}
- geeViz.taskManagerLib.jobCompletionTracker(starttime, endtime, check_interval)[source]¶
Track completion of all jobs started within a time interval.
- Parameters:
starttime (datetime) – UTC datetime object for interval start.
endtime (datetime) – UTC datetime object for interval end.
check_interval (int) – Seconds between status checks.
- Returns:
Lists of ready, running, completed, failed, cancelled, and all tasks.
- Return type:
list
Example
>>> from datetime import datetime, timedelta >>> start = datetime.utcnow() - timedelta(hours=1) >>> end = datetime.utcnow() >>> jobCompletionTracker(start, end, 10) ...
- geeViz.taskManagerLib.nameTaskList(nameIdentifier)[source]¶
Get list of tasks with specified name/description prefix.
- Parameters:
nameIdentifier (str) – Substring to search for in task descriptions.
- Returns:
List of matching task dicts.
- Return type:
list
Example
>>> nameTaskList('ExportImage') [{'id': 'ABCD', ...}, ...]
- geeViz.taskManagerLib.now()[source]¶
Get the current time as a formatted string.
- Returns:
Current time in “%Y-%m-%d %H:%M:%S” format.
- Return type:
str
Example
>>> now() '2025-06-01 12:34:56'
- geeViz.taskManagerLib.timeTaskList(starttime, endtime)[source]¶
Get list of tasks started within a specified time interval.
- Parameters:
starttime (datetime) – UTC datetime object for interval start.
endtime (datetime) – UTC datetime object for interval end.
- Returns:
List of task dicts started within the interval.
- Return type:
list
Example
>>> from datetime import datetime, timedelta >>> start = datetime.utcnow() - timedelta(hours=1) >>> end = datetime.utcnow() >>> timeTaskList(start, end) [{'id': 'ABCD', ...}, ...]
- geeViz.taskManagerLib.trackTasks()[source]¶
Track and print the number of ready and running tasks every 10 seconds, up to 1000 times.
Example
>>> trackTasks() 2 tasks ready 2025-06-01 12:34:56 1 tasks running 2025-06-01 12:34:56 Running names: ['ExportImage', '0:01:23'] ...
- geeViz.taskManagerLib.trackTasks2(credential_name=None, id_list=None, task_count=1)[source]¶
Track tasks for a specific credential or list of task IDs, printing status every 5 seconds.
- Parameters:
credential_name (str, optional) – Name of the credential to print.
id_list (list, optional) – List of task descriptions to filter.
task_count (int, optional) – Initial task count to start tracking.
Example
>>> trackTasks2(credential_name='user', id_list=['ExportImage'], task_count=1) user 1 tasks ready 2025-06-01 12:34:56 0 tasks running 2025-06-01 12:34:56 Running names: ...
geeViz.assetManagerLib¶
Helpful functions for managing GEE assets
geeViz.assetManagerLib includes functions for copying, deleting, uploading, changing permissions, and more.
- geeViz.assetManagerLib.assetsize(asset)[source]¶
Prints the size of a GEE asset.
- Parameters:
asset (str) – The path to the GEE asset.
- Returns:
None
Example
>>> assetsize('users/youruser/yourasset')
- geeViz.assetManagerLib.base(in_path)[source]¶
Gets the filename without extension.
- Parameters:
in_path (str) – The input path.
- Returns:
The filename without extension.
- Return type:
str
Example
>>> base('/tmp/image.tif') 'image'
- geeViz.assetManagerLib.batchCopy(fromFolder, toFolder, outType='imageCollection')[source]¶
Copies all assets from one folder to another in GEE.
- Parameters:
fromFolder (str) – The source folder path.
toFolder (str) – The destination folder path.
outType (str, optional) – The type of assets to copy (‘imageCollection’ or ‘tables’). Defaults to ‘imageCollection’.
- Returns:
None
Example
>>> batchCopy('users/youruser/source', 'users/youruser/dest')
- geeViz.assetManagerLib.batchDelete(Collection, type='imageCollection')[source]¶
Deletes all assets in a collection.
- Parameters:
Collection (str) – The path to the collection.
type (str, optional) – The type of assets to delete (‘imageCollection’ or ‘tables’). Defaults to ‘imageCollection’.
- Returns:
None
Example
>>> batchDelete('users/youruser/collection')
- geeViz.assetManagerLib.batchUpdateAcl(folder, writers=[], all_users_can_read=True, readers=[])[source]¶
Updates the ACL for all assets under a given folder in GEE.
- Parameters:
folder (str) – The path to the folder in GEE.
writers (list, optional) – List of users with write access. Defaults to an empty list.
all_users_can_read (bool, optional) – Whether all users can read the assets. Defaults to True.
readers (list, optional) – List of users with read access. Defaults to an empty list.
- Returns:
None
Example
>>> batchUpdateAcl('users/youruser/yourfolder', writers=['user1'], all_users_can_read=False)
- geeViz.assetManagerLib.check_dir(in_path)[source]¶
Ensures the directory exists.
- Parameters:
in_path (str) – The directory path.
- Returns:
None
Example
>>> check_dir('/tmp/mydir')
- geeViz.assetManagerLib.check_end(in_path, add='/')[source]¶
Ensures a trailing character is in the path.
- Parameters:
in_path (str) – The input path.
add (str, optional) – The character to add. Defaults to ‘/’.
- Returns:
The modified path.
- Return type:
str
Example
>>> check_end('users/youruser/collection') 'users/youruser/collection/'
- geeViz.assetManagerLib.copyByName(fromFolder, toFolder, nameIdentifier, outType='imageCollection')[source]¶
Copies assets from one folder to another based on a name identifier.
- Parameters:
fromFolder (str) – The source folder path.
toFolder (str) – The destination folder path.
nameIdentifier (str) – A substring to identify assets to copy.
outType (str, optional) – The type of assets to copy (‘imageCollection’ or ‘tables’). Defaults to ‘imageCollection’.
- Returns:
None
Example
>>> copyByName('users/youruser/source', 'users/youruser/dest', '2020')
- geeViz.assetManagerLib.countTasks(break_running_ready=False)[source]¶
Counts the number of tasks.
- Parameters:
break_running_ready (bool, optional) – Whether to break running and ready tasks. Defaults to False.
- Returns:
Total tasks or tuple of running and ready tasks.
- Return type:
int or tuple
Example
>>> countTasks() >>> countTasks(True)
- geeViz.assetManagerLib.create_asset(asset_path, asset_type='Folder', recursive=True)[source]¶
Creates an asset in GEE.
- Parameters:
asset_path (str) – The asset path.
asset_type (str, optional) – The type of asset. Defaults to ee.data.ASSET_TYPE_FOLDER.
recursive (bool, optional) – Whether to create nested folders. Defaults to True.
- Returns:
None
Example
>>> create_asset('users/youruser/newfolder')
- geeViz.assetManagerLib.create_image_collection(full_path_to_collection, properties=None)[source]¶
Creates an image collection in GEE.
- Parameters:
full_path_to_collection (str) – The full path to the collection.
properties (dict, optional) – Properties for the collection. Defaults to None.
- Returns:
None
Example
>>> create_image_collection('users/youruser/newcollection')
- geeViz.assetManagerLib.deleteByName(Collection, nameIdentifier, type='imageCollection')[source]¶
Deletes assets in a collection based on a name identifier.
- Parameters:
Collection (str) – The path to the collection.
nameIdentifier (str) – A substring to identify assets to delete.
type (str, optional) – The type of assets to delete (‘imageCollection’ or ‘tables’). Defaults to ‘imageCollection’.
- Returns:
None
Example
>>> deleteByName('users/youruser/collection', '2020')
- geeViz.assetManagerLib.ee_asset_exists(path)[source]¶
Checks if a GEE asset exists.
- Parameters:
path (str) – The asset path.
- Returns:
True if the asset exists, False otherwise.
- Return type:
bool
Example
>>> ee_asset_exists('users/youruser/yourasset')
- geeViz.assetManagerLib.getDate(year, month, day)[source]¶
Gets a date in ISO format.
- Parameters:
year (int) – The year.
month (int) – The month.
day (int) – The day.
- Returns:
The date in ISO format.
- Return type:
str
Example
>>> getDate(2020, 1, 1) '2020-01-01T00:00:00Z'
- geeViz.assetManagerLib.humansize(nbytes)[source]¶
Converts a file size in bytes to a human-readable format.
- Parameters:
nbytes (int) – The size in bytes.
- Returns:
The human-readable file size.
- Return type:
str
Example
>>> humansize(1048576) '1 MB'
- geeViz.assetManagerLib.ingestFromGCSImagesAsBands(gcsURIs, assetPath, overwrite=False, properties=None)[source]¶
Ingests multiple images from Google Cloud Storage as bands of a single GEE image.
- Parameters:
gcsURIs (list) – List of GCS URIs or dictionaries with band information.
assetPath (str) – The asset path in GEE.
overwrite (bool, optional) – Whether to overwrite existing assets. Defaults to False.
properties (dict, optional) – Properties for the asset. Defaults to None.
- Returns:
None
Example
>>> ingestFromGCSImagesAsBands([{'gcsURI': 'gs://mybucket/band1.tif', 'bandName': 'B1'}], 'users/youruser/yourasset')
- geeViz.assetManagerLib.ingestImageFromGCS(gcsURIs, assetPath, overwrite=False, bandNames=None, properties=None, pyramidingPolicy=None, noDataValues=None)[source]¶
Ingests an image from Google Cloud Storage to GEE.
- Parameters:
gcsURIs (list) – List of GCS URIs.
assetPath (str) – The asset path in GEE.
overwrite (bool, optional) – Whether to overwrite existing assets. Defaults to False.
bandNames (list, optional) – List of band names. Defaults to None.
properties (dict, optional) – Properties for the asset. Defaults to None.
pyramidingPolicy (list, optional) – Pyramiding policy for the bands. Defaults to None.
noDataValues (list, optional) – No data values for the bands. Defaults to None.
- Returns:
None
Example
>>> ingestImageFromGCS(['gs://mybucket/image.tif'], 'users/youruser/yourasset')
- geeViz.assetManagerLib.is_leap_year(year)[source]¶
Determines if a year is a leap year.
- Parameters:
year (int) – The year.
- Returns:
True if the year is a leap year, False otherwise.
- Return type:
bool
Example
>>> is_leap_year(2020) True
- geeViz.assetManagerLib.julian_to_calendar(julian_date, year)[source]¶
Converts a Julian date to a calendar date.
- Parameters:
julian_date (int) – The Julian date.
year (int) – The year.
- Returns:
List containing year, month, and day.
- Return type:
list
Example
>>> julian_to_calendar(32, 2020) [2020, 2, 1]
- geeViz.assetManagerLib.limitTasks(taskLimit)[source]¶
Limits the number of tasks running.
- Parameters:
taskLimit (int) – The maximum number of tasks.
- Returns:
None
Example
>>> limitTasks(10)
- geeViz.assetManagerLib.listAssets(folder: str) list[str] [source]¶
Lists assets within a given asset folder or image collection.
- Parameters:
folder (str) – The path to the asset folder or image collection.
- Returns:
A list of asset IDs within the specified folder.
- Return type:
list[str]
Example
>>> listAssets('users/youruser/yourfolder')
- geeViz.assetManagerLib.moveImages(images, toFolder, delete_original=False)[source]¶
Moves images to a new folder, optionally deleting the originals.
- Parameters:
images (list) – List of image paths to move.
toFolder (str) – The destination folder path.
delete_original (bool, optional) – Whether to delete the original images. Defaults to False.
- Returns:
None
Example
>>> moveImages(['users/youruser/img1', 'users/youruser/img2'], 'users/youruser/dest', delete_original=True)
- geeViz.assetManagerLib.now(Format='%b %d %Y %H:%M:%S %a')[source]¶
Gets the current readable date/time.
- Parameters:
Format (str, optional) – The format of the date/time. Defaults to ‘%b %d %Y %H:%M:%S %a’.
- Returns:
The current date/time.
- Return type:
str
Example
>>> now()
- geeViz.assetManagerLib.setDate(assetPath, year, month, day)[source]¶
Sets the date for an asset.
- Parameters:
assetPath (str) – The asset path.
year (int) – The year.
month (int) – The month.
day (int) – The day.
- Returns:
None
Example
>>> setDate('users/youruser/yourasset', 2020, 1, 1)
- geeViz.assetManagerLib.updateACL(assetName, writers=[], all_users_can_read=True, readers=[])[source]¶
Updates the Access Control List (ACL) for a given GEE asset.
- Parameters:
assetName (str) – The name of the GEE asset.
writers (list, optional) – List of users with write access. Defaults to an empty list.
all_users_can_read (bool, optional) – Whether all users can read the asset. Defaults to True.
readers (list, optional) – List of users with read access. Defaults to an empty list.
- Returns:
None
Example
>>> updateACL('users/youruser/yourasset', writers=['user1'], all_users_can_read=False, readers=['user2'])
- geeViz.assetManagerLib.uploadTifToGCS(tif, gcsBucket, overwrite=False)[source]¶
Uploads a single TIFF file to Google Cloud Storage.
- Parameters:
tif (str) – The path to the TIFF file.
gcsBucket (str) – The GCS bucket to upload to.
overwrite (bool, optional) – Whether to overwrite existing files. Defaults to False.
- Returns:
None
Example
>>> uploadTifToGCS('/tmp/image.tif', 'gs://mybucket')
- geeViz.assetManagerLib.uploadToGEEAssetImagesAsBands(tif_dict, gcsBucket, assetPath, overwrite=False, properties=None)[source]¶
Uploads images to GCS and manifests them as bands of a single GEE image.
- Parameters:
tif_dict (dict) – Dictionary of TIFF files and their properties.
gcsBucket (str) – The GCS bucket to upload to.
assetPath (str) – The asset path in GEE.
overwrite (bool, optional) – Whether to overwrite existing assets. Defaults to False.
properties (dict, optional) – Properties for the asset. Defaults to None.
- Returns:
None
Example
>>> tif_dict = {'/tmp/band1.tif': {'bandName': 'B1'}, '/tmp/band2.tif': {'bandName': 'B2'}} >>> uploadToGEEAssetImagesAsBands(tif_dict, 'gs://mybucket', 'users/youruser/yourasset')
- geeViz.assetManagerLib.uploadToGEEImageAsset(localTif, gcsBucket, assetPath, overwrite=False, bandNames=None, properties=None, pyramidingPolicy=None, noDataValues=None, parallel_threshold='150M', gsutil_path='C:/Program Files (x86)/Google/Cloud SDK/google-cloud-sdk/bin/gsutil.cmd')[source]¶
Uploads an image to GEE as an asset.
- Parameters:
localTif (str) – Path to the local TIFF file.
gcsBucket (str) – The GCS bucket to upload to.
assetPath (str) – The asset path in GEE.
overwrite (bool, optional) – Whether to overwrite existing assets. Defaults to False.
bandNames (list, optional) – List of band names. Defaults to None.
properties (dict, optional) – Properties for the asset. Defaults to None.
pyramidingPolicy (list, optional) – Pyramiding policy for the bands. Defaults to None.
noDataValues (list, optional) – No data values for the bands. Defaults to None.
parallel_threshold (str, optional) – Threshold for parallel uploads. Defaults to ‘150M’.
gsutil_path (str, optional) – Path to the gsutil command. Defaults to a default path.
- Returns:
None
Example
>>> uploadToGEEImageAsset('/tmp/image.tif', 'gs://mybucket', 'users/youruser/yourasset')
- geeViz.assetManagerLib.upload_to_gcs(image_dir, gs_bucket, image_extension='.tif', copy_or_sync='copy', overwrite=False)[source]¶
Uploads files to Google Cloud Storage.
- Parameters:
image_dir (str) – The directory containing the images to upload.
gs_bucket (str) – The GCS bucket to upload to.
image_extension (str, optional) – The file extension of the images. Defaults to ‘.tif’.
copy_or_sync (str, optional) – Whether to copy or sync files (‘copy’ or ‘sync’). Defaults to ‘copy’.
overwrite (bool, optional) – Whether to overwrite existing files. Defaults to False.
- Returns:
None
Example
>>> upload_to_gcs('/tmp/images/', 'gs://mybucket')
- geeViz.assetManagerLib.upload_to_gee(image_dir, gs_bucket, asset_dir, image_extension='.tif', resample_method='MEAN', band_names=[], property_list=[])[source]¶
Uploads images to Google Earth Engine.
- Parameters:
image_dir (str) – The directory containing the images to upload.
gs_bucket (str) – The GCS bucket to upload to.
asset_dir (str) – The GEE asset directory.
image_extension (str, optional) – The file extension of the images. Defaults to ‘.tif’.
resample_method (str, optional) – The resampling method. Defaults to ‘MEAN’.
band_names (list, optional) – List of band names. Defaults to an empty list.
property_list (list, optional) – List of properties for the images. Defaults to an empty list.
- Returns:
None
Example
>>> upload_to_gee('/tmp/images/', 'gs://mybucket', 'users/youruser/yourcollection')
- geeViz.assetManagerLib.verify_path(path)[source]¶
Verifies the validity of a path.
- Parameters:
path (str) – The path to verify.
- Returns:
None
Example
>>> verify_path('users/youruser/collection')
- geeViz.assetManagerLib.walkFolders(folder, images=[])[source]¶
Walks down folders and gets all images.
- Parameters:
folder (str) – The folder path.
images (list, optional) – List of images. Defaults to an empty list.
- Returns:
List of image paths.
- Return type:
list
Example
>>> walkFolders('users/youruser/collection')
- geeViz.assetManagerLib.walkFoldersTables(folder, tables=[])[source]¶
Walks down folders and gets all tables.
- Parameters:
folder (str) – The folder path.
tables (list, optional) – List of tables. Defaults to an empty list.
- Returns:
List of table paths.
- Return type:
list
Example
>>> walkFoldersTables('users/youruser/collection')
geeViz.cloudStorageManagerLib¶
Helpful functions for managing Google Cloud Storage (GCS) buckets and blobs
geeViz.cloudStorageManagerLib includes functions for renaming, seeing if a blob exists, and deleting blobs.
- geeViz.cloudStorageManagerLib.bucket_exists(bucket_name: str) bool [source]¶
Checks if a GCS bucket exists.
- Parameters:
bucket_name (str) – The name of the GCS bucket.
- Returns:
True if the bucket exists, False otherwise.
- Return type:
bool
Example
>>> if bucket_exists("my-bucket"): ... print("Bucket exists.") ... else: ... print("Bucket does not exist.")
- geeViz.cloudStorageManagerLib.create_bucket(bucket_name: str)[source]¶
Creates a GCS bucket.
- Parameters:
bucket_name (str) – The name of the GCS bucket to create.
- Returns:
The created bucket object.
- Return type:
google.cloud.storage.bucket.Bucket
Example
>>> bucket = create_bucket("my-new-bucket") >>> print(f"Created bucket: {bucket.name}")
- geeViz.cloudStorageManagerLib.delete_blob(bucket, filename)[source]¶
Deletes a specified file from a GCS bucket.
- Parameters:
bucket (str) – The name of the GCS bucket.
filename (str) – The name of the file to delete.
Example
>>> delete_blob("my-bucket", "file.txt") >>> print("File deleted.")
- geeViz.cloudStorageManagerLib.gcs_exists(bucket, filename)[source]¶
Checks if a specific file exists in a GCS bucket.
- Parameters:
bucket (str) – The name of the GCS bucket.
filename (str) – The name of the file to check.
- Returns:
True if the file exists, False otherwise.
- Return type:
bool
Example
>>> if gcs_exists("my-bucket", "file.txt"): ... print("File exists.") ... else: ... print("File does not exist.")
- geeViz.cloudStorageManagerLib.list_blobs(bucket_name: str) list [source]¶
Lists all blob objects in a bucket.
- Parameters:
bucket_name (str) – The name of the GCS bucket.
- Returns:
A list of blob objects in the bucket.
- Return type:
list
Example
>>> blobs = list_blobs("my-bucket") >>> for blob in blobs: ... print(blob.name)
- geeViz.cloudStorageManagerLib.list_files(bucket_name: str) list[str] [source]¶
Lists filenames in a bucket.
- Parameters:
bucket_name (str) – The name of the GCS bucket.
- Returns:
A list of filenames in the bucket.
- Return type:
list[str]
Example
>>> files = list_files("my-bucket") >>> for file in files: ... print(file)
- geeViz.cloudStorageManagerLib.rename_blobs(bucket_name, old_name, new_name)[source]¶
Renames a group of blobs in a bucket.
- Parameters:
bucket_name (str) – The name of the GCS bucket.
old_name (str) – The substring to replace in blob names.
new_name (str) – The new substring to use in blob names.
Example
>>> rename_blobs("my-bucket", "old_prefix", "new_prefix")
geeViz.gee2Pandas¶
Take data from GEE to Pandas and back
geeViz.gee2Pandas facilitates converting GEE objects to tabular formats that work well in more common packages such as Pandas.
- geeViz.gee2Pandas.dfToJSON(dbf, outJsonFilename)[source]¶
Converts a DBF file to a JSON file.
- Parameters:
dbf (str) – Path to the DBF file.
outJsonFilename (str) – Path to the output JSON file.
- Returns:
The JSON representation of the DBF file.
- Return type:
dict
Example
>>> from geeViz.gee2Pandas import dfToJSON >>> dbf_path = "data.dbf" >>> json_path = "data.json" >>> json_data = dfToJSON(dbf_path, json_path) >>> print(json_data)
- geeViz.gee2Pandas.df_to_geojson(df, properties=None, geometry_type_fieldname='geometry.type', geometry_coordinates_fieldname='geometry.coordinates')[source]¶
Converts a Pandas DataFrame to a GeoJSON object.
Assumes point location geometry. Adapted from: https://notebook.community/captainsafia/nteract/applications/desktop/example-notebooks/pandas-to-geojson
- Parameters:
df (pandas.DataFrame) – The DataFrame to convert.
properties (list, optional) – List of property column names to include. Defaults to None.
geometry_type_fieldname (str, optional) – Column name for geometry type. Defaults to “geometry.type”.
geometry_coordinates_fieldname (str, optional) – Column name for geometry coordinates. Defaults to “geometry.coordinates”.
- Returns:
The GeoJSON object.
- Return type:
dict
Example
>>> import pandas as pd >>> from geeViz.gee2Pandas import df_to_geojson >>> data = { ... "geometry.type": ["Point", "Point"], ... "geometry.coordinates": ['[-65.8491, 18.2233]', '[-66.1057, 18.4655]'], ... "name": ["Location1", "Location2"], ... } >>> df = pd.DataFrame(data) >>> geojson = df_to_geojson(df) >>> print(geojson)
- geeViz.gee2Pandas.extractPointImageValues(ee_image, pt, scale=None, crs=None, transform=None, reducer=<ee.reducer.Reducer object>, includeNonSystemProperties=False, includeSystemProperties=True)[source]¶
Extracts values from a GEE image at a specific point.
- Parameters:
ee_image (ee.Image) – The image to extract values from.
pt (ee.Geometry.Point) – The point location.
scale (float, optional) – The scale in meters for the analysis. Defaults to None.
crs (str, optional) – The coordinate reference system. Defaults to None.
transform (list, optional) – The affine transform. Defaults to None.
reducer (ee.Reducer, optional) – Reducer to apply. Defaults to ee.Reducer.first().
includeNonSystemProperties (bool, optional) – Whether to include non-system properties. Defaults to False.
includeSystemProperties (bool, optional) – Whether to include system properties. Defaults to True.
- Returns:
The extracted values.
- Return type:
ee.Dictionary
Example
>>> from geeViz.gee2Pandas import extractPointImageValues >>> img = ee.Image([1, 2, 3]) >>> pt = ee.Geometry.Point([-65.8491, 18.2233]) >>> values = extractPointImageValues(img, pt, scale=30) >>> print(values.getInfo())
- geeViz.gee2Pandas.extractPointValuesToDataFrame(ee_object, pt, scale=None, crs=None, transform=None, title=None, index=None, columns=None, bandName=None, reducer=<ee.reducer.Reducer object>, includeNonSystemProperties=False, includeSystemProperties=True)[source]¶
Extracts values from a GEE object at a specific point and converts them to a Pandas DataFrame.
- Parameters:
ee_object (ee.Image or ee.ImageCollection) – The GEE object to extract values from.
pt (ee.Geometry.Point) – The point location.
scale (float, optional) – The scale in meters for the analysis. Defaults to None.
crs (str, optional) – The coordinate reference system. Defaults to None.
transform (list, optional) – The affine transform. Defaults to None.
title (str, optional) – Title for the DataFrame. Defaults to None.
index (list, optional) – Index for the DataFrame. Defaults to None.
columns (list, optional) – Columns for the DataFrame. Defaults to None.
bandName (str, optional) – Band name for array images. Defaults to None.
reducer (ee.Reducer, optional) – Reducer to apply. Defaults to ee.Reducer.first().
includeNonSystemProperties (bool, optional) – Whether to include non-system properties. Defaults to False.
includeSystemProperties (bool, optional) – Whether to include system properties. Defaults to True.
- Returns:
The resulting DataFrame.
- Return type:
pandas.DataFrame
Example
>>> from geeViz.gee2Pandas import extractPointValuesToDataFrame >>> img = ee.Image([1, 2, 3]) >>> pt = ee.Geometry.Point([-65.8491, 18.2233]) >>> df = extractPointValuesToDataFrame(img, pt, scale=30) >>> print(df)
- geeViz.gee2Pandas.featureCollection_to_csv(featureCollection, output_csv_name, overwrite=False)[source]¶
Converts a GEE FeatureCollection to a CSV file.
If the output CSV file already exists and overwrite is False, the function skips the conversion. Otherwise, it converts the FeatureCollection to a Pandas DataFrame and writes it to a CSV file.
- Parameters:
featureCollection (ee.FeatureCollection) – The GEE FeatureCollection to convert.
output_csv_name (str) – The path to the output CSV file.
overwrite (bool, optional) – Whether to overwrite the existing file. Defaults to False.
Example
>>> from geeViz.gee2Pandas import featureCollection_to_csv >>> fc = ee.FeatureCollection("TIGER/2018/States").limit(10) >>> output_csv = "states.csv" >>> featureCollection_to_csv(fc, output_csv, overwrite=True)
- geeViz.gee2Pandas.featureCollection_to_json(featureCollection, output_json_name, overwrite=False, maxNumberOfFeatures=5000)[source]¶
Converts a Google Earth Engine (GEE) FeatureCollection to a JSON file.
If the output JSON file already exists and overwrite is False, the function reads the existing file. Otherwise, it converts the FeatureCollection to JSON and writes it to the specified file.
- Parameters:
featureCollection (ee.FeatureCollection) – The GEE FeatureCollection to convert.
output_json_name (str) – The path to the output JSON file.
overwrite (bool, optional) – Whether to overwrite the existing file. Defaults to False.
maxNumberOfFeatures (int, optional) – Maximum number of features to include. Defaults to 5000.
- Returns:
The JSON representation of the FeatureCollection.
- Return type:
dict
Example
>>> from geeViz.gee2Pandas import featureCollection_to_json >>> fc = ee.FeatureCollection("TIGER/2018/States").limit(10) >>> output_json = "states.json" >>> json_data = featureCollection_to_json(fc, output_json, overwrite=True) >>> print(json_data)
- geeViz.gee2Pandas.geeToLocalZonalStats(zones, raster, output_csv, reducer=<ee.reducer.Reducer object>, scale=None, crs=None, transform=None, tileScale=4, overwrite=False, maxNumberOfFeatures=5000)[source]¶
Computes zonal statistics in GEE and saves the results to a local CSV file.
- Parameters:
zones (ee.FeatureCollection) – The zones over which to compute statistics.
raster (ee.Image) – The raster image to analyze.
output_csv (str) – The path to the output CSV file.
reducer (ee.Reducer, optional) – The reducer to apply. Defaults to ee.Reducer.first().
scale (float, optional) – The scale in meters for the analysis. Defaults to None.
crs (str, optional) – The coordinate reference system. Defaults to None.
transform (list, optional) – The affine transform. Defaults to None.
tileScale (int, optional) – Tile scale for computation. Defaults to 4.
overwrite (bool, optional) – Whether to overwrite the existing file. Defaults to False.
maxNumberOfFeatures (int, optional) – Maximum number of features to include. Defaults to 5000.
Example
>>> from geeViz.gee2Pandas import geeToLocalZonalStats >>> zones = ee.FeatureCollection("TIGER/2018/States").limit(5) >>> raster = ee.Image("USGS/NLCD/NLCD2016").select("landcover") >>> output_csv = "zonal_stats.csv" >>> geeToLocalZonalStats(zones, raster, output_csv, scale=30, overwrite=True)
- geeViz.gee2Pandas.imageArrayPixelToDataFrame(img, pt, scale=None, crs=None, transform=None, title=None, index=None, columns=None, bandName=None, reducer=<ee.reducer.Reducer object>, arrayImage=None)[source]¶
Converts pixel values from an image array to a Pandas DataFrame.
- Parameters:
img (ee.Image) – The image to extract values from.
pt (ee.Geometry.Point) – The point location.
scale (float, optional) – The scale in meters for the analysis. Defaults to None.
crs (str, optional) – The coordinate reference system. Defaults to None.
transform (list, optional) – The affine transform. Defaults to None.
title (str, optional) – Title for the DataFrame. Defaults to None.
index (list, optional) – Index for the DataFrame. Defaults to None.
columns (list, optional) – Columns for the DataFrame. Defaults to None.
bandName (str, optional) – Band name for array images. Defaults to None.
reducer (ee.Reducer, optional) – Reducer to apply. Defaults to ee.Reducer.first().
arrayImage (bool, optional) – Whether the image is an array image. Defaults to None.
- Returns:
The resulting DataFrame.
- Return type:
pandas.DataFrame
Example
>>> from geeViz.gee2Pandas import imageArrayPixelToDataFrame >>> img = ee.Image([1, 2, 3]) >>> pt = ee.Geometry.Point([-65.8491, 18.2233]) >>> df = imageArrayPixelToDataFrame(img, pt, scale=30) >>> print(df)
- geeViz.gee2Pandas.robust_featureCollection_to_df(featureCollection, sep='___')[source]¶
Converts a GEE FeatureCollection to a Pandas DataFrame.
Handles the 5000-feature limit by slicing the FeatureCollection into manageable chunks. This function is memory-intensive and may fail for complex operations.
- Parameters:
featureCollection (ee.FeatureCollection) – The GEE FeatureCollection to convert.
sep (str, optional) – Separator for nested property names. Defaults to “___”.
- Returns:
The resulting DataFrame.
- Return type:
pandas.DataFrame
Example
>>> from geeViz.gee2Pandas import robust_featureCollection_to_df >>> fc = ee.FeatureCollection("TIGER/2018/States").limit(10) >>> df = robust_featureCollection_to_df(fc) >>> print(df.head())
- geeViz.gee2Pandas.setDFTitle(df, title)[source]¶
Sets a title for a Pandas DataFrame.
- Parameters:
df (pandas.DataFrame) – The DataFrame to modify.
title (str) – The title to set.
- Returns:
The styled DataFrame.
- Return type:
pandas.io.formats.style.Styler
Example
>>> import pandas as pd >>> from geeViz.gee2Pandas import setDFTitle >>> data = {"A": [1, 2], "B": [3, 4]} >>> df = pd.DataFrame(data) >>> styled_df = setDFTitle(df, "Sample DataFrame") >>> print(styled_df)
- geeViz.gee2Pandas.tableToFeatureCollection(table_path, properties=None, dateCol=None, groupByColumns=None, mode=None, geometry_type_fieldname='geometry.type', geometry_coordinates_fieldname='geometry.coordinates')[source]¶
Converts a table to a GEE FeatureCollection.
Supports Excel, CSV, and Pickle input table formats.
- Parameters:
table_path (str) – Path to the input table.
properties (list, optional) – List of property column names to include. Defaults to None.
dateCol (str, optional) – Column name for date. Defaults to None.
groupByColumns (list, optional) – Columns to group by. Defaults to None.
mode (str, optional) – Input table format. Defaults to None.
geometry_type_fieldname (str, optional) – Column name for geometry type. Defaults to “geometry.type”.
geometry_coordinates_fieldname (str, optional) – Column name for geometry coordinates. Defaults to “geometry.coordinates”.
- Returns:
The resulting FeatureCollection.
- Return type:
ee.FeatureCollection
Example
>>> from geeViz.gee2Pandas import tableToFeatureCollection >>> table_path = "locations.csv" >>> fc = tableToFeatureCollection(table_path, mode="csv") >>> print(fc.getInfo())
geeViz.foliumView¶
View GEE objects using Folium.
geeViz.foliumView facilitates viewing GEE objects in Folium. Layers can be added to the map using Map.addLayer and then viewed using the Map.view method.
Example
from geeViz.foliumView import foliumMapper
# Initialize the mapper mapper = foliumMapper()
# Set the map center mapper.setCenter(-122.4194, 37.7749, 10)
# Add a layer (example assumes you have an ee.Image object) mapper.addLayer(ee.Image(“LANDSAT/LC08/C01/T1_SR/LC08_044034_20140318”),
{“bands”: [“B4”, “B3”, “B2”], “min”: 0, “max”: 3000}, “Landsat Image”)
# View the map mapper.view()
- geeViz.foliumView.add_ee_layer(self, ee_object, vis_params, name, visible)[source]¶
Adds an Earth Engine object as a layer to a Folium map.
- Parameters:
ee_object (ee.Image | ee.ImageCollection | ee.FeatureCollection | ee.Feature | ee.Geometry) – The Earth Engine object to add.
vis_params (dict) – Visualization parameters for the layer.
name (str) – Name of the layer.
visible (bool) – Whether the layer is visible by default.
Example
>>> map = folium.Map(location=[37.7749, -122.4194], zoom_start=10) >>> map.add_ee_layer(ee.Image("LANDSAT/LC08/C01/T1_SR/LC08_044034_20140318"), ... {"bands": ["B4", "B3", "B2"], "min": 0, "max": 3000}, ... "Landsat Image", True)
- class geeViz.foliumView.foliumMapper(port=8001)[source]¶
A class for managing and visualizing Earth Engine objects using Folium.
Example
>>> mapper = foliumMapper() >>> mapper.setCenter(-122.4194, 37.7749, 10) >>> mapper.addLayer(ee.Image("LANDSAT/LC08/C01/T1_SR/LC08_044034_20140318"), ... {"bands": ["B4", "B3", "B2"], "min": 0, "max": 3000}, ... "Landsat Image") >>> mapper.view()
- addLayer(eeObject, viz={}, name=None, visible=True)[source]¶
Adds a layer to the map.
- Parameters:
eeObject – The Earth Engine object to add.
viz (dict) – Visualization parameters.
name (str, optional) – Name of the layer. Default is None.
visible (bool) – Whether the layer is visible by default.
Example
>>> mapper.addLayer(ee.Image("LANDSAT/LC08/C01/T1_SR/LC08_044034_20140318"), ... {"bands": ["B4", "B3", "B2"], "min": 0, "max": 3000}, ... "Landsat Image")
- centerObject(ee_object)[source]¶
Centers the map on an Earth Engine object.
- Parameters:
ee_object (ee.FeatureCollection | ee.Feature | ee.Geometry) – The object to center on.
Example
>>> mapper.centerObject(ee.FeatureCollection("FAO/GAUL/2015/level1"))
- setCenter(lon, lat, zoom=None)[source]¶
Sets the center of the map.
- Parameters:
lon (float) – Longitude of the center.
lat (float) – Latitude of the center.
zoom (int, optional) – Zoom level. Default is None.
Example
>>> mapper.setCenter(-122.4194, 37.7749, 10)
- setMapArg(key, value)[source]¶
Sets a map argument.
- Parameters:
key (str) – The argument key.
value – The argument value.
Example
>>> mapper.setMapArg("zoom_start", 10)
- turnOffAllLayers()[source]¶
Turns off visibility for all layers.
Example
>>> mapper.turnOffAllLayers()
- turnOnInspector()[source]¶
Prints a message indicating that only GEE map objects are supported.
Example
>>> mapper.turnOnInspector()
- view(open_browser=True, open_iframe=False, iframe_height=525)[source]¶
Displays the map.
- Parameters:
open_browser (bool) – Whether to open the map in a browser. Default is True.
open_iframe (bool) – Whether to display the map in an iframe. Default is False.
iframe_height (int) – Height of the iframe. Default is 525.
Example
>>> mapper.view()
geeViz.phEEnoViz¶
Visualize the spectral seasonality of an area to facilitate composting methods development
geeViz.phEEnoViz facilitates the creation of plots to show the seasonality of an area. This is a good tool for deciding what date ranges to use for compositing.
- geeViz.phEEnoViz.chartTimeSeriesDistributions(tables, output_dir, output_base_name, n_bins=40, min_pctl=0.05, max_pctl=99.95, background_color='#D6D1CA', font_color='#1B1716', overwrite=False, howManyHarmonics=3, showChart=False, annotate_harmonic_peaks=True)[source]¶
Plots time series histograms for each date in the given tables.
- Parameters:
tables (list) – List of CSV file paths.
output_dir (str) – Output directory for charts.
output_base_name (str) – Base name for output charts.
n_bins (int, optional) – Number of histogram bins. Defaults to 40.
min_pctl (float, optional) – Minimum percentile for value clipping. Defaults to 0.05.
max_pctl (float, optional) – Maximum percentile for value clipping. Defaults to 99.95.
background_color (str, optional) – Background color for plots. Defaults to “#D6D1CA”.
font_color (str, optional) – Font color for plots. Defaults to “#1B1716”.
overwrite (bool, optional) – Overwrite existing charts. Defaults to False.
howManyHarmonics (int, optional) – Number of harmonics for regression. Defaults to 3.
showChart (bool, optional) – Show chart interactively. Defaults to False.
annotate_harmonic_peaks (bool, optional) – Annotate harmonic peaks. Defaults to True.
Example
>>> chartTimeSeriesDistributions(['table_NDVI.csv'], './charts', 'study_NDVI')
- geeViz.phEEnoViz.check_dir(dir)[source]¶
Ensures that a directory exists, creating it if necessary.
- Parameters:
dir (str) – The directory path.
Example
>>> check_dir('/tmp/mydir')
- geeViz.phEEnoViz.convert_to_csv(output_table_name)[source]¶
Converts a JSON GEE table into CSV files, one per band.
- Parameters:
output_table_name (str) – Path to the JSON table.
Example
>>> convert_to_csv('output.json')
- geeViz.phEEnoViz.getTableWrapper(image, fc, outputName, reducer=<ee.reducer.Reducer object>, scale=30, crs='EPSG:4326', transform=None, tryNumber=1, maxTries=15)[source]¶
Extracts a JSON table of zonal statistics from an image and exports it.
- Parameters:
image (ee.Image) – The image to reduce.
fc (ee.FeatureCollection) – The feature collection for zonal stats.
outputName (str) – Output filename for the JSON table.
reducer (ee.Reducer, optional) – Reducer to use. Defaults to ee.Reducer.first().
scale (int, optional) – Scale in meters. Defaults to 30.
crs (str, optional) – Coordinate reference system. Defaults to “EPSG:4326”.
transform (optional) – Transform parameter. Defaults to None.
tryNumber (int, optional) – Current try number. Defaults to 1.
maxTries (int, optional) – Maximum number of tries. Defaults to 15.
Example
>>> getTableWrapper(image, fc, 'output.json')
- geeViz.phEEnoViz.getTimeSeriesSample(startYear, endYear, startJulian, endJulian, compositePeriod, exportBands, studyArea, nSamples, output_table_name, showGEEViz, maskSnow=False, programs=['Landsat', 'Sentinel2'])[source]¶
Samples locations for a given area and exports time series data.
- Parameters:
startYear (int) – Start year.
endYear (int) – End year.
startJulian (int) – Start Julian day.
endJulian (int) – End Julian day.
compositePeriod (int) – Composite period in days.
exportBands (list) – List of bands to export.
studyArea (ee.Geometry or ee.FeatureCollection) – Study area.
nSamples (int) – Number of samples.
output_table_name (str) – Output table name.
showGEEViz (bool) – Whether to show GEEViz visualization.
maskSnow (bool, optional) – Whether to mask snow. Defaults to False.
programs (list, optional) – List of programs. Defaults to [“Landsat”, “Sentinel2”].
Example
>>> getTimeSeriesSample(2019, 2020, 1, 365, 16, ['NDVI'], studyArea, 100, 'output.json', True)