API Reference

This page provides detailed documentation for all geeViz modules, classes, and functions. The API is organized by module category for easy navigation.

Visualization Modules

geeViz.geeView

The primary interactive map viewer for Earth Engine datasets.

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.RGB_to_hex(RGB: list[int]) str[source]

[255,255,255] -> “#FFFFFF”

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]

Bases: object

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._get_state().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._get_state().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()
setQueryWindowMode(mode)[source]
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.geeView.setProject(id)[source]

Sets the project id of an instance of ee

Parameters:

id (str) – Google Cloud Platform project id to use

geeViz.geeView.simpleSetProject(overwrite=False, verbose=False)[source]

Tries to find the current Google Cloud Platform project id and set it

Args: overwrite (bool, optional): Whether or not to overwrite a cached project ID file

geeViz.foliumView

Alternative Folium-based map viewer for lightweight visualizations.

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]

Bases: object

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"))
clearMap()[source]

Clears all layers and resets the map state.

Example

>>> mapper.clearMap()
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()
turnOnAllLayers()[source]

Turns on visibility for all layers.

Example

>>> mapper.turnOnAllLayers()
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()

Image Processing Modules

geeViz.getImagesLib

Comprehensive wrapper functions for accessing and processing satellite imagery from multiple sensors.

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.HoCalcAlgorithm1(image)[source]

Apply the Ho et al. algal bloom detection algorithm to a satellite image.

Implements Algorithm 1 from Wang & Shi (2007) for detecting algal blooms in water bodies using NIR-SWIR atmospheric correction. Adds a hue-based greenness filter to distinguish blooms from suspended sediment.

Reference:

Wang, M., & Shi, W. (2007). The NIR-SWIR combined atmospheric correction approach for MODIS ocean color data processing. Optics Express, 15(24), 15722-15733.

Parameters:

image (ee.Image) – Input image with red, green, blue, nir, and swir1 bands.

Returns:

The input image with additional bands: H (hue from

HoCalcGreenness), bloom1 (bloom intensity), and bloom1_mask (binary bloom classification).

Return type:

ee.Image

Examples

>>> import geeViz.getImagesLib as gil
>>> ee = gil.ee
>>> img = ee.Image("LANDSAT/LC09/C02/T1_TOA/LC09_017031_20220601")
>>> bands = img.select(["B4", "B3", "B2", "B5", "B6"], ["red", "green", "blue", "nir", "swir1"])
>>> result = gil.HoCalcAlgorithm1(bands)
>>> print(result.bandNames().getInfo())
geeViz.getImagesLib.HoCalcAlgorithm2(image: Image) Image[source]

Applies an algal bloom detection algorithm to an image.

Computes a green/blue ratio (‘bloom2’) and Normalized Difference Green Index (‘NDGI’) based on Matthews (2011), DOI: 10.1080/01431161.2010.512947.

Parameters:

image (ee.Image) – Input image with ‘green’ and ‘blue’ bands.

Returns:

The input image with added ‘bloom2’ (green/blue ratio)

and ‘NDGI’ (normalized difference of green and blue) bands.

Return type:

ee.Image

Examples

>>> import ee
>>> ee.Initialize()
>>> img = ee.Image('LANDSAT/LC08/C02/T1_L2/LC08_044034_20200601')
>>> bloom_img = HoCalcAlgorithm2(img)
>>> print(bloom_img.select(['bloom2', 'NDGI']).bandNames().getInfo())
geeViz.getImagesLib.HoCalcGreenness(img)[source]

Compute the hue component for algal bloom greenness detection.

Implements a hue calculation from RGB bands to help distinguish algal bloom pixels from suspended sediment. Pixels with hue below 1.6 are more likely to be algal blooms. Based on the Jeff Ho method for water quality analysis.

Parameters:

img (ee.Image) – Input image with red, green, and blue bands.

Returns:

Single-band image named H containing the hue values.

Return type:

ee.Image

Examples

>>> import geeViz.getImagesLib as gil
>>> ee = gil.ee
>>> img = ee.Image("LANDSAT/LC09/C02/T1_TOA/LC09_017031_20220601")
>>> hue = gil.HoCalcGreenness(img.select(["B4", "B3", "B2"], ["red", "green", "blue"]))
>>> print(hue.bandNames().getInfo())
['H']
geeViz.getImagesLib.RefinedLee(img: Image) Image[source]

Applies the Refined Lee speckle filter to a Sentinel-1 image.

Implements the Refined Lee filter as coded in SNAP 3.0 S1TBX. Uses directional statistics in 7x7 neighborhoods to reduce speckle noise while preserving edges. The input image must be in natural (linear) units, not dB.

Parameters:

img (ee.Image) – The input Sentinel-1 image in natural (linear power) units. Use toNatural() to convert from dB first.

Returns:

The speckle-filtered image with a single band named "sum".

Return type:

ee.Image

Examples

>>> import geeViz.getImagesLib as gil
>>> ee = gil.ee
>>> s1 = ee.ImageCollection("COPERNICUS/S1_GRD").first().select("VV")
>>> filtered = gil.RefinedLee(gil.toNatural(s1))
geeViz.getImagesLib.addAbsDiff(inCollection, qualityBand, percentile, sign)[source]

Add a band with the absolute difference from a percentile-based quality target.

Computes the specified percentile of a quality band across the collection, then adds a delta band to each image representing the absolute difference from that percentile value, multiplied by the given sign.

Parameters:
  • inCollection (ee.ImageCollection) – Input image collection.

  • qualityBand (str) – Name of the band to compute the percentile on.

  • percentile (int | float) – Percentile value (0–100) to use as the target quality.

  • sign (int) – Multiplier for the delta band, typically -1 to invert for use with qualityMosaic (which selects the max).

Returns:

Collection with an added delta band on each image.

Return type:

ee.ImageCollection

Examples

>>> import geeViz.getImagesLib as gil
>>> ee = gil.ee
>>> collection = ee.ImageCollection("LANDSAT/LC09/C02/T1_L2").limit(10)
>>> withDelta = gil.addAbsDiff(collection, "SR_B4", 50, -1)
>>> print(ee.Image(withDelta.first()).bandNames().getInfo())
geeViz.getImagesLib.addDateBand(img: Image, maskTime: bool = False) Image[source]

Adds a "year" band containing the fractional year (year + day-of-year fraction).

The band value is computed as year + fraction_of_year (e.g., 2020.5 for approximately July 2, 2020).

Parameters:
  • img (ee.Image) – The input Earth Engine image with a "system:time_start" property.

  • maskTime (bool, optional) – If True, masks the date band to match the first band’s mask of the input image. Defaults to False.

Returns:

The input image with an added "year" band (float).

Return type:

ee.Image

Examples

>>> img = ee.Image("LANDSAT/LC08/C02/T1_L2/LC08_044034_20200701")
>>> with_date = addDateBand(img)
>>> with_masked_date = addDateBand(img, maskTime=True)
geeViz.getImagesLib.addFullYearJulianDayBand(img: Image) Image[source]

Adds a "yearJulian" band encoding the full 4-digit year and Julian day (YYYYDD).

The band value is a number in the format YYYYDD, where YYYY is the 4-digit year and DD is the day of the year. For example, July 1, 2020 yields 2020182.

Parameters:

img (ee.Image) – The input Earth Engine image with a "system:time_start" property.

Returns:

The input image with an added "yearJulian" band (int64, cast to float).

Return type:

ee.Image

Examples

>>> img = ee.Image("LANDSAT/LC08/C02/T1_L2/LC08_044034_20200701")
>>> with_full_yj = addFullYearJulianDayBand(img)
geeViz.getImagesLib.addIndices(img: Image) Image[source]

Adds a comprehensive set of spectral indices to an image.

Computes all pairwise normalized differences (NDSV) across blue, green, red, nir, swir1, and swir2 bands. Also adds band ratios, EVI, SAVI, and IBI.

Parameters:

img (ee.Image) – Input image with bands named ‘blue’, ‘green’, ‘red’, ‘nir’, ‘swir1’, and ‘swir2’.

Returns:

The input image with additional bands including ND_*

(normalized differences), R_* (ratios), EVI, SAVI, and IBI.

Return type:

ee.Image

Examples

>>> import ee
>>> ee.Initialize()
>>> img = ee.Image('LANDSAT/LC08/C02/T1_L2/LC08_044034_20200601')
>>> img_with_indices = addIndices(img)
>>> print(img_with_indices.bandNames().getInfo())
geeViz.getImagesLib.addJulianDayBand(img: Image) Image[source]

Adds a "julianDay" band containing the day of the year (1–366).

Parameters:

img (ee.Image) – The input Earth Engine image with a "system:time_start" property.

Returns:

The input image with an added "julianDay" band (float).

Return type:

ee.Image

Examples

>>> img = ee.Image("LANDSAT/LC08/C02/T1_L2/LC08_044034_20200701")
>>> with_julian = addJulianDayBand(img)
geeViz.getImagesLib.addSAVIandEVI(img: Image) Image[source]

Adds SAVI, EVI, and NIRv vegetation indices to an image.

Computes the Enhanced Vegetation Index (EVI), Soil Adjusted Vegetation Index (SAVI with L=0.5), and Near-Infrared Reflectance of Vegetation (NIRv).

Parameters:

img (ee.Image) – Input image with bands named ‘nir’, ‘red’, ‘blue’, and ‘NDVI’. The NDVI band is required for NIRv computation.

Returns:

The input image with added ‘EVI’, ‘SAVI’, and ‘NIRv’ bands.

Return type:

ee.Image

Examples

>>> import ee
>>> ee.Initialize()
>>> img = simpleAddIndices(ee.Image('LANDSAT/LC08/C02/T1_L2/LC08_044034_20200601'))
>>> img_with_vi = addSAVIandEVI(img)
>>> print(img_with_vi.select(['EVI', 'SAVI', 'NIRv']).bandNames().getInfo())
geeViz.getImagesLib.addSensorBand(img: Image, whichProgram: str, toaOrSR: str) Image[source]

Adds a band encoding the satellite sensor as a numeric value.

Maps satellite names (e.g., LANDSAT_8, Sentinel-2A) to integer codes (e.g., 8, 21) and adds the result as a "sensor" band. Also sets the "sensor" property on the image.

Parameters:
  • img (ee.Image) – The input Earth Engine image with appropriate spacecraft metadata.

  • whichProgram (str) – The satellite program. One of "C1_landsat", "C2_landsat", or "sentinel2".

  • toaOrSR (str) – The processing level, "TOA" or "SR".

Returns:

The input image with an added "sensor" band (byte type) and "sensor" property.

Return type:

ee.Image

Examples

>>> img = ee.Image("LANDSAT/LC08/C02/T1_L2/LC08_044034_20200101")
>>> with_sensor = addSensorBand(img, "C2_landsat", "SR")
geeViz.getImagesLib.addSoilIndices(img: Image) Image[source]

Adds soil-related spectral indices to an image.

Computes NDCI (Normalized Difference Chlorophyll Index), NDII (Normalized Difference Infrared Index), NDFI (Normalized Difference Fraction Index), BSI (Bare Soil Index), and HI (SWIR1/SWIR2 ratio).

Parameters:

img (ee.Image) – Input image with bands named ‘blue’, ‘red’, ‘green’, ‘nir’, ‘swir1’, and ‘swir2’.

Returns:

The input image with added ‘NDCI’, ‘NDII’, ‘NDFI’, ‘BSI’,

and ‘HI’ bands.

Return type:

ee.Image

Examples

>>> import ee
>>> ee.Initialize()
>>> img = ee.Image('LANDSAT/LC08/C02/T1_L2/LC08_044034_20200601')
>>> img = addSoilIndices(img)
>>> print(img.select(['BSI', 'HI']).bandNames().getInfo())
geeViz.getImagesLib.addTCAngles(image: Image) Image[source]

Adds Tasseled Cap angles and distances to an image.

Computes pairwise angles (atan2) and Euclidean distances (hypot) between the brightness, greenness, and wetness TC components. Angles are divided by pi to normalize to the range [-1, 1].

Parameters:

image (ee.Image) – Input image with ‘brightness’, ‘greenness’, and ‘wetness’ bands (e.g., output of getTasseledCap).

Returns:

The input image with added bands: ‘tcAngleBG’, ‘tcAngleGW’,

’tcAngleBW’, ‘tcDistBG’, ‘tcDistGW’, ‘tcDistBW’.

Return type:

ee.Image

Examples

>>> import ee
>>> ee.Initialize()
>>> img = getTasseledCap(ee.Image('LANDSAT/LC08/C02/T1_TOA/LC08_044034_20200601'))
>>> img = addTCAngles(img)
>>> print(img.select(['tcAngleBG', 'tcDistBG']).bandNames().getInfo())
geeViz.getImagesLib.addYearBand(img: Image) Image[source]

Adds a "year" band containing the integer year of the image acquisition.

Parameters:

img (ee.Image) – The input Earth Engine image with a "system:time_start" property.

Returns:

The input image with an added "year" band (float, e.g., 2020.0).

Return type:

ee.Image

Examples

>>> img = ee.Image("LANDSAT/LC08/C02/T1_L2/LC08_044034_20200701")
>>> with_year = addYearBand(img)
geeViz.getImagesLib.addYearFractionBand(img: Image) Image[source]

Adds a "year" band containing only the fractional part of the year (0 to 1).

Unlike addDateBand(), this does not include the integer year component. A value of 0.5 corresponds to approximately July 2.

Parameters:

img (ee.Image) – The input Earth Engine image with a "system:time_start" property.

Returns:

The input image with an added "year" band (float, range 0–1).

Return type:

ee.Image

Examples

>>> img = ee.Image("LANDSAT/LC08/C02/T1_L2/LC08_044034_20200701")
>>> with_frac = addYearFractionBand(img)
geeViz.getImagesLib.addYearJulianDayBand(img: Image) Image[source]

Adds a "yearJulian" band encoding the 2-digit year and Julian day (YYDD).

The band value is a number in the format YYDD, where YY is the 2-digit year and DD is the day of the year. For example, January 15, 2020 yields 2015.

Parameters:

img (ee.Image) – The input Earth Engine image with a "system:time_start" property.

Returns:

The input image with an added "yearJulian" band (float).

Return type:

ee.Image

Examples

>>> img = ee.Image("LANDSAT/LC08/C02/T1_L2/LC08_044034_20200115")
>>> with_yj = addYearJulianDayBand(img)
geeViz.getImagesLib.addYearYearFractionBand(img: Image) Image[source]

Adds a "year" band containing the full fractional year (year + fraction).

Functionally equivalent to addDateBand() with maskTime=False, but computed by explicitly adding the integer year and fractional year components.

Parameters:

img (ee.Image) – The input Earth Engine image with a "system:time_start" property.

Returns:

The input image with an added "year" band (float, e.g., 2020.5).

Return type:

ee.Image

Examples

>>> img = ee.Image("LANDSAT/LC08/C02/T1_L2/LC08_044034_20200701")
>>> with_year_frac = addYearYearFractionBand(img)
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 as bands to an image.

Reads sun angle metadata properties from the image, converts degrees to radians, and adds them as constant-value ‘zenith’ and ‘azimuth’ bands. For TOA images, zenith is derived from SUN_ELEVATION (90 - elevation); for SR images it is read directly from SOLAR_ZENITH_ANGLE.

Parameters:
  • img (ee.Image) – Input Landsat image with sun angle metadata properties.

  • toaOrSR (str) – Either 'TOA' or 'SR', indicating the processing level and which metadata properties to use.

  • zenithDict (dict, optional) – Mapping from toaOrSR key to the zenith metadata property name. Defaults to {'TOA': 'SUN_ELEVATION', 'SR': 'SOLAR_ZENITH_ANGLE'}.

  • azimuthDict (dict, optional) – Mapping from toaOrSR key to the azimuth metadata property name. Defaults to {'TOA': 'SUN_AZIMUTH', 'SR': 'SOLAR_AZIMUTH_ANGLE'}.

Returns:

The input image with added ‘zenith’ and ‘azimuth’ bands

in radians.

Return type:

ee.Image

Examples

>>> import ee
>>> ee.Initialize()
>>> img = ee.Image('LANDSAT/LC08/C02/T1_TOA/LC08_044034_20200601')
>>> img = addZenithAzimuth(img, 'TOA')
>>> print(img.select(['zenith', 'azimuth']).bandNames().getInfo())
geeViz.getImagesLib.applyBitMask(img: Image, bit: int, bitMaskBandName: str = 'QA_PIXEL') Image[source]

Masks pixels where a specific bit is set in a QA bitmask band.

Parameters:
  • img (ee.Image) – The input image containing a QA bitmask band.

  • bit (int) – The bit position (0-indexed) to test. Pixels with this bit set to 1 will be masked out.

  • bitMaskBandName (str, optional) – The name of the QA bitmask band. Defaults to "QA_PIXEL".

Returns:

The image with pixels masked where the specified bit is set.

Return type:

ee.Image

Examples

>>> import geeViz.getImagesLib as gil
>>> ee = gil.ee
>>> img = ee.Image("LANDSAT/LC08/C02/T1_L2/LC08_044034_20210508")
>>> cloud_masked = gil.applyBitMask(img, 3)  # Bit 3 = cloud in C2
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 and masks cloudy pixels.

Computes per-pixel cloud scores, optionally subtracts a percentile-based offset to reduce commission errors, then masks pixels exceeding the threshold.

Parameters:
  • collection (ee.ImageCollection) – The input image collection.

  • cloudScoreFunction (Callable[[ee.Image], ee.Image]) – A function that takes an image and returns a single-band cloud score image.

  • cloudScoreThresh (float, optional) – Cloud score threshold for masking. Defaults to 20.

  • cloudScorePctl (float, optional) – Percentile for computing the cloud score offset. Defaults to 10.

  • contractPixels (float, optional) – Erosion kernel size in pixels. Defaults to 1.5.

  • dilatePixels (float, optional) – Dilation kernel size in pixels. Defaults to 3.5.

  • performCloudScoreOffset (bool, optional) – Whether to subtract a per-pixel offset based on the time series. Defaults to True.

  • preComputedCloudScoreOffset (ee.Image | None, optional) – A pre-computed cloud score offset image. If None, computed from the collection. Defaults to None.

Returns:

The image collection with cloudy pixels masked out.

Return type:

ee.ImageCollection

Examples

>>> import geeViz.getImagesLib as gil
>>> ee = gil.ee
>>> studyArea = gil.testAreas["CA"]
>>> ls = gil.getLandsat(studyArea, "2023-06-01", "2023-09-01", 152, 244)
>>> masked = gil.applyCloudScoreAlgorithm(ls, gil.landsatCloudScore)
geeViz.getImagesLib.applyScaleFactors(image, landsatCollectionVersion)[source]

Rescales Landsat reflectance bands to 0-1 and thermal bands to Kelvin.

Applies collection-specific scale factors and offsets to optical and thermal bands. Adapted from the method provided by Google for rescaling Collection 2.

Parameters:
  • image (ee.Image) – The input Landsat image with common band names (blue, green, red, nir, swir1, swir2, temp).

  • landsatCollectionVersion (str) – The Landsat collection version, either "C1" or "C2".

Returns:

The image with optical bands scaled to 0-1 reflectance and the thermal band scaled to Kelvin.

Return type:

ee.Image

Examples

>>> import geeViz.getImagesLib as gil
>>> ee = gil.ee
>>> img = ee.Image("LANDSAT/LC08/C02/T1_L2/LC08_044034_20210508")
>>> img = img.select(["SR_B2","SR_B3","SR_B4","SR_B5","SR_B6","ST_B10","SR_B7"],
...                  ["blue","green","red","nir","swir1","temp","swir2"])
>>> scaled = gil.applyScaleFactors(img, "C2")
geeViz.getImagesLib.cFmask(img: Image, fmaskClass: str, bitMaskBandName: str = 'QA_PIXEL') Image[source]

Applies the CFMask algorithm to mask a specific class in a Landsat image.

Supports masking clouds, cloud shadows, snow, and confidence-level cloud classes using the QA_PIXEL bitmask band.

Parameters:
  • img (ee.Image) – The input Landsat image containing a QA bitmask band.

  • fmaskClass (str) – The class to mask. Options: "cloud", "shadow", "snow", "high_confidence_cloud", "med_confidence_cloud".

  • bitMaskBandName (str, optional) – The name of the QA bitmask band. Defaults to "QA_PIXEL".

Returns:

The image with the specified class masked out.

Return type:

ee.Image

Examples

>>> import geeViz.getImagesLib as gil
>>> ee = gil.ee
>>> studyArea = gil.testAreas["CA"]
>>> ls = gil.getLandsat(studyArea, "2023-06-01", "2023-09-01", 152, 244)
>>> cloud_masked = ls.map(lambda img: gil.cFmask(img, "cloud"))
geeViz.getImagesLib.cFmaskCloud(img: Image, landsatCollectionVersion: str, bitMaskBandName: str = 'QA_PIXEL') Image[source]

Applies the CFMask cloud mask to a Landsat image.

Convenience wrapper around applyBitMask that uses the correct cloud bit position for the specified Landsat collection version.

Parameters:
  • img (ee.Image) – The input Landsat image containing a QA bitmask band.

  • landsatCollectionVersion (str) – The Landsat collection version ("C1" or "C2").

  • bitMaskBandName (str, optional) – The name of the QA bitmask band. Defaults to "QA_PIXEL".

Returns:

The image with cloud pixels masked out.

Return type:

ee.Image

Examples

>>> import geeViz.getImagesLib as gil
>>> ee = gil.ee
>>> studyArea = gil.testAreas["CA"]
>>> ls = gil.getLandsat(studyArea, "2023-06-01", "2023-09-01", 152, 244)
>>> cloud_free = ls.map(lambda img: gil.cFmaskCloud(img, "C2"))
geeViz.getImagesLib.cFmaskCloudShadow(img: Image, landsatCollectionVersion: str, bitMaskBandName: str = 'QA_PIXEL') Image[source]

Applies the CFMask cloud shadow mask to a Landsat image.

Convenience wrapper around applyBitMask that uses the correct shadow bit position for the specified Landsat collection version.

Parameters:
  • img (ee.Image) – The input Landsat image containing a QA bitmask band.

  • landsatCollectionVersion (str) – The Landsat collection version ("C1" or "C2").

  • bitMaskBandName (str, optional) – The name of the QA bitmask band. Defaults to "QA_PIXEL".

Returns:

The image with cloud shadow pixels masked out.

Return type:

ee.Image

Examples

>>> import geeViz.getImagesLib as gil
>>> ee = gil.ee
>>> studyArea = gil.testAreas["CA"]
>>> ls = gil.getLandsat(studyArea, "2023-06-01", "2023-09-01", 152, 244)
>>> shadow_free = ls.map(lambda img: gil.cFmaskCloudShadow(img, "C2"))
geeViz.getImagesLib.coRegisterCollection(images, referenceBands=['nir'])[source]

Co-register all images in a collection to the first image.

Uses ee.Image.displacement and ee.Image.displace to align every image to the first image in the collection based on the specified reference bands.

Parameters:
  • images (ee.ImageCollection) – Collection of images to co-register.

  • referenceBands (list[str]) – Band names used for displacement matching. Defaults to ["nir"].

Returns:

Co-registered image collection where the first image is unchanged and all subsequent images are displaced to align with it.

Return type:

ee.ImageCollection

Example

>>> import geeViz.getImagesLib as gil
>>> import ee
>>> imgs = ee.ImageCollection('COPERNICUS/S2_SR_HARMONIZED') \
...     .filterBounds(ee.Geometry.Point([-122.0, 37.0])) \
...     .limit(3)
>>> registered = gil.coRegisterCollection(imgs)
geeViz.getImagesLib.coRegisterGroups(imgs, fieldName='SENSING_ORBIT_NUMBER', fieldIsNumeric=True)[source]

Co-register images within groups defined by a metadata field.

Splits the collection by unique values of fieldName, co-registers each group independently using coRegisterCollection, and merges the results back into a single collection.

Parameters:
  • imgs (ee.ImageCollection) – Collection of images to co-register.

  • fieldName (str) – Metadata property to group by. Defaults to "SENSING_ORBIT_NUMBER".

  • fieldIsNumeric (bool) – Whether the field values are numeric (parsed with ee.Number.parse). Defaults to True.

Returns:

Co-registered image collection with images aligned within each group.

Return type:

ee.ImageCollection

Example

>>> import geeViz.getImagesLib as gil
>>> import ee
>>> s2 = ee.ImageCollection('COPERNICUS/S2_SR_HARMONIZED') \
...     .filterBounds(ee.Geometry.Point([-122.0, 37.0])) \
...     .filterDate('2023-06-01', '2023-06-30')
>>> registered = gil.coRegisterGroups(s2)
geeViz.getImagesLib.collectionToImage(collection: ImageCollection) Image[source]

Converts an image collection to a single multiband image.

Deprecated since version Use: ee.ImageCollection.toBands() instead, which is more efficient.

Iterates over the collection and stacks all bands into a single image.

Parameters:

collection (ee.ImageCollection) – The input Earth Engine image collection.

Returns:

A multiband image containing all bands from all images in the collection.

Return type:

ee.Image

Examples

>>> col = ee.ImageCollection("LANDSAT/LC08/C02/T1_L2").limit(3)
>>> stacked = collectionToImage(col)
geeViz.getImagesLib.compositeDates(images: ImageCollection, composite: Image, bandNames: list = None) Image[source]

Finds the acquisition dates corresponding to each band in a composite image.

Works on composites computed with methods that may include different dates across different bands (e.g., median). For medoid composites, only a single band needs to be passed through. A known limitation is that if the same pixel value occurs on two different dates, only one date will be selected.

Parameters:
  • images (ee.ImageCollection) – The original image collection used to create the composite.

  • composite (ee.Image) – The composite image whose per-band dates are to be found.

  • bandNames (list[str] or ee.List, optional) – Band names to consider. If None, uses all bands from the first image in the collection. Defaults to None.

Returns:

A multiband image where each band contains the date (as YYYYDD float) of the source image that contributed to that band of the composite.

Return type:

ee.Image

Examples

>>> col = ee.ImageCollection("LANDSAT/LC08/C02/T1_L2").filterDate("2020-06-01", "2020-09-01")
>>> composite = col.median()
>>> dates = compositeDates(col, composite, ["SR_B4", "SR_B5"])
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 annual composites from an image collection over a year range.

Generates one composite per year between startYear and endYear, filtering by Julian day window. Supports multi-year time buffering with weighted averaging and various compositing methods.

Parameters:
  • ls (ee.ImageCollection) – Input image collection to composite.

  • startYear (int) – First year to produce a composite for.

  • endYear (int) – Last year to produce a composite for (inclusive).

  • startJulian (int) – Start day of year for the compositing window (1-365).

  • endJulian (int) – End day of year for the compositing window (1-365). Can be less than startJulian for cross-year windows.

  • timebuffer (int, optional) – Number of years on each side to include in a weighted moving window. Defaults to 0.

  • weights (list, optional) – Weights for the moving window years. Length should be 2 * timebuffer + 1. Defaults to [1].

  • compositingMethod (str | None, optional) – Method name, e.g., 'median' or 'medoid'. Defaults to None.

  • compositingReducer (ee.Reducer | None, optional) – Custom reducer to use instead of a named method. Defaults to None.

Returns:

Collection of annual composite images, each tagged

with compositing metadata properties.

Return type:

ee.ImageCollection

Examples

>>> import geeViz.getImagesLib as gil
>>> ee = gil.ee
>>> area = ee.Geometry.Point([-105.5, 40.0]).buffer(5000)
>>> composites = compositeTimeSeries(
...     gil.getProcessedLandsatScenes(area, 2020, 2022, 152, 273),
...     2020, 2022, 152, 273)
geeViz.getImagesLib.customQualityMosaic(inCollection, qualityBand, percentile)[source]

Create a quality mosaic using a specified percentile rather than the max.

Wraps addAbsDiff and ee.ImageCollection.qualityMosaic to select pixels closest to the given percentile of a quality band, rather than always selecting the maximum.

Parameters:
  • inCollection (ee.ImageCollection) – Input image collection to mosaic.

  • qualityBand (str) – Name of the band to use for quality ranking.

  • percentile (int | float) – Target percentile (0–100). The pixel closest to this percentile value of qualityBand is selected.

Returns:

Mosaic image where each pixel is chosen from the image whose

quality band value is closest to the specified percentile.

Return type:

ee.Image

Examples

>>> import geeViz.getImagesLib as gil
>>> ee = gil.ee
>>> collection = ee.ImageCollection("LANDSAT/LC09/C02/T1_L2").limit(20)
>>> mosaic = gil.customQualityMosaic(collection, "SR_B4", 50)
>>> print(mosaic.bandNames().getInfo())
geeViz.getImagesLib.dailyMosaics(imgs: ImageCollection) ImageCollection[source]

Creates daily mosaics from an image collection grouped by date and orbit.

Groups images by acquisition date and Sentinel-2 orbit number, then mosaics them to remove redundant observations in MGRS tile overlap areas.

Parameters:

imgs (ee.ImageCollection) – The input Earth Engine image collection. Must contain the SENSING_ORBIT_NUMBER property (Sentinel-2).

Returns:

A collection of daily mosaic images, one per unique date-orbit combination.

Return type:

ee.ImageCollection

Examples

>>> import geeViz.getImagesLib as gil
>>> ee = gil.ee
>>> s2 = ee.ImageCollection("COPERNICUS/S2_HARMONIZED").filterDate("2023-06-01", "2023-06-10")
>>> daily = gil.dailyMosaics(s2)
geeViz.getImagesLib.defringeLandsat(img: Image) Image[source]

Defringes a Landsat 7 image by masking fringe pixels with insufficient valid neighbors.

Parameters:

img (ee.Image) – The input Landsat 7 image to defringe.

Returns:

The defringed Landsat 7 image with fringe pixels masked out.

Return type:

ee.Image

Examples

>>> import geeViz.getImagesLib as gil
>>> ee = gil.ee
>>> l7 = ee.ImageCollection("LANDSAT/LE07/C02/T1").first()
>>> defringed = gil.defringeLandsat(l7)
geeViz.getImagesLib.despikeCollection(c, absoluteSpike, bandNo)[source]

Removes spike artifacts from a time series image collection.

Uses a moving window of three images (left, center, right) to detect and replace spikes. A pixel is considered a spike if it deviates from both its neighbors by more than the absolute threshold. Spikes are replaced with the mean of the left and right neighbors.

Parameters:
  • c (ee.ImageCollection) – The input image collection to despike. Should be temporally ordered.

  • absoluteSpike (float) – The absolute threshold for spike detection. A pixel is flagged as a spike if its difference from both neighbors exceeds this value.

  • bandNo (int) – The band index used to detect spikes.

Returns:

The despiked image collection with spike values

replaced by the mean of neighboring images.

Return type:

ee.ImageCollection

Examples

>>> import geeViz.getImagesLib as gil
>>> ee = gil.ee
>>> ndvi = ee.ImageCollection("MODIS/061/MOD13A1").filterDate("2024-01-01", "2024-12-31").select("NDVI")
>>> despiked = gil.despikeCollection(ndvi, 1000, 0)
>>> print(despiked.size().getInfo())
geeViz.getImagesLib.dir0Regression(img, slopes, intercepts)[source]

Applies a forward linear regression model: corrected = img * slopes + intercepts.

Used internally by harmonizationChastain() to apply Chastain et al. (2018) cross-sensor harmonization in the forward direction.

Parameters:
  • img (ee.Image) – The input image with spectral bands to correct.

  • slopes (list[float]) – Regression slope coefficients for each band in chastainBandNames.

  • intercepts (list[float]) – Regression intercept coefficients for each band in chastainBandNames.

Returns:

The image with corrected spectral bands and all other bands preserved.

Return type:

ee.Image

Examples

>>> img = ee.Image("LANDSAT/LC08/C02/T1_L2/LC08_044034_20200101")
>>> corrected = dir0Regression(img, msiOLISlopes, msiOLIIntercepts)
geeViz.getImagesLib.dir1Regression(img, slopes, intercepts)[source]

Applies an inverse linear regression model: corrected = (img - intercepts) / slopes.

Used internally by harmonizationChastain() to apply Chastain et al. (2018) cross-sensor harmonization in the reverse direction.

Parameters:
  • img (ee.Image) – The input image with spectral bands to correct.

  • slopes (list[float]) – Regression slope coefficients for each band in chastainBandNames.

  • intercepts (list[float]) – Regression intercept coefficients for each band in chastainBandNames.

Returns:

The image with corrected spectral bands and all other bands preserved.

Return type:

ee.Image

Examples

>>> img = ee.Image("LANDSAT/LE07/C02/T1_L2/LE07_044034_20200101")
>>> corrected = dir1Regression(img, oliETMSlopes, oliETMIntercepts)
geeViz.getImagesLib.exportCollection(exportPathRoot, outputName, studyArea, crs, transform, scale, collection, startYear, endYear, startJulian, endJulian, compositingReducer, timebuffer, exportBands, overwrite=False, exportToAssets=False, exportToCloud=False, bucket=None)[source]

Exports yearly composites from an image collection to EE assets or Cloud Storage.

Iterates through each year (adjusted by timebuffer), extracts the first image for that year, clips it to the study area, and exports it.

Parameters:
  • exportPathRoot (str) – Root path for exports.

  • outputName (str) – Base name for exported files.

  • studyArea (ee.Geometry | ee.FeatureCollection) – Region to clip to.

  • crs (str) – Coordinate reference system (e.g., “EPSG:5070”).

  • transform (list[float] | None) – Affine transform for the output.

  • scale (int | None) – Output resolution in meters.

  • collection (ee.ImageCollection) – Image collection to export from.

  • startYear (int) – First year of the collection.

  • endYear (int) – Last year of the collection.

  • startJulian (int) – Starting Julian day used in naming.

  • endJulian (int) – Ending Julian day used in naming.

  • compositingReducer (str) – Compositing method label for metadata.

  • timebuffer (int) – Years to buffer. Exports from startYear + timebuffer to endYear - timebuffer.

  • exportBands (list[str]) – Band names to select for export.

  • overwrite (bool, optional) – Overwrite existing assets. Defaults to False.

  • exportToAssets (bool, optional) – Export to EE assets. Defaults to False.

  • exportToCloud (bool, optional) – Export to Cloud Storage. Defaults to False.

  • bucket (str | None, optional) – Cloud Storage bucket name. Defaults to None.

Returns:

Submits export tasks as a side effect.

Return type:

None

Examples

>>> import geeViz.getImagesLib as gil
>>> ee = gil.ee
>>> studyArea = ee.Geometry.Rectangle([-110, 40, -109, 41])
>>> collection = ee.ImageCollection("LANDSAT/LC08/C02/T1_L2").filterDate("2023-06-01", "2023-09-01")
>>> gil.exportCollection("projects/my-project/assets/out", "L8", studyArea, "EPSG:5070", None, 30, collection, 2023, 2023, 152, 244, "median", 0, ["SR_B4", "SR_B5"], exportToAssets=True)
geeViz.getImagesLib.exportCompositeCollection(collection, exportPathRoot, outputName, origin, studyArea, crs, transform, scale, startYear, endYear, startJulian, endJulian, compositingMethod, timebuffer, toaOrSR, nonDivideBands, exportBands, additionalPropertyDict=None, overwrite=False)[source]

Exports yearly composites to Earth Engine assets with scaled integer values.

