Package: astrometry
AstrometryGet startedExamplesProvide size and position hintsPrint progress information (download and solve)Print field stars metadataCalculate field stars pixel positions with astropyPrint series description and size (without downloading them)Disable tune-up and distortionStop the solver early using the log-odds callbackReturn after the first matchReturn early if the best log-odds are larger than 100.0Return early if there are at least ten matchesReturn early if the three best matches are similarChoosing seriesDocumentationSolverSizeHintPositionHintActionParitySolutionParametersSolutionMatchStarSeriesbatches_generatorSupportsFloatMappingContributePublishMSVC compatibility (work in progress)AstrometryAstrometry turns a list of star positions into a pixel-to-sky transformation (WCS) by calling C functions from the Astrometry.net library (https://astrometry.net).Astrometry.net star index files ("series") are automatically downloaded when required.This package is useful for solving plates from a Python script, comparing star extraction methods, or hosting a simple local version of Astrometry.net with minimal dependencies. Seehttps://github.com/dam90/astrometryfor a more complete self-hosting solution.Unlike Astrometry.net, Astrometry does not include FITS parsing or image pre-processing algorithms. Stars must be provided as a list of pixel positions.This library works on Linux and macOS, but not Windows (at the moment). WSL should work but has not been tested.We are not the authors of the Astrometry.net library. You should cite works fromhttps://astrometry.net/biblio.htmlif you use the Astrometry.net algorithm via this package.Get startedpython3-mpipinstallastrometryimportastrometrysolver=astrometry.Solver(astrometry.series_5200.index_files(cache_directory="astrometry_cache",scales={6},))stars=[[388.9140568247906,656.5003281719216],[732.9210858972549,473.66395545775106],[401.03459504299843,253.788113189415],[312.6591868096163,624.7527729425295],[694.6844564647456,606.8371776658344],[741.7233477959561,344.41284826261443],[867.3574610200455,672.014835980283],[1063.546651153479,593.7844603550848],[286.69070190952704,422.170016812049],[401.12779619355155,16.13543616977013],[205.12103484692776,698.1847350789413],[202.88444768690894,111.24830187635557],[339.1627757703069,86.60739435924549],]solution=solver.solve(stars=stars,size_hint=None,position_hint=None,solution_parameters=astrometry.SolutionParameters(),)ifsolution.has_match():print(f"{solution.best_match().center_ra_deg=}")print(f"{solution.best_match().center_dec_deg=}")print(f"{solution.best_match().scale_arcsec_per_pixel=}")solveis thread-safe. It can be called any number of times from the sameSolverobject.ExamplesProvide size and position hintsimportastrometrysolver=...solution=solver.solve(stars=...,size_hint=astrometry.SizeHint(lower_arcsec_per_pixel=1.0,upper_arcsec_per_pixel=2.0,),position_hint=astrometry.PositionHint(ra_deg=65.7,dec_deg=36.2,radius_deg=1.0,),solution_parameters=...)Print progress information (download and solve)importastrometryimportlogginglogging.getLogger().setLevel(logging.INFO)solver=...solution=...Print field stars metadataAstrometry extracts metadata from the star index ("series"). SeeChoosing seriesfor a description of the available data.importastrometrysolver=...solution=...ifsolution.has_match():forstarinsolution.best_match().stars:print(f"{star.ra_deg}º,{star.dec_deg}º:",star.metadata)Calculate field stars pixel positions with astropyimportastrometrysolver=...solution=...ifsolution.has_match():wcs=solution.best_match().astropy_wcs()pixels=wcs.all_world2pix([[star.ra_deg,star.dec_deg]forstarinsolution.best_match().stars],0,)# pixels is a len(solution.best_match().stars) x 2 numpy array of float valuesastropy.wcs.WCSprovides many more functions to probe the transformation properties and convert from and to pixel coordinates. Seehttps://docs.astropy.org/en/stable/api/astropy.wcs.WCS.htmlfor details. Astropy (https://pypi.org/project/astropy/) must be installed to use this method.Print series description and size (without downloading them)importastrometryprint(astrometry.series_5200_heavy.description)print(astrometry.series_5200_heavy.size_as_string({2,3,4}))SeeChoosing Seriesfor a list of available series.Disable tune-up and distortionimportastrometrysolver=...solution=solver.solve(stars=...,size_hint=...,position_hint=...,solution_parameters=astrometry.SolutionParameters(sip_order=0,tune_up_logodds_threshold=None,),)Stop the solver early using the log-odds callbackReturn after the first matchimportastrometrysolver=...solution=solver.solve(stars=...,size_hint=...,position_hint=...,solution_parameters=astrometry.SolutionParameters(logodds_callback=lambdalogodds_list:astrometry.Action.STOP,),)Return early if the best log-odds are larger than 100.0importastrometrysolver=...solution=solver.solve(stars=...,size_hint=...,position_hint=...,solution_parameters=astrometry.SolutionParameters(logodds_callback=lambdalogodds_list:(astrometry.Action.STOPiflogodds_list[0]>100.0elseastrometry.Action.CONTINUE),),)Return early if there are at least ten matchesimportastrometrysolver=...solution=solver.solve(stars=...,size_hint=...,position_hint=...,solution_parameters=astrometry.SolutionParameters(logodds_callback=lambdalogodds_list:(astrometry.Action.STOPiflen(logodds_list)>=10.0elseastrometry.Action.CONTINUE),),)Return early if the three best matches are similarimportastrometrydeflogodds_callback(logodds_list:list[float])->astrometry.Action:iflen(logodds_list)<3:returnastrometry.Action.CONTINUEiflogodds_list[1]>logodds_list[0]-10andlogodds_list[2]>logodds_list[0]-10:returnastrometry.Action.STOPreturnastrometry.Action.CONTINUEsolver=...solution=solver.solve(stars=...,size_hint=...,position_hint=...,solution_parameters=astrometry.SolutionParameters(logodds_callback=logodds_callback,),)Choosing seriesThis library downloads series fromhttp://data.astrometry.net. A solver can be instantiated with multiple series and scales as follows:importastrometrysolver=astrometry.Solver(astrometry.series_5200.index_files(cache_directory="astrometry_cache",scales={4,5,6},)+astrometry.series_4200.index_files(cache_directory="astrometry_cache",scales={6,7,12},))Astrometry.net gives the following recommendations to choose a scale:Each index file contains a large number of “skymarks” (landmarks for the sky) that allow our solver to identify your images. The skymarks contained in each index file have sizes (diameters) within a narrow range. You probably want to download index files whose quads are, say, 10% to 100% of the sizes of the images you want to solve.For example, let’s say you have some 1-degree square images. You should grab index files that contain skymarks of size 0.1 to 1 degree, or 6 to 60 arcminutes. Referring to the table below, you should [try index files with scales 3 to 9]. You might find that the same number of fields solve, and faster, using just one or two of the index files in the middle of that range - in our example you might try [5, 6 and 7].--http://astrometry.net/doc/readme.htmlScale012345678910111213141516171819Skymark diameter (arcmin)[2.0, 2.8][2.8, 4.0][4.0, 5.6][5.6, 8.0][8, 11][11, 16][16, 22][22, 30][30, 42][42, 60][60, 85][85, 120][120, 170][170, 240][240, 340][340, 480][480, 680][680, 1000][1000, 1400][1400, 2000]The table below lists series sizes and properties (we copied the descriptions fromhttp://data.astrometry.net). You can access a series' object withastrometry.series_{name}(for exampleastrometry.series_4200).NameTotal sizeScalesDescriptionMetadata41000.36 GB[7, 19]built from the Tycho-2 catalog, good for images wider than 1 degree, recommendedMAG_BT: floatMAG_VT: floatMAG_HP: floatMAG: float420033.78 GB[0, 19]built from the near-infared 2MASS survey, runs out of stars at the low end, most users will probably prefer 4100 or 5200j_mag: float500076.24 GB[0, 7]an older version from Gaia-DR2 but without Tycho-2 stars merged in, our belief is that series_5200 will work better than this onesource_id: intphot_g_mean_mag: floatphot_bp_mean_mag: floatphot_rp_mean_mag: floatparallax: floatparallax_error: floatpmra: floatpmra_error: floatpmdec: floatpmdec_error: floatra: floatdec: floatref_epoch: float520036.14 GB[0, 6]LIGHT version built from Tycho-2 + Gaia-DR2, good for images narrower than 1 degree, combine with 4100-series for broader scale coverage, the LIGHT version contains smaller files with no additional Gaia-DR2 information tagged along, recommended-5200_heavy79.67 GB[0, 6]HEAVY version same as 5200, but with additional Gaia-DR2 information (magnitude in G, BP, RP, proper motions and parallaxes), handy if you want that extra Gaia information for matched starsra: floatdec: floatmag: floatref_cat: strref_id: intpmra: floatpmdec: floatparallax: floatra_ivar: floatdec_ivar: floatpmra_ivar: floatpmdec_ivar: floatparallax_ivar: floatphot_bp_mean_mag: floatphot_rp_mean_mag: float60001.20 GB[4, 6]very specialized, uses GALEX Near-UV measurements, and only a narrow range of scalesfuv_mag: floatnuv_mag: float61001.58 GB[4, 6]very specialized, uses GALEX Far-UV measurements, and only a narrow range of scalesfuv_mag: floatnuv_mag: floatThe table below indicates the total file size for each scale (most series have multiple index files per scale).Name0123456789101112131415161718194100-------165.00 MB94.55 MB49.77 MB24.87 MB10.21 MB5.30 MB2.73 MB1.38 MB740.16 kB408.96 kB247.68 kB187.20 kB144.00 kB420014.22 GB9.25 GB5.06 GB2.63 GB1.31 GB659.09 MB328.25 MB165.44 MB81.84 MB41.18 MB20.52 MB8.02 MB4.17 MB2.16 MB1.10 MB596.16 kB339.84 kB213.12 kB164.16 kB132.48 kB500034.79 GB20.19 GB10.74 GB5.44 GB2.71 GB1.36 GB676.79 MB340.73 MB------------520017.20 GB9.49 GB4.86 GB2.45 GB1.22 GB614.89 MB307.72 MB-------------5200_heavy36.46 GB21.20 GB11.29 GB5.72 GB2.85 GB1.43 GB714.56 MB-------------6000----892.55 MB457.66 MB233.23 MB-------------6100----599.33 MB384.09 MB214.79 MB-------------DocumentationSolverclassSolver:def__init__(self,index_files:list[pathlib.Path]):...defsolve(self,stars:typing.Iterable[SupportsFloatMapping],size_hint:typing.Optional[SizeHint],position_hint:typing.Optional[PositionHint],solution_parameters:SolutionParameters,)->Solution:...solveis thread-safe and can be called any number of times.index_files: List of index files to use for solving. The list need not come from aSeriesobject. Series subsets and combinations are possible as well.star: iterator over a list of pixel coordinates for the input stars.size_hint: Optional angular pixel size range (SizeHint). Significantly speeds upsolvewhen provided. Ifsize_hintisNone, the range[0.1, 1000.0]is used. This default range can be changed by settingastrometry.DEFAULT_LOWER_ARCSEC_PER_PIXELandastrometry.DEFAULT_UPPER_ARCSEC_PER_PIXELto other values.position_hint: Optional field center Ra/Dec coordinates and error radius (PositionHint). Significantly speeds upsolvewhen provided. Ifposition_hintis None, the entire sky is used (radius_deg = 180.0).solution_parameters: Advanced solver parameters (SolutionParameters)SizeHint@dataclasses.dataclassclassSizeHint:lower_arcsec_per_pixel:floatupper_arcsec_per_pixel:floatlower_arcsec_per_pixelandupper_arcsec_per_pixelmust be larger than0andupper_arcsec_per_pixelmust be smaller than or equal toupper_arcsec_per_pixel.PositionHint@dataclasses.dataclassclassPositionHint:ra_deg:floatdec_deg:floatradius_deg:floatra_degmust be in the range[0.0, 360.0[.dec_degmust be in the range[-90.0, 90.0].radiusmust be larger than or equal to zero.All values are in degrees and must use the same frame of reference as the index files. Astrometry.net index files use J2000 FK5 (https://docs.astropy.org/en/stable/api/astropy.coordinates.FK5.html). ICRS and FK5 differ by less than 0.1 arcsec (https://www.iers.org/IERS/EN/Science/ICRS/ICRS.html).ActionclassAction(enum.Enum):STOP=0CONTINUE=1ParityclassParity(enum.IntEnum):NORMAL=0FLIP=1BOTH=2SolutionParameters@dataclasses.dataclassclassSolutionParameters:solve_id:typing.Optional[str]=Noneuniformize_index:bool=Truededuplicate:bool=Truesip_order:int=3sip_inverse_order:int=0distance_from_quad_bonus:bool=Truepositional_noise_pixels:float=1.0distractor_ratio:float=0.25code_tolerance_l2_distance:float=0.01minimum_quad_size_pixels:typing.Optional[float]=Noneminimum_quad_size_fraction:float=0.1maximum_quad_size_pixels:float=0.0maximum_quads:int=0maximum_matches:int=0parity:Parity=Parity.BOTHtune_up_logodds_threshold:typing.Optional[float]=14.0output_logodds_threshold:float=21.0slices_generator:typing.Callable[[int],typing.Iterable[tuple[int,int]]]=astrometry.batches_generator(25)logodds_callback:typing.Callable[[list[float]],Action]=lambda_:Action.CONTINUEsolve_id: Optional plate identifier used in logging messages. Ifsolve_idisNone, it is automatically assigned a unique integer. The value can be retrieved from the Solution object (solution.solve_id).uniformize_index: Uniformize field stars at the matched index scale before verifying a match.deduplicate: De-duplicate field stars before verifying a match.sip_order: Polynomial order of the Simple Imaging Polynomial distortion (seehttps://irsa.ipac.caltech.edu/data/SPITZER/docs/files/spitzer/shupeADASS.pdf).0disables SIP distortion.tune_up_logodds_thresholdmust beNoneifsip_orderis0.sip_inverse_order: Polynomial order of the inversee Simple Polynomial distortion. Usually equal tosip_order.0means "equal tosip_order".distance_from_quad_bonus: Assume that stars far from the matched quad will have larger positional variance.positional_noise_pixels: Expected error on the positions of stars.distractor_ratio: Fraction of distractors in the range]0, 1].code_tolerance_l2_distance: Code tolerance in 4D codespace L2 distance.minimum_quad_size_pixels: Minimum size of field quads to try,Nonecalculates the size automatically asminimum_quad_size_fraction * min(Δx, Δy), whereΔx(resp.Δy) is the maximumxdistance (resp.ydistance) between stars in the field.minimum_quad_size_fraction: Only used ifminimum_quad_size_pixelsisNone(see above).maximum_quad_size_pixels: Maximum size of field quads to try,0.0means no limit.maximum_quads: Number of field quads to try,0means no limit.maximum_matches: Number of quad matches to try,0means no limit.parity: Parity.NORMAL does not flip the axes, Parity.FLIP does, and Parity.BOTH tries flipped and non-flipped axes (at the cost of doubling computations).tune_up_logodds_threshold: Matches whose log-odds are larger than this value are tuned-up (SIP distortion estimation) and accepted if their post-tune-up log-odds are larger thanoutput_logodds_threshold.Nonedisables tune-up and distortion estimation (SIP). The default Astrometry.net value ismath.log(1e6).output_logodds_threshold: Matches whose log-odds are larger than this value are immediately accepted (added to the solution matches). The default Astrometry.net value ismath.log(1e9).slices_generator: User-provided function that takes a number of stars as parameter and returns an iterable (such as list) of two-elements tuples representing ranges. The first tuple item (start) is included while the second tuple item (end) is not. The returned ranges can have a variable size and/or overlap. The algorithm compares each range with the star catalogue sequentially. Small ranges significantly speed up the algorithm but increase the odds of missing matches.astrometry.batches_generator(n)generates non-overlapping batches ofnstars.logodds_callback: User-provided function that takes a list of matches log-odds as parameter and returns anastrometry.Actionobject.astrometry.Action.CONTINUEtells the solver to keep searching for matches whereasastrometry.Action.STOPtells the solver to return the current matches immediately. The log-odds list is sorted from highest to lowest value and should not be modified by the callback function.Accepted matches are always tuned up, even if they hittune_up_logodds_thresholdand were already tuned-up. Since log-odds are compared with the thresholds before the tune-up, the final log-odds are often significantly larger thanoutput_logodds_threshold. Settune_up_logodds_thresholdto a value larger than or equal tooutput_logodds_thresholdto disable the first tune-up, andNoneto disable tune-up altogether. Tune-up logic is equivalent to the following Python snippet:# This (pseudo-code) snippet assumes the following definitions:# match: candidate match object# log_odds: current match log-odds# add_to_solution: appends the match to the solution list# tune_up: tunes up a match object and returns the new match and the new log-oddsiftune_up_logodds_thresholdisNone:iflog_odds>=output_logodds_threshold:add_to_solution(match)else:iflog_odds>=output_logodds_threshold:tuned_up_match,tuned_up_loggods=tune_up(match)add_to_solution(tuned_up_match)eliflog_odds>=tune_up_logodds_threshold:tuned_up_match,tuned_up_loggods=tune_up(match)iftuned_up_loggods>=output_logodds_threshold:tuned_up_twice_match,tuned_up_twice_loggods=tune_up(tuned_up_match)add_to_solution(tuned_up_twice_match)Astrometry.net gives the following description of the tune-up algorithm. Seetweak2inastrometry.net/solver/tweak2.cfor the implementation.Given an initial WCS solution, compute SIP polynomial distortions using an annealing-like strategy. That is, it finds matches between image and reference catalog by searching within a radius, and that radius is small near a region of confidence, and grows as you move away. That makes it possible to pick up more distant matches, but they are downweighted in the fit. The annealing process reduces the slope of the growth of the matching radius with respect to the distance from the region of confidence.--astrometry.net/include/astrometry/tweak2.hSolution@dataclasses.dataclassclassSolution:solve_id:strmatches:list[Match]defhas_match(self)->bool:...defbest_match(self)->Match:...defto_json(self)->str:...@classmethoddeffrom_json(cls,solution_as_json:str)->Solution:...matchesare sorted in descending log-odds order.best_matchreturns the first match in the list.to_jsonandfrom_jsonmay be used to save and load solutions.Match@dataclasses.dataclassclassMatch:logodds:floatcenter_ra_deg:floatcenter_dec_deg:floatscale_arcsec_per_pixel:floatindex_path:pathlib.Pathstars:tuple[Star,...]quad_stars:tuple[Star,...]wcs_fields:dict[str,tuple[typing.Any,str]]defastropy_wcs(self)->astropy.wcs.WCS:...logodds: Log-odds (https://en.wikipedia.org/wiki/Logit) of the match.center_ra_deg: Right ascension of the stars bounding box's center, in degrees and in the frame of reference of the index (J200 FK5 for Astrometry.net series).center_dec_deg: Declination of the stars bounding box's center in degrees and in the frame of reference of the index (J200 FK5 for Astrometry.net series).scale_arcsec_per_pixel: Pixel scale in arcsec per pixel.index_path: File system path of the index file used for this match.stars: List of visible index stars. This list is almost certainly going to differ from the input stars list.quad_stars: The index stars subset (usually 4 but can be 3 or 5) used in the hash code search step (seehttps://arxiv.org/pdf/0910.2233.pdf, 2. Methods).wcs_fields: WCS fields describing the transformation between pixel coordinates and world coordinates. This dictionary can be passed directly toastropy.wcs.WCS.astropy_wcsgenerates an Astropy WCS object. Astropy (https://pypi.org/project/astropy/) must be installed to use this method. SeeCalculate field stars pixel positions with astropyfor details.Star@dataclasses.dataclassclassStar:ra_deg:floatdec_deg:floatmetadata:dict[str,typing.Any]ra_deganddec_degare in degrees and use the same frame of reference as the index files. Astrometry.net index files use J2000 FK5 (https://docs.astropy.org/en/stable/api/astropy.coordinates.FK5.html). ICRS and FK5 differ by less than 0.1 arcsec (https://www.iers.org/IERS/EN/Science/ICRS/ICRS.html).The contents ofmetadatadepend on the data available in index files. SeeSeriesfor details.Series@dataclasses.dataclassclassSeries:name:strdescription:strscale_to_sizes:dict[int,tuple[int,...]]url_pattern:strdefsize(self,scales:typing.Optional[set[int]]=None):...defsize_as_string(self,scales:typing.Optional[set[int]]=None):...defindex_files(self,cache_directory:typing.Union[bytes,str,os.PathLike],scales:typing.Optional[set[int]]=None,)->list[pathlib.Path]:...namedefines the cache subdirectory name.descriptionis a copy of the text description inhttp://data.astrometry.net.scale_to_sizesmaps each available HEALPix resolution to index files sizes in bytes. The smaller the scale, the larger the number of HEALPix subdivisions.url_patternis the base pattern used to generate file download links.sizereturns the cumulative file sizes for the given scales in bytes. IfscalesisNone, all the scales available for the series are used.size_as_stringreturns a human-readable string representation ofsize.index_filesreturns index files paths for the given scales (or all available scales ifscalesisNone). This function downloads files that are not already in the cache directory.cache_directoryis created if it does not exist. Download automatically resumes for partially downloaded files.Change the constantsastrometry.CHUNK_SIZE,astrometry.DOWNLOAD_SUFFIXandastrometry.TIMEOUTto configure the downloader parameters.batches_generatordefbatches_generator(batch_size:int,)->typing.Callable[[int],typing.Iterable[tuple[int,int]]]:...batch_sizesets the size of the generated batches.batches_generatorreturns a slices generator compatible withSolutionParameters.slices_generator. The slices are non-overlapping and non-full slices are ignored. For instance, a batch size of25over83stars would generate the slices(0, 25),(25, 50), and(50, 75).SupportsFloatMappingclassSupportsFloatMapping(typing.Protocol):def__getitem__(self,index:typing.SupportsIndex,/)->typing.SupportsFloat:...ContributeClone this repository and pull its submodule:git clone --recursive https://github.com/neuromorphicsystems/astrometry.git
cd astrometryorgit clone https://github.com/neuromorphicsystems/astrometry.git
cd astrometry
git submodule update --recursiveFormat the code:clang-format-iastrometry_extension/astrometry_extension.castrometry_extension/astrometry_extension_utilities.hBuild a local version:python3-mpipinstall-e.# use 'CC="ccache clang" python3 -m pip install -e .' to speed up incremental buildsPublishBump the version number insetup.py.Create a new release on GitHub.MSVC compatibility (work in progress)fitsbin.c,kdtree_internal.c,kdtree_internal_fits.c,solver.c: replace Variable Length Arrays (VAL) with _alloca (type name[size]->type* name = _alloca(size))fitsbin.c,fitsioutils.c,fitstable.c: castvoid*tochar*to enable pointer arithmeticanqfits.c,verify.c:#define debug(args...)->#define debug(...)qfits_time.c: remove#include <pwd.h>log.h,keywords.h: remove__attribute__directivesbl.c: remove redundant bl.inc and bl_nl.c includesreplace all POSIX calls (file IO, network, select...). This requires significant effort when targeting the entire Astrometry.net library. It might be less complicated with Astrometry, which uses only a subset of Astrometry.net.