Earth2studio Create Datasource
NVIDIAOfficialCreated by NVIDIA Earth-2 Team
- Skill
- Workflow
- Software development
- Apache-2.0
- Medium risk
- Has scripts
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
This skill provides a structured, 14-step procedure for developers to integrate new remote data sources into the Earth2Studio framework. It covers the entire lifecycle from initial analysis of the remote store, through implementation of the appropriate source wrapper (DataSource, ForecastSource, DataFrameSource, or ForecastFrameSource), to testing, documentation, and PR submission. The workflow emphasizes asynchronous data fetching patterns, proper lexicon mapping, and rigorous validation using sanity-check plots to ensure data integrity before final submission.
What it does
- Determines the correct Earth2Studio source wrapper type based on data characteristics.
- Guides the implementation of asynchronous data fetching logic using fsspec.
- Facilitates the creation of lexicon mappings to standardize variable names.
- Automates the generation of skeleton files for source code and unit tests.
- Provides templates for variable validation and sanity-check visualization.
- Assists with PR creation and automated code review triage.
When to use it
- When you need to connect a new remote data store (S3, GCS, Azure, HTTP, HuggingFace) to Earth2Studio.
- When implementing custom data ingestion logic for gridded or sparse climate data.
- When you need to ensure your new data source meets project standards for testing, linting, and documentation.
- When you require a systematic approach to validate variable coverage and data quality.
Advantages
- Ensures consistency across all Earth2Studio data source implementations.
- Promotes high code quality through mandatory linting, formatting, and 90% test coverage.
- Reduces development time by providing standardized skeletons and async utility patterns.
- Prevents common errors by enforcing a clear validation and sanity-check process.
Usage examples
- “Add a new data source for the NOAA GFS analysis stored on S3.”
- The agent will initiate the 14-step workflow, starting by analyzing the S3 bucket, determining the appropriate DataSource type, and guiding you through the implementation, testing, and PR submission process.
Install
Download the skill as a ZIP:
https://mp-staging.autogineer.com/agent-skills/nvidia/earth2studio-create-datasource/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip earth2studio-create-datasource.zip -d .agents/skills
Documentation by NVIDIA Earth-2 Team
Create and Validate Data Source
Purpose
End-to-end workflow for implementing a new Earth2Studio data source wrapper that connects a remote data store (S3, GCS, Azure, HTTP, HuggingFace) to Earth2Studio's async data fetching infrastructure — from analysis through implementation, testing, validation, and PR submission.
Prerequisites
Earth2Studio dev environment with
uv(uv run pythonmust work)Git configured with fork (
origin) and upstream (upstream) remotesAccess to the target remote data store (credentials if private)
Python 3.10+
Workspace
Use the directory containing pyproject.toml. For Harbor evals, write to
/workspace/output/ preserving paths. Never read evals/targets/.
Instructions
Python Environment: Always use
uv run pythonor the local.venv. Never use the system Python directly.
Follow every step in order.
[CONFIRM] gates: Only Step 1 (Source Type) and Step 12 (Sanity-Check Plots) require explicit user approval. All other
[CONFIRM]markers are advisory — present decisions inline and proceed without blocking.Deliverables first: Write the source file and test file (Steps 6–7) before extended exploration, documentation, registration, CHANGELOG, or PR work. Skip Steps 8–14 when the user asks for implementation only.
Before you finish: Run verification commands in the repo root so results appear in the session log:
uv run pytest test/data/test_<source>.py -x make format && make lintBe concise: Avoid long architecture reports; summarize decisions in a few sentences and move on to file writes.
Hangs or User Feedback If agent becomes stuck or user provides a correction during this skills use, conservatively review relevant part of the skill and improve. Be concise.
One source type per invocation. Invoke again for companion types.
Reference Files
Load these on demand during the relevant steps:
| File | Content | Load at |
|---|---|---|
references/implementation-guide.py | Skeleton source with FILL comments | Steps 3–10 |
references/testing-guide.py | Test skeleton with FILL comments | Step 11 |
references/validation-guide.md | Plot templates, PR body template, Greptile handling | Steps 12–14 (optional, for templates) |
Workflow Overview
Step 0: Obtain reference → Step 1: Determine type → Step 2: Dependencies
→ Step 3: Add deps → Step 4: Create lexicon → Step 5: Update vocab/schema
→ Step 6: Create skeleton → Step 7: Implement source → Step 8: Register
→ Step 9: Documentation → Step 10: CHANGELOG → Step 11: Tests
→ Step 12: Validate & plots (user confirms) → Step 13: PR + sanity comment
→ Step 14: Greptile reviewStep 0 — Obtain Remote Data Store Reference
If $ARGUMENTS is provided, use it (URL → WebFetch; file path → read).
If empty, ask:
Please provide a URL, API documentation link, or description of the remote data store. This will be used to understand storage format, access pattern, variable inventory, temporal/spatial resolution.
Step 1 — Determine Source Type
| Protocol | Returns | Has lead_time? | Use |
|---|---|---|---|
| DataSource | xr.DataArray | No | Gridded analysis/reanalysis |
| ForecastSource | xr.DataArray | Yes | Gridded forecast |
| DataFrameSource | pd.DataFrame | No | Sparse/station obs |
| ForecastFrameSource | pd.DataFrame | Yes | Sparse forecast obs |
Key factors: gridded vs sparse → DataArray vs DataFrame; analysis vs forecast → Source vs ForecastSource.
[CONFIRM — Source Type]
Present recommended type with justification. Ask for confirmation.
Step 2 — Examine Remote Store & Propose Dependencies
Analyze: storage backend, file format, authentication, access pattern, temporal/spatial resolution, variable inventory.
Prefer fsspec:
| Backend | Preferred | Avoid |
|---|---|---|
| AWS S3 | s3fs (core dep) | boto3 directly |
| GCS | gcsfs (core dep) | google-cloud-storage |
| Azure | adlfs | azure-storage-blob |
| HTTP | fsspec (core dep) | requests |
| HuggingFace | huggingface_hub (core dep) | custom scripts |
Only fall back to dedicated libraries when fsspec cannot access the store.
Check pyproject.toml — only propose packages not already present.
Core deps include: s3fs, gcsfs, fsspec, zarr, netCDF4, h5py,
pygrib, huggingface-hub, pandas, pyarrow.
[CONFIRM — Dependencies & Access Pattern]
Present: backend, fsspec filesystem, new packages (with license), auth method.
Step 3 — Add Dependencies
Load
references/implementation-guide.pyfrom here through Step 10.
If new packages needed:
uv add --extra data <package>uv lockAdd optional dependency imports using
OptionalDependencyFailurepattern
Step 4 — Create Lexicon Class
Create earth2studio/lexicon/<source_name>.py with:
metaclass=LexiconTypeVOCAB: dict[str, str]mapping E2S names → remote keysget_item(cls, val)returningtuple[str, Callable]Use
::separator for structured keys
Map remote variables against E2STUDIO_VOCAB (282 entries in
earth2studio/lexicon/base.py).
[CONFIRM — Lexicon & Variable Mapping]
Present: class name, key format, full mapping table, modifiers, reference URL.
Step 5 — Update E2STUDIO_VOCAB / SCHEMA (if needed)
New vocab: surface = descriptive abbrev; pressure =
{name}{level}New schema fields: DataFrame sources only, check
E2STUDIO_SCHEMA
[CONFIRM — Vocabulary & Schema Updates]
Skip if no updates needed.
Step 6 — Create Skeleton Data Source File
Follow canonical method ordering:
Class constants
SCHEMA
__init___async_init__call__fetch_create_tasksfetch_wrapperfetch_array_validate_timeHelpers
cachepropertyavailableclassmethod
Use async task dataclass pattern for parallel execution.
[CONFIRM — Skeleton]
Present: class name, file path, skeleton code, task dataclass.
Step 7 — Implement the Data Source & Tests
The test file is a co-equal deliverable. Create
test/data/test_<filename>.pyalongside the source. Addtest_<source>_call_mockfor async sources.
Sync sources: Use prep_data_inputs/prep_forecast_inputs, direct __call__.
Async sources: See references/implementation-guide.py for required patterns:
_sync_async, managed_session, gather_with_concurrency, async_retry,
pure async I/O, try/finally cleanup. Constructor params: cache=True,
verbose=True, async_timeout=600, async_workers=16, retries=3.
DataFrame sources add time_tolerance.
Step 8 — Register the Source
earth2studio/data/__init__.py— alphabetical importearth2studio/lexicon/__init__.py— alphabetical importVerify
pyproject.tomldeps
Step 9 — Update Documentation
Add to correct RST file (
datasources_analysis.rst/_forecast.rst/_dataframe.rst)Class docstring: Parameters, Warning (download size), Note (reference URLs), Badges (last)
All public methods: NumPy-style docstrings
Step 10 — Update CHANGELOG.md
Add entry under the current unreleased version. See
references/implementation-guide.py REGISTRATION CHECKLIST for the format.
One line per source. Do NOT add separate lexicon entries.
Step 11 — Verify Style & Expand Tests
Run make format && make lint && make license. Load references/testing-guide.py
for test skeletons. Required tests: test_<source>_fetch (slow), _cache (slow),
_call_mock, _exceptions, _available. Target 90%+ coverage with --slow.
[CONFIRM — Tests]
Present test file, functions, coverage.
Step 12 — Validate Variables & Sanity-Check
Validate all lexicon vars against real data (run script, do NOT commit)
Remove variables with < 10% valid data
Create sanity-check plot (gridded or sparse template)
Tell user the plot path and ask for visual confirmation
[CONFIRM — Sanity-Check Plots]
User MUST visually inspect plots. Do not proceed without confirmation.
Step 13 — Branch, Commit & Open PR
Create branch
feat/data-source-<name>Commit (do NOT add sanity-check script/images)
Push to fork
gh pr create --repo NVIDIA/earth2studioImmediately post sanity-check validation as PR comment with:
Variable coverage table (name, count, range, unit)
Data validation summary (regions, storms/stations, time range)
Key findings (physically reasonable values, conversions verified)
Full validation script in
<details>blockImage placeholder:
<!-- Drag and drop sanity-check image here -->
[CONFIRM — Ready to Submit]
Verify all steps complete before creating PR.
Step 14 — Automated Code Review
Poll for Greptile review (5 min timeout)
Categorize feedback (bug/style/perf/docs/suggestion/false-positive)
Present triage table to user
Implement accepted fixes
Respond to PR comments
Push
[CONFIRM — Review Triage]
User approves which comments to address.
Examples
User: Add a data source for the NOAA GFS analysis on S3
Agent: [loads skill, proceeds through Steps 0–14]Limitations
One source type per invocation
Requires network access for validation (Step 12)
SPDX license headers required in all files
Reminders
DO: uv run python, loguru.logger, alphabetical order in __init__.py/RST/CHANGELOG,
canonical method ordering, async utilities (managed_session, gather_with_concurrency,
async_retry), pure async I/O, reference URLs in docstrings, try/finally cleanup.
AVOID: asyncio.to_thread, bare tqdm.gather, xarray for loading, full file downloads.
NEVER: loop.set_default_executor(), commit secrets, commit sanity-check scripts/images.
Files
- ATTRIBUTION.mdAdded by AutoGineer961 B
- BENCHMARK.md2.4 KiB
- LICENSELicence file added by AutoGineer11.2 KiB
- SKILL.md10.4 KiB
- evals/config.yml1.1 KiB
- evals/environment/Dockerfile867 B
- evals/environment/setup/bootstrap.shScript934 B
- evals/evals.json6.1 KiB
- evals/targets/eval_1_target.pyScript2.5 KiB
- evals/targets/eval_2_target.pyScript2.9 KiB
- evals/targets/eval_3_target.pyScript3.8 KiB
- evals/targets/eval_4_target.pyScript11.5 KiB
- evals/targets/test/eval_1_test_target.pyScript2.4 KiB
- evals/targets/test/eval_2_test_target.pyScript3.1 KiB
- evals/targets/test/eval_3_test_target.pyScript3.7 KiB
- evals/targets/test/eval_4_test_target.pyScript4.5 KiB
- references/implementation-guide.pyScript17.3 KiB
- references/testing-guide.pyScript10.1 KiB
- references/validation-guide.md9.5 KiB
- skill-card.md2.6 KiB
- skill.oms.sig7.9 KiB
evals/targets/eval_4_target.py
# SPDX-FileCopyrightText: Copyright (c) 2024-2026 NVIDIA CORPORATION & AFFILIATES.
# SPDX-FileCopyrightText: All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import hashlib
import os
import pathlib
import shutil
import uuid
from collections.abc import Callable
from dataclasses import dataclass
from datetime import datetime
import numpy as np
import s3fs
import xarray as xr
from loguru import logger
from earth2studio.data.utils import (
_sync_async,
async_retry,
datasource_cache_root,
gather_with_concurrency,
managed_session,
prep_data_inputs,
)
from earth2studio.lexicon import PhooLexicon
from earth2studio.utils.type import TimeArray, VariableArray
@dataclass
class PhooAsyncTask:
"""Async task for a single variable/time NetCDF file fetch."""
time_index: int
variable_index: int
s3_uri: str
modifier: Callable
class PhooAnalysis:
"""Phoo global analysis data source on a 1-degree lat/lon grid.
Fetches analysis data from the ``s3://phoo-weather-data`` S3 bucket. Data
is stored as individual NetCDF files per variable and time step on a
181x360 global grid at 6-hour intervals from 2020-01-01 to present.
Parameters
----------
cache : bool, optional
Cache data source on local memory, by default True
verbose : bool, optional
Print download progress, by default True
async_timeout : int, optional
Time in seconds after which download will be cancelled, by default 600
async_workers : int, optional
Maximum number of concurrent download tasks, by default 16
retries : int, optional
Number of retry attempts for failed downloads, by default 3
Warning
-------
This is a remote data source and can potentially download a large amount of data
to your local machine for large requests.
Note
----
Additional information on the data repository can be referenced here:
- https://phoo-weather-data.example.com/docs
Badges
------
region:global dataclass:analysis product:temp product:atmos
"""
PHOO_BUCKET = "phoo-weather-data"
PHOO_LAT = np.linspace(-90.0, 90.0, 181)
PHOO_LON = np.linspace(0.0, 360.0, 360, endpoint=False)
MIN_DATE = datetime(2020, 1, 1)
def __init__(
self,
cache: bool = True,
verbose: bool = True,
async_timeout: int = 600,
async_workers: int = 16,
retries: int = 3,
) -> None:
self._cache = cache
self._verbose = verbose
self._async_workers = async_workers
self._retries = retries
self.async_timeout = async_timeout
self._tmp_cache_hash: str | None = None
self.fs: s3fs.S3FileSystem | None = None
async def _async_init(self) -> None:
"""Async initialization of S3 filesystem.
Note
----
Async fsspec expects initialization inside of the execution loop.
"""
self.fs = s3fs.S3FileSystem(
anon=True, client_kwargs={}, asynchronous=True, skip_instance_cache=True
)
def __call__(
self,
time: datetime | list[datetime] | TimeArray,
variable: str | list[str] | VariableArray,
) -> xr.DataArray:
"""Retrieve Phoo analysis data.
Parameters
----------
time : datetime | list[datetime] | TimeArray
Timestamps to return data for (UTC).
variable : str | list[str] | VariableArray
Strings or list of strings that refer to variables to return.
Must be in the Phoo lexicon.
Returns
-------
xr.DataArray
Phoo weather data array with dims [time, variable, lat, lon]
"""
try:
xr_array = _sync_async(
self.fetch, time, variable, timeout=self.async_timeout
)
finally:
if not self._cache:
shutil.rmtree(self.cache, ignore_errors=True)
return xr_array
async def fetch(
self,
time: datetime | list[datetime] | TimeArray,
variable: str | list[str] | VariableArray,
) -> xr.DataArray:
"""Async function to get data.
Parameters
----------
time : datetime | list[datetime] | TimeArray
Timestamps to return data for (UTC).
variable : str | list[str] | VariableArray
Strings or list of strings that refer to variables to return.
Must be in the Phoo lexicon.
Returns
-------
xr.DataArray
Phoo weather data array with dims [time, variable, lat, lon]
"""
if self.fs is None:
await self._async_init()
time, variable = prep_data_inputs(time, variable)
self._validate_time(time)
pathlib.Path(self.cache).mkdir(parents=True, exist_ok=True)
# Pre-allocate output array
xr_array = xr.DataArray(
data=np.empty(
(len(time), len(variable), len(self.PHOO_LAT), len(self.PHOO_LON))
),
dims=["time", "variable", "lat", "lon"],
coords={
"time": time,
"variable": variable,
"lat": self.PHOO_LAT,
"lon": self.PHOO_LON,
},
)
async_tasks = self._create_tasks(time, variable)
async with managed_session(self.fs):
coros = [self.fetch_wrapper(task, xr_array) for task in async_tasks]
await gather_with_concurrency(
coros,
max_workers=self._async_workers,
task_timeout=60.0,
desc="Fetching Phoo data",
verbose=(not self._verbose),
)
return xr_array
def _create_tasks(
self, time: list[datetime], variable: list[str]
) -> list[PhooAsyncTask]:
"""Create download tasks for each time/variable combination.
Parameters
----------
time : list[datetime]
Timestamps to be downloaded (UTC).
variable : list[str]
List of variables to be downloaded.
Returns
-------
list[PhooAsyncTask]
List of async download tasks.
"""
tasks: list[PhooAsyncTask] = []
for i, t in enumerate(time):
for k, v in enumerate(variable):
try:
phoo_name, modifier = PhooLexicon[v]
except KeyError as e:
raise KeyError(f"Variable '{v}' not found in PhooLexicon") from e
s3_uri = self._netcdf_uri(t, phoo_name)
tasks.append(
PhooAsyncTask(
time_index=i,
variable_index=k,
s3_uri=s3_uri,
modifier=modifier,
)
)
return tasks
async def fetch_wrapper(self, task: PhooAsyncTask, xr_array: xr.DataArray) -> None:
"""Wrapper to download and insert array data into the output."""
out = await async_retry(
self.fetch_array,
task,
retries=self._retries,
backoff=1.0,
task_timeout=120.0,
exceptions=(OSError, IOError, TimeoutError, ConnectionError),
)
xr_array[task.time_index, task.variable_index] = task.modifier(out)
async def fetch_array(self, task: PhooAsyncTask) -> np.ndarray:
"""Fetch a single NetCDF variable array from S3.
Parameters
----------
task : PhooAsyncTask
Async task containing S3 URI and modifier.
Returns
-------
np.ndarray
2D array of shape (181, 360).
"""
logger.debug(f"Fetching Phoo file: {task.s3_uri}")
cache_path = await self._fetch_remote_file(task.s3_uri)
with xr.open_dataset(cache_path) as ds:
# Assume single variable in file, extract first data variable
var_name = list(ds.data_vars)[0]
values = ds[var_name].values
return values
@classmethod
def _validate_time(cls, times: list[datetime]) -> None:
"""Verify if date time is valid for Phoo data source.
Parameters
----------
times : list[datetime]
List of date times to validate.
"""
for time in times:
if time.hour % 6 != 0 or time.minute != 0 or time.second != 0:
raise ValueError(
f"Requested datetime {time} must align to a 6-hour cycle "
f"(00, 06, 12, 18z)."
)
if time < cls.MIN_DATE:
raise ValueError(
f"Requested datetime {time} is earlier than "
f"PhooAnalysis.MIN_DATE ({cls.MIN_DATE.isoformat()})."
)
async def _fetch_remote_file(self, path: str) -> str:
"""Download a remote file to local cache using async S3.
Parameters
----------
path : str
S3 URI to download.
Returns
-------
str
Local cache path of the downloaded file.
"""
if self.fs is None:
raise ValueError("File system is not initialized")
sha = hashlib.sha256(path.encode())
filename = sha.hexdigest()
cache_path = os.path.join(self.cache, filename)
if not pathlib.Path(cache_path).is_file():
data = await self.fs._cat_file(path)
with open(cache_path, "wb") as fh:
fh.write(data)
return cache_path
def _netcdf_uri(self, time: datetime, variable: str) -> str:
"""Generate the S3 URI for a given time and variable.
Parameters
----------
time : datetime
Timestamp.
variable : str
Remote variable name.
Returns
-------
str
S3 URI path.
"""
return (
f"s3://{self.PHOO_BUCKET}/analysis/"
f"{time.year:04d}/{time.month:02d}/{time.day:02d}/"
f"{time.hour:02d}z/{variable}.nc"
)
@property
def cache(self) -> str:
"""Return appropriate cache location."""
cache_location = os.path.join(datasource_cache_root(), "phoo")
if not self._cache:
if self._tmp_cache_hash is None:
self._tmp_cache_hash = uuid.uuid4().hex[:8]
cache_location = os.path.join(
cache_location, f"tmp_phoo_{self._tmp_cache_hash}"
)
return cache_location
@classmethod
def available(cls, time: datetime | np.datetime64) -> bool:
"""Check if given date time is available.
Parameters
----------
time : datetime | np.datetime64
Date time to check.
Returns
-------
bool
If date time is available based on offline validation.
"""
if isinstance(time, np.datetime64):
time = time.astype("datetime64[ns]").astype("datetime64[us]").item()
try:
cls._validate_time([time])
except ValueError:
return False
return True
Requirements and compatibility
Written for: Claude Code
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Needs: Claude Code frontmatter, Names Claude Code tools, Needs Python
Security
What our scanner noticed· Medium risk
- Large base64-encoded blobs
- Scripts that your agent may run
This skill includes scripts that your agent may run. Read them before you use it.
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- Created by
- NVIDIA Earth-2 Team
- Publisher
- NVIDIA (Official)
- Source
- NVIDIA/skills · skills/earth2studio-create-datasource · commit fce3cca
- Licence
- Apache License 2.0 (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE-APACHE)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
AutoGineer is not affiliated with or endorsed by NVIDIA Earth-2 Team or NVIDIA.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download earth2studio-create-datasource.zip