Iterates through each year (adjusted by timebuffer), scales reflectance bands by 10000, converts to int16, attaches metadata, and exports each yearly composite to an Earth Engine asset. Non-divide bands (e.g., indices or categorical bands) are kept unscaled.

Parameters:
  • collection (ee.ImageCollection) – The composite image collection.

  • exportPathRoot (str) – The root asset path for exports.

  • outputName (str) – Base name for the exported assets.

  • origin (str) – The data origin label (e.g., “Landsat”, “MODIS”).

  • studyArea (ee.Geometry | ee.FeatureCollection) – The export region.

  • crs (str) – The coordinate reference system (e.g., “EPSG:5070”).

  • transform (list[float] | None) – The affine transform for the output.

  • scale (int | None) – The output resolution in meters.

  • startYear (int) – The first year of the collection.

  • endYear (int) – The last year of the collection.

  • startJulian (int) – The starting Julian day used in naming.

  • endJulian (int) – The ending Julian day used in naming.

  • compositingMethod (str) – The compositing method (e.g., “medoid”, “median”) used in naming and metadata.

  • timebuffer (int) – Number of years before/after to buffer the year range.

  • toaOrSR (str) – Reflectance type label (“TOA” or “SR”) used in naming.

  • nonDivideBands (list[str] | None) – Band names that should not be multiplied by 10000. If None, all bands are scaled.

  • exportBands (list[str]) – Band names to select for export.

  • additionalPropertyDict (dict | None, optional) – Extra properties to attach to each exported image. Defaults to None.

  • overwrite (bool, optional) – If True, overwrites existing assets. Defaults to False.

Returns:

Submits export tasks as a side effect.

Return type:

None

Examples

>>> import geeViz.getImagesLib as gil
>>> ee = gil.ee
>>> studyArea = ee.Geometry.Rectangle([-110, 40, -109, 41])
>>> result = gil.getLandsatWrapper(studyArea, 2023, 2023, 152, 273)
>>> composites = result["processedComposites"]
>>> gil.exportCompositeCollection(composites, "projects/my-project/assets/composites", "L8_Composite", "Landsat", studyArea, "EPSG:5070", None, 30, 2023, 2023, 152, 273, "medoid", 0, "SR", ["NDVI", "NBR"], ["blue", "green", "red", "nir", "swir1", "swir2", "NDVI"])
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 with overwrite handling.

Wraps ee.batch.Export.image.toAsset with logic to check for existing assets or running exports, and optionally overwrite them.

Parameters:
  • imageForExport (ee.Image) – The image to export.

  • assetName (str) – Task description / asset name (spaces replaced with ‘-‘).

  • assetPath (str) – Full Earth Engine asset path (e.g., 'projects/my-project/assets/my_image').

  • pyramidingPolicyObject (dict | None, optional) – Pyramiding policy, e.g., {'.default': 'mean'}. If a string is provided it is wrapped as {'.default': value}. Defaults to None (uses 'mean').

  • roi (ee.Geometry | None, optional) – Region of interest. The image is clipped to this geometry before export. Defaults to None.

  • scale (float | None, optional) – Export resolution in meters. Defaults to None (uses the image’s native scale).

  • crs (str | None, optional) – Coordinate reference system, e.g., 'EPSG:4326'. Defaults to None.

  • transform (list | None, optional) – Affine transform as a 6-element list. Defaults to None.

  • overwrite (bool, optional) – If True, deletes existing asset or cancels a running export before re-exporting. Defaults to False.

Returns:

Starts an Earth Engine export task as a side effect.

Return type:

None

Examples

>>> import ee
>>> ee.Initialize()
>>> img = ee.Image('USGS/SRTMGL1_003')
>>> roi = ee.Geometry.Rectangle([-105.5, 39.5, -105.0, 40.0])
>>> exportToAssetWrapper(img, 'srtm_export', 'projects/my-project/assets/srtm', roi=roi, scale=30)
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 with overwrite handling.

Wraps ee.batch.Export.image.toCloudStorage, clipping the image to the region of interest and optionally deleting existing blobs before export.

Parameters:
  • imageForExport (ee.Image) – The image to export.

  • outputName (str) – Object name / prefix in the bucket (spaces replaced with ‘-‘).

  • bucketName (str) – Name of the Google Cloud Storage bucket.

  • roi (ee.Geometry) – Region of interest; the image is clipped to this geometry.

  • scale (float | None, optional) – Export resolution in meters. Defaults to None.

  • crs (str | None, optional) – Coordinate reference system, e.g., 'EPSG:4326'. Defaults to None.

  • transform (list | None, optional) – Affine transform as a 6-element list. Defaults to None.

  • outputNoData (int, optional) – Value used to fill masked pixels. Defaults to -32768.

  • fileFormat (str, optional) – Output format, e.g., 'GeoTIFF' or 'TFRecord'. Defaults to 'GeoTIFF'.

  • formatOptions (dict, optional) – Additional format options passed to the export. Defaults to {'cloudOptimized': True}.

  • overwrite (bool, optional) – If True, deletes existing blobs or cancels running exports before re-exporting. Defaults to False.

Returns:

Starts an Earth Engine export task as a side effect.

Return type:

None

Examples

>>> import ee
>>> ee.Initialize()
>>> img = ee.Image('USGS/SRTMGL1_003')
>>> roi = ee.Geometry.Rectangle([-105.5, 39.5, -105.0, 40.0])
>>> exportToCloudStorageWrapper(img, 'srtm_cog', 'my-bucket', roi, scale=30)
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 as a GeoTIFF.

Wraps ee.batch.Export.image.toDrive, clipping the image to the provided region of interest and filling masked pixels with outputNoData.

Parameters:
  • imageForExport (ee.Image) – The image to export.

  • outputName (str) – File name for the exported GeoTIFF (spaces replaced with ‘-‘).

  • driveFolderName (str) – Google Drive folder name to export into.

  • roi (ee.Geometry) – Region of interest; the image is clipped to this geometry.

  • scale (float | None, optional) – Export resolution in meters. Defaults to None (uses the image’s native scale).

  • crs (str | None, optional) – Coordinate reference system, e.g., 'EPSG:4326'. Defaults to None.

  • transform (list | None, optional) – Affine transform as a 6-element list. Defaults to None.

  • outputNoData (int, optional) – Value used to fill masked pixels. Defaults to -32768.

Returns:

Starts an Earth Engine export task as a side effect.

Return type:

None

Examples

>>> import ee
>>> ee.Initialize()
>>> img = ee.Image('USGS/SRTMGL1_003')
>>> roi = ee.Geometry.Rectangle([-105.5, 39.5, -105.0, 40.0])
>>> exportToDriveWrapper(img, 'srtm_export', 'EE_Exports', roi, scale=30)
geeViz.getImagesLib.fillEmptyCollections(inCollection: ImageCollection, dummyImage: Image) ImageCollection[source]

Fills empty image collections with a fully-masked dummy image.

Prevents downstream errors from empty collections by substituting a single fully-masked dummy image when the input collection contains no images.

Parameters:
  • inCollection (ee.ImageCollection) – The input image collection that may be empty.

  • dummyImage (ee.Image) – A template image whose band structure matches the expected output. It will be fully masked (all pixels set to 0) if used.

Returns:

The original collection if non-empty, otherwise a collection containing the fully-masked dummyImage.

Return type:

ee.ImageCollection

Examples

>>> col = ee.ImageCollection("LANDSAT/LC08/C02/T1_L2").filterDate("2000-01-01", "2000-01-02")
>>> dummy = ee.Image("LANDSAT/LC08/C02/T1_L2/LC08_044034_20200101")
>>> safe_col = fillEmptyCollections(col, dummy)
geeViz.getImagesLib.formatArgs(args: dict) dict[source]

Formats arguments as strings for setting as Earth Engine image properties.

Converts booleans, lists, dicts, and None values to their string representations. Strings and ints are kept as-is. Other types are omitted.

Parameters:

args (dict) – A dictionary of arguments to format.

Returns:

A dictionary with values converted to strings or kept as str/int.

Return type:

dict

Examples

>>> formatted = formatArgs({"threshold": 0.5, "apply": True, "bands": ["nir", "swir1"]})
>>> print(formatted)
{'apply': 'True', 'bands': "['nir', 'swir1']"}
geeViz.getImagesLib.getAreaUnderCurve(harmCoeffs, t0=0, t1=1)[source]

Compute the definite integral (area under curve) of a single-harmonic model.

Analytically integrates the harmonic function amplitude + sin_coeff * sin(2*pi*t) + cos_coeff * cos(2*pi*t) between t0 and t1, normalizing so the minimum of the curve is zero.

Parameters:
  • harmCoeffs (ee.Image) – Two-band image where band 0 is the sin coefficient and band 1 is the cos coefficient from a harmonic regression.

  • t0 (float, optional) – Start of the integration interval as a fraction of the year (0 = Jan 1). Defaults to 0.

  • t1 (float, optional) – End of the integration interval as a fraction of the year (1 = Dec 31). Defaults to 1.

Returns:

Single-band image named AUC with the area under the curve.

Return type:

ee.Image

Examples

>>> import geeViz.getImagesLib as gil
>>> ee = gil.ee
>>> harmCoeffs = ee.Image([0.05, -0.1])
>>> auc = gil.getAreaUnderCurve(harmCoeffs, t0=0, t1=1)
>>> print(auc.bandNames().getInfo())
['AUC']
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.getDateStack(startYear, endYear, startJulian, endJulian, frequency)[source]

Generate a synthetic date image stack for predicting harmonic time series.

Creates an ImageCollection of dummy images at regular intervals, each tagged with system:time_start and containing a year band with year-fraction values, plus constant bands for each index in the module-level indexNames list.

Parameters:
  • startYear (int) – First year to include.

  • endYear (int) – Last year to include.

  • startJulian (int) – Starting Julian day within each year.

  • endJulian (int) – Ending Julian day within each year.

  • frequency (int) – Step size in days between successive images.

Returns:

Collection of images with year (year.dd) and

constant index bands, each with system:time_start and system:time_end properties set.

Return type:

ee.ImageCollection

Examples

>>> import geeViz.getImagesLib as gil
>>> ee = gil.ee
>>> dateStack = gil.getDateStack(2020, 2023, 1, 365, 32)
>>> print(dateStack.size().getInfo())
geeViz.getImagesLib.getHarmonicCoefficientsAndFit(allImages, indexNames, whichHarmonics=[2], detrend=False)[source]

Fit harmonic regression to an ImageCollection and return coefficients and fitted values.

Convenience wrapper that chains getHarmonics2, newRobustMultipleLinear2, and newPredict to fit a harmonic model to selected bands and return both the coefficient image and the predicted time series.

Parameters:
  • allImages (ee.ImageCollection) – Input image collection containing the bands to model.

  • indexNames (list[str]) – List of band names to fit harmonics to (e.g., ["NDVI", "NBR"]).

  • whichHarmonics (list[int], optional) – Harmonic numbers to include (e.g., [2] for annual, [2, 4] for annual + semi-annual). Defaults to [2].

  • detrend (bool, optional) – If True, includes a linear year trend term in the regression. Defaults to False.

Returns:

Two-element list [coeffs, predicted] where:
  • coeffs (ee.Image): Regression coefficients image.

  • predicted (ee.ImageCollection): Collection with actual and predicted bands.

Return type:

list

Examples

>>> import geeViz.getImagesLib as gil
>>> ee = gil.ee
>>> studyArea = gil.testAreas["CO"]
>>> result = gil.getLandsatWrapper(studyArea, 2018, 2023, 1, 365)
>>> composites = result["processedComposites"]
>>> coeffs, predicted = gil.getHarmonicCoefficientsAndFit(
...     composites, ["NDVI"], whichHarmonics=[2])
geeViz.getImagesLib.getHarmonicList(yearDateImg, transformBandName, harmonicList)[source]

Compute sin and cos harmonic predictor bands for a year-fraction image.

Takes a year.dd date image and a list of harmonic frequencies, and appends sin and cos bands for each harmonic to the input image.

Parameters:
  • yearDateImg (ee.Image) – Image containing a band with year-fraction values (e.g., 2020.5 for mid-year 2020).

  • transformBandName (str) – Name of the band in yearDateImg that holds the year-fraction values (e.g., "year").

  • harmonicList (list[int]) – List of harmonic numbers to generate predictors for (e.g., [1, 2, 3]). Each value h produces sin(h * pi * t) and cos(h * pi * t) bands.

Returns:

The input image with additional sin and cos bands appended.

Band names follow the pattern sin_<h*100>_<transformBandName> and cos_<h*100>_<transformBandName>.

Return type:

ee.Image

Examples

>>> import geeViz.getImagesLib as gil
>>> ee = gil.ee
>>> dateImg = ee.Image(2020.5).rename('year')
>>> result = gil.getHarmonicList(dateImg, 'year', [2])
>>> print(result.bandNames().getInfo())
['year', 'sin_200_year', 'cos_200_year']
geeViz.getImagesLib.getHarmonics2(collection, transformBandName, harmonicList, detrend=False)[source]

Prepare an ImageCollection with harmonic predictor bands for regression.

Adds sin and cos harmonic predictor bands to each image in the collection, and stores metadata about dependent and independent band names/numbers on the returned collection for use by newRobustMultipleLinear2.

Parameters:
  • collection (ee.ImageCollection) – Input collection where each image has a year-fraction band (named transformBandName) and one or more dependent variable bands.

  • transformBandName (str) – Name of the band containing year-fraction values (e.g., "year").

  • harmonicList (list[int]) – List of harmonic numbers (e.g., [2] for annual, [2, 4] for annual + semi-annual).

  • detrend (bool, optional) – If True, retains the "year" band as an additional linear trend predictor. Defaults to False.

Returns:

Collection with harmonic bands appended to each image

and metadata properties indBandNames, depBandNames, indBandNumbers, and depBandNumbers set on the collection.

Return type:

ee.ImageCollection

Examples

>>> import geeViz.getImagesLib as gil
>>> ee = gil.ee
>>> composites = ee.ImageCollection('projects/my-project/assets/composites')
>>> withHarmonics = gil.getHarmonics2(composites, 'year', [2])
>>> print(withHarmonics.get('indBandNames').getInfo())
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.getLandsatAndSentinel2HybridWrapper(studyArea, startYear, endYear, startJulian, endJulian, timebuffer=0, weights=[1], compositingMethod='medoid', toaOrSR='TOA', includeSLCOffL7=False, defringeL5=False, applyQABand=False, applyCloudProbability=False, applyShadowShift=False, applyCloudScoreLandsat=False, applyCloudScoreSentinel2=False, applyTDOMLandsat=True, applyTDOMSentinel2=False, applyFmaskCloudMask=True, applyFmaskCloudShadowMask=True, applyFmaskSnowMask=False, cloudHeights=<ee.ee_list.List object>, cloudScoreThresh=20, performCloudScoreOffset=True, cloudScorePctl=10, zScoreThresh=-1, shadowSumThresh=0.35, contractPixels=1.5, dilatePixels=3.5, shadowSumBands=['nir', 'swir1'], landsatResampleMethod='near', sentinel2ResampleMethod='aggregate', convertToDailyMosaics=True, runChastainHarmonization=True, correctIllumination=False, correctScale=250, exportComposites=False, outputName='Landsat-Sentinel2-Hybrid', exportPathRoot=None, crs='EPSG:5070', transform=[30, 0, -2361915.0, 0, -30, 3177735.0], scale=None, preComputedLandsatCloudScoreOffset=None, preComputedLandsatTDOMIRMean=None, preComputedLandsatTDOMIRStdDev=None, preComputedSentinel2CloudScoreOffset=None, preComputedSentinel2TDOMIRMean=None, preComputedSentinel2TDOMIRStdDev=None, cloudProbThresh=40, landsatCollectionVersion='C2', overwrite=False, verbose=False, applyCloudScorePlusSentinel2=True, cloudScorePlusThresh=0.6, cloudScorePlusScore='cs')[source]

Get annual Landsat + Sentinel-2 hybrid composites.

Wraps getProcessedLandsatAndSentinel2Scenes to retrieve merged, cloud-masked Landsat and Sentinel-2 scenes, then composites them into annual images. Optionally exports composites to an EE asset.

Parameters:
  • studyArea (ee.Geometry | ee.FeatureCollection) – Area of interest.

  • startYear (int) – First year to include.

  • endYear (int) – Last year to include.

  • startJulian (int) – Start day of year (1-365).

  • endJulian (int) – End day of year (1-365).

  • timebuffer (int) – Years to buffer each composite. Defaults to 0.

  • weights (list[int]) – Temporal weights. Defaults to [1].

  • compositingMethod (str) – "medoid" or "median". Defaults to "medoid".

  • toaOrSR (str) – "TOA" or "SR". Defaults to "TOA".

  • includeSLCOffL7 (bool) – Include Landsat 7 SLC-off. Defaults to False.

  • defringeL5 (bool) – Defringe Landsat 5. Defaults to False.

  • applyQABand (bool) – Apply QA band mask. Defaults to False.

  • applyCloudProbability (bool) – Apply S2 cloud probability. Defaults to False.

  • applyShadowShift (bool) – Apply shadow-shift. Defaults to False.

  • applyCloudScoreLandsat (bool) – Cloud score for Landsat. Defaults to False.

  • applyCloudScoreSentinel2 (bool) – Cloud score for S2. Defaults to False.

  • applyTDOMLandsat (bool) – TDOM for Landsat. Defaults to True.

  • applyTDOMSentinel2 (bool) – TDOM for S2. Defaults to False.

  • applyFmaskCloudMask (bool) – Fmask clouds for Landsat. Defaults to True.

  • applyFmaskCloudShadowMask (bool) – Fmask shadows. Defaults to True.

  • applyFmaskSnowMask (bool) – Fmask snow. Defaults to False.

  • cloudHeights (ee.List) – Cloud heights for shadow projection. Defaults to ee.List.sequence(500, 10000, 500).

  • cloudScoreThresh (int) – Cloud score threshold. Defaults to 20.

  • performCloudScoreOffset (bool) – Per-scene offset. Defaults to True.

  • cloudScorePctl (int) – Offset percentile. Defaults to 10.

  • zScoreThresh (float) – TDOM z-score threshold. Defaults to -1.

  • shadowSumThresh (float) – TDOM shadow sum threshold. Defaults to 0.35.

  • contractPixels (float) – Contract mask pixels. Defaults to 1.5.

  • dilatePixels (float) – Dilate mask pixels. Defaults to 3.5.

  • shadowSumBands (list[str]) – Shadow detection bands. Defaults to ["nir", "swir1"].

  • landsatResampleMethod (str) – Landsat resampling. Defaults to "near".

  • sentinel2ResampleMethod (str) – S2 resampling. Defaults to "aggregate".

  • convertToDailyMosaics (bool) – Mosaic same-day images. Defaults to True.

  • runChastainHarmonization (bool) – Harmonize Landsat/S2. Defaults to True.

  • correctIllumination (bool) – Reserved. Defaults to False.

  • correctScale (int) – Illumination correction scale. Defaults to 250.

  • exportComposites (bool) – Export to EE asset. Defaults to False.

  • outputName (str) – Asset name prefix. Defaults to "Landsat-Sentinel2-Hybrid".

  • exportPathRoot (str | None) – Asset folder path. Defaults to None.

  • crs (str) – Output CRS. Defaults to "EPSG:5070".

  • transform (list) – Affine transform. Defaults to [30, 0, -2361915.0, 0, -30, 3177735.0].

  • scale (int | None) – Output scale (overrides transform). Defaults to None.

  • preComputedLandsatCloudScoreOffset (ee.Image | None) – Defaults to None.

  • preComputedLandsatTDOMIRMean (ee.Image | None) – Defaults to None.

  • preComputedLandsatTDOMIRStdDev (ee.Image | None) – Defaults to None.

  • preComputedSentinel2CloudScoreOffset (ee.Image | None) – Defaults to None.

  • preComputedSentinel2TDOMIRMean (ee.Image | None) – Defaults to None.

  • preComputedSentinel2TDOMIRStdDev (ee.Image | None) – Defaults to None.

  • cloudProbThresh (int) – Cloud probability threshold. Defaults to 40.

  • landsatCollectionVersion (str) – Defaults to "C2".

  • overwrite (bool) – Overwrite existing exports. Defaults to False.

  • verbose (bool) – Print all parameters. Defaults to False.

  • applyCloudScorePlusSentinel2 (bool) – Cloud Score+ for S2. Defaults to True.

  • cloudScorePlusThresh (float) – Cloud Score+ threshold (0-1). Defaults to 0.6.

  • cloudScorePlusScore (str) – "cs" or "cs_cdf". Defaults to "cs".

Returns:

Dictionary with all input args plus:
  • "processedScenes": ee.ImageCollection of merged scenes

  • "processedComposites": ee.ImageCollection of annual composites

Return type:

dict

Example

>>> import geeViz.getImagesLib as gil
>>> study = ee.Geometry.Point([-105.0, 40.0]).buffer(5000)
>>> result = gil.getLandsatAndSentinel2HybridWrapper(
...     study, 2023, 2023, 152, 273
... )
>>> composites = result['processedComposites']
>>> print(composites.size().getInfo())
1
geeViz.getImagesLib.getLandsatWrapper(studyArea, startYear, endYear, startJulian, endJulian, timebuffer=0, weights=[1], compositingMethod='medoid', toaOrSR='SR', includeSLCOffL7=False, defringeL5=False, applyCloudScore=False, applyFmaskCloudMask=True, applyTDOM=False, applyFmaskCloudShadowMask=True, applyFmaskSnowMask=False, cloudScoreThresh=10, performCloudScoreOffset=True, cloudScorePctl=10, zScoreThresh=-1, shadowSumThresh=0.35, contractPixels=1.5, dilatePixels=3.5, correctIllumination=False, correctScale=250, exportComposites=False, outputName='Landsat-Composite', exportPathRoot='users/username/test', crs='EPSG:5070', transform=[30, 0, -2361915.0, 0, -30, 3177735.0], scale=None, resampleMethod='near', preComputedCloudScoreOffset=None, preComputedTDOMIRMean=None, preComputedTDOMIRStdDev=None, compositingReducer=None, harmonizeOLI=False, landsatCollectionVersion='C2', overwrite=False, verbose=False)[source]

Retrieve cloud-masked Landsat annual composites for a study area and date range.

This is the main high-level wrapper for Landsat imagery. It retrieves and cloud-masks Landsat scenes via getProcessedLandsatScenes, composites them into annual images, and optionally exports the composites to an Earth Engine asset.

Parameters:
  • studyArea (ee.Geometry | ee.Feature | ee.FeatureCollection) – The geographic area of interest.

  • 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 (1-365). If startJulian > endJulian, dates wrap across the new year.

  • endJulian (int) – The ending Julian day of year (1-365).

  • timebuffer (int, optional) – Number of years to buffer composites on each side. Defaults to 0.

  • weights (list[int], optional) – Weights for years in the composite (length must equal 2 * timebuffer + 1). Defaults to [1].

  • compositingMethod (str, optional) – Compositing method, e.g. "medoid" or "median". Defaults to "medoid".

  • toaOrSR (str, optional) – "TOA" for Top of Atmosphere or "SR" for Surface Reflectance. Defaults to "SR".

  • includeSLCOffL7 (bool, optional) – Whether to include Landsat 7 SLC-off scenes. Defaults to False.

  • defringeL5 (bool, optional) – Whether to defringe Landsat 5 scenes. Defaults to False.

  • applyCloudScore (bool, optional) – Whether to apply the CloudScore simple cloud mask. Defaults to False.

  • applyFmaskCloudMask (bool, optional) – Whether to apply the Fmask cloud mask. Defaults to True.

  • applyTDOM (bool, optional) – Whether to apply TDOM cloud shadow masking. Defaults to False.

  • applyFmaskCloudShadowMask (bool, optional) – Whether to apply Fmask cloud shadow mask. Defaults to True.

  • applyFmaskSnowMask (bool, optional) – Whether to apply Fmask snow mask. Defaults to False.

  • cloudScoreThresh (int, optional) – Cloud score threshold; lower masks more. Defaults to 10.

  • performCloudScoreOffset (bool, optional) – Whether to offset cloud score over bright surfaces. Defaults to True.

  • cloudScorePctl (int, optional) – Percentile for cloud score offset correction. Defaults to 10.

  • zScoreThresh (float, optional) – Z-score threshold for TDOM shadow masking. Defaults to -1.

  • shadowSumThresh (float, optional) – Sum-of-reflectance threshold for TDOM. Defaults to 0.35.

  • contractPixels (float, optional) – Pixels to contract cloud/shadow masks. Defaults to 1.5.

  • dilatePixels (float, optional) – Pixels to dilate cloud/shadow masks. Defaults to 3.5.

  • correctIllumination (bool, optional) – Whether to apply terrain illumination correction. Defaults to False.

  • correctScale (int, optional) – Scale in meters for illumination correction. Defaults to 250.

  • exportComposites (bool, optional) – Whether to export composites to an Earth Engine asset. Defaults to False.

  • outputName (str, optional) – Base name for exported assets. Defaults to "Landsat-Composite".

  • exportPathRoot (str, optional) – Asset folder path for exports. Defaults to "users/username/test".

  • crs (str, optional) – Coordinate reference system for exports. Defaults to "EPSG:5070".

  • transform (list[float] | None, optional) – Affine transform for exports. Defaults to [30, 0, -2361915.0, 0, -30, 3177735.0].

  • scale (float | None, optional) – Scale in meters for exports. Overrides transform if provided. Defaults to None.

  • resampleMethod (str, optional) – Resampling method ("near", "bilinear", "bicubic"). Defaults to "near".

  • preComputedCloudScoreOffset (ee.Image | None, optional) – Pre-computed cloud score offset image. Defaults to None.

  • preComputedTDOMIRMean (ee.Image | None, optional) – Pre-computed TDOM IR mean image. Defaults to None.

  • preComputedTDOMIRStdDev (ee.Image | None, optional) – Pre-computed TDOM IR standard deviation image. Defaults to None.

  • compositingReducer (ee.Reducer | None, optional) – Custom reducer for compositing. Overrides compositingMethod if provided. Defaults to None.

  • harmonizeOLI (bool, optional) – Whether to harmonize OLI to TM/ETM+ spectral response. Defaults to False.

  • landsatCollectionVersion (str, optional) – Landsat collection version ("C1" or "C2"). Defaults to "C2".

  • overwrite (bool, optional) – Whether to overwrite existing exported assets. Defaults to False.

  • verbose (bool, optional) – Whether to print processing details. Defaults to False.

Returns:

A dictionary containing all input arguments plus two additional keys:

  • 'processedScenes' (ee.ImageCollection): The cloud-masked individual Landsat scenes.

  • 'processedComposites' (ee.ImageCollection): The annual composite time series.

Return type:

dict

Examples

>>> import geeViz.getImagesLib as gil
>>> ee = gil.ee
>>> studyArea = gil.testAreas["CO"]
>>> result = gil.getLandsatWrapper(studyArea, 2020, 2023, 190, 250)
>>> composites = result['processedComposites']
>>> Map = gil.Map
>>> Map.addLayer(composites, gil.vizParamsFalse, "Landsat Composites", True)
>>> 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.getPeakDate(coeffs, peakDirection=1)[source]

Compute the Julian day, month, and day-of-month of peak vegetation vigor.

Finds the date within an annual cycle where the first harmonic (sin/cos) reaches its maximum, accounting for the sign of the peak direction. Uses module-level lookup tables to convert Julian day to month and day of month.

Parameters:
  • coeffs (ee.Image) – Two-band image where band 0 is the sin coefficient and band 1 is the cos coefficient from a harmonic regression.

  • peakDirection (int, optional) – Set to 1 for bands positively correlated with vegetation vigor, or -1 for negatively correlated bands. Defaults to 1.

Returns:

Three-band image with bands peakJulianDay (1–365),

peakMonth (1–12), and peakDayOfMonth (1–31).

Return type:

ee.Image

Examples

>>> import geeViz.getImagesLib as gil
>>> ee = gil.ee
>>> coeffs = ee.Image([0.1, -0.2])
>>> peakInfo = gil.getPeakDate(coeffs, peakDirection=1)
>>> print(peakInfo.bandNames().getInfo())
['peakJulianDay', 'peakMonth', 'peakDayOfMonth']
geeViz.getImagesLib.getPhaseAmplitudePeak(coeffs, t0=0, t1=1)[source]

Extract phase, amplitude, peak date, and AUC from harmonic regression coefficients.

Parses multi-band harmonic regression coefficients (from newRobustMultipleLinear2) and computes per-dependent-variable amplitude, phase (0–1 scaled), peak date (Julian day, month, day of month), and area under the curve.

Parameters:
  • coeffs (ee.Image) – Harmonic regression coefficient image as returned by newRobustMultipleLinear2, with metadata noDependents and modelLength.

  • t0 (float, optional) – Start of integration interval for AUC calculation (fraction of year). Defaults to 0.

  • t1 (float, optional) – End of integration interval for AUC calculation (fraction of year). Defaults to 1.

Returns:

Multi-band image with bands named

<dep>_amplitude, <dep>_phase, <dep>_peakJulianDay, <dep>_peakMonth, <dep>_peakDayOfMonth, and <dep>_AUC for each dependent variable.

Return type:

ee.Image

Examples

>>> import geeViz.getImagesLib as gil
>>> ee = gil.ee
>>> studyArea = gil.testAreas["CO"]
>>> result = gil.getLandsatWrapper(studyArea, 2018, 2023, 1, 365)
>>> composites = result["processedComposites"]
>>> coeffs, predicted = gil.getHarmonicCoefficientsAndFit(
...     composites, ["NDVI"], whichHarmonics=[2])
>>> pap = gil.getPhaseAmplitudePeak(coeffs)
>>> print(pap.bandNames().getInfo())
geeViz.getImagesLib.getPrecomputedCloudScoreOffsets(cloudScorePctl=10)[source]

Retrieves precomputed cloud score offset images for Landsat and Sentinel-2.

These offsets represent a lower percentile of cloud scores on a pixel-wise basis, precomputed for all CONUS. They are appropriate for any time period within the growing season.

Parameters:

cloudScorePctl (int, optional) – The cloud score percentile to use. Defaults to 10.

Returns:

A dictionary with keys "landsat" and "sentinel2", each containing an ee.Image of the cloud score offset for that sensor.

Return type:

dict

Examples

>>> offsets = getPrecomputedCloudScoreOffsets(10)
>>> landsat_offset = offsets["landsat"]
>>> sentinel2_offset = offsets["sentinel2"]
geeViz.getImagesLib.getPrecomputedTDOMStats()[source]

Retrieves precomputed TDOM (Temporal Dark Outlier Mask) statistics for Landsat and Sentinel-2.

Returns the mean and standard deviation of the NIR and SWIR1 bands, precomputed for all CONUS. These are used by the TDOM cloud shadow masking algorithm.

Returns:

A nested dictionary with keys "landsat" and "sentinel2", each containing "mean" and "stdDev" keys mapped to ee.Image objects with the corresponding band statistics.

Return type:

dict

Examples

>>> stats = getPrecomputedTDOMStats()
>>> landsat_mean = stats["landsat"]["mean"]
>>> sentinel2_stddev = stats["sentinel2"]["stdDev"]
geeViz.getImagesLib.getProcessedLandsatAndSentinel2Scenes(studyArea, startYear, endYear, startJulian, endJulian, toaOrSR='TOA', includeSLCOffL7=False, defringeL5=False, applyQABand=False, applyCloudProbability=False, applyShadowShift=False, applyCloudScoreLandsat=False, applyCloudScoreSentinel2=False, applyTDOMLandsat=True, applyTDOMSentinel2=False, applyFmaskCloudMask=True, applyFmaskCloudShadowMask=True, applyFmaskSnowMask=False, cloudHeights=<ee.ee_list.List object>, cloudScoreThresh=20, performCloudScoreOffset=True, cloudScorePctl=10, zScoreThresh=-1, shadowSumThresh=0.35, contractPixels=1.5, dilatePixels=3.5, shadowSumBands=['nir', 'swir1'], landsatResampleMethod='near', sentinel2ResampleMethod='aggregate', convertToDailyMosaics=True, runChastainHarmonization=True, correctIllumination=False, correctScale=250, preComputedLandsatCloudScoreOffset=None, preComputedLandsatTDOMIRMean=None, preComputedLandsatTDOMIRStdDev=None, preComputedSentinel2CloudScoreOffset=None, preComputedSentinel2TDOMIRMean=None, preComputedSentinel2TDOMIRStdDev=None, cloudProbThresh=40, landsatCollectionVersion='C2', verbose=False, applyCloudScorePlus=True, cloudScorePlusThresh=0.6, cloudScorePlusScore='cs')[source]

Get cloud/shadow-masked Landsat + Sentinel-2 scenes merged together.

Retrieves and masks both Landsat and Sentinel-2 imagery for the same date range, optionally applies Chastain harmonization to align the two sensor families, and returns the merged scene collection. This is the scene-level counterpart to getLandsatAndSentinel2HybridWrapper.

Parameters:
  • studyArea (ee.Geometry | ee.FeatureCollection) – Area of interest.

  • startYear (int) – First year to include.

  • endYear (int) – Last year to include.

  • startJulian (int) – Start day of year (1-365).

  • endJulian (int) – End day of year (1-365).

  • toaOrSR (str) – "TOA" or "SR". Defaults to "TOA".

  • includeSLCOffL7 (bool) – Include Landsat 7 SLC-off imagery. Defaults to False.

  • defringeL5 (bool) – Defringe Landsat 5 scenes. Defaults to False.

  • applyQABand (bool) – Apply QA band cloud mask. Defaults to False.

  • applyCloudProbability (bool) – Apply S2 cloud probability. Defaults to False.

  • applyShadowShift (bool) – Apply shadow-shift detection. Defaults to False.

  • applyCloudScoreLandsat (bool) – Apply cloud score to Landsat. Defaults to False.

  • applyCloudScoreSentinel2 (bool) – Apply cloud score to Sentinel-2. Defaults to False.

  • applyTDOMLandsat (bool) – Apply TDOM to Landsat. Defaults to True.

  • applyTDOMSentinel2 (bool) – Apply TDOM to Sentinel-2. Defaults to False.

  • applyFmaskCloudMask (bool) – Apply Fmask cloud mask to Landsat. Defaults to True.

  • applyFmaskCloudShadowMask (bool) – Apply Fmask shadow mask. Defaults to True.

  • applyFmaskSnowMask (bool) – Apply Fmask snow mask. Defaults to False.

  • cloudHeights (ee.List) – Cloud heights for shadow projection. Defaults to ee.List.sequence(500, 10000, 500).

  • cloudScoreThresh (int) – Cloud score threshold. Defaults to 20.

  • performCloudScoreOffset (bool) – Per-scene cloud score offset. Defaults to True.

  • cloudScorePctl (int) – Percentile for offset. Defaults to 10.

  • zScoreThresh (float) – TDOM z-score threshold. Defaults to -1.

  • shadowSumThresh (float) – TDOM shadow sum threshold. Defaults to 0.35.

  • contractPixels (float) – Pixels to contract mask. Defaults to 1.5.

  • dilatePixels (float) – Pixels to dilate mask. Defaults to 3.5.

  • shadowSumBands (list[str]) – Bands for shadow detection. Defaults to ["nir", "swir1"].

  • landsatResampleMethod (str) – Landsat resampling. Defaults to "near".

  • sentinel2ResampleMethod (str) – S2 resampling. Defaults to "aggregate".

  • convertToDailyMosaics (bool) – Mosaic same-day images. Defaults to True.

  • runChastainHarmonization (bool) – Apply Chastain et al. harmonization between Landsat and S2. Forced to False when toaOrSR="SR". Defaults to True.

  • correctIllumination (bool) – Reserved. Defaults to False.

  • correctScale (int) – Scale for illumination correction. Defaults to 250.

  • preComputedLandsatCloudScoreOffset (ee.Image | None) – Pre-computed Landsat cloud score offset. Defaults to None.

  • preComputedLandsatTDOMIRMean (ee.Image | None) – Pre-computed Landsat TDOM mean. Defaults to None.

  • preComputedLandsatTDOMIRStdDev (ee.Image | None) – Pre-computed Landsat TDOM std dev. Defaults to None.

  • preComputedSentinel2CloudScoreOffset (ee.Image | None) – Pre-computed S2 cloud score offset. Defaults to None.

  • preComputedSentinel2TDOMIRMean (ee.Image | None) – Pre-computed S2 TDOM mean. Defaults to None.

  • preComputedSentinel2TDOMIRStdDev (ee.Image | None) – Pre-computed S2 TDOM std dev. Defaults to None.

  • cloudProbThresh (int) – Cloud probability threshold. Defaults to 40.

  • landsatCollectionVersion (str) – "C2" for Collection 2. Defaults to "C2".

  • verbose (bool) – Print all parameters. Defaults to False.

  • applyCloudScorePlus (bool) – Apply Cloud Score+ to S2. Defaults to True.

  • cloudScorePlusThresh (float) – Cloud Score+ threshold (0-1). Defaults to 0.6.

  • cloudScorePlusScore (str) – "cs" or "cs_cdf". Defaults to "cs".

