This guide walks through implementing a mission source from scratch and registering it with the Fornax Cutouts registry.
What Is a Source?¶
A source is a Python class that answers one question: given a list of sky positions, which FITS files contain data for those positions?
The framework calls your source’s get_filenames() method to build the list of files to cut. Everything else — job queuing, worker dispatch, cutout generation, result storage — is handled by Fornax Cutouts.
Step 1: Create the Source File¶
Create a new .py file anywhere under your CUTOUTS__SOURCE_PATH directory:
sources/
└── my_mission.pyThe file name does not matter. The registry discovers all *.py files under the configured path recursively.
Step 2: Implement the Source Class¶
from fornax_cutouts.sources import cutout_registry, AbstractMissionSource, MissionMetadata
from fornax_cutouts.models.base import Positions, TargetPosition
from fornax_cutouts.models.cutouts import FilenameLookupResponse, FilenameWithMetadata
@cutout_registry.register_source("my_mission")
class MyMissionSource(AbstractMissionSource):
metadata = MissionMetadata(
name="my_mission",
pixel_size=0.5, # arcseconds per pixel
max_cutout_size=2000, # maximum cutout size in pixels
filter=["g", "r", "i"], # valid filter names
survey=["wide"], # valid survey names
)
source_file_patterns = ("*/my-bucket/data/*",)
def get_filenames(
self,
position: TargetPosition | Positions,
filter: str | list[str] = ["g", "r", "i"],
survey: str | list[str] = ["wide"],
**kwargs,
) -> list[FilenameLookupResponse]:
filter = self._cast_list_parameter(filter)
survey = self._cast_list_parameter(survey)
results = []
for ra, dec in position:
for f in filter:
filename = self._lookup_file(ra, dec, f)
if filename is None:
continue
results.append(
FilenameLookupResponse(
mission="my_mission",
target=(ra, dec),
filenames=[FilenameWithMetadata(filename=filename)],
)
)
return results
def _lookup_file(self, ra: float, dec: float, filter: str) -> str | None:
# Replace with your actual file lookup logic
return f"s3://my-bucket/data/{filter}/{ra:.4f}_{dec:.4f}.fits"Key points¶
The
@cutout_registry.register_source("my_mission")decorator registers the class under the key"my_mission". This key is used in API requests as the mission name.metadatais a class-level attribute, not an instance attribute.get_filenames()receives the positions as aTargetPosition(single position) orPositions(list of(ra, dec)tuples). Always handle both cases.Use
self._cast_list_parameter()to normalizefilterandsurveyfrom either a string or list to a list.When a request omits
filterorsurvey, the API does not pass them; yourget_filenames()defaults apply.Return an empty list if no files are found — never raise an exception for missing data.
Optional
source_file_patternsto allow sync cutouts to infermissionfor logs and source resolution. The default (no patterns) stays"sync"andcolor_preview. Overridematches_source_file()if globbing behavior needs customization. Async jobs pass mission explicitly and are not inferred.Optional: override
resolve_source_file(source_file)to translate a filename/identifier to the URL or path the worker should open (e.g. minting a short-lived presigned URL right before cutting). By default it returnssource_fileunchanged. Sync cutouts rely onsource_file_patterns(ormatches_source_file()) to infer the mission before calling this hook.
Step 3: Define MissionMetadata¶
MissionMetadata describes the capabilities of your source. The framework uses it to validate requests before dispatching jobs.
MissionMetadata(
name="my_mission", # must match the register_source() key
pixel_size=0.5, # arcseconds per pixel (used for coordinate math)
max_cutout_size=2000, # max cutout size in pixels, per axis
filter=["g", "r", "i"], # valid values for the filter parameter
survey=["wide"], # valid values for the survey parameter
)MissionMetadata allows extra fields beyond the standard ones. Use this for mission-specific metadata you want to expose via the /missions endpoint:
MissionMetadata(
name="my_mission",
pixel_size=0.5,
max_cutout_size=2000,
filter=["g", "r", "i"],
survey=["wide"],
# Mission-specific extras
stack_files=["data", "wt", "mask"],
)Step 4: Implement File Lookup¶
The core of your source is the file lookup logic. The approach depends on how your survey’s metadata is stored.
Option A: DuckDB + Parquet (recommended for large catalogs)¶
This is the pattern used by the PS1 source. Parquet files are queried directly with DuckDB, which supports both local files and S3:
import duckdb
from fornax_cutouts.sources import cutout_registry, AbstractMissionSource, MissionMetadata
from fornax_cutouts.models.base import Positions, TargetPosition
from fornax_cutouts.models.cutouts import FilenameLookupResponse, FilenameWithMetadata
@cutout_registry.register_source()
class MyMissionSource(AbstractMissionSource):
metadata = MissionMetadata(
name="my_mission",
pixel_size=0.5,
max_cutout_size=2000,
filter=["g", "r", "i"],
survey=["wide"],
)
_metadata_path = "s3://my-bucket/metadata/files.parquet"
def __init__(self):
self.conn = duckdb.connect()
# Configure S3 access if needed
self.conn.execute("INSTALL httpfs; LOAD httpfs;")
self.conn.execute("SET s3_region='us-east-1';")
def get_filenames(
self,
position: TargetPosition | Positions,
filter: str | list[str] = ["g", "r", "i"],
survey: str | list[str] = ["wide"],
**kwargs,
) -> list[FilenameLookupResponse]:
filter = self._cast_list_parameter(filter)
# Convert positions to RA/Dec arrays
positions = list(position) if not isinstance(position, list) else position
ra_min = min(p[0] for p in positions) - 0.1
ra_max = max(p[0] for p in positions) + 0.1
dec_min = min(p[1] for p in positions) - 0.1
dec_max = max(p[1] for p in positions) + 0.1
filter_list = ", ".join(f"'{f}'" for f in filter)
query = f"""
SELECT path, ra, dec, filter
FROM read_parquet('{self._metadata_path}')
WHERE ra BETWEEN {ra_min} AND {ra_max}
AND dec BETWEEN {dec_min} AND {dec_max}
AND filter IN ({filter_list})
"""
results = []
for row in self.conn.execute(query).fetchall():
path, ra, dec, filt = row
results.append(
FilenameLookupResponse(
mission="my_mission",
target=(ra, dec),
filenames=[
FilenameWithMetadata(
filename=path,
metadata={"filter": filt},
)
],
)
)
return resultsOption B: Simple path construction¶
For surveys with predictable file naming conventions:
def get_filenames(
self,
position: TargetPosition | Positions,
filter: str | list[str] = ["g"],
**kwargs,
) -> list[FilenameLookupResponse]:
filter = self._cast_list_parameter(filter)
positions = [position] if isinstance(position, TargetPosition) else list(position)
results = []
for ra, dec in positions:
for f in filter:
# Construct a deterministic path from coordinates
tile = self._sky_to_tile(ra, dec)
path = f"s3://my-bucket/{f}/{tile}.fits"
results.append(
FilenameLookupResponse(
mission="my_mission",
target=(ra, dec),
filenames=[FilenameWithMetadata(filename=path)],
)
)
return resultsStep 5: Optional Hooks¶
Custom Validation¶
Override validate_request() to add mission-specific validation beyond the built-in size and filter checks. size is an (x, y) tuple in pixels, already converted from angular units using metadata.pixel_size:
def validate_request(self, size: tuple[int, int], **extras) -> bool:
# Run the standard checks first
is_valid = super().validate_request(size=size, **extras)
# Add custom checks
epoch = extras.get("epoch")
if epoch is not None:
is_valid &= epoch in ["2010", "2015", "2020"]
return is_validResolving Source Files at Cutout Time¶
Override resolve_source_file() when get_filenames() returns a basename or stable identifier that must be resolved to a readable path or URL (such as a short-lived presigned URL) right before cutting:
def resolve_source_file(self, source_file: str) -> str:
return self._mint_presigned_url(source_file)For sync cutouts (where mission is not passed), set source_file_patterns or override matches_source_file() so the worker can infer the mission and invoke resolve_source_file().
When a source file cannot be resolved, resolve_source_file should raise a SourceFileResolutionException to fail the cutout for that file and report the error.
Step 6: Verify Registration¶
Start the API and check that your source appears in the missions list:
fornax-cutouts api
curl http://localhost:8000/api/v0/missionsExpected response includes your mission:
{
"my_mission": {
"name": "my_mission",
"pixel_size": 0.5,
"max_cutout_size": 2000,
"filter": ["g", "r", "i"],
"survey": ["wide"]
}
}Step 7: Submit a Test Job¶
curl -X POST http://localhost:8000/api/v0/cutouts/async \
-F "position[]=83.8221,-5.3911" \
-F "size=500" \
-F "my_mission.filter=r" \
-F "my_mission.survey=wide"Follow the redirect to poll the job status:
curl http://localhost:8000/api/v0/cutouts/async/{job_id}/phaseChecklist¶
Source file is under
CUTOUTS__SOURCE_PATHClass is decorated with
@cutout_registry.register_source("mission_key")metadata.namematches theregister_source()keyget_filenames()handles bothTargetPositionandPositionsinputget_filenames()returns an empty list (not an exception) when no files are foundOptional: override
get_count()if counting files is cheaper than returning the full listOptional: override
resolve_source_file()if filenames need resolution (e.g. presigned URLs) when the worker opens themOptional: set
source_file_patternsso sync cutouts can infermissionfrom the filenamefilterandsurveyare normalized with_cast_list_parameter()Source appears in
GET /api/v0/missionsafter startup