Details#
geeViz.geeView#
View GEE objects using Python
geeViz.geeView is the core module for managing GEE objects on the geeViz mapper object. geeViz instantiates an instance of the mapper class as Map by default. Layers can be added to the map using Map.addLayer or Map.addTimeLapse and then viewed using the Map.view method.
- geeViz.geeView.baseDomain(url)[source]#
Get root domain for a given url
- Parameters:
url (str) – URL to find the base domain of
- Returns:
domain of given URL
- Return type:
str
- geeViz.geeView.cleanAccessToken(accessToken)[source]#
Remove trailing ‘….’ in generated access token
- Parameters:
accessToken (str) – Raw access token
- Returns:
Given access token without trailing ‘….’
- Return type:
str
- geeViz.geeView.color_dict_maker(gradient: list[list[int]]) dict [source]#
Takes in a list of RGB sub-lists and returns dictionary of colors in RGB and hex form for use in a graphing function defined later on
- geeViz.geeView.getProject(overwrite=False)[source]#
Tries to find the current Google Cloud Platform project id
- Parameters:
overwrite (bool, optional) – Whether or not to overwrite a cached project ID file
- Returns:
The currently selected Google Cloud Platform project id
- Return type:
str
- geeViz.geeView.get_poly_gradient_ct(palette: list[str], min: int, max: int) list[str] [source]#
Take a palette and a set of min and max stretch values to get a 1:1 value to color hex list
- Parameters:
palette (list) – A list of hex code colors that will be interpolated
min (int) – The min value for the stretch
max (int) – The max value for the stretch
- Returns:
A list of linearly interpolated hex codes where there is 1:1 color to value from min-max (inclusive)
- Return type:
list
>>> import geeViz.geeView as gv >>> viz = {"palette": ["#FFFF00", "00F", "0FF", "FF0000"], "min": 1, "max": 20} >>> color_ramp = gv.get_poly_gradient_ct(viz["palette"], viz["min"], viz["max"]) >>> print("Color ramp:", color_ramp)
- geeViz.geeView.hex_to_rgb(value: str) tuple [source]#
Return (red, green, blue) for the color given as #rrggbb.
- geeViz.geeView.isPortActive(port: int = 8001)[source]#
See if a given port number is currently active
- Parameters:
port (int) – Port number to check status of
- Returns:
Whether or not the port is already active
- Return type:
bool
- geeViz.geeView.is_notebook()[source]#
Check if inside Jupyter shell
- Returns:
Whether inside Jupyter shell or not
- Return type:
bool
- geeViz.geeView.linear_gradient(start_hex: str, finish_hex: str = '#FFFFFF', n: int = 10) dict [source]#
returns a gradient list of (n) colors between two hex colors. start_hex and finish_hex should be the full six-digit color string, inlcuding the number sign (“#FFFFFF”)
- class geeViz.geeView.mapper(port: int = 8001)[source]#
Primary geeViz map setup and manipulation object
Map object that is used to manage layers, activated user input methods, and launching the map viewer user interface
- Parameters:
port (int, default 8001) – Which port to user for web server. Sometimes a port will become “stuck,” so this will need set to some other number than what it was set at in previous runs of a given session.
- port#
Which port to user for web server. Sometimes a port will become “stuck,” so this will need set to some other number than what it was set at in previous runs of a given session.
- Type:
int, default 8001
- proxy_url#
The proxy url the web server runs through for either Google Colab or Vertex AI Workbench. This is automatically specified in Google Colab, but in Vertex AI Workbench, the Map.proxy_url must be specified as the current URL Workbench Notebook is running from (e.g. https://code-dot-region.notebooks.googleusercontent.com/).
- Type:
str, default None
- refreshTokenPath#
Refresh token credentials file path
- Type:
str, default ee.oauth.get_credentials_path()
- serviceKeyPath#
Location of a service account key json. If provided, this will be used for authentication inside geeView instead of the refresh token
- Type:
str, default None
- project#
Can override which project geeView will use for authentication. While geeViz will try to find a project if ee.data._cloud_api_user_project isn’t already set (usually by ee.Initialize(project=”someProjectID”)) by prompting the user to enter one, in some builds, this does not work. Set this attribute manually if the URL say project=None when launching geeView using Map.view().
- Type:
str, default ee.data._cloud_api_user_project
- turnOffLayersWhenTimeLapseIsOn#
Whether all other layers should be turned off when a time lapse is turned on. This is set to True by default to avoid confusing layer order rendering that can occur when time lapses and non-time lapses are visible at the same time. Often this confusion is fine and visualizing time lapses and other layers is desired. Set Map.turnOffLayersWhenTimeLapseIsOn to False in this instance.
- Type:
bool, default True
- addAreaChartLayer(image: Image | ImageCollection, params: dict = {}, name: str | None = None, shouldChart: bool = True)[source]#
Use this method to add a layer for area charting that you do not want as a map layer as well. Once you add all area chart layers to the map, you can turn them on using the Map.populateAreaChartLayerSelect method. This will create a selection menu inside the Area Tools -> Area Tools Parameters menu. You can then turn layers to include in any area charts on and off from that menu.
- Parameters:
image (ImageCollection, Image) – ee Image or ImageCollection to add to include in area charting.
params (dict) –
Primary set of parameters for charting setup (colors, chart types, etc), charting, etc. The accepted keys are:
{
“reducer” (Reducer, default ee.Reducer.mean() if no bandName_class_values, bandName_class_names, bandName_class_palette properties are available. ee.Reducer.frequencyHistogram if those are available or thematic:True (see below)): The reducer used to compute zonal summary statistics.,
”crs” (str, default “EPSG:5070”): the coordinate reference system string to use for are chart zonal stats,
”transform” (list, default [30, 0, -2361915, 0, -30, 3177735]): the transform to snap to for zonal stats,
”scale” (int, default None): The spatial resolution to use for zonal stats. Only specify if transform : None.
”line” (bool, default True): Whether to create a line chart,
”sankey” (bool, default False): Whether to create Sankey charts - only available for thematic (discrete) inputs that have a system:time_start property set for each image,
”chartLabelMaxWidth” (int, default 40): The maximum number of characters, including spaces, allowed in a single line of a chart class label. The class name will be broken at this number of characters, including spaces, to go to the next line,
”chartLabelMaxLength” (int, default 100): The maximum number of characters, including spaces, allowed in a chart class label. Any class name with more characters, including spaces, than this number will be cut off at this number of characters,
”sankeyTransitionPeriods” (list of lists, default None): The years to use as transition periods for sankey charts (e.g. [[1985,1987],[2000,2002],[2020,2022]]). If not provided, users can enter years in the map user interface under Area Tools -> Transition Charting Periods. These will automatically be used for any layers where no sankeyTransitionPeriods were provided. If years are provided, the years in the user interface will not be used for that layer,
”sankeyMinPercentage” (float, default 0.5): The minimum percentage a given class has to be to be shown in the sankey chart,
”thematic” (bool): Whether input has discrete values or not. If True, it forces the reducer to ee.Reducer.frequencyHistogram() even if not specified and even if bandName_class_values, bandName_class_names, bandName_class_palette properties are not available,
”palette” (list, or comma-separated strings): List of hex codes for colors for charts. This is especially useful when bandName_class_values, bandName_class_names, bandName_class_palette properties are not available, but there is a desired set of colors for each band to have on the chart,
”showGrid” (bool, default True): Whether to show the grid lines on the line or bar graph,
”rangeSlider” (bool,default False): Whether to include the x-axis range selector on the bottom of each graph (https://plotly.com/javascript/range-slider/>),
”barChartMaxClasses” (int, default 20): The maximum number of classes to show for image bar charts. Will automatically only show the top bartChartMaxClasses in any image bar chart. Any downloaded csv table will still have all of the class counts,
”minZoomSpecifiedScale” (int, default 11): The map zoom level where any lower zoom level, not including this zoom level, will multiply the spatial resolution used for the zonal stats by 2 for each lower zoom level. E.g. if the minZoomSpecifiedScale is 9 and the scale is 30, any zoom level >= 9 will compute zonal stats at 30m spatial resolution. Then, at zoom level 8, it will be 60m. Zoom level 7 will be 120m, etc,
”chartPrecision” (int, default 3): Used to override the default global precision settings for a specific area charting layer. See setQueryPrecision for setting the global charting precision. When specified, for this specific area charting layer, will show the larger of chartPrecision decimal places or ceiling(chartDecimalProportion * total decimal places). E.g. if the number is 1.12345678, 0.25 of 8 decimal places is 2, so 3 will be used and yield 1.123,
”chartDecimalProportion” (float, default 0.25): Used to override the default global precision settings for a specific area charting layer. See setQueryPrecision for setting the global charting precision. When specified, for this specific area charting layer, will show the larger of chartPrecision decimal places or chartDecimalProportion * total decimal places. E.g. if the number is 1.1234567891234, ceiling(0.25 of 13) decimal places is 4, so 4 will be used and yield 1.1235,
”hovermode” (str, default “closest”): The mode to show hover text in area summary charts. Options include “closest”, “x”, “y”, “x unified”, and “y unified”,
}
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”,
}
}
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”,
}
}
name (str) – Descriptive name for map layer that will be shown on the map UI
visible (bool, default True) – Whether layer should be visible when map UI loads
>>> import geeViz.geeView as gv >>> Map = gv.Map >>> ee = gv.ee >>> lcms = ee.ImageCollection("USFS/GTAC/LCMS/v2023-9").filter(ee.Filter.calendarRange(2010, 2023, "year")) >>> Map.addTimeLapse(lcms.select(["Land_Cover"]), {"autoViz": True, "mosaic": True}, "LCMS Land Cover Time Lapse") >>> Map.addTimeLapse(lcms.select(["Change"]), {"autoViz": True, "mosaic": True}, "LCMS Change Time Lapse") >>> Map.addTimeLapse(lcms.select(["Land_Use"]), {"autoViz": True, "mosaic": True}, "LCMS Land Use Time Lapse") >>> Map.turnOnInspector() >>> Map.view()
- centerObject(feature: Geometry | Feature | FeatureCollection | Image, zoom: int | None = None)[source]#
Center the map on an object on loading
- Parameters:
feature (Feature, FeatureCollection, or Geometry) – The object to center the map on
zoom (int, optional) – If provided, will force the map to zoom to this level after centering it on the object. If not provided, the highest zoom level that allows the feature to be viewed fully will be used.
>>> from geeViz.geeView import * >>> pt = ee.Geometry.Point([-111, 41]) >>> Map.addLayer(pt.buffer(10), {}, "Plot") >>> Map.centerObject(pt) >>> Map.view()
- clearMap()[source]#
Removes all map layers and commands - useful if running geeViz in a notebook and don’t want layers/commands from a prior code block to still be included.
>>> from geeViz.geeView import * >>> lcms = ee.ImageCollection("USFS/GTAC/LCMS/v2023-9").filter('study_area=="CONUS"') >>> Map.addLayer(lcms, {"autoViz": True}, "LCMS") # Layer >>> Map.turnOnInspector() # Command >>> Map.clearMap() # Clear map layer and commands >>> Map.view()
- clearMapCommands()[source]#
Removes all map commands - useful if running geeViz in a notebook and don’t want commands from a prior code block to still be included, but want layers to remain.
>>> from geeViz.geeView import * >>> lcms = ee.ImageCollection("USFS/GTAC/LCMS/v2023-9").filter('study_area=="CONUS"') >>> Map.addLayer(lcms, {"autoViz": True}, "LCMS") # Layer >>> Map.turnOnInspector() # Command - this will be removed >>> Map.clearMapCommands() # Clear map comands only and leave layers >>> Map.view()
- clearMapLayers()[source]#
Removes all map layers - useful if running geeViz in a notebook and don’t want layers from a prior code block to still be included, but want commands to remain.
>>> from geeViz.geeView import * >>> lcms = ee.ImageCollection("USFS/GTAC/LCMS/v2023-9").filter('study_area=="CONUS"') >>> Map.addLayer(lcms, {"autoViz": True}, "LCMS") # Layer - this will be removed >>> Map.turnOnInspector() # Command - this will remain (even though there will be no layers to query) >>> Map.clearMapLayers() # Clear map layer only and leave commands >>> Map.view()
- populateAreaChartLayerSelect()[source]#
Once you add all area chart layers to the map, you can turn them on using this method- Map.populateAreaChartLayerSelect. This will create a selection menu inside the Area Tools -> Area Tools Parameters menu. You can then turn layers to include in any area charts on and off from that menu.
>>> import geeViz.geeView as gv >>> Map = gv.Map >>> ee = gv.ee >>> lcms = ee.ImageCollection("USFS/GTAC/LCMS/v2023-9").filter('study_area=="CONUS"') >>> Map.addLayer(lcms.select(["Change_Raw_Probability.*"]), {"reducer": ee.Reducer.stdDev(), "min": 0, "max": 10}, "LCMS Change Prob") >>> Map.addAreaChartLayer(lcms, {"line": True, "layerType": "ImageCollection"}, "LCMS All Thematic Classes Line", True) >>> Map.addAreaChartLayer(lcms, {"sankey": True}, "LCMS All Thematic Classes Sankey", True) >>> Map.populateAreaChartLayerSelect() >>> Map.turnOnAutoAreaCharting() >>> Map.view()
- setCanReorderLayers(canReorderLayers: bool)[source]#
Set whether layers can be reordered by dragging layer user interface objects. By default all non timelapse and non geojson layers can be reordereed by dragging.
- Parameters:
canReorderLayers (bool, default True) – Set whether layers can be reordered by dragging layer user interface objects. By default all non timelapse and non geojson layers can be reordereed by dragging.
>>> from geeViz.geeView import * >>> lcms = ee.ImageCollection("USFS/GTAC/LCMS/v2023-9").filter('study_area=="CONUS"') >>> Map.addLayer(lcms.select([2]), {"autoViz": True}, "LCMS Land Use") >>> Map.addLayer(lcms.select([1]), {"autoViz": True}, "LCMS Land Cover") >>> Map.addLayer(lcms.select([0]), {"autoViz": True}, "LCMS Change") >>> Map.turnOnInspector() >>> Map.setCanReorderLayers(False) # Notice you cannot drag and reorder layers. Change to True and rerun and notice you now can drag layers to reorder >>> Map.setCenter(-109.446, 43.620, 12) >>> Map.view()
- setCenter(lng: float, lat: float, zoom: int | None = None)[source]#
Center the map on a specified point and optional zoom on loading
- Parameters:
lng (int or float) – The longitude to center the map on
lat (int or float) – The latitude to center the map on
zoom (int, optional) – If provided, will force the map to zoom to this level after centering it on the provided coordinates. If not provided, the current zoom level will be used.
>>> from geeViz.geeView import * >>> Map.setCenter(-111,41,10) >>> Map.view()
- setMapTitle(title)[source]#
Set the title that appears in the left sidebar header and the page title
- Parameters:
title (str, default geeViz Data Explorer) – The title to appear in the header on the left sidebar as well as the title of the viewer webpage.
>>> from geeViz.geeView import * >>> lcms = ee.ImageCollection("USFS/GTAC/LCMS/v2023-9").filter('study_area=="CONUS"') >>> Map.addLayer(lcms, {"autoViz": True}, "LCMS") >>> Map.turnOnInspector() >>> Map.setMapTitle("<h2>A Custom Title!!!</h2>") # Set custom map title >>> Map.view()
- setQueryBoxColor(color: str)[source]#
Set the color of the query box to something other than yellow
- Parameters:
color (str, default "FFFF00") – Set the default query box color shown on the map by providing a hex color.
>>> from geeViz.geeView import * >>> lcms = ee.ImageCollection("USFS/GTAC/LCMS/v2023-9").filter('study_area=="CONUS"') >>> Map.addLayer(lcms.select([1]), {"autoViz": True}, "LCMS Land Cover") >>> Map.turnOnInspector() >>> Map.setQueryBoxColor("0FF") >>> Map.view()
- setQueryCRS(crs: str)[source]#
The coordinate reference system string to query layers with
- Parameters:
(str (crs) – 5070”): Which projection (CRS) to use for querying map layers.
"EPSG (default) – 5070”): Which projection (CRS) to use for querying map layers.
>>> import geeViz.getImagesLib as gil >>> from geeViz.geeView import * >>> crs = gil.common_projections["NLCD_AK"]["crs"] >>> transform = gil.common_projections["NLCD_AK"]["transform"] >>> lcms = ee.ImageCollection("USFS/GTAC/LCMS/v2023-9").filter('study_area=="SEAK"') >>> Map.addLayer(lcms, {"autoViz": True}, "LCMS") >>> Map.turnOnInspector() >>> Map.setQueryCRS(crs) >>> Map.setQueryTransform(transform) >>> Map.setCenter(-144.36390353, 60.20479529215, 8) >>> Map.view()
- setQueryDateFormat(defaultQueryDateFormat: str = 'YYYY-MM-dd')[source]#
Set the date format to be used for any dates when querying.
- Parameters:
defaultQueryDateFormat (str, default "YYYY-MM-dd") – The date format string to use for query outputs with dates. To simplify date outputs, “YYYY” is often used instead of the default.
>>> from geeViz.geeView import * >>> lcms = ee.ImageCollection("USFS/GTAC/LCMS/v2023-9").filter('study_area=="CONUS"') >>> Map.addLayer(lcms.select([1]), {"autoViz": True}, "LCMS Land Cover") >>> Map.addLayer(lcms.select([0]), {"autoViz": True}, "LCMS Change") >>> Map.turnOnInspector() >>> Map.setQueryDateFormat("YYYY") >>> Map.view()
- setQueryPrecision(chartPrecision: int = 3, chartDecimalProportion: float = 0.25)[source]#
What level of precision to show for queried layers. This avoids showing too many digits after the decimal.
- Parameters:
chartPrecision (int, default 3) – Will show the larger of chartPrecision decimal places or ceiling(chartDecimalProportion * total decimal places). E.g. if the number is 1.12345678, 0.25 of 8 decimal places is 2, so 3 will be used and yield 1.123.
chartDecimalProportion (float, default 0.25) – Will show the larger of chartPrecision decimal places or chartDecimalProportion * total decimal places. E.g. if the number is 1.1234567891234, ceiling(0.25 of 13) decimal places is 4, so 4 will be used and yield 1.1235.
>>> import geeViz.getImagesLib as gil >>> from geeViz.geeView import * >>> s2s = gil.superSimpleGetS2(ee.Geometry.Point([-107.61, 37.85]), "2024-01-01", "2024-12-31", 190, 250).select(["blue", "green", "red", "nir", "swir1", "swir2"]) >>> projection = s2s.first().select(["nir"]).projection().getInfo() >>> s2s = s2s.map(lambda img: ee.Image(img).divide(10000).set("system:time_start",img.date().millis())) >>> Map.addLayer(s2s, gil.vizParamsFalse, "Sentinel-2 Images") >>> Map.addLayer(s2s.median(), gil.vizParamsFalse, "Sentinel-2 Composite") >>> Map.turnOnInspector() >>> Map.setQueryCRS(projection["crs"]) >>> Map.setQueryTransform(projection["transform"]) >>> Map.setQueryPrecision(chartPrecision=2, chartDecimalProportion=0.1) >>> Map.centerObject(s2s.first()) >>> Map.view()
- setQueryScale(scale: int)[source]#
What scale to query map layers with. Will also update the size of the box drawn on the map query layers are queried.
- Parameters:
scale (int, default None) – The spatial resolution to use for querying map layers in meters. If set, the query transform will be set to None in the map viewer.
>>> import geeViz.getImagesLib as gil >>> from geeViz.geeView import * >>> s2s = gil.superSimpleGetS2(ee.Geometry.Point([-107.61, 37.85]), "2024-01-01", "2024-12-31", 190, 250) >>> projection = s2s.first().select(["nir"]).projection().getInfo() >>> Map.addLayer(s2s.median(), gil.vizParamsFalse10k, "Sentinel-2 Composite") >>> Map.turnOnInspector() >>> Map.setQueryCRS(projection["crs"]) >>> Map.setQueryScale(projection["transform"][0]) >>> Map.centerObject(s2s.first()) >>> Map.view()
- setQueryToInfoWindow()[source]#
Set the location of query outputs to an info window popup over the map
>>> from geeViz.geeView import * >>> lcms = ee.ImageCollection("USFS/GTAC/LCMS/v2023-9").filter('study_area=="CONUS"') >>> Map.addLayer(lcms.select([1]), {"autoViz": True}, "LCMS Land Cover") >>> Map.turnOnInspector() >>> Map.setQueryToInfoWindow() >>> Map.view()
- setQueryToSidePane()[source]#
Set the location of query outputs to the right sidebar above the legend
>>> from geeViz.geeView import * >>> lcms = ee.ImageCollection("USFS/GTAC/LCMS/v2023-9").filter('study_area=="CONUS"') >>> Map.addLayer(lcms.select([1]), {"autoViz": True}, "LCMS Land Cover") >>> Map.turnOnInspector() >>> Map.setQueryToSidePane() >>> Map.view()
- setQueryTransform(transform: list[int])[source]#
What transform to query map layers with. Will also update the size of the box drawn on the map query layers are queried.
- Parameters:
transform (list, default [30, 0, -2361915, 0, -30, 3177735]) – The snap to grid to use for querying layers on the map. If set, the query scale will be set to None in the map viewer.
>>> import geeViz.getImagesLib as gil >>> from geeViz.geeView import * >>> s2s = gil.superSimpleGetS2(ee.Geometry.Point([-107.61, 37.85]), "2024-01-01", "2024-12-31", 190, 250) >>> projection = s2s.first().select(["nir"]).projection().getInfo() >>> Map.addLayer(s2s.median(), gil.vizParamsFalse10k, "Sentinel-2 Composite") >>> Map.turnOnInspector() >>> Map.setQueryCRS(projection["crs"]) >>> Map.setQueryTransform(projection["transform"]) >>> Map.centerObject(s2s.first()) >>> Map.view()
- setTitle(title)[source]#
Redundant function for setMapTitle. Set the title that appears in the left sidebar header and the page title
- Parameters:
title (str, default geeViz Data Explorer) – The title to appear in the header on the left sidebar as well as the title of the viewer webpage.
>>> from geeViz.geeView import * >>> lcms = ee.ImageCollection("USFS/GTAC/LCMS/v2023-9").filter('study_area=="CONUS"') >>> Map.addLayer(lcms, {"autoViz": True}, "LCMS") >>> Map.turnOnInspector() >>> Map.setMapTitle("<h2>A Custom Title!!!</h2>") # Set custom map title >>> Map.view()
- setYLabelBreakLength(maxLength: int)[source]#
Set the maximum length per line a Y axis label can have in charts
- Parameters:
maxLength (int, default 10) – Maximum number of characters in each line of a Y axis label. Will break total characters (setYLabelMaxLength) until maxLines (setYLabelMaxLines) is reached
>>> from geeViz.geeView import * >>> lcms = ee.ImageCollection("USFS/GTAC/LCMS/v2023-9").filter('study_area=="CONUS"') >>> Map.addLayer(lcms.select([1]), {"autoViz": True}, "LCMS Land Cover") >>> Map.setYLabelBreakLength(5) # Double-click on map to inspect area. Change to a larger number and rerun to see how Y labels are impacted >>> Map.turnOnInspector() >>> Map.setCenter(-109.446, 43.620, 12) >>> Map.view()
- setYLabelFontSize(fontSize: int)[source]#
Set the size of the font on the y-axis labels. Useful when y-axis labels are too large to fit on the chart.
- Parameters:
fontSize (int, default 10) – The font size used on the y-axis labels for query charting.
>>> from geeViz.geeView import * >>> lcms = ee.ImageCollection("USFS/GTAC/LCMS/v2023-9").filter('study_area=="CONUS"') >>> Map.addLayer(lcms.select([1]), {"autoViz": True}, "LCMS Land Cover") >>> Map.setYLabelFontSize(8) # Double-click on map to inspect area. Change to a different number and rerun to see how Y labels are impacted >>> Map.turnOnInspector() >>> Map.setCenter(-109.446, 43.620, 12) >>> Map.view()
- setYLabelMaxLength(maxLength: int)[source]#
Set the maximum length a Y axis label can have in charts
- Parameters:
maxLength (int, default 30) – Maximum number of characters in a Y axis label.
>>> from geeViz.geeView import * >>> lcms = ee.ImageCollection("USFS/GTAC/LCMS/v2023-9").filter('study_area=="CONUS"') >>> Map.addLayer(lcms.select([1]), {"autoViz": True}, "LCMS Land Cover") >>> Map.setYLabelMaxLength(10) # Double-click on map to inspect area. Change to a larger number and rerun to see how Y labels are impacted >>> Map.turnOnInspector() >>> Map.setCenter(-109.446, 43.620, 12) >>> Map.view()
- setYLabelMaxLines(maxLines)[source]#
Set the max number of lines each y-axis label can have.
- Parameters:
maxLines (int, default 5) – The maximum number of lines each y-axis label can have. Will simply exclude any remaining lines.
>>> from geeViz.geeView import * >>> lcms = ee.ImageCollection("USFS/GTAC/LCMS/v2023-9").filter('study_area=="CONUS"') >>> Map.addLayer(lcms.select([1]), {"autoViz": True}, "LCMS Land Cover") >>> Map.setYLabelMaxLines(3) # Double-click on map to inspect area. Change to a larger number and rerun to see how Y labels are impacted >>> Map.turnOnInspector() >>> Map.setCenter(-109.446, 43.620, 12) >>> Map.view()
- setZoom(zoom: int)[source]#
Set the map zoom level
- Parameters:
zoom (int) – The zoom level to set the map to on loading.
>>> from geeViz.geeView import * >>> Map.setZoom(10) >>> Map.view()
- turnOffAllLayers()[source]#
Turn off all layers added to the mapper object. Typically used in notebooks or iPython when you want to allow existing layers to remain, but want to turn them all off.
>>> #%% >>> from geeViz.geeView import * >>> lcms = ee.ImageCollection("USFS/GTAC/LCMS/v2023-9").filter('study_area=="CONUS"') >>> Map.addLayer(lcms.select([2]), {"autoViz": True}, "LCMS Land Use") >>> Map.addLayer(lcms.select([1]), {"autoViz": True}, "LCMS Land Cover") >>> Map.turnOnInspector() >>> Map.setCenter(-109.446, 43.620, 5) >>> Map.view() >>> #%% >>> Map.turnOffAllLayers() >>> Map.addLayer(lcms.select([0]), {"autoViz": True}, "LCMS Change") >>> Map.view()
- turnOnAllLayers()[source]#
Turn on all layers added to the mapper object
>>> #%% >>> from geeViz.geeView import * >>> lcms = ee.ImageCollection("USFS/GTAC/LCMS/v2023-9").filter('study_area=="CONUS"') >>> Map.addLayer(lcms.select([2]), {"autoViz": True}, "LCMS Land Use",False) >>> Map.addLayer(lcms.select([1]), {"autoViz": True}, "LCMS Land Cover",False) >>> Map.turnOnInspector() >>> Map.setCenter(-109.446, 43.620, 5) >>> Map.view() >>> #%% >>> Map.turnOnAllLayers() >>> Map.addLayer(lcms.select([0]), {"autoViz": True}, "LCMS Change") >>> Map.view()
- turnOnAutoAreaCharting()[source]#
Turn on automatic area charting upon map loading. This will automatically update charts by summarizing any visible layers with “canAreaChart” : True any time the map finishes panning or zooming.
>>> from geeViz.geeView import * >>> lcms = ee.ImageCollection("USFS/GTAC/LCMS/v2023-9").filter('study_area=="CONUS"') >>> Map.addLayer(lcms.select([1]), {"autoViz": True,'canAreaChart':True}, "LCMS Land Cover") >>> Map.turnOnAutoAreaCharting() >>> Map.view()
- turnOnInspector()[source]#
Turn on the query inspector tool upon map loading. This is used frequently so map layers can be queried as soon as the map viewer loads.
>>> from geeViz.geeView import * >>> lcms = ee.ImageCollection("USFS/GTAC/LCMS/v2023-9").filter('study_area=="CONUS"') >>> Map.addLayer(lcms.select([1]), {"autoViz": True}, "LCMS Land Cover") >>> Map.turnOnInspector() >>> Map.view()
- turnOnSelectionAreaCharting()[source]#
Turn on area charting by a user selected area upon map loading. This will update charts by summarizing any visible layers with “canAreaChart” : True when the user selects selection areas to summarize and hits the Chart Selected Areas button in the user interface under Area Tools -> Select an Area on Map.
>>> from geeViz.geeView import * >>> lcms = ee.ImageCollection("USFS/GTAC/LCMS/v2023-9").filter('study_area=="CONUS"') >>> Map.addLayer(lcms.select([1]), {"autoViz": True,'canAreaChart':True}, "LCMS Land Cover") >>> mtbsBoundaries = ee.FeatureCollection("USFS/GTAC/MTBS/burned_area_boundaries/v1") >>> mtbsBoundaries = mtbsBoundaries.map(lambda f: f.set("system:time_start", f.get("Ig_Date"))) >>> Map.addSelectLayer(mtbsBoundaries, {"strokeColor": "00F", "selectLayerNameProperty": "Incid_Name"}, "MTBS Fire Boundaries") >>> Map.turnOnSelectionAreaCharting() >>> Map.view()
- turnOnUserDefinedAreaCharting()[source]#
Turn on area charting by a user defined area upon map loading. This will update charts by summarizing any visible layers with “canAreaChart” : True when the user draws an area to summarize and hits the Chart Selected Areas button in the user interface under Area Tools -> User-Defined Area.
>>> from geeViz.geeView import * >>> lcms = ee.ImageCollection("USFS/GTAC/LCMS/v2023-9").filter('study_area=="CONUS"') >>> Map.addLayer(lcms.select([1]), {"autoViz": True,'canAreaChart':True}, "LCMS Land Cover") >>> Map.turnOnUserDefinedAreaCharting() >>> Map.view()
- view(open_browser: bool | None = None, open_iframe: bool | None = None, iframe_height: int = 525)[source]#
Compiles all map objects and commands and starts the map server
- Parameters:
open_browser (bool) – Whether or not to open the browser. If unspecified, will automatically be selected depending on whether geeViz is being used in a notebook (False) or not (True).
open_iframe (bool) – Whether or not to open an iframe. If unspecified, will automatically be selected depending on whether geeViz is being used in a notebook (True) or not (False).
iframe_height (int, default 525) – The height of the iframe shown if running inside a notebook
>>> from geeViz.geeView import * >>> lcms = ee.ImageCollection("USFS/GTAC/LCMS/v2023-9").filter('study_area=="CONUS"') >>> Map.addLayer(lcms, {"autoViz": True, "canAreaChart": True, "areaChartParams": {"line": True, "sankey": True}}, "LCMS") >>> Map.turnOnInspector() >>> Map.view()
- geeViz.geeView.polylinear_gradient(colors: list[str], n: int)[source]#
returns a list of colors forming linear gradients between all sequential pairs of colors. “n” specifies the total number of desired output colors
- geeViz.geeView.refreshToken()[source]#
Get a refresh token from currently authenticated ee instance
- Returns:
temporary access token
- Return type:
str
- geeViz.geeView.robustInitializer()[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 initialize to a project prior to importing geeViz
- geeViz.geeView.run_local_server(port: int = 8001)[source]#
Start a local webserver using the Python http.server
- Parameters:
port (int) – Port number to run local server at
- geeViz.geeView.serviceAccountToken(service_key_file_path)[source]#
Get a refresh token from service account key file credentials
- Returns:
temporary access token
- Return type:
str
geeViz.getImagesLib#
Get images and organize them so they are easier to work with
geeViz.getImagesLib is the core module for setting up various imageCollections from GEE. Notably, it facilitates Landsat, Sentinel-2, and MODIS data organization. This module helps avoid many common mistakes in GEE. Most functions ease matching band names, ensuring resampling methods are properly set, date wrapping, and helping with cloud and cloud shadow masking.
- geeViz.getImagesLib.HoCalcAlgorithm2(image: Image) Image [source]#
Applies an algal detection algorithm based on: Matthews, M. (2011) A current review of empirical procedures of remote sensing in inland and near-coastal transitional waters, International Journal of Remote Sensing, 32:21, 6855-6899, DOI: 10.1080/01431161.2010.512947.
- Parameters:
image – The input Earth Engine image.
- Returns:
The image with added bloom2 and NDGI bands.
- geeViz.getImagesLib.RefinedLee(img: Image) Image [source]#
Applies the Refined Lee speckle filter to a Sentinel-1 image.
- Parameters:
img – The input Sentinel-1 image in natural units.
- Returns:
The speckle filtered image.
- geeViz.getImagesLib.addDateBand(img: Image, maskTime: bool = False) Image [source]#
Adds a date band to an image.
- Parameters:
img – The input Earth Engine image.
maskTime – Whether to mask the date band based on the image mask.
- Returns:
The input image with an added date band.
- geeViz.getImagesLib.addFullYearJulianDayBand(img: Image) Image [source]#
Adds a full year Julian day band to an image.
- Parameters:
img – The input Earth Engine image.
- Returns:
The input image with an added full year Julian day band.
- geeViz.getImagesLib.addIndices(img: Image) Image [source]#
Adds various spectral indices to an image.
- Parameters:
img – The input Earth Engine image.
- Returns:
The image with added spectral indices.
- geeViz.getImagesLib.addJulianDayBand(img: Image) Image [source]#
Adds a Julian day band to an image.
- Parameters:
img – The input Earth Engine image.
- Returns:
The input image with an added Julian day band.
- geeViz.getImagesLib.addSAVIandEVI(img: Image) Image [source]#
Adds SAVI and EVI indices to an image.
- Parameters:
img – The input Earth Engine image.
- Returns:
The image with added SAVI and EVI indices.
- geeViz.getImagesLib.addSensorBand(img: Image, whichProgram: str, toaOrSR: str) Image [source]#
Adds a sensor band to an image.
- Parameters:
img – The input Earth Engine image.
whichProgram – The program (e.g., ‘C1_landsat’, “C2_landsat”, ‘sentinel2’).
toaOrSR – Whether the image is TOA or SR.
- Returns:
The input image with an added sensor band.
- geeViz.getImagesLib.addSoilIndices(img: Image) Image [source]#
Adds soil-related indices to an image.
- Parameters:
img – The input Earth Engine image.
- Returns:
The image with added soil indices.
- geeViz.getImagesLib.addTCAngles(image: Image) Image [source]#
Adds Tasseled Cap angles and distances to an image. Assumes image has bands: ‘brightness’, ‘greenness’, and ‘wetness’.
- Parameters:
image – The input Earth Engine image with brightness, greenness, and wetness bands.
- Returns:
The image with added Tasseled Cap angles and distances.
- geeViz.getImagesLib.addYearBand(img: Image) Image [source]#
Adds a year band to an image.
- Parameters:
img – The input Earth Engine image.
- Returns:
The input image with an added year band.
- geeViz.getImagesLib.addYearFractionBand(img: Image) Image [source]#
Adds a year fraction band to an image.
- Parameters:
img – The input Earth Engine image.
- Returns:
The input image with an added year fraction band.
- geeViz.getImagesLib.addYearJulianDayBand(img: Image) Image [source]#
Adds a year and Julian day band to an image.
- Parameters:
img – The input Earth Engine image.
- Returns:
The input image with an added year and Julian day band.
- geeViz.getImagesLib.addYearYearFractionBand(img: Image) Image [source]#
Adds a year and year fraction band to an image.
- Parameters:
img – The input Earth Engine image.
- Returns:
The input image with an added year and year fraction band.
- geeViz.getImagesLib.addZenithAzimuth(img: Image, toaOrSR: str, zenithDict: dict = {'SR': 'SOLAR_ZENITH_ANGLE', 'TOA': 'SUN_ELEVATION'}, azimuthDict: dict = {'SR': 'SOLAR_AZIMUTH_ANGLE', 'TOA': 'SUN_AZIMUTH'})[source]#
Adds solar zenith and azimuth angles in radians to an image.
- Parameters:
img – The input Earth Engine image.
toaOrSR – Whether the image is TOA or SR.
zenithDict – A dictionary mapping toaOrSR to the zenith band name.
azimuthDict – A dictionary mapping toaOrSR to the azimuth band name.
- Returns:
The image with added zenith and azimuth bands.
- geeViz.getImagesLib.applyBitMask(img: Image, bit: int, bitMaskBandName: str = 'QA_PIXEL') Image [source]#
Applies a bitmask to an image.
- Parameters:
img – The input image.
bit – The bit position to mask.
bitMaskBandName – The name of the QA band (default: “QA_PIXEL”).
- Returns:
The masked image.
- geeViz.getImagesLib.applyCloudScoreAlgorithm(collection: ImageCollection, cloudScoreFunction: function, cloudScoreThresh: float = 20, cloudScorePctl: float = 10, contractPixels: float = 1.5, dilatePixels: float = 3.5, performCloudScoreOffset: bool = True, preComputedCloudScoreOffset: Image = None) ImageCollection [source]#
Applies a cloud score algorithm to an image collection.
- Parameters:
collection – The input Earth Engine image collection.
cloudScoreFunction – A function to calculate the cloud score for an image.
cloudScoreThresh – The cloud score threshold for masking (default: 20).
cloudScorePctl – The percentile for computing the cloud score offset (default: 10).
contractPixels – The contraction kernel size (default: 1.5).
dilatePixels – The dilation kernel size (default: 3.5).
performCloudScoreOffset – Whether to perform cloud score offsetting (default: True).
preComputedCloudScoreOffset – A pre-computed cloud score offset image (optional).
- Returns:
The image collection with cloud masks applied.
- geeViz.getImagesLib.cFmask(img: Image, fmaskClass: str, bitMaskBandName: str = 'QA_PIXEL') Image [source]#
Applies the CFMask algorithm to a Landsat image.
- Parameters:
img – The input Landsat image.
fmaskClass – The CFMask class to apply (e.g., ‘cloud’, ‘shadow’, ‘snow’).
bitMaskBandName – The name of the QA band (default: “QA_PIXEL”).
- Returns:
The cloud-masked image.
- geeViz.getImagesLib.cFmaskCloud(img: Image, landsatCollectionVersion: str, bitMaskBandName: str = 'QA_PIXEL') Image [source]#
Applies the CFMask cloud mask to a Landsat image.
- Parameters:
img – The input Landsat image.
landsatCollectionVersion – The Landsat collection version (e.g., ‘C1’, ‘C2’).
bitMaskBandName – The name of the QA band (default: “QA_PIXEL”).
- Returns:
The cloud-masked image.
- geeViz.getImagesLib.cFmaskCloudShadow(img: Image, landsatCollectionVersion: str, bitMaskBandName: str = 'QA_PIXEL') Image [source]#
Applies the CFMask cloud shadow mask to a Landsat image.
- Parameters:
img – The input Landsat image.
landsatCollectionVersion – The Landsat collection version (e.g., ‘C1’, ‘C2’).
bitMaskBandName – The name of the QA band (default: “QA_PIXEL”).
- Returns:
The cloud shadow masked image.
- geeViz.getImagesLib.collectionToImage(collection: ImageCollection) Image [source]#
Deprecated - use .toBands(). Converts an image collection to a multiband image.
- Parameters:
collection – The input Earth Engine image collection.
- Returns:
A multiband Earth Engine image.
- geeViz.getImagesLib.compositeDates(images: ImageCollection, composite: Image, bandNames: list = None) Image [source]#
Finds the dates corresponding to bands in a composite image.
- Parameters:
images – The original image collection.
composite – The composite image.
bandNames – Optional list of band names to consider.
- Returns:
An Earth Engine image with date information for each band.
- geeViz.getImagesLib.compositeTimeSeries(ls: ImageCollection, startYear: int, endYear: int, startJulian: int, endJulian: int, timebuffer: int = 0, weights: list = [1], compositingMethod: str | None = None, compositingReducer: Reducer | None = None) ImageCollection [source]#
Creates composites for each year within a specified date range.
This function generates annual composites from an image collection, allowing for time buffering and weighted averaging.
- Parameters:
ls – The input Earth Engine image collection.
startYear – The start year of the composite period.
endYear – The end year of the composite period.
startJulian – The start Julian day of the composite period.
endJulian – The end Julian day of the composite period.
timebuffer – The number of years to include in the composite (default: 0).
weights – The weights for the composite (default: [1]).
compositingMethod – The compositing method (e.g., ‘median’, ‘medoid’) (optional).
compositingReducer – A custom compositing reducer (optional).
- Returns:
An Earth Engine image collection containing the composites.
- geeViz.getImagesLib.dailyMosaics(imgs: ImageCollection) ImageCollection [source]#
Creates daily mosaics from an image collection.
- Parameters:
imgs – The input Earth Engine image collection.
- Returns:
An Earth Engine image collection containing daily mosaics.
- geeViz.getImagesLib.defringeLandsat(img: Image) Image [source]#
Defringes a Landsat 7 image.
- Parameters:
img – The input Landsat 7 image.
- Returns:
The defringed Landsat 7 image.
- geeViz.getImagesLib.exportToAssetWrapper(imageForExport: Image, assetName: str, assetPath: str, pyramidingPolicyObject: dict | None = None, roi: Geometry | None = None, scale: float | None = None, crs: str | None = None, transform: list | None = None, overwrite: bool = False)[source]#
Exports an image to an Earth Engine asset.
This function provides a wrapper for exporting images to Earth Engine assets with additional features like handling existing assets and setting the pyramiding policy.
- Parameters:
imageForExport – The Earth Engine Image to export.
assetName – The desired name for the asset.
assetPath – The full path for the asset in the Earth Engine asset tree.
pyramidingPolicyObject – An optional dictionary specifying the pyramiding policy for the exported asset.
roi – An optional Earth Engine Geometry defining the region of interest for export.
scale – The desired export scale in meters.
crs – The desired coordinate reference system for the export.
transform – The desired transform for the export.
overwrite – A boolean indicating whether to overwrite an existing asset.
- Returns:
None. The function starts the export task.
- geeViz.getImagesLib.exportToCloudStorageWrapper(imageForExport: Image, outputName: str, bucketName: str, roi: Geometry, scale: float | None = None, crs: str | None = None, transform: list | None = None, outputNoData: int = -32768, fileFormat: str = 'GeoTIFF', formatOptions: dict = {'cloudOptimized': True}, overwrite: bool = False)[source]#
Exports an image to Google Cloud Storage.
This function exports an Earth Engine Image to a specified Google Cloud Storage bucket.
- Parameters:
imageForExport – The Earth Engine Image to export.
outputName – The desired name for the exported file.
bucketName – The name of the Google Cloud Storage bucket.
roi – The Earth Engine Geometry defining the region of interest.
scale – The desired export scale in meters.
crs – The desired coordinate reference system for the export.
transform – The desired transform for the export.
outputNoData – The no data value to use for the export.
fileFormat – The desired output file format (e.g., “GeoTIFF”, “TFRecord”).
formatOptions – Additional format options for the export.
overwrite – A boolean indicating whether to overwrite an existing file.
- Returns:
None. The function starts the export task.
- geeViz.getImagesLib.exportToDriveWrapper(imageForExport: Image, outputName: str, driveFolderName: str, roi: Geometry, scale: float | None = None, crs: str | None = None, transform: list | None = None, outputNoData: int = -32768)[source]#
Exports an image to Google Drive.
This function exports an Earth Engine Image to a specified Google Drive folder.
- Parameters:
imageForExport – The Earth Engine Image to export.
outputName – The desired name for the exported file.
driveFolderName – The name of the Google Drive folder to export to.
roi – The Earth Engine Geometry defining the region of interest.
scale – The desired export scale in meters.
crs – The desired coordinate reference system for the export.
transform – The desired transform for the export.
outputNoData – The no data value to use for the export.
- Returns:
None. The function starts the export task.
- geeViz.getImagesLib.fillEmptyCollections(inCollection: ImageCollection, dummyImage: Image) ImageCollection [source]#
Fills empty image collections with a dummy image. This handles empty collections that will cause subsequent processes to fail.
- Parameters:
inCollection – The input Earth Engine image collection.
dummyImage – A dummy Earth Engine image.
- Returns:
The input image collection or a collection containing the dummy image if empty.
- geeViz.getImagesLib.formatArgs(args: dict) dict [source]#
Formats arguments as strings for setting as image properties.
- Parameters:
args – A dictionary of arguments.
- Returns:
A dictionary of formatted arguments.
- geeViz.getImagesLib.getClimateWrapper(collectionName: str, studyArea: Geometry | Feature | FeatureCollection, startYear: int, endYear: int, startJulian: int, endJulian: int, timebuffer: int = 0, weights: List | list | None = None, compositingReducer: Reducer | None = None, exportComposites: bool = False, exportPathRoot: str | None = None, crs: str | None = None, transform: list[int] | None = None, scale: int | None = None, exportBands: List | list | None = None, exportNamePrefix: str = '') 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.
- 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) >>> Map.addTimeLapse(climateComposites.select(exportBands), {}, "Climate Composite Time Lapse") >>> Map.addLayer(studyArea, {"strokeColor": "0000FF", "canQuery": False}, "Study Area", True) >>> Map.centerObject(studyArea) >>> Map.turnOnInspector() >>> Map.view()
- geeViz.getImagesLib.getImageCollection(studyArea: Geometry | Feature | FeatureCollection, startDate: Date | datetime | str, endDate: Date | datetime | str, startJulian: int = 1, endJulian: int = 365, toaOrSR: str = 'SR', includeSLCOffL7: bool = False, defringeL5: bool = False, addPixelQA: bool = False, resampleMethod: str = 'near', landsatCollectionVersion: str = 'C2')#
Retrieves Landsat imagery for a specified study area and date range.
- Parameters:
studyArea (ee.Geometry, ee.Feature, or ee.FeatureCollection) – The geographic area of interest.
startDate (ee.Date, datetime.datetime, or str) – The start date of the desired image range.
endDate (ee.Date, datetime.datetime, or str) – The end date of the desired image range.
startJulian (int, optional) – The start Julian day of the desired image range. Defaults to 1.
endJulian (int, optional) – The end Julian day of the desired image range. Defaults to 365.
toaOrSR (str, optional) – Whether to retrieve TOA or SR data. Defaults to “SR”.
includeSLCOffL7 (bool, optional) – Whether to include SLC-off L7 data. Defaults to False.
defringeL5 (bool, optional) – Whether to defringe L5 data. Defaults to False.
addPixelQA (bool, optional) – Whether to add pixel QA band. Defaults to False.
resampleMethod (str, optional) – Resampling method. Options are “near”, “bilinear”, or “bicubic”. Defaults to “near”.
landsatCollectionVersion (str, optional) – Landsat collection version. Options are “C1” or “C2”. Defaults to “C2”.
- Returns:
A collection of Landsat images meeting the specified criteria.
- Return type:
ee.ImageCollection
>>> import geeViz.getImagesLib as gil >>> Map = gil.Map >>> ee = gil.ee >>> studyArea = gil.testAreas["CA"] >>> composite = gil.getLandsat(studyArea, "2024-01-01", "2024-12-31", 190, 250).median() >>> Map.addLayer(composite, gil.vizParamsFalse, "Landsat Composite") >>> Map.addLayer(studyArea, {"canQuery": False}, "Study Area") >>> Map.centerObject(studyArea) >>> Map.turnOnInspector() >>> Map.view()
- geeViz.getImagesLib.getLandsat(studyArea: Geometry | Feature | FeatureCollection, startDate: Date | datetime | str, endDate: Date | datetime | str, startJulian: int = 1, endJulian: int = 365, toaOrSR: str = 'SR', includeSLCOffL7: bool = False, defringeL5: bool = False, addPixelQA: bool = False, resampleMethod: str = 'near', landsatCollectionVersion: str = 'C2')[source]#
Retrieves Landsat imagery for a specified study area and date range.
- Parameters:
studyArea (ee.Geometry, ee.Feature, or ee.FeatureCollection) – The geographic area of interest.
startDate (ee.Date, datetime.datetime, or str) – The start date of the desired image range.
endDate (ee.Date, datetime.datetime, or str) – The end date of the desired image range.
startJulian (int, optional) – The start Julian day of the desired image range. Defaults to 1.
endJulian (int, optional) – The end Julian day of the desired image range. Defaults to 365.
toaOrSR (str, optional) – Whether to retrieve TOA or SR data. Defaults to “SR”.
includeSLCOffL7 (bool, optional) – Whether to include SLC-off L7 data. Defaults to False.
defringeL5 (bool, optional) – Whether to defringe L5 data. Defaults to False.
addPixelQA (bool, optional) – Whether to add pixel QA band. Defaults to False.
resampleMethod (str, optional) – Resampling method. Options are “near”, “bilinear”, or “bicubic”. Defaults to “near”.
landsatCollectionVersion (str, optional) – Landsat collection version. Options are “C1” or “C2”. Defaults to “C2”.
- Returns:
A collection of Landsat images meeting the specified criteria.
- Return type:
ee.ImageCollection
>>> import geeViz.getImagesLib as gil >>> Map = gil.Map >>> ee = gil.ee >>> studyArea = gil.testAreas["CA"] >>> composite = gil.getLandsat(studyArea, "2024-01-01", "2024-12-31", 190, 250).median() >>> Map.addLayer(composite, gil.vizParamsFalse, "Landsat Composite") >>> Map.addLayer(studyArea, {"canQuery": False}, "Study Area") >>> Map.centerObject(studyArea) >>> Map.turnOnInspector() >>> Map.view()
- geeViz.getImagesLib.getModisData(startYear: int, endYear: int, startJulian: int, endJulian: int, daily: bool = False, maskWQA: bool = False, zenithThresh: int = 90, useTempInCloudMask: bool = True, addLookAngleBands: bool = False, resampleMethod: str = 'near')[source]#
Retrieves MODIS imagery from Earth Engine for a specified period. Handles joining all MODIS collections for Terra and Aqua and aligning band names
- Parameters:
startYear (int) – The starting year for the data collection.
endYear (int) – The ending year for the data collection.
startJulian (int) – The starting Julian day of year for the data collection (1-366).
endJulian (int) – The ending Julian day of year for the data collection (1-366).
daily (bool, optional) – Determines whether to retrieve daily or 8-day composite data. Defaults to False (8-day composite).
maskWQA (bool, optional) – Controls whether to mask pixels based on the Quality Assurance (QA) band. Only applicable for daily data (daily=True). Defaults to False.
zenithThresh (float, optional) – Sets the threshold for solar zenith angle in degrees. Pixels with zenith angle exceeding this threshold will be masked out. Defaults to 90.
useTempInCloudMask (bool, optional) – Determines whether to use the thermal band for cloud masking. Defaults to True.
addLookAngleBands (bool, optional) – Controls whether to include view angle bands in the output. Defaults to False.
resampleMethod (str, optional) – Specifies the resampling method to apply to the imagery. Valid options include “near”, “bilinear”, and “bicubic”. Defaults to “near” (nearest neighbor).
- Returns:
A collection of MODIS imagery for the specified criteria.
- Return type:
ee.ImageCollection
>>> import geeViz.getImagesLib as gil >>> Map = gil.Map >>> ee = gil.ee >>> crs = gil.common_projections["NLCD_CONUS"]["crs"] >>> transform = gil.common_projections["NLCD_CONUS"]["transform"] >>> scale = 240 >>> transform[0] = scale >>> transform[4] = -scale >>> composite = gil.getModisData(2024, 2024, 190, 250, resampleMethod="bicubic").median().reproject(crs, transform) >>> Map.addLayer(composite, gil.vizParamsFalse, "MODIS Composite") >>> Map.setCenter(-111, 41, 7) >>> Map.turnOnInspector() >>> Map.view()
- geeViz.getImagesLib.getProcessedLandsatScenes(studyArea: Geometry | Feature | FeatureCollection, startYear: int, endYear: int, startJulian: int, endJulian: int, toaOrSR: str = 'SR', includeSLCOffL7: bool = False, defringeL5: bool = False, applyCloudScore: bool = False, applyFmaskCloudMask: bool = True, applyTDOM: bool = False, applyFmaskCloudShadowMask: bool = True, applyFmaskSnowMask: bool = False, cloudScoreThresh: int = 10, performCloudScoreOffset: bool = True, cloudScorePctl: int = 10, zScoreThresh: float = -1, shadowSumThresh: float = 0.35, contractPixels: float = 1.5, dilatePixels: float = 3.5, shadowSumBands: list[str] = ['nir', 'swir1'], resampleMethod: str = 'near', harmonizeOLI: bool = False, preComputedCloudScoreOffset: Image | None = None, preComputedTDOMIRMean: Image | None = None, preComputedTDOMIRStdDev: Image | None = None, landsatCollectionVersion: str = 'C2', verbose: bool = False) ImageCollection [source]#
Retrieves, processes, and filters Landsat scenes for a specified area and time period.
This function retrieves Landsat scenes from Earth Engine, applies various cloud, cloud shadow, and snow masking techniques, calculates common indices, and returns a collection of processed images.
- Parameters:
studyArea (ee.Geometry) – The geographic area of interest (study area) as an Earth Engine geometry, Feature, or FeatureCollection object.
startYear (int) – The starting year for the data collection.
endYear (int) – The ending year for the data collection.
startJulian (int) – The starting Julian day of year for the data collection (1-365).
endJulian (int) – The ending Julian day of year for the data collection (1-365).
toaOrSR (str, optional) – Flag indicating desired reflectance type: “TOA” (Top Of Atmosphere) or “SR” (Surface Reflectance). Defaults to “SR”.
includeSLCOffL7 (bool, optional) – Determines whether to include Landsat 7 SLC-off scenes. Defaults to False.
defringeL5 (bool, optional) – Determines whether to defringe Landsat 5 scenes. Defaults to False.
applyCloudScore (bool, optional) – Determines whether to apply cloud masking based on the CloudScore simple algorithm. Defaults to False.
applyFmaskCloudMask (bool, optional) – Determines whether to apply the Fmask cloud mask. Defaults to True.
applyTDOM (bool, optional) – Determines whether to apply the TDOM (Temporal Dark Outlier Mask) technique for cloud shadow masking. Defaults to False.
applyFmaskCloudShadowMask (bool, optional) – Determines whether to apply the Fmask cloud shadow mask. Defaults to True.
applyFmaskSnowMask (bool, optional) – Determines whether to apply the Fmask snow mask. Defaults to False.
cloudScoreThresh (int, optional) – Threshold for the CloudScore simple algorithm to classify a pixel as cloudy. Lower number masks out more. Defaults to 10.
performCloudScoreOffset (bool, optional) – Controls whether to perform an offset correction on the Cloud Score data over bright surfaces. Only use this if bright areas are being masked as clouds. Do not use this in persistently cloud areas. Defaults to True.
cloudScorePctl (int, optional) – Percentile of the Cloud Score product to use for the offset correction. Defaults to 10.
zScoreThresh (float, optional) – Threshold for the z-score used in TDOM cloud shadow masking. Pixels with z-scores below this threshold are masked. Defaults to -1.
shadowSumThresh (float, optional) – Threshold for the sum of reflectance in shadow bands used in TDOM cloud shadow masking. Pixels below this threshold and the zScoreThresh are masked as dark outliers (likely cloud shadows). Defaults to 0.35.
contractPixels (float, optional) – Number of pixels to contract cloud and shadow masks by. Defaults to 1.5.
dilatePixels (float, optional) – Number of pixels to dilate cloud and shadow masks by. Defaults to 3.5.
shadowSumBands (list[str], optional) – List of band names to use for calculating the sum of reflectance in TDOM cloud shadow masking. Defaults to [“nir”, “swir1”].
resampleMethod (str, optional) – Specifies the resampling method to apply to the imagery. Valid options include “near”, “bilinear”, and “bicubic”. Defaults to “near”.
harmonizeOLI (bool, optional) – Determines whether to harmonize OLI data to match TM/ETM+ spectral response. Defaults to False.
preComputedCloudScoreOffset (float | None, optional) – Pre-computed Cloud Score offset value to avoid redundant calculations. Defaults to None (automatic calculation).
preComputedTDOMIRMean (float | None, optional) – Pre-computed mean of the IR band used in TDOM cloud shadow masking to avoid redundant calculations. Defaults to None (automatic calculation).
preComputedTDOMIRStdDev (float | None, optional) – Pre-computed standard deviation of the IR band used in TDOM cloud shadow masking to avoid redundant calculations. Defaults to None (automatic calculation).
landsatCollectionVersion (str, optional) – Specifies the Landsat collection version to use (e.g., “C1”, “C2”). Defaults to “C2”.
verbose (bool, optional) – Controls whether to print additional information during processing. Defaults to False.
- Returns:
A collection of analysis ready, cloud and cloud shadow asked Landsat scenes with common band names.
- Return type:
ee.ImageCollection
>>> import geeViz.getImagesLib as gil >>> Map = gil.Map >>> ee = gil.ee >>> studyArea = gil.testAreas["CO"] >>> composite = gil.getProcessedLandsatScenes(studyArea, 2023, 2023, 190, 250).median() >>> Map.addLayer(composite, gil.vizParamsFalse, "Landsat Composite") >>> Map.addLayer(studyArea, {"canQuery": False}, "Study Area") >>> Map.centerObject(studyArea) >>> Map.turnOnInspector() >>> Map.view()
- geeViz.getImagesLib.getProcessedModis(startYear: int, endYear: int, startJulian: int, endJulian: int, zenithThresh: float = 90, addLookAngleBands: bool = True, applyCloudScore: bool = True, applyTDOM: bool = True, useTempInCloudMask: bool = True, cloudScoreThresh: int = 20, performCloudScoreOffset: bool = True, cloudScorePctl: int = 10, zScoreThresh: float = -1, shadowSumThresh: float = 0.35, contractPixels: int = 0, dilatePixels: float = 2.5, shadowSumBands: list[str] = ['nir', 'swir2'], resampleMethod: str = 'bicubic', preComputedCloudScoreOffset: Image | None = None, preComputedTDOMIRMean: Image | None = None, preComputedTDOMIRStdDev: Image | None = None, addToMap: bool = False, crs: str = 'EPSG:4326', scale: int | None = 250, transform: list[int] | None = None)[source]#
Retrieves, processes, and filters MODIS imagery for a specified period.
This function retrieves daily MODIS imagery from Earth Engine, applies various cloud and cloud shadow masking techniques, and returns a collection of processed images.
- Parameters:
startYear (int) – The starting year for the data collection.
endYear (int) – The ending year for the data collection.
startJulian (int) – The starting Julian day of year for the data collection (1-366).
endJulian (int) – The ending Julian day of year for the data collection (1-366).
zenithThresh (float, optional) – Sets the threshold for solar zenith angle in degrees. Pixels with zenith angle exceeding this threshold will be masked out. Defaults to 90.
addLookAngleBands (bool, optional) – Controls whether to include view angle bands in the output. Defaults to True.
applyCloudScore (bool, optional) – Determines whether to apply cloud masking based on the CloudScore simple algorithm adapted to MODIS. Defaults to True.
applyTDOM (bool, optional) – Determines whether to apply the TDOM (Temporal Dark Outlier Mask)
True. (technique for cloud shadow masking. Defaults to) –
useTempInCloudMask (bool, optional) – Determines whether to use the thermal band for cloud masking during MODIS data retrieval. Defaults to True.
cloudScoreThresh (int, optional) – Threshold for the CloudScore simple algorithm to classify a pixel as cloudy. Lower number masks out more. Defaults to 20.
performCloudScoreOffset (bool, optional) – Controls whether to perform an offset correction on the Cloud Score data over bright surfaces. Only use this if bright areas are being masked as clouds. Do not use this in persistently cloud areas. Defaults to True.
cloudScorePctl (int, optional) – Percentile of the Cloud Score product to use for the offset correction. Defaults to 10.
zScoreThresh (float, optional) – Threshold for the z-score used in TDOM cloud shadow masking. Pixels with z-scores below this threshold are masked. Defaults to -1.
shadowSumThresh (float, optional) – Threshold for the sum of reflectance in shadow bands used in TDOM cloud shadow masking. Pixels below this threshold and the zScoreThresh are masked as dark outliers (likely cloud shadows). Defaults to 0.35.
contractPixels (int, optional) – Number of pixels to contract cloud and shadow masks by. Defaults to 0.
dilatePixels (float, optional) – Number of pixels to dilate cloud and shadow masks by. Defaults to 2.5.
shadowSumBands (list[str], optional) – List of band names to use for calculating the sum of reflectance in TDOM cloud shadow masking. Defaults to [“nir”, “swir2”].
resampleMethod (str, optional) – Specifies the resampling method to apply to the imagery. Valid options include “near”, “bilinear”, and “bicubic”. Defaults to “bicubic”.
preComputedCloudScoreOffset (float | None, optional) – Pre-computed Cloud Score offset value to avoid redundant calculations. Defaults to None (automatic calculation).
preComputedTDOMIRMean (float | None, optional) – Pre-computed mean of the IR band used in TDOM cloud shadow masking to avoid redundant calculations. Defaults to None (automatic calculation).
preComputedTDOMIRStdDev (float | None, optional) – Pre-computed standard deviation of the IR band used in TDOM cloud shadow masking to avoid redundant calculations. Defaults to None (automatic calculation).
addToMap (bool, optional) – Controls whether to add intermediate processing steps (masked medians) to the Earth Engine map for visualization purposes. Defaults to False.
crs (str, optional) – Only used if addToMap is True. Coordinate Reference System (CRS) for the output imagery. Defaults to “EPSG:4326”.
scale (int | None, optional) – Only used if addToMap is True. Scale (resolution) of the output imagery in meters. Defaults to 250.
transform (list | None, optional) – Only used if addToMap is True. Optional transformation matrix to apply to the output imagery. Defaults to None.
>>> import geeViz.getImagesLib as gil >>> Map = gil.Map >>> ee = gil.ee >>> crs = gil.common_projections["NLCD_CONUS"]["crs"] >>> transform = gil.common_projections["NLCD_CONUS"]["transform"] >>> scale = 240 >>> transform[0] = scale >>> transform[4] = -scale >>> composite = gil.getProcessedModis(2024, 2024, 190, 250).median().reproject(crs, transform) >>> Map.addLayer(composite, gil.vizParamsFalse, "MODIS Composite") >>> Map.setCenter(-111, 41, 7) >>> Map.turnOnInspector() >>> Map.view()
- geeViz.getImagesLib.getQABits(image: Image, start: int, end: int, name: str) Image [source]#
Extracts specific bits from a QA band.
This function extracts a range of bits from a QA band and creates a new band.
- Parameters:
image – The input Earth Engine Image with a QA band.
start – The starting bit position (0-based).
end – The ending bit position.
name – The name for the output band.
- Returns:
The Earth Engine Image with the extracted bits.
- geeViz.getImagesLib.getS1(studyArea: Geometry | Feature | FeatureCollection, startYear: int, endYear: int, startJulian: int, endJulian: int, polarization: str = 'VV', pass_direction: str = 'ASCENDING') ImageCollection [source]#
Loads Sentinel-1 GRD data for a given area and time period.
- Parameters:
studyArea – The geographic area of interest.
startYear – The start year of the desired data.
endYear – The end year of the desired data.
startJulian – The start Julian day of the desired data.
endJulian – The end Julian day of the desired data.
polarization – The desired polarization (default: “VV”).
pass_direction – The desired pass direction (default: “ASCENDING”).
- Returns:
An Earth Engine ImageCollection containing the loaded Sentinel-1 data.
- geeViz.getImagesLib.getS2(studyArea: Geometry | Feature | FeatureCollection, startDate: Date | datetime | str, endDate: Date | datetime | str, startJulian: int = 1, endJulian: int = 365, resampleMethod: str = 'nearest', toaOrSR: str = 'TOA', convertToDailyMosaics: bool = True, addCloudProbability: bool = False, addCloudScorePlus: bool = True, cloudScorePlusScore: str = 'cs') ImageCollection [source]#
Loads Sentinel-2 data for a given area and time period and joins cloud score information. Partially deprecated in favor of the simpler superSimpleGetS2.
- Parameters:
studyArea – The geographic area of interest.
startDate – The start date of the desired data. Can be an ee.Date object, datetime object, or date string.
endDate – The end date of the desired data. Can be an ee.Date object, datetime object, or date string.
startJulian – The start Julian day of the desired data.
endJulian – The end Julian day of the desired data.
resampleMethod – The resampling method (default: “nearest”).
toaOrSR – Whether to load TOA or SR data (default: “TOA”).
convertToDailyMosaics – Whether to convert the data to daily mosaics (default: True).
addCloudProbability – Whether to add cloud probability data (default: False).
addCloudScorePlus – Whether to add cloud score plus data (default: True).
cloudScorePlusScore – The band name for cloud score plus (default: “cs”).
- Returns:
A collection of Sentinel-2 satellite images filtered by the specified criteria.
- Return type:
ee.ImageCollection
>>> import geeViz.getImagesLib as gil >>> Map = gil.Map >>> ee = gil.ee >>> studyArea = gil.testAreas["CA"] >>> composite = gil.getS2(studyArea, "2024-01-01", "2024-12-31", 190, 250).median() >>> Map.addLayer(composite, gil.vizParamsFalse, "Sentinel-2 Composite") >>> Map.addLayer(studyArea, {"canQuery": False}, "Study Area") >>> Map.centerObject(studyArea) >>> Map.turnOnInspector() >>> Map.view()
- geeViz.getImagesLib.getSentinel2(studyArea: Geometry | Feature | FeatureCollection, startDate: Date | datetime | str, endDate: Date | datetime | str, startJulian: int = 1, endJulian: int = 365, resampleMethod: str = 'nearest', toaOrSR: str = 'TOA', convertToDailyMosaics: bool = True, addCloudProbability: bool = False, addCloudScorePlus: bool = True, cloudScorePlusScore: str = 'cs') ImageCollection #
Loads Sentinel-2 data for a given area and time period and joins cloud score information. Partially deprecated in favor of the simpler superSimpleGetS2.
- Parameters:
studyArea – The geographic area of interest.
startDate – The start date of the desired data. Can be an ee.Date object, datetime object, or date string.
endDate – The end date of the desired data. Can be an ee.Date object, datetime object, or date string.
startJulian – The start Julian day of the desired data.
endJulian – The end Julian day of the desired data.
resampleMethod – The resampling method (default: “nearest”).
toaOrSR – Whether to load TOA or SR data (default: “TOA”).
convertToDailyMosaics – Whether to convert the data to daily mosaics (default: True).
addCloudProbability – Whether to add cloud probability data (default: False).
addCloudScorePlus – Whether to add cloud score plus data (default: True).
cloudScorePlusScore – The band name for cloud score plus (default: “cs”).
- Returns:
A collection of Sentinel-2 satellite images filtered by the specified criteria.
- Return type:
ee.ImageCollection
>>> import geeViz.getImagesLib as gil >>> Map = gil.Map >>> ee = gil.ee >>> studyArea = gil.testAreas["CA"] >>> composite = gil.getS2(studyArea, "2024-01-01", "2024-12-31", 190, 250).median() >>> Map.addLayer(composite, gil.vizParamsFalse, "Sentinel-2 Composite") >>> Map.addLayer(studyArea, {"canQuery": False}, "Study Area") >>> Map.centerObject(studyArea) >>> Map.turnOnInspector() >>> Map.view()
- geeViz.getImagesLib.getTasseledCap(image: Image) Image [source]#
Computes the Tasseled Cap transformation for an image using the Crist 1985 coefficients.
- Parameters:
image – The input Earth Engine image.
- Returns:
The image with added Tasseled Cap components.
- geeViz.getImagesLib.harmonizationChastain(img: Image, fromSensor: str, toSensor: str) Image [source]#
Harmonizes Landsat images using Chastain et al. (2018) coefficients.
- Parameters:
img – The input Landsat image.
fromSensor – The sensor of the input image (e.g., ‘OLI’, ‘ETM+’).
toSensor – The target sensor for harmonization (e.g., ‘OLI’, ‘ETM+’).
- Returns:
A harmonized Landsat image.
- geeViz.getImagesLib.harmonizationRoy(oli: Image) Image [source]#
Harmonizes Landsat 8 OLI to Landsat 7 ETM+ using Roy et al. (2016) coefficients.
- Parameters:
oli – A Landsat 8 OLI image.
- Returns:
A harmonized Landsat 8 OLI image.
- geeViz.getImagesLib.landsatCloudScore(img: Image) Image [source]#
Computes a cloud score for a Landsat image and adds a band that represents the cloud mask. This expects the input image to have the common band names: [“red”, “blue”, etc], so it can work across sensors.
- Parameters:
img – The input Landsat image.
- Returns:
An image with a cloud score band.
- geeViz.getImagesLib.maskEmptyPixels(image: Image) Image [source]#
Masks pixels without observations in an image.
This function masks pixels where the number of observations is zero.
- Parameters:
image – The input Earth Engine Image with a “num_observations_1km” band.
- Returns:
The masked Earth Engine Image.
- geeViz.getImagesLib.maskS2clouds(image: Image) Image [source]#
Masks clouds in a Sentinel-2 image using the QA60 band.
- Parameters:
image – The input Sentinel-2 image.
- Returns:
The cloud-masked image.
- geeViz.getImagesLib.medoidMosaicMSD(inCollection: ImageCollection, medoidIncludeBands: List | None = None) Image [source]#
Creates a medoid mosaic using the Mean Squared Difference (MSD) (euclidean distance) method.
This function calculates the medoid image from an image collection based on minimizing the sum of squared differences between pixel values.
- Parameters:
inCollection – The input Earth Engine ImageCollection to create the mosaic from.
medoidIncludeBands – A list of band names to include in the MSD calculation. If None, all bands are used.
- Returns:
An Earth Engine Image representing the medoid mosaic.
Note
As the data are not normalized in this method, ensuring the medoidIncludeBands have roughly comparable ranges of values helps the function work properly. For example, if temperature is included, it will account for most of the variance thus resulting in a medoid mosaic that will more or less choose values closest to the median temperature only, rather than all the bands
The function assumes that the image collection has consistent band names and data types.
>>> import geeViz.getImagesLib as gil >>> Map = gil.Map >>> ee = gil.ee >>> studyArea = gil.testAreas["CO"] >>> s2s = gil.superSimpleGetS2(studyArea, "2024-01-01", "2024-12-31", 190, 250) >>> median_composite = s2s.median() >>> medoid_composite = gil.medoidMosaicMSD(s2s, ["green", "red", "nir", "swir1", "swir2"]) >>> Map.addLayer(median_composite, gil.vizParamsFalse10k, "Sentinel-2 Median Composite") >>> Map.addLayer(medoid_composite, gil.vizParamsFalse10k, "Sentinel-2 Medoid Composite") >>> Map.addLayer(studyArea, {"canQuery": False}, "Study Area") >>> Map.centerObject(studyArea) >>> Map.turnOnInspector() >>> Map.view()
- geeViz.getImagesLib.offsetImageDate(img: Image, n: int, unit: str) Image [source]#
Offsets the date of an image.
- Parameters:
img – The input Earth Engine image.
n – The number of units to offset.
unit – The unit of the offset (e.g., ‘year’, ‘month’, ‘day’).
- Returns:
The image with an offset date.
- geeViz.getImagesLib.rescale(img: Image, thresholds: tuple) Image [source]#
Rescales pixel values in an image using a min-max normalization.
- Parameters:
img – The input Earth Engine image.
thresholds – A tuple containing the minimum and maximum values for rescaling.
- Returns:
A rescaled Earth Engine image.
- geeViz.getImagesLib.setNoData(image: Image, noDataValue: float) Image [source]#
Sets null values for an image.
- Parameters:
image – The input Earth Engine image.
noDataValue – The value to assign to null pixels.
- Returns:
An Earth Engine image with null pixels set to the specified noDataValue.
- geeViz.getImagesLib.sieve(image: Image, mmu: float) Image [source]#
Performs clumping and elimination on an image.
- Parameters:
image – The input Earth Engine image.
mmu – The minimum mapping unit.
- Returns:
An Earth Engine image with clumping and elimination applied.
- geeViz.getImagesLib.simpleAddIndices(in_image: Image) Image [source]#
Adds common spectral indices to an image.
- Parameters:
in_image – The input Earth Engine image.
- Returns:
The image with added NDVI, NBR, NDMI, and NDSI indices.
- geeViz.getImagesLib.simpleAddTCAngles(image: Image) Image [source]#
Adds the Tasseled Cap brightness-greenness angle to an image as in Powell et al 2009. Assumes image has bands: ‘brightness’, ‘greenness’, and ‘wetness’.
- Parameters:
image – The input Earth Engine image with brightness and greenness bands.
- Returns:
The image with added brightness-greenness angle.
- geeViz.getImagesLib.simpleGetTasseledCap(image: Image) Image [source]#
Computes the Tasseled Cap transformation for an image, including only brightness, greenness, and wetness using the Crist 1985 coefficients.
- Parameters:
image – The input Earth Engine image.
- Returns:
The image with added brightness, greenness, and wetness bands.
- geeViz.getImagesLib.simpleTDOM2(collection: ImageCollection, zScoreThresh: float = -1, shadowSumThresh: float = 0.35, contractPixels: float = 1.5, dilatePixels: float = 3.5, shadowSumBands: list = ['nir', 'swir1'], preComputedTDOMIRMean: Image | None = None, preComputedTDOMIRStdDev: Image | None = None) ImageCollection [source]#
Applies a simple temporal dark object differencing (TDOM) algorithm to an image collection. Adds a band that is a mask of pixels that are dark, and dark outliers.
- Parameters:
collection – The input Earth Engine image collection.
zScoreThresh – The z-score threshold for dark outliers (default: -1).
shadowSumThresh – The shadow sum threshold (default: 0.35).
contractPixels – The contraction kernel size (default: 1.5).
dilatePixels – The dilation kernel size (default: 3.5).
shadowSumBands – The bands used for shadow sum calculation (default: [“nir”, “swir1”]).
preComputedTDOMIRMean – Precomputed mean of the shadow sum bands (optional).
preComputedTDOMIRStdDev – Precomputed standard deviation of the shadow sum bands (optional).
- Returns:
The image collection with dark outliers masked.
- geeViz.getImagesLib.simpleWaterMask(img: Image, contractPixels: int = 0, slope_thresh: float = 10, elevationImagePath: str = '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, optional) – Path to the Earth Engine image containing elevation data. Defaults to “USGS/3DEP/10m” (10m DEM from USGS 3D Elevation Program).
elevationFocalMeanRadius (float, optional) – Radius (in pixels) for the focal mean filter applied to the elevation data before calculating slope. Defaults to 5.5.
- Returns:
The water mask image with a single band named “waterMask”.
- Return type:
ee.Image
>>> import geeViz.getImagesLib as gil >>> Map = gil.Map >>> ee = gil.ee >>> studyArea = gil.testAreas["CO"] >>> s2s = gil.superSimpleGetS2(studyArea, "2024-01-01", "2024-12-31", 190, 250).map(lambda img: gil.getTasseledCap(img.resample("bicubic").divide(10000))) >>> median_composite = s2s.median() >>> water = gil.simpleWaterMask(median_composite).rename("Water") >>> water = water.selfMask().set({"Water_class_values": [1], "Water_class_names": ["Water"], "Water_class_palette": ["0000DD"]}) >>> Map.addLayer(median_composite.reproject("EPSG:32613", None, 10), gil.vizParamsFalse, "Sentinel-2 Median Composite") >>> Map.addLayer(water.reproject("EPSG:32613", None, 10), {"autoViz": True}, "Water Mask") >>> Map.addLayer(studyArea, {"canQuery": False}, "Study Area") >>> Map.centerObject(studyArea, 12) >>> Map.turnOnInspector() >>> Map.view()
- geeViz.getImagesLib.superSimpleGetS2(studyArea: Geometry | Feature | FeatureCollection, startDate: Date | datetime | str, endDate: Date | datetime | str, startJulian: int = 1, endJulian: int = 365, toaOrSR: str = 'TOA', applyCloudScorePlus: bool = True, cloudScorePlusThresh: float = 0.6, cloudScorePlusScore: str = 'cs') ImageCollection [source]#
This function retrieves Sentinel-2 satellite imagery from Earth Engine for a specified study area and date range. It applies the cloudScore+ algorithm unless told otherwise.
- Parameters:
studyArea (ee.Geometry) – An Earth Engine geometry object representing the area of interest.
startDate (ee.Date, datetime.datetime, or str) – The start date for the image collection in YYYY-MM-DD format.
endDate (ee.Date, datetime.datetime, or str) – The end date for the image collection in YYYY-MM-DD format.
startJulian (int, optional) – The start Julian day of the desired data. Defaults to 1.
endJulian (int, optional) – The end Julian day of the desired data. Defaults to 365.
toaOrSR (str, optional) – Specifies whether to retrieve data in Top-Of-Atmosphere (TOA) reflectance or Surface Reflectance (SR). Defaults to “TOA”.
applyCloudScorePlus (bool, optional) – Determines whether to apply cloud filtering based on the Cloud Score Plus product. Defaults to True.
cloudScorePlusThresh (float, optional) – Sets the threshold for cloud cover percentage based on Cloud Score Plus. Images with cloud cover exceeding this threshold will be masked out if applyCloudScorePlus is True. A higher value will mask out more pixels (call them cloud/cloud-shadow). Defaults to 0.6.
cloudScorePlusScore (str, optional) – One of “cs” - Tends to mask out more. Commits ephemeral water, but doesn’t omit cloud shadows as much or “cs_cdf” - Tends to mask out less, notably fewer water bodies and shadows. This can result in omitting cloud shadows, but not committing ephemeral water as a cloud shadow. Specifies the band name within the Cloud Score Plus product containing the cloud cover information. Defaults to “cs”.
- Returns:
A collection of cloud and cloud-shadow-free Sentinel-2 satellite images filtered by the specified criteria.
- Return type:
ee.ImageCollection
>>> import geeViz.getImagesLib as gil >>> Map = gil.Map >>> ee = gil.ee >>> studyArea = gil.testAreas["CA"] >>> composite = gil.superSimpleGetS2(studyArea, "2024-01-01", "2024-12-31", 190, 250).median() >>> Map.addLayer(composite, gil.vizParamsFalse10k, "Sentinel-2 Composite") >>> Map.addLayer(studyArea, {"canQuery": False}, "Study Area") >>> Map.centerObject(studyArea) >>> Map.turnOnInspector() >>> Map.view()
- geeViz.getImagesLib.toDB(img: Image) Image [source]#
Converts a Sentinel-1 image from natural units to dB.
- Parameters:
img – The input Sentinel-1 image in natural units.
- Returns:
The converted image in dB.
- geeViz.getImagesLib.toNatural(img: Image) Image [source]#
Converts a Sentinel-1 image from dB to natural units.
- Parameters:
img – The input Sentinel-1 image in dB.
- Returns:
The converted image in natural units.
- geeViz.getImagesLib.uniqueValues(collection: ImageCollection, field: str) List [source]#
Finds unique values of a field in an image collection.
- Parameters:
collection – The input Earth Engine image collection.
field – The field to extract unique values from.
- Returns:
A list of unique values.
- geeViz.getImagesLib.wrapDates(startJulian: int, endJulian: int) list [source]#
Wraps dates when the startJulian is greater than the endJulian.
This function handles cases where the start Julian day is later in the year than the end Julian day.
- Parameters:
startJulian – The start Julian day.
endJulian – The end Julian day.
- Returns:
A list containing the wrap offset and the year with the majority of days.
geeViz.changeDetectionLib#
Apply change detection methods usin GEE
geeViz.changeDetectionLib is the core module for setting up various change detection algorithms within GEE. Notably, it facilitates the use of LandTrendr and CCDC data preparation, application, and output formatting, compression, and decompression.
- geeViz.changeDetectionLib.batchFeatherCCDCImgs(ccdcAnnualizedCol1: ImageCollection, ccdcAnnualizedCol2: ImageCollection, featherStartYr: int, featherEndYr: int) ImageCollection [source]#
Wrapper function to join annualized CCDC images from two different CCDC collections, and iterate across images and apply featherCCDCImgs function The feather years are the overlapping years between the two CCDC collections that are used in weighting
- geeViz.changeDetectionLib.ccdcChangeDetection(ccdcImg: list[Image, Image] | Image, bandName: str, startYear: None | int = None, endYear: None | int = None) dict [source]#
Function for getting change years and magnitudes for a specified band from CCDC outputs Only change from the breaks is extracted. As of now, if a segment has a high slope value, this method will not extract that. If combining two CCDC raw outputs provide them as a list of two images for the ccdcImg parameter.
- Parameters:
ccdcImg (list[ee.Image, ee.Image] | ee.Image) – A raw CCDC ee.Image array or list of two raw CCDC ee.Image arrays. If a list of 2 images is provided, they will automatically be combined.
bandName (str) – The band name to use for magnitude of change.
startYear (None | int) – The start of the time window. If left as None, all years in the input CCDC images will be included. Defaults to None.
endYear (None | int) – The end of the time window (inclusive). If left as None, all years in the input CCDC images will be included. Defaults to None.
- Returns:
A dictionary of various CCDC change metrics.
- Return type:
dict
>>> import geeViz.changeDetectionLib as cdl >>> Map = cdl.Map >>> ee = cdl.ee >>> changeDetectionBandName = "NDVI" >>> ccdcChangeBandNames = ["tBreak", "changeProb", f"{changeDetectionBandName}.*"] >>> sortingMethod = "mostRecent" >>> ccdcImg1 = ee.ImageCollection("projects/lcms-292214/assets/CONUS-LCMS/Base-Learners/CCDC-Collection-1984-2022").select(ccdcChangeBandNames).mosaic() >>> ccdcImg2 = ee.ImageCollection("projects/lcms-292214/assets/CONUS-LCMS/Base-Learners/CCDC-Feathered-Collection").select(ccdcChangeBandNames).mosaic() >>> changeObjCombined = cdl.ccdcChangeDetection([ccdcImg1, ccdcImg2], changeDetectionBandName) >>> Map.addLayer(changeObjCombined[sortingMethod]["loss"]["year"], {"min": 1984, "max": 2024, "palette": cdl.lossYearPalette}, "Loss Year") >>> Map.addLayer(changeObjCombined[sortingMethod]["loss"]["mag"], {"min": -0.5, "max": -0.1, "palette": cdl.lossMagPalette}, "Loss Mag", False) >>> Map.addLayer(changeObjCombined[sortingMethod]["gain"]["year"], {"min": 1984, "max": 2024, "palette": cdl.gainYearPalette}, "Gain Year") >>> Map.addLayer(changeObjCombined[sortingMethod]["gain"]["mag"], {"min": 0.05, "max": 0.2, "palette": cdl.gainMagPalette}, "Gain Mag", False) >>> Map.turnOnInspector() >>> Map.setCenter(-88, 36, 12) >>> Map.view()
- geeViz.changeDetectionLib.featherCCDCImgs(joinedCCDCImg: Image, ccdcBnds: list | List, coeffs1_bns: list | List, coeffs2_bns: list | List, featherStartYr: int, featherEndYr: int) Image [source]#
Function to feather two CCDC collections together based on overlapping data time periods and weights The feather years are the overlapping years between the two CCDC collections that are used in weighting
- geeViz.changeDetectionLib.predictCCDC(ccdcImg: list[Image, Image] | Image, timeImgs: ImageCollection, fillGaps: bool = True, whichHarmonics: list[int] = [1, 2, 3], featherStartYr: int = 2015, featherEndYr: int = 2021) ImageCollection [source]#
Takes one or two raw CCDC ee.Image array outputs, an ee.ImageCollection of time images, and returns a time-series ee.ImageCollection with harmonic coefficients and fitted values
- Parameters:
ccdcImg (list[ee.Image, ee.Image] | ee.Image) – A raw CCDC ee.Image array or list of two raw CCDC ee.Image arrays. If a list of 2 images is provided, feathering will automatically be performed. Note that any pixel that is null in either CCDC image will result in a null value in the predicted output.
timeImgs (ee.ImageCollection) – An ee.ImageCollection of time images usually from functions such as simpleGetTimeImageCollection.
fillGaps (bool, optional) – Whether to fill gaps between segments. If false, outputs can have blank values mid time-series. Defaults to True.
whichHarmonics (list[int], optional) – Which harmonics to include in fitted outputs forreturned time-series. Defaults to [1,2,3].
featherStartYear (int, optional) – If a list of 2 images is provided as ccdcImg, this is the first year of the window used for feathering the two time-series together. Defaults to 2015.
featherEndYear (int, optional) – If a list of 2 images is provided as ccdcImg, this is the last year (inclusive) of the window used for feathering the two time-series together. Defaults to 2021.
- Returns:
A collection of CCDC coefficients and fitted values.
- Return type:
ee.ImageCollection
>>> import geeViz.changeDetectionLib as cdl >>> Map = cdl.Map >>> ee = cdl.ee >>> ccdcBandNames = ["tStart", "tEnd", "tBreak", "changeProb", "swir1.*", "NDVI.*"] >>> timeImgs = cdl.simpleGetTimeImageCollection(startYear=1984, endYear=2024, startJulian=1, endJulian=365, step=0.1) >>> ccdcImg1 = ee.ImageCollection("projects/lcms-292214/assets/CONUS-LCMS/Base-Learners/CCDC-Collection-1984-2022").select(ccdcBandNames).mosaic() >>> ccdcImg2 = ee.ImageCollection("projects/lcms-292214/assets/CONUS-LCMS/Base-Learners/CCDC-Feathered-Collection").select(ccdcBandNames).mosaic() >>> fittedFeathered = cdl.predictCCDC(ccdcImg=[ccdcImg1, ccdcImg2], timeImgs=timeImgs, fillGaps=True, whichHarmonics=[1, 2, 3], featherStartYr=2015, featherEndYr=2021) >>> Map.addLayer(fittedFeathered.select([".*_CCDC_fitted"]), {"reducer": ee.Reducer.mean(), "min": 0.3, "max": 0.8}, "Combined CCDC", True) >>> Map.turnOnInspector() >>> Map.setCenter(-88, 36, 12) >>> Map.view()
- geeViz.changeDetectionLib.simpleGetTimeImageCollection(startYear: int, endYear: int, startJulian: int = 1, endJulian: int = 365, step: float = 0.1)[source]#
Provides a time series of year and decimal days ee.ImageCollection. This is useful for CCDC predictions
- Parameters:
startYear (int) – The starting year for returned time-series.
endYear (int) – The ending year for the returned time-series.
startJulian (int) – The starting Julian day of year for returned time-series (1-365).
endJulian (int) – The ending Julian day of year for returned time-series (1-365).
step (float, optional) – Fraction of a year for each output in returned time-series (~0.01-1). Defaults to 0.1.
- Returns:
A collection of time images.
- Return type:
ee.ImageCollection
>>> import geeViz.changeDetectionLib as cdl >>> Map = cdl.Map >>> ee = cdl.ee >>> timeImgs = cdl.simpleGetTimeImageCollection(startYear = 1984, endYear = 2024, startJulian = 1, endJulian = 365, step = 0.1) >>> Map.addLayer(timeImgs, {}, "Time Images", True) >>> Map.turnOnInspector() >>> Map.view()
- geeViz.changeDetectionLib.simpleLANDTRENDR(ts, startYear, endYear, indexName='NBR', run_params=None, lossMagThresh=-0.15, lossSlopeThresh=-0.1, gainMagThresh=0.1, gainSlopeThresh=0.1, slowLossDurationThresh=3, chooseWhichLoss='largest', chooseWhichGain='largest', addToMap=True, howManyToPull=2, multBy=10000)[source]#
Takes annual time series input data, properly sets it up for LandTrendr, runs LandTrendr, and provides both a compressed vertex-only format output as well as a basic change detection output.
geeViz.taskManagerLib#
Monitor and manage tasks programatically
geeViz.taskManagerLib facilitates the monitoring and deleting of GEE export tasks.
geeViz.assetManagerLib#
Helpful functions for managing GEE assets
geeViz.assetManagerLib includes functions for copying, deleting, uploading, changing permissions, and more.
geeViz.cloudStorageManagerLib#
Helpful functions for managing Google Cloud Storage (GCS) buckets and blobs
geeViz.cloudStorageManagerLib includes functions for renaming, seeing if a blob exists, and deleting blobs.
geeViz.gee2Pandas#
Take data from GEE to Pandas and back
geeViz.gee2Pandas facilitates converting GEE objects to tabular formats that work well in more common packages such as Pandas.
geeViz.foliumView#
View GEE objects using Folium
geeViz.foliumView is facilitates viewing GEE objects in Folium. Layers can be added to the map using Map.addLayer and then viewed using the Map.view method.
geeViz.phEEnoViz#
Visualize the spectral seasonality of an area to facilitate composting methods development
geeViz.phEEnoViz facilitates the creation of plots to show the seasonality of an area. This is a good tool for deciding what date ranges to use for compositing.