Returns:

Merged, cloud/shadow-masked Landsat and Sentinel-2 scenes with standardized band names (blue, green, red, nir, swir1, swir2).

Return type:

ee.ImageCollection

Example

>>> import geeViz.getImagesLib as gil
>>> study = ee.Geometry.Point([-105.0, 40.0]).buffer(5000)
>>> scenes = gil.getProcessedLandsatAndSentinel2Scenes(
...     study, 2023, 2023, 152, 273
... )
>>> print(scenes.size().getInfo() > 0)
True
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.

Returns:

Cloud and shadow masked MODIS imagery with

spectral indices added. The collection has processing parameters stored as properties.

Return type:

ee.ImageCollection

Examples

>>> 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.getProcessedSentinel2Scenes(studyArea, startYear, endYear, startJulian, endJulian, applyQABand=False, applyCloudScore=False, applyShadowShift=False, applyTDOM=False, cloudScoreThresh=20, performCloudScoreOffset=True, cloudScorePctl=10, cloudHeights=<ee.ee_list.List object>, zScoreThresh=-1, shadowSumThresh=0.35, contractPixels=1.5, dilatePixels=3.5, shadowSumBands=['nir', 'swir1'], resampleMethod='aggregate', toaOrSR='TOA', convertToDailyMosaics=True, applyCloudProbability=False, preComputedCloudScoreOffset=None, preComputedTDOMIRMean=None, preComputedTDOMIRStdDev=None, cloudProbThresh=40, verbose=False, applyCloudScorePlus=True, cloudScorePlusThresh=0.6, cloudScorePlusScore='cs')[source]

Get cloud/shadow-masked Sentinel-2 scenes for a date range.

Retrieves Sentinel-2 imagery, applies selected cloud and shadow masking methods (QA band, cloud score, TDOM, Cloud Score+, cloud probability), and returns the processed scene collection. This is the scene-level counterpart to getSentinel2Wrapper, which also composites.

Parameters:
  • studyArea (ee.Geometry | ee.FeatureCollection) – Area of interest.

  • startYear (int) – First year to include.

  • endYear (int) – Last year to include.

  • startJulian (int) – Start day of year (1-365).

  • endJulian (int) – End day of year (1-365). If < startJulian, the date range wraps across the year boundary.

  • applyQABand (bool) – Apply the Sentinel-2 QA60 cloud bitmask. Defaults to False.

  • applyCloudScore (bool) – Apply simple cloud scoring. Defaults to False.

  • applyShadowShift (bool) – Apply shadow-shift cloud shadow detection. Defaults to False.

  • applyTDOM (bool) – Apply Temporal Dark Outlier Mask for shadows. Defaults to False.

  • cloudScoreThresh (int) – Cloud score threshold (0-100). Defaults to 20.

  • performCloudScoreOffset (bool) – Compute per-scene cloud score offset. Defaults to True.

  • cloudScorePctl (int) – Percentile for cloud score offset. Defaults to 10.

  • cloudHeights (ee.List) – Cloud heights in meters for shadow projection. Defaults to ee.List.sequence(500, 10000, 500).

  • zScoreThresh (float) – TDOM z-score threshold. Defaults to -1.

  • shadowSumThresh (float) – TDOM shadow sum threshold. Defaults to 0.35.

  • contractPixels (float) – Pixels to contract cloud/shadow mask. Defaults to 1.5.

  • dilatePixels (float) – Pixels to dilate cloud/shadow mask. Defaults to 3.5.

  • shadowSumBands (list[str]) – Bands for shadow detection. Defaults to ["nir", "swir1"].

  • resampleMethod (str) – Resampling method — "aggregate", "near", "bilinear", or "bicubic". Defaults to "aggregate".

  • toaOrSR (str) – "TOA" or "SR". Defaults to "TOA".

  • convertToDailyMosaics (bool) – Mosaic same-day images. Defaults to True.

  • applyCloudProbability (bool) – Apply the S2 cloud probability band. Defaults to False.

  • preComputedCloudScoreOffset (ee.Image | None) – Pre-computed cloud score offset image. Defaults to None.

  • preComputedTDOMIRMean (ee.Image | None) – Pre-computed TDOM IR mean. Defaults to None.

  • preComputedTDOMIRStdDev (ee.Image | None) – Pre-computed TDOM IR standard deviation. Defaults to None.

  • cloudProbThresh (int) – Cloud probability threshold (0-100). Defaults to 40.

  • verbose (bool) – Print all processing parameters. Defaults to False.

  • applyCloudScorePlus (bool) – Apply Cloud Score+ masking. Defaults to True.

  • cloudScorePlusThresh (float) – Cloud Score+ threshold (0-1). Defaults to 0.6.

  • cloudScorePlusScore (str) – Cloud Score+ band — "cs" or "cs_cdf". Defaults to "cs".

Returns:

Cloud/shadow-masked Sentinel-2 scenes with standardized band names.

Return type:

ee.ImageCollection

Example

>>> import geeViz.getImagesLib as gil
>>> study = ee.Geometry.Point([-122.3, 37.5]).buffer(5000)
>>> scenes = gil.getProcessedSentinel2Scenes(
...     study, 2023, 2023, 152, 273
... )
>>> print(scenes.first().bandNames().getInfo()[:3])
['cb', 'blue', 'green']
geeViz.getImagesLib.getQABits(image: Image, start: int, end: int, name: str) Image[source]

Extracts a range of bits from a QA band image.

Creates a bitmask for bits start through end, applies it with bitwiseAnd, and right-shifts to get the extracted value.

Parameters:
  • image (ee.Image) – Single-band QA image (e.g., a MODIS state_1km band).

  • start (int) – Starting bit position (0-based, inclusive).

  • end (int) – Ending bit position (inclusive).

  • name (str) – Name for the output band.

Returns:

Single-band image with the extracted QA bit values, renamed

to name.

Return type:

ee.Image

Examples

>>> import ee
>>> ee.Initialize()
>>> qa = ee.Image('MODIS/006/MOD09GA/2020_06_01').select('state_1km')
>>> cloud_bits = getQABits(qa, 0, 1, 'cloud_state')
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.

Filters the COPERNICUS/S1_GRD collection by date, bounds, IW instrument mode, polarization, pass direction, and 10m resolution.

Parameters:
  • studyArea (ee.Geometry | ee.Feature | ee.FeatureCollection) – The geographic area of interest.

  • startYear (int) – The start year (inclusive).

  • endYear (int) – The end year (inclusive).

  • startJulian (int) – The start Julian day of year (1-365).

  • endJulian (int) – The end Julian day of year (1-365).

  • polarization (str, optional) – The desired polarization band. Defaults to "VV". Other option is "VH".

  • pass_direction (str, optional) – The orbit pass direction. Defaults to "ASCENDING". Other option is "DESCENDING".

Returns:

A collection of Sentinel-1 GRD images filtered by the specified criteria.

Return type:

ee.ImageCollection

Examples

>>> import geeViz.getImagesLib as gil
>>> ee = gil.ee
>>> studyArea = gil.testAreas["CA"]
>>> s1 = gil.getS1(studyArea, 2023, 2023, 1, 365)
>>> print(s1.size().getInfo())
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.getSentinel2Wrapper(studyArea, startYear, endYear, startJulian, endJulian, timebuffer=0, weights=[1], compositingMethod='medoid', applyQABand=False, applyCloudScore=False, applyShadowShift=False, applyTDOM=False, cloudScoreThresh=20, performCloudScoreOffset=True, cloudScorePctl=10, cloudHeights=<ee.ee_list.List object>, zScoreThresh=-1, shadowSumThresh=0.35, contractPixels=1.5, dilatePixels=3.5, shadowSumBands=['nir', 'swir1'], correctIllumination=False, correctScale=250, exportComposites=False, outputName='Sentinel2-Composite', exportPathRoot='users/username/test', crs='EPSG:5070', transform=[10, 0, -2361915.0, 0, -10, 3177735.0], scale=None, resampleMethod='aggregate', toaOrSR='TOA', convertToDailyMosaics=True, applyCloudProbability=False, preComputedCloudScoreOffset=None, preComputedTDOMIRMean=None, preComputedTDOMIRStdDev=None, cloudProbThresh=40, overwrite=False, verbose=False, applyCloudScorePlus=True, cloudScorePlusThresh=0.6, cloudScorePlusScore='cs')[source]

Get annual Sentinel-2 composites with cloud/shadow masking.

Deprecated since version Use: superSimpleGetS2() instead for most use cases. It is simpler (fewer parameters), uses the newer Cloud Score Plus product, and returns individual scenes that you composite as needed (including medoid via compositeTimeSeries). This function is retained for workflows that need the all-in-one annual compositing pipeline with temporal buffering, TDOM, or asset export built in.

Wraps getProcessedSentinel2Scenes to retrieve cloud-masked scenes, then composites them into annual (or multi-year buffered) images using compositeTimeSeries. Optionally exports composites to an EE asset.

Parameters:
  • studyArea (ee.Geometry | ee.FeatureCollection) – Area of interest.

  • startYear (int) – First year to include.

  • endYear (int) – Last year to include.

  • startJulian (int) – Start day of year (1-365).

  • endJulian (int) – End day of year (1-365). If < startJulian, the date range wraps across the year boundary.

  • timebuffer (int) – Years to buffer each composite (e.g. 1 means +/- 1 year). Defaults to 0.

  • weights (list[int]) – Temporal weights for buffered compositing. Defaults to [1].

  • compositingMethod (str) – "medoid" or "median". Defaults to "medoid".

  • applyQABand (bool) – Apply the QA60 cloud bitmask. Defaults to False.

  • applyCloudScore (bool) – Apply simple cloud scoring. Defaults to False.

  • applyShadowShift (bool) – Apply shadow-shift detection. Defaults to False.

  • applyTDOM (bool) – Apply Temporal Dark Outlier Mask. Defaults to False.

  • cloudScoreThresh (int) – Cloud score threshold (0-100). Defaults to 20.

  • performCloudScoreOffset (bool) – Per-scene cloud score offset. Defaults to True.

  • cloudScorePctl (int) – Percentile for cloud score offset. Defaults to 10.

  • cloudHeights (ee.List) – Cloud heights in meters. Defaults to ee.List.sequence(500, 10000, 500).

  • zScoreThresh (float) – TDOM z-score threshold. Defaults to -1.

  • shadowSumThresh (float) – TDOM shadow sum threshold. Defaults to 0.35.

  • contractPixels (float) – Pixels to contract mask. Defaults to 1.5.

  • dilatePixels (float) – Pixels to dilate mask. Defaults to 3.5.

  • shadowSumBands (list[str]) – Bands for shadow detection. Defaults to ["nir", "swir1"].

  • correctIllumination (bool) – Reserved for future illumination correction. Defaults to False.

  • correctScale (int) – Scale for illumination correction. Defaults to 250.

  • exportComposites (bool) – Export composites to EE asset. Defaults to False.

  • outputName (str) – Asset name prefix. Defaults to "Sentinel2-Composite".

  • exportPathRoot (str) – Asset folder path. Defaults to "users/username/test".

  • crs (str) – Output CRS. Defaults to "EPSG:5070".

  • transform (list) – Affine transform. Defaults to [10, 0, -2361915.0, 0, -10, 3177735.0].

  • scale (int | None) – Output scale in meters (overrides transform if set). Defaults to None.

  • resampleMethod (str) – Resampling method. Defaults to "aggregate".

  • toaOrSR (str) – "TOA" or "SR". Defaults to "TOA".

  • convertToDailyMosaics (bool) – Mosaic same-day images. Defaults to True.

  • applyCloudProbability (bool) – Apply cloud probability band. Defaults to False.

  • preComputedCloudScoreOffset (ee.Image | None) – Pre-computed offset. Defaults to None.

  • preComputedTDOMIRMean (ee.Image | None) – Pre-computed TDOM mean. Defaults to None.

  • preComputedTDOMIRStdDev (ee.Image | None) – Pre-computed TDOM std dev. Defaults to None.

  • cloudProbThresh (int) – Cloud probability threshold (0-100). Defaults to 40.

  • overwrite (bool) – Overwrite existing exports. Defaults to False.

  • verbose (bool) – Print all parameters. Defaults to False.

  • applyCloudScorePlus (bool) – Apply Cloud Score+ masking. Defaults to True.

  • cloudScorePlusThresh (float) – Cloud Score+ threshold (0-1). Defaults to 0.6.

  • cloudScorePlusScore (str) – "cs" or "cs_cdf". Defaults to "cs".

Returns:

Dictionary with all input args plus:
  • "processedScenes": ee.ImageCollection of masked scenes

  • "processedComposites": ee.ImageCollection of annual composites

Return type:

dict

Example

>>> import geeViz.getImagesLib as gil
>>> study = ee.Geometry.Point([-122.3, 37.5]).buffer(5000)
>>> result = gil.getSentinel2Wrapper(
...     study, 2023, 2023, 152, 273
... )
>>> composites = result['processedComposites']
>>> print(composites.size().getInfo())
1
geeViz.getImagesLib.getTasseledCap(image: Image) Image[source]

Computes the Tasseled Cap transformation using Crist 1985 coefficients.

Applies the 6-component Tasseled Cap transformation for TOA reflectance data using coefficients from Crist (1985).

Parameters:

image (ee.Image) – Input image with bands named ‘blue’, ‘green’, ‘red’, ‘nir’, ‘swir1’, and ‘swir2’.

Returns:

The input image with added ‘brightness’, ‘greenness’,

’wetness’, ‘fourth’, ‘fifth’, and ‘sixth’ bands.

Return type:

ee.Image

Examples

>>> import ee
>>> ee.Initialize()
>>> img = ee.Image('LANDSAT/LC08/C02/T1_TOA/LC08_044034_20200601')
>>> tc = getTasseledCap(img)
>>> print(tc.select(['brightness', 'greenness', 'wetness']).bandNames().getInfo())
geeViz.getImagesLib.getUTMEpsg(location, datum: str = 'WGS84') str[source]

Return the EPSG code string for a UTM zone given a location and datum.

Combines getUTMZone() with a datum lookup to produce the full EPSG code (e.g. "EPSG:32612" for WGS84 UTM Zone 12N).

Parameters:
  • location – One of: - [longitude, latitude] list/tuple (GEE convention: lon first). - ee.Geometry.Point — coordinates are extracted via .getInfo().

  • datum – Datum name. One of "WGS84" (default), "NAD83", "NAD27", "WGS72", "ETRS89", "GDA94", "GDA2020", "SIRGAS2000". Case-insensitive.

Returns:

EPSG code string, e.g. "EPSG:32612".

Raises:

ValueError – If the datum is not recognized or location is not a supported type.

Examples

>>> getUTMEpsg([-113.15, 47.15])
'EPSG:32612'
>>> getUTMEpsg([-113.15, 47.15], datum="NAD83")
'EPSG:26912'
>>> getUTMEpsg([151.21, -33.86])
'EPSG:32756'
>>> getUTMEpsg(ee.Geometry.Point([-113.15, 47.15]))
'EPSG:32612'
geeViz.getImagesLib.getUTMZone(longitude: float) int[source]

Return the UTM zone number (1-60) for a given longitude.

Parameters:

longitude – Longitude in decimal degrees (-180 to 180).

Returns:

UTM zone number (1-60).

Examples

>>> getUTMZone(-113.15)
12
>>> getUTMZone(2.35)
31
geeViz.getImagesLib.harmonizationChastain(img: Image, fromSensor: str, toSensor: str) Image[source]

Harmonizes cross-sensor reflectance using Chastain et al. (2018) coefficients.

Supports pairwise harmonization between MSI (Sentinel-2), OLI (Landsat 8/9), and ETM (Landsat 7) using Model 2 (Major Axis) linear regression coefficients from Chastain et al. (2018).

Parameters:
  • img (ee.Image) – The input image with bands named "blue", "green", "red", "nir", "swir1", "swir2".

  • fromSensor (str) – Source sensor identifier. One of "MSI", "OLI", or "ETM".

  • toSensor (str) – Target sensor identifier. One of "MSI", "OLI", or "ETM".

Returns:

The harmonized image with properties "fromSensor" and "toSensor" set.

Return type:

ee.Image

Examples

>>> oli_img = ee.Image("LANDSAT/LC08/C02/T1_L2/LC08_044034_20200101")
>>> harmonized = harmonizationChastain(oli_img, "OLI", "ETM")
geeViz.getImagesLib.harmonizationRoy(oli: Image) Image[source]

Harmonizes Landsat 8 OLI to Landsat 7 ETM+ using Roy et al. (2016) coefficients.

Applies reduced major axis (RMA) regression coefficients from Roy, D.P. et al. (2016) to transform OLI reflectance to ETM+ equivalent. Operates on the blue, green, red, nir, swir1, and swir2 bands.

Parameters:

oli (ee.Image) – A Landsat 8 OLI image with bands named "blue", "green", "red", "nir", "swir1", "swir2".

Returns:

The image with spectral bands adjusted to ETM+ equivalents.

Return type:

ee.Image

Examples

>>> oli_image = ee.Image("LANDSAT/LC08/C02/T1_L2/LC08_044034_20200101")
>>> harmonized = harmonizationRoy(oli_image)
geeViz.getImagesLib.illuminationCorrection(img, scale, studyArea, bandList=['blue', 'green', 'red', 'nir', 'swir1', 'swir2', 'temp'])[source]

Applies SCSc topographic correction to specified bands of an image.

Uses the Sun-Canopy-Sensor + C (SCSc) method to correct for illumination effects caused by terrain slope and aspect. Requires ‘IC’, ‘cosZ’, ‘cosS’, and ‘slope’ bands (from the first illuminationCorrection overload). Based on code by Patrick Burns and Matt Macander.

Parameters:
  • img (ee.Image) – Input image with ‘IC’, ‘cosZ’, ‘cosS’, ‘slope’, and the bands listed in bandList.

  • scale (float) – Scale in meters for the linear regression reduction.

  • studyArea (ee.Geometry) – Region used for the linear fit regression.

  • bandList (list, optional) – Band names to apply the SCSc correction to. Defaults to ['blue', 'green', 'red', 'nir', 'swir1', 'swir2', 'temp'].

Returns:

The topographically corrected image with original metadata

properties and system:time_start preserved.

Return type:

ee.Image

Examples

>>> import ee
>>> ee.Initialize()
>>> area = ee.Geometry.Point([-122, 37]).buffer(5000)
>>> img = addZenithAzimuth(ee.Image('LANDSAT/LC08/C02/T1_TOA/LC08_044034_20200601'), 'TOA')
>>> img_ic = illuminationCorrection(img, 30, area)
>>> corrected = illuminationCorrection(img_ic, 30, area)
geeViz.getImagesLib.joinCollections(c1, c2, maskAnyNullValues=True, joinProperty='system:time_start', joinPropertySecondary=None)[source]

Joins two image collections by a shared property using an inner join.

Merges bands from matching images in two collections. Images are matched based on an exact match of the specified join property. Optionally masks pixels where any band has a null (zero) value after joining.

Parameters:
  • c1 (ee.ImageCollection) – The primary image collection.

  • c2 (ee.ImageCollection) – The secondary image collection to join.

  • maskAnyNullValues (bool, optional) – If True, masks pixels where any band value is zero after joining. Defaults to True.

  • joinProperty (str, optional) – The property name to match on in the primary collection. Defaults to “system:time_start”.

  • joinPropertySecondary (str | None, optional) – The property name to match on in the secondary collection. If None, uses the same value as joinProperty. Defaults to None.

Returns:

A new collection with bands from both input

collections merged together for each matching image pair.

Return type:

ee.ImageCollection

Examples

>>> import geeViz.getImagesLib as gil
>>> ee = gil.ee
>>> c1 = ee.ImageCollection("MODIS/061/MOD09GQ").filterDate("2024-01-01", "2024-01-10")
>>> c2 = ee.ImageCollection("MODIS/061/MOD09GA").filterDate("2024-01-01", "2024-01-10")
>>> joined = gil.joinCollections(c1, c2)
>>> print(joined.first().bandNames().getInfo())
geeViz.getImagesLib.joinFeatureCollections(primary, secondary, fieldName, fieldNameSecondary=None)[source]

Joins two feature collections by matching property values using an inner join.

Matches features from two collections based on an exact match of the specified field. Retains the geometry of the primary feature and copies all properties from the matching secondary feature.

Parameters:
  • primary (ee.FeatureCollection) – The primary feature collection whose geometry is retained.

  • secondary (ee.FeatureCollection) – The secondary feature collection whose properties are copied to matching features.

  • fieldName (str) – The property name to match on in the primary collection.

  • fieldNameSecondary (str | None, optional) – The property name to match on in the secondary collection. If None, uses the same value as fieldName. Defaults to None.

Returns:

A collection of features with the geometry from

the primary and properties from both collections.

Return type:

ee.FeatureCollection

Examples

>>> import geeViz.getImagesLib as gil
>>> ee = gil.ee
>>> states = ee.FeatureCollection("TIGER/2018/States")
>>> lookup = ee.FeatureCollection([ee.Feature(None, {"STATEFP": "08", "region": "Mountain"})])
>>> joined = gil.joinFeatureCollections(states, lookup, "STATEFP")
geeViz.getImagesLib.landsatCloudScore(img: Image) Image[source]

Computes a cloud score for a Landsat image based on spectral indicators.

Evaluates multiple cloud indicators (blue brightness, visible brightness, IR brightness, temperature, and NDSI) and returns the minimum score. Works across sensors as long as the image uses common band names (blue, green, red, nir, swir1, swir2, temp).

Parameters:

img (ee.Image) – The input image with common band names: blue, green, red, nir, swir1, swir2, and temp.

Returns:

A single-band image named "cloudScore" with values 0-100, where higher values indicate greater cloud likelihood.

Return type:

ee.Image

Examples

>>> import geeViz.getImagesLib as gil
>>> ee = gil.ee
>>> studyArea = gil.testAreas["CA"]
>>> ls = gil.getLandsat(studyArea, "2023-06-01", "2023-09-01", 152, 244)
>>> scored = ls.map(lambda img: img.addBands(gil.landsatCloudScore(img)))
geeViz.getImagesLib.maskCloudsWQA(image)[source]

Masks cloudy pixels using the MODIS state_1km QA band.

Extracts bit 10 (internal cloud algorithm flag) from the ‘state_1km’ band and masks pixels flagged as cloud.

Parameters:

image (ee.Image) – A MODIS image with a ‘state_1km’ QA band (e.g., from MOD09GA).

Returns:

The input image with cloudy pixels masked out.

Return type:

ee.Image

Examples

>>> import ee
>>> ee.Initialize()
>>> modis = ee.Image('MODIS/006/MOD09GA/2020_06_01')
>>> clear = maskCloudsWQA(modis)
geeViz.getImagesLib.maskEmptyPixels(image: Image) Image[source]

Masks pixels that have zero observations in a MODIS-style image.

Checks the ‘num_observations_1km’ band and masks out any pixel where the observation count is zero.

Parameters:

image (ee.Image) – Input image with a ‘num_observations_1km’ band (e.g., a MODIS daily product).

Returns:

The input image with zero-observation pixels masked out.

Return type:

ee.Image

Examples

>>> import ee
>>> ee.Initialize()
>>> modis = ee.Image('MODIS/006/MOD09GA/2020_06_01')
>>> masked = maskEmptyPixels(modis)
geeViz.getImagesLib.maskS2clouds(image: Image) Image[source]

Masks clouds and cirrus in a Sentinel-2 image using the QA60 band.

Uses bits 10 (opaque clouds) and 11 (cirrus) of the QA60 band to create a binary cloud mask.

Parameters:

image (ee.Image) – The input Sentinel-2 image containing a QA60 band.

Returns:

The cloud-masked Sentinel-2 image.

Return type:

ee.Image

Examples

>>> import geeViz.getImagesLib as gil
>>> ee = gil.ee
>>> s2 = ee.ImageCollection("COPERNICUS/S2_HARMONIZED").first()
>>> masked = gil.maskS2clouds(s2)
geeViz.getImagesLib.medoidMosaicMSD(inCollection: ImageCollection, medoidIncludeBands: List | None = None) Image[source]

Creates a medoid mosaic using the Mean Squared Difference (MSD) method.

Calculates the medoid image from an image collection by minimizing the sum of squared differences (Euclidean distance) between each pixel and the collection median.

Parameters:
  • inCollection (ee.ImageCollection) – The input collection to create the mosaic from. Must have consistent band names and data types.

  • medoidIncludeBands (ee.List | None, optional) – Band names to include in the MSD calculation. If None, all bands are used. Defaults to None.

Returns:

The medoid mosaic image, containing all original bands plus

’year’ and ‘julianDay’ bands.

Return type:

ee.Image

Note

Data are not normalized, so bands should have roughly comparable value ranges. If temperature is included alongside reflectance, it may dominate the variance and bias the medoid selection.

Examples

>>> import geeViz.getImagesLib as gil
>>> ee = gil.ee
>>> studyArea = gil.testAreas["CO"]
>>> s2s = gil.superSimpleGetS2(studyArea, "2024-01-01", "2024-12-31", 190, 250)
>>> medoid = gil.medoidMosaicMSD(s2s, ["green", "red", "nir", "swir1", "swir2"])
geeViz.getImagesLib.modisCloudScore(img)[source]

Computes a cloud score (0-100) for a MODIS image.

Combines brightness in visible and infrared bands with a snow index (NDSI) and an optional thermal mask to produce a per-pixel cloud likelihood score. Expects common band names (‘red’, ‘green’, ‘blue’, ‘nir’, ‘swir1’, ‘swir2’, ‘temp’).

Parameters:

img (ee.Image) – Input MODIS image with standard band names.

Returns:

Single-band image named ‘cloudScore’ with values 0-100,

where higher values indicate greater cloud likelihood.

Return type:

ee.Image

Examples

>>> import ee
>>> ee.Initialize()
>>> modis = ee.Image('MODIS/006/MOD09GA/2020_06_01')
>>> cloud = modisCloudScore(modis)
>>> print(cloud.bandNames().getInfo())
geeViz.getImagesLib.nDayComposites(images, startYear, endYear, startJulian, endJulian, compositePeriod)[source]

Creates median composites at regular n-day intervals from an image collection.

Divides the specified date range into equal periods of n days and computes the median composite for each period and year.

Parameters:
  • images (ee.ImageCollection) – The input image collection to composite.

  • startYear (int) – The first year to create composites for.

  • endYear (int) – The last year to create composites for.

  • startJulian (int) – The starting Julian day of year (1-366).

  • endJulian (int) – The ending Julian day of year (1-366).

  • compositePeriod (int) – The number of days per composite period.

Returns:

A collection of median composites, each with

”system:time_start” and “system:index” (formatted as “yyyy-MM-dd”) properties set.

Return type:

ee.ImageCollection

Examples

>>> import geeViz.getImagesLib as gil
>>> ee = gil.ee
>>> modis = ee.ImageCollection("MODIS/061/MOD09GQ").select(["sur_refl_b01", "sur_refl_b02"])
>>> composites = gil.nDayComposites(modis, 2024, 2024, 1, 365, 16)
>>> print(composites.size().getInfo())
geeViz.getImagesLib.newPredict(coeffs, harmonics)[source]

Apply harmonic regression coefficients to predict values for each image.

Uses the coefficient image from newRobustMultipleLinear2 and the harmonic predictor collection from getHarmonics2 to generate predicted values for each dependent variable at each time step.

Parameters:
  • coeffs (ee.Image) – Harmonic regression coefficient image as returned by newRobustMultipleLinear2, with metadata noDependents and modelLength.

  • harmonics (ee.ImageCollection) – Collection with harmonic predictor bands as returned by getHarmonics2, with metadata indBandNames, depBandNames, indBandNumbers, and depBandNumbers.

Returns:

Collection where each image contains the original

dependent bands plus <dep>_predicted bands for each dependent variable.

Return type:

ee.ImageCollection

Examples

>>> import geeViz.getImagesLib as gil
>>> ee = gil.ee
>>> composites = ee.ImageCollection("projects/my-project/assets/composites")
>>> withHarmonics = gil.getHarmonics2(composites, "year", [2])
>>> coeffs = gil.newRobustMultipleLinear2(withHarmonics)
>>> predicted = gil.newPredict(coeffs, withHarmonics)
>>> print(ee.Image(predicted.first()).bandNames().getInfo())
geeViz.getImagesLib.newRobustMultipleLinear2(dependentsIndependents)[source]

Fit a linear regression model across an ImageCollection with labeled bands.

Applies ee.Reducer.linearRegression to a collection that has been prepared by getHarmonics2, returning an image of regression coefficients for each dependent variable.

Parameters:

dependentsIndependents (ee.ImageCollection) – Collection with metadata properties depBandNames, depBandNumbers, indBandNames, and indBandNumbers set (as produced by getHarmonics2).

Returns:

Image of regression coefficients with bands named

<dependent>_intercept, <dependent>_<independent>, etc. Has metadata properties noDependents and modelLength.

Return type:

ee.Image

Examples

>>> import geeViz.getImagesLib as gil
>>> ee = gil.ee
>>> composites = ee.ImageCollection("projects/my-project/assets/composites")
>>> withHarmonics = gil.getHarmonics2(composites, "year", [2])
>>> coeffs = gil.newRobustMultipleLinear2(withHarmonics)
>>> print(coeffs.bandNames().getInfo())
geeViz.getImagesLib.offsetImageDate(img: Image, n: int, unit: str) Image[source]

Offsets the system:time_start property of an image by a specified amount.

Useful for shifting image dates when creating synthetic time series or aligning images from different years.

Parameters:
  • img (ee.Image) – The input Earth Engine image with a "system:time_start" property.

  • n (int) – The number of units to offset. Can be negative to shift backward.

  • unit (str) – The time unit for the offset. One of "year", "month", "week", "day", "hour", "minute", or "second".

Returns:

The image with its "system:time_start" property updated.

Return type:

ee.Image

Examples

>>> img = ee.Image("LANDSAT/LC08/C02/T1_L2/LC08_044034_20200701")
>>> shifted = offsetImageDate(img, -1, "year")
geeViz.getImagesLib.printEE(eeObject, message='')[source]

Asynchronously prints an Earth Engine object by fetching its value in a background thread.

Parameters:
  • eeObject (ee.ComputedObject) – Any Earth Engine object to print (e.g., ee.Image, ee.Number, ee.Dictionary).

  • message (str, optional) – A message to print before the object value. Defaults to "".

Returns:

None

Examples

>>> img = ee.Image("USGS/SRTMGL1_003")
>>> printEE(img.bandNames(), "Band names:")
geeViz.getImagesLib.projectShadows(cloudMask, image, irSumThresh, contractPixels, dilatePixels, cloudHeights, yMult=None)[source]

Projects cloud shadows based on solar geometry and masks them along with clouds.

Uses solar azimuth and zenith angles to cast shadows from a cloud mask at multiple cloud heights, then combines the shadow mask with a dark-pixel test.

Parameters:
  • cloudMask (ee.Image) – A binary cloud mask image (1 = cloud).

  • image (ee.Image) – The input satellite image with bands nir, swir1, swir2 and metadata properties MEAN_SOLAR_AZIMUTH_ANGLE and MEAN_SOLAR_ZENITH_ANGLE.

  • irSumThresh (float) – Threshold for the sum of infrared bands to identify dark pixels (e.g., 0.35).

  • contractPixels (float) – Number of pixels to erode the shadow mask.

  • dilatePixels (float) – Number of pixels to dilate the shadow mask.

  • cloudHeights (ee.List) – List of cloud heights (in meters) to test for shadow projection (e.g., ee.List.sequence(500, 10000, 500)).

  • yMult (int | None, optional) – Multiplier for the Y shadow direction. Automatically determined from projection if None. Defaults to None.

Returns:

The input image with cloud and cloud shadow pixels masked out and a cloudShadowMask band appended.

Return type:

ee.Image

Examples

>>> import geeViz.getImagesLib as gil
>>> ee = gil.ee
>>> heights = ee.List.sequence(500, 10000, 500)
>>> # Typically called via projectShadowsWrapper rather than directly
geeViz.getImagesLib.projectShadowsWrapper(img, cloudThresh=20, irSumThresh=0.35, contractPixels=1.5, dilatePixels=3.5, cloudHeights=<ee.ee_list.List object>)[source]

Wrapper that computes a cloud mask and projects cloud shadows for a Sentinel-2 image.

Combines cloud scoring with shadow projection in a single step. Uses sentinel2CloudScore to generate a cloud mask, then calls projectShadows to find and mask cloud shadows.

Parameters:
  • img (ee.Image) – The input Sentinel-2 image with common band names.

  • cloudThresh (float, optional) – Cloud score threshold (0-100). Pixels above this are considered cloud. Defaults to 20.

  • irSumThresh (float, optional) – IR sum threshold for dark pixel detection. Defaults to 0.35.

  • contractPixels (float, optional) – Erosion kernel size in pixels. Defaults to 1.5.

  • dilatePixels (float, optional) – Dilation kernel size in pixels. Defaults to 3.5.

  • cloudHeights (ee.List, optional) – Cloud heights to test in meters. Defaults to ee.List.sequence(500, 10000, 500).

Returns:

The image with clouds and cloud shadows masked out.

Return type:

ee.Image

Examples

>>> import geeViz.getImagesLib as gil
>>> ee = gil.ee
>>> studyArea = gil.testAreas["CA"]
>>> s2 = gil.getS2(studyArea, "2023-06-01", "2023-09-01", 152, 244)
>>> masked = s2.map(gil.projectShadowsWrapper)
geeViz.getImagesLib.rescale(img: Image, thresholds: tuple) Image[source]

