### Setup for geeViz outputLib.thumbs Examples Source: https://geeviz.org/notebooks/thumbLib_examples Imports necessary libraries and sets up the output directory for geeViz examples. Ensure the output directory exists before running. ```python import geeViz.geeView as gv import geeViz.getImagesLib as gil from geeViz.outputLib import thumbs as tl import geeViz.getSummaryAreasLib as sal from IPython.display import Image, display, HTML import os ee = gv.ee # Output directory output_dir = os.path.join(os.path.dirname(os.path.abspath("__file__")), "outputs", "thumbLib_examples") os.makedirs(output_dir, exist_ok=True) print(f"Output dir: {output_dir}") ``` -------------------------------- ### List and Get geeViz Examples Source: https://geeviz.org/mcp Access geeViz examples using `examples`. `action="list"` displays descriptions for all available examples, while `action="get"` retrieves the full source code for a specified example name. ```python examples(action="list") ``` ```python examples(action="get", name="...") ``` -------------------------------- ### Setup and Import geeViz Modules Source: https://geeviz.org/notebooks/lcmsViewerExampleNotebook This snippet handles the necessary setup for using the geeViz library, including installing it if not already present and importing core modules. Ensure this runs before utilizing other geeViz functionalities. ```python #Boiler plate #Import modules import os,sys sys.path.append(os.getcwd()) try: from geeViz.geeView import * except: !python -m pip install geeViz from geeViz.geeView import * print('Done') ``` -------------------------------- ### Import Libraries and Setup Source: https://geeviz.org/notebooks/LANDTRENDRWrapperNotebook Imports necessary libraries for Earth Engine operations and sets up the environment. Includes a fallback to install 'geeViz' if it's not already present. ```python #Example of how to get Landsat data using the getImagesLib, create median composites, run LandTrendr and then filter #LandTrendr output into usable data depicting where, when, and the magnitude of loss and gain #################################################################################################### import os,sys sys.path.append(os.getcwd()) #Module imports try: import geeViz.getImagesLib as gil except: !python -m pip install geeViz import geeViz.getImagesLib as gil import geeViz.changeDetectionLib as cdl ee = gil.ee #Set up to mapper objects to use #Can use the default one first Map = gil.Map print('done') ``` -------------------------------- ### Explicit Multi-Credential Workflow Setup Source: https://geeviz.org/_modules/geeViz/eeAuth/eeCreds Register multiple credentials by path or string, start the proxy, and switch between them using eeCreds.addCreds() and eeCreds.use(). ```python from geeViz.eeAuth import eeCreds import ee eeCreds.addCreds("path/to/sa-prod.json", name="prod") eeCreds.addCreds(b64_sa_string, name="acme") eeCreds.addCreds("~/.config/earthengine/credentials", name="ian") # OAuth eeCreds.start() # initializes ee + spawns local proxy ``` -------------------------------- ### List Example Files Source: https://geeviz.org/_modules/geeViz/mcp/server Returns a sorted list of Python (.py) and Jupyter Notebook (.ipynb) files from the examples directory, excluding __init__.py. Handles cases where the examples directory does not exist. ```python def _list_example_files(): """Return sorted list of example filenames.""" if not os.path.isdir(_EXAMPLES_DIR): return [] return sorted(f for f in os.listdir(_EXAMPLES_DIR) if (f.endswith(".py") or f.endswith(".ipynb")) and f != "__init__.py") ``` -------------------------------- ### Setup and Import geeViz Source: https://geeviz.org/notebooks/Annual_NLCD_Viewer_Notebook Imports necessary libraries and installs geeViz if not already present. Ensures the environment is ready for Earth Engine operations. ```python import os,sys sys.path.append(os.getcwd()) #Module imports try: import geeViz.geeView as gv except: !python -m pip install geeViz import geeViz.geeView as gv ee = gv.ee Map = gv.Map print('Done') ``` -------------------------------- ### GEE Data Loading and Directory Setup (Python) Source: https://geeviz.org/_modules/geeViz/gee2Pandas Example of setting up an output directory and loading Earth Engine ImageCollections for testing purposes. This code is typically run within an `if __name__ == "__main__":` block. ```python import os output_dir = r"C:\\tmp\\geeToPandasTest" if not os.path.exists(output_dir): os.makedirs(output_dir) pt = ee.Geometry.Point([-65.8491, 18.2233]) comps = ee.ImageCollection("projects/rcr-gee/assets/lcms-training/lcms-training_module-2_composites") lt = ee.ImageCollection("projects/rcr-gee/assets/lcms-training/lcms-training_module-3_landTrendr") ``` -------------------------------- ### Install geeViz MCP SDK Source: https://geeviz.org/mcp Install the geeViz package, which includes the MCP SDK as a dependency. This is the initial step for setting up the MCP server. ```bash $ pip install geeViz ``` -------------------------------- ### List geeViz Example Scripts via MCP Source: https://geeviz.org/mcp Example of an AI query to the MCP server to list geeViz example scripts filtered by a keyword. This demonstrates the `list_examples` tool usage. ```text "List the geeViz example scripts that involve LANDTRENDR" ``` -------------------------------- ### Quick Start: Search, Inspect, and Query EDW Services Source: https://geeviz.org/_modules/geeViz/edwLib Demonstrates the basic usage of the edwLib for searching services, getting service information, and querying features. Loaded into Earth Engine. ```python import geeViz.edwLib as edw # Search for fire-related services services = edw.search_services("fire") # Get layer info info = edw.get_service_info("EDW_MTBS_01") # Query features as GeoJSON geojson = edw.query_features("EDW_MTBS_01", 15, where="FIRE_NAME LIKE '%CAMERON PEAK%'", out_fields="FIRE_NAME,ACRES,YEAR") # Load into Earth Engine import ee fc = ee.FeatureCollection(geojson) ``` -------------------------------- ### Import and Setup geeViz Modules Source: https://geeviz.org/_modules/geeViz/foliumView This snippet shows the necessary imports and setup for using the geeViz package, including Earth Engine initialization and defining file paths for visualization outputs. ```python # Script to allow GEE objects to be viewed in folium # Adapted from: https://colab.research.google.com/github/giswqs/qgis-earthengine-examples/blob/master/Folium/ee-api-folium-setup.ipynb # Intended to work within the geeViz package ###################################################################### # Import modules import geeViz.geeView as geeView import os, sys, folium, json, numpy from folium import plugins from IPython.display import display, HTML # Set up GEE and paths ee = geeView.ee ``` -------------------------------- ### Main Function and Example Call Source: https://geeviz.org/_modules/geeViz/mcp/server The main entry point for the script, which includes a commented-out example of inspecting an asset and then calls the main application logic. ```python if __name__ == "__main__": # print(inspect_asset("COPERNICUS/S2_SR_HARMONIZED")) main() # %% ``` -------------------------------- ### foliumMapper Example Source: https://geeviz.org/info/geeViz.foliumView.html Example demonstrating how to initialize foliumMapper, set the map center, add a Landsat layer, and view the map. ```APIDOC from geeViz.foliumView import foliumMapper # Initialize the mapper mapper = foliumMapper() # Set the map center mapper.setCenter(-122.4194, 37.7749, 10) # Add a layer (example assumes you have an ee.Image object) mapper.addLayer(ee.Image("LANDSAT/LC08/C01/T1_SR/LC08_044034_20140318"), {"bands": ["B4", "B3", "B2"], "min": 0, "max": 3000}, "Landsat Image") # View the map mapper.view() ``` -------------------------------- ### Install and Import geeViz Source: https://geeviz.org/notebooks/Aboveground_Biomass_Viewer_Notebook Installs the geeViz library if not already present and imports necessary modules. This is a prerequisite for using the viewer functionalities. ```python try: import geeViz.geeView as geeView except: !python -m pip install geeViz import geeViz.geeView as geeView import geeViz.geePalettes as palettes ee = geeView.ee Map = geeView.Map print('done') ``` -------------------------------- ### Install geeViz with Optional Extras Source: https://geeviz.org/installation Use pip to install geeViz with specific optional features. Use '[gemini]' for AI, '[segmentation]' for image segmentation, or '[all]' for all available extras. ```bash $ pip install geeViz[gemini] # Adds google-genai for AI features ``` ```bash $ pip install geeViz[segmentation] # Adds torch + transformers for SegFormer ``` ```bash $ pip install geeViz[all] # Everything ``` -------------------------------- ### Start Earth Engine Credentials Service Source: https://geeviz.org/_modules/geeViz/eeAuth/eeCreds Starts the Earth Engine credentials service. It handles proxy launching and Earth Engine initialization based on provided flags. Calling start() multiple times is safe and returns the current state. ```python with self._lock: if self._started: return self._status() if not self._entries: raise RuntimeError( "eeCreds.start(): no credentials registered — " "call addCreds(...) first" ) if launch_proxy: self._launch_proxy(proxy_host, proxy_port) if ee_init: proxy_url = self._proxy_url or "" if proxy_url: # Pass the first registered credential's project so EE # builds API URLs like ``projects//value:compute`` # instead of the placeholder. The proxy then doesn't have # to rewrite paths — all tenants in a single eeCreds # instance share a process-wide ee.Initialize, and EE # rejects the placeholder string at the path level. first = next(iter(self._entries.values())) initialize_via_proxy( proxy_url, project=first.project_id or None, ) else: # No proxy → direct ee.Initialize with the FIRST creds # (single-tenant mode; .use() will then raise unless # the user re-initializes). first = next(iter(self._entries.values())) self._direct_init(first) self._started = True return self._status() ``` -------------------------------- ### geeViz.examples module Source: https://geeviz.org/genindex Module containing examples for geeViz. ```APIDOC ## geeViz.examples ### Description Module containing examples for geeViz. ``` -------------------------------- ### Install geeViz Package Source: https://geeviz.org/installation Install the geeViz package using pip after the Earth Engine API is set up. ```bash $ pip install geeViz ``` -------------------------------- ### Index geeViz Modules and Examples Source: https://geeviz.org/_modules/geeViz/mcp/server Walks through the geeViz package to index modules and examples using AST parsing and JSON parsing for notebooks. It populates a module tree and map, and prints a summary of indexed items. Modules are imported on-demand. ```python import pkgutil import geeViz tree = {} fq_map = {} for importer, modname, ispkg in pkgutil.walk_packages( geeViz.__path__, prefix="geeViz." ): # Skip excluded packages if any(modname == skip or modname.startswith(skip + ".") for skip in _SKIP_PACKAGES): continue # Skip private modules leaf = modname.rsplit(".", 1)[-1] if leaf.startswith("_"): continue # Find the source file without importing try: spec = importlib.util.find_spec(modname) if spec is None or spec.origin is None: continue except (ModuleNotFoundError, ValueError): continue # Parse with AST members, module_doc = _ast_extract_members(spec.origin) first_line = module_doc.split("\n")[0].strip()[:100] if module_doc else "" short = leaf entry = {"fq": modname, "mod": None, "file": spec.origin, "members": members, "doc": first_line} tree[modname] = entry if short not in tree: tree[short] = entry fq_map[short] = modname fq_map[modname] = modname # --- Index examples (AST parse .py, JSON parse .ipynb) --- example_members = [] for fname in _list_example_files(): fpath = os.path.join(_EXAMPLES_DIR, fname) base = fname.rsplit(".", 1)[0] desc = "" if fname.endswith(".py"): try: with open(fpath, "r", encoding="utf-8") as f: source = f.read() try: ex_tree = ast.parse(source) doc = ast.get_docstring(ex_tree) or "" desc = doc.split("\n")[0].strip()[:100] if doc else "" except SyntaxError: pass if not desc: for line in source.split("\n")[:20]: s = line.strip() if s.startswith("#") and len(s) > 2: desc = s.lstrip("#").strip() break except Exception: pass elif fname.endswith(".ipynb"): try: with open(fpath, "r", encoding="utf-8") as f: nb = json.load(f) for cell in nb.get("cells", []): if cell.get("cell_type") == "markdown": src = "".join(cell.get("source", [])).strip() if src: desc = src.split("\n")[0].lstrip("#").strip()[:100] break except Exception: pass example_members.append({"name": base, "type": "example", "description": desc or fname, "file": fname}) tree["examples"] = { "fq": "geeViz.examples", "mod": None, "file": _EXAMPLES_DIR, "members": example_members, "doc": "geeViz example scripts and notebooks", } fq_map["examples"] = "geeViz.examples" _MODULE_TREE = tree _MODULE_MAP = fq_map n_mods = len(set(e["fq"] for e in tree.values())) n_examples = len(example_members) print(f"[geeViz MCP] Module tree: {n_mods} modules, {n_examples} examples indexed (zero imports)") ``` -------------------------------- ### Full example: Single-section land cover report Source: https://geeviz.org/notebooks/report_generation_examples This comprehensive example demonstrates creating a single-section report for land cover in Salt Lake County. It includes data filtering, report initialization, section addition, and report generation. ```python # Example 1: Single-section report — LCMS Land Cover in Salt Lake County study_area_1 = sal.getUSCounties(ee.Geometry.Point([-111.89, 40.76])) print("County:", study_area_1.aggregate_array("NAMELSAD").getInfo()) lcms = ee.ImageCollection("USFS/GTAC/LCMS/v2024-10") lcms_2024 = lcms.filter(ee.Filter.calendarRange(2024, 2024, "year")) \ .filterBounds(study_area_1).mosaic().copyProperties(lcms.first()) report1 = rl.Report( title="Salt Lake County Land Cover", theme="dark", tone="informative", header_text="Current land cover from USFS LCMS v2024-10.", ) report1.add_section( ee_obj=lcms_2024, geometry=study_area_1, title="LCMS Land Cover (2024)", band_names=["Land_ Cover"], scale=60, basemap="esri-satellite", burn_in_geometry=True, geometry_outline_color="white", ) out_path = os.path.join(output_dir, "ex1_salt_lake_county.html") report1.generate(format="html", output_path=out_path) print(f"\nReport saved to: {out_path}") print(report1.metadata().to_markdown(index=False)) show_report(out_path) ``` -------------------------------- ### Example: Land Cover Comparison with Grouped Bar Chart Source: https://geeviz.org/_modules/geeViz/outputLib/charts Demonstrates using `summarize_and_chart` to compare land cover across multiple fire perimeters. This example showcases setting a title, stacking bars, and specifying chart dimensions. ```python import geeViz.geeView as gv from geeViz.outputLib import charts as cl ee = gv.ee lcms = ee.ImageCollection("USFS/GTAC/LCMS/v2024-10") fires = ee.FeatureCollection( "USFS/GTAC/MTBS/burned_area_boundaries/v1" ).sort("BurnBndAc", False).limit(5) lc_mode = lcms.select(["Land_Cover"]).mode().set( lcms.first().toDictionary() ) # summarize_and_chart handles reduceRegions + grouped bar: df, fig = cl.summarize_and_chart( lc_mode, fires, feature_label="Incid_Name", title="Land Cover — 5 Largest Fires", stacked=True, width=800, ) fig.show() ``` -------------------------------- ### Get Precomputed Cloud Score Offsets Source: https://geeviz.org/_modules/geeViz/getImagesLib Retrieves precomputed cloud score offsets for Landsat and Sentinel-2. Use this to get ee.Image objects representing cloud score offsets for specific percentile values. ```python offsets = getPrecomputedCloudScoreOffsets(10) landsat_offset = offsets["landsat"] sentinel2_offset = offsets["sentinel2"] ``` -------------------------------- ### Start Export Thread Source: https://geeviz.org/_modules/geeViz/phEEnoViz Starts an export process in a new thread to allow for parallel processing. Includes optional visualization setup for Earth Engine. ```python tt = threading.Thread(target=getTableWrapper, args=(stack, randomSample, output_table_nameT)) tt.start() time.sleep(0.1) # Set thread limit depending on whether visualization is shown threadLimit = 1 if showGEEViz: # Visualize the study area and samples in geeViz Map.addLayer(studyArea, {"strokeColor": "00F"}, "Study Area") Map.centerObject(studyArea) Map.view() threadLimit = 2 limitThreads(threadLimit) ``` -------------------------------- ### Verify geeViz Installation Source: https://geeviz.org/installation Run this Python code in a shell to confirm that Earth Engine is initialized and geeViz is installed correctly. No errors indicate a successful setup. ```python import ee import geeViz # Initialize Earth Engine ee.Initialize(project='your-project-id') # Test basic functionality print(f"geeViz version: {geeViz.__version__}") print("Earth Engine initialized successfully!") ``` -------------------------------- ### Running geeViz MCP Server Examples Source: https://geeviz.org/_modules/geeViz/mcp/server Demonstrates different ways to run the geeViz MCP server using command-line arguments and environment variables to control transport and sandbox behavior. ```bash python -m geeViz.mcp.server # stdio, no sandbox (default) python -m geeViz.mcp.server --sandbox # stdio with sandbox MCP_TRANSPORT=streamable-http python -m geeViz.mcp.server # HTTP, auto-sandbox python -m geeViz.mcp --help ``` -------------------------------- ### timeTaskList Source: https://geeviz.org/info/geeViz.taskManagerLib.html Get list of tasks started within a specified time interval. ```APIDOC ## timeTaskList ### Description Get list of tasks started within a specified time interval. ### Method APIDOC ### Endpoint APIDOC ### Parameters #### Path Parameters - **starttime** (string) - Required - The start time of the interval. - **endtime** (string) - Required - The end time of the interval. ### Request Example APIDOC ### Response APIDOC ``` -------------------------------- ### Get Sentinel-2 Image Collection Source: https://geeviz.org/_modules/geeViz/getImagesLib Filters a Sentinel-2 image collection by date, Julian day, and bounds, then maps a function to it and selects specific bands. Imports are assumed to be handled elsewhere. ```python print("Using S2 Collection:", s2CollectionDict[toaOrSR]) s2s = ( ee.ImageCollection(s2CollectionDict[toaOrSR]) .filterDate(startDate, endDate.advance(1, "day")) .filter(ee.Filter.calendarRange(startJulian, endJulian)) .filterBounds(studyArea) .map(multS2) .select(["QA60"] + sensorBandDict[toaOrSR], ["QA60"] + sensorBandNameDict[toaOrSR]) ) ``` -------------------------------- ### AI-assisted LANDTRENDR Change Detection Workflow Source: https://geeviz.org/mcp This example shows the sequence of AI calls to perform LANDTRENDR change detection. It includes listing examples, getting a specific example wrapper, searching for a geeViz function, and running Python code for analysis and map display. ```text User: "Do LANDTRENDR change detection near Bozeman and show me the results" AI calls: list_examples(filter="LANDTRENDR") AI calls: get_example("LANDTRENDRWrapper") AI calls: search_geeviz(name="simpleLANDTRENDR") AI calls: run_code(""" import geeViz.changeDetectionLib as cdl studyArea = ee.Geometry.Point([-111.04, 45.68]).buffer(20000) ... """) AI calls: run_code("Map.centerObject(studyArea)") AI calls: map_control(action="view") AI responds: "Here's your LANDTRENDR analysis. The map has been rendered and opened in the browser, and the script has been saved to geeViz/mcp/generated_scripts/session_20260226_143022.py" ``` -------------------------------- ### Get UTM EPSG Code for Location and Datum Source: https://geeviz.org/_modules/geeViz/getImagesLib Returns the EPSG code string for a UTM zone based on geographic coordinates and a specified datum. Handles both list/tuple coordinates and ee.Geometry.Point objects. Raises ValueError for unsupported datums or location types. ```python def getUTMEpsg(location, datum: str = "WGS84") -> str: """Return the EPSG code string for a UTM zone given a location and datum. Combines :func:`getUTMZone` with a datum lookup to produce the full EPSG code (e.g. ``"EPSG:32612"`` for WGS84 UTM Zone 12N). Args: location: One of: - ``[longitude, latitude]`` list/tuple (GEE convention: lon first). - ``ee.Geometry.Point`` — coordinates are extracted via ``.getInfo()``. datum: Datum name. One of ``"WGS84"`` (default), ``"NAD83"``, ``"NAD27"``, ``"WGS72"``, ``"ETRS89"``, ``"GDA94"``, ``"GDA2020"``, ``"SIRGAS2000"``. Case-insensitive. Returns: EPSG code string, e.g. ``"EPSG:32612"``. Raises: ValueError: If the datum is not recognized or ``location`` is not a supported type. Examples: >>> getUTMEpsg([-113.15, 47.15]) 'EPSG:32612' >>> getUTMEpsg([-113.15, 47.15], datum="NAD83") 'EPSG:26912' >>> getUTMEpsg([151.21, -33.86]) 'EPSG:32756' >>> getUTMEpsg(ee.Geometry.Point([-113.15, 47.15])) 'EPSG:32612' """ # Parse location into (longitude, latitude) if isinstance(location, ee.Geometry): coords = location.coordinates().getInfo() longitude, latitude = coords[0], coords[1] elif isinstance(location, (list, tuple)) and len(location) >= 2: longitude, latitude = location[0], location[1] else: raise ValueError( f"location must be a [lon, lat] list/tuple or ee.Geometry.Point, " f"got {type(location).__name__}" ) datum_upper = datum.upper().replace(" ", "").replace("-", "") if datum_upper not in _UTM_DATUM_EPSG: raise ValueError( f"Unknown datum '{datum}'. Supported: {', '.join(sorted(_UTM_DATUM_EPSG.keys()))}" ) north_prefix, south_prefix = _UTM_DATUM_EPSG[datum_upper] zone = getUTMZone(longitude) prefix = north_prefix if latitude >= 0 else south_prefix return f"EPSG:{prefix}{zone:02d}" ``` -------------------------------- ### Get US Counties - All US Counties Source: https://geeviz.org/_modules/geeViz/getSummaryAreasLib Example of retrieving all US counties by calling the function without any filters. ```python getUSCounties() ``` -------------------------------- ### Setup and API Key Check Source: https://geeviz.org/notebooks/googleMapsLib_examples Initializes the output directory and checks for the presence of the Google Maps API key. ```python import geeViz.googleMapsLib as gm from IPython.display import display, HTML, Image as IPImage, Markdown import json, os, time output_dir = os.path.join(os.path.dirname(os.getcwd()), "examples", "outputs", "google_maps") os.makedirs(output_dir, exist_ok=True) print(f"Output: {output_dir}") print(f"Maps key: {'set' if gm._get_api_key() else 'MISSING'}") ``` -------------------------------- ### Get Precomputed TDOM Statistics Source: https://geeviz.org/_modules/geeViz/getImagesLib Retrieves precomputed TDOM statistics (mean and standard deviation) for Landsat and Sentinel-2. These statistics are used in the TDOM cloud shadow masking algorithm. ```python stats = getPrecomputedTDOMStats() landsat_mean = stats["landsat"]["mean"] sentinel2_stddev = stats["sentinel2"]["stdDev"] ``` -------------------------------- ### Example: Get Yellowstone National Park Source: https://geeviz.org/_modules/geeViz/getSummaryAreasLib Demonstrates how to retrieve a specific protected area by its name using the getProtectedAreas function. ```python yellowstone = sal.getProtectedAreas(name="Yellowstone") ``` -------------------------------- ### Setup for geeViz Report Generation Source: https://geeviz.org/notebooks/report_generation_examples Imports necessary libraries and sets up the output directory. Includes a helper function to display generated reports inline. ```python # Setup — shared by all examples import os, time import geeViz.geeView as gv import geeViz.getImagesLib as gil import geeViz.getSummaryAreasLib as sal import geeViz.edwLib as edw from geeViz.outputLib import reports as rl from IPython.display import display, IFrame, HTML ee = gv.ee output_dir = os.path.join(os.path.dirname(os.getcwd()), "examples", "outputs", "reports") os.makedirs(output_dir, exist_ok=True) def show_report(path, height=800): """Display a generated HTML/PDF report inline in the notebook.""" if path.endswith(".pdf"): rel = os.path.relpath(path, os.getcwd()) display(HTML(f'

