From f11ec794e10a0b81537f70bbbaf14bb3deecb40c Mon Sep 17 00:00:00 2001 From: Emir Karamehmetoglu Date: Wed, 16 Nov 2022 13:35:25 +0100 Subject: [PATCH 1/7] Fix CI/CD,Tests ADD MyPy, Black, Flake8, Coverage. --- .github/workflows/python-package.yml | 84 +- cutouts.py | 67 +- fetch_eso_data.py | 67 +- fixlcogt.py | 28 +- flows_get_brightest/__init__.py | 4 +- flows_get_brightest/auth.py | 25 +- flows_get_brightest/catalogs.py | 90 +- flows_get_brightest/corner.py | 12 +- flows_get_brightest/instruments.py | 59 +- flows_get_brightest/observer.py | 51 +- flows_get_brightest/parser.py | 55 +- flows_get_brightest/plan.py | 11 +- flows_get_brightest/plots.py | 172 +- flows_get_brightest/run_get_brightest.py | 11 +- flows_get_brightest/target.py | 12 +- flows_get_brightest/tests.py | 30 +- flows_get_brightest/utils.py | 31 +- pyproject.toml | 37 +- typings/astropy/__init__.pyi | 87 + typings/astropy/_erfa/__init__.pyi | 11 + typings/astropy/_version.pyi | 6 + typings/astropy/config/__init__.pyi | 13 + typings/astropy/config/affiliated.pyi | 8 + typings/astropy/config/configuration.pyi | 428 +++ typings/astropy/config/paths.pyi | 142 + typings/astropy/conftest.pyi | 40 + typings/astropy/constants/__init__.pyi | 28 + typings/astropy/constants/cgs.pyi | 8 + typings/astropy/constants/config.pyi | 11 + typings/astropy/constants/constant.pyi | 116 + typings/astropy/constants/si.pyi | 8 + typings/astropy/constants/utils.pyi | 6 + typings/astropy/convolution/__init__.pyi | 10 + typings/astropy/convolution/convolve.pyi | 385 +++ typings/astropy/convolution/core.pyi | 254 ++ typings/astropy/convolution/kernels.pyi | 971 +++++++ typings/astropy/convolution/utils.pyi | 161 ++ typings/astropy/coordinates/__init__.pyi | 28 + typings/astropy/coordinates/angle_formats.pyi | 186 ++ .../astropy/coordinates/angle_utilities.pyi | 131 + typings/astropy/coordinates/angles.pyi | 424 +++ typings/astropy/coordinates/attributes.pyi | 354 +++ typings/astropy/coordinates/baseframe.pyi | 621 +++++ .../coordinates/builtin_frames/__init__.pyi | 68 + .../coordinates/builtin_frames/altaz.pyi | 55 + .../coordinates/builtin_frames/baseradec.pyi | 22 + .../coordinates/builtin_frames/cirs.pyi | 21 + .../cirs_observed_transforms.pyi | 23 + .../coordinates/builtin_frames/ecliptic.pyi | 164 ++ .../builtin_frames/ecliptic_transforms.pyi | 78 + .../coordinates/builtin_frames/equatorial.pyi | 80 + .../coordinates/builtin_frames/fk4.pyi | 64 + .../builtin_frames/fk4_fk5_transforms.pyi | 20 + .../coordinates/builtin_frames/fk5.pyi | 28 + .../coordinates/builtin_frames/galactic.pyi | 33 + .../builtin_frames/galactic_transforms.pyi | 22 + .../builtin_frames/galactocentric.pyi | 285 ++ .../coordinates/builtin_frames/gcrs.pyi | 51 + .../coordinates/builtin_frames/hadec.pyi | 46 + .../coordinates/builtin_frames/hcrs.pyi | 33 + .../coordinates/builtin_frames/icrs.pyi | 26 + .../builtin_frames/icrs_cirs_transforms.pyi | 44 + .../builtin_frames/icrs_fk5_transforms.pyi | 18 + .../icrs_observed_transforms.pyi | 23 + .../intermediate_rotation_transforms.pyi | 98 + .../coordinates/builtin_frames/itrs.pyi | 30 + .../coordinates/builtin_frames/lsr.pyi | 148 + .../coordinates/builtin_frames/skyoffset.pyi | 95 + .../builtin_frames/supergalactic.pyi | 23 + .../supergalactic_transforms.pyi | 17 + .../coordinates/builtin_frames/utils.pyi | 196 ++ typings/astropy/coordinates/calculation.pyi | 52 + typings/astropy/coordinates/distances.pyi | 144 + typings/astropy/coordinates/earth.pyi | 496 ++++ .../astropy/coordinates/earth_orientation.pyi | 144 + typings/astropy/coordinates/erfa_astrom.pyi | 148 + typings/astropy/coordinates/errors.pyi | 164 ++ typings/astropy/coordinates/funcs.pyi | 190 ++ typings/astropy/coordinates/jparser.pyi | 39 + typings/astropy/coordinates/matching.pyi | 217 ++ .../astropy/coordinates/matrix_utilities.pyi | 132 + typings/astropy/coordinates/name_resolve.pyi | 84 + .../astropy/coordinates/representation.pyi | 1697 ++++++++++++ typings/astropy/coordinates/sites.pyi | 99 + .../astropy/coordinates/sky_coordinate.pyi | 1231 +++++++++ .../coordinates/sky_coordinate_parsers.pyi | 7 + typings/astropy/coordinates/solar_system.pyi | 202 ++ .../coordinates/spectral_coordinate.pyi | 282 ++ .../astropy/coordinates/spectral_quantity.pyi | 152 ++ .../astropy/coordinates/transformations.pyi | 680 +++++ typings/astropy/cosmology/__init__.pyi | 36 + typings/astropy/cosmology/connect.pyi | 192 ++ typings/astropy/cosmology/core.pyi | 307 +++ typings/astropy/cosmology/flrw/__init__.pyi | 18 + typings/astropy/cosmology/flrw/base.pyi | 1048 +++++++ typings/astropy/cosmology/flrw/lambdacdm.pyi | 254 ++ .../astropy/cosmology/flrw/tests/__init__.pyi | 4 + typings/astropy/cosmology/flrw/w0cdm.pyi | 259 ++ typings/astropy/cosmology/flrw/w0wacdm.pyi | 221 ++ typings/astropy/cosmology/flrw/w0wzcdm.pyi | 132 + typings/astropy/cosmology/flrw/wpwazpcdm.pyi | 152 ++ typings/astropy/cosmology/funcs.pyi | 235 ++ typings/astropy/cosmology/io/__init__.pyi | 9 + typings/astropy/cosmology/io/cosmology.pyi | 63 + typings/astropy/cosmology/io/ecsv.pyi | 76 + typings/astropy/cosmology/io/mapping.pyi | 157 ++ typings/astropy/cosmology/io/model.pyi | 136 + typings/astropy/cosmology/io/row.pyi | 107 + typings/astropy/cosmology/io/table.pyi | 180 ++ typings/astropy/cosmology/io/utils.pyi | 39 + typings/astropy/cosmology/io/yaml.pyi | 91 + typings/astropy/cosmology/parameter.pyi | 196 ++ typings/astropy/cosmology/realizations.pyi | 78 + typings/astropy/cosmology/units.pyi | 208 ++ typings/astropy/cosmology/utils.pyi | 90 + typings/astropy/extern/__init__.pyi | 13 + typings/astropy/extern/_strptime.pyi | 88 + typings/astropy/extern/configobj/__init__.pyi | 4 + .../astropy/extern/configobj/configobj.pyi | 685 +++++ typings/astropy/extern/configobj/validate.pyi | 862 ++++++ typings/astropy/extern/ply/__init__.pyi | 6 + typings/astropy/extern/ply/lex.pyi | 140 + typings/astropy/extern/ply/yacc.pyi | 399 +++ typings/astropy/io/__init__.pyi | 8 + typings/astropy/io/ascii/__init__.pyi | 24 + typings/astropy/io/ascii/basic.pyi | 347 +++ typings/astropy/io/ascii/cds.pyi | 171 ++ typings/astropy/io/ascii/connect.pyi | 14 + typings/astropy/io/ascii/core.pyi | 716 +++++ typings/astropy/io/ascii/daophot.pyi | 177 ++ typings/astropy/io/ascii/docs.pyi | 8 + typings/astropy/io/ascii/ecsv.pyi | 166 ++ typings/astropy/io/ascii/fastbasic.pyi | 153 ++ typings/astropy/io/ascii/fixedwidth.pyi | 250 ++ typings/astropy/io/ascii/html.pyi | 206 ++ typings/astropy/io/ascii/ipac.pyi | 248 ++ typings/astropy/io/ascii/latex.pyi | 299 ++ typings/astropy/io/ascii/misc.pyi | 73 + typings/astropy/io/ascii/mrt.pyi | 142 + typings/astropy/io/ascii/qdp.pyi | 145 + typings/astropy/io/ascii/rst.pyi | 57 + typings/astropy/io/ascii/sextractor.pyi | 83 + typings/astropy/io/ascii/ui.pyi | 138 + typings/astropy/io/fits/__init__.pyi | 72 + typings/astropy/io/fits/card.pyi | 178 ++ typings/astropy/io/fits/column.pyi | 656 +++++ typings/astropy/io/fits/connect.pyi | 99 + typings/astropy/io/fits/convenience.pyi | 576 ++++ typings/astropy/io/fits/diff.pyi | 585 ++++ typings/astropy/io/fits/file.pyi | 83 + typings/astropy/io/fits/fitsrec.pyi | 186 ++ typings/astropy/io/fits/fitstime.pyi | 67 + typings/astropy/io/fits/hdu/__init__.pyi | 14 + typings/astropy/io/fits/hdu/base.pyi | 517 ++++ typings/astropy/io/fits/hdu/compressed.pyi | 348 +++ typings/astropy/io/fits/hdu/groups.pyi | 152 ++ typings/astropy/io/fits/hdu/hdulist.pyi | 498 ++++ typings/astropy/io/fits/hdu/image.pyi | 259 ++ typings/astropy/io/fits/hdu/nonstandard.pyi | 56 + typings/astropy/io/fits/hdu/streaming.pyi | 105 + typings/astropy/io/fits/hdu/table.pyi | 337 +++ typings/astropy/io/fits/header.pyi | 998 +++++++ typings/astropy/io/fits/util.pyi | 206 ++ typings/astropy/io/fits/verify.pyi | 69 + typings/astropy/io/misc/__init__.pyi | 10 + typings/astropy/io/misc/asdf/connect.pyi | 74 + typings/astropy/io/misc/asdf/deprecation.pyi | 7 + typings/astropy/io/misc/connect.pyi | 4 + typings/astropy/io/misc/hdf5.pyi | 86 + typings/astropy/io/misc/pandas/connect.pyi | 18 + typings/astropy/io/misc/parquet.pyi | 117 + typings/astropy/io/misc/pickle_helpers.pyi | 60 + typings/astropy/io/misc/yaml.pyi | 144 + typings/astropy/io/registry/__init__.pyi | 15 + typings/astropy/io/registry/base.pyi | 188 ++ typings/astropy/io/registry/compat.pyi | 15 + typings/astropy/io/registry/core.pyi | 248 ++ typings/astropy/io/registry/interface.pyi | 87 + typings/astropy/io/votable/__init__.pyi | 21 + typings/astropy/io/votable/connect.pyi | 85 + typings/astropy/io/votable/converters.pyi | 656 +++++ typings/astropy/io/votable/exceptions.pyi | 1274 +++++++++ typings/astropy/io/votable/table.pyi | 213 ++ typings/astropy/io/votable/tree.pyi | 1642 +++++++++++ typings/astropy/io/votable/ucd.pyi | 105 + typings/astropy/io/votable/util.pyi | 86 + typings/astropy/io/votable/xmlutil.pyi | 79 + typings/astropy/logger.pyi | 250 ++ typings/astropy/modeling/__init__.pyi | 15 + typings/astropy/modeling/bounding_box.pyi | 781 ++++++ typings/astropy/modeling/convolution.pyi | 60 + typings/astropy/modeling/core.pyi | 1391 ++++++++++ typings/astropy/modeling/fitting.pyi | 724 +++++ .../astropy/modeling/functional_models.pyi | 2406 +++++++++++++++++ typings/astropy/modeling/mappings.pyi | 238 ++ typings/astropy/modeling/math_functions.pyi | 25 + typings/astropy/modeling/models.pyi | 19 + typings/astropy/modeling/optimizers.pyi | 150 + typings/astropy/modeling/parameters.pyi | 348 +++ typings/astropy/modeling/physical_models.pyi | 430 +++ typings/astropy/modeling/polynomial.pyi | 956 +++++++ typings/astropy/modeling/powerlaws.pyi | 414 +++ typings/astropy/modeling/projections.pyi | 1381 ++++++++++ typings/astropy/modeling/rotations.pyi | 329 +++ typings/astropy/modeling/separable.pyi | 85 + typings/astropy/modeling/spline.pyi | 280 ++ typings/astropy/modeling/statistic.pyi | 141 + typings/astropy/modeling/tabular.pyi | 183 ++ typings/astropy/modeling/utils.pyi | 308 +++ typings/astropy/nddata/__init__.pyi | 36 + typings/astropy/nddata/bitmask.pyi | 406 +++ typings/astropy/nddata/blocks.pyi | 150 + typings/astropy/nddata/ccddata.pyi | 328 +++ typings/astropy/nddata/compat.pyi | 176 ++ typings/astropy/nddata/decorators.pyi | 110 + typings/astropy/nddata/flag_collection.pyi | 27 + .../astropy/nddata/mixins/ndarithmetic.pyi | 92 + typings/astropy/nddata/mixins/ndio.pyi | 111 + typings/astropy/nddata/mixins/ndslicing.pyi | 54 + typings/astropy/nddata/nddata.pyi | 168 ++ typings/astropy/nddata/nddata_base.pyi | 75 + typings/astropy/nddata/nddata_withmixins.pyi | 71 + typings/astropy/nddata/nduncertainty.pyi | 431 +++ typings/astropy/nddata/utils.pyi | 538 ++++ typings/astropy/samp/__init__.pyi | 31 + typings/astropy/samp/client.pyi | 427 +++ typings/astropy/samp/constants.pyi | 13 + typings/astropy/samp/errors.pyi | 39 + typings/astropy/samp/hub.pyi | 183 ++ typings/astropy/samp/hub_proxy.pyi | 144 + typings/astropy/samp/integrated_client.pyi | 401 +++ typings/astropy/samp/lockfile_helpers.pyi | 63 + typings/astropy/samp/standard_profile.pyi | 39 + typings/astropy/samp/utils.pyi | 92 + typings/astropy/samp/web_profile.pyi | 51 + typings/astropy/stats/__init__.pyi | 29 + typings/astropy/stats/bayesian_blocks.pyi | 340 +++ typings/astropy/stats/biweight.pyi | 538 ++++ typings/astropy/stats/bls/__init__.pyi | 33 + typings/astropy/stats/circstats.pyi | 414 +++ typings/astropy/stats/funcs.pyi | 990 +++++++ typings/astropy/stats/histogram.pyi | 283 ++ typings/astropy/stats/info_theory.pyi | 380 +++ typings/astropy/stats/jackknife.pyi | 133 + .../astropy/stats/lombscargle/__init__.pyi | 21 + typings/astropy/stats/sigma_clipping.pyi | 495 ++++ typings/astropy/stats/spatial.pyi | 184 ++ typings/astropy/table/__init__.pyi | 29 + typings/astropy/table/bst.pyi | 303 +++ typings/astropy/table/column.pyi | 782 ++++++ typings/astropy/table/connect.pyi | 104 + typings/astropy/table/groups.pyi | 171 ++ typings/astropy/table/index.pyi | 621 +++++ typings/astropy/table/info.pyi | 101 + typings/astropy/table/jsviewer.pyi | 62 + typings/astropy/table/meta.pyi | 111 + typings/astropy/table/mixins/dask.pyi | 31 + typings/astropy/table/mixins/registry.pyi | 54 + typings/astropy/table/ndarray_mixin.pyi | 32 + typings/astropy/table/np_utils.pyi | 48 + typings/astropy/table/operations.pyi | 529 ++++ typings/astropy/table/pprint.pyi | 33 + typings/astropy/table/row.pyi | 112 + typings/astropy/table/serialize.pyi | 117 + typings/astropy/table/soco.pyi | 124 + typings/astropy/table/sorted_array.pyi | 178 ++ typings/astropy/table/table.pyi | 1876 +++++++++++++ typings/astropy/tests/__init__.pyi | 9 + typings/astropy/tests/runner.pyi | 252 ++ typings/astropy/time/__init__.pyi | 16 + typings/astropy/time/core.pyi | 1184 ++++++++ typings/astropy/time/formats.pyi | 820 ++++++ .../time/time_helper/function_helpers.pyi | 17 + typings/astropy/time/utils.pyi | 134 + typings/astropy/timeseries/__init__.pyi | 14 + typings/astropy/timeseries/binned.pyi | 153 ++ typings/astropy/timeseries/core.pyi | 23 + typings/astropy/timeseries/downsample.pyi | 61 + typings/astropy/timeseries/io/__init__.pyi | 6 + typings/astropy/timeseries/io/kepler.pyi | 29 + .../timeseries/periodograms/__init__.pyi | 8 + .../astropy/timeseries/periodograms/base.pyi | 36 + .../timeseries/periodograms/bls/__init__.pyi | 15 + .../timeseries/periodograms/bls/core.pyi | 332 +++ .../timeseries/periodograms/bls/methods.pyi | 85 + .../periodograms/bls/setup_package.pyi | 8 + .../periodograms/bls/tests/__init__.pyi | 4 + .../periodograms/lombscargle/__init__.pyi | 11 + .../periodograms/lombscargle/_statistics.pyi | 286 ++ .../periodograms/lombscargle/core.pyi | 461 ++++ .../lombscargle/implementations/__init__.pyi | 12 + .../lombscargle/implementations/chi2_impl.pyi | 44 + .../lombscargle/implementations/fast_impl.pyi | 55 + .../implementations/fastchi2_impl.pyi | 47 + .../lombscargle/implementations/main.pyi | 83 + .../lombscargle/implementations/mle.pyi | 55 + .../implementations/scipy_impl.pyi | 39 + .../lombscargle/implementations/slow_impl.pyi | 42 + .../lombscargle/implementations/utils.pyi | 96 + .../lombscargle/tests/__init__.pyi | 4 + .../periodograms/lombscargle/utils.pyi | 53 + typings/astropy/timeseries/sampled.pyi | 191 ++ typings/astropy/uncertainty/__init__.pyi | 12 + typings/astropy/uncertainty/core.pyi | 195 ++ typings/astropy/uncertainty/distributions.pyi | 106 + typings/astropy/units/__init__.pyi | 33 + typings/astropy/units/_typing.pyi | 10 + typings/astropy/units/astrophys.pyi | 14 + typings/astropy/units/cds.pyi | 41 + typings/astropy/units/cgs.pyi | 22 + typings/astropy/units/core.pyi | 1228 +++++++++ typings/astropy/units/decorators.pyi | 91 + typings/astropy/units/equivalencies.pyi | 365 +++ typings/astropy/units/format/__init__.pyi | 37 + typings/astropy/units/format/base.pyi | 31 + typings/astropy/units/format/cds.pyi | 27 + typings/astropy/units/format/console.pyi | 34 + typings/astropy/units/format/fits.pyi | 27 + typings/astropy/units/format/generic.pyi | 47 + typings/astropy/units/format/latex.pyi | 55 + typings/astropy/units/format/ogip.pyi | 28 + .../astropy/units/format/unicode_format.pyi | 30 + typings/astropy/units/format/utils.pyi | 126 + typings/astropy/units/format/vounit.pyi | 29 + typings/astropy/units/function/__init__.pyi | 12 + typings/astropy/units/function/core.pyi | 352 +++ .../astropy/units/function/logarithmic.pyi | 219 ++ typings/astropy/units/function/mixin.pyi | 28 + typings/astropy/units/function/units.pyi | 16 + typings/astropy/units/imperial.pyi | 34 + typings/astropy/units/misc.pyi | 11 + typings/astropy/units/photometric.pyi | 25 + typings/astropy/units/physical.pyi | 266 ++ typings/astropy/units/quantity.pyi | 948 +++++++ .../units/quantity_helper/__init__.pyi | 12 + .../units/quantity_helper/converters.pyi | 133 + .../astropy/units/quantity_helper/erfa.pyi | 102 + .../quantity_helper/function_helpers.pyi | 226 ++ .../astropy/units/quantity_helper/helpers.pyi | 119 + .../units/quantity_helper/scipy_special.pyi | 22 + typings/astropy/units/required_by_vounit.pyi | 17 + typings/astropy/units/si.pyi | 13 + typings/astropy/units/structured.pyi | 250 ++ typings/astropy/units/utils.pyi | 95 + typings/astropy/utils/__init__.pyi | 24 + typings/astropy/utils/codegen.pyi | 32 + typings/astropy/utils/collections.pyi | 42 + typings/astropy/utils/compat/__init__.pyi | 20 + typings/astropy/utils/compat/misc.pyi | 55 + typings/astropy/utils/compat/numpycompat.pyi | 17 + .../astropy/utils/compat/optional_deps.pyi | 14 + typings/astropy/utils/console.pyi | 532 ++++ typings/astropy/utils/data.pyi | 1063 ++++++++ typings/astropy/utils/data_info.pyi | 373 +++ typings/astropy/utils/decorators.pyi | 665 +++++ typings/astropy/utils/diff.pyi | 75 + typings/astropy/utils/exceptions.pyi | 73 + typings/astropy/utils/iers/__init__.pyi | 6 + typings/astropy/utils/iers/iers.pyi | 623 +++++ typings/astropy/utils/introspection.pyi | 246 ++ typings/astropy/utils/masked/__init__.pyi | 14 + typings/astropy/utils/masked/core.pyi | 362 +++ .../astropy/utils/masked/function_helpers.pyi | 348 +++ typings/astropy/utils/metadata.pyi | 289 ++ typings/astropy/utils/misc.pyi | 474 ++++ typings/astropy/utils/parsing.pyi | 77 + typings/astropy/utils/shapes.pyi | 215 ++ typings/astropy/utils/state.pyi | 69 + typings/astropy/utils/xml/__init__.pyi | 4 + typings/astropy/utils/xml/check.pyi | 43 + typings/astropy/utils/xml/iterparser.pyi | 85 + typings/astropy/utils/xml/validate.pyi | 30 + typings/astropy/utils/xml/writer.pyi | 215 ++ typings/astropy/version.pyi | 8 + typings/astropy/visualization/__init__.pyi | 14 + typings/astropy/visualization/hist.pyi | 54 + typings/astropy/visualization/interval.pyi | 176 ++ typings/astropy/visualization/lupton_rgb.pyi | 228 ++ .../astropy/visualization/mpl_normalize.pyi | 208 ++ typings/astropy/visualization/mpl_style.pyi | 8 + typings/astropy/visualization/stretch.pyi | 530 ++++ typings/astropy/visualization/time.pyi | 49 + typings/astropy/visualization/transform.pyi | 40 + typings/astropy/visualization/units.pyi | 35 + .../visualization/wcsaxes/__init__.pyi | 21 + .../visualization/wcsaxes/axislabels.pyi | 33 + .../wcsaxes/coordinate_helpers.pyi | 414 +++ .../wcsaxes/coordinate_range.pyi | 31 + .../visualization/wcsaxes/coordinates_map.pyi | 84 + .../astropy/visualization/wcsaxes/core.pyi | 308 +++ .../wcsaxes/formatter_locator.pyi | 141 + .../astropy/visualization/wcsaxes/frame.pyi | 176 ++ .../visualization/wcsaxes/grid_paths.pyi | 37 + .../astropy/visualization/wcsaxes/patches.pyi | 81 + .../visualization/wcsaxes/ticklabels.pyi | 72 + .../astropy/visualization/wcsaxes/ticks.pyi | 114 + .../visualization/wcsaxes/transforms.pyi | 133 + .../astropy/visualization/wcsaxes/utils.pyi | 30 + .../astropy/visualization/wcsaxes/wcsapi.pyi | 76 + typings/astropy/wcs/__init__.pyi | 37 + typings/astropy/wcs/docstrings.pyi | 227 ++ typings/astropy/wcs/utils.pyi | 511 ++++ typings/astropy/wcs/wcs.pyi | 944 +++++++ typings/astropy/wcs/wcsapi/__init__.pyi | 10 + typings/astropy/wcs/wcsapi/fitswcs.pyi | 129 + typings/astropy/wcs/wcsapi/high_level_api.pyi | 147 + .../wcs/wcsapi/high_level_wcs_wrapper.pyi | 76 + typings/astropy/wcs/wcsapi/low_level_api.pyi | 327 +++ typings/astropy/wcs/wcsapi/utils.pyi | 14 + .../astropy/wcs/wcsapi/wrappers/__init__.pyi | 7 + typings/astropy/wcs/wcsapi/wrappers/base.pyi | 87 + .../wcs/wcsapi/wrappers/sliced_wcs.pyi | 107 + .../wcs/wcsapi/wrappers/tests/__init__.pyi | 4 + typings/astroquery/__init__.pyi | 19 + typings/astroquery/_astropy_init.pyi | 7 + typings/astroquery/exceptions.pyi | 112 + typings/astroquery/logger.pyi | 20 + typings/astroquery/query.pyi | 107 + typings/astroquery/simbad/__init__.pyi | 27 + typings/astroquery/simbad/core.pyi | 573 ++++ .../astroquery/simbad/get_votable_fields.pyi | 7 + typings/astroquery/simbad/setup_package.pyi | 7 + typings/astroquery/simbad/tests/__init__.pyi | 4 + typings/astroquery/skyview/__init__.pyi | 16 + typings/astroquery/skyview/core.pyi | 166 ++ typings/astroquery/utils/__init__.pyi | 16 + .../astroquery/utils/class_or_instance.pyi | 28 + typings/astroquery/utils/commons.pyi | 236 ++ typings/astroquery/utils/docstr_chompers.pyi | 26 + .../astroquery/utils/download_file_list.pyi | 37 + typings/astroquery/utils/process_asyncs.pyi | 24 + typings/astroquery/utils/progressbar.pyi | 17 + typings/astroquery/utils/system_tools.pyi | 23 + typings/astroquery/version.pyi | 14 + typings/erfa/__init__.pyi | 3 + typings/erfa/_version.pyi | 5 + typings/erfa/core.pyi | 283 ++ typings/erfa/helpers.pyi | 25 + typings/erfa/ufunc.pyi | 265 ++ typings/erfa/version.pyi | 7 + typings/matplotlib/__init__.pyi | 67 + typings/matplotlib/_afm.pyi | 40 + typings/matplotlib/_animation_data.pyi | 4 + typings/matplotlib/_api/__init__.pyi | 21 + typings/matplotlib/_api/deprecation.pyi | 23 + typings/matplotlib/_blocking_input.pyi | 1 + typings/matplotlib/_c_internal_utils.pyi | 8 + typings/matplotlib/_cm.pyi | 6 + typings/matplotlib/_cm_listed.pyi | 4 + typings/matplotlib/_color_data.pyi | 6 + typings/matplotlib/_constrained_layout.pyi | 17 + typings/matplotlib/_docstring.pyi | 21 + typings/matplotlib/_enums.pyi | 19 + typings/matplotlib/_fontconfig_pattern.pyi | 17 + typings/matplotlib/_image.pyi | 22 + typings/matplotlib/_internal_utils.pyi | 4 + typings/matplotlib/_layoutgrid.pyi | 51 + typings/matplotlib/_mathtext.pyi | 292 ++ typings/matplotlib/_mathtext_data.pyi | 8 + typings/matplotlib/_path.pyi | 20 + typings/matplotlib/_pylab_helpers.pyi | 24 + typings/matplotlib/_qhull.pyi | 4 + typings/matplotlib/_text_helpers.pyi | 8 + typings/matplotlib/_tight_bbox.pyi | 5 + typings/matplotlib/_tight_layout.pyi | 7 + typings/matplotlib/_tri.pyi | 20 + typings/matplotlib/_ttconv.pyi | 3 + typings/matplotlib/_type1font.pyi | 55 + typings/matplotlib/_version.pyi | 5 + typings/matplotlib/afm.pyi | 1 + typings/matplotlib/animation.pyi | 138 + typings/matplotlib/artist.pyi | 122 + typings/matplotlib/axes/__init__.pyi | 2 + typings/matplotlib/axes/_axes.pyi | 80 + typings/matplotlib/axes/_base.pyi | 207 ++ typings/matplotlib/axes/_secondary_axes.pyi | 15 + typings/matplotlib/axes/_subplots.pyi | 14 + typings/matplotlib/axis.pyi | 205 ++ typings/matplotlib/backend_bases.pyi | 299 ++ typings/matplotlib/backend_managers.pyi | 44 + typings/matplotlib/backend_tools.pyi | 183 ++ typings/matplotlib/backends/__init__.pyi | 0 typings/matplotlib/backends/_backend_agg.pyi | 15 + typings/matplotlib/backends/_backend_gtk.pyi | 41 + .../matplotlib/backends/_backend_pdf_ps.pyi | 22 + typings/matplotlib/backends/_backend_tk.pyi | 106 + typings/matplotlib/backends/_tkagg.pyi | 4 + typings/matplotlib/backends/backend_agg.pyi | 59 + typings/matplotlib/backends/backend_cairo.pyi | 63 + typings/matplotlib/backends/backend_gtk3.pyi | 68 + .../matplotlib/backends/backend_gtk3agg.pyi | 14 + .../matplotlib/backends/backend_gtk3cairo.pyi | 9 + typings/matplotlib/backends/backend_gtk4.pyi | 55 + .../matplotlib/backends/backend_gtk4agg.pyi | 12 + .../matplotlib/backends/backend_gtk4cairo.pyi | 9 + .../matplotlib/backends/backend_macosx.pyi | 37 + typings/matplotlib/backends/backend_mixed.pyi | 12 + typings/matplotlib/backends/backend_nbagg.pyi | 46 + typings/matplotlib/backends/backend_pdf.pyi | 229 ++ typings/matplotlib/backends/backend_pgf.pyi | 76 + typings/matplotlib/backends/backend_ps.pyi | 81 + typings/matplotlib/backends/backend_qt.pyi | 112 + typings/matplotlib/backends/backend_qt5.pyi | 6 + .../matplotlib/backends/backend_qt5agg.pyi | 4 + .../matplotlib/backends/backend_qt5cairo.pyi | 4 + typings/matplotlib/backends/backend_qtagg.pyi | 13 + .../matplotlib/backends/backend_qtcairo.pyi | 11 + typings/matplotlib/backends/backend_svg.pyi | 65 + .../matplotlib/backends/backend_template.pyi | 31 + typings/matplotlib/backends/backend_tkagg.pyi | 10 + .../matplotlib/backends/backend_tkcairo.pyi | 9 + .../matplotlib/backends/backend_webagg.pyi | 57 + .../backends/backend_webagg_core.pyi | 75 + typings/matplotlib/backends/backend_wx.pyi | 158 ++ typings/matplotlib/backends/backend_wxagg.pyi | 14 + .../matplotlib/backends/backend_wxcairo.pyi | 13 + typings/matplotlib/backends/qt_compat.pyi | 15 + .../backends/qt_editor/__init__.pyi | 0 .../backends/qt_editor/_formlayout.pyi | 79 + .../backends/qt_editor/figureoptions.pyi | 10 + typings/matplotlib/bezier.pyi | 29 + typings/matplotlib/blocking_input.pyi | 54 + typings/matplotlib/category.pyi | 24 + typings/matplotlib/cbook/__init__.pyi | 110 + typings/matplotlib/cm.pyi | 47 + typings/matplotlib/collections.pyi | 143 + typings/matplotlib/colorbar.pyi | 74 + typings/matplotlib/colors.pyi | 188 ++ typings/matplotlib/container.pyi | 33 + typings/matplotlib/contour.pyi | 66 + typings/matplotlib/dates.pyi | 123 + typings/matplotlib/docstring.pyi | 1 + typings/matplotlib/dviread.pyi | 70 + typings/matplotlib/figure.pyi | 162 ++ typings/matplotlib/font_manager.pyi | 90 + typings/matplotlib/fontconfig_pattern.pyi | 1 + typings/matplotlib/ft2font.pyi | 91 + typings/matplotlib/gridspec.pyi | 60 + typings/matplotlib/hatch.pyi | 66 + typings/matplotlib/image.pyi | 91 + typings/matplotlib/layout_engine.pyi | 27 + typings/matplotlib/legend.pyi | 72 + typings/matplotlib/legend_handler.pyi | 76 + typings/matplotlib/lines.pyi | 100 + typings/matplotlib/markers.pyi | 39 + typings/matplotlib/mathtext.pyi | 52 + typings/matplotlib/mlab.pyi | 35 + typings/matplotlib/offsetbox.pyi | 204 ++ typings/matplotlib/patches.pyi | 390 +++ typings/matplotlib/path.pyi | 76 + typings/matplotlib/patheffects.pyi | 44 + typings/matplotlib/projections/__init__.pyi | 16 + typings/matplotlib/projections/geo.pyi | 82 + typings/matplotlib/projections/polar.pyi | 131 + typings/matplotlib/pylab.pyi | 12 + typings/matplotlib/pyplot.pyi | 185 ++ typings/matplotlib/quiver.pyi | 75 + typings/matplotlib/rcsetup.pyi | 80 + typings/matplotlib/sankey.pyi | 27 + typings/matplotlib/scale.pyi | 141 + typings/matplotlib/sphinxext/__init__.pyi | 0 typings/matplotlib/sphinxext/mathmpl.pyi | 22 + .../matplotlib/sphinxext/plot_directive.pyi | 41 + typings/matplotlib/spines.pyi | 48 + typings/matplotlib/stackplot.pyi | 3 + typings/matplotlib/streamplot.pyi | 50 + typings/matplotlib/style/__init__.pyi | 1 + typings/matplotlib/style/core.pyi | 16 + typings/matplotlib/table.pyi | 52 + typings/matplotlib/texmanager.pyi | 29 + typings/matplotlib/text.pyi | 108 + typings/matplotlib/textpath.pyi | 31 + typings/matplotlib/ticker.pyi | 254 ++ typings/matplotlib/tight_bbox.pyi | 1 + typings/matplotlib/tight_layout.pyi | 3 + typings/matplotlib/transforms.pyi | 343 +++ typings/matplotlib/tri/__init__.pyi | 8 + typings/matplotlib/tri/triangulation.pyi | 20 + typings/matplotlib/tri/tricontour.pyi | 8 + typings/matplotlib/tri/trifinder.pyi | 8 + typings/matplotlib/tri/triinterpolate.pyi | 69 + typings/matplotlib/tri/tripcolor.pyi | 6 + typings/matplotlib/tri/triplot.pyi | 3 + typings/matplotlib/tri/trirefine.pyi | 10 + typings/matplotlib/tri/tritools.pyi | 8 + typings/matplotlib/type1font.pyi | 1 + typings/matplotlib/units.pyi | 32 + typings/matplotlib/widgets.pyi | 305 +++ typings/regions/__init__.pyi | 9 + typings/regions/_astropy_init.pyi | 3 + typings/regions/_geometry/__init__.pyi | 4 + .../regions/_geometry/circular_overlap.pyi | 53 + typings/regions/_geometry/core.pyi | 51 + .../regions/_geometry/elliptical_overlap.pyi | 53 + typings/regions/_geometry/pnpoly.pyi | 13 + .../regions/_geometry/polygonal_overlap.pyi | 53 + .../regions/_geometry/rectangular_overlap.pyi | 53 + typings/regions/_utils/__init__.pyi | 1 + typings/regions/_utils/examples.pyi | 18 + typings/regions/_utils/optional_deps.pyi | 4 + typings/regions/_utils/wcs_helpers.pyi | 3 + typings/regions/compiler_version.pyi | 1 + typings/regions/core/__init__.pyi | 8 + typings/regions/core/attributes.pyi | 31 + typings/regions/core/bounding_box.pyi | 25 + typings/regions/core/compound.pyi | 32 + typings/regions/core/core.pyi | 56 + typings/regions/core/mask.pyi | 14 + typings/regions/core/metadata.pyi | 20 + typings/regions/core/pixcoord.pyi | 18 + typings/regions/core/regions.pyi | 22 + typings/regions/core/registry.pyi | 22 + typings/regions/io/__init__.pyi | 12 + typings/regions/io/crtf/__init__.pyi | 0 typings/regions/io/crtf/connect.pyi | 4 + typings/regions/io/crtf/core.pyi | 7 + typings/regions/io/crtf/io_core.pyi | 37 + typings/regions/io/crtf/read.pyi | 55 + typings/regions/io/crtf/write.pyi | 2 + typings/regions/io/ds9/__init__.pyi | 0 typings/regions/io/ds9/connect.pyi | 4 + typings/regions/io/ds9/core.pyi | 18 + typings/regions/io/ds9/meta.pyi | 1 + typings/regions/io/ds9/read.pyi | 12 + typings/regions/io/ds9/write.pyi | 4 + typings/regions/io/fits/__init__.pyi | 0 typings/regions/io/fits/connect.pyi | 4 + typings/regions/io/fits/core.pyi | 6 + typings/regions/io/fits/read.pyi | 9 + typings/regions/io/fits/write.pyi | 13 + typings/regions/shapes/__init__.pyi | 8 + typings/regions/shapes/annulus.pyi | 91 + typings/regions/shapes/circle.pyi | 26 + typings/regions/shapes/ellipse.pyi | 31 + typings/regions/shapes/line.pyi | 27 + typings/regions/shapes/point.pyi | 25 + typings/regions/shapes/polygon.pyi | 41 + typings/regions/shapes/rectangle.pyi | 35 + typings/regions/shapes/text.pyi | 19 + typings/regions/version.pyi | 3 + typings/tendrils/__init__.pyi | 14 + typings/tendrils/api/__init__.pyi | 34 + typings/tendrils/api/catalogs.pyi | 42 + typings/tendrils/api/datafiles.pyi | 38 + typings/tendrils/api/filters.pyi | 18 + typings/tendrils/api/lightcurves.pyi | 25 + typings/tendrils/api/photometry_api.pyi | 67 + .../tendrils/api/set_photometry_status.pyi | 29 + typings/tendrils/api/sites.pyi | 31 + typings/tendrils/api/targets.pyi | 88 + typings/tendrils/utils/__init__.pyi | 15 + typings/tendrils/utils/config.pyi | 72 + typings/tendrils/utils/files.pyi | 16 + typings/tendrils/utils/time.pyi | 19 + typings/tendrils/utils/tns.pyi | 80 + typings/tendrils/utils/urls.pyi | 97 + typings/tendrils/utils/ztf.pyi | 47 + typings/tendrils/version.pyi | 12 + 658 files changed, 93026 insertions(+), 329 deletions(-) create mode 100644 typings/astropy/__init__.pyi create mode 100644 typings/astropy/_erfa/__init__.pyi create mode 100644 typings/astropy/_version.pyi create mode 100644 typings/astropy/config/__init__.pyi create mode 100644 typings/astropy/config/affiliated.pyi create mode 100644 typings/astropy/config/configuration.pyi create mode 100644 typings/astropy/config/paths.pyi create mode 100644 typings/astropy/conftest.pyi create mode 100644 typings/astropy/constants/__init__.pyi create mode 100644 typings/astropy/constants/cgs.pyi create mode 100644 typings/astropy/constants/config.pyi create mode 100644 typings/astropy/constants/constant.pyi create mode 100644 typings/astropy/constants/si.pyi create mode 100644 typings/astropy/constants/utils.pyi create mode 100644 typings/astropy/convolution/__init__.pyi create mode 100644 typings/astropy/convolution/convolve.pyi create mode 100644 typings/astropy/convolution/core.pyi create mode 100644 typings/astropy/convolution/kernels.pyi create mode 100644 typings/astropy/convolution/utils.pyi create mode 100644 typings/astropy/coordinates/__init__.pyi create mode 100644 typings/astropy/coordinates/angle_formats.pyi create mode 100644 typings/astropy/coordinates/angle_utilities.pyi create mode 100644 typings/astropy/coordinates/angles.pyi create mode 100644 typings/astropy/coordinates/attributes.pyi create mode 100644 typings/astropy/coordinates/baseframe.pyi create mode 100644 typings/astropy/coordinates/builtin_frames/__init__.pyi create mode 100644 typings/astropy/coordinates/builtin_frames/altaz.pyi create mode 100644 typings/astropy/coordinates/builtin_frames/baseradec.pyi create mode 100644 typings/astropy/coordinates/builtin_frames/cirs.pyi create mode 100644 typings/astropy/coordinates/builtin_frames/cirs_observed_transforms.pyi create mode 100644 typings/astropy/coordinates/builtin_frames/ecliptic.pyi create mode 100644 typings/astropy/coordinates/builtin_frames/ecliptic_transforms.pyi create mode 100644 typings/astropy/coordinates/builtin_frames/equatorial.pyi create mode 100644 typings/astropy/coordinates/builtin_frames/fk4.pyi create mode 100644 typings/astropy/coordinates/builtin_frames/fk4_fk5_transforms.pyi create mode 100644 typings/astropy/coordinates/builtin_frames/fk5.pyi create mode 100644 typings/astropy/coordinates/builtin_frames/galactic.pyi create mode 100644 typings/astropy/coordinates/builtin_frames/galactic_transforms.pyi create mode 100644 typings/astropy/coordinates/builtin_frames/galactocentric.pyi create mode 100644 typings/astropy/coordinates/builtin_frames/gcrs.pyi create mode 100644 typings/astropy/coordinates/builtin_frames/hadec.pyi create mode 100644 typings/astropy/coordinates/builtin_frames/hcrs.pyi create mode 100644 typings/astropy/coordinates/builtin_frames/icrs.pyi create mode 100644 typings/astropy/coordinates/builtin_frames/icrs_cirs_transforms.pyi create mode 100644 typings/astropy/coordinates/builtin_frames/icrs_fk5_transforms.pyi create mode 100644 typings/astropy/coordinates/builtin_frames/icrs_observed_transforms.pyi create mode 100644 typings/astropy/coordinates/builtin_frames/intermediate_rotation_transforms.pyi create mode 100644 typings/astropy/coordinates/builtin_frames/itrs.pyi create mode 100644 typings/astropy/coordinates/builtin_frames/lsr.pyi create mode 100644 typings/astropy/coordinates/builtin_frames/skyoffset.pyi create mode 100644 typings/astropy/coordinates/builtin_frames/supergalactic.pyi create mode 100644 typings/astropy/coordinates/builtin_frames/supergalactic_transforms.pyi create mode 100644 typings/astropy/coordinates/builtin_frames/utils.pyi create mode 100644 typings/astropy/coordinates/calculation.pyi create mode 100644 typings/astropy/coordinates/distances.pyi create mode 100644 typings/astropy/coordinates/earth.pyi create mode 100644 typings/astropy/coordinates/earth_orientation.pyi create mode 100644 typings/astropy/coordinates/erfa_astrom.pyi create mode 100644 typings/astropy/coordinates/errors.pyi create mode 100644 typings/astropy/coordinates/funcs.pyi create mode 100644 typings/astropy/coordinates/jparser.pyi create mode 100644 typings/astropy/coordinates/matching.pyi create mode 100644 typings/astropy/coordinates/matrix_utilities.pyi create mode 100644 typings/astropy/coordinates/name_resolve.pyi create mode 100644 typings/astropy/coordinates/representation.pyi create mode 100644 typings/astropy/coordinates/sites.pyi create mode 100644 typings/astropy/coordinates/sky_coordinate.pyi create mode 100644 typings/astropy/coordinates/sky_coordinate_parsers.pyi create mode 100644 typings/astropy/coordinates/solar_system.pyi create mode 100644 typings/astropy/coordinates/spectral_coordinate.pyi create mode 100644 typings/astropy/coordinates/spectral_quantity.pyi create mode 100644 typings/astropy/coordinates/transformations.pyi create mode 100644 typings/astropy/cosmology/__init__.pyi create mode 100644 typings/astropy/cosmology/connect.pyi create mode 100644 typings/astropy/cosmology/core.pyi create mode 100644 typings/astropy/cosmology/flrw/__init__.pyi create mode 100644 typings/astropy/cosmology/flrw/base.pyi create mode 100644 typings/astropy/cosmology/flrw/lambdacdm.pyi create mode 100644 typings/astropy/cosmology/flrw/tests/__init__.pyi create mode 100644 typings/astropy/cosmology/flrw/w0cdm.pyi create mode 100644 typings/astropy/cosmology/flrw/w0wacdm.pyi create mode 100644 typings/astropy/cosmology/flrw/w0wzcdm.pyi create mode 100644 typings/astropy/cosmology/flrw/wpwazpcdm.pyi create mode 100644 typings/astropy/cosmology/funcs.pyi create mode 100644 typings/astropy/cosmology/io/__init__.pyi create mode 100644 typings/astropy/cosmology/io/cosmology.pyi create mode 100644 typings/astropy/cosmology/io/ecsv.pyi create mode 100644 typings/astropy/cosmology/io/mapping.pyi create mode 100644 typings/astropy/cosmology/io/model.pyi create mode 100644 typings/astropy/cosmology/io/row.pyi create mode 100644 typings/astropy/cosmology/io/table.pyi create mode 100644 typings/astropy/cosmology/io/utils.pyi create mode 100644 typings/astropy/cosmology/io/yaml.pyi create mode 100644 typings/astropy/cosmology/parameter.pyi create mode 100644 typings/astropy/cosmology/realizations.pyi create mode 100644 typings/astropy/cosmology/units.pyi create mode 100644 typings/astropy/cosmology/utils.pyi create mode 100644 typings/astropy/extern/__init__.pyi create mode 100644 typings/astropy/extern/_strptime.pyi create mode 100644 typings/astropy/extern/configobj/__init__.pyi create mode 100644 typings/astropy/extern/configobj/configobj.pyi create mode 100644 typings/astropy/extern/configobj/validate.pyi create mode 100644 typings/astropy/extern/ply/__init__.pyi create mode 100644 typings/astropy/extern/ply/lex.pyi create mode 100644 typings/astropy/extern/ply/yacc.pyi create mode 100644 typings/astropy/io/__init__.pyi create mode 100644 typings/astropy/io/ascii/__init__.pyi create mode 100644 typings/astropy/io/ascii/basic.pyi create mode 100644 typings/astropy/io/ascii/cds.pyi create mode 100644 typings/astropy/io/ascii/connect.pyi create mode 100644 typings/astropy/io/ascii/core.pyi create mode 100644 typings/astropy/io/ascii/daophot.pyi create mode 100644 typings/astropy/io/ascii/docs.pyi create mode 100644 typings/astropy/io/ascii/ecsv.pyi create mode 100644 typings/astropy/io/ascii/fastbasic.pyi create mode 100644 typings/astropy/io/ascii/fixedwidth.pyi create mode 100644 typings/astropy/io/ascii/html.pyi create mode 100644 typings/astropy/io/ascii/ipac.pyi create mode 100644 typings/astropy/io/ascii/latex.pyi create mode 100644 typings/astropy/io/ascii/misc.pyi create mode 100644 typings/astropy/io/ascii/mrt.pyi create mode 100644 typings/astropy/io/ascii/qdp.pyi create mode 100644 typings/astropy/io/ascii/rst.pyi create mode 100644 typings/astropy/io/ascii/sextractor.pyi create mode 100644 typings/astropy/io/ascii/ui.pyi create mode 100644 typings/astropy/io/fits/__init__.pyi create mode 100644 typings/astropy/io/fits/card.pyi create mode 100644 typings/astropy/io/fits/column.pyi create mode 100644 typings/astropy/io/fits/connect.pyi create mode 100644 typings/astropy/io/fits/convenience.pyi create mode 100644 typings/astropy/io/fits/diff.pyi create mode 100644 typings/astropy/io/fits/file.pyi create mode 100644 typings/astropy/io/fits/fitsrec.pyi create mode 100644 typings/astropy/io/fits/fitstime.pyi create mode 100644 typings/astropy/io/fits/hdu/__init__.pyi create mode 100644 typings/astropy/io/fits/hdu/base.pyi create mode 100644 typings/astropy/io/fits/hdu/compressed.pyi create mode 100644 typings/astropy/io/fits/hdu/groups.pyi create mode 100644 typings/astropy/io/fits/hdu/hdulist.pyi create mode 100644 typings/astropy/io/fits/hdu/image.pyi create mode 100644 typings/astropy/io/fits/hdu/nonstandard.pyi create mode 100644 typings/astropy/io/fits/hdu/streaming.pyi create mode 100644 typings/astropy/io/fits/hdu/table.pyi create mode 100644 typings/astropy/io/fits/header.pyi create mode 100644 typings/astropy/io/fits/util.pyi create mode 100644 typings/astropy/io/fits/verify.pyi create mode 100644 typings/astropy/io/misc/__init__.pyi create mode 100644 typings/astropy/io/misc/asdf/connect.pyi create mode 100644 typings/astropy/io/misc/asdf/deprecation.pyi create mode 100644 typings/astropy/io/misc/connect.pyi create mode 100644 typings/astropy/io/misc/hdf5.pyi create mode 100644 typings/astropy/io/misc/pandas/connect.pyi create mode 100644 typings/astropy/io/misc/parquet.pyi create mode 100644 typings/astropy/io/misc/pickle_helpers.pyi create mode 100644 typings/astropy/io/misc/yaml.pyi create mode 100644 typings/astropy/io/registry/__init__.pyi create mode 100644 typings/astropy/io/registry/base.pyi create mode 100644 typings/astropy/io/registry/compat.pyi create mode 100644 typings/astropy/io/registry/core.pyi create mode 100644 typings/astropy/io/registry/interface.pyi create mode 100644 typings/astropy/io/votable/__init__.pyi create mode 100644 typings/astropy/io/votable/connect.pyi create mode 100644 typings/astropy/io/votable/converters.pyi create mode 100644 typings/astropy/io/votable/exceptions.pyi create mode 100644 typings/astropy/io/votable/table.pyi create mode 100644 typings/astropy/io/votable/tree.pyi create mode 100644 typings/astropy/io/votable/ucd.pyi create mode 100644 typings/astropy/io/votable/util.pyi create mode 100644 typings/astropy/io/votable/xmlutil.pyi create mode 100644 typings/astropy/logger.pyi create mode 100644 typings/astropy/modeling/__init__.pyi create mode 100644 typings/astropy/modeling/bounding_box.pyi create mode 100644 typings/astropy/modeling/convolution.pyi create mode 100644 typings/astropy/modeling/core.pyi create mode 100644 typings/astropy/modeling/fitting.pyi create mode 100644 typings/astropy/modeling/functional_models.pyi create mode 100644 typings/astropy/modeling/mappings.pyi create mode 100644 typings/astropy/modeling/math_functions.pyi create mode 100644 typings/astropy/modeling/models.pyi create mode 100644 typings/astropy/modeling/optimizers.pyi create mode 100644 typings/astropy/modeling/parameters.pyi create mode 100644 typings/astropy/modeling/physical_models.pyi create mode 100644 typings/astropy/modeling/polynomial.pyi create mode 100644 typings/astropy/modeling/powerlaws.pyi create mode 100644 typings/astropy/modeling/projections.pyi create mode 100644 typings/astropy/modeling/rotations.pyi create mode 100644 typings/astropy/modeling/separable.pyi create mode 100644 typings/astropy/modeling/spline.pyi create mode 100644 typings/astropy/modeling/statistic.pyi create mode 100644 typings/astropy/modeling/tabular.pyi create mode 100644 typings/astropy/modeling/utils.pyi create mode 100644 typings/astropy/nddata/__init__.pyi create mode 100644 typings/astropy/nddata/bitmask.pyi create mode 100644 typings/astropy/nddata/blocks.pyi create mode 100644 typings/astropy/nddata/ccddata.pyi create mode 100644 typings/astropy/nddata/compat.pyi create mode 100644 typings/astropy/nddata/decorators.pyi create mode 100644 typings/astropy/nddata/flag_collection.pyi create mode 100644 typings/astropy/nddata/mixins/ndarithmetic.pyi create mode 100644 typings/astropy/nddata/mixins/ndio.pyi create mode 100644 typings/astropy/nddata/mixins/ndslicing.pyi create mode 100644 typings/astropy/nddata/nddata.pyi create mode 100644 typings/astropy/nddata/nddata_base.pyi create mode 100644 typings/astropy/nddata/nddata_withmixins.pyi create mode 100644 typings/astropy/nddata/nduncertainty.pyi create mode 100644 typings/astropy/nddata/utils.pyi create mode 100644 typings/astropy/samp/__init__.pyi create mode 100644 typings/astropy/samp/client.pyi create mode 100644 typings/astropy/samp/constants.pyi create mode 100644 typings/astropy/samp/errors.pyi create mode 100644 typings/astropy/samp/hub.pyi create mode 100644 typings/astropy/samp/hub_proxy.pyi create mode 100644 typings/astropy/samp/integrated_client.pyi create mode 100644 typings/astropy/samp/lockfile_helpers.pyi create mode 100644 typings/astropy/samp/standard_profile.pyi create mode 100644 typings/astropy/samp/utils.pyi create mode 100644 typings/astropy/samp/web_profile.pyi create mode 100644 typings/astropy/stats/__init__.pyi create mode 100644 typings/astropy/stats/bayesian_blocks.pyi create mode 100644 typings/astropy/stats/biweight.pyi create mode 100644 typings/astropy/stats/bls/__init__.pyi create mode 100644 typings/astropy/stats/circstats.pyi create mode 100644 typings/astropy/stats/funcs.pyi create mode 100644 typings/astropy/stats/histogram.pyi create mode 100644 typings/astropy/stats/info_theory.pyi create mode 100644 typings/astropy/stats/jackknife.pyi create mode 100644 typings/astropy/stats/lombscargle/__init__.pyi create mode 100644 typings/astropy/stats/sigma_clipping.pyi create mode 100644 typings/astropy/stats/spatial.pyi create mode 100644 typings/astropy/table/__init__.pyi create mode 100644 typings/astropy/table/bst.pyi create mode 100644 typings/astropy/table/column.pyi create mode 100644 typings/astropy/table/connect.pyi create mode 100644 typings/astropy/table/groups.pyi create mode 100644 typings/astropy/table/index.pyi create mode 100644 typings/astropy/table/info.pyi create mode 100644 typings/astropy/table/jsviewer.pyi create mode 100644 typings/astropy/table/meta.pyi create mode 100644 typings/astropy/table/mixins/dask.pyi create mode 100644 typings/astropy/table/mixins/registry.pyi create mode 100644 typings/astropy/table/ndarray_mixin.pyi create mode 100644 typings/astropy/table/np_utils.pyi create mode 100644 typings/astropy/table/operations.pyi create mode 100644 typings/astropy/table/pprint.pyi create mode 100644 typings/astropy/table/row.pyi create mode 100644 typings/astropy/table/serialize.pyi create mode 100644 typings/astropy/table/soco.pyi create mode 100644 typings/astropy/table/sorted_array.pyi create mode 100644 typings/astropy/table/table.pyi create mode 100644 typings/astropy/tests/__init__.pyi create mode 100644 typings/astropy/tests/runner.pyi create mode 100644 typings/astropy/time/__init__.pyi create mode 100644 typings/astropy/time/core.pyi create mode 100644 typings/astropy/time/formats.pyi create mode 100644 typings/astropy/time/time_helper/function_helpers.pyi create mode 100644 typings/astropy/time/utils.pyi create mode 100644 typings/astropy/timeseries/__init__.pyi create mode 100644 typings/astropy/timeseries/binned.pyi create mode 100644 typings/astropy/timeseries/core.pyi create mode 100644 typings/astropy/timeseries/downsample.pyi create mode 100644 typings/astropy/timeseries/io/__init__.pyi create mode 100644 typings/astropy/timeseries/io/kepler.pyi create mode 100644 typings/astropy/timeseries/periodograms/__init__.pyi create mode 100644 typings/astropy/timeseries/periodograms/base.pyi create mode 100644 typings/astropy/timeseries/periodograms/bls/__init__.pyi create mode 100644 typings/astropy/timeseries/periodograms/bls/core.pyi create mode 100644 typings/astropy/timeseries/periodograms/bls/methods.pyi create mode 100644 typings/astropy/timeseries/periodograms/bls/setup_package.pyi create mode 100644 typings/astropy/timeseries/periodograms/bls/tests/__init__.pyi create mode 100644 typings/astropy/timeseries/periodograms/lombscargle/__init__.pyi create mode 100644 typings/astropy/timeseries/periodograms/lombscargle/_statistics.pyi create mode 100644 typings/astropy/timeseries/periodograms/lombscargle/core.pyi create mode 100644 typings/astropy/timeseries/periodograms/lombscargle/implementations/__init__.pyi create mode 100644 typings/astropy/timeseries/periodograms/lombscargle/implementations/chi2_impl.pyi create mode 100644 typings/astropy/timeseries/periodograms/lombscargle/implementations/fast_impl.pyi create mode 100644 typings/astropy/timeseries/periodograms/lombscargle/implementations/fastchi2_impl.pyi create mode 100644 typings/astropy/timeseries/periodograms/lombscargle/implementations/main.pyi create mode 100644 typings/astropy/timeseries/periodograms/lombscargle/implementations/mle.pyi create mode 100644 typings/astropy/timeseries/periodograms/lombscargle/implementations/scipy_impl.pyi create mode 100644 typings/astropy/timeseries/periodograms/lombscargle/implementations/slow_impl.pyi create mode 100644 typings/astropy/timeseries/periodograms/lombscargle/implementations/utils.pyi create mode 100644 typings/astropy/timeseries/periodograms/lombscargle/tests/__init__.pyi create mode 100644 typings/astropy/timeseries/periodograms/lombscargle/utils.pyi create mode 100644 typings/astropy/timeseries/sampled.pyi create mode 100644 typings/astropy/uncertainty/__init__.pyi create mode 100644 typings/astropy/uncertainty/core.pyi create mode 100644 typings/astropy/uncertainty/distributions.pyi create mode 100644 typings/astropy/units/__init__.pyi create mode 100644 typings/astropy/units/_typing.pyi create mode 100644 typings/astropy/units/astrophys.pyi create mode 100644 typings/astropy/units/cds.pyi create mode 100644 typings/astropy/units/cgs.pyi create mode 100644 typings/astropy/units/core.pyi create mode 100644 typings/astropy/units/decorators.pyi create mode 100644 typings/astropy/units/equivalencies.pyi create mode 100644 typings/astropy/units/format/__init__.pyi create mode 100644 typings/astropy/units/format/base.pyi create mode 100644 typings/astropy/units/format/cds.pyi create mode 100644 typings/astropy/units/format/console.pyi create mode 100644 typings/astropy/units/format/fits.pyi create mode 100644 typings/astropy/units/format/generic.pyi create mode 100644 typings/astropy/units/format/latex.pyi create mode 100644 typings/astropy/units/format/ogip.pyi create mode 100644 typings/astropy/units/format/unicode_format.pyi create mode 100644 typings/astropy/units/format/utils.pyi create mode 100644 typings/astropy/units/format/vounit.pyi create mode 100644 typings/astropy/units/function/__init__.pyi create mode 100644 typings/astropy/units/function/core.pyi create mode 100644 typings/astropy/units/function/logarithmic.pyi create mode 100644 typings/astropy/units/function/mixin.pyi create mode 100644 typings/astropy/units/function/units.pyi create mode 100644 typings/astropy/units/imperial.pyi create mode 100644 typings/astropy/units/misc.pyi create mode 100644 typings/astropy/units/photometric.pyi create mode 100644 typings/astropy/units/physical.pyi create mode 100644 typings/astropy/units/quantity.pyi create mode 100644 typings/astropy/units/quantity_helper/__init__.pyi create mode 100644 typings/astropy/units/quantity_helper/converters.pyi create mode 100644 typings/astropy/units/quantity_helper/erfa.pyi create mode 100644 typings/astropy/units/quantity_helper/function_helpers.pyi create mode 100644 typings/astropy/units/quantity_helper/helpers.pyi create mode 100644 typings/astropy/units/quantity_helper/scipy_special.pyi create mode 100644 typings/astropy/units/required_by_vounit.pyi create mode 100644 typings/astropy/units/si.pyi create mode 100644 typings/astropy/units/structured.pyi create mode 100644 typings/astropy/units/utils.pyi create mode 100644 typings/astropy/utils/__init__.pyi create mode 100644 typings/astropy/utils/codegen.pyi create mode 100644 typings/astropy/utils/collections.pyi create mode 100644 typings/astropy/utils/compat/__init__.pyi create mode 100644 typings/astropy/utils/compat/misc.pyi create mode 100644 typings/astropy/utils/compat/numpycompat.pyi create mode 100644 typings/astropy/utils/compat/optional_deps.pyi create mode 100644 typings/astropy/utils/console.pyi create mode 100644 typings/astropy/utils/data.pyi create mode 100644 typings/astropy/utils/data_info.pyi create mode 100644 typings/astropy/utils/decorators.pyi create mode 100644 typings/astropy/utils/diff.pyi create mode 100644 typings/astropy/utils/exceptions.pyi create mode 100644 typings/astropy/utils/iers/__init__.pyi create mode 100644 typings/astropy/utils/iers/iers.pyi create mode 100644 typings/astropy/utils/introspection.pyi create mode 100644 typings/astropy/utils/masked/__init__.pyi create mode 100644 typings/astropy/utils/masked/core.pyi create mode 100644 typings/astropy/utils/masked/function_helpers.pyi create mode 100644 typings/astropy/utils/metadata.pyi create mode 100644 typings/astropy/utils/misc.pyi create mode 100644 typings/astropy/utils/parsing.pyi create mode 100644 typings/astropy/utils/shapes.pyi create mode 100644 typings/astropy/utils/state.pyi create mode 100644 typings/astropy/utils/xml/__init__.pyi create mode 100644 typings/astropy/utils/xml/check.pyi create mode 100644 typings/astropy/utils/xml/iterparser.pyi create mode 100644 typings/astropy/utils/xml/validate.pyi create mode 100644 typings/astropy/utils/xml/writer.pyi create mode 100644 typings/astropy/version.pyi create mode 100644 typings/astropy/visualization/__init__.pyi create mode 100644 typings/astropy/visualization/hist.pyi create mode 100644 typings/astropy/visualization/interval.pyi create mode 100644 typings/astropy/visualization/lupton_rgb.pyi create mode 100644 typings/astropy/visualization/mpl_normalize.pyi create mode 100644 typings/astropy/visualization/mpl_style.pyi create mode 100644 typings/astropy/visualization/stretch.pyi create mode 100644 typings/astropy/visualization/time.pyi create mode 100644 typings/astropy/visualization/transform.pyi create mode 100644 typings/astropy/visualization/units.pyi create mode 100644 typings/astropy/visualization/wcsaxes/__init__.pyi create mode 100644 typings/astropy/visualization/wcsaxes/axislabels.pyi create mode 100644 typings/astropy/visualization/wcsaxes/coordinate_helpers.pyi create mode 100644 typings/astropy/visualization/wcsaxes/coordinate_range.pyi create mode 100644 typings/astropy/visualization/wcsaxes/coordinates_map.pyi create mode 100644 typings/astropy/visualization/wcsaxes/core.pyi create mode 100644 typings/astropy/visualization/wcsaxes/formatter_locator.pyi create mode 100644 typings/astropy/visualization/wcsaxes/frame.pyi create mode 100644 typings/astropy/visualization/wcsaxes/grid_paths.pyi create mode 100644 typings/astropy/visualization/wcsaxes/patches.pyi create mode 100644 typings/astropy/visualization/wcsaxes/ticklabels.pyi create mode 100644 typings/astropy/visualization/wcsaxes/ticks.pyi create mode 100644 typings/astropy/visualization/wcsaxes/transforms.pyi create mode 100644 typings/astropy/visualization/wcsaxes/utils.pyi create mode 100644 typings/astropy/visualization/wcsaxes/wcsapi.pyi create mode 100644 typings/astropy/wcs/__init__.pyi create mode 100644 typings/astropy/wcs/docstrings.pyi create mode 100644 typings/astropy/wcs/utils.pyi create mode 100644 typings/astropy/wcs/wcs.pyi create mode 100644 typings/astropy/wcs/wcsapi/__init__.pyi create mode 100644 typings/astropy/wcs/wcsapi/fitswcs.pyi create mode 100644 typings/astropy/wcs/wcsapi/high_level_api.pyi create mode 100644 typings/astropy/wcs/wcsapi/high_level_wcs_wrapper.pyi create mode 100644 typings/astropy/wcs/wcsapi/low_level_api.pyi create mode 100644 typings/astropy/wcs/wcsapi/utils.pyi create mode 100644 typings/astropy/wcs/wcsapi/wrappers/__init__.pyi create mode 100644 typings/astropy/wcs/wcsapi/wrappers/base.pyi create mode 100644 typings/astropy/wcs/wcsapi/wrappers/sliced_wcs.pyi create mode 100644 typings/astropy/wcs/wcsapi/wrappers/tests/__init__.pyi create mode 100644 typings/astroquery/__init__.pyi create mode 100644 typings/astroquery/_astropy_init.pyi create mode 100644 typings/astroquery/exceptions.pyi create mode 100644 typings/astroquery/logger.pyi create mode 100644 typings/astroquery/query.pyi create mode 100644 typings/astroquery/simbad/__init__.pyi create mode 100644 typings/astroquery/simbad/core.pyi create mode 100644 typings/astroquery/simbad/get_votable_fields.pyi create mode 100644 typings/astroquery/simbad/setup_package.pyi create mode 100644 typings/astroquery/simbad/tests/__init__.pyi create mode 100644 typings/astroquery/skyview/__init__.pyi create mode 100644 typings/astroquery/skyview/core.pyi create mode 100644 typings/astroquery/utils/__init__.pyi create mode 100644 typings/astroquery/utils/class_or_instance.pyi create mode 100644 typings/astroquery/utils/commons.pyi create mode 100644 typings/astroquery/utils/docstr_chompers.pyi create mode 100644 typings/astroquery/utils/download_file_list.pyi create mode 100644 typings/astroquery/utils/process_asyncs.pyi create mode 100644 typings/astroquery/utils/progressbar.pyi create mode 100644 typings/astroquery/utils/system_tools.pyi create mode 100644 typings/astroquery/version.pyi create mode 100644 typings/erfa/__init__.pyi create mode 100644 typings/erfa/_version.pyi create mode 100644 typings/erfa/core.pyi create mode 100644 typings/erfa/helpers.pyi create mode 100644 typings/erfa/ufunc.pyi create mode 100644 typings/erfa/version.pyi create mode 100644 typings/matplotlib/__init__.pyi create mode 100644 typings/matplotlib/_afm.pyi create mode 100644 typings/matplotlib/_animation_data.pyi create mode 100644 typings/matplotlib/_api/__init__.pyi create mode 100644 typings/matplotlib/_api/deprecation.pyi create mode 100644 typings/matplotlib/_blocking_input.pyi create mode 100644 typings/matplotlib/_c_internal_utils.pyi create mode 100644 typings/matplotlib/_cm.pyi create mode 100644 typings/matplotlib/_cm_listed.pyi create mode 100644 typings/matplotlib/_color_data.pyi create mode 100644 typings/matplotlib/_constrained_layout.pyi create mode 100644 typings/matplotlib/_docstring.pyi create mode 100644 typings/matplotlib/_enums.pyi create mode 100644 typings/matplotlib/_fontconfig_pattern.pyi create mode 100644 typings/matplotlib/_image.pyi create mode 100644 typings/matplotlib/_internal_utils.pyi create mode 100644 typings/matplotlib/_layoutgrid.pyi create mode 100644 typings/matplotlib/_mathtext.pyi create mode 100644 typings/matplotlib/_mathtext_data.pyi create mode 100644 typings/matplotlib/_path.pyi create mode 100644 typings/matplotlib/_pylab_helpers.pyi create mode 100644 typings/matplotlib/_qhull.pyi create mode 100644 typings/matplotlib/_text_helpers.pyi create mode 100644 typings/matplotlib/_tight_bbox.pyi create mode 100644 typings/matplotlib/_tight_layout.pyi create mode 100644 typings/matplotlib/_tri.pyi create mode 100644 typings/matplotlib/_ttconv.pyi create mode 100644 typings/matplotlib/_type1font.pyi create mode 100644 typings/matplotlib/_version.pyi create mode 100644 typings/matplotlib/afm.pyi create mode 100644 typings/matplotlib/animation.pyi create mode 100644 typings/matplotlib/artist.pyi create mode 100644 typings/matplotlib/axes/__init__.pyi create mode 100644 typings/matplotlib/axes/_axes.pyi create mode 100644 typings/matplotlib/axes/_base.pyi create mode 100644 typings/matplotlib/axes/_secondary_axes.pyi create mode 100644 typings/matplotlib/axes/_subplots.pyi create mode 100644 typings/matplotlib/axis.pyi create mode 100644 typings/matplotlib/backend_bases.pyi create mode 100644 typings/matplotlib/backend_managers.pyi create mode 100644 typings/matplotlib/backend_tools.pyi create mode 100644 typings/matplotlib/backends/__init__.pyi create mode 100644 typings/matplotlib/backends/_backend_agg.pyi create mode 100644 typings/matplotlib/backends/_backend_gtk.pyi create mode 100644 typings/matplotlib/backends/_backend_pdf_ps.pyi create mode 100644 typings/matplotlib/backends/_backend_tk.pyi create mode 100644 typings/matplotlib/backends/_tkagg.pyi create mode 100644 typings/matplotlib/backends/backend_agg.pyi create mode 100644 typings/matplotlib/backends/backend_cairo.pyi create mode 100644 typings/matplotlib/backends/backend_gtk3.pyi create mode 100644 typings/matplotlib/backends/backend_gtk3agg.pyi create mode 100644 typings/matplotlib/backends/backend_gtk3cairo.pyi create mode 100644 typings/matplotlib/backends/backend_gtk4.pyi create mode 100644 typings/matplotlib/backends/backend_gtk4agg.pyi create mode 100644 typings/matplotlib/backends/backend_gtk4cairo.pyi create mode 100644 typings/matplotlib/backends/backend_macosx.pyi create mode 100644 typings/matplotlib/backends/backend_mixed.pyi create mode 100644 typings/matplotlib/backends/backend_nbagg.pyi create mode 100644 typings/matplotlib/backends/backend_pdf.pyi create mode 100644 typings/matplotlib/backends/backend_pgf.pyi create mode 100644 typings/matplotlib/backends/backend_ps.pyi create mode 100644 typings/matplotlib/backends/backend_qt.pyi create mode 100644 typings/matplotlib/backends/backend_qt5.pyi create mode 100644 typings/matplotlib/backends/backend_qt5agg.pyi create mode 100644 typings/matplotlib/backends/backend_qt5cairo.pyi create mode 100644 typings/matplotlib/backends/backend_qtagg.pyi create mode 100644 typings/matplotlib/backends/backend_qtcairo.pyi create mode 100644 typings/matplotlib/backends/backend_svg.pyi create mode 100644 typings/matplotlib/backends/backend_template.pyi create mode 100644 typings/matplotlib/backends/backend_tkagg.pyi create mode 100644 typings/matplotlib/backends/backend_tkcairo.pyi create mode 100644 typings/matplotlib/backends/backend_webagg.pyi create mode 100644 typings/matplotlib/backends/backend_webagg_core.pyi create mode 100644 typings/matplotlib/backends/backend_wx.pyi create mode 100644 typings/matplotlib/backends/backend_wxagg.pyi create mode 100644 typings/matplotlib/backends/backend_wxcairo.pyi create mode 100644 typings/matplotlib/backends/qt_compat.pyi create mode 100644 typings/matplotlib/backends/qt_editor/__init__.pyi create mode 100644 typings/matplotlib/backends/qt_editor/_formlayout.pyi create mode 100644 typings/matplotlib/backends/qt_editor/figureoptions.pyi create mode 100644 typings/matplotlib/bezier.pyi create mode 100644 typings/matplotlib/blocking_input.pyi create mode 100644 typings/matplotlib/category.pyi create mode 100644 typings/matplotlib/cbook/__init__.pyi create mode 100644 typings/matplotlib/cm.pyi create mode 100644 typings/matplotlib/collections.pyi create mode 100644 typings/matplotlib/colorbar.pyi create mode 100644 typings/matplotlib/colors.pyi create mode 100644 typings/matplotlib/container.pyi create mode 100644 typings/matplotlib/contour.pyi create mode 100644 typings/matplotlib/dates.pyi create mode 100644 typings/matplotlib/docstring.pyi create mode 100644 typings/matplotlib/dviread.pyi create mode 100644 typings/matplotlib/figure.pyi create mode 100644 typings/matplotlib/font_manager.pyi create mode 100644 typings/matplotlib/fontconfig_pattern.pyi create mode 100644 typings/matplotlib/ft2font.pyi create mode 100644 typings/matplotlib/gridspec.pyi create mode 100644 typings/matplotlib/hatch.pyi create mode 100644 typings/matplotlib/image.pyi create mode 100644 typings/matplotlib/layout_engine.pyi create mode 100644 typings/matplotlib/legend.pyi create mode 100644 typings/matplotlib/legend_handler.pyi create mode 100644 typings/matplotlib/lines.pyi create mode 100644 typings/matplotlib/markers.pyi create mode 100644 typings/matplotlib/mathtext.pyi create mode 100644 typings/matplotlib/mlab.pyi create mode 100644 typings/matplotlib/offsetbox.pyi create mode 100644 typings/matplotlib/patches.pyi create mode 100644 typings/matplotlib/path.pyi create mode 100644 typings/matplotlib/patheffects.pyi create mode 100644 typings/matplotlib/projections/__init__.pyi create mode 100644 typings/matplotlib/projections/geo.pyi create mode 100644 typings/matplotlib/projections/polar.pyi create mode 100644 typings/matplotlib/pylab.pyi create mode 100644 typings/matplotlib/pyplot.pyi create mode 100644 typings/matplotlib/quiver.pyi create mode 100644 typings/matplotlib/rcsetup.pyi create mode 100644 typings/matplotlib/sankey.pyi create mode 100644 typings/matplotlib/scale.pyi create mode 100644 typings/matplotlib/sphinxext/__init__.pyi create mode 100644 typings/matplotlib/sphinxext/mathmpl.pyi create mode 100644 typings/matplotlib/sphinxext/plot_directive.pyi create mode 100644 typings/matplotlib/spines.pyi create mode 100644 typings/matplotlib/stackplot.pyi create mode 100644 typings/matplotlib/streamplot.pyi create mode 100644 typings/matplotlib/style/__init__.pyi create mode 100644 typings/matplotlib/style/core.pyi create mode 100644 typings/matplotlib/table.pyi create mode 100644 typings/matplotlib/texmanager.pyi create mode 100644 typings/matplotlib/text.pyi create mode 100644 typings/matplotlib/textpath.pyi create mode 100644 typings/matplotlib/ticker.pyi create mode 100644 typings/matplotlib/tight_bbox.pyi create mode 100644 typings/matplotlib/tight_layout.pyi create mode 100644 typings/matplotlib/transforms.pyi create mode 100644 typings/matplotlib/tri/__init__.pyi create mode 100644 typings/matplotlib/tri/triangulation.pyi create mode 100644 typings/matplotlib/tri/tricontour.pyi create mode 100644 typings/matplotlib/tri/trifinder.pyi create mode 100644 typings/matplotlib/tri/triinterpolate.pyi create mode 100644 typings/matplotlib/tri/tripcolor.pyi create mode 100644 typings/matplotlib/tri/triplot.pyi create mode 100644 typings/matplotlib/tri/trirefine.pyi create mode 100644 typings/matplotlib/tri/tritools.pyi create mode 100644 typings/matplotlib/type1font.pyi create mode 100644 typings/matplotlib/units.pyi create mode 100644 typings/matplotlib/widgets.pyi create mode 100644 typings/regions/__init__.pyi create mode 100644 typings/regions/_astropy_init.pyi create mode 100644 typings/regions/_geometry/__init__.pyi create mode 100644 typings/regions/_geometry/circular_overlap.pyi create mode 100644 typings/regions/_geometry/core.pyi create mode 100644 typings/regions/_geometry/elliptical_overlap.pyi create mode 100644 typings/regions/_geometry/pnpoly.pyi create mode 100644 typings/regions/_geometry/polygonal_overlap.pyi create mode 100644 typings/regions/_geometry/rectangular_overlap.pyi create mode 100644 typings/regions/_utils/__init__.pyi create mode 100644 typings/regions/_utils/examples.pyi create mode 100644 typings/regions/_utils/optional_deps.pyi create mode 100644 typings/regions/_utils/wcs_helpers.pyi create mode 100644 typings/regions/compiler_version.pyi create mode 100644 typings/regions/core/__init__.pyi create mode 100644 typings/regions/core/attributes.pyi create mode 100644 typings/regions/core/bounding_box.pyi create mode 100644 typings/regions/core/compound.pyi create mode 100644 typings/regions/core/core.pyi create mode 100644 typings/regions/core/mask.pyi create mode 100644 typings/regions/core/metadata.pyi create mode 100644 typings/regions/core/pixcoord.pyi create mode 100644 typings/regions/core/regions.pyi create mode 100644 typings/regions/core/registry.pyi create mode 100644 typings/regions/io/__init__.pyi create mode 100644 typings/regions/io/crtf/__init__.pyi create mode 100644 typings/regions/io/crtf/connect.pyi create mode 100644 typings/regions/io/crtf/core.pyi create mode 100644 typings/regions/io/crtf/io_core.pyi create mode 100644 typings/regions/io/crtf/read.pyi create mode 100644 typings/regions/io/crtf/write.pyi create mode 100644 typings/regions/io/ds9/__init__.pyi create mode 100644 typings/regions/io/ds9/connect.pyi create mode 100644 typings/regions/io/ds9/core.pyi create mode 100644 typings/regions/io/ds9/meta.pyi create mode 100644 typings/regions/io/ds9/read.pyi create mode 100644 typings/regions/io/ds9/write.pyi create mode 100644 typings/regions/io/fits/__init__.pyi create mode 100644 typings/regions/io/fits/connect.pyi create mode 100644 typings/regions/io/fits/core.pyi create mode 100644 typings/regions/io/fits/read.pyi create mode 100644 typings/regions/io/fits/write.pyi create mode 100644 typings/regions/shapes/__init__.pyi create mode 100644 typings/regions/shapes/annulus.pyi create mode 100644 typings/regions/shapes/circle.pyi create mode 100644 typings/regions/shapes/ellipse.pyi create mode 100644 typings/regions/shapes/line.pyi create mode 100644 typings/regions/shapes/point.pyi create mode 100644 typings/regions/shapes/polygon.pyi create mode 100644 typings/regions/shapes/rectangle.pyi create mode 100644 typings/regions/shapes/text.pyi create mode 100644 typings/regions/version.pyi create mode 100644 typings/tendrils/__init__.pyi create mode 100644 typings/tendrils/api/__init__.pyi create mode 100644 typings/tendrils/api/catalogs.pyi create mode 100644 typings/tendrils/api/datafiles.pyi create mode 100644 typings/tendrils/api/filters.pyi create mode 100644 typings/tendrils/api/lightcurves.pyi create mode 100644 typings/tendrils/api/photometry_api.pyi create mode 100644 typings/tendrils/api/set_photometry_status.pyi create mode 100644 typings/tendrils/api/sites.pyi create mode 100644 typings/tendrils/api/targets.pyi create mode 100644 typings/tendrils/utils/__init__.pyi create mode 100644 typings/tendrils/utils/config.pyi create mode 100644 typings/tendrils/utils/files.pyi create mode 100644 typings/tendrils/utils/time.pyi create mode 100644 typings/tendrils/utils/tns.pyi create mode 100644 typings/tendrils/utils/urls.pyi create mode 100644 typings/tendrils/utils/ztf.pyi create mode 100644 typings/tendrils/version.pyi diff --git a/.github/workflows/python-package.yml b/.github/workflows/python-package.yml index 63a6cdd..845e5ff 100644 --- a/.github/workflows/python-package.yml +++ b/.github/workflows/python-package.yml @@ -10,13 +10,69 @@ on: branches: [ main ] jobs: + linting: + name: Lint with Flake8, Black + runs-on: ubuntu-latest + steps: + - name: Checkout code + uses: actions/checkout@v3 + with: + persist-credentials: true + - name: Set up Python 3.10 + uses: actions/setup-python@v3 + with: + python-version: "3.10" + - name: Install dependencies + run: | + python -m pip install --upgrade pip + python -m pip install flake8 black + - name: Lint with Flake8 + run: | + # stop the build if there are Python syntax errors or undefined names + flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics --extend-ignore=F821 --exclude .git,.idea,.mypy_cache,Notebooks/ + # exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide + flake8 . --count --exit-zero --max-complexity=10 --max-line-length=120 --statistics --extend-ignore=F821 --exclude .git,.idea,.mypy_cache,Notebooks/ + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + - name: Enforce Black codestyle. + uses: psf/black@stable + with: + options: "--check --verbose" + src: "./flows_get_brightest" + version: "21.10.0" + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + mypy: + name: mypy + runs-on: ubuntu-latest + steps: + - name: Checkout code + uses: actions/checkout@v3 + with: + persist-credentials: true + - name: Set up Python 3.10 + uses: actions/setup-python@v3 + with: + python-version: "3.10" + - name: Install dependencies + run: | + python -m pip install --upgrade pip + python -m pip install mypy + - name: Run MyPy + id: runmypy + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + mypy flows_get_brightest/ typings/tendrils/ --config-file=pyproject.toml --check-untyped-defs + build: - runs-on: ${{ matrix.os }} strategy: fail-fast: false matrix: os: [ubuntu-latest, macos-latest] python-version: ["3.10"] + runs-on: ${{ matrix.os }} + name: Pytest on ${{ matrix.os }}, python 3.10 steps: - uses: actions/checkout@v3 @@ -27,20 +83,20 @@ jobs: - name: Install dependencies run: | python -m pip install --upgrade pip - python -m pip install flake8 pytest - if [ -f requirements.txt ]; then pip install -r requirements.txt; fi - pip install '.[test]' - - name: Lint with flake8 - run: | - # stop the build if there are Python syntax errors or undefined names - flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics - # exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide - flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics - - name: update tendrils - run: | - + python -m pip install '.[test]' - name: Test with pytest env: FLOWS_API_TOKEN: ${{ secrets.FLOWS_API_TOKEN }} run: | - pytest -v + pytest -v --cov-report "xml:coverage.xml" --cov + - name: Pytest coverage report + uses: MishaKav/pytest-coverage-comment@main + if: ${{ matrix.os == ubuntu-latest }} + with: + pytest-xml-coverage-path: ./coverage.xml + token: ${{ secrets.GITHUB_TOKEN }} + title: Coverage Report + badge-title: Tests Coverage + hide-badge: false + hide-report: false + diff --git a/cutouts.py b/cutouts.py index eca1e60..6beb908 100644 --- a/cutouts.py +++ b/cutouts.py @@ -1,4 +1,5 @@ import astropy.io.fits as fits + # noinspection PyProtectedMember from astropy.io.fits.hdu.image import _ImageBaseHDU from astropy.nddata import Cutout2D @@ -11,9 +12,9 @@ import numpy as np from abc import ABC, abstractmethod -"""Expects fits compatible images saved with a single file extension (no .fits.gz), +"""Expects fits compatible images saved with a single file extension (no .fits.gz), Makes a cutout based on values of y and x and recomputes wcs, -Saves the new fits file in output dir, +Saves the new fits file in output dir, preserves all extensions and applies the same cut to all image extensions optionally plots the primary image in cut and uncut form. @@ -22,7 +23,6 @@ class AbstractImage(ABC): - @abstractmethod def __init__(self, image: _ImageBaseHDU): self.image = image @@ -41,9 +41,7 @@ def make_cutout(self, y: int, x: int): # noinspection PyAttributeOutsideInit class Image(AbstractImage): - - def __init__(self, image: _ImageBaseHDU, - primary: bool = False): + def __init__(self, image: _ImageBaseHDU, primary: bool = False): self.image = image self.data = image.data self.header = image.header @@ -63,12 +61,7 @@ def __init__(self, image: _ImageBaseHDU, # else: raise(TypeError) def cutout(self, y, x): - self.cut = Cutout2D( - self.data, - position=self.wcs.wcs.crpix, - wcs=self.wcs, - size=(y, x) - ) + self.cut = Cutout2D(self.data, position=self.wcs.wcs.crpix, wcs=self.wcs, size=(y, x)) # noinspection PyCallingNonCallable def make_fits_from_cutout(self): @@ -82,7 +75,7 @@ def fill_cut_image_header(self): try: self.cut_image.header[key] = self.header[key] except ValueError: - print(f'Bad fits key: {key}') + print(f"Bad fits key: {key}") def make_cutout(self, y: int, x: int): """convenience function for making a cutout image and forward filling header""" @@ -93,13 +86,9 @@ def make_cutout(self, y: int, x: int): class Plotter: - - def __init__(self, - figsize: tuple = (8, 8), - zs: BaseInterval = ZScaleInterval(1000), - subplots: int = 1, - dpi: int = 125 - ): + def __init__( + self, figsize: tuple = (8, 8), zs: BaseInterval = ZScaleInterval(1000), subplots: int = 1, dpi: int = 125 + ): self.figsize = figsize self.interval_finder = zs self.fig = plt.figure(figsize=self.figsize, dpi=dpi) @@ -109,8 +98,8 @@ def __init__(self, self.ax = None # noinspection SpellCheckingInspection - def plot_img(self, image: Image, wcs: WCS = 'None'): - if wcs == 'None': + def plot_img(self, image: Image, wcs: WCS = "None"): + if wcs == "None": wcs = image.wcs self.ax = self.fig.add_subplot(1, self.subplots, self.active_axis, projection=wcs) vmin, vmax = self.interval_finder.get_limits(image.data) @@ -124,18 +113,15 @@ def parse(): """Parse input :rtype: object """ - parser = argparse.ArgumentParser(prog='cut_image', - description='Cut image and all image extensions') + parser = argparse.ArgumentParser(prog="cut_image", description="Cut image and all image extensions") parser.add_argument("file", help="Specify the original file here") - parser.add_argument("--output_dir", help="Give output directory for saving", default='./') - parser.add_argument("-x", help='output suffix', type=int, default=4096) - parser.add_argument("-y", help='output suffix', type=int, default=4030) - parser.add_argument("-o", "--overwrite", help='overwrite output if exists', - action='store_true', default=False) - parser.add_argument("-p", "--plot", help='overwrite output if exists', - action='store_true', default=False) + parser.add_argument("--output_dir", help="Give output directory for saving", default="./") + parser.add_argument("-x", help="output suffix", type=int, default=4096) + parser.add_argument("-y", help="output suffix", type=int, default=4030) + parser.add_argument("-o", "--overwrite", help="overwrite output if exists", action="store_true", default=False) + parser.add_argument("-p", "--plot", help="overwrite output if exists", action="store_true", default=False) return parser.parse_args() @@ -144,8 +130,10 @@ def find_primary(hdul): # Find primary HDU and use its wcs primary_index = np.argwhere([isinstance(i, fits.PrimaryHDU) for i in hdul]).flatten() if primary_index.size <= 0 or primary_index.size > 1: - raise ValueError('WCS to use could not be set as there were less than or greater than one Primary HDUs \ - This should never be the case, please check your fits image!') + raise ValueError( + "WCS to use could not be set as there were less than or greater than one Primary HDUs " + " This should never be the case, please check your fits image!" + ) return primary_index[0] @@ -163,7 +151,7 @@ def make_img_cutout(i, wcs, y, x) -> AbstractImage: def main(): args = parse() curr = Path(args.file) - save_path = Path.joinpath(Path(args.output_dir), curr.stem + '_cutout' + curr.suffix).resolve() + save_path = Path.joinpath(Path(args.output_dir), curr.stem + "_cutout" + curr.suffix).resolve() hdul = fits.open(curr) new_hdul = fits.HDUList() @@ -184,16 +172,15 @@ def main(): if args.plot: plotter = Plotter(subplots=2, dpi=200) plotter.plot_img(Image(new_hdul[0], primary=True)) - plotter.ax.set_title('cutout') + plotter.ax.set_title("cutout") plotter.plot_img(Image(hdul[0], primary=True)) - plotter.ax.set_title('uncut') + plotter.ax.set_title("uncut") plt.show(block=True) # Save - new_hdul.writeto(str(save_path), output_verify='exception', - overwrite=args.overwrite, checksum=False) - print(f'saved to: {save_path}') + new_hdul.writeto(str(save_path), output_verify="exception", overwrite=args.overwrite, checksum=False) + print(f"saved to: {save_path}") -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/fetch_eso_data.py b/fetch_eso_data.py index bb16bef..5b7dae3 100644 --- a/fetch_eso_data.py +++ b/fetch_eso_data.py @@ -1,62 +1,63 @@ -from tendrils import api, utils -import pandas as pd -import multiprocessing as mp +import asyncio from typing import Collection, Optional import numpy as np -from astropy.table import Table -import asyncio +import pandas as pd from requests.exceptions import HTTPError +from tendrils import api eso_sites = [2, 12, 15] -eso_site_names = {2:"VLT-HAWKI", 12: "NTT-SOFI", 15: "NTT-EFOSC"} -usecols = ['fileid_img','time', 'mag', 'site', 'photfilter'] -tgtcols = ['target_name','redshift','ra','decl'] +eso_site_names = {2: "VLT-HAWKI", 12: "NTT-SOFI", 15: "NTT-EFOSC"} +usecols = ["fileid_img", "time", "mag", "site", "photfilter"] +tgtcols = ["target_name", "redshift", "ra", "decl"] + def get_targets(sub_targets: Optional[list[int]] = None) -> pd.DataFrame: targets = api.get_targets() targets = pd.DataFrame(targets) - targets = targets[targets['target_status']=='target'] + targets = targets[targets["target_status"] == "target"] if sub_targets is not None: - targets = targets[targets['targetid'].isin(sub_targets)] - return targets.set_index('targetid') + targets = targets[targets["targetid"].isin(sub_targets)] + return targets.set_index("targetid") + def get_target_data(tgtid: int, targets: pd.DataFrame) -> pd.Series: return targets.loc[(tgtid, tgtcols)] + def get_sites(fids: Collection[int]) -> pd.DataFrame: - keys = ['obstime', 'site', 'photfilter'] - r = {fid:{k:dat[k] for k in keys} - for fid in fids - if (dat:=api.get_datafile(fid))['site'] in eso_sites} + keys = ["obstime", "site", "photfilter"] + r = {fid: {k: dat[k] for k in keys} for fid in fids if (dat := api.get_datafile(fid))["site"] in eso_sites} df = pd.DataFrame(r).T - df.index.name = 'fileid_img' - df.rename({'obstime':'time'}, axis=1, inplace=True) - df['mag'] = np.nan + df.index.name = "fileid_img" + df.rename({"obstime": "time"}, axis=1, inplace=True) + df["mag"] = np.nan return df -async def get_target_lc(tgtid: int, targets: pd.DataFrame) -> pd.DataFrame: +async def get_target_lc(tgtid: int, targets: pd.DataFrame) -> pd.DataFrame: lc = api.get_lightcurve(tgtid) - lc['time'] = lc['time'].mjd # type: ignore + lc["time"] = lc["time"].mjd # type: ignore lc = lc.to_pandas() - lc['mag'] = lc['mag_sub'].fillna(lc['mag_raw']) + lc["mag"] = lc["mag_sub"].fillna(lc["mag_raw"]) lc = lc[usecols] - return lc.set_index('fileid_img') - + return lc.set_index("fileid_img") + + async def get_missing_eso_lcs(lc: pd.DataFrame, tgtid: int, targets: pd.DataFrame) -> pd.DataFrame: # add data with failed/missing photometry - dfs = api.get_datafiles(tgtid, filt='all') + dfs = api.get_datafiles(tgtid, filt="all") missing_fids = set(dfs) - set(lc.index.values) lc = pd.concat((lc, get_sites(missing_fids))) lc.sort_index(inplace=True) - return lc[lc['site'].isin(eso_sites)] + return lc[lc["site"].isin(eso_sites)] + async def get_eso_lc(tgtid: int, targets: pd.DataFrame) -> pd.DataFrame: try: lc = await get_target_lc(tgtid, targets) except HTTPError: lc = pd.DataFrame(index=[], columns=usecols) - lc.set_index('fileid_img', inplace=True) + lc.set_index("fileid_img", inplace=True) lc = await get_missing_eso_lcs(lc, tgtid, targets) if len(lc) == 0: return pd.DataFrame() @@ -64,20 +65,16 @@ async def get_eso_lc(tgtid: int, targets: pd.DataFrame) -> pd.DataFrame: return lc - async def main(): targets = get_targets() coroutines = [get_eso_lc(tgtid, targets) for tgtid in targets.index] eso_lcs_with_excp = await asyncio.gather(*coroutines, return_exceptions=True) eso_lcs = pd.concat([lc for lc in eso_lcs_with_excp if isinstance(lc, pd.DataFrame)]) - eso_lcs['site'] = eso_lcs.site.apply(lambda x: eso_site_names[x]) - eso_lcs.to_json('eso_lcs.json') - eso_lcs.to_csv('eso_lcs.csv') + eso_lcs["site"] = eso_lcs.site.apply(lambda x: eso_site_names[x]) + eso_lcs.to_json("eso_lcs.json") + eso_lcs.to_csv("eso_lcs.csv") print([lc for lc in eso_lcs_with_excp if not isinstance(lc, pd.DataFrame)]) - - - -if __name__ == '__main__': - asyncio.run(main()) +if __name__ == "__main__": + asyncio.run(main()) diff --git a/fixlcogt.py b/fixlcogt.py index d898adf..9ef7579 100644 --- a/fixlcogt.py +++ b/fixlcogt.py @@ -1,7 +1,6 @@ import argparse import astropy.io.fits as fits from astropy.wcs import WCS -import numpy as np from pathlib import Path @@ -20,23 +19,24 @@ def swap_wcs(hdul_orig, hdul_diff): return new_hdul -def get_basename_with_suffix(filename: Path, suffix=''): - return Path( - str(filename)[: str(filename).rfind(''.join(filename.suffixes))] - + suffix - + ''.join(filename.suffixes) - ) +def get_basename_with_suffix(filename: Path, suffix=""): + return Path(str(filename)[: str(filename).rfind("".join(filename.suffixes))] + suffix + "".join(filename.suffixes)) def parse(): - parser = argparse.ArgumentParser(prog='FixTemplateSubHeaderforLCOGT', description='Attach header and extra dimensions from second \ - file to the first, while checking to make sure WCS is identical.\ - If not, uses WCS offirst file.') + parser = argparse.ArgumentParser( + prog="FixTemplateSubHeaderforLCOGT", + description=( + "Attach header and extra dimensions from second file to the first," + " while checking to make sure WCS is identical. If not, uses WCS" + " offirst file." + ), + ) parser.add_argument("diff_file", help="Specify the diff file here") parser.add_argument("orig_file", help="Specify the original file here") - parser.add_argument("--suffix", help='output suffix', type=str, default="_hfix") - parser.add_argument("-o", "--overwrite", help='overwrite output if exists', action='store_true', default=False) + parser.add_argument("--suffix", help="output suffix", type=str, default="_hfix") + parser.add_argument("-o", "--overwrite", help="overwrite output if exists", action="store_true", default=False) return parser.parse_args() @@ -55,8 +55,8 @@ def main(): save_file = get_basename_with_suffix(diff_path, args.suffix) new_hdul = swap_wcs(hdul_orig, hdul_diff) new_hdul.writeto(save_file, overwrite=args.overwrite) - print(f'saved to: {save_file}') + print(f"saved to: {save_file}") -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/flows_get_brightest/__init__.py b/flows_get_brightest/__init__.py index f66df24..40379c5 100644 --- a/flows_get_brightest/__init__.py +++ b/flows_get_brightest/__init__.py @@ -4,5 +4,5 @@ tendrils API. Extensible for other instruments and projects. Can optionally make a finding chart using NASA SkyView. """ -from .version import __version__ -from .run_get_brightest import main +from .version import __version__ as __version__ # noqa: F401 +from .run_get_brightest import main as main # noqa: F401 diff --git a/flows_get_brightest/auth.py b/flows_get_brightest/auth.py index 2b1c684..b21c987 100644 --- a/flows_get_brightest/auth.py +++ b/flows_get_brightest/auth.py @@ -1,5 +1,4 @@ -import tendrils.api -import tendrils.utils +from tendrils import api, utils from requests.exceptions import HTTPError import warnings @@ -9,19 +8,19 @@ def test_tendrils() -> bool: Test Tendrils for API token authorization. """ try: - t = tendrils.api.get_target(8) + _ = api.get_target(8) # type: ignore return True except HTTPError as err: - if 'Unauthorized' in err.response.reason: + if "Unauthorized" in err.response.reason: return False raise err # This shouldn't happen. So raise it for debugging. def update_api_token() -> None: - token = input('Tendrils needs your FLOWS API token. Please enter it:') + token = input("Tendrils needs your FLOWS API token. Please enter it:") # We remove spaces from the token to avoid errors. - tendrils.utils.set_api_token(token.strip().replace(' ', ''), overwrite=True) - print('Token set. If there is a problem, please run `get_brightest` again.') + utils.set_api_token(token.strip().replace(" ", ""), overwrite=True) + print("Token set. If there is a problem, please run `get_brightest` again.") def test_connection() -> None: @@ -34,7 +33,11 @@ def test_connection() -> None: # But now we also query if connection fails after that too. # Useful when token is set to something invalid. update_api_token() - warnings.warn(RuntimeWarning("Could not connect to flows via Tendrils. " - "Check your API key and that target exists." - "Also try Tendrils config steps from:" - "https://www.github.com/SNFlows/tendrils/#before-you-begin-important")) + warnings.warn( + RuntimeWarning( + "Could not connect to flows via Tendrils. " + "Check your API key and that target exists." + "Also try Tendrils config steps from:" + "https://www.github.com/SNFlows/tendrils/#before-you-begin-important" + ) + ) diff --git a/flows_get_brightest/catalogs.py b/flows_get_brightest/catalogs.py index cf2d6f2..3f5e13d 100644 --- a/flows_get_brightest/catalogs.py +++ b/flows_get_brightest/catalogs.py @@ -9,7 +9,9 @@ from .utils import numeric -def query_simbad(coo_centre, radius= u.Quantity(24, u.arcmin)) -> tuple[Optional[Table], Optional[SkyCoord]]: +def query_simbad( + coo_centre: SkyCoord, radius: numeric = u.Quantity(24, u.arcmin) +) -> tuple[Optional[Table], Optional[SkyCoord]]: """ Query SIMBAD using cone-search around the position using astroquery Parameters: @@ -23,45 +25,47 @@ def query_simbad(coo_centre, radius= u.Quantity(24, u.arcmin)) -> tuple[Optional s = Simbad() s.ROW_LIMIT = 0 - s.remove_votable_fields('coordinates') - s.add_votable_fields('ra(d;A;ICRS;J2000)', 'dec(d;D;ICRS;2000)', 'pmra', 'pmdec') - s.add_votable_fields('otype') - s.add_votable_fields('flux(B)', 'flux(V)', 'flux(R)', 'flux(I)', 'flux(J)', 'flux(H)', 'flux(K)') - s.add_votable_fields('flux(u)', 'flux(g)', 'flux(r)', 'flux(i)', 'flux(z)') + s.remove_votable_fields("coordinates") + s.add_votable_fields("ra(d;A;ICRS;J2000)", "dec(d;D;ICRS;2000)", "pmra", "pmdec") + s.add_votable_fields("otype") + s.add_votable_fields("flux(B)", "flux(V)", "flux(R)", "flux(I)", "flux(J)", "flux(H)", "flux(K)") + s.add_votable_fields("flux(u)", "flux(g)", "flux(r)", "flux(i)", "flux(z)") rad = Angle(radius).arcmin with warnings.catch_warnings(): - warnings.filterwarnings('ignore', category=UserWarning) - results = s.query_criteria((f'region(circle, icrs, {coo_centre.icrs.ra.deg:.10f} ' - f'{coo_centre.icrs.dec.deg:+.10f}, {rad}m)'), otypes='Star') + warnings.filterwarnings("ignore", category=UserWarning) + results = s.query_criteria( + f"region(circle, icrs, {coo_centre.icrs.ra.deg:.10f} {coo_centre.icrs.dec.deg:+.10f}, {rad}m)", + otypes="Star", + ) if not results: return None, None # Rename columns: - results.rename_column('MAIN_ID', 'main_id') - results.rename_column('RA_d_A_ICRS_J2000', 'ra') - results.rename_column('DEC_d_D_ICRS_2000', 'dec') - results.rename_column('PMRA', 'pmra') - results.rename_column('PMDEC', 'pmdec') - results.rename_column('FLUX_B', 'B_mag') - results.rename_column('FLUX_V', 'V_mag') - results.rename_column('FLUX_R', 'R_mag') - results.rename_column('FLUX_I', 'I_mag') - results.rename_column('FLUX_J', 'J_mag') - results.rename_column('FLUX_H', 'H_mag') - results.rename_column('FLUX_K', 'K_mag') - results.rename_column('FLUX_u', 'u_mag') - results.rename_column('FLUX_g', 'g_mag') - results.rename_column('FLUX_r', 'r_mag') - results.rename_column('FLUX_i', 'i_mag') - results.rename_column('FLUX_z', 'z_mag') - results.rename_column('OTYPE', 'otype') - results.remove_column('SCRIPT_NUMBER_ID') - results.sort(['V_mag', 'B_mag', 'H_mag']) + results.rename_column("MAIN_ID", "main_id") + results.rename_column("RA_d_A_ICRS_J2000", "ra") + results.rename_column("DEC_d_D_ICRS_2000", "dec") + results.rename_column("PMRA", "pmra") + results.rename_column("PMDEC", "pmdec") + results.rename_column("FLUX_B", "B_mag") + results.rename_column("FLUX_V", "V_mag") + results.rename_column("FLUX_R", "R_mag") + results.rename_column("FLUX_I", "I_mag") + results.rename_column("FLUX_J", "J_mag") + results.rename_column("FLUX_H", "H_mag") + results.rename_column("FLUX_K", "K_mag") + results.rename_column("FLUX_u", "u_mag") + results.rename_column("FLUX_g", "g_mag") + results.rename_column("FLUX_r", "r_mag") + results.rename_column("FLUX_i", "i_mag") + results.rename_column("FLUX_z", "z_mag") + results.rename_column("OTYPE", "otype") + results.remove_column("SCRIPT_NUMBER_ID") + results.sort(["V_mag", "B_mag", "H_mag"]) # Filter out object types which shouldn'r really be in there anyway: - indx = (results['otype'] == 'Galaxy') | (results['otype'] == 'LINER') | (results['otype'] == 'SN') + indx = (results["otype"] == "Galaxy") | (results["otype"] == "LINER") | (results["otype"] == "SN") results = results[~indx] if len(results) == 0: @@ -69,20 +73,26 @@ def query_simbad(coo_centre, radius= u.Quantity(24, u.arcmin)) -> tuple[Optional # Build sky coordinates object: simbad = SkyCoord( - ra=results['ra'], - dec=results['dec'], - pm_ra_cosdec=results['pmra'], - pm_dec=results['pmdec'], - frame='icrs', - obstime='J2000') + ra=results["ra"], + dec=results["dec"], + pm_ra_cosdec=results["pmra"], + pm_dec=results["pmdec"], + frame="icrs", + obstime="J2000", + ) return results, simbad def query_2mass_image(ra: float, dec: float, pixels: int = 2500, radius: numeric = 50) -> PrimaryHDU: # ImageHDU qradius: u.Quantity = radius << u.arcmin # type: ignore # Convert to astropy units - out = SkyView.get_images(position='{}, {}'.format(ra, dec), - survey='2MASS-H', pixels=str(pixels), - coordinates='J2000', scaling='Linear', radius=qradius) + out = SkyView.get_images( + position="{}, {}".format(ra, dec), + survey="2MASS-H", + pixels=str(pixels), + coordinates="J2000", + scaling="Linear", + radius=qradius, + ) hdul = out.pop() - return cast(PrimaryHDU, hdul.pop()) + return cast(PrimaryHDU, hdul.pop()) diff --git a/flows_get_brightest/corner.py b/flows_get_brightest/corner.py index fef197d..b15739d 100644 --- a/flows_get_brightest/corner.py +++ b/flows_get_brightest/corner.py @@ -2,8 +2,8 @@ import numpy as np from numpy.typing import NDArray -class Corner: +class Corner: def __init__(self, x: u.Quantity, y: u.Quantity, hw: u.Quantity): self.x = x self.y = y @@ -15,10 +15,14 @@ def set_corners(self) -> tuple[u.Quantity, u.Quantity, u.Quantity, u.Quantity]: """Get corners of a rectangle for a given ra dec and side length :return: list[corner 1, corner 2, ..] """ - return ((self.x - self.hw, self.y - self.hw), (self.x - self.hw, self.y + self.hw), # type: ignore - (self.x + self.hw, self.y + self.hw), (self.x + self.hw, self.y - self.hw)) + return ( + (self.x - self.hw, self.y - self.hw), + (self.x - self.hw, self.y + self.hw), # type: ignore + (self.x + self.hw, self.y + self.hw), + (self.x + self.hw, self.y - self.hw), + ) def process_corner(self) -> NDArray: """Given corners of a rectangle defined as astropy Quantity objects, return it as an np array of floats""" - #_points: list[u.Quantity] = [u.quantity.Quantity(corner) for corner in self.corner_xy] + # _points: list[u.Quantity] = [u.quantity.Quantity(corner) for corner in self.corner_xy] return np.array(self.corner_xy) diff --git a/flows_get_brightest/instruments.py b/flows_get_brightest/instruments.py index 4d88bf0..d49e61a 100644 --- a/flows_get_brightest/instruments.py +++ b/flows_get_brightest/instruments.py @@ -12,6 +12,7 @@ class Instrument(ABC): """Instrument class""" + field_hw: u.Quantity @abstractmethod @@ -38,7 +39,7 @@ def get_regions(self) -> list[regions.RectangleSkyRegion]: @abstractmethod def region_names(self) -> list[str]: pass - + @property @abstractmethod def nregions(self) -> int: @@ -51,13 +52,14 @@ def get_corners(self) -> list[Corner]: class Hawki(Instrument): """Class for storing the hardcoded chip and detector information of a VLT HAWKI pointing""" + # This is the distance to Chip 1 center from Field center: - chip1_center= u.Quantity(2.125, u.arcmin) #3.75 / 2, u.arcmin) + u.Quantity(15, u.arcsecond) + chip1_center = u.Quantity(2.125, u.arcmin) # 3.75 / 2, u.arcmin) + u.Quantity(15, u.arcsecond) field_hw = u.Quantity(7.5, u.arcminute) # full field height width chip1_hw = u.Quantity(3.5, u.arcminute) # chip1 field height width chip1_offset = u.Quantity(112.5, u.arcsecond) # default pointing offset of Hawki. - def __init__(self, coords: SkyCoord, rotation: numeric = u.Quantity(0.0,u.deg)): + def __init__(self, coords: SkyCoord, rotation: numeric = u.Quantity(0.0, u.deg)): # Coordinates self.rotation: u.Quantity = rotation << u.deg # type: ignore self.coords = coords # initial (target) coord @@ -90,8 +92,8 @@ def get_regions(self) -> list[regions.RectangleSkyRegion]: @property def region_names(self) -> list[str]: - return ['HAWK-I', 'chip1'] - + return ["HAWK-I", "chip1"] + @property def nregions(self) -> int: return 2 @@ -101,7 +103,7 @@ def get_corners(self) -> list[Corner]: fieldra, fielddec = self.center_coords.ra, self.center_coords.dec quants = [chip1ra, chip1dec, fieldra, fielddec] if not is_quantity(quants): - raise ValueError(f'chip1_center_coords and center_coords must be SkyCoord with Quantity ra and dec.') + raise ValueError("chip1_center_coords and center_coords must be SkyCoord with Quantity ra and dec.") chip1_corners = Corner(quants[0], quants[1], self.chip1_hw) field_corners = Corner(quants[2], quants[3], self.field_hw) return [field_corners, chip1_corners] @@ -110,29 +112,38 @@ def get_corners(self) -> list[Corner]: def make_region(coords: SkyCoord, width: u.Quantity, height: u.Quantity, angle: u.Quantity): return regions.RectangleSkyRegion(coords, width=width, height=height, angle=angle) - def default_point(self, alpha: u.Quantity = u.Quantity(0.0, u.arcsec), delta: u.Quantity = u.Quantity(0.0, u.arcsec)) -> SkyCoord: - return self.offset(-self.chip1_offset + alpha, -self.chip1_offset + delta) # type: ignore # Hawki_center_coord + def default_point( + self, alpha: u.Quantity = u.Quantity(0.0, u.arcsec), delta: u.Quantity = u.Quantity(0.0, u.arcsec) + ) -> SkyCoord: + return self.offset(-self.chip1_offset + alpha, -self.chip1_offset + delta) # type: ignore # Hawki_center_coord - def point_chip1(self, alpha: u.Quantity = u.Quantity(0.0, u.arcsec), delta: u.Quantity = u.Quantity(0.0, u.arcsec)) -> SkyCoord: + def point_chip1( + self, alpha: u.Quantity = u.Quantity(0.0, u.arcsec), delta: u.Quantity = u.Quantity(0.0, u.arcsec) + ) -> SkyCoord: new_coords = self.chip1_center_coords.spherical_offsets_by( - alpha + 15/2 * u.arcsecond, delta + 15/2 * u.arcsecond) # type: ignore + alpha + 15 / 2 * u.arcsecond, delta + 15 / 2 * u.arcsecond + ) # type: ignore """returns the CCD4 (chip1) ra and dec center given a pointing in ra dec and rotation""" return self.center_coords.directional_offset_by( - self.center_coords.position_angle(new_coords) + self.rotation, # type: ignore - self.center_coords.separation(new_coords)) + self.center_coords.position_angle(new_coords) + self.rotation, # type: ignore + self.center_coords.separation(new_coords), + ) # return self.center_coords.spherical_offsets_by(self.chip1_center, self.chip1_center) @staticmethod def _get_pa_sep(coord1: SkyCoord, coord2: SkyCoord) -> tuple[u.Quantity, u.Quantity]: pa = coord1.position_angle(coord2) - if pa is None: raise ValueError('Position angle is None') + if pa is None: + raise ValueError("Position angle is None") sep = coord1.separation(coord2) return pa, sep + class FixedSizeInstrument(Instrument): """Generic Single field instrument with 7.5 arcminute field for making a finder chart.""" + field_hw = u.Quantity(7.5, u.arcminute) - + def __init__(self, coords: SkyCoord, rotation: numeric = u.Quantity(0.0, u.deg)): # Coordinates self.rotation: u.Quantity = rotation << u.deg # type: ignore @@ -148,20 +159,20 @@ def point(self, target: Target, plan: Plan) -> list[regions.RectangleSkyRegion]: self.center_coords = self.default_point(plan.alpha, plan.delta) self.field_region = self.get_regions() - return [self.field_region] + return self.field_region def offset(self, shifta: Optional[numeric] = 0.0, shiftd: Optional[numeric] = 0.0) -> SkyCoord: shifta = shifta << u.arcsecond # type: ignore shiftd = shiftd << u.arcsecond # type: ignore return self.coords.spherical_offsets_by(shifta, shiftd) - def get_regions(self) -> regions.RectangleSkyRegion: - return self.make_region(self.center_coords, self.field_hw, self.field_hw, self.rotation) + def get_regions(self) -> list[regions.RectangleSkyRegion]: + return [self.make_region(self.center_coords, self.field_hw, self.field_hw, self.rotation)] @property def region_names(self) -> list[str]: - return ['field'] - + return ["field"] + @property def nregions(self) -> int: return 1 @@ -170,13 +181,17 @@ def get_corners(self) -> list[Corner]: fieldra, fielddec = self.center_coords.ra, self.center_coords.dec quants = [fieldra, fielddec] if not is_quantity(quants): - raise ValueError(f'center_coords must be SkyCoord with Quantity ra and dec.') + raise ValueError("center_coords must be SkyCoord with Quantity ra and dec.") field_corners = Corner(quants[0], quants[1], self.field_hw) return [field_corners] @staticmethod - def make_region(coords: SkyCoord, width: u.Quantity, height: u.Quantity, angle: u.Quantity) -> regions.RectangleSkyRegion: + def make_region( + coords: SkyCoord, width: u.Quantity, height: u.Quantity, angle: u.Quantity + ) -> regions.RectangleSkyRegion: return regions.RectangleSkyRegion(coords, width=width, height=height, angle=angle) - def default_point(self, alpha: u.Quantity = u.Quantity(0.0, u.arcsec), delta: u.Quantity = u.Quantity(0.0, u.arcsec)) -> SkyCoord: + def default_point( + self, alpha: u.Quantity = u.Quantity(0.0, u.arcsec), delta: u.Quantity = u.Quantity(0.0, u.arcsec) + ) -> SkyCoord: return self.offset(alpha, delta) diff --git a/flows_get_brightest/observer.py b/flows_get_brightest/observer.py index 7266eb0..900fcf8 100644 --- a/flows_get_brightest/observer.py +++ b/flows_get_brightest/observer.py @@ -12,14 +12,13 @@ from tendrils import api from .instruments import Instrument, Hawki -from .target import Target, Target +from .target import Target from .utils import numeric, tabular from .catalogs import query_2mass_image, query_simbad from .plan import Plan class Observer: - def __init__(self, instrument: Instrument, target: Target, plan: Plan, verbose: bool = False): self.target = target # target info self.plan = plan # Store offsets and rotations. @@ -27,13 +26,15 @@ def __init__(self, instrument: Instrument, target: Target, plan: Plan, verbose: self.regions = self.ins.point(target, self.plan) self.nregions = len(self.regions) # How many sub-regions of important passed by Instrument.? - self.refcat_coords, self.refcat = self._make_refcat_catalog(mask=True, mask_dict={'H_mag': 14.0}) + self.refcat_coords, self.refcat = self._make_refcat_catalog(mask=True, mask_dict={"H_mag": 14.0}) self.simbad_coords, self.simbad = self._make_simbad_catalog() if not verbose: - print((f'Simbad and refcat skyframes are ' - f'equivalent: {self.refcat_coords.frame.is_equivalent_frame(self.simbad_coords.frame)}' - f'. If not, there might be a slight mismatch in alignment in current year.')) + print( + "Simbad and refcat skyframes are " + f"equivalent: {self.refcat_coords.frame.is_equivalent_frame(self.simbad_coords.frame)}" + ". If not, there might be a slight mismatch in alignment in current year." + ) self.wcs = self.get_wcs(self.refcat_coords.frame) def _make_refcat_catalog(self, mask: bool = True, mask_dict: Optional[dict[str, float]] = None) -> tabular: @@ -42,23 +43,27 @@ def _make_refcat_catalog(self, mask: bool = True, mask_dict: Optional[dict[str, masks = [] keys_values = mask_dict.items() for key, value in keys_values: - masks.append(refcat['references'][str(key)] <= float(value)) + masks.append(refcat["references"][str(key)] <= float(value)) if len(masks) == 1: - refcat['references'] = refcat['references'][masks[0]] + refcat["references"] = refcat["references"][masks[0]] else: for msk in masks: - refcat['references'] = refcat['references'][msk] - refcat_coords = SkyCoord(ra=refcat['references']['ra'], dec=refcat['references']['decl'], - pm_ra_cosdec=refcat['references']['pm_ra'], pm_dec=refcat['references']['pm_dec'], - obstime=Time(2015.5, format='decimalyear')) - return refcat_coords, refcat['references'] + refcat["references"] = refcat["references"][msk] + refcat_coords = SkyCoord( + ra=refcat["references"]["ra"], + dec=refcat["references"]["decl"], + pm_ra_cosdec=refcat["references"]["pm_ra"], + pm_dec=refcat["references"]["pm_dec"], + obstime=Time(2015.5, format="decimalyear"), + ) + return refcat_coords, refcat["references"] def _make_simbad_catalog(self) -> tabular: simbad, coords = query_simbad(self.target.coords) if simbad is None or coords is None: - raise ValueError('No Simbad catalog found for target.') + raise ValueError("No Simbad catalog found for target.") # propagate Simbad catalog coords to refcat reference year - simbad_coords = coords.apply_space_motion(new_obstime=Time(2015.5, format='decimalyear')) + simbad_coords = coords.apply_space_motion(new_obstime=Time(2015.5, format="decimalyear")) return simbad_coords, simbad def get_wcs(self, frame: Optional[object] = None, header: Optional[object] = None) -> WCS: @@ -86,26 +91,28 @@ def check_bright_stars(self, region: regions.RectangleSkyRegion, wcs: Optional[W simbad_stars: NDArray[np.bool_] = region.contains(self.simbad_coords, wcs) catalog_stars: NDArray[np.bool_] = region.contains(self.refcat_coords, wcs) - simbad_mag: NDArray[np.float_] = self.simbad[simbad_stars]['H_mag'].data # type: ignore - refcat_mag: NDArray[np.float_] = self.refcat[catalog_stars]['H_mag'].data # type: ignore - bright_stars = np.hstack((simbad_mag, refcat_mag)) + simbad_mag: NDArray[np.float_] = self.simbad[simbad_stars]["H_mag"].data # type: ignore + refcat_mag: NDArray[np.float_] = self.refcat[catalog_stars]["H_mag"].data # type: ignore + bright_stars = np.hstack((simbad_mag, refcat_mag)) if np.ma.isMaskedArray(bright_stars): bright_stars: NDArray[np.float_] = bright_stars.data[~np.isnan(bright_stars.data)] # type: ignore - print('Brightest star has H-mag = {0:.1f}'.format(np.round(bright_stars.min(), 1))) + print("Brightest star has H-mag = {0:.1f}".format(np.round(bright_stars.min(), 1))) return bright_stars -def get_flows_observer(rot: numeric, tid: Union[int, str], shifta: numeric, shiftd: numeric, instrument: type[Instrument] = Hawki) -> Observer: +def get_flows_observer( + rot: numeric, tid: Union[int, str], shifta: numeric, shiftd: numeric, instrument: type[Instrument] = Hawki +) -> Observer: """ Returns the H-mag of the brightest star in the given region. """ # Get query flows database target_info = api.get_target(tid) - target_info['skycoord'] = SkyCoord(target_info['ra'] * u.deg, target_info['decl'] * u.deg) + target_info["skycoord"] = SkyCoord(target_info["ra"] * u.deg, target_info["decl"] * u.deg) # Create Observer - target = Target(tid, target_info['ra'], target_info['decl'], target_info['skycoord'], target_info) + target = Target(tid, target_info["ra"], target_info["decl"], target_info["skycoord"], target_info) plan = Plan.from_numeric(rot, shifta, shiftd) hawki = instrument(target.coords) return Observer(hawki, target, plan) diff --git a/flows_get_brightest/parser.py b/flows_get_brightest/parser.py index 3524436..fe14302 100644 --- a/flows_get_brightest/parser.py +++ b/flows_get_brightest/parser.py @@ -2,30 +2,45 @@ import astropy.units as u from .instruments import Hawki, FixedSizeInstrument, Instrument + def parse() -> tuple[float, int | str, float, float, bool, type[Instrument]]: - """Parse command line input to get target, position angle (rotate), alpha and delta offsets (shifta, shiftd) - """ - parser = argparse.ArgumentParser(description='Calculate Brightest Star') - parser.add_argument('-t', '--target', help="calculate for this targetname or targetid", type=str, default='None', - action='store') - parser.add_argument('-r', '--rotate', help='rotation angle in degrees', type=float, default=0.0, action='store') - parser.add_argument('-a', '--shifta', help='shift alpha in arcsec', type=float, default=0.0, action='store') - parser.add_argument('-d', '--shiftd', help='shift delta in arcsec', type=float, default=0.0, action='store') - parser.add_argument('-p', '--plot', help='whether to query images and plot', action='store_true') - parser.add_argument('-i', '--instrument', help='instrument name', choices=['Hawki', 'FixedSize'], type=str, default='Hawki', action='store') - parser.add_argument('--size', help='Instrument FoV in arcmin (if using FixedSize instrument), finder chart will be roughly twice the size.', type=float, default=7.5, action='store') + """Parse command line input to get target, position angle (rotate), alpha and delta offsets (shifta, shiftd)""" + parser = argparse.ArgumentParser(description="Calculate Brightest Star") + parser.add_argument( + "-t", "--target", help="calculate for this targetname or targetid", type=str, default="None", action="store" + ) + parser.add_argument("-r", "--rotate", help="rotation angle in degrees", type=float, default=0.0, action="store") + parser.add_argument("-a", "--shifta", help="shift alpha in arcsec", type=float, default=0.0, action="store") + parser.add_argument("-d", "--shiftd", help="shift delta in arcsec", type=float, default=0.0, action="store") + parser.add_argument("-p", "--plot", help="whether to query images and plot", action="store_true") + parser.add_argument( + "-i", + "--instrument", + help="instrument name", + choices=["Hawki", "FixedSize"], + type=str, + default="Hawki", + action="store", + ) + parser.add_argument( + "--size", + help="Instrument FoV in arcmin (if using FixedSize instrument), finder chart will be roughly twice the size.", + type=float, + default=7.5, + action="store", + ) args = parser.parse_args() - if args.target == 'None': - parser.error('target id or name not provided, use -t or ') + if args.target == "None": + parser.error("target id or name not provided, use -t or ") elif args.target.isnumeric(): args.target = int(args.target) - - if args.instrument not in ['Hawki', 'FixedSize']: - raise ValueError(f'Instrument {args.instrument} not supported, use Hawki or FixedSize') - instrument = Hawki - if args.instrument == 'FixedSize': + + if args.instrument not in ["Hawki", "FixedSize"]: + raise ValueError(f"Instrument {args.instrument} not supported, use Hawki or FixedSize") + instrument: type[Instrument] = Hawki + if args.instrument == "FixedSize": instrument = FixedSizeInstrument instrument.field_hw = args.size << u.arcmin - - return args.rotate, args.target, args.shifta, args.shiftd, args.plot, instrument \ No newline at end of file + + return args.rotate, args.target, args.shifta, args.shiftd, args.plot, instrument diff --git a/flows_get_brightest/plan.py b/flows_get_brightest/plan.py index 00aa9f9..998d910 100644 --- a/flows_get_brightest/plan.py +++ b/flows_get_brightest/plan.py @@ -1,9 +1,9 @@ from dataclasses import dataclass -from typing import Any, TypeGuard import numpy as np import astropy.units as u from .utils import numeric + @dataclass class Plan: rotation: u.Quantity = u.Quantity(0, u.deg) @@ -30,19 +30,18 @@ def set_shift(self) -> bool: # self.alpha = self.alpha << u.arcsec # type: ignore # self.delta = self.delta << u.arcsec # type: ignore # self.rotation = self.rotation << u.deg # type: ignore - + @classmethod def from_numeric(cls, rotation: numeric, alpha: numeric, delta: numeric) -> "Plan": - return cls(rotation=rotation << u.deg, alpha=alpha << u.arcsec, delta=delta << u.arcsec) # type: ignore - + return cls(rotation=rotation << u.deg, alpha=alpha << u.arcsec, delta=delta << u.arcsec) # type: ignore + # def finalize(self) -> FinalizedPlan: # if self._finalized(self): # return FinalizedPlan(self.rotation, self.alpha, self.delta, self.rotate, self.shift) # raise ValueError('Plan not finalized, attributes must be quantites.') - + # @staticmethod # def _finalized(p: Any) -> TypeGuard[FinalizedPlan]: # if isinstance(p.rotation, u.Quantity) and isinstance(p.alpha, u.Quantity) and isinstance(p.delta, u.Quantity): # return True # return False - \ No newline at end of file diff --git a/flows_get_brightest/plots.py b/flows_get_brightest/plots.py index 7327f97..d434995 100644 --- a/flows_get_brightest/plots.py +++ b/flows_get_brightest/plots.py @@ -3,11 +3,11 @@ from typing import cast from dataclasses import dataclass import astropy.visualization as viz -import matplotlib -#from matplotlib.markers import MarkerStyle +from matplotlib.colors import Normalize from matplotlib.axes import Axes import matplotlib.pyplot as plt import numpy as np +from numpy.typing import NDArray from astropy.visualization import ZScaleInterval from astropy.io.fits import Header, PrimaryHDU from matplotlib.ticker import MaxNLocator @@ -18,16 +18,16 @@ @dataclass class Image: - data: np.ndarray + data: NDArray[np.float64] header: Header - + @classmethod def fromHDU(cls, hdu: PrimaryHDU) -> "Image": """Create Image from PrimaryHDU""" if hdu.data is None: - raise ValueError('HDU has no data.') + raise ValueError("HDU has no data.") return cls(data=cast(np.ndarray, hdu.data), header=hdu.header) - + class Plotter: """ @@ -41,34 +41,53 @@ def plot(self) -> None: """not implemented yet""" pass - def make_finding_chart(self, plot_refcat: bool = True, plot_simbad: bool = True, - savefig: bool = True, radius: numeric = 14) -> Axes: + def make_finding_chart( + self, plot_refcat: bool = True, plot_simbad: bool = True, savefig: bool = True, radius: numeric = 14 + ) -> Axes: """Make finding chart for a given observation.""" obs = self.obs - image = obs.get_image(radius=radius) + imagehdu = obs.get_image(radius=radius) zscale = ZScaleInterval() - image = Image.fromHDU(image) + image = Image.fromHDU(imagehdu) vmin, vmax = zscale.get_limits(image.data.flat) obs.wcs = obs.get_wcs(header=image.header) regions = obs.regions_to_physical() - fig, ax = plt.subplots(figsize=(10, 10), subplot_kw={'projection': obs.wcs}) + fig, ax = plt.subplots(figsize=(10, 10), subplot_kw={"projection": obs.wcs}) for i, region in enumerate(regions): - region.plot(ax=ax, edgecolor='cyan', linestyle='-.', label=obs.ins.region_names[i]) + region.plot(ax=ax, edgecolor="cyan", linestyle="-.", label=obs.ins.region_names[i]) - self.plot_image(image.data, ax=ax, cmap='viridis', scale='linear', vmin=vmin, vmax=vmax) + self.plot_image(image.data, ax=ax, cmap="viridis", scale="linear", vmin=vmin, vmax=vmax) tar_pix = obs.wcs.all_world2pix(obs.target.ra, obs.target.dec, 0) - ax.scatter(tar_pix[0], tar_pix[1], marker='*', s=250, label='SN', color='orange') + ax.scatter(tar_pix[0], tar_pix[1], marker="*", s=250, label="SN", color="orange") if plot_refcat: refcat_stars = obs.refcat_coords.to_pixel(obs.wcs) - ax.scatter(refcat_stars[0], refcat_stars[1], facecolors='none', edgecolors='red', zorder=4, alpha=0.8, - marker="o", s=100, label='Refcat2') + ax.scatter( + refcat_stars[0], + refcat_stars[1], + facecolors="none", + edgecolors="red", + zorder=4, + alpha=0.8, + marker="o", + s=100, + label="Refcat2", + ) if plot_simbad: simbad_stars = obs.simbad_coords.to_pixel(obs.wcs) - ax.scatter(simbad_stars[0], simbad_stars[1], facecolors='none', edgecolors='orange', zorder=5, alpha=0.8, - marker='o', s=100, label='Simbad') + ax.scatter( + simbad_stars[0], + simbad_stars[1], + facecolors="none", + edgecolors="orange", + zorder=5, + alpha=0.8, + marker="o", + s=100, + label="Simbad", + ) ax.legend(fontsize=15) ax.set_title(f"{obs.target.info['target_name']} {obs.ins.__class__.__name__} FC") @@ -79,9 +98,28 @@ def make_finding_chart(self, plot_refcat: bool = True, plot_simbad: bool = True, # Copied from flows image plotter. @staticmethod - def plot_image(image, ax=None, scale='log', cmap=None, origin='lower', xlabel=None, ylabel=None, cbar=None, - clabel='Flux ($e^{-}s^{-1}$)', cbar_ticks=None, cbar_ticklabels=None, cbar_pad=None, cbar_size='4%', - title=None, percentile=95.0, vmin=None, vmax=None, offset_axes=None, color_bad='k', **kwargs): + def plot_image( # noqa: C901 (ignore complexity) # Imported wholesale from flows, not worth refactoring. + image, + ax=None, + scale="log", + cmap=None, + origin="lower", + xlabel=None, + ylabel=None, + cbar=None, + clabel="Flux ($e^{-}s^{-1}$)", + cbar_ticks=None, + cbar_ticklabels=None, + cbar_pad=None, + cbar_size="4%", + title=None, + percentile=95.0, + vmin=None, + vmax=None, + offset_axes=None, + color_bad="k", + **kwargs, + ): """ Utility function to plot a 2D image. Parameters: @@ -122,18 +160,22 @@ def plot_image(image, ax=None, scale='log', cmap=None, origin='lower', xlabel=No logger = logging.getLogger(__name__) # Backward compatible settings: - make_cbar = kwargs.pop('make_cbar', None) + make_cbar = kwargs.pop("make_cbar", None) if make_cbar: raise FutureWarning("'make_cbar' is deprecated. Use 'cbar' instead.") if not cbar: cbar = make_cbar # Special treatment for boolean arrays: - if isinstance(image, np.ndarray) and image.dtype == 'bool': - if vmin is None: vmin = 0 - if vmax is None: vmax = 1 - if cbar_ticks is None: cbar_ticks = [0, 1] - if cbar_ticklabels is None: cbar_ticklabels = ['False', 'True'] + if isinstance(image, np.ndarray) and image.dtype == "bool": + if vmin is None: + vmin = 0 + if vmax is None: + vmax = 1 + if cbar_ticks is None: + cbar_ticks = [0, 1] + if cbar_ticklabels is None: + cbar_ticklabels = ["False", "True"] # Calculate limits of color scaling: interval = None @@ -152,36 +194,42 @@ def plot_image(image, ax=None, scale='log', cmap=None, origin='lower', xlabel=No interval = viz.PercentileInterval(percentile) # Create ImageNormalize object with extracted limits: - if scale in ('log', 'linear', 'sqrt', 'asinh', 'histeq', 'sinh', 'squared'): - if scale == 'log': + if scale in ("log", "linear", "sqrt", "asinh", "histeq", "sinh", "squared"): + stretch: viz.BaseStretch = viz.LinearStretch() + if scale == "log": stretch = viz.LogStretch() - elif scale == 'linear': + elif scale == "linear": stretch = viz.LinearStretch() - elif scale == 'sqrt': + elif scale == "sqrt": stretch = viz.SqrtStretch() - elif scale == 'asinh': + elif scale == "asinh": stretch = viz.AsinhStretch() - elif scale == 'histeq': + elif scale == "histeq": stretch = viz.HistEqStretch(image[np.isfinite(image)]) - elif scale == 'sinh': + elif scale == "sinh": stretch = viz.SinhStretch() - elif scale == 'squared': + elif scale == "squared": stretch = viz.SquaredStretch() - else: - stretch = viz.LinearStretch() # Create ImageNormalize object. Very important to use clip=False here, otherwise # NaN points will not be plotted correctly. - norm = viz.ImageNormalize(data=image, interval=interval, vmin=vmin, vmax=vmax, stretch=stretch, clip=False) # type: ignore + norm: viz.ImageNormalize | Normalize + norm = viz.ImageNormalize( + data=image, interval=interval, vmin=vmin, vmax=vmax, stretch=stretch, clip=False + ) # type: ignore - elif isinstance(scale, (viz.ImageNormalize, matplotlib.colors.Normalize)): + elif isinstance(scale, (viz.ImageNormalize, Normalize)): norm = scale else: raise ValueError("scale {} is not available.".format(scale)) if offset_axes: - extent = (offset_axes[0] - 0.5, offset_axes[0] + image.shape[1] - 0.5, offset_axes[1] - 0.5, - offset_axes[1] + image.shape[0] - 0.5) + extent = ( + offset_axes[0] - 0.5, + offset_axes[0] + image.shape[1] - 0.5, + offset_axes[1] - 0.5, + offset_axes[1] + image.shape[0] - 0.5, + ) else: extent = (-0.5, image.shape[1] - 0.5, -0.5, image.shape[0] - 0.5) @@ -191,14 +239,14 @@ def plot_image(image, ax=None, scale='log', cmap=None, origin='lower', xlabel=No # Set up the colormap to use. If a bad color is defined, # add it to the colormap: if cmap is None: - cmap = copy.copy(plt.get_cmap('Blues')) # type: ignore + cmap = copy.copy(plt.get_cmap("Blues")) # type: ignore elif isinstance(cmap, str): cmap = copy.copy(plt.get_cmap(cmap)) # type: ignore if color_bad: cmap.set_bad(color_bad, 1.0) - im = ax.imshow(image, cmap=cmap, norm=norm, origin=origin, extent=extent, interpolation='nearest', **kwargs) + im = ax.imshow(image, cmap=cmap, norm=norm, origin=origin, extent=extent, interpolation="nearest", **kwargs) if xlabel is not None: ax.set_xlabel(xlabel) if ylabel is not None: @@ -211,31 +259,31 @@ def plot_image(image, ax=None, scale='log', cmap=None, origin='lower', xlabel=No if cbar: fig = ax.figure divider = make_axes_locatable(ax) - if cbar == 'top': + if cbar == "top": cbar_pad = 0.05 if cbar_pad is None else cbar_pad - cax = divider.append_axes('top', size=cbar_size, pad=cbar_pad) - orientation = 'horizontal' - elif cbar == 'bottom': + cax = divider.append_axes("top", size=cbar_size, pad=cbar_pad) + orientation = "horizontal" + elif cbar == "bottom": cbar_pad = 0.35 if cbar_pad is None else cbar_pad - cax = divider.append_axes('bottom', size=cbar_size, pad=cbar_pad) - orientation = 'horizontal' - elif cbar == 'left': + cax = divider.append_axes("bottom", size=cbar_size, pad=cbar_pad) + orientation = "horizontal" + elif cbar == "left": cbar_pad = 0.35 if cbar_pad is None else cbar_pad - cax = divider.append_axes('left', size=cbar_size, pad=cbar_pad) - orientation = 'vertical' + cax = divider.append_axes("left", size=cbar_size, pad=cbar_pad) + orientation = "vertical" else: cbar_pad = 0.05 if cbar_pad is None else cbar_pad - cax = divider.append_axes('right', size=cbar_size, pad=cbar_pad) - orientation = 'vertical' + cax = divider.append_axes("right", size=cbar_size, pad=cbar_pad) + orientation = "vertical" cb = fig.colorbar(im, cax=cax, orientation=orientation) - if cbar == 'top': - cax.xaxis.set_ticks_position('top') - cax.xaxis.set_label_position('top') - elif cbar == 'left': - cax.yaxis.set_ticks_position('left') - cax.yaxis.set_label_position('left') + if cbar == "top": + cax.xaxis.set_ticks_position("top") + cax.xaxis.set_label_position("top") + elif cbar == "left": + cax.yaxis.set_ticks_position("left") + cax.yaxis.set_label_position("left") if clabel is not None: cb.set_label(clabel) @@ -246,7 +294,7 @@ def plot_image(image, ax=None, scale='log', cmap=None, origin='lower', xlabel=No # cax.yaxis.set_major_locator(matplotlib.ticker.AutoLocator()) # cax.yaxis.set_minor_locator(matplotlib.ticker.AutoLocator()) - cax.tick_params(which='both', direction='out', pad=5) + cax.tick_params(which="both", direction="out", pad=5) # Settings for ticks: integer_locator = MaxNLocator(nbins=10, integer=True) @@ -254,7 +302,7 @@ def plot_image(image, ax=None, scale='log', cmap=None, origin='lower', xlabel=No ax.xaxis.set_minor_locator(integer_locator) ax.yaxis.set_major_locator(integer_locator) ax.yaxis.set_minor_locator(integer_locator) - ax.tick_params(which='both', direction='out', pad=5) + ax.tick_params(which="both", direction="out", pad=5) ax.xaxis.tick_bottom() ax.yaxis.tick_left() diff --git a/flows_get_brightest/run_get_brightest.py b/flows_get_brightest/run_get_brightest.py index 4aba128..75f12b1 100644 --- a/flows_get_brightest/run_get_brightest.py +++ b/flows_get_brightest/run_get_brightest.py @@ -1,4 +1,5 @@ from __future__ import annotations +from typing import cast import warnings from erfa import ErfaWarning from .plots import Plotter @@ -6,9 +7,10 @@ from .observer import get_flows_observer from .parser import parse + # Most useless warnings ever spammed for every operation by this package! -warnings.filterwarnings('ignore', category=ErfaWarning, append=True) -warnings.filterwarnings('ignore', message='invalid value', category=RuntimeWarning, append=True) +warnings.filterwarnings("ignore", category=ErfaWarning, append=True) +warnings.filterwarnings("ignore", message="invalid value", category=RuntimeWarning, append=True) def main(): @@ -23,9 +25,10 @@ def main(): obs.check_bright_stars(region=obs.regions[0]) # Make finding chart if requested + radius = cast(float, inst.field_hw.value) * 2 if make_fc: - Plotter(obs).make_finding_chart(radius=inst.field_hw.value*2) + Plotter(obs).make_finding_chart(radius=radius) -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/flows_get_brightest/target.py b/flows_get_brightest/target.py index cd9de86..0eb0a42 100644 --- a/flows_get_brightest/target.py +++ b/flows_get_brightest/target.py @@ -3,6 +3,7 @@ from .utils import MISSING_COORDS from astropy.coordinates import SkyCoord + @dataclass class Target: tid: int | str # target id @@ -15,19 +16,18 @@ class Target: def __post_init__(self) -> None: if self.coords is MISSING_COORDS or self.coords is None: - c = SkyCoord(self.ra << u.deg, self.dec << u.deg, frame='icrs') # type: ignore - self.coords = c + c = SkyCoord(self.ra << u.deg, self.dec << u.deg, frame="icrs") # type: ignore + self.coords = c if self.name == "UNKNOWN": - self.name = self.info.get('target_name', f"Target {self.tid}") + self.name = self.info.get("target_name", f"Target {self.tid}") if isinstance(self.tid, str): if self.tid.isnumeric(): self.tid = int(self.tid) else: - tid = self.info.get('target_id', None) + tid = self.info.get("target_id", None) if tid: self.tid = int(tid) - + self.ra = float(self.coords.ra.deg) # type: ignore self.deg = float(self.coords.dec.deg) # type: ignore self.loaded = True - \ No newline at end of file diff --git a/flows_get_brightest/tests.py b/flows_get_brightest/tests.py index 9e9eeee..0df3cfc 100644 --- a/flows_get_brightest/tests.py +++ b/flows_get_brightest/tests.py @@ -6,7 +6,7 @@ from .auth import test_connection from .plots import Plotter from .utils import api_token -from .instruments import Hawki, Instrument, FixedSizeInstrument +from .instruments import Hawki, FixedSizeInstrument rot, tid, shifta, shiftd = 30, 8, 10, 10 token = api_token() @@ -18,22 +18,26 @@ def test_auth(monkeypatch): Test the auth module. """ with pytest.warns(RuntimeWarning): - monkeypatch.setattr('builtins.input', lambda _: 'bad_token') + monkeypatch.setattr("builtins.input", lambda _: "bad_token") test_connection() + @pytest.fixture def fixedinstrument_obs() -> Observer: return get_flows_observer(rot, tid, shifta, shiftd, instrument=FixedSizeInstrument) + @pytest.fixture def Hawki_obs() -> Observer: return get_flows_observer(rot, tid, shifta, shiftd, instrument=Hawki) + @pytest.fixture def observer(request) -> Observer: return request.getfixturevalue(request.param) -@pytest.mark.parametrize('observer', ['fixedinstrument_obs', 'Hawki_obs'], indirect=True) + +@pytest.mark.parametrize("observer", ["fixedinstrument_obs", "Hawki_obs"], indirect=True) def test_get_brightest(capsys, observer): observer.check_bright_stars(region=observer.regions[0]) captured = capsys.readouterr() @@ -41,7 +45,8 @@ def test_get_brightest(capsys, observer): sys.stdout.write(captured.out) sys.stderr.write(captured.err) -@pytest.mark.parametrize('observer', ['fixedinstrument_obs', 'Hawki_obs'], indirect=True) + +@pytest.mark.parametrize("observer", ["fixedinstrument_obs", "Hawki_obs"], indirect=True) def test_plan(observer): assert observer.plan.rotation == rot * u.deg # type: ignore assert observer.plan.alpha == shifta * u.arcsec # type: ignore @@ -49,16 +54,18 @@ def test_plan(observer): assert observer.plan.shift is True assert observer.plan.rotate is True -@pytest.mark.parametrize('observer', ['fixedinstrument_obs', 'Hawki_obs'], indirect=True) + +@pytest.mark.parametrize("observer", ["fixedinstrument_obs", "Hawki_obs"], indirect=True) def test_observer(observer): isinstance(observer, Observer) @pytest.mark.slow -@pytest.mark.parametrize('observer', ['fixedinstrument_obs', 'Hawki_obs'], indirect=True) +@pytest.mark.parametrize("observer", ["fixedinstrument_obs", "Hawki_obs"], indirect=True) def test_make_finding_chart(observer, monkeypatch): import matplotlib.pyplot as plt - monkeypatch.setattr(plt, 'show', lambda: None) + + monkeypatch.setattr(plt, "show", lambda: None) plotter = Plotter(observer) ax = plotter.make_finding_chart(observer, savefig=False) assert len(ax.get_images()) > 0 @@ -67,25 +74,24 @@ def test_make_finding_chart(observer, monkeypatch): assert title.endswith("FC") -## End to end test with Hawki. +# End to end test with Hawki. ARGS0 = (0, 8, 0, 0, False, 12.2) ARGS1 = (30, 8, 0, 0, False, 11.5) ARGS2 = (30, 8, -50, 100, False, 12.3) + @pytest.mark.slow @pytest.mark.parametrize("args", [ARGS0, ARGS1, ARGS2]) def test_end_to_end(args: tuple[int, int | str, int, int, bool, float]) -> None: - rot, tid, shifta, shiftd, make_fc , brightest = args + rot, tid, shifta, shiftd, make_fc, brightest = args # Print brightest star in field obs = get_flows_observer(rot, tid, shifta, shiftd) stars = obs.check_bright_stars(region=obs.regions[0]) assert pytest.approx(np.round(stars.min(), 1)) == brightest - - + # Make finding chart if requested if make_fc: plotter = Plotter(obs) assert plotter.obs == obs - \ No newline at end of file diff --git a/flows_get_brightest/utils.py b/flows_get_brightest/utils.py index e9e6ec3..733decd 100644 --- a/flows_get_brightest/utils.py +++ b/flows_get_brightest/utils.py @@ -1,5 +1,4 @@ import os -import argparse from typing import Any, Union, TypeGuard, TypedDict import astropy.units as u from astropy.coordinates import SkyCoord @@ -9,29 +8,35 @@ # custom types numeric = Union[float, int, u.Quantity] tabular = tuple[SkyCoord, Table] -flows_args = TypedDict('args', {'rotate': float, 'target': Union[str, int], 'shifta': float, 'shiftd': float, 'plot': bool}) +flows_args = TypedDict( + "flows_args", {"rotate": float, "target": Union[str, int], "shifta": float, "shiftd": float, "plot": bool} +) + class MissingCoords(SkyCoord): def __init__(self): - super().__init__(u.Quantity(0, u.deg), u.Quantity(0, u.deg), frame='icrs') + super().__init__(u.Quantity(0, u.deg), u.Quantity(0, u.deg), frame="icrs") + + MISSING_COORDS = MissingCoords() + def api_token() -> str: """Try to get the API token from environment variable or from tendrils config.ini""" - token = str(os.environ.get('FLOWS_API_TOKEN')) - if token is not None and token != 'None': + token = str(os.environ.get("FLOWS_API_TOKEN", None)) + if token != "None": tendrils.utils.set_api_token(token=token, overwrite=True) return token cfg = tendrils.utils.load_config() - token = cfg.get('api', 'token', fallback='None') - if token.lower() in ['', 'none', 'bad', 'bad_token', 'badtoken']: - token = None + token = cfg.get("api", "token", fallback="None") + if token.lower() in ["", "none", "bad", "bad_token", "badtoken"]: + token = "None" else: tendrils.utils.set_api_token(token=token, overwrite=True) - if isinstance(token, str): - return token - raise TypeError(f'API token is of type {type(token)} instead of string') + if token == "None": + raise AttributeError("API token is not set. Please set it in the config file or as an environment variable.") + return token def is_quantity(qt: list[Any]) -> TypeGuard[list[u.Quantity]]: @@ -41,6 +46,6 @@ def is_quantity(qt: list[Any]) -> TypeGuard[list[u.Quantity]]: return True -if __name__ == '__main__': +if __name__ == "__main__": token = api_token() - tendrils.utils.set_api_token('None') \ No newline at end of file + tendrils.utils.set_api_token("None") diff --git a/pyproject.toml b/pyproject.toml index 21b4122..d47f64f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -26,7 +26,13 @@ Home = "https://github.com/SNflows/flows-tools/" get_brightest = "flows_get_brightest:main" [project.optional-dependencies] -test = ["pytest >= 7.1.1"] +test = [ + "pytest >= 7.1.1", + "pytest-cov >= 4.0.0", + "mypy >= 0.991", + "flake8 >= 5.0.8", + "black >= 21.10.0", + ] [tool.pytest.ini_options] minversion = "7.1.1" @@ -56,4 +62,31 @@ exclude = ''' | LICENSE )/ ) -''' \ No newline at end of file +''' + +[tool.mypy] +exclude = 'mpl_toolkits' +implicit_reexport = true + +[[tool.mypy.overrides]] +module = [ + 'astroquery.logger', + 'astropy.*', + 'mpl_toolkits.*', + 'erfa.*', + 'matplotlib.colors.*', + 'matplotlib.ticker.*', + 'matplotlib.transforms.*', + 'matplotlib._mathtext.*', + 'matplotlib.layout_engine.*', + 'matplotlib.text.*', + 'matplotlib.textpath.*', + 'matplotlib.image.*', + 'matplotlib.patches.*', + 'matplotlib.offsetbox.*', + 'matplotlib.legend.*', +] +ignore_missing_imports = true +ignore_errors = true +allow_untyped_globals = true +implicit_reexport = true \ No newline at end of file diff --git a/typings/astropy/__init__.pyi b/typings/astropy/__init__.pyi new file mode 100644 index 0000000..f89914f --- /dev/null +++ b/typings/astropy/__init__.pyi @@ -0,0 +1,87 @@ +""" +This type stub file was generated by pyright. +""" + +import os +import sys +from .version import version as __version__ +from . import config as _config +from .utils.state import ScienceState +from .tests.runner import TestRunner +from .logger import _init_log, _teardown_log +from .utils.misc import find_api_page +from types import ModuleType as __module_type__ +def __getattr__(name: str) -> Any: ... +""" +Astropy is a package intended to contain core functionality and some +common tools needed for performing astronomy and astrophysics research with +Python. It also provides an index for other astronomy packages and tools for +managing them. +""" +if 'dev' in __version__: + online_docs_root = ... +else: + online_docs_root = ... +class Conf(_config.ConfigNamespace): + """ + Configuration parameters for `astropy`. + """ + unicode_output = ... + use_color = ... + max_lines = ... + max_width = ... + + +conf = ... +class base_constants_version(ScienceState): + """ + Base class for the real version-setters below + """ + _value = ... + _versions = ... + @classmethod + def validate(cls, value): # -> str: + ... + + @classmethod + def set(cls, value): # -> _ScienceStateContext: + """ + Set the current constants value. + """ + ... + + + +class physical_constants(base_constants_version): + """ + The version of physical constants to use + """ + _value = ... + _versions = ... + + +class astronomical_constants(base_constants_version): + """ + The version of astronomical constants to use + """ + _value = ... + _versions = ... + + +test = ... +__citation__ = ... +log = ... +def online_help(query): # -> None: + """ + Search the online Astropy documentation for the given query. + Opens the results in the default web browser. Requires an active + Internet connection. + + Parameters + ---------- + query : str + The search query. + """ + ... + +__dir_inc__ = ... diff --git a/typings/astropy/_erfa/__init__.pyi b/typings/astropy/_erfa/__init__.pyi new file mode 100644 index 0000000..4ace61a --- /dev/null +++ b/typings/astropy/_erfa/__init__.pyi @@ -0,0 +1,11 @@ +""" +This type stub file was generated by pyright. +""" + +import warnings +from erfa import core, helpers, ufunc +from erfa.core import * +from erfa.helpers import leap_seconds +from erfa.ufunc import dt_dmsf, dt_eraASTROM, dt_eraLDBODY, dt_eraLEAPSECOND, dt_hmsf, dt_pv, dt_sign, dt_type, dt_ymdf +from astropy.utils.exceptions import AstropyDeprecationWarning + diff --git a/typings/astropy/_version.pyi b/typings/astropy/_version.pyi new file mode 100644 index 0000000..da17a73 --- /dev/null +++ b/typings/astropy/_version.pyi @@ -0,0 +1,6 @@ +""" +This type stub file was generated by pyright. +""" + +__version__ = ... +__version_tuple__ = ... diff --git a/typings/astropy/config/__init__.pyi b/typings/astropy/config/__init__.pyi new file mode 100644 index 0000000..5d81d62 --- /dev/null +++ b/typings/astropy/config/__init__.pyi @@ -0,0 +1,13 @@ +""" +This type stub file was generated by pyright. +""" + +from .paths import * +from .configuration import * +from .affiliated import * + +""" +This module contains configuration and setup utilities for the +Astropy project. This includes all functionality related to the +affiliated package index. +""" diff --git a/typings/astropy/config/affiliated.pyi b/typings/astropy/config/affiliated.pyi new file mode 100644 index 0000000..a7d7854 --- /dev/null +++ b/typings/astropy/config/affiliated.pyi @@ -0,0 +1,8 @@ +""" +This type stub file was generated by pyright. +""" + +"""This module contains functions and classes for finding information about +affiliated packages and installing them. +""" +__all__ = [] diff --git a/typings/astropy/config/configuration.pyi b/typings/astropy/config/configuration.pyi new file mode 100644 index 0000000..b811e2a --- /dev/null +++ b/typings/astropy/config/configuration.pyi @@ -0,0 +1,428 @@ +""" +This type stub file was generated by pyright. +""" + +from contextlib import contextmanager +from astropy.utils.decorators import deprecated +from astropy.utils.exceptions import AstropyWarning + +"""This module contains classes and functions to standardize access to +configuration files for Astropy and affiliated packages. + +.. note:: + The configuration system makes use of the 'configobj' package, which stores + configuration in a text format like that used in the standard library + `ConfigParser`. More information and documentation for configobj can be + found at https://configobj.readthedocs.io . +""" +__all__ = ('InvalidConfigurationItemWarning', 'ConfigurationMissingWarning', 'get_config', 'reload_config', 'ConfigNamespace', 'ConfigItem', 'generate_config', 'create_config_file') +class InvalidConfigurationItemWarning(AstropyWarning): + """ A Warning that is issued when the configuration value specified in the + astropy configuration file does not match the type expected for that + configuration value. + """ + ... + + +@deprecated('5.0') +class ConfigurationMissingWarning(AstropyWarning): + """ A Warning that is issued when the configuration directory cannot be + accessed (usually due to a permissions problem). If this warning appears, + configuration items will be set to their defaults rather than read from the + configuration file, and no configuration will persist across sessions. + """ + ... + + +class ConfigurationDefaultMissingError(ValueError): + """ An exception that is raised when the configuration defaults (which + should be generated at build-time) are missing. + """ + ... + + +class ConfigurationDefaultMissingWarning(AstropyWarning): + """ A warning that is issued when the configuration defaults (which + should be generated at build-time) are missing. + """ + ... + + +class ConfigurationChangedWarning(AstropyWarning): + """ + A warning that the configuration options have changed. + """ + ... + + +class _ConfigNamespaceMeta(type): + def __init__(cls, name, bases, dict) -> None: + ... + + + +class ConfigNamespace(metaclass=_ConfigNamespaceMeta): + """ + A namespace of configuration items. Each subpackage with + configuration items should define a subclass of this class, + containing `ConfigItem` instances as members. + + For example:: + + class Conf(_config.ConfigNamespace): + unicode_output = _config.ConfigItem( + False, + 'Use Unicode characters when outputting values, ...') + use_color = _config.ConfigItem( + sys.platform != 'win32', + 'When True, use ANSI color escape sequences when ...', + aliases=['astropy.utils.console.USE_COLOR']) + conf = Conf() + """ + def __iter__(self): # -> Generator[str, None, None]: + ... + + keys = ... + def values(self): # -> Generator[ConfigItem, None, None]: + """Iterate over configuration item values.""" + ... + + def items(self): # -> Generator[tuple[str, ConfigItem], None, None]: + """Iterate over configuration item ``(name, value)`` pairs.""" + ... + + def set_temp(self, attr, value): # -> Any: + """ + Temporarily set a configuration value. + + Parameters + ---------- + attr : str + Configuration item name + + value : object + The value to set temporarily. + + Examples + -------- + >>> import astropy + >>> with astropy.conf.set_temp('use_color', False): + ... pass + ... # console output will not contain color + >>> # console output contains color again... + """ + ... + + def reload(self, attr=...): # -> Any | None: + """ + Reload a configuration item from the configuration file. + + Parameters + ---------- + attr : str, optional + The name of the configuration parameter to reload. If not + provided, reload all configuration parameters. + """ + ... + + def reset(self, attr=...): # -> None: + """ + Reset a configuration item to its default. + + Parameters + ---------- + attr : str, optional + The name of the configuration parameter to reload. If not + provided, reset all configuration parameters. + """ + ... + + + +class ConfigItem: + """ + A setting and associated value stored in a configuration file. + + These objects should be created as members of + `ConfigNamespace` subclasses, for example:: + + class _Conf(config.ConfigNamespace): + unicode_output = config.ConfigItem( + False, + 'Use Unicode characters when outputting values, and writing widgets ' + 'to the console.') + conf = _Conf() + + Parameters + ---------- + defaultvalue : object, optional + The default value for this item. If this is a list of strings, this + item will be interpreted as an 'options' value - this item must be one + of those values, and the first in the list will be taken as the default + value. + + description : str or None, optional + A description of this item (will be shown as a comment in the + configuration file) + + cfgtype : str or None, optional + A type specifier like those used as the *values* of a particular key + in a ``configspec`` file of ``configobj``. If None, the type will be + inferred from the default value. + + module : str or None, optional + The full module name that this item is associated with. The first + element (e.g. 'astropy' if this is 'astropy.config.configuration') + will be used to determine the name of the configuration file, while + the remaining items determine the section. If None, the package will be + inferred from the package within which this object's initializer is + called. + + aliases : str, or list of str, optional + The deprecated location(s) of this configuration item. If the + config item is not found at the new location, it will be + searched for at all of the old locations. + + Raises + ------ + RuntimeError + If ``module`` is `None`, but the module this item is created from + cannot be determined. + """ + _validator = ... + cfgtype = ... + rootname = ... + def __init__(self, defaultvalue=..., description=..., cfgtype=..., module=..., aliases=...) -> None: + ... + + def __set__(self, obj, value): # -> None: + ... + + def __get__(self, obj, objtype=...): # -> Self@ConfigItem | int | bool | list[int | float | str | bool] | string_type | None: + ... + + def set(self, value): # -> None: + """ + Sets the current value of this ``ConfigItem``. + + This also updates the comments that give the description and type + information. + + Parameters + ---------- + value + The value this item should be set to. + + Raises + ------ + TypeError + If the provided ``value`` is not valid for this ``ConfigItem``. + """ + ... + + @contextmanager + def set_temp(self, value): # -> Generator[None, None, None]: + """ + Sets this item to a specified value only inside a with block. + + Use as:: + + ITEM = ConfigItem('ITEM', 'default', 'description') + + with ITEM.set_temp('newval'): + #... do something that wants ITEM's value to be 'newval' ... + print(ITEM) + + # ITEM is now 'default' after the with block + + Parameters + ---------- + value + The value to set this item to inside the with block. + + """ + ... + + def reload(self): # -> str | LiteralString | list[str | Unknown] | list[Unknown] | None: + """ Reloads the value of this ``ConfigItem`` from the relevant + configuration file. + + Returns + ------- + val : object + The new value loaded from the configuration file. + + """ + ... + + def __repr__(self): # -> str: + ... + + def __str__(self) -> str: + ... + + def __call__(self): # -> int | bool | list[int | float | str | bool] | string_type | None: + """ Returns the value of this ``ConfigItem`` + + Returns + ------- + val : object + This item's value, with a type determined by the ``cfgtype`` + attribute. + + Raises + ------ + TypeError + If the configuration value as stored is not this item's type. + + """ + ... + + + +_cfgobjs = ... +def get_config_filename(packageormod=..., rootname=...): # -> str | None: + """ + Get the filename of the config file associated with the given + package or module. + """ + ... + +_override_config_file = ... +def get_config(packageormod=..., reload=..., rootname=...): # -> str | LiteralString | list[str | Unknown] | list[Unknown] | ConfigObj: + """ Gets the configuration object or section associated with a particular + package or module. + + Parameters + ---------- + packageormod : str or None + The package for which to retrieve the configuration object. If a + string, it must be a valid package name, or if ``None``, the package from + which this function is called will be used. + + reload : bool, optional + Reload the file, even if we have it cached. + + rootname : str or None + Name of the root configuration directory. If ``None`` and + ``packageormod`` is ``None``, this defaults to be the name of + the package from which this function is called. If ``None`` and + ``packageormod`` is not ``None``, this defaults to ``astropy``. + + Returns + ------- + cfgobj : ``configobj.ConfigObj`` or ``configobj.Section`` + If the requested package is a base package, this will be the + ``configobj.ConfigObj`` for that package, or if it is a subpackage or + module, it will return the relevant ``configobj.Section`` object. + + Raises + ------ + RuntimeError + If ``packageormod`` is `None`, but the package this item is created + from cannot be determined. + """ + ... + +def generate_config(pkgname=..., filename=..., verbose=...): # -> None: + """Generates a configuration file, from the list of `ConfigItem` + objects for each subpackage. + + .. versionadded:: 4.1 + + Parameters + ---------- + pkgname : str or None + The package for which to retrieve the configuration object. + filename : str or file-like or None + If None, the default configuration path is taken from `get_config`. + + """ + ... + +def reload_config(packageormod=..., rootname=...): # -> None: + """ Reloads configuration settings from a configuration file for the root + package of the requested package/module. + + This overwrites any changes that may have been made in `ConfigItem` + objects. This applies for any items that are based on this file, which + is determined by the *root* package of ``packageormod`` + (e.g. ``'astropy.cfg'`` for the ``'astropy.config.configuration'`` + module). + + Parameters + ---------- + packageormod : str or None + The package or module name - see `get_config` for details. + rootname : str or None + Name of the root configuration directory - see `get_config` + for details. + """ + ... + +def is_unedited_config_file(content, template_content=...): # -> bool: + """ + Determines if a config file can be safely replaced because it doesn't + actually contain any meaningful content, i.e. if it contains only comments + or is completely empty. + """ + ... + +@deprecated('5.0') +def update_default_config(pkg, default_cfg_dir_or_fn, version=..., rootname=...): # -> bool: + """ + Checks if the configuration file for the specified package exists, + and if not, copy over the default configuration. If the + configuration file looks like it has already been edited, we do + not write over it, but instead write a file alongside it named + ``pkg.version.cfg`` as a "template" for the user. + + Parameters + ---------- + pkg : str + The package to be updated. + default_cfg_dir_or_fn : str + The filename or directory name where the default configuration file is. + If a directory name, ``'pkg.cfg'`` will be used in that directory. + version : str, optional + The current version of the given package. If not provided, it will + be obtained from ``pkg.__version__``. + rootname : str + Name of the root configuration directory. + + Returns + ------- + updated : bool + If the profile was updated, `True`, otherwise `False`. + + Raises + ------ + AttributeError + If the version number of the package could not determined. + + """ + ... + +def create_config_file(pkg, rootname=..., overwrite=...): # -> bool: + """ + Create the default configuration file for the specified package. + If the file already exists, it is updated only if it has not been + modified. Otherwise the ``overwrite`` flag is needed to overwrite it. + + Parameters + ---------- + pkg : str + The package to be updated. + rootname : str + Name of the root configuration directory. + overwrite : bool + Force updating the file if it already exists. + + Returns + ------- + updated : bool + If the profile was updated, `True`, otherwise `False`. + + """ + ... + diff --git a/typings/astropy/config/paths.pyi b/typings/astropy/config/paths.pyi new file mode 100644 index 0000000..dabce07 --- /dev/null +++ b/typings/astropy/config/paths.pyi @@ -0,0 +1,142 @@ +""" +This type stub file was generated by pyright. +""" + +""" This module contains functions to determine where configuration and +data/cache files used by Astropy should be placed. +""" +__all__ = ['get_config_dir', 'get_cache_dir', 'set_temp_config', 'set_temp_cache'] +def get_config_dir(rootname=...): # -> str: + """ + Determines the package configuration directory name and creates the + directory if it doesn't exist. + + This directory is typically ``$HOME/.astropy/config``, but if the + XDG_CONFIG_HOME environment variable is set and the + ``$XDG_CONFIG_HOME/astropy`` directory exists, it will be that directory. + If neither exists, the former will be created and symlinked to the latter. + + Parameters + ---------- + rootname : str + Name of the root configuration directory. For example, if ``rootname = + 'pkgname'``, the configuration directory would be ``/.pkgname/`` + rather than ``/.astropy`` (depending on platform). + + Returns + ------- + configdir : str + The absolute path to the configuration directory. + + """ + ... + +def get_cache_dir(rootname=...): # -> str: + """ + Determines the Astropy cache directory name and creates the directory if it + doesn't exist. + + This directory is typically ``$HOME/.astropy/cache``, but if the + XDG_CACHE_HOME environment variable is set and the + ``$XDG_CACHE_HOME/astropy`` directory exists, it will be that directory. + If neither exists, the former will be created and symlinked to the latter. + + Parameters + ---------- + rootname : str + Name of the root cache directory. For example, if + ``rootname = 'pkgname'``, the cache directory will be + ``/.pkgname/``. + + Returns + ------- + cachedir : str + The absolute path to the cache directory. + + """ + ... + +class _SetTempPath: + _temp_path = ... + _default_path_getter = ... + def __init__(self, path=..., delete=...) -> None: + ... + + def __enter__(self): + ... + + def __exit__(self, *args): # -> None: + ... + + def __call__(self, func): # -> (*args: Unknown, **kwargs: Unknown) -> None: + """Implements use as a decorator.""" + ... + + + +class set_temp_config(_SetTempPath): + """ + Context manager to set a temporary path for the Astropy config, primarily + for use with testing. + + If the path set by this context manager does not already exist it will be + created, if possible. + + This may also be used as a decorator on a function to set the config path + just within that function. + + Parameters + ---------- + + path : str, optional + The directory (which must exist) in which to find the Astropy config + files, or create them if they do not already exist. If None, this + restores the config path to the user's default config path as returned + by `get_config_dir` as though this context manager were not in effect + (this is useful for testing). In this case the ``delete`` argument is + always ignored. + + delete : bool, optional + If True, cleans up the temporary directory after exiting the temp + context (default: False). + """ + _default_path_getter = ... + def __enter__(self): + ... + + def __exit__(self, *args): # -> None: + ... + + + +class set_temp_cache(_SetTempPath): + """ + Context manager to set a temporary path for the Astropy download cache, + primarily for use with testing (though there may be other applications + for setting a different cache directory, for example to switch to a cache + dedicated to large files). + + If the path set by this context manager does not already exist it will be + created, if possible. + + This may also be used as a decorator on a function to set the cache path + just within that function. + + Parameters + ---------- + + path : str + The directory (which must exist) in which to find the Astropy cache + files, or create them if they do not already exist. If None, this + restores the cache path to the user's default cache path as returned + by `get_cache_dir` as though this context manager were not in effect + (this is useful for testing). In this case the ``delete`` argument is + always ignored. + + delete : bool, optional + If True, cleans up the temporary directory after exiting the temp + context (default: False). + """ + _default_path_getter = ... + + diff --git a/typings/astropy/conftest.pyi b/typings/astropy/conftest.pyi new file mode 100644 index 0000000..f932845 --- /dev/null +++ b/typings/astropy/conftest.pyi @@ -0,0 +1,40 @@ +""" +This type stub file was generated by pyright. +""" + +import sys +import pytest +from astropy.utils.compat.optional_deps import HAS_MATPLOTLIB + +""" +This file contains pytest configuration settings that are astropy-specific +(i.e. those that would not necessarily be shared by affiliated packages +making use of astropy's test runner). +""" +if getattr(sys, 'frozen', False) and hasattr(sys, '_MEIPASS'): + ... +if HAS_MATPLOTLIB: + ... +matplotlibrc_cache = ... +@pytest.fixture +def ignore_matplotlibrc(): # -> Generator[None, None, None]: + ... + +@pytest.fixture +def fast_thread_switching(): # -> Generator[None, None, None]: + """Fixture that reduces thread switching interval. + + This makes it easier to provoke race conditions. + """ + ... + +def pytest_configure(config): # -> None: + ... + +def pytest_unconfigure(config): # -> None: + ... + +def pytest_terminal_summary(terminalreporter): # -> None: + """Output a warning to IPython users in case any tests failed.""" + ... + diff --git a/typings/astropy/constants/__init__.pyi b/typings/astropy/constants/__init__.pyi new file mode 100644 index 0000000..0b5a75b --- /dev/null +++ b/typings/astropy/constants/__init__.pyi @@ -0,0 +1,28 @@ +""" +This type stub file was generated by pyright. +""" + +import warnings +from astropy.utils import find_current_module +from astropy import units +from . import cgs, si, utils as _utils +from .config import codata, iaudata +from .constant import Constant, EMConstant + +""" +Contains astronomical and physical constants for use in Astropy or other +places. + +A typical use case might be:: + + >>> from astropy.constants import c, m_e + >>> # ... define the mass of something you want the rest energy of as m ... + >>> m = m_e + >>> E = m * c**2 + >>> E.to('MeV') # doctest: +FLOAT_CMP + + +""" +_lines = ... +if __doc__ is not None: + ... diff --git a/typings/astropy/constants/cgs.pyi b/typings/astropy/constants/cgs.pyi new file mode 100644 index 0000000..4cb4f18 --- /dev/null +++ b/typings/astropy/constants/cgs.pyi @@ -0,0 +1,8 @@ +""" +This type stub file was generated by pyright. +""" + +""" +Astronomical and physics constants in cgs units. See :mod:`astropy.constants` +for a complete listing of constants defined in Astropy. +""" diff --git a/typings/astropy/constants/config.pyi b/typings/astropy/constants/config.pyi new file mode 100644 index 0000000..ff58fee --- /dev/null +++ b/typings/astropy/constants/config.pyi @@ -0,0 +1,11 @@ +""" +This type stub file was generated by pyright. +""" + +""" +Configures the codata and iaudata used, possibly using user configuration. +""" +phys_version = ... +astro_version = ... +codata = ... +iaudata = ... diff --git a/typings/astropy/constants/constant.pyi b/typings/astropy/constants/constant.pyi new file mode 100644 index 0000000..c163fc3 --- /dev/null +++ b/typings/astropy/constants/constant.pyi @@ -0,0 +1,116 @@ +""" +This type stub file was generated by pyright. +""" + +from astropy.units.quantity import Quantity + +__all__ = ['Constant', 'EMConstant'] +class ConstantMeta(type): + """Metaclass for `~astropy.constants.Constant`. The primary purpose of this + is to wrap the double-underscore methods of `~astropy.units.Quantity` + which is the superclass of `~astropy.constants.Constant`. + + In particular this wraps the operator overloads such as `__add__` to + prevent their use with constants such as ``e`` from being used in + expressions without specifying a system. The wrapper checks to see if the + constant is listed (by name) in ``Constant._has_incompatible_units``, a set + of those constants that are defined in different systems of units are + physically incompatible. It also performs this check on each `Constant` if + it hasn't already been performed (the check is deferred until the + `Constant` is actually used in an expression to speed up import times, + among other reasons). + """ + def __new__(mcls, name, bases, d): # -> Self@ConstantMeta: + ... + + + +class Constant(Quantity, metaclass=ConstantMeta): + """A physical or astronomical constant. + + These objects are quantities that are meant to represent physical + constants. + """ + _registry = ... + _has_incompatible_units = ... + def __new__(cls, abbrev, name, value, unit, uncertainty, reference=..., system=...): # -> Self@Constant: + ... + + def __repr__(self): # -> str: + ... + + def __str__(self) -> str: + ... + + def __quantity_subclass__(self, unit): # -> tuple[Type[Quantity], Literal[False]]: + ... + + def copy(self): # -> Self@Constant: + """ + Return a copy of this `Constant` instance. Since they are by + definition immutable, this merely returns another reference to + ``self``. + """ + ... + + __deepcopy__ = ... + @property + def abbrev(self): # -> float | NDArray[void] | Any: + """A typical ASCII text abbreviation of the constant, also generally + the same as the Python variable used for this constant. + """ + ... + + @property + def name(self): # -> float | NDArray[void] | Any: + """The full name of the constant.""" + ... + + @property + def uncertainty(self): # -> float | NDArray[void] | Any: + """The known absolute uncertainty in this constant's value.""" + ... + + @property + def reference(self): # -> float | NDArray[void] | Any: + """The source used for the value of this constant.""" + ... + + @property + def system(self): # -> float | NDArray[void] | Any: + """The system of units in which this constant is defined (typically + `None` so long as the constant's units can be directly converted + between systems). + """ + ... + + @property + def si(self): # -> Any: + """If the Constant is defined in the SI system return that instance of + the constant, else convert to a Quantity in the appropriate SI units. + """ + ... + + @property + def cgs(self): # -> Any: + """If the Constant is defined in the CGS system return that instance of + the constant, else convert to a Quantity in the appropriate CGS units. + """ + ... + + def __array_finalize__(self, obj): # -> None: + ... + + + +class EMConstant(Constant): + """An electromagnetic constant.""" + @property + def cgs(self): + """Overridden for EMConstant to raise a `TypeError` + emphasizing that there are multiple EM extensions to CGS. + """ + ... + + + diff --git a/typings/astropy/constants/si.pyi b/typings/astropy/constants/si.pyi new file mode 100644 index 0000000..850138f --- /dev/null +++ b/typings/astropy/constants/si.pyi @@ -0,0 +1,8 @@ +""" +This type stub file was generated by pyright. +""" + +""" +Astronomical and physics constants in SI units. See :mod:`astropy.constants` +for a complete listing of constants defined in Astropy. +""" diff --git a/typings/astropy/constants/utils.pyi b/typings/astropy/constants/utils.pyi new file mode 100644 index 0000000..f62defb --- /dev/null +++ b/typings/astropy/constants/utils.pyi @@ -0,0 +1,6 @@ +""" +This type stub file was generated by pyright. +""" + +"""Utility functions for ``constants`` sub-package.""" +__all__ = [] diff --git a/typings/astropy/convolution/__init__.pyi b/typings/astropy/convolution/__init__.pyi new file mode 100644 index 0000000..a8a0ece --- /dev/null +++ b/typings/astropy/convolution/__init__.pyi @@ -0,0 +1,10 @@ +""" +This type stub file was generated by pyright. +""" + +from .convolve import convolve, convolve_fft, convolve_models, convolve_models_fft, interpolate_replace_nans +from .core import * +from .kernels import * +from .kernels import MexicanHat1DKernel, MexicanHat2DKernel +from .utils import * + diff --git a/typings/astropy/convolution/convolve.pyi b/typings/astropy/convolution/convolve.pyi new file mode 100644 index 0000000..8b71030 --- /dev/null +++ b/typings/astropy/convolution/convolve.pyi @@ -0,0 +1,385 @@ +""" +This type stub file was generated by pyright. +""" + +import numpy as np +from astropy.nddata import support_nddata + +LIBRARY_PATH = ... +_convolveNd_c = ... +_good_sizes = np.array([0, 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24, 25, 27, 30, 32, 36, 40, 45, 48, 50, 54, 60, 64, 72, 75, 80, 81, 90, 96, 100, 108, 120, 125, 128, 135, 144, 150, 160, 162, 180, 192, 200, 216, 225, 240, 243, 250, 256, 270, 288, 300, 320, 324, 360, 375, 384, 400, 405, 432, 450, 480, 486, 500, 512, 540, 576, 600, 625, 640, 648, 675, 720, 729, 750, 768, 800, 810, 864, 900, 960, 972, 1000, 1024, 1080, 1125, 1152, 1200, 1215, 1250, 1280, 1296, 1350, 1440, 1458, 1500, 1536, 1600, 1620, 1728, 1800, 1875, 1920, 1944, 2000, 2025, 2048, 2160, 2187, 2250, 2304, 2400, 2430, 2500, 2560, 2592, 2700, 2880, 2916, 3000, 3072, 3125, 3200, 3240, 3375, 3456, 3600, 3645, 3750, 3840, 3888, 4000, 4050, 4096, 4320, 4374, 4500, 4608, 4800, 4860, 5000, 5120, 5184, 5400, 5625, 5760, 5832, 6000, 6075, 6144, 6250, 6400, 6480, 6561, 6750, 6912, 7200, 7290, 7500, 7680, 7776, 8000, 8100, 8192, 8640, 8748, 9000, 9216, 9375, 9600, 9720, 10000]) +_good_range = ... +__doctest_requires__ = ... +BOUNDARY_OPTIONS = ... +@support_nddata(data='array') +def convolve(array, kernel, boundary=..., fill_value=..., nan_treatment=..., normalize_kernel=..., mask=..., preserve_nan=..., normalization_zero_tol=...): + """ + Convolve an array with a kernel. + + This routine differs from `scipy.ndimage.convolve` because + it includes a special treatment for ``NaN`` values. Rather than + including ``NaN`` values in the array in the convolution calculation, which + causes large ``NaN`` holes in the convolved array, ``NaN`` values are + replaced with interpolated values using the kernel as an interpolation + function. + + Parameters + ---------- + array : `~astropy.nddata.NDData` or array-like + The array to convolve. This should be a 1, 2, or 3-dimensional array + or a list or a set of nested lists representing a 1, 2, or + 3-dimensional array. If an `~astropy.nddata.NDData`, the ``mask`` of + the `~astropy.nddata.NDData` will be used as the ``mask`` argument. + kernel : `numpy.ndarray` or `~astropy.convolution.Kernel` + The convolution kernel. The number of dimensions should match those for + the array, and the dimensions should be odd in all directions. If a + masked array, the masked values will be replaced by ``fill_value``. + boundary : str, optional + A flag indicating how to handle boundaries: + * `None` + Set the ``result`` values to zero where the kernel + extends beyond the edge of the array. + * 'fill' + Set values outside the array boundary to ``fill_value`` (default). + * 'wrap' + Periodic boundary that wrap to the other side of ``array``. + * 'extend' + Set values outside the array to the nearest ``array`` + value. + fill_value : float, optional + The value to use outside the array when using ``boundary='fill'``. + normalize_kernel : bool, optional + Whether to normalize the kernel to have a sum of one. + nan_treatment : {'interpolate', 'fill'}, optional + The method used to handle NaNs in the input ``array``: + * ``'interpolate'``: ``NaN`` values are replaced with + interpolated values using the kernel as an interpolation + function. Note that if the kernel has a sum equal to + zero, NaN interpolation is not possible and will raise an + exception. + * ``'fill'``: ``NaN`` values are replaced by ``fill_value`` + prior to convolution. + preserve_nan : bool, optional + After performing convolution, should pixels that were originally NaN + again become NaN? + mask : None or ndarray, optional + A "mask" array. Shape must match ``array``, and anything that is masked + (i.e., not 0/`False`) will be set to NaN for the convolution. If + `None`, no masking will be performed unless ``array`` is a masked array. + If ``mask`` is not `None` *and* ``array`` is a masked array, a pixel is + masked of it is masked in either ``mask`` *or* ``array.mask``. + normalization_zero_tol : float, optional + The absolute tolerance on whether the kernel is different than zero. + If the kernel sums to zero to within this precision, it cannot be + normalized. Default is "1e-8". + + Returns + ------- + result : `numpy.ndarray` + An array with the same dimensions and as the input array, + convolved with kernel. The data type depends on the input + array type. If array is a floating point type, then the + return array keeps the same data type, otherwise the type + is ``numpy.float``. + + Notes + ----- + For masked arrays, masked values are treated as NaNs. The convolution + is always done at ``numpy.float`` precision. + """ + ... + +@support_nddata(data='array') +def convolve_fft(array, kernel, boundary=..., fill_value=..., nan_treatment=..., normalize_kernel=..., normalization_zero_tol=..., preserve_nan=..., mask=..., crop=..., return_fft=..., fft_pad=..., psf_pad=..., min_wt=..., allow_huge=..., fftn=..., ifftn=..., complex_dtype=..., dealias=...): + """ + Convolve an ndarray with an nd-kernel. Returns a convolved image with + ``shape = array.shape``. Assumes kernel is centered. + + `convolve_fft` is very similar to `convolve` in that it replaces ``NaN`` + values in the original image with interpolated values using the kernel as + an interpolation function. However, it also includes many additional + options specific to the implementation. + + `convolve_fft` differs from `scipy.signal.fftconvolve` in a few ways: + + * It can treat ``NaN`` values as zeros or interpolate over them. + * ``inf`` values are treated as ``NaN`` + * It optionally pads to the nearest faster sizes to improve FFT speed. + These sizes are optimized for the numpy and scipy implementations, and + ``fftconvolve`` uses them by default as well; when using other external + functions (see below), results may vary. + * Its only valid ``mode`` is 'same' (i.e., the same shape array is returned) + * It lets you use your own fft, e.g., + `pyFFTW `_ or + `pyFFTW3 `_ , which can lead to + performance improvements, depending on your system configuration. pyFFTW3 + is threaded, and therefore may yield significant performance benefits on + multi-core machines at the cost of greater memory requirements. Specify + the ``fftn`` and ``ifftn`` keywords to override the default, which is + `numpy.fft.fftn` and `numpy.fft.ifftn`. The `scipy.fft` functions also + offer somewhat better performance and a multi-threaded option. + + Parameters + ---------- + array : `numpy.ndarray` + Array to be convolved with ``kernel``. It can be of any + dimensionality, though only 1, 2, and 3d arrays have been tested. + kernel : `numpy.ndarray` or `astropy.convolution.Kernel` + The convolution kernel. The number of dimensions should match those + for the array. The dimensions *do not* have to be odd in all directions, + unlike in the non-fft `convolve` function. The kernel will be + normalized if ``normalize_kernel`` is set. It is assumed to be centered + (i.e., shifts may result if your kernel is asymmetric) + boundary : {'fill', 'wrap'}, optional + A flag indicating how to handle boundaries: + + * 'fill': set values outside the array boundary to fill_value + (default) + * 'wrap': periodic boundary + + The `None` and 'extend' parameters are not supported for FFT-based + convolution. + fill_value : float, optional + The value to use outside the array when using boundary='fill'. + nan_treatment : {'interpolate', 'fill'}, optional + The method used to handle NaNs in the input ``array``: + * ``'interpolate'``: ``NaN`` values are replaced with + interpolated values using the kernel as an interpolation + function. Note that if the kernel has a sum equal to + zero, NaN interpolation is not possible and will raise an + exception. + * ``'fill'``: ``NaN`` values are replaced by ``fill_value`` + prior to convolution. + normalize_kernel : callable or boolean, optional + If specified, this is the function to divide kernel by to normalize it. + e.g., ``normalize_kernel=np.sum`` means that kernel will be modified to be: + ``kernel = kernel / np.sum(kernel)``. If True, defaults to + ``normalize_kernel = np.sum``. + normalization_zero_tol : float, optional + The absolute tolerance on whether the kernel is different than zero. + If the kernel sums to zero to within this precision, it cannot be + normalized. Default is "1e-8". + preserve_nan : bool, optional + After performing convolution, should pixels that were originally NaN + again become NaN? + mask : None or ndarray, optional + A "mask" array. Shape must match ``array``, and anything that is masked + (i.e., not 0/`False`) will be set to NaN for the convolution. If + `None`, no masking will be performed unless ``array`` is a masked array. + If ``mask`` is not `None` *and* ``array`` is a masked array, a pixel is + masked of it is masked in either ``mask`` *or* ``array.mask``. + crop : bool, optional + Default on. Return an image of the size of the larger of the input + image and the kernel. + If the image and kernel are asymmetric in opposite directions, will + return the largest image in both directions. + For example, if an input image has shape [100,3] but a kernel with shape + [6,6] is used, the output will be [100,6]. + return_fft : bool, optional + Return the ``fft(image)*fft(kernel)`` instead of the convolution (which is + ``ifft(fft(image)*fft(kernel))``). Useful for making PSDs. + fft_pad : bool, optional + Default on. Zero-pad image to the nearest size supporting more efficient + execution of the FFT, generally values factorizable into the first 3-5 + prime numbers. With ``boundary='wrap'``, this will be disabled. + psf_pad : bool, optional + Zero-pad image to be at least the sum of the image sizes to avoid + edge-wrapping when smoothing. This is enabled by default with + ``boundary='fill'``, but it can be overridden with a boolean option. + ``boundary='wrap'`` and ``psf_pad=True`` are not compatible. + min_wt : float, optional + If ignoring ``NaN`` / zeros, force all grid points with a weight less than + this value to ``NaN`` (the weight of a grid point with *no* ignored + neighbors is 1.0). + If ``min_wt`` is zero, then all zero-weight points will be set to zero + instead of ``NaN`` (which they would be otherwise, because 1/0 = nan). + See the examples below. + allow_huge : bool, optional + Allow huge arrays in the FFT? If False, will raise an exception if the + array or kernel size is >1 GB. + fftn : callable, optional + The fft function. Can be overridden to use your own ffts, + e.g. an fftw3 wrapper or scipy's fftn, ``fft=scipy.fftpack.fftn``. + ifftn : callable, optional + The inverse fft function. Can be overridden the same way ``fttn``. + complex_dtype : complex type, optional + Which complex dtype to use. `numpy` has a range of options, from 64 to + 256. + dealias: bool, optional + Default off. Zero-pad image to enable explicit dealiasing + of convolution. With ``boundary='wrap'``, this will be disabled. + Note that for an input of nd dimensions this will increase + the size of the temporary arrays by at least ``1.5**nd``. + This may result in significantly more memory usage. + + Returns + ------- + default : ndarray + ``array`` convolved with ``kernel``. If ``return_fft`` is set, returns + ``fft(array) * fft(kernel)``. If crop is not set, returns the + image, but with the fft-padded size instead of the input size. + + Raises + ------ + `ValueError` + If the array is bigger than 1 GB after padding, will raise this + exception unless ``allow_huge`` is True. + + See Also + -------- + convolve: + Convolve is a non-fft version of this code. It is more memory + efficient and for small kernels can be faster. + + Notes + ----- + With ``psf_pad=True`` and a large PSF, the resulting data + can become large and consume a lot of memory. See Issue + https://github.com/astropy/astropy/pull/4366 and the update in + https://github.com/astropy/astropy/pull/11533 for further details. + + Dealiasing of pseudospectral convolutions is necessary for + numerical stability of the underlying algorithms. A common + method for handling this is to zero pad the image by at least + 1/2 to eliminate the wavenumbers which have been aliased + by convolution. This is so that the aliased 1/3 of the + results of the convolution computation can be thrown out. See + https://doi.org/10.1175/1520-0469(1971)028%3C1074:OTEOAI%3E2.0.CO;2 + https://iopscience.iop.org/article/10.1088/1742-6596/318/7/072037 + + Note that if dealiasing is necessary to your application, but your + process is memory constrained, you may want to consider using + FFTW++: https://github.com/dealias/fftwpp. It includes python + wrappers for a pseudospectral convolution which will implicitly + dealias your convolution without the need for additional padding. + Note that one cannot use FFTW++'s convlution directly in this + method as in handles the entire convolution process internally. + Additionally, FFTW++ includes other useful pseudospectral methods to + consider. + + Examples + -------- + >>> convolve_fft([1, 0, 3], [1, 1, 1]) + array([0.33333333, 1.33333333, 1. ]) + + >>> convolve_fft([1, np.nan, 3], [1, 1, 1]) + array([0.5, 2. , 1.5]) + + >>> convolve_fft([1, 0, 3], [0, 1, 0]) # doctest: +FLOAT_CMP + array([ 1.00000000e+00, -3.70074342e-17, 3.00000000e+00]) + + >>> convolve_fft([1, 2, 3], [1]) + array([1., 2., 3.]) + + >>> convolve_fft([1, np.nan, 3], [0, 1, 0], nan_treatment='interpolate') + array([1., 0., 3.]) + + >>> convolve_fft([1, np.nan, 3], [0, 1, 0], nan_treatment='interpolate', + ... min_wt=1e-8) + array([ 1., nan, 3.]) + + >>> convolve_fft([1, np.nan, 3], [1, 1, 1], nan_treatment='interpolate') + array([0.5, 2. , 1.5]) + + >>> convolve_fft([1, np.nan, 3], [1, 1, 1], nan_treatment='interpolate', + ... normalize_kernel=True) + array([0.5, 2. , 1.5]) + + >>> import scipy.fft # optional - requires scipy + >>> convolve_fft([1, np.nan, 3], [1, 1, 1], nan_treatment='interpolate', + ... normalize_kernel=True, + ... fftn=scipy.fft.fftn, ifftn=scipy.fft.ifftn) + array([0.5, 2. , 1.5]) + + >>> fft_mp = lambda a: scipy.fft.fftn(a, workers=-1) # use all available cores + >>> ifft_mp = lambda a: scipy.fft.ifftn(a, workers=-1) + >>> convolve_fft([1, np.nan, 3], [1, 1, 1], nan_treatment='interpolate', + ... normalize_kernel=True, fftn=fft_mp, ifftn=ifft_mp) + array([0.5, 2. , 1.5]) + """ + ... + +def interpolate_replace_nans(array, kernel, convolve=..., **kwargs): + """ + Given a data set containing NaNs, replace the NaNs by interpolating from + neighboring data points with a given kernel. + + Parameters + ---------- + array : `numpy.ndarray` + Array to be convolved with ``kernel``. It can be of any + dimensionality, though only 1, 2, and 3d arrays have been tested. + kernel : `numpy.ndarray` or `astropy.convolution.Kernel` + The convolution kernel. The number of dimensions should match those + for the array. The dimensions *do not* have to be odd in all directions, + unlike in the non-fft `convolve` function. The kernel will be + normalized if ``normalize_kernel`` is set. It is assumed to be centered + (i.e., shifts may result if your kernel is asymmetric). The kernel + *must be normalizable* (i.e., its sum cannot be zero). + convolve : `convolve` or `convolve_fft` + One of the two convolution functions defined in this package. + + Returns + ------- + newarray : `numpy.ndarray` + A copy of the original array with NaN pixels replaced with their + interpolated counterparts + """ + ... + +def convolve_models(model, kernel, mode=..., **kwargs): # -> CompoundModel: + """ + Convolve two models using `~astropy.convolution.convolve_fft`. + + Parameters + ---------- + model : `~astropy.modeling.core.Model` + Functional model + kernel : `~astropy.modeling.core.Model` + Convolution kernel + mode : str + Keyword representing which function to use for convolution. + * 'convolve_fft' : use `~astropy.convolution.convolve_fft` function. + * 'convolve' : use `~astropy.convolution.convolve`. + **kwargs : dict + Keyword arguments to me passed either to `~astropy.convolution.convolve` + or `~astropy.convolution.convolve_fft` depending on ``mode``. + + Returns + ------- + default : `~astropy.modeling.core.CompoundModel` + Convolved model + """ + ... + +def convolve_models_fft(model, kernel, bounding_box, resolution, cache=..., **kwargs): # -> Convolution: + """ + Convolve two models using `~astropy.convolution.convolve_fft`. + + Parameters + ---------- + model : `~astropy.modeling.core.Model` + Functional model + kernel : `~astropy.modeling.core.Model` + Convolution kernel + bounding_box : tuple + The bounding box which encompasses enough of the support of both + the ``model`` and ``kernel`` so that an accurate convolution can be + computed. + resolution : float + The resolution that one wishes to approximate the convolution + integral at. + cache : optional, bool + Default value True. Allow for the storage of the convolution + computation for later reuse. + **kwargs : dict + Keyword arguments to be passed either to `~astropy.convolution.convolve` + or `~astropy.convolution.convolve_fft` depending on ``mode``. + + Returns + ------- + default : `~astropy.modeling.core.CompoundModel` + Convolved model + """ + ... + diff --git a/typings/astropy/convolution/core.pyi b/typings/astropy/convolution/core.pyi new file mode 100644 index 0000000..85d2f2b --- /dev/null +++ b/typings/astropy/convolution/core.pyi @@ -0,0 +1,254 @@ +""" +This type stub file was generated by pyright. +""" + +""" +This module contains the convolution and filter functionalities of astropy. + +A few conceptual notes: +A filter kernel is mainly characterized by its response function. In the 1D +case we speak of "impulse response function", in the 2D case we call it "point +spread function". This response function is given for every kernel by an +astropy `FittableModel`, which is evaluated on a grid to obtain a filter array, +which can then be applied to binned data. + +The model is centered on the array and should have an amplitude such that the array +integrates to one per default. + +Currently only symmetric 2D kernels are supported. +""" +MAX_NORMALIZATION = ... +__all__ = ['Kernel', 'Kernel1D', 'Kernel2D', 'kernel_arithmetics'] +class Kernel: + """ + Convolution kernel base class. + + Parameters + ---------- + array : ndarray + Kernel array. + """ + _separable = ... + _is_bool = ... + _model = ... + def __init__(self, array) -> None: + ... + + @property + def truncation(self): + """ + Deviation from the normalization to one. + """ + ... + + @property + def is_bool(self): # -> bool: + """ + Indicates if kernel is bool. + + If the kernel is bool the multiplication in the convolution could + be omitted, to increase the performance. + """ + ... + + @property + def model(self): # -> None: + """ + Kernel response model. + """ + ... + + @property + def dimension(self): + """ + Kernel dimension. + """ + ... + + @property + def center(self): # -> list[Unknown]: + """ + Index of the kernel center. + """ + ... + + def normalize(self, mode=...): # -> None: + """ + Normalize the filter kernel. + + Parameters + ---------- + mode : {'integral', 'peak'} + One of the following modes: + * 'integral' (default) + Kernel is normalized such that its integral = 1. + * 'peak' + Kernel is normalized such that its peak = 1. + """ + ... + + @property + def shape(self): + """ + Shape of the kernel array. + """ + ... + + @property + def separable(self): # -> bool: + """ + Indicates if the filter kernel is separable. + + A 2D filter is separable, when its filter array can be written as the + outer product of two 1D arrays. + + If a filter kernel is separable, higher dimension convolutions will be + performed by applying the 1D filter array consecutively on every dimension. + This is significantly faster, than using a filter array with the same + dimension. + """ + ... + + @property + def array(self): # -> Unknown: + """ + Filter kernel array. + """ + ... + + def __add__(self, kernel): # -> Kernel1D | Kernel2D: + """ + Add two filter kernels. + """ + ... + + def __sub__(self, kernel): # -> Kernel1D | Kernel2D: + """ + Subtract two filter kernels. + """ + ... + + def __mul__(self, value): # -> Kernel1D | Kernel2D: + """ + Multiply kernel with number or convolve two kernels. + """ + ... + + def __rmul__(self, value): # -> Kernel1D | Kernel2D: + """ + Multiply kernel with number or convolve two kernels. + """ + ... + + def __array__(self): # -> Unknown: + """ + Array representation of the kernel. + """ + ... + + def __array_wrap__(self, array, context=...): # -> _NotImplementedType: + """ + Wrapper for multiplication with numpy arrays. + """ + ... + + + +class Kernel1D(Kernel): + """ + Base class for 1D filter kernels. + + Parameters + ---------- + model : `~astropy.modeling.FittableModel` + Model to be evaluated. + x_size : int or None, optional + Size of the kernel array. Default = ⌊8*width+1⌋. + Only used if ``array`` is None. + array : ndarray or None, optional + Kernel array. + width : number + Width of the filter kernel. + mode : str, optional + One of the following discretization modes: + * 'center' (default) + Discretize model by taking the value + at the center of the bin. + * 'linear_interp' + Discretize model by linearly interpolating + between the values at the corners of the bin. + * 'oversample' + Discretize model by taking the average + on an oversampled grid. + * 'integrate' + Discretize model by integrating the + model over the bin. + factor : number, optional + Factor of oversampling. Default factor = 10. + """ + def __init__(self, model=..., x_size=..., array=..., **kwargs) -> None: + ... + + + +class Kernel2D(Kernel): + """ + Base class for 2D filter kernels. + + Parameters + ---------- + model : `~astropy.modeling.FittableModel` + Model to be evaluated. + x_size : int, optional + Size in x direction of the kernel array. Default = ⌊8*width + 1⌋. + Only used if ``array`` is None. + y_size : int, optional + Size in y direction of the kernel array. Default = ⌊8*width + 1⌋. + Only used if ``array`` is None, + array : ndarray or None, optional + Kernel array. Default is None. + mode : str, optional + One of the following discretization modes: + * 'center' (default) + Discretize model by taking the value + at the center of the bin. + * 'linear_interp' + Discretize model by performing a bilinear interpolation + between the values at the corners of the bin. + * 'oversample' + Discretize model by taking the average + on an oversampled grid. + * 'integrate' + Discretize model by integrating the + model over the bin. + width : number + Width of the filter kernel. + factor : number, optional + Factor of oversampling. Default factor = 10. + """ + def __init__(self, model=..., x_size=..., y_size=..., array=..., **kwargs) -> None: + ... + + + +def kernel_arithmetics(kernel, value, operation): # -> Kernel1D | Kernel2D: + """ + Add, subtract or multiply two kernels. + + Parameters + ---------- + kernel : `astropy.convolution.Kernel` + Kernel instance. + value : `astropy.convolution.Kernel`, float, or int + Value to operate with. + operation : {'add', 'sub', 'mul'} + One of the following operations: + * 'add' + Add two kernels + * 'sub' + Subtract two kernels + * 'mul' + Multiply kernel with number or convolve two kernels. + """ + ... + diff --git a/typings/astropy/convolution/kernels.pyi b/typings/astropy/convolution/kernels.pyi new file mode 100644 index 0000000..22bba6b --- /dev/null +++ b/typings/astropy/convolution/kernels.pyi @@ -0,0 +1,971 @@ +""" +This type stub file was generated by pyright. +""" + +from astropy.utils.decorators import deprecated +from .core import Kernel, Kernel1D, Kernel2D + +__all__ = ['Gaussian1DKernel', 'Gaussian2DKernel', 'CustomKernel', 'Box1DKernel', 'Box2DKernel', 'Tophat2DKernel', 'Trapezoid1DKernel', 'RickerWavelet1DKernel', 'RickerWavelet2DKernel', 'AiryDisk2DKernel', 'Moffat2DKernel', 'Model1DKernel', 'Model2DKernel', 'TrapezoidDisk2DKernel', 'Ring2DKernel'] +class Gaussian1DKernel(Kernel1D): + """ + 1D Gaussian filter kernel. + + The Gaussian filter is a filter with great smoothing properties. It is + isotropic and does not produce artifacts. + + The generated kernel is normalized so that it integrates to 1. + + Parameters + ---------- + stddev : number + Standard deviation of the Gaussian kernel. + x_size : int, optional + Size of the kernel array. Default = ⌊8*stddev+1⌋. + mode : str, optional + One of the following discretization modes: + * 'center' (default) + Discretize model by taking the value + at the center of the bin. + * 'linear_interp' + Discretize model by linearly interpolating + between the values at the corners of the bin. + * 'oversample' + Discretize model by taking the average + on an oversampled grid. + * 'integrate' + Discretize model by integrating the + model over the bin. Very slow. + factor : number, optional + Factor of oversampling. Default factor = 10. If the factor + is too large, evaluation can be very slow. + + + See Also + -------- + Box1DKernel, Trapezoid1DKernel, RickerWavelet1DKernel + + + Examples + -------- + Kernel response: + + .. plot:: + :include-source: + + import matplotlib.pyplot as plt + from astropy.convolution import Gaussian1DKernel + gauss_1D_kernel = Gaussian1DKernel(10) + plt.plot(gauss_1D_kernel, drawstyle='steps') + plt.xlabel('x [pixels]') + plt.ylabel('value') + plt.show() + """ + _separable = ... + _is_bool = ... + def __init__(self, stddev, **kwargs) -> None: + ... + + + +class Gaussian2DKernel(Kernel2D): + """ + 2D Gaussian filter kernel. + + The Gaussian filter is a filter with great smoothing properties. It is + isotropic and does not produce artifacts. + + The generated kernel is normalized so that it integrates to 1. + + Parameters + ---------- + x_stddev : float + Standard deviation of the Gaussian in x before rotating by theta. + y_stddev : float + Standard deviation of the Gaussian in y before rotating by theta. + theta : float or `~astropy.units.Quantity` ['angle'] + Rotation angle. If passed as a float, it is assumed to be in radians. + The rotation angle increases counterclockwise. + x_size : int, optional + Size in x direction of the kernel array. Default = ⌊8*stddev + 1⌋. + y_size : int, optional + Size in y direction of the kernel array. Default = ⌊8*stddev + 1⌋. + mode : str, optional + One of the following discretization modes: + * 'center' (default) + Discretize model by taking the value + at the center of the bin. + * 'linear_interp' + Discretize model by performing a bilinear interpolation + between the values at the corners of the bin. + * 'oversample' + Discretize model by taking the average + on an oversampled grid. + * 'integrate' + Discretize model by integrating the + model over the bin. + factor : number, optional + Factor of oversampling. Default factor = 10. + + + See Also + -------- + Box2DKernel, Tophat2DKernel, RickerWavelet2DKernel, Ring2DKernel, + TrapezoidDisk2DKernel, AiryDisk2DKernel, Moffat2DKernel + + Examples + -------- + Kernel response: + + .. plot:: + :include-source: + + import matplotlib.pyplot as plt + from astropy.convolution import Gaussian2DKernel + gaussian_2D_kernel = Gaussian2DKernel(10) + plt.imshow(gaussian_2D_kernel, interpolation='none', origin='lower') + plt.xlabel('x [pixels]') + plt.ylabel('y [pixels]') + plt.colorbar() + plt.show() + + """ + _separable = ... + _is_bool = ... + def __init__(self, x_stddev, y_stddev=..., theta=..., **kwargs) -> None: + ... + + + +class Box1DKernel(Kernel1D): + """ + 1D Box filter kernel. + + The Box filter or running mean is a smoothing filter. It is not isotropic + and can produce artifacts when applied repeatedly to the same data. + + The generated kernel is normalized so that it integrates to 1. + + By default the Box kernel uses the ``linear_interp`` discretization mode, + which allows non-shifting, even-sized kernels. This is achieved by + weighting the edge pixels with 1/2. E.g a Box kernel with an effective + smoothing of 4 pixel would have the following array: [0.5, 1, 1, 1, 0.5]. + + + Parameters + ---------- + width : number + Width of the filter kernel. + mode : str, optional + One of the following discretization modes: + * 'center' + Discretize model by taking the value + at the center of the bin. + * 'linear_interp' (default) + Discretize model by linearly interpolating + between the values at the corners of the bin. + * 'oversample' + Discretize model by taking the average + on an oversampled grid. + * 'integrate' + Discretize model by integrating the + model over the bin. + factor : number, optional + Factor of oversampling. Default factor = 10. + + See Also + -------- + Gaussian1DKernel, Trapezoid1DKernel, RickerWavelet1DKernel + + + Examples + -------- + Kernel response function: + + .. plot:: + :include-source: + + import matplotlib.pyplot as plt + from astropy.convolution import Box1DKernel + box_1D_kernel = Box1DKernel(9) + plt.plot(box_1D_kernel, drawstyle='steps') + plt.xlim(-1, 9) + plt.xlabel('x [pixels]') + plt.ylabel('value') + plt.show() + + """ + _separable = ... + _is_bool = ... + def __init__(self, width, **kwargs) -> None: + ... + + + +class Box2DKernel(Kernel2D): + """ + 2D Box filter kernel. + + The Box filter or running mean is a smoothing filter. It is not isotropic + and can produce artifacts when applied repeatedly to the same data. + + The generated kernel is normalized so that it integrates to 1. + + By default the Box kernel uses the ``linear_interp`` discretization mode, + which allows non-shifting, even-sized kernels. This is achieved by + weighting the edge pixels with 1/2. + + + Parameters + ---------- + width : number + Width of the filter kernel. + mode : str, optional + One of the following discretization modes: + * 'center' + Discretize model by taking the value + at the center of the bin. + * 'linear_interp' (default) + Discretize model by performing a bilinear interpolation + between the values at the corners of the bin. + * 'oversample' + Discretize model by taking the average + on an oversampled grid. + * 'integrate' + Discretize model by integrating the + model over the bin. + factor : number, optional + Factor of oversampling. Default factor = 10. + + + See Also + -------- + Gaussian2DKernel, Tophat2DKernel, RickerWavelet2DKernel, Ring2DKernel, + TrapezoidDisk2DKernel, AiryDisk2DKernel, Moffat2DKernel + + Examples + -------- + Kernel response: + + .. plot:: + :include-source: + + import matplotlib.pyplot as plt + from astropy.convolution import Box2DKernel + box_2D_kernel = Box2DKernel(9) + plt.imshow(box_2D_kernel, interpolation='none', origin='lower', + vmin=0.0, vmax=0.015) + plt.xlim(-1, 9) + plt.ylim(-1, 9) + plt.xlabel('x [pixels]') + plt.ylabel('y [pixels]') + plt.colorbar() + plt.show() + """ + _separable = ... + _is_bool = ... + def __init__(self, width, **kwargs) -> None: + ... + + + +class Tophat2DKernel(Kernel2D): + """ + 2D Tophat filter kernel. + + The Tophat filter is an isotropic smoothing filter. It can produce + artifacts when applied repeatedly on the same data. + + The generated kernel is normalized so that it integrates to 1. + + Parameters + ---------- + radius : int + Radius of the filter kernel. + mode : str, optional + One of the following discretization modes: + * 'center' (default) + Discretize model by taking the value + at the center of the bin. + * 'linear_interp' + Discretize model by performing a bilinear interpolation + between the values at the corners of the bin. + * 'oversample' + Discretize model by taking the average + on an oversampled grid. + * 'integrate' + Discretize model by integrating the + model over the bin. + factor : number, optional + Factor of oversampling. Default factor = 10. + + + See Also + -------- + Gaussian2DKernel, Box2DKernel, RickerWavelet2DKernel, Ring2DKernel, + TrapezoidDisk2DKernel, AiryDisk2DKernel, Moffat2DKernel + + Examples + -------- + Kernel response: + + .. plot:: + :include-source: + + import matplotlib.pyplot as plt + from astropy.convolution import Tophat2DKernel + tophat_2D_kernel = Tophat2DKernel(40) + plt.imshow(tophat_2D_kernel, interpolation='none', origin='lower') + plt.xlabel('x [pixels]') + plt.ylabel('y [pixels]') + plt.colorbar() + plt.show() + + """ + def __init__(self, radius, **kwargs) -> None: + ... + + + +class Ring2DKernel(Kernel2D): + """ + 2D Ring filter kernel. + + The Ring filter kernel is the difference between two Tophat kernels of + different width. This kernel is useful for, e.g., background estimation. + + The generated kernel is normalized so that it integrates to 1. + + Parameters + ---------- + radius_in : number + Inner radius of the ring kernel. + width : number + Width of the ring kernel. + mode : str, optional + One of the following discretization modes: + * 'center' (default) + Discretize model by taking the value + at the center of the bin. + * 'linear_interp' + Discretize model by performing a bilinear interpolation + between the values at the corners of the bin. + * 'oversample' + Discretize model by taking the average + on an oversampled grid. + * 'integrate' + Discretize model by integrating the + model over the bin. + factor : number, optional + Factor of oversampling. Default factor = 10. + + See Also + -------- + Gaussian2DKernel, Box2DKernel, Tophat2DKernel, RickerWavelet2DKernel, + TrapezoidDisk2DKernel, AiryDisk2DKernel, Moffat2DKernel + + Examples + -------- + Kernel response: + + .. plot:: + :include-source: + + import matplotlib.pyplot as plt + from astropy.convolution import Ring2DKernel + ring_2D_kernel = Ring2DKernel(9, 8) + plt.imshow(ring_2D_kernel, interpolation='none', origin='lower') + plt.xlabel('x [pixels]') + plt.ylabel('y [pixels]') + plt.colorbar() + plt.show() + """ + def __init__(self, radius_in, width, **kwargs) -> None: + ... + + + +class Trapezoid1DKernel(Kernel1D): + """ + 1D trapezoid kernel. + + The generated kernel is normalized so that it integrates to 1. + + Parameters + ---------- + width : number + Width of the filter kernel, defined as the width of the constant part, + before it begins to slope down. + slope : number + Slope of the filter kernel's tails + mode : str, optional + One of the following discretization modes: + * 'center' (default) + Discretize model by taking the value + at the center of the bin. + * 'linear_interp' + Discretize model by linearly interpolating + between the values at the corners of the bin. + * 'oversample' + Discretize model by taking the average + on an oversampled grid. + * 'integrate' + Discretize model by integrating the + model over the bin. + factor : number, optional + Factor of oversampling. Default factor = 10. + + See Also + -------- + Box1DKernel, Gaussian1DKernel, RickerWavelet1DKernel + + Examples + -------- + Kernel response: + + .. plot:: + :include-source: + + import matplotlib.pyplot as plt + from astropy.convolution import Trapezoid1DKernel + trapezoid_1D_kernel = Trapezoid1DKernel(17, slope=0.2) + plt.plot(trapezoid_1D_kernel, drawstyle='steps') + plt.xlabel('x [pixels]') + plt.ylabel('amplitude') + plt.xlim(-1, 28) + plt.show() + """ + _is_bool = ... + def __init__(self, width, slope=..., **kwargs) -> None: + ... + + + +class TrapezoidDisk2DKernel(Kernel2D): + """ + 2D trapezoid kernel. + + The generated kernel is normalized so that it integrates to 1. + + Parameters + ---------- + radius : number + Width of the filter kernel, defined as the width of the constant part, + before it begins to slope down. + slope : number + Slope of the filter kernel's tails + mode : str, optional + One of the following discretization modes: + * 'center' (default) + Discretize model by taking the value + at the center of the bin. + * 'linear_interp' + Discretize model by performing a bilinear interpolation + between the values at the corners of the bin. + * 'oversample' + Discretize model by taking the average + on an oversampled grid. + * 'integrate' + Discretize model by integrating the + model over the bin. + factor : number, optional + Factor of oversampling. Default factor = 10. + + See Also + -------- + Gaussian2DKernel, Box2DKernel, Tophat2DKernel, RickerWavelet2DKernel, + Ring2DKernel, AiryDisk2DKernel, Moffat2DKernel + + Examples + -------- + Kernel response: + + .. plot:: + :include-source: + + import matplotlib.pyplot as plt + from astropy.convolution import TrapezoidDisk2DKernel + trapezoid_2D_kernel = TrapezoidDisk2DKernel(20, slope=0.2) + plt.imshow(trapezoid_2D_kernel, interpolation='none', origin='lower') + plt.xlabel('x [pixels]') + plt.ylabel('y [pixels]') + plt.colorbar() + plt.show() + + """ + _is_bool = ... + def __init__(self, radius, slope=..., **kwargs) -> None: + ... + + + +class RickerWavelet1DKernel(Kernel1D): + """ + 1D Ricker wavelet filter kernel (sometimes known as a "Mexican Hat" + kernel). + + The Ricker wavelet, or inverted Gaussian-Laplace filter, is a + bandpass filter. It smooths the data and removes slowly varying + or constant structures (e.g. Background). It is useful for peak or + multi-scale detection. + + This kernel is derived from a normalized Gaussian function, by + computing the second derivative. This results in an amplitude + at the kernels center of 1. / (sqrt(2 * pi) * width ** 3). The + normalization is the same as for `scipy.ndimage.gaussian_laplace`, + except for a minus sign. + + .. note:: + + See https://github.com/astropy/astropy/pull/9445 for discussions + related to renaming of this kernel. + + Parameters + ---------- + width : number + Width of the filter kernel, defined as the standard deviation + of the Gaussian function from which it is derived. + x_size : int, optional + Size in x direction of the kernel array. Default = ⌊8*width +1⌋. + mode : str, optional + One of the following discretization modes: + * 'center' (default) + Discretize model by taking the value + at the center of the bin. + * 'linear_interp' + Discretize model by linearly interpolating + between the values at the corners of the bin. + * 'oversample' + Discretize model by taking the average + on an oversampled grid. + * 'integrate' + Discretize model by integrating the + model over the bin. + factor : number, optional + Factor of oversampling. Default factor = 10. + + + See Also + -------- + Box1DKernel, Gaussian1DKernel, Trapezoid1DKernel + + Examples + -------- + Kernel response: + + .. plot:: + :include-source: + + import matplotlib.pyplot as plt + from astropy.convolution import RickerWavelet1DKernel + ricker_1d_kernel = RickerWavelet1DKernel(10) + plt.plot(ricker_1d_kernel, drawstyle='steps') + plt.xlabel('x [pixels]') + plt.ylabel('value') + plt.show() + + """ + _is_bool = ... + def __init__(self, width, **kwargs) -> None: + ... + + + +class RickerWavelet2DKernel(Kernel2D): + """ + 2D Ricker wavelet filter kernel (sometimes known as a "Mexican Hat" + kernel). + + The Ricker wavelet, or inverted Gaussian-Laplace filter, is a + bandpass filter. It smooths the data and removes slowly varying + or constant structures (e.g. Background). It is useful for peak or + multi-scale detection. + + This kernel is derived from a normalized Gaussian function, by + computing the second derivative. This results in an amplitude + at the kernels center of 1. / (pi * width ** 4). The normalization + is the same as for `scipy.ndimage.gaussian_laplace`, except + for a minus sign. + + .. note:: + + See https://github.com/astropy/astropy/pull/9445 for discussions + related to renaming of this kernel. + + Parameters + ---------- + width : number + Width of the filter kernel, defined as the standard deviation + of the Gaussian function from which it is derived. + x_size : int, optional + Size in x direction of the kernel array. Default = ⌊8*width +1⌋. + y_size : int, optional + Size in y direction of the kernel array. Default = ⌊8*width +1⌋. + mode : str, optional + One of the following discretization modes: + * 'center' (default) + Discretize model by taking the value + at the center of the bin. + * 'linear_interp' + Discretize model by performing a bilinear interpolation + between the values at the corners of the bin. + * 'oversample' + Discretize model by taking the average + on an oversampled grid. + * 'integrate' + Discretize model by integrating the + model over the bin. + factor : number, optional + Factor of oversampling. Default factor = 10. + + + See Also + -------- + Gaussian2DKernel, Box2DKernel, Tophat2DKernel, Ring2DKernel, + TrapezoidDisk2DKernel, AiryDisk2DKernel, Moffat2DKernel + + Examples + -------- + Kernel response: + + .. plot:: + :include-source: + + import matplotlib.pyplot as plt + from astropy.convolution import RickerWavelet2DKernel + ricker_2d_kernel = RickerWavelet2DKernel(10) + plt.imshow(ricker_2d_kernel, interpolation='none', origin='lower') + plt.xlabel('x [pixels]') + plt.ylabel('y [pixels]') + plt.colorbar() + plt.show() + """ + _is_bool = ... + def __init__(self, width, **kwargs) -> None: + ... + + + +class AiryDisk2DKernel(Kernel2D): + """ + 2D Airy disk kernel. + + This kernel models the diffraction pattern of a circular aperture. + + The generated kernel is normalized so that it integrates to 1. + + Parameters + ---------- + radius : float + The radius of the Airy disk kernel (radius of the first zero). + x_size : int, optional + Size in x direction of the kernel array. Default = ⌊8*radius + 1⌋. + y_size : int, optional + Size in y direction of the kernel array. Default = ⌊8*radius + 1⌋. + mode : str, optional + One of the following discretization modes: + * 'center' (default) + Discretize model by taking the value + at the center of the bin. + * 'linear_interp' + Discretize model by performing a bilinear interpolation + between the values at the corners of the bin. + * 'oversample' + Discretize model by taking the average + on an oversampled grid. + * 'integrate' + Discretize model by integrating the + model over the bin. + factor : number, optional + Factor of oversampling. Default factor = 10. + + See Also + -------- + Gaussian2DKernel, Box2DKernel, Tophat2DKernel, RickerWavelet2DKernel, + Ring2DKernel, TrapezoidDisk2DKernel, Moffat2DKernel + + Examples + -------- + Kernel response: + + .. plot:: + :include-source: + + import matplotlib.pyplot as plt + from astropy.convolution import AiryDisk2DKernel + airydisk_2D_kernel = AiryDisk2DKernel(10) + plt.imshow(airydisk_2D_kernel, interpolation='none', origin='lower') + plt.xlabel('x [pixels]') + plt.ylabel('y [pixels]') + plt.colorbar() + plt.show() + """ + _is_bool = ... + def __init__(self, radius, **kwargs) -> None: + ... + + + +class Moffat2DKernel(Kernel2D): + """ + 2D Moffat kernel. + + This kernel is a typical model for a seeing limited PSF. + + The generated kernel is normalized so that it integrates to 1. + + Parameters + ---------- + gamma : float + Core width of the Moffat model. + alpha : float + Power index of the Moffat model. + x_size : int, optional + Size in x direction of the kernel array. Default = ⌊8*radius + 1⌋. + y_size : int, optional + Size in y direction of the kernel array. Default = ⌊8*radius + 1⌋. + mode : str, optional + One of the following discretization modes: + * 'center' (default) + Discretize model by taking the value + at the center of the bin. + * 'linear_interp' + Discretize model by performing a bilinear interpolation + between the values at the corners of the bin. + * 'oversample' + Discretize model by taking the average + on an oversampled grid. + * 'integrate' + Discretize model by integrating the + model over the bin. + factor : number, optional + Factor of oversampling. Default factor = 10. + + See Also + -------- + Gaussian2DKernel, Box2DKernel, Tophat2DKernel, RickerWavelet2DKernel, + Ring2DKernel, TrapezoidDisk2DKernel, AiryDisk2DKernel + + Examples + -------- + Kernel response: + + .. plot:: + :include-source: + + import matplotlib.pyplot as plt + from astropy.convolution import Moffat2DKernel + moffat_2D_kernel = Moffat2DKernel(3, 2) + plt.imshow(moffat_2D_kernel, interpolation='none', origin='lower') + plt.xlabel('x [pixels]') + plt.ylabel('y [pixels]') + plt.colorbar() + plt.show() + """ + _is_bool = ... + def __init__(self, gamma, alpha, **kwargs) -> None: + ... + + + +class Model1DKernel(Kernel1D): + """ + Create kernel from 1D model. + + The model has to be centered on x = 0. + + Parameters + ---------- + model : `~astropy.modeling.Fittable1DModel` + Kernel response function model + x_size : int, optional + Size in x direction of the kernel array. Default = ⌊8*width +1⌋. + Must be odd. + mode : str, optional + One of the following discretization modes: + * 'center' (default) + Discretize model by taking the value + at the center of the bin. + * 'linear_interp' + Discretize model by linearly interpolating + between the values at the corners of the bin. + * 'oversample' + Discretize model by taking the average + on an oversampled grid. + * 'integrate' + Discretize model by integrating the + model over the bin. + factor : number, optional + Factor of oversampling. Default factor = 10. + + Raises + ------ + TypeError + If model is not an instance of `~astropy.modeling.Fittable1DModel` + + See also + -------- + Model2DKernel : Create kernel from `~astropy.modeling.Fittable2DModel` + CustomKernel : Create kernel from list or array + + Examples + -------- + Define a Gaussian1D model: + + >>> from astropy.modeling.models import Gaussian1D + >>> from astropy.convolution.kernels import Model1DKernel + >>> gauss = Gaussian1D(1, 0, 2) + + And create a custom one dimensional kernel from it: + + >>> gauss_kernel = Model1DKernel(gauss, x_size=9) + + This kernel can now be used like a usual Astropy kernel. + """ + _separable = ... + _is_bool = ... + def __init__(self, model, **kwargs) -> None: + ... + + + +class Model2DKernel(Kernel2D): + """ + Create kernel from 2D model. + + The model has to be centered on x = 0 and y = 0. + + Parameters + ---------- + model : `~astropy.modeling.Fittable2DModel` + Kernel response function model + x_size : int, optional + Size in x direction of the kernel array. Default = ⌊8*width +1⌋. + Must be odd. + y_size : int, optional + Size in y direction of the kernel array. Default = ⌊8*width +1⌋. + mode : str, optional + One of the following discretization modes: + * 'center' (default) + Discretize model by taking the value + at the center of the bin. + * 'linear_interp' + Discretize model by performing a bilinear interpolation + between the values at the corners of the bin. + * 'oversample' + Discretize model by taking the average + on an oversampled grid. + * 'integrate' + Discretize model by integrating the + model over the bin. + factor : number, optional + Factor of oversampling. Default factor = 10. + + Raises + ------ + TypeError + If model is not an instance of `~astropy.modeling.Fittable2DModel` + + See also + -------- + Model1DKernel : Create kernel from `~astropy.modeling.Fittable1DModel` + CustomKernel : Create kernel from list or array + + Examples + -------- + Define a Gaussian2D model: + + >>> from astropy.modeling.models import Gaussian2D + >>> from astropy.convolution.kernels import Model2DKernel + >>> gauss = Gaussian2D(1, 0, 0, 2, 2) + + And create a custom two dimensional kernel from it: + + >>> gauss_kernel = Model2DKernel(gauss, x_size=9) + + This kernel can now be used like a usual astropy kernel. + + """ + _is_bool = ... + _separable = ... + def __init__(self, model, **kwargs) -> None: + ... + + + +class PSFKernel(Kernel2D): + """ + Initialize filter kernel from astropy PSF instance. + """ + _separable = ... + def __init__(self) -> None: + ... + + + +class CustomKernel(Kernel): + """ + Create filter kernel from list or array. + + Parameters + ---------- + array : list or array + Filter kernel array. Size must be odd. + + Raises + ------ + TypeError + If array is not a list or array. + `~astropy.convolution.KernelSizeError` + If array size is even. + + See also + -------- + Model2DKernel, Model1DKernel + + Examples + -------- + Define one dimensional array: + + >>> from astropy.convolution.kernels import CustomKernel + >>> import numpy as np + >>> array = np.array([1, 2, 3, 2, 1]) + >>> kernel = CustomKernel(array) + >>> kernel.dimension + 1 + + Define two dimensional array: + + >>> array = np.array([[1, 1, 1], [1, 2, 1], [1, 1, 1]]) + >>> kernel = CustomKernel(array) + >>> kernel.dimension + 2 + """ + def __init__(self, array) -> None: + ... + + @property + def array(self): # -> NDArray[float64]: + """ + Filter kernel array. + """ + ... + + @array.setter + def array(self, array): # -> None: + """ + Filter kernel array setter + """ + ... + + + +@deprecated('4.0', alternative='RickerWavelet1DKernel') +class MexicanHat1DKernel(RickerWavelet1DKernel): + ... + + +@deprecated('4.0', alternative='RickerWavelet2DKernel') +class MexicanHat2DKernel(RickerWavelet2DKernel): + ... + + diff --git a/typings/astropy/convolution/utils.pyi b/typings/astropy/convolution/utils.pyi new file mode 100644 index 0000000..f2c417e --- /dev/null +++ b/typings/astropy/convolution/utils.pyi @@ -0,0 +1,161 @@ +""" +This type stub file was generated by pyright. +""" + +__all__ = ['discretize_model', 'KernelSizeError'] +class DiscretizationError(Exception): + """ + Called when discretization of models goes wrong. + """ + ... + + +class KernelSizeError(Exception): + """ + Called when size of kernels is even. + """ + ... + + +def has_even_axis(array): # -> bool: + ... + +def raise_even_kernel_exception(): + ... + +def add_kernel_arrays_1D(array_1, array_2): + """ + Add two 1D kernel arrays of different size. + + The arrays are added with the centers lying upon each other. + """ + ... + +def add_kernel_arrays_2D(array_1, array_2): + """ + Add two 2D kernel arrays of different size. + + The arrays are added with the centers lying upon each other. + """ + ... + +def discretize_model(model, x_range, y_range=..., mode=..., factor=...): # -> Any | Quantity | tuple[Quantity, ...] | NDArray[floating[Any]] | NDArray[Any] | NDArray[float64] | None: + """ + Function to evaluate analytical model functions on a grid. + + So far the function can only deal with pixel coordinates. + + Parameters + ---------- + model : `~astropy.modeling.Model` or callable. + Analytic model function to be discretized. Callables, which are not an + instances of `~astropy.modeling.Model` are passed to + `~astropy.modeling.custom_model` and then evaluated. + x_range : tuple + x range in which the model is evaluated. The difference between the + upper an lower limit must be a whole number, so that the output array + size is well defined. + y_range : tuple, optional + y range in which the model is evaluated. The difference between the + upper an lower limit must be a whole number, so that the output array + size is well defined. Necessary only for 2D models. + mode : str, optional + One of the following modes: + * ``'center'`` (default) + Discretize model by taking the value + at the center of the bin. + * ``'linear_interp'`` + Discretize model by linearly interpolating + between the values at the corners of the bin. + For 2D models interpolation is bilinear. + * ``'oversample'`` + Discretize model by taking the average + on an oversampled grid. + * ``'integrate'`` + Discretize model by integrating the model + over the bin using `scipy.integrate.quad`. + Very slow. + factor : float or int + Factor of oversampling. Default = 10. + + Returns + ------- + array : `numpy.array` + Model value array + + Notes + ----- + The ``oversample`` mode allows to conserve the integral on a subpixel + scale. Here is the example of a normalized Gaussian1D: + + .. plot:: + :include-source: + + import matplotlib.pyplot as plt + import numpy as np + from astropy.modeling.models import Gaussian1D + from astropy.convolution.utils import discretize_model + gauss_1D = Gaussian1D(1 / (0.5 * np.sqrt(2 * np.pi)), 0, 0.5) + y_center = discretize_model(gauss_1D, (-2, 3), mode='center') + y_corner = discretize_model(gauss_1D, (-2, 3), mode='linear_interp') + y_oversample = discretize_model(gauss_1D, (-2, 3), mode='oversample') + plt.plot(y_center, label='center sum = {0:3f}'.format(y_center.sum())) + plt.plot(y_corner, label='linear_interp sum = {0:3f}'.format(y_corner.sum())) + plt.plot(y_oversample, label='oversample sum = {0:3f}'.format(y_oversample.sum())) + plt.xlabel('pixels') + plt.ylabel('value') + plt.legend() + plt.show() + + + """ + ... + +def discretize_center_1D(model, x_range): + """ + Discretize model by taking the value at the center of the bin. + """ + ... + +def discretize_center_2D(model, x_range, y_range): + """ + Discretize model by taking the value at the center of the pixel. + """ + ... + +def discretize_linear_1D(model, x_range): + """ + Discretize model by performing a linear interpolation. + """ + ... + +def discretize_bilinear_2D(model, x_range, y_range): + """ + Discretize model by performing a bilinear interpolation. + """ + ... + +def discretize_oversample_1D(model, x_range, factor=...): # -> Any: + """ + Discretize model by taking the average on an oversampled grid. + """ + ... + +def discretize_oversample_2D(model, x_range, y_range, factor=...): # -> Any: + """ + Discretize model by taking the average on an oversampled grid. + """ + ... + +def discretize_integrate_1D(model, x_range): # -> NDArray[Any]: + """ + Discretize model by integrating numerically the model over the bin. + """ + ... + +def discretize_integrate_2D(model, x_range, y_range): # -> NDArray[float64]: + """ + Discretize model by integrating the model over the pixel. + """ + ... + diff --git a/typings/astropy/coordinates/__init__.pyi b/typings/astropy/coordinates/__init__.pyi new file mode 100644 index 0000000..cf7839a --- /dev/null +++ b/typings/astropy/coordinates/__init__.pyi @@ -0,0 +1,28 @@ +""" +This type stub file was generated by pyright. +""" + +from .errors import * +from .angles import * +from .baseframe import * +from .attributes import * +from .distances import * +from .earth import * +from .transformations import * +from .builtin_frames import * +from .name_resolve import * +from .matching import * +from .representation import * +from .sky_coordinate import * +from .funcs import * +from .calculation import * +from .solar_system import * +from .spectral_quantity import * +from .spectral_coordinate import * +from .angle_utilities import * + +""" +This subpackage contains classes and functions for celestial coordinates +of astronomical objects. It also contains a framework for conversions +between coordinate systems. +""" diff --git a/typings/astropy/coordinates/angle_formats.pyi b/typings/astropy/coordinates/angle_formats.pyi new file mode 100644 index 0000000..bc4c00a --- /dev/null +++ b/typings/astropy/coordinates/angle_formats.pyi @@ -0,0 +1,186 @@ +""" +This type stub file was generated by pyright. +""" + +from astropy.utils.decorators import deprecated + +""" +This module contains formatting functions that are for internal use in +astropy.coordinates.angles. Mainly they are conversions from one format +of data to another. +""" +class _AngleParser: + """ + Parses the various angle formats including: + + * 01:02:30.43 degrees + * 1 2 0 hours + * 1°2′3″ + * 1d2m3s + * -1h2m3s + * 1°2′3″N + + This class should not be used directly. Use `parse_angle` + instead. + """ + _thread_local = ... + def __init__(self) -> None: + ... + + def parse(self, angle, unit, debug=...): # -> tuple[Any, Any]: + ... + + + +def check_hms_ranges(h, m, s): # -> None: + """ + Checks that the given hour, minute and second are all within + reasonable range. + """ + ... + +def parse_angle(angle, unit=..., debug=...): # -> tuple[Any, Any]: + """ + Parses an input string value into an angle value. + + Parameters + ---------- + angle : str + A string representing the angle. May be in one of the following forms: + + * 01:02:30.43 degrees + * 1 2 0 hours + * 1°2′3″ + * 1d2m3s + * -1h2m3s + + unit : `~astropy.units.UnitBase` instance, optional + The unit used to interpret the string. If ``unit`` is not + provided, the unit must be explicitly represented in the + string, either at the end or as number separators. + + debug : bool, optional + If `True`, print debugging information from the parser. + + Returns + ------- + value, unit : tuple + ``value`` is the value as a floating point number or three-part + tuple, and ``unit`` is a `Unit` instance which is either the + unit passed in or the one explicitly mentioned in the input + string. + """ + ... + +def degrees_to_dms(d): # -> tuple[Any, Any, Any]: + """ + Convert a floating-point degree value into a ``(degree, arcminute, + arcsecond)`` tuple. + """ + ... + +@deprecated("dms_to_degrees (or creating an Angle with a tuple) has ambiguous " "behavior when the degree value is 0", alternative="another way of creating angles instead (e.g. a less " "ambiguous string like '-0d1m2.3s'") +def dms_to_degrees(d, m, s=...): # -> Any: + """ + Convert degrees, arcminute, arcsecond to a float degrees value. + """ + ... + +@deprecated("hms_to_hours (or creating an Angle with a tuple) has ambiguous " "behavior when the hour value is 0", alternative="another way of creating angles instead (e.g. a less " "ambiguous string like '-0h1m2.3s'") +def hms_to_hours(h, m, s=...): # -> Any: + """ + Convert hour, minute, second to a float hour value. + """ + ... + +def hms_to_degrees(h, m, s): # -> Any: + """ + Convert hour, minute, second to a float degrees value. + """ + ... + +def hms_to_radians(h, m, s): # -> float | Any: + """ + Convert hour, minute, second to a float radians value. + """ + ... + +def hms_to_dms(h, m, s): # -> tuple[Any, Any, Any]: + """ + Convert degrees, arcminutes, arcseconds to an ``(hour, minute, second)`` + tuple. + """ + ... + +def hours_to_decimal(h): # -> float | NDArray[void] | Any: + """ + Convert any parseable hour value into a float value. + """ + ... + +def hours_to_radians(h): # -> float | Any: + """ + Convert an angle in Hours to Radians. + """ + ... + +def hours_to_hms(h): # -> tuple[Any, Any, Any]: + """ + Convert an floating-point hour value into an ``(hour, minute, + second)`` tuple. + """ + ... + +def radians_to_degrees(r): # -> float | Any: + """ + Convert an angle in Radians to Degrees. + """ + ... + +def radians_to_hours(r): # -> float | Any: + """ + Convert an angle in Radians to Hours. + """ + ... + +def radians_to_hms(r): # -> tuple[Any, Any, Any]: + """ + Convert an angle in Radians to an ``(hour, minute, second)`` tuple. + """ + ... + +def radians_to_dms(r): # -> tuple[Any, Any, Any]: + """ + Convert an angle in Radians to an ``(degree, arcminute, + arcsecond)`` tuple. + """ + ... + +def sexagesimal_to_string(values, precision=..., pad=..., sep=..., fields=...): # -> str: + """ + Given an already separated tuple of sexagesimal values, returns + a string. + + See `hours_to_string` and `degrees_to_string` for a higher-level + interface to this functionality. + """ + ... + +def hours_to_string(h, precision=..., pad=..., sep=..., fields=...): # -> str: + """ + Takes a decimal hour value and returns a string formatted as hms with + separator specified by the 'sep' parameter. + + ``h`` must be a scalar. + """ + ... + +def degrees_to_string(d, precision=..., pad=..., sep=..., fields=...): # -> str: + """ + Takes a decimal hour value and returns a string formatted as dms with + separator specified by the 'sep' parameter. + + ``d`` must be a scalar. + """ + ... + diff --git a/typings/astropy/coordinates/angle_utilities.pyi b/typings/astropy/coordinates/angle_utilities.pyi new file mode 100644 index 0000000..b4b1192 --- /dev/null +++ b/typings/astropy/coordinates/angle_utilities.pyi @@ -0,0 +1,131 @@ +""" +This type stub file was generated by pyright. +""" + +""" +This module contains utility functions for working with angles. These are both +used internally in astropy.coordinates.angles, and of possible +""" +__all__ = ['angular_separation', 'position_angle', 'offset_by', 'golden_spiral_grid', 'uniform_spherical_random_surface', 'uniform_spherical_random_volume'] +def angular_separation(lon1, lat1, lon2, lat2): # -> Any: + """ + Angular separation between two points on a sphere. + + Parameters + ---------- + lon1, lat1, lon2, lat2 : `~astropy.coordinates.Angle`, `~astropy.units.Quantity` or float + Longitude and latitude of the two points. Quantities should be in + angular units; floats in radians. + + Returns + ------- + angular separation : `~astropy.units.Quantity` ['angle'] or float + Type depends on input; ``Quantity`` in angular units, or float in + radians. + + Notes + ----- + The angular separation is calculated using the Vincenty formula [1]_, + which is slightly more complex and computationally expensive than + some alternatives, but is stable at at all distances, including the + poles and antipodes. + + .. [1] https://en.wikipedia.org/wiki/Great-circle_distance + """ + ... + +def position_angle(lon1, lat1, lon2, lat2): # -> Angle | None: + """ + Position Angle (East of North) between two points on a sphere. + + Parameters + ---------- + lon1, lat1, lon2, lat2 : `~astropy.coordinates.Angle`, `~astropy.units.Quantity` or float + Longitude and latitude of the two points. Quantities should be in + angular units; floats in radians. + + Returns + ------- + pa : `~astropy.coordinates.Angle` + The (positive) position angle of the vector pointing from position 1 to + position 2. If any of the angles are arrays, this will contain an array + following the appropriate `numpy` broadcasting rules. + + """ + ... + +def offset_by(lon, lat, posang, distance): # -> tuple[Unknown, Self@Quantity | Quantity | Any | Unknown]: + """ + Point with the given offset from the given point. + + Parameters + ---------- + lon, lat, posang, distance : `~astropy.coordinates.Angle`, `~astropy.units.Quantity` or float + Longitude and latitude of the starting point, + position angle and distance to the final point. + Quantities should be in angular units; floats in radians. + Polar points at lat= +/-90 are treated as limit of +/-(90-epsilon) and same lon. + + Returns + ------- + lon, lat : `~astropy.coordinates.Angle` + The position of the final point. If any of the angles are arrays, + these will contain arrays following the appropriate `numpy` broadcasting rules. + 0 <= lon < 2pi. + """ + ... + +def golden_spiral_grid(size): # -> UnitSphericalRepresentation: + """Generate a grid of points on the surface of the unit sphere using the + Fibonacci or Golden Spiral method. + + .. seealso:: + + `Evenly distributing points on a sphere `_ + + Parameters + ---------- + size : int + The number of points to generate. + + Returns + ------- + rep : `~astropy.coordinates.UnitSphericalRepresentation` + The grid of points. + """ + ... + +def uniform_spherical_random_surface(size=...): # -> UnitSphericalRepresentation: + """Generate a random sampling of points on the surface of the unit sphere. + + Parameters + ---------- + size : int + The number of points to generate. + + Returns + ------- + rep : `~astropy.coordinates.UnitSphericalRepresentation` + The random points. + """ + ... + +def uniform_spherical_random_volume(size=..., max_radius=...): # -> SphericalRepresentation: + """Generate a random sampling of points that follow a uniform volume + density distribution within a sphere. + + Parameters + ---------- + size : int + The number of points to generate. + max_radius : number, quantity-like, optional + A dimensionless or unit-ful factor to scale the random distances. + + Returns + ------- + rep : `~astropy.coordinates.SphericalRepresentation` + The random points. + """ + ... + +__old_angle_utilities_funcs = ... diff --git a/typings/astropy/coordinates/angles.pyi b/typings/astropy/coordinates/angles.pyi new file mode 100644 index 0000000..5e6b83e --- /dev/null +++ b/typings/astropy/coordinates/angles.pyi @@ -0,0 +1,424 @@ +""" +This type stub file was generated by pyright. +""" + +from astropy import units as u + +""" +This module contains the fundamental classes used for representing +coordinates in astropy. +""" +__all__ = ['Angle', 'Latitude', 'Longitude'] +hms_tuple = ... +dms_tuple = ... +signed_dms_tuple = ... +class Angle(u.SpecificTypeQuantity): + """ + One or more angular value(s) with units equivalent to radians or degrees. + + An angle can be specified either as an array, scalar, tuple (see + below), string, `~astropy.units.Quantity` or another + :class:`~astropy.coordinates.Angle`. + + The input parser is flexible and supports a variety of formats. + The examples below illustrate common ways of initializing an `Angle` + object. First some imports:: + + >>> from astropy.coordinates import Angle + >>> from astropy import units as u + + The angle values can now be provided:: + + >>> Angle('10.2345d') + + >>> Angle(['10.2345d', '-20d']) + + >>> Angle('1:2:30.43 degrees') + + >>> Angle('1 2 0 hours') + + >>> Angle(np.arange(1, 8), unit=u.deg) + + >>> Angle('1°2′3″') + + >>> Angle('1°2′3″N') + + >>> Angle('1d2m3.4s') + + >>> Angle('1d2m3.4sS') + + >>> Angle('-1h2m3s') + + >>> Angle('-1h2m3sE') + + >>> Angle('-1h2.5m') + + >>> Angle('-1h2.5mW') + + >>> Angle('-1:2.5', unit=u.deg) + + >>> Angle(10.2345 * u.deg) + + >>> Angle(Angle(10.2345 * u.deg)) + + + Parameters + ---------- + angle : `~numpy.array`, scalar, `~astropy.units.Quantity`, :class:`~astropy.coordinates.Angle` + The angle value. If a tuple, will be interpreted as ``(h, m, + s)`` or ``(d, m, s)`` depending on ``unit``. If a string, it + will be interpreted following the rules described above. + + If ``angle`` is a sequence or array of strings, the resulting + values will be in the given ``unit``, or if `None` is provided, + the unit will be taken from the first given value. + + unit : unit-like, optional + The unit of the value specified for the angle. This may be + any string that `~astropy.units.Unit` understands, but it is + better to give an actual unit object. Must be an angular + unit. + + dtype : `~numpy.dtype`, optional + See `~astropy.units.Quantity`. + + copy : bool, optional + See `~astropy.units.Quantity`. + + Raises + ------ + `~astropy.units.UnitsError` + If a unit is not provided or it is not an angular unit. + """ + _equivalent_unit = ... + _include_easy_conversion_members = ... + def __new__(cls, angle, unit=..., dtype=..., copy=..., **kwargs): + ... + + @property + def hour(self): # -> float | NDArray[void] | Any: + """ + The angle's value in hours (read-only property). + """ + ... + + @property + def hms(self): # -> hms_tuple: + """ + The angle's value in hours, as a named tuple with ``(h, m, s)`` + members. (This is a read-only property.) + """ + ... + + @property + def dms(self): # -> dms_tuple: + """ + The angle's value in degrees, as a named tuple with ``(d, m, s)`` + members. (This is a read-only property.) + """ + ... + + @property + def signed_dms(self): # -> signed_dms_tuple: + """ + The angle's value in degrees, as a named tuple with ``(sign, d, m, s)`` + members. The ``d``, ``m``, ``s`` are thus always positive, and the sign of + the angle is given by ``sign``. (This is a read-only property.) + + This is primarily intended for use with `dms` to generate string + representations of coordinates that are correct for negative angles. + """ + ... + + def to_string(self, unit=..., decimal=..., sep=..., precision=..., alwayssign=..., pad=..., fields=..., format=...): # -> Any: + """ A string representation of the angle. + + Parameters + ---------- + unit : `~astropy.units.UnitBase`, optional + Specifies the unit. Must be an angular unit. If not + provided, the unit used to initialize the angle will be + used. + + decimal : bool, optional + If `True`, a decimal representation will be used, otherwise + the returned string will be in sexagesimal form. + + sep : str, optional + The separator between numbers in a sexagesimal + representation. E.g., if it is ':', the result is + ``'12:41:11.1241'``. Also accepts 2 or 3 separators. E.g., + ``sep='hms'`` would give the result ``'12h41m11.1241s'``, or + sep='-:' would yield ``'11-21:17.124'``. Alternatively, the + special string 'fromunit' means 'dms' if the unit is + degrees, or 'hms' if the unit is hours. + + precision : int, optional + The level of decimal precision. If ``decimal`` is `True`, + this is the raw precision, otherwise it gives the + precision of the last place of the sexagesimal + representation (seconds). If `None`, or not provided, the + number of decimal places is determined by the value, and + will be between 0-8 decimal places as required. + + alwayssign : bool, optional + If `True`, include the sign no matter what. If `False`, + only include the sign if it is negative. + + pad : bool, optional + If `True`, include leading zeros when needed to ensure a + fixed number of characters for sexagesimal representation. + + fields : int, optional + Specifies the number of fields to display when outputting + sexagesimal notation. For example: + + - fields == 1: ``'5d'`` + - fields == 2: ``'5d45m'`` + - fields == 3: ``'5d45m32.5s'`` + + By default, all fields are displayed. + + format : str, optional + The format of the result. If not provided, an unadorned + string is returned. Supported values are: + + - 'latex': Return a LaTeX-formatted string + + - 'latex_inline': Return a LaTeX-formatted string which is the + same as with ``format='latex'`` for |Angle| instances + + - 'unicode': Return a string containing non-ASCII unicode + characters, such as the degree symbol + + Returns + ------- + strrepr : str or array + A string representation of the angle. If the angle is an array, this + will be an array with a unicode dtype. + + """ + ... + + def wrap_at(self, wrap_angle, inplace=...): # -> Self@Angle | None: + """ + Wrap the `~astropy.coordinates.Angle` object at the given ``wrap_angle``. + + This method forces all the angle values to be within a contiguous + 360 degree range so that ``wrap_angle - 360d <= angle < + wrap_angle``. By default a new Angle object is returned, but if the + ``inplace`` argument is `True` then the `~astropy.coordinates.Angle` + object is wrapped in place and nothing is returned. + + For instance:: + + >>> from astropy.coordinates import Angle + >>> import astropy.units as u + >>> a = Angle([-20.0, 150.0, 350.0] * u.deg) + + >>> a.wrap_at(360 * u.deg).degree # Wrap into range 0 to 360 degrees # doctest: +FLOAT_CMP + array([340., 150., 350.]) + + >>> a.wrap_at('180d', inplace=True) # Wrap into range -180 to 180 degrees # doctest: +FLOAT_CMP + >>> a.degree # doctest: +FLOAT_CMP + array([-20., 150., -10.]) + + Parameters + ---------- + wrap_angle : angle-like + Specifies a single value for the wrap angle. This can be any + object that can initialize an `~astropy.coordinates.Angle` object, + e.g. ``'180d'``, ``180 * u.deg``, or ``Angle(180, unit=u.deg)``. + + inplace : bool + If `True` then wrap the object in place instead of returning + a new `~astropy.coordinates.Angle` + + Returns + ------- + out : Angle or None + If ``inplace is False`` (default), return new + `~astropy.coordinates.Angle` object with angles wrapped accordingly. + Otherwise wrap in place and return `None`. + """ + ... + + def is_within_bounds(self, lower=..., upper=...): # -> bool: + """ + Check if all angle(s) satisfy ``lower <= angle < upper`` + + If ``lower`` is not specified (or `None`) then no lower bounds check is + performed. Likewise ``upper`` can be left unspecified. For example:: + + >>> from astropy.coordinates import Angle + >>> import astropy.units as u + >>> a = Angle([-20, 150, 350] * u.deg) + >>> a.is_within_bounds('0d', '360d') + False + >>> a.is_within_bounds(None, '360d') + True + >>> a.is_within_bounds(-30 * u.deg, None) + True + + Parameters + ---------- + lower : angle-like or None + Specifies lower bound for checking. This can be any object + that can initialize an `~astropy.coordinates.Angle` object, e.g. ``'180d'``, + ``180 * u.deg``, or ``Angle(180, unit=u.deg)``. + upper : angle-like or None + Specifies upper bound for checking. This can be any object + that can initialize an `~astropy.coordinates.Angle` object, e.g. ``'180d'``, + ``180 * u.deg``, or ``Angle(180, unit=u.deg)``. + + Returns + ------- + is_within_bounds : bool + `True` if all angles satisfy ``lower <= angle < upper`` + """ + ... + + def __str__(self) -> str: + ... + + + +class Latitude(Angle): + """ + Latitude-like angle(s) which must be in the range -90 to +90 deg. + + A Latitude object is distinguished from a pure + :class:`~astropy.coordinates.Angle` by virtue of being constrained + so that:: + + -90.0 * u.deg <= angle(s) <= +90.0 * u.deg + + Any attempt to set a value outside that range will result in a + `ValueError`. + + The input angle(s) can be specified either as an array, list, + scalar, tuple (see below), string, + :class:`~astropy.units.Quantity` or another + :class:`~astropy.coordinates.Angle`. + + The input parser is flexible and supports all of the input formats + supported by :class:`~astropy.coordinates.Angle`. + + Parameters + ---------- + angle : array, list, scalar, `~astropy.units.Quantity`, `~astropy.coordinates.Angle` + The angle value(s). If a tuple, will be interpreted as ``(h, m, s)`` + or ``(d, m, s)`` depending on ``unit``. If a string, it will be + interpreted following the rules described for + :class:`~astropy.coordinates.Angle`. + + If ``angle`` is a sequence or array of strings, the resulting + values will be in the given ``unit``, or if `None` is provided, + the unit will be taken from the first given value. + + unit : unit-like, optional + The unit of the value specified for the angle. This may be + any string that `~astropy.units.Unit` understands, but it is + better to give an actual unit object. Must be an angular + unit. + + Raises + ------ + `~astropy.units.UnitsError` + If a unit is not provided or it is not an angular unit. + `TypeError` + If the angle parameter is an instance of :class:`~astropy.coordinates.Longitude`. + """ + def __new__(cls, angle, unit=..., **kwargs): + ... + + def __setitem__(self, item, value): # -> None: + ... + + def __array_ufunc__(self, *args, **kwargs): # -> tuple[Unknown, ...] | Angle | Any | list[Unknown] | Quantity: + ... + + + +class LongitudeInfo(u.QuantityInfo): + _represent_as_dict_attrs = ... + + +class Longitude(Angle): + """ + Longitude-like angle(s) which are wrapped within a contiguous 360 degree range. + + A ``Longitude`` object is distinguished from a pure + :class:`~astropy.coordinates.Angle` by virtue of a ``wrap_angle`` + property. The ``wrap_angle`` specifies that all angle values + represented by the object will be in the range:: + + wrap_angle - 360 * u.deg <= angle(s) < wrap_angle + + The default ``wrap_angle`` is 360 deg. Setting ``wrap_angle=180 * + u.deg`` would instead result in values between -180 and +180 deg. + Setting the ``wrap_angle`` attribute of an existing ``Longitude`` + object will result in re-wrapping the angle values in-place. + + The input angle(s) can be specified either as an array, list, + scalar, tuple, string, :class:`~astropy.units.Quantity` + or another :class:`~astropy.coordinates.Angle`. + + The input parser is flexible and supports all of the input formats + supported by :class:`~astropy.coordinates.Angle`. + + Parameters + ---------- + angle : tuple or angle-like + The angle value(s). If a tuple, will be interpreted as ``(h, m s)`` or + ``(d, m, s)`` depending on ``unit``. If a string, it will be interpreted + following the rules described for :class:`~astropy.coordinates.Angle`. + + If ``angle`` is a sequence or array of strings, the resulting + values will be in the given ``unit``, or if `None` is provided, + the unit will be taken from the first given value. + + unit : unit-like ['angle'], optional + The unit of the value specified for the angle. This may be + any string that `~astropy.units.Unit` understands, but it is + better to give an actual unit object. Must be an angular + unit. + + wrap_angle : angle-like or None, optional + Angle at which to wrap back to ``wrap_angle - 360 deg``. + If ``None`` (default), it will be taken to be 360 deg unless ``angle`` + has a ``wrap_angle`` attribute already (i.e., is a ``Longitude``), + in which case it will be taken from there. + + Raises + ------ + `~astropy.units.UnitsError` + If a unit is not provided or it is not an angular unit. + `TypeError` + If the angle parameter is an instance of :class:`~astropy.coordinates.Latitude`. + """ + _wrap_angle = ... + _default_wrap_angle = ... + info = ... + def __new__(cls, angle, unit=..., wrap_angle=..., **kwargs): + ... + + def __setitem__(self, item, value): # -> None: + ... + + @property + def wrap_angle(self): # -> Angle | Any | None: + ... + + @wrap_angle.setter + def wrap_angle(self, value): # -> None: + ... + + def __array_finalize__(self, obj): # -> None: + ... + + def __array_ufunc__(self, *args, **kwargs): # -> tuple[Unknown, ...] | Angle | Any | list[Unknown] | Quantity: + ... + + + diff --git a/typings/astropy/coordinates/attributes.pyi b/typings/astropy/coordinates/attributes.pyi new file mode 100644 index 0000000..dfefbf1 --- /dev/null +++ b/typings/astropy/coordinates/attributes.pyi @@ -0,0 +1,354 @@ +""" +This type stub file was generated by pyright. +""" + +__all__ = ['Attribute', 'TimeAttribute', 'QuantityAttribute', 'EarthLocationAttribute', 'CoordinateAttribute', 'CartesianRepresentationAttribute', 'DifferentialAttribute'] +class Attribute: + """A non-mutable data descriptor to hold a frame attribute. + + This class must be used to define frame attributes (e.g. ``equinox`` or + ``obstime``) that are included in a frame class definition. + + Examples + -------- + The `~astropy.coordinates.FK4` class uses the following class attributes:: + + class FK4(BaseCoordinateFrame): + equinox = TimeAttribute(default=_EQUINOX_B1950) + obstime = TimeAttribute(default=None, + secondary_attribute='equinox') + + This means that ``equinox`` and ``obstime`` are available to be set as + keyword arguments when creating an ``FK4`` class instance and are then + accessible as instance attributes. The instance value for the attribute + must be stored in ``'_' + `` by the frame ``__init__`` + method. + + Note in this example that ``equinox`` and ``obstime`` are time attributes + and use the ``TimeAttributeFrame`` class. This subclass overrides the + ``convert_input`` method to validate and convert inputs into a ``Time`` + object. + + Parameters + ---------- + default : object + Default value for the attribute if not provided + secondary_attribute : str + Name of a secondary instance attribute which supplies the value if + ``default is None`` and no value was supplied during initialization. + """ + name = ... + def __init__(self, default=..., secondary_attribute=...) -> None: + ... + + def __set_name__(self, owner, name): # -> None: + ... + + def convert_input(self, value): # -> tuple[Unknown, Literal[False]]: + """ + Validate the input ``value`` and convert to expected attribute class. + + The base method here does nothing, but subclasses can implement this + as needed. The method should catch any internal exceptions and raise + ValueError with an informative message. + + The method returns the validated input along with a boolean that + indicates whether the input value was actually converted. If the input + value was already the correct type then the ``converted`` return value + should be ``False``. + + Parameters + ---------- + value : object + Input value to be converted. + + Returns + ------- + output_value : object + The ``value`` converted to the correct type (or just ``value`` if + ``converted`` is False) + converted : bool + True if the conversion was actually performed, False otherwise. + + Raises + ------ + ValueError + If the input is not valid for this attribute. + + """ + ... + + def __get__(self, instance, frame_cls=...): # -> Any | None: + ... + + def __set__(self, instance, val): + ... + + + +class TimeAttribute(Attribute): + """ + Frame attribute descriptor for quantities that are Time objects. + See the `~astropy.coordinates.Attribute` API doc for further + information. + + Parameters + ---------- + default : object + Default value for the attribute if not provided + secondary_attribute : str + Name of a secondary instance attribute which supplies the value if + ``default is None`` and no value was supplied during initialization. + """ + def convert_input(self, value): # -> tuple[None, Literal[False]] | tuple[Time, bool]: + """ + Convert input value to a Time object and validate by running through + the Time constructor. Also check that the input was a scalar. + + Parameters + ---------- + value : object + Input value to be converted. + + Returns + ------- + out, converted : correctly-typed object, boolean + Tuple consisting of the correctly-typed object and a boolean which + indicates if conversion was actually performed. + + Raises + ------ + ValueError + If the input is not valid for this attribute. + """ + ... + + + +class CartesianRepresentationAttribute(Attribute): + """ + A frame attribute that is a CartesianRepresentation with specified units. + + Parameters + ---------- + default : object + Default value for the attribute if not provided + secondary_attribute : str + Name of a secondary instance attribute which supplies the value if + ``default is None`` and no value was supplied during initialization. + unit : unit-like or None + Name of a unit that the input will be converted into. If None, no + unit-checking or conversion is performed + """ + def __init__(self, default=..., secondary_attribute=..., unit=...) -> None: + ... + + def convert_input(self, value): # -> tuple[CartesianRepresentation, Literal[True]] | tuple[Unknown | list[Unknown], Literal[False]]: + """ + Checks that the input is a CartesianRepresentation with the correct + unit, or the special value ``[0, 0, 0]``. + + Parameters + ---------- + value : object + Input value to be converted. + + Returns + ------- + out : object + The correctly-typed object. + converted : boolean + A boolean which indicates if conversion was actually performed. + + Raises + ------ + ValueError + If the input is not valid for this attribute. + """ + ... + + + +class QuantityAttribute(Attribute): + """ + A frame attribute that is a quantity with specified units and shape + (optionally). + + Can be `None`, which should be used for special cases in associated + frame transformations like "this quantity should be ignored" or similar. + + Parameters + ---------- + default : number or `~astropy.units.Quantity` or None, optional + Default value for the attribute if the user does not supply one. If a + Quantity, it must be consistent with ``unit``, or if a value, ``unit`` + cannot be None. + secondary_attribute : str, optional + Name of a secondary instance attribute which supplies the value if + ``default is None`` and no value was supplied during initialization. + unit : unit-like or None, optional + Name of a unit that the input will be converted into. If None, no + unit-checking or conversion is performed + shape : tuple or None, optional + If given, specifies the shape the attribute must be + """ + def __init__(self, default=..., secondary_attribute=..., unit=..., shape=...) -> None: + ... + + def convert_input(self, value): # -> tuple[None, Literal[False]] | tuple[NDArray[Unknown] | Quantity, bool]: + """ + Checks that the input is a Quantity with the necessary units (or the + special value ``0``). + + Parameters + ---------- + value : object + Input value to be converted. + + Returns + ------- + out, converted : correctly-typed object, boolean + Tuple consisting of the correctly-typed object and a boolean which + indicates if conversion was actually performed. + + Raises + ------ + ValueError + If the input is not valid for this attribute. + """ + ... + + + +class EarthLocationAttribute(Attribute): + """ + A frame attribute that can act as a `~astropy.coordinates.EarthLocation`. + It can be created as anything that can be transformed to the + `~astropy.coordinates.ITRS` frame, but always presents as an `EarthLocation` + when accessed after creation. + + Parameters + ---------- + default : object + Default value for the attribute if not provided + secondary_attribute : str + Name of a secondary instance attribute which supplies the value if + ``default is None`` and no value was supplied during initialization. + """ + def convert_input(self, value): # -> tuple[None, Literal[False]] | tuple[EarthLocation, Literal[False]] | tuple[Unknown, Literal[True]]: + """ + Checks that the input is a Quantity with the necessary units (or the + special value ``0``). + + Parameters + ---------- + value : object + Input value to be converted. + + Returns + ------- + out, converted : correctly-typed object, boolean + Tuple consisting of the correctly-typed object and a boolean which + indicates if conversion was actually performed. + + Raises + ------ + ValueError + If the input is not valid for this attribute. + """ + ... + + + +class CoordinateAttribute(Attribute): + """ + A frame attribute which is a coordinate object. It can be given as a + `~astropy.coordinates.SkyCoord` or a low-level frame instance. If a + low-level frame instance is provided, it will always be upgraded to be a + `~astropy.coordinates.SkyCoord` to ensure consistent transformation + behavior. The coordinate object will always be returned as a low-level + frame instance when accessed. + + Parameters + ---------- + frame : `~astropy.coordinates.BaseCoordinateFrame` class + The type of frame this attribute can be + default : object + Default value for the attribute if not provided + secondary_attribute : str + Name of a secondary instance attribute which supplies the value if + ``default is None`` and no value was supplied during initialization. + """ + def __init__(self, frame, default=..., secondary_attribute=...) -> None: + ... + + def convert_input(self, value): # -> tuple[None, Literal[False]] | tuple[Unknown, Literal[False]] | tuple[Unknown | BaseCoordinateFrame, Literal[True]]: + """ + Checks that the input is a SkyCoord with the necessary units (or the + special value ``None``). + + Parameters + ---------- + value : object + Input value to be converted. + + Returns + ------- + out, converted : correctly-typed object, boolean + Tuple consisting of the correctly-typed object and a boolean which + indicates if conversion was actually performed. + + Raises + ------ + ValueError + If the input is not valid for this attribute. + """ + ... + + + +class DifferentialAttribute(Attribute): + """A frame attribute which is a differential instance. + + The optional ``allowed_classes`` argument allows specifying a restricted + set of valid differential classes to check the input against. Otherwise, + any `~astropy.coordinates.BaseDifferential` subclass instance is valid. + + Parameters + ---------- + default : object + Default value for the attribute if not provided + allowed_classes : tuple, optional + A list of allowed differential classes for this attribute to have. + secondary_attribute : str + Name of a secondary instance attribute which supplies the value if + ``default is None`` and no value was supplied during initialization. + """ + def __init__(self, default=..., allowed_classes=..., secondary_attribute=...) -> None: + ... + + def convert_input(self, value): # -> tuple[None, Literal[False]] | tuple[Unknown | BaseDifferential, Literal[True]]: + """ + Checks that the input is a differential object and is one of the + allowed class types. + + Parameters + ---------- + value : object + Input value. + + Returns + ------- + out, converted : correctly-typed object, boolean + Tuple consisting of the correctly-typed object and a boolean which + indicates if conversion was actually performed. + + Raises + ------ + ValueError + If the input is not valid for this attribute. + """ + ... + + + diff --git a/typings/astropy/coordinates/baseframe.pyi b/typings/astropy/coordinates/baseframe.pyi new file mode 100644 index 0000000..44bd015 --- /dev/null +++ b/typings/astropy/coordinates/baseframe.pyi @@ -0,0 +1,621 @@ +""" +This type stub file was generated by pyright. +""" + +from astropy.utils.compat.misc import override__dir__ +from astropy.utils.decorators import format_doc, lazyproperty +from astropy.utils import ShapedLikeNDArray + +""" +Framework and base classes for coordinate frames/"low-level" coordinate +classes. +""" +__all__ = ['BaseCoordinateFrame', 'frame_transform_graph', 'GenericFrame', 'RepresentationMapping'] +frame_transform_graph = ... +_RepresentationMappingBase = ... +class RepresentationMapping(_RepresentationMappingBase): + """ + This `~collections.namedtuple` is used with the + ``frame_specific_representation_info`` attribute to tell frames what + attribute names (and default units) to use for a particular representation. + ``reprname`` and ``framename`` should be strings, while ``defaultunit`` can + be either an astropy unit, the string ``'recommended'`` (which is degrees + for Angles, nothing otherwise), or None (to indicate that no unit mapping + should be done). + """ + def __new__(cls, reprname, framename, defaultunit=...): # -> Self@RepresentationMapping: + ... + + + +base_doc = ... +_components = ... +@format_doc(base_doc, components=_components, footer="") +class BaseCoordinateFrame(ShapedLikeNDArray): + """ + The base class for coordinate frames. + + This class is intended to be subclassed to create instances of specific + systems. Subclasses can implement the following attributes: + + * `default_representation` + A subclass of `~astropy.coordinates.BaseRepresentation` that will be + treated as the default representation of this frame. This is the + representation assumed by default when the frame is created. + + * `default_differential` + A subclass of `~astropy.coordinates.BaseDifferential` that will be + treated as the default differential class of this frame. This is the + differential class assumed by default when the frame is created. + + * `~astropy.coordinates.Attribute` class attributes + Frame attributes such as ``FK4.equinox`` or ``FK4.obstime`` are defined + using a descriptor class. See the narrative documentation or + built-in classes code for details. + + * `frame_specific_representation_info` + A dictionary mapping the name or class of a representation to a list of + `~astropy.coordinates.RepresentationMapping` objects that tell what + names and default units should be used on this frame for the components + of that representation. + + Unless overridden via `frame_specific_representation_info`, velocity name + defaults are: + + * ``pm_{lon}_cos{lat}``, ``pm_{lat}`` for `SphericalCosLatDifferential` + proper motion components + * ``pm_{lon}``, ``pm_{lat}`` for `SphericalDifferential` proper motion + components + * ``radial_velocity`` for any ``d_distance`` component + * ``v_{x,y,z}`` for `CartesianDifferential` velocity components + + where ``{lon}`` and ``{lat}`` are the frame names of the angular components. + """ + default_representation = ... + default_differential = ... + frame_specific_representation_info = ... + frame_attributes = ... + def __init_subclass__(cls, **kwargs): # -> None: + ... + + def __init__(self, *args, copy=..., representation_type=..., differential_type=..., **kwargs) -> None: + ... + + @lazyproperty + def cache(self): # -> defaultdict[Unknown, dict[Unknown, Unknown]]: + """ + Cache for this frame, a dict. It stores anything that should be + computed from the coordinate data (*not* from the frame attributes). + This can be used in functions to store anything that might be + expensive to compute but might be re-used by some other function. + E.g.:: + + if 'user_data' in myframe.cache: + data = myframe.cache['user_data'] + else: + myframe.cache['user_data'] = data = expensive_func(myframe.lat) + + If in-place modifications are made to the frame data, the cache should + be cleared:: + + myframe.cache.clear() + + """ + ... + + @property + def data(self): + """ + The coordinate data for this object. If this frame has no data, an + `ValueError` will be raised. Use `has_data` to + check if data is present on this frame object. + """ + ... + + @property + def has_data(self): # -> bool: + """ + True if this frame has `data`, False otherwise. + """ + ... + + @property + def shape(self): # -> tuple[()] | tuple[Unknown, ...]: + ... + + def __len__(self): # -> int: + ... + + def __bool__(self): # -> Literal[False]: + ... + + @property + def size(self): + ... + + @property + def isscalar(self): # -> Literal[False]: + ... + + @classmethod + def get_frame_attr_names(cls): # -> dict[Unknown, Any]: + ... + + def get_representation_cls(self, which=...): # -> Type[BaseRepresentation] | dict[str, None] | dict[str, Unknown | Type[BaseRepresentation]] | None: + """The class used for part of this frame's data. + + Parameters + ---------- + which : ('base', 's', `None`) + The class of which part to return. 'base' means the class used to + represent the coordinates; 's' the first derivative to time, i.e., + the class representing the proper motion and/or radial velocity. + If `None`, return a dict with both. + + Returns + ------- + representation : `~astropy.coordinates.BaseRepresentation` or `~astropy.coordinates.BaseDifferential`. + """ + ... + + def set_representation_cls(self, base=..., s=...): # -> None: + """Set representation and/or differential class for this frame's data. + + Parameters + ---------- + base : str, `~astropy.coordinates.BaseRepresentation` subclass, optional + The name or subclass to use to represent the coordinate data. + s : `~astropy.coordinates.BaseDifferential` subclass, optional + The differential subclass to use to represent any velocities, + such as proper motion and radial velocity. If equal to 'base', + which is the default, it will be inferred from the representation. + If `None`, the representation will drop any differentials. + """ + ... + + representation_type = ... + @property + def differential_type(self): # -> Type[BaseRepresentation] | dict[str, None] | dict[str, Unknown | Type[BaseRepresentation]] | None: + """ + The differential used for this frame's data. + + This will be a subclass from `~astropy.coordinates.BaseDifferential`. + For simultaneous setting of representation and differentials, see the + ``set_representation_cls`` method. + """ + ... + + @differential_type.setter + def differential_type(self, value): # -> None: + ... + + @lazyproperty + def representation_info(self): + """ + A dictionary with the information of what attribute names for this frame + apply to particular representations. + """ + ... + + def get_representation_component_names(self, which=...): # -> dict[Unknown, Unknown]: + ... + + def get_representation_component_units(self, which=...): # -> dict[Unknown, Unknown]: + ... + + representation_component_names = ... + representation_component_units = ... + def replicate(self, copy=..., **kwargs): # -> Self@BaseCoordinateFrame: + """ + Return a replica of the frame, optionally with new frame attributes. + + The replica is a new frame object that has the same data as this frame + object and with frame attributes overridden if they are provided as extra + keyword arguments to this method. If ``copy`` is set to `True` then a + copy of the internal arrays will be made. Otherwise the replica will + use a reference to the original arrays when possible to save memory. The + internal arrays are normally not changeable by the user so in most cases + it should not be necessary to set ``copy`` to `True`. + + Parameters + ---------- + copy : bool, optional + If True, the resulting object is a copy of the data. When False, + references are used where possible. This rule also applies to the + frame attributes. + **kwargs + Any additional keywords are treated as frame attributes to be set on the + new frame object. + + Returns + ------- + frameobj : `BaseCoordinateFrame` subclass instance + Replica of this object, but possibly with new frame attributes. + """ + ... + + def replicate_without_data(self, copy=..., **kwargs): # -> Self@BaseCoordinateFrame: + """ + Return a replica without data, optionally with new frame attributes. + + The replica is a new frame object without data but with the same frame + attributes as this object, except where overridden by extra keyword + arguments to this method. The ``copy`` keyword determines if the frame + attributes are truly copied vs being references (which saves memory for + cases where frame attributes are large). + + This method is essentially the converse of `realize_frame`. + + Parameters + ---------- + copy : bool, optional + If True, the resulting object has copies of the frame attributes. + When False, references are used where possible. + **kwargs + Any additional keywords are treated as frame attributes to be set on the + new frame object. + + Returns + ------- + frameobj : `BaseCoordinateFrame` subclass instance + Replica of this object, but without data and possibly with new frame + attributes. + """ + ... + + def realize_frame(self, data, **kwargs): # -> Self@BaseCoordinateFrame: + """ + Generates a new frame with new data from another frame (which may or + may not have data). Roughly speaking, the converse of + `replicate_without_data`. + + Parameters + ---------- + data : `~astropy.coordinates.BaseRepresentation` + The representation to use as the data for the new frame. + **kwargs + Any additional keywords are treated as frame attributes to be set on the + new frame object. In particular, `representation_type` can be specified. + + Returns + ------- + frameobj : `BaseCoordinateFrame` subclass instance + A new object in *this* frame, with the same frame attributes as + this one, but with the ``data`` as the coordinate data. + + """ + ... + + def represent_as(self, base, s=..., in_frame_units=...): + """ + Generate and return a new representation of this frame's `data` + as a Representation object. + + Note: In order to make an in-place change of the representation + of a Frame or SkyCoord object, set the ``representation`` + attribute of that object to the desired new representation, or + use the ``set_representation_cls`` method to also set the differential. + + Parameters + ---------- + base : subclass of BaseRepresentation or string + The type of representation to generate. Must be a *class* + (not an instance), or the string name of the representation + class. + s : subclass of `~astropy.coordinates.BaseDifferential`, str, optional + Class in which any velocities should be represented. Must be + a *class* (not an instance), or the string name of the + differential class. If equal to 'base' (default), inferred from + the base class. If `None`, all velocity information is dropped. + in_frame_units : bool, keyword-only + Force the representation units to match the specified units + particular to this frame + + Returns + ------- + newrep : BaseRepresentation-derived object + A new representation object of this frame's `data`. + + Raises + ------ + AttributeError + If this object had no `data` + + Examples + -------- + >>> from astropy import units as u + >>> from astropy.coordinates import SkyCoord, CartesianRepresentation + >>> coord = SkyCoord(0*u.deg, 0*u.deg) + >>> coord.represent_as(CartesianRepresentation) # doctest: +FLOAT_CMP + + + >>> coord.representation_type = CartesianRepresentation + >>> coord # doctest: +FLOAT_CMP + + """ + ... + + def transform_to(self, new_frame): # -> Any: + """ + Transform this object's coordinate data to a new frame. + + Parameters + ---------- + new_frame : coordinate-like or `BaseCoordinateFrame` subclass instance + The frame to transform this coordinate frame into. + The frame class option is deprecated. + + Returns + ------- + transframe : coordinate-like + A new object with the coordinate data represented in the + ``newframe`` system. + + Raises + ------ + ValueError + If there is no possible transformation route. + """ + ... + + def is_transformable_to(self, new_frame): # -> bool | Literal['same']: + """ + Determines if this coordinate frame can be transformed to another + given frame. + + Parameters + ---------- + new_frame : `BaseCoordinateFrame` subclass or instance + The proposed frame to transform into. + + Returns + ------- + transformable : bool or str + `True` if this can be transformed to ``new_frame``, `False` if + not, or the string 'same' if ``new_frame`` is the same system as + this object but no transformation is defined. + + Notes + ----- + A return value of 'same' means the transformation will work, but it will + just give back a copy of this object. The intended usage is:: + + if coord.is_transformable_to(some_unknown_frame): + coord2 = coord.transform_to(some_unknown_frame) + + This will work even if ``some_unknown_frame`` turns out to be the same + frame class as ``coord``. This is intended for cases where the frame + is the same regardless of the frame attributes (e.g. ICRS), but be + aware that it *might* also indicate that someone forgot to define the + transformation between two objects of the same frame class but with + different attributes. + """ + ... + + def is_frame_attr_default(self, attrnm): # -> bool: + """ + Determine whether or not a frame attribute has its value because it's + the default value, or because this frame was created with that value + explicitly requested. + + Parameters + ---------- + attrnm : str + The name of the attribute to check. + + Returns + ------- + isdefault : bool + True if the attribute ``attrnm`` has its value by default, False if + it was specified at creation of this frame. + """ + ... + + def is_equivalent_frame(self, other): # -> bool: + """ + Checks if this object is the same frame as the ``other`` object. + + To be the same frame, two objects must be the same frame class and have + the same frame attributes. Note that it does *not* matter what, if any, + data either object has. + + Parameters + ---------- + other : :class:`~astropy.coordinates.BaseCoordinateFrame` + the other frame to check + + Returns + ------- + isequiv : bool + True if the frames are the same, False if not. + + Raises + ------ + TypeError + If ``other`` isn't a `BaseCoordinateFrame` or subclass. + """ + ... + + def __repr__(self): # -> str: + ... + + def __setitem__(self, item, value): # -> None: + ... + + @override__dir__ + def __dir__(self): # -> set[Any]: + """ + Override the builtin `dir` behavior to include representation + names. + + TODO: dynamic representation transforms (i.e. include cylindrical et al.). + """ + ... + + def __getattr__(self, attr): # -> Any: + """ + Allow access to attributes on the representation and differential as + found via ``self.get_representation_component_names``. + + TODO: We should handle dynamic representation transforms here (e.g., + `.cylindrical`) instead of defining properties as below. + """ + ... + + def __setattr__(self, attr, value): # -> None: + ... + + def __eq__(self, value) -> bool: + """Equality operator for frame. + + This implements strict equality and requires that the frames are + equivalent and that the representation data are exactly equal. + """ + ... + + def __ne__(self, value) -> bool: + ... + + def separation(self, other): # -> Angle: + """ + Computes on-sky separation between this coordinate and another. + + .. note:: + + If the ``other`` coordinate object is in a different frame, it is + first transformed to the frame of this object. This can lead to + unintuitive behavior if not accounted for. Particularly of note is + that ``self.separation(other)`` and ``other.separation(self)`` may + not give the same answer in this case. + + Parameters + ---------- + other : `~astropy.coordinates.BaseCoordinateFrame` + The coordinate to get the separation to. + + Returns + ------- + sep : `~astropy.coordinates.Angle` + The on-sky separation between this and the ``other`` coordinate. + + Notes + ----- + The separation is calculated using the Vincenty formula, which + is stable at all locations, including poles and antipodes [1]_. + + .. [1] https://en.wikipedia.org/wiki/Great-circle_distance + + """ + ... + + def separation_3d(self, other): # -> Distance: + """ + Computes three dimensional separation between this coordinate + and another. + + Parameters + ---------- + other : `~astropy.coordinates.BaseCoordinateFrame` + The coordinate system to get the distance to. + + Returns + ------- + sep : `~astropy.coordinates.Distance` + The real-space distance between these two coordinates. + + Raises + ------ + ValueError + If this or the other coordinate do not have distances. + """ + ... + + @property + def cartesian(self): + """ + Shorthand for a cartesian representation of the coordinates in this + object. + """ + ... + + @property + def cylindrical(self): + """ + Shorthand for a cylindrical representation of the coordinates in this + object. + """ + ... + + @property + def spherical(self): + """ + Shorthand for a spherical representation of the coordinates in this + object. + """ + ... + + @property + def sphericalcoslat(self): + """ + Shorthand for a spherical representation of the positional data and a + `SphericalCosLatDifferential` for the velocity data in this object. + """ + ... + + @property + def velocity(self): + """ + Shorthand for retrieving the Cartesian space-motion as a + `CartesianDifferential` object. This is equivalent to calling + ``self.cartesian.differentials['s']``. + """ + ... + + @property + def proper_motion(self): + """ + Shorthand for the two-dimensional proper motion as a + `~astropy.units.Quantity` object with angular velocity units. In the + returned `~astropy.units.Quantity`, ``axis=0`` is the longitude/latitude + dimension so that ``.proper_motion[0]`` is the longitudinal proper + motion and ``.proper_motion[1]`` is latitudinal. The longitudinal proper + motion already includes the cos(latitude) term. + """ + ... + + @property + def radial_velocity(self): + """ + Shorthand for the radial or line-of-sight velocity as a + `~astropy.units.Quantity` object. + """ + ... + + + +class GenericFrame(BaseCoordinateFrame): + """ + A frame object that can't store data but can hold any arbitrary frame + attributes. Mostly useful as a utility for the high-level class to store + intermediate frame attributes. + + Parameters + ---------- + frame_attrs : dict + A dictionary of attributes to be used as the frame attributes for this + frame. + """ + name = ... + def __init__(self, frame_attrs) -> None: + ... + + def __getattr__(self, name): # -> Any: + ... + + def __setattr__(self, name, value): # -> None: + ... + + + diff --git a/typings/astropy/coordinates/builtin_frames/__init__.pyi b/typings/astropy/coordinates/builtin_frames/__init__.pyi new file mode 100644 index 0000000..5d8a0bb --- /dev/null +++ b/typings/astropy/coordinates/builtin_frames/__init__.pyi @@ -0,0 +1,68 @@ +""" +This type stub file was generated by pyright. +""" + +from .baseradec import BaseRADecFrame +from .icrs import ICRS +from .fk5 import FK5 +from .fk4 import FK4, FK4NoETerms +from .galactic import Galactic +from .galactocentric import Galactocentric, galactocentric_frame_defaults +from .supergalactic import Supergalactic +from .altaz import AltAz +from .hadec import HADec +from .gcrs import GCRS, PrecessedGeocentric +from .cirs import CIRS +from .itrs import ITRS +from .hcrs import HCRS +from .equatorial import TEME, TETE +from .ecliptic import * +from .skyoffset import SkyOffsetFrame +from . import cirs_observed_transforms, ecliptic_transforms, fk4_fk5_transforms, galactic_transforms, icrs_cirs_transforms, icrs_fk5_transforms, icrs_observed_transforms, intermediate_rotation_transforms, supergalactic_transforms +from .lsr import GalacticLSR, LSR, LSRD, LSRK +from astropy.coordinates.baseframe import frame_transform_graph + +""" +This package contains the coordinate frames implemented by astropy. + +Users shouldn't use this module directly, but rather import from the +`astropy.coordinates` module. While it is likely to exist for the long-term, +the existence of this package and details of its organization should be +considered an implementation detail, and is not guaranteed to hold for future +versions of astropy. + +Notes +----- +The builtin frame classes are all imported automatically into this package's +namespace, so there's no need to access the sub-modules directly. + +To implement a new frame in Astropy, a developer should add the frame as a new +module in this package. Any "self" transformations (i.e., those that transform +from one frame to another frame of the same class) should be included in that +module. Transformation functions connecting the new frame to other frames +should be in a separate module, which should be imported in this package's +``__init__.py`` to ensure the transformations are hooked up when this package is +imported. Placing the transformation functions in separate modules avoids +circular dependencies, because they need references to the frame classes. +""" +__all__ = ['ICRS', 'FK5', 'FK4', 'FK4NoETerms', 'Galactic', 'Galactocentric', 'galactocentric_frame_defaults', 'Supergalactic', 'AltAz', 'HADec', 'GCRS', 'CIRS', 'ITRS', 'HCRS', 'TEME', 'TETE', 'PrecessedGeocentric', 'GeocentricMeanEcliptic', 'BarycentricMeanEcliptic', 'HeliocentricMeanEcliptic', 'GeocentricTrueEcliptic', 'BarycentricTrueEcliptic', 'HeliocentricTrueEcliptic', 'SkyOffsetFrame', 'GalacticLSR', 'LSR', 'LSRK', 'LSRD', 'BaseEclipticFrame', 'BaseRADecFrame', 'make_transform_graph_docs', 'HeliocentricEclipticIAU76', 'CustomBarycentricEcliptic'] +def make_transform_graph_docs(transform_graph): + """ + Generates a string that can be used in other docstrings to include a + transformation graph, showing the available transforms and + coordinate systems. + + Parameters + ---------- + transform_graph : `~.coordinates.TransformGraph` + + Returns + ------- + docstring : str + A string that can be added to the end of a docstring to show the + transform graph. + """ + ... + +_transform_graph_docs = ... +__doc__ = ... diff --git a/typings/astropy/coordinates/builtin_frames/altaz.pyi b/typings/astropy/coordinates/builtin_frames/altaz.pyi new file mode 100644 index 0000000..5d72594 --- /dev/null +++ b/typings/astropy/coordinates/builtin_frames/altaz.pyi @@ -0,0 +1,55 @@ +""" +This type stub file was generated by pyright. +""" + +from astropy.utils.decorators import format_doc +from astropy.coordinates import representation as r +from astropy.coordinates.baseframe import BaseCoordinateFrame, base_doc + +__all__ = ['AltAz'] +_90DEG = ... +doc_components = ... +doc_footer = ... +@format_doc(base_doc, components=doc_components, footer=doc_footer) +class AltAz(BaseCoordinateFrame): + """ + A coordinate or frame in the Altitude-Azimuth system (Horizontal + coordinates) with respect to the WGS84 ellipsoid. Azimuth is oriented + East of North (i.e., N=0, E=90 degrees). Altitude is also known as + elevation angle, so this frame is also in the Azimuth-Elevation system. + + This frame is assumed to *include* refraction effects if the ``pressure`` + frame attribute is non-zero. + + The frame attributes are listed under **Other Parameters**, which are + necessary for transforming from AltAz to some other system. + """ + frame_specific_representation_info = ... + default_representation = r.SphericalRepresentation + default_differential = r.SphericalCosLatDifferential + obstime = ... + location = ... + pressure = ... + temperature = ... + relative_humidity = ... + obswl = ... + def __init__(self, *args, **kwargs) -> None: + ... + + @property + def secz(self): # -> Any: + """ + Secant of the zenith angle for this coordinate, a common estimate of + the airmass. + """ + ... + + @property + def zen(self): + """ + The zenith angle (or zenith distance / co-altitude) for this coordinate. + """ + ... + + + diff --git a/typings/astropy/coordinates/builtin_frames/baseradec.pyi b/typings/astropy/coordinates/builtin_frames/baseradec.pyi new file mode 100644 index 0000000..33ef173 --- /dev/null +++ b/typings/astropy/coordinates/builtin_frames/baseradec.pyi @@ -0,0 +1,22 @@ +""" +This type stub file was generated by pyright. +""" + +from astropy.utils.decorators import format_doc +from astropy.coordinates import representation as r +from astropy.coordinates.baseframe import BaseCoordinateFrame, base_doc + +__all__ = ['BaseRADecFrame'] +doc_components = ... +@format_doc(base_doc, components=doc_components, footer="") +class BaseRADecFrame(BaseCoordinateFrame): + """ + A base class that defines default representation info for frames that + represent longitude and latitude as Right Ascension and Declination + following typical "equatorial" conventions. + """ + frame_specific_representation_info = ... + default_representation = r.SphericalRepresentation + default_differential = r.SphericalCosLatDifferential + + diff --git a/typings/astropy/coordinates/builtin_frames/cirs.pyi b/typings/astropy/coordinates/builtin_frames/cirs.pyi new file mode 100644 index 0000000..0cdf169 --- /dev/null +++ b/typings/astropy/coordinates/builtin_frames/cirs.pyi @@ -0,0 +1,21 @@ +""" +This type stub file was generated by pyright. +""" + +from astropy.utils.decorators import format_doc +from astropy.coordinates.baseframe import base_doc +from .baseradec import BaseRADecFrame, doc_components + +__all__ = ['CIRS'] +doc_footer = ... +@format_doc(base_doc, components=doc_components, footer=doc_footer) +class CIRS(BaseRADecFrame): + """ + A coordinate or frame in the Celestial Intermediate Reference System (CIRS). + + The frame attributes are listed under **Other Parameters**. + """ + obstime = ... + location = ... + + diff --git a/typings/astropy/coordinates/builtin_frames/cirs_observed_transforms.pyi b/typings/astropy/coordinates/builtin_frames/cirs_observed_transforms.pyi new file mode 100644 index 0000000..58baf03 --- /dev/null +++ b/typings/astropy/coordinates/builtin_frames/cirs_observed_transforms.pyi @@ -0,0 +1,23 @@ +""" +This type stub file was generated by pyright. +""" + +from astropy.coordinates.baseframe import frame_transform_graph +from astropy.coordinates.transformations import FunctionTransformWithFiniteDifference +from .cirs import CIRS +from .altaz import AltAz +from .hadec import HADec + +""" +Contains the transformation functions for getting to "observed" systems from CIRS. +""" +@frame_transform_graph.transform(FunctionTransformWithFiniteDifference, CIRS, AltAz) +@frame_transform_graph.transform(FunctionTransformWithFiniteDifference, CIRS, HADec) +def cirs_to_observed(cirs_coo, observed_frame): # -> AltAz: + ... + +@frame_transform_graph.transform(FunctionTransformWithFiniteDifference, AltAz, CIRS) +@frame_transform_graph.transform(FunctionTransformWithFiniteDifference, HADec, CIRS) +def observed_to_cirs(observed_coo, cirs_frame): # -> Any: + ... + diff --git a/typings/astropy/coordinates/builtin_frames/ecliptic.pyi b/typings/astropy/coordinates/builtin_frames/ecliptic.pyi new file mode 100644 index 0000000..175e0ba --- /dev/null +++ b/typings/astropy/coordinates/builtin_frames/ecliptic.pyi @@ -0,0 +1,164 @@ +""" +This type stub file was generated by pyright. +""" + +from astropy.utils.decorators import format_doc +from astropy.coordinates import representation as r +from astropy.coordinates.baseframe import BaseCoordinateFrame, base_doc + +__all__ = ['GeocentricMeanEcliptic', 'BarycentricMeanEcliptic', 'HeliocentricMeanEcliptic', 'BaseEclipticFrame', 'GeocentricTrueEcliptic', 'BarycentricTrueEcliptic', 'HeliocentricTrueEcliptic', 'HeliocentricEclipticIAU76', 'CustomBarycentricEcliptic'] +doc_components_ecl = ... +@format_doc(base_doc, components=doc_components_ecl.format('specified location'), footer="") +class BaseEclipticFrame(BaseCoordinateFrame): + """ + A base class for frames that have names and conventions like that of + ecliptic frames. + + .. warning:: + In the current version of astropy, the ecliptic frames do not yet have + stringent accuracy tests. We recommend you test to "known-good" cases + to ensure this frames are what you are looking for. (and then ideally + you would contribute these tests to Astropy!) + """ + default_representation = r.SphericalRepresentation + default_differential = r.SphericalCosLatDifferential + + +doc_footer_geo = ... +@format_doc(base_doc, components=doc_components_ecl.format('geocenter'), footer=doc_footer_geo) +class GeocentricMeanEcliptic(BaseEclipticFrame): + """ + Geocentric mean ecliptic coordinates. These origin of the coordinates are the + geocenter (Earth), with the x axis pointing to the *mean* (not true) equinox + at the time specified by the ``equinox`` attribute, and the xy-plane in the + plane of the ecliptic for that date. + + Be aware that the definition of "geocentric" here means that this frame + *includes* light deflection from the sun, aberration, etc when transforming + to/from e.g. ICRS. + + The frame attributes are listed under **Other Parameters**. + """ + equinox = ... + obstime = ... + + +@format_doc(base_doc, components=doc_components_ecl.format('geocenter'), footer=doc_footer_geo) +class GeocentricTrueEcliptic(BaseEclipticFrame): + """ + Geocentric true ecliptic coordinates. These origin of the coordinates are the + geocenter (Earth), with the x axis pointing to the *true* (not mean) equinox + at the time specified by the ``equinox`` attribute, and the xy-plane in the + plane of the ecliptic for that date. + + Be aware that the definition of "geocentric" here means that this frame + *includes* light deflection from the sun, aberration, etc when transforming + to/from e.g. ICRS. + + The frame attributes are listed under **Other Parameters**. + """ + equinox = ... + obstime = ... + + +doc_footer_bary = ... +@format_doc(base_doc, components=doc_components_ecl.format("barycenter"), footer=doc_footer_bary) +class BarycentricMeanEcliptic(BaseEclipticFrame): + """ + Barycentric mean ecliptic coordinates. These origin of the coordinates are the + barycenter of the solar system, with the x axis pointing in the direction of + the *mean* (not true) equinox as at the time specified by the ``equinox`` + attribute (as seen from Earth), and the xy-plane in the plane of the + ecliptic for that date. + + The frame attributes are listed under **Other Parameters**. + """ + equinox = ... + + +@format_doc(base_doc, components=doc_components_ecl.format("barycenter"), footer=doc_footer_bary) +class BarycentricTrueEcliptic(BaseEclipticFrame): + """ + Barycentric true ecliptic coordinates. These origin of the coordinates are the + barycenter of the solar system, with the x axis pointing in the direction of + the *true* (not mean) equinox as at the time specified by the ``equinox`` + attribute (as seen from Earth), and the xy-plane in the plane of the + ecliptic for that date. + + The frame attributes are listed under **Other Parameters**. + """ + equinox = ... + + +doc_footer_helio = ... +@format_doc(base_doc, components=doc_components_ecl.format("sun's center"), footer=doc_footer_helio) +class HeliocentricMeanEcliptic(BaseEclipticFrame): + """ + Heliocentric mean ecliptic coordinates. These origin of the coordinates are the + center of the sun, with the x axis pointing in the direction of + the *mean* (not true) equinox as at the time specified by the ``equinox`` + attribute (as seen from Earth), and the xy-plane in the plane of the + ecliptic for that date. + + The frame attributes are listed under **Other Parameters**. + + {params} + + + """ + equinox = ... + obstime = ... + + +@format_doc(base_doc, components=doc_components_ecl.format("sun's center"), footer=doc_footer_helio) +class HeliocentricTrueEcliptic(BaseEclipticFrame): + """ + Heliocentric true ecliptic coordinates. These origin of the coordinates are the + center of the sun, with the x axis pointing in the direction of + the *true* (not mean) equinox as at the time specified by the ``equinox`` + attribute (as seen from Earth), and the xy-plane in the plane of the + ecliptic for that date. + + The frame attributes are listed under **Other Parameters**. + + {params} + + + """ + equinox = ... + obstime = ... + + +@format_doc(base_doc, components=doc_components_ecl.format("sun's center"), footer="") +class HeliocentricEclipticIAU76(BaseEclipticFrame): + """ + Heliocentric mean (IAU 1976) ecliptic coordinates. These origin of the coordinates are the + center of the sun, with the x axis pointing in the direction of + the *mean* (not true) equinox of J2000, and the xy-plane in the plane of the + ecliptic of J2000 (according to the IAU 1976/1980 obliquity model). + It has, therefore, a fixed equinox and an older obliquity value + than the rest of the frames. + + The frame attributes are listed under **Other Parameters**. + + {params} + + + """ + obstime = ... + + +@format_doc(base_doc, components=doc_components_ecl.format("barycenter"), footer="") +class CustomBarycentricEcliptic(BaseEclipticFrame): + """ + Barycentric ecliptic coordinates with custom obliquity. + These origin of the coordinates are the + barycenter of the solar system, with the x axis pointing in the direction of + the *mean* (not true) equinox of J2000, and the xy-plane in the plane of the + ecliptic tilted a custom obliquity angle. + + The frame attributes are listed under **Other Parameters**. + """ + obliquity = ... + + diff --git a/typings/astropy/coordinates/builtin_frames/ecliptic_transforms.pyi b/typings/astropy/coordinates/builtin_frames/ecliptic_transforms.pyi new file mode 100644 index 0000000..c3bcddc --- /dev/null +++ b/typings/astropy/coordinates/builtin_frames/ecliptic_transforms.pyi @@ -0,0 +1,78 @@ +""" +This type stub file was generated by pyright. +""" + +from astropy.coordinates.baseframe import frame_transform_graph +from astropy.coordinates.transformations import AffineTransform, DynamicMatrixTransform, FunctionTransformWithFiniteDifference +from .icrs import ICRS +from .gcrs import GCRS +from .ecliptic import BarycentricMeanEcliptic, BarycentricTrueEcliptic, CustomBarycentricEcliptic, GeocentricMeanEcliptic, GeocentricTrueEcliptic, HeliocentricEclipticIAU76, HeliocentricMeanEcliptic, HeliocentricTrueEcliptic + +""" +Contains the transformation functions for getting to/from ecliptic systems. +""" +@frame_transform_graph.transform(FunctionTransformWithFiniteDifference, GCRS, GeocentricMeanEcliptic, finite_difference_frameattr_name='equinox') +def gcrs_to_geoecliptic(gcrs_coo, to_frame): + ... + +@frame_transform_graph.transform(FunctionTransformWithFiniteDifference, GeocentricMeanEcliptic, GCRS) +def geoecliptic_to_gcrs(from_coo, gcrs_frame): # -> Any: + ... + +@frame_transform_graph.transform(DynamicMatrixTransform, ICRS, BarycentricMeanEcliptic) +def icrs_to_baryecliptic(from_coo, to_frame): + ... + +@frame_transform_graph.transform(DynamicMatrixTransform, BarycentricMeanEcliptic, ICRS) +def baryecliptic_to_icrs(from_coo, to_frame): + ... + +_NEED_ORIGIN_HINT = ... +@frame_transform_graph.transform(AffineTransform, ICRS, HeliocentricMeanEcliptic) +def icrs_to_helioecliptic(from_coo, to_frame): # -> tuple[Unknown, Unknown | CartesianRepresentation]: + ... + +@frame_transform_graph.transform(AffineTransform, HeliocentricMeanEcliptic, ICRS) +def helioecliptic_to_icrs(from_coo, to_frame): # -> tuple[Unknown, Unknown | CartesianRepresentation | tuple[CartesianRepresentation, CartesianRepresentation | Unbound]]: + ... + +@frame_transform_graph.transform(FunctionTransformWithFiniteDifference, GCRS, GeocentricTrueEcliptic, finite_difference_frameattr_name='equinox') +def gcrs_to_true_geoecliptic(gcrs_coo, to_frame): + ... + +@frame_transform_graph.transform(FunctionTransformWithFiniteDifference, GeocentricTrueEcliptic, GCRS) +def true_geoecliptic_to_gcrs(from_coo, gcrs_frame): # -> Any: + ... + +@frame_transform_graph.transform(DynamicMatrixTransform, ICRS, BarycentricTrueEcliptic) +def icrs_to_true_baryecliptic(from_coo, to_frame): # -> Any: + ... + +@frame_transform_graph.transform(DynamicMatrixTransform, BarycentricTrueEcliptic, ICRS) +def true_baryecliptic_to_icrs(from_coo, to_frame): # -> Any: + ... + +@frame_transform_graph.transform(AffineTransform, ICRS, HeliocentricTrueEcliptic) +def icrs_to_true_helioecliptic(from_coo, to_frame): # -> tuple[Any, Unknown | CartesianRepresentation]: + ... + +@frame_transform_graph.transform(AffineTransform, HeliocentricTrueEcliptic, ICRS) +def true_helioecliptic_to_icrs(from_coo, to_frame): # -> tuple[Any, Unknown | CartesianRepresentation | tuple[CartesianRepresentation, CartesianRepresentation | Unbound]]: + ... + +@frame_transform_graph.transform(AffineTransform, HeliocentricEclipticIAU76, ICRS) +def ecliptic_to_iau76_icrs(from_coo, to_frame): # -> tuple[ndarray[Any, dtype[float64]] | Any, Unknown | CartesianRepresentation | tuple[CartesianRepresentation, CartesianRepresentation | Unbound]]: + ... + +@frame_transform_graph.transform(AffineTransform, ICRS, HeliocentricEclipticIAU76) +def icrs_to_iau76_ecliptic(from_coo, to_frame): # -> tuple[NDArray[float64] | Any, Unknown | CartesianRepresentation]: + ... + +@frame_transform_graph.transform(DynamicMatrixTransform, ICRS, CustomBarycentricEcliptic) +def icrs_to_custombaryecliptic(from_coo, to_frame): # -> NDArray[float64] | Any: + ... + +@frame_transform_graph.transform(DynamicMatrixTransform, CustomBarycentricEcliptic, ICRS) +def custombaryecliptic_to_icrs(from_coo, to_frame): # -> NDArray[float64] | Any: + ... + diff --git a/typings/astropy/coordinates/builtin_frames/equatorial.pyi b/typings/astropy/coordinates/builtin_frames/equatorial.pyi new file mode 100644 index 0000000..2c49615 --- /dev/null +++ b/typings/astropy/coordinates/builtin_frames/equatorial.pyi @@ -0,0 +1,80 @@ +""" +This type stub file was generated by pyright. +""" + +from astropy.utils.decorators import format_doc +from astropy.coordinates.representation import CartesianDifferential, CartesianRepresentation +from astropy.coordinates.baseframe import BaseCoordinateFrame, base_doc +from astropy.coordinates.builtin_frames.baseradec import BaseRADecFrame, doc_components + +""" +Coordinate frames tied to the Equator and Equinox of Earth. + +TEME is a True equator, Mean Equinox coordinate frame used in NORAD TLE +satellite files. + +TETE is a True equator, True Equinox coordinate frame often called the +"apparent" coordinates. It is the same frame as used by JPL Horizons +and can be combined with Local Apparent Sidereal Time to calculate the +hour angle. +""" +__all__ = ['TEME', 'TETE'] +doc_footer_teme = ... +doc_footer_tete = ... +@format_doc(base_doc, components=doc_components, footer=doc_footer_tete) +class TETE(BaseRADecFrame): + """ + An equatorial coordinate or frame using the True Equator and True Equinox (TETE). + + Equatorial coordinate frames measure RA with respect to the equinox and declination + with with respect to the equator. The location of the equinox and equator vary due + the gravitational torques on the oblate Earth. This variation is split into precession + and nutation, although really they are two aspects of a single phenomena. The smooth, + long term variation is known as precession, whilst smaller, periodic components are + called nutation. + + Calculation of the true equator and equinox involves the application of both precession + and nutation, whilst only applying precession gives a mean equator and equinox. + + TETE coordinates are often referred to as "apparent" coordinates, or + "apparent place". TETE is the apparent coordinate system used by JPL Horizons + and is the correct coordinate system to use when combining the right ascension + with local apparent sidereal time to calculate the apparent (TIRS) hour angle. + + For more background on TETE, see the references provided in the + :ref:`astropy:astropy-coordinates-seealso` section of the documentation. + Of particular note are Sections 5 and 6 of + `USNO Circular 179 `_) and + especially the diagram at the top of page 57. + + This frame also includes frames that are defined *relative* to the center of the Earth, + but that are offset (in both position and velocity) from the center of the Earth. You + may see such non-geocentric coordinates referred to as "topocentric". + + The frame attributes are listed under **Other Parameters**. + """ + obstime = ... + location = ... + + +@format_doc(base_doc, components="", footer=doc_footer_teme) +class TEME(BaseCoordinateFrame): + """ + A coordinate or frame in the True Equator Mean Equinox frame (TEME). + + This frame is a geocentric system similar to CIRS or geocentric apparent place, + except that the mean sidereal time is used to rotate from TIRS. TEME coordinates + are most often used in combination with orbital data for satellites in the + two-line-ephemeris format. + + Different implementations of the TEME frame exist. For clarity, this frame follows the + conventions and relations to other frames that are set out in Vallado et al (2006). + + For more background on TEME, see the references provided in the + :ref:`astropy:astropy-coordinates-seealso` section of the documentation. + """ + default_representation = CartesianRepresentation + default_differential = CartesianDifferential + obstime = ... + + diff --git a/typings/astropy/coordinates/builtin_frames/fk4.pyi b/typings/astropy/coordinates/builtin_frames/fk4.pyi new file mode 100644 index 0000000..63fe140 --- /dev/null +++ b/typings/astropy/coordinates/builtin_frames/fk4.pyi @@ -0,0 +1,64 @@ +""" +This type stub file was generated by pyright. +""" + +from astropy.utils.decorators import format_doc +from astropy.coordinates.baseframe import base_doc, frame_transform_graph +from astropy.coordinates.transformations import DynamicMatrixTransform, FunctionTransformWithFiniteDifference +from .baseradec import BaseRADecFrame, doc_components + +__all__ = ['FK4', 'FK4NoETerms'] +doc_footer_fk4 = ... +@format_doc(base_doc, components=doc_components, footer=doc_footer_fk4) +class FK4(BaseRADecFrame): + """ + A coordinate or frame in the FK4 system. + + Note that this is a barycentric version of FK4 - that is, the origin for + this frame is the Solar System Barycenter, *not* the Earth geocenter. + + The frame attributes are listed under **Other Parameters**. + """ + equinox = ... + obstime = ... + + +@frame_transform_graph.transform(FunctionTransformWithFiniteDifference, FK4, FK4) +def fk4_to_fk4(fk4coord1, fk4frame2): + ... + +@format_doc(base_doc, components=doc_components, footer=doc_footer_fk4) +class FK4NoETerms(BaseRADecFrame): + """ + A coordinate or frame in the FK4 system, but with the E-terms of aberration + removed. + + The frame attributes are listed under **Other Parameters**. + """ + equinox = ... + obstime = ... + + +@frame_transform_graph.transform(DynamicMatrixTransform, FK4NoETerms, FK4NoETerms) +def fk4noe_to_fk4noe(fk4necoord1, fk4neframe2): + ... + +def fk4_e_terms(equinox): # -> tuple[Any, Any, Any]: + """ + Return the e-terms of aberration vector + + Parameters + ---------- + equinox : Time object + The equinox for which to compute the e-terms + """ + ... + +@frame_transform_graph.transform(FunctionTransformWithFiniteDifference, FK4, FK4NoETerms) +def fk4_to_fk4_no_e(fk4coord, fk4noeframe): # -> Any | FK4NoETerms: + ... + +@frame_transform_graph.transform(FunctionTransformWithFiniteDifference, FK4NoETerms, FK4) +def fk4_no_e_to_fk4(fk4noecoord, fk4frame): + ... + diff --git a/typings/astropy/coordinates/builtin_frames/fk4_fk5_transforms.pyi b/typings/astropy/coordinates/builtin_frames/fk4_fk5_transforms.pyi new file mode 100644 index 0000000..3d526f0 --- /dev/null +++ b/typings/astropy/coordinates/builtin_frames/fk4_fk5_transforms.pyi @@ -0,0 +1,20 @@ +""" +This type stub file was generated by pyright. +""" + +import numpy as np +from astropy.coordinates.baseframe import frame_transform_graph +from astropy.coordinates.transformations import DynamicMatrixTransform +from .fk4 import FK4NoETerms +from .fk5 import FK5 + +_B1950_TO_J2000_M = np.array([[0.9999256794956877, -0.0111814832204662, -0.0048590038153592], [0.0111814832391717, 0.9999374848933135, -0.0000271625947142], [0.0048590037723143, -0.000027170293744, 0.9999881946023742]]) +_FK4_CORR = np.array([[-0.0026455262, -1.1539918689, +2.111134619], [+1.1540628161, -0.0129042997, +0.0236021478], [-2.1112979048, -0.0056024448, +0.0102587734]]) * 0.000001 +@frame_transform_graph.transform(DynamicMatrixTransform, FK4NoETerms, FK5) +def fk4_no_e_to_fk5(fk4noecoord, fk5frame): # -> Any: + ... + +@frame_transform_graph.transform(DynamicMatrixTransform, FK5, FK4NoETerms) +def fk5_to_fk4_no_e(fk5coord, fk4noeframe): # -> Any: + ... + diff --git a/typings/astropy/coordinates/builtin_frames/fk5.pyi b/typings/astropy/coordinates/builtin_frames/fk5.pyi new file mode 100644 index 0000000..d1beaf0 --- /dev/null +++ b/typings/astropy/coordinates/builtin_frames/fk5.pyi @@ -0,0 +1,28 @@ +""" +This type stub file was generated by pyright. +""" + +from astropy.utils.decorators import format_doc +from astropy.coordinates.baseframe import base_doc, frame_transform_graph +from astropy.coordinates.transformations import DynamicMatrixTransform +from .baseradec import BaseRADecFrame, doc_components + +__all__ = ['FK5'] +doc_footer = ... +@format_doc(base_doc, components=doc_components, footer=doc_footer) +class FK5(BaseRADecFrame): + """ + A coordinate or frame in the FK5 system. + + Note that this is a barycentric version of FK5 - that is, the origin for + this frame is the Solar System Barycenter, *not* the Earth geocenter. + + The frame attributes are listed under **Other Parameters**. + """ + equinox = ... + + +@frame_transform_graph.transform(DynamicMatrixTransform, FK5, FK5) +def fk5_to_fk5(fk5coord1, fk5frame2): + ... + diff --git a/typings/astropy/coordinates/builtin_frames/galactic.pyi b/typings/astropy/coordinates/builtin_frames/galactic.pyi new file mode 100644 index 0000000..e7d3729 --- /dev/null +++ b/typings/astropy/coordinates/builtin_frames/galactic.pyi @@ -0,0 +1,33 @@ +""" +This type stub file was generated by pyright. +""" + +from astropy.utils.decorators import format_doc +from astropy.coordinates import representation as r +from astropy.coordinates.baseframe import BaseCoordinateFrame, base_doc + +__all__ = ['Galactic'] +doc_components = ... +doc_footer = ... +@format_doc(base_doc, components=doc_components, footer=doc_footer) +class Galactic(BaseCoordinateFrame): + """ + A coordinate or frame in the Galactic coordinate system. + + This frame is used in a variety of Galactic contexts because it has as its + x-y plane the plane of the Milky Way. The positive x direction (i.e., the + l=0, b=0 direction) points to the center of the Milky Way and the z-axis + points toward the North Galactic Pole (following the IAU's 1958 definition + [1]_). However, unlike the `~astropy.coordinates.Galactocentric` frame, the + *origin* of this frame in 3D space is the solar system barycenter, not + the center of the Milky Way. + """ + frame_specific_representation_info = ... + default_representation = r.SphericalRepresentation + default_differential = r.SphericalCosLatDifferential + _ngp_B1950 = ... + _lon0_B1950 = ... + _ngp_J2000 = ... + _lon0_J2000 = ... + + diff --git a/typings/astropy/coordinates/builtin_frames/galactic_transforms.pyi b/typings/astropy/coordinates/builtin_frames/galactic_transforms.pyi new file mode 100644 index 0000000..3827e8a --- /dev/null +++ b/typings/astropy/coordinates/builtin_frames/galactic_transforms.pyi @@ -0,0 +1,22 @@ +""" +This type stub file was generated by pyright. +""" + +from astropy.coordinates.baseframe import frame_transform_graph +from astropy.coordinates.transformations import DynamicMatrixTransform +from .fk5 import FK5 +from .fk4 import FK4NoETerms +from .galactic import Galactic + +@frame_transform_graph.transform(DynamicMatrixTransform, FK5, Galactic) +def fk5_to_gal(fk5coord, galframe): # -> Any: + ... + +@frame_transform_graph.transform(DynamicMatrixTransform, FK4NoETerms, Galactic) +def fk4_to_gal(fk4coords, galframe): # -> Any: + ... + +@frame_transform_graph.transform(DynamicMatrixTransform, Galactic, FK4NoETerms) +def gal_to_fk4(galcoords, fk4frame): # -> Any: + ... + diff --git a/typings/astropy/coordinates/builtin_frames/galactocentric.pyi b/typings/astropy/coordinates/builtin_frames/galactocentric.pyi new file mode 100644 index 0000000..f9f720d --- /dev/null +++ b/typings/astropy/coordinates/builtin_frames/galactocentric.pyi @@ -0,0 +1,285 @@ +""" +This type stub file was generated by pyright. +""" + +from collections.abc import MappingView +from astropy.utils.state import ScienceState +from astropy.utils.decorators import classproperty, deprecated, format_doc +from astropy.coordinates import representation as r +from astropy.coordinates.baseframe import BaseCoordinateFrame, base_doc, frame_transform_graph +from astropy.coordinates.transformations import AffineTransform +from .icrs import ICRS + +__all__ = ['Galactocentric'] +_ROLL0 = ... +class _StateProxy(MappingView): + """ + `~collections.abc.MappingView` with a read-only ``getitem`` through + `~types.MappingProxyType`. + + """ + def __init__(self, mapping) -> None: + ... + + def __getitem__(self, key): + """Read-only ``getitem``.""" + ... + + def __deepcopy__(self, memo): + ... + + + +class galactocentric_frame_defaults(ScienceState): + """This class controls the global setting of default values for the frame + attributes in the `~astropy.coordinates.Galactocentric` frame, which may be + updated in future versions of ``astropy``. Note that when using + `~astropy.coordinates.Galactocentric`, changing values here will not affect + any attributes that are set explicitly by passing values in to the + `~astropy.coordinates.Galactocentric` initializer. Modifying these defaults + will only affect the frame attribute values when using the frame as, e.g., + ``Galactocentric`` or ``Galactocentric()`` with no explicit arguments. + + This class controls the parameter settings by specifying a string name, + with the following pre-specified options: + + - 'pre-v4.0': The current default value, which sets the default frame + attribute values to their original (pre-astropy-v4.0) values. + - 'v4.0': The attribute values as updated in Astropy version 4.0. + - 'latest': An alias of the most recent parameter set (currently: 'v4.0') + + Alternatively, user-defined parameter settings may be registered, with + :meth:`~astropy.coordinates.galactocentric_frame_defaults.register`, + and used identically as pre-specified parameter sets. At minimum, + registrations must have unique names and a dictionary of parameters + with keys "galcen_coord", "galcen_distance", "galcen_v_sun", "z_sun", + "roll". See examples below. + + This class also tracks the references for all parameter values in the + attribute ``references``, as well as any further information the registry. + The pre-specified options can be extended to include similar + state information as user-defined parameter settings -- for example, to add + parameter uncertainties. + + The preferred method for getting a parameter set and metadata, by name, is + :meth:`~galactocentric_frame_defaults.get_from_registry` since + it ensures the immutability of the registry. + + See :ref:`astropy:astropy-coordinates-galactocentric-defaults` for more + information. + + Examples + -------- + The default `~astropy.coordinates.Galactocentric` frame parameters can be + modified globally:: + + >>> from astropy.coordinates import galactocentric_frame_defaults + >>> _ = galactocentric_frame_defaults.set('v4.0') # doctest: +SKIP + >>> Galactocentric() # doctest: +SKIP + , galcen_distance=8.122 kpc, galcen_v_sun=(12.9, 245.6, 7.78) km / s, z_sun=20.8 pc, roll=0.0 deg)> + >>> _ = galactocentric_frame_defaults.set('pre-v4.0') # doctest: +SKIP + >>> Galactocentric() # doctest: +SKIP + , galcen_distance=8.3 kpc, galcen_v_sun=(11.1, 232.24, 7.25) km / s, z_sun=27.0 pc, roll=0.0 deg)> + + The default parameters can also be updated by using this class as a context + manager:: + + >>> with galactocentric_frame_defaults.set('pre-v4.0'): + ... print(Galactocentric()) # doctest: +FLOAT_CMP + , galcen_distance=8.3 kpc, galcen_v_sun=(11.1, 232.24, 7.25) km / s, z_sun=27.0 pc, roll=0.0 deg)> + + Again, changing the default parameter values will not affect frame + attributes that are explicitly specified:: + + >>> import astropy.units as u + >>> with galactocentric_frame_defaults.set('pre-v4.0'): + ... print(Galactocentric(galcen_distance=8.0*u.kpc)) # doctest: +FLOAT_CMP + , galcen_distance=8.0 kpc, galcen_v_sun=(11.1, 232.24, 7.25) km / s, z_sun=27.0 pc, roll=0.0 deg)> + + Additional parameter sets may be registered, for instance to use the + Dehnen & Binney (1998) measurements of the solar motion. We can also + add metadata, such as the 1-sigma errors. In this example we will modify + the required key "parameters", change the recommended key "references" to + match "parameters", and add the extra key "error" (any key can be added):: + + >>> state = galactocentric_frame_defaults.get_from_registry("v4.0") + >>> state["parameters"]["galcen_v_sun"] = (10.00, 225.25, 7.17) * (u.km / u.s) + >>> state["references"]["galcen_v_sun"] = "https://ui.adsabs.harvard.edu/full/1998MNRAS.298..387D" + >>> state["error"] = {"galcen_v_sun": (0.36, 0.62, 0.38) * (u.km / u.s)} + >>> galactocentric_frame_defaults.register(name="DB1998", **state) + + Just as in the previous examples, the new parameter set can be retrieved with:: + + >>> state = galactocentric_frame_defaults.get_from_registry("DB1998") + >>> print(state["error"]["galcen_v_sun"]) # doctest: +FLOAT_CMP + [0.36 0.62 0.38] km / s + + """ + _latest_value = ... + _value = ... + _references = ... + _state = ... + _registry = ... + @classproperty + def parameters(cls): # -> None: + ... + + @classproperty + def references(cls): # -> _StateProxy | None: + ... + + @classmethod + def get_from_registry(cls, name: str): # -> dict[str, _StateProxy]: + """ + Return Galactocentric solar parameters and metadata given string names + for the parameter sets. This method ensures the returned state is a + mutable copy, so any changes made do not affect the registry state. + + Returns + ------- + state : dict + Copy of the registry for the string name. + Should contain, at minimum: + + - "parameters": dict + Galactocentric solar parameters + - "references" : Dict[str, Union[str, Sequence[str]]] + References for "parameters". + Fields are str or sequence of str. + + Raises + ------ + KeyError + If invalid string input to registry + to retrieve solar parameters for Galactocentric frame. + + """ + ... + + @deprecated("v4.2", alternative="`get_from_registry`") + @classmethod + def get_solar_params_from_string(cls, arg): # -> _StateProxy: + """ + Return Galactocentric solar parameters given string names + for the parameter sets. + + Returns + ------- + parameters : dict + Copy of Galactocentric solar parameters from registry + + Raises + ------ + KeyError + If invalid string input to registry + to retrieve solar parameters for Galactocentric frame. + + """ + ... + + @classmethod + def validate(cls, value): # -> _StateProxy | dict[Unknown, Unknown]: + ... + + @classmethod + def register(cls, name: str, parameters: dict, references=..., **meta: dict): # -> None: + """Register a set of parameters. + + Parameters + ---------- + name : str + The registration name for the parameter and metadata set. + parameters : dict + The solar parameters for Galactocentric frame. + references : dict or None, optional + References for contents of `parameters`. + None becomes empty dict. + **meta : dict, optional + Any other properties to register. + + """ + ... + + + +doc_components = ... +doc_footer = ... +@format_doc(base_doc, components=doc_components, footer=doc_footer) +class Galactocentric(BaseCoordinateFrame): + r""" + A coordinate or frame in the Galactocentric system. + + This frame allows specifying the Sun-Galactic center distance, the height of + the Sun above the Galactic midplane, and the solar motion relative to the + Galactic center. However, as there is no modern standard definition of a + Galactocentric reference frame, it is important to pay attention to the + default values used in this class if precision is important in your code. + The default values of the parameters of this frame are taken from the + original definition of the frame in 2014. As such, the defaults are somewhat + out of date relative to recent measurements made possible by, e.g., Gaia. + The defaults can, however, be changed at runtime by setting the parameter + set name in `~astropy.coordinates.galactocentric_frame_defaults`. + + The current default parameter set is ``"pre-v4.0"``, indicating that the + parameters were adopted before ``astropy`` version 4.0. A regularly-updated + parameter set can instead be used by setting + ``galactocentric_frame_defaults.set ('latest')``, and other parameter set + names may be added in future versions. To find out the scientific papers + that the current default parameters are derived from, use + ``galcen.frame_attribute_references`` (where ``galcen`` is an instance of + this frame), which will update even if the default parameter set is changed. + + The position of the Sun is assumed to be on the x axis of the final, + right-handed system. That is, the x axis points from the position of + the Sun projected to the Galactic midplane to the Galactic center -- + roughly towards :math:`(l,b) = (0^\circ,0^\circ)`. For the default + transformation (:math:`{\rm roll}=0^\circ`), the y axis points roughly + towards Galactic longitude :math:`l=90^\circ`, and the z axis points + roughly towards the North Galactic Pole (:math:`b=90^\circ`). + + For a more detailed look at the math behind this transformation, see + the document :ref:`astropy:coordinates-galactocentric`. + + The frame attributes are listed under **Other Parameters**. + """ + default_representation = r.CartesianRepresentation + default_differential = r.CartesianDifferential + galcen_coord = ... + galcen_distance = ... + galcen_v_sun = ... + z_sun = ... + roll = ... + def __init__(self, *args, **kwargs) -> None: + ... + + @classmethod + def get_roll0(cls): # -> Angle: + """ + The additional roll angle (about the final x axis) necessary to align + the final z axis to match the Galactic yz-plane. Setting the ``roll`` + frame attribute to -this method's return value removes this rotation, + allowing the use of the `Galactocentric` frame in more general contexts. + """ + ... + + + +def get_matrix_vectors(galactocentric_frame, inverse=...): # -> tuple[Any, Unknown]: + """ + Use the ``inverse`` argument to get the inverse transformation, matrix and + offsets to go from Galactocentric to ICRS. + """ + ... + +@frame_transform_graph.transform(AffineTransform, ICRS, Galactocentric) +def icrs_to_galactocentric(icrs_coord, galactocentric_frame): # -> tuple[Any, Unknown]: + ... + +@frame_transform_graph.transform(AffineTransform, Galactocentric, ICRS) +def galactocentric_to_icrs(galactocentric_coord, icrs_frame): # -> tuple[Any, Unknown]: + ... + diff --git a/typings/astropy/coordinates/builtin_frames/gcrs.pyi b/typings/astropy/coordinates/builtin_frames/gcrs.pyi new file mode 100644 index 0000000..7804231 --- /dev/null +++ b/typings/astropy/coordinates/builtin_frames/gcrs.pyi @@ -0,0 +1,51 @@ +""" +This type stub file was generated by pyright. +""" + +from astropy.utils.decorators import format_doc +from astropy.coordinates.baseframe import base_doc +from .baseradec import BaseRADecFrame, doc_components + +__all__ = ['GCRS', 'PrecessedGeocentric'] +doc_footer_gcrs = ... +@format_doc(base_doc, components=doc_components, footer=doc_footer_gcrs) +class GCRS(BaseRADecFrame): + """ + A coordinate or frame in the Geocentric Celestial Reference System (GCRS). + + GCRS is distinct form ICRS mainly in that it is relative to the Earth's + center-of-mass rather than the solar system Barycenter. That means this + frame includes the effects of aberration (unlike ICRS). For more background + on the GCRS, see the references provided in the + :ref:`astropy:astropy-coordinates-seealso` section of the documentation. (Of + particular note is Section 1.2 of + `USNO Circular 179 `_) + + This frame also includes frames that are defined *relative* to the Earth, + but that are offset (in both position and velocity) from the Earth. + + The frame attributes are listed under **Other Parameters**. + """ + obstime = ... + obsgeoloc = ... + obsgeovel = ... + + +doc_footer_prec_geo = ... +@format_doc(base_doc, components=doc_components, footer=doc_footer_prec_geo) +class PrecessedGeocentric(BaseRADecFrame): + """ + A coordinate frame defined in a similar manner as GCRS, but precessed to a + requested (mean) equinox. Note that this does *not* end up the same as + regular GCRS even for J2000 equinox, because the GCRS orientation is fixed + to that of ICRS, which is not quite the same as the dynamical J2000 + orientation. + + The frame attributes are listed under **Other Parameters** + """ + equinox = ... + obstime = ... + obsgeoloc = ... + obsgeovel = ... + + diff --git a/typings/astropy/coordinates/builtin_frames/hadec.pyi b/typings/astropy/coordinates/builtin_frames/hadec.pyi new file mode 100644 index 0000000..fb5b0f3 --- /dev/null +++ b/typings/astropy/coordinates/builtin_frames/hadec.pyi @@ -0,0 +1,46 @@ +""" +This type stub file was generated by pyright. +""" + +from astropy.utils.decorators import format_doc +from astropy.coordinates import representation as r +from astropy.coordinates.baseframe import BaseCoordinateFrame, base_doc + +__all__ = ['HADec'] +doc_components = ... +doc_footer = ... +@format_doc(base_doc, components=doc_components, footer=doc_footer) +class HADec(BaseCoordinateFrame): + """ + A coordinate or frame in the Hour Angle-Declination system (Equatorial + coordinates) with respect to the WGS84 ellipsoid. Hour Angle is oriented + with respect to upper culmination such that the hour angle is negative to + the East and positive to the West. + + This frame is assumed to *include* refraction effects if the ``pressure`` + frame attribute is non-zero. + + The frame attributes are listed under **Other Parameters**, which are + necessary for transforming from HADec to some other system. + """ + frame_specific_representation_info = ... + default_representation = r.SphericalRepresentation + default_differential = r.SphericalCosLatDifferential + obstime = ... + location = ... + pressure = ... + temperature = ... + relative_humidity = ... + obswl = ... + def __init__(self, *args, **kwargs) -> None: + ... + + def represent_as(self, base, s=..., in_frame_units=...): + """ + Ensure the wrap angle for any spherical + representations. + """ + ... + + + diff --git a/typings/astropy/coordinates/builtin_frames/hcrs.pyi b/typings/astropy/coordinates/builtin_frames/hcrs.pyi new file mode 100644 index 0000000..83f94bf --- /dev/null +++ b/typings/astropy/coordinates/builtin_frames/hcrs.pyi @@ -0,0 +1,33 @@ +""" +This type stub file was generated by pyright. +""" + +from astropy.utils.decorators import format_doc +from astropy.coordinates.baseframe import base_doc +from .baseradec import BaseRADecFrame, doc_components + +__all__ = ['HCRS'] +doc_footer = ... +@format_doc(base_doc, components=doc_components, footer=doc_footer) +class HCRS(BaseRADecFrame): + """ + A coordinate or frame in a Heliocentric system, with axes aligned to ICRS. + + The ICRS has an origin at the Barycenter and axes which are fixed with + respect to space. + + This coordinate system is distinct from ICRS mainly in that it is relative + to the Sun's center-of-mass rather than the solar system Barycenter. + In principle, therefore, this frame should include the effects of + aberration (unlike ICRS), but this is not done, since they are very small, + of the order of 8 milli-arcseconds. + + For more background on the ICRS and related coordinate transformations, see + the references provided in the :ref:`astropy:astropy-coordinates-seealso` + section of the documentation. + + The frame attributes are listed under **Other Parameters**. + """ + obstime = ... + + diff --git a/typings/astropy/coordinates/builtin_frames/icrs.pyi b/typings/astropy/coordinates/builtin_frames/icrs.pyi new file mode 100644 index 0000000..f5ff38b --- /dev/null +++ b/typings/astropy/coordinates/builtin_frames/icrs.pyi @@ -0,0 +1,26 @@ +""" +This type stub file was generated by pyright. +""" + +from astropy.utils.decorators import format_doc +from astropy.coordinates.baseframe import base_doc +from .baseradec import BaseRADecFrame, doc_components + +__all__ = ['ICRS'] +@format_doc(base_doc, components=doc_components, footer="") +class ICRS(BaseRADecFrame): + """ + A coordinate or frame in the ICRS system. + + If you're looking for "J2000" coordinates, and aren't sure if you want to + use this or `~astropy.coordinates.FK5`, you probably want to use ICRS. It's + more well-defined as a catalog coordinate and is an inertial system, and is + very close (within tens of milliarcseconds) to J2000 equatorial. + + For more background on the ICRS and related coordinate transformations, see + the references provided in the :ref:`astropy:astropy-coordinates-seealso` + section of the documentation. + """ + ... + + diff --git a/typings/astropy/coordinates/builtin_frames/icrs_cirs_transforms.pyi b/typings/astropy/coordinates/builtin_frames/icrs_cirs_transforms.pyi new file mode 100644 index 0000000..bc05f93 --- /dev/null +++ b/typings/astropy/coordinates/builtin_frames/icrs_cirs_transforms.pyi @@ -0,0 +1,44 @@ +""" +This type stub file was generated by pyright. +""" + +from astropy.coordinates.baseframe import frame_transform_graph +from astropy.coordinates.transformations import AffineTransform, FunctionTransformWithFiniteDifference +from .icrs import ICRS +from .gcrs import GCRS +from .cirs import CIRS +from .hcrs import HCRS + +""" +Contains the transformation functions for getting from ICRS/HCRS to CIRS and +anything in between (currently that means GCRS) +""" +@frame_transform_graph.transform(FunctionTransformWithFiniteDifference, ICRS, CIRS) +def icrs_to_cirs(icrs_coo, cirs_frame): + ... + +@frame_transform_graph.transform(FunctionTransformWithFiniteDifference, CIRS, ICRS) +def cirs_to_icrs(cirs_coo, icrs_frame): + ... + +@frame_transform_graph.transform(FunctionTransformWithFiniteDifference, ICRS, GCRS) +def icrs_to_gcrs(icrs_coo, gcrs_frame): + ... + +@frame_transform_graph.transform(FunctionTransformWithFiniteDifference, GCRS, ICRS) +def gcrs_to_icrs(gcrs_coo, icrs_frame): + ... + +@frame_transform_graph.transform(FunctionTransformWithFiniteDifference, GCRS, HCRS) +def gcrs_to_hcrs(gcrs_coo, hcrs_frame): + ... + +_NEED_ORIGIN_HINT = ... +@frame_transform_graph.transform(AffineTransform, HCRS, ICRS) +def hcrs_to_icrs(hcrs_coo, icrs_frame): # -> tuple[None, Unknown | CartesianRepresentation | tuple[CartesianRepresentation, CartesianRepresentation | Unbound]]: + ... + +@frame_transform_graph.transform(AffineTransform, ICRS, HCRS) +def icrs_to_hcrs(icrs_coo, hcrs_frame): # -> tuple[None, Unknown | CartesianRepresentation | tuple[CartesianRepresentation, CartesianRepresentation | Unbound]]: + ... + diff --git a/typings/astropy/coordinates/builtin_frames/icrs_fk5_transforms.pyi b/typings/astropy/coordinates/builtin_frames/icrs_fk5_transforms.pyi new file mode 100644 index 0000000..aee6a3a --- /dev/null +++ b/typings/astropy/coordinates/builtin_frames/icrs_fk5_transforms.pyi @@ -0,0 +1,18 @@ +""" +This type stub file was generated by pyright. +""" + +from astropy.coordinates.baseframe import frame_transform_graph +from astropy.coordinates.transformations import DynamicMatrixTransform +from .fk5 import FK5 +from .icrs import ICRS + +_ICRS_TO_FK5_J2000_MAT = ... +@frame_transform_graph.transform(DynamicMatrixTransform, ICRS, FK5) +def icrs_to_fk5(icrscoord, fk5frame): # -> Any: + ... + +@frame_transform_graph.transform(DynamicMatrixTransform, FK5, ICRS) +def fk5_to_icrs(fk5coord, icrsframe): # -> Any: + ... + diff --git a/typings/astropy/coordinates/builtin_frames/icrs_observed_transforms.pyi b/typings/astropy/coordinates/builtin_frames/icrs_observed_transforms.pyi new file mode 100644 index 0000000..060c87e --- /dev/null +++ b/typings/astropy/coordinates/builtin_frames/icrs_observed_transforms.pyi @@ -0,0 +1,23 @@ +""" +This type stub file was generated by pyright. +""" + +from astropy.coordinates.baseframe import frame_transform_graph +from astropy.coordinates.transformations import FunctionTransformWithFiniteDifference +from .icrs import ICRS +from .altaz import AltAz +from .hadec import HADec + +""" +Contains the transformation functions for getting to "observed" systems from ICRS. +""" +@frame_transform_graph.transform(FunctionTransformWithFiniteDifference, ICRS, AltAz) +@frame_transform_graph.transform(FunctionTransformWithFiniteDifference, ICRS, HADec) +def icrs_to_observed(icrs_coo, observed_frame): # -> AltAz: + ... + +@frame_transform_graph.transform(FunctionTransformWithFiniteDifference, AltAz, ICRS) +@frame_transform_graph.transform(FunctionTransformWithFiniteDifference, HADec, ICRS) +def observed_to_icrs(observed_coo, icrs_frame): + ... + diff --git a/typings/astropy/coordinates/builtin_frames/intermediate_rotation_transforms.pyi b/typings/astropy/coordinates/builtin_frames/intermediate_rotation_transforms.pyi new file mode 100644 index 0000000..bd7eea4 --- /dev/null +++ b/typings/astropy/coordinates/builtin_frames/intermediate_rotation_transforms.pyi @@ -0,0 +1,98 @@ +""" +This type stub file was generated by pyright. +""" + +from astropy.coordinates.baseframe import frame_transform_graph +from astropy.coordinates.transformations import FunctionTransformWithFiniteDifference +from .gcrs import GCRS, PrecessedGeocentric +from .cirs import CIRS +from .itrs import ITRS +from .equatorial import TEME, TETE + +""" +Contains the transformation functions for getting to/from ITRS, TEME, GCRS, and CIRS. +These are distinct from the ICRS and AltAz functions because they are just +rotations without aberration corrections or offsets. +""" +def teme_to_itrs_mat(time): + ... + +def gcrs_to_cirs_mat(time): + ... + +def cirs_to_itrs_mat(time): + ... + +def tete_to_itrs_mat(time, rbpn=...): + """Compute the polar motion p-matrix at the given time. + + If the nutation-precession matrix is already known, it should be passed in, + as this is by far the most expensive calculation. + """ + ... + +def gcrs_precession_mat(equinox): + ... + +def get_location_gcrs(location, obstime, ref_to_itrs, gcrs_to_ref): # -> GCRS: + """Create a GCRS frame at the location and obstime. + + The reference frame z axis must point to the Celestial Intermediate Pole + (as is the case for CIRS and TETE). + + This function is here to avoid location.get_gcrs(obstime), which would + recalculate matrices that are already available below (and return a GCRS + coordinate, rather than a frame with obsgeoloc and obsgeovel). Instead, + it uses the private method that allows passing in the matrices. + + """ + ... + +@frame_transform_graph.transform(FunctionTransformWithFiniteDifference, GCRS, TETE) +def gcrs_to_tete(gcrs_coo, tete_frame): + ... + +@frame_transform_graph.transform(FunctionTransformWithFiniteDifference, TETE, GCRS) +def tete_to_gcrs(tete_coo, gcrs_frame): # -> Any: + ... + +@frame_transform_graph.transform(FunctionTransformWithFiniteDifference, TETE, ITRS) +def tete_to_itrs(tete_coo, itrs_frame): + ... + +@frame_transform_graph.transform(FunctionTransformWithFiniteDifference, ITRS, TETE) +def itrs_to_tete(itrs_coo, tete_frame): # -> Any: + ... + +@frame_transform_graph.transform(FunctionTransformWithFiniteDifference, GCRS, CIRS) +def gcrs_to_cirs(gcrs_coo, cirs_frame): + ... + +@frame_transform_graph.transform(FunctionTransformWithFiniteDifference, CIRS, GCRS) +def cirs_to_gcrs(cirs_coo, gcrs_frame): # -> Any: + ... + +@frame_transform_graph.transform(FunctionTransformWithFiniteDifference, CIRS, ITRS) +def cirs_to_itrs(cirs_coo, itrs_frame): + ... + +@frame_transform_graph.transform(FunctionTransformWithFiniteDifference, ITRS, CIRS) +def itrs_to_cirs(itrs_coo, cirs_frame): # -> Any: + ... + +@frame_transform_graph.transform(FunctionTransformWithFiniteDifference, GCRS, PrecessedGeocentric) +def gcrs_to_precessedgeo(from_coo, to_frame): + ... + +@frame_transform_graph.transform(FunctionTransformWithFiniteDifference, PrecessedGeocentric, GCRS) +def precessedgeo_to_gcrs(from_coo, to_frame): # -> Any: + ... + +@frame_transform_graph.transform(FunctionTransformWithFiniteDifference, TEME, ITRS) +def teme_to_itrs(teme_coo, itrs_frame): # -> Any: + ... + +@frame_transform_graph.transform(FunctionTransformWithFiniteDifference, ITRS, TEME) +def itrs_to_teme(itrs_coo, teme_frame): + ... + diff --git a/typings/astropy/coordinates/builtin_frames/itrs.pyi b/typings/astropy/coordinates/builtin_frames/itrs.pyi new file mode 100644 index 0000000..a3ada6d --- /dev/null +++ b/typings/astropy/coordinates/builtin_frames/itrs.pyi @@ -0,0 +1,30 @@ +""" +This type stub file was generated by pyright. +""" + +from astropy.utils.decorators import format_doc +from astropy.coordinates.representation import CartesianDifferential, CartesianRepresentation +from astropy.coordinates.baseframe import BaseCoordinateFrame, base_doc + +__all__ = ['ITRS'] +@format_doc(base_doc, components="", footer="") +class ITRS(BaseCoordinateFrame): + """ + A coordinate or frame in the International Terrestrial Reference System + (ITRS). This is approximately a geocentric system, although strictly it is + defined by a series of reference locations near the surface of the Earth. + For more background on the ITRS, see the references provided in the + :ref:`astropy:astropy-coordinates-seealso` section of the documentation. + """ + default_representation = CartesianRepresentation + default_differential = CartesianDifferential + obstime = ... + @property + def earth_location(self): # -> EarthLocation: + """ + The data in this frame as an `~astropy.coordinates.EarthLocation` class. + """ + ... + + + diff --git a/typings/astropy/coordinates/builtin_frames/lsr.pyi b/typings/astropy/coordinates/builtin_frames/lsr.pyi new file mode 100644 index 0000000..4ca1409 --- /dev/null +++ b/typings/astropy/coordinates/builtin_frames/lsr.pyi @@ -0,0 +1,148 @@ +""" +This type stub file was generated by pyright. +""" + +from astropy.utils.decorators import format_doc +from astropy.coordinates import representation as r +from astropy.coordinates.baseframe import BaseCoordinateFrame, base_doc, frame_transform_graph +from astropy.coordinates.transformations import AffineTransform +from .baseradec import BaseRADecFrame, doc_components as doc_components_radec +from .icrs import ICRS +from .galactic import Galactic + +J2000 = ... +v_bary_Schoenrich2010 = ... +__all__ = ['LSR', 'GalacticLSR', 'LSRK', 'LSRD'] +doc_footer_lsr = ... +@format_doc(base_doc, components=doc_components_radec, footer=doc_footer_lsr) +class LSR(BaseRADecFrame): + r"""A coordinate or frame in the Local Standard of Rest (LSR). + + This coordinate frame is axis-aligned and co-spatial with `ICRS`, but has + a velocity offset relative to the solar system barycenter to remove the + peculiar motion of the sun relative to the LSR. Roughly, the LSR is the mean + velocity of the stars in the solar neighborhood, but the precise definition + of which depends on the study. As defined in Schönrich et al. (2010): + "The LSR is the rest frame at the location of the Sun of a star that would + be on a circular orbit in the gravitational potential one would obtain by + azimuthally averaging away non-axisymmetric features in the actual Galactic + potential." No such orbit truly exists, but it is still a commonly used + velocity frame. + + We use default values from Schönrich et al. (2010) for the barycentric + velocity relative to the LSR, which is defined in Galactic (right-handed) + cartesian velocity components + :math:`(U, V, W) = (11.1, 12.24, 7.25)~{{\rm km}}~{{\rm s}}^{{-1}}`. These + values are customizable via the ``v_bary`` argument which specifies the + velocity of the solar system barycenter with respect to the LSR. + + The frame attributes are listed under **Other Parameters**. + """ + v_bary = ... + + +@frame_transform_graph.transform(AffineTransform, ICRS, LSR) +def icrs_to_lsr(icrs_coord, lsr_frame): # -> tuple[None, CartesianRepresentation]: + ... + +@frame_transform_graph.transform(AffineTransform, LSR, ICRS) +def lsr_to_icrs(lsr_coord, icrs_frame): # -> tuple[None, CartesianRepresentation]: + ... + +doc_components_gal = ... +@format_doc(base_doc, components=doc_components_gal, footer=doc_footer_lsr) +class GalacticLSR(BaseCoordinateFrame): + r"""A coordinate or frame in the Local Standard of Rest (LSR), axis-aligned + to the `Galactic` frame. + + This coordinate frame is axis-aligned and co-spatial with `ICRS`, but has + a velocity offset relative to the solar system barycenter to remove the + peculiar motion of the sun relative to the LSR. Roughly, the LSR is the mean + velocity of the stars in the solar neighborhood, but the precise definition + of which depends on the study. As defined in Schönrich et al. (2010): + "The LSR is the rest frame at the location of the Sun of a star that would + be on a circular orbit in the gravitational potential one would obtain by + azimuthally averaging away non-axisymmetric features in the actual Galactic + potential." No such orbit truly exists, but it is still a commonly used + velocity frame. + + We use default values from Schönrich et al. (2010) for the barycentric + velocity relative to the LSR, which is defined in Galactic (right-handed) + cartesian velocity components + :math:`(U, V, W) = (11.1, 12.24, 7.25)~{{\rm km}}~{{\rm s}}^{{-1}}`. These + values are customizable via the ``v_bary`` argument which specifies the + velocity of the solar system barycenter with respect to the LSR. + + The frame attributes are listed under **Other Parameters**. + """ + frame_specific_representation_info = ... + default_representation = r.SphericalRepresentation + default_differential = r.SphericalCosLatDifferential + v_bary = ... + + +@frame_transform_graph.transform(AffineTransform, Galactic, GalacticLSR) +def galactic_to_galacticlsr(galactic_coord, lsr_frame): # -> tuple[None, CartesianRepresentation]: + ... + +@frame_transform_graph.transform(AffineTransform, GalacticLSR, Galactic) +def galacticlsr_to_galactic(lsr_coord, galactic_frame): # -> tuple[None, CartesianRepresentation]: + ... + +class LSRK(BaseRADecFrame): + r""" + A coordinate or frame in the Kinematic Local Standard of Rest (LSR). + + This frame is defined as having a velocity of 20 km/s towards RA=270 Dec=30 + (B1900) relative to the solar system Barycenter. This is defined in: + + Gordon 1975, Methods of Experimental Physics: Volume 12: + Astrophysics, Part C: Radio Observations - Section 6.1.5. + + This coordinate frame is axis-aligned and co-spatial with `ICRS`, but has + a velocity offset relative to the solar system barycenter to remove the + peculiar motion of the sun relative to the LSRK. + """ + ... + + +V_OFFSET_LSRK = ... +ICRS_LSRK_OFFSET = ... +LSRK_ICRS_OFFSET = ... +@frame_transform_graph.transform(AffineTransform, ICRS, LSRK) +def icrs_to_lsrk(icrs_coord, lsr_frame): # -> tuple[None, CartesianRepresentation]: + ... + +@frame_transform_graph.transform(AffineTransform, LSRK, ICRS) +def lsrk_to_icrs(lsr_coord, icrs_frame): # -> tuple[None, CartesianRepresentation]: + ... + +class LSRD(BaseRADecFrame): + r""" + A coordinate or frame in the Dynamical Local Standard of Rest (LSRD) + + This frame is defined as a velocity of U=9 km/s, V=12 km/s, + and W=7 km/s in Galactic coordinates or 16.552945 km/s + towards l=53.13 b=25.02. This is defined in: + + Delhaye 1965, Solar Motion and Velocity Distribution of + Common Stars. + + This coordinate frame is axis-aligned and co-spatial with `ICRS`, but has + a velocity offset relative to the solar system barycenter to remove the + peculiar motion of the sun relative to the LSRD. + """ + ... + + +V_OFFSET_LSRD = ... +ICRS_LSRD_OFFSET = ... +LSRD_ICRS_OFFSET = ... +@frame_transform_graph.transform(AffineTransform, ICRS, LSRD) +def icrs_to_lsrd(icrs_coord, lsr_frame): # -> tuple[None, CartesianRepresentation]: + ... + +@frame_transform_graph.transform(AffineTransform, LSRD, ICRS) +def lsrd_to_icrs(lsr_coord, icrs_frame): # -> tuple[None, CartesianRepresentation]: + ... + diff --git a/typings/astropy/coordinates/builtin_frames/skyoffset.pyi b/typings/astropy/coordinates/builtin_frames/skyoffset.pyi new file mode 100644 index 0000000..bdc1fad --- /dev/null +++ b/typings/astropy/coordinates/builtin_frames/skyoffset.pyi @@ -0,0 +1,95 @@ +""" +This type stub file was generated by pyright. +""" + +from astropy.coordinates.baseframe import BaseCoordinateFrame + +_skyoffset_cache = ... +def make_skyoffset_cls(framecls): # -> Any: + """ + Create a new class that is the sky offset frame for a specific class of + origin frame. If such a class has already been created for this frame, the + same class will be returned. + + The new class will always have component names for spherical coordinates of + ``lon``/``lat``. + + Parameters + ---------- + framecls : `~astropy.coordinates.BaseCoordinateFrame` subclass + The class to create the SkyOffsetFrame of. + + Returns + ------- + skyoffsetframecls : class + The class for the new skyoffset frame. + + Notes + ----- + This function is necessary because Astropy's frame transformations depend + on connection between specific frame *classes*. So each type of frame + needs its own distinct skyoffset frame class. This function generates + just that class, as well as ensuring that only one example of such a class + actually gets created in any given python session. + """ + ... + +class SkyOffsetFrame(BaseCoordinateFrame): + """ + A frame which is relative to some specific position and oriented to match + its frame. + + SkyOffsetFrames always have component names for spherical coordinates + of ``lon``/``lat``, *not* the component names for the frame of ``origin``. + + This is useful for calculating offsets and dithers in the frame of the sky + relative to an arbitrary position. Coordinates in this frame are both centered on the position specified by the + ``origin`` coordinate, *and* they are oriented in the same manner as the + ``origin`` frame. E.g., if ``origin`` is `~astropy.coordinates.ICRS`, this + object's ``lat`` will be pointed in the direction of Dec, while ``lon`` + will point in the direction of RA. + + For more on skyoffset frames, see :ref:`astropy:astropy-skyoffset-frames`. + + Parameters + ---------- + representation : `~astropy.coordinates.BaseRepresentation` or None + A representation object or None to have no data (or use the other keywords) + origin : coordinate-like + The coordinate which specifies the origin of this frame. Note that this + origin is used purely for on-sky location/rotation. It can have a + ``distance`` but it will not be used by this ``SkyOffsetFrame``. + rotation : angle-like + The final rotation of the frame about the ``origin``. The sign of + the rotation is the left-hand rule. That is, an object at a + particular position angle in the un-rotated system will be sent to + the positive latitude (z) direction in the final frame. + + + Notes + ----- + ``SkyOffsetFrame`` is a factory class. That is, the objects that it + yields are *not* actually objects of class ``SkyOffsetFrame``. Instead, + distinct classes are created on-the-fly for whatever the frame class is + of ``origin``. + """ + rotation = ... + origin = ... + def __new__(cls, *args, **kwargs): # -> Any | SkyOffsetFrame: + ... + + def __init__(self, *args, **kwargs) -> None: + ... + + def represent_as(self, base, s=..., in_frame_units=...): + """ + Ensure the wrap angle for any spherical + representations. + """ + ... + + def __reduce__(self): # -> tuple[(origin: Unknown) -> (Unknown | Any | SkyOffsetFrame), tuple[Unknown | Any | None], dict[str, Any]]: + ... + + + diff --git a/typings/astropy/coordinates/builtin_frames/supergalactic.pyi b/typings/astropy/coordinates/builtin_frames/supergalactic.pyi new file mode 100644 index 0000000..d6ca580 --- /dev/null +++ b/typings/astropy/coordinates/builtin_frames/supergalactic.pyi @@ -0,0 +1,23 @@ +""" +This type stub file was generated by pyright. +""" + +from astropy.utils.decorators import format_doc +from astropy.coordinates import representation as r +from astropy.coordinates.baseframe import BaseCoordinateFrame, base_doc + +__all__ = ['Supergalactic'] +doc_components = ... +@format_doc(base_doc, components=doc_components, footer="") +class Supergalactic(BaseCoordinateFrame): + """ + Supergalactic Coordinates + (see Lahav et al. 2000, , + and references therein). + """ + frame_specific_representation_info = ... + default_representation = r.SphericalRepresentation + default_differential = r.SphericalCosLatDifferential + _nsgp_gal = ... + + diff --git a/typings/astropy/coordinates/builtin_frames/supergalactic_transforms.pyi b/typings/astropy/coordinates/builtin_frames/supergalactic_transforms.pyi new file mode 100644 index 0000000..9fefe58 --- /dev/null +++ b/typings/astropy/coordinates/builtin_frames/supergalactic_transforms.pyi @@ -0,0 +1,17 @@ +""" +This type stub file was generated by pyright. +""" + +from astropy.coordinates.baseframe import frame_transform_graph +from astropy.coordinates.transformations import StaticMatrixTransform +from .galactic import Galactic +from .supergalactic import Supergalactic + +@frame_transform_graph.transform(StaticMatrixTransform, Galactic, Supergalactic) +def gal_to_supergal(): # -> Any: + ... + +@frame_transform_graph.transform(StaticMatrixTransform, Supergalactic, Galactic) +def supergal_to_gal(): # -> Any: + ... + diff --git a/typings/astropy/coordinates/builtin_frames/utils.pyi b/typings/astropy/coordinates/builtin_frames/utils.pyi new file mode 100644 index 0000000..ecad857 --- /dev/null +++ b/typings/astropy/coordinates/builtin_frames/utils.pyi @@ -0,0 +1,196 @@ +""" +This type stub file was generated by pyright. +""" + +""" +This module contains functions/values used repeatedly in different modules of +the ``builtin_frames`` package. +""" +EQUINOX_J2000 = ... +EQUINOX_B1950 = ... +DEFAULT_OBSTIME = ... +EARTH_CENTER = ... +PIOVER2 = ... +_DEFAULT_PM = ... +def get_polar_motion(time): # -> tuple[Unknown, Unknown]: + """ + gets the two polar motion components in radians for use with apio + """ + ... + +def get_dut1utc(time): # -> NDArray[float64]: + """ + This function is used to get UT1-UTC in coordinates because normally it + gives an error outside the IERS range, but in coordinates we want to allow + it to go through but with a warning. + """ + ... + +def get_jd12(time, scale): # -> tuple[Unknown | Any, Unknown | Any]: + """ + Gets ``jd1`` and ``jd2`` from a time object in a particular scale. + + Parameters + ---------- + time : `~astropy.time.Time` + The time to get the jds for + scale : str + The time scale to get the jds for + + Returns + ------- + jd1 : float + jd2 : float + """ + ... + +def norm(p): + """ + Normalise a p-vector. + """ + ... + +def pav2pv(p, v): # -> NDArray[float64]: + """ + Combine p- and v- vectors into a pv-vector. + """ + ... + +def get_cip(jd1, jd2): # -> tuple[Unknown, Unknown, Unknown]: + """ + Find the X, Y coordinates of the CIP and the CIO locator, s. + + Parameters + ---------- + jd1 : float or `np.ndarray` + First part of two part Julian date (TDB) + jd2 : float or `np.ndarray` + Second part of two part Julian date (TDB) + + Returns + ------- + x : float or `np.ndarray` + x coordinate of the CIP + y : float or `np.ndarray` + y coordinate of the CIP + s : float or `np.ndarray` + CIO locator, s + """ + ... + +def aticq(srepr, astrom): # -> tuple[Unknown, Unknown]: + """ + A slightly modified version of the ERFA function ``eraAticq``. + + ``eraAticq`` performs the transformations between two coordinate systems, + with the details of the transformation being encoded into the ``astrom`` array. + + There are two issues with the version of aticq in ERFA. Both are associated + with the handling of light deflection. + + The companion function ``eraAtciqz`` is meant to be its inverse. However, this + is not true for directions close to the Solar centre, since the light deflection + calculations are numerically unstable and therefore not reversible. + + This version sidesteps that problem by artificially reducing the light deflection + for directions which are within 90 arcseconds of the Sun's position. This is the + same approach used by the ERFA functions above, except that they use a threshold of + 9 arcseconds. + + In addition, ERFA's aticq assumes a distant source, so there is no difference between + the object-Sun vector and the observer-Sun vector. This can lead to errors of up to a + few arcseconds in the worst case (e.g a Venus transit). + + Parameters + ---------- + srepr : `~astropy.coordinates.SphericalRepresentation` + Astrometric GCRS or CIRS position of object from observer + astrom : eraASTROM array + ERFA astrometry context, as produced by, e.g. ``eraApci13`` or ``eraApcs13`` + + Returns + ------- + rc : float or `~numpy.ndarray` + Right Ascension in radians + dc : float or `~numpy.ndarray` + Declination in radians + """ + ... + +def atciqz(srepr, astrom): # -> tuple[Unknown, Unknown]: + """ + A slightly modified version of the ERFA function ``eraAtciqz``. + + ``eraAtciqz`` performs the transformations between two coordinate systems, + with the details of the transformation being encoded into the ``astrom`` array. + + There are two issues with the version of atciqz in ERFA. Both are associated + with the handling of light deflection. + + The companion function ``eraAticq`` is meant to be its inverse. However, this + is not true for directions close to the Solar centre, since the light deflection + calculations are numerically unstable and therefore not reversible. + + This version sidesteps that problem by artificially reducing the light deflection + for directions which are within 90 arcseconds of the Sun's position. This is the + same approach used by the ERFA functions above, except that they use a threshold of + 9 arcseconds. + + In addition, ERFA's atciqz assumes a distant source, so there is no difference between + the object-Sun vector and the observer-Sun vector. This can lead to errors of up to a + few arcseconds in the worst case (e.g a Venus transit). + + Parameters + ---------- + srepr : `~astropy.coordinates.SphericalRepresentation` + Astrometric ICRS position of object from observer + astrom : eraASTROM array + ERFA astrometry context, as produced by, e.g. ``eraApci13`` or ``eraApcs13`` + + Returns + ------- + ri : float or `~numpy.ndarray` + Right Ascension in radians + di : float or `~numpy.ndarray` + Declination in radians + """ + ... + +def prepare_earth_position_vel(time): # -> tuple[Unknown | NDArray[float64], Unknown]: + """ + Get barycentric position and velocity, and heliocentric position of Earth + + Parameters + ---------- + time : `~astropy.time.Time` + time at which to calculate position and velocity of Earth + + Returns + ------- + earth_pv : `np.ndarray` + Barycentric position and velocity of Earth, in au and au/day + earth_helio : `np.ndarray` + Heliocentric position of Earth in au + """ + ... + +def get_offset_sun_from_barycenter(time, include_velocity=..., reverse=...): # -> CartesianRepresentation | tuple[CartesianRepresentation, CartesianRepresentation | Unbound]: + """ + Returns the offset of the Sun center from the solar-system barycenter (SSB). + + Parameters + ---------- + time : `~astropy.time.Time` + Time at which to calculate the offset + include_velocity : `bool` + If ``True``, attach the velocity as a differential. Defaults to ``False``. + reverse : `bool` + If ``True``, return the offset of the barycenter from the Sun. Defaults to ``False``. + + Returns + ------- + `~astropy.coordinates.CartesianRepresentation` + The offset + """ + ... + diff --git a/typings/astropy/coordinates/calculation.pyi b/typings/astropy/coordinates/calculation.pyi new file mode 100644 index 0000000..96e6961 --- /dev/null +++ b/typings/astropy/coordinates/calculation.pyi @@ -0,0 +1,52 @@ +""" +This type stub file was generated by pyright. +""" + +__all__ = [] +class HumanError(ValueError): + ... + + +class CelestialError(ValueError): + ... + + +def get_sign(dt): # -> Literal['capricorn', 'aquarius', 'pisces', 'aries', 'taurus', 'gemini', 'cancer', 'leo', 'virgo', 'libra', 'scorpio', 'sagittarius']: + """ + """ + ... + +_VALID_SIGNS = ... +_CONST_TO_SIGNS = ... +_ZODIAC = ... +def horoscope(birthday, corrected=..., chinese=...): # -> None: + """ + Enter your birthday as an `astropy.time.Time` object and + receive a mystical horoscope about things to come. + + Parameters + ---------- + birthday : `astropy.time.Time` or str + Your birthday as a `datetime.datetime` or `astropy.time.Time` object + or "YYYY-MM-DD"string. + corrected : bool + Whether to account for the precession of the Earth instead of using the + ancient Greek dates for the signs. After all, you do want your *real* + horoscope, not a cheap inaccurate approximation, right? + + chinese : bool + Chinese annual zodiac wisdom instead of Western one. + + Returns + ------- + Infinite wisdom, condensed into astrologically precise prose. + + Notes + ----- + This function was implemented on April 1. Take note of that date. + """ + ... + +def inject_horoscope(): # -> None: + ... + diff --git a/typings/astropy/coordinates/distances.pyi b/typings/astropy/coordinates/distances.pyi new file mode 100644 index 0000000..12c28ed --- /dev/null +++ b/typings/astropy/coordinates/distances.pyi @@ -0,0 +1,144 @@ +""" +This type stub file was generated by pyright. +""" + +from astropy import units as u + +""" +This module contains the classes and utility functions for distance and +cartesian coordinates. +""" +__all__ = ['Distance'] +__doctest_requires__ = ... +class Distance(u.SpecificTypeQuantity): + """ + A one-dimensional distance. + + This can be initialized by providing one of the following: + + * Distance ``value`` (array or float) and a ``unit`` + * |Quantity| object with dimensionality of length + * Redshift and (optionally) a `~astropy.cosmology.Cosmology` + * Distance modulus + * Parallax + + Parameters + ---------- + value : scalar or `~astropy.units.Quantity` ['length'] + The value of this distance. + unit : `~astropy.units.UnitBase` ['length'] + The unit for this distance. + z : float + A redshift for this distance. It will be converted to a distance + by computing the luminosity distance for this redshift given the + cosmology specified by ``cosmology``. Must be given as a keyword + argument. + cosmology : `~astropy.cosmology.Cosmology` or None + A cosmology that will be used to compute the distance from ``z``. + If `None`, the current cosmology will be used (see + `astropy.cosmology` for details). + distmod : float or `~astropy.units.Quantity` + The distance modulus for this distance. Note that if ``unit`` is not + provided, a guess will be made at the unit between AU, pc, kpc, and Mpc. + parallax : `~astropy.units.Quantity` or `~astropy.coordinates.Angle` + The parallax in angular units. + dtype : `~numpy.dtype`, optional + See `~astropy.units.Quantity`. + copy : bool, optional + See `~astropy.units.Quantity`. + order : {'C', 'F', 'A'}, optional + See `~astropy.units.Quantity`. + subok : bool, optional + See `~astropy.units.Quantity`. + ndmin : int, optional + See `~astropy.units.Quantity`. + allow_negative : bool, optional + Whether to allow negative distances (which are possible in some + cosmologies). Default: `False`. + + Raises + ------ + `~astropy.units.UnitsError` + If the ``unit`` is not a length unit. + ValueError + If value specified is less than 0 and ``allow_negative=False``. + + If ``cosmology`` is provided when ``z`` is *not* given. + + If either none or more than one of ``value``, ``z``, ``distmod``, + or ``parallax`` were given. + + + Examples + -------- + >>> from astropy import units as u + >>> from astropy.cosmology import WMAP5 + >>> Distance(10, u.Mpc) + + >>> Distance(40*u.pc, unit=u.kpc) + + >>> Distance(z=0.23) # doctest: +FLOAT_CMP + + >>> Distance(z=0.23, cosmology=WMAP5) # doctest: +FLOAT_CMP + + >>> Distance(distmod=24.47*u.mag) # doctest: +FLOAT_CMP + + >>> Distance(parallax=21.34*u.mas) # doctest: +FLOAT_CMP + + """ + _equivalent_unit = ... + _include_easy_conversion_members = ... + def __new__(cls, value=..., unit=..., z=..., cosmology=..., distmod=..., parallax=..., dtype=..., copy=..., order=..., subok=..., ndmin=..., allow_negative=...): + ... + + @property + def z(self): # -> Any: + """Short for ``self.compute_z()``""" + ... + + def compute_z(self, cosmology=..., **atzkw): # -> Any: + """ + The redshift for this distance assuming its physical distance is + a luminosity distance. + + Parameters + ---------- + cosmology : `~astropy.cosmology.Cosmology` or None + The cosmology to assume for this calculation, or `None` to use the + current cosmology (see `astropy.cosmology` for details). + **atzkw + keyword arguments for :func:`~astropy.cosmology.z_at_value` + + Returns + ------- + z : `~astropy.units.Quantity` + The redshift of this distance given the provided ``cosmology``. + + Warnings + -------- + This method can be slow for large arrays. + The redshift is determined using :func:`astropy.cosmology.z_at_value`, + which handles vector inputs (e.g. an array of distances) by + element-wise calling of :func:`scipy.optimize.minimize_scalar`. + For faster results consider using an interpolation table; + :func:`astropy.cosmology.z_at_value` provides details. + + See Also + -------- + :func:`astropy.cosmology.z_at_value` : Find the redshift corresponding to a + :meth:`astropy.cosmology.FLRW.luminosity_distance`. + """ + ... + + @property + def distmod(self): # -> Quantity: + """The distance modulus as a `~astropy.units.Quantity`""" + ... + + @property + def parallax(self): # -> Angle: + """The parallax angle as an `~astropy.coordinates.Angle` object""" + ... + + + diff --git a/typings/astropy/coordinates/earth.pyi b/typings/astropy/coordinates/earth.pyi new file mode 100644 index 0000000..7ac85bc --- /dev/null +++ b/typings/astropy/coordinates/earth.pyi @@ -0,0 +1,496 @@ +""" +This type stub file was generated by pyright. +""" + +from astropy import units as u +from astropy.units.quantity import QuantityInfoBase +from astropy.utils.decorators import format_doc +from .representation import BaseRepresentation + +__all__ = ['EarthLocation', 'BaseGeodeticRepresentation', 'WGS84GeodeticRepresentation', 'WGS72GeodeticRepresentation', 'GRS80GeodeticRepresentation'] +GeodeticLocation = ... +ELLIPSOIDS = ... +OMEGA_EARTH = ... +class EarthLocationInfo(QuantityInfoBase): + """ + Container for meta information like name, description, format. This is + required when the object is used as a mixin column within a table, but can + be used as a general way to store meta information. + """ + _represent_as_dict_attrs = ... + def new_like(self, cols, length, metadata_conflicts=..., name=...): + """ + Return a new EarthLocation instance which is consistent with the + input ``cols`` and has ``length`` rows. + + This is intended for creating an empty column object whose elements can + be set in-place for table operations like join or vstack. + + Parameters + ---------- + cols : list + List of input columns + length : int + Length of the output column object + metadata_conflicts : str ('warn'|'error'|'silent') + How to handle metadata conflicts + name : str + Output column name + + Returns + ------- + col : EarthLocation (or subclass) + Empty instance of this class consistent with ``cols`` + """ + ... + + + +class EarthLocation(u.Quantity): + """ + Location on the Earth. + + Initialization is first attempted assuming geocentric (x, y, z) coordinates + are given; if that fails, another attempt is made assuming geodetic + coordinates (longitude, latitude, height above a reference ellipsoid). + When using the geodetic forms, Longitudes are measured increasing to the + east, so west longitudes are negative. Internally, the coordinates are + stored as geocentric. + + To ensure a specific type of coordinates is used, use the corresponding + class methods (`from_geocentric` and `from_geodetic`) or initialize the + arguments with names (``x``, ``y``, ``z`` for geocentric; ``lon``, ``lat``, + ``height`` for geodetic). See the class methods for details. + + + Notes + ----- + This class fits into the coordinates transformation framework in that it + encodes a position on the `~astropy.coordinates.ITRS` frame. To get a + proper `~astropy.coordinates.ITRS` object from this object, use the ``itrs`` + property. + """ + _ellipsoid = ... + _location_dtype = ... + _array_dtype = ... + info = ... + def __new__(cls, *args, **kwargs): # -> EarthLocation: + ... + + @classmethod + def from_geocentric(cls, x, y, z, unit=...): + """ + Location on Earth, initialized from geocentric coordinates. + + Parameters + ---------- + x, y, z : `~astropy.units.Quantity` or array-like + Cartesian coordinates. If not quantities, ``unit`` should be given. + unit : unit-like or None + Physical unit of the coordinate values. If ``x``, ``y``, and/or + ``z`` are quantities, they will be converted to this unit. + + Raises + ------ + astropy.units.UnitsError + If the units on ``x``, ``y``, and ``z`` do not match or an invalid + unit is given. + ValueError + If the shapes of ``x``, ``y``, and ``z`` do not match. + TypeError + If ``x`` is not a `~astropy.units.Quantity` and no unit is given. + """ + ... + + @classmethod + def from_geodetic(cls, lon, lat, height=..., ellipsoid=...): + """ + Location on Earth, initialized from geodetic coordinates. + + Parameters + ---------- + lon : `~astropy.coordinates.Longitude` or float + Earth East longitude. Can be anything that initialises an + `~astropy.coordinates.Angle` object (if float, in degrees). + lat : `~astropy.coordinates.Latitude` or float + Earth latitude. Can be anything that initialises an + `~astropy.coordinates.Latitude` object (if float, in degrees). + height : `~astropy.units.Quantity` ['length'] or float, optional + Height above reference ellipsoid (if float, in meters; default: 0). + ellipsoid : str, optional + Name of the reference ellipsoid to use (default: 'WGS84'). + Available ellipsoids are: 'WGS84', 'GRS80', 'WGS72'. + + Raises + ------ + astropy.units.UnitsError + If the units on ``lon`` and ``lat`` are inconsistent with angular + ones, or that on ``height`` with a length. + ValueError + If ``lon``, ``lat``, and ``height`` do not have the same shape, or + if ``ellipsoid`` is not recognized as among the ones implemented. + + Notes + ----- + For the conversion to geocentric coordinates, the ERFA routine + ``gd2gc`` is used. See https://github.com/liberfa/erfa + """ + ... + + @classmethod + def of_site(cls, site_name): # -> Any: + """ + Return an object of this class for a known observatory/site by name. + + This is intended as a quick convenience function to get basic site + information, not a fully-featured exhaustive registry of observatories + and all their properties. + + Additional information about the site is stored in the ``.info.meta`` + dictionary of sites obtained using this method (see the examples below). + + .. note:: + When this function is called, it will attempt to download site + information from the astropy data server. If you would like a site + to be added, issue a pull request to the + `astropy-data repository `_ . + If a site cannot be found in the registry (i.e., an internet + connection is not available), it will fall back on a built-in list, + In the future, this bundled list might include a version-controlled + list of canonical observatories extracted from the online version, + but it currently only contains the Greenwich Royal Observatory as an + example case. + + Parameters + ---------- + site_name : str + Name of the observatory (case-insensitive). + + Returns + ------- + site : `~astropy.coordinates.EarthLocation` (or subclass) instance + The location of the observatory. The returned class will be the same + as this class. + + Examples + -------- + >>> from astropy.coordinates import EarthLocation + >>> keck = EarthLocation.of_site('Keck Observatory') # doctest: +REMOTE_DATA + >>> keck.geodetic # doctest: +REMOTE_DATA +FLOAT_CMP + GeodeticLocation(lon=, lat=, height=) + >>> keck.info # doctest: +REMOTE_DATA + name = W. M. Keck Observatory + dtype = (float64, float64, float64) + unit = m + class = EarthLocation + n_bad = 0 + >>> keck.info.meta # doctest: +REMOTE_DATA + {'source': 'IRAF Observatory Database', 'timezone': 'US/Hawaii'} + + See Also + -------- + get_site_names : the list of sites that this function can access + """ + ... + + @classmethod + def of_address(cls, address, get_height=..., google_api_key=...): + """ + Return an object of this class for a given address by querying either + the OpenStreetMap Nominatim tool [1]_ (default) or the Google geocoding + API [2]_, which requires a specified API key. + + This is intended as a quick convenience function to get easy access to + locations. If you need to specify a precise location, you should use the + initializer directly and pass in a longitude, latitude, and elevation. + + In the background, this just issues a web query to either of + the APIs noted above. This is not meant to be abused! Both + OpenStreetMap and Google use IP-based query limiting and will ban your + IP if you send more than a few thousand queries per hour [2]_. + + .. warning:: + If the query returns more than one location (e.g., searching on + ``address='springfield'``), this function will use the **first** + returned location. + + Parameters + ---------- + address : str + The address to get the location for. As per the Google maps API, + this can be a fully specified street address (e.g., 123 Main St., + New York, NY) or a city name (e.g., Danbury, CT), or etc. + get_height : bool, optional + This only works when using the Google API! See the ``google_api_key`` + block below. Use the retrieved location to perform a second query to + the Google maps elevation API to retrieve the height of the input + address [3]_. + google_api_key : str, optional + A Google API key with the Geocoding API and (optionally) the + elevation API enabled. See [4]_ for more information. + + Returns + ------- + location : `~astropy.coordinates.EarthLocation` (or subclass) instance + The location of the input address. + Will be type(this class) + + References + ---------- + .. [1] https://nominatim.openstreetmap.org/ + .. [2] https://developers.google.com/maps/documentation/geocoding/start + .. [3] https://developers.google.com/maps/documentation/elevation/start + .. [4] https://developers.google.com/maps/documentation/geocoding/get-api-key + + """ + ... + + @classmethod + def get_site_names(cls): # -> list[Unknown] | Any: + """ + Get list of names of observatories for use with + `~astropy.coordinates.EarthLocation.of_site`. + + .. note:: + When this function is called, it will first attempt to + download site information from the astropy data server. If it + cannot (i.e., an internet connection is not available), it will fall + back on the list included with astropy (which is a limited and dated + set of sites). If you think a site should be added, issue a pull + request to the + `astropy-data repository `_ . + + Returns + ------- + names : list of str + List of valid observatory names + + See Also + -------- + of_site : Gets the actual location object for one of the sites names + this returns. + """ + ... + + @property + def ellipsoid(self): # -> str: + """The default ellipsoid used to convert to geodetic coordinates.""" + ... + + @ellipsoid.setter + def ellipsoid(self, ellipsoid): # -> None: + ... + + @property + def geodetic(self): # -> GeodeticLocation: + """Convert to geodetic coordinates for the default ellipsoid.""" + ... + + def to_geodetic(self, ellipsoid=...): # -> GeodeticLocation: + """Convert to geodetic coordinates. + + Parameters + ---------- + ellipsoid : str, optional + Reference ellipsoid to use. Default is the one the coordinates + were initialized with. Available are: 'WGS84', 'GRS80', 'WGS72' + + Returns + ------- + lon, lat, height : `~astropy.units.Quantity` + The tuple is a ``GeodeticLocation`` namedtuple and is comprised of + instances of `~astropy.coordinates.Longitude`, + `~astropy.coordinates.Latitude`, and `~astropy.units.Quantity`. + + Raises + ------ + ValueError + if ``ellipsoid`` is not recognized as among the ones implemented. + + Notes + ----- + For the conversion to geodetic coordinates, the ERFA routine + ``gc2gd`` is used. See https://github.com/liberfa/erfa + """ + ... + + @property + def lon(self): + """Longitude of the location, for the default ellipsoid.""" + ... + + @property + def lat(self): + """Latitude of the location, for the default ellipsoid.""" + ... + + @property + def height(self): + """Height of the location, for the default ellipsoid.""" + ... + + @property + def geocentric(self): # -> tuple[EarthLocation | Any | Unknown | Quantity, EarthLocation | Any | Unknown | Quantity, EarthLocation | Any | Unknown | Quantity]: + """Convert to a tuple with X, Y, and Z as quantities""" + ... + + def to_geocentric(self): # -> tuple[EarthLocation | Any | Unknown | Quantity, EarthLocation | Any | Unknown | Quantity, EarthLocation | Any | Unknown | Quantity]: + """Convert to a tuple with X, Y, and Z as quantities""" + ... + + def get_itrs(self, obstime=...): # -> ITRS: + """ + Generates an `~astropy.coordinates.ITRS` object with the location of + this object at the requested ``obstime``. + + Parameters + ---------- + obstime : `~astropy.time.Time` or None + The ``obstime`` to apply to the new `~astropy.coordinates.ITRS`, or + if None, the default ``obstime`` will be used. + + Returns + ------- + itrs : `~astropy.coordinates.ITRS` + The new object in the ITRS frame + """ + ... + + itrs = ... + def get_gcrs(self, obstime): # -> GCRS: + """GCRS position with velocity at ``obstime`` as a GCRS coordinate. + + Parameters + ---------- + obstime : `~astropy.time.Time` + The ``obstime`` to calculate the GCRS position/velocity at. + + Returns + ------- + gcrs : `~astropy.coordinates.GCRS` instance + With velocity included. + """ + ... + + def get_gcrs_posvel(self, obstime): # -> tuple[CartesianRepresentation, CartesianRepresentation]: + """ + Calculate the GCRS position and velocity of this object at the + requested ``obstime``. + + Parameters + ---------- + obstime : `~astropy.time.Time` + The ``obstime`` to calculate the GCRS position/velocity at. + + Returns + ------- + obsgeoloc : `~astropy.coordinates.CartesianRepresentation` + The GCRS position of the object + obsgeovel : `~astropy.coordinates.CartesianRepresentation` + The GCRS velocity of the object + """ + ... + + def gravitational_redshift(self, obstime, bodies=..., masses=...): # -> int: + """Return the gravitational redshift at this EarthLocation. + + Calculates the gravitational redshift, of order 3 m/s, due to the + requested solar system bodies. + + Parameters + ---------- + obstime : `~astropy.time.Time` + The ``obstime`` to calculate the redshift at. + + bodies : iterable, optional + The bodies (other than the Earth) to include in the redshift + calculation. List elements should be any body name + `get_body_barycentric` accepts. Defaults to Jupiter, the Sun, and + the Moon. Earth is always included (because the class represents + an *Earth* location). + + masses : dict[str, `~astropy.units.Quantity`], optional + The mass or gravitational parameters (G * mass) to assume for the + bodies requested in ``bodies``. Can be used to override the + defaults for the Sun, Jupiter, the Moon, and the Earth, or to + pass in masses for other bodies. + + Returns + ------- + redshift : `~astropy.units.Quantity` + Gravitational redshift in velocity units at given obstime. + """ + ... + + @property + def x(self): # -> EarthLocation | Any | Quantity: + """The X component of the geocentric coordinates.""" + ... + + @property + def y(self): # -> EarthLocation | Any | Quantity: + """The Y component of the geocentric coordinates.""" + ... + + @property + def z(self): # -> EarthLocation | Any | Quantity: + """The Z component of the geocentric coordinates.""" + ... + + def __getitem__(self, item): # -> Self@EarthLocation | Any | Quantity: + ... + + def __array_finalize__(self, obj): # -> None: + ... + + def __len__(self): # -> int: + ... + + + +geodetic_base_doc = ... +@format_doc(geodetic_base_doc) +class BaseGeodeticRepresentation(BaseRepresentation): + """Base geodetic representation.""" + attr_classes = ... + def __init_subclass__(cls, **kwargs): # -> None: + ... + + def __init__(self, lon, lat=..., height=..., copy=...) -> None: + ... + + def to_cartesian(self): # -> CartesianRepresentation: + """ + Converts WGS84 geodetic coordinates to 3D rectangular (geocentric) + cartesian coordinates. + """ + ... + + @classmethod + def from_cartesian(cls, cart): # -> Self@BaseGeodeticRepresentation: + """ + Converts 3D rectangular cartesian coordinates (assumed geocentric) to + WGS84 geodetic coordinates. + """ + ... + + + +@format_doc(geodetic_base_doc) +class WGS84GeodeticRepresentation(BaseGeodeticRepresentation): + """Representation of points in WGS84 3D geodetic coordinates.""" + _ellipsoid = ... + + +@format_doc(geodetic_base_doc) +class WGS72GeodeticRepresentation(BaseGeodeticRepresentation): + """Representation of points in WGS72 3D geodetic coordinates.""" + _ellipsoid = ... + + +@format_doc(geodetic_base_doc) +class GRS80GeodeticRepresentation(BaseGeodeticRepresentation): + """Representation of points in GRS80 3D geodetic coordinates.""" + _ellipsoid = ... + + diff --git a/typings/astropy/coordinates/earth_orientation.pyi b/typings/astropy/coordinates/earth_orientation.pyi new file mode 100644 index 0000000..86773c0 --- /dev/null +++ b/typings/astropy/coordinates/earth_orientation.pyi @@ -0,0 +1,144 @@ +""" +This type stub file was generated by pyright. +""" + +from astropy.time import Time + +""" +This module contains standard functions for earth orientation, such as +precession and nutation. + +This module is (currently) not intended to be part of the public API, but +is instead primarily for internal use in `coordinates` +""" +jd1950 = Time('B1950').jd +jd2000 = Time('J2000').jd +_asecperrad = ... +def eccentricity(jd): # -> NDArray[floating[Any]]: + """ + Eccentricity of the Earth's orbit at the requested Julian Date. + + Parameters + ---------- + jd : scalar or array-like + Julian date at which to compute the eccentricity + + Returns + ------- + eccentricity : scalar or array + The eccentricity (or array of eccentricities) + + References + ---------- + * Explanatory Supplement to the Astronomical Almanac: P. Kenneth + Seidelmann (ed), University Science Books (1992). + """ + ... + +def mean_lon_of_perigee(jd): # -> NDArray[floating[Any]]: + """ + Computes the mean longitude of perigee of the Earth's orbit at the + requested Julian Date. + + Parameters + ---------- + jd : scalar or array-like + Julian date at which to compute the mean longitude of perigee + + Returns + ------- + mean_lon_of_perigee : scalar or array + Mean longitude of perigee in degrees (or array of mean longitudes) + + References + ---------- + * Explanatory Supplement to the Astronomical Almanac: P. Kenneth + Seidelmann (ed), University Science Books (1992). + """ + ... + +def obliquity(jd, algorithm=...): # -> NDArray[floating[Any]]: + """ + Computes the obliquity of the Earth at the requested Julian Date. + + Parameters + ---------- + jd : scalar or array-like + Julian date at which to compute the obliquity + algorithm : int + Year of algorithm based on IAU adoption. Can be 2006, 2000 or 1980. The + 2006 algorithm is mentioned in Circular 179, but the canonical reference + for the IAU adoption is apparently Hilton et al. 06 is composed of the + 1980 algorithm with a precession-rate correction due to the 2000 + precession models, and a description of the 1980 algorithm can be found + in the Explanatory Supplement to the Astronomical Almanac. + + Returns + ------- + obliquity : scalar or array + Mean obliquity in degrees (or array of obliquities) + + References + ---------- + * Hilton, J. et al., 2006, Celest.Mech.Dyn.Astron. 94, 351. 2000 + * USNO Circular 179 + * Explanatory Supplement to the Astronomical Almanac: P. Kenneth + Seidelmann (ed), University Science Books (1992). + """ + ... + +def precession_matrix_Capitaine(fromepoch, toepoch): # -> Any: + """ + Computes the precession matrix from one Julian epoch to another. + The exact method is based on Capitaine et al. 2003, which should + match the IAU 2006 standard. + + Parameters + ---------- + fromepoch : `~astropy.time.Time` + The epoch to precess from. + toepoch : `~astropy.time.Time` + The epoch to precess to. + + Returns + ------- + pmatrix : 3x3 array + Precession matrix to get from ``fromepoch`` to ``toepoch`` + + References + ---------- + USNO Circular 179 + """ + ... + +_nut_data_00b = ... +_nut_data_00b = _load_nutation_data(_nut_data_00b, 'lunisolar') +def nutation_components2000B(jd): # -> tuple[NDArray[Any], Unknown, Unknown]: + """ + Computes nutation components following the IAU 2000B specification + + Parameters + ---------- + jd : scalar + epoch at which to compute the nutation components as a JD + + Returns + ------- + eps : float + epsilon in radians + dpsi : float + dpsi in radians + deps : float + depsilon in raidans + """ + ... + +def nutation_matrix(epoch): # -> Any: + """ + Nutation matrix generated from nutation components. + + Matrix converts from mean coordinate to true coordinate as + r_true = M * r_mean + """ + ... + diff --git a/typings/astropy/coordinates/erfa_astrom.pyi b/typings/astropy/coordinates/erfa_astrom.pyi new file mode 100644 index 0000000..2f98a49 --- /dev/null +++ b/typings/astropy/coordinates/erfa_astrom.pyi @@ -0,0 +1,148 @@ +""" +This type stub file was generated by pyright. +""" + +import astropy.units as u +from astropy.utils.state import ScienceState + +""" +This module contains a helper function to fill erfa.astrom struct and a +ScienceState, which allows to speed up coordinate transformations at the +expense of accuracy. +""" +__all__ = [] +class ErfaAstrom: + ''' + The default provider for astrometry values. + A utility class to extract the necessary arguments for + erfa functions from frame attributes, call the corresponding + erfa functions and return the astrom object. + ''' + @staticmethod + def apco(frame_or_coord): + ''' + Wrapper for ``erfa.apco``, used in conversions AltAz <-> ICRS and CIRS <-> ICRS + + Parameters + ---------- + frame_or_coord : ``astropy.coordinates.BaseCoordinateFrame`` or ``astropy.coordinates.SkyCoord`` + Frame or coordinate instance in the corresponding frame + for which to calculate the calculate the astrom values. + For this function, an AltAz or CIRS frame is expected. + ''' + ... + + @staticmethod + def apcs(frame_or_coord): + ''' + Wrapper for ``erfa.apcs``, used in conversions GCRS <-> ICRS + + Parameters + ---------- + frame_or_coord : ``astropy.coordinates.BaseCoordinateFrame`` or ``astropy.coordinates.SkyCoord`` + Frame or coordinate instance in the corresponding frame + for which to calculate the calculate the astrom values. + For this function, a GCRS frame is expected. + ''' + ... + + @staticmethod + def apio(frame_or_coord): # -> NDArray[float64]: + ''' + Slightly modified equivalent of ``erfa.apio``, used in conversions AltAz <-> CIRS. + + Since we use a topocentric CIRS frame, we have dropped the steps needed to calculate + diurnal aberration. + + Parameters + ---------- + frame_or_coord : ``astropy.coordinates.BaseCoordinateFrame`` or ``astropy.coordinates.SkyCoord`` + Frame or coordinate instance in the corresponding frame + for which to calculate the calculate the astrom values. + For this function, an AltAz frame is expected. + ''' + ... + + + +class ErfaAstromInterpolator(ErfaAstrom): + ''' + A provider for astrometry values that does not call erfa + for each individual timestamp but interpolates linearly + between support points. + + For the interpolation, float64 MJD values are used, so time precision + for the interpolation will be around a microsecond. + + This can dramatically speed up coordinate transformations, + e.g. between CIRS and ICRS, + when obstime is an array of many values (factors of 10 to > 100 depending + on the selected resolution, number of points and the time range of the values). + + The precision of the transformation will still be in the order of microseconds + for reasonable values of time_resolution, e.g. ``300 * u.s``. + + Users should benchmark performance and accuracy with the default transformation + for their specific use case and then choose a suitable ``time_resolution`` + from there. + + This class is intended be used together with the ``erfa_astrom`` science state, + e.g. in a context manager like this + + Example + ------- + >>> from astropy.coordinates import SkyCoord, CIRS + >>> from astropy.coordinates.erfa_astrom import erfa_astrom, ErfaAstromInterpolator + >>> import astropy.units as u + >>> from astropy.time import Time + >>> import numpy as np + + >>> obstime = Time('2010-01-01T20:00:00') + np.linspace(0, 4, 1000) * u.hour + >>> crab = SkyCoord(ra='05h34m31.94s', dec='22d00m52.2s') + >>> with erfa_astrom.set(ErfaAstromInterpolator(300 * u.s)): + ... cirs = crab.transform_to(CIRS(obstime=obstime)) + ''' + @u.quantity_input(time_resolution=u.day) + def __init__(self, time_resolution) -> None: + ... + + def apco(self, frame_or_coord): + ''' + Wrapper for ``erfa.apco``, used in conversions AltAz <-> ICRS and CIRS <-> ICRS + + Parameters + ---------- + frame_or_coord : ``astropy.coordinates.BaseCoordinateFrame`` or ``astropy.coordinates.SkyCoord`` + Frame or coordinate instance in the corresponding frame + for which to calculate the calculate the astrom values. + For this function, an AltAz or CIRS frame is expected. + ''' + ... + + def apcs(self, frame_or_coord): + ''' + Wrapper for ``erfa.apci``, used in conversions GCRS <-> ICRS + + Parameters + ---------- + frame_or_coord : ``astropy.coordinates.BaseCoordinateFrame`` or ``astropy.coordinates.SkyCoord`` + Frame or coordinate instance in the corresponding frame + for which to calculate the calculate the astrom values. + For this function, a GCRS frame is expected. + ''' + ... + + + +class erfa_astrom(ScienceState): + """ + ScienceState to select with astrom provider is used in + coordinate transformations. + """ + _value = ... + @classmethod + def validate(cls, value): # -> ErfaAstrom: + ... + + + diff --git a/typings/astropy/coordinates/errors.pyi b/typings/astropy/coordinates/errors.pyi new file mode 100644 index 0000000..6dde089 --- /dev/null +++ b/typings/astropy/coordinates/errors.pyi @@ -0,0 +1,164 @@ +""" +This type stub file was generated by pyright. +""" + +from astropy.utils.exceptions import AstropyWarning + +''' This module defines custom errors and exceptions used in astropy.coordinates. +''' +__all__ = ['RangeError', 'BoundsError', 'IllegalHourError', 'IllegalMinuteError', 'IllegalSecondError', 'ConvertError', 'IllegalHourWarning', 'IllegalMinuteWarning', 'IllegalSecondWarning', 'UnknownSiteException'] +class RangeError(ValueError): + """ + Raised when some part of an angle is out of its valid range. + """ + ... + + +class BoundsError(RangeError): + """ + Raised when an angle is outside of its user-specified bounds. + """ + ... + + +class IllegalHourError(RangeError): + """ + Raised when an hour value is not in the range [0,24). + + Parameters + ---------- + hour : int, float + + Examples + -------- + + .. code-block:: python + + if not 0 <= hr < 24: + raise IllegalHourError(hour) + """ + def __init__(self, hour) -> None: + ... + + def __str__(self) -> str: + ... + + + +class IllegalHourWarning(AstropyWarning): + """ + Raised when an hour value is 24. + + Parameters + ---------- + hour : int, float + """ + def __init__(self, hour, alternativeactionstr=...) -> None: + ... + + def __str__(self) -> str: + ... + + + +class IllegalMinuteError(RangeError): + """ + Raised when an minute value is not in the range [0,60]. + + Parameters + ---------- + minute : int, float + + Examples + -------- + + .. code-block:: python + + if not 0 <= min < 60: + raise IllegalMinuteError(minute) + + """ + def __init__(self, minute) -> None: + ... + + def __str__(self) -> str: + ... + + + +class IllegalMinuteWarning(AstropyWarning): + """ + Raised when a minute value is 60. + + Parameters + ---------- + minute : int, float + """ + def __init__(self, minute, alternativeactionstr=...) -> None: + ... + + def __str__(self) -> str: + ... + + + +class IllegalSecondError(RangeError): + """ + Raised when an second value (time) is not in the range [0,60]. + + Parameters + ---------- + second : int, float + + Examples + -------- + + .. code-block:: python + + if not 0 <= sec < 60: + raise IllegalSecondError(second) + """ + def __init__(self, second) -> None: + ... + + def __str__(self) -> str: + ... + + + +class IllegalSecondWarning(AstropyWarning): + """ + Raised when a second value is 60. + + Parameters + ---------- + second : int, float + """ + def __init__(self, second, alternativeactionstr=...) -> None: + ... + + def __str__(self) -> str: + ... + + + +class UnitsError(ValueError): + """ + Raised if units are missing or invalid. + """ + ... + + +class ConvertError(Exception): + """ + Raised if a coordinate system cannot be converted to another + """ + ... + + +class UnknownSiteException(KeyError): + def __init__(self, site, attribute, close_names=...) -> None: + ... + + + diff --git a/typings/astropy/coordinates/funcs.pyi b/typings/astropy/coordinates/funcs.pyi new file mode 100644 index 0000000..e8ba84a --- /dev/null +++ b/typings/astropy/coordinates/funcs.pyi @@ -0,0 +1,190 @@ +""" +This type stub file was generated by pyright. +""" + +""" +This module contains convenience functions for coordinate-related functionality. + +This is generally just wrapping around the object-oriented coordinates +framework, but it is useful for some users who are used to more functional +interfaces. +""" +__all__ = ['cartesian_to_spherical', 'spherical_to_cartesian', 'get_sun', 'get_constellation', 'concatenate_representations', 'concatenate'] +def cartesian_to_spherical(x, y, z): # -> tuple[Unknown | Distance, Unknown, Unknown]: + """ + Converts 3D rectangular cartesian coordinates to spherical polar + coordinates. + + Note that the resulting angles are latitude/longitude or + elevation/azimuthal form. I.e., the origin is along the equator + rather than at the north pole. + + .. note:: + This function simply wraps functionality provided by the + `~astropy.coordinates.CartesianRepresentation` and + `~astropy.coordinates.SphericalRepresentation` classes. In general, + for both performance and readability, we suggest using these classes + directly. But for situations where a quick one-off conversion makes + sense, this function is provided. + + Parameters + ---------- + x : scalar, array-like, or `~astropy.units.Quantity` + The first Cartesian coordinate. + y : scalar, array-like, or `~astropy.units.Quantity` + The second Cartesian coordinate. + z : scalar, array-like, or `~astropy.units.Quantity` + The third Cartesian coordinate. + + Returns + ------- + r : `~astropy.units.Quantity` + The radial coordinate (in the same units as the inputs). + lat : `~astropy.units.Quantity` ['angle'] + The latitude in radians + lon : `~astropy.units.Quantity` ['angle'] + The longitude in radians + """ + ... + +def spherical_to_cartesian(r, lat, lon): # -> tuple[Unknown, Unknown, Unknown]: + """ + Converts spherical polar coordinates to rectangular cartesian + coordinates. + + Note that the input angles should be in latitude/longitude or + elevation/azimuthal form. I.e., the origin is along the equator + rather than at the north pole. + + .. note:: + This is a low-level function used internally in + `astropy.coordinates`. It is provided for users if they really + want to use it, but it is recommended that you use the + `astropy.coordinates` coordinate systems. + + Parameters + ---------- + r : scalar, array-like, or `~astropy.units.Quantity` + The radial coordinate (in the same units as the inputs). + lat : scalar, array-like, or `~astropy.units.Quantity` ['angle'] + The latitude (in radians if array or scalar) + lon : scalar, array-like, or `~astropy.units.Quantity` ['angle'] + The longitude (in radians if array or scalar) + + Returns + ------- + x : float or array + The first cartesian coordinate. + y : float or array + The second cartesian coordinate. + z : float or array + The third cartesian coordinate. + + """ + ... + +def get_sun(time): # -> SkyCoord: + """ + Determines the location of the sun at a given time (or times, if the input + is an array `~astropy.time.Time` object), in geocentric coordinates. + + Parameters + ---------- + time : `~astropy.time.Time` + The time(s) at which to compute the location of the sun. + + Returns + ------- + newsc : `~astropy.coordinates.SkyCoord` + The location of the sun as a `~astropy.coordinates.SkyCoord` in the + `~astropy.coordinates.GCRS` frame. + + Notes + ----- + The algorithm for determining the sun/earth relative position is based + on the simplified version of VSOP2000 that is part of ERFA. Compared to + JPL's ephemeris, it should be good to about 4 km (in the Sun-Earth + vector) from 1900-2100 C.E., 8 km for the 1800-2200 span, and perhaps + 250 km over the 1000-3000. + + """ + ... + +_constellation_data = ... +def get_constellation(coord, short_name=..., constellation_list=...): # -> Any: + """ + Determines the constellation(s) a given coordinate object contains. + + Parameters + ---------- + coord : coordinate-like + The object to determine the constellation of. + short_name : bool + If True, the returned names are the IAU-sanctioned abbreviated + names. Otherwise, full names for the constellations are used. + constellation_list : str + The set of constellations to use. Currently only ``'iau'`` is + supported, meaning the 88 "modern" constellations endorsed by the IAU. + + Returns + ------- + constellation : str or string array + If ``coords`` contains a scalar coordinate, returns the name of the + constellation. If it is an array coordinate object, it returns an array + of names. + + Notes + ----- + To determine which constellation a point on the sky is in, this precesses + to B1875, and then uses the Delporte boundaries of the 88 modern + constellations, as tabulated by + `Roman 1987 `_. + """ + ... + +def concatenate_representations(reps): # -> Any: + """ + Combine multiple representation objects into a single instance by + concatenating the data in each component. + + Currently, all of the input representations have to be the same type. This + properly handles differential or velocity data, but all input objects must + have the same differential object type as well. + + Parameters + ---------- + reps : sequence of `~astropy.coordinates.BaseRepresentation` + The objects to concatenate + + Returns + ------- + rep : `~astropy.coordinates.BaseRepresentation` subclass instance + A single representation object with its data set to the concatenation of + all the elements of the input sequence of representations. + + """ + ... + +def concatenate(coords): # -> SkyCoord: + """ + Combine multiple coordinate objects into a single + `~astropy.coordinates.SkyCoord`. + + "Coordinate objects" here mean frame objects with data, + `~astropy.coordinates.SkyCoord`, or representation objects. Currently, + they must all be in the same frame, but in a future version this may be + relaxed to allow inhomogeneous sequences of objects. + + Parameters + ---------- + coords : sequence of coordinate-like + The objects to concatenate + + Returns + ------- + cskycoord : SkyCoord + A single sky coordinate with its data set to the concatenation of all + the elements in ``coords`` + """ + ... + diff --git a/typings/astropy/coordinates/jparser.pyi b/typings/astropy/coordinates/jparser.pyi new file mode 100644 index 0000000..4accea9 --- /dev/null +++ b/typings/astropy/coordinates/jparser.pyi @@ -0,0 +1,39 @@ +""" +This type stub file was generated by pyright. +""" + +""" +Module for parsing astronomical object names to extract embedded coordinates +eg: '2MASS J06495091-0737408' +""" +RA_REGEX = ... +DEC_REGEX = ... +JCOORD_REGEX = ... +JPARSER = ... +def search(name, raise_=...): # -> Match[str] | None: + """Regex match for coordinates in name""" + ... + +def to_ra_dec_angles(name): # -> tuple[Unknown, Unknown]: + """get RA in hourangle and DEC in degrees by parsing name """ + ... + +def to_skycoord(name, frame=...): # -> SkyCoord: + """Convert to `name` to `SkyCoords` object""" + ... + +def shorten(name): # -> str: + """ + Produce a shortened version of the full object name using: the prefix + (usually the survey name) and RA (hour, minute), DEC (deg, arcmin) parts. + e.g.: '2MASS J06495091-0737408' --> '2MASS J0649-0737' + Parameters + ---------- + name : str + Full object name with J-coords embedded. + Returns + ------- + shortName: str + """ + ... + diff --git a/typings/astropy/coordinates/matching.pyi b/typings/astropy/coordinates/matching.pyi new file mode 100644 index 0000000..183ee5c --- /dev/null +++ b/typings/astropy/coordinates/matching.pyi @@ -0,0 +1,217 @@ +""" +This type stub file was generated by pyright. +""" + +""" +This module contains functions for matching coordinate catalogs. +""" +__all__ = ['match_coordinates_3d', 'match_coordinates_sky', 'search_around_3d', 'search_around_sky'] +def match_coordinates_3d(matchcoord, catalogcoord, nthneighbor=..., storekdtree=...): # -> tuple[Unknown, Unknown, Unknown]: + """ + Finds the nearest 3-dimensional matches of a coordinate or coordinates in + a set of catalog coordinates. + + This finds the 3-dimensional closest neighbor, which is only different + from the on-sky distance if ``distance`` is set in either ``matchcoord`` + or ``catalogcoord``. + + Parameters + ---------- + matchcoord : `~astropy.coordinates.BaseCoordinateFrame` or `~astropy.coordinates.SkyCoord` + The coordinate(s) to match to the catalog. + catalogcoord : `~astropy.coordinates.BaseCoordinateFrame` or `~astropy.coordinates.SkyCoord` + The base catalog in which to search for matches. Typically this will + be a coordinate object that is an array (i.e., + ``catalogcoord.isscalar == False``) + nthneighbor : int, optional + Which closest neighbor to search for. Typically ``1`` is desired here, + as that is correct for matching one set of coordinates to another. + The next likely use case is ``2``, for matching a coordinate catalog + against *itself* (``1`` is inappropriate because each point will find + itself as the closest match). + storekdtree : bool or str, optional + If a string, will store the KD-Tree used for the computation + in the ``catalogcoord``, as in ``catalogcoord.cache`` with the + provided name. This dramatically speeds up subsequent calls with the + same catalog. If False, the KD-Tree is discarded after use. + + Returns + ------- + idx : int array + Indices into ``catalogcoord`` to get the matched points for each + ``matchcoord``. Shape matches ``matchcoord``. + sep2d : `~astropy.coordinates.Angle` + The on-sky separation between the closest match for each ``matchcoord`` + and the ``matchcoord``. Shape matches ``matchcoord``. + dist3d : `~astropy.units.Quantity` ['length'] + The 3D distance between the closest match for each ``matchcoord`` and + the ``matchcoord``. Shape matches ``matchcoord``. + + Notes + ----- + This function requires `SciPy `_ to be installed + or it will fail. + """ + ... + +def match_coordinates_sky(matchcoord, catalogcoord, nthneighbor=..., storekdtree=...): # -> tuple[Unknown, Unknown, Unknown]: + """ + Finds the nearest on-sky matches of a coordinate or coordinates in + a set of catalog coordinates. + + This finds the on-sky closest neighbor, which is only different from the + 3-dimensional match if ``distance`` is set in either ``matchcoord`` + or ``catalogcoord``. + + Parameters + ---------- + matchcoord : `~astropy.coordinates.BaseCoordinateFrame` or `~astropy.coordinates.SkyCoord` + The coordinate(s) to match to the catalog. + catalogcoord : `~astropy.coordinates.BaseCoordinateFrame` or `~astropy.coordinates.SkyCoord` + The base catalog in which to search for matches. Typically this will + be a coordinate object that is an array (i.e., + ``catalogcoord.isscalar == False``) + nthneighbor : int, optional + Which closest neighbor to search for. Typically ``1`` is desired here, + as that is correct for matching one set of coordinates to another. + The next likely use case is ``2``, for matching a coordinate catalog + against *itself* (``1`` is inappropriate because each point will find + itself as the closest match). + storekdtree : bool or str, optional + If a string, will store the KD-Tree used for the computation + in the ``catalogcoord`` in ``catalogcoord.cache`` with the + provided name. This dramatically speeds up subsequent calls with the + same catalog. If False, the KD-Tree is discarded after use. + + Returns + ------- + idx : int array + Indices into ``catalogcoord`` to get the matched points for each + ``matchcoord``. Shape matches ``matchcoord``. + sep2d : `~astropy.coordinates.Angle` + The on-sky separation between the closest match for each + ``matchcoord`` and the ``matchcoord``. Shape matches ``matchcoord``. + dist3d : `~astropy.units.Quantity` ['length'] + The 3D distance between the closest match for each ``matchcoord`` and + the ``matchcoord``. Shape matches ``matchcoord``. If either + ``matchcoord`` or ``catalogcoord`` don't have a distance, this is the 3D + distance on the unit sphere, rather than a true distance. + + Notes + ----- + This function requires `SciPy `_ to be installed + or it will fail. + """ + ... + +def search_around_3d(coords1, coords2, distlimit, storekdtree=...): # -> tuple[NDArray[Any], NDArray[Any], Angle, Quantity] | tuple[NDArray[Any], NDArray[Any], Angle | Unknown, Quantity | Unknown]: + """ + Searches for pairs of points that are at least as close as a specified + distance in 3D space. + + This is intended for use on coordinate objects with arrays of coordinates, + not scalars. For scalar coordinates, it is better to use the + ``separation_3d`` methods. + + Parameters + ---------- + coords1 : `~astropy.coordinates.BaseCoordinateFrame` or `~astropy.coordinates.SkyCoord` + The first set of coordinates, which will be searched for matches from + ``coords2`` within ``seplimit``. Cannot be a scalar coordinate. + coords2 : `~astropy.coordinates.BaseCoordinateFrame` or `~astropy.coordinates.SkyCoord` + The second set of coordinates, which will be searched for matches from + ``coords1`` within ``seplimit``. Cannot be a scalar coordinate. + distlimit : `~astropy.units.Quantity` ['length'] + The physical radius to search within. + storekdtree : bool or str, optional + If a string, will store the KD-Tree used in the search with the name + ``storekdtree`` in ``coords2.cache``. This speeds up subsequent calls + to this function. If False, the KD-Trees are not saved. + + Returns + ------- + idx1 : int array + Indices into ``coords1`` that matches to the corresponding element of + ``idx2``. Shape matches ``idx2``. + idx2 : int array + Indices into ``coords2`` that matches to the corresponding element of + ``idx1``. Shape matches ``idx1``. + sep2d : `~astropy.coordinates.Angle` + The on-sky separation between the coordinates. Shape matches ``idx1`` + and ``idx2``. + dist3d : `~astropy.units.Quantity` ['length'] + The 3D distance between the coordinates. Shape matches ``idx1`` and + ``idx2``. The unit is that of ``coords1``. + + Notes + ----- + This function requires `SciPy `_ + to be installed or it will fail. + + If you are using this function to search in a catalog for matches around + specific points, the convention is for ``coords2`` to be the catalog, and + ``coords1`` are the points to search around. While these operations are + mathematically the same if ``coords1`` and ``coords2`` are flipped, some of + the optimizations may work better if this convention is obeyed. + + In the current implementation, the return values are always sorted in the + same order as the ``coords1`` (so ``idx1`` is in ascending order). This is + considered an implementation detail, though, so it could change in a future + release. + """ + ... + +def search_around_sky(coords1, coords2, seplimit, storekdtree=...): # -> tuple[NDArray[Any], NDArray[Any], Angle, Quantity] | tuple[NDArray[Any], NDArray[Any], Angle | Unknown, Quantity | Unknown | Any]: + """ + Searches for pairs of points that have an angular separation at least as + close as a specified angle. + + This is intended for use on coordinate objects with arrays of coordinates, + not scalars. For scalar coordinates, it is better to use the ``separation`` + methods. + + Parameters + ---------- + coords1 : coordinate-like + The first set of coordinates, which will be searched for matches from + ``coords2`` within ``seplimit``. Cannot be a scalar coordinate. + coords2 : coordinate-like + The second set of coordinates, which will be searched for matches from + ``coords1`` within ``seplimit``. Cannot be a scalar coordinate. + seplimit : `~astropy.units.Quantity` ['angle'] + The on-sky separation to search within. + storekdtree : bool or str, optional + If a string, will store the KD-Tree used in the search with the name + ``storekdtree`` in ``coords2.cache``. This speeds up subsequent calls + to this function. If False, the KD-Trees are not saved. + + Returns + ------- + idx1 : int array + Indices into ``coords1`` that matches to the corresponding element of + ``idx2``. Shape matches ``idx2``. + idx2 : int array + Indices into ``coords2`` that matches to the corresponding element of + ``idx1``. Shape matches ``idx1``. + sep2d : `~astropy.coordinates.Angle` + The on-sky separation between the coordinates. Shape matches ``idx1`` + and ``idx2``. + dist3d : `~astropy.units.Quantity` ['length'] + The 3D distance between the coordinates. Shape matches ``idx1`` + and ``idx2``; the unit is that of ``coords1``. + If either ``coords1`` or ``coords2`` don't have a distance, + this is the 3D distance on the unit sphere, rather than a + physical distance. + + Notes + ----- + This function requires `SciPy `_ + to be installed or it will fail. + + In the current implementation, the return values are always sorted in the + same order as the ``coords1`` (so ``idx1`` is in ascending order). This is + considered an implementation detail, though, so it could change in a future + release. + """ + ... + diff --git a/typings/astropy/coordinates/matrix_utilities.pyi b/typings/astropy/coordinates/matrix_utilities.pyi new file mode 100644 index 0000000..8307415 --- /dev/null +++ b/typings/astropy/coordinates/matrix_utilities.pyi @@ -0,0 +1,132 @@ +""" +This type stub file was generated by pyright. +""" + +""" +Utililies used for constructing and inspecting rotation matrices. +""" +def matrix_product(*matrices): # -> Any: + """Matrix multiply all arguments together. + + Arguments should have dimension 2 or larger. Larger dimensional objects + are interpreted as stacks of matrices residing in the last two dimensions. + + This function mostly exists for readability: using `~numpy.matmul` + directly, one would have ``matmul(matmul(m1, m2), m3)``, etc. For even + better readability, one might consider using `~numpy.matrix` for the + arguments (so that one could write ``m1 * m2 * m3``), but then it is not + possible to handle stacks of matrices. Once only python >=3.5 is supported, + this function can be replaced by ``m1 @ m2 @ m3``. + """ + ... + +def matrix_transpose(matrix): + """Transpose a matrix or stack of matrices by swapping the last two axes. + + This function mostly exists for readability; seeing ``.swapaxes(-2, -1)`` + it is not that obvious that one does a transpose. Note that one cannot + use `~numpy.ndarray.T`, as this transposes all axes and thus does not + work for stacks of matrices. + """ + ... + +def rotation_matrix(angle, axis=..., unit=...): # -> NDArray[float64] | Any: + """ + Generate matrices for rotation by some angle around some axis. + + Parameters + ---------- + angle : angle-like + The amount of rotation the matrices should represent. Can be an array. + axis : str or array-like + Either ``'x'``, ``'y'``, ``'z'``, or a (x,y,z) specifying the axis to + rotate about. If ``'x'``, ``'y'``, or ``'z'``, the rotation sense is + counterclockwise looking down the + axis (e.g. positive rotations obey + left-hand-rule). If given as an array, the last dimension should be 3; + it will be broadcast against ``angle``. + unit : unit-like, optional + If ``angle`` does not have associated units, they are in this + unit. If neither are provided, it is assumed to be degrees. + + Returns + ------- + rmat : `numpy.matrix` + A unitary rotation matrix. + """ + ... + +def angle_axis(matrix): # -> tuple[Angle, Any]: + """ + Angle of rotation and rotation axis for a given rotation matrix. + + Parameters + ---------- + matrix : array-like + A 3 x 3 unitary rotation matrix (or stack of matrices). + + Returns + ------- + angle : `~astropy.coordinates.Angle` + The angle of rotation. + axis : array + The (normalized) axis of rotation (with last dimension 3). + """ + ... + +def is_O3(matrix): # -> Any: + """Check whether a matrix is in the length-preserving group O(3). + + Parameters + ---------- + matrix : (..., N, N) array-like + Must have attribute ``.shape`` and method ``.swapaxes()`` and not error + when using `~numpy.isclose`. + + Returns + ------- + is_o3 : bool or array of bool + If the matrix has more than two axes, the O(3) check is performed on + slices along the last two axes -- (M, N, N) => (M, ) bool array. + + Notes + ----- + The orthogonal group O(3) preserves lengths, but is not guaranteed to keep + orientations. Rotations and reflections are in this group. + For more information, see https://en.wikipedia.org/wiki/Orthogonal_group + """ + ... + +def is_rotation(matrix, allow_improper=...): # -> Any: + """Check whether a matrix is a rotation, proper or improper. + + Parameters + ---------- + matrix : (..., N, N) array-like + Must have attribute ``.shape`` and method ``.swapaxes()`` and not error + when using `~numpy.isclose` and `~numpy.linalg.det`. + allow_improper : bool, optional + Whether to restrict check to the SO(3), the group of proper rotations, + or also allow improper rotations (with determinant -1). + The default (False) is only SO(3). + + Returns + ------- + isrot : bool or array of bool + If the matrix has more than two axes, the checks are performed on + slices along the last two axes -- (M, N, N) => (M, ) bool array. + + See Also + -------- + astopy.coordinates.matrix_utilities.is_O3 : + For the less restrictive check that a matrix is in the group O(3). + + Notes + ----- + The group SO(3) is the rotation group. It is O(3), with determinant 1. + Rotations with determinant -1 are improper rotations, combining both a + rotation and a reflection. + For more information, see https://en.wikipedia.org/wiki/Orthogonal_group + + """ + ... + diff --git a/typings/astropy/coordinates/name_resolve.pyi b/typings/astropy/coordinates/name_resolve.pyi new file mode 100644 index 0000000..d19a852 --- /dev/null +++ b/typings/astropy/coordinates/name_resolve.pyi @@ -0,0 +1,84 @@ +""" +This type stub file was generated by pyright. +""" + +from astropy.utils.state import ScienceState + +""" +This module contains convenience functions for getting a coordinate object +for a named object by querying SESAME and getting the first returned result. +Note that this is intended to be a convenience, and is very simple. If you +need precise coordinates for an object you should find the appropriate +reference for that measurement and input the coordinates manually. +""" +__all__ = ["get_icrs_coordinates"] +class sesame_url(ScienceState): + """ + The URL(s) to Sesame's web-queryable database. + """ + _value = ... + @classmethod + def validate(cls, value): + ... + + + +class sesame_database(ScienceState): + """ + This specifies the default database that SESAME will query when + using the name resolve mechanism in the coordinates + subpackage. Default is to search all databases, but this can be + 'all', 'simbad', 'ned', or 'vizier'. + """ + _value = ... + @classmethod + def validate(cls, value): + ... + + + +class NameResolveError(Exception): + ... + + +def get_icrs_coordinates(name, parse=..., cache=...): # -> SkyCoord: + """ + Retrieve an ICRS object by using an online name resolving service to + retrieve coordinates for the specified name. By default, this will + search all available databases until a match is found. If you would like + to specify the database, use the science state + ``astropy.coordinates.name_resolve.sesame_database``. You can also + specify a list of servers to use for querying Sesame using the science + state ``astropy.coordinates.name_resolve.sesame_url``. This will try + each one in order until a valid response is returned. By default, this + list includes the main Sesame host and a mirror at vizier. The + configuration item `astropy.utils.data.Conf.remote_timeout` controls the + number of seconds to wait for a response from the server before giving + up. + + Parameters + ---------- + name : str + The name of the object to get coordinates for, e.g. ``'M42'``. + parse : bool + Whether to attempt extracting the coordinates from the name by + parsing with a regex. For objects catalog names that have + J-coordinates embedded in their names eg: + 'CRTS SSS100805 J194428-420209', this may be much faster than a + sesame query for the same object name. The coordinates extracted + in this way may differ from the database coordinates by a few + deci-arcseconds, so only use this option if you do not need + sub-arcsecond accuracy for coordinates. + cache : bool, str, optional + Determines whether to cache the results or not. Passed through to + `~astropy.utils.data.download_file`, so pass "update" to update the + cached value. + + Returns + ------- + coord : `astropy.coordinates.ICRS` object + The object's coordinates in the ICRS frame. + + """ + ... + diff --git a/typings/astropy/coordinates/representation.pyi b/typings/astropy/coordinates/representation.pyi new file mode 100644 index 0000000..71a8572 --- /dev/null +++ b/typings/astropy/coordinates/representation.pyi @@ -0,0 +1,1697 @@ +""" +This type stub file was generated by pyright. +""" + +import abc +from astropy.utils import ShapedLikeNDArray +from astropy.utils.data_info import MixinInfo + +""" +In this module, we define the coordinate representation classes, which are +used to represent low-level cartesian, spherical, cylindrical, and other +coordinates. +""" +__all__ = ["BaseRepresentationOrDifferential", "BaseRepresentation", "CartesianRepresentation", "SphericalRepresentation", "UnitSphericalRepresentation", "RadialRepresentation", "PhysicsSphericalRepresentation", "CylindricalRepresentation", "BaseDifferential", "CartesianDifferential", "BaseSphericalDifferential", "BaseSphericalCosLatDifferential", "SphericalDifferential", "SphericalCosLatDifferential", "UnitSphericalDifferential", "UnitSphericalCosLatDifferential", "RadialDifferential", "CylindricalDifferential", "PhysicsSphericalDifferential"] +REPRESENTATION_CLASSES = ... +DIFFERENTIAL_CLASSES = ... +DUPLICATE_REPRESENTATIONS = ... +_REPRDIFF_HASH = ... +def get_reprdiff_cls_hash(): # -> int: + """ + Returns a hash value that should be invariable if the + `REPRESENTATION_CLASSES` and `DIFFERENTIAL_CLASSES` dictionaries have not + changed. + """ + ... + +class BaseRepresentationOrDifferentialInfo(MixinInfo): + """ + Container for meta information like name, description, format. This is + required when the object is used as a mixin column within a table, but can + be used as a general way to store meta information. + """ + attrs_from_parent = ... + _supports_indexing = ... + @staticmethod + def default_format(val): # -> str: + ... + + @property + def unit(self): # -> None: + ... + + def new_like(self, reps, length, metadata_conflicts=..., name=...): + """ + Return a new instance like ``reps`` with ``length`` rows. + + This is intended for creating an empty column object whose elements can + be set in-place for table operations like join or vstack. + + Parameters + ---------- + reps : list + List of input representations or differentials. + length : int + Length of the output column object + metadata_conflicts : str ('warn'|'error'|'silent') + How to handle metadata conflicts + name : str + Output column name + + Returns + ------- + col : `BaseRepresentation` or `BaseDifferential` subclass instance + Empty instance of this class consistent with ``cols`` + + """ + ... + + + +class BaseRepresentationOrDifferential(ShapedLikeNDArray): + """3D coordinate representations and differentials. + + Parameters + ---------- + comp1, comp2, comp3 : `~astropy.units.Quantity` or subclass + The components of the 3D point or differential. The names are the + keys and the subclasses the values of the ``attr_classes`` attribute. + copy : bool, optional + If `True` (default), arrays will be copied; if `False`, they will be + broadcast together but not use new memory. + """ + __array_priority__ = ... + info = ... + def __init__(self, *args, **kwargs) -> None: + ... + + @classmethod + def get_name(cls): # -> str: + """Name of the representation or differential. + + In lower case, with any trailing 'representation' or 'differential' + removed. (E.g., 'spherical' for + `~astropy.coordinates.SphericalRepresentation` or + `~astropy.coordinates.SphericalDifferential`.) + """ + ... + + @classmethod + @abc.abstractmethod + def from_cartesian(cls, other): + """Create a representation of this class from a supplied Cartesian one. + + Parameters + ---------- + other : `CartesianRepresentation` + The representation to turn into this class + + Returns + ------- + representation : `BaseRepresentation` subclass instance + A new representation of this class's type. + """ + ... + + @abc.abstractmethod + def to_cartesian(self): + """Convert the representation to its Cartesian form. + + Note that any differentials get dropped. + Also note that orientation information at the origin is *not* preserved by + conversions through Cartesian coordinates. For example, transforming + an angular position defined at distance=0 through cartesian coordinates + and back will lose the original angular coordinates:: + + >>> import astropy.units as u + >>> import astropy.coordinates as coord + >>> rep = coord.SphericalRepresentation( + ... lon=15*u.deg, + ... lat=-11*u.deg, + ... distance=0*u.pc) + >>> rep.to_cartesian().represent_as(coord.SphericalRepresentation) + + + Returns + ------- + cartrepr : `CartesianRepresentation` + The representation in Cartesian form. + """ + ... + + @property + def components(self): # -> tuple[Unknown, ...]: + """A tuple with the in-order names of the coordinate components.""" + ... + + def __eq__(self, value) -> bool: + """Equality operator + + This implements strict equality and requires that the representation + classes are identical and that the representation data are exactly equal. + """ + ... + + def __ne__(self, value) -> bool: + ... + + def __setitem__(self, item, value): # -> None: + ... + + @property + def shape(self): # -> Any: + """The shape of the instance and underlying arrays. + + Like `~numpy.ndarray.shape`, can be set to a new shape by assigning a + tuple. Note that if different instances share some but not all + underlying data, setting the shape of one instance can make the other + instance unusable. Hence, it is strongly recommended to get new, + reshaped instances with the ``reshape`` method. + + Raises + ------ + ValueError + If the new shape has the wrong total number of elements. + AttributeError + If the shape of any of the components cannot be changed without the + arrays being copied. For these cases, use the ``reshape`` method + (which copies any arrays that cannot be reshaped in-place). + """ + ... + + @shape.setter + def shape(self, shape): # -> None: + ... + + def __mul__(self, other): + ... + + def __rmul__(self, other): + ... + + def __truediv__(self, other): + ... + + def __neg__(self): + ... + + def __pos__(self): + ... + + def __add__(self, other): + ... + + def __radd__(self, other): + ... + + def __sub__(self, other): + ... + + def __rsub__(self, other): + ... + + def __str__(self) -> str: + ... + + def __repr__(self): # -> str: + ... + + + +class RepresentationInfo(BaseRepresentationOrDifferentialInfo): + ... + + +class BaseRepresentation(BaseRepresentationOrDifferential): + """Base for representing a point in a 3D coordinate system. + + Parameters + ---------- + comp1, comp2, comp3 : `~astropy.units.Quantity` or subclass + The components of the 3D points. The names are the keys and the + subclasses the values of the ``attr_classes`` attribute. + differentials : dict, `~astropy.coordinates.BaseDifferential`, optional + Any differential classes that should be associated with this + representation. The input must either be a single `~astropy.coordinates.BaseDifferential` + subclass instance, or a dictionary with keys set to a string + representation of the SI unit with which the differential (derivative) + is taken. For example, for a velocity differential on a positional + representation, the key would be ``'s'`` for seconds, indicating that + the derivative is a time derivative. + copy : bool, optional + If `True` (default), arrays will be copied. If `False`, arrays will + be references, though possibly broadcast to ensure matching shapes. + + Notes + ----- + All representation classes should subclass this base representation class, + and define an ``attr_classes`` attribute, a `dict` + which maps component names to the class that creates them. They must also + define a ``to_cartesian`` method and a ``from_cartesian`` class method. By + default, transformations are done via the cartesian system, but classes + that want to define a smarter transformation path can overload the + ``represent_as`` method. If one wants to use an associated differential + class, one should also define ``unit_vectors`` and ``scale_factors`` + methods (see those methods for details). + """ + info = ... + def __init_subclass__(cls, **kwargs): # -> None: + ... + + def __init__(self, *args, differentials=..., **kwargs) -> None: + ... + + @property + def differentials(self): # -> dict[Unknown, Unknown] | dict[str, BaseDifferential | RadialDifferential]: + """A dictionary of differential class instances. + + The keys of this dictionary must be a string representation of the SI + unit with which the differential (derivative) is taken. For example, for + a velocity differential on a positional representation, the key would be + ``'s'`` for seconds, indicating that the derivative is a time + derivative. + """ + ... + + def unit_vectors(self): + r"""Cartesian unit vectors in the direction of each component. + + Given unit vectors :math:`\hat{e}_c` and scale factors :math:`f_c`, + a change in one component of :math:`\delta c` corresponds to a change + in representation of :math:`\delta c \times f_c \times \hat{e}_c`. + + Returns + ------- + unit_vectors : dict of `CartesianRepresentation` + The keys are the component names. + """ + ... + + def scale_factors(self): + r"""Scale factors for each component's direction. + + Given unit vectors :math:`\hat{e}_c` and scale factors :math:`f_c`, + a change in one component of :math:`\delta c` corresponds to a change + in representation of :math:`\delta c \times f_c \times \hat{e}_c`. + + Returns + ------- + scale_factors : dict of `~astropy.units.Quantity` + The keys are the component names. + """ + ... + + def represent_as(self, other_class, differential_class=...): # -> Self@BaseRepresentation: + """Convert coordinates to another representation. + + If the instance is of the requested class, it is returned unmodified. + By default, conversion is done via Cartesian coordinates. + Also note that orientation information at the origin is *not* preserved by + conversions through Cartesian coordinates. See the docstring for + :meth:`~astropy.coordinates.BaseRepresentationOrDifferential.to_cartesian` + for an example. + + Parameters + ---------- + other_class : `~astropy.coordinates.BaseRepresentation` subclass + The type of representation to turn the coordinates into. + differential_class : dict of `~astropy.coordinates.BaseDifferential`, optional + Classes in which the differentials should be represented. + Can be a single class if only a single differential is attached, + otherwise it should be a `dict` keyed by the same keys as the + differentials. + """ + ... + + def transform(self, matrix): + """Transform coordinates using a 3x3 matrix in a Cartesian basis. + + This returns a new representation and does not modify the original one. + Any differentials attached to this representation will also be + transformed. + + Parameters + ---------- + matrix : (3,3) array-like + A 3x3 (or stack thereof) matrix, such as a rotation matrix. + + """ + ... + + def with_differentials(self, differentials): # -> Self@BaseRepresentation: + """ + Create a new representation with the same positions as this + representation, but with these new differentials. + + Differential keys that already exist in this object's differential dict + are overwritten. + + Parameters + ---------- + differentials : sequence of `~astropy.coordinates.BaseDifferential` subclass instance + The differentials for the new representation to have. + + Returns + ------- + `~astropy.coordinates.BaseRepresentation` subclass instance + A copy of this representation, but with the ``differentials`` as + its differentials. + """ + ... + + def without_differentials(self): # -> Self@BaseRepresentation: + """Return a copy of the representation without attached differentials. + + Returns + ------- + `~astropy.coordinates.BaseRepresentation` subclass instance + A shallow copy of this representation, without any differentials. + If no differentials were present, no copy is made. + """ + ... + + @classmethod + def from_representation(cls, representation): + """Create a new instance of this representation from another one. + + Parameters + ---------- + representation : `~astropy.coordinates.BaseRepresentation` instance + The presentation that should be converted to this class. + """ + ... + + def __eq__(self, value) -> bool: + """Equality operator for BaseRepresentation + + This implements strict equality and requires that the representation + classes are identical, the differentials are identical, and that the + representation data are exactly equal. + """ + ... + + def __ne__(self, value) -> bool: + ... + + def __setitem__(self, item, value): # -> None: + ... + + @BaseRepresentationOrDifferential.shape.setter + def shape(self, shape): # -> None: + ... + + def norm(self): # -> Any: + """Vector norm. + + The norm is the standard Frobenius norm, i.e., the square root of the + sum of the squares of all components with non-angular units. + + Note that any associated differentials will be dropped during this + operation. + + Returns + ------- + norm : `astropy.units.Quantity` + Vector norm, with the same shape as the representation. + """ + ... + + def mean(self, *args, **kwargs): + """Vector mean. + + Averaging is done by converting the representation to cartesian, and + taking the mean of the x, y, and z components. The result is converted + back to the same representation as the input. + + Refer to `~numpy.mean` for full documentation of the arguments, noting + that ``axis`` is the entry in the ``shape`` of the representation, and + that the ``out`` argument cannot be used. + + Returns + ------- + mean : `~astropy.coordinates.BaseRepresentation` subclass instance + Vector mean, in the same representation as that of the input. + """ + ... + + def sum(self, *args, **kwargs): + """Vector sum. + + Adding is done by converting the representation to cartesian, and + summing the x, y, and z components. The result is converted back to the + same representation as the input. + + Refer to `~numpy.sum` for full documentation of the arguments, noting + that ``axis`` is the entry in the ``shape`` of the representation, and + that the ``out`` argument cannot be used. + + Returns + ------- + sum : `~astropy.coordinates.BaseRepresentation` subclass instance + Vector sum, in the same representation as that of the input. + """ + ... + + def dot(self, other): + """Dot product of two representations. + + The calculation is done by converting both ``self`` and ``other`` + to `~astropy.coordinates.CartesianRepresentation`. + + Note that any associated differentials will be dropped during this + operation. + + Parameters + ---------- + other : `~astropy.coordinates.BaseRepresentation` + The representation to take the dot product with. + + Returns + ------- + dot_product : `~astropy.units.Quantity` + The sum of the product of the x, y, and z components of the + cartesian representations of ``self`` and ``other``. + """ + ... + + def cross(self, other): + """Vector cross product of two representations. + + The calculation is done by converting both ``self`` and ``other`` + to `~astropy.coordinates.CartesianRepresentation`, and converting the + result back to the type of representation of ``self``. + + Parameters + ---------- + other : `~astropy.coordinates.BaseRepresentation` subclass instance + The representation to take the cross product with. + + Returns + ------- + cross_product : `~astropy.coordinates.BaseRepresentation` subclass instance + With vectors perpendicular to both ``self`` and ``other``, in the + same type of representation as ``self``. + """ + ... + + + +class CartesianRepresentation(BaseRepresentation): + """ + Representation of points in 3D cartesian coordinates. + + Parameters + ---------- + x, y, z : `~astropy.units.Quantity` or array + The x, y, and z coordinates of the point(s). If ``x``, ``y``, and ``z`` + have different shapes, they should be broadcastable. If not quantity, + ``unit`` should be set. If only ``x`` is given, it is assumed that it + contains an array with the 3 coordinates stored along ``xyz_axis``. + unit : unit-like + If given, the coordinates will be converted to this unit (or taken to + be in this unit if not given. + xyz_axis : int, optional + The axis along which the coordinates are stored when a single array is + provided rather than distinct ``x``, ``y``, and ``z`` (default: 0). + + differentials : dict, `CartesianDifferential`, optional + Any differential classes that should be associated with this + representation. The input must either be a single + `CartesianDifferential` instance, or a dictionary of + `CartesianDifferential` s with keys set to a string representation of + the SI unit with which the differential (derivative) is taken. For + example, for a velocity differential on a positional representation, the + key would be ``'s'`` for seconds, indicating that the derivative is a + time derivative. + + copy : bool, optional + If `True` (default), arrays will be copied. If `False`, arrays will + be references, though possibly broadcast to ensure matching shapes. + """ + attr_classes = ... + _xyz = ... + def __init__(self, x, y=..., z=..., unit=..., xyz_axis=..., differentials=..., copy=...) -> None: + ... + + def unit_vectors(self): # -> dict[str, CartesianRepresentation]: + ... + + def scale_factors(self): # -> dict[str, NDArray[bool_]]: + ... + + def get_xyz(self, xyz_axis=...): # -> Quantity | NDArray[Unknown]: + """Return a vector array of the x, y, and z coordinates. + + Parameters + ---------- + xyz_axis : int, optional + The axis in the final array along which the x, y, z components + should be stored (default: 0). + + Returns + ------- + xyz : `~astropy.units.Quantity` + With dimension 3 along ``xyz_axis``. Note that, if possible, + this will be a view. + """ + ... + + xyz = ... + @classmethod + def from_cartesian(cls, other): + ... + + def to_cartesian(self): # -> Self@CartesianRepresentation: + ... + + def transform(self, matrix): # -> Self@CartesianRepresentation: + """ + Transform the cartesian coordinates using a 3x3 matrix. + + This returns a new representation and does not modify the original one. + Any differentials attached to this representation will also be + transformed. + + Parameters + ---------- + matrix : ndarray + A 3x3 transformation matrix, such as a rotation matrix. + + Examples + -------- + We can start off by creating a cartesian representation object: + + >>> from astropy import units as u + >>> from astropy.coordinates import CartesianRepresentation + >>> rep = CartesianRepresentation([1, 2] * u.pc, + ... [2, 3] * u.pc, + ... [3, 4] * u.pc) + + We now create a rotation matrix around the z axis: + + >>> from astropy.coordinates.matrix_utilities import rotation_matrix + >>> rotation = rotation_matrix(30 * u.deg, axis='z') + + Finally, we can apply this transformation: + + >>> rep_new = rep.transform(rotation) + >>> rep_new.xyz # doctest: +FLOAT_CMP + + """ + ... + + def norm(self): + """Vector norm. + + The norm is the standard Frobenius norm, i.e., the square root of the + sum of the squares of all components with non-angular units. + + Note that any associated differentials will be dropped during this + operation. + + Returns + ------- + norm : `astropy.units.Quantity` + Vector norm, with the same shape as the representation. + """ + ... + + def mean(self, *args, **kwargs): # -> BaseRepresentation: + """Vector mean. + + Returns a new CartesianRepresentation instance with the means of the + x, y, and z components. + + Refer to `~numpy.mean` for full documentation of the arguments, noting + that ``axis`` is the entry in the ``shape`` of the representation, and + that the ``out`` argument cannot be used. + """ + ... + + def sum(self, *args, **kwargs): # -> BaseRepresentation: + """Vector sum. + + Returns a new CartesianRepresentation instance with the sums of the + x, y, and z components. + + Refer to `~numpy.sum` for full documentation of the arguments, noting + that ``axis`` is the entry in the ``shape`` of the representation, and + that the ``out`` argument cannot be used. + """ + ... + + def dot(self, other): + """Dot product of two representations. + + Note that any associated differentials will be dropped during this + operation. + + Parameters + ---------- + other : `~astropy.coordinates.BaseRepresentation` subclass instance + If not already cartesian, it is converted. + + Returns + ------- + dot_product : `~astropy.units.Quantity` + The sum of the product of the x, y, and z components of ``self`` + and ``other``. + """ + ... + + def cross(self, other): # -> Self@CartesianRepresentation: + """Cross product of two representations. + + Parameters + ---------- + other : `~astropy.coordinates.BaseRepresentation` subclass instance + If not already cartesian, it is converted. + + Returns + ------- + cross_product : `~astropy.coordinates.CartesianRepresentation` + With vectors perpendicular to both ``self`` and ``other``. + """ + ... + + + +class UnitSphericalRepresentation(BaseRepresentation): + """ + Representation of points on a unit sphere. + + Parameters + ---------- + lon, lat : `~astropy.units.Quantity` ['angle'] or str + The longitude and latitude of the point(s), in angular units. The + latitude should be between -90 and 90 degrees, and the longitude will + be wrapped to an angle between 0 and 360 degrees. These can also be + instances of `~astropy.coordinates.Angle`, + `~astropy.coordinates.Longitude`, or `~astropy.coordinates.Latitude`. + + differentials : dict, `~astropy.coordinates.BaseDifferential`, optional + Any differential classes that should be associated with this + representation. The input must either be a single `~astropy.coordinates.BaseDifferential` + instance (see `._compatible_differentials` for valid types), or a + dictionary of of differential instances with keys set to a string + representation of the SI unit with which the differential (derivative) + is taken. For example, for a velocity differential on a positional + representation, the key would be ``'s'`` for seconds, indicating that + the derivative is a time derivative. + + copy : bool, optional + If `True` (default), arrays will be copied. If `False`, arrays will + be references, though possibly broadcast to ensure matching shapes. + """ + attr_classes = ... + def __init__(self, lon, lat=..., differentials=..., copy=...) -> None: + ... + + @property + def lon(self): + """ + The longitude of the point(s). + """ + ... + + @property + def lat(self): + """ + The latitude of the point(s). + """ + ... + + def unit_vectors(self): # -> dict[str, CartesianRepresentation]: + ... + + def scale_factors(self, omit_coslat=...): # -> dict[str, NDArray[Unknown] | Any]: + ... + + def to_cartesian(self): # -> CartesianRepresentation: + """ + Converts spherical polar coordinates to 3D rectangular cartesian + coordinates. + """ + ... + + @classmethod + def from_cartesian(cls, cart): # -> Self@UnitSphericalRepresentation: + """ + Converts 3D rectangular cartesian coordinates to spherical polar + coordinates. + """ + ... + + def represent_as(self, other_class, differential_class=...): # -> PhysicsSphericalRepresentation | SphericalRepresentation | Self@BaseRepresentation: + ... + + def transform(self, matrix): # -> Self@UnitSphericalRepresentation | SphericalRepresentation: + r"""Transform the unit-spherical coordinates using a 3x3 matrix. + + This returns a new representation and does not modify the original one. + Any differentials attached to this representation will also be + transformed. + + Parameters + ---------- + matrix : (3,3) array-like + A 3x3 matrix, such as a rotation matrix (or a stack of matrices). + + Returns + ------- + `UnitSphericalRepresentation` or `SphericalRepresentation` + If ``matrix`` is O(3) -- :math:`M \dot M^T = I` -- like a rotation, + then the result is a `UnitSphericalRepresentation`. + All other matrices will change the distance, so the dimensional + representation is used instead. + + """ + ... + + def __neg__(self): # -> Self@UnitSphericalRepresentation: + ... + + def norm(self): # -> Quantity: + """Vector norm. + + The norm is the standard Frobenius norm, i.e., the square root of the + sum of the squares of all components with non-angular units, which is + always unity for vectors on the unit sphere. + + Returns + ------- + norm : `~astropy.units.Quantity` ['dimensionless'] + Dimensionless ones, with the same shape as the representation. + """ + ... + + def mean(self, *args, **kwargs): # -> SphericalRepresentation: + """Vector mean. + + The representation is converted to cartesian, the means of the x, y, + and z components are calculated, and the result is converted to a + `~astropy.coordinates.SphericalRepresentation`. + + Refer to `~numpy.mean` for full documentation of the arguments, noting + that ``axis`` is the entry in the ``shape`` of the representation, and + that the ``out`` argument cannot be used. + """ + ... + + def sum(self, *args, **kwargs): # -> SphericalRepresentation: + """Vector sum. + + The representation is converted to cartesian, the sums of the x, y, + and z components are calculated, and the result is converted to a + `~astropy.coordinates.SphericalRepresentation`. + + Refer to `~numpy.sum` for full documentation of the arguments, noting + that ``axis`` is the entry in the ``shape`` of the representation, and + that the ``out`` argument cannot be used. + """ + ... + + def cross(self, other): # -> SphericalRepresentation: + """Cross product of two representations. + + The calculation is done by converting both ``self`` and ``other`` + to `~astropy.coordinates.CartesianRepresentation`, and converting the + result back to `~astropy.coordinates.SphericalRepresentation`. + + Parameters + ---------- + other : `~astropy.coordinates.BaseRepresentation` subclass instance + The representation to take the cross product with. + + Returns + ------- + cross_product : `~astropy.coordinates.SphericalRepresentation` + With vectors perpendicular to both ``self`` and ``other``. + """ + ... + + + +class RadialRepresentation(BaseRepresentation): + """ + Representation of the distance of points from the origin. + + Note that this is mostly intended as an internal helper representation. + It can do little else but being used as a scale in multiplication. + + Parameters + ---------- + distance : `~astropy.units.Quantity` ['length'] + The distance of the point(s) from the origin. + + differentials : dict, `~astropy.coordinates.BaseDifferential`, optional + Any differential classes that should be associated with this + representation. The input must either be a single `~astropy.coordinates.BaseDifferential` + instance (see `._compatible_differentials` for valid types), or a + dictionary of of differential instances with keys set to a string + representation of the SI unit with which the differential (derivative) + is taken. For example, for a velocity differential on a positional + representation, the key would be ``'s'`` for seconds, indicating that + the derivative is a time derivative. + + copy : bool, optional + If `True` (default), arrays will be copied. If `False`, arrays will + be references, though possibly broadcast to ensure matching shapes. + """ + attr_classes = ... + def __init__(self, distance, differentials=..., copy=...) -> None: + ... + + @property + def distance(self): + """ + The distance from the origin to the point(s). + """ + ... + + def unit_vectors(self): + """Cartesian unit vectors are undefined for radial representation.""" + ... + + def scale_factors(self): # -> dict[str, NDArray[bool_]]: + ... + + def to_cartesian(self): + """Cannot convert radial representation to cartesian.""" + ... + + @classmethod + def from_cartesian(cls, cart): # -> Self@RadialRepresentation: + """ + Converts 3D rectangular cartesian coordinates to radial coordinate. + """ + ... + + def __mul__(self, other): + ... + + def norm(self): + """Vector norm. + + Just the distance itself. + + Returns + ------- + norm : `~astropy.units.Quantity` ['dimensionless'] + Dimensionless ones, with the same shape as the representation. + """ + ... + + def transform(self, matrix): + """Radial representations cannot be transformed by a Cartesian matrix. + + Parameters + ---------- + matrix : array-like + The transformation matrix in a Cartesian basis. + Must be a multiplication: a diagonal matrix with identical elements. + Must have shape (..., 3, 3), where the last 2 indices are for the + matrix on each other axis. Make sure that the matrix shape is + compatible with the shape of this representation. + + Raises + ------ + ValueError + If the matrix is not a multiplication. + + """ + ... + + + +class SphericalRepresentation(BaseRepresentation): + """ + Representation of points in 3D spherical coordinates. + + Parameters + ---------- + lon, lat : `~astropy.units.Quantity` ['angle'] + The longitude and latitude of the point(s), in angular units. The + latitude should be between -90 and 90 degrees, and the longitude will + be wrapped to an angle between 0 and 360 degrees. These can also be + instances of `~astropy.coordinates.Angle`, + `~astropy.coordinates.Longitude`, or `~astropy.coordinates.Latitude`. + + distance : `~astropy.units.Quantity` ['length'] + The distance to the point(s). If the distance is a length, it is + passed to the :class:`~astropy.coordinates.Distance` class, otherwise + it is passed to the :class:`~astropy.units.Quantity` class. + + differentials : dict, `~astropy.coordinates.BaseDifferential`, optional + Any differential classes that should be associated with this + representation. The input must either be a single `~astropy.coordinates.BaseDifferential` + instance (see `._compatible_differentials` for valid types), or a + dictionary of of differential instances with keys set to a string + representation of the SI unit with which the differential (derivative) + is taken. For example, for a velocity differential on a positional + representation, the key would be ``'s'`` for seconds, indicating that + the derivative is a time derivative. + + copy : bool, optional + If `True` (default), arrays will be copied. If `False`, arrays will + be references, though possibly broadcast to ensure matching shapes. + """ + attr_classes = ... + _unit_representation = UnitSphericalRepresentation + def __init__(self, lon, lat=..., distance=..., differentials=..., copy=...) -> None: + ... + + @property + def lon(self): + """ + The longitude of the point(s). + """ + ... + + @property + def lat(self): + """ + The latitude of the point(s). + """ + ... + + @property + def distance(self): # -> Distance: + """ + The distance from the origin to the point(s). + """ + ... + + def unit_vectors(self): # -> dict[str, CartesianRepresentation]: + ... + + def scale_factors(self, omit_coslat=...): # -> dict[str, Distance | Quantity | Any | Unknown | _NotImplementedType | NDArray[float64] | NDArray[bool_]]: + ... + + def represent_as(self, other_class, differential_class=...): # -> PhysicsSphericalRepresentation | UnitSphericalRepresentation | Self@BaseRepresentation: + ... + + def to_cartesian(self): # -> CartesianRepresentation: + """ + Converts spherical polar coordinates to 3D rectangular cartesian + coordinates. + """ + ... + + @classmethod + def from_cartesian(cls, cart): # -> Self@SphericalRepresentation: + """ + Converts 3D rectangular cartesian coordinates to spherical polar + coordinates. + """ + ... + + def transform(self, matrix): # -> Self@SphericalRepresentation: + """Transform the spherical coordinates using a 3x3 matrix. + + This returns a new representation and does not modify the original one. + Any differentials attached to this representation will also be + transformed. + + Parameters + ---------- + matrix : (3,3) array-like + A 3x3 matrix, such as a rotation matrix (or a stack of matrices). + + """ + ... + + def norm(self): # -> NDArray[Any]: + """Vector norm. + + The norm is the standard Frobenius norm, i.e., the square root of the + sum of the squares of all components with non-angular units. For + spherical coordinates, this is just the absolute value of the distance. + + Returns + ------- + norm : `astropy.units.Quantity` + Vector norm, with the same shape as the representation. + """ + ... + + + +class PhysicsSphericalRepresentation(BaseRepresentation): + """ + Representation of points in 3D spherical coordinates (using the physics + convention of using ``phi`` and ``theta`` for azimuth and inclination + from the pole). + + Parameters + ---------- + phi, theta : `~astropy.units.Quantity` or str + The azimuth and inclination of the point(s), in angular units. The + inclination should be between 0 and 180 degrees, and the azimuth will + be wrapped to an angle between 0 and 360 degrees. These can also be + instances of `~astropy.coordinates.Angle`. If ``copy`` is False, `phi` + will be changed inplace if it is not between 0 and 360 degrees. + + r : `~astropy.units.Quantity` + The distance to the point(s). If the distance is a length, it is + passed to the :class:`~astropy.coordinates.Distance` class, otherwise + it is passed to the :class:`~astropy.units.Quantity` class. + + differentials : dict, `PhysicsSphericalDifferential`, optional + Any differential classes that should be associated with this + representation. The input must either be a single + `PhysicsSphericalDifferential` instance, or a dictionary of of + differential instances with keys set to a string representation of the + SI unit with which the differential (derivative) is taken. For example, + for a velocity differential on a positional representation, the key + would be ``'s'`` for seconds, indicating that the derivative is a time + derivative. + + copy : bool, optional + If `True` (default), arrays will be copied. If `False`, arrays will + be references, though possibly broadcast to ensure matching shapes. + """ + attr_classes = ... + def __init__(self, phi, theta=..., r=..., differentials=..., copy=...) -> None: + ... + + @property + def phi(self): + """ + The azimuth of the point(s). + """ + ... + + @property + def theta(self): + """ + The elevation of the point(s). + """ + ... + + @property + def r(self): + """ + The distance from the origin to the point(s). + """ + ... + + def unit_vectors(self): # -> dict[str, CartesianRepresentation]: + ... + + def scale_factors(self): # -> dict[str, Unknown | NDArray[bool_]]: + ... + + def represent_as(self, other_class, differential_class=...): # -> SphericalRepresentation | UnitSphericalRepresentation | Self@BaseRepresentation: + ... + + def to_cartesian(self): # -> CartesianRepresentation: + """ + Converts spherical polar coordinates to 3D rectangular cartesian + coordinates. + """ + ... + + @classmethod + def from_cartesian(cls, cart): # -> Self@PhysicsSphericalRepresentation: + """ + Converts 3D rectangular cartesian coordinates to spherical polar + coordinates. + """ + ... + + def transform(self, matrix): # -> Self@PhysicsSphericalRepresentation: + """Transform the spherical coordinates using a 3x3 matrix. + + This returns a new representation and does not modify the original one. + Any differentials attached to this representation will also be + transformed. + + Parameters + ---------- + matrix : (3,3) array-like + A 3x3 matrix, such as a rotation matrix (or a stack of matrices). + + """ + ... + + def norm(self): # -> Any: + """Vector norm. + + The norm is the standard Frobenius norm, i.e., the square root of the + sum of the squares of all components with non-angular units. For + spherical coordinates, this is just the absolute value of the radius. + + Returns + ------- + norm : `astropy.units.Quantity` + Vector norm, with the same shape as the representation. + """ + ... + + + +class CylindricalRepresentation(BaseRepresentation): + """ + Representation of points in 3D cylindrical coordinates. + + Parameters + ---------- + rho : `~astropy.units.Quantity` + The distance from the z axis to the point(s). + + phi : `~astropy.units.Quantity` or str + The azimuth of the point(s), in angular units, which will be wrapped + to an angle between 0 and 360 degrees. This can also be instances of + `~astropy.coordinates.Angle`, + + z : `~astropy.units.Quantity` + The z coordinate(s) of the point(s) + + differentials : dict, `CylindricalDifferential`, optional + Any differential classes that should be associated with this + representation. The input must either be a single + `CylindricalDifferential` instance, or a dictionary of of differential + instances with keys set to a string representation of the SI unit with + which the differential (derivative) is taken. For example, for a + velocity differential on a positional representation, the key would be + ``'s'`` for seconds, indicating that the derivative is a time + derivative. + + copy : bool, optional + If `True` (default), arrays will be copied. If `False`, arrays will + be references, though possibly broadcast to ensure matching shapes. + """ + attr_classes = ... + def __init__(self, rho, phi=..., z=..., differentials=..., copy=...) -> None: + ... + + @property + def rho(self): + """ + The distance of the point(s) from the z-axis. + """ + ... + + @property + def phi(self): + """ + The azimuth of the point(s). + """ + ... + + @property + def z(self): + """ + The height of the point(s). + """ + ... + + def unit_vectors(self): # -> dict[str, CartesianRepresentation]: + ... + + def scale_factors(self): # -> dict[str, NDArray[bool_] | Unknown]: + ... + + @classmethod + def from_cartesian(cls, cart): # -> Self@CylindricalRepresentation: + """ + Converts 3D rectangular cartesian coordinates to cylindrical polar + coordinates. + """ + ... + + def to_cartesian(self): # -> CartesianRepresentation: + """ + Converts cylindrical polar coordinates to 3D rectangular cartesian + coordinates. + """ + ... + + + +class BaseDifferential(BaseRepresentationOrDifferential): + r"""A base class representing differentials of representations. + + These represent differences or derivatives along each component. + E.g., for physics spherical coordinates, these would be + :math:`\delta r, \delta \theta, \delta \phi`. + + Parameters + ---------- + d_comp1, d_comp2, d_comp3 : `~astropy.units.Quantity` or subclass + The components of the 3D differentials. The names are the keys and the + subclasses the values of the ``attr_classes`` attribute. + copy : bool, optional + If `True` (default), arrays will be copied. If `False`, arrays will + be references, though possibly broadcast to ensure matching shapes. + + Notes + ----- + All differential representation classes should subclass this base class, + and define an ``base_representation`` attribute with the class of the + regular `~astropy.coordinates.BaseRepresentation` for which differential + coordinates are provided. This will set up a default ``attr_classes`` + instance with names equal to the base component names prefixed by ``d_``, + and all classes set to `~astropy.units.Quantity`, plus properties to access + those, and a default ``__init__`` for initialization. + """ + def __init_subclass__(cls, **kwargs): # -> None: + """Set default ``attr_classes`` and component getters on a Differential. + class BaseDifferential(BaseRepresentationOrDifferential): + + For these, the components are those of the base representation prefixed + by 'd_', and the class is `~astropy.units.Quantity`. + """ + ... + + def to_cartesian(self, base): # -> Any: + """Convert the differential to 3D rectangular cartesian coordinates. + + Parameters + ---------- + base : instance of ``self.base_representation`` + The points for which the differentials are to be converted: each of + the components is multiplied by its unit vectors and scale factors. + + Returns + ------- + `CartesianDifferential` + This object, converted. + + """ + ... + + @classmethod + def from_cartesian(cls, other, base): # -> Self@BaseDifferential: + """Convert the differential from 3D rectangular cartesian coordinates to + the desired class. + + Parameters + ---------- + other + The object to convert into this differential. + base : `BaseRepresentation` + The points for which the differentials are to be converted: each of + the components is multiplied by its unit vectors and scale factors. + Will be converted to ``cls.base_representation`` if needed. + + Returns + ------- + `BaseDifferential` subclass instance + A new differential object that is this class' type. + """ + ... + + def represent_as(self, other_class, base): # -> Self@BaseDifferential | BaseDifferential: + """Convert coordinates to another representation. + + If the instance is of the requested class, it is returned unmodified. + By default, conversion is done via cartesian coordinates. + + Parameters + ---------- + other_class : `~astropy.coordinates.BaseRepresentation` subclass + The type of representation to turn the coordinates into. + base : instance of ``self.base_representation`` + Base relative to which the differentials are defined. If the other + class is a differential representation, the base will be converted + to its ``base_representation``. + """ + ... + + @classmethod + def from_representation(cls, representation, base): # -> Self@BaseDifferential: + """Create a new instance of this representation from another one. + + Parameters + ---------- + representation : `~astropy.coordinates.BaseRepresentation` instance + The presentation that should be converted to this class. + base : instance of ``cls.base_representation`` + The base relative to which the differentials will be defined. If + the representation is a differential itself, the base will be + converted to its ``base_representation`` to help convert it. + """ + ... + + def transform(self, matrix, base, transformed_base): # -> Self@BaseDifferential | BaseDifferential: + """Transform differential using a 3x3 matrix in a Cartesian basis. + + This returns a new differential and does not modify the original one. + + Parameters + ---------- + matrix : (3,3) array-like + A 3x3 (or stack thereof) matrix, such as a rotation matrix. + base : instance of ``cls.base_representation`` + Base relative to which the differentials are defined. If the other + class is a differential representation, the base will be converted + to its ``base_representation``. + transformed_base : instance of ``cls.base_representation`` + Base relative to which the transformed differentials are defined. + If the other class is a differential representation, the base will + be converted to its ``base_representation``. + """ + ... + + def __sub__(self, other): # -> _NotImplementedType: + ... + + def norm(self, base=...): # -> Any: + """Vector norm. + + The norm is the standard Frobenius norm, i.e., the square root of the + sum of the squares of all components with non-angular units. + + Parameters + ---------- + base : instance of ``self.base_representation`` + Base relative to which the differentials are defined. This is + required to calculate the physical size of the differential for + all but Cartesian differentials or radial differentials. + + Returns + ------- + norm : `astropy.units.Quantity` + Vector norm, with the same shape as the representation. + """ + ... + + + +class CartesianDifferential(BaseDifferential): + """Differentials in of points in 3D cartesian coordinates. + + Parameters + ---------- + d_x, d_y, d_z : `~astropy.units.Quantity` or array + The x, y, and z coordinates of the differentials. If ``d_x``, ``d_y``, + and ``d_z`` have different shapes, they should be broadcastable. If not + quantities, ``unit`` should be set. If only ``d_x`` is given, it is + assumed that it contains an array with the 3 coordinates stored along + ``xyz_axis``. + unit : `~astropy.units.Unit` or str + If given, the differentials will be converted to this unit (or taken to + be in this unit if not given. + xyz_axis : int, optional + The axis along which the coordinates are stored when a single array is + provided instead of distinct ``d_x``, ``d_y``, and ``d_z`` (default: 0). + copy : bool, optional + If `True` (default), arrays will be copied. If `False`, arrays will + be references, though possibly broadcast to ensure matching shapes. + """ + base_representation = CartesianRepresentation + _d_xyz = ... + def __init__(self, d_x, d_y=..., d_z=..., unit=..., xyz_axis=..., copy=...) -> None: + ... + + def to_cartesian(self, base=...): # -> CartesianRepresentation: + ... + + @classmethod + def from_cartesian(cls, other, base=...): # -> Self@CartesianDifferential: + ... + + def transform(self, matrix, base=..., transformed_base=...): # -> Self@CartesianDifferential: + """Transform differentials using a 3x3 matrix in a Cartesian basis. + + This returns a new differential and does not modify the original one. + + Parameters + ---------- + matrix : (3,3) array-like + A 3x3 (or stack thereof) matrix, such as a rotation matrix. + base, transformed_base : `~astropy.coordinates.CartesianRepresentation` or None, optional + Not used in the Cartesian transformation. + """ + ... + + def get_d_xyz(self, xyz_axis=...): # -> Quantity | NDArray[Unknown]: + """Return a vector array of the x, y, and z coordinates. + + Parameters + ---------- + xyz_axis : int, optional + The axis in the final array along which the x, y, z components + should be stored (default: 0). + + Returns + ------- + d_xyz : `~astropy.units.Quantity` + With dimension 3 along ``xyz_axis``. Note that, if possible, + this will be a view. + """ + ... + + d_xyz = ... + + +class BaseSphericalDifferential(BaseDifferential): + ... + + +class UnitSphericalDifferential(BaseSphericalDifferential): + """Differential(s) of points on a unit sphere. + + Parameters + ---------- + d_lon, d_lat : `~astropy.units.Quantity` + The longitude and latitude of the differentials. + copy : bool, optional + If `True` (default), arrays will be copied. If `False`, arrays will + be references, though possibly broadcast to ensure matching shapes. + """ + base_representation = UnitSphericalRepresentation + def __init__(self, d_lon, d_lat=..., copy=...) -> None: + ... + + @classmethod + def from_cartesian(cls, other, base): + ... + + def to_cartesian(self, base): # -> Any: + ... + + def represent_as(self, other_class, base=...): # -> UnitSphericalCosLatDifferential | Self@BaseDifferential | BaseDifferential: + ... + + @classmethod + def from_representation(cls, representation, base=...): # -> Self@UnitSphericalDifferential | UnitSphericalDifferential: + ... + + def transform(self, matrix, base, transformed_base): # -> UnitSphericalDifferential | BaseDifferential | SphericalDifferential: + """Transform differential using a 3x3 matrix in a Cartesian basis. + + This returns a new differential and does not modify the original one. + + Parameters + ---------- + matrix : (3,3) array-like + A 3x3 (or stack thereof) matrix, such as a rotation matrix. + base : instance of ``cls.base_representation`` + Base relative to which the differentials are defined. If the other + class is a differential representation, the base will be converted + to its ``base_representation``. + transformed_base : instance of ``cls.base_representation`` + Base relative to which the transformed differentials are defined. + If the other class is a differential representation, the base will + be converted to its ``base_representation``. + """ + ... + + + +class SphericalDifferential(BaseSphericalDifferential): + """Differential(s) of points in 3D spherical coordinates. + + Parameters + ---------- + d_lon, d_lat : `~astropy.units.Quantity` + The differential longitude and latitude. + d_distance : `~astropy.units.Quantity` + The differential distance. + copy : bool, optional + If `True` (default), arrays will be copied. If `False`, arrays will + be references, though possibly broadcast to ensure matching shapes. + """ + base_representation = SphericalRepresentation + _unit_differential = UnitSphericalDifferential + def __init__(self, d_lon, d_lat=..., d_distance=..., copy=...) -> None: + ... + + def represent_as(self, other_class, base=...): # -> UnitSphericalDifferential | RadialDifferential | SphericalCosLatDifferential | UnitSphericalCosLatDifferential | PhysicsSphericalDifferential | Self@BaseDifferential | BaseDifferential: + ... + + @classmethod + def from_representation(cls, representation, base=...): # -> Self@SphericalDifferential | SphericalDifferential: + ... + + + +class BaseSphericalCosLatDifferential(BaseDifferential): + """Differentials from points on a spherical base representation. + + With cos(lat) assumed to be included in the longitude differential. + """ + ... + + +class UnitSphericalCosLatDifferential(BaseSphericalCosLatDifferential): + """Differential(s) of points on a unit sphere. + + Parameters + ---------- + d_lon_coslat, d_lat : `~astropy.units.Quantity` + The longitude and latitude of the differentials. + copy : bool, optional + If `True` (default), arrays will be copied. If `False`, arrays will + be references, though possibly broadcast to ensure matching shapes. + """ + base_representation = UnitSphericalRepresentation + attr_classes = ... + def __init__(self, d_lon_coslat, d_lat=..., copy=...) -> None: + ... + + @classmethod + def from_cartesian(cls, other, base): + ... + + def to_cartesian(self, base): # -> Any: + ... + + def represent_as(self, other_class, base=...): # -> UnitSphericalDifferential | Self@BaseDifferential | BaseDifferential: + ... + + @classmethod + def from_representation(cls, representation, base=...): # -> Self@UnitSphericalCosLatDifferential | UnitSphericalCosLatDifferential: + ... + + def transform(self, matrix, base, transformed_base): # -> UnitSphericalCosLatDifferential | BaseDifferential | SphericalCosLatDifferential: + """Transform differential using a 3x3 matrix in a Cartesian basis. + + This returns a new differential and does not modify the original one. + + Parameters + ---------- + matrix : (3,3) array-like + A 3x3 (or stack thereof) matrix, such as a rotation matrix. + base : instance of ``cls.base_representation`` + Base relative to which the differentials are defined. If the other + class is a differential representation, the base will be converted + to its ``base_representation``. + transformed_base : instance of ``cls.base_representation`` + Base relative to which the transformed differentials are defined. + If the other class is a differential representation, the base will + be converted to its ``base_representation``. + """ + ... + + + +class SphericalCosLatDifferential(BaseSphericalCosLatDifferential): + """Differential(s) of points in 3D spherical coordinates. + + Parameters + ---------- + d_lon_coslat, d_lat : `~astropy.units.Quantity` + The differential longitude (with cos(lat) included) and latitude. + d_distance : `~astropy.units.Quantity` + The differential distance. + copy : bool, optional + If `True` (default), arrays will be copied. If `False`, arrays will + be references, though possibly broadcast to ensure matching shapes. + """ + base_representation = SphericalRepresentation + _unit_differential = UnitSphericalCosLatDifferential + attr_classes = ... + def __init__(self, d_lon_coslat, d_lat=..., d_distance=..., copy=...) -> None: + ... + + def represent_as(self, other_class, base=...): # -> UnitSphericalCosLatDifferential | RadialDifferential | SphericalDifferential | UnitSphericalDifferential | PhysicsSphericalDifferential | Self@BaseDifferential | BaseDifferential: + ... + + @classmethod + def from_representation(cls, representation, base=...): # -> Self@SphericalCosLatDifferential | SphericalCosLatDifferential: + ... + + + +class RadialDifferential(BaseDifferential): + """Differential(s) of radial distances. + + Parameters + ---------- + d_distance : `~astropy.units.Quantity` + The differential distance. + copy : bool, optional + If `True` (default), arrays will be copied. If `False`, arrays will + be references, though possibly broadcast to ensure matching shapes. + """ + base_representation = RadialRepresentation + def to_cartesian(self, base): + ... + + def norm(self, base=...): + ... + + @classmethod + def from_cartesian(cls, other, base): # -> Self@RadialDifferential: + ... + + @classmethod + def from_representation(cls, representation, base=...): # -> Self@RadialDifferential | RadialDifferential: + ... + + + +class PhysicsSphericalDifferential(BaseDifferential): + """Differential(s) of 3D spherical coordinates using physics convention. + + Parameters + ---------- + d_phi, d_theta : `~astropy.units.Quantity` + The differential azimuth and inclination. + d_r : `~astropy.units.Quantity` + The differential radial distance. + copy : bool, optional + If `True` (default), arrays will be copied. If `False`, arrays will + be references, though possibly broadcast to ensure matching shapes. + """ + base_representation = PhysicsSphericalRepresentation + def __init__(self, d_phi, d_theta=..., d_r=..., copy=...) -> None: + ... + + def represent_as(self, other_class, base=...): # -> SphericalDifferential | UnitSphericalDifferential | SphericalCosLatDifferential | UnitSphericalCosLatDifferential | RadialDifferential | Self@BaseDifferential | BaseDifferential: + ... + + @classmethod + def from_representation(cls, representation, base=...): # -> Self@PhysicsSphericalDifferential | PhysicsSphericalDifferential: + ... + + + +class CylindricalDifferential(BaseDifferential): + """Differential(s) of points in cylindrical coordinates. + + Parameters + ---------- + d_rho : `~astropy.units.Quantity` ['speed'] + The differential cylindrical radius. + d_phi : `~astropy.units.Quantity` ['angular speed'] + The differential azimuth. + d_z : `~astropy.units.Quantity` ['speed'] + The differential height. + copy : bool, optional + If `True` (default), arrays will be copied. If `False`, arrays will + be references, though possibly broadcast to ensure matching shapes. + """ + base_representation = CylindricalRepresentation + def __init__(self, d_rho, d_phi=..., d_z=..., copy=...) -> None: + ... + + + diff --git a/typings/astropy/coordinates/sites.pyi b/typings/astropy/coordinates/sites.pyi new file mode 100644 index 0000000..b6a036c --- /dev/null +++ b/typings/astropy/coordinates/sites.pyi @@ -0,0 +1,99 @@ +""" +This type stub file was generated by pyright. +""" + +from collections.abc import Mapping + +""" +Currently the only site accessible without internet access is the Royal +Greenwich Observatory, as an example (and for testing purposes). In future +releases, a canonical set of sites may be bundled into astropy for when the +online registry is unavailable. + +Additions or corrections to the observatory list can be submitted via Pull +Request to the [astropy-data GitHub repository](https://github.com/astropy/astropy-data), +updating the ``location.json`` file. +""" +class SiteRegistry(Mapping): + """ + A bare-bones registry of EarthLocation objects. + + This acts as a mapping (dict-like object) but with the important caveat that + it's always transforms its inputs to lower-case. So keys are always all + lower-case, and even if you ask for something that's got mixed case, it will + be interpreted as the all lower-case version. + """ + def __init__(self) -> None: + ... + + def __getitem__(self, site_name): + """ + Returns an EarthLocation for a known site in this registry. + + Parameters + ---------- + site_name : str + Name of the observatory (case-insensitive). + + Returns + ------- + site : `~astropy.coordinates.EarthLocation` + The location of the observatory. + """ + ... + + def __len__(self): # -> int: + ... + + def __iter__(self): # -> Iterator[Unknown]: + ... + + def __contains__(self, site_name): # -> bool: + ... + + @property + def names(self): # -> list[Unknown]: + """ + The names in this registry. Note that these are *not* exactly the same + as the keys: keys are always lower-case, while `names` is what you + should use for the actual readable names (which may be case-sensitive) + + Returns + ------- + site : list of str + The names of the sites in this registry + """ + ... + + def add_site(self, names, locationobj): # -> None: + """ + Adds a location to the registry. + + Parameters + ---------- + names : list of str + All the names this site should go under + locationobj : `~astropy.coordinates.EarthLocation` + The actual site object + """ + ... + + @classmethod + def from_json(cls, jsondb): # -> Self@SiteRegistry: + ... + + + +def get_builtin_sites(): # -> SiteRegistry: + """ + Load observatory database from data/observatories.json and parse them into + a SiteRegistry. + """ + ... + +def get_downloaded_sites(jsonurl=...): # -> SiteRegistry: + """ + Load observatory database from data.astropy.org and parse into a SiteRegistry + """ + ... + diff --git a/typings/astropy/coordinates/sky_coordinate.pyi b/typings/astropy/coordinates/sky_coordinate.pyi new file mode 100644 index 0000000..3a2853d --- /dev/null +++ b/typings/astropy/coordinates/sky_coordinate.pyi @@ -0,0 +1,1231 @@ +""" +This type stub file was generated by pyright. +""" + +from astropy.utils.compat.misc import override__dir__ +from astropy.utils.data_info import MixinInfo +from astropy.utils import ShapedLikeNDArray + +__all__ = ['SkyCoord', 'SkyCoordInfo'] +class SkyCoordInfo(MixinInfo): + """ + Container for meta information like name, description, format. This is + required when the object is used as a mixin column within a table, but can + be used as a general way to store meta information. + """ + attrs_from_parent = ... + _supports_indexing = ... + @staticmethod + def default_format(val): # -> LiteralString: + ... + + @property + def unit(self): # -> str: + ... + + def new_like(self, skycoords, length, metadata_conflicts=..., name=...): + """ + Return a new SkyCoord instance which is consistent with the input + SkyCoord objects ``skycoords`` and has ``length`` rows. Being + "consistent" is defined as being able to set an item from one to each of + the rest without any exception being raised. + + This is intended for creating a new SkyCoord instance whose elements can + be set in-place for table operations like join or vstack. This is used + when a SkyCoord object is used as a mixin column in an astropy Table. + + The data values are not predictable and it is expected that the consumer + of the object will fill in all values. + + Parameters + ---------- + skycoords : list + List of input SkyCoord objects + length : int + Length of the output skycoord object + metadata_conflicts : str ('warn'|'error'|'silent') + How to handle metadata conflicts + name : str + Output name (sets output skycoord.info.name) + + Returns + ------- + skycoord : SkyCoord (or subclass) + Instance of this class consistent with ``skycoords`` + + """ + ... + + + +class SkyCoord(ShapedLikeNDArray): + """High-level object providing a flexible interface for celestial coordinate + representation, manipulation, and transformation between systems. + + The `SkyCoord` class accepts a wide variety of inputs for initialization. At + a minimum these must provide one or more celestial coordinate values with + unambiguous units. Inputs may be scalars or lists/tuples/arrays, yielding + scalar or array coordinates (can be checked via ``SkyCoord.isscalar``). + Typically one also specifies the coordinate frame, though this is not + required. The general pattern for spherical representations is:: + + SkyCoord(COORD, [FRAME], keyword_args ...) + SkyCoord(LON, LAT, [FRAME], keyword_args ...) + SkyCoord(LON, LAT, [DISTANCE], frame=FRAME, unit=UNIT, keyword_args ...) + SkyCoord([FRAME], =LON, =LAT, keyword_args ...) + + It is also possible to input coordinate values in other representations + such as cartesian or cylindrical. In this case one includes the keyword + argument ``representation_type='cartesian'`` (for example) along with data + in ``x``, ``y``, and ``z``. + + See also: https://docs.astropy.org/en/stable/coordinates/ + + Examples + -------- + The examples below illustrate common ways of initializing a `SkyCoord` + object. For a complete description of the allowed syntax see the + full coordinates documentation. First some imports:: + + >>> from astropy.coordinates import SkyCoord # High-level coordinates + >>> from astropy.coordinates import ICRS, Galactic, FK4, FK5 # Low-level frames + >>> from astropy.coordinates import Angle, Latitude, Longitude # Angles + >>> import astropy.units as u + + The coordinate values and frame specification can now be provided using + positional and keyword arguments:: + + >>> c = SkyCoord(10, 20, unit="deg") # defaults to ICRS frame + >>> c = SkyCoord([1, 2, 3], [-30, 45, 8], frame="icrs", unit="deg") # 3 coords + + >>> coords = ["1:12:43.2 +31:12:43", "1 12 43.2 +31 12 43"] + >>> c = SkyCoord(coords, frame=FK4, unit=(u.hourangle, u.deg), obstime="J1992.21") + + >>> c = SkyCoord("1h12m43.2s +1d12m43s", frame=Galactic) # Units from string + >>> c = SkyCoord(frame="galactic", l="1h12m43.2s", b="+1d12m43s") + + >>> ra = Longitude([1, 2, 3], unit=u.deg) # Could also use Angle + >>> dec = np.array([4.5, 5.2, 6.3]) * u.deg # Astropy Quantity + >>> c = SkyCoord(ra, dec, frame='icrs') + >>> c = SkyCoord(frame=ICRS, ra=ra, dec=dec, obstime='2001-01-02T12:34:56') + + >>> c = FK4(1 * u.deg, 2 * u.deg) # Uses defaults for obstime, equinox + >>> c = SkyCoord(c, obstime='J2010.11', equinox='B1965') # Override defaults + + >>> c = SkyCoord(w=0, u=1, v=2, unit='kpc', frame='galactic', + ... representation_type='cartesian') + + >>> c = SkyCoord([ICRS(ra=1*u.deg, dec=2*u.deg), ICRS(ra=3*u.deg, dec=4*u.deg)]) + + Velocity components (proper motions or radial velocities) can also be + provided in a similar manner:: + + >>> c = SkyCoord(ra=1*u.deg, dec=2*u.deg, radial_velocity=10*u.km/u.s) + + >>> c = SkyCoord(ra=1*u.deg, dec=2*u.deg, pm_ra_cosdec=2*u.mas/u.yr, pm_dec=1*u.mas/u.yr) + + As shown, the frame can be a `~astropy.coordinates.BaseCoordinateFrame` + class or the corresponding string alias. The frame classes that are built in + to astropy are `ICRS`, `FK5`, `FK4`, `FK4NoETerms`, and `Galactic`. + The string aliases are simply lower-case versions of the class name, and + allow for creating a `SkyCoord` object and transforming frames without + explicitly importing the frame classes. + + Parameters + ---------- + frame : `~astropy.coordinates.BaseCoordinateFrame` class or string, optional + Type of coordinate frame this `SkyCoord` should represent. Defaults to + to ICRS if not given or given as None. + unit : `~astropy.units.Unit`, string, or tuple of :class:`~astropy.units.Unit` or str, optional + Units for supplied coordinate values. + If only one unit is supplied then it applies to all values. + Note that passing only one unit might lead to unit conversion errors + if the coordinate values are expected to have mixed physical meanings + (e.g., angles and distances). + obstime : time-like, optional + Time(s) of observation. + equinox : time-like, optional + Coordinate frame equinox time. + representation_type : str or Representation class + Specifies the representation, e.g. 'spherical', 'cartesian', or + 'cylindrical'. This affects the positional args and other keyword args + which must correspond to the given representation. + copy : bool, optional + If `True` (default), a copy of any coordinate data is made. This + argument can only be passed in as a keyword argument. + **keyword_args + Other keyword arguments as applicable for user-defined coordinate frames. + Common options include: + + ra, dec : angle-like, optional + RA and Dec for frames where ``ra`` and ``dec`` are keys in the + frame's ``representation_component_names``, including `ICRS`, + `FK5`, `FK4`, and `FK4NoETerms`. + pm_ra_cosdec, pm_dec : `~astropy.units.Quantity` ['angular speed'], optional + Proper motion components, in angle per time units. + l, b : angle-like, optional + Galactic ``l`` and ``b`` for for frames where ``l`` and ``b`` are + keys in the frame's ``representation_component_names``, including + the `Galactic` frame. + pm_l_cosb, pm_b : `~astropy.units.Quantity` ['angular speed'], optional + Proper motion components in the `Galactic` frame, in angle per time + units. + x, y, z : float or `~astropy.units.Quantity` ['length'], optional + Cartesian coordinates values + u, v, w : float or `~astropy.units.Quantity` ['length'], optional + Cartesian coordinates values for the Galactic frame. + radial_velocity : `~astropy.units.Quantity` ['speed'], optional + The component of the velocity along the line-of-sight (i.e., the + radial direction), in velocity units. + """ + info = ... + def __init__(self, *args, copy=..., **kwargs) -> None: + ... + + @property + def frame(self): # -> BaseCoordinateFrame: + ... + + @property + def representation_type(self): # -> Any: + ... + + @representation_type.setter + def representation_type(self, value): # -> None: + ... + + @property + def representation(self): # -> Any: + ... + + @representation.setter + def representation(self, value): # -> None: + ... + + @property + def shape(self): # -> tuple[()] | tuple[Unknown, ...]: + ... + + def __eq__(self, value) -> bool: + """Equality operator for SkyCoord + + This implements strict equality and requires that the frames are + equivalent, extra frame attributes are equivalent, and that the + representation data are exactly equal. + """ + ... + + def __ne__(self, value) -> bool: + ... + + def __setitem__(self, item, value): # -> None: + """Implement self[item] = value for SkyCoord + + The right hand ``value`` must be strictly consistent with self: + - Identical class + - Equivalent frames + - Identical representation_types + - Identical representation differentials keys + - Identical frame attributes + - Identical "extra" frame attributes (e.g. obstime for an ICRS coord) + + With these caveats the setitem ends up as effectively a setitem on + the representation data. + + self.frame.data[item] = value.frame.data + """ + ... + + def insert(self, obj, values, axis=...): # -> None: + """ + Insert coordinate values before the given indices in the object and + return a new Frame object. + + The values to be inserted must conform to the rules for in-place setting + of ``SkyCoord`` objects. + + The API signature matches the ``np.insert`` API, but is more limited. + The specification of insert index ``obj`` must be a single integer, + and the ``axis`` must be ``0`` for simple insertion before the index. + + Parameters + ---------- + obj : int + Integer index before which ``values`` is inserted. + values : array-like + Value(s) to insert. If the type of ``values`` is different + from that of quantity, ``values`` is converted to the matching type. + axis : int, optional + Axis along which to insert ``values``. Default is 0, which is the + only allowed value and will insert a row. + + Returns + ------- + out : `~astropy.coordinates.SkyCoord` instance + New coordinate object with inserted value(s) + + """ + ... + + def is_transformable_to(self, new_frame): # -> bool | Literal['same']: + """ + Determines if this coordinate frame can be transformed to another + given frame. + + Parameters + ---------- + new_frame : frame class, frame object, or str + The proposed frame to transform into. + + Returns + ------- + transformable : bool or str + `True` if this can be transformed to ``new_frame``, `False` if + not, or the string 'same' if ``new_frame`` is the same system as + this object but no transformation is defined. + + Notes + ----- + A return value of 'same' means the transformation will work, but it will + just give back a copy of this object. The intended usage is:: + + if coord.is_transformable_to(some_unknown_frame): + coord2 = coord.transform_to(some_unknown_frame) + + This will work even if ``some_unknown_frame`` turns out to be the same + frame class as ``coord``. This is intended for cases where the frame + is the same regardless of the frame attributes (e.g. ICRS), but be + aware that it *might* also indicate that someone forgot to define the + transformation between two objects of the same frame class but with + different attributes. + """ + ... + + def transform_to(self, frame, merge_attributes=...): # -> Self@SkyCoord: + """Transform this coordinate to a new frame. + + The precise frame transformed to depends on ``merge_attributes``. + If `False`, the destination frame is used exactly as passed in. + But this is often not quite what one wants. E.g., suppose one wants to + transform an ICRS coordinate that has an obstime attribute to FK4; in + this case, one likely would want to use this information. Thus, the + default for ``merge_attributes`` is `True`, in which the precedence is + as follows: (1) explicitly set (i.e., non-default) values in the + destination frame; (2) explicitly set values in the source; (3) default + value in the destination frame. + + Note that in either case, any explicitly set attributes on the source + `SkyCoord` that are not part of the destination frame's definition are + kept (stored on the resulting `SkyCoord`), and thus one can round-trip + (e.g., from FK4 to ICRS to FK4 without losing obstime). + + Parameters + ---------- + frame : str, `BaseCoordinateFrame` class or instance, or `SkyCoord` instance + The frame to transform this coordinate into. If a `SkyCoord`, the + underlying frame is extracted, and all other information ignored. + merge_attributes : bool, optional + Whether the default attributes in the destination frame are allowed + to be overridden by explicitly set attributes in the source + (see note above; default: `True`). + + Returns + ------- + coord : `SkyCoord` + A new object with this coordinate represented in the `frame` frame. + + Raises + ------ + ValueError + If there is no possible transformation route. + + """ + ... + + def apply_space_motion(self, new_obstime=..., dt=...): # -> Self@SkyCoord: + """ + Compute the position of the source represented by this coordinate object + to a new time using the velocities stored in this object and assuming + linear space motion (including relativistic corrections). This is + sometimes referred to as an "epoch transformation." + + The initial time before the evolution is taken from the ``obstime`` + attribute of this coordinate. Note that this method currently does not + support evolving coordinates where the *frame* has an ``obstime`` frame + attribute, so the ``obstime`` is only used for storing the before and + after times, not actually as an attribute of the frame. Alternatively, + if ``dt`` is given, an ``obstime`` need not be provided at all. + + Parameters + ---------- + new_obstime : `~astropy.time.Time`, optional + The time at which to evolve the position to. Requires that the + ``obstime`` attribute be present on this frame. + dt : `~astropy.units.Quantity`, `~astropy.time.TimeDelta`, optional + An amount of time to evolve the position of the source. Cannot be + given at the same time as ``new_obstime``. + + Returns + ------- + new_coord : `SkyCoord` + A new coordinate object with the evolved location of this coordinate + at the new time. ``obstime`` will be set on this object to the new + time only if ``self`` also has ``obstime``. + """ + ... + + def __getattr__(self, attr): # -> Self@SkyCoord | Any | None: + """ + Overrides getattr to return coordinates that this can be transformed + to, based on the alias attr in the primary transform graph. + """ + ... + + def __setattr__(self, attr, val): # -> None: + ... + + def __delattr__(self, attr): # -> None: + ... + + @override__dir__ + def __dir__(self): # -> set[Unknown]: + """ + Override the builtin `dir` behavior to include: + - Transforms available by aliases + - Attribute / methods of the underlying self.frame object + """ + ... + + def __repr__(self): # -> LiteralString: + ... + + def to_string(self, style=..., **kwargs): # -> ndarray[Any, dtype[Unknown]] | list[Unknown]: + """ + A string representation of the coordinates. + + The default styles definitions are:: + + 'decimal': 'lat': {'decimal': True, 'unit': "deg"} + 'lon': {'decimal': True, 'unit': "deg"} + 'dms': 'lat': {'unit': "deg"} + 'lon': {'unit': "deg"} + 'hmsdms': 'lat': {'alwayssign': True, 'pad': True, 'unit': "deg"} + 'lon': {'pad': True, 'unit': "hour"} + + See :meth:`~astropy.coordinates.Angle.to_string` for details and + keyword arguments (the two angles forming the coordinates are are + both :class:`~astropy.coordinates.Angle` instances). Keyword + arguments have precedence over the style defaults and are passed + to :meth:`~astropy.coordinates.Angle.to_string`. + + Parameters + ---------- + style : {'hmsdms', 'dms', 'decimal'} + The formatting specification to use. These encode the three most + common ways to represent coordinates. The default is `decimal`. + **kwargs + Keyword args passed to :meth:`~astropy.coordinates.Angle.to_string`. + """ + ... + + def to_table(self): # -> QTable: + """ + Convert this |SkyCoord| to a |QTable|. + + Any attributes that have the same length as the |SkyCoord| will be + converted to columns of the |QTable|. All other attributes will be + recorded as metadata. + + Returns + ------- + `~astropy.table.QTable` + A |QTable| containing the data of this |SkyCoord|. + + Examples + -------- + >>> sc = SkyCoord(ra=[40, 70]*u.deg, dec=[0, -20]*u.deg, + ... obstime=Time([2000, 2010], format='jyear')) + >>> t = sc.to_table() + >>> t + + ra dec obstime + deg deg + float64 float64 Time + ------- ------- ------- + 40.0 0.0 2000.0 + 70.0 -20.0 2010.0 + >>> t.meta + {'representation_type': 'spherical', 'frame': 'icrs'} + """ + ... + + def is_equivalent_frame(self, other): # -> bool: + """ + Checks if this object's frame as the same as that of the ``other`` + object. + + To be the same frame, two objects must be the same frame class and have + the same frame attributes. For two `SkyCoord` objects, *all* of the + frame attributes have to match, not just those relevant for the object's + frame. + + Parameters + ---------- + other : SkyCoord or BaseCoordinateFrame + The other object to check. + + Returns + ------- + isequiv : bool + True if the frames are the same, False if not. + + Raises + ------ + TypeError + If ``other`` isn't a `SkyCoord` or a `BaseCoordinateFrame` or subclass. + """ + ... + + def separation(self, other): # -> Angle: + """ + Computes on-sky separation between this coordinate and another. + + .. note:: + + If the ``other`` coordinate object is in a different frame, it is + first transformed to the frame of this object. This can lead to + unintuitive behavior if not accounted for. Particularly of note is + that ``self.separation(other)`` and ``other.separation(self)`` may + not give the same answer in this case. + + For more on how to use this (and related) functionality, see the + examples in :doc:`astropy:/coordinates/matchsep`. + + Parameters + ---------- + other : `~astropy.coordinates.SkyCoord` or `~astropy.coordinates.BaseCoordinateFrame` + The coordinate to get the separation to. + + Returns + ------- + sep : `~astropy.coordinates.Angle` + The on-sky separation between this and the ``other`` coordinate. + + Notes + ----- + The separation is calculated using the Vincenty formula, which + is stable at all locations, including poles and antipodes [1]_. + + .. [1] https://en.wikipedia.org/wiki/Great-circle_distance + + """ + ... + + def separation_3d(self, other): # -> Distance: + """ + Computes three dimensional separation between this coordinate + and another. + + For more on how to use this (and related) functionality, see the + examples in :doc:`astropy:/coordinates/matchsep`. + + Parameters + ---------- + other : `~astropy.coordinates.SkyCoord` or `~astropy.coordinates.BaseCoordinateFrame` + The coordinate to get the separation to. + + Returns + ------- + sep : `~astropy.coordinates.Distance` + The real-space distance between these two coordinates. + + Raises + ------ + ValueError + If this or the other coordinate do not have distances. + """ + ... + + def spherical_offsets_to(self, tocoord): # -> tuple[Unknown, Unknown]: + r""" + Computes angular offsets to go *from* this coordinate *to* another. + + Parameters + ---------- + tocoord : `~astropy.coordinates.BaseCoordinateFrame` + The coordinate to find the offset to. + + Returns + ------- + lon_offset : `~astropy.coordinates.Angle` + The angular offset in the longitude direction. The definition of + "longitude" depends on this coordinate's frame (e.g., RA for + equatorial coordinates). + lat_offset : `~astropy.coordinates.Angle` + The angular offset in the latitude direction. The definition of + "latitude" depends on this coordinate's frame (e.g., Dec for + equatorial coordinates). + + Raises + ------ + ValueError + If the ``tocoord`` is not in the same frame as this one. This is + different from the behavior of the `separation`/`separation_3d` + methods because the offset components depend critically on the + specific choice of frame. + + Notes + ----- + This uses the sky offset frame machinery, and hence will produce a new + sky offset frame if one does not already exist for this object's frame + class. + + See Also + -------- + separation : + for the *total* angular offset (not broken out into components). + position_angle : + for the direction of the offset. + + """ + ... + + def spherical_offsets_by(self, d_lon, d_lat): # -> Self@SkyCoord: + """ + Computes the coordinate that is a specified pair of angular offsets away + from this coordinate. + + Parameters + ---------- + d_lon : angle-like + The angular offset in the longitude direction. The definition of + "longitude" depends on this coordinate's frame (e.g., RA for + equatorial coordinates). + d_lat : angle-like + The angular offset in the latitude direction. The definition of + "latitude" depends on this coordinate's frame (e.g., Dec for + equatorial coordinates). + + Returns + ------- + newcoord : `~astropy.coordinates.SkyCoord` + The coordinates for the location that corresponds to offsetting by + ``d_lat`` in the latitude direction and ``d_lon`` in the longitude + direction. + + Notes + ----- + This internally uses `~astropy.coordinates.SkyOffsetFrame` to do the + transformation. For a more complete set of transform offsets, use + `~astropy.coordinates.SkyOffsetFrame` or `~astropy.wcs.WCS` manually. + This specific method can be reproduced by doing + ``SkyCoord(SkyOffsetFrame(d_lon, d_lat, origin=self.frame).transform_to(self))``. + + See Also + -------- + spherical_offsets_to : compute the angular offsets to another coordinate + directional_offset_by : offset a coordinate by an angle in a direction + """ + ... + + def directional_offset_by(self, position_angle, separation): # -> SkyCoord: + """ + Computes coordinates at the given offset from this coordinate. + + Parameters + ---------- + position_angle : `~astropy.coordinates.Angle` + position_angle of offset + separation : `~astropy.coordinates.Angle` + offset angular separation + + Returns + ------- + newpoints : `~astropy.coordinates.SkyCoord` + The coordinates for the location that corresponds to offsetting by + the given `position_angle` and `separation`. + + Notes + ----- + Returned SkyCoord frame retains only the frame attributes that are for + the resulting frame type. (e.g. if the input frame is + `~astropy.coordinates.ICRS`, an ``equinox`` value will be retained, but + an ``obstime`` will not.) + + For a more complete set of transform offsets, use `~astropy.wcs.WCS`. + `~astropy.coordinates.SkyCoord.skyoffset_frame()` can also be used to + create a spherical frame with (lat=0, lon=0) at a reference point, + approximating an xy cartesian system for small offsets. This method + is distinct in that it is accurate on the sphere. + + See Also + -------- + position_angle : inverse operation for the ``position_angle`` component + separation : inverse operation for the ``separation`` component + + """ + ... + + def match_to_catalog_sky(self, catalogcoord, nthneighbor=...): # -> tuple[Unknown, Unknown, Unknown]: + """ + Finds the nearest on-sky matches of this coordinate in a set of + catalog coordinates. + + For more on how to use this (and related) functionality, see the + examples in :doc:`astropy:/coordinates/matchsep`. + + Parameters + ---------- + catalogcoord : `~astropy.coordinates.SkyCoord` or `~astropy.coordinates.BaseCoordinateFrame` + The base catalog in which to search for matches. Typically this + will be a coordinate object that is an array (i.e., + ``catalogcoord.isscalar == False``) + nthneighbor : int, optional + Which closest neighbor to search for. Typically ``1`` is + desired here, as that is correct for matching one set of + coordinates to another. The next likely use case is ``2``, + for matching a coordinate catalog against *itself* (``1`` + is inappropriate because each point will find itself as the + closest match). + + Returns + ------- + idx : int array + Indices into ``catalogcoord`` to get the matched points for + each of this object's coordinates. Shape matches this + object. + sep2d : `~astropy.coordinates.Angle` + The on-sky separation between the closest match for each + element in this object in ``catalogcoord``. Shape matches + this object. + dist3d : `~astropy.units.Quantity` ['length'] + The 3D distance between the closest match for each element + in this object in ``catalogcoord``. Shape matches this + object. Unless both this and ``catalogcoord`` have associated + distances, this quantity assumes that all sources are at a + distance of 1 (dimensionless). + + Notes + ----- + This method requires `SciPy `_ to be + installed or it will fail. + + See Also + -------- + astropy.coordinates.match_coordinates_sky + SkyCoord.match_to_catalog_3d + """ + ... + + def match_to_catalog_3d(self, catalogcoord, nthneighbor=...): # -> tuple[Unknown, Unknown, Unknown]: + """ + Finds the nearest 3-dimensional matches of this coordinate to a set + of catalog coordinates. + + This finds the 3-dimensional closest neighbor, which is only different + from the on-sky distance if ``distance`` is set in this object or the + ``catalogcoord`` object. + + For more on how to use this (and related) functionality, see the + examples in :doc:`astropy:/coordinates/matchsep`. + + Parameters + ---------- + catalogcoord : `~astropy.coordinates.SkyCoord` or `~astropy.coordinates.BaseCoordinateFrame` + The base catalog in which to search for matches. Typically this + will be a coordinate object that is an array (i.e., + ``catalogcoord.isscalar == False``) + nthneighbor : int, optional + Which closest neighbor to search for. Typically ``1`` is + desired here, as that is correct for matching one set of + coordinates to another. The next likely use case is + ``2``, for matching a coordinate catalog against *itself* + (``1`` is inappropriate because each point will find + itself as the closest match). + + Returns + ------- + idx : int array + Indices into ``catalogcoord`` to get the matched points for + each of this object's coordinates. Shape matches this + object. + sep2d : `~astropy.coordinates.Angle` + The on-sky separation between the closest match for each + element in this object in ``catalogcoord``. Shape matches + this object. + dist3d : `~astropy.units.Quantity` ['length'] + The 3D distance between the closest match for each element + in this object in ``catalogcoord``. Shape matches this + object. + + Notes + ----- + This method requires `SciPy `_ to be + installed or it will fail. + + See Also + -------- + astropy.coordinates.match_coordinates_3d + SkyCoord.match_to_catalog_sky + """ + ... + + def search_around_sky(self, searcharoundcoords, seplimit): # -> tuple[NDArray[Any], NDArray[Any], Angle, Quantity] | tuple[NDArray[Any], NDArray[Any], Angle | Unknown, Quantity | Unknown | Any]: + """ + Searches for all coordinates in this object around a supplied set of + points within a given on-sky separation. + + This is intended for use on `~astropy.coordinates.SkyCoord` objects + with coordinate arrays, rather than a scalar coordinate. For a scalar + coordinate, it is better to use + `~astropy.coordinates.SkyCoord.separation`. + + For more on how to use this (and related) functionality, see the + examples in :doc:`astropy:/coordinates/matchsep`. + + Parameters + ---------- + searcharoundcoords : coordinate-like + The coordinates to search around to try to find matching points in + this `SkyCoord`. This should be an object with array coordinates, + not a scalar coordinate object. + seplimit : `~astropy.units.Quantity` ['angle'] + The on-sky separation to search within. + + Returns + ------- + idxsearcharound : int array + Indices into ``searcharoundcoords`` that match the + corresponding elements of ``idxself``. Shape matches + ``idxself``. + idxself : int array + Indices into ``self`` that match the + corresponding elements of ``idxsearcharound``. Shape matches + ``idxsearcharound``. + sep2d : `~astropy.coordinates.Angle` + The on-sky separation between the coordinates. Shape matches + ``idxsearcharound`` and ``idxself``. + dist3d : `~astropy.units.Quantity` ['length'] + The 3D distance between the coordinates. Shape matches + ``idxsearcharound`` and ``idxself``. + + Notes + ----- + This method requires `SciPy `_ to be + installed or it will fail. + + In the current implementation, the return values are always sorted in + the same order as the ``searcharoundcoords`` (so ``idxsearcharound`` is + in ascending order). This is considered an implementation detail, + though, so it could change in a future release. + + See Also + -------- + astropy.coordinates.search_around_sky + SkyCoord.search_around_3d + """ + ... + + def search_around_3d(self, searcharoundcoords, distlimit): # -> tuple[NDArray[Any], NDArray[Any], Angle, Quantity] | tuple[NDArray[Any], NDArray[Any], Angle | Unknown, Quantity | Unknown]: + """ + Searches for all coordinates in this object around a supplied set of + points within a given 3D radius. + + This is intended for use on `~astropy.coordinates.SkyCoord` objects + with coordinate arrays, rather than a scalar coordinate. For a scalar + coordinate, it is better to use + `~astropy.coordinates.SkyCoord.separation_3d`. + + For more on how to use this (and related) functionality, see the + examples in :doc:`astropy:/coordinates/matchsep`. + + Parameters + ---------- + searcharoundcoords : `~astropy.coordinates.SkyCoord` or `~astropy.coordinates.BaseCoordinateFrame` + The coordinates to search around to try to find matching points in + this `SkyCoord`. This should be an object with array coordinates, + not a scalar coordinate object. + distlimit : `~astropy.units.Quantity` ['length'] + The physical radius to search within. + + Returns + ------- + idxsearcharound : int array + Indices into ``searcharoundcoords`` that match the + corresponding elements of ``idxself``. Shape matches + ``idxself``. + idxself : int array + Indices into ``self`` that match the + corresponding elements of ``idxsearcharound``. Shape matches + ``idxsearcharound``. + sep2d : `~astropy.coordinates.Angle` + The on-sky separation between the coordinates. Shape matches + ``idxsearcharound`` and ``idxself``. + dist3d : `~astropy.units.Quantity` ['length'] + The 3D distance between the coordinates. Shape matches + ``idxsearcharound`` and ``idxself``. + + Notes + ----- + This method requires `SciPy `_ to be + installed or it will fail. + + In the current implementation, the return values are always sorted in + the same order as the ``searcharoundcoords`` (so ``idxsearcharound`` is + in ascending order). This is considered an implementation detail, + though, so it could change in a future release. + + See Also + -------- + astropy.coordinates.search_around_3d + SkyCoord.search_around_sky + """ + ... + + def position_angle(self, other): # -> Angle | None: + """ + Computes the on-sky position angle (East of North) between this + `SkyCoord` and another. + + Parameters + ---------- + other : `SkyCoord` + The other coordinate to compute the position angle to. It is + treated as the "head" of the vector of the position angle. + + Returns + ------- + pa : `~astropy.coordinates.Angle` + The (positive) position angle of the vector pointing from ``self`` + to ``other``. If either ``self`` or ``other`` contain arrays, this + will be an array following the appropriate `numpy` broadcasting + rules. + + Examples + -------- + >>> c1 = SkyCoord(0*u.deg, 0*u.deg) + >>> c2 = SkyCoord(1*u.deg, 0*u.deg) + >>> c1.position_angle(c2).degree + 90.0 + >>> c3 = SkyCoord(1*u.deg, 1*u.deg) + >>> c1.position_angle(c3).degree # doctest: +FLOAT_CMP + 44.995636455344844 + """ + ... + + def skyoffset_frame(self, rotation=...): # -> SkyOffsetFrame: + """ + Returns the sky offset frame with this `SkyCoord` at the origin. + + Returns + ------- + astrframe : `~astropy.coordinates.SkyOffsetFrame` + A sky offset frame of the same type as this `SkyCoord` (e.g., if + this object has an ICRS coordinate, the resulting frame is + SkyOffsetICRS, with the origin set to this object) + rotation : angle-like + The final rotation of the frame about the ``origin``. The sign of + the rotation is the left-hand rule. That is, an object at a + particular position angle in the un-rotated system will be sent to + the positive latitude (z) direction in the final frame. + """ + ... + + def get_constellation(self, short_name=..., constellation_list=...): # -> Any: + """ + Determines the constellation(s) of the coordinates this `SkyCoord` + contains. + + Parameters + ---------- + short_name : bool + If True, the returned names are the IAU-sanctioned abbreviated + names. Otherwise, full names for the constellations are used. + constellation_list : str + The set of constellations to use. Currently only ``'iau'`` is + supported, meaning the 88 "modern" constellations endorsed by the IAU. + + Returns + ------- + constellation : str or string array + If this is a scalar coordinate, returns the name of the + constellation. If it is an array `SkyCoord`, it returns an array of + names. + + Notes + ----- + To determine which constellation a point on the sky is in, this first + precesses to B1875, and then uses the Delporte boundaries of the 88 + modern constellations, as tabulated by + `Roman 1987 `_. + + See Also + -------- + astropy.coordinates.get_constellation + """ + ... + + def to_pixel(self, wcs, origin=..., mode=...): # -> tuple[Unknown, Unknown]: + """ + Convert this coordinate to pixel coordinates using a `~astropy.wcs.WCS` + object. + + Parameters + ---------- + wcs : `~astropy.wcs.WCS` + The WCS to use for convert + origin : int + Whether to return 0 or 1-based pixel coordinates. + mode : 'all' or 'wcs' + Whether to do the transformation including distortions (``'all'``) or + only including only the core WCS transformation (``'wcs'``). + + Returns + ------- + xp, yp : `numpy.ndarray` + The pixel coordinates + + See Also + -------- + astropy.wcs.utils.skycoord_to_pixel : the implementation of this method + """ + ... + + @classmethod + def from_pixel(cls, xp, yp, wcs, origin=..., mode=...): # -> SkyCoord: + """ + Create a new `SkyCoord` from pixel coordinates using an + `~astropy.wcs.WCS` object. + + Parameters + ---------- + xp, yp : float or ndarray + The coordinates to convert. + wcs : `~astropy.wcs.WCS` + The WCS to use for convert + origin : int + Whether to return 0 or 1-based pixel coordinates. + mode : 'all' or 'wcs' + Whether to do the transformation including distortions (``'all'``) or + only including only the core WCS transformation (``'wcs'``). + + Returns + ------- + coord : `~astropy.coordinates.SkyCoord` + A new object with sky coordinates corresponding to the input ``xp`` + and ``yp``. + + See Also + -------- + to_pixel : to do the inverse operation + astropy.wcs.utils.pixel_to_skycoord : the implementation of this method + """ + ... + + def contained_by(self, wcs, image=..., **kwargs): # -> Literal[False]: + """ + Determines if the SkyCoord is contained in the given wcs footprint. + + Parameters + ---------- + wcs : `~astropy.wcs.WCS` + The coordinate to check if it is within the wcs coordinate. + image : array + Optional. The image associated with the wcs object that the cooordinate + is being checked against. If not given the naxis keywords will be used + to determine if the coordinate falls within the wcs footprint. + **kwargs + Additional arguments to pass to `~astropy.coordinates.SkyCoord.to_pixel` + + Returns + ------- + response : bool + True means the WCS footprint contains the coordinate, False means it does not. + """ + ... + + def radial_velocity_correction(self, kind=..., obstime=..., location=...): # -> Any: + """ + Compute the correction required to convert a radial velocity at a given + time and place on the Earth's Surface to a barycentric or heliocentric + velocity. + + Parameters + ---------- + kind : str + The kind of velocity correction. Must be 'barycentric' or + 'heliocentric'. + obstime : `~astropy.time.Time` or None, optional + The time at which to compute the correction. If `None`, the + ``obstime`` frame attribute on the `SkyCoord` will be used. + location : `~astropy.coordinates.EarthLocation` or None, optional + The observer location at which to compute the correction. If + `None`, the ``location`` frame attribute on the passed-in + ``obstime`` will be used, and if that is None, the ``location`` + frame attribute on the `SkyCoord` will be used. + + Raises + ------ + ValueError + If either ``obstime`` or ``location`` are passed in (not ``None``) + when the frame attribute is already set on this `SkyCoord`. + TypeError + If ``obstime`` or ``location`` aren't provided, either as arguments + or as frame attributes. + + Returns + ------- + vcorr : `~astropy.units.Quantity` ['speed'] + The correction with a positive sign. I.e., *add* this + to an observed radial velocity to get the barycentric (or + heliocentric) velocity. If m/s precision or better is needed, + see the notes below. + + Notes + ----- + The barycentric correction is calculated to higher precision than the + heliocentric correction and includes additional physics (e.g time dilation). + Use barycentric corrections if m/s precision is required. + + The algorithm here is sufficient to perform corrections at the mm/s level, but + care is needed in application. The barycentric correction returned uses the optical + approximation v = z * c. Strictly speaking, the barycentric correction is + multiplicative and should be applied as:: + + >>> from astropy.time import Time + >>> from astropy.coordinates import SkyCoord, EarthLocation + >>> from astropy.constants import c + >>> t = Time(56370.5, format='mjd', scale='utc') + >>> loc = EarthLocation('149d33m00.5s','-30d18m46.385s',236.87*u.m) + >>> sc = SkyCoord(1*u.deg, 2*u.deg) + >>> vcorr = sc.radial_velocity_correction(kind='barycentric', obstime=t, location=loc) # doctest: +REMOTE_DATA + >>> rv = rv + vcorr + rv * vcorr / c # doctest: +SKIP + + Also note that this method returns the correction velocity in the so-called + *optical convention*:: + + >>> vcorr = zb * c # doctest: +SKIP + + where ``zb`` is the barycentric correction redshift as defined in section 3 + of Wright & Eastman (2014). The application formula given above follows from their + equation (11) under assumption that the radial velocity ``rv`` has also been defined + using the same optical convention. Note, this can be regarded as a matter of + velocity definition and does not by itself imply any loss of accuracy, provided + sufficient care has been taken during interpretation of the results. If you need + the barycentric correction expressed as the full relativistic velocity (e.g., to provide + it as the input to another software which performs the application), the + following recipe can be used:: + + >>> zb = vcorr / c # doctest: +REMOTE_DATA + >>> zb_plus_one_squared = (zb + 1) ** 2 # doctest: +REMOTE_DATA + >>> vcorr_rel = c * (zb_plus_one_squared - 1) / (zb_plus_one_squared + 1) # doctest: +REMOTE_DATA + + or alternatively using just equivalencies:: + + >>> vcorr_rel = vcorr.to(u.Hz, u.doppler_optical(1*u.Hz)).to(vcorr.unit, u.doppler_relativistic(1*u.Hz)) # doctest: +REMOTE_DATA + + See also `~astropy.units.equivalencies.doppler_optical`, + `~astropy.units.equivalencies.doppler_radio`, and + `~astropy.units.equivalencies.doppler_relativistic` for more information on + the velocity conventions. + + The default is for this method to use the builtin ephemeris for + computing the sun and earth location. Other ephemerides can be chosen + by setting the `~astropy.coordinates.solar_system_ephemeris` variable, + either directly or via ``with`` statement. For example, to use the JPL + ephemeris, do:: + + >>> from astropy.coordinates import solar_system_ephemeris + >>> sc = SkyCoord(1*u.deg, 2*u.deg) + >>> with solar_system_ephemeris.set('jpl'): # doctest: +REMOTE_DATA + ... rv += sc.radial_velocity_correction(obstime=t, location=loc) # doctest: +SKIP + + """ + ... + + @classmethod + def guess_from_table(cls, table, **coord_kwargs): # -> Self@SkyCoord: + r""" + A convenience method to create and return a new `SkyCoord` from the data + in an astropy Table. + + This method matches table columns that start with the case-insensitive + names of the the components of the requested frames (including + differentials), if they are also followed by a non-alphanumeric + character. It will also match columns that *end* with the component name + if a non-alphanumeric character is *before* it. + + For example, the first rule means columns with names like + ``'RA[J2000]'`` or ``'ra'`` will be interpreted as ``ra`` attributes for + `~astropy.coordinates.ICRS` frames, but ``'RAJ2000'`` or ``'radius'`` + are *not*. Similarly, the second rule applied to the + `~astropy.coordinates.Galactic` frame means that a column named + ``'gal_l'`` will be used as the the ``l`` component, but ``gall`` or + ``'fill'`` will not. + + The definition of alphanumeric here is based on Unicode's definition + of alphanumeric, except without ``_`` (which is normally considered + alphanumeric). So for ASCII, this means the non-alphanumeric characters + are ``_!"#$%&'()*+,-./\:;<=>?@[]^`{|}~``). + + Parameters + ---------- + table : `~astropy.table.Table` or subclass + The table to load data from. + **coord_kwargs + Any additional keyword arguments are passed directly to this class's + constructor. + + Returns + ------- + newsc : `~astropy.coordinates.SkyCoord` or subclass + The new `SkyCoord` (or subclass) object. + + Raises + ------ + ValueError + If more than one match is found in the table for a component, + unless the additional matches are also valid frame component names. + If a "coord_kwargs" is provided for a value also found in the table. + + """ + ... + + @classmethod + def from_name(cls, name, frame=..., parse=..., cache=...): # -> Self@SkyCoord: + """ + Given a name, query the CDS name resolver to attempt to retrieve + coordinate information for that object. The search database, sesame + url, and query timeout can be set through configuration items in + ``astropy.coordinates.name_resolve`` -- see docstring for + `~astropy.coordinates.get_icrs_coordinates` for more + information. + + Parameters + ---------- + name : str + The name of the object to get coordinates for, e.g. ``'M42'``. + frame : str or `BaseCoordinateFrame` class or instance + The frame to transform the object to. + parse : bool + Whether to attempt extracting the coordinates from the name by + parsing with a regex. For objects catalog names that have + J-coordinates embedded in their names, e.g., + 'CRTS SSS100805 J194428-420209', this may be much faster than a + Sesame query for the same object name. The coordinates extracted + in this way may differ from the database coordinates by a few + deci-arcseconds, so only use this option if you do not need + sub-arcsecond accuracy for coordinates. + cache : bool, optional + Determines whether to cache the results or not. To update or + overwrite an existing value, pass ``cache='update'``. + + Returns + ------- + coord : SkyCoord + Instance of the SkyCoord class. + """ + ... + + + diff --git a/typings/astropy/coordinates/sky_coordinate_parsers.pyi b/typings/astropy/coordinates/sky_coordinate_parsers.pyi new file mode 100644 index 0000000..688304f --- /dev/null +++ b/typings/astropy/coordinates/sky_coordinate_parsers.pyi @@ -0,0 +1,7 @@ +""" +This type stub file was generated by pyright. +""" + +PLUS_MINUS_RE = ... +J_PREFIXED_RA_DEC_RE = ... +_conflict_err_msg = ... diff --git a/typings/astropy/coordinates/solar_system.pyi b/typings/astropy/coordinates/solar_system.pyi new file mode 100644 index 0000000..2f765d5 --- /dev/null +++ b/typings/astropy/coordinates/solar_system.pyi @@ -0,0 +1,202 @@ +""" +This type stub file was generated by pyright. +""" + +from astropy.utils.decorators import classproperty +from astropy.utils.state import ScienceState + +""" +This module contains convenience functions for retrieving solar system +ephemerides from jplephem. +""" +__all__ = ["get_body", "get_moon", "get_body_barycentric", "get_body_barycentric_posvel", "solar_system_ephemeris"] +DEFAULT_JPL_EPHEMERIS = ... +BODY_NAME_TO_KERNEL_SPEC = ... +PLAN94_BODY_NAME_TO_PLANET_INDEX = ... +_EPHEMERIS_NOTE = ... +class solar_system_ephemeris(ScienceState): + """Default ephemerides for calculating positions of Solar-System bodies. + + This can be one of the following: + + - 'builtin': polynomial approximations to the orbital elements. + - 'dexxx[s]', for a JPL dynamical model, where xxx is the three digit + version number (e.g. de430), and the 's' is optional to specify the + 'small' version of a kernel. The version number must correspond to an + ephemeris file available at: + https://naif.jpl.nasa.gov/pub/naif/generic_kernels/spk/planets/ + - 'jpl': Alias for the default JPL ephemeris (currently, 'de430'). + - URL: (str) The url to a SPK ephemeris in SPICE binary (.bsp) format. + - PATH: (str) File path to a SPK ephemeris in SPICE binary (.bsp) format. + - `None`: Ensure an Exception is raised without an explicit ephemeris. + + The default is 'builtin', which uses the ``epv00`` and ``plan94`` + routines from the ``erfa`` implementation of the Standards Of Fundamental + Astronomy library. + + Notes + ----- + Any file required will be downloaded (and cached) when the state is set. + The default Satellite Planet Kernel (SPK) file from NASA JPL (de430) is + ~120MB, and covers years ~1550-2650 CE [1]_. The smaller de432s file is + ~10MB, and covers years 1950-2050 [2]_ (and similarly for the newer de440 + and de440s). Older versions of the JPL ephemerides (such as the widely + used de200) can be used via their URL [3]_. + + .. [1] https://naif.jpl.nasa.gov/pub/naif/generic_kernels/spk/planets/aareadme_de430-de431.txt + .. [2] https://naif.jpl.nasa.gov/pub/naif/generic_kernels/spk/planets/aareadme_de432s.txt + .. [3] https://naif.jpl.nasa.gov/pub/naif/generic_kernels/spk/planets/a_old_versions/ + """ + _value = ... + _kernel = ... + @classmethod + def validate(cls, value): # -> str: + ... + + @classmethod + def get_kernel(cls, value): # -> None: + ... + + @classproperty + def kernel(cls): # -> None: + ... + + @classproperty + def bodies(cls): # -> tuple[str, ...] | None: + ... + + + +def get_body_barycentric_posvel(body, time, ephemeris=...): # -> tuple[CartesianRepresentation, CartesianRepresentation | Unbound] | CartesianRepresentation: + """Calculate the barycentric position and velocity of a solar system body. + + Parameters + ---------- + body : str or list of tuple + The solar system body for which to calculate positions. Can also be a + kernel specifier (list of 2-tuples) if the ``ephemeris`` is a JPL + kernel. + time : `~astropy.time.Time` + Time of observation. + ephemeris : str, optional + Ephemeris to use. By default, use the one set with + ``astropy.coordinates.solar_system_ephemeris.set`` + + Returns + ------- + position, velocity : tuple of `~astropy.coordinates.CartesianRepresentation` + Tuple of barycentric (ICRS) position and velocity. + + See Also + -------- + get_body_barycentric : to calculate position only. + This is faster by about a factor two for JPL kernels, but has no + speed advantage for the built-in ephemeris. + + Notes + ----- + {_EPHEMERIS_NOTE} + """ + ... + +def get_body_barycentric(body, time, ephemeris=...): # -> tuple[CartesianRepresentation, CartesianRepresentation | Unbound] | CartesianRepresentation: + """Calculate the barycentric position of a solar system body. + + Parameters + ---------- + body : str or list of tuple + The solar system body for which to calculate positions. Can also be a + kernel specifier (list of 2-tuples) if the ``ephemeris`` is a JPL + kernel. + time : `~astropy.time.Time` + Time of observation. + ephemeris : str, optional + Ephemeris to use. By default, use the one set with + ``astropy.coordinates.solar_system_ephemeris.set`` + + Returns + ------- + position : `~astropy.coordinates.CartesianRepresentation` + Barycentric (ICRS) position of the body in cartesian coordinates + + See Also + -------- + get_body_barycentric_posvel : to calculate both position and velocity. + + Notes + ----- + {_EPHEMERIS_NOTE} + """ + ... + +def get_body(body, time, location=..., ephemeris=...): # -> SkyCoord: + """ + Get a `~astropy.coordinates.SkyCoord` for a solar system body as observed + from a location on Earth in the `~astropy.coordinates.GCRS` reference + system. + + Parameters + ---------- + body : str or list of tuple + The solar system body for which to calculate positions. Can also be a + kernel specifier (list of 2-tuples) if the ``ephemeris`` is a JPL + kernel. + time : `~astropy.time.Time` + Time of observation. + location : `~astropy.coordinates.EarthLocation`, optional + Location of observer on the Earth. If not given, will be taken from + ``time`` (if not present, a geocentric observer will be assumed). + ephemeris : str, optional + Ephemeris to use. If not given, use the one set with + ``astropy.coordinates.solar_system_ephemeris.set`` (which is + set to 'builtin' by default). + + Returns + ------- + skycoord : `~astropy.coordinates.SkyCoord` + GCRS Coordinate for the body + + Notes + ----- + The coordinate returned is the apparent position, which is the position of + the body at time *t* minus the light travel time from the *body* to the + observing *location*. + + {_EPHEMERIS_NOTE} + """ + ... + +def get_moon(time, location=..., ephemeris=...): # -> SkyCoord: + """ + Get a `~astropy.coordinates.SkyCoord` for the Earth's Moon as observed + from a location on Earth in the `~astropy.coordinates.GCRS` reference + system. + + Parameters + ---------- + time : `~astropy.time.Time` + Time of observation + location : `~astropy.coordinates.EarthLocation` + Location of observer on the Earth. If none is supplied, taken from + ``time`` (if not present, a geocentric observer will be assumed). + ephemeris : str, optional + Ephemeris to use. If not given, use the one set with + ``astropy.coordinates.solar_system_ephemeris.set`` (which is + set to 'builtin' by default). + + Returns + ------- + skycoord : `~astropy.coordinates.SkyCoord` + GCRS Coordinate for the Moon + + Notes + ----- + The coordinate returned is the apparent position, which is the position of + the moon at time *t* minus the light travel time from the moon to the + observing *location*. + + {_EPHEMERIS_NOTE} + """ + ... + +deprecation_msg = ... diff --git a/typings/astropy/coordinates/spectral_coordinate.pyi b/typings/astropy/coordinates/spectral_coordinate.pyi new file mode 100644 index 0000000..59258f5 --- /dev/null +++ b/typings/astropy/coordinates/spectral_coordinate.pyi @@ -0,0 +1,282 @@ +""" +This type stub file was generated by pyright. +""" + +import astropy.units as u +from astropy.coordinates.spectral_quantity import SpectralQuantity +from astropy.utils.exceptions import AstropyUserWarning + +__all__ = ['SpectralCoord'] +class NoVelocityWarning(AstropyUserWarning): + ... + + +class NoDistanceWarning(AstropyUserWarning): + ... + + +KMS = ... +ZERO_VELOCITIES = ... +DEFAULT_DISTANCE = ... +__doctest_skip__ = ... +def update_differentials_to_match(original, velocity_reference, preserve_observer_frame=...): + """ + Given an original coordinate object, update the differentials so that + the final coordinate is at the same location as the original coordinate + but co-moving with the velocity reference object. + + If preserve_original_frame is set to True, the resulting object will be in + the frame of the original coordinate, otherwise it will be in the frame of + the velocity reference. + """ + ... + +def attach_zero_velocities(coord): + """ + Set the differentials to be stationary on a coordinate object. + """ + ... + +class SpectralCoord(SpectralQuantity): + """ + A spectral coordinate with its corresponding unit. + + .. note:: The |SpectralCoord| class is new in Astropy v4.1 and should be + considered experimental at this time. Note that we do not fully + support cases where the observer and target are moving + relativistically relative to each other, so care should be taken + in those cases. It is possible that there will be API changes in + future versions of Astropy based on user feedback. If you have + specific ideas for how it might be improved, please let us know + on the `astropy-dev mailing list`_ or at + http://feedback.astropy.org. + + Parameters + ---------- + value : ndarray or `~astropy.units.Quantity` or `SpectralCoord` + Spectral values, which should be either wavelength, frequency, + energy, wavenumber, or velocity values. + unit : unit-like + Unit for the given spectral values. + observer : `~astropy.coordinates.BaseCoordinateFrame` or `~astropy.coordinates.SkyCoord`, optional + The coordinate (position and velocity) of observer. If no velocities + are present on this object, the observer is assumed to be stationary + relative to the frame origin. + target : `~astropy.coordinates.BaseCoordinateFrame` or `~astropy.coordinates.SkyCoord`, optional + The coordinate (position and velocity) of target. If no velocities + are present on this object, the target is assumed to be stationary + relative to the frame origin. + radial_velocity : `~astropy.units.Quantity` ['speed'], optional + The radial velocity of the target with respect to the observer. This + can only be specified if ``redshift`` is not specified. + redshift : float, optional + The relativistic redshift of the target with respect to the observer. + This can only be specified if ``radial_velocity`` cannot be specified. + doppler_rest : `~astropy.units.Quantity`, optional + The rest value to use when expressing the spectral value as a velocity. + doppler_convention : str, optional + The Doppler convention to use when expressing the spectral value as a velocity. + """ + @u.quantity_input(radial_velocity=u.km / u.s) + def __new__(cls, value, unit=..., observer=..., target=..., radial_velocity=..., redshift=..., **kwargs): + ... + + def __array_finalize__(self, obj): # -> None: + ... + + def replicate(self, value=..., unit=..., observer=..., target=..., radial_velocity=..., redshift=..., doppler_convention=..., doppler_rest=..., copy=...): # -> Self@SpectralCoord: + """ + Return a replica of the `SpectralCoord`, optionally changing the + values or attributes. + + Note that no conversion is carried out by this method - this keeps + all the values and attributes the same, except for the ones explicitly + passed to this method which are changed. + + If ``copy`` is set to `True` then a full copy of the internal arrays + will be made. By default the replica will use a reference to the + original arrays when possible to save memory. + + Parameters + ---------- + value : ndarray or `~astropy.units.Quantity` or `SpectralCoord`, optional + Spectral values, which should be either wavelength, frequency, + energy, wavenumber, or velocity values. + unit : unit-like + Unit for the given spectral values. + observer : `~astropy.coordinates.BaseCoordinateFrame` or `~astropy.coordinates.SkyCoord`, optional + The coordinate (position and velocity) of observer. + target : `~astropy.coordinates.BaseCoordinateFrame` or `~astropy.coordinates.SkyCoord`, optional + The coordinate (position and velocity) of target. + radial_velocity : `~astropy.units.Quantity` ['speed'], optional + The radial velocity of the target with respect to the observer. + redshift : float, optional + The relativistic redshift of the target with respect to the observer. + doppler_rest : `~astropy.units.Quantity`, optional + The rest value to use when expressing the spectral value as a velocity. + doppler_convention : str, optional + The Doppler convention to use when expressing the spectral value as a velocity. + copy : bool, optional + If `True`, and ``value`` is not specified, the values are copied to + the new `SkyCoord` - otherwise a reference to the same values is used. + + Returns + ------- + sc : `SpectralCoord` object + Replica of this object + """ + ... + + @property + def quantity(self): # -> Quantity: + """ + Convert the ``SpectralCoord`` to a `~astropy.units.Quantity`. + Equivalent to ``self.view(u.Quantity)``. + + Returns + ------- + `~astropy.units.Quantity` + This object viewed as a `~astropy.units.Quantity`. + + """ + ... + + @property + def observer(self): # -> Any | BaseCoordinateFrame | SkyCoord | None: + """ + The coordinates of the observer. + + If set, and a target is set as well, this will override any explicit + radial velocity passed in. + + Returns + ------- + `~astropy.coordinates.BaseCoordinateFrame` + The astropy coordinate frame representing the observation. + """ + ... + + @observer.setter + def observer(self, value): # -> None: + ... + + @property + def target(self): # -> Any | BaseCoordinateFrame | SkyCoord | None: + """ + The coordinates of the target being observed. + + If set, and an observer is set as well, this will override any explicit + radial velocity passed in. + + Returns + ------- + `~astropy.coordinates.BaseCoordinateFrame` + The astropy coordinate frame representing the target. + """ + ... + + @target.setter + def target(self, value): # -> None: + ... + + @property + def radial_velocity(self): # -> Any: + """ + Radial velocity of target relative to the observer. + + Returns + ------- + `~astropy.units.Quantity` ['speed'] + Radial velocity of target. + + Notes + ----- + This is different from the ``.radial_velocity`` property of a + coordinate frame in that this calculates the radial velocity with + respect to the *observer*, not the origin of the frame. + """ + ... + + @property + def redshift(self): # -> Any: + """ + Redshift of target relative to observer. Calculated from the radial + velocity. + + Returns + ------- + `astropy.units.Quantity` + Redshift of target. + """ + ... + + @u.quantity_input(velocity=u.km / u.s) + def with_observer_stationary_relative_to(self, frame, velocity=..., preserve_observer_frame=...): # -> Self@SpectralCoord: + """ + A new `SpectralCoord` with the velocity of the observer altered, + but not the position. + + If a coordinate frame is specified, the observer velocities will be + modified to be stationary in the specified frame. If a coordinate + instance is specified, optionally with non-zero velocities, the + observer velocities will be updated so that the observer is co-moving + with the specified coordinates. + + Parameters + ---------- + frame : str, `~astropy.coordinates.BaseCoordinateFrame` or `~astropy.coordinates.SkyCoord` + The observation frame in which the observer will be stationary. This + can be the name of a frame (e.g. 'icrs'), a frame class, frame instance + with no data, or instance with data. This can optionally include + velocities. + velocity : `~astropy.units.Quantity` or `~astropy.coordinates.CartesianDifferential`, optional + If ``frame`` does not contain velocities, these can be specified as + a 3-element `~astropy.units.Quantity`. In the case where this is + also not specified, the velocities default to zero. + preserve_observer_frame : bool + If `True`, the final observer frame class will be the same as the + original one, and if `False` it will be the frame of the velocity + reference class. + + Returns + ------- + new_coord : `SpectralCoord` + The new coordinate object representing the spectral data + transformed based on the observer's new velocity frame. + """ + ... + + def with_radial_velocity_shift(self, target_shift=..., observer_shift=...): # -> Self@SpectralCoord: + """ + Apply a velocity shift to this spectral coordinate. + + The shift can be provided as a redshift (float value) or radial + velocity (`~astropy.units.Quantity` with physical type of 'speed'). + + Parameters + ---------- + target_shift : float or `~astropy.units.Quantity` ['speed'] + Shift value to apply to current target. + observer_shift : float or `~astropy.units.Quantity` ['speed'] + Shift value to apply to current observer. + + Returns + ------- + `SpectralCoord` + New spectral coordinate with the target/observer velocity changed + to incorporate the shift. This is always a new object even if + ``target_shift`` and ``observer_shift`` are both `None`. + """ + ... + + def to_rest(self): # -> Self@SpectralCoord: + """ + Transforms the spectral axis to the rest frame. + """ + ... + + def __repr__(self): # -> str: + ... + + + diff --git a/typings/astropy/coordinates/spectral_quantity.pyi b/typings/astropy/coordinates/spectral_quantity.pyi new file mode 100644 index 0000000..e0770e8 --- /dev/null +++ b/typings/astropy/coordinates/spectral_quantity.pyi @@ -0,0 +1,152 @@ +""" +This type stub file was generated by pyright. +""" + +from astropy.units.quantity import SpecificTypeQuantity +from astropy.units.decorators import quantity_input + +__all__ = ['SpectralQuantity'] +__doctest_skip__ = ... +KMS = ... +SPECTRAL_UNITS = ... +DOPPLER_CONVENTIONS = ... +class SpectralQuantity(SpecificTypeQuantity): + """ + One or more value(s) with spectral units. + + The spectral units should be those for frequencies, wavelengths, energies, + wavenumbers, or velocities (interpreted as Doppler velocities relative to a + rest spectral value). The advantage of using this class over the regular + `~astropy.units.Quantity` class is that in `SpectralQuantity`, the + ``u.spectral`` equivalency is enabled by default (allowing automatic + conversion between spectral units), and a preferred Doppler rest value and + convention can be stored for easy conversion to/from velocities. + + Parameters + ---------- + value : ndarray or `~astropy.units.Quantity` or `SpectralQuantity` + Spectral axis data values. + unit : unit-like + Unit for the given data. + doppler_rest : `~astropy.units.Quantity` ['speed'], optional + The rest value to use for conversions from/to velocities + doppler_convention : str, optional + The convention to use when converting the spectral data to/from + velocities. + """ + _equivalent_unit = ... + _include_easy_conversion_members = ... + def __new__(cls, value, unit=..., doppler_rest=..., doppler_convention=..., **kwargs): + ... + + def __array_finalize__(self, obj): # -> None: + ... + + def __quantity_subclass__(self, unit): # -> tuple[Type[SpectralQuantity], Literal[True]] | tuple[Type[Quantity], Literal[False]]: + ... + + def __array_ufunc__(self, function, method, *inputs, **kwargs): # -> Any | Self@SpectralQuantity | ndarray[Unknown, Unknown] | Quantity: + ... + + @property + def doppler_rest(self): # -> Any | None: + """ + The rest value of the spectrum used for transformations to/from + velocity space. + + Returns + ------- + `~astropy.units.Quantity` ['speed'] + Rest value as an astropy `~astropy.units.Quantity` object. + """ + ... + + @doppler_rest.setter + @quantity_input(value=SPECTRAL_UNITS) + def doppler_rest(self, value): # -> None: + """ + New rest value needed for velocity-space conversions. + + Parameters + ---------- + value : `~astropy.units.Quantity` ['speed'] + Rest value. + """ + ... + + @property + def doppler_convention(self): # -> Any | None: + """ + The defined convention for conversions to/from velocity space. + + Returns + ------- + str + One of 'optical', 'radio', or 'relativistic' representing the + equivalency used in the unit conversions. + """ + ... + + @doppler_convention.setter + def doppler_convention(self, value): # -> None: + """ + New velocity convention used for velocity space conversions. + + Parameters + ---------- + value + + Notes + ----- + More information on the equations dictating the transformations can be + found in the astropy documentation [1]_. + + References + ---------- + .. [1] Astropy documentation: https://docs.astropy.org/en/stable/units/equivalencies.html#spectral-doppler-equivalencies + + """ + ... + + @quantity_input(doppler_rest=SPECTRAL_UNITS) + def to(self, unit, equivalencies=..., doppler_rest=..., doppler_convention=...): # -> Self@SpectralQuantity | Any: + """ + Return a new `~astropy.coordinates.SpectralQuantity` object with the specified unit. + + By default, the ``spectral`` equivalency will be enabled, as well as + one of the Doppler equivalencies if converting to/from velocities. + + Parameters + ---------- + unit : unit-like + An object that represents the unit to convert to. Must be + an `~astropy.units.UnitBase` object or a string parseable + by the `~astropy.units` package, and should be a spectral unit. + equivalencies : list of `~astropy.units.equivalencies.Equivalency`, optional + A list of equivalence pairs to try if the units are not + directly convertible (along with spectral). + See :ref:`astropy:unit_equivalencies`. + If not provided or ``[]``, spectral equivalencies will be used. + If `None`, no equivalencies will be applied at all, not even any + set globally or within a context. + doppler_rest : `~astropy.units.Quantity` ['speed'], optional + The rest value used when converting to/from velocities. This will + also be set at an attribute on the output + `~astropy.coordinates.SpectralQuantity`. + doppler_convention : {'relativistic', 'optical', 'radio'}, optional + The Doppler convention used when converting to/from velocities. + This will also be set at an attribute on the output + `~astropy.coordinates.SpectralQuantity`. + + Returns + ------- + `SpectralQuantity` + New spectral coordinate object with data converted to the new unit. + """ + ... + + def to_value(self, unit=..., *args, **kwargs): # -> ndarray[Unknown, Unknown] | Any: + ... + + + diff --git a/typings/astropy/coordinates/transformations.pyi b/typings/astropy/coordinates/transformations.pyi new file mode 100644 index 0000000..702fe6e --- /dev/null +++ b/typings/astropy/coordinates/transformations.pyi @@ -0,0 +1,680 @@ +""" +This type stub file was generated by pyright. +""" + +from abc import ABCMeta, abstractmethod +from contextlib import contextmanager + +""" +This module contains a general framework for defining graphs of transformations +between coordinates, suitable for either spatial coordinates or more generalized +coordinate systems. + +The fundamental idea is that each class is a node in the transformation graph, +and transitions from one node to another are defined as functions (or methods) +wrapped in transformation objects. + +This module also includes more specific transformation classes for +celestial/spatial coordinate frames, generally focused around matrix-style +transformations that are typically how the algorithms are defined. +""" +__all__ = ['TransformGraph', 'CoordinateTransform', 'FunctionTransform', 'BaseAffineTransform', 'AffineTransform', 'StaticMatrixTransform', 'DynamicMatrixTransform', 'FunctionTransformWithFiniteDifference', 'CompositeTransform'] +def frame_attrs_from_set(frame_set): # -> dict[Unknown, Unknown]: + """ + A `dict` of all the attributes of all frame classes in this + `TransformGraph`. + + Broken out of the class so this can be called on a temporary frame set to + validate new additions to the transform graph before actually adding them. + """ + ... + +def frame_comps_from_set(frame_set): # -> set[Unknown]: + """ + A `set` of all component names every defined within any frame class in + this `TransformGraph`. + + Broken out of the class so this can be called on a temporary frame set to + validate new additions to the transform graph before actually adding them. + """ + ... + +class TransformGraph: + """ + A graph representing the paths between coordinate frames. + """ + def __init__(self) -> None: + ... + + @property + def frame_set(self): # -> set[Unknown]: + """ + A `set` of all the frame classes present in this `TransformGraph`. + """ + ... + + @property + def frame_attributes(self): # -> dict[Unknown, Unknown]: + """ + A `dict` of all the attributes of all frame classes in this + `TransformGraph`. + """ + ... + + @property + def frame_component_names(self): # -> set[Unknown]: + """ + A `set` of all component names every defined within any frame class in + this `TransformGraph`. + """ + ... + + def invalidate_cache(self): # -> None: + """ + Invalidates the cache that stores optimizations for traversing the + transform graph. This is called automatically when transforms + are added or removed, but will need to be called manually if + weights on transforms are modified inplace. + """ + ... + + def add_transform(self, fromsys, tosys, transform): # -> None: + """ + Add a new coordinate transformation to the graph. + + Parameters + ---------- + fromsys : class + The coordinate frame class to start from. + tosys : class + The coordinate frame class to transform into. + transform : `CoordinateTransform` + The transformation object. Typically a `CoordinateTransform` object, + although it may be some other callable that is called with the same + signature. + + Raises + ------ + TypeError + If ``fromsys`` or ``tosys`` are not classes or ``transform`` is + not callable. + """ + ... + + def remove_transform(self, fromsys, tosys, transform): # -> None: + """ + Removes a coordinate transform from the graph. + + Parameters + ---------- + fromsys : class or None + The coordinate frame *class* to start from. If `None`, + ``transform`` will be searched for and removed (``tosys`` must + also be `None`). + tosys : class or None + The coordinate frame *class* to transform into. If `None`, + ``transform`` will be searched for and removed (``fromsys`` must + also be `None`). + transform : callable or None + The transformation object to be removed or `None`. If `None` + and ``tosys`` and ``fromsys`` are supplied, there will be no + check to ensure the correct object is removed. + """ + ... + + def find_shortest_path(self, fromsys, tosys): # -> tuple[list[Unknown], Literal[0]] | tuple[list[Unknown], float] | tuple[None, float]: + """ + Computes the shortest distance along the transform graph from + one system to another. + + Parameters + ---------- + fromsys : class + The coordinate frame class to start from. + tosys : class + The coordinate frame class to transform into. + + Returns + ------- + path : list of class or None + The path from ``fromsys`` to ``tosys`` as an in-order sequence + of classes. This list includes *both* ``fromsys`` and + ``tosys``. Is `None` if there is no possible path. + distance : float or int + The total distance/priority from ``fromsys`` to ``tosys``. If + priorities are not set this is the number of transforms + needed. Is ``inf`` if there is no possible path. + """ + ... + + def get_transform(self, fromsys, tosys): # -> None: + """ + Generates and returns the `CompositeTransform` for a transformation + between two coordinate systems. + + Parameters + ---------- + fromsys : class + The coordinate frame class to start from. + tosys : class + The coordinate frame class to transform into. + + Returns + ------- + trans : `CompositeTransform` or None + If there is a path from ``fromsys`` to ``tosys``, this is a + transform object for that path. If no path could be found, this is + `None`. + + Notes + ----- + This function always returns a `CompositeTransform`, because + `CompositeTransform` is slightly more adaptable in the way it can be + called than other transform classes. Specifically, it takes care of + intermediate steps of transformations in a way that is consistent with + 1-hop transformations. + + """ + ... + + def lookup_name(self, name): # -> None: + """ + Tries to locate the coordinate class with the provided alias. + + Parameters + ---------- + name : str + The alias to look up. + + Returns + ------- + `BaseCoordinateFrame` subclass + The coordinate class corresponding to the ``name`` or `None` if + no such class exists. + """ + ... + + def get_names(self): # -> list[Unknown]: + """ + Returns all available transform names. They will all be + valid arguments to `lookup_name`. + + Returns + ------- + nms : list + The aliases for coordinate systems. + """ + ... + + def to_dot_graph(self, priorities=..., addnodes=..., savefn=..., savelayout=..., saveformat=..., color_edges=...): # -> str: + """ + Converts this transform graph to the graphviz_ DOT format. + + Optionally saves it (requires `graphviz`_ be installed and on your path). + + .. _graphviz: http://www.graphviz.org/ + + Parameters + ---------- + priorities : bool + If `True`, show the priority values for each transform. Otherwise, + the will not be included in the graph. + addnodes : sequence of str + Additional coordinate systems to add (this can include systems + already in the transform graph, but they will only appear once). + savefn : None or str + The file name to save this graph to or `None` to not save + to a file. + savelayout : str + The graphviz program to use to layout the graph (see + graphviz_ for details) or 'plain' to just save the DOT graph + content. Ignored if ``savefn`` is `None`. + saveformat : str + The graphviz output format. (e.g. the ``-Txxx`` option for + the command line program - see graphviz docs for details). + Ignored if ``savefn`` is `None`. + color_edges : bool + Color the edges between two nodes (frames) based on the type of + transform. ``FunctionTransform``: red, ``StaticMatrixTransform``: + blue, ``DynamicMatrixTransform``: green. + + Returns + ------- + dotgraph : str + A string with the DOT format graph. + """ + ... + + def to_networkx_graph(self): + """ + Converts this transform graph into a networkx graph. + + .. note:: + You must have the `networkx `_ + package installed for this to work. + + Returns + ------- + nxgraph : ``networkx.Graph`` + This `TransformGraph` as a `networkx.Graph `_. + """ + ... + + def transform(self, transcls, fromsys, tosys, priority=..., **kwargs): # -> (func: Unknown) -> Unknown: + """ + A function decorator for defining transformations. + + .. note:: + If decorating a static method of a class, ``@staticmethod`` + should be added *above* this decorator. + + Parameters + ---------- + transcls : class + The class of the transformation object to create. + fromsys : class + The coordinate frame class to start from. + tosys : class + The coordinate frame class to transform into. + priority : float or int + The priority if this transform when finding the shortest + coordinate transform path - large numbers are lower priorities. + + Additional keyword arguments are passed into the ``transcls`` + constructor. + + Returns + ------- + deco : function + A function that can be called on another function as a decorator + (see example). + + Notes + ----- + This decorator assumes the first argument of the ``transcls`` + initializer accepts a callable, and that the second and third + are ``fromsys`` and ``tosys``. If this is not true, you should just + initialize the class manually and use `add_transform` instead of + using this decorator. + + Examples + -------- + :: + + graph = TransformGraph() + + class Frame1(BaseCoordinateFrame): + ... + + class Frame2(BaseCoordinateFrame): + ... + + @graph.transform(FunctionTransform, Frame1, Frame2) + def f1_to_f2(f1_obj): + ... do something with f1_obj ... + return f2_obj + + """ + ... + + @contextmanager + def impose_finite_difference_dt(self, dt): # -> Generator[None, None, None]: + """ + Context manager to impose a finite-difference time step on all applicable transformations + + For each transformation in this transformation graph that has the attribute + ``finite_difference_dt``, that attribute is set to the provided value. The only standard + transformation with this attribute is + `~astropy.coordinates.transformations.FunctionTransformWithFiniteDifference`. + + Parameters + ---------- + dt : `~astropy.units.Quantity` ['time'] or callable + If a quantity, this is the size of the differential used to do the finite difference. + If a callable, should accept ``(fromcoord, toframe)`` and return the ``dt`` value. + """ + ... + + + +class CoordinateTransform(metaclass=ABCMeta): + """ + An object that transforms a coordinate from one system to another. + Subclasses must implement `__call__` with the provided signature. + They should also call this superclass's ``__init__`` in their + ``__init__``. + + Parameters + ---------- + fromsys : `~astropy.coordinates.BaseCoordinateFrame` subclass + The coordinate frame class to start from. + tosys : `~astropy.coordinates.BaseCoordinateFrame` subclass + The coordinate frame class to transform into. + priority : float or int + The priority if this transform when finding the shortest + coordinate transform path - large numbers are lower priorities. + register_graph : `TransformGraph` or None + A graph to register this transformation with on creation, or + `None` to leave it unregistered. + """ + def __init__(self, fromsys, tosys, priority=..., register_graph=...) -> None: + ... + + def register(self, graph): # -> None: + """ + Add this transformation to the requested Transformation graph, + replacing anything already connecting these two coordinates. + + Parameters + ---------- + graph : `TransformGraph` object + The graph to register this transformation with. + """ + ... + + def unregister(self, graph): # -> None: + """ + Remove this transformation from the requested transformation + graph. + + Parameters + ---------- + graph : a TransformGraph object + The graph to unregister this transformation from. + + Raises + ------ + ValueError + If this is not currently in the transform graph. + """ + ... + + @abstractmethod + def __call__(self, fromcoord, toframe): # -> None: + """ + Does the actual coordinate transformation from the ``fromsys`` class to + the ``tosys`` class. + + Parameters + ---------- + fromcoord : `~astropy.coordinates.BaseCoordinateFrame` subclass instance + An object of class matching ``fromsys`` that is to be transformed. + toframe : object + An object that has the attributes necessary to fully specify the + frame. That is, it must have attributes with names that match the + keys of the dictionary that ``tosys.get_frame_attr_names()`` + returns. Typically this is of class ``tosys``, but it *might* be + some other class as long as it has the appropriate attributes. + + Returns + ------- + tocoord : `BaseCoordinateFrame` subclass instance + The new coordinate after the transform has been applied. + """ + ... + + + +class FunctionTransform(CoordinateTransform): + """ + A coordinate transformation defined by a function that accepts a + coordinate object and returns the transformed coordinate object. + + Parameters + ---------- + func : callable + The transformation function. Should have a call signature + ``func(formcoord, toframe)``. Note that, unlike + `CoordinateTransform.__call__`, ``toframe`` is assumed to be of type + ``tosys`` for this function. + fromsys : class + The coordinate frame class to start from. + tosys : class + The coordinate frame class to transform into. + priority : float or int + The priority if this transform when finding the shortest + coordinate transform path - large numbers are lower priorities. + register_graph : `TransformGraph` or None + A graph to register this transformation with on creation, or + `None` to leave it unregistered. + + Raises + ------ + TypeError + If ``func`` is not callable. + ValueError + If ``func`` cannot accept two arguments. + + + """ + def __init__(self, func, fromsys, tosys, priority=..., register_graph=...) -> None: + ... + + def __call__(self, fromcoord, toframe): + ... + + + +class FunctionTransformWithFiniteDifference(FunctionTransform): + r""" + A coordinate transformation that works like a `FunctionTransform`, but + computes velocity shifts based on the finite-difference relative to one of + the frame attributes. Note that the transform function should *not* change + the differential at all in this case, as any differentials will be + overridden. + + When a differential is in the from coordinate, the finite difference + calculation has two components. The first part is simple the existing + differential, but re-orientation (using finite-difference techniques) to + point in the direction the velocity vector has in the *new* frame. The + second component is the "induced" velocity. That is, the velocity + intrinsic to the frame itself, estimated by shifting the frame using the + ``finite_difference_frameattr_name`` frame attribute a small amount + (``finite_difference_dt``) in time and re-calculating the position. + + Parameters + ---------- + finite_difference_frameattr_name : str or None + The name of the frame attribute on the frames to use for the finite + difference. Both the to and the from frame will be checked for this + attribute, but only one needs to have it. If None, no velocity + component induced from the frame itself will be included - only the + re-orientation of any existing differential. + finite_difference_dt : `~astropy.units.Quantity` ['time'] or callable + If a quantity, this is the size of the differential used to do the + finite difference. If a callable, should accept + ``(fromcoord, toframe)`` and return the ``dt`` value. + symmetric_finite_difference : bool + If True, the finite difference is computed as + :math:`\frac{x(t + \Delta t / 2) - x(t + \Delta t / 2)}{\Delta t}`, or + if False, :math:`\frac{x(t + \Delta t) - x(t)}{\Delta t}`. The latter + case has slightly better performance (and more stable finite difference + behavior). + + All other parameters are identical to the initializer for + `FunctionTransform`. + + """ + def __init__(self, func, fromsys, tosys, priority=..., register_graph=..., finite_difference_frameattr_name=..., finite_difference_dt=..., symmetric_finite_difference=...) -> None: + ... + + @property + def finite_difference_frameattr_name(self): + ... + + @finite_difference_frameattr_name.setter + def finite_difference_frameattr_name(self, value): # -> None: + ... + + def __call__(self, fromcoord, toframe): + ... + + + +class BaseAffineTransform(CoordinateTransform): + """Base class for common functionality between the ``AffineTransform``-type + subclasses. + + This base class is needed because ``AffineTransform`` and the matrix + transform classes share the ``__call__()`` method, but differ in how they + generate the affine parameters. ``StaticMatrixTransform`` passes in a + matrix stored as a class attribute, and both of the matrix transforms pass + in ``None`` for the offset. Hence, user subclasses would likely want to + subclass this (rather than ``AffineTransform``) if they want to provide + alternative transformations using this machinery. + """ + def __call__(self, fromcoord, toframe): + ... + + + +class AffineTransform(BaseAffineTransform): + """ + A coordinate transformation specified as a function that yields a 3 x 3 + cartesian transformation matrix and a tuple of displacement vectors. + + See `~astropy.coordinates.builtin_frames.galactocentric.Galactocentric` for + an example. + + Parameters + ---------- + transform_func : callable + A callable that has the signature ``transform_func(fromcoord, toframe)`` + and returns: a (3, 3) matrix that operates on ``fromcoord`` in a + Cartesian representation, and a ``CartesianRepresentation`` with + (optionally) an attached velocity ``CartesianDifferential`` to represent + a translation and offset in velocity to apply after the matrix + operation. + fromsys : class + The coordinate frame class to start from. + tosys : class + The coordinate frame class to transform into. + priority : float or int + The priority if this transform when finding the shortest + coordinate transform path - large numbers are lower priorities. + register_graph : `TransformGraph` or None + A graph to register this transformation with on creation, or + `None` to leave it unregistered. + + Raises + ------ + TypeError + If ``transform_func`` is not callable + + """ + def __init__(self, transform_func, fromsys, tosys, priority=..., register_graph=...) -> None: + ... + + + +class StaticMatrixTransform(BaseAffineTransform): + """ + A coordinate transformation defined as a 3 x 3 cartesian + transformation matrix. + + This is distinct from DynamicMatrixTransform in that this kind of matrix is + independent of frame attributes. That is, it depends *only* on the class of + the frame. + + Parameters + ---------- + matrix : array-like or callable + A 3 x 3 matrix for transforming 3-vectors. In most cases will + be unitary (although this is not strictly required). If a callable, + will be called *with no arguments* to get the matrix. + fromsys : class + The coordinate frame class to start from. + tosys : class + The coordinate frame class to transform into. + priority : float or int + The priority if this transform when finding the shortest + coordinate transform path - large numbers are lower priorities. + register_graph : `TransformGraph` or None + A graph to register this transformation with on creation, or + `None` to leave it unregistered. + + Raises + ------ + ValueError + If the matrix is not 3 x 3 + + """ + def __init__(self, matrix, fromsys, tosys, priority=..., register_graph=...) -> None: + ... + + + +class DynamicMatrixTransform(BaseAffineTransform): + """ + A coordinate transformation specified as a function that yields a + 3 x 3 cartesian transformation matrix. + + This is similar to, but distinct from StaticMatrixTransform, in that the + matrix for this class might depend on frame attributes. + + Parameters + ---------- + matrix_func : callable + A callable that has the signature ``matrix_func(fromcoord, toframe)`` and + returns a 3 x 3 matrix that converts ``fromcoord`` in a cartesian + representation to the new coordinate system. + fromsys : class + The coordinate frame class to start from. + tosys : class + The coordinate frame class to transform into. + priority : float or int + The priority if this transform when finding the shortest + coordinate transform path - large numbers are lower priorities. + register_graph : `TransformGraph` or None + A graph to register this transformation with on creation, or + `None` to leave it unregistered. + + Raises + ------ + TypeError + If ``matrix_func`` is not callable + + """ + def __init__(self, matrix_func, fromsys, tosys, priority=..., register_graph=...) -> None: + ... + + + +class CompositeTransform(CoordinateTransform): + """ + A transformation constructed by combining together a series of single-step + transformations. + + Note that the intermediate frame objects are constructed using any frame + attributes in ``toframe`` or ``fromframe`` that overlap with the intermediate + frame (``toframe`` favored over ``fromframe`` if there's a conflict). Any frame + attributes that are not present use the defaults. + + Parameters + ---------- + transforms : sequence of `CoordinateTransform` object + The sequence of transformations to apply. + fromsys : class + The coordinate frame class to start from. + tosys : class + The coordinate frame class to transform into. + priority : float or int + The priority if this transform when finding the shortest + coordinate transform path - large numbers are lower priorities. + register_graph : `TransformGraph` or None + A graph to register this transformation with on creation, or + `None` to leave it unregistered. + collapse_static_mats : bool + If `True`, consecutive `StaticMatrixTransform` will be collapsed into a + single transformation to speed up the calculation. + + """ + def __init__(self, transforms, fromsys, tosys, priority=..., register_graph=..., collapse_static_mats=...) -> None: + ... + + def __call__(self, fromcoord, toframe): + ... + + + +trans_to_color = ... diff --git a/typings/astropy/cosmology/__init__.pyi b/typings/astropy/cosmology/__init__.pyi new file mode 100644 index 0000000..73cde69 --- /dev/null +++ b/typings/astropy/cosmology/__init__.pyi @@ -0,0 +1,36 @@ +""" +This type stub file was generated by pyright. +""" + +from . import core, flrw, funcs, io, parameter, realizations, units, utils +from .core import * +from .flrw import * +from .funcs import * +from .parameter import * +from .realizations import available, default_cosmology +from .utils import * + +""" astropy.cosmology contains classes and functions for cosmological +distance measures and other cosmology-related calculations. + +See the `Astropy documentation +`_ for more +detailed usage examples and references. + +""" +__all__ = (core.__all__ + flrw.__all__ + realizations.__all__ + ["units"] + funcs.__all__ + parameter.__all__ + utils.__all__) +def __getattr__(name): # -> Any: + """Get realizations using lazy import from + `PEP 562 `_. + + Raises + ------ + AttributeError + If "name" is not in :mod:`astropy.cosmology.realizations` + """ + ... + +def __dir__(): # -> list[str]: + """Directory, including lazily-imported objects.""" + ... + diff --git a/typings/astropy/cosmology/connect.pyi b/typings/astropy/cosmology/connect.pyi new file mode 100644 index 0000000..3ff98ce --- /dev/null +++ b/typings/astropy/cosmology/connect.pyi @@ -0,0 +1,192 @@ +""" +This type stub file was generated by pyright. +""" + +from astropy.io import registry as io_registry + +__all__ = ["CosmologyRead", "CosmologyWrite", "CosmologyFromFormat", "CosmologyToFormat"] +__doctest_skip__ = ... +readwrite_registry = ... +class CosmologyRead(io_registry.UnifiedReadWrite): + """Read and parse data to a `~astropy.cosmology.Cosmology`. + + This function provides the Cosmology interface to the Astropy unified I/O + layer. This allows easily reading a file in supported data formats using + syntax such as:: + + >>> from astropy.cosmology import Cosmology + >>> cosmo1 = Cosmology.read('') + + When the ``read`` method is called from a subclass the subclass will + provide a keyword argument ``cosmology=`` to the registered read + method. The method uses this cosmology class, regardless of the class + indicated in the file, and sets parameters' default values from the class' + signature. + + Get help on the available readers using the ``help()`` method:: + + >>> Cosmology.read.help() # Get help reading and list supported formats + >>> Cosmology.read.help(format='') # Get detailed help on a format + >>> Cosmology.read.list_formats() # Print list of available formats + + See also: https://docs.astropy.org/en/stable/io/unified.html + + Parameters + ---------- + *args + Positional arguments passed through to data reader. If supplied the + first argument is typically the input filename. + format : str (optional, keyword-only) + File format specifier. + **kwargs + Keyword arguments passed through to data reader. + + Returns + ------- + out : `~astropy.cosmology.Cosmology` subclass instance + `~astropy.cosmology.Cosmology` corresponding to file contents. + + Notes + ----- + """ + def __init__(self, instance, cosmo_cls) -> None: + ... + + def __call__(self, *args, **kwargs): + ... + + + +class CosmologyWrite(io_registry.UnifiedReadWrite): + """Write this Cosmology object out in the specified format. + + This function provides the Cosmology interface to the astropy unified I/O + layer. This allows easily writing a file in supported data formats + using syntax such as:: + + >>> from astropy.cosmology import Planck18 + >>> Planck18.write('') + + Get help on the available writers for ``Cosmology`` using the ``help()`` + method:: + + >>> Cosmology.write.help() # Get help writing and list supported formats + >>> Cosmology.write.help(format='') # Get detailed help on format + >>> Cosmology.write.list_formats() # Print list of available formats + + Parameters + ---------- + *args + Positional arguments passed through to data writer. If supplied the + first argument is the output filename. + format : str (optional, keyword-only) + File format specifier. + **kwargs + Keyword arguments passed through to data writer. + + Notes + ----- + """ + def __init__(self, instance, cls) -> None: + ... + + def __call__(self, *args, **kwargs): # -> None: + ... + + + +convert_registry = ... +class CosmologyFromFormat(io_registry.UnifiedReadWrite): + """Transform object to a `~astropy.cosmology.Cosmology`. + + This function provides the Cosmology interface to the Astropy unified I/O + layer. This allows easily parsing supported data formats using + syntax such as:: + + >>> from astropy.cosmology import Cosmology + >>> cosmo1 = Cosmology.from_format(cosmo_mapping, format='mapping') + + When the ``from_format`` method is called from a subclass the subclass will + provide a keyword argument ``cosmology=`` to the registered parser. + The method uses this cosmology class, regardless of the class indicated in + the data, and sets parameters' default values from the class' signature. + + Get help on the available readers using the ``help()`` method:: + + >>> Cosmology.from_format.help() # Get help and list supported formats + >>> Cosmology.from_format.help('') # Get detailed help on a format + >>> Cosmology.from_format.list_formats() # Print list of available formats + + See also: https://docs.astropy.org/en/stable/io/unified.html + + Parameters + ---------- + obj : object + The object to parse according to 'format' + *args + Positional arguments passed through to data parser. + format : str or None, optional keyword-only + Object format specifier. For `None` (default) CosmologyFromFormat tries + to identify the correct format. + **kwargs + Keyword arguments passed through to data parser. + Parsers should accept the following keyword arguments: + + - cosmology : the class (or string name thereof) to use / check when + constructing the cosmology instance. + + Returns + ------- + out : `~astropy.cosmology.Cosmology` subclass instance + `~astropy.cosmology.Cosmology` corresponding to ``obj`` contents. + + """ + def __init__(self, instance, cosmo_cls) -> None: + ... + + def __call__(self, obj, *args, format=..., **kwargs): + ... + + + +class CosmologyToFormat(io_registry.UnifiedReadWrite): + """Transform this Cosmology to another format. + + This function provides the Cosmology interface to the astropy unified I/O + layer. This allows easily transforming to supported data formats + using syntax such as:: + + >>> from astropy.cosmology import Planck18 + >>> Planck18.to_format("mapping") + {'cosmology': astropy.cosmology.core.FlatLambdaCDM, + 'name': 'Planck18', + 'H0': , + 'Om0': 0.30966, + ... + + Get help on the available representations for ``Cosmology`` using the + ``help()`` method:: + + >>> Cosmology.to_format.help() # Get help and list supported formats + >>> Cosmology.to_format.help('') # Get detailed help on format + >>> Cosmology.to_format.list_formats() # Print list of available formats + + Parameters + ---------- + format : str + Format specifier. + *args + Positional arguments passed through to data writer. If supplied the + first argument is the output filename. + **kwargs + Keyword arguments passed through to data writer. + + """ + def __init__(self, instance, cls) -> None: + ... + + def __call__(self, format, *args, **kwargs): + ... + + + diff --git a/typings/astropy/cosmology/core.pyi b/typings/astropy/cosmology/core.pyi new file mode 100644 index 0000000..0225799 --- /dev/null +++ b/typings/astropy/cosmology/core.pyi @@ -0,0 +1,307 @@ +""" +This type stub file was generated by pyright. +""" + +import abc +from typing import Mapping, Optional, Type, TypeVar + +__all__ = ["Cosmology", "CosmologyError", "FlatCosmologyMixin"] +__doctest_requires__ = ... +_COSMOLOGY_CLASSES = ... +_CosmoT = TypeVar("_CosmoT", bound="Cosmology") +_FlatCosmoT = TypeVar("_FlatCosmoT", bound="FlatCosmologyMixin") +class CosmologyError(Exception): + ... + + +class Cosmology(metaclass=abc.ABCMeta): + """Base-class for all Cosmologies. + + Parameters + ---------- + *args + Arguments into the cosmology; used by subclasses, not this base class. + name : str or None (optional, keyword-only) + The name of the cosmology. + meta : dict or None (optional, keyword-only) + Metadata for the cosmology, e.g., a reference. + **kwargs + Arguments into the cosmology; used by subclasses, not this base class. + + Notes + ----- + Class instances are static -- you cannot (and should not) change the values + of the parameters. That is, all of the above attributes (except meta) are + read only. + + For details on how to create performant custom subclasses, see the + documentation on :ref:`astropy-cosmology-fast-integrals`. + """ + meta = ... + from_format = ... + to_format = ... + read = ... + write = ... + __parameters__ = ... + __all_parameters__ = ... + def __init_subclass__(cls): # -> None: + ... + + def __init__(self, name=..., meta=...) -> None: + ... + + @property + def name(self): # -> str | None: + """The name of the Cosmology instance.""" + ... + + @property + @abc.abstractmethod + def is_flat(self): + """ + Return bool; `True` if the cosmology is flat. + This is abstract and must be defined in subclasses. + """ + ... + + def clone(self, *, meta=..., **kwargs): # -> Self@Cosmology: + """Returns a copy of this object with updated parameters, as specified. + + This cannot be used to change the type of the cosmology, so ``clone()`` + cannot be used to change between flat and non-flat cosmologies. + + Parameters + ---------- + meta : mapping or None (optional, keyword-only) + Metadata that will update the current metadata. + **kwargs + Cosmology parameter (and name) modifications. If any parameter is + changed and a new name is not given, the name will be set to "[old + name] (modified)". + + Returns + ------- + newcosmo : `~astropy.cosmology.Cosmology` subclass instance + A new instance of this class with updated parameters as specified. + If no arguments are given, then a reference to this object is + returned instead of copy. + + Examples + -------- + To make a copy of the ``Planck13`` cosmology with a different matter + density (``Om0``), and a new name: + + >>> from astropy.cosmology import Planck13 + >>> Planck13.clone(name="Modified Planck 2013", Om0=0.35) + FlatLambdaCDM(name="Modified Planck 2013", H0=67.77 km / (Mpc s), + Om0=0.35, ... + + If no name is specified, the new name will note the modification. + + >>> Planck13.clone(Om0=0.35).name + 'Planck13 (modified)' + """ + ... + + def is_equivalent(self, other, *, format=...): # -> _NotImplementedType | bool: + r"""Check equivalence between Cosmologies. + + Two cosmologies may be equivalent even if not the same class. + For example, an instance of ``LambdaCDM`` might have :math:`\Omega_0=1` + and :math:`\Omega_k=0` and therefore be flat, like ``FlatLambdaCDM``. + + Parameters + ---------- + other : `~astropy.cosmology.Cosmology` subclass instance + The object in which to compare. + format : bool or None or str, optional keyword-only + Whether to allow, before equivalence is checked, the object to be + converted to a |Cosmology|. This allows, e.g. a |Table| to be + equivalent to a Cosmology. + `False` (default) will not allow conversion. `True` or `None` will, + and will use the auto-identification to try to infer the correct + format. A `str` is assumed to be the correct format to use when + converting. + + Returns + ------- + bool + True if cosmologies are equivalent, False otherwise. + + Examples + -------- + Two cosmologies may be equivalent even if not of the same class. + In this examples the ``LambdaCDM`` has ``Ode0`` set to the same value + calculated in ``FlatLambdaCDM``. + + >>> import astropy.units as u + >>> from astropy.cosmology import LambdaCDM, FlatLambdaCDM + >>> cosmo1 = LambdaCDM(70 * (u.km/u.s/u.Mpc), 0.3, 0.7) + >>> cosmo2 = FlatLambdaCDM(70 * (u.km/u.s/u.Mpc), 0.3) + >>> cosmo1.is_equivalent(cosmo2) + True + + While in this example, the cosmologies are not equivalent. + + >>> cosmo3 = FlatLambdaCDM(70 * (u.km/u.s/u.Mpc), 0.3, Tcmb0=3 * u.K) + >>> cosmo3.is_equivalent(cosmo2) + False + + Also, using the keyword argument, the notion of equivalence is extended + to any Python object that can be converted to a |Cosmology|. + + >>> from astropy.cosmology import Planck18 + >>> tbl = Planck18.to_format("astropy.table") + >>> Planck18.is_equivalent(tbl, format=True) + True + + The list of valid formats, e.g. the |Table| in this example, may be + checked with ``Cosmology.from_format.list_formats()``. + + As can be seen in the list of formats, not all formats can be + auto-identified by ``Cosmology.from_format.registry``. Objects of + these kinds can still be checked for equivalence, but the correct + format string must be used. + + >>> tbl = Planck18.to_format("yaml") + >>> Planck18.is_equivalent(tbl, format="yaml") + True + """ + ... + + def __equiv__(self, other): # -> _NotImplementedType | bool: + """Cosmology equivalence. Use ``.is_equivalent()`` for actual check! + + Parameters + ---------- + other : `~astropy.cosmology.Cosmology` subclass instance + The object in which to compare. + + Returns + ------- + bool or `NotImplemented` + `NotImplemented` if 'other' is from a different class. + `True` if 'other' is of the same class and has matching parameters + and parameter values. `False` otherwise. + """ + ... + + def __eq__(self, other) -> bool: + """Check equality between Cosmologies. + + Checks the Parameters and immutable fields (i.e. not "meta"). + + Parameters + ---------- + other : `~astropy.cosmology.Cosmology` subclass instance + The object in which to compare. + + Returns + ------- + bool + `True` if Parameters and names are the same, `False` otherwise. + """ + ... + + def __repr__(self): # -> str: + ... + + def __astropy_table__(self, cls, copy, **kwargs): + """Return a `~astropy.table.Table` of type ``cls``. + + Parameters + ---------- + cls : type + Astropy ``Table`` class or subclass. + copy : bool + Ignored. + **kwargs : dict, optional + Additional keyword arguments. Passed to ``self.to_format()``. + See ``Cosmology.to_format.help("astropy.table")`` for allowed kwargs. + + Returns + ------- + `astropy.table.Table` or subclass instance + Instance of type ``cls``. + """ + ... + + + +class FlatCosmologyMixin(metaclass=abc.ABCMeta): + """ + Mixin class for flat cosmologies. Do NOT instantiate directly. + Note that all instances of ``FlatCosmologyMixin`` are flat, but not all + flat cosmologies are instances of ``FlatCosmologyMixin``. As example, + ``LambdaCDM`` **may** be flat (for the a specific set of parameter values), + but ``FlatLambdaCDM`` **will** be flat. + """ + def __init_subclass__(cls: Type[_FlatCosmoT]) -> None: + ... + + _nonflat_cls_ = ... + @property + def is_flat(self): # -> Literal[True]: + """Return `True`, the cosmology is flat.""" + ... + + @abc.abstractmethod + def nonflat(self: _FlatCosmoT) -> _CosmoT: + """Return the equivalent non-flat-class instance of this cosmology.""" + ... + + def clone(self, *, meta: Optional[Mapping] = ..., to_nonflat: bool = ..., **kwargs): # -> Any: + """Returns a copy of this object with updated parameters, as specified. + + This cannot be used to change the type of the cosmology, except for + changing to the non-flat version of this cosmology. + + Parameters + ---------- + meta : mapping or None (optional, keyword-only) + Metadata that will update the current metadata. + to_nonflat : bool, optional keyword-only + Whether to change to the non-flat version of this cosmology. + **kwargs + Cosmology parameter (and name) modifications. If any parameter is + changed and a new name is not given, the name will be set to "[old + name] (modified)". + + Returns + ------- + newcosmo : `~astropy.cosmology.Cosmology` subclass instance + A new instance of this class with updated parameters as specified. + If no arguments are given, then a reference to this object is + returned instead of copy. + + Examples + -------- + To make a copy of the ``Planck13`` cosmology with a different matter + density (``Om0``), and a new name: + + >>> from astropy.cosmology import Planck13 + >>> Planck13.clone(name="Modified Planck 2013", Om0=0.35) + FlatLambdaCDM(name="Modified Planck 2013", H0=67.77 km / (Mpc s), + Om0=0.35, ... + + If no name is specified, the new name will note the modification. + + >>> Planck13.clone(Om0=0.35).name + 'Planck13 (modified)' + + The keyword 'to_nonflat' can be used to clone on the non-flat equivalent + cosmology. + + >>> Planck13.clone(to_nonflat=True) + LambdaCDM(name="Planck13", ... + + >>> Planck13.clone(H0=70, to_nonflat=True) + LambdaCDM(name="Planck13 (modified)", H0=70.0 km / (Mpc s), ... + """ + ... + + + +def __getattr__(attr): # -> Any: + ... + diff --git a/typings/astropy/cosmology/flrw/__init__.pyi b/typings/astropy/cosmology/flrw/__init__.pyi new file mode 100644 index 0000000..ba4d651 --- /dev/null +++ b/typings/astropy/cosmology/flrw/__init__.pyi @@ -0,0 +1,18 @@ +""" +This type stub file was generated by pyright. +""" + +from . import base, lambdacdm, w0cdm, w0wacdm, w0wzcdm, wpwazpcdm +from .base import * +from .lambdacdm import * +from .w0cdm import * +from .w0wacdm import * +from .w0wzcdm import * +from .wpwazpcdm import * + +"""Astropy FLRW classes.""" +__all__ = (base.__all__ + lambdacdm.__all__ + w0cdm.__all__ + w0wacdm.__all__ + wpwazpcdm.__all__ + w0wzcdm.__all__) +def __getattr__(attr): # -> Any: + """Lazy import deprecated private API.""" + ... + diff --git a/typings/astropy/cosmology/flrw/base.pyi b/typings/astropy/cosmology/flrw/base.pyi new file mode 100644 index 0000000..caeb02c --- /dev/null +++ b/typings/astropy/cosmology/flrw/base.pyi @@ -0,0 +1,1048 @@ +""" +This type stub file was generated by pyright. +""" + +from abc import abstractmethod +from typing import Any, Mapping, Optional, TypeVar +from astropy.cosmology.core import Cosmology, FlatCosmologyMixin +from astropy.cosmology.utils import vectorize_redshift_method +from astropy.utils.compat.optional_deps import HAS_SCIPY +from astropy.utils.decorators import lazyproperty + +if HAS_SCIPY: + ... +else: + def quad(*args, **kwargs): + ... + +__all__ = ["FLRW", "FlatFLRWMixin"] +__doctest_requires__ = ... +_H0units_to_invs = ... +_sec_to_Gyr = ... +_critdens_const = ... +_radian_in_arcsec = ... +_radian_in_arcmin = ... +_a_B_c2 = ... +_kB_evK = ... +_FLRWT = TypeVar("_FLRWT", bound="FLRW") +_FlatFLRWMixinT = TypeVar("_FlatFLRWMixinT", bound="FlatFLRWMixin") +class FLRW(Cosmology): + """ + A class describing an isotropic and homogeneous + (Friedmann-Lemaitre-Robertson-Walker) cosmology. + + This is an abstract base class -- you cannot instantiate examples of this + class, but must work with one of its subclasses, such as + :class:`~astropy.cosmology.LambdaCDM` or :class:`~astropy.cosmology.wCDM`. + + Parameters + ---------- + H0 : float or scalar quantity-like ['frequency'] + Hubble constant at z = 0. If a float, must be in [km/sec/Mpc]. + + Om0 : float + Omega matter: density of non-relativistic matter in units of the + critical density at z=0. Note that this does not include massive + neutrinos. + + Ode0 : float + Omega dark energy: density of dark energy in units of the critical + density at z=0. + + Tcmb0 : float or scalar quantity-like ['temperature'], optional + Temperature of the CMB z=0. If a float, must be in [K]. Default: 0 [K]. + Setting this to zero will turn off both photons and neutrinos + (even massive ones). + + Neff : float, optional + Effective number of Neutrino species. Default 3.04. + + m_nu : quantity-like ['energy', 'mass'] or array-like, optional + Mass of each neutrino species in [eV] (mass-energy equivalency enabled). + If this is a scalar Quantity, then all neutrino species are assumed to + have that mass. Otherwise, the mass of each species. The actual number + of neutrino species (and hence the number of elements of m_nu if it is + not scalar) must be the floor of Neff. Typically this means you should + provide three neutrino masses unless you are considering something like + a sterile neutrino. + + Ob0 : float or None, optional + Omega baryons: density of baryonic matter in units of the critical + density at z=0. If this is set to None (the default), any computation + that requires its value will raise an exception. + + name : str or None (optional, keyword-only) + Name for this cosmological object. + + meta : mapping or None (optional, keyword-only) + Metadata for the cosmology, e.g., a reference. + + Notes + ----- + Class instances are immutable -- you cannot change the parameters' values. + That is, all of the above attributes (except meta) are read only. + + For details on how to create performant custom subclasses, see the + documentation on :ref:`astropy-cosmology-fast-integrals`. + """ + H0 = ... + Om0 = ... + Ode0 = ... + Tcmb0 = ... + Neff = ... + m_nu = ... + Ob0 = ... + def __init__(self, H0, Om0, Ode0, Tcmb0=..., Neff=..., m_nu=..., Ob0=..., *, name=..., meta=...) -> None: + ... + + @Ob0.validator + def Ob0(self, param, value): # -> float: + """Validate baryon density to None or positive float > matter density.""" + ... + + @m_nu.validator + def m_nu(self, param, value): # -> NDArray[Unknown] | Quantity | None: + """Validate neutrino masses to right value, units, and shape. + + There are no neutrinos if floor(Neff) or Tcmb0 are 0. + The number of neutrinos must match floor(Neff). + Neutrino masses cannot be negative. + """ + ... + + @property + def is_flat(self): # -> bool: + """Return bool; `True` if the cosmology is flat.""" + ... + + @property + def Otot0(self): + """Omega total; the total density/critical density at z=0.""" + ... + + @property + def Odm0(self): # -> None: + """Omega dark matter; dark matter density/critical density at z=0.""" + ... + + @property + def Ok0(self): + """Omega curvature; the effective curvature density/critical density at z=0.""" + ... + + @property + def Tnu0(self): + """Temperature of the neutrino background as `~astropy.units.Quantity` at z=0.""" + ... + + @property + def has_massive_nu(self): # -> bool: + """Does this cosmology have at least one massive neutrino species?""" + ... + + @property + def h(self): + """Dimensionless Hubble constant: h = H_0 / 100 [km/sec/Mpc].""" + ... + + @property + def hubble_time(self): + """Hubble time as `~astropy.units.Quantity`.""" + ... + + @property + def hubble_distance(self): + """Hubble distance as `~astropy.units.Quantity`.""" + ... + + @property + def critical_density0(self): + """Critical density as `~astropy.units.Quantity` at z=0.""" + ... + + @property + def Ogamma0(self): + """Omega gamma; the density/critical density of photons at z=0.""" + ... + + @property + def Onu0(self): + """Omega nu; the density/critical density of neutrinos at z=0.""" + ... + + @abstractmethod + def w(self, z): + r"""The dark energy equation of state. + + Parameters + ---------- + z : Quantity-like ['redshift'], array-like, or `~numbers.Number` + Input redshift. + + Returns + ------- + w : ndarray or float + The dark energy equation of state. + `float` if scalar input. + + Notes + ----- + The dark energy equation of state is defined as + :math:`w(z) = P(z)/\rho(z)`, where :math:`P(z)` is the pressure at + redshift z and :math:`\rho(z)` is the density at redshift z, both in + units where c=1. + + This must be overridden by subclasses. + """ + ... + + def Otot(self, z): + """The total density parameter at redshift ``z``. + + Parameters + ---------- + z : Quantity-like ['redshift'], array-like, or `~numbers.Number` + Input redshifts. + + Returns + ------- + Otot : ndarray or float + The total density relative to the critical density at each redshift. + Returns float if input scalar. + """ + ... + + def Om(self, z): + """ + Return the density parameter for non-relativistic matter + at redshift ``z``. + + Parameters + ---------- + z : Quantity-like ['redshift'], array-like, or `~numbers.Number` + Input redshift. + + Returns + ------- + Om : ndarray or float + The density of non-relativistic matter relative to the critical + density at each redshift. + Returns `float` if the input is scalar. + + Notes + ----- + This does not include neutrinos, even if non-relativistic at the + redshift of interest; see `Onu`. + """ + ... + + def Ob(self, z): + """Return the density parameter for baryonic matter at redshift ``z``. + + Parameters + ---------- + z : Quantity-like ['redshift'], array-like, or `~numbers.Number` + Input redshift. + + Returns + ------- + Ob : ndarray or float + The density of baryonic matter relative to the critical density at + each redshift. + Returns `float` if the input is scalar. + + Raises + ------ + ValueError + If ``Ob0`` is `None`. + """ + ... + + def Odm(self, z): + """Return the density parameter for dark matter at redshift ``z``. + + Parameters + ---------- + z : Quantity-like ['redshift'], array-like, or `~numbers.Number` + Input redshift. + + Returns + ------- + Odm : ndarray or float + The density of non-relativistic dark matter relative to the + critical density at each redshift. + Returns `float` if the input is scalar. + + Raises + ------ + ValueError + If ``Ob0`` is `None`. + + Notes + ----- + This does not include neutrinos, even if non-relativistic at the + redshift of interest. + """ + ... + + def Ok(self, z): # -> NDArray[float64] | float: + """ + Return the equivalent density parameter for curvature at redshift ``z``. + + Parameters + ---------- + z : Quantity-like ['redshift'], array-like, or `~numbers.Number` + Input redshift. + + Returns + ------- + Ok : ndarray or float + The equivalent density parameter for curvature at each redshift. + Returns `float` if the input is scalar. + """ + ... + + def Ode(self, z): # -> NDArray[float64] | float: + """Return the density parameter for dark energy at redshift ``z``. + + Parameters + ---------- + z : Quantity-like ['redshift'], array-like, or `~numbers.Number` + Input redshift. + + Returns + ------- + Ode : ndarray or float + The density of non-relativistic matter relative to the critical + density at each redshift. + Returns `float` if the input is scalar. + """ + ... + + def Ogamma(self, z): + """Return the density parameter for photons at redshift ``z``. + + Parameters + ---------- + z : Quantity-like ['redshift'], array-like, or `~numbers.Number` + Input redshift. + + Returns + ------- + Ogamma : ndarray or float + The energy density of photons relative to the critical density at + each redshift. + Returns `float` if the input is scalar. + """ + ... + + def Onu(self, z): # -> NDArray[float64] | float: + r"""Return the density parameter for neutrinos at redshift ``z``. + + Parameters + ---------- + z : Quantity-like ['redshift'], array-like, or `~numbers.Number` + Input redshift. + + Returns + ------- + Onu : ndarray or float + The energy density of neutrinos relative to the critical density at + each redshift. Note that this includes their kinetic energy (if + they have mass), so it is not equal to the commonly used + :math:`\sum \frac{m_{\nu}}{94 eV}`, which does not include + kinetic energy. + Returns `float` if the input is scalar. + """ + ... + + def Tcmb(self, z): + """Return the CMB temperature at redshift ``z``. + + Parameters + ---------- + z : Quantity-like ['redshift'], array-like, or `~numbers.Number` + Input redshift. + + Returns + ------- + Tcmb : `~astropy.units.Quantity` ['temperature'] + The temperature of the CMB in K. + """ + ... + + def Tnu(self, z): + """Return the neutrino temperature at redshift ``z``. + + Parameters + ---------- + z : Quantity-like ['redshift'], array-like, or `~numbers.Number` + Input redshift. + + Returns + ------- + Tnu : `~astropy.units.Quantity` ['temperature'] + The temperature of the cosmic neutrino background in K. + """ + ... + + def nu_relative_density(self, z): + r"""Neutrino density function relative to the energy density in photons. + + Parameters + ---------- + z : Quantity-like ['redshift'], array-like, or `~numbers.Number` + Input redshift. + + Returns + ------- + f : ndarray or float + The neutrino density scaling factor relative to the density in + photons at each redshift. + Only returns `float` if z is scalar. + + Notes + ----- + The density in neutrinos is given by + + .. math:: + + \rho_{\nu} \left(a\right) = 0.2271 \, N_{eff} \, + f\left(m_{\nu} a / T_{\nu 0} \right) \, + \rho_{\gamma} \left( a \right) + + where + + .. math:: + + f \left(y\right) = \frac{120}{7 \pi^4} + \int_0^{\infty} \, dx \frac{x^2 \sqrt{x^2 + y^2}} + {e^x + 1} + + assuming that all neutrino species have the same mass. + If they have different masses, a similar term is calculated for each + one. Note that ``f`` has the asymptotic behavior :math:`f(0) = 1`. This + method returns :math:`0.2271 f` using an analytical fitting formula + given in Komatsu et al. 2011, ApJS 192, 18. + """ + ... + + def de_density_scale(self, z): + r"""Evaluates the redshift dependence of the dark energy density. + + Parameters + ---------- + z : Quantity-like ['redshift'], array-like, or `~numbers.Number` + Input redshift. + + Returns + ------- + I : ndarray or float + The scaling of the energy density of dark energy with redshift. + Returns `float` if the input is scalar. + + Notes + ----- + The scaling factor, I, is defined by :math:`\rho(z) = \rho_0 I`, + and is given by + + .. math:: + + I = \exp \left( 3 \int_{a}^1 \frac{ da^{\prime} }{ a^{\prime} } + \left[ 1 + w\left( a^{\prime} \right) \right] \right) + + The actual integral used is rewritten from [1]_ to be in terms of z. + + It will generally helpful for subclasses to overload this method if + the integral can be done analytically for the particular dark + energy equation of state that they implement. + + References + ---------- + .. [1] Linder, E. (2003). Exploring the Expansion History of the + Universe. Phys. Rev. Lett., 90, 091301. + """ + ... + + def efunc(self, z): + """Function used to calculate H(z), the Hubble parameter. + + Parameters + ---------- + z : Quantity-like ['redshift'], array-like, or `~numbers.Number` + Input redshift. + + Returns + ------- + E : ndarray or float + The redshift scaling of the Hubble constant. + Returns `float` if the input is scalar. + Defined such that :math:`H(z) = H_0 E(z)`. + + Notes + ----- + It is not necessary to override this method, but if de_density_scale + takes a particularly simple form, it may be advantageous to. + """ + ... + + def inv_efunc(self, z): + """Inverse of ``efunc``. + + Parameters + ---------- + z : Quantity-like ['redshift'], array-like, or `~numbers.Number` + Input redshift. + + Returns + ------- + E : ndarray or float + The redshift scaling of the inverse Hubble constant. + Returns `float` if the input is scalar. + """ + ... + + def lookback_time_integrand(self, z): + """Integrand of the lookback time (equation 30 of [1]_). + + Parameters + ---------- + z : Quantity-like ['redshift'], array-like, or `~numbers.Number` + Input redshift. + + Returns + ------- + I : float or array + The integrand for the lookback time. + + References + ---------- + .. [1] Hogg, D. (1999). Distance measures in cosmology, section 11. + arXiv e-prints, astro-ph/9905116. + """ + ... + + def abs_distance_integrand(self, z): + """Integrand of the absorption distance [1]_. + + Parameters + ---------- + z : Quantity-like ['redshift'], array-like, or `~numbers.Number` + Input redshift. + + Returns + ------- + X : float or array + The integrand for the absorption distance. + + References + ---------- + .. [1] Hogg, D. (1999). Distance measures in cosmology, section 11. + arXiv e-prints, astro-ph/9905116. + """ + ... + + def H(self, z): + """Hubble parameter (km/s/Mpc) at redshift ``z``. + + Parameters + ---------- + z : Quantity-like ['redshift'], array-like, or `~numbers.Number` + Input redshift. + + Returns + ------- + H : `~astropy.units.Quantity` ['frequency'] + Hubble parameter at each input redshift. + """ + ... + + def scale_factor(self, z): + """Scale factor at redshift ``z``. + + The scale factor is defined as :math:`a = 1 / (1 + z)`. + + Parameters + ---------- + z : Quantity-like ['redshift'], array-like, or `~numbers.Number` + Input redshift. + + Returns + ------- + a : ndarray or float + Scale factor at each input redshift. + Returns `float` if the input is scalar. + """ + ... + + def lookback_time(self, z): + """Lookback time in Gyr to redshift ``z``. + + The lookback time is the difference between the age of the Universe now + and the age at redshift ``z``. + + Parameters + ---------- + z : Quantity-like ['redshift'], array-like, or `~numbers.Number` + Input redshift. + + Returns + ------- + t : `~astropy.units.Quantity` ['time'] + Lookback time in Gyr to each input redshift. + + See Also + -------- + z_at_value : Find the redshift corresponding to a lookback time. + """ + ... + + def lookback_distance(self, z): + """ + The lookback distance is the light travel time distance to a given + redshift. It is simply c * lookback_time. It may be used to calculate + the proper distance between two redshifts, e.g. for the mean free path + to ionizing radiation. + + Parameters + ---------- + z : Quantity-like ['redshift'], array-like, or `~numbers.Number` + Input redshift. + + Returns + ------- + d : `~astropy.units.Quantity` ['length'] + Lookback distance in Mpc + """ + ... + + def age(self, z): + """Age of the universe in Gyr at redshift ``z``. + + Parameters + ---------- + z : Quantity-like ['redshift'], array-like, or `~numbers.Number` + Input redshift. + + Returns + ------- + t : `~astropy.units.Quantity` ['time'] + The age of the universe in Gyr at each input redshift. + + See Also + -------- + z_at_value : Find the redshift corresponding to an age. + """ + ... + + def critical_density(self, z): + """Critical density in grams per cubic cm at redshift ``z``. + + Parameters + ---------- + z : Quantity-like ['redshift'], array-like, or `~numbers.Number` + Input redshift. + + Returns + ------- + rho : `~astropy.units.Quantity` + Critical density in g/cm^3 at each input redshift. + """ + ... + + def comoving_distance(self, z): + """Comoving line-of-sight distance in Mpc at a given redshift. + + The comoving distance along the line-of-sight between two objects + remains constant with time for objects in the Hubble flow. + + Parameters + ---------- + z : Quantity-like ['redshift'], array-like, or `~numbers.Number` + Input redshift. + + Returns + ------- + d : `~astropy.units.Quantity` ['length'] + Comoving distance in Mpc to each input redshift. + """ + ... + + def comoving_transverse_distance(self, z): + r"""Comoving transverse distance in Mpc at a given redshift. + + This value is the transverse comoving distance at redshift ``z`` + corresponding to an angular separation of 1 radian. This is the same as + the comoving distance if :math:`\Omega_k` is zero (as in the current + concordance Lambda-CDM model). + + Parameters + ---------- + z : Quantity-like ['redshift'], array-like, or `~numbers.Number` + Input redshift. + + Returns + ------- + d : `~astropy.units.Quantity` ['length'] + Comoving transverse distance in Mpc at each input redshift. + + Notes + ----- + This quantity is also called the 'proper motion distance' in some texts. + """ + ... + + def angular_diameter_distance(self, z): + """Angular diameter distance in Mpc at a given redshift. + + This gives the proper (sometimes called 'physical') transverse + distance corresponding to an angle of 1 radian for an object + at redshift ``z`` ([1]_, [2]_, [3]_). + + Parameters + ---------- + z : Quantity-like ['redshift'], array-like, or `~numbers.Number` + Input redshift. + + Returns + ------- + d : `~astropy.units.Quantity` ['length'] + Angular diameter distance in Mpc at each input redshift. + + References + ---------- + .. [1] Weinberg, 1972, pp 420-424; Weedman, 1986, pp 421-424. + .. [2] Weedman, D. (1986). Quasar astronomy, pp 65-67. + .. [3] Peebles, P. (1993). Principles of Physical Cosmology, pp 325-327. + """ + ... + + def luminosity_distance(self, z): + """Luminosity distance in Mpc at redshift ``z``. + + This is the distance to use when converting between the bolometric flux + from an object at redshift ``z`` and its bolometric luminosity [1]_. + + Parameters + ---------- + z : Quantity-like ['redshift'], array-like, or `~numbers.Number` + Input redshift. + + Returns + ------- + d : `~astropy.units.Quantity` ['length'] + Luminosity distance in Mpc at each input redshift. + + See Also + -------- + z_at_value : Find the redshift corresponding to a luminosity distance. + + References + ---------- + .. [1] Weinberg, 1972, pp 420-424; Weedman, 1986, pp 60-62. + """ + ... + + def angular_diameter_distance_z1z2(self, z1, z2): + """Angular diameter distance between objects at 2 redshifts. + + Useful for gravitational lensing, for example computing the angular + diameter distance between a lensed galaxy and the foreground lens. + + Parameters + ---------- + z1, z2 : Quantity-like ['redshift'], array-like, or `~numbers.Number` + Input redshifts. For most practical applications such as + gravitational lensing, ``z2`` should be larger than ``z1``. The + method will work for ``z2 < z1``; however, this will return + negative distances. + + Returns + ------- + d : `~astropy.units.Quantity` + The angular diameter distance between each input redshift pair. + Returns scalar if input is scalar, array else-wise. + """ + ... + + @vectorize_redshift_method + def absorption_distance(self, z, /): + """Absorption distance at redshift ``z``. + + This is used to calculate the number of objects with some cross section + of absorption and number density intersecting a sightline per unit + redshift path ([1]_, [2]_). + + Parameters + ---------- + z : Quantity-like ['redshift'], array-like, or `~numbers.Number` + Input redshift. + + Returns + ------- + d : float or ndarray + Absorption distance (dimensionless) at each input redshift. + Returns `float` if input scalar, `~numpy.ndarray` otherwise. + + References + ---------- + .. [1] Hogg, D. (1999). Distance measures in cosmology, section 11. + arXiv e-prints, astro-ph/9905116. + .. [2] Bahcall, John N. and Peebles, P.J.E. 1969, ApJ, 156L, 7B + """ + ... + + def distmod(self, z): + """Distance modulus at redshift ``z``. + + The distance modulus is defined as the (apparent magnitude - absolute + magnitude) for an object at redshift ``z``. + + Parameters + ---------- + z : Quantity-like ['redshift'], array-like, or `~numbers.Number` + Input redshift. + + Returns + ------- + distmod : `~astropy.units.Quantity` ['length'] + Distance modulus at each input redshift, in magnitudes. + + See Also + -------- + z_at_value : Find the redshift corresponding to a distance modulus. + """ + ... + + def comoving_volume(self, z): + r"""Comoving volume in cubic Mpc at redshift ``z``. + + This is the volume of the universe encompassed by redshifts less than + ``z``. For the case of :math:`\Omega_k = 0` it is a sphere of radius + `comoving_distance` but it is less intuitive if :math:`\Omega_k` is not. + + Parameters + ---------- + z : Quantity-like ['redshift'], array-like, or `~numbers.Number` + Input redshift. + + Returns + ------- + V : `~astropy.units.Quantity` + Comoving volume in :math:`Mpc^3` at each input redshift. + """ + ... + + def differential_comoving_volume(self, z): + """Differential comoving volume at redshift z. + + Useful for calculating the effective comoving volume. + For example, allows for integration over a comoving volume that has a + sensitivity function that changes with redshift. The total comoving + volume is given by integrating ``differential_comoving_volume`` to + redshift ``z`` and multiplying by a solid angle. + + Parameters + ---------- + z : Quantity-like ['redshift'], array-like, or `~numbers.Number` + Input redshift. + + Returns + ------- + dV : `~astropy.units.Quantity` + Differential comoving volume per redshift per steradian at each + input redshift. + """ + ... + + def kpc_comoving_per_arcmin(self, z): + """ + Separation in transverse comoving kpc corresponding to an arcminute at + redshift ``z``. + + Parameters + ---------- + z : Quantity-like ['redshift'], array-like, or `~numbers.Number` + Input redshift. + + Returns + ------- + d : `~astropy.units.Quantity` ['length'] + The distance in comoving kpc corresponding to an arcmin at each + input redshift. + """ + ... + + def kpc_proper_per_arcmin(self, z): + """ + Separation in transverse proper kpc corresponding to an arcminute at + redshift ``z``. + + Parameters + ---------- + z : Quantity-like ['redshift'], array-like, or `~numbers.Number` + Input redshift. + + Returns + ------- + d : `~astropy.units.Quantity` ['length'] + The distance in proper kpc corresponding to an arcmin at each input + redshift. + """ + ... + + def arcsec_per_kpc_comoving(self, z): + """ + Angular separation in arcsec corresponding to a comoving kpc at + redshift ``z``. + + Parameters + ---------- + z : Quantity-like ['redshift'], array-like, or `~numbers.Number` + Input redshift. + + Returns + ------- + theta : `~astropy.units.Quantity` ['angle'] + The angular separation in arcsec corresponding to a comoving kpc at + each input redshift. + """ + ... + + def arcsec_per_kpc_proper(self, z): + """ + Angular separation in arcsec corresponding to a proper kpc at redshift + ``z``. + + Parameters + ---------- + z : Quantity-like ['redshift'], array-like, or `~numbers.Number` + Input redshift. + + Returns + ------- + theta : `~astropy.units.Quantity` ['angle'] + The angular separation in arcsec corresponding to a proper kpc at + each input redshift. + """ + ... + + + +class FlatFLRWMixin(FlatCosmologyMixin): + """ + Mixin class for flat FLRW cosmologies. Do NOT instantiate directly. + Must precede the base class in the multiple-inheritance so that this + mixin's ``__init__`` proceeds the base class'. + Note that all instances of ``FlatFLRWMixin`` are flat, but not all + flat cosmologies are instances of ``FlatFLRWMixin``. As example, + ``LambdaCDM`` **may** be flat (for the a specific set of parameter values), + but ``FlatLambdaCDM`` **will** be flat. + """ + Ode0 = ... + def __init_subclass__(cls): # -> None: + ... + + def __init__(self, *args, **kw) -> None: + ... + + @lazyproperty + def nonflat(self: _FlatFLRWMixinT) -> _FLRWT: + ... + + def clone(self, *, meta: Optional[Mapping] = ..., to_nonflat: bool = ..., **kwargs: Any): # -> Any: + """Returns a copy of this object with updated parameters, as specified. + + This cannot be used to change the type of the cosmology, except for + changing to the non-flat version of this cosmology. + + Parameters + ---------- + meta : mapping or None (optional, keyword-only) + Metadata that will update the current metadata. + to_nonflat : bool or None, optional keyword-only + Whether to change to the non-flat version of this cosmology. + **kwargs + Cosmology parameter (and name) modifications. If any parameter is + changed and a new name is not given, the name will be set to "[old + name] (modified)". + + Returns + ------- + newcosmo : `~astropy.cosmology.Cosmology` subclass instance + A new instance of this class with updated parameters as specified. + If no arguments are given, then a reference to this object is + returned instead of copy. + + Examples + -------- + To make a copy of the ``Planck13`` cosmology with a different matter + density (``Om0``), and a new name: + + >>> from astropy.cosmology import Planck13 + >>> Planck13.clone(name="Modified Planck 2013", Om0=0.35) + FlatLambdaCDM(name="Modified Planck 2013", H0=67.77 km / (Mpc s), + Om0=0.35, ... + + If no name is specified, the new name will note the modification. + + >>> Planck13.clone(Om0=0.35).name + 'Planck13 (modified)' + + The keyword 'to_nonflat' can be used to clone on the non-flat equivalent + cosmology. + + >>> Planck13.clone(to_nonflat=True) + LambdaCDM(name="Planck13", ... + + >>> Planck13.clone(H0=70, to_nonflat=True) + LambdaCDM(name="Planck13 (modified)", H0=70.0 km / (Mpc s), ... + + With 'to_nonflat' `True`, ``Ode0`` can be modified. + + >>> Planck13.clone(to_nonflat=True, Ode0=1) + LambdaCDM(name="Planck13 (modified)", H0=67.77 km / (Mpc s), + Om0=0.30712, Ode0=1.0, ... + """ + ... + + @property + def Otot0(self): # -> float: + """Omega total; the total density/critical density at z=0.""" + ... + + def Otot(self, z): # -> float | NDArray[Unknown]: + """The total density parameter at redshift ``z``. + + Parameters + ---------- + z : Quantity-like ['redshift'], array-like, or `~numbers.Number` + Input redshifts. + + Returns + ------- + Otot : ndarray or float + Returns float if input scalar. Value of 1. + """ + ... + + def __equiv__(self, other): # -> _NotImplementedType | Literal[False]: + """flat-FLRW equivalence. Use ``.is_equivalent()`` for actual check! + + Parameters + ---------- + other : `~astropy.cosmology.FLRW` subclass instance + The object in which to compare. + + Returns + ------- + bool or `NotImplemented` + `True` if 'other' is of the same class / non-flat class (e.g. + ``FlatLambdaCDM`` and ``LambdaCDM``) has matching parameters + and parameter values. `False` if 'other' is of the same class but + has different parameters. `NotImplemented` otherwise. + """ + ... + + + diff --git a/typings/astropy/cosmology/flrw/lambdacdm.pyi b/typings/astropy/cosmology/flrw/lambdacdm.pyi new file mode 100644 index 0000000..ed81398 --- /dev/null +++ b/typings/astropy/cosmology/flrw/lambdacdm.pyi @@ -0,0 +1,254 @@ +""" +This type stub file was generated by pyright. +""" + +from astropy.utils.compat.optional_deps import HAS_SCIPY +from .base import FLRW, FlatFLRWMixin + +if HAS_SCIPY: + ... +else: + def ellipkinc(*args, **kwargs): + ... + + def hyp2f1(*args, **kwargs): + ... + +__all__ = ["LambdaCDM", "FlatLambdaCDM"] +__doctest_requires__ = ... +class LambdaCDM(FLRW): + """FLRW cosmology with a cosmological constant and curvature. + + This has no additional attributes beyond those of FLRW. + + Parameters + ---------- + H0 : float or scalar quantity-like ['frequency'] + Hubble constant at z = 0. If a float, must be in [km/sec/Mpc]. + + Om0 : float + Omega matter: density of non-relativistic matter in units of the + critical density at z=0. + + Ode0 : float + Omega dark energy: density of the cosmological constant in units of + the critical density at z=0. + + Tcmb0 : float or scalar quantity-like ['temperature'], optional + Temperature of the CMB z=0. If a float, must be in [K]. Default: 0 [K]. + Setting this to zero will turn off both photons and neutrinos + (even massive ones). + + Neff : float, optional + Effective number of Neutrino species. Default 3.04. + + m_nu : quantity-like ['energy', 'mass'] or array-like, optional + Mass of each neutrino species in [eV] (mass-energy equivalency enabled). + If this is a scalar Quantity, then all neutrino species are assumed to + have that mass. Otherwise, the mass of each species. The actual number + of neutrino species (and hence the number of elements of m_nu if it is + not scalar) must be the floor of Neff. Typically this means you should + provide three neutrino masses unless you are considering something like + a sterile neutrino. + + Ob0 : float or None, optional + Omega baryons: density of baryonic matter in units of the critical + density at z=0. If this is set to None (the default), any computation + that requires its value will raise an exception. + + name : str or None (optional, keyword-only) + Name for this cosmological object. + + meta : mapping or None (optional, keyword-only) + Metadata for the cosmology, e.g., a reference. + + Examples + -------- + >>> from astropy.cosmology import LambdaCDM + >>> cosmo = LambdaCDM(H0=70, Om0=0.3, Ode0=0.7) + + The comoving distance in Mpc at redshift z: + + >>> z = 0.5 + >>> dc = cosmo.comoving_distance(z) + """ + def __init__(self, H0, Om0, Ode0, Tcmb0=..., Neff=..., m_nu=..., Ob0=..., *, name=..., meta=...) -> None: + ... + + def w(self, z): # -> NDArray[floating[Any]] | float: + r"""Returns dark energy equation of state at redshift ``z``. + + Parameters + ---------- + z : Quantity-like ['redshift'], array-like, or `~numbers.Number` + Input redshift. + + Returns + ------- + w : ndarray or float + The dark energy equation of state. + Returns `float` if the input is scalar. + + Notes + ----- + The dark energy equation of state is defined as + :math:`w(z) = P(z)/\rho(z)`, where :math:`P(z)` is the pressure at + redshift z and :math:`\rho(z)` is the density at redshift z, both in + units where c=1. Here this is :math:`w(z) = -1`. + """ + ... + + def de_density_scale(self, z): # -> NDArray[float64] | float: + r"""Evaluates the redshift dependence of the dark energy density. + + Parameters + ---------- + z : Quantity-like ['redshift'], array-like, or `~numbers.Number` + Input redshift. + + Returns + ------- + I : ndarray or float + The scaling of the energy density of dark energy with redshift. + Returns `float` if the input is scalar. + + Notes + ----- + The scaling factor, I, is defined by :math:`\rho(z) = \rho_0 I`, + and in this case is given by :math:`I = 1`. + """ + ... + + def efunc(self, z): # -> Any: + """Function used to calculate H(z), the Hubble parameter. + + Parameters + ---------- + z : Quantity-like ['redshift'], array-like, or `~numbers.Number` + Input redshift. + + Returns + ------- + E : ndarray or float + The redshift scaling of the Hubble constant. + Returns `float` if the input is scalar. + Defined such that :math:`H(z) = H_0 E(z)`. + """ + ... + + def inv_efunc(self, z): + r"""Function used to calculate :math:`\frac{1}{H_z}`. + + Parameters + ---------- + z : Quantity-like ['redshift'], array-like, or `~numbers.Number` + Input redshift. + + Returns + ------- + E : ndarray or float + The inverse redshift scaling of the Hubble constant. + Returns `float` if the input is scalar. + Defined such that :math:`H_z = H_0 / E`. + """ + ... + + + +class FlatLambdaCDM(FlatFLRWMixin, LambdaCDM): + """FLRW cosmology with a cosmological constant and no curvature. + + This has no additional attributes beyond those of FLRW. + + Parameters + ---------- + H0 : float or scalar quantity-like ['frequency'] + Hubble constant at z = 0. If a float, must be in [km/sec/Mpc]. + + Om0 : float + Omega matter: density of non-relativistic matter in units of the + critical density at z=0. + + Tcmb0 : float or scalar quantity-like ['temperature'], optional + Temperature of the CMB z=0. If a float, must be in [K]. Default: 0 [K]. + Setting this to zero will turn off both photons and neutrinos + (even massive ones). + + Neff : float, optional + Effective number of Neutrino species. Default 3.04. + + m_nu : quantity-like ['energy', 'mass'] or array-like, optional + Mass of each neutrino species in [eV] (mass-energy equivalency enabled). + If this is a scalar Quantity, then all neutrino species are assumed to + have that mass. Otherwise, the mass of each species. The actual number + of neutrino species (and hence the number of elements of m_nu if it is + not scalar) must be the floor of Neff. Typically this means you should + provide three neutrino masses unless you are considering something like + a sterile neutrino. + + Ob0 : float or None, optional + Omega baryons: density of baryonic matter in units of the critical + density at z=0. If this is set to None (the default), any computation + that requires its value will raise an exception. + + name : str or None (optional, keyword-only) + Name for this cosmological object. + + meta : mapping or None (optional, keyword-only) + Metadata for the cosmology, e.g., a reference. + + Examples + -------- + >>> from astropy.cosmology import FlatLambdaCDM + >>> cosmo = FlatLambdaCDM(H0=70, Om0=0.3) + + The comoving distance in Mpc at redshift z: + + >>> z = 0.5 + >>> dc = cosmo.comoving_distance(z) + + To get an equivalent cosmology, but of type `astropy.cosmology.LambdaCDM`, + use :attr:`astropy.cosmology.FlatFLRWMixin.nonflat`. + + >>> cosmo.nonflat + LambdaCDM(H0=70.0 km / (Mpc s), Om0=0.3, ... + """ + def __init__(self, H0, Om0, Tcmb0=..., Neff=..., m_nu=..., Ob0=..., *, name=..., meta=...) -> None: + ... + + def efunc(self, z): # -> Any: + """Function used to calculate H(z), the Hubble parameter. + + Parameters + ---------- + z : Quantity-like ['redshift'], array-like, or `~numbers.Number` + Input redshift. + + Returns + ------- + E : ndarray or float + The redshift scaling of the Hubble constant. + Returns `float` if the input is scalar. + Defined such that :math:`H(z) = H_0 E(z)`. + """ + ... + + def inv_efunc(self, z): + r"""Function used to calculate :math:`\frac{1}{H_z}`. + + Parameters + ---------- + z : Quantity-like ['redshift'], array-like, or `~numbers.Number` + Input redshift. + + Returns + ------- + E : ndarray or float + The inverse redshift scaling of the Hubble constant. + Returns `float` if the input is scalar. + Defined such that :math:`H_z = H_0 / E`. + """ + ... + + + diff --git a/typings/astropy/cosmology/flrw/tests/__init__.pyi b/typings/astropy/cosmology/flrw/tests/__init__.pyi new file mode 100644 index 0000000..006bc27 --- /dev/null +++ b/typings/astropy/cosmology/flrw/tests/__init__.pyi @@ -0,0 +1,4 @@ +""" +This type stub file was generated by pyright. +""" + diff --git a/typings/astropy/cosmology/flrw/w0cdm.pyi b/typings/astropy/cosmology/flrw/w0cdm.pyi new file mode 100644 index 0000000..371cc30 --- /dev/null +++ b/typings/astropy/cosmology/flrw/w0cdm.pyi @@ -0,0 +1,259 @@ +""" +This type stub file was generated by pyright. +""" + +from .base import FLRW, FlatFLRWMixin + +__all__ = ["wCDM", "FlatwCDM"] +__doctest_requires__ = ... +class wCDM(FLRW): + """ + FLRW cosmology with a constant dark energy equation of state and curvature. + + This has one additional attribute beyond those of FLRW. + + Parameters + ---------- + H0 : float or scalar quantity-like ['frequency'] + Hubble constant at z = 0. If a float, must be in [km/sec/Mpc]. + + Om0 : float + Omega matter: density of non-relativistic matter in units of the + critical density at z=0. + + Ode0 : float + Omega dark energy: density of dark energy in units of the critical + density at z=0. + + w0 : float, optional + Dark energy equation of state at all redshifts. This is + pressure/density for dark energy in units where c=1. A cosmological + constant has w0=-1.0. + + Tcmb0 : float or scalar quantity-like ['temperature'], optional + Temperature of the CMB z=0. If a float, must be in [K]. Default: 0 [K]. + Setting this to zero will turn off both photons and neutrinos + (even massive ones). + + Neff : float, optional + Effective number of Neutrino species. Default 3.04. + + m_nu : quantity-like ['energy', 'mass'] or array-like, optional + Mass of each neutrino species in [eV] (mass-energy equivalency enabled). + If this is a scalar Quantity, then all neutrino species are assumed to + have that mass. Otherwise, the mass of each species. The actual number + of neutrino species (and hence the number of elements of m_nu if it is + not scalar) must be the floor of Neff. Typically this means you should + provide three neutrino masses unless you are considering something like + a sterile neutrino. + + Ob0 : float or None, optional + Omega baryons: density of baryonic matter in units of the critical + density at z=0. If this is set to None (the default), any computation + that requires its value will raise an exception. + + name : str or None (optional, keyword-only) + Name for this cosmological object. + + meta : mapping or None (optional, keyword-only) + Metadata for the cosmology, e.g., a reference. + + Examples + -------- + >>> from astropy.cosmology import wCDM + >>> cosmo = wCDM(H0=70, Om0=0.3, Ode0=0.7, w0=-0.9) + + The comoving distance in Mpc at redshift z: + + >>> z = 0.5 + >>> dc = cosmo.comoving_distance(z) + """ + w0 = ... + def __init__(self, H0, Om0, Ode0, w0=..., Tcmb0=..., Neff=..., m_nu=..., Ob0=..., *, name=..., meta=...) -> None: + ... + + def w(self, z): + r"""Returns dark energy equation of state at redshift ``z``. + + Parameters + ---------- + z : Quantity-like ['redshift'], array-like, or `~numbers.Number` + Input redshift. + + Returns + ------- + w : ndarray or float + The dark energy equation of state + Returns `float` if the input is scalar. + + Notes + ----- + The dark energy equation of state is defined as + :math:`w(z) = P(z)/\rho(z)`, where :math:`P(z)` is the pressure at + redshift z and :math:`\rho(z)` is the density at redshift z, both in + units where c=1. Here this is :math:`w(z) = w_0`. + """ + ... + + def de_density_scale(self, z): + r"""Evaluates the redshift dependence of the dark energy density. + + Parameters + ---------- + z : Quantity-like ['redshift'], array-like, or `~numbers.Number` + Input redshift. + + Returns + ------- + I : ndarray or float + The scaling of the energy density of dark energy with redshift. + Returns `float` if the input is scalar. + + Notes + ----- + The scaling factor, I, is defined by :math:`\rho(z) = \rho_0 I`, + and in this case is given by + :math:`I = \left(1 + z\right)^{3\left(1 + w_0\right)}` + """ + ... + + def efunc(self, z): # -> Any: + """Function used to calculate H(z), the Hubble parameter. + + Parameters + ---------- + z : Quantity-like ['redshift'], array-like, or `~numbers.Number` + Input redshift. + + Returns + ------- + E : ndarray or float + The redshift scaling of the Hubble constant. + Returns `float` if the input is scalar. + Defined such that :math:`H(z) = H_0 E(z)`. + """ + ... + + def inv_efunc(self, z): + r"""Function used to calculate :math:`\frac{1}{H_z}`. + + Parameters + ---------- + z : Quantity-like ['redshift'], array-like, or `~numbers.Number` + Input redshift. + + Returns + ------- + E : ndarray or float + The inverse redshift scaling of the Hubble constant. + Returns `float` if the input is scalar. + Defined such that :math:`H_z = H_0 / E`. + """ + ... + + + +class FlatwCDM(FlatFLRWMixin, wCDM): + """ + FLRW cosmology with a constant dark energy equation of state and no spatial + curvature. + + This has one additional attribute beyond those of FLRW. + + Parameters + ---------- + H0 : float or scalar quantity-like ['frequency'] + Hubble constant at z = 0. If a float, must be in [km/sec/Mpc]. + + Om0 : float + Omega matter: density of non-relativistic matter in units of the + critical density at z=0. + + w0 : float, optional + Dark energy equation of state at all redshifts. This is + pressure/density for dark energy in units where c=1. A cosmological + constant has w0=-1.0. + + Tcmb0 : float or scalar quantity-like ['temperature'], optional + Temperature of the CMB z=0. If a float, must be in [K]. Default: 0 [K]. + Setting this to zero will turn off both photons and neutrinos + (even massive ones). + + Neff : float, optional + Effective number of Neutrino species. Default 3.04. + + m_nu : quantity-like ['energy', 'mass'] or array-like, optional + Mass of each neutrino species in [eV] (mass-energy equivalency enabled). + If this is a scalar Quantity, then all neutrino species are assumed to + have that mass. Otherwise, the mass of each species. The actual number + of neutrino species (and hence the number of elements of m_nu if it is + not scalar) must be the floor of Neff. Typically this means you should + provide three neutrino masses unless you are considering something like + a sterile neutrino. + + Ob0 : float or None, optional + Omega baryons: density of baryonic matter in units of the critical + density at z=0. If this is set to None (the default), any computation + that requires its value will raise an exception. + + name : str or None (optional, keyword-only) + Name for this cosmological object. + + meta : mapping or None (optional, keyword-only) + Metadata for the cosmology, e.g., a reference. + + Examples + -------- + >>> from astropy.cosmology import FlatwCDM + >>> cosmo = FlatwCDM(H0=70, Om0=0.3, w0=-0.9) + + The comoving distance in Mpc at redshift z: + + >>> z = 0.5 + >>> dc = cosmo.comoving_distance(z) + + To get an equivalent cosmology, but of type `astropy.cosmology.wCDM`, + use :attr:`astropy.cosmology.FlatFLRWMixin.nonflat`. + + >>> cosmo.nonflat + wCDM(H0=70.0 km / (Mpc s), Om0=0.3, ... + """ + def __init__(self, H0, Om0, w0=..., Tcmb0=..., Neff=..., m_nu=..., Ob0=..., *, name=..., meta=...) -> None: + ... + + def efunc(self, z): # -> Any: + """Function used to calculate H(z), the Hubble parameter. + + Parameters + ---------- + z : Quantity-like ['redshift'], array-like, or `~numbers.Number` + Input redshift. + + Returns + ------- + E : ndarray or float + The redshift scaling of the Hubble constant. + Returns `float` if the input is scalar. + Defined such that :math:`H(z) = H_0 E(z)`. + """ + ... + + def inv_efunc(self, z): + r"""Function used to calculate :math:`\frac{1}{H_z}`. + + Parameters + ---------- + z : Quantity-like ['redshift'], array-like, or `~numbers.Number` + Input redshift. + + Returns + ------- + E : ndarray or float + The inverse redshift scaling of the Hubble constant. + Returns `float` if the input is scalar. + Defined such that :math:`H(z) = H_0 E(z)`. + """ + ... + + + diff --git a/typings/astropy/cosmology/flrw/w0wacdm.pyi b/typings/astropy/cosmology/flrw/w0wacdm.pyi new file mode 100644 index 0000000..998b655 --- /dev/null +++ b/typings/astropy/cosmology/flrw/w0wacdm.pyi @@ -0,0 +1,221 @@ +""" +This type stub file was generated by pyright. +""" + +from .base import FLRW, FlatFLRWMixin + +__all__ = ["w0waCDM", "Flatw0waCDM"] +__doctest_requires__ = ... +class w0waCDM(FLRW): + r"""FLRW cosmology with a CPL dark energy equation of state and curvature. + + The equation for the dark energy equation of state uses the + CPL form as described in Chevallier & Polarski [1]_ and Linder [2]_: + :math:`w(z) = w_0 + w_a (1-a) = w_0 + w_a z / (1+z)`. + + Parameters + ---------- + H0 : float or scalar quantity-like ['frequency'] + Hubble constant at z = 0. If a float, must be in [km/sec/Mpc]. + + Om0 : float + Omega matter: density of non-relativistic matter in units of the + critical density at z=0. + + Ode0 : float + Omega dark energy: density of dark energy in units of the critical + density at z=0. + + w0 : float, optional + Dark energy equation of state at z=0 (a=1). This is pressure/density + for dark energy in units where c=1. + + wa : float, optional + Negative derivative of the dark energy equation of state with respect + to the scale factor. A cosmological constant has w0=-1.0 and wa=0.0. + + Tcmb0 : float or scalar quantity-like ['temperature'], optional + Temperature of the CMB z=0. If a float, must be in [K]. Default: 0 [K]. + Setting this to zero will turn off both photons and neutrinos + (even massive ones). + + Neff : float, optional + Effective number of Neutrino species. Default 3.04. + + m_nu : quantity-like ['energy', 'mass'] or array-like, optional + Mass of each neutrino species in [eV] (mass-energy equivalency enabled). + If this is a scalar Quantity, then all neutrino species are assumed to + have that mass. Otherwise, the mass of each species. The actual number + of neutrino species (and hence the number of elements of m_nu if it is + not scalar) must be the floor of Neff. Typically this means you should + provide three neutrino masses unless you are considering something like + a sterile neutrino. + + Ob0 : float or None, optional + Omega baryons: density of baryonic matter in units of the critical + density at z=0. If this is set to None (the default), any computation + that requires its value will raise an exception. + + name : str or None (optional, keyword-only) + Name for this cosmological object. + + meta : mapping or None (optional, keyword-only) + Metadata for the cosmology, e.g., a reference. + + Examples + -------- + >>> from astropy.cosmology import w0waCDM + >>> cosmo = w0waCDM(H0=70, Om0=0.3, Ode0=0.7, w0=-0.9, wa=0.2) + + The comoving distance in Mpc at redshift z: + + >>> z = 0.5 + >>> dc = cosmo.comoving_distance(z) + + References + ---------- + .. [1] Chevallier, M., & Polarski, D. (2001). Accelerating Universes with + Scaling Dark Matter. International Journal of Modern Physics D, + 10(2), 213-223. + .. [2] Linder, E. (2003). Exploring the Expansion History of the + Universe. Phys. Rev. Lett., 90, 091301. + """ + w0 = ... + wa = ... + def __init__(self, H0, Om0, Ode0, w0=..., wa=..., Tcmb0=..., Neff=..., m_nu=..., Ob0=..., *, name=..., meta=...) -> None: + ... + + def w(self, z): + r"""Returns dark energy equation of state at redshift ``z``. + + Parameters + ---------- + z : Quantity-like ['redshift'], array-like, or `~numbers.Number` + Input redshift. + + Returns + ------- + w : ndarray or float + The dark energy equation of state + Returns `float` if the input is scalar. + + Notes + ----- + The dark energy equation of state is defined as + :math:`w(z) = P(z)/\rho(z)`, where :math:`P(z)` is the pressure at + redshift z and :math:`\rho(z)` is the density at redshift z, both in + units where c=1. Here this is + :math:`w(z) = w_0 + w_a (1 - a) = w_0 + w_a \frac{z}{1+z}`. + """ + ... + + def de_density_scale(self, z): + r"""Evaluates the redshift dependence of the dark energy density. + + Parameters + ---------- + z : Quantity-like ['redshift'], array-like, or `~numbers.Number` + Input redshift. + + Returns + ------- + I : ndarray or float + The scaling of the energy density of dark energy with redshift. + Returns `float` if the input is scalar. + + Notes + ----- + The scaling factor, I, is defined by :math:`\rho(z) = \rho_0 I`, + and in this case is given by + + .. math:: + + I = \left(1 + z\right)^{3 \left(1 + w_0 + w_a\right)} + \exp \left(-3 w_a \frac{z}{1+z}\right) + """ + ... + + + +class Flatw0waCDM(FlatFLRWMixin, w0waCDM): + """FLRW cosmology with a CPL dark energy equation of state and no + curvature. + + The equation for the dark energy equation of state uses the CPL form as + described in Chevallier & Polarski [1]_ and Linder [2]_: + :math:`w(z) = w_0 + w_a (1-a) = w_0 + w_a z / (1+z)`. + + Parameters + ---------- + H0 : float or scalar quantity-like ['frequency'] + Hubble constant at z = 0. If a float, must be in [km/sec/Mpc]. + + Om0 : float + Omega matter: density of non-relativistic matter in units of the + critical density at z=0. + + w0 : float, optional + Dark energy equation of state at z=0 (a=1). This is pressure/density + for dark energy in units where c=1. + + wa : float, optional + Negative derivative of the dark energy equation of state with respect + to the scale factor. A cosmological constant has w0=-1.0 and wa=0.0. + + Tcmb0 : float or scalar quantity-like ['temperature'], optional + Temperature of the CMB z=0. If a float, must be in [K]. Default: 0 [K]. + Setting this to zero will turn off both photons and neutrinos + (even massive ones). + + Neff : float, optional + Effective number of Neutrino species. Default 3.04. + + m_nu : quantity-like ['energy', 'mass'] or array-like, optional + Mass of each neutrino species in [eV] (mass-energy equivalency enabled). + If this is a scalar Quantity, then all neutrino species are assumed to + have that mass. Otherwise, the mass of each species. The actual number + of neutrino species (and hence the number of elements of m_nu if it is + not scalar) must be the floor of Neff. Typically this means you should + provide three neutrino masses unless you are considering something like + a sterile neutrino. + + Ob0 : float or None, optional + Omega baryons: density of baryonic matter in units of the critical + density at z=0. If this is set to None (the default), any computation + that requires its value will raise an exception. + + name : str or None (optional, keyword-only) + Name for this cosmological object. + + meta : mapping or None (optional, keyword-only) + Metadata for the cosmology, e.g., a reference. + + Examples + -------- + >>> from astropy.cosmology import Flatw0waCDM + >>> cosmo = Flatw0waCDM(H0=70, Om0=0.3, w0=-0.9, wa=0.2) + + The comoving distance in Mpc at redshift z: + + >>> z = 0.5 + >>> dc = cosmo.comoving_distance(z) + + To get an equivalent cosmology, but of type `astropy.cosmology.w0waCDM`, + use :attr:`astropy.cosmology.FlatFLRWMixin.nonflat`. + + >>> cosmo.nonflat + w0waCDM(H0=70.0 km / (Mpc s), Om0=0.3, ... + + References + ---------- + .. [1] Chevallier, M., & Polarski, D. (2001). Accelerating Universes with + Scaling Dark Matter. International Journal of Modern Physics D, + 10(2), 213-223. + .. [2] Linder, E. (2003). Exploring the Expansion History of the + Universe. Phys. Rev. Lett., 90, 091301. + """ + def __init__(self, H0, Om0, w0=..., wa=..., Tcmb0=..., Neff=..., m_nu=..., Ob0=..., *, name=..., meta=...) -> None: + ... + + + diff --git a/typings/astropy/cosmology/flrw/w0wzcdm.pyi b/typings/astropy/cosmology/flrw/w0wzcdm.pyi new file mode 100644 index 0000000..77cd166 --- /dev/null +++ b/typings/astropy/cosmology/flrw/w0wzcdm.pyi @@ -0,0 +1,132 @@ +""" +This type stub file was generated by pyright. +""" + +from .base import FLRW + +__all__ = ["w0wzCDM"] +__doctest_requires__ = ... +class w0wzCDM(FLRW): + """ + FLRW cosmology with a variable dark energy equation of state and curvature. + + The equation for the dark energy equation of state uses the simple form: + :math:`w(z) = w_0 + w_z z`. + + This form is not recommended for z > 1. + + Parameters + ---------- + H0 : float or scalar quantity-like ['frequency'] + Hubble constant at z = 0. If a float, must be in [km/sec/Mpc]. + + Om0 : float + Omega matter: density of non-relativistic matter in units of the + critical density at z=0. + + Ode0 : float + Omega dark energy: density of dark energy in units of the critical + density at z=0. + + w0 : float, optional + Dark energy equation of state at z=0. This is pressure/density for + dark energy in units where c=1. + + wz : float, optional + Derivative of the dark energy equation of state with respect to z. + A cosmological constant has w0=-1.0 and wz=0.0. + + Tcmb0 : float or scalar quantity-like ['temperature'], optional + Temperature of the CMB z=0. If a float, must be in [K]. Default: 0 [K]. + Setting this to zero will turn off both photons and neutrinos + (even massive ones). + + Neff : float, optional + Effective number of Neutrino species. Default 3.04. + + m_nu : quantity-like ['energy', 'mass'] or array-like, optional + Mass of each neutrino species in [eV] (mass-energy equivalency enabled). + If this is a scalar Quantity, then all neutrino species are assumed to + have that mass. Otherwise, the mass of each species. The actual number + of neutrino species (and hence the number of elements of m_nu if it is + not scalar) must be the floor of Neff. Typically this means you should + provide three neutrino masses unless you are considering something like + a sterile neutrino. + + Ob0 : float or None, optional + Omega baryons: density of baryonic matter in units of the critical + density at z=0. If this is set to None (the default), any computation + that requires its value will raise an exception. + + name : str or None (optional, keyword-only) + Name for this cosmological object. + + meta : mapping or None (optional, keyword-only) + Metadata for the cosmology, e.g., a reference. + + Examples + -------- + >>> from astropy.cosmology import w0wzCDM + >>> cosmo = w0wzCDM(H0=70, Om0=0.3, Ode0=0.7, w0=-0.9, wz=0.2) + + The comoving distance in Mpc at redshift z: + + >>> z = 0.5 + >>> dc = cosmo.comoving_distance(z) + """ + w0 = ... + wz = ... + def __init__(self, H0, Om0, Ode0, w0=..., wz=..., Tcmb0=..., Neff=..., m_nu=..., Ob0=..., *, name=..., meta=...) -> None: + ... + + def w(self, z): + r"""Returns dark energy equation of state at redshift ``z``. + + Parameters + ---------- + z : Quantity-like ['redshift'], array-like, or `~numbers.Number` + Input redshift. + + Returns + ------- + w : ndarray or float + The dark energy equation of state. + Returns `float` if the input is scalar. + + Notes + ----- + The dark energy equation of state is defined as + :math:`w(z) = P(z)/\rho(z)`, where :math:`P(z)` is the pressure at + redshift z and :math:`\rho(z)` is the density at redshift z, both in + units where c=1. Here this is given by :math:`w(z) = w_0 + w_z z`. + """ + ... + + def de_density_scale(self, z): + r"""Evaluates the redshift dependence of the dark energy density. + + Parameters + ---------- + z : Quantity-like ['redshift'], array-like, or `~numbers.Number` + Input redshift. + + Returns + ------- + I : ndarray or float + The scaling of the energy density of dark energy with redshift. + Returns `float` if the input is scalar. + + Notes + ----- + The scaling factor, I, is defined by :math:`\rho(z) = \rho_0 I`, + and in this case is given by + + .. math:: + + I = \left(1 + z\right)^{3 \left(1 + w_0 - w_z\right)} + \exp \left(-3 w_z z\right) + """ + ... + + + diff --git a/typings/astropy/cosmology/flrw/wpwazpcdm.pyi b/typings/astropy/cosmology/flrw/wpwazpcdm.pyi new file mode 100644 index 0000000..1298e92 --- /dev/null +++ b/typings/astropy/cosmology/flrw/wpwazpcdm.pyi @@ -0,0 +1,152 @@ +""" +This type stub file was generated by pyright. +""" + +from .base import FLRW + +__all__ = ["wpwaCDM"] +__doctest_requires__ = ... +class wpwaCDM(FLRW): + r""" + FLRW cosmology with a CPL dark energy equation of state, a pivot redshift, + and curvature. + + The equation for the dark energy equation of state uses the CPL form as + described in Chevallier & Polarski [1]_ and Linder [2]_, but modified to + have a pivot redshift as in the findings of the Dark Energy Task Force + [3]_: :math:`w(a) = w_p + w_a (a_p - a) = w_p + w_a( 1/(1+zp) - 1/(1+z) )`. + + Parameters + ---------- + H0 : float or scalar quantity-like ['frequency'] + Hubble constant at z = 0. If a float, must be in [km/sec/Mpc]. + + Om0 : float + Omega matter: density of non-relativistic matter in units of the + critical density at z=0. + + Ode0 : float + Omega dark energy: density of dark energy in units of the critical + density at z=0. + + wp : float, optional + Dark energy equation of state at the pivot redshift zp. This is + pressure/density for dark energy in units where c=1. + + wa : float, optional + Negative derivative of the dark energy equation of state with respect + to the scale factor. A cosmological constant has wp=-1.0 and wa=0.0. + + zp : float or quantity-like ['redshift'], optional + Pivot redshift -- the redshift where w(z) = wp + + Tcmb0 : float or scalar quantity-like ['temperature'], optional + Temperature of the CMB z=0. If a float, must be in [K]. Default: 0 [K]. + Setting this to zero will turn off both photons and neutrinos + (even massive ones). + + Neff : float, optional + Effective number of Neutrino species. Default 3.04. + + m_nu : quantity-like ['energy', 'mass'] or array-like, optional + Mass of each neutrino species in [eV] (mass-energy equivalency enabled). + If this is a scalar Quantity, then all neutrino species are assumed to + have that mass. Otherwise, the mass of each species. The actual number + of neutrino species (and hence the number of elements of m_nu if it is + not scalar) must be the floor of Neff. Typically this means you should + provide three neutrino masses unless you are considering something like + a sterile neutrino. + + Ob0 : float or None, optional + Omega baryons: density of baryonic matter in units of the critical + density at z=0. If this is set to None (the default), any computation + that requires its value will raise an exception. + + name : str or None (optional, keyword-only) + Name for this cosmological object. + + meta : mapping or None (optional, keyword-only) + Metadata for the cosmology, e.g., a reference. + + Examples + -------- + >>> from astropy.cosmology import wpwaCDM + >>> cosmo = wpwaCDM(H0=70, Om0=0.3, Ode0=0.7, wp=-0.9, wa=0.2, zp=0.4) + + The comoving distance in Mpc at redshift z: + + >>> z = 0.5 + >>> dc = cosmo.comoving_distance(z) + + References + ---------- + .. [1] Chevallier, M., & Polarski, D. (2001). Accelerating Universes with + Scaling Dark Matter. International Journal of Modern Physics D, + 10(2), 213-223. + .. [2] Linder, E. (2003). Exploring the Expansion History of the + Universe. Phys. Rev. Lett., 90, 091301. + .. [3] Albrecht, A., Amendola, L., Bernstein, G., Clowe, D., Eisenstein, + D., Guzzo, L., Hirata, C., Huterer, D., Kirshner, R., Kolb, E., & + Nichol, R. (2009). Findings of the Joint Dark Energy Mission Figure + of Merit Science Working Group. arXiv e-prints, arXiv:0901.0721. + """ + wp = ... + wa = ... + zp = ... + def __init__(self, H0, Om0, Ode0, wp=..., wa=..., zp=..., Tcmb0=..., Neff=..., m_nu=..., Ob0=..., *, name=..., meta=...) -> None: + ... + + def w(self, z): + r"""Returns dark energy equation of state at redshift ``z``. + + Parameters + ---------- + z : Quantity-like ['redshift'], array-like, or `~numbers.Number` + Input redshift. + + Returns + ------- + w : ndarray or float + The dark energy equation of state + Returns `float` if the input is scalar. + + Notes + ----- + The dark energy equation of state is defined as + :math:`w(z) = P(z)/\rho(z)`, where :math:`P(z)` is the pressure at + redshift z and :math:`\rho(z)` is the density at redshift z, both in + units where c=1. Here this is :math:`w(z) = w_p + w_a (a_p - a)` where + :math:`a = 1/1+z` and :math:`a_p = 1 / 1 + z_p`. + """ + ... + + def de_density_scale(self, z): + r"""Evaluates the redshift dependence of the dark energy density. + + Parameters + ---------- + z : Quantity-like ['redshift'], array-like, or `~numbers.Number` + Input redshift. + + Returns + ------- + I : ndarray or float + The scaling of the energy density of dark energy with redshift. + Returns `float` if the input is scalar. + + Notes + ----- + The scaling factor, I, is defined by :math:`\rho(z) = \rho_0 I`, + and in this case is given by + + .. math:: + + a_p = \frac{1}{1 + z_p} + + I = \left(1 + z\right)^{3 \left(1 + w_p + a_p w_a\right)} + \exp \left(-3 w_a \frac{z}{1+z}\right) + """ + ... + + + diff --git a/typings/astropy/cosmology/funcs.pyi b/typings/astropy/cosmology/funcs.pyi new file mode 100644 index 0000000..28e110c --- /dev/null +++ b/typings/astropy/cosmology/funcs.pyi @@ -0,0 +1,235 @@ +""" +This type stub file was generated by pyright. +""" + +""" +Convenience functions for `astropy.cosmology`. +""" +__all__ = ['z_at_value'] +__doctest_requires__ = ... +def z_at_value(func, fval, zmin=..., zmax=..., ztol=..., maxfun=..., method=..., bracket=..., verbose=...): # -> Any: + """Find the redshift ``z`` at which ``func(z) = fval``. + + This finds the redshift at which one of the cosmology functions or + methods (for example Planck13.distmod) is equal to a known value. + + .. warning:: + Make sure you understand the behavior of the function that you are + trying to invert! Depending on the cosmology, there may not be a + unique solution. For example, in the standard Lambda CDM cosmology, + there are two redshifts which give an angular diameter distance of + 1500 Mpc, z ~ 0.7 and z ~ 3.8. To force ``z_at_value`` to find the + solution you are interested in, use the ``zmin`` and ``zmax`` keywords + to limit the search range (see the example below). + + Parameters + ---------- + func : function or method + A function that takes a redshift as input. + + fval : `~astropy.units.Quantity` + The (scalar or array) value of ``func(z)`` to recover. + + zmin : float or array-like['dimensionless'] or quantity-like, optional + The lower search limit for ``z``. Beware of divergences + in some cosmological functions, such as distance moduli, + at z=0 (default 1e-8). + + zmax : float or array-like['dimensionless'] or quantity-like, optional + The upper search limit for ``z`` (default 1000). + + ztol : float or array-like['dimensionless'], optional + The relative error in ``z`` acceptable for convergence. + + maxfun : int or array-like, optional + The maximum number of function evaluations allowed in the + optimization routine (default 500). + + method : str or callable, optional + Type of solver to pass to the minimizer. The built-in options provided + by :func:`~scipy.optimize.minimize_scalar` are 'Brent' (default), + 'Golden' and 'Bounded' with names case insensitive - see documentation + there for details. It also accepts a custom solver by passing any + user-provided callable object that meets the requirements listed + therein under the Notes on "Custom minimizers" - or in more detail in + :doc:`scipy:tutorial/optimize` - although their use is currently + untested. + + .. versionadded:: 4.3 + + bracket : sequence or object array[sequence], optional + For methods 'Brent' and 'Golden', ``bracket`` defines the bracketing + interval and can either have three items (z1, z2, z3) so that + z1 < z2 < z3 and ``func(z2) < func (z1), func(z3)`` or two items z1 + and z3 which are assumed to be a starting interval for a downhill + bracket search. For non-monotonic functions such as angular diameter + distance this may be used to start the search on the desired side of + the maximum, but see Examples below for usage notes. + + .. versionadded:: 4.3 + + verbose : bool, optional + Print diagnostic output from solver (default `False`). + + .. versionadded:: 4.3 + + Returns + ------- + z : `~astropy.units.Quantity` ['redshift'] + The redshift ``z`` satisfying ``zmin < z < zmax`` and ``func(z) = + fval`` within ``ztol``. Has units of cosmological redshift. + + Warns + ----- + :class:`~astropy.utils.exceptions.AstropyUserWarning` + If ``fval`` is not bracketed by ``func(zmin)=fval(zmin)`` and + ``func(zmax)=fval(zmax)``. + + If the solver was not successful. + + Raises + ------ + :class:`astropy.cosmology.CosmologyError` + If the result is very close to either ``zmin`` or ``zmax``. + ValueError + If ``bracket`` is not an array nor a 2 (or 3) element sequence. + TypeError + If ``bracket`` is not an object array. 2 (or 3) element sequences will + be turned into object arrays, so this error should only occur if a + non-object array is used for ``bracket``. + + Notes + ----- + This works for any arbitrary input cosmology, but is inefficient if you + want to invert a large number of values for the same cosmology. In this + case, it is faster to instead generate an array of values at many + closely-spaced redshifts that cover the relevant redshift range, and then + use interpolation to find the redshift at each value you are interested + in. For example, to efficiently find the redshifts corresponding to 10^6 + values of the distance modulus in a Planck13 cosmology, you could do the + following: + + >>> import astropy.units as u + >>> from astropy.cosmology import Planck13, z_at_value + + Generate 10^6 distance moduli between 24 and 44 for which we + want to find the corresponding redshifts: + + >>> Dvals = (24 + np.random.rand(1000000) * 20) * u.mag + + Make a grid of distance moduli covering the redshift range we + need using 50 equally log-spaced values between zmin and + zmax. We use log spacing to adequately sample the steep part of + the curve at low distance moduli: + + >>> zmin = z_at_value(Planck13.distmod, Dvals.min()) + >>> zmax = z_at_value(Planck13.distmod, Dvals.max()) + >>> zgrid = np.geomspace(zmin, zmax, 50) + >>> Dgrid = Planck13.distmod(zgrid) + + Finally interpolate to find the redshift at each distance modulus: + + >>> zvals = np.interp(Dvals.value, Dgrid.value, zgrid) + + Examples + -------- + >>> import astropy.units as u + >>> from astropy.cosmology import Planck13, Planck18, z_at_value + + The age and lookback time are monotonic with redshift, and so a + unique solution can be found: + + >>> z_at_value(Planck13.age, 2 * u.Gyr) # doctest: +FLOAT_CMP + + + The angular diameter is not monotonic however, and there are two + redshifts that give a value of 1500 Mpc. You can use the zmin and + zmax keywords to find the one you are interested in: + + >>> z_at_value(Planck18.angular_diameter_distance, + ... 1500 * u.Mpc, zmax=1.5) # doctest: +FLOAT_CMP + + >>> z_at_value(Planck18.angular_diameter_distance, + ... 1500 * u.Mpc, zmin=2.5) # doctest: +FLOAT_CMP + + + Alternatively the ``bracket`` option may be used to initialize the + function solver on a desired region, but one should be aware that this + does not guarantee it will remain close to this starting bracket. + For the example of angular diameter distance, which has a maximum near + a redshift of 1.6 in this cosmology, defining a bracket on either side + of this maximum will often return a solution on the same side: + + >>> z_at_value(Planck18.angular_diameter_distance, + ... 1500 * u.Mpc, bracket=(1.0, 1.2)) # doctest: +FLOAT_CMP +IGNORE_WARNINGS + + + But this is not ascertained especially if the bracket is chosen too wide + and/or too close to the turning point: + + >>> z_at_value(Planck18.angular_diameter_distance, + ... 1500 * u.Mpc, bracket=(0.1, 1.5)) # doctest: +SKIP + # doctest: +SKIP + + Likewise, even for the same minimizer and same starting conditions different + results can be found depending on architecture or library versions: + + >>> z_at_value(Planck18.angular_diameter_distance, + ... 1500 * u.Mpc, bracket=(2.0, 2.5)) # doctest: +SKIP + # doctest: +SKIP + + >>> z_at_value(Planck18.angular_diameter_distance, + ... 1500 * u.Mpc, bracket=(2.0, 2.5)) # doctest: +SKIP + # doctest: +SKIP + + It is therefore generally safer to use the 3-parameter variant to ensure + the solution stays within the bracketing limits: + + >>> z_at_value(Planck18.angular_diameter_distance, 1500 * u.Mpc, + ... bracket=(0.1, 1.0, 1.5)) # doctest: +FLOAT_CMP + + + Also note that the luminosity distance and distance modulus (two + other commonly inverted quantities) are monotonic in flat and open + universes, but not in closed universes. + + All the arguments except ``func``, ``method`` and ``verbose`` accept array + inputs. This does NOT use interpolation tables or any method to speed up + evaluations, rather providing a convenient means to broadcast arguments + over an element-wise scalar evaluation. + + The most common use case for non-scalar input is to evaluate 'func' for an + array of ``fval``: + + >>> z_at_value(Planck13.age, [2, 7] * u.Gyr) # doctest: +FLOAT_CMP + + + ``fval`` can be any shape: + + >>> z_at_value(Planck13.age, [[2, 7], [1, 3]]*u.Gyr) # doctest: +FLOAT_CMP + + + Other arguments can be arrays. For non-monotic functions -- for example, + the angular diameter distance -- this can be useful to find all solutions. + + >>> z_at_value(Planck13.angular_diameter_distance, 1500 * u.Mpc, + ... zmin=[0, 2.5], zmax=[2, 4]) # doctest: +FLOAT_CMP + + + The ``bracket`` argument can likewise be be an array. However, since + bracket must already be a sequence (or None), it MUST be given as an + object `numpy.ndarray`. Importantly, the depth of the array must be such + that each bracket subsequence is an object. Errors or unexpected results + will happen otherwise. A convenient means to ensure the right depth is by + including a length-0 tuple as a bracket and then truncating the object + array to remove the placeholder. This can be seen in the following + example: + + >>> bracket=np.array([(1.0, 1.2),(2.0, 2.5), ()], dtype=object)[:-1] + >>> z_at_value(Planck18.angular_diameter_distance, 1500 * u.Mpc, + ... bracket=bracket) # doctest: +SKIP + + """ + ... + diff --git a/typings/astropy/cosmology/io/__init__.pyi b/typings/astropy/cosmology/io/__init__.pyi new file mode 100644 index 0000000..f3d483b --- /dev/null +++ b/typings/astropy/cosmology/io/__init__.pyi @@ -0,0 +1,9 @@ +""" +This type stub file was generated by pyright. +""" + +from . import cosmology, ecsv, mapping, model, row, table, yaml + +""" +Read/Write/Interchange methods for `astropy.cosmology`. **NOT public API**. +""" diff --git a/typings/astropy/cosmology/io/cosmology.pyi b/typings/astropy/cosmology/io/cosmology.pyi new file mode 100644 index 0000000..461738c --- /dev/null +++ b/typings/astropy/cosmology/io/cosmology.pyi @@ -0,0 +1,63 @@ +""" +This type stub file was generated by pyright. +""" + +""" +The following are private functions. These functions are registered into +:meth:`~astropy.cosmology.Cosmology.to_format` and +:meth:`~astropy.cosmology.Cosmology.from_format` and should only be accessed +via these methods. +""" +__all__ = [] +def from_cosmology(cosmo, /, **kwargs): + """Return the |Cosmology| unchanged. + + Parameters + ---------- + cosmo : `~astropy.cosmology.Cosmology` + The cosmology to return. + **kwargs + This argument is required for compatibility with the standard set of + keyword arguments in format `~astropy.cosmology.Cosmology.from_format`, + e.g. "cosmology". If "cosmology" is included and is not `None`, + ``cosmo`` is checked for correctness. + + Returns + ------- + `~astropy.cosmology.Cosmology` subclass instance + Just ``cosmo`` passed through. + + Raises + ------ + TypeError + If the |Cosmology| object is not an instance of ``cosmo`` (and + ``cosmology`` is not `None`). + """ + ... + +def to_cosmology(cosmo, *args): + """Return the |Cosmology| unchanged. + + Parameters + ---------- + cosmo : `~astropy.cosmology.Cosmology` + The cosmology to return. + *args + Not used. + + Returns + ------- + `~astropy.cosmology.Cosmology` subclass instance + Just ``cosmo`` passed through. + """ + ... + +def cosmology_identify(origin, format, *args, **kwargs): # -> bool: + """Identify if object is a `~astropy.cosmology.Cosmology`. + + Returns + ------- + bool + """ + ... + diff --git a/typings/astropy/cosmology/io/ecsv.pyi b/typings/astropy/cosmology/io/ecsv.pyi new file mode 100644 index 0000000..c889729 --- /dev/null +++ b/typings/astropy/cosmology/io/ecsv.pyi @@ -0,0 +1,76 @@ +""" +This type stub file was generated by pyright. +""" + +def read_ecsv(filename, index=..., *, move_to_meta=..., cosmology=..., **kwargs): + """Read a `~astropy.cosmology.Cosmology` from an ECSV file. + + Parameters + ---------- + filename : path-like or file-like + From where to read the Cosmology. + index : int, str, or None, optional + Needed to select the row in tables with multiple rows. ``index`` can be + an integer for the row number or, if the table is indexed by a column, + the value of that column. If the table is not indexed and ``index`` + is a string, the "name" column is used as the indexing column. + + move_to_meta : bool (optional, keyword-only) + Whether to move keyword arguments that are not in the Cosmology class' + signature to the Cosmology's metadata. This will only be applied if the + Cosmology does NOT have a keyword-only argument (e.g. ``**kwargs``). + Arguments moved to the metadata will be merged with existing metadata, + preferring specified metadata in the case of a merge conflict + (e.g. for ``Cosmology(meta={'key':10}, key=42)``, the ``Cosmology.meta`` + will be ``{'key': 10}``). + + cosmology : str, `~astropy.cosmology.Cosmology` class, or None (optional, keyword-only) + The cosmology class (or string name thereof) to use when constructing + the cosmology instance. The class also provides default parameter values, + filling in any non-mandatory arguments missing in 'table'. + + **kwargs + Passed to :attr:`astropy.table.QTable.read` + + Returns + ------- + `~astropy.cosmology.Cosmology` subclass instance + """ + ... + +def write_ecsv(cosmology, file, *, overwrite=..., cls=..., cosmology_in_meta=..., **kwargs): # -> None: + """Serialize the cosmology into a ECSV. + + Parameters + ---------- + cosmology : `~astropy.cosmology.Cosmology` subclass instance + file : path-like or file-like + Location to save the serialized cosmology. + + overwrite : bool + Whether to overwrite the file, if it exists. + cls : type (optional, keyword-only) + Astropy :class:`~astropy.table.Table` (sub)class to use when writing. + Default is :class:`~astropy.table.QTable`. + cosmology_in_meta : bool + Whether to put the cosmology class in the Table metadata (if `True`, + default) or as the first column (if `False`). + **kwargs + Passed to ``cls.write`` + + Raises + ------ + TypeError + If kwarg (optional) 'cls' is not a subclass of `astropy.table.Table` + """ + ... + +def ecsv_identify(origin, filepath, fileobj, *args, **kwargs): # -> Literal[False]: + """Identify if object uses the Table format. + + Returns + ------- + bool + """ + ... + diff --git a/typings/astropy/cosmology/io/mapping.pyi b/typings/astropy/cosmology/io/mapping.pyi new file mode 100644 index 0000000..dc65564 --- /dev/null +++ b/typings/astropy/cosmology/io/mapping.pyi @@ -0,0 +1,157 @@ +""" +This type stub file was generated by pyright. +""" + +""" +The following are private functions, included here **FOR REFERENCE ONLY** since +the io registry cannot be displayed. These functions are registered into +:meth:`~astropy.cosmology.Cosmology.to_format` and +:meth:`~astropy.cosmology.Cosmology.from_format` and should only be accessed +via these methods. +""" +__all__ = [] +def from_mapping(map, *, move_to_meta=..., cosmology=...): + """Load `~astropy.cosmology.Cosmology` from mapping object. + + Parameters + ---------- + map : mapping + Arguments into the class -- like "name" or "meta". + If 'cosmology' is None, must have field "cosmology" which can be either + the string name of the cosmology class (e.g. "FlatLambdaCDM") or the + class itself. + + move_to_meta : bool (optional, keyword-only) + Whether to move keyword arguments that are not in the Cosmology class' + signature to the Cosmology's metadata. This will only be applied if the + Cosmology does NOT have a keyword-only argument (e.g. ``**kwargs``). + Arguments moved to the metadata will be merged with existing metadata, + preferring specified metadata in the case of a merge conflict + (e.g. for ``Cosmology(meta={'key':10}, key=42)``, the ``Cosmology.meta`` + will be ``{'key': 10}``). + + cosmology : str, `~astropy.cosmology.Cosmology` class, or None (optional, keyword-only) + The cosmology class (or string name thereof) to use when constructing + the cosmology instance. The class also provides default parameter values, + filling in any non-mandatory arguments missing in 'map'. + + Returns + ------- + `~astropy.cosmology.Cosmology` subclass instance + + Examples + -------- + To see loading a `~astropy.cosmology.Cosmology` from a dictionary with + ``from_mapping``, we will first make a mapping using + :meth:`~astropy.cosmology.Cosmology.to_format`. + + >>> from astropy.cosmology import Cosmology, Planck18 + >>> cm = Planck18.to_format('mapping') + >>> cm + {'cosmology': , + 'name': 'Planck18', 'H0': , 'Om0': 0.30966, + 'Tcmb0': , 'Neff': 3.046, + 'm_nu': , 'Ob0': 0.04897, + 'meta': ... + + Now this dict can be used to load a new cosmological instance identical + to the ``Planck18`` cosmology from which it was generated. + + >>> cosmo = Cosmology.from_format(cm, format="mapping") + >>> cosmo + FlatLambdaCDM(name="Planck18", H0=67.66 km / (Mpc s), Om0=0.30966, + Tcmb0=2.7255 K, Neff=3.046, m_nu=[0. 0. 0.06] eV, Ob0=0.04897) + + Specific cosmology classes can be used to parse the data. The class' + default parameter values are used to fill in any information missing in the + data. + + >>> from astropy.cosmology import FlatLambdaCDM + >>> del cm["Tcmb0"] # show FlatLambdaCDM provides default + >>> FlatLambdaCDM.from_format(cm) + FlatLambdaCDM(name="Planck18", H0=67.66 km / (Mpc s), Om0=0.30966, + Tcmb0=0.0 K, Neff=3.046, m_nu=None, Ob0=0.04897) + """ + ... + +def to_mapping(cosmology, *args, cls=..., cosmology_as_str=..., move_from_meta=...): # -> dict[Unknown, Unknown]: + """Return the cosmology class, parameters, and metadata as a `dict`. + + Parameters + ---------- + cosmology : `~astropy.cosmology.Cosmology` subclass instance + *args + Not used. Needed for compatibility with + `~astropy.io.registry.UnifiedReadWriteMethod` + cls : type (optional, keyword-only) + `dict` or `collections.Mapping` subclass. + The mapping type to return. Default is `dict`. + cosmology_as_str : bool (optional, keyword-only) + Whether the cosmology value is the class (if `False`, default) or + the semi-qualified name (if `True`). + move_from_meta : bool (optional, keyword-only) + Whether to add the Cosmology's metadata as an item to the mapping (if + `False`, default) or to merge with the rest of the mapping, preferring + the original values (if `True`) + + Returns + ------- + dict + with key-values for the cosmology parameters and also: + - 'cosmology' : the class + - 'meta' : the contents of the cosmology's metadata attribute. + If ``move_from_meta`` is `True`, this key is missing and the + contained metadata are added to the main `dict`. + + Examples + -------- + A Cosmology as a mapping will have the cosmology's name and + parameters as items, and the metadata as a nested dictionary. + + >>> from astropy.cosmology import Planck18 + >>> Planck18.to_format('mapping') + {'cosmology': , + 'name': 'Planck18', 'H0': , 'Om0': 0.30966, + 'Tcmb0': , 'Neff': 3.046, + 'm_nu': , 'Ob0': 0.04897, + 'meta': ... + + The dictionary type may be changed with the ``cls`` keyword argument: + + >>> from collections import OrderedDict + >>> Planck18.to_format('mapping', cls=OrderedDict) + OrderedDict([('cosmology', ), + ('name', 'Planck18'), ('H0', ), + ('Om0', 0.30966), ('Tcmb0', ), ('Neff', 3.046), + ('m_nu', ), ('Ob0', 0.04897), + ('meta', ... + + Sometimes it is more useful to have the name of the cosmology class, not + the object itself. The keyword argument ``cosmology_as_str`` may be used: + + >>> Planck18.to_format('mapping', cosmology_as_str=True) + {'cosmology': 'FlatLambdaCDM', ... + + The metadata is normally included as a nested mapping. To move the metadata + into the main mapping, use the keyword argument ``move_from_meta``. This + kwarg inverts ``move_to_meta`` in + ``Cosmology.to_format("mapping", move_to_meta=...)`` where extra items + are moved to the metadata (if the cosmology constructor does not have a + variable keyword-only argument -- ``**kwargs``). + + >>> from astropy.cosmology import Planck18 + >>> Planck18.to_format('mapping', move_from_meta=True) + {'cosmology': , + 'name': 'Planck18', 'Oc0': 0.2607, 'n': 0.9665, 'sigma8': 0.8102, ... + """ + ... + +def mapping_identify(origin, format, *args, **kwargs): # -> bool: + """Identify if object uses the mapping format. + + Returns + ------- + bool + """ + ... + diff --git a/typings/astropy/cosmology/io/model.pyi b/typings/astropy/cosmology/io/model.pyi new file mode 100644 index 0000000..544e2dd --- /dev/null +++ b/typings/astropy/cosmology/io/model.pyi @@ -0,0 +1,136 @@ +""" +This type stub file was generated by pyright. +""" + +from astropy.modeling import FittableModel +from astropy.utils.decorators import classproperty + +""" +The following are private functions, included here **FOR REFERENCE ONLY** since +the io registry cannot be displayed. These functions are registered into +:meth:`~astropy.cosmology.Cosmology.to_format` and +:meth:`~astropy.cosmology.Cosmology.from_format` and should only be accessed +via these methods. +""" +__all__ = [] +class _CosmologyModel(FittableModel): + """Base class for Cosmology redshift-method Models. + + .. note:: + + This class is not publicly scoped so should not be used directly. + Instead, from a Cosmology instance use ``.to_format("astropy.model")`` + to create an instance of a subclass of this class. + + `_CosmologyModel` (subclasses) wrap a redshift-method of a + :class:`~astropy.cosmology.Cosmology` class, converting each non-`None` + |Cosmology| :class:`~astropy.cosmology.Parameter` to a + :class:`astropy.modeling.Model` :class:`~astropy.modeling.Parameter` + and the redshift-method to the model's ``__call__ / evaluate``. + + See Also + -------- + astropy.cosmology.Cosmology.to_format + """ + @classproperty + def cosmology_class(cls): # -> () -> None: + """|Cosmology| class.""" + ... + + @property + def cosmology(self): + """Return |Cosmology| using `~astropy.modeling.Parameter` values.""" + ... + + @classproperty + def method_name(self): # -> () -> None: + """Redshift-method name on |Cosmology| instance.""" + ... + + def evaluate(self, *args, **kwargs): # -> Any: + """Evaluate method {method!r} of {cosmo_cls!r} Cosmology. + + The Model wraps the :class:`~astropy.cosmology.Cosmology` method, + converting each |Cosmology| :class:`~astropy.cosmology.Parameter` to a + :class:`astropy.modeling.Model` :class:`~astropy.modeling.Parameter` + (unless the Parameter is None, in which case it is skipped). + Here an instance of the cosmology is created using the current + Parameter values and the method is evaluated given the input. + + Parameters + ---------- + *args, **kwargs + The first ``n_inputs`` of ``*args`` are for evaluating the method + of the cosmology. The remaining args and kwargs are passed to the + cosmology class constructor. + Any unspecified Cosmology Parameter use the current value of the + corresponding Model Parameter. + + Returns + ------- + Any + Results of evaluating the Cosmology method. + """ + ... + + + +def from_model(model): + """Load |Cosmology| from `~astropy.modeling.Model` object. + + Parameters + ---------- + model : `_CosmologyModel` subclass instance + See ``Cosmology.to_format.help("astropy.model") for details. + + Returns + ------- + `~astropy.cosmology.Cosmology` subclass instance + + Examples + -------- + >>> from astropy.cosmology import Cosmology, Planck18 + >>> model = Planck18.to_format("astropy.model", method="lookback_time") + >>> Cosmology.from_format(model) + FlatLambdaCDM(name="Planck18", H0=67.66 km / (Mpc s), Om0=0.30966, + Tcmb0=2.7255 K, Neff=3.046, m_nu=[0. 0. 0.06] eV, Ob0=0.04897) + """ + ... + +def to_model(cosmology, *_, method): # -> Any: + """Convert a `~astropy.cosmology.Cosmology` to a `~astropy.modeling.Model`. + + Parameters + ---------- + cosmology : `~astropy.cosmology.Cosmology` subclass instance + method : str, keyword-only + The name of the method on the ``cosmology``. + + Returns + ------- + `_CosmologyModel` subclass instance + The Model wraps the |Cosmology| method, converting each non-`None` + :class:`~astropy.cosmology.Parameter` to a + :class:`astropy.modeling.Model` :class:`~astropy.modeling.Parameter` + and the method to the model's ``__call__ / evaluate``. + + Examples + -------- + >>> from astropy.cosmology import Planck18 + >>> model = Planck18.to_format("astropy.model", method="lookback_time") + >>> model + + """ + ... + +def model_identify(origin, format, *args, **kwargs): # -> bool: + """Identify if object uses the :class:`~astropy.modeling.Model` format. + + Returns + ------- + bool + """ + ... + diff --git a/typings/astropy/cosmology/io/row.pyi b/typings/astropy/cosmology/io/row.pyi new file mode 100644 index 0000000..c8f0dd1 --- /dev/null +++ b/typings/astropy/cosmology/io/row.pyi @@ -0,0 +1,107 @@ +""" +This type stub file was generated by pyright. +""" + +def from_row(row, *, move_to_meta=..., cosmology=...): + """Instantiate a `~astropy.cosmology.Cosmology` from a `~astropy.table.Row`. + + Parameters + ---------- + row : `~astropy.table.Row` + The object containing the Cosmology information. + move_to_meta : bool (optional, keyword-only) + Whether to move keyword arguments that are not in the Cosmology class' + signature to the Cosmology's metadata. This will only be applied if the + Cosmology does NOT have a keyword-only argument (e.g. ``**kwargs``). + Arguments moved to the metadata will be merged with existing metadata, + preferring specified metadata in the case of a merge conflict + (e.g. for ``Cosmology(meta={'key':10}, key=42)``, the ``Cosmology.meta`` + will be ``{'key': 10}``). + + cosmology : str, `~astropy.cosmology.Cosmology` class, or None (optional, keyword-only) + The cosmology class (or string name thereof) to use when constructing + the cosmology instance. The class also provides default parameter values, + filling in any non-mandatory arguments missing in 'table'. + + Returns + ------- + `~astropy.cosmology.Cosmology` subclass instance + + Examples + -------- + To see loading a `~astropy.cosmology.Cosmology` from a Row with + ``from_row``, we will first make a `~astropy.table.Row` using + :func:`~astropy.cosmology.Cosmology.to_format`. + + >>> from astropy.cosmology import Cosmology, Planck18 + >>> cr = Planck18.to_format("astropy.row") + >>> cr + + cosmology name H0 Om0 Tcmb0 Neff m_nu Ob0 + km / (Mpc s) K eV + str13 str8 float64 float64 float64 float64 float64[3] float64 + ------------- -------- ------------ ------- ------- ------- ----------- ------- + FlatLambdaCDM Planck18 67.66 0.30966 2.7255 3.046 0.0 .. 0.06 0.04897 + + Now this row can be used to load a new cosmological instance identical + to the ``Planck18`` cosmology from which it was generated. + + >>> cosmo = Cosmology.from_format(cr, format="astropy.row") + >>> cosmo + FlatLambdaCDM(name="Planck18", H0=67.66 km / (Mpc s), Om0=0.30966, + Tcmb0=2.7255 K, Neff=3.046, m_nu=[0. 0. 0.06] eV, Ob0=0.04897) + """ + ... + +def to_row(cosmology, *args, cosmology_in_meta=..., table_cls=...): # -> _VT@OrderedDict | TableColumns | Row | QTable: + """Serialize the cosmology into a `~astropy.table.Row`. + + Parameters + ---------- + cosmology : `~astropy.cosmology.Cosmology` subclass instance + *args + Not used. Needed for compatibility with + `~astropy.io.registry.UnifiedReadWriteMethod` + table_cls : type (optional, keyword-only) + Astropy :class:`~astropy.table.Table` class or subclass type to use. + Default is :class:`~astropy.table.QTable`. + cosmology_in_meta : bool + Whether to put the cosmology class in the Table metadata (if `True`) or + as the first column (if `False`, default). + + Returns + ------- + `~astropy.table.Row` + With columns for the cosmology parameters, and metadata in the Table's + ``meta`` attribute. The cosmology class name will either be a column + or in ``meta``, depending on 'cosmology_in_meta'. + + Examples + -------- + A Cosmology as a `~astropy.table.Row` will have the cosmology's name and + parameters as columns. + + >>> from astropy.cosmology import Planck18 + >>> cr = Planck18.to_format("astropy.row") + >>> cr + + cosmology name H0 Om0 Tcmb0 Neff m_nu Ob0 + km / (Mpc s) K eV + str13 str8 float64 float64 float64 float64 float64[3] float64 + ------------- -------- ------------ ------- ------- ------- ----------- ------- + FlatLambdaCDM Planck18 67.66 0.30966 2.7255 3.046 0.0 .. 0.06 0.04897 + + The cosmological class and other metadata, e.g. a paper reference, are in + the Table's metadata. + """ + ... + +def row_identify(origin, format, *args, **kwargs): # -> bool: + """Identify if object uses the `~astropy.table.Row` format. + + Returns + ------- + bool + """ + ... + diff --git a/typings/astropy/cosmology/io/table.pyi b/typings/astropy/cosmology/io/table.pyi new file mode 100644 index 0000000..078a2c7 --- /dev/null +++ b/typings/astropy/cosmology/io/table.pyi @@ -0,0 +1,180 @@ +""" +This type stub file was generated by pyright. +""" + +def from_table(table, index=..., *, move_to_meta=..., cosmology=...): + """Instantiate a `~astropy.cosmology.Cosmology` from a |QTable|. + + Parameters + ---------- + table : `~astropy.table.Table` + The object to parse into a |Cosmology|. + index : int, str, or None, optional + Needed to select the row in tables with multiple rows. ``index`` can be + an integer for the row number or, if the table is indexed by a column, + the value of that column. If the table is not indexed and ``index`` + is a string, the "name" column is used as the indexing column. + + move_to_meta : bool (optional, keyword-only) + Whether to move keyword arguments that are not in the Cosmology class' + signature to the Cosmology's metadata. This will only be applied if the + Cosmology does NOT have a keyword-only argument (e.g. ``**kwargs``). + Arguments moved to the metadata will be merged with existing metadata, + preferring specified metadata in the case of a merge conflict + (e.g. for ``Cosmology(meta={'key':10}, key=42)``, the ``Cosmology.meta`` + will be ``{'key': 10}``). + + cosmology : str, `~astropy.cosmology.Cosmology` class, or None (optional, keyword-only) + The cosmology class (or string name thereof) to use when constructing + the cosmology instance. The class also provides default parameter values, + filling in any non-mandatory arguments missing in 'table'. + + Returns + ------- + `~astropy.cosmology.Cosmology` subclass instance + + Examples + -------- + To see loading a `~astropy.cosmology.Cosmology` from a Table with + ``from_table``, we will first make a |QTable| using + :func:`~astropy.cosmology.Cosmology.to_format`. + + >>> from astropy.cosmology import Cosmology, Planck18 + >>> ct = Planck18.to_format("astropy.table") + >>> ct + + name H0 Om0 Tcmb0 Neff m_nu Ob0 + km / (Mpc s) K eV + str8 float64 float64 float64 float64 float64[3] float64 + -------- ------------ ------- ------- ------- ----------- ------- + Planck18 67.66 0.30966 2.7255 3.046 0.0 .. 0.06 0.04897 + + Now this table can be used to load a new cosmological instance identical + to the ``Planck18`` cosmology from which it was generated. + + >>> cosmo = Cosmology.from_format(ct, format="astropy.table") + >>> cosmo + FlatLambdaCDM(name="Planck18", H0=67.66 km / (Mpc s), Om0=0.30966, + Tcmb0=2.7255 K, Neff=3.046, m_nu=[0. 0. 0.06] eV, Ob0=0.04897) + + Specific cosmology classes can be used to parse the data. The class' + default parameter values are used to fill in any information missing in the + data. + + >>> from astropy.cosmology import FlatLambdaCDM + >>> del ct["Tcmb0"] # show FlatLambdaCDM provides default + >>> FlatLambdaCDM.from_format(ct) + FlatLambdaCDM(name="Planck18", H0=67.66 km / (Mpc s), Om0=0.30966, + Tcmb0=0.0 K, Neff=3.046, m_nu=None, Ob0=0.04897) + + For tables with multiple rows of cosmological parameters, the ``index`` + argument is needed to select the correct row. The index can be an integer + for the row number or, if the table is indexed by a column, the value of + that column. If the table is not indexed and ``index`` is a string, the + "name" column is used as the indexing column. + + Here is an example where ``index`` is needed and can be either an integer + (for the row number) or the name of one of the cosmologies, e.g. 'Planck15'. + + >>> from astropy.cosmology import Planck13, Planck15, Planck18 + >>> from astropy.table import vstack + >>> cts = vstack([c.to_format("astropy.table") + ... for c in (Planck13, Planck15, Planck18)], + ... metadata_conflicts='silent') + >>> cts + + name H0 Om0 Tcmb0 Neff m_nu Ob0 + km / (Mpc s) K eV + str8 float64 float64 float64 float64 float64[3] float64 + -------- ------------ ------- ------- ------- ----------- -------- + Planck13 67.77 0.30712 2.7255 3.046 0.0 .. 0.06 0.048252 + Planck15 67.74 0.3075 2.7255 3.046 0.0 .. 0.06 0.0486 + Planck18 67.66 0.30966 2.7255 3.046 0.0 .. 0.06 0.04897 + + >>> cosmo = Cosmology.from_format(cts, index=1, format="astropy.table") + >>> cosmo == Planck15 + True + + For further examples, see :doc:`astropy:cosmology/io`. + """ + ... + +def to_table(cosmology, *args, cls=..., cosmology_in_meta=...): # -> QTable: + """Serialize the cosmology into a `~astropy.table.QTable`. + + Parameters + ---------- + cosmology : `~astropy.cosmology.Cosmology` subclass instance + *args + Not used. Needed for compatibility with + `~astropy.io.registry.UnifiedReadWriteMethod` + cls : type (optional, keyword-only) + Astropy :class:`~astropy.table.Table` class or subclass type to return. + Default is :class:`~astropy.table.QTable`. + cosmology_in_meta : bool + Whether to put the cosmology class in the Table metadata (if `True`, + default) or as the first column (if `False`). + + Returns + ------- + `~astropy.table.QTable` + With columns for the cosmology parameters, and metadata and + cosmology class name in the Table's ``meta`` attribute + + Raises + ------ + TypeError + If kwarg (optional) 'cls' is not a subclass of `astropy.table.Table` + + Examples + -------- + A Cosmology as a `~astropy.table.QTable` will have the cosmology's name and + parameters as columns. + + >>> from astropy.cosmology import Planck18 + >>> ct = Planck18.to_format("astropy.table") + >>> ct + + name H0 Om0 Tcmb0 Neff m_nu Ob0 + km / (Mpc s) K eV + str8 float64 float64 float64 float64 float64[3] float64 + -------- ------------ ------- ------- ------- ----------- ------- + Planck18 67.66 0.30966 2.7255 3.046 0.0 .. 0.06 0.04897 + + The cosmological class and other metadata, e.g. a paper reference, are in + the Table's metadata. + + >>> ct.meta + OrderedDict([..., ('cosmology', 'FlatLambdaCDM')]) + + To move the cosmology class from the metadata to a Table row, set the + ``cosmology_in_meta`` argument to `False`: + + >>> Planck18.to_format("astropy.table", cosmology_in_meta=False) + + cosmology name H0 Om0 Tcmb0 Neff m_nu Ob0 + km / (Mpc s) K eV + str13 str8 float64 float64 float64 float64 float64[3] float64 + ------------- -------- ------------ ------- ------- ------- ----------- ------- + FlatLambdaCDM Planck18 67.66 0.30966 2.7255 3.046 0.0 .. 0.06 0.04897 + + Astropy recommends `~astropy.table.QTable` for tables with + `~astropy.units.Quantity` columns. However the returned type may be + overridden using the ``cls`` argument: + + >>> from astropy.table import Table + >>> Planck18.to_format("astropy.table", cls=Table) + + ... + """ + ... + +def table_identify(origin, format, *args, **kwargs): # -> bool: + """Identify if object uses the Table format. + + Returns + ------- + bool + """ + ... + diff --git a/typings/astropy/cosmology/io/utils.pyi b/typings/astropy/cosmology/io/utils.pyi new file mode 100644 index 0000000..1e7ab91 --- /dev/null +++ b/typings/astropy/cosmology/io/utils.pyi @@ -0,0 +1,39 @@ +""" +This type stub file was generated by pyright. +""" + +FULLQUALNAME_SUBSTITUTIONS = ... +def convert_parameter_to_column(parameter, value, meta=...): # -> Column: + """Convert a |Cosmology| Parameter to a Table |Column|. + + Parameters + ---------- + parameter : `astropy.cosmology.parameter.Parameter` + value : Any + meta : dict or None, optional + Information from the Cosmology's metadata. + + Returns + ------- + `astropy.table.Column` + """ + ... + +def convert_parameter_to_model_parameter(parameter, value, meta=...): # -> Parameter: + """Convert a Cosmology Parameter to a Model Parameter. + + Parameters + ---------- + parameter : `astropy.cosmology.parameter.Parameter` + value : Any + meta : dict or None, optional + Information from the Cosmology's metadata. + This function will use any of: 'getter', 'setter', 'fixed', 'tied', + 'min', 'max', 'bounds', 'prior', 'posterior'. + + Returns + ------- + `astropy.modeling.Parameter` + """ + ... + diff --git a/typings/astropy/cosmology/io/yaml.pyi b/typings/astropy/cosmology/io/yaml.pyi new file mode 100644 index 0000000..29053ec --- /dev/null +++ b/typings/astropy/cosmology/io/yaml.pyi @@ -0,0 +1,91 @@ +""" +This type stub file was generated by pyright. +""" + +""" +The following are private functions, included here **FOR REFERENCE ONLY** since +the io registry cannot be displayed. These functions are registered into +:meth:`~astropy.cosmology.Cosmology.to_format` and +:meth:`~astropy.cosmology.Cosmology.from_format` and should only be accessed +via these methods. +""" +__all__ = [] +def yaml_representer(tag): # -> (dumper: Unknown, obj: Unknown) -> Unknown: + """:mod:`yaml` representation of |Cosmology| object. + + Parameters + ---------- + tag : str + The class tag, e.g. '!astropy.cosmology.LambdaCDM' + + Returns + ------- + representer : callable[[`~astropy.io.misc.yaml.AstropyDumper`, |Cosmology|], str] + Function to construct :mod:`yaml` representation of |Cosmology| object. + """ + ... + +def yaml_constructor(cls): # -> (loader: Unknown, node: Unknown) -> Unknown: + """Cosmology| object from :mod:`yaml` representation. + + Parameters + ---------- + cls : type + The class type, e.g. `~astropy.cosmology.LambdaCDM`. + + Returns + ------- + constructor : callable + Function to construct |Cosmology| object from :mod:`yaml` representation. + """ + ... + +def register_cosmology_yaml(cosmo_cls): # -> None: + """Register :mod:`yaml` for Cosmology class. + + Parameters + ---------- + cosmo_cls : `~astropy.cosmology.Cosmology` class + """ + ... + +def from_yaml(yml, *, cosmology=...): # -> Any: + """Load `~astropy.cosmology.Cosmology` from :mod:`yaml` object. + + Parameters + ---------- + yml : str + :mod:`yaml` representation of |Cosmology| object + cosmology : str, `~astropy.cosmology.Cosmology` class, or None (optional, keyword-only) + The expected cosmology class (or string name thereof). This argument is + is only checked for correctness if not `None`. + + Returns + ------- + `~astropy.cosmology.Cosmology` subclass instance + + Raises + ------ + TypeError + If the |Cosmology| object loaded from ``yml`` is not an instance of + the ``cosmology`` (and ``cosmology`` is not `None`). + """ + ... + +def to_yaml(cosmology, *args): # -> _Yaml: + """Return the cosmology class, parameters, and metadata as a :mod:`yaml` object. + + Parameters + ---------- + cosmology : `~astropy.cosmology.Cosmology` subclass instance + *args + Not used. Needed for compatibility with + `~astropy.io.registry.UnifiedReadWriteMethod` + + Returns + ------- + str + :mod:`yaml` representation of |Cosmology| object + """ + ... + diff --git a/typings/astropy/cosmology/parameter.pyi b/typings/astropy/cosmology/parameter.pyi new file mode 100644 index 0000000..43738bd --- /dev/null +++ b/typings/astropy/cosmology/parameter.pyi @@ -0,0 +1,196 @@ +""" +This type stub file was generated by pyright. +""" + +from astropy.utils.decorators import deprecated_renamed_argument + +__all__ = ["Parameter"] +class Parameter: + r"""Cosmological parameter (descriptor). + + Should only be used with a :class:`~astropy.cosmology.Cosmology` subclass. + + Parameters + ---------- + derived : bool (optional, keyword-only) + Whether the Parameter is 'derived', default `False`. + Derived parameters behave similarly to normal parameters, but are not + sorted by the |Cosmology| signature (probably not there) and are not + included in all methods. For reference, see ``Ode0`` in + ``FlatFLRWMixin``, which removes :math:`\Omega_{de,0}`` as an + independent parameter (:math:`\Omega_{de,0} \equiv 1 - \Omega_{tot}`). + unit : unit-like or None (optional, keyword-only) + The `~astropy.units.Unit` for the Parameter. If None (default) no + unit as assumed. + equivalencies : `~astropy.units.Equivalency` or sequence thereof + Unit equivalencies for this Parameter. + fvalidate : callable[[object, object, Any], Any] or str (optional, keyword-only) + Function to validate the Parameter value from instances of the + cosmology class. If "default", uses default validator to assign units + (with equivalencies), if Parameter has units. + For other valid string options, see ``Parameter._registry_validators``. + 'fvalidate' can also be set through a decorator with + :meth:`~astropy.cosmology.Parameter.validator`. + fmt : str (optional, keyword-only) + `format` specification, used when making string representation + of the containing Cosmology. + See https://docs.python.org/3/library/string.html#formatspec + + .. deprecated:: 5.1 + + doc : str or None (optional, keyword-only) + Parameter description. + + Examples + -------- + For worked examples see :class:`~astropy.cosmology.FLRW`. + """ + _registry_validators = ... + @deprecated_renamed_argument("fmt", None, since="5.1") + def __init__(self, *, derived=..., unit=..., equivalencies=..., fvalidate=..., fmt=..., doc=...) -> None: + ... + + def __set_name__(self, cosmo_cls, name): # -> None: + ... + + @property + def name(self): # -> None: + """Parameter name.""" + ... + + @property + def unit(self): # -> Unit | None: + """Parameter unit.""" + ... + + @property + def equivalencies(self): + """Equivalencies used when initializing Parameter.""" + ... + + format_spec = ... + @property + def derived(self): # -> bool: + """Whether the Parameter is derived; true parameters are not.""" + ... + + def __get__(self, cosmology, cosmo_cls=...): # -> Self@Parameter | Any: + ... + + def __set__(self, cosmology, value): # -> None: + """Allows attribute setting once. Raises AttributeError subsequently.""" + ... + + @property + def fvalidate(self): # -> : + """Function to validate a potential value of this Parameter.""" + ... + + def validator(self, fvalidate): # -> Self@Parameter: + """Make new Parameter with custom ``fvalidate``. + + Note: ``Parameter.fvalidator`` must be the top-most descriptor decorator. + + Parameters + ---------- + fvalidate : callable[[type, type, Any], Any] + + Returns + ------- + `~astropy.cosmology.Parameter` + Copy of this Parameter but with custom ``fvalidate``. + """ + ... + + def validate(self, cosmology, value): + """Run the validator on this Parameter. + + Parameters + ---------- + cosmology : `~astropy.cosmology.Cosmology` instance + value : Any + The object to validate. + + Returns + ------- + Any + The output of calling ``fvalidate(cosmology, self, value)`` + (yes, that parameter order). + """ + ... + + @classmethod + def register_validator(cls, key, fvalidate=...): # -> (fvalidate: Unknown) -> Unknown: + """Decorator to register a new kind of validator function. + + Parameters + ---------- + key : str + fvalidate : callable[[object, object, Any], Any] or None, optional + Value validation function. + + Returns + ------- + ``validator`` or callable[``validator``] + if validator is None returns a function that takes and registers a + validator. This allows ``register_validator`` to be used as a + decorator. + """ + ... + + def clone(self, **kw): # -> Self@Parameter: + """Clone this `Parameter`, changing any constructor argument. + + Parameters + ---------- + **kw + Passed to constructor. The current values, eg. ``fvalidate`` are + used as the default values, so an empty ``**kw`` is an exact copy. + + Examples + -------- + >>> p = Parameter() + >>> p + Parameter(derived=False, unit=None, equivalencies=[], + fvalidate='default', doc=None) + + >>> p.clone(unit="km") + Parameter(derived=False, unit=Unit("km"), equivalencies=[], + fvalidate='default', doc=None) + """ + ... + + def __eq__(self, other) -> bool: + """Check Parameter equality. Only equal to other Parameter objects. + + Returns + ------- + NotImplemented or True + `True` if equal, `NotImplemented` otherwise. This allows `other` to + be check for equality with ``other.__eq__``. + + Examples + -------- + >>> p1, p2 = Parameter(unit="km"), Parameter(unit="km") + >>> p1 == p2 + True + + >>> p3 = Parameter(unit="km / s") + >>> p3 == p1 + False + + >>> p1 != 2 + True + """ + ... + + def __repr__(self): # -> str: + """String representation. + + ``eval(repr())`` should work, depending if contents like ``fvalidate`` + can be similarly round-tripped. + """ + ... + + + diff --git a/typings/astropy/cosmology/realizations.pyi b/typings/astropy/cosmology/realizations.pyi new file mode 100644 index 0000000..b96d3a2 --- /dev/null +++ b/typings/astropy/cosmology/realizations.pyi @@ -0,0 +1,78 @@ +""" +This type stub file was generated by pyright. +""" + +from typing import Optional, Union +from astropy.utils.decorators import deprecated +from astropy.utils.state import ScienceState +from .core import Cosmology + +_COSMOLOGY_DATA_DIR = ... +available = ... +__all__ = ["available", "default_cosmology"] + list(available) +__doctest_requires__ = ... +def __getattr__(name): + """Make specific realizations from data files with lazy import from + `PEP 562 `_. + + Raises + ------ + AttributeError + If "name" is not in :mod:`astropy.cosmology.realizations` + """ + ... + +def __dir__(): # -> list[str]: + """Directory, including lazily-imported objects.""" + ... + +class default_cosmology(ScienceState): + """The default cosmology to use. + + To change it:: + + >>> from astropy.cosmology import default_cosmology, WMAP7 + >>> with default_cosmology.set(WMAP7): + ... # WMAP7 cosmology in effect + ... pass + + Or, you may use a string:: + + >>> with default_cosmology.set('WMAP7'): + ... # WMAP7 cosmology in effect + ... pass + + To get the default cosmology: + + >>> default_cosmology.get() + FlatLambdaCDM(name="Planck18", H0=67.66 km / (Mpc s), Om0=0.30966, ... + """ + _default_value = ... + _value = ... + @deprecated("5.0", alternative="get") + @classmethod + def get_cosmology_from_string(cls, arg): # -> Cosmology | None: + """Return a cosmology instance from a string.""" + ... + + @classmethod + def validate(cls, value: Union[Cosmology, str, None]) -> Optional[Cosmology]: + """Return a Cosmology given a value. + + Parameters + ---------- + value : None, str, or `~astropy.cosmology.Cosmology` + + Returns + ------- + `~astropy.cosmology.Cosmology` instance + + Raises + ------ + TypeError + If ``value`` is not a string or |Cosmology|. + """ + ... + + + diff --git a/typings/astropy/cosmology/units.pyi b/typings/astropy/cosmology/units.pyi new file mode 100644 index 0000000..ad61c9a --- /dev/null +++ b/typings/astropy/cosmology/units.pyi @@ -0,0 +1,208 @@ +""" +This type stub file was generated by pyright. +""" + +"""Cosmological units and equivalencies. +""" +__all__ = ["littleh", "redshift", "dimensionless_redshift", "with_redshift", "redshift_distance", "redshift_hubble", "redshift_temperature", "with_H0"] +__doctest_requires__ = ... +_ns = ... +redshift = ... +littleh = ... +def dimensionless_redshift(): # -> Equivalency: + """Allow redshift to be 1-to-1 equivalent to dimensionless. + + It is special compared to other equivalency pairs in that it + allows this independent of the power to which the redshift is raised, + and independent of whether it is part of a more complicated unit. + It is similar to u.dimensionless_angles() in this respect. + """ + ... + +def redshift_distance(cosmology=..., kind=..., **atzkw): # -> Equivalency: + """Convert quantities between redshift and distance. + + Care should be taken to not misinterpret a relativistic, gravitational, etc + redshift as a cosmological one. + + Parameters + ---------- + cosmology : `~astropy.cosmology.Cosmology`, str, or None, optional + A cosmology realization or built-in cosmology's name (e.g. 'Planck18'). + If None, will use the default cosmology + (controlled by :class:`~astropy.cosmology.default_cosmology`). + kind : {'comoving', 'lookback', 'luminosity'} or None, optional + The distance type for the Equivalency. + Note this does NOT include the angular diameter distance as this + distance measure is not monotonic. + **atzkw + keyword arguments for :func:`~astropy.cosmology.z_at_value` + + Returns + ------- + `~astropy.units.equivalencies.Equivalency` + Equivalency between redshift and temperature. + + Examples + -------- + >>> import astropy.units as u + >>> import astropy.cosmology.units as cu + >>> from astropy.cosmology import WMAP9 + + >>> z = 1100 * cu.redshift + >>> z.to(u.Mpc, cu.redshift_distance(WMAP9, kind="comoving")) # doctest: +FLOAT_CMP + + """ + ... + +def redshift_hubble(cosmology=..., **atzkw): # -> Equivalency: + """Convert quantities between redshift and Hubble parameter and little-h. + + Care should be taken to not misinterpret a relativistic, gravitational, etc + redshift as a cosmological one. + + Parameters + ---------- + cosmology : `~astropy.cosmology.Cosmology`, str, or None, optional + A cosmology realization or built-in cosmology's name (e.g. 'Planck18'). + If None, will use the default cosmology + (controlled by :class:`~astropy.cosmology.default_cosmology`). + **atzkw + keyword arguments for :func:`~astropy.cosmology.z_at_value` + + Returns + ------- + `~astropy.units.equivalencies.Equivalency` + Equivalency between redshift and Hubble parameter and little-h unit. + + Examples + -------- + >>> import astropy.units as u + >>> import astropy.cosmology.units as cu + >>> from astropy.cosmology import WMAP9 + + >>> z = 1100 * cu.redshift + >>> equivalency = cu.redshift_hubble(WMAP9) # construct equivalency + + >>> z.to(u.km / u.s / u.Mpc, equivalency) # doctest: +FLOAT_CMP + + + >>> z.to(cu.littleh, equivalency) # doctest: +FLOAT_CMP + + """ + ... + +def redshift_temperature(cosmology=..., **atzkw): # -> Equivalency: + """Convert quantities between redshift and CMB temperature. + + Care should be taken to not misinterpret a relativistic, gravitational, etc + redshift as a cosmological one. + + Parameters + ---------- + cosmology : `~astropy.cosmology.Cosmology`, str, or None, optional + A cosmology realization or built-in cosmology's name (e.g. 'Planck18'). + If None, will use the default cosmology + (controlled by :class:`~astropy.cosmology.default_cosmology`). + **atzkw + keyword arguments for :func:`~astropy.cosmology.z_at_value` + + Returns + ------- + `~astropy.units.equivalencies.Equivalency` + Equivalency between redshift and temperature. + + Examples + -------- + >>> import astropy.units as u + >>> import astropy.cosmology.units as cu + >>> from astropy.cosmology import WMAP9 + + >>> z = 1100 * cu.redshift + >>> z.to(u.K, cu.redshift_temperature(WMAP9)) + + """ + ... + +def with_redshift(cosmology=..., *, distance=..., hubble=..., Tcmb=..., atzkw=...): # -> Equivalency: + """Convert quantities between measures of cosmological distance. + + Note: by default all equivalencies are on and must be explicitly turned off. + Care should be taken to not misinterpret a relativistic, gravitational, etc + redshift as a cosmological one. + + Parameters + ---------- + cosmology : `~astropy.cosmology.Cosmology`, str, or None, optional + A cosmology realization or built-in cosmology's name (e.g. 'Planck18'). + If `None`, will use the default cosmology + (controlled by :class:`~astropy.cosmology.default_cosmology`). + + distance : {'comoving', 'lookback', 'luminosity'} or None (optional, keyword-only) + The type of distance equivalency to create or `None`. + Default is 'comoving'. + hubble : bool (optional, keyword-only) + Whether to create a Hubble parameter <-> redshift equivalency, using + ``Cosmology.H``. Default is `True`. + Tcmb : bool (optional, keyword-only) + Whether to create a CMB temperature <-> redshift equivalency, using + ``Cosmology.Tcmb``. Default is `True`. + + atzkw : dict or None (optional, keyword-only) + keyword arguments for :func:`~astropy.cosmology.z_at_value` + + Returns + ------- + `~astropy.units.equivalencies.Equivalency` + With equivalencies between redshift and distance / Hubble / temperature. + + Examples + -------- + >>> import astropy.units as u + >>> import astropy.cosmology.units as cu + >>> from astropy.cosmology import WMAP9 + + >>> equivalency = cu.with_redshift(WMAP9) + >>> z = 1100 * cu.redshift + + Redshift to (comoving) distance: + + >>> z.to(u.Mpc, equivalency) # doctest: +FLOAT_CMP + + + Redshift to the Hubble parameter: + + >>> z.to(u.km / u.s / u.Mpc, equivalency) # doctest: +FLOAT_CMP + + + >>> z.to(cu.littleh, equivalency) # doctest: +FLOAT_CMP + + + Redshift to CMB temperature: + + >>> z.to(u.K, equivalency) + + """ + ... + +def with_H0(H0=...): # -> Equivalency: + """ + Convert between quantities with little-h and the equivalent physical units. + + Parameters + ---------- + H0 : None or `~astropy.units.Quantity` ['frequency'] + The value of the Hubble constant to assume. If a + `~astropy.units.Quantity`, will assume the quantity *is* ``H0``. If + `None` (default), use the ``H0`` attribute from + :mod:`~astropy.cosmology.default_cosmology`. + + References + ---------- + For an illuminating discussion on why you may or may not want to use + little-h at all, see https://arxiv.org/pdf/1308.4150.pdf + """ + ... + +if __doc__ is not None: + ... diff --git a/typings/astropy/cosmology/utils.pyi b/typings/astropy/cosmology/utils.pyi new file mode 100644 index 0000000..8edb597 --- /dev/null +++ b/typings/astropy/cosmology/utils.pyi @@ -0,0 +1,90 @@ +""" +This type stub file was generated by pyright. +""" + +from astropy.utils.decorators import deprecated + +__all__ = [] +__doctest_skip__ = ... +def vectorize_redshift_method(func=..., nin=...): # -> partial[Unknown] | ((self: Unknown, *args: Unknown, **kwargs: Unknown) -> (Unknown | Any)): + """Vectorize a method of redshift(s). + + Parameters + ---------- + func : callable or None + method to wrap. If `None` returns a :func:`functools.partial` + with ``nin`` loaded. + nin : int + Number of positional redshift arguments. + + Returns + ------- + wrapper : callable + :func:`functools.wraps` of ``func`` where the first ``nin`` + arguments are converted from |Quantity| to :class:`numpy.ndarray`. + """ + ... + +@deprecated(since="5.0", message="vectorize_if_needed has been removed because it constructs a new ufunc on each call", alternative="use a pre-vectorized function instead for a target array 'z'") +def vectorize_if_needed(f, *x, **vkw): # -> Any: + """Helper function to vectorize scalar functions on array inputs. + + Parameters + ---------- + f : callable + 'f' must accept positional arguments and no mandatory keyword + arguments. + *x + Arguments into ``f``. + **vkw + Keyword arguments into :class:`numpy.vectorize`. + + Examples + -------- + >>> func = lambda x: x ** 2 + >>> vectorize_if_needed(func, 2) + 4 + >>> vectorize_if_needed(func, [2, 3]) + array([4, 9]) + """ + ... + +@deprecated(since="5.0", message="inf_like has been removed because it duplicates " "functionality provided by numpy.full_like()", alternative="Use numpy.full_like(z, numpy.inf) instead for a target array 'z'") +def inf_like(x): # -> float | NDArray[Any]: + """Return the shape of x with value infinity and dtype='float'. + + Preserves 'shape' for both array and scalar inputs. + But always returns a float array, even if x is of integer type. + + Parameters + ---------- + x : scalar or array-like + Must work with functions `numpy.isscalar` and `numpy.full_like` (if `x` + is not a scalar` + + Returns + ------- + `math.inf` or ndarray[float] thereof + Returns a scalar `~math.inf` if `x` is a scalar, an array of floats + otherwise. + + Examples + -------- + >>> inf_like(0.) # float scalar + inf + >>> inf_like(1) # integer scalar should give float output + inf + >>> inf_like([0., 1., 2., 3.]) # float list + array([inf, inf, inf, inf]) + >>> inf_like([0, 1, 2, 3]) # integer list should give float output + array([inf, inf, inf, inf]) + """ + ... + +def aszarr(z): # -> Number | generic | Any: + """ + Redshift as a `~numbers.Number` or `~numpy.ndarray` / |Quantity| / |Column|. + Allows for any ndarray ducktype by checking for attribute "shape". + """ + ... + diff --git a/typings/astropy/extern/__init__.pyi b/typings/astropy/extern/__init__.pyi new file mode 100644 index 0000000..9ae1c46 --- /dev/null +++ b/typings/astropy/extern/__init__.pyi @@ -0,0 +1,13 @@ +""" +This type stub file was generated by pyright. +""" + +""" +This packages contains python packages that are bundled with Astropy but are +external to Astropy, and hence are developed in a separate source tree. Note +that this package is distinct from the /cextern directory of the source code +distribution, as that directory only contains C extension code. + +See the README.rst in this directory of the Astropy source repository for more +details. +""" diff --git a/typings/astropy/extern/_strptime.pyi b/typings/astropy/extern/_strptime.pyi new file mode 100644 index 0000000..5368f10 --- /dev/null +++ b/typings/astropy/extern/_strptime.pyi @@ -0,0 +1,88 @@ +""" +This type stub file was generated by pyright. +""" + +"""Strptime-related classes and functions. + +CLASSES: + LocaleTime -- Discovers and stores locale-specific time information + TimeRE -- Creates regexes for pattern matching a string of text containing + time information + +FUNCTIONS: + _getlang -- Figure out what language is being used for the locale + strptime -- Calculates the time struct represented by the passed-in string + +""" +__all__ = [] +class LocaleTime: + """Stores and handles locale-specific information related to time. + + ATTRIBUTES: + f_weekday -- full weekday names (7-item list) + a_weekday -- abbreviated weekday names (7-item list) + f_month -- full month names (13-item list; dummy value in [0], which + is added by code) + a_month -- abbreviated month names (13-item list, dummy value in + [0], which is added by code) + am_pm -- AM/PM representation (2-item list) + LC_date_time -- format string for date/time representation (string) + LC_date -- format string for date representation (string) + LC_time -- format string for time representation (string) + timezone -- daylight- and non-daylight-savings timezone representation + (2-item list of sets) + lang -- Language used by instance (2-item tuple) + """ + def __init__(self) -> None: + """Set all attributes. + + Order of methods called matters for dependency reasons. + + The locale language is set at the offset and then checked again before + exiting. This is to make sure that the attributes were not set with a + mix of information from more than one locale. This would most likely + happen when using threads where one thread calls a locale-dependent + function while another thread changes the locale while the function in + the other thread is still running. Proper coding would call for + locks to prevent changing the locale while locale-dependent code is + running. The check here is done in case someone does not think about + doing this. + + Only other possible issue is if someone changed the timezone and did + not call tz.tzset . That is an issue for the programmer, though, + since changing the timezone is worthless without that call. + + """ + ... + + + +class TimeRE(dict): + """Handle conversion from format directives to regexes.""" + def __init__(self, locale_time=...) -> None: + """Create keys/values. + + Order of execution is important for dependency reasons. + + """ + ... + + def pattern(self, format): # -> str: + """Return regex pattern for the format string. + + Need to make sure that any characters that might be interpreted as + regex syntax are escaped. + + """ + ... + + def compile(self, format): # -> Pattern[str]: + """Return a compiled re object for the format string.""" + ... + + + +_cache_lock = ... +_TimeRE_cache = ... +_CACHE_MAX_SIZE = ... +_regex_cache = ... diff --git a/typings/astropy/extern/configobj/__init__.pyi b/typings/astropy/extern/configobj/__init__.pyi new file mode 100644 index 0000000..006bc27 --- /dev/null +++ b/typings/astropy/extern/configobj/__init__.pyi @@ -0,0 +1,4 @@ +""" +This type stub file was generated by pyright. +""" + diff --git a/typings/astropy/extern/configobj/configobj.pyi b/typings/astropy/extern/configobj/configobj.pyi new file mode 100644 index 0000000..89c1ca1 --- /dev/null +++ b/typings/astropy/extern/configobj/configobj.pyi @@ -0,0 +1,685 @@ +""" +This type stub file was generated by pyright. +""" + +compiler = ... +BOMS = ... +BOM_LIST = ... +BOM_SET = ... +def match_utf8(encoding): # -> bool: + ... + +squot = ... +dquot = ... +noquot = ... +wspace_plus = ... +tsquot = ... +tdquot = ... +MISSING = ... +__all__ = ('DEFAULT_INDENT_TYPE', 'DEFAULT_INTERPOLATION', 'ConfigObjError', 'NestingError', 'ParseError', 'DuplicateError', 'ConfigspecError', 'ConfigObj', 'SimpleVal', 'InterpolationError', 'InterpolationLoopError', 'MissingInterpolationOption', 'RepeatSectionError', 'ReloadError', 'UnreprError', 'UnknownType', 'flatten_errors', 'get_extra_values') +DEFAULT_INTERPOLATION = ... +DEFAULT_INDENT_TYPE = ... +MAX_INTERPOL_DEPTH = ... +OPTION_DEFAULTS = ... +def getObj(s): + ... + +class UnknownType(Exception): + ... + + +class Builder: + def build(self, o): + ... + + def build_List(self, o): # -> list[Unknown]: + ... + + def build_Const(self, o): + ... + + def build_Dict(self, o): # -> dict[Unknown, Unknown]: + ... + + def build_Tuple(self, o): # -> tuple[Unknown, ...]: + ... + + def build_Name(self, o): # -> bool | None: + ... + + def build_Add(self, o): # -> complex: + ... + + def build_Getattr(self, o): # -> Any: + ... + + def build_UnarySub(self, o): + ... + + def build_UnaryAdd(self, o): + ... + + + +_builder = ... +def unrepr(s): # -> Any: + ... + +class ConfigObjError(SyntaxError): + """ + This is the base class for all errors that ConfigObj raises. + It is a subclass of SyntaxError. + """ + def __init__(self, message=..., line_number=..., line=...) -> None: + ... + + + +class NestingError(ConfigObjError): + """ + This error indicates a level of nesting that doesn't match. + """ + ... + + +class ParseError(ConfigObjError): + """ + This error indicates that a line is badly written. + It is neither a valid ``key = value`` line, + nor a valid section marker line. + """ + ... + + +class ReloadError(IOError): + """ + A 'reload' operation failed. + This exception is a subclass of ``IOError``. + """ + def __init__(self) -> None: + ... + + + +class DuplicateError(ConfigObjError): + """ + The keyword or section specified already exists. + """ + ... + + +class ConfigspecError(ConfigObjError): + """ + An error occured whilst parsing a configspec. + """ + ... + + +class InterpolationError(ConfigObjError): + """Base class for the two interpolation errors.""" + ... + + +class InterpolationLoopError(InterpolationError): + """Maximum interpolation depth exceeded in string interpolation.""" + def __init__(self, option) -> None: + ... + + + +class RepeatSectionError(ConfigObjError): + """ + This error indicates additional sections in a section with a + ``__many__`` (repeated) section. + """ + ... + + +class MissingInterpolationOption(InterpolationError): + """A value specified for interpolation was missing.""" + def __init__(self, option) -> None: + ... + + + +class UnreprError(ConfigObjError): + """An error parsing in unrepr mode.""" + ... + + +class InterpolationEngine: + """ + A helper class to help perform string interpolation. + + This class is an abstract base class; its descendants perform + the actual work. + """ + _KEYCRE = ... + _cookie = ... + def __init__(self, section) -> None: + ... + + def interpolate(self, key, value): # -> LiteralString: + ... + + + +class ConfigParserInterpolation(InterpolationEngine): + """Behaves like ConfigParser.""" + _cookie = ... + _KEYCRE = ... + + +class TemplateInterpolation(InterpolationEngine): + """Behaves like string.Template.""" + _cookie = ... + _delimiter = ... + _KEYCRE = ... + + +interpolation_engines = ... +def __newobj__(cls, *args): + ... + +class Section(dict): + """ + A dictionary-like object that represents a section in a config file. + + It does string interpolation if the 'interpolation' attribute + of the 'main' object is set to True. + + Interpolation is tried first from this object, then from the 'DEFAULT' + section of this object, next from the parent and its 'DEFAULT' section, + and so on until the main object is reached. + + A Section will behave like an ordered dictionary - following the + order of the ``scalars`` and ``sections`` attributes. + You can use this to change the order of members. + + Iteration follows the order: scalars, then sections. + """ + def __setstate__(self, state): # -> None: + ... + + def __reduce__(self): # -> tuple[(cls: Unknown, *args: Unknown) -> Unknown, tuple[Type[Self@Section]], tuple[dict[Unknown, str | Unknown | list[str | Unknown] | list[Unknown]], dict[str, Any]]]: + ... + + def __init__(self, parent, depth, main, indict=..., name=...) -> None: + """ + * parent is the section above + * depth is the depth level of this section + * main is the main ConfigObj + * indict is a dictionary to initialise the section with + """ + ... + + def __getitem__(self, key): # -> str | LiteralString | list[str | Unknown] | list[Unknown]: + """Fetch the item and do string interpolation.""" + ... + + def __setitem__(self, key, value, unrepr=...): # -> None: + """ + Correctly set a value. + + Making dictionary values Section instances. + (We have to special case 'Section' instances - which are also dicts) + + Keys must be strings. + Values need only be strings (or lists of strings) if + ``main.stringify`` is set. + + ``unrepr`` must be set when setting a value to a dictionary, without + creating a new sub-section. + """ + ... + + def __delitem__(self, key): # -> None: + """Remove items from the sequence when deleting.""" + ... + + def get(self, key, default=...): # -> str | LiteralString | list[str | Unknown] | list[Unknown] | None: + """A version of ``get`` that doesn't bypass string interpolation.""" + ... + + def update(self, indict): # -> None: + """ + A version of update that uses our ``__setitem__``. + """ + ... + + def pop(self, key, default=...): # -> str | LiteralString | list[str | Unknown] | list[Unknown] | object: + """ + 'D.pop(k[,d]) -> v, remove specified key and return the corresponding value. + If key is not found, d is returned if given, otherwise KeyError is raised' + """ + ... + + def popitem(self): # -> tuple[Unknown, str | Unknown | LiteralString | list[str | Unknown] | list[Unknown]]: + """Pops the first (key,val)""" + ... + + def clear(self): # -> None: + """ + A version of clear that also affects scalars/sections + Also clears comments and configspec. + + Leaves other attributes alone : + depth/main/parent are not affected + """ + ... + + def setdefault(self, key, default=...): # -> str | LiteralString | list[str | Unknown] | list[Unknown]: + """A version of setdefault that sets sequence if appropriate.""" + ... + + def items(self): # -> list[tuple[Unknown, str | Unknown | list[str | Unknown] | list[Unknown]]]: + """D.items() -> list of D's (key, value) pairs, as 2-tuples""" + ... + + def keys(self): # -> list[Unknown]: + """D.keys() -> list of D's keys""" + ... + + def values(self): # -> list[str | Unknown | list[str | Unknown] | list[Unknown]]: + """D.values() -> list of D's values""" + ... + + def iteritems(self): # -> Iterator[tuple[Unknown, str | Unknown | list[str | Unknown] | list[Unknown]]]: + """D.iteritems() -> an iterator over the (key, value) items of D""" + ... + + def iterkeys(self): # -> Iterator[Unknown]: + """D.iterkeys() -> an iterator over the keys of D""" + ... + + __iter__ = ... + def itervalues(self): # -> Iterator[str | Unknown | list[str | Unknown] | list[Unknown]]: + """D.itervalues() -> an iterator over the values of D""" + ... + + def __repr__(self): # -> str: + """x.__repr__() <==> repr(x)""" + ... + + __str__ = ... + def dict(self): # -> dict[Unknown, Unknown]: + """ + Return a deepcopy of self as a dictionary. + + All members that are ``Section`` instances are recursively turned to + ordinary dictionaries - by calling their ``dict`` method. + + >>> n = a.dict() + >>> n == a + 1 + >>> n is a + 0 + """ + ... + + def merge(self, indict): # -> None: + """ + A recursive update - useful for merging config files. + + >>> a = '''[section1] + ... option1 = True + ... [[subsection]] + ... more_options = False + ... # end of file'''.splitlines() + >>> b = '''# File is user.ini + ... [section1] + ... option1 = False + ... # end of file'''.splitlines() + >>> c1 = ConfigObj(b) + >>> c2 = ConfigObj(a) + >>> c2.merge(c1) + >>> c2 + ConfigObj({'section1': {'option1': 'False', 'subsection': {'more_options': 'False'}}}) + """ + ... + + def rename(self, oldkey, newkey): # -> None: + """ + Change a keyname to another, without changing position in sequence. + + Implemented so that transformations can be made on keys, + as well as on values. (used by encode and decode) + + Also renames comments. + """ + ... + + def walk(self, function, raise_errors=..., call_on_sections=..., **keywargs): # -> dict[Unknown, Unknown]: + """ + Walk every member and call a function on the keyword and value. + + Return a dictionary of the return values + + If the function raises an exception, raise the errror + unless ``raise_errors=False``, in which case set the return value to + ``False``. + + Any unrecognized keyword arguments you pass to walk, will be pased on + to the function you pass in. + + Note: if ``call_on_sections`` is ``True`` then - on encountering a + subsection, *first* the function is called for the *whole* subsection, + and then recurses into it's members. This means your function must be + able to handle strings, dictionaries and lists. This allows you + to change the key of subsections as well as for ordinary members. The + return value when called on the whole subsection has to be discarded. + + See the encode and decode methods for examples, including functions. + + .. admonition:: caution + + You can use ``walk`` to transform the names of members of a section + but you mustn't add or delete members. + + >>> config = '''[XXXXsection] + ... XXXXkey = XXXXvalue'''.splitlines() + >>> cfg = ConfigObj(config) + >>> cfg + ConfigObj({'XXXXsection': {'XXXXkey': 'XXXXvalue'}}) + >>> def transform(section, key): + ... val = section[key] + ... newkey = key.replace('XXXX', 'CLIENT1') + ... section.rename(key, newkey) + ... if isinstance(val, (tuple, list, dict)): + ... pass + ... else: + ... val = val.replace('XXXX', 'CLIENT1') + ... section[newkey] = val + >>> cfg.walk(transform, call_on_sections=True) + {'CLIENT1section': {'CLIENT1key': None}} + >>> cfg + ConfigObj({'CLIENT1section': {'CLIENT1key': 'CLIENT1value'}}) + """ + ... + + def as_bool(self, key): # -> bool: + """ + Accepts a key as input. The corresponding value must be a string or + the objects (``True`` or 1) or (``False`` or 0). We allow 0 and 1 to + retain compatibility with Python 2.2. + + If the string is one of ``True``, ``On``, ``Yes``, or ``1`` it returns + ``True``. + + If the string is one of ``False``, ``Off``, ``No``, or ``0`` it returns + ``False``. + + ``as_bool`` is not case sensitive. + + Any other input will raise a ``ValueError``. + + >>> a = ConfigObj() + >>> a['a'] = 'fish' + >>> a.as_bool('a') + Traceback (most recent call last): + ValueError: Value "fish" is neither True nor False + >>> a['b'] = 'True' + >>> a.as_bool('b') + 1 + >>> a['b'] = 'off' + >>> a.as_bool('b') + 0 + """ + ... + + def as_int(self, key): # -> int: + """ + A convenience method which coerces the specified value to an integer. + + If the value is an invalid literal for ``int``, a ``ValueError`` will + be raised. + + >>> a = ConfigObj() + >>> a['a'] = 'fish' + >>> a.as_int('a') + Traceback (most recent call last): + ValueError: invalid literal for int() with base 10: 'fish' + >>> a['b'] = '1' + >>> a.as_int('b') + 1 + >>> a['b'] = '3.2' + >>> a.as_int('b') + Traceback (most recent call last): + ValueError: invalid literal for int() with base 10: '3.2' + """ + ... + + def as_float(self, key): # -> float: + """ + A convenience method which coerces the specified value to a float. + + If the value is an invalid literal for ``float``, a ``ValueError`` will + be raised. + + >>> a = ConfigObj() + >>> a['a'] = 'fish' + >>> a.as_float('a') #doctest: +IGNORE_EXCEPTION_DETAIL + Traceback (most recent call last): + ValueError: invalid literal for float(): fish + >>> a['b'] = '1' + >>> a.as_float('b') + 1.0 + >>> a['b'] = '3.2' + >>> a.as_float('b') #doctest: +ELLIPSIS + 3.2... + """ + ... + + def as_list(self, key): # -> list[str | Unknown]: + """ + A convenience method which fetches the specified value, guaranteeing + that it is a list. + + >>> a = ConfigObj() + >>> a['a'] = 1 + >>> a.as_list('a') + [1] + >>> a['a'] = (1,) + >>> a.as_list('a') + [1] + >>> a['a'] = [1] + >>> a.as_list('a') + [1] + """ + ... + + def restore_default(self, key): + """ + Restore (and return) default value for the specified key. + + This method will only work for a ConfigObj that was created + with a configspec and has been validated. + + If there is no default value for this key, ``KeyError`` is raised. + """ + ... + + def restore_defaults(self): # -> None: + """ + Recursively restore default values to all members + that have them. + + This method will only work for a ConfigObj that was created + with a configspec and has been validated. + + It doesn't delete or modify entries without default values. + """ + ... + + + +class ConfigObj(Section): + """An object to read, create, and write config files.""" + _keyword = ... + _sectionmarker = ... + _valueexp = ... + _listvalueexp = ... + _nolistvalue = ... + _single_line_single = ... + _single_line_double = ... + _multi_line_single = ... + _multi_line_double = ... + _triple_quote = ... + _bools = ... + def __init__(self, infile=..., options=..., configspec=..., encoding=..., interpolation=..., raise_errors=..., list_values=..., create_empty=..., file_error=..., stringify=..., indent_type=..., default_encoding=..., unrepr=..., write_empty_values=..., _inspec=...) -> None: + """ + Parse a config file or create a config file object. + + ``ConfigObj(infile=None, configspec=None, encoding=None, + interpolation=True, raise_errors=False, list_values=True, + create_empty=False, file_error=False, stringify=True, + indent_type=None, default_encoding=None, unrepr=False, + write_empty_values=False, _inspec=False)`` + """ + ... + + def __repr__(self): # -> str: + ... + + def write(self, outfile=..., section=...): + """ + Write the current ConfigObj as a file + + tekNico: FIXME: use StringIO instead of real files + + >>> filename = a.filename + >>> a.filename = 'test.ini' + >>> a.write() + >>> a.filename = filename + >>> a == ConfigObj('test.ini', raise_errors=True) + 1 + >>> import os + >>> os.remove('test.ini') + """ + ... + + def validate(self, validator, preserve_errors=..., copy=..., section=...): + """ + Test the ConfigObj against a configspec. + + It uses the ``validator`` object from *validate.py*. + + To run ``validate`` on the current ConfigObj, call: :: + + test = config.validate(validator) + + (Normally having previously passed in the configspec when the ConfigObj + was created - you can dynamically assign a dictionary of checks to the + ``configspec`` attribute of a section though). + + It returns ``True`` if everything passes, or a dictionary of + pass/fails (True/False). If every member of a subsection passes, it + will just have the value ``True``. (It also returns ``False`` if all + members fail). + + In addition, it converts the values from strings to their native + types if their checks pass (and ``stringify`` is set). + + If ``preserve_errors`` is ``True`` (``False`` is default) then instead + of a marking a fail with a ``False``, it will preserve the actual + exception object. This can contain info about the reason for failure. + For example the ``VdtValueTooSmallError`` indicates that the value + supplied was too small. If a value (or section) is missing it will + still be marked as ``False``. + + You must have the validate module to use ``preserve_errors=True``. + + You can then use the ``flatten_errors`` function to turn your nested + results dictionary into a flattened list of failures - useful for + displaying meaningful error messages. + """ + ... + + def reset(self): # -> None: + """Clear ConfigObj instance and restore to 'freshly created' state.""" + ... + + def reload(self): # -> None: + """ + Reload a ConfigObj from file. + + This method raises a ``ReloadError`` if the ConfigObj doesn't have + a filename attribute pointing to a file. + """ + ... + + + +class SimpleVal: + """ + A simple validator. + Can be used to check that all members expected are present. + + To use it, provide a configspec with all your members in (the value given + will be ignored). Pass an instance of ``SimpleVal`` to the ``validate`` + method of your ``ConfigObj``. ``validate`` will return ``True`` if all + members are present, or a dictionary with True/False meaning + present/missing. (Whole missing sections will be replaced with ``False``) + """ + def __init__(self) -> None: + ... + + def check(self, check, member, missing=...): + """A dummy check method, always returns the value unchanged.""" + ... + + + +def flatten_errors(cfg, res, levels=..., results=...): # -> list[Unknown]: + """ + An example function that will turn a nested dictionary of results + (as returned by ``ConfigObj.validate``) into a flat list. + + ``cfg`` is the ConfigObj instance being checked, ``res`` is the results + dictionary returned by ``validate``. + + (This is a recursive function, so you shouldn't use the ``levels`` or + ``results`` arguments - they are used by the function.) + + Returns a list of keys that failed. Each member of the list is a tuple:: + + ([list of sections...], key, result) + + If ``validate`` was called with ``preserve_errors=False`` (the default) + then ``result`` will always be ``False``. + + *list of sections* is a flattened list of sections that the key was found + in. + + If the section was missing (or a section was expected and a scalar provided + - or vice-versa) then key will be ``None``. + + If the value (or section) was missing then ``result`` will be ``False``. + + If ``validate`` was called with ``preserve_errors=True`` and a value + was present, but failed the check, then ``result`` will be the exception + object returned. You can use this as a string that describes the failure. + + For example *The value "3" is of the wrong type*. + """ + ... + +def get_extra_values(conf, _prepend=...): # -> list[Unknown]: + """ + Find all the values and sections not in the configspec from a validated + ConfigObj. + + ``get_extra_values`` returns a list of tuples where each tuple represents + either an extra section, or an extra value. + + The tuples contain two values, a tuple representing the section the value + is in and the name of the extra values. For extra values in the top level + section the first member will be an empty tuple. For values in the 'foo' + section the first member will be ``('foo',)``. For members in the 'bar' + subsection of the 'foo' section the first member will be ``('foo', 'bar')``. + + NOTE: If you call ``get_extra_values`` on a ConfigObj instance that hasn't + been validated it will return an empty list. + """ + ... + diff --git a/typings/astropy/extern/configobj/validate.pyi b/typings/astropy/extern/configobj/validate.pyi new file mode 100644 index 0000000..6b854dd --- /dev/null +++ b/typings/astropy/extern/configobj/validate.pyi @@ -0,0 +1,862 @@ +""" +This type stub file was generated by pyright. +""" + +import sys + +""" + The Validator object is used to check that supplied values + conform to a specification. + + The value can be supplied as a string - e.g. from a config file. + In this case the check will also *convert* the value to + the required type. This allows you to add validation + as a transparent layer to access data stored as strings. + The validation checks that the data is correct *and* + converts it to the expected type. + + Some standard checks are provided for basic data types. + Additional checks are easy to write. They can be + provided when the ``Validator`` is instantiated or + added afterwards. + + The standard functions work with the following basic data types : + + * integers + * floats + * booleans + * strings + * ip_addr + + plus lists of these datatypes + + Adding additional checks is done through coding simple functions. + + The full set of standard checks are : + + * 'integer': matches integer values (including negative) + Takes optional 'min' and 'max' arguments : :: + + integer() + integer(3, 9) # any value from 3 to 9 + integer(min=0) # any positive value + integer(max=9) + + * 'float': matches float values + Has the same parameters as the integer check. + + * 'boolean': matches boolean values - ``True`` or ``False`` + Acceptable string values for True are : + true, on, yes, 1 + Acceptable string values for False are : + false, off, no, 0 + + Any other value raises an error. + + * 'ip_addr': matches an Internet Protocol address, v.4, represented + by a dotted-quad string, i.e. '1.2.3.4'. + + * 'string': matches any string. + Takes optional keyword args 'min' and 'max' + to specify min and max lengths of the string. + + * 'list': matches any list. + Takes optional keyword args 'min', and 'max' to specify min and + max sizes of the list. (Always returns a list.) + + * 'tuple': matches any tuple. + Takes optional keyword args 'min', and 'max' to specify min and + max sizes of the tuple. (Always returns a tuple.) + + * 'int_list': Matches a list of integers. + Takes the same arguments as list. + + * 'float_list': Matches a list of floats. + Takes the same arguments as list. + + * 'bool_list': Matches a list of boolean values. + Takes the same arguments as list. + + * 'ip_addr_list': Matches a list of IP addresses. + Takes the same arguments as list. + + * 'string_list': Matches a list of strings. + Takes the same arguments as list. + + * 'mixed_list': Matches a list with different types in + specific positions. List size must match + the number of arguments. + + Each position can be one of : + 'integer', 'float', 'ip_addr', 'string', 'boolean' + + So to specify a list with two strings followed + by two integers, you write the check as : :: + + mixed_list('string', 'string', 'integer', 'integer') + + * 'pass': This check matches everything ! It never fails + and the value is unchanged. + + It is also the default if no check is specified. + + * 'option': This check matches any from a list of options. + You specify this check with : :: + + option('option 1', 'option 2', 'option 3') + + You can supply a default value (returned if no value is supplied) + using the default keyword argument. + + You specify a list argument for default using a list constructor syntax in + the check : :: + + checkname(arg1, arg2, default=list('val 1', 'val 2', 'val 3')) + + A badly formatted set of arguments will raise a ``VdtParamError``. +""" +__version__ = ... +__all__ = ('__version__', 'dottedQuadToNum', 'numToDottedQuad', 'ValidateError', 'VdtUnknownCheckError', 'VdtParamError', 'VdtTypeError', 'VdtValueError', 'VdtValueTooSmallError', 'VdtValueTooBigError', 'VdtValueTooShortError', 'VdtValueTooLongError', 'VdtMissingValue', 'Validator', 'is_integer', 'is_float', 'is_boolean', 'is_list', 'is_tuple', 'is_ip_addr', 'is_string', 'is_int_list', 'is_bool_list', 'is_float_list', 'is_string_list', 'is_ip_addr_list', 'is_mixed_list', 'is_option', '__docformat__') +if sys.version_info < (3, ): + ... +else: + string_type = str + unicode = ... + long = int +_list_arg = ... +_list_members = ... +_paramstring = ... +_matchstring = ... +def dottedQuadToNum(ip): # -> Any: + """ + Convert decimal dotted quad string to long integer + + >>> int(dottedQuadToNum('1 ')) + 1 + >>> int(dottedQuadToNum(' 1.2')) + 16777218 + >>> int(dottedQuadToNum(' 1.2.3 ')) + 16908291 + >>> int(dottedQuadToNum('1.2.3.4')) + 16909060 + >>> dottedQuadToNum('255.255.255.255') + 4294967295 + >>> dottedQuadToNum('255.255.255.256') + Traceback (most recent call last): + ValueError: Not a good dotted-quad IP: 255.255.255.256 + """ + ... + +def numToDottedQuad(num): # -> str: + """ + Convert int or long int to dotted quad string + + >>> numToDottedQuad(long(-1)) + Traceback (most recent call last): + ValueError: Not a good numeric IP: -1 + >>> numToDottedQuad(long(1)) + '0.0.0.1' + >>> numToDottedQuad(long(16777218)) + '1.0.0.2' + >>> numToDottedQuad(long(16908291)) + '1.2.0.3' + >>> numToDottedQuad(long(16909060)) + '1.2.3.4' + >>> numToDottedQuad(long(4294967295)) + '255.255.255.255' + >>> numToDottedQuad(long(4294967296)) + Traceback (most recent call last): + ValueError: Not a good numeric IP: 4294967296 + >>> numToDottedQuad(-1) + Traceback (most recent call last): + ValueError: Not a good numeric IP: -1 + >>> numToDottedQuad(1) + '0.0.0.1' + >>> numToDottedQuad(16777218) + '1.0.0.2' + >>> numToDottedQuad(16908291) + '1.2.0.3' + >>> numToDottedQuad(16909060) + '1.2.3.4' + >>> numToDottedQuad(4294967295) + '255.255.255.255' + >>> numToDottedQuad(4294967296) + Traceback (most recent call last): + ValueError: Not a good numeric IP: 4294967296 + + """ + ... + +class ValidateError(Exception): + """ + This error indicates that the check failed. + It can be the base class for more specific errors. + + Any check function that fails ought to raise this error. + (or a subclass) + + >>> raise ValidateError + Traceback (most recent call last): + ValidateError + """ + ... + + +class VdtMissingValue(ValidateError): + """No value was supplied to a check that needed one.""" + ... + + +class VdtUnknownCheckError(ValidateError): + """An unknown check function was requested""" + def __init__(self, value) -> None: + """ + >>> raise VdtUnknownCheckError('yoda') + Traceback (most recent call last): + VdtUnknownCheckError: the check "yoda" is unknown. + """ + ... + + + +class VdtParamError(SyntaxError): + """An incorrect parameter was passed""" + def __init__(self, name, value) -> None: + """ + >>> raise VdtParamError('yoda', 'jedi') + Traceback (most recent call last): + VdtParamError: passed an incorrect value "jedi" for parameter "yoda". + """ + ... + + + +class VdtTypeError(ValidateError): + """The value supplied was of the wrong type""" + def __init__(self, value) -> None: + """ + >>> raise VdtTypeError('jedi') + Traceback (most recent call last): + VdtTypeError: the value "jedi" is of the wrong type. + """ + ... + + + +class VdtValueError(ValidateError): + """The value supplied was of the correct type, but was not an allowed value.""" + def __init__(self, value) -> None: + """ + >>> raise VdtValueError('jedi') + Traceback (most recent call last): + VdtValueError: the value "jedi" is unacceptable. + """ + ... + + + +class VdtValueTooSmallError(VdtValueError): + """The value supplied was of the correct type, but was too small.""" + def __init__(self, value) -> None: + """ + >>> raise VdtValueTooSmallError('0') + Traceback (most recent call last): + VdtValueTooSmallError: the value "0" is too small. + """ + ... + + + +class VdtValueTooBigError(VdtValueError): + """The value supplied was of the correct type, but was too big.""" + def __init__(self, value) -> None: + """ + >>> raise VdtValueTooBigError('1') + Traceback (most recent call last): + VdtValueTooBigError: the value "1" is too big. + """ + ... + + + +class VdtValueTooShortError(VdtValueError): + """The value supplied was of the correct type, but was too short.""" + def __init__(self, value) -> None: + """ + >>> raise VdtValueTooShortError('jed') + Traceback (most recent call last): + VdtValueTooShortError: the value "jed" is too short. + """ + ... + + + +class VdtValueTooLongError(VdtValueError): + """The value supplied was of the correct type, but was too long.""" + def __init__(self, value) -> None: + """ + >>> raise VdtValueTooLongError('jedie') + Traceback (most recent call last): + VdtValueTooLongError: the value "jedie" is too long. + """ + ... + + + +class Validator: + """ + Validator is an object that allows you to register a set of 'checks'. + These checks take input and test that it conforms to the check. + + This can also involve converting the value from a string into + the correct datatype. + + The ``check`` method takes an input string which configures which + check is to be used and applies that check to a supplied value. + + An example input string would be: + 'int_range(param1, param2)' + + You would then provide something like: + + >>> def int_range_check(value, min, max): + ... # turn min and max from strings to integers + ... min = int(min) + ... max = int(max) + ... # check that value is of the correct type. + ... # possible valid inputs are integers or strings + ... # that represent integers + ... if not isinstance(value, (int, long, string_type)): + ... raise VdtTypeError(value) + ... elif isinstance(value, string_type): + ... # if we are given a string + ... # attempt to convert to an integer + ... try: + ... value = int(value) + ... except ValueError: + ... raise VdtValueError(value) + ... # check the value is between our constraints + ... if not min <= value: + ... raise VdtValueTooSmallError(value) + ... if not value <= max: + ... raise VdtValueTooBigError(value) + ... return value + + >>> fdict = {'int_range': int_range_check} + >>> vtr1 = Validator(fdict) + >>> vtr1.check('int_range(20, 40)', '30') + 30 + >>> vtr1.check('int_range(20, 40)', '60') + Traceback (most recent call last): + VdtValueTooBigError: the value "60" is too big. + + New functions can be added with : :: + + >>> vtr2 = Validator() + >>> vtr2.functions['int_range'] = int_range_check + + Or by passing in a dictionary of functions when Validator + is instantiated. + + Your functions *can* use keyword arguments, + but the first argument should always be 'value'. + + If the function doesn't take additional arguments, + the parentheses are optional in the check. + It can be written with either of : :: + + keyword = function_name + keyword = function_name() + + The first program to utilise Validator() was Michael Foord's + ConfigObj, an alternative to ConfigParser which supports lists and + can validate a config file using a config schema. + For more details on using Validator with ConfigObj see: + https://configobj.readthedocs.org/en/latest/configobj.html + """ + _func_re = ... + _key_arg = ... + _list_arg = ... + _list_members = ... + _paramfinder = ... + _matchfinder = ... + def __init__(self, functions=...) -> None: + """ + >>> vtri = Validator() + """ + ... + + def check(self, check, value, missing=...): # -> int | bool | list[int | float | str | bool] | string_type | None: + """ + Usage: check(check, value) + + Arguments: + check: string representing check to apply (including arguments) + value: object to be checked + Returns value, converted to correct type if necessary + + If the check fails, raises a ``ValidateError`` subclass. + + >>> vtor.check('yoda', '') + Traceback (most recent call last): + VdtUnknownCheckError: the check "yoda" is unknown. + >>> vtor.check('yoda()', '') + Traceback (most recent call last): + VdtUnknownCheckError: the check "yoda" is unknown. + + >>> vtor.check('string(default="")', '', missing=True) + '' + """ + ... + + def get_default_value(self, check): # -> int | bool | list[int | float | str | bool] | string_type | None: + """ + Given a check, return the default value for the check + (converted to the right type). + + If the check doesn't specify a default value then a + ``KeyError`` will be raised. + """ + ... + + + +def is_integer(value, min=..., max=...): # -> int: + """ + A check that tests that a given value is an integer (int, or long) + and optionally, between bounds. A negative value is accepted, while + a float will fail. + + If the value is a string, then the conversion is done - if possible. + Otherwise a VdtError is raised. + + >>> vtor.check('integer', '-1') + -1 + >>> vtor.check('integer', '0') + 0 + >>> vtor.check('integer', 9) + 9 + >>> vtor.check('integer', 'a') + Traceback (most recent call last): + VdtTypeError: the value "a" is of the wrong type. + >>> vtor.check('integer', '2.2') + Traceback (most recent call last): + VdtTypeError: the value "2.2" is of the wrong type. + >>> vtor.check('integer(10)', '20') + 20 + >>> vtor.check('integer(max=20)', '15') + 15 + >>> vtor.check('integer(10)', '9') + Traceback (most recent call last): + VdtValueTooSmallError: the value "9" is too small. + >>> vtor.check('integer(10)', 9) + Traceback (most recent call last): + VdtValueTooSmallError: the value "9" is too small. + >>> vtor.check('integer(max=20)', '35') + Traceback (most recent call last): + VdtValueTooBigError: the value "35" is too big. + >>> vtor.check('integer(max=20)', 35) + Traceback (most recent call last): + VdtValueTooBigError: the value "35" is too big. + >>> vtor.check('integer(0, 9)', False) + 0 + """ + ... + +def is_float(value, min=..., max=...): # -> float: + """ + A check that tests that a given value is a float + (an integer will be accepted), and optionally - that it is between bounds. + + If the value is a string, then the conversion is done - if possible. + Otherwise a VdtError is raised. + + This can accept negative values. + + >>> vtor.check('float', '2') + 2.0 + + From now on we multiply the value to avoid comparing decimals + + >>> vtor.check('float', '-6.8') * 10 + -68.0 + >>> vtor.check('float', '12.2') * 10 + 122.0 + >>> vtor.check('float', 8.4) * 10 + 84.0 + >>> vtor.check('float', 'a') + Traceback (most recent call last): + VdtTypeError: the value "a" is of the wrong type. + >>> vtor.check('float(10.1)', '10.2') * 10 + 102.0 + >>> vtor.check('float(max=20.2)', '15.1') * 10 + 151.0 + >>> vtor.check('float(10.0)', '9.0') + Traceback (most recent call last): + VdtValueTooSmallError: the value "9.0" is too small. + >>> vtor.check('float(max=20.0)', '35.0') + Traceback (most recent call last): + VdtValueTooBigError: the value "35.0" is too big. + """ + ... + +bool_dict = ... +def is_boolean(value): # -> bool: + """ + Check if the value represents a boolean. + + >>> vtor.check('boolean', 0) + 0 + >>> vtor.check('boolean', False) + 0 + >>> vtor.check('boolean', '0') + 0 + >>> vtor.check('boolean', 'off') + 0 + >>> vtor.check('boolean', 'false') + 0 + >>> vtor.check('boolean', 'no') + 0 + >>> vtor.check('boolean', 'nO') + 0 + >>> vtor.check('boolean', 'NO') + 0 + >>> vtor.check('boolean', 1) + 1 + >>> vtor.check('boolean', True) + 1 + >>> vtor.check('boolean', '1') + 1 + >>> vtor.check('boolean', 'on') + 1 + >>> vtor.check('boolean', 'true') + 1 + >>> vtor.check('boolean', 'yes') + 1 + >>> vtor.check('boolean', 'Yes') + 1 + >>> vtor.check('boolean', 'YES') + 1 + >>> vtor.check('boolean', '') + Traceback (most recent call last): + VdtTypeError: the value "" is of the wrong type. + >>> vtor.check('boolean', 'up') + Traceback (most recent call last): + VdtTypeError: the value "up" is of the wrong type. + + """ + ... + +def is_ip_addr(value): # -> str: + """ + Check that the supplied value is an Internet Protocol address, v.4, + represented by a dotted-quad string, i.e. '1.2.3.4'. + + >>> vtor.check('ip_addr', '1 ') + '1' + >>> vtor.check('ip_addr', ' 1.2') + '1.2' + >>> vtor.check('ip_addr', ' 1.2.3 ') + '1.2.3' + >>> vtor.check('ip_addr', '1.2.3.4') + '1.2.3.4' + >>> vtor.check('ip_addr', '0.0.0.0') + '0.0.0.0' + >>> vtor.check('ip_addr', '255.255.255.255') + '255.255.255.255' + >>> vtor.check('ip_addr', '255.255.255.256') + Traceback (most recent call last): + VdtValueError: the value "255.255.255.256" is unacceptable. + >>> vtor.check('ip_addr', '1.2.3.4.5') + Traceback (most recent call last): + VdtValueError: the value "1.2.3.4.5" is unacceptable. + >>> vtor.check('ip_addr', 0) + Traceback (most recent call last): + VdtTypeError: the value "0" is of the wrong type. + """ + ... + +def is_list(value, min=..., max=...): # -> list[Unknown]: + """ + Check that the value is a list of values. + + You can optionally specify the minimum and maximum number of members. + + It does no check on list members. + + >>> vtor.check('list', ()) + [] + >>> vtor.check('list', []) + [] + >>> vtor.check('list', (1, 2)) + [1, 2] + >>> vtor.check('list', [1, 2]) + [1, 2] + >>> vtor.check('list(3)', (1, 2)) + Traceback (most recent call last): + VdtValueTooShortError: the value "(1, 2)" is too short. + >>> vtor.check('list(max=5)', (1, 2, 3, 4, 5, 6)) + Traceback (most recent call last): + VdtValueTooLongError: the value "(1, 2, 3, 4, 5, 6)" is too long. + >>> vtor.check('list(min=3, max=5)', (1, 2, 3, 4)) + [1, 2, 3, 4] + >>> vtor.check('list', 0) + Traceback (most recent call last): + VdtTypeError: the value "0" is of the wrong type. + >>> vtor.check('list', '12') + Traceback (most recent call last): + VdtTypeError: the value "12" is of the wrong type. + """ + ... + +def is_tuple(value, min=..., max=...): # -> tuple[Unknown, ...]: + """ + Check that the value is a tuple of values. + + You can optionally specify the minimum and maximum number of members. + + It does no check on members. + + >>> vtor.check('tuple', ()) + () + >>> vtor.check('tuple', []) + () + >>> vtor.check('tuple', (1, 2)) + (1, 2) + >>> vtor.check('tuple', [1, 2]) + (1, 2) + >>> vtor.check('tuple(3)', (1, 2)) + Traceback (most recent call last): + VdtValueTooShortError: the value "(1, 2)" is too short. + >>> vtor.check('tuple(max=5)', (1, 2, 3, 4, 5, 6)) + Traceback (most recent call last): + VdtValueTooLongError: the value "(1, 2, 3, 4, 5, 6)" is too long. + >>> vtor.check('tuple(min=3, max=5)', (1, 2, 3, 4)) + (1, 2, 3, 4) + >>> vtor.check('tuple', 0) + Traceback (most recent call last): + VdtTypeError: the value "0" is of the wrong type. + >>> vtor.check('tuple', '12') + Traceback (most recent call last): + VdtTypeError: the value "12" is of the wrong type. + """ + ... + +def is_string(value, min=..., max=...): # -> string_type: + """ + Check that the supplied value is a string. + + You can optionally specify the minimum and maximum number of members. + + >>> vtor.check('string', '0') + '0' + >>> vtor.check('string', 0) + Traceback (most recent call last): + VdtTypeError: the value "0" is of the wrong type. + >>> vtor.check('string(2)', '12') + '12' + >>> vtor.check('string(2)', '1') + Traceback (most recent call last): + VdtValueTooShortError: the value "1" is too short. + >>> vtor.check('string(min=2, max=3)', '123') + '123' + >>> vtor.check('string(min=2, max=3)', '1234') + Traceback (most recent call last): + VdtValueTooLongError: the value "1234" is too long. + """ + ... + +def is_int_list(value, min=..., max=...): # -> list[int]: + """ + Check that the value is a list of integers. + + You can optionally specify the minimum and maximum number of members. + + Each list member is checked that it is an integer. + + >>> vtor.check('int_list', ()) + [] + >>> vtor.check('int_list', []) + [] + >>> vtor.check('int_list', (1, 2)) + [1, 2] + >>> vtor.check('int_list', [1, 2]) + [1, 2] + >>> vtor.check('int_list', [1, 'a']) + Traceback (most recent call last): + VdtTypeError: the value "a" is of the wrong type. + """ + ... + +def is_bool_list(value, min=..., max=...): # -> list[bool]: + """ + Check that the value is a list of booleans. + + You can optionally specify the minimum and maximum number of members. + + Each list member is checked that it is a boolean. + + >>> vtor.check('bool_list', ()) + [] + >>> vtor.check('bool_list', []) + [] + >>> check_res = vtor.check('bool_list', (True, False)) + >>> check_res == [True, False] + 1 + >>> check_res = vtor.check('bool_list', [True, False]) + >>> check_res == [True, False] + 1 + >>> vtor.check('bool_list', [True, 'a']) + Traceback (most recent call last): + VdtTypeError: the value "a" is of the wrong type. + """ + ... + +def is_float_list(value, min=..., max=...): # -> list[float]: + """ + Check that the value is a list of floats. + + You can optionally specify the minimum and maximum number of members. + + Each list member is checked that it is a float. + + >>> vtor.check('float_list', ()) + [] + >>> vtor.check('float_list', []) + [] + >>> vtor.check('float_list', (1, 2.0)) + [1.0, 2.0] + >>> vtor.check('float_list', [1, 2.0]) + [1.0, 2.0] + >>> vtor.check('float_list', [1, 'a']) + Traceback (most recent call last): + VdtTypeError: the value "a" is of the wrong type. + """ + ... + +def is_string_list(value, min=..., max=...): # -> list[string_type]: + """ + Check that the value is a list of strings. + + You can optionally specify the minimum and maximum number of members. + + Each list member is checked that it is a string. + + >>> vtor.check('string_list', ()) + [] + >>> vtor.check('string_list', []) + [] + >>> vtor.check('string_list', ('a', 'b')) + ['a', 'b'] + >>> vtor.check('string_list', ['a', 1]) + Traceback (most recent call last): + VdtTypeError: the value "1" is of the wrong type. + >>> vtor.check('string_list', 'hello') + Traceback (most recent call last): + VdtTypeError: the value "hello" is of the wrong type. + """ + ... + +def is_ip_addr_list(value, min=..., max=...): # -> list[str]: + """ + Check that the value is a list of IP addresses. + + You can optionally specify the minimum and maximum number of members. + + Each list member is checked that it is an IP address. + + >>> vtor.check('ip_addr_list', ()) + [] + >>> vtor.check('ip_addr_list', []) + [] + >>> vtor.check('ip_addr_list', ('1.2.3.4', '5.6.7.8')) + ['1.2.3.4', '5.6.7.8'] + >>> vtor.check('ip_addr_list', ['a']) + Traceback (most recent call last): + VdtValueError: the value "a" is unacceptable. + """ + ... + +def force_list(value, min=..., max=...): # -> list[Unknown]: + """ + Check that a value is a list, coercing strings into + a list with one member. Useful where users forget the + trailing comma that turns a single value into a list. + + You can optionally specify the minimum and maximum number of members. + A minumum of greater than one will fail if the user only supplies a + string. + + >>> vtor.check('force_list', ()) + [] + >>> vtor.check('force_list', []) + [] + >>> vtor.check('force_list', 'hello') + ['hello'] + """ + ... + +fun_dict = ... +def is_mixed_list(value, *args): # -> list[int | float | str | bool]: + """ + Check that the value is a list. + Allow specifying the type of each member. + Work on lists of specific lengths. + + You specify each member as a positional argument specifying type + + Each type should be one of the following strings : + 'integer', 'float', 'ip_addr', 'string', 'boolean' + + So you can specify a list of two strings, followed by + two integers as : + + mixed_list('string', 'string', 'integer', 'integer') + + The length of the list must match the number of positional + arguments you supply. + + >>> mix_str = "mixed_list('integer', 'float', 'ip_addr', 'string', 'boolean')" + >>> check_res = vtor.check(mix_str, (1, 2.0, '1.2.3.4', 'a', True)) + >>> check_res == [1, 2.0, '1.2.3.4', 'a', True] + 1 + >>> check_res = vtor.check(mix_str, ('1', '2.0', '1.2.3.4', 'a', 'True')) + >>> check_res == [1, 2.0, '1.2.3.4', 'a', True] + 1 + >>> vtor.check(mix_str, ('b', 2.0, '1.2.3.4', 'a', True)) + Traceback (most recent call last): + VdtTypeError: the value "b" is of the wrong type. + >>> vtor.check(mix_str, (1, 2.0, '1.2.3.4', 'a')) + Traceback (most recent call last): + VdtValueTooShortError: the value "(1, 2.0, '1.2.3.4', 'a')" is too short. + >>> vtor.check(mix_str, (1, 2.0, '1.2.3.4', 'a', 1, 'b')) + Traceback (most recent call last): + VdtValueTooLongError: the value "(1, 2.0, '1.2.3.4', 'a', 1, 'b')" is too long. + >>> vtor.check(mix_str, 0) + Traceback (most recent call last): + VdtTypeError: the value "0" is of the wrong type. + + >>> vtor.check('mixed_list("yoda")', ('a')) + Traceback (most recent call last): + VdtParamError: passed an incorrect value "KeyError('yoda',)" for parameter "'mixed_list'" + """ + ... + +def is_option(value, *options): # -> string_type: + """ + This check matches the value to any of a set of options. + + >>> vtor.check('option("yoda", "jedi")', 'yoda') + 'yoda' + >>> vtor.check('option("yoda", "jedi")', 'jed') + Traceback (most recent call last): + VdtValueError: the value "jed" is unacceptable. + >>> vtor.check('option("yoda", "jedi")', 0) + Traceback (most recent call last): + VdtTypeError: the value "0" is of the wrong type. + """ + ... + +if __name__ == '__main__': + m = ... + globs = ... diff --git a/typings/astropy/extern/ply/__init__.pyi b/typings/astropy/extern/ply/__init__.pyi new file mode 100644 index 0000000..0670e58 --- /dev/null +++ b/typings/astropy/extern/ply/__init__.pyi @@ -0,0 +1,6 @@ +""" +This type stub file was generated by pyright. +""" + +__version__ = ... +__all__ = ['lex', 'yacc'] diff --git a/typings/astropy/extern/ply/lex.pyi b/typings/astropy/extern/ply/lex.pyi new file mode 100644 index 0000000..ff50701 --- /dev/null +++ b/typings/astropy/extern/ply/lex.pyi @@ -0,0 +1,140 @@ +""" +This type stub file was generated by pyright. +""" + +__version__ = ... +__tabversion__ = ... +_is_identifier = ... +class LexError(Exception): + def __init__(self, message, s) -> None: + ... + + + +class LexToken: + def __str__(self) -> str: + ... + + def __repr__(self): # -> str: + ... + + + +class PlyLogger: + def __init__(self, f) -> None: + ... + + def critical(self, msg, *args, **kwargs): # -> None: + ... + + def warning(self, msg, *args, **kwargs): # -> None: + ... + + def error(self, msg, *args, **kwargs): # -> None: + ... + + info = ... + debug = ... + + +class NullLogger: + def __getattribute__(self, name): # -> Self@NullLogger: + ... + + def __call__(self, *args, **kwargs): # -> Self@NullLogger: + ... + + + +class Lexer: + def __init__(self) -> None: + ... + + def clone(self, object=...): # -> Self@Lexer: + ... + + def writetab(self, lextab, outputdir=...): # -> None: + ... + + def readtab(self, tabfile, fdict): # -> None: + ... + + def input(self, s): # -> None: + ... + + def begin(self, state): # -> None: + ... + + def push_state(self, state): # -> None: + ... + + def pop_state(self): # -> None: + ... + + def current_state(self): # -> str: + ... + + def skip(self, n): # -> None: + ... + + def token(self): # -> LexToken | None: + ... + + def __iter__(self): # -> Self@Lexer: + ... + + def next(self): # -> LexToken: + ... + + __next__ = ... + + +def get_caller_module_dict(levels): # -> dict[str, Any]: + ... + +class LexerReflect: + def __init__(self, ldict, log=..., reflags=...) -> None: + ... + + def get_all(self): # -> None: + ... + + def validate_all(self): # -> bool: + ... + + def get_tokens(self): # -> None: + ... + + def validate_tokens(self): # -> None: + ... + + def get_literals(self): # -> None: + ... + + def validate_literals(self): # -> None: + ... + + def get_states(self): # -> None: + ... + + def get_rules(self): # -> None: + ... + + def validate_rules(self): # -> None: + ... + + def validate_module(self, module): # -> None: + ... + + + +def lex(module=..., object=..., debug=..., optimize=..., lextab=..., reflags=..., nowarn=..., outputdir=..., debuglog=..., errorlog=...): + ... + +def runmain(lexer=..., data=...): # -> None: + ... + +def TOKEN(r): # -> (f: Unknown) -> Unknown: + ... + +Token = ... diff --git a/typings/astropy/extern/ply/yacc.pyi b/typings/astropy/extern/ply/yacc.pyi new file mode 100644 index 0000000..93e620c --- /dev/null +++ b/typings/astropy/extern/ply/yacc.pyi @@ -0,0 +1,399 @@ +""" +This type stub file was generated by pyright. +""" + +import sys + +__version__ = ... +__tabversion__ = ... +yaccdebug = ... +debug_file = ... +tab_module = ... +default_lr = ... +error_count = ... +yaccdevel = ... +resultlimit = ... +pickle_protocol = ... +if sys.version_info[0] < 3: + ... +else: + string_types = str +MAXINT = ... +class PlyLogger: + def __init__(self, f) -> None: + ... + + def debug(self, msg, *args, **kwargs): # -> None: + ... + + info = ... + def warning(self, msg, *args, **kwargs): # -> None: + ... + + def error(self, msg, *args, **kwargs): # -> None: + ... + + critical = ... + + +class NullLogger: + def __getattribute__(self, name): # -> Self@NullLogger: + ... + + def __call__(self, *args, **kwargs): # -> Self@NullLogger: + ... + + + +class YaccError(Exception): + ... + + +def format_result(r): # -> str: + ... + +def format_stack_entry(r): # -> str: + ... + +_errok = ... +_token = ... +_restart = ... +_warnmsg = ... +def errok(): + ... + +def restart(): + ... + +def token(): + ... + +def call_errorfunc(errorfunc, token, parser): + ... + +class YaccSymbol: + def __str__(self) -> str: + ... + + def __repr__(self): # -> str: + ... + + + +class YaccProduction: + def __init__(self, s, stack=...) -> None: + ... + + def __getitem__(self, n): # -> list[Unknown]: + ... + + def __setitem__(self, n, v): # -> None: + ... + + def __getslice__(self, i, j): # -> list[Unknown]: + ... + + def __len__(self): # -> int: + ... + + def lineno(self, n): # -> Any | int: + ... + + def set_lineno(self, n, lineno): # -> None: + ... + + def linespan(self, n): # -> tuple[Any | int, Any | int]: + ... + + def lexpos(self, n): # -> Any | int: + ... + + def set_lexpos(self, n, lexpos): # -> None: + ... + + def lexspan(self, n): # -> tuple[Any | int, Any | int]: + ... + + def error(self): + ... + + + +class LRParser: + def __init__(self, lrtab, errorf) -> None: + ... + + def errok(self): # -> None: + ... + + def restart(self): # -> None: + ... + + def set_defaulted_states(self): # -> None: + ... + + def disable_defaulted_states(self): # -> None: + ... + + def parse(self, input=..., lexer=..., debug=..., tracking=..., tokenfunc=...): + ... + + def parsedebug(self, input=..., lexer=..., debug=..., tracking=..., tokenfunc=...): + ... + + def parseopt(self, input=..., lexer=..., debug=..., tracking=..., tokenfunc=...): + ... + + def parseopt_notrack(self, input=..., lexer=..., debug=..., tracking=..., tokenfunc=...): + ... + + + +_is_identifier = ... +class Production: + reduced = ... + def __init__(self, number, name, prod, precedence=..., func=..., file=..., line=...) -> None: + ... + + def __str__(self) -> str: + ... + + def __repr__(self): # -> str: + ... + + def __len__(self): # -> int: + ... + + def __nonzero__(self): # -> Literal[1]: + ... + + def __getitem__(self, index): + ... + + def lr_item(self, n): # -> LRItem | None: + ... + + def bind(self, pdict): # -> None: + ... + + + +class MiniProduction: + def __init__(self, str, name, len, func, file, line) -> None: + ... + + def __str__(self) -> str: + ... + + def __repr__(self): # -> LiteralString: + ... + + def bind(self, pdict): # -> None: + ... + + + +class LRItem: + def __init__(self, p, n) -> None: + ... + + def __str__(self) -> str: + ... + + def __repr__(self): # -> str: + ... + + + +def rightmost_terminal(symbols, terminals): # -> None: + ... + +class GrammarError(YaccError): + ... + + +class Grammar: + def __init__(self, terminals) -> None: + ... + + def __len__(self): # -> int: + ... + + def __getitem__(self, index): # -> None: + ... + + def set_precedence(self, term, assoc, level): # -> None: + ... + + def add_production(self, prodname, syms, func=..., file=..., line=...): # -> None: + ... + + def set_start(self, start=...): # -> None: + ... + + def find_unreachable(self): # -> list[Unknown]: + ... + + def infinite_cycles(self): # -> list[Unknown]: + ... + + def undefined_symbols(self): # -> list[Unknown]: + ... + + def unused_terminals(self): # -> list[Unknown]: + ... + + def unused_rules(self): # -> list[Unknown]: + ... + + def unused_precedence(self): # -> list[Unknown]: + ... + + def compute_first(self): # -> dict[Unknown, Unknown]: + ... + + def compute_follow(self, start=...): # -> dict[Unknown, Unknown]: + ... + + def build_lritems(self): # -> None: + ... + + + +class VersionError(YaccError): + ... + + +class LRTable: + def __init__(self) -> None: + ... + + def read_table(self, module): # -> Any: + ... + + def read_pickle(self, filename): # -> Any: + ... + + def bind_callables(self, pdict): # -> None: + ... + + + +def digraph(X, R, FP): # -> dict[Unknown, Unknown]: + ... + +def traverse(x, N, stack, F, X, R, FP): # -> None: + ... + +class LALRError(YaccError): + ... + + +class LRGeneratedTable(LRTable): + def __init__(self, grammar, method=..., log=...) -> None: + ... + + def lr0_closure(self, I): + ... + + def lr0_goto(self, I, x): # -> list[Unknown] | None: + ... + + def lr0_items(self): # -> list[list[Unknown]]: + ... + + def compute_nullable_nonterminals(self): # -> set[Unknown]: + ... + + def find_nonterminal_transitions(self, C): # -> list[Unknown]: + ... + + def dr_relation(self, C, trans, nullable): # -> list[Unknown]: + ... + + def reads_relation(self, C, trans, empty): # -> list[Unknown]: + ... + + def compute_lookback_includes(self, C, trans, nullable): # -> tuple[dict[Unknown, Unknown], dict[Unknown, Unknown]]: + ... + + def compute_read_sets(self, C, ntrans, nullable): # -> dict[Unknown, Unknown]: + ... + + def compute_follow_sets(self, ntrans, readsets, inclsets): # -> dict[Unknown, Unknown]: + ... + + def add_lookaheads(self, lookbacks, followset): # -> None: + ... + + def add_lalr_lookaheads(self, C): # -> None: + ... + + def lr_parse_table(self): # -> None: + ... + + def write_table(self, tabmodule, outputdir=..., signature=...): + ... + + def pickle_table(self, filename, signature=...): # -> None: + ... + + + +def get_caller_module_dict(levels): # -> dict[str, Any]: + ... + +def parse_grammar(doc, file, line): # -> list[Unknown]: + ... + +class ParserReflect: + def __init__(self, pdict, log=...) -> None: + ... + + def get_all(self): # -> None: + ... + + def validate_all(self): # -> bool: + ... + + def signature(self): # -> LiteralString: + ... + + def validate_modules(self): # -> None: + ... + + def get_start(self): # -> None: + ... + + def validate_start(self): # -> None: + ... + + def get_error_func(self): # -> None: + ... + + def validate_error_func(self): # -> None: + ... + + def get_tokens(self): # -> None: + ... + + def validate_tokens(self): # -> None: + ... + + def get_precedence(self): # -> None: + ... + + def validate_precedence(self): # -> None: + ... + + def get_pfunctions(self): # -> None: + ... + + def validate_pfunctions(self): # -> None: + ... + + + +def yacc(method=..., debug=..., module=..., tabmodule=..., start=..., check_recursion=..., optimize=..., write_tables=..., debugfile=..., outputdir=..., debuglog=..., errorlog=..., picklefile=...): + ... + diff --git a/typings/astropy/io/__init__.pyi b/typings/astropy/io/__init__.pyi new file mode 100644 index 0000000..892b8f4 --- /dev/null +++ b/typings/astropy/io/__init__.pyi @@ -0,0 +1,8 @@ +""" +This type stub file was generated by pyright. +""" + +""" +This subpackage contains modules and packages for interpreting data storage +formats used by and in astropy. +""" diff --git a/typings/astropy/io/ascii/__init__.pyi b/typings/astropy/io/ascii/__init__.pyi new file mode 100644 index 0000000..e9f51e5 --- /dev/null +++ b/typings/astropy/io/ascii/__init__.pyi @@ -0,0 +1,24 @@ +""" +This type stub file was generated by pyright. +""" + +from .core import AllType, BaseData, BaseHeader, BaseInputter, BaseOutputter, BaseReader, BaseSplitter, Column, ContinuationLinesInputter, DefaultSplitter, FloatType, InconsistentTableError, IntType, NoType, NumType, ParameterError, StrType, TableOutputter, WhitespaceSplitter, convert_numpy, masked +from .basic import Basic, BasicData, BasicHeader, CommentedHeader, Csv, NoHeader, Rdb, Tab +from .fastbasic import FastBasic, FastCommentedHeader, FastCsv, FastNoHeader, FastRdb, FastTab +from .cds import Cds +from .mrt import Mrt +from .ecsv import Ecsv +from .latex import AASTex, Latex, latexdicts +from .html import HTML +from .ipac import Ipac +from .daophot import Daophot +from .qdp import QDP +from .sextractor import SExtractor +from .fixedwidth import FixedWidth, FixedWidthData, FixedWidthHeader, FixedWidthNoHeader, FixedWidthSplitter, FixedWidthTwoLine +from .rst import RST +from .ui import get_read_trace, get_reader, get_writer, read, set_guess, write +from . import connect + +""" An extensible ASCII table reader and writer. + +""" diff --git a/typings/astropy/io/ascii/basic.pyi b/typings/astropy/io/ascii/basic.pyi new file mode 100644 index 0000000..323fb14 --- /dev/null +++ b/typings/astropy/io/ascii/basic.pyi @@ -0,0 +1,347 @@ +""" +This type stub file was generated by pyright. +""" + +from . import core + +"""An extensible ASCII table reader and writer. + +basic.py: + Basic table read / write functionality for simple character + delimited files with various options for column header definition. + +:Copyright: Smithsonian Astrophysical Observatory (2011) +:Author: Tom Aldcroft (aldcroft@head.cfa.harvard.edu) +""" +class BasicHeader(core.BaseHeader): + """ + Basic table Header Reader + + Set a few defaults for common ascii table formats + (start at line 0, comments begin with ``#`` and possibly white space) + """ + start_line = ... + comment = ... + write_comment = ... + + +class BasicData(core.BaseData): + """ + Basic table Data Reader + + Set a few defaults for common ascii table formats + (start at line 1, comments begin with ``#`` and possibly white space) + """ + start_line = ... + comment = ... + write_comment = ... + + +class Basic(core.BaseReader): + r"""Character-delimited table with a single header line at the top. + + Lines beginning with a comment character (default='#') as the first + non-whitespace character are comments. + + Example table:: + + # Column definition is the first uncommented line + # Default delimiter is the space character. + apples oranges pears + + # Data starts after the header column definition, blank lines ignored + 1 2 3 + 4 5 6 + """ + _format_name = ... + _description = ... + _io_registry_format_aliases = ... + header_class = BasicHeader + data_class = BasicData + + +class NoHeaderHeader(BasicHeader): + """ + Reader for table header without a header + + Set the start of header line number to `None`, which tells the basic + reader there is no header line. + """ + start_line = ... + + +class NoHeaderData(BasicData): + """ + Reader for table data without a header + + Data starts at first uncommented line since there is no header line. + """ + start_line = ... + + +class NoHeader(Basic): + """Character-delimited table with no header line. + + When reading, columns are autonamed using header.auto_format which defaults + to "col%d". Otherwise this reader the same as the :class:`Basic` class + from which it is derived. Example:: + + # Table data + 1 2 "hello there" + 3 4 world + + """ + _format_name = ... + _description = ... + header_class = NoHeaderHeader + data_class = NoHeaderData + + +class CommentedHeaderHeader(BasicHeader): + """ + Header class for which the column definition line starts with the + comment character. See the :class:`CommentedHeader` class for an example. + """ + def process_lines(self, lines): # -> Generator[Unknown, None, None]: + """ + Return only lines that start with the comment regexp. For these + lines strip out the matching characters. + """ + ... + + def write(self, lines): # -> None: + ... + + + +class CommentedHeader(Basic): + """Character-delimited table with column names in a comment line. + + When reading, ``header_start`` can be used to specify the + line index of column names, and it can be a negative index (for example -1 + for the last commented line). The default delimiter is the + character. + + This matches the format produced by ``np.savetxt()``, with ``delimiter=','``, + and ``header=''``. + + Example:: + + # col1 col2 col3 + # Comment line + 1 2 3 + 4 5 6 + + """ + _format_name = ... + _description = ... + header_class = CommentedHeaderHeader + data_class = NoHeaderData + def read(self, table): # -> Table: + """ + Read input data (file-like object, filename, list of strings, or + single string) into a Table and return the result. + """ + ... + + def write_header(self, lines, meta): # -> None: + """ + Write comment lines after, rather than before, the header. + """ + ... + + + +class TabHeaderSplitter(core.DefaultSplitter): + """Split lines on tab and do not remove whitespace""" + delimiter = ... + def process_line(self, line): + ... + + + +class TabDataSplitter(TabHeaderSplitter): + """ + Don't strip data value whitespace since that is significant in TSV tables + """ + process_val = ... + skipinitialspace = ... + + +class TabHeader(BasicHeader): + """ + Reader for header of tables with tab separated header + """ + splitter_class = TabHeaderSplitter + + +class TabData(BasicData): + """ + Reader for data of tables with tab separated data + """ + splitter_class = TabDataSplitter + + +class Tab(Basic): + """Tab-separated table. + + Unlike the :class:`Basic` reader, whitespace is not stripped from the + beginning and end of either lines or individual column values. + + Example:: + + col1 col2 col3 + # Comment line + 1 2 5 + + """ + _format_name = ... + _description = ... + header_class = TabHeader + data_class = TabData + + +class CsvSplitter(core.DefaultSplitter): + """ + Split on comma for CSV (comma-separated-value) tables + """ + delimiter = ... + + +class CsvHeader(BasicHeader): + """ + Header that uses the :class:`astropy.io.ascii.basic.CsvSplitter` + """ + splitter_class = CsvSplitter + comment = ... + write_comment = ... + + +class CsvData(BasicData): + """ + Data that uses the :class:`astropy.io.ascii.basic.CsvSplitter` + """ + splitter_class = CsvSplitter + fill_values = ... + comment = ... + write_comment = ... + + +class Csv(Basic): + """CSV (comma-separated-values) table. + + This file format may contain rows with fewer entries than the number of + columns, a situation that occurs in output from some spreadsheet editors. + The missing entries are marked as masked in the output table. + + Masked values (indicated by an empty '' field value when reading) are + written out in the same way with an empty ('') field. This is different + from the typical default for `astropy.io.ascii` in which missing values are + indicated by ``--``. + + Since the `CSV format `_ does not + formally support comments, any comments defined for the table via + ``tbl.meta['comments']`` are ignored by default. If you would still like to + write those comments then include a keyword ``comment='#'`` to the + ``write()`` call. + + Example:: + + num,ra,dec,radius,mag + 1,32.23222,10.1211 + 2,38.12321,-88.1321,2.2,17.0 + + """ + _format_name = ... + _io_registry_format_aliases = ... + _io_registry_can_write = ... + _io_registry_suffix = ... + _description = ... + header_class = CsvHeader + data_class = CsvData + def inconsistent_handler(self, str_vals, ncols): + """ + Adjust row if it is too short. + + If a data row is shorter than the header, add empty values to make it the + right length. + Note that this will *not* be called if the row already matches the header. + + Parameters + ---------- + str_vals : list + A list of value strings from the current row of the table. + ncols : int + The expected number of entries from the table header. + + Returns + ------- + str_vals : list + List of strings to be parsed into data entries in the output table. + """ + ... + + + +class RdbHeader(TabHeader): + """ + Header for RDB tables + """ + col_type_map = ... + def get_type_map_key(self, col): + ... + + def get_cols(self, lines): # -> None: + """ + Initialize the header Column objects from the table ``lines``. + + This is a specialized get_cols for the RDB type: + Line 0: RDB col names + Line 1: RDB col definitions + Line 2+: RDB data rows + + Parameters + ---------- + lines : list + List of table lines + + Returns + ------- + None + + """ + ... + + def write(self, lines): # -> None: + ... + + + +class RdbData(TabData): + """ + Data reader for RDB data. Starts reading at line 2. + """ + start_line = ... + + +class Rdb(Tab): + """Tab-separated file with an extra line after the column definition line that + specifies either numeric (N) or string (S) data. + + See: https://www.drdobbs.com/rdb-a-unix-command-line-database/199101326 + + Example:: + + col1 col2 col3 + N S N + 1 2 5 + + """ + _format_name = ... + _io_registry_format_aliases = ... + _io_registry_suffix = ... + _description = ... + header_class = RdbHeader + data_class = RdbData + + diff --git a/typings/astropy/io/ascii/cds.pyi b/typings/astropy/io/ascii/cds.pyi new file mode 100644 index 0000000..7841c85 --- /dev/null +++ b/typings/astropy/io/ascii/cds.pyi @@ -0,0 +1,171 @@ +""" +This type stub file was generated by pyright. +""" + +from . import core, fixedwidth + +"""An extensible ASCII table reader and writer. + +cds.py: + Classes to read CDS / Vizier table format + +:Copyright: Smithsonian Astrophysical Observatory (2011) +:Author: Tom Aldcroft (aldcroft@head.cfa.harvard.edu) +""" +__doctest_skip__ = ... +class CdsHeader(core.BaseHeader): + _subfmt = ... + col_type_map = ... + readme = ... + def get_type_map_key(self, col): # -> str | Any: + ... + + def get_cols(self, lines): # -> None: + """ + Initialize the header Column objects from the table ``lines`` for a CDS/MRT + header. + + Parameters + ---------- + lines : list + List of table lines + + """ + ... + + + +class CdsData(core.BaseData): + """CDS table data reader + """ + _subfmt = ... + splitter_class = fixedwidth.FixedWidthSplitter + def process_lines(self, lines): + """Skip over CDS/MRT header by finding the last section delimiter""" + ... + + + +class Cds(core.BaseReader): + """CDS format table. + + See: http://vizier.u-strasbg.fr/doc/catstd.htx + + Example:: + + Table: Table name here + = ============================================================================== + Catalog reference paper + Bibliography info here + ================================================================================ + ADC_Keywords: Keyword ; Another keyword ; etc + + Description: + Catalog description here. + ================================================================================ + Byte-by-byte Description of file: datafile3.txt + -------------------------------------------------------------------------------- + Bytes Format Units Label Explanations + -------------------------------------------------------------------------------- + 1- 3 I3 --- Index Running identification number + 5- 6 I2 h RAh Hour of Right Ascension (J2000) + 8- 9 I2 min RAm Minute of Right Ascension (J2000) + 11- 15 F5.2 s RAs Second of Right Ascension (J2000) + -------------------------------------------------------------------------------- + Note (1): A CDS file can contain sections with various metadata. + Notes can be multiple lines. + Note (2): Another note. + -------------------------------------------------------------------------------- + 1 03 28 39.09 + 2 04 18 24.11 + + **About parsing the CDS format** + + The CDS format consists of a table description and the table data. These + can be in separate files as a ``ReadMe`` file plus data file(s), or + combined in a single file. Different subsections within the description + are separated by lines of dashes or equal signs ("------" or "======"). + The table which specifies the column information must be preceded by a line + starting with "Byte-by-byte Description of file:". + + In the case where the table description is combined with the data values, + the data must be in the last section and must be preceded by a section + delimiter line (dashes or equal signs only). + + **Basic usage** + + Use the ``ascii.read()`` function as normal, with an optional ``readme`` + parameter indicating the CDS ReadMe file. If not supplied it is assumed that + the header information is at the top of the given table. Examples:: + + >>> from astropy.io import ascii + >>> table = ascii.read("data/cds.dat") + >>> table = ascii.read("data/vizier/table1.dat", readme="data/vizier/ReadMe") + >>> table = ascii.read("data/cds/multi/lhs2065.dat", readme="data/cds/multi/ReadMe") + >>> table = ascii.read("data/cds/glob/lmxbrefs.dat", readme="data/cds/glob/ReadMe") + + The table name and the CDS ReadMe file can be entered as URLs. This can be used + to directly load tables from the Internet. For example, Vizier tables from the + CDS:: + + >>> table = ascii.read("ftp://cdsarc.u-strasbg.fr/pub/cats/VII/253/snrs.dat", + ... readme="ftp://cdsarc.u-strasbg.fr/pub/cats/VII/253/ReadMe") + + If the header (ReadMe) and data are stored in a single file and there + is content between the header and the data (for instance Notes), then the + parsing process may fail. In this case you can instruct the reader to + guess the actual start of the data by supplying ``data_start='guess'`` in the + call to the ``ascii.read()`` function. You should verify that the output + data table matches expectation based on the input CDS file. + + **Using a reader object** + + When ``Cds`` reader object is created with a ``readme`` parameter + passed to it at initialization, then when the ``read`` method is + executed with a table filename, the header information for the + specified table is taken from the ``readme`` file. An + ``InconsistentTableError`` is raised if the ``readme`` file does not + have header information for the given table. + + >>> readme = "data/vizier/ReadMe" + >>> r = ascii.get_reader(ascii.Cds, readme=readme) + >>> table = r.read("data/vizier/table1.dat") + >>> # table5.dat has the same ReadMe file + >>> table = r.read("data/vizier/table5.dat") + + If no ``readme`` parameter is specified, then the header + information is assumed to be at the top of the given table. + + >>> r = ascii.get_reader(ascii.Cds) + >>> table = r.read("data/cds.dat") + >>> #The following gives InconsistentTableError, since no + >>> #readme file was given and table1.dat does not have a header. + >>> table = r.read("data/vizier/table1.dat") + Traceback (most recent call last): + ... + InconsistentTableError: No CDS section delimiter found + + Caveats: + + * The Units and Explanations are available in the column ``unit`` and + ``description`` attributes, respectively. + * The other metadata defined by this format is not available in the output table. + """ + _format_name = ... + _io_registry_format_aliases = ... + _io_registry_can_write = ... + _description = ... + data_class = CdsData + header_class = CdsHeader + def __init__(self, readme=...) -> None: + ... + + def write(self, table=...): + """Not available for the CDS class (raises NotImplementedError)""" + ... + + def read(self, table): # -> Table | None: + ... + + + diff --git a/typings/astropy/io/ascii/connect.pyi b/typings/astropy/io/ascii/connect.pyi new file mode 100644 index 0000000..dc56112 --- /dev/null +++ b/typings/astropy/io/ascii/connect.pyi @@ -0,0 +1,14 @@ +""" +This type stub file was generated by pyright. +""" + +__all__ = [] +def io_read(format, filename, **kwargs): + ... + +def io_write(format, table, filename, **kwargs): # -> None: + ... + +def io_identify(suffix, origin, filepath, fileobj, *args, **kwargs): # -> Literal[False]: + ... + diff --git a/typings/astropy/io/ascii/core.pyi b/typings/astropy/io/ascii/core.pyi new file mode 100644 index 0000000..70cbf33 --- /dev/null +++ b/typings/astropy/io/ascii/core.pyi @@ -0,0 +1,716 @@ +""" +This type stub file was generated by pyright. +""" + +import numpy + +""" An extensible ASCII table reader and writer. + +core.py: + Core base classes and functions for reading and writing tables. + +:Copyright: Smithsonian Astrophysical Observatory (2010) +:Author: Tom Aldcroft (aldcroft@head.cfa.harvard.edu) +""" +FORMAT_CLASSES = ... +FAST_CLASSES = ... +class CsvWriter: + """ + Internal class to replace the csv writer ``writerow`` and ``writerows`` + functions so that in the case of ``delimiter=' '`` and + ``quoting=csv.QUOTE_MINIMAL``, the output field value is quoted for empty + fields (when value == ''). + + This changes the API slightly in that the writerow() and writerows() + methods return the output written string instead of the length of + that string. + + Examples + -------- + + >>> from astropy.io.ascii.core import CsvWriter + >>> writer = CsvWriter(delimiter=' ') + >>> print(writer.writerow(['hello', '', 'world'])) + hello "" world + """ + replace_sentinel = ... + def __init__(self, csvfile=..., **kwargs) -> None: + ... + + def writerow(self, values): # -> str: + """ + Similar to csv.writer.writerow but with the custom quoting behavior. + Returns the written string instead of the length of that string. + """ + ... + + def writerows(self, values_list): # -> str: + """ + Similar to csv.writer.writerows but with the custom quoting behavior. + Returns the written string instead of the length of that string. + """ + ... + + + +class MaskedConstant(numpy.ma.core.MaskedConstant): + """A trivial extension of numpy.ma.masked + + We want to be able to put the generic term ``masked`` into a dictionary. + The constant ``numpy.ma.masked`` is not hashable (see + https://github.com/numpy/numpy/issues/4660), so we need to extend it + here with a hash value. + + See https://github.com/numpy/numpy/issues/11021 for rationale for + __copy__ and __deepcopy__ methods. + """ + def __hash__(self) -> int: + '''All instances of this class shall have the same hash.''' + ... + + def __copy__(self): # -> Self@MaskedConstant: + """This is a singleton so just return self.""" + ... + + def __deepcopy__(self, memo): # -> Self@MaskedConstant: + ... + + + +masked = ... +class InconsistentTableError(ValueError): + """ + Indicates that an input table is inconsistent in some way. + + The default behavior of ``BaseReader`` is to throw an instance of + this class if a data row doesn't match the header. + """ + ... + + +class OptionalTableImportError(ImportError): + """ + Indicates that a dependency for table reading is not present. + + An instance of this class is raised whenever an optional reader + with certain required dependencies cannot operate because of + an ImportError. + """ + ... + + +class ParameterError(NotImplementedError): + """ + Indicates that a reader cannot handle a passed parameter. + + The C-based fast readers in ``io.ascii`` raise an instance of + this error class upon encountering a parameter that the + C engine cannot handle. + """ + ... + + +class FastOptionsError(NotImplementedError): + """ + Indicates that one of the specified options for fast + reading is invalid. + """ + ... + + +class NoType: + """ + Superclass for ``StrType`` and ``NumType`` classes. + + This class is the default type of ``Column`` and provides a base + class for other data types. + """ + ... + + +class StrType(NoType): + """ + Indicates that a column consists of text data. + """ + ... + + +class NumType(NoType): + """ + Indicates that a column consists of numerical data. + """ + ... + + +class FloatType(NumType): + """ + Describes floating-point data. + """ + ... + + +class BoolType(NoType): + """ + Describes boolean data. + """ + ... + + +class IntType(NumType): + """ + Describes integer data. + """ + ... + + +class AllType(StrType, FloatType, IntType): + """ + Subclass of all other data types. + + This type is returned by ``convert_numpy`` if the given numpy + type does not match ``StrType``, ``FloatType``, or ``IntType``. + """ + ... + + +class Column: + """Table column. + + The key attributes of a Column object are: + + * **name** : column name + * **type** : column type (NoType, StrType, NumType, FloatType, IntType) + * **dtype** : numpy dtype (optional, overrides **type** if set) + * **str_vals** : list of column values as strings + * **fill_values** : dict of fill values + * **shape** : list of element shape (default [] => scalar) + * **data** : list of converted column values + * **subtype** : actual datatype for columns serialized with JSON + """ + def __init__(self, name) -> None: + ... + + + +class BaseInputter: + """ + Get the lines from the table input and return a list of lines. + + """ + encoding = ... + def get_lines(self, table, newline=...): + """ + Get the lines from the ``table`` input. The input table can be one of: + + * File name + * String (newline separated) with all header and data lines (must have at least 2 lines) + * File-like object with read() method + * List of strings + + Parameters + ---------- + table : str, file-like, list + Can be either a file name, string (newline separated) with all header and data + lines (must have at least 2 lines), a file-like object with a + ``read()`` method, or a list of strings. + newline : + Line separator. If `None` use OS default from ``splitlines()``. + + Returns + ------- + lines : list + List of lines + """ + ... + + def process_lines(self, lines): + """Process lines for subsequent use. In the default case do nothing. + This routine is not generally intended for removing comment lines or + stripping whitespace. These are done (if needed) in the header and + data line processing. + + Override this method if something more has to be done to convert raw + input lines to the table rows. For example the + ContinuationLinesInputter derived class accounts for continuation + characters if a row is split into lines.""" + ... + + + +class BaseSplitter: + """ + Base splitter that uses python's split method to do the work. + + This does not handle quoted values. A key feature is the formulation of + __call__ as a generator that returns a list of the split line values at + each iteration. + + There are two methods that are intended to be overridden, first + ``process_line()`` to do pre-processing on each input line before splitting + and ``process_val()`` to do post-processing on each split string value. By + default these apply the string ``strip()`` function. These can be set to + another function via the instance attribute or be disabled entirely, for + example:: + + reader.header.splitter.process_val = lambda x: x.lstrip() + reader.data.splitter.process_val = None + + """ + delimiter = ... + def process_line(self, line): + """Remove whitespace at the beginning or end of line. This is especially useful for + whitespace-delimited files to prevent spurious columns at the beginning or end.""" + ... + + def process_val(self, val): + """Remove whitespace at the beginning or end of value.""" + ... + + def __call__(self, lines): # -> Generator[list[Unknown] | Unknown, None, None]: + ... + + def join(self, vals): # -> str: + ... + + + +class DefaultSplitter(BaseSplitter): + """Default class to split strings into columns using python csv. The class + attributes are taken from the csv Dialect class. + + Typical usage:: + + # lines = .. + splitter = ascii.DefaultSplitter() + for col_vals in splitter(lines): + for col_val in col_vals: + ... + + """ + delimiter = ... + quotechar = ... + doublequote = ... + escapechar = ... + quoting = ... + skipinitialspace = ... + csv_writer = ... + csv_writer_out = ... + def process_line(self, line): # -> LiteralString: + """Remove whitespace at the beginning or end of line. This is especially useful for + whitespace-delimited files to prevent spurious columns at the beginning or end. + If splitting on whitespace then replace unquoted tabs with space first""" + ... + + def process_val(self, val): + """Remove whitespace at the beginning or end of value.""" + ... + + def __call__(self, lines): # -> Generator[list[str], None, None]: + """Return an iterator over the table ``lines``, where each iterator output + is a list of the split line values. + + Parameters + ---------- + lines : list + List of table lines + + Yields + ------ + line : list of str + Each line's split values. + + """ + ... + + def join(self, vals): # -> str: + ... + + + +class BaseHeader: + """ + Base table header reader + """ + auto_format = ... + start_line = ... + comment = ... + splitter_class = DefaultSplitter + names = ... + write_comment = ... + write_spacer_lines = ... + def __init__(self) -> None: + ... + + def update_meta(self, lines, meta): # -> None: + """ + Extract any table-level metadata, e.g. keywords, comments, column metadata, from + the table ``lines`` and update the OrderedDict ``meta`` in place. This base + method extracts comment lines and stores them in ``meta`` for output. + """ + ... + + def get_cols(self, lines): # -> None: + """Initialize the header Column objects from the table ``lines``. + + Based on the previously set Header attributes find or create the column names. + Sets ``self.cols`` with the list of Columns. + + Parameters + ---------- + lines : list + List of table lines + + """ + ... + + def process_lines(self, lines): # -> Generator[Unknown, None, None]: + """Generator to yield non-blank and non-comment lines""" + ... + + def write_comments(self, lines, meta): # -> None: + ... + + def write(self, lines): # -> None: + ... + + @property + def colnames(self): # -> tuple[str, ...]: + """Return the column names of the table""" + ... + + def remove_columns(self, names): # -> None: + """ + Remove several columns from the table. + + Parameters + ---------- + names : list + A list containing the names of the columns to remove + """ + ... + + def rename_column(self, name, new_name): # -> None: + """ + Rename a column. + + Parameters + ---------- + name : str + The current name of the column. + new_name : str + The new name for the column + """ + ... + + def get_type_map_key(self, col): + ... + + def get_col_type(self, col): + ... + + def check_column_names(self, names, strict_names, guessing): # -> None: + """ + Check column names. + + This must be done before applying the names transformation + so that guessing will fail appropriately if ``names`` is supplied. + For instance if the basic reader is given a table with no column header + row. + + Parameters + ---------- + names : list + User-supplied list of column names + strict_names : bool + Whether to impose extra requirements on names + guessing : bool + True if this method is being called while guessing the table format + """ + ... + + + +class BaseData: + """ + Base table data reader. + """ + start_line = ... + end_line = ... + comment = ... + splitter_class = DefaultSplitter + write_spacer_lines = ... + fill_include_names = ... + fill_exclude_names = ... + fill_values = ... + formats = ... + def __init__(self) -> None: + ... + + def process_lines(self, lines): # -> list[Unknown]: + """ + READ: Strip out comment lines and blank lines from list of ``lines`` + + Parameters + ---------- + lines : list + All lines in table + + Returns + ------- + lines : list + List of lines + + """ + ... + + def get_data_lines(self, lines): # -> None: + """READ: Set ``data_lines`` attribute to lines slice comprising table data values. + """ + ... + + def get_str_vals(self): # -> Generator[list[str], None, None]: + """Return a generator that returns a list of column values (as strings) + for each data line.""" + ... + + def masks(self, cols): # -> None: + """READ: Set fill value for each column and then apply that fill value + + In the first step it is evaluated with value from ``fill_values`` applies to + which column using ``fill_include_names`` and ``fill_exclude_names``. + In the second step all replacements are done for the appropriate columns. + """ + ... + + def str_vals(self): # -> list[Unknown]: + """WRITE: convert all values in table to a list of lists of strings + + This sets the fill values and possibly column formats from the input + formats={} keyword, then ends up calling table.pprint._pformat_col_iter() + by a circuitous path. That function does the real work of formatting. + Finally replace anything matching the fill_values. + + Returns + ------- + values : list of list of str + """ + ... + + def write(self, lines): # -> None: + """Write ``self.cols`` in place to ``lines``. + + Parameters + ---------- + lines : list + List for collecting output of writing self.cols. + """ + ... + + + +def convert_numpy(numpy_type): # -> tuple[(vals: Unknown) -> (NDArray[Any] | Any), Type[IntType] | Type[FloatType] | Type[BoolType] | Type[StrType] | Type[AllType]]: + """Return a tuple containing a function which converts a list into a numpy + array and the type produced by the converter function. + + Parameters + ---------- + numpy_type : numpy data-type + The numpy type required of an array returned by ``converter``. Must be a + valid `numpy type `_ + (e.g., numpy.uint, numpy.int8, numpy.int64, numpy.float64) or a python + type covered by a numpy type (e.g., int, float, str, bool). + + Returns + ------- + converter : callable + ``converter`` is a function which accepts a list and converts it to a + numpy array of type ``numpy_type``. + converter_type : type + ``converter_type`` tracks the generic data type produced by the + converter function. + + Raises + ------ + ValueError + Raised by ``converter`` if the list elements could not be converted to + the required type. + """ + ... + +class BaseOutputter: + """Output table as a dict of column objects keyed on column name. The + table data are stored as plain python lists within the column objects. + """ + converters = ... + + +class TableOutputter(BaseOutputter): + """ + Output the table as an astropy.table.Table object. + """ + default_converters = ... + def __call__(self, cols, meta): # -> Table: + ... + + + +class MetaBaseReader(type): + def __init__(cls, name, bases, dct) -> None: + ... + + + +class BaseReader(metaclass=MetaBaseReader): + """Class providing methods to read and write an ASCII table using the specified + header, data, inputter, and outputter instances. + + Typical usage is to instantiate a Reader() object and customize the + ``header``, ``data``, ``inputter``, and ``outputter`` attributes. Each + of these is an object of the corresponding class. + + There is one method ``inconsistent_handler`` that can be used to customize the + behavior of ``read()`` in the event that a data row doesn't match the header. + The default behavior is to raise an InconsistentTableError. + + """ + names = ... + include_names = ... + exclude_names = ... + strict_names = ... + guessing = ... + encoding = ... + header_class = BaseHeader + data_class = BaseData + inputter_class = BaseInputter + outputter_class = TableOutputter + max_ndim = ... + def __init__(self) -> None: + ... + + def read(self, table): # -> Table: + """Read the ``table`` and return the results in a format determined by + the ``outputter`` attribute. + + The ``table`` parameter is any string or object that can be processed + by the instance ``inputter``. For the base Inputter class ``table`` can be + one of: + + * File name + * File-like object + * String (newline separated) with all header and data lines (must have at least 2 lines) + * List of strings + + Parameters + ---------- + table : str, file-like, list + Input table. + + Returns + ------- + table : `~astropy.table.Table` + Output table + + """ + ... + + def inconsistent_handler(self, str_vals, ncols): + """ + Adjust or skip data entries if a row is inconsistent with the header. + + The default implementation does no adjustment, and hence will always trigger + an exception in read() any time the number of data entries does not match + the header. + + Note that this will *not* be called if the row already matches the header. + + Parameters + ---------- + str_vals : list + A list of value strings from the current row of the table. + ncols : int + The expected number of entries from the table header. + + Returns + ------- + str_vals : list + List of strings to be parsed into data entries in the output table. If + the length of this list does not match ``ncols``, an exception will be + raised in read(). Can also be None, in which case the row will be + skipped. + """ + ... + + @property + def comment_lines(self): # -> list[Unknown]: + """Return lines in the table that match header.comment regexp""" + ... + + def update_table_data(self, table): + """ + Update table columns in place if needed. + + This is a hook to allow updating the table columns after name + filtering but before setting up to write the data. This is currently + only used by ECSV and is otherwise just a pass-through. + + Parameters + ---------- + table : `astropy.table.Table` + Input table for writing + + Returns + ------- + table : `astropy.table.Table` + Output table for writing + """ + ... + + def write_header(self, lines, meta): # -> None: + ... + + def write(self, table): # -> list[Unknown]: + """ + Write ``table`` as list of strings. + + Parameters + ---------- + table : `~astropy.table.Table` + Input table data. + + Returns + ------- + lines : list + List of strings corresponding to ASCII table + + """ + ... + + + +class ContinuationLinesInputter(BaseInputter): + """Inputter where lines ending in ``continuation_char`` are joined + with the subsequent line. Example:: + + col1 col2 col3 + 1 \ + 2 3 + 4 5 \ + 6 + """ + continuation_char = ... + replace_char = ... + no_continue = ... + def process_lines(self, lines): # -> list[Unknown]: + ... + + + +class WhitespaceSplitter(DefaultSplitter): + def process_line(self, line): # -> LiteralString: + """Replace tab with space within ``line`` while respecting quoted substrings""" + ... + + + +extra_reader_pars = ... +extra_writer_pars = ... diff --git a/typings/astropy/io/ascii/daophot.pyi b/typings/astropy/io/ascii/daophot.pyi new file mode 100644 index 0000000..d331c7b --- /dev/null +++ b/typings/astropy/io/ascii/daophot.pyi @@ -0,0 +1,177 @@ +""" +This type stub file was generated by pyright. +""" + +from . import core, fixedwidth + +""" +An extensible ASCII table reader and writer. + +Classes to read DAOphot table format + +:Copyright: Smithsonian Astrophysical Observatory (2011) +:Author: Tom Aldcroft (aldcroft@head.cfa.harvard.edu) +""" +class DaophotHeader(core.BaseHeader): + """ + Read the header from a file produced by the IRAF DAOphot routine. + """ + comment = ... + re_format = ... + re_header_keyword = ... + aperture_values = ... + def __init__(self) -> None: + ... + + def parse_col_defs(self, grouped_lines_dict): # -> dict[Unknown, list[Unknown]]: + """ + Parse a series of column definition lines like below. There may be several + such blocks in a single file (where continuation characters have already been + stripped). + #N ID XCENTER YCENTER MAG MERR MSKY NITER + #U ## pixels pixels magnitudes magnitudes counts ## + #F %-9d %-10.3f %-10.3f %-12.3f %-14.3f %-15.7g %-6d + """ + ... + + def update_meta(self, lines, meta): # -> None: + """ + Extract table-level keywords for DAOphot table. These are indicated by + a leading '#K ' prefix. + """ + ... + + def extract_keyword_line(self, line): # -> tuple[str | Any, dict[str, str | Any]] | None: + """ + Extract info from a header keyword line (#K) + """ + ... + + def get_cols(self, lines): # -> None: + """ + Initialize the header Column objects from the table ``lines`` for a DAOphot + header. The DAOphot header is specialized so that we just copy the entire BaseHeader + get_cols routine and modify as needed. + + Parameters + ---------- + lines : list + List of table lines + + Returns + ------- + col : list + List of table Columns + """ + ... + + + +class DaophotData(core.BaseData): + splitter_class = fixedwidth.FixedWidthSplitter + start_line = ... + comment = ... + def __init__(self) -> None: + ... + + def get_data_lines(self, lines): # -> None: + ... + + + +class DaophotInputter(core.ContinuationLinesInputter): + continuation_char = ... + multiline_char = ... + replace_char = ... + re_multiline = ... + def search_multiline(self, lines, depth=...): # -> tuple[None, None, Unknown] | tuple[Unknown, Unknown, Unknown]: + """ + Search lines for special continuation character to determine number of + continued rows in a datablock. For efficiency, depth gives the upper + limit of lines to search. + """ + ... + + def process_lines(self, lines): # -> list[Unknown]: + ... + + + +class Daophot(core.BaseReader): + """ + DAOphot format table. + + Example:: + + #K MERGERAD = INDEF scaleunit %-23.7g + #K IRAF = NOAO/IRAFV2.10EXPORT version %-23s + #K USER = davis name %-23s + #K HOST = tucana computer %-23s + # + #N ID XCENTER YCENTER MAG MERR MSKY NITER \\ + #U ## pixels pixels magnitudes magnitudes counts ## \\ + #F %-9d %-10.3f %-10.3f %-12.3f %-14.3f %-15.7g %-6d + # + #N SHARPNESS CHI PIER PERROR \\ + #U ## ## ## perrors \\ + #F %-23.3f %-12.3f %-6d %-13s + # + 14 138.538 INDEF 15.461 0.003 34.85955 4 \\ + -0.032 0.802 0 No_error + + The keywords defined in the #K records are available via the output table + ``meta`` attribute:: + + >>> import os + >>> from astropy.io import ascii + >>> filename = os.path.join(ascii.__path__[0], 'tests/data/daophot.dat') + >>> data = ascii.read(filename) + >>> for name, keyword in data.meta['keywords'].items(): + ... print(name, keyword['value'], keyword['units'], keyword['format']) + ... + MERGERAD INDEF scaleunit %-23.7g + IRAF NOAO/IRAFV2.10EXPORT version %-23s + USER name %-23s + ... + + The unit and formats are available in the output table columns:: + + >>> for colname in data.colnames: + ... col = data[colname] + ... print(colname, col.unit, col.format) + ... + ID None %-9d + XCENTER pixels %-10.3f + YCENTER pixels %-10.3f + ... + + Any column values of INDEF are interpreted as a missing value and will be + masked out in the resultant table. + + In case of multi-aperture daophot files containing repeated entries for the last + row of fields, extra unique column names will be created by suffixing + corresponding field names with numbers starting from 2 to N (where N is the + total number of apertures). + For example, + first aperture radius will be RAPERT and corresponding magnitude will be MAG, + second aperture radius will be RAPERT2 and corresponding magnitude will be MAG2, + third aperture radius will be RAPERT3 and corresponding magnitude will be MAG3, + and so on. + + """ + _format_name = ... + _io_registry_format_aliases = ... + _io_registry_can_write = ... + _description = ... + header_class = DaophotHeader + data_class = DaophotData + inputter_class = DaophotInputter + table_width = ... + def __init__(self) -> None: + ... + + def write(self, table=...): + ... + + + diff --git a/typings/astropy/io/ascii/docs.pyi b/typings/astropy/io/ascii/docs.pyi new file mode 100644 index 0000000..0bed2c2 --- /dev/null +++ b/typings/astropy/io/ascii/docs.pyi @@ -0,0 +1,8 @@ +""" +This type stub file was generated by pyright. +""" + +READ_DOCSTRING = ... +READ_KWARG_TYPES = ... +WRITE_DOCSTRING = ... +WRITE_KWARG_TYPES = ... diff --git a/typings/astropy/io/ascii/ecsv.pyi b/typings/astropy/io/ascii/ecsv.pyi new file mode 100644 index 0000000..dbdb1b5 --- /dev/null +++ b/typings/astropy/io/ascii/ecsv.pyi @@ -0,0 +1,166 @@ +""" +This type stub file was generated by pyright. +""" + +from . import basic, core +from astropy.utils.exceptions import AstropyUserWarning + +""" +Define the Enhanced Character-Separated-Values (ECSV) which allows for reading and +writing all the meta data associated with an astropy Table object. +""" +ECSV_VERSION = ... +DELIMITERS = ... +ECSV_DATATYPES = ... +class InvalidEcsvDatatypeWarning(AstropyUserWarning): + """ + ECSV specific Astropy warning class. + """ + ... + + +class EcsvHeader(basic.BasicHeader): + """Header class for which the column definition line starts with the + comment character. See the :class:`CommentedHeader` class for an example. + """ + def process_lines(self, lines): # -> Generator[Unknown, None, None]: + """Return only non-blank lines that start with the comment regexp. For these + lines strip out the matching characters and leading/trailing whitespace.""" + ... + + def write(self, lines): # -> None: + """ + Write header information in the ECSV ASCII format. + + This function is called at the point when preprocessing has been done to + convert the input table columns to `self.cols` which is a list of + `astropy.io.ascii.core.Column` objects. In particular `col.str_vals` + is available for each column with the string representation of each + column item for output. + + This format starts with a delimiter separated list of the column names + in order to make this format readable by humans and simple csv-type + readers. It then encodes the full table meta and column attributes and + meta as YAML and pretty-prints this in the header. Finally the + delimited column names are repeated again, for humans and readers that + look for the *last* comment line as defining the column names. + """ + ... + + def write_comments(self, lines, meta): # -> None: + """ + WRITE: Override the default write_comments to do nothing since this is handled + in the custom write method. + """ + ... + + def update_meta(self, lines, meta): # -> None: + """ + READ: Override the default update_meta to do nothing. This process is done + in get_cols() for this reader. + """ + ... + + def get_cols(self, lines): # -> None: + """ + READ: Initialize the header Column objects from the table ``lines``. + + Parameters + ---------- + lines : list + List of table lines + + """ + ... + + + +class EcsvOutputter(core.TableOutputter): + """ + After reading the input lines and processing, convert the Reader columns + and metadata to an astropy.table.Table object. This overrides the default + converters to be an empty list because there is no "guessing" of the + conversion function. + """ + default_converters = ... + def __call__(self, cols, meta): # -> Table | QTable: + ... + + + +class EcsvData(basic.BasicData): + def str_vals(self): # -> list[Unknown]: + """WRITE: convert all values in table to a list of lists of strings + + This version considerably simplifies the base method: + - No need to set fill values and column formats + - No per-item formatting, just use repr() + - Use JSON for object-type or multidim values + - Only Column or MaskedColumn can end up as cols here. + - Only replace masked values with "", not the generalized filling + """ + ... + + + +class Ecsv(basic.Basic): + """ECSV (Enhanced Character Separated Values) format table. + + Th ECSV format allows for specification of key table and column meta-data, in + particular the data type and unit. + + See: https://github.com/astropy/astropy-APEs/blob/main/APE6.rst + + Examples + -------- + + >>> from astropy.table import Table + >>> ecsv_content = '''# %ECSV 0.9 + ... # --- + ... # datatype: + ... # - {name: a, unit: m / s, datatype: int64, format: '%03d'} + ... # - {name: b, unit: km, datatype: int64, description: This is column b} + ... a b + ... 001 2 + ... 004 3 + ... ''' + + >>> Table.read(ecsv_content, format='ascii.ecsv') +
+ a b + m / s km + int64 int64 + ----- ----- + 001 2 + 004 3 + + """ + _format_name = ... + _description = ... + _io_registry_suffix = ... + header_class = EcsvHeader + data_class = EcsvData + outputter_class = EcsvOutputter + max_ndim = ... + def update_table_data(self, table): # -> Table: + """ + Update table columns in place if mixin columns are present. + + This is a hook to allow updating the table columns after name + filtering but before setting up to write the data. This is currently + only used by ECSV and is otherwise just a pass-through. + + Parameters + ---------- + table : `astropy.table.Table` + Input table for writing + + Returns + ------- + table : `astropy.table.Table` + Output table for writing + """ + ... + + + diff --git a/typings/astropy/io/ascii/fastbasic.pyi b/typings/astropy/io/ascii/fastbasic.pyi new file mode 100644 index 0000000..219201c --- /dev/null +++ b/typings/astropy/io/ascii/fastbasic.pyi @@ -0,0 +1,153 @@ +""" +This type stub file was generated by pyright. +""" + +from . import core + +class FastBasic(metaclass=core.MetaBaseReader): + """ + This class is intended to handle the same format addressed by the + ordinary :class:`Basic` writer, but it acts as a wrapper for underlying C + code and is therefore much faster. Unlike the other ASCII readers and + writers, this class is not very extensible and is restricted + by optimization requirements. + """ + _format_name = ... + _description = ... + _fast = ... + fill_extra_cols = ... + guessing = ... + strict_names = ... + def __init__(self, default_kwargs=..., **user_kwargs) -> None: + ... + + def read(self, table): # -> Table: + """ + Read input data (file-like object, filename, list of strings, or + single string) into a Table and return the result. + """ + ... + + def make_table(self, data, comments): # -> Table: + """Actually make the output table give the data and comments.""" + ... + + def check_header(self): # -> None: + ... + + def write(self, table, output): # -> None: + """ + Use a fast Cython method to write table data to output, + where output is a filename or file-like object. + """ + ... + + + +class FastCsv(FastBasic): + """ + A faster version of the ordinary :class:`Csv` writer that uses the + optimized C parsing engine. Note that this reader will append empty + field values to the end of any row with not enough columns, while + :class:`FastBasic` simply raises an error. + """ + _format_name = ... + _description = ... + _fast = ... + fill_extra_cols = ... + def __init__(self, **kwargs) -> None: + ... + + def write(self, table, output): # -> None: + """ + Override the default write method of `FastBasic` to + output masked values as empty fields. + """ + ... + + + +class FastTab(FastBasic): + """ + A faster version of the ordinary :class:`Tab` reader that uses + the optimized C parsing engine. + """ + _format_name = ... + _description = ... + _fast = ... + def __init__(self, **kwargs) -> None: + ... + + + +class FastNoHeader(FastBasic): + """ + This class uses the fast C engine to read tables with no header line. If + the names parameter is unspecified, the columns will be autonamed with + "col{}". + """ + _format_name = ... + _description = ... + _fast = ... + def __init__(self, **kwargs) -> None: + ... + + def write(self, table, output): # -> None: + """ + Override the default writing behavior in `FastBasic` so + that columns names are not included in output. + """ + ... + + + +class FastCommentedHeader(FastBasic): + """ + A faster version of the :class:`CommentedHeader` reader, which looks for + column names in a commented line. ``header_start`` denotes the index of + the header line among all commented lines and is 0 by default. + """ + _format_name = ... + _description = ... + _fast = ... + def __init__(self, **kwargs) -> None: + ... + + def make_table(self, data, comments): # -> Table: + """ + Actually make the output table give the data and comments. This is + slightly different from the base FastBasic method in the way comments + are handled. + """ + ... + + def write(self, table, output): # -> None: + """ + Override the default writing behavior in `FastBasic` so + that column names are commented. + """ + ... + + + +class FastRdb(FastBasic): + """ + A faster version of the :class:`Rdb` reader. This format is similar to + tab-delimited, but it also contains a header line after the column + name line denoting the type of each column (N for numeric, S for string). + """ + _format_name = ... + _description = ... + _fast = ... + def __init__(self, **kwargs) -> None: + ... + + def write(self, table, output): # -> None: + """ + Override the default writing behavior in `FastBasic` to + output a line with column types after the column name line. + """ + ... + + + diff --git a/typings/astropy/io/ascii/fixedwidth.pyi b/typings/astropy/io/ascii/fixedwidth.pyi new file mode 100644 index 0000000..86ff420 --- /dev/null +++ b/typings/astropy/io/ascii/fixedwidth.pyi @@ -0,0 +1,250 @@ +""" +This type stub file was generated by pyright. +""" + +from . import basic, core +from .core import DefaultSplitter + +"""An extensible ASCII table reader and writer. + +fixedwidth.py: + Read or write a table with fixed width columns. + +:Copyright: Smithsonian Astrophysical Observatory (2011) +:Author: Tom Aldcroft (aldcroft@head.cfa.harvard.edu) +""" +class FixedWidthSplitter(core.BaseSplitter): + """ + Split line based on fixed start and end positions for each ``col`` in + ``self.cols``. + + This class requires that the Header class will have defined ``col.start`` + and ``col.end`` for each column. The reference to the ``header.cols`` gets + put in the splitter object by the base Reader.read() function just in time + for splitting data lines by a ``data`` object. + + Note that the ``start`` and ``end`` positions are defined in the pythonic + style so line[start:end] is the desired substring for a column. This splitter + class does not have a hook for ``process_lines`` since that is generally not + useful for fixed-width input. + + """ + delimiter_pad = ... + bookend = ... + delimiter = ... + def __call__(self, lines): # -> Generator[list[Unknown], None, None]: + ... + + def join(self, vals, widths): # -> str: + ... + + + +class FixedWidthHeaderSplitter(DefaultSplitter): + '''Splitter class that splits on ``|``.''' + delimiter = ... + + +class FixedWidthHeader(basic.BasicHeader): + """ + Fixed width table header reader. + """ + splitter_class = FixedWidthHeaderSplitter + position_line = ... + set_of_position_line_characters = ... + def get_line(self, lines, index): + ... + + def get_cols(self, lines): # -> None: + """ + Initialize the header Column objects from the table ``lines``. + + Based on the previously set Header attributes find or create the column names. + Sets ``self.cols`` with the list of Columns. + + Parameters + ---------- + lines : list + List of table lines + + """ + ... + + def get_fixedwidth_params(self, line): # -> tuple[list[Unknown], list[Unknown] | list[int], list[Unknown | None] | list[Unknown]]: + """ + Split ``line`` on the delimiter and determine column values and + column start and end positions. This might include null columns with + zero length (e.g. for ``header row = "| col1 || col2 | col3 |"`` or + ``header2_row = "----- ------- -----"``). The null columns are + stripped out. Returns the values between delimiters and the + corresponding start and end positions. + + Parameters + ---------- + line : str + Input line + + Returns + ------- + vals : list + List of values. + starts : list + List of starting indices. + ends : list + List of ending indices. + + """ + ... + + def write(self, lines): # -> None: + ... + + + +class FixedWidthData(basic.BasicData): + """ + Base table data reader. + """ + splitter_class = FixedWidthSplitter + def write(self, lines): + ... + + + +class FixedWidth(basic.Basic): + """Fixed width table with single header line defining column names and positions. + + Examples:: + + # Bar delimiter in header and data + + | Col1 | Col2 | Col3 | + | 1.2 | hello there | 3 | + | 2.4 | many words | 7 | + + # Bar delimiter in header only + + Col1 | Col2 | Col3 + 1.2 hello there 3 + 2.4 many words 7 + + # No delimiter with column positions specified as input + + Col1 Col2Col3 + 1.2hello there 3 + 2.4many words 7 + + See the :ref:`astropy:fixed_width_gallery` for specific usage examples. + + """ + _format_name = ... + _description = ... + header_class = FixedWidthHeader + data_class = FixedWidthData + def __init__(self, col_starts=..., col_ends=..., delimiter_pad=..., bookend=...) -> None: + ... + + + +class FixedWidthNoHeaderHeader(FixedWidthHeader): + '''Header reader for fixed with tables with no header line''' + start_line = ... + + +class FixedWidthNoHeaderData(FixedWidthData): + '''Data reader for fixed width tables with no header line''' + start_line = ... + + +class FixedWidthNoHeader(FixedWidth): + """Fixed width table which has no header line. + + When reading, column names are either input (``names`` keyword) or + auto-generated. Column positions are determined either by input + (``col_starts`` and ``col_stops`` keywords) or by splitting the first data + line. In the latter case a ``delimiter`` is required to split the data + line. + + Examples:: + + # Bar delimiter in header and data + + | 1.2 | hello there | 3 | + | 2.4 | many words | 7 | + + # Compact table having no delimiter and column positions specified as input + + 1.2hello there3 + 2.4many words 7 + + This class is just a convenience wrapper around the ``FixedWidth`` reader + but with ``header_start=None`` and ``data_start=0``. + + See the :ref:`astropy:fixed_width_gallery` for specific usage examples. + + """ + _format_name = ... + _description = ... + header_class = FixedWidthNoHeaderHeader + data_class = FixedWidthNoHeaderData + def __init__(self, col_starts=..., col_ends=..., delimiter_pad=..., bookend=...) -> None: + ... + + + +class FixedWidthTwoLineHeader(FixedWidthHeader): + '''Header reader for fixed width tables splitting on whitespace. + + For fixed width tables with several header lines, there is typically + a white-space delimited format line, so splitting on white space is + needed. + ''' + splitter_class = DefaultSplitter + + +class FixedWidthTwoLineDataSplitter(FixedWidthSplitter): + '''Splitter for fixed width tables splitting on ``' '``.''' + delimiter = ... + + +class FixedWidthTwoLineData(FixedWidthData): + '''Data reader for fixed with tables with two header lines.''' + splitter_class = FixedWidthTwoLineDataSplitter + + +class FixedWidthTwoLine(FixedWidth): + """Fixed width table which has two header lines. + + The first header line defines the column names and the second implicitly + defines the column positions. + + Examples:: + + # Typical case with column extent defined by ---- under column names. + + col1 col2 <== header_start = 0 + ----- ------------ <== position_line = 1, position_char = "-" + 1 bee flies <== data_start = 2 + 2 fish swims + + # Pretty-printed table + + +------+------------+ + | Col1 | Col2 | + +------+------------+ + | 1.2 | "hello" | + | 2.4 | there world| + +------+------------+ + + See the :ref:`astropy:fixed_width_gallery` for specific usage examples. + + """ + _format_name = ... + _description = ... + data_class = FixedWidthTwoLineData + header_class = FixedWidthTwoLineHeader + def __init__(self, position_line=..., position_char=..., delimiter_pad=..., bookend=...) -> None: + ... + + + diff --git a/typings/astropy/io/ascii/html.pyi b/typings/astropy/io/ascii/html.pyi new file mode 100644 index 0000000..43ad27b --- /dev/null +++ b/typings/astropy/io/ascii/html.pyi @@ -0,0 +1,206 @@ +""" +This type stub file was generated by pyright. +""" + +from . import core + +"""An extensible HTML table reader and writer. + +html.py: + Classes to read and write HTML tables + +`BeautifulSoup `_ +must be installed to read HTML tables. +""" +class SoupString(str): + """ + Allows for strings to hold BeautifulSoup data. + """ + def __new__(cls, *args, **kwargs): # -> Self@SoupString: + ... + + def __init__(self, val) -> None: + ... + + + +class ListWriter: + """ + Allows for XMLWriter to write to a list instead of a file. + """ + def __init__(self, out) -> None: + ... + + def write(self, data): # -> None: + ... + + + +def identify_table(soup, htmldict, numtable): # -> Literal[False]: + """ + Checks whether the given BeautifulSoup tag is the table + the user intends to process. + """ + ... + +class HTMLInputter(core.BaseInputter): + """ + Input lines of HTML in a valid form. + + This requires `BeautifulSoup + `_ to be installed. + """ + def process_lines(self, lines): # -> list[SoupString]: + """ + Convert the given input into a list of SoupString rows + for further processing. + """ + ... + + + +class HTMLSplitter(core.BaseSplitter): + """ + Split HTML table data. + """ + def __call__(self, lines): # -> Generator[list[tuple[Unknown, Unknown] | Unknown] | list[Unknown], None, None]: + """ + Return HTML data from lines as a generator. + """ + ... + + + +class HTMLOutputter(core.TableOutputter): + """ + Output the HTML data as an ``astropy.table.Table`` object. + + This subclass allows for the final table to contain + multidimensional columns (defined using the colspan attribute + of
). + """ + default_converters = ... + def __call__(self, cols, meta): # -> Table: + """ + Process the data in multidimensional columns. + """ + ... + + + +class HTMLHeader(core.BaseHeader): + splitter_class = HTMLSplitter + def start_line(self, lines): # -> int | None: + """ + Return the line number at which header data begins. + """ + ... + + + +class HTMLData(core.BaseData): + splitter_class = HTMLSplitter + def start_line(self, lines): # -> int: + """ + Return the line number at which table data begins. + """ + ... + + def end_line(self, lines): # -> int | None: + """ + Return the line number at which table data ends. + """ + ... + + + +class HTML(core.BaseReader): + """HTML format table. + + In order to customize input and output, a dict of parameters may + be passed to this class holding specific customizations. + + **htmldict** : Dictionary of parameters for HTML input/output. + + * css : Customized styling + If present, this parameter will be included in a