Rescales pixel values in an image using min-max normalization.

Computes (img - min) / (max - min) for linear rescaling. Used internally by cloud scoring functions.

Parameters:
  • img (ee.Image) – The input Earth Engine image (typically single-band).

  • thresholds (tuple[float, float]) – A tuple of (min, max) values for the rescaling range.

Returns:

The rescaled image with values nominally between 0 and 1.

Return type:

ee.Image

Examples

>>> import geeViz.getImagesLib as gil
>>> ee = gil.ee
>>> img = ee.Image.constant(0.2)
>>> rescaled = gil.rescale(img, (0.1, 0.3))
geeViz.getImagesLib.sentinel2CloudScore(img)[source]

Computes a cloud score (0-100) for a Sentinel-2 image.

Adapts the Landsat cloudScore algorithm for Sentinel-2 by combining brightness in blue/cirrus, visible, and infrared bands with an NDSI snow filter. Currently in beta and may need tuning per study area.

Parameters:

img (ee.Image) – Input Sentinel-2 image with bands named ‘blue’, ‘cb’, ‘green’, ‘red’, ‘nir’, ‘swir1’, and ‘swir2’.

Returns:

Single-band image named ‘cloudScore’ with values 0-100,

where higher values indicate greater cloud likelihood.

Return type:

ee.Image

Examples

>>> import ee
>>> ee.Initialize()
>>> s2 = ee.Image('COPERNICUS/S2_SR/20200601T184919_20200601T185630_T10SEG')
>>> cloud = sentinel2CloudScore(s2)
>>> print(cloud.bandNames().getInfo())
geeViz.getImagesLib.sentinel2SnowMask(img, dilatePixels=3.5)[source]

Masks snow-covered pixels in a Sentinel-2 image using NDSI thresholds.

Identifies snow in open land (NDSI > 0.4 and NIR > 0.11) and snow in forest (0.1 < NDSI < 0.4), then masks those pixels. Adapted from ESA training materials (Salomonson and Appel, 2004/2006).

Parameters:
  • img (ee.Image) – Input Sentinel-2 image with ‘green’, ‘swir1’, and ‘nir’ bands.

  • dilatePixels (float, optional) – Number of pixels to erode the snow mask with focal_min to remove edge effects. Defaults to 3.5.

Returns:

The input image with snow pixels masked out.

Return type:

ee.Image

Examples

>>> import ee
>>> ee.Initialize()
>>> s2 = ee.Image('COPERNICUS/S2_SR/20200101T184919_20200101T185630_T10SEG')
>>> snow_free = sentinel2SnowMask(s2, dilatePixels=3.5)
geeViz.getImagesLib.setNoData(image: Image, noDataValue: float) Image[source]

Sets null values for an image, replacing masked pixels with a constant.

Useful for preparing images for export or conversion to arrays where null values are not supported.

Parameters:
  • image (ee.Image) – The input Earth Engine image.

  • noDataValue (float) – The value to assign to null (masked) pixels.

Returns:

The image with null pixels replaced by noDataValue.

Return type:

ee.Image

Examples

>>> img = ee.Image("USGS/SRTMGL1_003")
>>> filled = setNoData(img, -9999)
geeViz.getImagesLib.sieve(image: Image, mmu: float) Image[source]

Performs clumping and elimination (sieving) on a classified image.

Removes patches smaller than the minimum mapping unit by replacing them with the focal mode of surrounding pixels.

Parameters:
  • image (ee.Image) – The input classified Earth Engine image.

  • mmu (float) – The minimum mapping unit in pixels. Patches smaller than this will be replaced by the focal mode.

Returns:

The sieved image with small patches eliminated.

Return type:

ee.Image

Examples

>>> classified = ee.Image("USGS/NLCD/NLCD2019").select("landcover")
>>> sieved = sieve(classified, 5)
geeViz.getImagesLib.simpleAddIndices(in_image: Image) Image[source]

Adds common spectral indices (NDVI, NBR, NDMI, NDSI) to an image.

A lightweight alternative to addIndices that computes only the four most commonly used normalized-difference indices.

Parameters:

in_image (ee.Image) – Input image with bands named ‘nir’, ‘red’, ‘swir1’, ‘swir2’, and ‘green’.

Returns:

The input image with added ‘NDVI’, ‘NBR’, ‘NDMI’, and

’NDSI’ bands.

Return type:

ee.Image

Examples

>>> import ee
>>> ee.Initialize()
>>> img = ee.Image('LANDSAT/LC08/C02/T1_L2/LC08_044034_20200601')
>>> img = simpleAddIndices(img)
>>> print(img.select(['NDVI', 'NBR', 'NDMI', 'NDSI']).bandNames().getInfo())
geeViz.getImagesLib.simpleAddTCAngles(image: Image) Image[source]

Adds the Tasseled Cap brightness-greenness angle as in Powell et al. (2009).

A simplified version of addTCAngles that only computes the tcAngleBG band. See: https://doi.org/10.1016/j.rse.2009.08.016

Parameters:

image (ee.Image) – Input image with ‘brightness’, ‘greenness’, and ‘wetness’ bands (e.g., output of simpleGetTasseledCap).

Returns:

The input image with an added ‘tcAngleBG’ band (angle

normalized by pi).

Return type:

ee.Image

Examples

>>> import ee
>>> ee.Initialize()
>>> img = simpleGetTasseledCap(ee.Image('LANDSAT/LC08/C02/T1_TOA/LC08_044034_20200601'))
>>> img = simpleAddTCAngles(img)
>>> print(img.select('tcAngleBG').bandNames().getInfo())
geeViz.getImagesLib.simpleGetTasseledCap(image: Image) Image[source]

Computes a simplified Tasseled Cap with brightness, greenness, and wetness only.

Uses Crist 1985 TOA reflectance coefficients but returns only the first three components, omitting the fourth through sixth.

Parameters:

image (ee.Image) – Input image with bands named ‘blue’, ‘green’, ‘red’, ‘nir’, ‘swir1’, and ‘swir2’.

Returns:

The input image with added ‘brightness’, ‘greenness’, and

’wetness’ bands.

Return type:

ee.Image

Examples

>>> import ee
>>> ee.Initialize()
>>> img = ee.Image('LANDSAT/LC08/C02/T1_TOA/LC08_044034_20200601')
>>> tc = simpleGetTasseledCap(img)
>>> print(tc.select(['brightness', 'greenness', 'wetness']).bandNames().getInfo())
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 Temporal Dark Outlier Mask (TDOM) to detect and mask cloud shadows.

Identifies dark outlier pixels by comparing each image to the temporal mean and standard deviation. Pixels that are both statistically dark (z-score below threshold) and absolutely dark (IR sum below threshold) are masked.

Parameters:
  • collection (ee.ImageCollection) – The input image collection.

  • zScoreThresh (float, optional) – Z-score threshold for identifying dark outliers. More negative values are more conservative. Defaults to -1.

  • shadowSumThresh (float, optional) – Absolute threshold for the sum of shadow bands. Defaults to 0.35.

  • contractPixels (float, optional) – Erosion kernel size in pixels. Defaults to 1.5.

  • dilatePixels (float, optional) – Dilation kernel size in pixels. Defaults to 3.5.

  • shadowSumBands (list[str], optional) – Band names used for shadow detection. Defaults to ["nir", "swir1"].

  • preComputedTDOMIRMean (ee.Image | None, optional) – Pre-computed temporal mean of shadow bands. Computed from collection if None. Defaults to None.

  • preComputedTDOMIRStdDev (ee.Image | None, optional) – Pre-computed temporal standard deviation. Computed from collection if None. Defaults to None.

Returns:

The collection with dark outlier (shadow) pixels masked out.

Return type:

ee.ImageCollection

Examples

>>> import geeViz.getImagesLib as gil
>>> ee = gil.ee
>>> studyArea = gil.testAreas["CA"]
>>> ls = gil.getLandsat(studyArea, "2023-01-01", "2023-12-31", 152, 244)
>>> shadow_free = gil.simpleTDOM2(ls)
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.smartJoin(primary, secondary, hourDiff)[source]

Joins two image collections by closest timestamp within a time window.

For each image in the primary collection, finds the best-matching image in the secondary collection within the specified time difference and merges their bands together.

Parameters:
  • primary (ee.ImageCollection) – The primary image collection.

  • secondary (ee.ImageCollection) – The secondary image collection to match against.

  • hourDiff (int | float) – Maximum time difference in hours to consider a match between images.

Returns:

The primary collection with bands from the

best-matching secondary image appended to each image.

Return type:

ee.ImageCollection

Examples

>>> import geeViz.getImagesLib as gil
>>> ee = gil.ee
>>> terra = ee.ImageCollection("MODIS/061/MOD09GQ").filterDate("2024-06-01", "2024-06-30")
>>> aqua = ee.ImageCollection("MODIS/061/MYD09GQ").filterDate("2024-06-01", "2024-06-30")
>>> joined = gil.smartJoin(terra, aqua, 24)
geeViz.getImagesLib.spatioTemporalJoin(primary, secondary, hourDiff=24, outKey='secondary')[source]

Joins two image collections by spatial intersection and closest timestamp.

For each image in the primary collection, finds the best-matching image in the secondary collection that both intersects spatially and falls within the specified time window. Bands from the secondary image are renamed with a suffix and appended.

Parameters:
  • primary (ee.ImageCollection) – The primary image collection.

  • secondary (ee.ImageCollection) – The secondary image collection to match against.

  • hourDiff (int | float, optional) – Maximum time difference in hours to consider a match. Defaults to 24.

  • outKey (str, optional) – Suffix appended to secondary band names in the format “bandName_outKey”. Defaults to “secondary”.

Returns:

The primary collection with renamed bands from

the best-matching secondary image appended to each image.

Return type:

ee.ImageCollection

Examples

>>> import geeViz.getImagesLib as gil
>>> ee = gil.ee
>>> modis_terra = ee.ImageCollection("MODIS/061/MOD09GQ").filterDate("2024-01-01", "2024-01-31")
>>> modis_aqua = ee.ImageCollection("MODIS/061/MYD09GQ").filterDate("2024-01-01", "2024-01-31")
>>> joined = gil.spatioTemporalJoin(modis_terra, modis_aqua, hourDiff=12, outKey="aqua")
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]

Retrieve cloud-masked Sentinel-2 imagery — preferred S2 function.

This is the recommended way to get Sentinel-2 data. It uses the Cloud Score Plus product for cloud/shadow masking and returns an ee.ImageCollection of individual scenes (not annual composites). Use .median() or .mosaic() to composite as needed.

For annual composites with medoid compositing, see getSentinel2Wrapper() (legacy, more complex).

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

Note

The spectral values range 0-10000.

>>> 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.synthImage(coeffs, dateImage, indexNames, harmonics, detrend)[source]

Predict band values at a single date using harmonic regression coefficients.

Builds a predictor image from a date value (year.dd format) and the specified harmonics, then multiplies by the regression coefficients to produce a synthetic image for each band.

Parameters:
  • coeffs (ee.Image) – Harmonic regression coefficient image as returned by getHarmonicCoefficientsAndFit (first element of the returned list).

  • dateImage (ee.Image) – Single-band image with year-fraction values (e.g., ee.Image(2021.5)).

  • indexNames (list[str]) – List of band names that were modeled (e.g., ["NDVI", "NBR"]).

  • harmonics (list[int]) – Harmonic numbers used when fitting the model (e.g., [2] or [2, 4]).

  • detrend (bool) – Whether a linear trend term was included in the model.

Returns:

Predicted image with one band per index name.

Return type:

ee.Image

Examples

>>> import geeViz.getImagesLib as gil
>>> ee = gil.ee
>>> studyArea = gil.testAreas["CO"]
>>> result = gil.getLandsatWrapper(studyArea, 2018, 2023, 1, 365)
>>> composites = result["processedComposites"]
>>> coeffs, _ = gil.getHarmonicCoefficientsAndFit(
...     composites, ["NDVI", "NBR"], whichHarmonics=[2])
>>> synth = gil.synthImage(coeffs, ee.Image(2022.5), ["NDVI", "NBR"], [2], False)
>>> print(synth.bandNames().getInfo())
['NDVI', 'NBR']
geeViz.getImagesLib.toDB(img: Image) Image[source]

Converts a Sentinel-1 image from natural (linear power) units to dB.

Applies the formula: 10 * log10(value).

Parameters:

img (ee.Image) – The input Sentinel-1 image in natural (linear power) units.

Returns:

The converted image in dB units.

Return type:

ee.Image

Examples

>>> import geeViz.getImagesLib as gil
>>> ee = gil.ee
>>> natural_img = gil.toNatural(ee.ImageCollection("COPERNICUS/S1_GRD").first())
>>> db_img = gil.toDB(natural_img)
geeViz.getImagesLib.toNatural(img: Image) Image[source]

Converts a Sentinel-1 image from dB to natural (linear power) units.

Applies the formula: 10^(dB / 10).

Parameters:

img (ee.Image) – The input Sentinel-1 image in dB units.

Returns:

The converted image in natural (linear power) units.

Return type:

ee.Image

Examples

>>> import geeViz.getImagesLib as gil
>>> ee = gil.ee
>>> s1 = ee.ImageCollection("COPERNICUS/S1_GRD").first()
>>> natural = gil.toNatural(s1)
geeViz.getImagesLib.uniqueValues(collection: ImageCollection, field: str) List[source]

Finds unique values of a field in an image collection.

Parameters:
  • collection (ee.ImageCollection) – The input Earth Engine image collection.

  • field (str) – The metadata field name to extract unique values from.

Returns:

A list of unique values for the specified field.

Return type:

ee.List

Examples

>>> import geeViz.getImagesLib as gil
>>> ee = gil.ee
>>> col = ee.ImageCollection("LANDSAT/LC08/C02/T1").filterDate("2023-06-01", "2023-06-30")
>>> paths = gil.uniqueValues(col, "WRS_PATH")
geeViz.getImagesLib.wrapDates(startJulian: int, endJulian: int) list[source]

Computes date-wrapping parameters when startJulian > endJulian.

When the compositing window crosses a year boundary (e.g., Oct-Mar), this function returns the offset and which year contains the majority of days, so that year labels are assigned correctly.

Parameters:
  • startJulian (int) – Start day of year (1-365).

  • endJulian (int) – End day of year (1-365).

Returns:

A two-element list [wrapOffset, yearWithMajority].

wrapOffset is 365 if wrapping occurs, else 0. yearWithMajority is 1 if the second calendar year has more days in the window, else 0.

Return type:

list

Examples

>>> wrapDates(250, 100)
[365, 1]
>>> wrapDates(1, 250)
[0, 0]

Analysis Modules

geeViz.changeDetectionLib

Tools for temporal segmentation and change detection algorithms.

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.LANDTRENDRFitMagSlopeDiffCollection(ts, indexName, run_params)[source]
geeViz.changeDetectionLib.LANDTRENDRVertStack(composites, indexName, run_params, startYear, endYear)[source]
geeViz.changeDetectionLib.LTExportPrep(rawLT, multBy=10000)[source]
geeViz.changeDetectionLib.LTLossGainExportPrep(lossGainDict, indexName='Bn', multBy=10000)[source]
geeViz.changeDetectionLib.LT_VT_multBands(img, multBy)[source]
geeViz.changeDetectionLib.LT_VT_vertStack_multBands(img, verdet_or_landtrendr, multBy)[source]
geeViz.changeDetectionLib.VERDETFitMagSlopeDiffCollection(composites, indexName, run_params={'alpha': 0.1, 'tolerance': 0.0001}, maxSegments=10, correctionFactor=1, doLinearInterp='false', masks=None)[source]
geeViz.changeDetectionLib.VERDETVertStack(ts, indexName, run_params={'alpha': 0.1, 'tolerance': 0.0001}, maxSegments=10, correctionFactor=1, doLinearInterp='false')[source]
geeViz.changeDetectionLib.addLossGainToMap(lossGainStack, startYear, endYear, lossMagMin=-8000, lossMagMax=-2000, gainMagMin=1000, gainMagMax=8000, indexName=None, howManyToPull=None)[source]
geeViz.changeDetectionLib.addMillisecondsTimeBand(img)[source]
geeViz.changeDetectionLib.addToImage(img, howMuch)[source]
geeViz.changeDetectionLib.annualizeCCDC(ccdcImg, startYear, endYear, startJulian, endJulian, tEndExtrapolationPeriod, yearStartMonth=9, yearStartDay=1, annualizeWithCompositeDates=False, compositeCollection=None, interpolateCompositeDates=True)[source]
geeViz.changeDetectionLib.applyDistDir_vertStack(stack, distDir, verdet_or_landtrendr)[source]
geeViz.changeDetectionLib.applyLinearInterp(composites, nYearsInterpolate)[source]
geeViz.changeDetectionLib.applyVerdetScaling(ts, indexName, correctionFactor)[source]
geeViz.changeDetectionLib.arrayToTimeSeries(tsArray, yearsArray, possibleYears, bandName)[source]
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.batchSimpleLTFit(ltStacks, startYear, endYear, indexNames=None, bandPropertyName='band', arrayMode=True, maxSegs=6, multBy=1, mosaicReducer=<ee.reducer.Reducer object>)[source]
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.convertStack_To_DurFitMagSlope(stackCollection, VTorLT)[source]
geeViz.changeDetectionLib.convertToLossGain(ltStack, format='rawLandTrendr', lossMagThresh=-0.15, lossSlopeThresh=-0.1, gainMagThresh=0.1, gainSlopeThresh=0.1, slowLossDurationThresh=3, chooseWhichLoss='largest', chooseWhichGain='largest', howManyToPull=2)[source]
geeViz.changeDetectionLib.extractDisturbance(lt, distDir, params, mmu)[source]
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.fitStackToCollection(stack, maxSegments, startYear, endYear)[source]
geeViz.changeDetectionLib.getCCDCSegCoeffs(timeImg, ccdcImg, fillGaps)[source]
geeViz.changeDetectionLib.getFitSlopeCCDC(annualSegCoeffs, startYear, endYear)[source]
geeViz.changeDetectionLib.getLTStack(LTresult, maxVertices, bandNames)[source]
geeViz.changeDetectionLib.getLTvertStack(LTresult, run_params)[source]
geeViz.changeDetectionLib.getLinearFit(c, bandNames=None)[source]
geeViz.changeDetectionLib.getRawAndFittedLT(rawTs, lt, startYear, endYear, indexName='Band', distDir=-1)[source]
geeViz.changeDetectionLib.getSegmentParamsForYear(ccdc, yearImg)[source]
geeViz.changeDetectionLib.getTimeImageCollection(startYear, endYear, startJulian=1, endJulian=365, step=0.1, yearStartMonth=1, yearStartDay=1)[source]
geeViz.changeDetectionLib.getTimeImageCollectionFromComposites(compositeCollection, startYear=None, endYear=None, interpolate=True, useNewInterpMethod=False)[source]
geeViz.changeDetectionLib.landtrendrWrapper(processedComposites, startYear, endYear, indexName, distDir, run_params, distParams, mmu)[source]
geeViz.changeDetectionLib.linearInterp(imgcol, frame=32, nodata=0)[source]
geeViz.changeDetectionLib.multBands(img, distDir, by=1)[source]
geeViz.changeDetectionLib.multLT(rawLT, multBy)[source]
geeViz.changeDetectionLib.new_interp_date(dateYr, dateCollection, max_window=10, dummyImage=None, extrapolate=True)[source]
geeViz.changeDetectionLib.new_interp_date_collection(dateCollection, max_window=20, dummyImage=None, extrapolate=True)[source]
geeViz.changeDetectionLib.nullFinder(img, countMask)[source]
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.predictModel(c, model, bandNames=None)[source]
geeViz.changeDetectionLib.prepTimeSeriesForLandTrendr(ts, indexName, run_params)[source]
geeViz.changeDetectionLib.prepTimeSeriesForVerdet(ts, indexName, run_params, correctionFactor)[source]
geeViz.changeDetectionLib.rawLTToVertices(rawLT, indexName=None, multBy=10000, vertexNoData=-32768)[source]
geeViz.changeDetectionLib.replace_mask(img, newimg, nodata=0)[source]
geeViz.changeDetectionLib.runLANDTRENDR(ts, bandName, run_params=None)[source]
geeViz.changeDetectionLib.simpleCCDCPrediction(img, timeBandName, whichHarmonics, whichBands)[source]
geeViz.changeDetectionLib.simpleCCDCPredictionAnnualized(img, timeBandName, whichBands)[source]
geeViz.changeDetectionLib.simpleCCDCPredictionWrapper(c, timeBandName, whichHarmonics)[source]
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.changeDetectionLib.simpleLTFit(ltStack, startYear, endYear, indexName='bn', arrayMode=True, maxSegs=6, multBy=1)[source]
geeViz.changeDetectionLib.simpleRawLTToVertices(rawLT)[source]
geeViz.changeDetectionLib.thresholdChange(changeCollection, changeThresh, changeDir=None)[source]
geeViz.changeDetectionLib.thresholdZAndTrend(zAndTrendCollection, zThresh, slopeThresh, startYear, endYear, negativeOrPositiveChange=None)[source]
geeViz.changeDetectionLib.toAnnualMedian(images, startYear, endYear)[source]
geeViz.changeDetectionLib.undoVerdetScaling(fitted, indexName, correctionFactor)[source]
geeViz.changeDetectionLib.updateVerdetMasks(img, linearInterpMasks)[source]
geeViz.changeDetectionLib.verdetAnnualSlope(tsIndex, indexName, startYear, endYear, alpha, tolerance=0.0001)[source]
geeViz.changeDetectionLib.yearlySlope(rightYear, fitted)[source]
geeViz.changeDetectionLib.zAndTrendChangeDetection(allScenes, indexNames, nDays, startYear, endYear, startJulian, endJulian, baselineLength=5, baselineGap=1, epochLength=5, zReducer=<ee.reducer.Reducer object>, useAnnualMedianForTrend=True, exportImages=False, exportPathRoot='users/iwhousman/test/ChangeCollection', studyArea=None, scale=30, crs=None, transform=None, minBaselineObservationsNeeded=10)[source]

geeViz.outputLib

The outputLib package provides charting, thumbnails, reports, theming, and basemap utilities for producing publication-ready outputs from Earth Engine data.

geeViz.outputLib.charts

Zonal summary and charting library for Earth Engine. Provides zonal statistics, Plotly charts (time series, bar, donut, scatter), D3 Sankey transition diagrams with gradient-colored links, and auto-detection of thematic vs. continuous data. Use chart_type='sankey' for Sankey charts.

Zonal Summary & Charting Library for GEE

geeViz.outputLib.charts provides a Python pipeline for running zonal statistics on ee.Image / ee.ImageCollection objects and producing Plotly charts (time series, bar, sankey). It mirrors the logic in the geeView JS frontend so that both human users and AI agents have a clean, efficient API for this common workflow.

Quick start:

>>> import geeViz.geeView as gv
>>> from geeViz.outputLib import charts as cl
>>> ee = gv.ee
>>> study_area = ee.Geometry.Polygon(
...     [[[-106, 39.5], [-105, 39.5], [-105, 40.5], [-106, 40.5]]]
... )
>>> lcms = ee.ImageCollection("USFS/GTAC/LCMS/v2024-10")
>>> df, fig = cl.summarize_and_chart(
...     lcms.select(['Land_Cover']),
...     study_area,
...     stacked=True,
... )
>>> print(df.to_markdown())
>>> fig.write_html("chart.html", include_plotlyjs="cdn")

See summarize_and_chart() for the full API and more examples.

geeViz.outputLib.charts.CHART_TYPES = ['bar', 'stacked_bar', 'line', 'line+markers', 'stacked_line', 'stacked_line+markers', 'donut', 'scatter', 'sankey']

Valid chart type strings for chart_type / chart_types parameters. Use these in summarize_and_chart(chart_type=...) or Report.add_section(chart_types=[...]).

geeViz.outputLib.charts.chart_bar(df, colors=None, title='Class Distribution', y_label=None, max_classes=30, chart_type='bar', width=800, height=600, legend_position='right')[source]

Create a Plotly bar chart from a single-Image zonal stats DataFrame.

Automatically chooses horizontal or vertical orientation based on label length.

Parameters:
  • df (pandas.DataFrame) – Output of zonal_stats() for a single Image. Single row, columns = class names.

  • colors (list, optional) – Hex color strings for each bar.

  • title (str, optional) – Chart title.

  • y_label (str, optional) – Value axis label.

  • max_classes (int, optional) – Maximum number of classes to display.

  • width (int, optional) – Chart width in pixels.

  • height (int, optional) – Chart height in pixels.

  • legend_position (dict or str, optional) – Plotly legend layout dict (e.g. {"orientation": "h", "x": 0.5, "y": -0.1}), or "right"/None for the Plotly default.

Returns:

plotly.graph_objects.Figure

Examples

Bar chart of NLCD land cover for a single image:

>>> import geeViz.geeView as gv
>>> from geeViz.outputLib import charts as cl
>>> ee = gv.ee
>>> study_area = ee.Geometry.Polygon(
...     [[[-106, 39.5], [-105, 39.5], [-105, 40.5], [-106, 40.5]]]
... )
>>> nlcd = ee.ImageCollection(
...     "USGS/NLCD_RELEASES/2021_REL/NLCD"
... ).select(['landcover']).mode().set(
...     ee.ImageCollection("USGS/NLCD_RELEASES/2021_REL/NLCD")
...     .first().toDictionary()
... )
>>> info = cl.get_obj_info(nlcd)
>>> df = cl.zonal_stats(nlcd, study_area)
>>> colors = info['class_info']['landcover']['class_palette']
>>> fig = cl.chart_bar(
...     df, colors=colors, title='NLCD Land Cover',
... )
>>> fig.show()
geeViz.outputLib.charts.chart_donut(df, colors=None, title='Class Distribution', max_classes=30, width=800, height=600, legend_position='right', hole=0.45)[source]

Create a Plotly donut chart from a single-Image zonal stats DataFrame.

Only valid for thematic (categorical) data from a single ee.Image. Raises ValueError for continuous data or ee.ImageCollection inputs.

Parameters:
  • df (pandas.DataFrame) – Output of zonal_stats() for a single Image. Single row, columns = class names, values = area/%.

  • colors (list, optional) – Hex colour strings, one per class.

  • title (str, optional) – Chart title.

  • max_classes (int, optional) – Maximum number of classes to display. Smaller classes are grouped into “Other”. Defaults to 30.

  • width (int, optional) – Chart width in pixels.

  • height (int, optional) – Chart height in pixels.

  • legend_position (dict or str, optional) – Plotly legend dict or "right" / "bottom".

  • hole (float, optional) – Size of the centre hole (0–1). Defaults to 0.45.

Returns:

plotly.graph_objects.Figure

geeViz.outputLib.charts.chart_donut_multi_feature(df, colors=None, title='Class Distribution by Feature', max_classes=30, width=800, height=600, columns=2, legend_position='bottom', hole=0.45)[source]

Create a subplot grid of donut charts, one per feature.

For multi-feature reduceRegions output where the DataFrame index is the feature label and columns are class names.

Parameters:
  • df (pandas.DataFrame) – Output of zonal_stats() with feature_label set. Index = feature names, columns = class names, values = area/%.

  • colors (list, optional) – Hex colour strings, one per class.

  • title (str, optional) – Overall chart title.

  • max_classes (int, optional) – Max classes per donut.

  • width (int, optional) – Chart width in pixels.

  • height (int, optional) – Chart height in pixels.

  • columns (int, optional) – Number of subplot columns.

  • legend_position (dict or str, optional) – Legend position.

  • hole (float, optional) – Centre hole size.

Returns:

plotly.graph_objects.Figure

geeViz.outputLib.charts.chart_grouped_bar(df, colors=None, title='Zonal Summary by Feature', y_label=None, chart_type='bar', width=800, height=600, legend_position='right')[source]

Create a grouped (or stacked) bar chart for multi-feature zonal stats.

Each group on the x-axis is a feature (row) and each bar/segment within the group is a class (column). This is the natural chart type when reduceRegions returns one row per zone.

Parameters:
  • df (pandas.DataFrame) – Rows = features (index used as labels), columns = class names, values = numeric area/percentage.

  • colors (list, optional) – Hex color strings, one per column (class).

  • title (str, optional) – Chart title.

  • y_label (str, optional) – Y-axis label.

  • stacked (bool, optional) – Stack bars instead of grouping. Defaults to False.

  • width (int, optional) – Chart width in pixels.

  • height (int, optional) – Chart height in pixels.

  • legend_position (dict or str, optional) – Plotly legend layout dict (e.g. {"orientation": "h", "x": 0.5, "y": -0.1}), or "right"/None for the Plotly default.

Returns:

plotly.graph_objects.Figure

Examples

Compare land cover across the 5 largest MTBS fire perimeters:

>>> import geeViz.geeView as gv
>>> from geeViz.outputLib import charts as cl
>>> ee = gv.ee
>>> lcms = ee.ImageCollection("USFS/GTAC/LCMS/v2024-10")
>>> fires = ee.FeatureCollection(
...     "USFS/GTAC/MTBS/burned_area_boundaries/v1"
... ).sort("BurnBndAc", False).limit(5)
>>> lc_mode = lcms.select(["Land_Cover"]).mode().set(
...     lcms.first().toDictionary()
... )
>>> # summarize_and_chart handles reduceRegions + grouped bar:
>>> df, fig = cl.summarize_and_chart(
...     lc_mode, fires,
...     feature_label="Incid_Name",
...     title="Land Cover — 5 Largest Fires",
...     stacked=True, width=800,
... )
>>> fig.show()
geeViz.outputLib.charts.chart_multi_feature_timeseries(per_feature_dfs, colors=None, chart_type='line+markers', title='Time Series by Feature', x_label='Year', y_label=None, width=800, height=None, columns=2, legend_position='bottom', line_width=2, marker_size=5, max_x_tick_labels=10, max_y_tick_labels=None)[source]

Create a subplot figure with one time-series chart per feature.

Features are arranged in a grid with columns columns (default 2). Each subplot gets height pixels tall (total height scales with number of rows). The legend defaults to "bottom".

Parameters:
  • per_feature_dfs (dict) – {feature_name: DataFrame} from _pivot_multi_feature_timeseries().

  • colors (list, optional) – Hex color strings for each column.

  • chart_type (str, optional) – "line+markers" (default), "line", "bar", "stacked_line", "stacked_line+markers", or "stacked_bar".

  • title (str, optional) – Overall chart title.

  • x_label (str, optional) – X-axis label.

  • y_label (str, optional) – Y-axis label.

  • width (int, optional) – Chart width in pixels.

  • height (int, optional) – Total chart height. When None each subplot gets 400 px.

  • legend_position (dict or str, optional) – Legend layout. Default "bottom".

  • line_width (int or float, optional) – Line width in pixels. Defaults to 2.

  • marker_size (int or float, optional) – Marker diameter in pixels. Defaults to 5.

  • max_x_tick_labels (int, optional) – Maximum number of x-axis tick labels per subplot. Labels are thinned to every 2nd, 5th, 10th, etc. value when exceeded. Defaults to 10. Set to None or 0 to disable.

  • max_y_tick_labels (int, optional) – Maximum number of y-axis tick labels per subplot. Uses Plotly’s nticks. Defaults to None (automatic).

Returns:

plotly.graph_objects.Figure

geeViz.outputLib.charts.chart_sankey_d3(sankey_df, class_names, class_palette, transition_periods, title='Class Transitions', width=800, height=600, node_thickness=20, node_pad=15, opacity=0.9, theme='dark', bg_color=None, font_color=None, hide_toolbar=False)[source]

Create a D3 Sankey diagram directly from transition data — no Plotly.

Builds a self-contained HTML string with native SVG linearGradient elements so each link fades from its source node color to its target node color. Uses d3-sankey for layout.

This is the preferred rendering path for Sankey charts. Unlike chart_sankey() (which builds a Plotly figure that must be post-processed by sankey_to_html() for gradients), this function goes straight from the raw sankey_df to D3 HTML.

Parameters:
  • sankey_df (pandas.DataFrame) – Output of prepare_sankey_data(). Columns: source, target, value, source_name, target_name, source_color, target_color.

  • class_names (list) – List of class names.

  • class_palette (list) – List of hex color strings.

  • transition_periods (list) – Period list (for node labeling).

  • title (str, optional) – Chart title. Defaults to "Class Transitions".

  • width (int, optional) – Chart width in pixels.

  • height (int, optional) – Chart height in pixels.

  • node_thickness (int, optional) – Sankey node bar thickness.

  • node_pad (int, optional) – Padding between Sankey nodes.

  • opacity (float, optional) – Link opacity (0-1). Defaults to 0.9.

  • theme (str, optional) – Theme preset. Defaults to "dark".

  • bg_color (str, optional) – Background color override.

  • font_color (str, optional) – Font color override.

  • hide_toolbar (bool, optional) – Hide the download button.

Returns:

Self-contained HTML string with embedded D3 Sankey chart.

Return type:

str

Examples

>>> sankey_df, matrix_dict = cl.prepare_sankey_data(
...     lcms.select(['Land_Use']), 'Land_Use',
...     transition_periods=[1990, 2005, 2023],
...     class_info=info['class_info'], geometry=study_area,
... )
>>> html = cl.chart_sankey_d3(
...     sankey_df, info['class_info']['Land_Use']['class_names'],
...     info['class_info']['Land_Use']['class_palette'],
...     transition_periods=[1990, 2005, 2023],
... )
geeViz.outputLib.charts.chart_scatter(df, x_band, y_band, feature_label=None, title='Scatter Plot', width=800, height=600, legend_position='right', trendline=True, opacity=0.7, show_labels=None, thematic_col=None, class_names=None, class_palette=None, class_values=None)[source]

Create a scatter plot of two bands across features.

Each point represents one feature (e.g. a county, fire perimeter, or watershed). The x- and y-axes show the mean (or other reduced) value of two image bands over that feature.

When thematic_col is provided, points are colored by the thematic class value in that column, using the class palette and names from image properties.

Parameters:
  • df (pandas.DataFrame) – DataFrame with at least two numeric columns for the x and y bands. Optionally a thematic_col column with integer class values.

  • x_band (str) – Column name for the x-axis.

  • y_band (str) – Column name for the y-axis.

  • feature_label (str, optional) – Name of the index (used in hover).

  • title (str, optional) – Chart title.

  • width (int, optional) – Chart width in pixels.

  • height (int, optional) – Chart height in pixels.

  • legend_position (dict or str, optional) – Legend position.

  • trendline (bool, optional) – Draw a linear trendline. Defaults to True.

  • opacity (float, optional) – Point opacity (0-1). Lower values help visualize overlapping points. Defaults to 0.7.

  • show_labels (bool, optional) – Label each point with the feature name. When None (default), labels are shown only when the DataFrame has fewer than 30 rows.

  • thematic_col (str, optional) – Column containing thematic class values used to color each point. Defaults to None.

  • class_names (list, optional) – Class name strings matching class_values.

  • class_palette (list, optional) – Hex colour strings matching class_values.

  • class_values (list, optional) – Integer class values that map to class_names and class_palette.

Returns:

plotly.graph_objects.Figure