PDF cannot be displayed inline. Download here.

')) else: rel = os.path.relpath(path, os.getcwd()) display(IFrame(src=rel, width="100%", height=height)) print(f"Reports will be saved to: {output_dir}") print("Use show_report(path) after generate() to display the report inline.") ``` -------------------------------- ### Get US Counties - All Montana Counties Source: https://geeviz.org/_modules/geeViz/getSummaryAreasLib Example of retrieving all counties within a specific state using the state abbreviation filter. ```python getUSCounties(state_abbr='MT') ``` -------------------------------- ### Get US Counties - Intersecting Area and State Filter Source: https://geeviz.org/_modules/geeViz/getSummaryAreasLib Example of filtering counties that intersect a given area and are within a specific state. ```python getUSCounties(area=my_point, state_abbr='CO') ``` -------------------------------- ### Initialize and Configure a Report Source: https://geeviz.org/_modules/geeViz/outputLib/reports Demonstrates how to create a Report object, setting the title, theme, and layout. This is the starting point for generating any report. ```Python import geeViz.geeView as gv from geeViz.outputLib import reports as rl ee = gv.ee report = rl.Report( title="Wasatch Front Assessment", theme="dark", layout="poster", # landscape multi-column ) report.header_text = "An analysis of land cover and fire trends." report.add_section( ee_obj=lcms.select(['Land_Cover']), geometry=counties, title="LCMS Land Cover", stacked=True, scale=60, ) # PDF with static chart images report.generate(format="pdf", output_path="report.pdf") # HTML (interactive charts) report.generate(format="html", output_path="report.html") ``` -------------------------------- ### Get US Counties - Specific Counties in a State Source: https://geeviz.org/_modules/geeViz/getSummaryAreasLib Example of filtering counties by name within a specific state, using both state abbreviation and county name filters. ```python getUSCounties(state_abbr='MT', county_names='Missoula,Ravalli') ``` -------------------------------- ### Instantiate EECreds and Add Credentials Source: https://geeviz.org/info/geeViz.eeAuth.eeCreds.html Demonstrates how to create an instance of EECreds, add credentials, and initiate the Earth Engine startup process. This is useful for managing multiple independent credential sets. ```python from geeViz.eeAuth.eeCreds import EECreds creds = EECreds() creds.addCreds(...) creds.start() ``` -------------------------------- ### annualizeCCDC Source: https://geeviz.org/_modules/geeViz/changeDetectionLib Function to get yearly CCDC coefficients. It calculates CCDC coefficients for each year, allowing for customization of the year start month/day and the use of composite dates for annualization. ```APIDOC ## annualizeCCDC ### Description Functions to get yearly ccdc coefficients. Get CCDC coefficients for each year. yearStartMonth and yearStartDay are the date that you want the CCDC "year" to start at. This is mostly important for Annualized CCDC. For CONUS & COASTAL AK LCMS, this is Sept. 1. So any change that occurs before Sept 1 in that year will be counted in that year, and Sept. 1 and after will be counted in the following year. 10/21 LSC Added Capability to use pixel-wise Composite Dates instead of set dates. If used, set annualizeWithCompositeDates to True and provide imported/prepped composite image collection with 'year' and 'julianDay' bands. Optionally, if there are holes in the composite dates, they can be interpolated using linear interpolation across time. ### Parameters - **ccdcImg** (ee.Image) - The CCDC image. - **startYear** (integer) - The starting year for annualization. - **endYear** (integer) - The ending year for annualization. - **startJulian** (integer) - The Julian day to start the annualization period. - **endJulian** (integer) - The Julian day to end the annualization period. - **tEndExtrapolationPeriod** (float) - A period to extrapolate the last tEnd segment by (fraction of a year). - **yearStartMonth** (integer, optional) - The month to start the CCDC year (default is 9). - **yearStartDay** (integer, optional) - The day to start the CCDC year (default is 1). - **annualizeWithCompositeDates** (boolean, optional) - If true, use composite dates from a provided collection (default is False). - **compositeCollection** (ee.ImageCollection, optional) - An image collection of composites with 'year' and 'julianDay' bands, used if `annualizeWithCompositeDates` is True. - **interpolateCompositeDates** (boolean, optional) - If true, interpolate missing composite dates (default is True). ### Returns ee.ImageCollection - An image collection of annual CCDC segment coefficients. ``` -------------------------------- ### run_local_server Source: https://geeviz.org/genindex Starts a local server using geeViz.geeView. ```APIDOC ## run_local_server() ### Description Starts a local server for development or testing. ### Method N/A (Function call) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ``` -------------------------------- ### Example: Get US National Parks in an Area Source: https://geeviz.org/_modules/geeViz/getSummaryAreasLib Shows how to filter protected areas to find US national parks (IUCN category II) that intersect with a defined area of interest. ```python parks = sal.getProtectedAreas(area=my_aoi, iucn_cat="II") ``` -------------------------------- ### Get US Counties - Counties by Name Across States Source: https://geeviz.org/_modules/geeViz/getSummaryAreasLib Example of retrieving counties by name, without specifying a state. Note that county names may exist in multiple states. ```python getUSCounties(county_names='Washington') ``` -------------------------------- ### Get USFS Forests and Land Cover Data Source: https://geeviz.org/notebooks/report_generation_examples Retrieves USFS forest boundaries within a specified region and selects the Land Cover band from the LCMS collection. This is a setup step for generating reports on forest land cover. ```python # In run_code: forests = sal.getUSFSForests(ee.Geometry.Point([-114, 46.5]).buffer(300000), region='01') lcms_lc = ee.ImageCollection('USFS/GTAC/LCMS/v2024-10').select(['Land_Cover']) ``` -------------------------------- ### Get GeeViz Theme Presets and Custom Themes Source: https://geeviz.org/_modules/geeViz/outputLib/themes Demonstrates how to obtain predefined themes like 'dark', 'light', and 'teal', or generate custom themes by specifying background and font colors. It also shows how to access color values in different formats (hex, RGB, RGBA) and check if a theme is dark. ```python from geeViz.outputLib.themes import get_theme # Named presets dark = get_theme("dark") light = get_theme("light") teal = get_theme("teal") # Auto-generate from a single color red_bg = get_theme(bg_color="#F00") # dark text auto-picked custom = get_theme(bg_color="#1a1a2e", font_color="#eee") # Access colors in different formats dark.bg_hex # '#272822' dark.bg_rgb # (39, 40, 34) dark.text_hex # '#f8f8f2' dark.is_dark # True dark.grid_rgba # 'rgba(248,248,242,0.15)' ``` -------------------------------- ### Explicitly Register Service Account Credential Source: https://geeviz.org/notebooks/eeAuthExamples Resets the credential singleton, adds a specific service account JSON file, and starts the proxy. This is useful for explicitly controlling which credentials are used, especially in multi-tenant scenarios. This example is skipped if DEMO_SA_PATH is not configured. ```python if not HAS_SA: print("Skipped (DEMO_SA_PATH not set).") else: from geeViz.eeAuth import eeCreds import ee # Reset the singleton so we register from a clean slate. eeCreds.stop() eeCreds._entries.clear() eeCreds.addCreds(DEMO_SA_PATH, name="prod") eeCreds.start() # With only one credential, no `.use()` needed — it's the default. print(eeCreds.current(), "→", ee.Number(2).getInfo()) ``` ```text [geeViz.eeAuth] EE initialized via proxy: http://127.0.0.1:8890/ee-api (tenant_header=X-geeViz-Creds) ``` ```text prod → 2 ``` -------------------------------- ### Get Tasks by Time Interval Source: https://geeviz.org/_modules/geeViz/taskManagerLib Retrieves a list of Earth Engine tasks that were created within a specified time interval. Requires 'datetime' objects for start and end times. The function converts the datetime objects to milliseconds since the epoch for comparison. ```python def timeTaskList(starttime, endtime): """Get list of tasks started within a specified time interval. Args: starttime (datetime): UTC datetime object for interval start. endtime (datetime): UTC datetime object for interval end. Returns: list: List of task dicts started within the interval. Example: >>> from datetime import datetime, timedelta >>> start = datetime.utcnow() - timedelta(hours=1) >>> end = datetime.utcnow() >>> timeTaskList(start, end) [{'id': 'ABCD', ...}, ...] """ tasks = ee.data.getTaskList() epoch = datetime.utcfromtimestamp(0) starttime = (starttime - epoch).total_seconds() * 1000.0 # Convert to ms since epoch endtime = (endtime - epoch).total_seconds() * 1000.0 thisList = [i for i in tasks if (i["creation_timestamp_ms"] >= starttime and i["creation_timestamp_ms"] <= endtime)] return thisList ``` -------------------------------- ### Initialize and View Folium Map with GEE Layers Source: https://geeviz.org/_modules/geeViz/foliumView This example demonstrates how to initialize a Folium map, set its center, add a Landsat image layer with specific visualization parameters, and finally view the map. Ensure you have an ee.Image object available. ```python from geeViz.foliumView import foliumMapper # Initialize the mapper mapper = foliumMapper() # Set the map center mapper.setCenter(-122.4194, 37.7749, 10) # Add a layer (example assumes you have an ee.Image object) mapper.addLayer(ee.Image("LANDSAT/LC08/C01/T1_SR/LC08_044034_20140318"), {"bands": ["B4", "B3", "B2"], "min": 0, "max": 3000}, "Landsat Image") # View the map mapper.view() ``` -------------------------------- ### Handle GET Request Source: https://geeviz.org/_modules/geeViz/geeView Handles GET requests. If the request is for the Earth Engine API, it proxies the request; otherwise, it falls back to the default GET behavior of the base handler (likely serving static files). ```python # Override each HTTP verb so reverse-proxy fires for /ee-api/*; everything # else falls through to ``SimpleHTTPRequestHandler``'s static-file behavior. def do_GET(self): # noqa: N802 - stdlib API if self._is_ee_api(): return self._proxy_ee_api() return super().do_GET() ``` -------------------------------- ### Instantiate and Add Credentials to EECreds Source: https://geeviz.org/_modules/geeViz/eeAuth/eeCreds Demonstrates how to create an instance of EECreds, add credentials using different methods, and start the credential management process. Useful for setting up independent credential registries. ```python from geeViz.eeAuth.eeCreds import EECreds creds = EECreds() creds.addCreds(...) creds.start() ``` -------------------------------- ### Run geeViz.eeAuth Server Standalone Source: https://geeviz.org/info/geeViz.eeAuth.server Starts the geeViz Earth Engine authentication proxy server as a standalone application. Use this for direct execution from the command line. ```python python -m geeViz.eeAuth --port 8888 ``` -------------------------------- ### Import geeViz and Initialize Earth Engine Source: https://geeviz.org/notebooks/getLandsatWrapperNotebook Imports the necessary geeViz modules and initializes the Earth Engine library. Includes a fallback to install the library if it's not found. ```python #Example of how to get Landsat data using the getImagesLib and view outputs using the Python visualization tools #Acquires Landsat data and then adds them to the viewer #################################################################################################### import os,sys sys.path.append(os.getcwd()) #Module imports try: import geeViz.getImagesLib as getImagesLib except: !python -m pip install geeViz import geeViz.getImagesLib as getImagesLib ee = getImagesLib.ee Map = getImagesLib.Map print('done') ``` -------------------------------- ### Get and Use geeViz Themes Source: https://geeviz.org/info/geeViz.outputLib.themes.html Demonstrates how to retrieve predefined themes like 'dark', 'light', and 'teal', or generate custom themes from specific background and font colors. It also shows how to access color values in different formats (hex, RGB, RGBA) and check if a theme is dark. ```python from geeViz.outputLib.themes import get_theme # Named presets dark = get_theme("dark") light = get_theme("light") teal = get_theme("teal") # Auto-generate from a single color red_bg = get_theme(bg_color="#F00") # dark text auto-picked custom = get_theme(bg_color="#1a1a2e", font_color="#eee") # Access colors in different formats dark.bg_hex # '#272822' dark.bg_rgb # (39, 40, 34) dark.text_hex # '#f8f8f2' dark.is_dark # True dark.grid_rgba # 'rgba(248,248,242,0.15)' ```