geeViz.outputLib.charts.chart_time_series(df, colors=None, chart_type='line+markers', title='Time Series', x_label='Year', y_label=None, width=800, height=600, label_max_length=30, legend_position='right', line_width=2, marker_size=5, max_x_tick_labels=10, max_y_tick_labels=None)[source]

Create a Plotly time series chart from a zonal stats DataFrame.

Parameters:
  • df (pandas.DataFrame) – Output of zonal_stats() for an ImageCollection. Index = x-axis labels, columns = data series.

  • colors (list, optional) – Hex color strings for each column.

  • chart_type (str, optional) – "line+markers" (default), "line", "bar", "stacked_line", "stacked_line+markers", or "stacked_bar".

  • title (str, optional) – Chart title.

  • x_label (str, optional) – X-axis label.

  • y_label (str, optional) – Y-axis label.

  • width (int, optional) – Chart width in pixels.

  • height (int, optional) – Chart height in pixels.

  • label_max_length (int, optional) – Max characters for legend labels.

  • legend_position (dict or str, optional) – Plotly legend layout dict (e.g. {"orientation": "h", "x": 0.5, "y": -0.1}), or "right"/None for the Plotly default.

  • line_width (int or float, optional) – Line width in pixels for line/scatter traces. Defaults to 2.

  • marker_size (int or float, optional) – Marker diameter in pixels for traces that include markers. Defaults to 5.

  • max_x_tick_labels (int, optional) – Maximum number of x-axis tick labels to display. When the number of x values exceeds this, labels are thinned to every 2nd, 5th, 10th, etc. value. Defaults to 10. Set to None or 0 to disable.

  • max_y_tick_labels (int, optional) – Maximum number of y-axis tick labels. Uses Plotly’s nticks. Defaults to None (automatic).

Returns:

plotly.graph_objects.Figure

Examples

Build a time series chart from a zonal_stats DataFrame:

>>> import geeViz.geeView as gv
>>> from geeViz.outputLib import charts as cl
>>> ee = gv.ee
>>> study_area = ee.Geometry.Polygon(
...     [[[-106, 39.5], [-105, 39.5], [-105, 40.5], [-106, 40.5]]]
... )
>>> lcms = ee.ImageCollection("USFS/GTAC/LCMS/v2024-10")
>>> # Step 1: get the data
>>> info = cl.get_obj_info(lcms.select(['Land_Cover']))
>>> df = cl.zonal_stats(
...     lcms.select(['Land_Cover']), study_area,
... )
>>> # Step 2: chart it with class colors
>>> colors = info['class_info']['Land_Cover']['class_palette']
>>> fig = cl.chart_time_series(
...     df, colors=colors,
...     title='LCMS Land Cover',
...     y_label='% Area',
... )
>>> fig.show()
geeViz.outputLib.charts.detect_geometry_type(geometry)[source]

Determine whether the input geometry represents a single region or multiple.

Parameters:

geometry – An ee.Geometry, ee.Feature, or ee.FeatureCollection.

Returns:

(geo_type, geometry) where geo_type is 'single' or 'multi',

and geometry is an ee.Geometry (single) or ee.FeatureCollection (multi).

Return type:

tuple

geeViz.outputLib.charts.get_obj_info(ee_obj, band_names=None)[source]

Detect the type of a GEE object and read its thematic class metadata.

Parameters:
  • ee_obj (ee.Image or ee.ImageCollection) – The GEE object to inspect.

  • band_names (list, optional) – Override the band names to use.

Returns:

Keys obj_type, band_names, is_thematic, class_info, size.

class_info is {band_name: {class_values, class_names, class_palette}}

Return type:

dict

Examples

Inspect LCMS to see its thematic class metadata:

>>> import geeViz.geeView as gv
>>> from geeViz.outputLib import charts as cl
>>> ee = gv.ee
>>> lcms = ee.ImageCollection("USFS/GTAC/LCMS/v2024-10")
>>> info = cl.get_obj_info(lcms.select(['Land_Cover']))
>>> print(info['is_thematic'])
True
>>> print(info['class_info']['Land_Cover']['class_names'])
['Trees', 'Tall Shrubs & Trees Mix (AK Only)', ...]
geeViz.outputLib.charts.parse_continuous_results(raw_dict, obj_info, x_axis_labels, split_str='----')[source]

Parse continuous (mean/median/etc.) reduction results into a DataFrame.

Parameters:
  • raw_dict (dict) – Output of reduce_region().

  • obj_info (dict) – Output of get_obj_info().

  • x_axis_labels (list) – Labels for the x-axis.

  • split_str (str, optional) – Band name separator.

Returns:

Rows are x-axis labels (or single row), columns are band names.

Return type:

pandas.DataFrame

geeViz.outputLib.charts.parse_thematic_results(raw_dict, obj_info, x_axis_labels, area_format='Percentage', scale=30, split_str='----')[source]

Parse frequency histogram reduction results into a DataFrame with class names as columns.

Parameters:
  • raw_dict (dict) – Output of reduce_region() using frequencyHistogram.

  • obj_info (dict) – Output of get_obj_info().

  • x_axis_labels (list) – Labels for the x-axis (e.g. years).

  • area_format (str, optional) – One of 'Percentage', 'Hectares', 'Acres', 'Pixels'.

  • scale (int, optional) – Pixel scale used in reduction.

  • split_str (str, optional) – Band name separator.

Returns:

Rows are x-axis labels (or a single row for Image),

columns are class names.

Return type:

pandas.DataFrame

geeViz.outputLib.charts.prepare_for_reduction(ee_obj, obj_info, x_axis_property='system:time_start', date_format='YYYY')[source]

Prepare a GEE object for reduction by stacking an ImageCollection into a single multi-band image.

Parameters:
  • ee_objee.Image or ee.ImageCollection.

  • obj_info (dict) – Output of get_obj_info().

  • x_axis_property (str, optional) – Property name to use for x-axis labels.

  • date_format (str, optional) – Earth Engine date format string (e.g. 'YYYY').

Returns:

(stacked_image, stack_band_names, x_axis_labels)

Return type:

tuple

geeViz.outputLib.charts.prepare_sankey_data(ee_collection, band_name, transition_periods, class_info, geometry, scale=30, crs=None, transform=None, tile_scale=4, area_format='Percentage', min_percentage=0.2)[source]

Build a Sankey diagram dataset from class transitions across time periods.

For each consecutive pair of periods, this function: 1. Filters the collection to each period 2. Computes the mode for each period 3. Creates a transition image encoding {from}0990{to} 4. Runs frequencyHistogram to count transitions 5. Parses results into both a source/target/value DataFrame and a

transition matrix DataFrame

Parameters:
  • ee_collection (ee.ImageCollection) – The input collection.

  • band_name (str) – The thematic band to analyze.

  • transition_periods (list) – List of [start_year, end_year] pairs.

  • class_info (dict) – Class info dict for the band (from get_obj_info()).

  • geometryee.Geometry or ee.Feature.

  • scale (int, optional) – Pixel scale in meters.

  • crs (str, optional) – CRS string.

  • transform (list, optional) – Affine transform.

  • tile_scale (int, optional) – Tile scale for parallelism.

  • area_format (str, optional) – Area unit.

  • min_percentage (float, optional) – Minimum percentage threshold for including a flow in the source-target table. The transition matrix always includes all observed transitions regardless of this threshold.

Returns:

(sankey_df, matrix_dict)

  • sankey_df (pandas.DataFrame): Source-target-value table with columns source, target, value, source_name, target_name, source_color, target_color, period. Flows below min_percentage are excluded.

  • matrix_dict (dict[str, pandas.DataFrame]): One transition matrix per consecutive period pair, keyed by "{from_period} {to_period}". Each DataFrame has class names as both row and column labels, with values as converted counts.

Return type:

tuple

Examples

Typically called via summarize_and_chart(chart_type='sankey'), but can be used directly for custom sankey workflows:

>>> import geeViz.geeView as gv
>>> from geeViz.outputLib import charts as cl
>>> ee = gv.ee
>>> study_area = ee.Geometry.Polygon(
...     [[[-106, 39.5], [-105, 39.5], [-105, 40.5], [-106, 40.5]]]
... )
>>> lcms = ee.ImageCollection("USFS/GTAC/LCMS/v2024-10")
>>> info = cl.get_obj_info(lcms.select(['Land_Use']))
>>> sankey_df, matrix_dict = cl.prepare_sankey_data(
...     lcms.select(['Land_Use']),
...     'Land_Use',
...     transition_periods=[[1990, 2000], [2000, 2010], [2010, 2023]],
...     class_info=info['class_info']['Land_Use'],
...     geometry=study_area,
...     scale=30,
... )
>>> print(sankey_df.head().to_markdown())
>>> for label, mdf in matrix_dict.items():
...     print(f"\n{label}")
...     print(mdf.to_markdown())
geeViz.outputLib.charts.reduce_region(image, geometry, reducer, scale=30, crs=None, transform=None, tile_scale=4)[source]

Run image.reduceRegion with sensible defaults.

If both scale and transform are provided, scale is set to None (transform takes precedence in GEE).

Parameters:
  • image (ee.Image) – The image to reduce.

  • geometry – An ee.Geometry or ee.Feature.

  • reducer (ee.Reducer) – The reducer to apply.

  • scale (int, optional) – Pixel scale in meters. Defaults to 30.

  • crs (str, optional) – CRS string. Defaults to None.

  • transform (list, optional) – Affine transform. Defaults to None.

  • tile_scale (int, optional) – Tile scale for parallelism. Defaults to 4.

Returns:

The reduction result dictionary.

Return type:

dict

geeViz.outputLib.charts.reduce_regions(image, features, reducer, scale=30, crs=None, transform=None, tile_scale=4)[source]

Run image.reduceRegions and return the result as a DataFrame.

Parameters:
  • image (ee.Image) – The image to reduce.

  • features (ee.FeatureCollection) – The zones.

  • reducer (ee.Reducer) – The reducer to apply.

  • scale (int, optional) – Pixel scale in meters. Defaults to 30.

  • crs (str, optional) – CRS string. Defaults to None.

  • transform (list, optional) – Affine transform. Defaults to None.

  • tile_scale (int, optional) – Tile scale for parallelism. Defaults to 4.

Returns:

The reduction results.

Return type:

pandas.DataFrame

geeViz.outputLib.charts.sankey_iframe(sankey_html, width=None, height=None)[source]

Wrap sankey D3 HTML in an iframe for Jupyter notebook display.

Jupyter sanitizes <script> tags in display(HTML(...)), so D3 sankey charts must be embedded in an iframe. Uses a data:text/html;base64 src for maximum compatibility across Jupyter environments (classic notebook, JupyterLab, VS Code).

Parameters:
  • sankey_html (str) – Full HTML string from chart_sankey_d3() or summarize_and_chart(chart_type='sankey').

  • width (int, optional) – Iframe width in pixels. Auto-detected from the HTML when None.

  • height (int, optional) – Iframe height in pixels. Auto-detected from the HTML when None.

Returns:

HTML <iframe> element suitable for display(HTML(...)).

Return type:

str

Example

>>> from IPython.display import HTML, display
>>> display(HTML(cl.sankey_iframe(sankey_html)))
geeViz.outputLib.charts.sankey_to_html(fig, full_html=True, include_plotlyjs='https://cdnjs.cloudflare.com/ajax/libs/plotly.js/1.33.1/plotly.min.js', renderer='d3', theme='dark', bg_color=None, font_color=None, hide_toolbar=False)[source]

Return sankey HTML, accepting either a raw HTML string or legacy Plotly figure.

Sankey charts from summarize_and_chart(chart_type='sankey') are now returned as D3 HTML strings directly. This function is kept for backward compatibility — it passes HTML strings through unchanged.

Parameters:
  • fig – D3 HTML string (preferred) or legacy Plotly Figure.

  • full_html (bool) – Ignored for HTML strings.

  • include_plotlyjs – Ignored for HTML strings.

  • renderer (str) – Ignored (always D3).

  • theme – Theme preset for legacy Plotly figures.

  • bg_color – Background color override.

  • font_color – Font/text color override.

  • hide_toolbar (bool) – Hide the download button.

Returns:

HTML string.

Return type:

str

geeViz.outputLib.charts.save_chart_html(fig, filename, include_plotlyjs='https://cdnjs.cloudflare.com/ajax/libs/plotly.js/1.33.1/plotly.min.js', sankey=False, theme='dark', bg_color=None, font_color=None, **kwargs)[source]

Save a chart to an HTML file.

Accepts either a Plotly Figure or an HTML string (from summarize_and_chart(chart_type='sankey')). Applies a theme so all chart types have a consistent look. Works both inside and outside the MCP sandbox.

Parameters:
  • figplotly.graph_objects.Figure or str (D3 sankey HTML from summarize_and_chart(chart_type='sankey')).

  • filename (str) – Output filename (e.g. "chart.html"). In the MCP sandbox, files are saved to generated_outputs/.

  • include_plotlyjs – How to include Plotly.js. Default "cdn".

  • sankey (bool) – Deprecated — ignored. Sankey charts are now returned as HTML strings and detected automatically.

  • theme – Theme preset name, Theme instance, or color string. Default "dark".

  • bg_color – Background color override.

  • font_color – Font/text color override.

Returns:

Path to the saved file.

Return type:

str

Examples

>>> path = cl.save_chart_html(fig, "ndvi_trend.html")
>>> path = cl.save_chart_html(sankey_html, "sankey.html")
>>> path = cl.save_chart_html(fig, "chart.html", theme="light")
geeViz.outputLib.charts.summarize_and_chart(ee_obj, geometry, band_names=None, reducer=None, scale=30, crs=None, transform=None, tile_scale=4, area_format='Percentage', x_axis_property='system:time_start', date_format='YYYY', title=None, chart_type=None, sankey=False, transition_periods=None, sankey_band_name=None, min_percentage=0.2, palette=None, feature_label=None, width=800, height=600, opacity=0.9, legend_position='right', columns=2, include_masked_area=True, stacked=None, thematic_band_name=None, line_width=2, marker_size=5, class_visible=None, max_x_tick_labels=10, max_y_tick_labels=None)[source]

Run zonal statistics and produce a chart in one call.

Orchestrates zonal_stats() (or prepare_sankey_data()) and the appropriate chart function. The chart type is chosen automatically:

  • ee.ImageCollection -> line chart (default "line+markers").

  • ee.Image -> bar chart (default "bar").

  • chart_type=”donut” -> donut chart (Image + thematic only).

  • chart_type=”scatter” -> scatter plot (Image + FeatureCollection only; uses 2 continuous bands as x/y axes, optionally coloured by thematic_band_name).

  • chart_type=”sankey” -> Sankey transition diagram.

  • feature_label + ee.FeatureCollection + ee.Image -> grouped bar or per-feature donut chart.

  • feature_label + ee.FeatureCollection + ee.ImageCollection -> per-feature time series subplots.

Parameters:
  • ee_objee.Image or ee.ImageCollection.

  • geometryee.Geometry, ee.Feature, or ee.FeatureCollection.

  • band_names (list, optional) – Bands to include.

  • reducer (ee.Reducer, optional) – Override the auto-selected reducer.

  • scale (int, optional) – Pixel scale in meters.

  • crs (str, optional) – CRS string.

  • transform (list, optional) – Affine transform.

  • tile_scale (int, optional) – Tile scale for parallelism.

  • area_format (str, optional) – Area unit for thematic data.

  • x_axis_property (str, optional) – Property for x-axis labels.

  • date_format (str, optional) – Date format string.

  • title (str, optional) – Chart title. Auto-generated if None.

  • chart_type (str, optional) – Chart type. One of "bar", "stacked_bar", "donut" (Image + thematic only), "scatter" (Image + FeatureCollection only), "sankey" (ImageCollection + thematic, requires transition_periods), "line", "stacked_line", "line+markers" (default for ImageCollection), or "stacked_line+markers". Defaults to "bar" for single ee.Image, "line+markers" for ee.ImageCollection.

  • stacked (bool, optional) – Deprecated — use chart_type instead. When True, prepends "stacked_" to chart_type. Defaults to None.

  • sankey (bool, optional) – Deprecated — use chart_type='sankey' instead. Still accepted for backward compatibility.

  • transition_periods (list, optional) – Period list for Sankey.

  • sankey_band_name (str, optional) – Band for Sankey analysis.

  • min_percentage (float, optional) – Minimum percentage for Sankey flows.

  • palette (list, optional) – Hex color strings for each series/band. Overrides auto-detected class palette when provided.

  • feature_label (str, optional) – Property name to use as row labels when the geometry is a multi-feature ee.FeatureCollection. Triggers the reduceRegions path. For ee.Image input produces a grouped bar chart; for ee.ImageCollection input produces per-feature time series subplots.

  • width (int, optional) – Chart width in pixels (per cell for multi-feature subplots).

  • height (int, optional) – Chart height in pixels (per cell for multi-feature subplots).

  • opacity (float, optional) – Opacity for Sankey nodes and links (0-1). Defaults to 0.9.

  • legend_position (dict or str, optional) – Plotly legend layout dict for non-Sankey charts (e.g. {"orientation": "h", "x": 0.5, "y": -0.1}), or "right"/None for the Plotly default.

  • columns (int, optional) – Number of subplot columns for multi-feature time series. Total width/height scale to n_cols * width / n_rows * height. Defaults to 2.

  • include_masked_area (bool, optional) – When True (default) and using the histogram reducer, unmasked pixels with value 0 are included so percentages are relative to the total area, not just the unmasked portion. The sentinel class is removed from results.

  • thematic_band_name (str, optional) – For chart_type="scatter" only. Name of a thematic band in the image whose mode value per feature is used to colour each scatter point. The image must carry {band}_class_values, {band}_class_names, and {band}_class_palette properties for the colours and legend entries. Defaults to None (single-colour points).

  • line_width (int or float, optional) – Line width in pixels for time series traces. Defaults to 2.

  • marker_size (int or float, optional) – Marker diameter in pixels for time series traces. Defaults to 5.

  • class_visible (dict, optional) –

    Per-class visibility control. Maps class names to booleans. Classes set to False are toggled off in the chart legend (set to "legendonly"). The traces remain in the figure — users can click the legend to re-enable them. Useful for hiding background, no-data, or stable classes by default. Works for all chart paths including single-geometry, multi-feature time series subplots, and multi-feature bar/donut charts. Example:

    class_visible={
        "Non-Processing Area Mask": False,
        "Stable": False,
        "Background": False,
    }
    

    When None (default), all classes are visible.

  • max_x_tick_labels (int, optional) – Maximum number of x-axis tick labels. When the data has more x values than this, tick labels are thinned to every 2nd, 5th, 10th, etc. value. Defaults to 10. Set to None or 0 to show all.

  • max_y_tick_labels (int, optional) – Maximum number of y-axis tick labels. Passed as Plotly’s nticks. Defaults to None (Plotly automatic).

Returns:

Depends on chart type:

  • Standard (single geometry): (DataFrame, Figure)

  • Sankey: (sankey_df, sankey_html, matrix_dict) where sankey_html is a D3 HTML string (display with display(HTML(cl.sankey_iframe(sankey_html)))), and matrix_dict is {period_label: DataFrame}

  • Multi-feature + ee.Image (bar/donut): (DataFrame, Figure)

  • Multi-feature + ee.ImageCollection: (dict, Figure) where dict is {feature_name: DataFrame}

  • Scatter: (DataFrame, Figure) where the DataFrame has columns for the two bands (and optionally the thematic band)

Return type:

tuple

Examples

Stacked time series of thematic land cover (auto-detects class properties from the image collection):

>>> import geeViz.geeView as gv
>>> from geeViz.outputLib import charts as cl
>>> ee = gv.ee
>>> study_area = ee.Geometry.Polygon(
...     [[[-106, 39.5], [-105, 39.5], [-105, 40.5], [-106, 40.5]]]
... )
>>> lcms = ee.ImageCollection("USFS/GTAC/LCMS/v2024-10")
>>> df, fig = cl.summarize_and_chart(
...     lcms.select(['Land_Cover']),
...     study_area,
...     title='LCMS Land Cover',
...     stacked=True,
... )
>>> print(df.to_markdown())
>>> fig.write_html("lcms_land_cover.html", include_plotlyjs="cdn")

Sankey transition diagram with D3 gradient-colored links:

>>> df, sankey_html, matrix = cl.summarize_and_chart(
...     lcms.select(['Land_Use']),
...     study_area,
...     chart_type='sankey',
...     transition_periods=[1990, 2000, 2024],
...     sankey_band_name='Land_Use',
...     min_percentage=0.5,
... )
>>> # In notebooks: display(HTML(cl.sankey_iframe(sankey_html)))
>>> # Save to file:
>>> cl.save_chart_html(sankey_html, "land_use_transitions.html")

Bar chart for a single image at a point (use ee.Reducer.first()):

>>> nlcd = ee.Image("USGS/NLCD_RELEASES/2021_REL/NLCD/2021")
>>> point = ee.Geometry.Point([-104.99, 39.74])
>>> df, fig = cl.summarize_and_chart(
...     nlcd,
...     point,
...     reducer=ee.Reducer.first(),
...     scale=30,
...     title='NLCD Land Cover',
... )

Continuous time series (non-thematic bands auto-select ee.Reducer.mean()):

>>> import geeViz.getImagesLib as gil
>>> composites = gil.getLandsatWrapper(
...     study_area, 2000, 2024
... )['composites']
>>> df, fig = cl.summarize_and_chart(
...     composites,
...     study_area,
...     band_names=['nir', 'swir1', 'swir2'],
...     title='Spectral Band Means',
...     palette=['D0D', '0DD', 'DD0'],
... )

Grouped bar chart comparing multiple features (uses reduceRegions internally):

>>> fires = ee.FeatureCollection(
...     "USFS/GTAC/MTBS/burned_area_boundaries/v1"
... )
>>> top5 = fires.sort("BurnBndAc", False).limit(5)
>>> lc_mode = lcms.select(["Land_Cover"]).mode().set(
...     lcms.first().toDictionary()
... )
>>> df, fig = cl.summarize_and_chart(
...     lc_mode,
...     top5,
...     feature_label="Incid_Name",
...     title="Land Cover — 5 Largest MTBS Fires",
...     stacked=True,
...     width=800,
... )

Thematic data without class properties — force frequencyHistogram or set properties on-the-fly:

>>> lcpri = ee.ImageCollection(
...     "projects/sat-io/open-datasets/LCMAP/LCPRI"
... ).select(['b1'], ['LC'])
>>> # Force thematic (class values used as labels):
>>> df, fig = cl.summarize_and_chart(
...     lcpri,
...     study_area,
...     reducer=ee.Reducer.frequencyHistogram(),
...     title='LCMAP LC Primary',
... )
>>> # Or set properties for proper names and colors:
>>> lcpri_named = lcpri.map(lambda img: img.set({
...     'LC_class_values': list(range(1, 10)),
...     'LC_class_names': ['Developed', 'Cropland', 'Grass/Shrub',
...         'Tree Cover', 'Water', 'Wetlands', 'Ice/Snow',
...         'Barren', 'Class Change'],
...     'LC_class_palette': ['E60000', 'A87000', 'E3E3C2', '1D6330',
...         '476BA1', 'BAD9EB', 'FFFFFF', 'B3B0A3', 'A201FF'],
... }))
>>> df, fig = cl.summarize_and_chart(
...     lcpri_named, study_area, stacked=True,
... )

Switch area format to hectares or acres:

>>> df_ha, fig_ha = cl.summarize_and_chart(
...     lcms.select(['Land_Cover']),
...     study_area,
...     area_format='Hectares',
...     title='LCMS Land Cover (Hectares)',
... )
geeViz.outputLib.charts.zonal_stats(ee_obj, geometry, band_names=None, reducer=None, scale=30, crs=None, transform=None, tile_scale=4, area_format='Percentage', x_axis_property='system:time_start', date_format='YYYY', include_masked_area=True)[source]

Compute zonal statistics for a GEE Image or ImageCollection over a geometry.

This is the main entry point for the data pipeline. It auto-detects the object type, whether data is thematic or continuous, the appropriate reducer, and the geometry type.

Parameters:
  • ee_objee.Image or ee.ImageCollection.

  • geometryee.Geometry, ee.Feature, or ee.FeatureCollection.

  • band_names (list, optional) – Bands to include. Auto-detected if None.

  • reducer (ee.Reducer, optional) – Override the auto-selected reducer.

  • scale (int, optional) – Pixel scale in meters. Defaults to 30.

  • crs (str, optional) – CRS string.

  • transform (list, optional) – Affine transform.

  • tile_scale (int, optional) – Tile scale for parallelism. Defaults to 4.

  • area_format (str, optional) – Area unit for thematic data. One of 'Percentage', 'Hectares', 'Acres', 'Pixels'.

  • x_axis_property (str, optional) – Property for x-axis labels (ImageCollection).

  • date_format (str, optional) – Date format string for x-axis labels.

Returns:

The zonal statistics table.

Return type:

pandas.DataFrame

Examples

Get just the data (no chart) for an LCMS land cover time series:

>>> import geeViz.geeView as gv
>>> from geeViz.outputLib import charts as cl
>>> ee = gv.ee
>>> study_area = ee.Geometry.Polygon(
...     [[[-106, 39.5], [-105, 39.5], [-105, 40.5], [-106, 40.5]]]
... )
>>> lcms = ee.ImageCollection("USFS/GTAC/LCMS/v2024-10")
>>> df = cl.zonal_stats(
...     lcms.select(['Land_Cover']),
...     study_area,
...     area_format='Percentage',
... )
>>> print(df.to_markdown())

Continuous data with a custom reducer:

>>> df = cl.zonal_stats(
...     lcms.select(['Change_Raw_Probability_Slow_Loss']),
...     study_area,
...     reducer=ee.Reducer.mean(),
... )

geeViz.outputLib.thumbs

Publication-ready thumbnail, GIF, and filmstrip generation from Earth Engine imagery. Includes auto-visualization detection, basemap compositing, scalebar, north arrow, projected CRS support, inset maps, and legend rendering.

Generate Earth Engine thumbnails with automatic visualization handling.

geeViz.outputLib.thumbs provides functions that mirror the auto-visualization logic in geeView and geeViz.outputLib.charts — detecting thematic vs. continuous data, reading *_class_values / *_class_palette image properties, and building appropriate viz params — so you can get publication-ready thumbnail URLs and embeddable HTML <img> tags without manual configuration.

Supports ee.Image (PNG) and ee.ImageCollection (animated GIF or filmstrip), with optional per-feature clipping for ee.FeatureCollection geometries.

Animated GIFs

For ee.ImageCollection inputs, generate_gif() creates properly mosaicked per-time-step frames, with optional date burn-in using system:time_start metadata.

Example:

import geeViz.geeView as gv
from geeViz.outputLib import thumbs as tl

ee = gv.ee
lcms = ee.ImageCollection("USFS/GTAC/LCMS/v2024-10")
area = ee.Geometry.Point([-111.8, 40.7]).buffer(10000)

url = tl.get_thumb_url(lcms.select(["Land_Cover"]).first(), area)
html = tl.embed_thumb(url, title="LCMS Land Cover")

# Animated GIF with date labels
gif_html = tl.generate_gif(
    lcms.select(["Land_Cover"]),
    area,
    burn_in_date=True,
    date_format="YYYY",
)
geeViz.outputLib.thumbs.auto_viz(ee_obj, band_name=None, geometry=None, stretch_type='percentile', percentiles=None, n_stddev=2, gamma=1.6, scale=300, timeout=5)[source]

Build visualization parameters automatically from image properties.

For thematic data (images with {band}_class_values and {band}_class_palette properties) returns a palette-based viz dict mapping class values to colours.

For continuous data:

  • When geometry is provided, delegates to auto_viz_continuous() which samples the region to compute data-driven min/max.

  • Otherwise falls back to hard-coded defaults.

Parameters:
  • ee_obj (ee.Image or ee.ImageCollection) – Earth Engine object to inspect.

  • band_name (str, optional) – Specific band to visualize.

  • geometryee.Geometry, ee.Feature, or ee.FeatureCollection. When provided continuous data is stretched from actual region values.

  • stretch_type (str) – Stretch for continuous data — "percentile" (default), "min-max", or "stddev".

  • percentiles (list[int], optional) – [lower, upper] for percentile stretch. Default [5, 95].

  • n_stddev (float) – Standard deviations for "stddev" stretch.

  • gamma (float, optional) – Gamma correction for continuous data. Values > 1 brighten midtones; < 1 darken. Included in the returned dict as "gamma" when not 1.0. Ignored for thematic data. Defaults to 1.6.

  • scale (int) – Starting scale (m) for reduceRegion.

  • timeout (int) – Timeout (s) per reduceRegion attempt.

Returns:

Visualization parameters suitable for ee.Image.getThumbURL(). For continuous data includes bands, min, max, and gamma (when not 1.0). For thematic data includes bands, min, max, and palette.

Return type:

dict

Example

>>> viz = auto_viz(lcms.select(["Land_Cover"]))
>>> viz["bands"]
['Land_Cover']
>>> viz = auto_viz(s2_composite, geometry=study_area,
...                stretch_type="percentile", percentiles=[2, 98])
>>> viz["gamma"]
1.6
geeViz.outputLib.thumbs.auto_viz_continuous(image, geometry, band_names=None, stretch_type='percentile', percentiles=None, n_stddev=2, gamma=1.6, scale=300, timeout=5, max_scale=None)[source]

Build visualization parameters for a continuous ee.Image by sampling the region.

Performs a reduceRegion at a coarse resolution to compute stretch statistics. If the call times out the scale is doubled and retried until it succeeds or max_scale is exceeded.

Parameters:
  • image (ee.Image) – Image to visualize. Must not be an ee.ImageCollection — reduce the collection first.

  • geometryee.Geometry, ee.Feature, or ee.FeatureCollection defining the region to sample.

  • band_names (list[str], optional) – Bands to visualize — length must be 1 or 3. When None the first 3 bands are used (or first 1 if fewer than 3 exist). Defaults to None.

  • stretch_type (str) – One of "percentile" (default), "min-max", or "stddev".

  • percentiles (list[int], optional) – [lower, upper] percentiles for the "percentile" stretch. Defaults to [0, 95].

  • n_stddev (float) – Number of standard deviations for the "stddev" stretch (symmetric around the mean). Default 2.

  • gamma (float, optional) – Gamma correction applied to the output viz params. Values > 1 brighten midtones (lifts dark pixels without blowing out highlights); values < 1 darken midtones. 1.0 means no correction. Included in the returned dict as "gamma" when not 1.0. Defaults to 1.6.

  • scale (int) – Starting spatial resolution in meters for reduceRegion. Default 300.

  • timeout (int) – getInfo timeout in seconds per attempt. Default 5.

  • max_scale (int, optional) – Stop retrying when scale exceeds this value. Default is scale * 16 (4 doublings).

Returns:

Visualization parameters with bands, min, max keys, and gamma when gamma is not 1.0. min / max are scalars for single-band images and lists for 3-band images.

Return type:

dict

Raises:
  • TypeError – If image is an ee.ImageCollection.

  • ValueError – If band_names length is not 1 or 3, or if stretch_type is unrecognised.

Example

>>> viz = auto_viz_continuous(
...     s2_composite, study_area,
...     band_names=["swir2", "nir", "red"],
...     stretch_type="percentile", percentiles=[0, 99],
... )
>>> sorted(viz.keys())
['bands', 'gamma', 'max', 'min']
>>> viz["gamma"]
1.6
geeViz.outputLib.thumbs.download_thumb(url, timeout=120)[source]

Download raw image bytes from an Earth Engine thumbnail URL.

Fetches the PNG or GIF data from a URL returned by ee.Image.getThumbURL() or ee.ImageCollection.getVideoThumbURL().

Parameters:
  • url (str) – Thumbnail URL from getThumbURL() or getVideoThumbURL().

  • timeout (int, optional) – HTTP request timeout in seconds. Defaults to 120.

Returns:

Raw image data (PNG or GIF format).

Return type:

bytes

Example

>>> data = download_thumb("https://earthengine.googleapis.com/...")
>>> len(data) > 0
True
geeViz.outputLib.thumbs.embed_thumb(url, title='', width=None, download=False)[source]

Generate an embeddable HTML <figure> element for a thumbnail.

Wraps a thumbnail URL (or base64 data URI) in an HTML <figure> with an <img> tag and optional <figcaption>. When download is True the image bytes are fetched and embedded inline as a base64 data URI so the resulting HTML is fully self-contained.

Parameters:
  • url (str) – Thumbnail URL from getThumbURL() or a data:image/... base64 data URI.

  • title (str, optional) – Alt text and caption for the image. Defaults to "".

  • width (int, optional) – CSS width in pixels applied via an inline style. Defaults to None (natural size).

  • download (bool, optional) – Download the image from url and embed it as a base64 data URI for self-contained HTML. Defaults to False (reference the URL directly).

Returns:

HTML string containing a <figure> with <img> and optional <figcaption> elements.

Return type:

str

Example

>>> html = embed_thumb(
...     "https://earthengine.googleapis.com/...",
...     title="Study Area", width=400,
... )
>>> "<img" in html
True
geeViz.outputLib.thumbs.embed_thumb_grid(thumb_results, columns=3, thumb_width=300, download=False)[source]

Generate an HTML CSS-grid layout of multiple thumbnails.

Takes a list of per-feature thumbnail results (from get_thumb_urls_by_feature() or get_thumb_urls_by_feature_parallel()) and assembles them into a responsive CSS grid <div> with labeled <figure> elements.

Parameters:
  • thumb_results (list[dict]) – List of thumbnail result dictionaries, each containing "label" (str) and "url" (str) keys.

  • columns (int, optional) – Number of grid columns. Defaults to 3.

  • thumb_width (int, optional) – Display width in pixels for each thumbnail image. Defaults to 300.

  • download (bool, optional) – Download each image and embed as base64 for self-contained HTML. Defaults to False.

Returns:

HTML string containing a <div> with CSS grid styling and one <figure> per thumbnail.

Return type:

str

Example

>>> results = get_thumb_urls_by_feature_parallel(image, counties)
>>> grid_html = embed_thumb_grid(results, columns=4, thumb_width=250)
>>> "thumb-grid" in grid_html
True
geeViz.outputLib.thumbs.generate_filmstrip(ee_obj, geometry, viz_params=None, band_name=None, dimensions=640, max_frames=50, columns=3, date_format='YYYY', burn_in_legend=True, legend_scale=1.0, legend_position='bottom', bg_color=None, font_color=None, font_outline_color=None, output_path=None, crs='EPSG:3857', transform=None, scale=None, margin=16, basemap=None, overlay_opacity=None, scalebar=True, scalebar_units='metric', north_arrow=True, north_arrow_style='solid', inset_map=True, inset_basemap=None, inset_scale=0.3, inset_on_map=False, title=None, burn_in_geometry=False, geometry_outline_color=None, geometry_fill_color=None, geometry_outline_weight=2, clip_to_geometry=True, geometry_legend_label='Study Area', title_font_size=18, label_font_size=12)[source]

Generate a filmstrip grid image from an Earth Engine ImageCollection.

Downloads individual frame thumbnails, mosaics tiled collections by date, labels each frame with its date, and arranges them in a grid layout. Optionally composites a basemap behind the EE data and appends cartographic elements including a legend panel, scalebar, north arrow, inset overview map, and title strip.

Parameters:
  • ee_obj (ee.ImageCollection) – Image collection to render.

  • geometry (ee.Geometry or ee.Feature or ee.FeatureCollection) – Region to clip and bound each frame.

  • viz_params (dict, optional) – Visualization parameters (bands, min, max, palette). Auto-detected via auto_viz() when None. Defaults to None.

  • band_name (str, optional) – Band to visualize when using auto-detection. Defaults to None (first band).

  • dimensions (int, optional) – Width per frame in pixels. Defaults to 640.

  • max_frames (int, optional) – Maximum number of frames to include in the grid. Defaults to 50.

  • columns (int, optional) – Number of columns in the grid layout. Defaults to 3.

  • date_format (str, optional) – Date label format above each frame. Supports "YYYY", "YYYY-MM", "YYYY-MM-dd", "MMM YYYY", etc. Defaults to "YYYY".

  • burn_in_legend (bool, optional) – Append a legend panel for thematic data. Only rendered when class names and palette are available. Defaults to True.

  • legend_scale (float, optional) – Scale multiplier for legend size. Defaults to 1.0.

  • legend_position (str, optional) – Where to place the legend relative to the grid – "bottom" or "top". Defaults to "bottom".

  • bg_color (str or None, optional) – Background color for the grid, margins, and legend panel. Resolved via theme when None. Defaults to None.

  • font_color (str or tuple or None, optional) – Text color for date labels and legend text. Resolved via theme when None. Defaults to None.

  • font_outline_color (str or tuple or None, optional) – Outline / halo color for text readability. Auto-derived when None. Defaults to None.

  • output_path (str, optional) – File path to save the PNG. Parent directories are created automatically. Defaults to None (not saved).

  • crs (str, optional) – CRS code (e.g. "EPSG:4326"). Applies setDefaultProjection to each frame. Defaults to None.

  • transform (list, optional) – Affine transform as a 6-element list. Requires crs. Defaults to None.

  • scale (float, optional) – Nominal pixel scale in meters. Requires crs. Defaults to None.

  • margin (int, optional) – Pixel margin on all sides of the final image. Defaults to 16.

  • basemap (str or dict or None, optional) – Basemap to composite behind each frame. A preset name (e.g. "esri-satellite"), a config dict, or a raw tile URL. Defaults to None (no basemap).

  • overlay_opacity (float or None, optional) – Opacity of the EE overlay when a basemap is present (0.0 – 1.0). Defaults to None (auto: 0.8 with basemap, 1.0 without).

  • scalebar (bool, optional) – Include a scalebar below the grid. Only rendered when cartographic context is available. Defaults to True.

  • scalebar_units (str, optional) – Unit system for the scalebar – "metric" or "imperial". Defaults to "metric".

  • north_arrow (bool, optional) – Include a north arrow below the grid. Defaults to True.

  • north_arrow_style (str, optional) – Arrow style – "solid", "classic", or "outline". Defaults to "solid".

  • inset_map (bool, optional) – Include an inset overview map below the grid. Defaults to True.

  • inset_basemap (str or dict or None, optional) – Basemap for the inset. Falls back to basemap when None. Defaults to None.

  • inset_scale (float, optional) – Relative height of the inset compared to the frame height. Defaults to 0.3.

  • inset_on_map (bool, optional) – Place the inset on the map rather than as a separate strip. For filmstrips this controls positioning in the bottom strip area. Defaults to True.

  • title (str, optional) – Title text rendered as a strip above the grid. Defaults to None (no title).

Returns:

A dictionary with the following keys:

  • "html" (str): HTML <figure> element containing the filmstrip as a base64-embedded PNG <img> tag.

  • "thumb_bytes" (bytes): Raw PNG byte data.

Return type:

dict

Raises:

ValueError – If transform or scale is provided without crs.

Example

>>> result = generate_filmstrip(
...     lcms.select(["Land_Cover"]),
...     study_area,
...     columns=4,
...     date_format="YYYY",
...     basemap="esri-satellite",
...     title="LCMS Land Cover Time Series",
... )
>>> png_bytes = result["thumb_bytes"]
geeViz.outputLib.thumbs.generate_gif(ee_obj, geometry, viz_params=None, band_name=None, dimensions=640, fps=2, max_frames=50, burn_in_date=True, date_format='YYYY', date_position='upper-left', date_font_size=None, burn_in_legend=True, legend_scale=1.0, bg_color=None, font_color=None, font_outline_color=None, output_path=None, crs='EPSG:3857', transform=None, scale=None, margin=16, basemap=None, overlay_opacity=None, scalebar=True, scalebar_units='metric', north_arrow=True, north_arrow_style='solid', inset_map=True, inset_basemap=None, inset_scale=0.3, inset_on_map=True, title=None, title_font_size=18, label_font_size=12, burn_in_geometry=False, geometry_outline_color=None, geometry_fill_color=None, geometry_outline_weight=2, clip_to_geometry=True)[source]

Generate an animated GIF from an Earth Engine ImageCollection.

Downloads individual frame thumbnails, properly mosaics tiled collections (LCMS, NLCD, etc.) by time step, and composites them into an animated GIF. Optional cartographic elements include date burn-in, thematic legend panel, basemap underlay, scalebar, north arrow, inset overview map, and title strip.

Parameters:
  • ee_obj (ee.ImageCollection) – Image collection to animate.

  • geometry (ee.Geometry or ee.Feature or ee.FeatureCollection) – Region to clip and bound each frame.

  • viz_params (dict, optional) – Visualization parameters (bands, min, max, palette). Auto-detected via auto_viz() when None. Defaults to None.

  • band_name (str, optional) – Band to visualize when using auto-detection. Defaults to None (first band).

  • dimensions (int, optional) – Width of each frame in pixels. Defaults to 640.

  • fps (int, optional) – Frames per second in the output GIF. Defaults to 2.

  • max_frames (int, optional) – Maximum number of frames to include. Defaults to 50.

  • burn_in_date (bool, optional) – Burn the date label from system:time_start into each frame. Defaults to True.

  • date_format (str, optional) – Date format string. Supported values include "YYYY", "YYYY-MM", "YYYY-MM-dd", "MMM YYYY", "MMMM YYYY", "MM/YYYY", "MM/dd/YYYY". Defaults to "YYYY".

  • date_position (str, optional) – Position of the date label on each frame – "upper-left", "upper-right", "lower-left", or "lower-right". Defaults to "upper-left".

  • date_font_size (int, optional) – Font size in pixels for the date label. Auto-scaled from dimensions when None. Defaults to None.

  • burn_in_legend (bool, optional) – Append a legend panel to the right side of each frame for thematic data. Only rendered when class names and palette are available in image properties. Defaults to True.

  • legend_scale (float, optional) – Scale multiplier for the legend panel size. Defaults to 1.0.

  • bg_color (str or None, optional) – Background color for transparent areas, legend panel, and margins. Accepts CSS color names or hex strings. Resolved via theme when None. Defaults to None.

  • font_color (str or tuple or None, optional) – Text color for date labels and legend text. Resolved via theme when None. Defaults to None.

  • font_outline_color (str or tuple or None, optional) – Outline / halo color for text readability. Auto-derived to contrast with font_color when None. Defaults to None.

  • output_path (str, optional) – File path to save the GIF to disk. Parent directories are created automatically. Defaults to None (not saved).

  • crs (str, optional) – CRS code (e.g. "EPSG:4326"). Applies setDefaultProjection to each frame. Defaults to None.

  • transform (list, optional) – Affine transform as a 6-element list. Requires crs. Defaults to None.

  • scale (float, optional) – Nominal pixel scale in meters. Requires crs. Defaults to None.

  • margin (int, optional) – Pixel margin on all sides of each frame. Defaults to 16.

  • basemap (str or dict or None, optional) – Basemap to composite behind the EE data. A preset name (e.g. "esri-satellite", "usfs-topo"), a config dict with type and url keys, or a raw tile URL template. Defaults to None (no basemap).

  • overlay_opacity (float or None, optional) – Opacity of the EE overlay when a basemap is present (0.0 – 1.0). Defaults to None (auto: 0.8 with basemap, 1.0 without).

  • scalebar (bool, optional) – Draw a scalebar on each frame. Only rendered when basemap or inset_basemap is set and bounds are available. Defaults to True.

  • scalebar_units (str, optional) – Unit system for the scalebar – "metric" or "imperial". Defaults to "metric".

  • north_arrow (bool, optional) – Draw a north arrow on each frame. Defaults to True.

  • north_arrow_style (str, optional) – Arrow style – "solid", "classic", or "outline". Defaults to "solid".

  • inset_map (bool, optional) – Include an inset overview map. Defaults to True.

  • inset_basemap (str or dict or None, optional) – Basemap for the inset. Falls back to basemap when None. Defaults to None.

  • inset_scale (float, optional) – Relative height of the inset compared to the frame height. Defaults to 0.3.

  • inset_on_map (bool, optional) – Place the inset directly on the map (lower-right) rather than below it. Defaults to True.

  • title (str, optional) – Title text rendered as a strip above the GIF frames. Defaults to None (no title).

Returns:

A dictionary with the following keys:

  • "html" (str): HTML <figure> element containing the GIF as a base64-embedded <img> tag.

  • "gif_bytes" (bytes): Raw animated GIF byte data.

Return type:

dict

Raises:

ValueError – If transform or scale is provided without crs.

Example

>>> result = generate_gif(
...     lcms.select(["Land_Cover"]),
...     study_area,
...     burn_in_date=True,
...     date_format="YYYY",
...     basemap="esri-satellite",
...     title="LCMS Land Cover",
... )
>>> gif_bytes = result["gif_bytes"]
>>> html_snippet = result["html"]
geeViz.outputLib.thumbs.generate_map_chart(ee_obj, geometry, viz_params=None, band_name=None, dimensions=640, bg_color=None, font_color=None, font_outline_color=None, output_path=None, crs='EPSG:3857', transform=None, scale=None, margin=16, basemap=None, overlay_opacity=None, scalebar=True, scalebar_units='metric', north_arrow=True, north_arrow_style='solid', inset_map=True, inset_basemap=None, inset_scale=0.25, title=None, chart_type=None, chart_scale=30, area_format='Percentage', chart_height=None, legend_position='right', include_masked_area=True, burn_in_geometry=True, burn_in_legend=True, title_font_size=18, label_font_size=12, geometry_outline_color=None, geometry_fill_color=None, geometry_outline_weight=2, clip_to_geometry=True, feature_label=None, columns=2, thumb_width=None, band_names=None, thematic_band_name=None, opacity=0.7, layout='side-by-side')[source]

Generate a combined map + chart output.

For ee.Image inputs, produces a static PNG with a map thumbnail beside (or above) a chart. For ee.ImageCollection inputs, automatically delegates to generate_map_chart_gif() and returns an animated GIF with cumulative time-series charts.

The title appears once on the combined output — the chart itself has no title. For thematic data the legend appears on the map thumbnail only (not duplicated on the chart).

Supports:

  • ee.Image + single geometry (ee.Geometry / ee.Feature) with thematic data -> map + bar or donut chart

  • ee.Image + single geometry with continuous data -> map + horizontal bar chart of band means

  • ee.Image + multi-feature ee.FeatureCollection with thematic data -> per-feature map grid + grouped/stacked bar or per-feature donut chart

  • ee.Image + multi-feature FC with chart_type="scatter" -> map of bounding region with sample points burned in + scatter plot (optionally coloured by thematic_band_name)

  • ee.ImageCollection + any geometry -> delegates to generate_map_chart_gif(), returning gif_bytes

Parameters:
  • ee_objee.Image or ee.ImageCollection.

  • geometryee.Geometry, ee.Feature, or ee.FeatureCollection.

  • viz_params (dict, optional) – Visualization parameters for the map thumbnail. Auto-detected via auto_viz() when None.

  • band_name (str, optional) – Band to visualize on the map.

  • dimensions (int, optional) – Map thumbnail width in pixels. Defaults to 640.

  • bg_color (str, optional) – Background colour. Dark theme when None.

  • font_color (str or tuple, optional) – Font colour override.

  • font_outline_color (str or tuple, optional) – Font outline.

  • output_path (str, optional) – Save output to this path.

  • crs (str, optional) – Output CRS (e.g. "EPSG:5070"). Defaults to "EPSG:3857".

  • transform (list, optional) – CRS transform.

  • scale (int, optional) – Pixel scale in metres.

  • margin (int, optional) – Margin around the output in pixels.

  • basemap (str or dict, optional) – Basemap preset name (e.g. "esri-satellite") or config dict.

  • overlay_opacity (float, optional) – Opacity of EE data over basemap. Default 0.8 when basemap is set.

  • scalebar (bool, optional) – Draw scalebar. Defaults to True.

  • scalebar_units (str, optional) – "metric" or "imperial".

  • north_arrow (bool, optional) – Draw north arrow. Defaults to True.

  • north_arrow_style (str, optional) – Arrow style.

  • inset_map (bool, optional) – Show inset overview map.

  • inset_basemap – Basemap for inset.

  • inset_scale (float, optional) – Inset size as fraction of frame.

  • title (str, optional) – Title displayed once above the combined map + chart output.

  • chart_type (str, optional) – "bar" (default for Image), "stacked_bar", "donut", "scatter", or any time-series type ("line+markers", etc.). None auto-detects: "bar" for Image, "line+markers" for ImageCollection.

  • chart_scale (int, optional) – Scale in metres for zonal stats reduceRegion. Defaults to 30.

  • area_format (str, optional) – "Percentage" (default), "Hectares", "Acres", or "Pixels".

  • chart_height (int, optional) – Chart height in pixels. Defaults to map height for side-by-side, map width for stacked.

  • legend_position (str or dict, optional) – Chart legend position. Suppressed automatically for thematic data when burn_in_legend=True (legend on thumb only).

  • include_masked_area (bool, optional) – Include masked pixels in area totals. Defaults to True.

  • burn_in_geometry (bool, optional) – Paint geometry boundary on map frames. Defaults to True.

  • burn_in_legend (bool, optional) – Add legend panel to the map thumbnail. Defaults to True.

  • title_font_size (int, optional) – Title font size. Default 18.

  • label_font_size (int, optional) – Label font size. Default 12.

  • geometry_outline_color (str, optional) – Boundary colour.

  • geometry_fill_color (str, optional) – Boundary fill (hex+alpha).

  • geometry_outline_weight (int, optional) – Boundary width.

  • clip_to_geometry (bool, optional) – Mask data outside boundary.

  • feature_label (str, optional) – FC property name for per-feature labels (multi-feature mode).

  • columns (int, optional) – Columns for multi-feature grid or multi-feature donut subplot layout. Defaults to 2.

  • thumb_width (int, optional) – Per-feature thumbnail width.

  • band_names (list[str], optional) – Bands for scatter x/y axes. Uses first two image bands when None.

  • thematic_band_name (str, optional) – Thematic band name for colouring scatter points by class. The image must carry {band}_class_values/names/palette properties.

  • opacity (float, optional) – Point opacity for scatter charts. Defaults to 0.7.

  • layout (str, optional) – "side-by-side" (default) places the chart to the right of the map. "stacked" places the chart below the map.

Returns:

For ee.Image inputs:

{"html": str, "thumb_bytes": bytes, "df": DataFrame, "fig": Figure}. For ee.ImageCollection inputs (delegated to GIF): {"html": str, "gif_bytes": bytes}.

Return type:

dict

geeViz.outputLib.thumbs.generate_map_chart_gif(ee_obj, geometry, viz_params=None, band_name=None, dimensions=640, fps=2, max_frames=50, date_format='YYYY', bg_color=None, font_color=None, font_outline_color=None, output_path=None, crs='EPSG:3857', transform=None, scale=None, margin=16, basemap=None, overlay_opacity=None, scalebar=True, scalebar_units='metric', north_arrow=True, north_arrow_style='solid', inset_map=True, inset_basemap=None, inset_scale=0.25, title=None, chart_type='line+markers', chart_scale=30, area_format='Percentage', chart_height=None, legend_position='bottom', include_masked_area=True, burn_in_geometry=True, title_font_size=18, label_font_size=12, geometry_outline_color=None, geometry_fill_color=None, geometry_outline_weight=2, clip_to_geometry=True)[source]

Generate an animated GIF with map thumbnails and cumulative line charts.

Each frame shows a map thumbnail for one time step above a chart that accumulates data from the first year up to the current year. The chart’s x-axis spans the full time range so the frame-to-frame progression is visually stable. A legend is placed below the chart.

This mirrors the layout of https://storage.googleapis.com/lcms-gifs/San_Juan_NF_Land_Cover.gif.

Parameters:
  • ee_obj (ee.ImageCollection) – Multi-temporal image collection.

  • geometryee.Geometry, ee.Feature, or ee.FeatureCollection.

  • viz_params (dict, optional) – Viz params for the map thumbnails. Auto-detected when None.

  • band_name (str, optional) – Band to visualize.

  • dimensions (int) – Map thumbnail width in pixels.

  • fps (int) – Frames per second.

  • max_frames (int) – Max number of frames.

  • date_format (str) – Date format for labels (e.g. "YYYY").

  • bg_color – Background colour.

  • font_color – Font colour.

  • font_outline_color – Font outline colour.

  • output_path (str, optional) – Save GIF to this path.

  • crs – Projection params for thumbnails.

  • transform – Projection params for thumbnails.

  • scale – Projection params for thumbnails.

  • margin (int) – Margin in pixels.

  • basemap – Basemap preset for map thumbnails.

  • overlay_opacity (float) – Opacity of EE data over basemap.

  • scalebar (bool) – Draw scalebar on map.

  • scalebar_units (str) – "metric" or "imperial".

  • north_arrow (bool) – Draw north arrow on map.

  • north_arrow_style (str) – Arrow style.

  • title (str, optional) – Title above the map.

  • chart_type (str) – Chart type for the time series. Default "line+markers".

  • chart_scale (int) – Scale in metres for reduceRegion.

  • area_format (str) – "Percentage", "Hectares", "Acres".

  • chart_height (int, optional) – Chart height in pixels. Default is dimensions * 0.6.

  • legend_position (str or dict) – Legend placement on chart.

Returns:

{"html": str, "gif_bytes": bytes}

Return type:

dict

geeViz.outputLib.thumbs.generate_thumbs(ee_obj, geometry, viz_params=None, band_name=None, dimensions=640, feature_label=None, max_features=6, columns=3, thumb_width=300, burn_in_legend=True, legend_scale=1.0, bg_color=None, font_color=None, font_outline_color=None, output_path=None, crs='EPSG:3857', transform=None, scale=None, margin=16, basemap=None, overlay_opacity=None, scalebar=True, scalebar_units='metric', north_arrow=True, north_arrow_style='solid', inset_map=True, inset_basemap=None, inset_scale=0.3, inset_on_map=False, title=None, burn_in_geometry=False, geometry_outline_color=None, geometry_fill_color=None, geometry_outline_weight=2, clip_to_geometry=True, geometry_legend_label='Study Area', title_font_size=18, label_font_size=12)[source]

Generate a publication-ready thumbnail PNG for a report section.

Provides an all-in-one workflow: auto-viz detection, thumbnail URL generation, image download, basemap compositing, and optional cartographic embellishments (legend, scalebar, north arrow, inset map, title).

For ee.FeatureCollection geometries with multiple features, produces a labeled grid of per-feature thumbnails. For single geometries, produces a single thumbnail with optional cartographic elements.

For ee.ImageCollection input, the collection is reduced to a single representative image using the temporal mode (thematic data) or median (continuous data).

Parameters:
  • ee_obj (ee.Image or ee.ImageCollection) – Image to thumbnail. Collections are reduced to a single representative image.

  • geometry (ee.Geometry or ee.Feature or ee.FeatureCollection) – Region to clip and bound the thumbnail. When a FeatureCollection with multiple features is provided, a per-feature grid is generated instead.

  • viz_params (dict, optional) – Visualization parameters (bands, min, max, palette). Auto-detected via auto_viz() when None. Defaults to None.

  • band_name (str, optional) – Band to visualize when using auto-detection. Defaults to None (first band).

  • dimensions (int, optional) – Thumbnail width in pixels. Defaults to 640.

  • feature_label (str, optional) – Property name for per-feature labels in grid mode. Auto-detected when None. Defaults to None.

  • max_features (int, optional) – Maximum features to include in the grid. Defaults to 6.

  • columns (int, optional) – Number of columns in the per-feature grid. Defaults to 3.

  • thumb_width (int, optional) – Width in pixels for each cell in the per-feature grid. Defaults to 300.

  • burn_in_legend (bool, optional) – Append a legend panel for thematic data. Only rendered when class names and palette are available in image properties. Defaults to True.

  • legend_scale (float, optional) – Scale multiplier for the legend panel size. Defaults to 1.0.

  • bg_color (str or None, optional) – Background color for margins, legend panel, and transparent areas. Resolved via theme when None. Defaults to None.

  • font_color (str or tuple or None, optional) – Text color for labels and legend text. Resolved via theme when None. Defaults to None.

  • font_outline_color (str or tuple or None, optional) – Outline / halo color for text readability. Auto-derived when None. Defaults to None.

  • output_path (str, optional) – File path to save the PNG. Parent directories are created automatically. Defaults to None (not saved).

  • crs (str, optional) – CRS code (e.g. "EPSG:4326"). Applies setDefaultProjection to the image. Defaults to None.

  • transform (list, optional) – Affine transform as a 6-element list. Requires crs. Defaults to None.

  • scale (float, optional) – Nominal pixel scale in meters. Requires crs. Defaults to None.

  • margin (int, optional) – Pixel margin on all sides of the final image. Defaults to 16.

  • basemap (str or dict or None, optional) – Basemap to composite behind the EE data. A preset name (e.g. "esri-satellite", "usfs-topo"), a config dict with type and url keys, or a raw tile URL template. Defaults to None (no basemap).

  • overlay_opacity (float or None, optional) – Opacity of the EE overlay when a basemap is present (0.0 – 1.0). Defaults to None (auto: 0.8 with basemap, 1.0 without).

  • scalebar (bool, optional) – Draw a scalebar on the thumbnail. Only rendered when cartographic context is available. Defaults to True.

  • scalebar_units (str, optional) – Unit system for the scalebar – "metric" or "imperial". Defaults to "metric".

  • north_arrow (bool, optional) – Draw a north arrow on the thumbnail. Defaults to True.

  • north_arrow_style (str, optional) – Arrow style – "solid", "classic", or "outline". Defaults to "solid".

  • inset_map (bool, optional) – Include an inset overview map. Defaults to True.

  • inset_basemap (str or dict or None, optional) – Basemap for the inset. Falls back to basemap when None. Defaults to None.

  • inset_scale (float, optional) – Relative height of the inset compared to the frame height. Defaults to 0.3.

  • inset_on_map (bool, optional) – Place the inset directly on the map rather than below it. Defaults to True.

  • title (str, optional) – Title text rendered as a strip above the thumbnail. Defaults to None (no title).

  • burn_in_geometry (bool, optional) – Paint the geometry boundary outline onto the image using FeatureCollection.style(). Defaults to False.

  • geometry_outline_color (tuple or None, optional) – (R, G, B) colour for the boundary outline. When None, auto-detected from the basemap luminance. Defaults to None.

  • geometry_fill_color (str or None, optional) – CSS fill colour for the geometry interior (e.g. "33333366"). Used for geometry-only thumbnails (ee_obj=None). Defaults to None.

  • geometry_outline_weight (int, optional) – Width of the boundary outline in pixels. Defaults to 2.

  • geometry_legend_label (str, optional) – Label for the geometry swatch in the legend. Defaults to "Study Area".

  • clip_to_geometry (bool, optional) – When True, clip the image to the geometry. When False, use the geometry’s bounding box as the region (data extends beyond boundary). Defaults to True.

  • title_font_size (int, optional) – Font size in pixels for the title strip. Defaults to 18.

  • label_font_size (int, optional) – Font size in pixels for date labels, feature labels, scalebar ticks, and legend text. Defaults to 12.

Returns:

A dictionary with the following keys:

  • "html" (str): HTML <figure> element containing the thumbnail as a base64-embedded <img> tag.

  • "thumb_bytes" (bytes): Raw PNG byte data.

  • "is_grid" (bool): True if a multi-feature grid was produced, False for a single thumbnail.

Return type:

dict

Raises:

ValueError – If transform or scale is provided without crs.

Example

>>> result = generate_thumbs(
...     lcms.select(["Land_Cover"]).first(),
...     study_area,
...     basemap="esri-satellite",
...     title="LCMS Land Cover 2023",
... )
>>> result["is_grid"]
False
>>> len(result["thumb_bytes"]) > 0
True
geeViz.outputLib.thumbs.get_animation_url(ee_obj, geometry=None, viz_params=None, dimensions=640, fps=2, band_name=None, max_frames=50, crs='EPSG:3857', transform=None, scale=None)[source]

Get an animated GIF thumbnail URL for an ee.ImageCollection.

Note

For tiled collections (LCMS, NLCD, etc.) this may produce blank frames. Use generate_gif() instead, which properly mosaics per time step and supports date burn-in.

Parameters:
  • ee_objee.ImageCollection.

  • geometryee.Geometry, ee.Feature, or ee.FeatureCollection.

  • viz_params (dict, optional) – Must include bands (3 for RGB, or 1 + palette). Auto-detected if not provided.

  • dimensions (int) – Width in pixels.

  • fps (int) – Frames per second. Default 2.

  • band_name (str, optional) – Band to visualize (for auto_viz).

  • max_frames (int) – Maximum frames to include. Default 40.

  • crs (str, optional) – CRS code (e.g. "EPSG:4326").

  • transform (list, optional) – Affine transform. Requires crs.

  • scale (float, optional) – Nominal scale in meters. Requires crs.

Returns:

Animated GIF thumbnail URL.

Return type:

str

Raises:

ValueError – If transform or scale is provided without crs.

geeViz.outputLib.thumbs.get_filmstrip_url(ee_obj, geometry=None, viz_params=None, dimensions=640, band_name=None, max_frames=50, crs='EPSG:3857', transform=None, scale=None)[source]

Get a filmstrip thumbnail URL — all frames side-by-side in one PNG.

Parameters:
  • ee_objee.ImageCollection.

  • geometry – Clip region.

  • viz_params (dict, optional) – Auto-detected if not provided.

  • dimensions (int) – Width per frame.

  • band_name (str, optional) – Band to visualize.

  • max_frames (int) – Maximum frames.

  • crs (str, optional) – CRS code (e.g. "EPSG:4326").

  • transform (list, optional) – Affine transform. Requires crs.

  • scale (float, optional) – Nominal scale in meters. Requires crs.

Returns:

Filmstrip PNG thumbnail URL.

Return type:

str

Raises:

ValueError – If transform or scale is provided without crs.

geeViz.outputLib.thumbs.get_thumb_url(ee_obj, geometry=None, viz_params=None, dimensions=640, band_name=None, crs='EPSG:3857', transform=None, scale=None, burn_in_geometry=False, geometry_outline_color=None, geometry_fill_color=None, geometry_outline_weight=2, clip_to_geometry=True)[source]

Get a PNG thumbnail URL for an Earth Engine image.

Generates an ee.Image.getThumbURL() call with automatic visualization detection when viz_params is not supplied. The image is optionally clipped to geometry and reprojected when crs is provided. For ee.ImageCollection inputs, the collection is reduced to a single image (mode for thematic data, median for continuous).

Parameters:
  • ee_obj (ee.Image or ee.ImageCollection) – Image to thumbnail. Collections are reduced to a single representative image.

  • geometry (ee.Geometry or ee.Feature or ee.FeatureCollection, optional) – Region to clip and bound the thumbnail. Defaults to None (full image extent).

  • viz_params (dict, optional) – Visualization parameters (bands, min, max, palette, etc.). Auto-detected via auto_viz() when None. Defaults to None.

  • dimensions (int, optional) – Thumbnail width in pixels. Defaults to 640.

  • band_name (str, optional) – Band to visualize when using auto-detection. Defaults to None (first band).

  • crs (str, optional) – Coordinate reference system code (e.g. "EPSG:4326", "EPSG:32612"). When provided, setDefaultProjection is applied to the image. Defaults to None.

  • transform (list, optional) – Affine transform as a 6-element list. Requires crs. Defaults to None.

  • scale (float, optional) – Nominal pixel scale in meters. Requires crs. Defaults to None.

Returns:

PNG thumbnail URL string from the Earth Engine servers.

Return type:

str

Raises:

ValueError – If transform or scale is provided without crs.

Example

>>> url = get_thumb_url(
...     image, study_area,
...     {"min": 0, "max": 3000, "bands": ["swir1", "nir", "red"]},
... )
>>> url[:5]
'https'
geeViz.outputLib.thumbs.get_thumb_urls_by_feature(ee_obj, features, viz_params=None, dimensions=640, feature_label=None, band_name=None, max_features=10)[source]

Get thumbnail URLs for an image clipped to each feature in a collection.

Iterates over features sequentially, clipping the image to each feature’s geometry and generating a separate thumbnail URL. For faster processing with many features, use get_thumb_urls_by_feature_parallel() instead.

Parameters:
  • ee_obj (ee.Image or ee.ImageCollection) – Image to thumbnail. Collections are reduced to a single representative image.

  • features (ee.FeatureCollection) – Collection of features; each feature’s geometry is used to clip a separate thumbnail.

  • viz_params (dict, optional) – Visualization parameters. Auto-detected via auto_viz() when None. Defaults to None.

  • dimensions (int, optional) – Width in pixels per thumbnail. Defaults to 640.

  • feature_label (str, optional) – Property name to use as a human-readable label for each feature. Auto-detected when None. Defaults to None.

  • band_name (str, optional) – Band to visualize when using auto-detection. Defaults to None.

  • max_features (int, optional) – Maximum number of features to process. Defaults to 10.

Returns:

List of dictionaries, one per feature, each containing:

  • "label" (str): Feature label from feature_label property.

  • "url" (str): PNG thumbnail URL.

  • "geometry" (ee.Geometry): The feature’s geometry.

Return type:

list[dict]

Example

>>> results = get_thumb_urls_by_feature(
...     image, counties.limit(3), feature_label="NAME",
... )
>>> results[0].keys()
dict_keys(['label', 'url', 'geometry'])
geeViz.outputLib.thumbs.get_thumb_urls_by_feature_parallel(ee_obj, features, viz_params=None, dimensions=640, feature_label=None, band_name=None, max_features=10, max_workers=6, burn_in_params=None, clip_to_geometry=True)[source]

Generate per-feature thumbnail URLs in parallel using a thread pool.

Like get_thumb_urls_by_feature(), but uses concurrent.futures.ThreadPoolExecutor to issue multiple getThumbURL() requests concurrently, significantly reducing wall-clock time for collections with many features.

Parameters:
  • ee_obj (ee.Image or ee.ImageCollection) – Image to thumbnail. Collections are reduced to a single representative image.

  • features (ee.FeatureCollection) – Collection of features; each feature’s geometry is used to clip a separate thumbnail.

  • viz_params (dict, optional) – Visualization parameters. Auto-detected via auto_viz() when None. Defaults to None.

  • dimensions (int, optional) – Width in pixels per thumbnail. Defaults to 640.

  • feature_label (str, optional) – Property name to use as a human-readable label for each feature. Auto-detected when None. Defaults to None.

  • band_name (str, optional) – Band to visualize when using auto-detection. Defaults to None.

  • max_features (int, optional) – Maximum number of features to process. Defaults to 10.

  • max_workers (int, optional) – Maximum threads in the pool. Defaults to 6.

Returns:

List of dictionaries, one per feature, each containing:

  • "label" (str): Feature label from feature_label property.

  • "url" (str): PNG thumbnail URL.

Return type:

list[dict]

Example

>>> counties = ee.FeatureCollection("TIGER/2018/Counties")
>>> results = get_thumb_urls_by_feature_parallel(
...     image, counties.limit(5),
...     feature_label="NAME",
... )
>>> results[0]["label"]
'Some County'
geeViz.outputLib.thumbs.thumb_to_base64(url, timeout=120)[source]

Download a thumbnail and return it as a base64 data URI string.

Fetches image bytes from the given URL, detects the format (PNG or GIF) from the magic bytes, and encodes the result as a data:image/...;base64,... URI suitable for embedding in HTML.

Parameters:
  • url (str) – Thumbnail URL from getThumbURL() or getVideoThumbURL().

  • timeout (int, optional) – HTTP request timeout in seconds. Defaults to 120.

Returns:

Base64 data URI string (e.g. "data:image/png;base64,iVBOR...").

Return type:

str

Example

>>> data_uri = thumb_to_base64("https://earthengine.googleapis.com/...")
>>> data_uri.startswith("data:image/")
True

geeViz.outputLib.reports

Automated report generation with parallel EE data fetching, Plotly charts, D3 Sankey diagrams, thumbnails/GIFs, and LLM-generated narratives (via Gemini). Supports HTML, Markdown, and PDF output with dark/light themes.

Generate reports from Earth Engine data with LLM-powered narratives.

geeViz.outputLib.reports provides a Report class that combines chartingLib.summarize_and_chart() results, thumbLib thumbnails, and Gemini-generated narratives into styled HTML or Markdown reports.

All Earth Engine data requests (charts, tables, thumbnails, GIFs) and LLM narratives for every section are executed in parallel using concurrent.futures. Only the executive summary waits for all sections to finish before it is generated.

Layouts
  • "report" (default) — traditional multi-page portrait layout, sections flow vertically.

  • "poster" — landscape multi-column layout, designed for large-format printing or screen display. Sections tile into a responsive grid.

Themes

Two built-in themes match the geeView color palette:

  • "dark" (default) — deep brown/black background with warm gray text

  • "light" — white background with deep brown text

Example:

import geeViz.geeView as gv
from geeViz.outputLib import reports as rl

ee = gv.ee
report = rl.Report(
    title="Wasatch Front Assessment",
    theme="dark",
    layout="poster",       # landscape multi-column
)
report.header_text = "An analysis of land cover and fire trends."

report.add_section(
    ee_obj=lcms.select(['Land_Cover']),
    geometry=counties,
    title="LCMS Land Cover",
    stacked=True,
    scale=60,
)

# PDF with static chart images
report.generate(format="pdf", output_path="report.pdf")

# HTML (interactive charts)
report.generate(format="html", output_path="report.html")
class geeViz.outputLib.reports.Report(title='Report', model='gemini-3-flash-preview', api_key=None, prompt=None, header_text=None, header_icon=None, theme='dark', layout='report', tone='neutral', max_workers=6)[source]

Bases: object

Build and generate reports from Earth Engine data.

Parameters:
  • title (str) – Report title.

  • model (str) – Gemini model name. Default "gemini-3-flash-preview".

  • api_key (str, optional) – Google API key. If not provided, loaded from the GEMINI_API_KEY environment variable (via .env).

  • prompt (str, optional) – Additional guidance for the executive summary.

  • header_text (str, optional) – Introductory text shown below the title.

  • header_icon (str, optional) – Path to a PNG/JPG image for the report header icon. If None, uses the built-in geeViz logo (theme-aware). Pass False to suppress the icon entirely.

  • theme (str) – Color theme — "dark" or "light". Default "dark".

  • layout (str) – Layout mode — "report" (portrait, vertical flow) or "poster" (landscape, multi-column grid). Default "report".

  • tone (str) – Narrative tone for LLM-generated text. Built-in options: "neutral" (default) — data-driven, no superlatives or narrative; "informative" — accessible, explains significance; "technical" — formal, precise terminology. Can also be a custom string with tone instructions.

  • max_workers (int) – Thread pool size for parallel EE requests. Default 6.

Example:

report = Report(title="My Analysis", theme="light", layout="report")
report.add_section(ee_obj=lcms, geometry=area, title="Land Cover")
html = report.generate(format="html", output_path="report.html")
add_section(ee_obj, geometry, title='Section', prompt=None, generate_table=True, generate_chart=True, thumb_format='png', chart_types=None, **kwargs)[source]

Add a data section to the report.

Parameters:
  • ee_objee.Image or ee.ImageCollection to summarize.

  • geometryee.Geometry, ee.Feature, or ee.FeatureCollection.

  • title (str) – Section heading.

  • prompt (str, optional) – Per-section LLM guidance for the narrative.

  • generate_table (bool) – Include data table. Default True.

  • generate_chart (bool) – Include chart. Default True.

  • thumb_format (str or None) –

    Thumbnail image format. Default "png" (static thumbnail). Options:

    • "png" — single composite thumbnail (works for both ee.Image and ee.ImageCollection).

    • "gif" — animated GIF with date labels (ee.ImageCollection only).

    • "filmstrip" — grid of individual time-step frames (ee.ImageCollection only).

    • None or False — no thumbnail.

  • chart_types (list of str, optional) –

    Chart types to produce for this section. Each entry is a single chart type string passed to summarize_and_chart(chart_type=...). Valid values include "bar", "stacked_bar", "line+markers", "stacked_line+markers", "donut", "scatter", and "sankey".

    When "sankey" is in the list, the sankey, transition_periods, sankey_band_name, and min_percentage kwargs are used for that chart.

    An empty list [] or None auto-detects a single chart type (existing behavior). Maximum recommended length is 3.

    Examples:

    chart_types=["sankey", "line+markers"]
    chart_types=["bar", "donut"]
    chart_types=["sankey"]  # sankey only, no line chart
    

  • **kwargs

    All other keyword arguments. Thumbnail params (prefixed thumb_) are extracted and forwarded to thumbLib; remaining kwargs go to chartingLib.summarize_and_chart().

    Thumbnail params (all optional):

    thumb_viz_params, thumb_band_name, thumb_dimensions, thumb_fps (gif only), thumb_columns (filmstrip only), thumb_max_frames (gif/filmstrip), thumb_burn_in_date (gif), thumb_date_format (gif/filmstrip), thumb_date_position (gif), thumb_bg_color, thumb_geometry (override clip region), thumb_crs, thumb_transform, burn_in_legend, legend_scale.

    Chart params (examples):

    stacked=True, scale=60, feature_label="NAME", etc.

Returns:

self (for method chaining).

Return type:

Report

generate(format='html', output_path=None)[source]

Generate the report.

All section data (charts, tables, thumbnails, GIFs) and LLM narratives are computed in parallel. Only the executive summary waits for all sections to finish first.

Parameters:
  • format (str) – Output format — "html", "md", or "pdf". PDF uses kaleido to render charts as static PNG images and pdfkit/wkhtmltopdf for the final conversion. If wkhtmltopdf is not installed, a print-ready HTML file with @page CSS directives is generated instead (open in a browser and Print → Save as PDF).

  • output_path (str, optional) – File path to write. If None, returns the content as a string (except for PDF which always requires a path).

Returns:

The report content (or the file path if output_path given).

Return type:

str

metadata()[source]

Return a summary DataFrame describing each section’s generated outputs.

Each row corresponds to one section. Columns include the section title, what was requested, what was produced, data dimensions, and any errors. Call this after generate() to inspect results.

Returns:

pandas.DataFrame with one row per section.

geeViz.outputLib.themes

Unified theme system for consistent colors across charts, thumbnails, and reports. Provides named presets (dark, light, teal) and auto-generation from a single background color.

Unified theme system for geeViz output libraries.

Provides a Theme class that holds all resolved color values for backgrounds, text, accents, borders, and chart styling. Used by charts, thumbs, and reports for consistent colors.

Usage:

from geeViz.outputLib.themes import get_theme

# Named presets
dark  = get_theme("dark")
light = get_theme("light")
teal  = get_theme("teal")

# Auto-generate from a single color
red_bg = get_theme(bg_color="#F00")           # dark text auto-picked
custom = get_theme(bg_color="#1a1a2e", font_color="#eee")

# Access colors in different formats
dark.bg_hex          # '#272822'
dark.bg_rgb          # (39, 40, 34)
dark.text_hex        # '#f8f8f2'
dark.is_dark         # True
dark.grid_rgba       # 'rgba(248,248,242,0.15)'
class geeViz.outputLib.themes.Theme(bg, text, accent=None, highlight=None, surface=None, border=None, divider=None, swatch_outline=None, muted_text=None, is_dark=None, title_font_size=18, label_font_size=12, font_family='Roboto Condensed')[source]

Bases: object

Resolved color theme for geeViz visualizations.

A Theme holds all of the resolved color values needed to style charts, thumbnails, reports, and other geeViz outputs consistently. All colors are stored internally as (R, G, B) tuples with integer components in the 0–255 range. Convenience properties provide hex-string, RGB-tuple, and RGBA-string formats for direct use in Plotly layouts, HTML/CSS, and Pillow operations.

Colors that are not explicitly provided to the constructor are automatically derived from the bg and text colors using perceptually reasonable blending and HSL manipulation.

bg

Background color as an (R, G, B) tuple.

Type:

tuple

text

Primary text/foreground color as an (R, G, B) tuple.

Type:

tuple

accent

Accent color for headings and links as an (R, G, B) tuple. Derived from text if not provided.

Type:

tuple

highlight

Highlight/emphasis color as an (R, G, B) tuple. Derived from accent if not provided.

Type:

tuple

surface

Card or panel background color, slightly offset from bg, as an (R, G, B) tuple.

Type:

tuple

border

Border and table-line color as an (R, G, B) tuple.

Type:

tuple

divider

Subtle separator/divider color as an (R, G, B) tuple.

Type:

tuple

swatch_outline

Legend swatch outline color as an (R, G, B) tuple.

Type:

tuple

muted_text

Secondary/caption text color as an (R, G, B) tuple.

Type:

tuple

is_dark

True if this is a dark-background theme (background luminance < 128).

Type:

bool

Example

>>> from geeViz.outputLib.themes import Theme
>>> t = Theme(bg=(39, 40, 34), text=(248, 248, 242))
>>> t.is_dark
True
>>> t.bg_hex
'#272822'
accent
property accent_hex

Return the accent color as a hex string.

Returns:

Accent color in '#RRGGBB' format.

Return type:

str

Example

>>> Theme(bg=(0, 0, 0), text=(255, 255, 255), accent=(0, 191, 165)).accent_hex
'#00bfa5'
bg
property bg_hex

Return the background color as a hex string.

Returns:

Background color in '#RRGGBB' format.

Return type:

str

Example

>>> Theme(bg=(39, 40, 34), text=(248, 248, 242)).bg_hex
'#272822'
property bg_rgb

Return the background color as an RGB tuple.

This is an alias for the bg attribute, provided for symmetry with the *_hex properties.

Returns:

Background color as (R, G, B) with values 0–255.

Return type:

tuple

Example

>>> Theme(bg=(39, 40, 34), text=(248, 248, 242)).bg_rgb
(39, 40, 34)
border
property border_hex

Return the border color as a hex string.

Returns:

Border color in '#RRGGBB' format.

Return type:

str

Example

>>> Theme(bg=(0, 0, 0), text=(255, 255, 255)).border_hex
'#4d4d4d'
property button_bg_rgba

Return a toolbar button background color.

Uses the muted text color at 15 % opacity.

Returns:

RGBA color string for button backgrounds.

Return type:

str

Example

>>> Theme(bg=(0, 0, 0), text=(255, 255, 255)).button_bg_rgba
'rgba(140,140,140,0.15)'
property button_border_rgba

Return a toolbar button border color.

Uses the muted text color at 30 % opacity.

Returns:

RGBA color string for button borders.

Return type:

str

Example

>>> Theme(bg=(0, 0, 0), text=(255, 255, 255)).button_border_rgba
'rgba(140,140,140,0.3)'
property button_hover_rgba

Return a toolbar button hover background color.

Uses the muted text color at 30 % opacity.

Returns:

RGBA color string for button hover backgrounds.

Return type:

str

Example

>>> Theme(bg=(0, 0, 0), text=(255, 255, 255)).button_hover_rgba
'rgba(140,140,140,0.3)'
divider
property divider_hex

Return the divider color as a hex string.

Returns:

Divider color in '#RRGGBB' format.

Return type:

str

Example

>>> Theme(bg=(0, 0, 0), text=(255, 255, 255)).divider_hex
'#262626'
property error_bg_rgba

Return an error-box background color with appropriate alpha.

Uses the highlight color with an alpha of 0.1 for dark themes and 0.08 for light themes, producing a tinted but unobtrusive error background.

Returns:

RGBA color string for the error background.

Return type:

str

Example

>>> t = Theme(bg=(0, 0, 0), text=(255, 255, 255),
...           highlight=(255, 0, 0))
>>> t.error_bg_rgba
'rgba(255,0,0,0.1)'
font_family
property grid_rgba

Return a chart gridline color with appropriate alpha.

Uses an alpha of 0.15 for dark themes and 0.1 for light themes to keep gridlines subtle against the background.

Returns:

RGBA color string, e.g. 'rgba(248,248,242,0.15)'.

Return type:

str

Example

>>> Theme(bg=(0, 0, 0), text=(255, 255, 255)).grid_rgba
'rgba(255,255,255,0.15)'
highlight
property highlight_hex

Return the highlight color as a hex string.

Returns:

Highlight color in '#RRGGBB' format.

Return type:

str

Example

>>> Theme(bg=(0, 0, 0), text=(255, 255, 255), highlight=(255, 131, 76)).highlight_hex
'#ff834c'
is_dark
label_font_size
property legend_title_font_size

Legend title font size (1.15x label size).

property line_rgba

Return a chart axis line color with appropriate alpha.

Uses an alpha of 0.25 for dark themes and 0.2 for light themes.

Returns:

RGBA color string, e.g. 'rgba(248,248,242,0.25)'.

Return type:

str

Example

>>> Theme(bg=(0, 0, 0), text=(255, 255, 255)).line_rgba
'rgba(255,255,255,0.25)'

Return a Sankey link stroke color for gradient edges.

Dark themes use a faint white stroke (rgba(255,255,255,0.15)); light themes use a faint black stroke (rgba(0,0,0,0.08)).

Returns:

RGBA color string for Sankey link strokes.

Return type:

str

Example

>>> Theme(bg=(0, 0, 0), text=(255, 255, 255)).link_stroke_rgba
'rgba(255,255,255,0.15)'
muted_text
property muted_text_hex

Return the muted text color as a hex string.

Returns:

Muted text color in '#RRGGBB' format.

Return type:

str

Example

>>> Theme(bg=(0, 0, 0), text=(255, 255, 255)).muted_text_hex
'#8c8c8c'
surface
property surface_hex

Return the surface/panel color as a hex string.

Returns:

Surface color in '#RRGGBB' format.

Return type:

str

Example

>>> Theme(bg=(255, 255, 255), text=(0, 0, 0)).surface_hex
'#f5f5f5'
property surface_rgba

Return the surface color with alpha for table row striping.

Uses an alpha of 0.5 for dark themes and 0.3 for light themes so that alternating rows are visible but not overpowering.

Returns:

RGBA color string for the surface, e.g. 'rgba(55,46,44,0.5)'.

Return type:

str

Example

>>> Theme(bg=(0, 0, 0), text=(255, 255, 255)).surface_rgba
'rgba(15,15,15,0.5)'
swatch_outline
property swatch_outline_hex

Return the swatch outline color as a hex string.

Returns:

Swatch outline color in '#RRGGBB' format.

Return type:

str

Example

>>> Theme(bg=(0, 0, 0), text=(255, 255, 255)).swatch_outline_hex
'#404040'
text
property text_hex

Return the text color as a hex string.

Returns:

Text color in '#RRGGBB' format.

Return type:

str

Example

>>> Theme(bg=(39, 40, 34), text=(248, 248, 242)).text_hex
'#f8f8f2'
property text_rgb

Return the text color as an RGB tuple.

This is an alias for the text attribute, provided for symmetry with the *_hex properties.

Returns:

Text color as (R, G, B) with values 0–255.

Return type:

tuple

Example

>>> Theme(bg=(39, 40, 34), text=(248, 248, 242)).text_rgb
(248, 248, 242)
title_font_size
property tooltip_bg_rgba

Return a tooltip background as a semi-transparent inverse of bg.

Dark themes get a near-black tooltip (rgba(0,0,0,0.85)); light themes get a near-white tooltip (rgba(255,255,255,0.92)).

Returns:

RGBA color string for tooltip backgrounds.

Return type:

str

Example

>>> Theme(bg=(0, 0, 0), text=(255, 255, 255)).tooltip_bg_rgba
'rgba(0,0,0,0.85)'
property zeroline_rgba

Return a chart zero-line color with appropriate alpha.

Uses an alpha of 0.2 for dark themes and 0.15 for light themes.

Returns:

RGBA color string, e.g. 'rgba(248,248,242,0.2)'.

Return type:

str

Example

>>> Theme(bg=(0, 0, 0), text=(255, 255, 255)).zeroline_rgba
'rgba(255,255,255,0.2)'
geeViz.outputLib.themes.apply_plotly_theme(fig, theme=None, bg_color=None, font_color=None)[source]

Apply a theme’s colors to a Plotly figure in-place.

Resolves a Theme from the provided arguments (using get_theme()) and then updates the figure’s layout – including paper/plot background, font colors, axis grid/line/zeroline colors, title, legend, and annotation colors – to match the theme.

Parameters:
  • fig (plotly.graph_objects.Figure) – The Plotly figure to style. Modified in-place.

  • theme (str or Theme or tuple or None, optional) – Preset name, Theme instance, or color string/tuple. Passed through to get_theme(). Defaults to None.

  • bg_color (str or tuple, optional) – Background color override. Defaults to None.

  • font_color (str or tuple, optional) – Font color override. Defaults to None.

Returns:

The same figure, modified in-place, for method chaining convenience.

Return type:

plotly.graph_objects.Figure

Example

>>> import plotly.graph_objects as go
>>> fig = go.Figure(data=[go.Bar(x=[1, 2], y=[3, 4])])
>>> fig = apply_plotly_theme(fig, "dark")
>>> fig.layout.paper_bgcolor
'#272822'
geeViz.outputLib.themes.get_theme(theme=None, bg_color=None, font_color=None)[source]

Resolve a Theme from a preset name, instance, or custom colors.

This is the main entry point for obtaining a theme. It accepts a preset name ("dark", "light", "teal"), a Theme instance (pass-through), a color string or tuple (treated as bg_color), or None. When bg_color and/or font_color are also supplied alongside a preset, they override the preset’s background and text colors respectively, and accent/highlight are re-derived from the new colors.

Parameters:
  • theme (str or Theme or tuple or None, optional) – A preset name ("dark", "light", "teal"), a Theme instance (returned as-is unless overrides are given), a color string or (R, G, B) tuple (treated as bg_color), or None. Defaults to None.

  • bg_color (str or tuple, optional) – Background color override in any format accepted by resolve_color(). Overrides the preset’s background when combined with theme. Defaults to None.

  • font_color (str or tuple, optional) – Text/font color override in any format accepted by resolve_color(). Overrides the preset’s text when combined with theme. Defaults to None.

Returns:

A fully resolved Theme instance.

Return type:

Theme

Example

>>> get_theme("dark").bg_hex
'#272822'
>>> get_theme("light").is_dark
False
>>> get_theme(bg_color="#F00").is_dark
True
>>> get_theme("dark", font_color="yellow").text_hex
'#ffff00'
geeViz.outputLib.themes.register_preset(name, theme)[source]

Register a named theme preset for later retrieval via get_theme().

Presets are stored in a module-level dictionary keyed by the lower-cased name. Calling this function with a name that already exists will overwrite the previous preset.

Parameters:
  • name (str) – Preset name (e.g. "dark", "ocean"). Stored in lower case.

  • theme (Theme) – A Theme instance to register.

Returns:

None

Example

>>> t = Theme(bg=(0, 0, 0), text=(255, 255, 255))
>>> register_preset("midnight", t)
>>> get_theme("midnight").bg_hex
'#000000'

geeViz.phEEnoViz

Phenology visualization and vegetation temporal pattern analysis.

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)
geeViz.phEEnoViz.limitThreads(limit)[source]

Limits the number of active threads to a specified limit.

Parameters:

limit (int) – The maximum number of threads allowed.

Example

>>> limitThreads(2)

Summary Areas Module

geeViz.getSummaryAreasLib

Functions to retrieve common study and summary area ee.FeatureCollection objects for political boundaries (countries, states, counties), USFS units (forests, districts, regions), US census geographies (tracts, block groups, blocks, urban areas), buildings, roads, and protected areas. Every function accepts an area parameter and returns spatially filtered results.

Functions for retrieving common summary and study area FeatureCollections.

geeViz.getSummaryAreasLib provides helpers that return filtered ee.FeatureCollection objects for political boundaries, USFS administrative units, census geographies, buildings, roads, protected areas, and more. Every public function accepts an area parameter (an ee.FeatureCollection, ee.Feature, or ee.Geometry) that is used to spatially filter the result.

geeViz.getSummaryAreasLib.getAdminBoundaries(area, level=0, source='geob')[source]

Return administrative boundaries at a given level that intersect area.

Levels follow the standard admin hierarchy:

  • 0 — Countries

  • 1 — States / provinces

  • 2 — Districts / counties / municipalities

  • 3 — Sub-districts / wards (FieldMaps only)

  • 4 — Neighborhoods / localities (FieldMaps only)

Available sources and their level coverage:

  • "geob" — geoBoundaries v6.0 (official GEE catalog, levels 0–2). Name property: shapeName.

  • "gaul" — FAO GAUL 2015 (official GEE catalog, levels 0–2). Name property: ADM{level}_NAME (e.g. ADM0_NAME).

  • "gaul2024" — FAO GAUL 2024 (community catalog, levels 0–2). Name property: gaul{level}_name.

  • "fieldmaps" — FieldMaps humanitarian edge-matched boundaries (community catalog, levels 1–4). Name property: adm{level}_name. Includes parent admin names and ISO codes.

For levels 3–4, if the requested source doesn’t support them the function automatically falls back to FieldMaps.

Parameters:
  • area – ee.FeatureCollection, ee.Feature, or ee.Geometry to filter by.

  • level (int) – Administrative level (0–4). Default 0.

  • source (str) – Boundary source. Default "geob".

Returns:

ee.FeatureCollection of admin boundary polygons.

Example

>>> countries = getAdminBoundaries(my_area, level=0)
>>> states = getAdminBoundaries(my_area, level=1)
>>> districts = getAdminBoundaries(my_area, level=2, source="gaul")
>>> wards = getAdminBoundaries(my_area, level=3)  # auto-uses FieldMaps
geeViz.getSummaryAreasLib.getAdminNameProperty(level=0, source='geob')[source]

Return the feature property name that contains the admin unit name.

Useful for setting feature_label in summarize_and_chart or selectLayerNameProperty in Map.addSelectLayer.

Parameters:
  • level (int) – Administrative level (0–4).

  • source (str) – Boundary source (same options as getAdminBoundaries()).

Returns:

The property name (e.g. "shapeName", "ADM1_NAME").

Return type:

str

Example

>>> prop = getAdminNameProperty(level=1, source="gaul")  # "ADM1_NAME"
geeViz.getSummaryAreasLib.getBuildings(area, source='vida')[source]

Return building footprints that intersect area.

This function determines which countries intersect the given area, then loads and merges per-country building footprint collections.

Parameters:
  • area – ee.FeatureCollection, ee.Feature, or ee.Geometry.

  • source (str) –

    Building footprint source.

    • "vida" — VIDA Combined Building Footprints (179 countries, ISO-3 keyed). Properties: area_in_meters, confidence, bf_source.

    • "ms" — Microsoft Building Footprints (202 countries, country-name keyed). Properties vary by country.

    • "google" — Google Open Buildings v3 (Africa, South/Southeast Asia). Properties: area_in_meters, confidence, full_plus_code.

Returns:

ee.FeatureCollection of building footprint polygons.

Note

Building collections are very large. Use a small study area or the query may be slow / exceed memory limits.

Example

>>> buildings = getBuildings(ee.Geometry.Point([-111, 40.7]).buffer(1000))
geeViz.getSummaryAreasLib.getProtectedAreas(area, iucn_cat=None, desig_type=None)[source]

Return WDPA protected area polygons that intersect area.

Properties include NAME, DESIG_ENG, IUCN_CAT, STATUS, STATUS_YR, GOV_TYPE, DESIG_TYPE, REP_AREA, GIS_AREA, ISO3.

Parameters:
  • area – ee.FeatureCollection, ee.Feature, or ee.Geometry.

  • iucn_cat (str, optional) – Filter by IUCN category (e.g. "II" for National Parks, "Ia" for Strict Nature Reserve).

  • desig_type (str, optional) – Filter by designation type ("National", "Regional", "International", "Not Applicable").

Returns:

ee.FeatureCollection.

geeViz.getSummaryAreasLib.getRoads(area, source='tiger', year=2024)[source]

Return road features that intersect area.

Supports two road data sources covering different geographies and classification schemes.

Parameters:
  • area – ee.FeatureCollection, ee.Feature, or ee.Geometry.

  • source (str) –

    Road data source:

    • "tiger" (default) — US Census TIGER roads. Detailed classification via MTFCC codes. Available 2012-2025 via the community catalog, plus 2016 in the official GEE catalog. US only. Properties: FULLNAME, MTFCC, RTTYP, LINEARID.

    • "grip" — GRIP4 (Global Roads Inventory Project). Global coverage across 7 regional shards. Road type classification via GP_RTP (1=Highway, 2=Primary, 3=Secondary, 4=Tertiary, 5=Local). Based on OpenStreetMap and other sources. CC-BY 4.0.

  • year (int) – Year for TIGER roads (2012-2025). Ignored for other sources. Years other than 2016 use the community catalog (projects/sat-io/open-datasets/TIGER/{year}/Roads). Defaults to 2024.

Returns:

ee.FeatureCollection of road line features.

Common TIGER MTFCC codes:

  • S1100 — Primary road (interstate)

  • S1200 — Secondary road (US/state highway)

  • S1400 — Local road

  • S1500 — Vehicular trail (4WD)

  • S1630 — Ramp

  • S1640 — Service drive

  • S1730 — Alley

  • S1780 — Parking lot road

  • S1820 — Bike path / trail

GRIP4 GP_RTP road types:

  • 1 — Highway

  • 2 — Primary road

  • 3 — Secondary road

  • 4 — Tertiary road

  • 5 — Local / residential

Examples

>>> # US interstates from TIGER 2024
>>> interstates = getRoads(my_area).filter(ee.Filter.eq('MTFCC', 'S1100'))
>>> # Global highways from GRIP4
>>> highways = getRoads(my_area, source='grip').filter(ee.Filter.eq('GP_RTP', 1))
>>> # TIGER roads from a specific year
>>> roads_2020 = getRoads(my_area, year=2020)
geeViz.getSummaryAreasLib.getUSBlockGroups(area)[source]

Return TIGER 2020 census block groups that intersect area.

Parameters:

area – ee.FeatureCollection, ee.Feature, or ee.Geometry.

Returns:

ee.FeatureCollection.

geeViz.getSummaryAreasLib.getUSCensusBlocks(area)[source]

Return TIGER 2020 census blocks that intersect area.

Warning

Census blocks are extremely numerous. Use a small study area or the query may be slow / exceed memory limits.

Parameters:

area – ee.FeatureCollection, ee.Feature, or ee.Geometry.

Returns:

ee.FeatureCollection.

geeViz.getSummaryAreasLib.getUSCensusTracts(area)[source]

Return TIGER 2020 census tracts that intersect area.

Parameters:

area – ee.FeatureCollection, ee.Feature, or ee.Geometry.

Returns:

ee.FeatureCollection.

geeViz.getSummaryAreasLib.getUSCounties(area, state_fips=None, state_abbr=None)[source]

Return US county boundaries that intersect area.

Optionally filter to a single state by FIPS code or postal abbreviation.

Properties include NAME, FULL_NAME, STATEFP, STUSPS, COUNTYFP, GEOID.

Parameters:
  • area – ee.FeatureCollection, ee.Feature, or ee.Geometry.

  • state_fips (str, optional) – Two-digit state FIPS (e.g. "49" for Utah).

  • state_abbr (str, optional) – Two-letter postal abbreviation (e.g. "UT").

Returns:

ee.FeatureCollection.

geeViz.getSummaryAreasLib.getUSFSDistricts(area, forest_name=None, region=None)[source]

Return USFS Ranger District boundaries that intersect area.

Properties include DISTRICTNA, FORESTNAME, FORESTNUMB, REGION, GIS_ACRES.

Parameters:
  • area – ee.FeatureCollection, ee.Feature, or ee.Geometry.

  • forest_name (str, optional) – Filter to districts within a specific National Forest (exact match on FORESTNAME).

  • region (str, optional) – Two-digit USFS region number.

Returns:

ee.FeatureCollection.

geeViz.getSummaryAreasLib.getUSFSForests(area, region=None)[source]

Return USFS National Forest boundaries that intersect area.

Properties include FORESTNAME, FORESTNUMB, REGION, FORESTORGC, GIS_ACRES.

Parameters:
  • area – ee.FeatureCollection, ee.Feature, or ee.Geometry.

  • region (str, optional) – Two-digit USFS region number to filter by (e.g. "01" for Northern Region).

Returns:

ee.FeatureCollection.

geeViz.getSummaryAreasLib.getUSFSRegions(area)[source]

Return USFS region boundaries that intersect area.

Properties include REGION, REGIONNAME, REGIONHEAD (headquarters city), FS_ADMINAC (admin acres).

Parameters:

area – ee.FeatureCollection, ee.Feature, or ee.Geometry.

Returns:

ee.FeatureCollection with one feature per USFS region.

geeViz.getSummaryAreasLib.getUSStates(area)[source]

Return US state boundaries (TIGER 2018) that intersect area.

Properties include NAME, STUSPS (abbreviation), STATEFP (FIPS code), REGION, DIVISION.

Parameters:

area – ee.FeatureCollection, ee.Feature, or ee.Geometry.

Returns:

ee.FeatureCollection.

geeViz.getSummaryAreasLib.getUSUrbanAreas(area)[source]

Return TIGER 2024 urban area boundaries that intersect area.

Properties include NAME20, NAMELSAD20, ALAND20, AWATER20.

Parameters:

area – ee.FeatureCollection, ee.Feature, or ee.Geometry.

Returns:

ee.FeatureCollection.

geeViz.getSummaryAreasLib.simple_buffer(geom, size=15000)[source]

Create a square buffer around a point using simple coordinate arithmetic.

A lightweight alternative to ee.Geometry.buffer() that avoids the server-side geodesic circle computation. Transforms the point to EPSG:3857 (Web Mercator), applies a latitude-corrected offset so that size represents true ground meters, and returns the polygon in EPSG:3857.

Accepts a point in any projection — it will be transformed to EPSG:3857 internally.

Parameters:
  • geom (ee.Geometry) – A point geometry in any projection.

  • size (int or float, optional) – Half-width of the square in meters on the ground. The resulting square spans 2 * size on each side. Defaults to 15000 (producing a 30 km x 30 km square).

Returns:

A square polygon centered on the input point, defined in EPSG:3857.

Return type:

ee.Geometry.Polygon

Example

>>> pt = ee.Geometry.Point([-111.5, 40.5])
>>> square = simple_buffer(pt, size=5000)  # 10 km x 10 km

External Data Modules

geeViz.edwLib

USFS Enterprise Data Warehouse (EDW) REST API client. Search, inspect, and query ~215 Forest Service geospatial services (fire, ownership, vegetation, roads, etc.).

USFS Enterprise Data Warehouse (EDW) REST API client.

Provides search, metadata inspection, and spatial feature queries against the ArcGIS REST services at https://apps.fs.usda.gov/arcx/rest/services/EDW.

Quick start:

import geeViz.edwLib as edw

# Search for fire-related services
services = edw.search_services("fire")

# Get layer info
info = edw.get_service_info("EDW_MTBS_01")

# Query features as GeoJSON
geojson = edw.query_features("EDW_MTBS_01", 15,
    where="FIRE_NAME LIKE '%CAMERON PEAK%'",
    out_fields="FIRE_NAME,ACRES,YEAR")

# Load into Earth Engine
import ee
fc = ee.FeatureCollection(geojson)
geeViz.edwLib.get_layer_info(service_name: str, layer_id: int) dict[str, Any][source]

Get detailed metadata for a specific layer: fields, geometry type, capabilities.

Parameters:
  • service_name – Short service name, e.g. “EDW_MTBS_01”.

  • layer_id – Layer ID within the service.

Returns:

name, geometryType, description, fields, extent, maxRecordCount, supportedQueryFormats.

Return type:

Dict with keys

geeViz.edwLib.get_service_info(service_name: str) dict[str, Any][source]

Get metadata for an EDW MapServer service: description, layers, spatial ref.

Parameters:

service_name – Short service name, e.g. “EDW_MTBS_01”.

Returns:

name, description, spatialReference, layers (id, name, geometryType, defaultVisibility, minScale, maxScale).

Return type:

Dict with keys

geeViz.edwLib.query_features(service_name: str, layer_id: int, geometry: dict | str | None = None, geometry_type: str = 'esriGeometryEnvelope', spatial_rel: str = 'esriSpatialRelIntersects', where: str = '1=1', out_fields: str = '*', max_features: int = 1000, out_sr: int = 4326, return_count_only: bool = False) dict[source]

Query features from an EDW layer, optionally filtered by spatial intersection.

Parameters:
  • service_name – Short service name, e.g. “EDW_MTBS_01”.

  • layer_id – Layer ID within the service.

  • geometry – Geometry for spatial filter. Can be: - A GeoJSON geometry dict (Point, Polygon, Envelope-style bbox) - An Esri JSON geometry string/dict - A bbox string “xmin,ymin,xmax,ymax” - None for no spatial filter

  • geometry_type – Esri geometry type. Common values: esriGeometryPoint, esriGeometryEnvelope, esriGeometryPolygon

  • spatial_rel – Spatial relationship. Default: esriSpatialRelIntersects.

  • where – SQL WHERE clause. Default: “1=1” (all features).

  • out_fields – Comma-separated field names or “*” for all.

  • max_features – Maximum features to return (capped at server max).

  • out_sr – Output spatial reference WKID. Default: 4326 (WGS84).

  • return_count_only – If True, return only the count of matching features.

Returns:

N} if return_count_only.

Return type:

GeoJSON FeatureCollection dict, or {“count”

geeViz.edwLib.query_features_with_pagination(service_name: str, layer_id: int, geometry: dict | str | None = None, geometry_type: str = 'esriGeometryEnvelope', spatial_rel: str = 'esriSpatialRelIntersects', where: str = '1=1', out_fields: str = '*', max_features: int = 5000, out_sr: int = 4326) dict[source]

Query features with automatic pagination to get more than 2000 results.

Same args as query_features, but max_features can exceed the server limit. Returns a combined GeoJSON FeatureCollection.

geeViz.edwLib.search_services(query: str = '', theme: str = '') list[dict[str, str]][source]

Search EDW services by keyword and/or theme.

Uses three matching strategies (results are deduplicated): 1. Substring match on service name (e.g. “mtbs” → EDW_MTBS_01) 2. Keyword alias expansion (e.g. “riparian” → inland_waters theme + stream services) 3. Theme filter (e.g. theme=”inland_waters”)

Parameters:
  • query – Search keyword (case-insensitive). Matches against service names, theme descriptions, and keyword aliases.

  • theme – Filter by theme category. Valid themes: biota, boundaries, environment, geoscientific, inland_waters, planning_cadastre, structure, transportation. Pass “” to skip theme filtering.

Returns a list of dicts with keys: name, type, url, theme, description. If both query and theme are empty, returns all services.

geeViz.googleMapsLib

Google Maps Platform client for ground-truthing remote sensing analysis. Includes geocoding, places search, Street View imagery, panorama stitching, AI interpretation, semantic segmentation (SegFormer), elevation, air quality, solar, roads, and more.

Google Maps Platform client for geeViz.

Provides functions for ground-truthing and enriching remote sensing analysis using Google Maps Platform APIs:

  • Geocoding — address to coordinates and reverse

  • Places — search, nearby, details, photos

  • Street View — static images, panoramas, AI interpretation

  • Elevation — terrain height at any location

  • Static Maps — basemap images for reports

  • Air Quality — current AQI and pollutants

  • Solar — rooftop solar potential

  • Roads — snap GPS traces to nearest roads

24 public functions:

  • Geocoding: geocode, reverse_geocode, validate_address

  • Places: search_places, search_nearby, get_place_photo

  • Street View: streetview_metadata, streetview_image, streetview_images_cardinal, streetview_panorama, streetview_html

  • AI Analysis: interpret_image, label_streetview, segment_image, segment_streetview

  • Elevation: get_elevation, get_elevations, get_elevation_along_path

  • Environment: get_air_quality, get_solar_insights, get_timezone

  • Maps: get_static_map

  • Roads: snap_to_roads, nearest_roads

Quick start:

import geeViz.googleMapsLib as gm

# Geocode an address
result = gm.geocode("4240 S Olympic Way, Salt Lake City, UT")

# Street View panorama + AI interpretation
pano = gm.streetview_panorama(-111.80, 40.68, fov=360)
analysis = gm.interpret_image(pano)

# Semantic segmentation (SegFormer)
seg = gm.segment_image(pano, model_variant="b4")

# Elevation, air quality, solar
elev = gm.get_elevation(-111.80, 40.68)
aq = gm.get_air_quality(-111.80, 40.68)
solar = gm.get_solar_insights(-111.80, 40.68)

Requires a GOOGLE_MAPS_PLATFORM_API_KEY in your environment or .env file. Gemini AI features use GEMINI_API_KEY.

Copyright 2026 Ian Housman

Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file except in compliance with the License. You may obtain a copy of the License at

geeViz.googleMapsLib.geocode(address: str) dict[str, Any] | None[source]

Geocode an address to coordinates using the Google Geocoding API.

Parameters:

address (str) – Street address, place name, or location description.

Returns:

Result with keys:

  • lat (float): Latitude.

  • lon (float): Longitude.

  • formatted_address (str): Full formatted address.

  • place_id (str): Google Place ID.

  • location_type (str): Accuracy — "ROOFTOP", "RANGE_INTERPOLATED", "GEOMETRIC_CENTER", or "APPROXIMATE".

  • address_components (list): Decomposed address parts.

Returns None if no results found.

Return type:

dict or None

Example

>>> result = geocode("4240 S Olympic Way, Salt Lake City, UT")
>>> if result:
...     print(f"{result['lat']}, {result['lon']}")
geeViz.googleMapsLib.get_air_quality(lon: float, lat: float) dict[str, Any] | None[source]

Get current air quality conditions at a location.

Parameters:
  • lon (float) – Longitude.

  • lat (float) – Latitude.

Returns:

Keys: aqi (US AQI), category, dominant_pollutant, pollutants (list), date.

Return type:

dict or None

Example

>>> aq = get_air_quality(-111.89, 40.76)
>>> if aq:
...     print(f"AQI: {aq['aqi']} ({aq['category']})")
geeViz.googleMapsLib.get_elevation(lon: float, lat: float) float | None[source]

Get elevation in meters at a geographic location.

Parameters:
  • lon (float) – Longitude.

  • lat (float) – Latitude.

Returns:

Elevation in meters above sea level, or None on error.

Return type:

float or None

Example

>>> elev = get_elevation(-111.80, 40.68)
>>> print(f"{elev:.0f} meters")
geeViz.googleMapsLib.get_elevation_along_path(points: list[tuple[float, float]], samples: int = 100) list[dict[str, Any]][source]

Get elevation profile along a path.

Samples evenly-spaced points along the path defined by the input waypoints.

Parameters:
  • points (list) – Path waypoints as (lon, lat) tuples.

  • samples (int, optional) – Number of sample points. Defaults to 100.

Returns:

Sampled points with lon, lat, elevation, resolution.

Return type:

list of dict

Example

>>> path = [(-111.80, 40.68), (-111.85, 40.72)]
>>> profile = get_elevation_along_path(path, samples=50)
geeViz.googleMapsLib.get_elevations(points: list[tuple[float, float]]) list[dict[str, Any]][source]

Get elevations for multiple locations in one request.

Parameters:

points (list) – List of (lon, lat) tuples. Max ~500 per request.

Returns:

Each dict has lon, lat, elevation (meters), and resolution (meters).

Return type:

list of dict

Example

>>> pts = [(-111.80, 40.68), (-111.81, 40.69), (-111.82, 40.70)]
>>> elevs = get_elevations(pts)
>>> for e in elevs:
...     print(f"{e['lat']:.4f}: {e['elevation']:.0f}m")
geeViz.googleMapsLib.get_place_photo(photo_name: str, max_width: int = 400, max_height: int = 400) bytes | None[source]

Fetch a place photo by its resource name.

Photo names come from search_places() or search_nearby() results (the photo_name field).

Parameters:
  • photo_name (str) – Photo resource name from a Places API response.

  • max_width (int, optional) – Maximum width in pixels (1-4800).

  • max_height (int, optional) – Maximum height in pixels (1-4800).

Returns:

JPEG/PNG image bytes, or None on error.

Return type:

bytes or None

Example

>>> places = search_places("Arches National Park visitor center")
>>> if places and places[0]['photo_name']:
...     photo = get_place_photo(places[0]['photo_name'])
geeViz.googleMapsLib.get_solar_insights(lon: float, lat: float, quality: str = 'MEDIUM') dict[str, Any] | None[source]

Get rooftop solar potential for the nearest building.

Parameters:
  • lon (float) – Longitude.

  • lat (float) – Latitude.

  • quality (str, optional) – Image quality — "LOW", "MEDIUM", or "HIGH". Defaults to "MEDIUM".

Returns:

Keys: max_panels, max_capacity_watts, max_annual_kwh, roof_area_m2, max_sunshine_hours, carbon_offset_kg.

Return type:

dict or None

Example

>>> solar = get_solar_insights(-111.80, 40.68)
>>> if solar:
...     print(f"Capacity: {solar['max_capacity_watts']:.0f}W")
...     print(f"Annual: {solar['max_annual_kwh']:.0f} kWh")
geeViz.googleMapsLib.get_static_map(lon: float, lat: float, zoom: int = 14, size: str = '640x480', maptype: str = 'satellite', markers: list[tuple[float, float]] | None = None, path_points: list[tuple[float, float]] | None = None, path_color: str = 'red', format: str = 'png') bytes | None[source]

Get a static map image centered on a location.

Parameters:
  • lon (float) – Center longitude.

  • lat (float) – Center latitude.

  • zoom (int, optional) – Zoom level (1-21). Defaults to 14.

  • size (str, optional) – Image size. Defaults to "640x480".

  • maptype (str, optional) – "satellite", "roadmap", "terrain", or "hybrid". Defaults to "satellite".

  • markers (list, optional) – List of (lon, lat) marker positions.

  • path_points (list, optional) – List of (lon, lat) for a path overlay.

  • path_color (str, optional) – Path line color. Defaults to "red".

  • format (str, optional) – "png" or "jpg". Defaults to "png".

Returns:

Image bytes.

Return type:

bytes or None

Example

>>> img = get_static_map(-111.80, 40.68, zoom=16, maptype="hybrid")
>>> with open("map.png", "wb") as f:
...     f.write(img)
geeViz.googleMapsLib.get_timezone(lon: float, lat: float, timestamp: int = 0) dict[str, Any] | None[source]

Get timezone information for a location.

Parameters:
  • lon (float) – Longitude.

  • lat (float) – Latitude.

  • timestamp (int, optional) – Unix timestamp for DST calculation. Defaults to 0 (current time).

Returns:

Keys: timezone_id, timezone_name, utc_offset_seconds, dst_offset_seconds.

Return type:

dict or None

Example

>>> tz = get_timezone(-111.80, 40.68)
>>> print(tz['timezone_id'])  # 'America/Denver'
geeViz.googleMapsLib.interpret_image(image_bytes: bytes, prompt: str | None = None, model: str = 'gemini-3-flash-preview', context: str | None = None) dict[str, Any][source]

Interpret a Street View or satellite image using Google Gemini.

Sends the image to Gemini with instructions to identify and count all notable features. Returns a structured description with a tabular object inventory.

Parameters:
  • image_bytes (bytes) – JPEG or PNG image bytes.

  • prompt (str, optional) – Custom prompt to override the default. When None, uses a built-in prompt that asks for feature identification and a tabular count.

  • model (str, optional) – Gemini model name. Defaults to "gemini-3-flash-preview".

  • context (str, optional) – Additional context to include in the prompt (e.g. location, date, purpose). Defaults to None.

Returns:

Keys:

  • description (str): Full text description of the image.

  • object_counts (str): Markdown table of object counts.

  • raw_response (str): Complete Gemini response text.

Return type:

dict

Example

>>> img = streetview_image(-111.80, 40.68, heading=0)
>>> result = interpret_image(img)
>>> print(result['description'])
>>> print(result['object_counts'])
geeViz.googleMapsLib.label_streetview(lon: float, lat: float, prompt: str | None = None, heading: float = 0, fov: float = 360, pitch: float = 0, size: str = '640x480', radius: int = 50, source: str = 'default', model: str = 'gemini-3-flash-preview', max_labels: int = 30, font_size: int = 12) dict[str, Any] | None[source]

Fetch a Street View panorama and label detected objects with bounding boxes.

Uses Gemini’s vision model to detect objects and return bounding boxes, then draws labeled boxes on the panorama.

Parameters:
  • lon (float) – Longitude.

  • lat (float) – Latitude.

  • prompt (str, optional) – Custom detection prompt. The location context header and JSON format footer are always included.

  • heading (float, optional) – Center heading. Defaults to 0.

  • fov (float, optional) – Field of view (1-360). Defaults to 360.

  • pitch (float, optional) – Camera pitch. Defaults to 0.

  • size (str, optional) – Per-frame size. Defaults to "640x480".

  • radius (int, optional) – Search radius. Defaults to 50.

  • source (str, optional) – "default" or "outdoor".

  • model (str, optional) – Gemini model. Defaults to "gemini-3-flash-preview".

  • max_labels (int, optional) – Maximum objects. Defaults to 30.

  • font_size (int, optional) – Label font size. Defaults to 12.

Returns:

Keys: image, detections, summary, original, location.

Return type:

dict or None

Example

>>> result = label_streetview(-111.80, 40.68, fov=360)
>>> if result:
...     with open("labeled.jpg", "wb") as f:
...         f.write(result['image'])
...     print(result['summary'])
geeViz.googleMapsLib.nearest_roads(lon: float, lat: float) list[dict[str, Any]][source]

Find the nearest road segments to a point.

Parameters:
  • lon (float) – Longitude.

  • lat (float) – Latitude.

Returns:

Nearby road points with lon, lat, place_id.

Return type:

list of dict

Example

>>> roads = nearest_roads(-111.80, 40.68)
>>> for r in roads:
...     print(f"Road at ({r['lat']:.5f}, {r['lon']:.5f})")
geeViz.googleMapsLib.reverse_geocode(lon: float, lat: float) dict[str, Any] | None[source]

Convert coordinates to an address (reverse geocoding).

Parameters:
  • lon (float) – Longitude.

  • lat (float) – Latitude.

Returns:

Keys: formatted_address, place_id, types, address_components.

Return type:

dict or None

Example

>>> result = reverse_geocode(-111.80, 40.68)
>>> print(result['formatted_address'])
geeViz.googleMapsLib.search_nearby(lat: float, lon: float, radius: float = 1000, included_types: list[str] | None = None, max_results: int = 10) list[dict[str, Any]][source]

Search for places near a location using Nearby Search (New).

Parameters:
  • lat (float) – Latitude.

  • lon (float) – Longitude.

  • radius (float, optional) – Search radius in meters (max 50000). Defaults to 1000.

  • included_types (list, optional) – Place type filters (e.g. ["restaurant"]).

  • max_results (int, optional) – Maximum results (1-20). Defaults to 10.

Returns:

Same format as search_places().

Return type:

list of dict

Example

>>> nearby = search_nearby(40.76, -111.89, radius=2000,
...     included_types=["park"])
geeViz.googleMapsLib.search_places(query: str, lat: float | None = None, lon: float | None = None, radius: float = 5000, max_results: int = 10, included_types: list[str] | None = None) list[dict[str, Any]][source]

Search for places using the Google Places API (New) Text Search.

Parameters:
  • query (str) – Search text (e.g. “coffee shops”, “gas station”, “Yellowstone visitor center”).

  • lat (float, optional) – Latitude for location bias.

  • lon (float, optional) – Longitude for location bias.

  • radius (float, optional) – Bias radius in meters. Defaults to 5000.

  • max_results (int, optional) – Maximum results (1-20). Defaults to 10.

  • included_types (list, optional) – Place type filters (e.g. ["restaurant"], ["gas_station"]).

Returns:

Each dict has keys: name, display_name, address, lat, lon, types, rating, place_id, photo_name (first photo resource name, if any).

Return type:

list of dict

Example

>>> places = search_places("fire station", lat=40.76, lon=-111.89)
>>> for p in places:
...     print(f"{p['display_name']}: {p['address']}")
geeViz.googleMapsLib.segment_image(image_bytes: bytes, model_variant: str = 'b4', broad_categories: bool = False) dict[str, Any][source]

Perform pixel-level semantic segmentation using SegFormer.

Uses NVIDIA’s SegFormer model pre-trained on ADE20K (150 classes). Downloads the model on first use (~64 MB for B4).

Parameters:
  • image_bytes (bytes) – JPEG or PNG image bytes.

  • model_variant (str, optional) – SegFormer size — "b0" (fast, 3.8M params), "b1", "b2", "b3", "b4" (balanced, 64M params), or "b5" (best, 82M params). Defaults to "b4".

  • broad_categories (bool, optional) – If True, merge the 150 ADE20K classes into broad land cover categories (sky, vegetation, impervious, building, vehicle, water, terrain, etc.). Defaults to False.

Returns:

Keys:

  • class_map (numpy.ndarray): (H, W) array of class IDs.

  • class_names (list): Class name for each ID.

  • colored_image (bytes): JPEG with colored overlay.

  • legend (dict): {class_name: hex_color} for classes present.

  • summary (str): Markdown table of area percentages.

  • area_pct (dict): {class_name: float} area percentages.

Return type:

dict

Example

>>> pano = streetview_panorama(-111.80, 40.68, fov=360)
>>> seg = segment_image(pano)
>>> print(seg['summary'])
>>> with open("segmented.jpg", "wb") as f:
...     f.write(seg['colored_image'])
geeViz.googleMapsLib.segment_streetview(lon: float, lat: float, heading: float = 0, fov: float = 360, pitch: float = 0, size: str = '640x480', radius: int = 50, source: str = 'default', model_variant: str = 'b4', broad_categories: bool = True) dict[str, Any] | None[source]

Fetch a Street View panorama and segment it with SegFormer.

Convenience wrapper that combines streetview_panorama() and segment_image().

Parameters:
Returns:

Same as segment_image() plus original (raw panorama bytes) and location (address string). Returns None if no Street View coverage.

Return type:

dict or None

Example

>>> result = segment_streetview(-111.80, 40.68, fov=360)
>>> if result:
...     print(result['summary'])
...     with open("segmented.jpg", "wb") as f:
...         f.write(result['colored_image'])
geeViz.googleMapsLib.snap_to_roads(points: list[tuple[float, float]], interpolate: bool = False) list[dict[str, Any]][source]

Snap GPS points to the nearest road segments.

Parameters:
  • points (list) – GPS trace as (lon, lat) tuples. Max 100 points.

  • interpolate (bool, optional) – If True, interpolate additional points along the road between snapped locations. Defaults to False.

Returns:

Snapped points with lon, lat, place_id, and original_index (which input point this snapped from).

Return type:

list of dict

Example

>>> gps = [(-111.80, 40.68), (-111.81, 40.69), (-111.82, 40.70)]
>>> snapped = snap_to_roads(gps)
>>> for s in snapped:
...     print(f"({s['lat']:.5f}, {s['lon']:.5f})")
geeViz.googleMapsLib.streetview_html(lon: float, lat: float, headings: list[float] | None = None, pitch: float = 0, fov: float = 90, size: str = '400x300', radius: int = 50, source: str = 'default', title: str | None = None) str | None[source]

Generate an HTML panel with embedded Street View images.

Parameters:
Returns:

Self-contained HTML string, or None if no imagery.

Return type:

str or None

geeViz.googleMapsLib.streetview_image(lon: float, lat: float, heading: float = 0, pitch: float = 0, fov: float = 90, size: str = '640x480', radius: int = 50, source: str = 'default') bytes | None[source]

Fetch a Street View static image as JPEG bytes.

Returns None if no imagery exists (checks metadata first).

Parameters:
  • lon (float) – Longitude.

  • lat (float) – Latitude.

  • heading (float, optional) – Compass heading (0=N, 90=E, 180=S, 270=W).

  • pitch (float, optional) – Camera pitch (positive=up).

  • fov (float, optional) – Field of view (1-120). Defaults to 90.

  • size (str, optional) – Image size. Defaults to "640x480".

  • radius (int, optional) – Search radius. Defaults to 50.

  • source (str, optional) – "default" or "outdoor".

Returns:

JPEG image bytes.

Return type:

bytes or None

geeViz.googleMapsLib.streetview_images_cardinal(lon: float, lat: float, pitch: float = 0, fov: float = 90, size: str = '640x480', radius: int = 50, source: str = 'default') dict[str, bytes] | None[source]

Fetch Street View images looking N, E, S, and W.

Returns None if no imagery exists.

Parameters:
Returns:

{"N": bytes, "E": bytes, "S": bytes, "W": bytes}.

Return type:

dict or None

geeViz.googleMapsLib.streetview_metadata(lon: float, lat: float, radius: int = 50, source: str = 'default') dict[str, Any][source]

Check if Street View imagery exists at a location.

This is a free call (no quota consumed).

Parameters:
  • lon (float) – Longitude in decimal degrees.

  • lat (float) – Latitude in decimal degrees.

  • radius (int, optional) – Search radius in meters. Defaults to 50.

  • source (str, optional) – "default" or "outdoor".

Returns:

Keys: status, pano_id, location, date, copyright.

Return type:

dict

Example

>>> meta = streetview_metadata(-111.89, 40.76)
>>> if meta['status'] == 'OK':
...     print(f"Imagery from {meta['date']}")
geeViz.googleMapsLib.streetview_panorama(lon: float, lat: float, heading: float = 0, fov: float = 360, pitch: float = 0, size: str = '640x480', radius: int = 50, source: str = 'default') bytes | None[source]

Fetch a wide-angle or full 360° Street View panorama as a stitched image.

The Google Street View Static API caps FOV at 120°. This function automatically splits wider requests into multiple 120° frames and stitches them horizontally using PIL.

Parameters:
  • lon (float) – Longitude.

  • lat (float) – Latitude.

  • heading (float, optional) – Center compass heading of the panorama (0=North). The panorama spans heading - fov/2 to heading + fov/2. Defaults to 0.

  • fov (float, optional) – Total horizontal field of view in degrees (1–360). Values ≤ 120 are handled in a single frame. Defaults to 360.

  • pitch (float, optional) – Camera pitch. Defaults to 0.

  • size (str, optional) – Per-frame size as "WxH". Defaults to "640x480".

  • radius (int, optional) – Search radius. Defaults to 50.

  • source (str, optional) – "default" or "outdoor".

Returns:

JPEG bytes of the stitched panorama, or None if no imagery exists.

Return type:

bytes or None

Example

>>> pano = streetview_panorama(-111.80, 40.68, heading=0, fov=360)
>>> if pano:
...     with open("panorama_360.jpg", "wb") as f:
...         f.write(pano)
geeViz.googleMapsLib.validate_address(address: str, region_code: str = 'US') dict[str, Any] | None[source]

Validate and standardize an address.

Parameters:
  • address (str) – Address to validate.

  • region_code (str, optional) – ISO country code. Defaults to "US".

Returns:

Keys: formatted_address, lat, lon, verdict (address quality), components (parsed parts), usps_data (USPS-standardized for US addresses).

Return type:

dict or None

Example

>>> result = validate_address("4240 olympic way, slc ut")
>>> print(result['formatted_address'])

Data Management Modules

geeViz.taskManagerLib

Utilities for managing and monitoring Earth Engine export tasks.

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

Functions for managing Earth Engine assets and collections.

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.assetManagerLib.year_month_day_to_seconds(year_month_day)[source]

Converts a date to seconds since epoch.

Parameters:

year_month_day (list) – List containing year, month, and day.

Returns:

Seconds since epoch.

Return type:

int

Example

>>> year_month_day_to_seconds([2020, 1, 1])

geeViz.cloudStorageManagerLib

Tools for interacting with Google Cloud Storage for geospatial data.

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

Utilities for converting Earth Engine data structures to pandas DataFrames.

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())

MCP Server

geeViz.mcp

MCP (Model Context Protocol) server package. See MCP Server for setup and usage guide.

geeViz MCP (Model Context Protocol) server package.

Exposes an MCP server with 34 execution and introspection tools for Earth Engine via geeViz. Unlike static code snippets, these tools execute code in a persistent REPL, inspect live GEE assets, and dynamically query API signatures.

Quick start:

Run server: python -m geeViz.mcp.server Help: python -m geeViz.mcp.server –help As package: python -m geeViz.mcp –help

In code: from geeViz.mcp import app

See geeViz/mcp/README.md for setup and tool documentation.

geeViz.mcp.server

MCP server implementation with 22 tools for code execution, API introspection, asset management, map control, Google Maps, and report generation. Charting, thumbnails, EDW queries, and geocoding are accessed via run_code.

geeViz MCP Server – execution and introspection tools for Earth Engine via geeViz.

Unlike static doc snippets, this server executes code, inspects live GEE assets, and dynamically queries API signatures. 27 tools.

geeViz.mcp.server.add_report_section(ee_obj_var: str, geometry_var: str, title: str = 'Section', prompt: str = '', thumb_format: str = 'png', band_names: str = '', scale: int = 30, chart_types: str = '', basemap: str = '', burn_in_geometry: bool = False, geometry_outline_color: str = '', geometry_fill_color: str = '', transition_periods: str = '', sankey_band_name: str = '', feature_label: str = '', area_format: str = 'Percentage', date_format: str = 'YYYY', reducer: str = '', generate_table: bool = True, generate_chart: bool = True) str[source]

Add a section to the active report.

Each section analyses one ee.Image or ee.ImageCollection over a geometry. The report automatically generates a thumbnail, data table, chart, and LLM narrative for each section.

Parameters:
  • ee_obj_var – Name of an ee.Image or ee.ImageCollection variable in the REPL namespace.

  • geometry_var – Name of an ee.Geometry, ee.Feature, or ee.FeatureCollection variable in the REPL namespace.

  • title – Section heading.

  • prompt – Optional per-section guidance for the LLM narrative.

  • thumb_format – “png” (static), “gif” (animated), “filmstrip” (grid), or “none” (no thumbnail). Default “png”.

  • band_names – Comma-separated band names (auto-detected if empty).

  • scale – Pixel scale in meters (default 30).

  • chart_types – Comma-separated list of chart types to produce (0-3). Valid types: “bar”, “line+markers”, “donut”, “scatter”, “sankey”, “stacked_bar”, “stacked_line+markers”. When “sankey” is included, transition_periods and sankey_band_name are used for that chart. Leave empty to auto-detect a single chart type. Examples: “sankey,line+markers”, “bar,donut”, “sankey”.

  • basemap – Basemap preset for thumbnail (e.g. “esri-satellite”).

  • burn_in_geometry – Burn study area boundary onto the thumbnail.

  • geometry_outline_color – Boundary outline color (e.g. “white”, “red”).

  • geometry_fill_color – Boundary fill color with alpha (e.g. “FFFFFF33”).

  • transition_periods – JSON list of year pairs for Sankey (e.g. “[[1985,2000],[2000,2024]]”).

  • sankey_band_name – Band name for Sankey (auto-detected if empty).

  • feature_label – Property for per-feature labels (FeatureCollection).

  • area_format – “Percentage” (default), “Hectares”, “Acres”, “Pixels”.

  • date_format – EE date format (default “YYYY”).

  • reducer – Override reducer (“mean”, “first”, “mode”, etc.).

  • generate_table – Include a data table (default True).

  • generate_chart – Include a chart (default True).

Returns:

Confirmation with the section index and title.

geeViz.mcp.server.cancel_tasks(name_filter: str = '') str[source]

Cancel running and ready Earth Engine tasks.

If name_filter is provided, cancels only tasks whose description contains the filter string. Otherwise cancels ALL ready/running tasks.

Uses geeViz’s taskManagerLib for the actual cancellation.

Parameters:

name_filter – Optional substring filter. Only tasks whose description contains this string will be cancelled. If empty, all ready/running tasks are cancelled.

Returns:

JSON with task counts and cancellation status.

geeViz.mcp.server.clear_report() str[source]

Discard the active report and all its sections.

Returns:

Confirmation that the report was cleared.

geeViz.mcp.server.create_report(title: str = 'Report', theme: str = 'dark', layout: str = 'report', tone: str = 'neutral', header_text: str = '', prompt: str = '') str[source]

Create (or reset) a report. Must be called before add_report_section.

Initializes a new Report object that persists across MCP calls. Any previously active report is discarded.

Parameters:
  • title – Report title.

  • theme – “dark” (default) or “light”.

  • layout – “report” (portrait, vertical) or “poster” (landscape grid).

  • tone – “neutral” (default), “informative”, “technical”, or custom tone.

  • header_text – Introductory text below the title.

  • prompt – Additional guidance for the executive summary LLM narrative.

Returns:

Confirmation with the report title and settings.

geeViz.mcp.server.env_info(action: str = 'version') str[source]

Get environment information: versions, REPL namespace, or project details.

Parameters:

action – What to return: - “version” (default): geeViz, EE, and Python versions. - “namespace”: User-defined variables in the REPL (no getInfo calls). - “project”: Current EE project ID and root assets.

Returns:

JSON with action-specific results.

geeViz.mcp.server.examples(action: str = 'list', name: str = '', filter: str = '') str[source]

List or read geeViz example scripts.

Parameters:
  • action – “list” (default) to list available examples, or “get” to read the source of a specific example.

  • name – For action=”get”, the example name (with or without extension).

  • filter – For action=”list”, optional substring filter (case-insensitive).

Returns:

JSON list of {name, description} objects. For “get”: The example source code.

Return type:

For “list”

geeViz.mcp.server.export_image(destination: str, image_var: str, region_var: str = '', scale: int = 30, crs: str = 'EPSG:4326', overwrite: bool = False, asset_id: str = '', pyramiding_policy: str = 'mean', output_name: str = '', drive_folder: str = '', bucket: str = '', output_no_data: int = -32768, file_format: str = 'GeoTIFF') str[source]

Export an ee.Image to a GEE asset, Google Drive, or Cloud Storage.

Parameters:
  • destination – Where to export – “asset”, “drive”, or “cloud”.

  • image_var – Name of the ee.Image variable in the REPL namespace.

  • region_var – Name of an ee.Geometry or ee.FeatureCollection variable for the export region. Required for drive/cloud exports; optional for asset exports (uses image footprint if omitted).

  • scale – Output resolution in meters (default 30).

  • crs – Coordinate reference system (default “EPSG:4326”).

  • overwrite – If True, overwrite existing asset/file (default False).

  • Asset-specific – asset_id: Full destination asset ID (required for destination=”asset”). pyramiding_policy: “mean” (default), “mode”, “min”, “max”, “median”, “sample”.

  • Drive-specific – output_name: Output filename without extension (required for drive/cloud). drive_folder: Google Drive folder name (required for destination=”drive”).

  • Storage-specific (Cloud) – output_name: Output filename without extension (required for drive/cloud). bucket: GCS bucket name (required for destination=”cloud”). output_no_data: NoData value (default -32768). file_format: “GeoTIFF” (default) or “TFRecord”.

Returns:

JSON with export status or an error.

geeViz.mcp.server.generate_report(format: str = 'html', output_filename: str = '') str[source]

Generate the report from all added sections.

Runs all EE computations (thumbnails, charts, tables) and LLM narratives in parallel, then renders the final output. This may take 30-120 seconds depending on the number of sections.

Parameters:
  • format – Output format – “html” (interactive charts, default), “md” (markdown text only), or “pdf” (static images).

  • output_filename – Filename for the output (saved to generated_outputs/). Auto-generated if empty.

Returns:

The file path of the generated report, plus a metadata summary.

geeViz.mcp.server.get_api_reference(module: str, function_name: str = '') str[source]

Look up the signature and docstring of a geeViz function or module.

Uses Python’s inspect module – always reflects the installed code.

Parameters:
  • module – Short module name. One of: geeView, getImagesLib, changeDetectionLib, gee2Pandas, assetManagerLib, taskManagerLib, foliumView, phEEnoViz, cloudStorageManagerLib, chartingLib, thumbLib, reportLib, getSummaryAreasLib, edwLib.

  • function_name – Optional function or class name within the module. If omitted, returns the module-level docstring.

Returns:

Signature and docstring text, or error message.

geeViz.mcp.server.get_catalog_info(dataset_id: str) str[source]

Get detailed STAC metadata for a GEE dataset.

Fetches the full STAC JSON record from earthengine-stac.storage.googleapis.com and returns it as-is. The record includes bands (with classes, wavelengths, scale/offset), description, temporal/spatial extent, keywords, license, visualization parameters, provider info, and links.

This is the “drill down” companion to search_datasets – use search_datasets to find datasets, then get_catalog_info for full details.

Only works for official GEE datasets (STAC records don’t exist for community datasets). For community datasets, use inspect_asset instead.

Parameters:

dataset_id – Full GEE dataset ID (e.g. “LANDSAT/LC09/C02/T1_L2”).

Returns:

The full STAC JSON record for the dataset, or an error message.

geeViz.mcp.server.get_reference_data(name: str = '') str[source]

Look up geeViz reference dictionaries (band mappings, collection IDs, viz params, etc.).

Parameters:

name – Name of the reference dict to retrieve. Pass “” (empty) to list all available dicts with descriptions.

Returns:

JSON string with the dict contents or listing of available dicts.

geeViz.mcp.server.get_report_status() str[source]

Check the current report status – title, theme, section count, and section titles.

Returns:

Report status or a message if no report is active.

geeViz.mcp.server.get_streetview(lon: float, lat: float, headings: str = '0,90,180,270', pitch: float = 0, fov: float = 90, radius: int = 50, source: str = 'default') str[source]

Get Google Street View imagery at a location for ground-truthing.

Checks if Street View coverage exists, then fetches static images at the requested headings (compass directions). Returns images inline for visual inspection.

Useful for ground-truthing remote sensing analysis — see what a location actually looks like from the ground.

Parameters:
  • lon – Longitude in decimal degrees.

  • lat – Latitude in decimal degrees.

  • headings – Comma-separated compass headings in degrees (0=North, 90=East, 180=South, 270=West). Default “0,90,180,270” (all 4 cardinal directions).

  • pitch – Camera pitch (-90 to 90). 0=horizontal, positive=up.

  • fov – Field of view in degrees (1-120). Lower = more zoom. Default 90.

  • radius – Search radius in meters for nearest panorama. Default 50.

  • source – “default” (all) or “outdoor” (outdoor only).

Returns:

Metadata (date, location, copyright) and Street View images. Returns error if no imagery exists at the location.

geeViz.mcp.server.inspect_asset(asset_id: str, start_date: str = '', end_date: str = '', region_var: str = '') str[source]

Get detailed metadata for any GEE asset (Image, ImageCollection, FeatureCollection, etc.).

Returns band names/types, CRS, scale, date range, size, columns, and properties. Uses ee.data.getInfo for fast catalog metadata, then fetches live details with a 10-second timeout per query to avoid hangs on large collections.

Parameters:
  • asset_id – Full Earth Engine asset ID (e.g. “COPERNICUS/S2_SR_HARMONIZED”).

  • start_date – Optional start date filter for ImageCollections (YYYY-MM-DD).

  • end_date – Optional end date filter for ImageCollections (YYYY-MM-DD).

  • region_var – Optional name of an ee.Geometry or ee.FeatureCollection variable in the REPL namespace for spatial filtering (ImageCollections only).

Returns:

JSON with asset metadata.

geeViz.mcp.server.list_assets(folder: str) str[source]

List assets in a GEE folder or collection.

Parameters:

folder – Full asset path (e.g. “projects/my-project/assets/my-folder”).

Returns:

JSON list of {id, type, sizeBytes} for each asset (max 200).

geeViz.mcp.server.manage_asset(action: str, asset_id: str = '', dest_id: str = '', overwrite: bool = False, folder_type: str = 'Folder', all_users_can_read: bool = False, readers: str = '', writers: str = '') str[source]

Manage GEE assets: delete, copy, move, create folders, update permissions.

Parameters:
  • action – Operation to perform: - “delete”: Delete a single asset. - “copy”: Copy asset_id to dest_id. - “move”: Copy asset_id to dest_id, then delete source. - “create”: Create a folder or ImageCollection at asset_id. - “update_acl”: Update permissions on asset_id.

  • asset_id – Full asset path. Required for all actions. For “create”, this is the folder path to create.

  • dest_id – Destination path (required for “copy” and “move”).

  • overwrite – If True, overwrite existing destination (default False).

  • folder_type – For action=”create” – “Folder” (default) or “ImageCollection”.

  • all_users_can_read – For action=”update_acl” – make publicly readable.

  • readers – For action=”update_acl” – comma-separated reader emails.

  • writers – For action=”update_acl” – comma-separated writer emails.

Returns:

JSON confirmation or error.

geeViz.mcp.server.map_control(action: str = 'view', open_browser: bool = True) str[source]

Control the geeView interactive map.

Parameters:
  • action – Action to perform: - “view” (default): Open the map and return the URL. - “layers”: List current layers, visibility, and viz params. - “clear”: Remove all layers and commands.

  • open_browser – For action=”view”, whether to open in browser (default True).

Returns:

JSON with action-specific results.

async geeViz.mcp.server.run_code(code: str, timeout: int = 120, reset: bool = False, ctx: Context = None) str[source]

Execute Python/GEE code in a persistent REPL namespace (like Jupyter).

The namespace persists across calls – variables set in one call are available in the next. Pre-populated with: ee, Map (gv.Map), gv (geeViz.geeView), gil (geeViz.getImagesLib), sal (geeViz.getSummaryAreasLib), tl (geeViz.outputLib.thumbs), rl (geeViz.outputLib.reports), save_file.

Sandbox mode: When the server is run with --sandbox or over HTTP to a non-localhost address, open(), os, sys, eval, etc. are blocked. For local/stdio use (the default), sandbox is OFF and full Python access is available. Use save_file(filename, content) to write files to the generated_outputs/ directory regardless of sandbox mode.

While executing, progress heartbeats are sent every ~10 seconds to keep the MCP client connection alive and inform the agent that the tool is still running.

Parameters:
  • code – Python code to execute.

  • timeout – Max seconds to wait (default 120). On Windows a hung getInfo() cannot be force-killed; the thread continues in background.

  • reset – If True, clear the namespace and re-initialize before executing.

  • ctx – MCP Context (auto-injected by FastMCP). Used for progress reporting.

Returns:

success (bool), stdout, stderr, result, error.

Return type:

JSON with keys

geeViz.mcp.server.save_session(filename: str = '', format: str = 'py') str[source]

Save the accumulated run_code history to a .py script or .ipynb notebook.

Parameters:
  • filename – Optional custom filename (saved in geeViz/mcp/generated_scripts/). If omitted, uses a timestamped default. The correct extension is added automatically based on format.

  • format – Output format – “py” (default) for a standalone Python script, “ipynb” for a Jupyter notebook.

Returns:

JSON with the file path and number of code blocks/cells saved.

geeViz.mcp.server.search_datasets(query: str, source: str = 'all', max_results: int = 50) str[source]

Search the GEE dataset catalog by keyword.

Searches both the official Earth Engine catalog (~500+ datasets) and the community catalog (~200+ datasets). Uses word-level matching against title, tags, id, and provider fields with relevance scoring.

Parameters:
  • query – Search terms (e.g. “landsat surface reflectance”, “DEM”, “sentinel fire”). Case-insensitive.

  • source – Which catalog to search: “official”, “community”, or “all” (default).

  • max_results – Maximum number of results to return (default 10).

Returns:

JSON list of matching datasets with id, title, type, provider, tags, source, and additional metadata.

geeViz.mcp.server.search_functions(query: str = '', module: str = '') str[source]

Search for functions across geeViz modules, or list functions in a specific module.

Combines search and listing into one tool: - query only → search all modules for matching functions (by name or docstring) - module only → list all public functions in that module - both → search within a specific module - neither → return list of available modules with usage hint

Parameters:
  • query – Search term (case-insensitive). Matched against function names and the first line of their docstrings.

  • module – Short module name to restrict search to a single module. Valid names: geeView, getImagesLib, changeDetectionLib, gee2Pandas, assetManagerLib, taskManagerLib, foliumView, phEEnoViz, cloudStorageManagerLib, chartingLib, getSummaryAreasLib.

Returns:

JSON with matching functions. Each entry has module, name, type, description.

geeViz.mcp.server.search_places(query: str, lon: float = 0, lat: float = 0, radius: float = 5000, max_results: int = 10) str[source]

Search for places using the Google Places API.

Useful for finding landmarks, businesses, or points of interest near a study area. Can also geocode addresses.

Parameters:
  • query – Search text (e.g. “fire station”, “visitor center”, “4240 S Olympic Way, SLC, UT”).

  • lon – Longitude for location bias (0 = no bias).

  • lat – Latitude for location bias (0 = no bias).

  • radius – Bias radius in meters. Default 5000.

  • max_results – Maximum results (1-20). Default 10.

Returns:

JSON with matching places (name, address, coordinates, rating, types).

geeViz.mcp.server.track_tasks(name_filter: str = '') str[source]

Get status of recent Earth Engine tasks.

Parameters:

name_filter – Optional case-insensitive filter on task description.

Returns:

JSON list of recent tasks with description, state, type, start time, runtime, and error message (max 50).