repo
string | instance_id
string | html_url
string | feature_patch
string | test_patch
string | doc_changes
list | version
string | base_commit
string | PASS2PASS
list | FAIL2PASS
list | mask_doc_diff
list | augmentations
dict | problem_statement
string |
---|---|---|---|---|---|---|---|---|---|---|---|---|
astropy/astropy
|
astropy__astropy-9288
|
https://github.com/astropy/astropy/pull/9288
|
diff --git a/CHANGES.rst b/CHANGES.rst
index 80b4e8d3406e..95d78702124c 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -129,9 +129,12 @@ astropy.table
- ``MaskedColumn.data`` will now return a plain ``MaskedArray`` rather than
the previous (unintended) ``masked_BaseColumn``. [#8855]
-- Adding depth-wise stacking ``cstack()`` in higher level table operation.
+- Added depth-wise stacking ``cstack()`` in higher level table operation.
It help will in stacking table column depth-wise. [#8939]
+- Added new ``join_type='cartesian'`` option to the ``join`` operation.
+ [#9288]
+
- Allow adding a table column as a list of mixin-type objects, for instance
``t['q'] = [1 * u.m, 2 * u.m]``. [#9165]
diff --git a/astropy/table/operations.py b/astropy/table/operations.py
index f6810b2dc8c8..46a84b1a764a 100644
--- a/astropy/table/operations.py
+++ b/astropy/table/operations.py
@@ -104,7 +104,7 @@ def join(left, right, keys=None, join_type='inner',
Name(s) of column(s) used to match rows of left and right tables.
Default is to use all columns which are common to both tables.
join_type : str
- Join type ('inner' | 'outer' | 'left' | 'right'), default is 'inner'
+ Join type ('inner' | 'outer' | 'left' | 'right' | 'cartesian'), default is 'inner'
uniq_col_name : str or None
String generate a unique output column name in case of a conflict.
The default is '{col_name}_{table_name}'.
@@ -777,7 +777,7 @@ def _join(left, right, keys=None, join_type='inner',
Name(s) of column(s) used to match rows of left and right tables.
Default is to use all columns which are common to both tables.
join_type : str
- Join type ('inner' | 'outer' | 'left' | 'right'), default is 'inner'
+ Join type ('inner' | 'outer' | 'left' | 'right' | 'cartesian'), default is 'inner'
uniq_col_name : str or None
String generate a unique output column name in case of a conflict.
The default is '{col_name}_{table_name}'.
@@ -801,11 +801,27 @@ def _join(left, right, keys=None, join_type='inner',
# Store user-provided col_name_map until the end
_col_name_map = col_name_map
- if join_type not in ('inner', 'outer', 'left', 'right'):
+ # Special column name for cartesian join, should never collide with real column
+ cartesian_index_name = '__table_cartesian_join_temp_index__'
+
+ if join_type not in ('inner', 'outer', 'left', 'right', 'cartesian'):
raise ValueError("The 'join_type' argument should be in 'inner', "
- "'outer', 'left' or 'right' (got '{}' instead)".
+ "'outer', 'left', 'right', or 'cartesian' "
+ "(got '{}' instead)".
format(join_type))
+ if join_type == 'cartesian':
+ if keys:
+ raise ValueError('cannot supply keys for a cartesian join')
+
+ # Make light copies of left and right, then add temporary index columns
+ # with all the same value so later an outer join turns into a cartesian join.
+ left = left.copy(copy_data=False)
+ right = right.copy(copy_data=False)
+ left[cartesian_index_name] = np.uint8(0)
+ right[cartesian_index_name] = np.uint8(0)
+ keys = (cartesian_index_name, )
+
# If we have a single key, put it in a tuple
if keys is None:
keys = tuple(name for name in left.colnames if name in right.colnames)
@@ -840,13 +856,16 @@ def _join(left, right, keys=None, join_type='inner',
# Main inner loop in Cython to compute the cartesian product
# indices for the given join type
- int_join_type = {'inner': 0, 'outer': 1, 'left': 2, 'right': 3}[join_type]
+ int_join_type = {'inner': 0, 'outer': 1, 'left': 2, 'right': 3,
+ 'cartesian': 1}[join_type]
masked, n_out, left_out, left_mask, right_out, right_mask = \
_np_utils.join_inner(idxs, idx_sort, len_left, int_join_type)
out = _get_out_class([left, right])()
for out_name, dtype, shape in out_descrs:
+ if out_name == cartesian_index_name:
+ continue
left_name, right_name = col_name_map[out_name]
if left_name and right_name: # this is a key which comes from left and right
diff --git a/docs/table/operations.rst b/docs/table/operations.rst
index fc40c8d63bb7..2c026fbd8a31 100644
--- a/docs/table/operations.rst
+++ b/docs/table/operations.rst
@@ -721,7 +721,7 @@ matching key includes both ``name`` and ``obs_date``. Specifying the key as onl
Likewise one can construct a new table with every row of the right table and matching left
values (when available) using ``join_type='right'``.
-Finally, to make a table with the union of rows from both tables do an "outer" join::
+To make a table with the union of rows from both tables do an "outer" join::
>>> print(join(optical, xray, join_type='outer'))
name obs_date mag_b mag_v logLx
@@ -732,9 +732,26 @@ Finally, to make a table with the union of rows from both tables do an "outer" j
M82 2012-10-29 16.2 15.2 45.0
NGC3516 2011-11-11 -- -- 42.1
-In all cases the output join table will be sorted by the key column(s) and in general
+In all the above cases the output join table will be sorted by the key column(s) and in general
will not preserve the row order of the input tables.
+Finally, one can do a "cartesian" join, which is the cartesian product of all available
+rows. In this case one there are no key columns (and supplying a ``keys`` argument is
+an error)::
+
+ >>> print(join(optical, xray, join_type='cartesian'))
+ name_1 obs_date_1 mag_b mag_v name_2 obs_date_2 logLx
+ ------ ---------- ----- ----- ------- ---------- -----
+ M31 2012-01-02 17.0 16.0 NGC3516 2011-11-11 42.1
+ M31 2012-01-02 17.0 16.0 M31 1999-01-05 43.1
+ M31 2012-01-02 17.0 16.0 M82 2012-10-29 45.0
+ M82 2012-10-29 16.2 15.2 NGC3516 2011-11-11 42.1
+ M82 2012-10-29 16.2 15.2 M31 1999-01-05 43.1
+ M82 2012-10-29 16.2 15.2 M82 2012-10-29 45.0
+ M101 2012-10-31 15.1 15.5 NGC3516 2011-11-11 42.1
+ M101 2012-10-31 15.1 15.5 M31 1999-01-05 43.1
+ M101 2012-10-31 15.1 15.5 M82 2012-10-29 45.0
+
Non-identical key column names
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
diff --git a/astropy/table/tests/test_operations.py b/astropy/table/tests/test_operations.py
index da5f9f1020be..6da2f2a8eff5 100644
--- a/astropy/table/tests/test_operations.py
+++ b/astropy/table/tests/test_operations.py
@@ -547,15 +547,36 @@ def test_mixin_functionality(self, mixin_cols):
assert ('join requires masking' in str(err.value) or
'join unavailable' in str(err.value))
+ def test_cartesian_join(self, operation_table_type):
+ t1 = Table(rows=[(1, 'a'),
+ (2, 'b')], names=['a', 'b'])
+ t2 = Table(rows=[(3, 'c'),
+ (4, 'd')], names=['a', 'c'])
+ t12 = table.join(t1, t2, join_type='cartesian')
+
+ assert t1.colnames == ['a', 'b']
+ assert t2.colnames == ['a', 'c']
+ assert len(t12) == len(t1) * len(t2)
+ assert str(t12).splitlines() == [
+ 'a_1 b a_2 c ',
+ '--- --- --- ---',
+ ' 1 a 3 c',
+ ' 1 a 4 d',
+ ' 2 b 3 c',
+ ' 2 b 4 d']
+
+ with pytest.raises(ValueError, match='cannot supply keys for a cartesian join'):
+ t12 = table.join(t1, t2, join_type='cartesian', keys='a')
+
class TestSetdiff():
def _setup(self, t_cls=Table):
lines1 = [' a b ',
- ' 0 foo ',
- ' 1 foo ',
- ' 1 bar ',
- ' 2 bar ']
+ ' 0 foo ',
+ ' 1 foo ',
+ ' 1 bar ',
+ ' 2 bar ']
lines2 = [' a b ',
' 0 foo ',
' 3 foo ',
|
[
{
"path": "docs/table/operations.rst",
"old_path": "a/docs/table/operations.rst",
"new_path": "b/docs/table/operations.rst",
"metadata": "diff --git a/docs/table/operations.rst b/docs/table/operations.rst\nindex fc40c8d63bb7..2c026fbd8a31 100644\n--- a/docs/table/operations.rst\n+++ b/docs/table/operations.rst\n@@ -721,7 +721,7 @@ matching key includes both ``name`` and ``obs_date``. Specifying the key as onl\n Likewise one can construct a new table with every row of the right table and matching left\n values (when available) using ``join_type='right'``.\n \n-Finally, to make a table with the union of rows from both tables do an \"outer\" join::\n+To make a table with the union of rows from both tables do an \"outer\" join::\n \n >>> print(join(optical, xray, join_type='outer'))\n name obs_date mag_b mag_v logLx\n@@ -732,9 +732,26 @@ Finally, to make a table with the union of rows from both tables do an \"outer\" j\n M82 2012-10-29 16.2 15.2 45.0\n NGC3516 2011-11-11 -- -- 42.1\n \n-In all cases the output join table will be sorted by the key column(s) and in general\n+In all the above cases the output join table will be sorted by the key column(s) and in general\n will not preserve the row order of the input tables.\n \n+Finally, one can do a \"cartesian\" join, which is the cartesian product of all available\n+rows. In this case one there are no key columns (and supplying a ``keys`` argument is\n+an error)::\n+\n+ >>> print(join(optical, xray, join_type='cartesian'))\n+ name_1 obs_date_1 mag_b mag_v name_2 obs_date_2 logLx\n+ ------ ---------- ----- ----- ------- ---------- -----\n+ M31 2012-01-02 17.0 16.0 NGC3516 2011-11-11 42.1\n+ M31 2012-01-02 17.0 16.0 M31 1999-01-05 43.1\n+ M31 2012-01-02 17.0 16.0 M82 2012-10-29 45.0\n+ M82 2012-10-29 16.2 15.2 NGC3516 2011-11-11 42.1\n+ M82 2012-10-29 16.2 15.2 M31 1999-01-05 43.1\n+ M82 2012-10-29 16.2 15.2 M82 2012-10-29 45.0\n+ M101 2012-10-31 15.1 15.5 NGC3516 2011-11-11 42.1\n+ M101 2012-10-31 15.1 15.5 M31 1999-01-05 43.1\n+ M101 2012-10-31 15.1 15.5 M82 2012-10-29 45.0\n+\n Non-identical key column names\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n \n",
"update": null
}
] |
4.0
|
b5da86a0fd5ceb785127f82078c6706a5feef157
|
[
"astropy/table/tests/test_operations.py::TestSetdiff::test_keys[QTable]",
"astropy/table/tests/test_operations.py::TestHStack::test_bad_input_type[QTable]",
"astropy/table/tests/test_operations.py::TestJoin::test_no_common_keys[Table]",
"astropy/table/tests/test_operations.py::TestHStack::test_stack_columns[QTable]",
"astropy/table/tests/test_operations.py::TestVStack::test_stack_basic_inner[Table]",
"astropy/table/tests/test_operations.py::TestSetdiff::test_default_same_columns[Table]",
"astropy/table/tests/test_operations.py::TestVStack::test_col_meta_merge_inner[Table]",
"astropy/table/tests/test_operations.py::TestHStack::test_mixin_functionality[time]",
"astropy/table/tests/test_operations.py::TestJoin::test_bad_join_type[Table]",
"astropy/table/tests/test_operations.py::TestVStack::test_vstack_one_table[Table]",
"astropy/table/tests/test_operations.py::TestJoin::test_both_unmasked_single_key_inner[Table]",
"astropy/table/tests/test_operations.py::TestJoin::test_col_rename[QTable]",
"astropy/table/tests/test_operations.py::TestHStack::test_stack_incompatible[Table]",
"astropy/table/tests/test_operations.py::TestJoin::test_rename_conflict[QTable]",
"astropy/table/tests/test_operations.py::TestJoin::test_table_meta_merge[QTable]",
"astropy/table/tests/test_operations.py::TestHStack::test_mixin_functionality[longitude]",
"astropy/table/tests/test_operations.py::TestHStack::test_mixin_functionality[quantity]",
"astropy/table/tests/test_operations.py::TestJoin::test_no_common_keys[QTable]",
"astropy/table/tests/test_operations.py::TestVStack::test_mixin_functionality[longitude]",
"astropy/table/tests/test_operations.py::test_stack_columns",
"astropy/table/tests/test_operations.py::TestSetdiff::test_missing_key[Table]",
"astropy/table/tests/test_operations.py::TestCStack::test_cstack_single_table",
"astropy/table/tests/test_operations.py::TestHStack::test_stack_basic[QTable]",
"astropy/table/tests/test_operations.py::TestCStack::test_cstack_basic_outer[Table]",
"astropy/table/tests/test_operations.py::TestHStack::test_mixin_functionality[latitude]",
"astropy/table/tests/test_operations.py::test_vstack_bytes[Table]",
"astropy/table/tests/test_operations.py::test_join_mixins_time_quantity",
"astropy/table/tests/test_operations.py::test_join_non_1d_key_column",
"astropy/table/tests/test_operations.py::TestJoin::test_classes",
"astropy/table/tests/test_operations.py::TestVStack::test_stack_basic_inner[QTable]",
"astropy/table/tests/test_operations.py::TestJoin::test_mixin_functionality[quantity]",
"astropy/table/tests/test_operations.py::TestSetdiff::test_missing_key[QTable]",
"astropy/table/tests/test_operations.py::TestJoin::test_rename_conflict[Table]",
"astropy/table/tests/test_operations.py::TestVStack::test_stack_basic_outer[Table]",
"astropy/table/tests/test_operations.py::TestVStack::test_bad_input_type[QTable]",
"astropy/table/tests/test_operations.py::TestJoin::test_both_unmasked_left_right_outer[Table]",
"astropy/table/tests/test_operations.py::TestHStack::test_mixin_functionality[skycoord]",
"astropy/table/tests/test_operations.py::test_masking_required_exception",
"astropy/table/tests/test_operations.py::TestHStack::test_table_meta_merge[QTable]",
"astropy/table/tests/test_operations.py::TestJoin::test_mixin_functionality[ndarray]",
"astropy/table/tests/test_operations.py::TestJoin::test_mixin_functionality[latitude]",
"astropy/table/tests/test_operations.py::TestJoin::test_col_rename[Table]",
"astropy/table/tests/test_operations.py::TestJoin::test_col_meta_merge[Table]",
"astropy/table/tests/test_operations.py::TestVStack::test_mixin_functionality[earthlocation]",
"astropy/table/tests/test_operations.py::TestVStack::test_col_meta_merge_outer[Table]",
"astropy/table/tests/test_operations.py::TestCStack::test_cstack_table_column[Table]",
"astropy/table/tests/test_operations.py::TestCStack::test_cstack_multi_dimension_column[Table]",
"astropy/table/tests/test_operations.py::TestJoin::test_masked_unmasked[Table]",
"astropy/table/tests/test_operations.py::TestCStack::test_cstack_different_length_table[Table]",
"astropy/table/tests/test_operations.py::TestHStack::test_stack_same_table[QTable]",
"astropy/table/tests/test_operations.py::TestHStack::test_mixin_functionality[arraywrap]",
"astropy/table/tests/test_operations.py::TestVStack::test_stack_incompatible[QTable]",
"astropy/table/tests/test_operations.py::TestHStack::test_hstack_one_masked[Table]",
"astropy/table/tests/test_operations.py::TestJoin::test_mixin_functionality[longitude]",
"astropy/table/tests/test_operations.py::TestVStack::test_table_meta_merge_conflict[QTable]",
"astropy/table/tests/test_operations.py::TestCStack::test_cstack_different_length_table[QTable]",
"astropy/table/tests/test_operations.py::test_unique[QTable]",
"astropy/table/tests/test_operations.py::TestJoin::test_masked_masked[Table]",
"astropy/table/tests/test_operations.py::TestJoin::test_missing_keys[QTable]",
"astropy/table/tests/test_operations.py::TestVStack::test_mixin_functionality[skycoord]",
"astropy/table/tests/test_operations.py::TestVStack::test_stack_incompatible[Table]",
"astropy/table/tests/test_operations.py::TestHStack::test_col_meta_merge[QTable]",
"astropy/table/tests/test_operations.py::TestSetdiff::test_extra_col_left_table[Table]",
"astropy/table/tests/test_operations.py::TestHStack::test_bad_input_type[Table]",
"astropy/table/tests/test_operations.py::test_mixin_join_regression",
"astropy/table/tests/test_operations.py::TestSetdiff::test_extra_col_right_table[QTable]",
"astropy/table/tests/test_operations.py::TestHStack::test_mixin_functionality[earthlocation]",
"astropy/table/tests/test_operations.py::TestCStack::test_cstack_basic_inner[Table]",
"astropy/table/tests/test_operations.py::TestJoin::test_mixin_functionality[skycoord]",
"astropy/table/tests/test_operations.py::TestJoin::test_both_unmasked_single_key_left_right_outer[Table]",
"astropy/table/tests/test_operations.py::TestVStack::test_vstack_one_table[QTable]",
"astropy/table/tests/test_operations.py::TestJoin::test_join_multidimensional[QTable]",
"astropy/table/tests/test_operations.py::TestVStack::test_mixin_functionality[arraywrap]",
"astropy/table/tests/test_operations.py::test_unique[Table]",
"astropy/table/tests/test_operations.py::TestJoin::test_join_multidimensional_masked[Table]",
"astropy/table/tests/test_operations.py::TestVStack::test_mixin_functionality[ndarray]",
"astropy/table/tests/test_operations.py::TestHStack::test_stack_rows[QTable]",
"astropy/table/tests/test_operations.py::TestVStack::test_table_meta_merge[QTable]",
"astropy/table/tests/test_operations.py::TestCStack::test_cstack_table_column[QTable]",
"astropy/table/tests/test_operations.py::TestHStack::test_table_col_rename[QTable]",
"astropy/table/tests/test_operations.py::test_get_out_class",
"astropy/table/tests/test_operations.py::TestSetdiff::test_extra_col_left_table[QTable]",
"astropy/table/tests/test_operations.py::TestHStack::test_stack_incompatible[QTable]",
"astropy/table/tests/test_operations.py::TestCStack::test_cstack_basic_inner[QTable]",
"astropy/table/tests/test_operations.py::TestJoin::test_mixin_functionality[arraywrap]",
"astropy/table/tests/test_operations.py::TestVStack::test_stack_rows[Table]",
"astropy/table/tests/test_operations.py::TestJoin::test_mixin_functionality[earthlocation]",
"astropy/table/tests/test_operations.py::TestVStack::test_bad_input_type[Table]",
"astropy/table/tests/test_operations.py::TestJoin::test_both_unmasked_single_key_inner[QTable]",
"astropy/table/tests/test_operations.py::TestSetdiff::test_extra_col_right_table[Table]",
"astropy/table/tests/test_operations.py::TestHStack::test_stack_same_table[Table]",
"astropy/table/tests/test_operations.py::TestHStack::test_table_meta_merge[Table]",
"astropy/table/tests/test_operations.py::TestJoin::test_mixin_functionality[time]",
"astropy/table/tests/test_operations.py::TestHStack::test_stack_rows[Table]",
"astropy/table/tests/test_operations.py::TestHStack::test_table_meta_merge_conflict[QTable]",
"astropy/table/tests/test_operations.py::TestVStack::test_stack_table_column[QTable]",
"astropy/table/tests/test_operations.py::TestHStack::test_col_meta_merge[Table]",
"astropy/table/tests/test_operations.py::TestJoin::test_table_meta_merge_conflict[QTable]",
"astropy/table/tests/test_operations.py::TestVStack::test_table_meta_merge_conflict[Table]",
"astropy/table/tests/test_operations.py::TestHStack::test_stack_basic[Table]",
"astropy/table/tests/test_operations.py::TestJoin::test_both_unmasked_inner[QTable]",
"astropy/table/tests/test_operations.py::test_vstack_bytes[QTable]",
"astropy/table/tests/test_operations.py::TestVStack::test_col_meta_merge_inner[QTable]",
"astropy/table/tests/test_operations.py::TestHStack::test_stack_columns[Table]",
"astropy/table/tests/test_operations.py::TestSetdiff::test_keys[Table]",
"astropy/table/tests/test_operations.py::test_vstack_unicode",
"astropy/table/tests/test_operations.py::TestJoin::test_bad_join_type[QTable]",
"astropy/table/tests/test_operations.py::TestHStack::test_mixin_functionality[ndarray]",
"astropy/table/tests/test_operations.py::TestVStack::test_vstack_one_masked[Table]",
"astropy/table/tests/test_operations.py::TestCStack::test_cstack_multi_dimension_column[QTable]",
"astropy/table/tests/test_operations.py::TestJoin::test_table_meta_merge_conflict[Table]",
"astropy/table/tests/test_operations.py::TestVStack::test_table_meta_merge[Table]",
"astropy/table/tests/test_operations.py::TestJoin::test_masked_key_column[Table]",
"astropy/table/tests/test_operations.py::TestJoin::test_missing_keys[Table]",
"astropy/table/tests/test_operations.py::TestVStack::test_mixin_functionality[latitude]",
"astropy/table/tests/test_operations.py::TestSetdiff::test_default_same_tables[QTable]",
"astropy/table/tests/test_operations.py::TestSetdiff::test_default_same_tables[Table]",
"astropy/table/tests/test_operations.py::TestVStack::test_mixin_functionality[quantity]",
"astropy/table/tests/test_operations.py::TestHStack::test_table_meta_merge_conflict[Table]",
"astropy/table/tests/test_operations.py::TestJoin::test_both_unmasked_inner[Table]",
"astropy/table/tests/test_operations.py::TestJoin::test_table_meta_merge[Table]",
"astropy/table/tests/test_operations.py::test_join_mixins_not_sortable",
"astropy/table/tests/test_operations.py::TestVStack::test_mixin_functionality[time]",
"astropy/table/tests/test_operations.py::TestJoin::test_join_multidimensional[Table]",
"astropy/table/tests/test_operations.py::TestJoin::test_col_meta_merge[QTable]",
"astropy/table/tests/test_operations.py::TestHStack::test_table_col_rename[Table]",
"astropy/table/tests/test_operations.py::TestVStack::test_stack_table_column[Table]",
"astropy/table/tests/test_operations.py::TestSetdiff::test_default_same_columns[QTable]",
"astropy/table/tests/test_operations.py::TestHStack::test_hstack_one_table[QTable]",
"astropy/table/tests/test_operations.py::TestVStack::test_stack_rows[QTable]",
"astropy/table/tests/test_operations.py::TestHStack::test_hstack_one_table[Table]"
] |
[
"astropy/table/tests/test_operations.py::TestJoin::test_cartesian_join[Table]",
"astropy/table/tests/test_operations.py::TestJoin::test_cartesian_join[QTable]"
] |
[
{
"path": "docs/table/operations.rst",
"old_path": "a/docs/table/operations.rst",
"new_path": "b/docs/table/operations.rst",
"metadata": "diff --git a/docs/table/operations.rst b/docs/table/operations.rst\nindex fc40c8d63b..2c026fbd8a 100644\n--- a/docs/table/operations.rst\n+++ b/docs/table/operations.rst\n@@ -721,7 +721,7 @@ matching key includes both ``name`` and ``obs_date``. Specifying the key as onl\n Likewise one can construct a new table with every row of the right table and matching left\n values (when available) using ``join_type='right'``.\n \n-Finally, to make a table with the union of rows from both tables do an \"outer\" join::\n+To make a table with the union of rows from both tables do an \"outer\" join::\n \n >>> print(join(optical, xray, join_type='outer'))\n name obs_date mag_b mag_v logLx\n@@ -732,9 +732,26 @@ Finally, to make a table with the union of rows from both tables do an \"outer\" j\n M82 2012-10-29 16.2 15.2 45.0\n NGC3516 2011-11-11 -- -- 42.1\n \n-In all cases the output join table will be sorted by the key column(s) and in general\n+In all the above cases the output join table will be sorted by the key column(s) and in general\n will not preserve the row order of the input tables.\n \n+Finally, one can do a \"cartesian\" join, which is the cartesian product of all available\n+rows. In this case one there are no key columns (and supplying a ``keys`` argument is\n+an error)::\n+\n+ >>> print(join(optical, xray, join_type='cartesian'))\n+ name_1 obs_date_1 mag_b mag_v name_2 obs_date_2 logLx\n+ ------ ---------- ----- ----- ------- ---------- -----\n+ M31 2012-01-02 17.0 16.0 NGC3516 2011-11-11 42.1\n+ M31 2012-01-02 17.0 16.0 M31 1999-01-05 43.1\n+ M31 2012-01-02 17.0 16.0 M82 2012-10-29 45.0\n+ M82 2012-10-29 16.2 15.2 NGC3516 2011-11-11 42.1\n+ M82 2012-10-29 16.2 15.2 M31 1999-01-05 43.1\n+ M82 2012-10-29 16.2 15.2 M82 2012-10-29 45.0\n+ M101 2012-10-31 15.1 15.5 NGC3516 2011-11-11 42.1\n+ M101 2012-10-31 15.1 15.5 M31 1999-01-05 43.1\n+ M101 2012-10-31 15.1 15.5 M82 2012-10-29 45.0\n+\n Non-identical key column names\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n \n"
}
] |
{
"header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:",
"data": [
{
"type": "error_msg",
"name": "cannot supply keys for a cartesian join"
}
]
}
|
diff --git a/docs/table/operations.rst b/docs/table/operations.rst
index fc40c8d63b..2c026fbd8a 100644
--- a/docs/table/operations.rst
+++ b/docs/table/operations.rst
@@ -721,7 +721,7 @@ matching key includes both ``name`` and ``obs_date``. Specifying the key as onl
Likewise one can construct a new table with every row of the right table and matching left
values (when available) using ``join_type='right'``.
-Finally, to make a table with the union of rows from both tables do an "outer" join::
+To make a table with the union of rows from both tables do an "outer" join::
>>> print(join(optical, xray, join_type='outer'))
name obs_date mag_b mag_v logLx
@@ -732,9 +732,26 @@ Finally, to make a table with the union of rows from both tables do an "outer" j
M82 2012-10-29 16.2 15.2 45.0
NGC3516 2011-11-11 -- -- 42.1
-In all cases the output join table will be sorted by the key column(s) and in general
+In all the above cases the output join table will be sorted by the key column(s) and in general
will not preserve the row order of the input tables.
+Finally, one can do a "cartesian" join, which is the cartesian product of all available
+rows. In this case one there are no key columns (and supplying a ``keys`` argument is
+an error)::
+
+ >>> print(join(optical, xray, join_type='cartesian'))
+ name_1 obs_date_1 mag_b mag_v name_2 obs_date_2 logLx
+ ------ ---------- ----- ----- ------- ---------- -----
+ M31 2012-01-02 17.0 16.0 NGC3516 2011-11-11 42.1
+ M31 2012-01-02 17.0 16.0 M31 1999-01-05 43.1
+ M31 2012-01-02 17.0 16.0 M82 2012-10-29 45.0
+ M82 2012-10-29 16.2 15.2 NGC3516 2011-11-11 42.1
+ M82 2012-10-29 16.2 15.2 M31 1999-01-05 43.1
+ M82 2012-10-29 16.2 15.2 M82 2012-10-29 45.0
+ M101 2012-10-31 15.1 15.5 NGC3516 2011-11-11 42.1
+ M101 2012-10-31 15.1 15.5 M31 1999-01-05 43.1
+ M101 2012-10-31 15.1 15.5 M82 2012-10-29 45.0
+
Non-identical key column names
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:
[{'type': 'error_msg', 'name': 'cannot supply keys for a cartesian join'}]
|
astropy/astropy
|
astropy__astropy-9135
|
https://github.com/astropy/astropy/pull/9135
|
diff --git a/CHANGES.rst b/CHANGES.rst
index 67d0d76684a9..085cc9382632 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -71,7 +71,12 @@ astropy.modeling
- Add ``Tabular1D.inverse`` [#9083]
- Significant reorganization of the documentation. [#9078, #9171]
-- ``Model.rename`` was changed to add the ability to rename ``Model.inputs`` and ``Model.outputs``. [#9220]
+- ``Model.rename`` was changed to add the ability to rename ``Model.inputs``
+ and ``Model.outputs``. [#9220]
+
+- New function ``fix_inputs`` to generate new models from others by fixing
+ specific inputs variable values to constants. [#9135]
+
astropy.nddata
^^^^^^^^^^^^^^
diff --git a/astropy/io/misc/asdf/tags/transform/compound.py b/astropy/io/misc/asdf/tags/transform/compound.py
index b228c0f9de6d..aa41693138d9 100644
--- a/astropy/io/misc/asdf/tags/transform/compound.py
+++ b/astropy/io/misc/asdf/tags/transform/compound.py
@@ -22,7 +22,8 @@
'/' : 'divide',
'**' : 'power',
'|' : 'compose',
- '&' : 'concatenate'
+ '&' : 'concatenate',
+ 'fix_inputs': 'fix_inputs'
}
@@ -33,7 +34,8 @@
'divide' : '__truediv__',
'power' : '__pow__',
'compose' : '__or__',
- 'concatenate' : '__and__'
+ 'concatenate' : '__and__',
+ 'fix_inputs' : 'fix_inputs'
}
@@ -54,10 +56,15 @@ def from_tree_tagged(cls, node, ctx):
node['forward'][0]._tag))
right = yamlutil.tagged_tree_to_custom_tree(
node['forward'][1], ctx)
- if not isinstance(right, Model):
+ if not isinstance(right, Model) and \
+ not (oper == 'fix_inputs' and isinstance(right, dict)):
raise TypeError("Unknown model type '{0}'".format(
node['forward'][1]._tag))
- model = getattr(left, oper)(right)
+ if oper == 'fix_inputs':
+ right = dict(zip(right['keys'], right['values']))
+ model = CompoundModel('fix_inputs', left, right)
+ else:
+ model = getattr(left, oper)(right)
model = cls._from_tree_base_transform_members(model, node, ctx)
model.map_parameters()
@@ -73,8 +80,13 @@ def _to_tree_from_model_tree(cls, tree, ctx):
left = cls._to_tree_from_model_tree(tree.left, ctx)
if not isinstance(tree.right, CompoundModel):
- right = yamlutil.custom_tree_to_tagged_tree(
- tree.right, ctx)
+ if isinstance(tree.right, dict):
+ right = {'keys': list(tree.right.keys()),
+ 'values': list(tree.right.values())
+ }
+ else:
+ right = yamlutil.custom_tree_to_tagged_tree(
+ tree.right, ctx)
else:
right = cls._to_tree_from_model_tree(tree.right, ctx)
diff --git a/astropy/modeling/core.py b/astropy/modeling/core.py
index debfa057e753..6af24eee49eb 100644
--- a/astropy/modeling/core.py
+++ b/astropy/modeling/core.py
@@ -47,7 +47,7 @@
__all__ = ['Model', 'FittableModel', 'Fittable1DModel', 'Fittable2DModel',
- 'CompoundModel', 'custom_model', 'ModelDefinitionError']
+ 'CompoundModel', 'fix_inputs', 'custom_model', 'ModelDefinitionError']
def _model_oper(oper, **kwargs):
@@ -103,6 +103,7 @@ def __new__(mcls, name, bases, members):
('__pow__', _model_oper('**')),
('__or__', _model_oper('|')),
('__and__', _model_oper('&')),
+ ('_fix_inputs', _model_oper('fix_inputs'))
]
for opermethod, opercall in opermethods:
@@ -455,6 +456,7 @@ def __init__(self, *params, **kwargs):
__pow__ = _model_oper('**')
__or__ = _model_oper('|')
__and__ = _model_oper('&')
+ _fix_inputs = _model_oper('fix_inputs')
# *** Other utilities ***
@@ -2315,14 +2317,13 @@ def __init__(self, op, left, right, name=None, inverse=None):
self._has_inverse = False # may be set to True in following code
if inverse:
self.inverse = inverse
- # else:
- # self._user_inverse = None
- if len(left) != len(right):
+
+ if op != 'fix_inputs' and len(left) != len(right):
raise ValueError(
'Both operands must have equal values for n_models')
else:
self._n_models = len(left)
- if ((left.model_set_axis != right.model_set_axis)
+ if op != 'fix_inputs' and ((left.model_set_axis != right.model_set_axis)
or left.model_set_axis): # not False and not 0
raise ValueError("model_set_axis must be False or 0 and consistent for operands")
else:
@@ -2368,15 +2369,62 @@ def __init__(self, op, left, right, name=None, inverse=None):
self.right.inverse,
self.left.inverse,
inverse=self)
+ elif op == 'fix_inputs':
+ if not isinstance(left, Model):
+ raise ValueError('First argument to "fix_inputs" must be an instance of an astropy Model.')
+ if not isinstance(right, dict):
+ raise ValueError('Expected a dictionary for second argument of "fix_inputs".')
+
+ # Dict keys must match either possible indices
+ # for model on left side, or names for inputs.
+ self.n_inputs = left.n_inputs - len(right)
+ self.outputs = left.outputs
+ self.n_outputs = left.n_outputs
+ newinputs = list(left.inputs)
+ keys = right.keys()
+ input_ind = []
+ for key in keys:
+ if isinstance(key, int):
+ if key >= left.n_inputs or key < 0:
+ raise ValueError(
+ 'Substitution key integer value '
+ 'not among possible input choices.')
+ else:
+ if key in input_ind:
+ raise ValueError("Duplicate specification of "
+ "same input (index/name).")
+ else:
+ input_ind.append(key)
+ elif isinstance(key, str):
+ if key not in left.inputs:
+ raise ValueError(
+ 'Substitution key string not among possible '
+ 'input choices.')
+ # Check to see it doesn't match positional
+ # specification.
+ ind = left.inputs.index(key)
+ if ind in input_ind:
+ raise ValueError("Duplicate specification of "
+ "same input (index/name).")
+ else:
+ input_ind.append(ind)
+ # Remove substituted inputs
+ input_ind.sort()
+ input_ind.reverse()
+ for ind in input_ind:
+ del newinputs[ind]
+ self.inputs = tuple(newinputs)
+ # Now check to see if the input model has bounding_box defined.
+ # If so, remove the appropriate dimensions and set it for this
+ # instance.
+ try:
+ bounding_box = self.left.bounding_box
+ self._fix_input_bounding_box(input_ind)
+ except NotImplementedError:
+ pass
+
else:
- #raise ModelDefinitionError('Illegal operator: ', self.op)
- raise ModelDefinitionError(
- "Unsupported operands for {0}: {1} (n_inputs={2}, "
- "n_outputs={3}) and {4} (n_inputs={5}, n_outputs={6}); "
- "models must have the same n_inputs and the same "
- "n_outputs for this operator".format(
- operator, left.name, left.n_inputs, left.n_outputs,
- right.name, right.n_inputs, right.n_outputs))
+ raise ModelDefinitionError('Illegal operator: ', self.op)
self.name = name
self._fittable = None
self.fit_deriv = None
@@ -2475,38 +2523,81 @@ def __call__(self, *args, **kw):
def _evaluate(self, *args, **kw):
op = self.op
- if op != '&':
- leftval = self.left(*args, **kw)
- if op != '|':
- rightval = self.right(*args, **kw)
- else:
- leftval = self.left(*(args[:self.left.n_inputs]), **kw)
- rightval = self.right(*(args[self.left.n_inputs:]), **kw)
- if op == '+':
- return binary_operation(operator.add, leftval, rightval)
- elif op == '-':
- return binary_operation(operator.sub, leftval, rightval)
- elif op == '*':
- return binary_operation(operator.mul, leftval, rightval)
- elif op == '/':
- return binary_operation(operator.truediv, leftval, rightval)
- elif op == '**':
- return binary_operation(operator.pow, leftval, rightval)
- elif op == '&':
- if not isinstance(leftval, tuple):
- leftval = (leftval,)
- if not isinstance(rightval, tuple):
- rightval = (rightval,)
- return leftval + rightval
- elif op == '|':
- if isinstance(leftval, tuple):
- return self.right(*leftval, **kw)
+ if op != 'fix_inputs':
+ if op != '&':
+ leftval = self.left(*args, **kw)
+ if op != '|':
+ rightval = self.right(*args, **kw)
+
+ else:
+ leftval = self.left(*(args[:self.left.n_inputs]), **kw)
+ rightval = self.right(*(args[self.left.n_inputs:]), **kw)
+ if op == '+':
+ return binary_operation(operator.add, leftval, rightval)
+ elif op == '-':
+ return binary_operation(operator.sub, leftval, rightval)
+ elif op == '*':
+ return binary_operation(operator.mul, leftval, rightval)
+ elif op == '/':
+ return binary_operation(operator.truediv, leftval, rightval)
+ elif op == '**':
+ return binary_operation(operator.pow, leftval, rightval)
+ elif op == '&':
+ if not isinstance(leftval, tuple):
+ leftval = (leftval,)
+ if not isinstance(rightval, tuple):
+ rightval = (rightval,)
+ return leftval + rightval
+ elif op == '|':
+ if isinstance(leftval, tuple):
+ return self.right(*leftval, **kw)
+ else:
+ return self.right(leftval, **kw)
+ elif op in SPECIAL_OPERATORS:
+ return binary_operation(SPECIAL_OPERATORS[op], leftval, rightval)
else:
- return self.right(leftval, **kw)
- elif op in SPECIAL_OPERATORS:
- return binary_operation(SPECIAL_OPERATORS[op], leftval, rightval)
+
+ raise ModelDefinitionError('Unrecognized operator {op}')
else:
- raise ModelDefinitionError('Unrecognized operator {op}')
+ subs = self.right
+ newargs = list(args)
+ subinds = []
+ subvals = []
+ for key in subs.keys():
+ if isinstance(key, int):
+ subinds.append(key)
+ elif isinstance(key, str):
+ ind = self.left.inputs.index(key)
+ subinds.append(ind)
+ subvals.append(subs[key])
+ # Turn inputs specified in kw into positional indices.
+ # Names for compound inputs do not propagate to sub models.
+ kwind = []
+ kwval = []
+ for kwkey in list(kw.keys()):
+ if kwkey in self.inputs:
+ ind = self.inputs.index(kwkey)
+ if ind < len(args):
+ raise ValueError("Keyword argument duplicates "
+ "positional value supplied.")
+ kwind.append(ind)
+ kwval.append(kw[kwkey])
+ del kw[kwkey]
+ # Build new argument list
+ # Append keyword specified args first
+ if kwind:
+ kwargs = list(zip(kwind, kwval))
+ kwargs.sort()
+ kwindsorted, kwvalsorted = list(zip(*kwargs))
+ newargs = newargs + list(kwvalsorted)
+ if subinds:
+ subargs = list(zip(subinds, subvals))
+ subargs.sort()
+ subindsorted, subvalsorted = list(zip(*subargs))
+ # The substitutions must be inserted in order
+ for ind, val in subargs:
+ newargs.insert(ind, val)
+ return self.left(*newargs, **kw)
@property
def param_names(self):
@@ -2735,14 +2826,6 @@ def isleaf(self):
def has_inverse(self):
return self._has_inverse
- @property
- def bounding_box(self):
- return self._bounding_box
-
- @bounding_box.setter
- def bounding_box(self, bounding_box):
- self._bounding_box = bounding_box
-
@property
def inverse(self):
if self.has_inverse():
@@ -2864,13 +2947,14 @@ def map_parameters(self):
param_map = {}
self._param_names = []
for lindex, leaf in enumerate(self._leaflist):
- for param_name in leaf.param_names:
- param = getattr(leaf, param_name)
- new_param_name = "{}_{}".format(param_name, lindex)
- self.__dict__[new_param_name] = param
- self._parameters_[new_param_name] = param
- self._param_names.append(new_param_name)
- param_map[new_param_name] = (lindex, param_name)
+ if not isinstance(leaf, dict):
+ for param_name in leaf.param_names:
+ param = getattr(leaf, param_name)
+ new_param_name = "{}_{}".format(param_name, lindex)
+ self.__dict__[new_param_name] = param
+ self._parameters_[new_param_name] = param
+ self._param_names.append(new_param_name)
+ param_map[new_param_name] = (lindex, param_name)
self._param_metrics = {}
self._param_map = param_map
self._param_map_inverse = dict((v, k) for k, v in param_map.items())
@@ -3207,6 +3291,21 @@ def bounding_box(self, bounding_box):
def bounding_box(self):
self._user_bounding_box = None
+ def _fix_input_bounding_box(self, input_ind):
+ """
+ If the ``fix_inputs`` operator is used and the model it is applied to
+ has a bounding box definition, delete the corresponding inputs from
+ that bounding box. This method presumes the bounding_box is not None.
+ This also presumes that the list of input indices to remove (i.e.,
+ input_ind has already been put in reverse sorted order).
+ """
+ bounding_box = list(self.left.bounding_box)
+ for ind in input_ind:
+ del bounding_box[ind]
+ if self.n_inputs == 1:
+ bounding_box = bounding_box[0]
+ self.bounding_box = bounding_box
+
@property
def has_user_bounding_box(self):
"""
@@ -3403,7 +3502,7 @@ def make_subtree_dict(tree, nodepath, tdict, leaflist):
tdict[nodepath] = (tree, leftmostind, rightmostind)
-_ORDER_OF_OPERATORS = [('|',), ('&',), ('+', '-'), ('*', '/'), ('**',)]
+_ORDER_OF_OPERATORS = [('fix_inputs',),('|',), ('&',), ('+', '-'), ('*', '/'), ('**',)]
OPERATOR_PRECEDENCE = {}
for idx, ops in enumerate(_ORDER_OF_OPERATORS):
for op in ops:
@@ -3411,6 +3510,31 @@ def make_subtree_dict(tree, nodepath, tdict, leaflist):
del idx, op, ops
+def fix_inputs(modelinstance, values):
+ """
+ This function creates a compound model with one or more of the input
+ values of the input model assigned fixed values (scalar or array).
+
+ Parameters
+ ----------
+ modelinstance : Model instance. This is the model that one or more of the
+ model input values will be fixed to some constant value.
+ values : A dictionary where the key identifies which input to fix
+ and its value is the value to fix it at. The key may either be the
+ name of the input or a number reflecting its order in the inputs.
+
+ Examples
+ --------
+
+ >>> from astropy.modeling.models import Gaussian2D
+ >>> g = Gaussian2D(1, 2, 3, 4, 5)
+ >>> gv = fix_inputs(g, {0: 2.5})
+
+ Results in a 1D function equivalent to Gaussian2D(1, 2, 3, 4, 5)(x=2.5, y)
+ """
+ return CompoundModel('fix_inputs', modelinstance, values)
+
+
def custom_model(*args, fit_deriv=None, **kwargs):
"""
Create a model from a user defined function. The inputs and parameters of
diff --git a/astropy/modeling/models.py b/astropy/modeling/models.py
index 6f6dbf348977..87f9ff07019e 100644
--- a/astropy/modeling/models.py
+++ b/astropy/modeling/models.py
@@ -5,7 +5,7 @@
"""
-from .core import custom_model, hide_inverse # pylint: disable=W0611
+from .core import custom_model, hide_inverse, fix_inputs # pylint: disable=W0611
from .mappings import *
from .projections import *
from .rotations import *
diff --git a/docs/modeling/compound-models.rst b/docs/modeling/compound-models.rst
index 54c35cce1532..a509bdf5d430 100644
--- a/docs/modeling/compound-models.rst
+++ b/docs/modeling/compound-models.rst
@@ -1369,3 +1369,34 @@ This opens up the possibility of essentially arbitrarily complex transformation
graphs. Currently the tools do not exist to make it easy to navigate and
reason about highly complex compound models that use these mappings, but that
is a possible enhancement for future versions.
+
+
+Model Reduction
+---------------
+
+In order to save much duplication in the construction of complex models, it is
+possible to define one complex model that covers all cases where the
+variables that distinguish the models are made part of the model's input
+variables. The ``fix_inputs`` function allows defining models derived from
+the more complex one by setting one or more of the inputs to a constant
+value. Examples of this sort of situation arise when working out
+the transformations from detector pixel to RA, Dec, and lambda for
+spectrographs when the slit locations may be moved (e.g., fiber fed or
+commandable slit masks), or different orders may be selected (e.g., Eschelle).
+In the case of order, one may have a function of pixel ``x``, ``y``, ``spectral_order``
+that map into ``RA``, ``Dec`` and ``lambda``. Without specifying ``spectral_order``, it is
+ambiguious what ``RA``, ``Dec`` and ``Lambda`` corresponds to a pixel location. It
+is usually possible to define a function of all three inputs. Presuming
+this model is ``general_transform`` then ``fix_inputs`` may be used to define
+the transform for a specific order as follows:
+
+::
+ >>> order1_transform = fix_inputs(general_transform, {'order': 1}) # doctest: +SKIP
+
+creates a new compound model that takes only pixel position and generates
+``RA``, ``Dec``, and ``lambda``. The ``fix_inputs`` function can be used to set input
+values by position (0 is the first) or by input variable name, and more
+than one can be set in the dictionary supplied.
+
+If the input model has a bounding_box, the generated model will have the
+bounding for the input coordinate removed.
|
diff --git a/astropy/io/misc/asdf/tags/transform/tests/test_transform.py b/astropy/io/misc/asdf/tags/transform/tests/test_transform.py
index e3ba12bfc0a2..173e642d30d1 100644
--- a/astropy/io/misc/asdf/tags/transform/tests/test_transform.py
+++ b/astropy/io/misc/asdf/tags/transform/tests/test_transform.py
@@ -11,6 +11,7 @@
from asdf.tests import helpers
import astropy.units as u
+from astropy.modeling.core import fix_inputs
from astropy.modeling import models as astmodels
test_models = [
@@ -165,3 +166,27 @@ def test_tabular_model_units(tmpdir):
method='nearest')
tree = {'model': model2}
helpers.assert_roundtrip_tree(tree, tmpdir)
+
+
+def test_fix_inputs(tmpdir):
+ model = astmodels.Pix2Sky_TAN() | astmodels.Rotation2D()
+ tree = {
+ 'compound': fix_inputs(model, {'x': 45}),
+ 'compound1': fix_inputs(model, {0: 45})
+ }
+
+ helpers.assert_roundtrip_tree(tree, tmpdir)
+
+
+def test_fix_inputs_type():
+ with pytest.raises(TypeError):
+ tree = {
+ 'compound': fix_inputs(3, {'x': 45})
+ }
+ helpers.assert_roundtrip_tree(tree, tmpdir)
+
+ with pytest.raises(AttributeError):
+ tree = {
+ 'compound': astmodels.Pix2Sky_TAN() & {'x': 45}
+ }
+ helpers.assert_roundtrip_tree(tree, tmpdir)
diff --git a/astropy/modeling/tests/test_compound.py b/astropy/modeling/tests/test_compound.py
index 096b66c4b269..a7feb59db0a6 100644
--- a/astropy/modeling/tests/test_compound.py
+++ b/astropy/modeling/tests/test_compound.py
@@ -10,13 +10,13 @@
from numpy.testing import assert_allclose, assert_array_equal
from astropy.utils import minversion
-from astropy.modeling.core import Model, ModelDefinitionError
+from astropy.modeling.core import Model, ModelDefinitionError, CompoundModel
from astropy.modeling.parameters import Parameter
from astropy.modeling.models import (Const1D, Shift, Scale, Rotation2D, Gaussian1D,
Gaussian2D, Polynomial1D, Polynomial2D,
Chebyshev2D, Legendre2D, Chebyshev1D, Legendre1D,
Identity, Mapping,
- Tabular1D)
+ Tabular1D, fix_inputs)
import astropy.units as u
from ..core import CompoundModel
@@ -307,6 +307,63 @@ def test_compound_with_polynomials(poly):
assert_allclose(result, result_compound)
+def test_fix_inputs():
+ g1 = Gaussian2D(1, 0, 0, 1, 2)
+ g2 = Gaussian2D(1.5, .5, -.2, .5, .3)
+ sg1_1 = fix_inputs(g1, {1: 0})
+ assert_allclose(sg1_1(0), g1(0, 0))
+ assert_allclose(sg1_1([0,1,3]), g1([0,1,3],[0,0,0]))
+ sg1_2 = fix_inputs(g1, {'x': 1})
+ assert_allclose(sg1_2(1.5), g1(1, 1.5))
+ gg1 = g1 & g2
+ sgg1_1 = fix_inputs(gg1, {1: 0.1, 3: 0.2})
+ assert_allclose(sgg1_1(0, 0), gg1(0, 0.1, 0, 0.2))
+ sgg1_2 = fix_inputs(gg1, {'x0': -.1, 2: .1})
+ assert_allclose(sgg1_2(1,1), gg1(-0.1, 1, 0.1, 1))
+ assert_allclose(sgg1_2(y0=1, y1=1), gg1(-0.1, 1, 0.1, 1))
+
+
+def test_fix_inputs_invalid():
+ g1 = Gaussian2D(1, 0, 0, 1, 2)
+ with pytest.raises(ValueError):
+ fix_inputs(g1, {'x0': 0, 0: 0})
+
+ with pytest.raises(ValueError):
+ fix_inputs(g1, (0, 1))
+
+ with pytest.raises(ValueError):
+ fix_inputs(g1, {3: 2})
+
+ with pytest.raises(ValueError):
+ fix_inputs(g1, {'w': 2})
+
+ with pytest.raises(ModelDefinitionError):
+ CompoundModel('#', g1, g1)
+
+ with pytest.raises(ValueError):
+ gg1 = fix_inputs(g1, {0: 1})
+ gg1(2, y=2)
+
+
+def test_fix_inputs_with_bounding_box():
+ g1 = Gaussian2D(1, 0, 0, 1, 1)
+ g2 = Gaussian2D(1, 0, 0, 1, 1)
+ assert g1.bounding_box == ((-5.5,5.5), (-5.5,5.5))
+
+ gg1 = g1 & g2
+ gg1.bounding_box = ((-5.5,5.5), (-5.4,5.4), (-5.3,5.3), (-5.2,5.2))
+ assert gg1.bounding_box == ((-5.5,5.5), (-5.4,5.4), (-5.3,5.3), (-5.2,5.2))
+
+ sg = fix_inputs(gg1, {0: 0, 2: 0})
+ assert sg.bounding_box == ((-5.4,5.4), (-5.2,5.2))
+
+ g1 = Gaussian1D(10, 3, 1)
+ g = g1 & g1
+ g.bounding_box = ((1, 4), (6, 8))
+ gf = fix_inputs(g, {0: 1})
+ assert gf.bounding_box == (6, 8)
+
+
def test_indexing_on_instance():
"""Test indexing on compound model instances."""
diff --git a/astropy/modeling/tests/test_model_sets.py b/astropy/modeling/tests/test_model_sets.py
index a24c52c81b0b..808e5afbe1e2 100644
--- a/astropy/modeling/tests/test_model_sets.py
+++ b/astropy/modeling/tests/test_model_sets.py
@@ -244,3 +244,8 @@ def test_model_set_axis_outputs():
assert_allclose(y0[:, 1], y1[1])
with pytest.raises(ValueError):
model_set(x)
+
+
+def test_compound_model_sets():
+ with pytest.raises(ValueError):
+ Polynomial1D(1, n_models=2, model_set_axis=1) | Polynomial1D(1, n_models=2, model_set_axis=0)
|
[
{
"path": "docs/modeling/compound-models.rst",
"old_path": "a/docs/modeling/compound-models.rst",
"new_path": "b/docs/modeling/compound-models.rst",
"metadata": "diff --git a/docs/modeling/compound-models.rst b/docs/modeling/compound-models.rst\nindex 54c35cce1532..a509bdf5d430 100644\n--- a/docs/modeling/compound-models.rst\n+++ b/docs/modeling/compound-models.rst\n@@ -1369,3 +1369,34 @@ This opens up the possibility of essentially arbitrarily complex transformation\n graphs. Currently the tools do not exist to make it easy to navigate and\n reason about highly complex compound models that use these mappings, but that\n is a possible enhancement for future versions.\n+\n+\n+Model Reduction\n+---------------\n+\n+In order to save much duplication in the construction of complex models, it is\n+possible to define one complex model that covers all cases where the\n+variables that distinguish the models are made part of the model's input\n+variables. The ``fix_inputs`` function allows defining models derived from\n+the more complex one by setting one or more of the inputs to a constant\n+value. Examples of this sort of situation arise when working out\n+the transformations from detector pixel to RA, Dec, and lambda for\n+spectrographs when the slit locations may be moved (e.g., fiber fed or\n+commandable slit masks), or different orders may be selected (e.g., Eschelle).\n+In the case of order, one may have a function of pixel ``x``, ``y``, ``spectral_order``\n+that map into ``RA``, ``Dec`` and ``lambda``. Without specifying ``spectral_order``, it is\n+ambiguious what ``RA``, ``Dec`` and ``Lambda`` corresponds to a pixel location. It\n+is usually possible to define a function of all three inputs. Presuming\n+this model is ``general_transform`` then ``fix_inputs`` may be used to define\n+the transform for a specific order as follows:\n+\n+::\n+ >>> order1_transform = fix_inputs(general_transform, {'order': 1}) # doctest: +SKIP\n+\n+creates a new compound model that takes only pixel position and generates\n+``RA``, ``Dec``, and ``lambda``. The ``fix_inputs`` function can be used to set input\n+values by position (0 is the first) or by input variable name, and more\n+than one can be set in the dictionary supplied.\n+\n+If the input model has a bounding_box, the generated model will have the\n+bounding for the input coordinate removed.\n",
"update": null
}
] |
4.0
|
a2e3a8d311fb91ec5b868cb11ebae7d579094519
|
[
"astropy/modeling/tests/test_model_sets.py::test_axis_0",
"astropy/modeling/tests/test_model_sets.py::test_shapes",
"astropy/modeling/tests/test_model_sets.py::test_model_axis_1",
"astropy/modeling/tests/test_model_sets.py::test_linearlsqfitter",
"astropy/modeling/tests/test_model_sets.py::test_negative_axis",
"astropy/modeling/tests/test_model_sets.py::test_model_axis_2",
"astropy/modeling/tests/test_model_sets.py::test_compound_model_sets",
"astropy/modeling/tests/test_model_sets.py::test_model_set_axis_outputs"
] |
[
"astropy/modeling/tests/test_compound.py::test_model_set[<lambda>-result1]",
"astropy/modeling/tests/test_compound.py::test_simple_two_model_compose_2d",
"astropy/modeling/tests/test_compound.py::test_identity_input",
"astropy/modeling/tests/test_compound.py::test_compound_unsupported_inverse[model3]",
"astropy/modeling/tests/test_compound.py::test_fix_inputs",
"astropy/modeling/tests/test_compound.py::test_invalid_operands",
"astropy/modeling/tests/test_compound.py::test_n_submodels",
"astropy/modeling/tests/test_compound.py::test_bounding_box",
"astropy/modeling/tests/test_compound.py::test_two_model_instance_arithmetic_1d[<lambda>--1.0]",
"astropy/modeling/tests/test_compound.py::test_model_set[<lambda>-result3]",
"astropy/modeling/tests/test_compound.py::test_compound_unsupported_inverse[model5]",
"astropy/modeling/tests/test_compound.py::test_model_set[<lambda>-result2]",
"astropy/modeling/tests/test_compound.py::test_two_model_instance_arithmetic_1d[<lambda>-5.0]",
"astropy/modeling/tests/test_compound.py::test_name_index",
"astropy/modeling/tests/test_compound.py::test_model_set[<lambda>-result0]",
"astropy/modeling/tests/test_compound.py::test_expression_formatting",
"astropy/modeling/tests/test_compound.py::test_model_set_raises_value_error[<lambda>-result1]",
"astropy/modeling/tests/test_compound.py::test_compound_unsupported_inverse[model2]",
"astropy/modeling/tests/test_compound.py::test_model_set_raises_value_error[<lambda>-result3]",
"astropy/modeling/tests/test_compound.py::test_two_model_instance_arithmetic_1d[<lambda>-6.0]",
"astropy/modeling/tests/test_compound.py::test_indexing_on_instance",
"astropy/modeling/tests/test_compound.py::test_two_model_instance_arithmetic_1d[<lambda>-0.6666666666666666]",
"astropy/modeling/tests/test_compound.py::test_pickle_compound",
"astropy/modeling/tests/test_compound.py::test_compound_unsupported_inverse[model4]",
"astropy/modeling/tests/test_compound.py::test_model_set_raises_value_error[<lambda>-result0]",
"astropy/modeling/tests/test_compound.py::test_mapping_inverse",
"astropy/modeling/tests/test_compound.py::test_simple_two_model_compose_1d",
"astropy/modeling/tests/test_compound.py::test_compound_with_polynomials[poly1]",
"astropy/modeling/tests/test_compound.py::test_model_set_raises_value_error[<lambda>-result4]",
"astropy/modeling/tests/test_compound.py::test_compound_with_polynomials[poly2]",
"astropy/modeling/tests/test_compound.py::test_compound_custom_inverse",
"astropy/modeling/tests/test_compound.py::test_compound_with_polynomials[poly5]",
"astropy/modeling/tests/test_compound.py::test_fix_inputs_with_bounding_box",
"astropy/modeling/tests/test_compound.py::test_compound_with_polynomials[poly3]",
"astropy/modeling/tests/test_compound.py::test_inherit_constraints",
"astropy/modeling/tests/test_compound.py::test_model_set_raises_value_error[<lambda>-result2]",
"astropy/modeling/tests/test_compound.py::test_two_model_instance_arithmetic_1d[<lambda>-8.0]",
"astropy/modeling/tests/test_compound.py::test_mapping_basic_permutations",
"astropy/modeling/tests/test_compound.py::test_compound_unsupported_inverse[model1]",
"astropy/modeling/tests/test_compound.py::test_name",
"astropy/modeling/tests/test_compound.py::test_update_parameters",
"astropy/modeling/tests/test_compound.py::test_compound_with_polynomials[poly4]",
"astropy/modeling/tests/test_compound.py::test_basic_compound_inverse",
"astropy/modeling/tests/test_compound.py::test_compound_unsupported_inverse[model0]",
"astropy/modeling/tests/test_compound.py::test_fix_inputs_invalid",
"astropy/modeling/tests/test_compound.py::test_model_set[<lambda>-result4]",
"astropy/modeling/tests/test_compound.py::test_compound_with_polynomials[poly0]"
] |
[
{
"path": "docs/modeling/compound-models.rst",
"old_path": "a/docs/modeling/compound-models.rst",
"new_path": "b/docs/modeling/compound-models.rst",
"metadata": "diff --git a/docs/modeling/compound-models.rst b/docs/modeling/compound-models.rst\nindex 54c35cce15..a509bdf5d4 100644\n--- a/docs/modeling/compound-models.rst\n+++ b/docs/modeling/compound-models.rst\n@@ -1369,3 +1369,34 @@ This opens up the possibility of essentially arbitrarily complex transformation\n graphs. Currently the tools do not exist to make it easy to navigate and\n reason about highly complex compound models that use these mappings, but that\n is a possible enhancement for future versions.\n+\n+\n+Model Reduction\n+---------------\n+\n+In order to save much duplication in the construction of complex models, it is\n+possible to define one complex model that covers all cases where the\n+variables that distinguish the models are made part of the model's input\n+variables. The ``fix_inputs`` function allows defining models derived from\n+the more complex one by setting one or more of the inputs to a constant\n+value. Examples of this sort of situation arise when working out\n+the transformations from detector pixel to RA, Dec, and lambda for\n+spectrographs when the slit locations may be moved (e.g., fiber fed or\n+commandable slit masks), or different orders may be selected (e.g., Eschelle).\n+In the case of order, one may have a function of pixel ``x``, ``y``, ``spectral_order``\n+that map into ``RA``, ``Dec`` and ``lambda``. Without specifying ``spectral_order``, it is\n+ambiguious what ``RA``, ``Dec`` and ``Lambda`` corresponds to a pixel location. It\n+is usually possible to define a function of all three inputs. Presuming\n+this model is ``general_transform`` then ``fix_inputs`` may be used to define\n+the transform for a specific order as follows:\n+\n+::\n+ >>> order1_transform = fix_inputs(general_transform, {'order': 1}) # doctest: +SKIP\n+\n+creates a new compound model that takes only pixel position and generates\n+``RA``, ``Dec``, and ``lambda``. The ``fix_inputs`` function can be used to set input\n+values by position (0 is the first) or by input variable name, and more\n+than one can be set in the dictionary supplied.\n+\n+If the input model has a bounding_box, the generated model will have the\n+bounding for the input coordinate removed.\n"
}
] |
{
"header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:",
"data": []
}
|
diff --git a/docs/modeling/compound-models.rst b/docs/modeling/compound-models.rst
index 54c35cce15..a509bdf5d4 100644
--- a/docs/modeling/compound-models.rst
+++ b/docs/modeling/compound-models.rst
@@ -1369,3 +1369,34 @@ This opens up the possibility of essentially arbitrarily complex transformation
graphs. Currently the tools do not exist to make it easy to navigate and
reason about highly complex compound models that use these mappings, but that
is a possible enhancement for future versions.
+
+
+Model Reduction
+---------------
+
+In order to save much duplication in the construction of complex models, it is
+possible to define one complex model that covers all cases where the
+variables that distinguish the models are made part of the model's input
+variables. The ``fix_inputs`` function allows defining models derived from
+the more complex one by setting one or more of the inputs to a constant
+value. Examples of this sort of situation arise when working out
+the transformations from detector pixel to RA, Dec, and lambda for
+spectrographs when the slit locations may be moved (e.g., fiber fed or
+commandable slit masks), or different orders may be selected (e.g., Eschelle).
+In the case of order, one may have a function of pixel ``x``, ``y``, ``spectral_order``
+that map into ``RA``, ``Dec`` and ``lambda``. Without specifying ``spectral_order``, it is
+ambiguious what ``RA``, ``Dec`` and ``Lambda`` corresponds to a pixel location. It
+is usually possible to define a function of all three inputs. Presuming
+this model is ``general_transform`` then ``fix_inputs`` may be used to define
+the transform for a specific order as follows:
+
+::
+ >>> order1_transform = fix_inputs(general_transform, {'order': 1}) # doctest: +SKIP
+
+creates a new compound model that takes only pixel position and generates
+``RA``, ``Dec``, and ``lambda``. The ``fix_inputs`` function can be used to set input
+values by position (0 is the first) or by input variable name, and more
+than one can be set in the dictionary supplied.
+
+If the input model has a bounding_box, the generated model will have the
+bounding for the input coordinate removed.
|
astropy/astropy
|
astropy__astropy-8517
|
https://github.com/astropy/astropy/pull/8517
|
diff --git a/CHANGES.rst b/CHANGES.rst
index 9cc0c28c2d96..5d5bf3f541a2 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -10,6 +10,9 @@ astropy.config
astropy.constants
^^^^^^^^^^^^^^^^^
+- The version of constants can be specified via ScienceState in a way
+ that ``constants`` and ``units`` will be consistent. [#8517]
+
astropy.convolution
^^^^^^^^^^^^^^^^^^^
diff --git a/astropy/__init__.py b/astropy/__init__.py
index ab8d1736ad27..edfea0da948d 100644
--- a/astropy/__init__.py
+++ b/astropy/__init__.py
@@ -157,6 +157,80 @@ class Conf(_config.ConfigNamespace):
conf = Conf()
+
+# Define a base ScienceState for configuring constants and units
+from .utils.state import ScienceState
+class base_constants_version(ScienceState):
+ """
+ Base class for the real version-setters below
+ """
+ _value = 'test'
+
+ _versions = dict(test='test')
+
+ @classmethod
+ def validate(cls, value):
+ if value not in cls._versions:
+ raise ValueError('Must be one of {}'
+ .format(list(cls._versions.keys())))
+ return cls._versions[value]
+
+ @classmethod
+ def set(cls, value):
+ """
+ Set the current constants value.
+ """
+ import sys
+ if 'astropy.units' in sys.modules:
+ raise RuntimeError('astropy.units is already imported')
+ if 'astropy.constants' in sys.modules:
+ raise RuntimeError('astropy.constants is already imported')
+
+ class _Context:
+ def __init__(self, parent, value):
+ self._value = value
+ self._parent = parent
+
+ def __enter__(self):
+ pass
+
+ def __exit__(self, type, value, tb):
+ self._parent._value = self._value
+
+ def __repr__(self):
+ return ('<ScienceState {0}: {1!r}>'
+ .format(self._parent.__name__, self._parent._value))
+
+ ctx = _Context(cls, cls._value)
+ value = cls.validate(value)
+ cls._value = value
+ return ctx
+
+
+class physical_constants(base_constants_version):
+ """
+ The version of physical constants to use
+ """
+ # Maintainers: update when new constants are added
+ _value = 'codata2014'
+
+ _versions = dict(codata2018='codata2018', codata2014='codata2014',
+ codata2010='codata2010', astropyconst40='codata2018',
+ astropyconst20='codata2014', astropyconst13='codata2010')
+
+
+class astronomical_constants(base_constants_version):
+ """
+ The version of astronomical constants to use
+ """
+ # Maintainers: update when new constants are added
+ _value = 'iau2015'
+
+ _versions = dict(iau2015='iau2015', iau2012='iau2012',
+ astropyconst40='iau2015', astropyconst20='iau2015',
+ astropyconst13='iau2012')
+
+
# Create the test() function
from .tests.runner import TestRunner
test = TestRunner.make_test_runner_in(__path__[0])
@@ -320,7 +394,8 @@ def online_help(query):
__dir_inc__ = ['__version__', '__githash__', '__minimum_numpy_version__',
'__bibtex__', 'test', 'log', 'find_api_page', 'online_help',
- 'online_docs_root', 'conf']
+ 'online_docs_root', 'conf', 'physical_constants',
+ 'astronomical_constants']
from types import ModuleType as __module_type__
diff --git a/astropy/constants/__init__.py b/astropy/constants/__init__.py
index 65350120f9d9..7607e642de77 100644
--- a/astropy/constants/__init__.py
+++ b/astropy/constants/__init__.py
@@ -13,21 +13,21 @@
<Quantity 0.510998927603161 MeV>
"""
+import warnings
from contextlib import contextmanager
from astropy.utils import find_current_module
# Hack to make circular imports with units work
-try:
- from astropy import units
- del units
-except ImportError:
- pass
+from astropy import units
+del units
+# These lines import some namespaces into the top level
from .constant import Constant, EMConstant # noqa
from . import si # noqa
from . import cgs # noqa
-from . import codata2014, iau2015 # noqa
+from .config import codata, iaudata
+
from . import utils as _utils
# for updating the constants module docstring
@@ -38,9 +38,11 @@
'========== ============== ================ =========================',
]
-# NOTE: Update this when default changes.
-_utils._set_c(codata2014, iau2015, find_current_module(),
- not_in_module_only=True, doclines=_lines, set_class=True)
+# Catch warnings about "already has a definition in the None system"
+with warnings.catch_warnings():
+ warnings.filterwarnings('ignore', 'Constant .*already has a definition')
+ _utils._set_c(codata, iaudata, find_current_module(),
+ not_in_module_only=False, doclines=_lines, set_class=True)
_lines.append(_lines[1])
@@ -65,38 +67,42 @@ def set_enabled_constants(modname):
"""
# Re-import here because these were deleted from namespace on init.
+ import importlib
import warnings
from astropy.utils import find_current_module
from . import utils as _utils
- # NOTE: Update this when default changes.
- if modname == 'astropyconst13':
- from .astropyconst13 import codata2010 as codata
- from .astropyconst13 import iau2012 as iaudata
- else:
- raise ValueError(
- 'Context manager does not currently handle {}'.format(modname))
+ try:
+ modmodule = importlib.import_module('.constants.' + modname, 'astropy')
+ codata_context = modmodule.codata
+ iaudata_context = modmodule.iaudata
+ except ImportError as exc:
+ exc.args += ('Context manager does not currently handle {}'
+ .format(modname),)
+ raise
module = find_current_module()
# Ignore warnings about "Constant xxx already has a definition..."
with warnings.catch_warnings():
- warnings.simplefilter('ignore')
- _utils._set_c(codata, iaudata, module,
+ warnings.filterwarnings('ignore',
+ 'Constant .*already has a definition')
+ _utils._set_c(codata_context, iaudata_context, module,
not_in_module_only=False, set_class=True)
try:
yield
finally:
with warnings.catch_warnings():
- warnings.simplefilter('ignore')
- # NOTE: Update this when default changes.
- _utils._set_c(codata2014, iau2015, module,
+ warnings.filterwarnings('ignore',
+ 'Constant .*already has a definition')
+ _utils._set_c(codata, iaudata, module,
not_in_module_only=False, set_class=True)
# Clean up namespace
del find_current_module
+del warnings
del contextmanager
del _utils
del _lines
diff --git a/astropy/constants/astropyconst13.py b/astropy/constants/astropyconst13.py
index 4e19a0f883d5..b22fca4ccd67 100644
--- a/astropy/constants/astropyconst13.py
+++ b/astropy/constants/astropyconst13.py
@@ -8,7 +8,10 @@
from . import utils as _utils
from . import codata2010, iau2012
-_utils._set_c(codata2010, iau2012, find_current_module())
+codata = codata2010
+iaudata = iau2012
+
+_utils._set_c(codata, iaudata, find_current_module())
# Clean up namespace
del find_current_module
diff --git a/astropy/constants/astropyconst20.py b/astropy/constants/astropyconst20.py
index 5a04ec7d6196..050db5d0af16 100644
--- a/astropy/constants/astropyconst20.py
+++ b/astropy/constants/astropyconst20.py
@@ -7,7 +7,11 @@
from . import utils as _utils
from . import codata2014, iau2015
-_utils._set_c(codata2014, iau2015, find_current_module())
+
+codata = codata2014
+iaudata = iau2015
+
+_utils._set_c(codata, iaudata, find_current_module())
# Clean up namespace
del find_current_module
diff --git a/astropy/constants/cgs.py b/astropy/constants/cgs.py
index adca1b3411c3..0c7aeb536765 100644
--- a/astropy/constants/cgs.py
+++ b/astropy/constants/cgs.py
@@ -3,14 +3,13 @@
Astronomical and physics constants in cgs units. See :mod:`astropy.constants`
for a complete listing of constants defined in Astropy.
"""
-
import itertools
from .constant import Constant
-from . import codata2014, iau2015
+from .config import codata, iaudata
-for _nm, _c in itertools.chain(sorted(vars(codata2014).items()),
- sorted(vars(iau2015).items())):
+for _nm, _c in itertools.chain(sorted(vars(codata).items()),
+ sorted(vars(iaudata).items())):
if (isinstance(_c, Constant) and _c.abbrev not in locals()
- and _c.system in ['esu', 'gauss', 'emu']):
+ and _c.system in ['esu', 'gauss', 'emu']):
locals()[_c.abbrev] = _c
diff --git a/astropy/constants/config.py b/astropy/constants/config.py
new file mode 100644
index 000000000000..c163b820ec98
--- /dev/null
+++ b/astropy/constants/config.py
@@ -0,0 +1,14 @@
+# Licensed under a 3-clause BSD style license - see LICENSE.rst
+"""
+Configures the codata and iaudata used, possibly using user configuration.
+"""
+# Note: doing this in __init__ causes import problems with units,
+# as si.py and cgs.py have to import the result.
+import importlib
+import astropy
+
+phys_version = astropy.physical_constants.get()
+astro_version = astropy.astronomical_constants.get()
+
+codata = importlib.import_module('.constants.' + phys_version, 'astropy')
+iaudata = importlib.import_module('.constants.' + astro_version, 'astropy')
diff --git a/astropy/constants/si.py b/astropy/constants/si.py
index 65e5a2d13eb8..c8f83a841110 100644
--- a/astropy/constants/si.py
+++ b/astropy/constants/si.py
@@ -3,16 +3,13 @@
Astronomical and physics constants in SI units. See :mod:`astropy.constants`
for a complete listing of constants defined in Astropy.
"""
-
-
-
import itertools
from .constant import Constant
-from . import codata2014, iau2015
+from .config import codata, iaudata
-for _nm, _c in itertools.chain(sorted(vars(codata2014).items()),
- sorted(vars(iau2015).items())):
+for _nm, _c in itertools.chain(sorted(vars(codata).items()),
+ sorted(vars(iaudata).items())):
if (isinstance(_c, Constant) and _c.abbrev not in locals()
- and _c.system == 'si'):
+ and _c.system == 'si'):
locals()[_c.abbrev] = _c
diff --git a/docs/constants/index.rst b/docs/constants/index.rst
index de4e4709f299..d31aa1656a40 100644
--- a/docs/constants/index.rst
+++ b/docs/constants/index.rst
@@ -118,9 +118,57 @@ Union (IAU) are collected in modules with names like ``iau2012`` or ``iau2015``:
Reference = IAU 2015 Resolution B 3
The astronomical and physical constants are combined into modules with
-names like ``astropyconst13`` and ``astropyconst20``. To temporarily set
-constants to an older version (e.g., for regression testing), a context
-manager is available as follows:
+names like ``astropyconst13`` and ``astropyconst20`` for different versions.
+However, importing these prior version modules directly will lead to
+inconsistencies with other subpackages that have already imported
+`astropy.constants`. Notably, `astropy.units` will have already used
+the default version of constants. When using prior versions of the constants
+in this manner, quantities should be constructed with constants instead of units.
+
+To ensure consistent use of a prior version of constants in other Astropy
+packages (such as `astropy.units`) that import constants, the physical and
+astronomical constants versions should be set via ScienceState classes.
+These must be set before the first import of either `astropy.constants` or
+`astropy.units`. For example, you can use the CODATA2010 physical constants and the
+IAU 2012 astronomical constants:
+
+ >>> from astropy import physical_constants, astronomical_constants
+ >>> physical_constants.set('codata2010') # doctest: +SKIP
+ <ScienceState physical_constants: 'codata2010'>
+ >>> physical_constants.get() # doctest: +SKIP
+ 'codata2010'
+ >>> astronomical_constants.set('iau2012') # doctest: +SKIP
+ <ScienceState astronomical_constants: 'iau2012'>
+ >>> astronomical_constants.get() # doctest: +SKIP
+ 'iau2012'
+
+Then all other packages that import `astropy.constants` will self-consistently
+initialize with that prior version of constants.
+
+The versions may also be set using values referring to the version modules:
+
+ >>> from astropy import physical_constants, astronomical_constants
+ >>> physical_constants.set('astropyconst13') # doctest: +SKIP
+ <ScienceState physical_constants: 'codata2010'>
+ >>> physical_constants.get() # doctest: +SKIP
+ 'codata2010'
+ >>> astronomical_constants.set('astropyconst13') # doctest: +SKIP
+ <ScienceState astronomical_constants: 'iau2012'>
+ >>> astronomical_constants.get() # doctest: +SKIP
+ 'iau2012'
+
+If either `astropy.constants` or `astropy.units` have already been imported, a
+``RuntimeError`` will be raised.
+
+ >>> import astropy.units
+ >>> from astropy import physical_constants, astronomical_constants
+ >>> astronomical_constants.set('astropyconst13')
+ Traceback (most recent call last):
+ ...
+ RuntimeError: astropy.units is already imported
+
+To temporarily set constants to an older version (e.g.,
+for regression testing), a context manager is available, as follows:
>>> from astropy import constants as const
>>> with const.set_enabled_constants('astropyconst13'):
@@ -137,11 +185,10 @@ manager is available as follows:
Unit = J s
Reference = CODATA 2014
-.. warning::
+The context manager may be used at any time in a Python session, but it
+uses the prior version only for `astropy.constants`, and not for any
+other subpackage such as `astropy.units`.
- Units such as ``u.M_sun`` will use the current version of the
- corresponding constant. When using prior versions of the constants,
- quantities should be constructed with constants instead of units.
.. note that if this section gets too long, it should be moved to a separate
doc page - see the top of performance.inc.rst for the instructions on how to
diff --git a/docs/units/constants_versions.rst b/docs/units/constants_versions.rst
new file mode 100644
index 000000000000..4663b3257f24
--- /dev/null
+++ b/docs/units/constants_versions.rst
@@ -0,0 +1,29 @@
+Using prior versions of constants
+*********************************
+
+By default, `astropy.units` are initialized upon first import to use
+the current versions of `astropy.constants`. For units to initialize
+properly to a prior version of constants, the constants versions must
+be set before the first import of `astropy.units` or `astropy.constants`.
+
+This is accomplished using ScienceState classes in the top-level package.
+Setting the prior versions at the start of a Python session will allow
+consistent units, as follows:
+
+>>> import astropy
+>>> astropy.physical_constants.set('codata2010') # doctest: +SKIP
+<ScienceState physical_constants: 'codata2010'>
+>>> astropy.astronomical_constants.set('iau2012') # doctest: +SKIP
+<ScienceState astronomical_constants: 'iau2012'>
+>>> import astropy.units as u
+>>> import astropy.constants as const
+>>> (const.M_sun / u.M_sun).to(u.dimensionless_unscaled) - 1 # doctest: +SKIP
+<Quantity 0.>
+>>> const.M_sun # doctest: +SKIP
+ Name = Solar mass
+ Value = 1.9891e+30
+ Uncertainty = 5e+25
+ Unit = kg
+ Reference = Allen's Astrophysical Quantities 4th Ed.
+
+If `astropy.units` has already been imported, a RuntimeError is raised.
diff --git a/docs/units/index.rst b/docs/units/index.rst
index 4267de423490..82a7d412d664 100644
--- a/docs/units/index.rst
+++ b/docs/units/index.rst
@@ -165,6 +165,7 @@ Using `astropy.units`
logarithmic_units
format
equivalencies
+ constants_versions
conversion
See Also
|
diff --git a/astropy/constants/tests/test_prior_version.py b/astropy/constants/tests/test_prior_version.py
index 5d13c66a7b98..c7f54ef75b60 100644
--- a/astropy/constants/tests/test_prior_version.py
+++ b/astropy/constants/tests/test_prior_version.py
@@ -163,6 +163,6 @@ def test_context_manager():
assert const.h.value == 6.626070040e-34 # CODATA2014
- with pytest.raises(ValueError):
+ with pytest.raises(ImportError):
with const.set_enabled_constants('notreal'):
const.h
diff --git a/astropy/constants/tests/test_sciencestate.py b/astropy/constants/tests/test_sciencestate.py
new file mode 100644
index 000000000000..1fa32b6909e1
--- /dev/null
+++ b/astropy/constants/tests/test_sciencestate.py
@@ -0,0 +1,21 @@
+import pytest
+
+from astropy import physical_constants, astronomical_constants
+import astropy.constants as const
+
+
+def test_version_match():
+ pversion = physical_constants.get()
+ refpversion = const.h.__class__.__name__.lower()
+ assert pversion == refpversion
+ aversion = astronomical_constants.get()
+ refaversion = const.M_sun.__class__.__name__.lower()
+ assert aversion == refaversion
+
+
+def test_previously_imported():
+ with pytest.raises(RuntimeError):
+ physical_constants.set('codata2018')
+
+ with pytest.raises(RuntimeError):
+ astronomical_constants.set('iau2015')
|
[
{
"path": "docs/constants/index.rst",
"old_path": "a/docs/constants/index.rst",
"new_path": "b/docs/constants/index.rst",
"metadata": "diff --git a/docs/constants/index.rst b/docs/constants/index.rst\nindex de4e4709f299..d31aa1656a40 100644\n--- a/docs/constants/index.rst\n+++ b/docs/constants/index.rst\n@@ -118,9 +118,57 @@ Union (IAU) are collected in modules with names like ``iau2012`` or ``iau2015``:\n Reference = IAU 2015 Resolution B 3\n \n The astronomical and physical constants are combined into modules with\n-names like ``astropyconst13`` and ``astropyconst20``. To temporarily set\n-constants to an older version (e.g., for regression testing), a context\n-manager is available as follows:\n+names like ``astropyconst13`` and ``astropyconst20`` for different versions.\n+However, importing these prior version modules directly will lead to\n+inconsistencies with other subpackages that have already imported\n+`astropy.constants`. Notably, `astropy.units` will have already used\n+the default version of constants. When using prior versions of the constants\n+in this manner, quantities should be constructed with constants instead of units.\n+\n+To ensure consistent use of a prior version of constants in other Astropy\n+packages (such as `astropy.units`) that import constants, the physical and\n+astronomical constants versions should be set via ScienceState classes.\n+These must be set before the first import of either `astropy.constants` or\n+`astropy.units`. For example, you can use the CODATA2010 physical constants and the\n+IAU 2012 astronomical constants:\n+\n+ >>> from astropy import physical_constants, astronomical_constants\n+ >>> physical_constants.set('codata2010') # doctest: +SKIP\n+ <ScienceState physical_constants: 'codata2010'>\n+ >>> physical_constants.get() # doctest: +SKIP\n+ 'codata2010'\n+ >>> astronomical_constants.set('iau2012') # doctest: +SKIP\n+ <ScienceState astronomical_constants: 'iau2012'>\n+ >>> astronomical_constants.get() # doctest: +SKIP\n+ 'iau2012'\n+\n+Then all other packages that import `astropy.constants` will self-consistently\n+initialize with that prior version of constants.\n+\n+The versions may also be set using values referring to the version modules:\n+\n+ >>> from astropy import physical_constants, astronomical_constants\n+ >>> physical_constants.set('astropyconst13') # doctest: +SKIP\n+ <ScienceState physical_constants: 'codata2010'>\n+ >>> physical_constants.get() # doctest: +SKIP\n+ 'codata2010'\n+ >>> astronomical_constants.set('astropyconst13') # doctest: +SKIP\n+ <ScienceState astronomical_constants: 'iau2012'>\n+ >>> astronomical_constants.get() # doctest: +SKIP\n+ 'iau2012'\n+\n+If either `astropy.constants` or `astropy.units` have already been imported, a\n+``RuntimeError`` will be raised.\n+\n+ >>> import astropy.units\n+ >>> from astropy import physical_constants, astronomical_constants\n+ >>> astronomical_constants.set('astropyconst13')\n+ Traceback (most recent call last):\n+ ...\n+ RuntimeError: astropy.units is already imported\n+\n+To temporarily set constants to an older version (e.g.,\n+for regression testing), a context manager is available, as follows:\n \n >>> from astropy import constants as const\n >>> with const.set_enabled_constants('astropyconst13'):\n@@ -137,11 +185,10 @@ manager is available as follows:\n Unit = J s\n Reference = CODATA 2014\n \n-.. warning::\n+The context manager may be used at any time in a Python session, but it\n+uses the prior version only for `astropy.constants`, and not for any\n+other subpackage such as `astropy.units`.\n \n- Units such as ``u.M_sun`` will use the current version of the\n- corresponding constant. When using prior versions of the constants,\n- quantities should be constructed with constants instead of units.\n \n .. note that if this section gets too long, it should be moved to a separate\n doc page - see the top of performance.inc.rst for the instructions on how to\n",
"update": null
},
{
"path": "docs/units/constants_versions.rst",
"old_path": "/dev/null",
"new_path": "b/docs/units/constants_versions.rst",
"metadata": "diff --git a/docs/units/constants_versions.rst b/docs/units/constants_versions.rst\nnew file mode 100644\nindex 000000000000..4663b3257f24\n--- /dev/null\n+++ b/docs/units/constants_versions.rst\n@@ -0,0 +1,29 @@\n+Using prior versions of constants\n+*********************************\n+\n+By default, `astropy.units` are initialized upon first import to use\n+the current versions of `astropy.constants`. For units to initialize\n+properly to a prior version of constants, the constants versions must\n+be set before the first import of `astropy.units` or `astropy.constants`.\n+\n+This is accomplished using ScienceState classes in the top-level package.\n+Setting the prior versions at the start of a Python session will allow\n+consistent units, as follows:\n+\n+>>> import astropy\n+>>> astropy.physical_constants.set('codata2010') # doctest: +SKIP\n+<ScienceState physical_constants: 'codata2010'>\n+>>> astropy.astronomical_constants.set('iau2012') # doctest: +SKIP\n+<ScienceState astronomical_constants: 'iau2012'>\n+>>> import astropy.units as u\n+>>> import astropy.constants as const\n+>>> (const.M_sun / u.M_sun).to(u.dimensionless_unscaled) - 1 # doctest: +SKIP\n+<Quantity 0.>\n+>>> const.M_sun # doctest: +SKIP\n+ Name = Solar mass\n+ Value = 1.9891e+30\n+ Uncertainty = 5e+25\n+ Unit = kg\n+ Reference = Allen's Astrophysical Quantities 4th Ed.\n+\n+If `astropy.units` has already been imported, a RuntimeError is raised.\n",
"update": null
},
{
"path": "docs/units/index.rst",
"old_path": "a/docs/units/index.rst",
"new_path": "b/docs/units/index.rst",
"metadata": "diff --git a/docs/units/index.rst b/docs/units/index.rst\nindex 4267de423490..82a7d412d664 100644\n--- a/docs/units/index.rst\n+++ b/docs/units/index.rst\n@@ -165,6 +165,7 @@ Using `astropy.units`\n logarithmic_units\n format\n equivalencies\n+ constants_versions\n conversion\n \n See Also\n",
"update": null
}
] |
4.0
|
cfe7616626c00c3dc7a912c1f432c00d52dba8b0
|
[
"astropy/constants/tests/test_prior_version.py::test_e",
"astropy/constants/tests/test_prior_version.py::test_h",
"astropy/constants/tests/test_prior_version.py::test_c",
"astropy/constants/tests/test_prior_version.py::test_view",
"astropy/constants/tests/test_prior_version.py::test_b_wien",
"astropy/constants/tests/test_prior_version.py::test_g0",
"astropy/constants/tests/test_prior_version.py::test_copy",
"astropy/constants/tests/test_prior_version.py::test_unit"
] |
[
"astropy/constants/tests/test_sciencestate.py::test_previously_imported",
"astropy/constants/tests/test_prior_version.py::test_context_manager",
"astropy/constants/tests/test_sciencestate.py::test_version_match"
] |
[
{
"path": "docs/constants/index.rst",
"old_path": "a/docs/constants/index.rst",
"new_path": "b/docs/constants/index.rst",
"metadata": "diff --git a/docs/constants/index.rst b/docs/constants/index.rst\nindex de4e4709f2..d31aa1656a 100644\n--- a/docs/constants/index.rst\n+++ b/docs/constants/index.rst\n@@ -118,9 +118,57 @@ Union (IAU) are collected in modules with names like ``iau2012`` or ``iau2015``:\n Reference = IAU 2015 Resolution B 3\n \n The astronomical and physical constants are combined into modules with\n-names like ``astropyconst13`` and ``astropyconst20``. To temporarily set\n-constants to an older version (e.g., for regression testing), a context\n-manager is available as follows:\n+names like ``astropyconst13`` and ``astropyconst20`` for different versions.\n+However, importing these prior version modules directly will lead to\n+inconsistencies with other subpackages that have already imported\n+`astropy.constants`. Notably, `astropy.units` will have already used\n+the default version of constants. When using prior versions of the constants\n+in this manner, quantities should be constructed with constants instead of units.\n+\n+To ensure consistent use of a prior version of constants in other Astropy\n+packages (such as `astropy.units`) that import constants, the physical and\n+astronomical constants versions should be set via ScienceState classes.\n+These must be set before the first import of either `astropy.constants` or\n+`astropy.units`. For example, you can use the CODATA2010 physical constants and the\n+IAU 2012 astronomical constants:\n+\n+ >>> from astropy import physical_constants, astronomical_constants\n+ >>> physical_constants.set('codata2010') # doctest: +SKIP\n+ <ScienceState physical_constants: 'codata2010'>\n+ >>> physical_constants.get() # doctest: +SKIP\n+ 'codata2010'\n+ >>> astronomical_constants.set('iau2012') # doctest: +SKIP\n+ <ScienceState astronomical_constants: 'iau2012'>\n+ >>> astronomical_constants.get() # doctest: +SKIP\n+ 'iau2012'\n+\n+Then all other packages that import `astropy.constants` will self-consistently\n+initialize with that prior version of constants.\n+\n+The versions may also be set using values referring to the version modules:\n+\n+ >>> from astropy import physical_constants, astronomical_constants\n+ >>> physical_constants.set('astropyconst13') # doctest: +SKIP\n+ <ScienceState physical_constants: 'codata2010'>\n+ >>> physical_constants.get() # doctest: +SKIP\n+ 'codata2010'\n+ >>> astronomical_constants.set('astropyconst13') # doctest: +SKIP\n+ <ScienceState astronomical_constants: 'iau2012'>\n+ >>> astronomical_constants.get() # doctest: +SKIP\n+ 'iau2012'\n+\n+If either `astropy.constants` or `astropy.units` have already been imported, a\n+``RuntimeError`` will be raised.\n+\n+ >>> import astropy.units\n+ >>> from astropy import physical_constants, astronomical_constants\n+ >>> astronomical_constants.set('astropyconst13')\n+ Traceback (most recent call last):\n+ ...\n+ RuntimeError: astropy.units is already imported\n+\n+To temporarily set constants to an older version (e.g.,\n+for regression testing), a context manager is available, as follows:\n \n >>> from astropy import constants as const\n >>> with const.set_enabled_constants('astropyconst13'):\n@@ -137,11 +185,10 @@ manager is available as follows:\n Unit = J s\n Reference = CODATA 2014\n \n-.. warning::\n+The context manager may be used at any time in a Python session, but it\n+uses the prior version only for `astropy.constants`, and not for any\n+other subpackage such as `astropy.units`.\n \n- Units such as ``u.M_sun`` will use the current version of the\n- corresponding constant. When using prior versions of the constants,\n- quantities should be constructed with constants instead of units.\n \n .. note that if this section gets too long, it should be moved to a separate\n doc page - see the top of performance.inc.rst for the instructions on how to\n"
},
{
"path": "docs/units/constants_versions.rst",
"old_path": "/dev/null",
"new_path": "b/docs/units/constants_versions.rst",
"metadata": "diff --git a/docs/units/constants_versions.rst b/docs/units/constants_versions.rst\nnew file mode 100644\nindex 0000000000..4663b3257f\n--- /dev/null\n+++ b/docs/units/constants_versions.rst\n@@ -0,0 +1,29 @@\n+Using prior versions of constants\n+*********************************\n+\n+By default, `astropy.units` are initialized upon first import to use\n+the current versions of `astropy.constants`. For units to initialize\n+properly to a prior version of constants, the constants versions must\n+be set before the first import of `astropy.units` or `astropy.constants`.\n+\n+This is accomplished using ScienceState classes in the top-level package.\n+Setting the prior versions at the start of a Python session will allow\n+consistent units, as follows:\n+\n+>>> import astropy\n+>>> astropy.physical_constants.set('codata2010') # doctest: +SKIP\n+<ScienceState physical_constants: 'codata2010'>\n+>>> astropy.astronomical_constants.set('iau2012') # doctest: +SKIP\n+<ScienceState astronomical_constants: 'iau2012'>\n+>>> import astropy.units as u\n+>>> import astropy.constants as const\n+>>> (const.M_sun / u.M_sun).to(u.dimensionless_unscaled) - 1 # doctest: +SKIP\n+<Quantity 0.>\n+>>> const.M_sun # doctest: +SKIP\n+ Name = Solar mass\n+ Value = 1.9891e+30\n+ Uncertainty = 5e+25\n+ Unit = kg\n+ Reference = Allen's Astrophysical Quantities 4th Ed.\n+\n+If `astropy.units` has already been imported, a RuntimeError is raised.\n"
},
{
"path": "docs/units/index.rst",
"old_path": "a/docs/units/index.rst",
"new_path": "b/docs/units/index.rst",
"metadata": "diff --git a/docs/units/index.rst b/docs/units/index.rst\nindex 4267de4234..82a7d412d6 100644\n--- a/docs/units/index.rst\n+++ b/docs/units/index.rst\n@@ -165,6 +165,7 @@ Using `astropy.units`\n logarithmic_units\n format\n equivalencies\n+ constants_versions\n conversion\n \n See Also\n"
}
] |
{
"header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:",
"data": [
{
"type": "file",
"name": "astropy/constants/config.py"
}
]
}
|
diff --git a/docs/constants/index.rst b/docs/constants/index.rst
index de4e4709f2..d31aa1656a 100644
--- a/docs/constants/index.rst
+++ b/docs/constants/index.rst
@@ -118,9 +118,57 @@ Union (IAU) are collected in modules with names like ``iau2012`` or ``iau2015``:
Reference = IAU 2015 Resolution B 3
The astronomical and physical constants are combined into modules with
-names like ``astropyconst13`` and ``astropyconst20``. To temporarily set
-constants to an older version (e.g., for regression testing), a context
-manager is available as follows:
+names like ``astropyconst13`` and ``astropyconst20`` for different versions.
+However, importing these prior version modules directly will lead to
+inconsistencies with other subpackages that have already imported
+`astropy.constants`. Notably, `astropy.units` will have already used
+the default version of constants. When using prior versions of the constants
+in this manner, quantities should be constructed with constants instead of units.
+
+To ensure consistent use of a prior version of constants in other Astropy
+packages (such as `astropy.units`) that import constants, the physical and
+astronomical constants versions should be set via ScienceState classes.
+These must be set before the first import of either `astropy.constants` or
+`astropy.units`. For example, you can use the CODATA2010 physical constants and the
+IAU 2012 astronomical constants:
+
+ >>> from astropy import physical_constants, astronomical_constants
+ >>> physical_constants.set('codata2010') # doctest: +SKIP
+ <ScienceState physical_constants: 'codata2010'>
+ >>> physical_constants.get() # doctest: +SKIP
+ 'codata2010'
+ >>> astronomical_constants.set('iau2012') # doctest: +SKIP
+ <ScienceState astronomical_constants: 'iau2012'>
+ >>> astronomical_constants.get() # doctest: +SKIP
+ 'iau2012'
+
+Then all other packages that import `astropy.constants` will self-consistently
+initialize with that prior version of constants.
+
+The versions may also be set using values referring to the version modules:
+
+ >>> from astropy import physical_constants, astronomical_constants
+ >>> physical_constants.set('astropyconst13') # doctest: +SKIP
+ <ScienceState physical_constants: 'codata2010'>
+ >>> physical_constants.get() # doctest: +SKIP
+ 'codata2010'
+ >>> astronomical_constants.set('astropyconst13') # doctest: +SKIP
+ <ScienceState astronomical_constants: 'iau2012'>
+ >>> astronomical_constants.get() # doctest: +SKIP
+ 'iau2012'
+
+If either `astropy.constants` or `astropy.units` have already been imported, a
+``RuntimeError`` will be raised.
+
+ >>> import astropy.units
+ >>> from astropy import physical_constants, astronomical_constants
+ >>> astronomical_constants.set('astropyconst13')
+ Traceback (most recent call last):
+ ...
+ RuntimeError: astropy.units is already imported
+
+To temporarily set constants to an older version (e.g.,
+for regression testing), a context manager is available, as follows:
>>> from astropy import constants as const
>>> with const.set_enabled_constants('astropyconst13'):
@@ -137,11 +185,10 @@ manager is available as follows:
Unit = J s
Reference = CODATA 2014
-.. warning::
+The context manager may be used at any time in a Python session, but it
+uses the prior version only for `astropy.constants`, and not for any
+other subpackage such as `astropy.units`.
- Units such as ``u.M_sun`` will use the current version of the
- corresponding constant. When using prior versions of the constants,
- quantities should be constructed with constants instead of units.
.. note that if this section gets too long, it should be moved to a separate
doc page - see the top of performance.inc.rst for the instructions on how to
diff --git a/docs/units/constants_versions.rst b/docs/units/constants_versions.rst
new file mode 100644
index 0000000000..4663b3257f
--- /dev/null
+++ b/docs/units/constants_versions.rst
@@ -0,0 +1,29 @@
+Using prior versions of constants
+*********************************
+
+By default, `astropy.units` are initialized upon first import to use
+the current versions of `astropy.constants`. For units to initialize
+properly to a prior version of constants, the constants versions must
+be set before the first import of `astropy.units` or `astropy.constants`.
+
+This is accomplished using ScienceState classes in the top-level package.
+Setting the prior versions at the start of a Python session will allow
+consistent units, as follows:
+
+>>> import astropy
+>>> astropy.physical_constants.set('codata2010') # doctest: +SKIP
+<ScienceState physical_constants: 'codata2010'>
+>>> astropy.astronomical_constants.set('iau2012') # doctest: +SKIP
+<ScienceState astronomical_constants: 'iau2012'>
+>>> import astropy.units as u
+>>> import astropy.constants as const
+>>> (const.M_sun / u.M_sun).to(u.dimensionless_unscaled) - 1 # doctest: +SKIP
+<Quantity 0.>
+>>> const.M_sun # doctest: +SKIP
+ Name = Solar mass
+ Value = 1.9891e+30
+ Uncertainty = 5e+25
+ Unit = kg
+ Reference = Allen's Astrophysical Quantities 4th Ed.
+
+If `astropy.units` has already been imported, a RuntimeError is raised.
diff --git a/docs/units/index.rst b/docs/units/index.rst
index 4267de4234..82a7d412d6 100644
--- a/docs/units/index.rst
+++ b/docs/units/index.rst
@@ -165,6 +165,7 @@ Using `astropy.units`
logarithmic_units
format
equivalencies
+ constants_versions
conversion
See Also
If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:
[{'type': 'file', 'name': 'astropy/constants/config.py'}]
|
astropy/astropy
|
astropy__astropy-10632
|
https://github.com/astropy/astropy/pull/10632
|
diff --git a/CHANGES.rst b/CHANGES.rst
index 9b04db77f3ac..5a642df49854 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -144,6 +144,10 @@ astropy.utils
- ``get_free_space_in_dir`` now takes a new ``unit`` keyword and
``check_free_space_in_dir`` takes ``size`` defined as ``Quantity``. [#10627]
+- New ``astropy.utils.data.conf.allow_internet`` configuration item to
+ control downloading data from the Internet. Setting ``allow_internet=False``
+ is the same as ``remote_timeout=0``. Using ``remote_timeout=0`` to control
+ internet access will stop working in a future release. [#10632]
astropy.visualization
^^^^^^^^^^^^^^^^^^^^^
diff --git a/astropy/utils/data.py b/astropy/utils/data.py
index fcb5009f409f..0f7e8bf5aa1e 100644
--- a/astropy/utils/data.py
+++ b/astropy/utils/data.py
@@ -70,8 +70,12 @@ class Conf(_config.ConfigNamespace):
remote_timeout = _config.ConfigItem(
10.,
'Time to wait for remote data queries (in seconds). Set this to zero '
- 'to prevent any attempt to download anything.',
+ 'to prevent any attempt to download anything (this will stop working '
+ 'in a future release, use allow_internet=False instead).',
aliases=['astropy.coordinates.name_resolve.name_resolve_timeout'])
+ allow_internet = _config.ConfigItem(
+ True,
+ 'If False, prevents any attempt to download from Internet.')
compute_hash_block_size = _config.ConfigItem(
2 ** 16, # 64K
'Block size for computing file hashes.')
@@ -187,8 +191,7 @@ def get_readable_fileobj(name_or_obj, encoding=None, cache=False,
remote_timeout : float
Timeout for remote requests in seconds (default is the configurable
- `astropy.utils.data.Conf.remote_timeout`, which is 3s by default).
- Set this to zero to prevent any attempt at downloading.
+ `astropy.utils.data.Conf.remote_timeout`).
sources : list of str, optional
If provided, a list of URLs to try to obtain the file from. The
@@ -486,7 +489,7 @@ def get_pkg_data_fileobj(data_name, package=None, encoding=None, cache=True):
--------
get_pkg_data_contents : returns the contents of a file or url as a bytes object
get_pkg_data_filename : returns a local name for a file containing the data
- """
+ """ # noqa
datafn = _find_pkg_data_path(data_name, package=package)
if os.path.isdir(datafn):
@@ -550,9 +553,7 @@ def get_pkg_data_filename(data_name, package=None, show_progress=True,
remote_timeout : float
Timeout for the requests in seconds (default is the
- configurable `astropy.utils.data.Conf.remote_timeout`, which
- is 3s by default). Set this to zero to prevent any attempt
- at downloading.
+ configurable `astropy.utils.data.Conf.remote_timeout`).
Raises
------
@@ -998,8 +999,16 @@ def _download_file_from_source(source_url, show_progress=True, timeout=None,
if timeout == 0:
raise urllib.error.URLError(
f"URL {remote_url} was supposed to be downloaded but timeout was set to 0; "
- f"if this is unexpected check the astropy config file for the option "
- f"remote_timeout")
+ f"if this is unexpected check the astropy.cfg file for the option "
+ f"remote_timeout. If this is intentional, this will stop working "
+ f"in a future release. Use astropy.utils.data.conf.allow_internet=False instead.")
+
+ if not conf.allow_internet:
+ raise urllib.error.URLError(
+ f"URL {remote_url} was supposed to be downloaded but "
+ f"allow_internet is {conf.allow_internet}; "
+ f"if this is unexpected check the astropy.cfg file for the option "
+ f"allow_internet")
if remote_url is None:
remote_url = source_url
@@ -1120,9 +1129,8 @@ def download_file(remote_url, cache=False, show_progress=True, timeout=None,
displayed when outputting to a terminal.
timeout : float, optional
- The timeout, in seconds. Otherwise, use
- `astropy.utils.data.Conf.remote_timeout`. Set this to zero to prevent
- any attempt to download anything.
+ Timeout for remote requests in seconds (default is the configurable
+ `astropy.utils.data.Conf.remote_timeout`).
sources : list of str, optional
If provided, a list of URLs to try to obtain the file from. The
@@ -1356,8 +1364,7 @@ def download_files_in_parallel(urls,
timeout : float, optional
Timeout for each individual requests in seconds (default is the
- configurable `astropy.utils.data.Conf.remote_timeout`). Set this to
- zero to prevent any attempt to download anything.
+ configurable `astropy.utils.data.Conf.remote_timeout`).
sources : dict, optional
If provided, for each URL a list of URLs to try to obtain the
diff --git a/docs/utils/data.rst b/docs/utils/data.rst
index 6e94642ecaf2..578fc1659a42 100644
--- a/docs/utils/data.rst
+++ b/docs/utils/data.rst
@@ -257,7 +257,7 @@ therefore recommend the following guidelines:
not suddenly notice an out-of-date table all at once and frantically attempt
to download it.
- * Optionally, in this file, set ``astropy.utils.data.conf.remote_timeout = 0`` to
+ * Optionally, in this file, set ``astropy.utils.data.conf.allow_internet = False`` to
prevent any attempt to download any file from the worker nodes; if you do this,
you will need to override this setting in your script that does the actual
downloading.
|
diff --git a/astropy/utils/tests/test_data.py b/astropy/utils/tests/test_data.py
index 15b28eb3f356..88903fc097da 100644
--- a/astropy/utils/tests/test_data.py
+++ b/astropy/utils/tests/test_data.py
@@ -2061,6 +2061,17 @@ def test_zero_remote_timeout(temp_cache, valid_urls):
download_file(TESTURL, timeout=0)
+def test_no_allow_internet(temp_cache, valid_urls):
+ u, c = next(valid_urls)
+ with conf.set_temp('allow_internet', False):
+ with pytest.raises(urllib.error.URLError):
+ download_file(u)
+ assert not is_url_in_cache(u)
+ with pytest.raises(urllib.error.URLError):
+ # This will trigger the remote data error if it's allowed to touch the internet
+ download_file(TESTURL)
+
+
def test_clear_download_cache_not_too_aggressive(temp_cache, valid_urls):
u, c = next(valid_urls)
download_file(u, cache=True)
|
[
{
"path": "docs/utils/data.rst",
"old_path": "a/docs/utils/data.rst",
"new_path": "b/docs/utils/data.rst",
"metadata": "diff --git a/docs/utils/data.rst b/docs/utils/data.rst\nindex 6e94642ecaf2..578fc1659a42 100644\n--- a/docs/utils/data.rst\n+++ b/docs/utils/data.rst\n@@ -257,7 +257,7 @@ therefore recommend the following guidelines:\n not suddenly notice an out-of-date table all at once and frantically attempt\n to download it.\n \n- * Optionally, in this file, set ``astropy.utils.data.conf.remote_timeout = 0`` to\n+ * Optionally, in this file, set ``astropy.utils.data.conf.allow_internet = False`` to\n prevent any attempt to download any file from the worker nodes; if you do this,\n you will need to override this setting in your script that does the actual\n downloading.\n",
"update": null
}
] |
4.2
|
ca9677164c08c6695ba7d779efa5ba68cc0dbe1b
|
[
"astropy/utils/tests/test_data.py::test_download_parallel_with_empty_sources",
"astropy/utils/tests/test_data.py::test_update_parallel",
"astropy/utils/tests/test_data.py::test_download_file_schedules_deletion",
"astropy/utils/tests/test_data.py::test_get_fileobj_localpath",
"astropy/utils/tests/test_data.py::test_path_objects_get_readable_fileobj",
"astropy/utils/tests/test_data.py::test_download_file_wrong_size",
"astropy/utils/tests/test_data.py::test_nested_get_readable_fileobj",
"astropy/utils/tests/test_data.py::test_download_file_cache_fake_readonly",
"astropy/utils/tests/test_data.py::test_clear_download_cache_not_too_aggressive",
"astropy/utils/tests/test_data.py::test_get_pkg_data_contents",
"astropy/utils/tests/test_data.py::test_cache_relocatable",
"astropy/utils/tests/test_data.py::test_local_data_obj_invalid[invalid.dat.gz]",
"astropy/utils/tests/test_data.py::test_check_download_cache_finds_bogus_entries",
"astropy/utils/tests/test_data.py::test_clear_download_cache",
"astropy/utils/tests/test_data.py::test_export_import_roundtrip",
"astropy/utils/tests/test_data.py::test_export_import_roundtrip_different_location",
"astropy/utils/tests/test_data.py::test_domain_name_case",
"astropy/utils/tests/test_data.py::test_empty_url",
"astropy/utils/tests/test_data.py::test_pkgname_isolation",
"astropy/utils/tests/test_data.py::test_download_parallel_update",
"astropy/utils/tests/test_data.py::test_local_data_name",
"astropy/utils/tests/test_data.py::test_download_parallel_many",
"astropy/utils/tests/test_data.py::test_cache_dir_is_actually_a_file",
"astropy/utils/tests/test_data.py::test_get_fileobj_already_open_text",
"astropy/utils/tests/test_data.py::test_read_unicode[unicode.txt]",
"astropy/utils/tests/test_data.py::test_invalid_location_download_noconnect",
"astropy/utils/tests/test_data.py::test_download_parallel_partial_success_lock_safe",
"astropy/utils/tests/test_data.py::test_url_trailing_slash[http://example.com]",
"astropy/utils/tests/test_data.py::test_get_fileobj_pathlib",
"astropy/utils/tests/test_data.py::test_get_readable_fileobj_cleans_up_temporary_files",
"astropy/utils/tests/test_data.py::test_clear_download_multiple_references_doesnt_corrupt_storage",
"astropy/utils/tests/test_data.py::test_sources_fallback",
"astropy/utils/tests/test_data.py::test_get_fileobj_binary",
"astropy/utils/tests/test_data.py::test_sources_multiple",
"astropy/utils/tests/test_data.py::test_read_cache_fake_readonly",
"astropy/utils/tests/test_data.py::test_sources_multiple_missing",
"astropy/utils/tests/test_data.py::test_free_space_checker_huge[1000000000000000000]",
"astropy/utils/tests/test_data.py::test_read_unicode[unicode.txt.gz]",
"astropy/utils/tests/test_data.py::test_download_file_basic",
"astropy/utils/tests/test_data.py::test_get_free_space_file_directory",
"astropy/utils/tests/test_data.py::test_is_url_in_cache_local",
"astropy/utils/tests/test_data.py::test_threaded_segfault",
"astropy/utils/tests/test_data.py::test_sources_ignore_primary",
"astropy/utils/tests/test_data.py::test_download_parallel_partial_success",
"astropy/utils/tests/test_data.py::test_zero_remote_timeout",
"astropy/utils/tests/test_data.py::test_download_file_local_directory",
"astropy/utils/tests/test_data.py::test_download_file_threaded_many",
"astropy/utils/tests/test_data.py::test_local_data_obj[local.dat.gz]",
"astropy/utils/tests/test_data.py::test_data_name_third_party_package",
"astropy/utils/tests/test_data.py::test_download_file_cache_fake_readonly_cache_miss",
"astropy/utils/tests/test_data.py::test_download_file_local_cache_survives[False]",
"astropy/utils/tests/test_data.py::test_download_file_threaded_many_partial_success",
"astropy/utils/tests/test_data.py::test_export_import_roundtrip_stream",
"astropy/utils/tests/test_data.py::test_local_data_obj[local.dat]",
"astropy/utils/tests/test_data.py::test_download_parallel_with_sources_and_bogus_original",
"astropy/utils/tests/test_data.py::test_cache_size_changes_correctly_when_files_are_added_and_removed",
"astropy/utils/tests/test_data.py::test_clear_download_cache_refuses_to_delete_outside_the_cache",
"astropy/utils/tests/test_data.py::test_mkdtemp_cache_fake_readonly",
"astropy/utils/tests/test_data.py::test_download_file_cache_fake_readonly_update",
"astropy/utils/tests/test_data.py::test_get_fileobj_binary_already_open_binary",
"astropy/utils/tests/test_data.py::test_export_url_not_present",
"astropy/utils/tests/test_data.py::test_import_file_cache_fake_readonly",
"astropy/utils/tests/test_data.py::test_removal_of_open_files",
"astropy/utils/tests/test_data.py::test_import_one",
"astropy/utils/tests/test_data.py::test_cache_contents_agrees_with_get_urls",
"astropy/utils/tests/test_data.py::test_get_fileobj_already_open_binary",
"astropy/utils/tests/test_data.py::test_local_data_obj_invalid[invalid.dat.bz2]",
"astropy/utils/tests/test_data.py::test_read_unicode[unicode.txt.xz]",
"astropy/utils/tests/test_data.py::test_check_download_cache_finds_bogus_subentries",
"astropy/utils/tests/test_data.py::test_export_import_roundtrip_one",
"astropy/utils/tests/test_data.py::test_check_download_cache_cleanup",
"astropy/utils/tests/test_data.py::test_download_cache_after_clear",
"astropy/utils/tests/test_data.py::test_transport_cache_via_zip",
"astropy/utils/tests/test_data.py::test_download_cache_update_doesnt_damage_cache",
"astropy/utils/tests/test_data.py::test_download_with_sources_and_bogus_original[False]",
"astropy/utils/tests/test_data.py::test_compute_hash",
"astropy/utils/tests/test_data.py::test_download_file_absolute_path",
"astropy/utils/tests/test_data.py::test_find_by_hash",
"astropy/utils/tests/test_data.py::test_TD_cache_fake_readonly",
"astropy/utils/tests/test_data.py::test_update_parallel_multi",
"astropy/utils/tests/test_data.py::test_download_parallel_fills_cache[spawn]",
"astropy/utils/tests/test_data.py::test_cache_size_is_zero_when_empty",
"astropy/utils/tests/test_data.py::test_free_space_checker_huge[desired_size1]",
"astropy/utils/tests/test_data.py::test_read_unicode[unicode.txt.bz2]",
"astropy/utils/tests/test_data.py::test_unicode_url",
"astropy/utils/tests/test_data.py::test_sources_normal",
"astropy/utils/tests/test_data.py::test_update_url",
"astropy/utils/tests/test_data.py::test_clear_download_cache_variants",
"astropy/utils/tests/test_data.py::test_download_parallel_respects_pkgname",
"astropy/utils/tests/test_data.py::test_get_fileobj_str",
"astropy/utils/tests/test_data.py::test_export_overwrite_flag_works",
"astropy/utils/tests/test_data.py::test_download_file_local_cache_survives[True]",
"astropy/utils/tests/test_data.py::test_compressed_stream",
"astropy/utils/tests/test_data.py::test_check_download_cache_works_if_fake_readonly",
"astropy/utils/tests/test_data.py::test_download_with_sources_and_bogus_original[True]",
"astropy/utils/tests/test_data.py::test_local_data_obj[local.dat.xz]",
"astropy/utils/tests/test_data.py::test_local_data_nonlocalfail",
"astropy/utils/tests/test_data.py::test_check_download_cache",
"astropy/utils/tests/test_data.py::test_temp_cache",
"astropy/utils/tests/test_data.py::test_download_file_bogus_settings",
"astropy/utils/tests/test_data.py::test_update_of_open_files",
"astropy/utils/tests/test_data.py::test_case_collision",
"astropy/utils/tests/test_data.py::test_too_long_url",
"astropy/utils/tests/test_data.py::test_local_data_obj[local.dat.bz2]",
"astropy/utils/tests/test_data.py::test_cache_contents_not_writable",
"astropy/utils/tests/test_data.py::test_download_parallel_fills_cache[None]",
"astropy/utils/tests/test_data.py::test_url_trailing_slash[https://example.com]"
] |
[
"astropy/utils/tests/test_data.py::test_no_allow_internet"
] |
[
{
"path": "docs/utils/data.rst",
"old_path": "a/docs/utils/data.rst",
"new_path": "b/docs/utils/data.rst",
"metadata": "diff --git a/docs/utils/data.rst b/docs/utils/data.rst\nindex 6e94642eca..578fc1659a 100644\n--- a/docs/utils/data.rst\n+++ b/docs/utils/data.rst\n@@ -257,7 +257,7 @@ therefore recommend the following guidelines:\n not suddenly notice an out-of-date table all at once and frantically attempt\n to download it.\n \n- * Optionally, in this file, set ``astropy.utils.data.conf.remote_timeout = 0`` to\n+ * Optionally, in this file, set ``astropy.utils.data.conf.allow_internet = False`` to\n prevent any attempt to download any file from the worker nodes; if you do this,\n you will need to override this setting in your script that does the actual\n downloading.\n"
}
] |
{
"header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:",
"data": []
}
|
diff --git a/docs/utils/data.rst b/docs/utils/data.rst
index 6e94642eca..578fc1659a 100644
--- a/docs/utils/data.rst
+++ b/docs/utils/data.rst
@@ -257,7 +257,7 @@ therefore recommend the following guidelines:
not suddenly notice an out-of-date table all at once and frantically attempt
to download it.
- * Optionally, in this file, set ``astropy.utils.data.conf.remote_timeout = 0`` to
+ * Optionally, in this file, set ``astropy.utils.data.conf.allow_internet = False`` to
prevent any attempt to download any file from the worker nodes; if you do this,
you will need to override this setting in your script that does the actual
downloading.
|
astropy/astropy
|
astropy__astropy-11638
|
https://github.com/astropy/astropy/pull/11638
|
diff --git a/astropy/time/core.py b/astropy/time/core.py
index 0cc559ccce14..44deaf7e175f 100644
--- a/astropy/time/core.py
+++ b/astropy/time/core.py
@@ -545,6 +545,11 @@ def _set_scale(self, scale):
raise ValueError("Scale {!r} is not in the allowed scales {}"
.format(scale, sorted(self.SCALES)))
+ if scale == 'utc' or self.scale == 'utc':
+ # If doing a transform involving UTC then check that the leap
+ # seconds table is up to date.
+ _check_leapsec()
+
# Determine the chain of scale transformations to get from the current
# scale to the new scale. MULTI_HOPS contains a dict of all
# transformations (xforms) that require intermediate xforms.
@@ -1484,27 +1489,6 @@ def __new__(cls, val, val2=None, format=None, scale=None,
precision=None, in_subfmt=None, out_subfmt=None,
location=None, copy=False):
- # Because of import problems, this can only be done on
- # first call of Time. The initialization is complicated because
- # update_leap_seconds uses Time.
- # In principle, this may cause wrong leap seconds in
- # update_leap_seconds itself, but since expiration is in
- # units of days, that is fine.
- global _LEAP_SECONDS_CHECK
- if _LEAP_SECONDS_CHECK != _LeapSecondsCheck.DONE:
- with _LEAP_SECONDS_LOCK:
- # There are three ways we can get here:
- # 1. First call (NOT_STARTED).
- # 2. Re-entrant call (RUNNING). We skip the initialisation
- # and don't worry about leap second errors.
- # 3. Another thread which raced with the first call
- # (RUNNING). The first thread has relinquished the
- # lock to us, so initialization is complete.
- if _LEAP_SECONDS_CHECK == _LeapSecondsCheck.NOT_STARTED:
- _LEAP_SECONDS_CHECK = _LeapSecondsCheck.RUNNING
- update_leap_seconds()
- _LEAP_SECONDS_CHECK = _LeapSecondsCheck.DONE
-
if isinstance(val, Time):
self = val.replicate(format=format, copy=copy, cls=cls)
else:
@@ -2654,6 +2638,24 @@ def __init__(self, left, right, op=None):
right.__class__.__name__))
+def _check_leapsec():
+ global _LEAP_SECONDS_CHECK
+ if _LEAP_SECONDS_CHECK != _LeapSecondsCheck.DONE:
+ from astropy.utils import iers
+ with _LEAP_SECONDS_LOCK:
+ # There are three ways we can get here:
+ # 1. First call (NOT_STARTED).
+ # 2. Re-entrant call (RUNNING). We skip the initialisation
+ # and don't worry about leap second errors.
+ # 3. Another thread which raced with the first call
+ # (RUNNING). The first thread has relinquished the
+ # lock to us, so initialization is complete.
+ if _LEAP_SECONDS_CHECK == _LeapSecondsCheck.NOT_STARTED:
+ _LEAP_SECONDS_CHECK = _LeapSecondsCheck.RUNNING
+ update_leap_seconds()
+ _LEAP_SECONDS_CHECK = _LeapSecondsCheck.DONE
+
+
def update_leap_seconds(files=None):
"""If the current ERFA leap second table is out of date, try to update it.
diff --git a/astropy/utils/iers/iers.py b/astropy/utils/iers/iers.py
index 01a4717503b6..704e724ea205 100644
--- a/astropy/utils/iers/iers.py
+++ b/astropy/utils/iers/iers.py
@@ -881,6 +881,11 @@ class LeapSeconds(QTable):
``iers.LEAP_SECONDS_LIST_URL``. Many systems also store a version
of ``leap-seconds.list`` for use with ``ntp`` (e.g., on Debian/Ubuntu
systems, ``/usr/share/zoneinfo/leap-seconds.list``).
+
+ To prevent querying internet resources if the available local leap second
+ file(s) are out of date, set ``iers.conf.auto_download = False``. This
+ must be done prior to performing any ``Time`` scale transformations related
+ to UTC (e.g. converting from UTC to TAI).
"""
# Note: Time instances in this class should use scale='tai' to avoid
# needing leap seconds in their creation or interpretation.
diff --git a/docs/changes/utils/11638.feature.rst b/docs/changes/utils/11638.feature.rst
new file mode 100644
index 000000000000..656f0b38f95b
--- /dev/null
+++ b/docs/changes/utils/11638.feature.rst
@@ -0,0 +1,8 @@
+Change the Time and IERS leap second handling so that the leap second table is
+updated only when a Time transform involving UTC is performed. Previously this
+update check was done the first time a ``Time`` object was created, which in
+practice occured when importing common astropy subpackages like
+``astropy.coordinates``. Now you can prevent querying internet resources (for
+instance on a cluster) by setting ``iers.conf.auto_download = False``. This can
+be done after importing astrpoy but prior to performing any ``Time`` scale
+transformations related to UTC.
diff --git a/docs/utils/iers.rst b/docs/utils/iers.rst
index 57d136e0e2a9..92e6b12ce28b 100644
--- a/docs/utils/iers.rst
+++ b/docs/utils/iers.rst
@@ -76,8 +76,9 @@ of the automatic IERS downloading:
auto_download:
Enable auto-downloading of the latest IERS data. If set to ``False`` then
the local IERS-B file will be used by default (even if the full IERS file
- with predictions was already downloaded and cached). This replicates the
- behavior prior to astropy 1.2. (default=True)
+ with predictions was already downloaded and cached). This parameter also
+ controls whether internet resources will be queried to update the leap
+ second table if the installed version is out of date.
auto_max_age:
Maximum age of predictive data before auto-downloading (days). See
|
diff --git a/astropy/timeseries/tests/test_downsample.py b/astropy/timeseries/tests/test_downsample.py
index 067561b774e2..36b5e644f3cf 100644
--- a/astropy/timeseries/tests/test_downsample.py
+++ b/astropy/timeseries/tests/test_downsample.py
@@ -12,8 +12,6 @@
INPUT_TIME = Time(['2016-03-22T12:30:31', '2016-03-22T12:30:32',
'2016-03-22T12:30:33', '2016-03-22T12:30:34'])
-ts = TimeSeries(time=INPUT_TIME, data=[[1, 2, 3, 4]], names=['a'])
-ts_units = TimeSeries(time=INPUT_TIME, data=[[1, 2, 3, 4] * u.count], names=['a'])
def test_reduceat():
@@ -41,6 +39,9 @@ def test_timeseries_invalid():
def test_downsample():
+ ts = TimeSeries(time=INPUT_TIME, data=[[1, 2, 3, 4]], names=['a'])
+ ts_units = TimeSeries(time=INPUT_TIME, data=[[1, 2, 3, 4] * u.count], names=['a'])
+
down_1 = aggregate_downsample(ts, time_bin_size=1*u.second)
u.isclose(down_1.time_bin_size, [1, 1, 1, 1]*u.second)
assert_equal(down_1.time_bin_start.isot, Time(['2016-03-22T12:30:31.000', '2016-03-22T12:30:32.000',
diff --git a/astropy/utils/iers/tests/test_leap_second.py b/astropy/utils/iers/tests/test_leap_second.py
index d9c86033f950..19981d3aa18c 100644
--- a/astropy/utils/iers/tests/test_leap_second.py
+++ b/astropy/utils/iers/tests/test_leap_second.py
@@ -12,7 +12,26 @@
from astropy.time import Time, TimeDelta
from astropy.utils.iers import iers
from astropy.utils.data import get_pkg_data_filename
-
+from astropy.tests.tests.test_imports import test_imports
+
+# Import every top-level astropy module as a test that the ERFA leap second
+# table is not updated for normal imports.
+test_imports()
+
+# Now test that the erfa leap_seconds table has not been udpated. This must be
+# done at the module level, which unfortunately will abort the entire test run
+# if if fails. Running within a normal pytest test will not work because the
+# other tests will end up updating this attribute by virtue of doing Time UTC
+# transformations.
+assert erfa.leap_seconds._expires is None
+
+# Tests in this module assume that the erfa.leap_seconds attribute has been
+# updated from the `erfa` package built-in table to the astropy built-in
+# leap-second table. That has the effect of ensuring that the
+# `erfa.leap_seconds.expires` property is sufficiently in the future.
+iers_table = iers.LeapSeconds.auto_open()
+erfa.leap_seconds.update(iers_table)
+assert erfa.leap_seconds._expires is not None
SYSTEM_FILE = '/usr/share/zoneinfo/leap-seconds.list'
|
[
{
"path": "docs/changes/utils/11638.feature.rst",
"old_path": "/dev/null",
"new_path": "b/docs/changes/utils/11638.feature.rst",
"metadata": "diff --git a/docs/changes/utils/11638.feature.rst b/docs/changes/utils/11638.feature.rst\nnew file mode 100644\nindex 000000000000..656f0b38f95b\n--- /dev/null\n+++ b/docs/changes/utils/11638.feature.rst\n@@ -0,0 +1,8 @@\n+Change the Time and IERS leap second handling so that the leap second table is\n+updated only when a Time transform involving UTC is performed. Previously this\n+update check was done the first time a ``Time`` object was created, which in\n+practice occured when importing common astropy subpackages like\n+``astropy.coordinates``. Now you can prevent querying internet resources (for\n+instance on a cluster) by setting ``iers.conf.auto_download = False``. This can\n+be done after importing astrpoy but prior to performing any ``Time`` scale\n+transformations related to UTC.\n",
"update": null
},
{
"path": "docs/utils/iers.rst",
"old_path": "a/docs/utils/iers.rst",
"new_path": "b/docs/utils/iers.rst",
"metadata": "diff --git a/docs/utils/iers.rst b/docs/utils/iers.rst\nindex 57d136e0e2a9..92e6b12ce28b 100644\n--- a/docs/utils/iers.rst\n+++ b/docs/utils/iers.rst\n@@ -76,8 +76,9 @@ of the automatic IERS downloading:\n auto_download:\n Enable auto-downloading of the latest IERS data. If set to ``False`` then\n the local IERS-B file will be used by default (even if the full IERS file\n- with predictions was already downloaded and cached). This replicates the\n- behavior prior to astropy 1.2. (default=True)\n+ with predictions was already downloaded and cached). This parameter also\n+ controls whether internet resources will be queried to update the leap\n+ second table if the installed version is out of date.\n \n auto_max_age:\n Maximum age of predictive data before auto-downloading (days). See\n",
"update": null
}
] |
4.3
|
dfa48c3d9b6ea3988754067b7ee4678b0e7348c9
|
[] |
[
"astropy/timeseries/tests/test_downsample.py::test_timeseries_invalid",
"astropy/timeseries/tests/test_downsample.py::test_reduceat"
] |
[
{
"path": "docs/changes/utils/#####.feature.rst",
"old_path": "/dev/null",
"new_path": "b/docs/changes/utils/#####.feature.rst",
"metadata": "diff --git a/docs/changes/utils/#####.feature.rst b/docs/changes/utils/#####.feature.rst\nnew file mode 100644\nindex 0000000000..656f0b38f9\n--- /dev/null\n+++ b/docs/changes/utils/#####.feature.rst\n@@ -0,0 +1,8 @@\n+Change the Time and IERS leap second handling so that the leap second table is\n+updated only when a Time transform involving UTC is performed. Previously this\n+update check was done the first time a ``Time`` object was created, which in\n+practice occured when importing common astropy subpackages like\n+``astropy.coordinates``. Now you can prevent querying internet resources (for\n+instance on a cluster) by setting ``iers.conf.auto_download = False``. This can\n+be done after importing astrpoy but prior to performing any ``Time`` scale\n+transformations related to UTC.\n"
},
{
"path": "docs/utils/iers.rst",
"old_path": "a/docs/utils/iers.rst",
"new_path": "b/docs/utils/iers.rst",
"metadata": "diff --git a/docs/utils/iers.rst b/docs/utils/iers.rst\nindex 57d136e0e2..92e6b12ce2 100644\n--- a/docs/utils/iers.rst\n+++ b/docs/utils/iers.rst\n@@ -76,8 +76,9 @@ of the automatic IERS downloading:\n auto_download:\n Enable auto-downloading of the latest IERS data. If set to ``False`` then\n the local IERS-B file will be used by default (even if the full IERS file\n- with predictions was already downloaded and cached). This replicates the\n- behavior prior to astropy 1.2. (default=True)\n+ with predictions was already downloaded and cached). This parameter also\n+ controls whether internet resources will be queried to update the leap\n+ second table if the installed version is out of date.\n \n auto_max_age:\n Maximum age of predictive data before auto-downloading (days). See\n"
}
] |
{
"header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:",
"data": []
}
|
diff --git a/docs/changes/utils/#####.feature.rst b/docs/changes/utils/#####.feature.rst
new file mode 100644
index 0000000000..656f0b38f9
--- /dev/null
+++ b/docs/changes/utils/#####.feature.rst
@@ -0,0 +1,8 @@
+Change the Time and IERS leap second handling so that the leap second table is
+updated only when a Time transform involving UTC is performed. Previously this
+update check was done the first time a ``Time`` object was created, which in
+practice occured when importing common astropy subpackages like
+``astropy.coordinates``. Now you can prevent querying internet resources (for
+instance on a cluster) by setting ``iers.conf.auto_download = False``. This can
+be done after importing astrpoy but prior to performing any ``Time`` scale
+transformations related to UTC.
diff --git a/docs/utils/iers.rst b/docs/utils/iers.rst
index 57d136e0e2..92e6b12ce2 100644
--- a/docs/utils/iers.rst
+++ b/docs/utils/iers.rst
@@ -76,8 +76,9 @@ of the automatic IERS downloading:
auto_download:
Enable auto-downloading of the latest IERS data. If set to ``False`` then
the local IERS-B file will be used by default (even if the full IERS file
- with predictions was already downloaded and cached). This replicates the
- behavior prior to astropy 1.2. (default=True)
+ with predictions was already downloaded and cached). This parameter also
+ controls whether internet resources will be queried to update the leap
+ second table if the installed version is out of date.
auto_max_age:
Maximum age of predictive data before auto-downloading (days). See
|
astropy/astropy
|
astropy__astropy-11788
|
https://github.com/astropy/astropy/pull/11788
|
diff --git a/astropy/units/si.py b/astropy/units/si.py
index f2bebef5a60f..1e8f96e8365d 100644
--- a/astropy/units/si.py
+++ b/astropy/units/si.py
@@ -34,6 +34,7 @@
def_unit(['Angstrom', 'AA', 'angstrom'], 0.1 * nm, namespace=_ns,
doc="ångström: 10 ** -10 m",
+ prefixes=[(['m', 'milli'], ['milli', 'm'], 1.e-3)],
format={'latex': r'\mathring{A}', 'unicode': 'Å',
'vounit': 'Angstrom'})
diff --git a/docs/changes/units/11788.feature.rst b/docs/changes/units/11788.feature.rst
new file mode 100644
index 000000000000..8431c639a324
--- /dev/null
+++ b/docs/changes/units/11788.feature.rst
@@ -0,0 +1,1 @@
+The milli- prefix has been added to ``astropy.units.Angstrom``.
diff --git a/docs/units/format.rst b/docs/units/format.rst
index 90d85c50d387..1d83f2496fef 100644
--- a/docs/units/format.rst
+++ b/docs/units/format.rst
@@ -273,11 +273,11 @@ particular alias is used::
>>> u.Unit("Angstroem") == u.Angstrom
Traceback (most recent call last):
...
- ValueError: 'Angstroem' did not parse as unit: At col 0, Angstroem is not a
- valid unit. Did you mean Angstrom or angstrom? If this is meant to be a
- custom unit, define it with 'u.def_unit'. To have it recognized inside a
- file reader or other code, enable it with 'u.add_enabled_units'. For
- details, see
+ ValueError: 'Angstroem' did not parse as unit: At col 0, Angstroem is not
+ a valid unit. Did you mean Angstrom, angstrom, mAngstrom or mangstrom? If
+ this is meant to be a custom unit, define it with 'u.def_unit'. To have it
+ recognized inside a file reader or other code, enable it with
+ 'u.add_enabled_units'. For details, see
https://docs.astropy.org/en/latest/units/combining_and_defining.html
.. EXAMPLE END
|
diff --git a/astropy/units/tests/test_format.py b/astropy/units/tests/test_format.py
index bae51be43848..7c2816360c29 100644
--- a/astropy/units/tests/test_format.py
+++ b/astropy/units/tests/test_format.py
@@ -606,6 +606,7 @@ def test_powers(power, expected):
('\N{ANGSTROM SIGN} \N{OHM SIGN}', u.Angstrom * u.Ohm),
('\N{LATIN CAPITAL LETTER A WITH RING ABOVE}', u.Angstrom),
('\N{LATIN CAPITAL LETTER A}\N{COMBINING RING ABOVE}', u.Angstrom),
+ ('m\N{ANGSTROM SIGN}', u.milliAngstrom),
('°C', u.deg_C),
('°', u.deg),
])
@@ -620,7 +621,7 @@ def test_unicode(string, unit):
'm\N{SUPERSCRIPT MINUS}1',
'm+\N{SUPERSCRIPT ONE}',
'm\N{MINUS SIGN}\N{SUPERSCRIPT ONE}',
- 'm\N{ANGSTROM SIGN}',
+ 'k\N{ANGSTROM SIGN}',
])
def test_unicode_failures(string):
with pytest.raises(ValueError):
diff --git a/astropy/units/tests/test_units.py b/astropy/units/tests/test_units.py
index 83ab11a8932e..a044243187dd 100644
--- a/astropy/units/tests/test_units.py
+++ b/astropy/units/tests/test_units.py
@@ -639,7 +639,7 @@ def test_suggestions():
('metre', 'meter'),
('angstroms', 'Angstrom or angstrom'),
('milimeter', 'millimeter'),
- ('ångström', 'Angstrom or angstrom'),
+ ('ångström', 'Angstrom, angstrom, mAngstrom or mangstrom'),
('kev', 'EV, eV, kV or keV')]:
with pytest.raises(ValueError, match=f'Did you mean {matches}'):
u.Unit(search)
|
[
{
"path": "docs/changes/units/11788.feature.rst",
"old_path": "/dev/null",
"new_path": "b/docs/changes/units/11788.feature.rst",
"metadata": "diff --git a/docs/changes/units/11788.feature.rst b/docs/changes/units/11788.feature.rst\nnew file mode 100644\nindex 000000000000..8431c639a324\n--- /dev/null\n+++ b/docs/changes/units/11788.feature.rst\n@@ -0,0 +1,1 @@\n+The milli- prefix has been added to ``astropy.units.Angstrom``.\n",
"update": null
},
{
"path": "docs/units/format.rst",
"old_path": "a/docs/units/format.rst",
"new_path": "b/docs/units/format.rst",
"metadata": "diff --git a/docs/units/format.rst b/docs/units/format.rst\nindex 90d85c50d387..1d83f2496fef 100644\n--- a/docs/units/format.rst\n+++ b/docs/units/format.rst\n@@ -273,11 +273,11 @@ particular alias is used::\n >>> u.Unit(\"Angstroem\") == u.Angstrom\n Traceback (most recent call last):\n ...\n- ValueError: 'Angstroem' did not parse as unit: At col 0, Angstroem is not a\n- valid unit. Did you mean Angstrom or angstrom? If this is meant to be a\n- custom unit, define it with 'u.def_unit'. To have it recognized inside a\n- file reader or other code, enable it with 'u.add_enabled_units'. For\n- details, see\n+ ValueError: 'Angstroem' did not parse as unit: At col 0, Angstroem is not\n+ a valid unit. Did you mean Angstrom, angstrom, mAngstrom or mangstrom? If\n+ this is meant to be a custom unit, define it with 'u.def_unit'. To have it\n+ recognized inside a file reader or other code, enable it with\n+ 'u.add_enabled_units'. For details, see\n https://docs.astropy.org/en/latest/units/combining_and_defining.html\n \n .. EXAMPLE END\n",
"update": null
}
] |
5.0
|
99ab72daf324c481e4b1a241c091d9c6faca3c5c
|
[
"astropy/units/tests/test_units.py::test_compose_roundtrip[%]",
"astropy/units/tests/test_units.py::test_compose_roundtrip[W]",
"astropy/units/tests/test_units.py::test_compose_si_to_cgs[t]",
"astropy/units/tests/test_units.py::test_compose_roundtrip[Bq]",
"astropy/units/tests/test_units.py::test_compose_si_to_cgs[fortnight]",
"astropy/units/tests/test_units.py::test_decompose_to_cgs",
"astropy/units/tests/test_units.py::test_invalid_type",
"astropy/units/tests/test_units.py::test_long_int",
"astropy/units/tests/test_units.py::test_compose_cgs_to_si[K]",
"astropy/units/tests/test_units.py::test_compare_with_none",
"astropy/units/tests/test_units.py::test_compose_roundtrip[AB]",
"astropy/units/tests/test_units.py::test_compose_roundtrip[Ry]",
"astropy/units/tests/test_units.py::test_compose_cgs_to_si[rad]",
"astropy/units/tests/test_units.py::test_compose_roundtrip[solRad]",
"astropy/units/tests/test_units.py::test_compose_si_to_cgs[N]",
"astropy/units/tests/test_units.py::test_compose_si_to_cgs[sr]",
"astropy/units/tests/test_units.py::test_compose_cgs_to_si[Fr]",
"astropy/units/tests/test_units.py::test_compose_roundtrip[mag]",
"astropy/units/tests/test_units.py::test_compose_roundtrip[mol]",
"astropy/units/tests/test_units.py::test_compose_cgs_to_si[g]",
"astropy/units/tests/test_units.py::test_compose_cgs_to_si[statA]",
"astropy/units/tests/test_units.py::test_compose_roundtrip[mas]",
"astropy/units/tests/test_units.py::test_compose_roundtrip[uas]",
"astropy/units/tests/test_units.py::test_compose_roundtrip[erg]",
"astropy/units/tests/test_units.py::test_compose_roundtrip[Bi]",
"astropy/units/tests/test_units.py::test_compose_roundtrip[Jy]",
"astropy/units/tests/test_units.py::test_compose_si_to_cgs[a]",
"astropy/units/tests/test_units.py::test_sqrt_mag",
"astropy/units/tests/test_units.py::test_compose_no_duplicates",
"astropy/units/tests/test_units.py::test_compose_cgs_to_si[Gal]",
"astropy/units/tests/test_units.py::test_compose_roundtrip[mgy]",
"astropy/units/tests/test_units.py::test_fits_hst_unit",
"astropy/units/tests/test_units.py::test_compose_roundtrip[ST]",
"astropy/units/tests/test_units.py::test_compose_si_to_cgs[W]",
"astropy/units/tests/test_units.py::test_multiple_solidus",
"astropy/units/tests/test_units.py::test_radian_base",
"astropy/units/tests/test_units.py::test_compose_si_to_cgs[kg]",
"astropy/units/tests/test_units.py::test_compose_cgs_to_si[k]",
"astropy/units/tests/test_units.py::test_compose_si_to_cgs[sday]",
"astropy/units/tests/test_units.py::test_compose_roundtrip[h]",
"astropy/units/tests/test_units.py::test_initialisation",
"astropy/units/tests/test_units.py::test_compose_si_to_cgs[g]",
"astropy/units/tests/test_units.py::test_compose_roundtrip[jupiterRad]",
"astropy/units/tests/test_units.py::test_self_compose",
"astropy/units/tests/test_units.py::test_units_conversion",
"astropy/units/tests/test_units.py::test_compose_roundtrip[arcmin]",
"astropy/units/tests/test_units.py::test_compose_cgs_to_si[cd]",
"astropy/units/tests/test_units.py::test_compose_si_to_cgs[d]",
"astropy/units/tests/test_units.py::test_dimensionless_to_cgs",
"astropy/units/tests/test_units.py::test_compose_roundtrip[Bol]",
"astropy/units/tests/test_units.py::test_dimensionless_to_si",
"astropy/units/tests/test_units.py::test_unicode_policy",
"astropy/units/tests/test_units.py::test_compose_roundtrip[Fr]",
"astropy/units/tests/test_units.py::test_compose_si_to_cgs[Pa]",
"astropy/units/tests/test_units.py::test_compose_prefix_unit",
"astropy/units/tests/test_units.py::test_compose_roundtrip[earthMass]",
"astropy/units/tests/test_units.py::test_compose_fractional_powers",
"astropy/units/tests/test_units.py::test_no_as",
"astropy/units/tests/test_units.py::test_compose_roundtrip[electron]",
"astropy/units/tests/test_units.py::test_convertible_exception2",
"astropy/units/tests/test_units.py::test_barn_prefixes",
"astropy/units/tests/test_units.py::test_compose_si_to_cgs[S]",
"astropy/units/tests/test_units.py::test_compose_roundtrip[statA]",
"astropy/units/tests/test_units.py::test_empty_compose",
"astropy/units/tests/test_units.py::test_invalid_power",
"astropy/units/tests/test_units.py::test_invalid_compare",
"astropy/units/tests/test_units.py::test_compose_si_to_cgs[rad]",
"astropy/units/tests/test_units.py::test_unknown_unit3",
"astropy/units/tests/test_units.py::test_compose_roundtrip[kg]",
"astropy/units/tests/test_units.py::test_compose_roundtrip[deg_C]",
"astropy/units/tests/test_units.py::test_raise_to_negative_power",
"astropy/units/tests/test_units.py::test_compose_si_to_cgs[wk]",
"astropy/units/tests/test_units.py::test_compose_si_to_cgs[uas]",
"astropy/units/tests/test_units.py::test_compose_roundtrip[Ci]",
"astropy/units/tests/test_units.py::test_compose_si_to_cgs[Ci]",
"astropy/units/tests/test_units.py::test_compose_roundtrip[A]",
"astropy/units/tests/test_units.py::test_compose_roundtrip[N]",
"astropy/units/tests/test_units.py::test_compose_si_to_cgs[micron]",
"astropy/units/tests/test_units.py::test_compose_roundtrip[g]",
"astropy/units/tests/test_units.py::test_compose_roundtrip[bar]",
"astropy/units/tests/test_units.py::test_compose_cgs_to_si[Bi]",
"astropy/units/tests/test_units.py::test_compose_si_to_cgs[Bq]",
"astropy/units/tests/test_units.py::test_compose_cgs_to_si[abC]",
"astropy/units/tests/test_units.py::test_compose_roundtrip[Sun]",
"astropy/units/tests/test_units.py::test_decompose",
"astropy/units/tests/test_units.py::test_compose_roundtrip[a]",
"astropy/units/tests/test_units.py::test_compose_roundtrip[ct]",
"astropy/units/tests/test_units.py::test_compose_roundtrip[s]",
"astropy/units/tests/test_units.py::test_compose_roundtrip[cd]",
"astropy/units/tests/test_units.py::test_compose_roundtrip[cm]",
"astropy/units/tests/test_units.py::test_in_units",
"astropy/units/tests/test_units.py::test_invalid_scale",
"astropy/units/tests/test_units.py::test_repr_latex",
"astropy/units/tests/test_units.py::test_repr",
"astropy/units/tests/test_units.py::test_compose_roundtrip[t]",
"astropy/units/tests/test_units.py::test_compose_si_to_cgs[arcsec]",
"astropy/units/tests/test_units.py::test_fractional_rounding_errors_simple",
"astropy/units/tests/test_units.py::test_compose_si_to_cgs[mas]",
"astropy/units/tests/test_units.py::test_units_manipulation",
"astropy/units/tests/test_units.py::test_convertible_exception",
"astropy/units/tests/test_units.py::test_compose_roundtrip[beam]",
"astropy/units/tests/test_units.py::test_compose_roundtrip[sday]",
"astropy/units/tests/test_units.py::test_compose_cgs_to_si[St]",
"astropy/units/tests/test_units.py::test_compose_si_to_cgs[H]",
"astropy/units/tests/test_units.py::test_complex_compose",
"astropy/units/tests/test_units.py::test_no_duplicates_in_names",
"astropy/units/tests/test_units.py::test_compose_si_to_cgs[mol]",
"astropy/units/tests/test_units.py::test_convert_fail",
"astropy/units/tests/test_units.py::test_compose_roundtrip[chan]",
"astropy/units/tests/test_units.py::test_compose_roundtrip[cycle]",
"astropy/units/tests/test_units.py::test_all_units",
"astropy/units/tests/test_units.py::test_compose_roundtrip[P]",
"astropy/units/tests/test_units.py::test_complex_fractional_rounding_errors",
"astropy/units/tests/test_units.py::test_compose_si_to_cgs[K]",
"astropy/units/tests/test_units.py::test_compose_roundtrip[u]",
"astropy/units/tests/test_units.py::test_compose_roundtrip[micron]",
"astropy/units/tests/test_units.py::test_compose_roundtrip[bin]",
"astropy/units/tests/test_units.py::test_compose_roundtrip[Ohm]",
"astropy/units/tests/test_units.py::test_decompose_bases",
"astropy/units/tests/test_units.py::test_compose_roundtrip[dex]",
"astropy/units/tests/test_units.py::test_compose_roundtrip[solMass]",
"astropy/units/tests/test_units.py::test_compose_roundtrip[arcsec]",
"astropy/units/tests/test_units.py::test_compose_si_to_cgs[F]",
"astropy/units/tests/test_units.py::test_compose_si_to_cgs[hourangle]",
"astropy/units/tests/test_units.py::test_pickle_unrecognized_unit",
"astropy/units/tests/test_units.py::test_compose_roundtrip[lyr]",
"astropy/units/tests/test_units.py::test_compose_roundtrip[]",
"astropy/units/tests/test_units.py::test_compose_roundtrip[Hz]",
"astropy/units/tests/test_units.py::test_unrecognized_equivalency",
"astropy/units/tests/test_units.py::test_register",
"astropy/units/tests/test_units.py::test_compose_issue_579",
"astropy/units/tests/test_units.py::test_compose_si_to_cgs[m]",
"astropy/units/tests/test_units.py::test_compose_si_to_cgs[lx]",
"astropy/units/tests/test_units.py::test_compose_roundtrip[lm]",
"astropy/units/tests/test_units.py::test_enable_unit_groupings",
"astropy/units/tests/test_units.py::test_compose_roundtrip[m]",
"astropy/units/tests/test_units.py::test_compose_roundtrip[spat]",
"astropy/units/tests/test_units.py::test_composite",
"astropy/units/tests/test_units.py::test_compose_roundtrip[yr]",
"astropy/units/tests/test_units.py::test_compose_failed",
"astropy/units/tests/test_units.py::test_compose_cgs_to_si[s]",
"astropy/units/tests/test_units.py::test_compose_roundtrip[Wb]",
"astropy/units/tests/test_units.py::test_to_cgs",
"astropy/units/tests/test_units.py::test_compose_si_to_cgs[s]",
"astropy/units/tests/test_units.py::test_unit_summary_prefixes",
"astropy/units/tests/test_units.py::test_compose_best_unit_first",
"astropy/units/tests/test_units.py::test_compose_roundtrip[dB]",
"astropy/units/tests/test_units.py::test_compose_roundtrip[min]",
"astropy/units/tests/test_units.py::test_compose_roundtrip[G]",
"astropy/units/tests/test_units.py::test_compose_roundtrip[adu]",
"astropy/units/tests/test_units.py::test_compose_si_to_cgs[min]",
"astropy/units/tests/test_units.py::test_compose_si_to_cgs[T]",
"astropy/units/tests/test_units.py::test_compose_roundtrip[abC]",
"astropy/units/tests/test_units.py::test_compose_roundtrip[rad]",
"astropy/units/tests/test_units.py::test_duplicate_define",
"astropy/units/tests/test_units.py::test_comparison",
"astropy/units/tests/test_units.py::test_compose_si_to_cgs[h]",
"astropy/units/tests/test_units.py::test_compose_roundtrip[AU]",
"astropy/units/tests/test_units.py::test_compose_roundtrip[solLum]",
"astropy/units/tests/test_units.py::test_compose_si_to_cgs[V]",
"astropy/units/tests/test_units.py::test_compose_cgs_to_si[erg]",
"astropy/units/tests/test_units.py::test_composite_unit_get_format_name",
"astropy/units/tests/test_units.py::test_compose_roundtrip[DN]",
"astropy/units/tests/test_units.py::test_compose_roundtrip[earthRad]",
"astropy/units/tests/test_units.py::test_compose_si_to_cgs[l]",
"astropy/units/tests/test_units.py::test_operations_with_strings",
"astropy/units/tests/test_units.py::test_compose_si_to_cgs[lm]",
"astropy/units/tests/test_units.py::test_compose_si_to_cgs[cd]",
"astropy/units/tests/test_units.py::test_compose_roundtrip[bol]",
"astropy/units/tests/test_units.py::test_unit_multiplication_with_string",
"astropy/units/tests/test_units.py::test_null_unit",
"astropy/units/tests/test_units.py::test_compose_roundtrip[d]",
"astropy/units/tests/test_units.py::test_compose_cgs_to_si[sr]",
"astropy/units/tests/test_units.py::test_compose_cgs_to_si[G]",
"astropy/units/tests/test_units.py::test_fractional_powers",
"astropy/units/tests/test_units.py::test_unit_division_by_string",
"astropy/units/tests/test_units.py::test_compose_roundtrip[fortnight]",
"astropy/units/tests/test_units.py::test_equiv_compose",
"astropy/units/tests/test_units.py::test_compose_roundtrip[hourangle]",
"astropy/units/tests/test_units.py::test_compose_roundtrip[littleh]",
"astropy/units/tests/test_units.py::test_endian_independence",
"astropy/units/tests/test_units.py::test_compose_roundtrip[byte]",
"astropy/units/tests/test_units.py::test_composite_compose",
"astropy/units/tests/test_units.py::test_compose_cgs_to_si[cm]",
"astropy/units/tests/test_units.py::test_compose_cgs_to_si[P]",
"astropy/units/tests/test_units.py::test_str",
"astropy/units/tests/test_units.py::test_compose_roundtrip[Ba]",
"astropy/units/tests/test_units.py::test_compose_roundtrip[St]",
"astropy/units/tests/test_units.py::test_compose_roundtrip[M_e]",
"astropy/units/tests/test_units.py::test_compose_roundtrip[bit]",
"astropy/units/tests/test_units.py::test_compose_roundtrip[vox]",
"astropy/units/tests/test_units.py::test_to_si",
"astropy/units/tests/test_units.py::test_compose_roundtrip[ph]",
"astropy/units/tests/test_units.py::test_compose_si_to_cgs[Wb]",
"astropy/units/tests/test_units.py::test_compose_roundtrip[F]",
"astropy/units/tests/test_units.py::test_compose_cgs_to_si[mol]",
"astropy/units/tests/test_units.py::test_compose_si_to_cgs[arcmin]",
"astropy/units/tests/test_units.py::test_compose_cgs_to_si[Ba]",
"astropy/units/tests/test_units.py::test_compose_roundtrip[K]",
"astropy/units/tests/test_units.py::test_compose_roundtrip[deg]",
"astropy/units/tests/test_units.py::test_validate_power_detect_fraction",
"astropy/units/tests/test_units.py::test_convert",
"astropy/units/tests/test_units.py::test_compose_roundtrip[T]",
"astropy/units/tests/test_units.py::test_compose_si_to_cgs[%]",
"astropy/units/tests/test_units.py::test_compose_roundtrip[H]",
"astropy/units/tests/test_units.py::test_compose_roundtrip[Gal]",
"astropy/units/tests/test_units.py::test_compose_si_to_cgs[J]",
"astropy/units/tests/test_units.py::test_compose_si_to_cgs[A]",
"astropy/units/tests/test_units.py::test_compose_cgs_to_si[C]",
"astropy/units/tests/test_units.py::test_data_quantities",
"astropy/units/tests/test_units.py::test_compose_roundtrip[jupiterMass]",
"astropy/units/tests/test_units.py::test_compose_roundtrip[R]",
"astropy/units/tests/test_units.py::test_compose_roundtrip[lx]",
"astropy/units/tests/test_units.py::test_compose_roundtrip[dyn]",
"astropy/units/tests/test_units.py::test_compose_roundtrip[D]",
"astropy/units/tests/test_units.py::test_compose_roundtrip[wk]",
"astropy/units/tests/test_units.py::test_compose_roundtrip[Angstrom]",
"astropy/units/tests/test_units.py::test_compose_roundtrip[k]",
"astropy/units/tests/test_units.py::test_compose_si_to_cgs[yr]",
"astropy/units/tests/test_units.py::test_compose_roundtrip[sr]",
"astropy/units/tests/test_units.py::test_compose_roundtrip[M_p]",
"astropy/units/tests/test_units.py::test_compose_roundtrip[eV]",
"astropy/units/tests/test_units.py::test_compose_roundtrip[l]",
"astropy/units/tests/test_units.py::test_megabit",
"astropy/units/tests/test_units.py::test_sorted_bases",
"astropy/units/tests/test_units.py::test_steradian",
"astropy/units/tests/test_units.py::test_compose_si_to_cgs[Ohm]",
"astropy/units/tests/test_units.py::test_compose_cgs_to_si[dyn]",
"astropy/units/tests/test_units.py::test_compose_si_to_cgs[eV]",
"astropy/units/tests/test_units.py::test_compose_si_to_cgs[Hz]",
"astropy/units/tests/test_units.py::test_pickling",
"astropy/units/tests/test_units.py::test_cds_power",
"astropy/units/tests/test_units.py::test_compose_cgs_to_si[D]",
"astropy/units/tests/test_units.py::test_compose_roundtrip[S]",
"astropy/units/tests/test_units.py::test_compose_si_to_cgs[C]",
"astropy/units/tests/test_units.py::test_unknown_unit",
"astropy/units/tests/test_units.py::test_compose_roundtrip[C]",
"astropy/units/tests/test_units.py::test_compose_roundtrip[Pa]",
"astropy/units/tests/test_units.py::test_compose_roundtrip[J]",
"astropy/units/tests/test_units.py::test_compose_roundtrip[pc]",
"astropy/units/tests/test_units.py::test_compose_roundtrip[barn]",
"astropy/units/tests/test_units.py::test_compose_into_arbitrary_units",
"astropy/units/tests/test_units.py::test_compose_roundtrip[pix]",
"astropy/units/tests/test_units.py::test_compose_si_to_cgs[Angstrom]",
"astropy/units/tests/test_units.py::test_represents",
"astropy/units/tests/test_units.py::test_compose_si_to_cgs[deg]",
"astropy/units/tests/test_units.py::test_compose_roundtrip[Torr]",
"astropy/units/tests/test_units.py::test_compose_roundtrip[V]"
] |
[
"astropy/units/tests/test_format.py::test_ogip_grammar[strings1-unit1]",
"astropy/units/tests/test_format.py::test_scaled_dimensionless",
"astropy/units/tests/test_format.py::test_fits_scale_factor[10(+2)-100-10**2]",
"astropy/units/tests/test_format.py::test_unicode[g\\u22121-unit2]",
"astropy/units/tests/test_format.py::test_fits_scale_factor[10**2-100-10**2]",
"astropy/units/tests/test_format.py::test_cds_grammar[strings22-unit22]",
"astropy/units/tests/test_format.py::test_fits_scale_factor[10^-20-1e-20-10**-20]",
"astropy/units/tests/test_format.py::test_unicode[\\xb5g-unit0]",
"astropy/units/tests/test_format.py::test_ogip_grammar[strings0-unit0]",
"astropy/units/tests/test_format.py::test_cds_grammar[strings14-unit14]",
"astropy/units/tests/test_format.py::test_fits_scale_factor[10(-20)-1e-20-10**-20]",
"astropy/units/tests/test_format.py::test_scale_effectively_unity",
"astropy/units/tests/test_format.py::test_cds_grammar[strings20-unit20]",
"astropy/units/tests/test_format.py::test_unit_grammar[strings3-unit3]",
"astropy/units/tests/test_format.py::test_cds_grammar[strings11-unit11]",
"astropy/units/tests/test_format.py::test_ogip_grammar[strings5-unit5]",
"astropy/units/tests/test_format.py::test_format_styles[console- erg \\n ------\\n s cm^2]",
"astropy/units/tests/test_format.py::test_deprecated_did_you_mean_units",
"astropy/units/tests/test_format.py::test_cds_grammar[strings24-unit24]",
"astropy/units/tests/test_format.py::test_format_styles[latex_inline-$\\\\mathrm{erg\\\\,s^{-1}\\\\,cm^{-2}}$]",
"astropy/units/tests/test_format.py::test_cds_grammar_fail[0.1 nm]",
"astropy/units/tests/test_format.py::test_double_superscript",
"astropy/units/tests/test_format.py::test_cds_grammar_fail[km / s]",
"astropy/units/tests/test_format.py::test_format_styles[>20s- erg / (cm2 s)]",
"astropy/units/tests/test_format.py::test_cds_grammar[strings26-unit26]",
"astropy/units/tests/test_format.py::test_unit_grammar_fail[mag(mag)]",
"astropy/units/tests/test_format.py::test_cds_grammar[strings28-unit28]",
"astropy/units/tests/test_format.py::test_cds_grammar_fail[solMass(3/2)]",
"astropy/units/tests/test_format.py::test_cds_grammar[strings33-unit33]",
"astropy/units/tests/test_format.py::test_cds_grammar_fail[pix0.1nm]",
"astropy/units/tests/test_format.py::test_unit_grammar[strings5-unit5]",
"astropy/units/tests/test_format.py::test_cds_grammar[strings2-unit2]",
"astropy/units/tests/test_format.py::test_ogip_grammar_fail[dB(mW)]",
"astropy/units/tests/test_format.py::test_cds_grammar_fail[km*s]",
"astropy/units/tests/test_format.py::test_cds_grammar[strings9-unit9]",
"astropy/units/tests/test_format.py::test_unit_grammar_fail[sin( /pixel /s)]",
"astropy/units/tests/test_format.py::test_ogip_grammar_fail[sin( /pixel /s)]",
"astropy/units/tests/test_format.py::test_cds_grammar[strings31-unit31]",
"astropy/units/tests/test_format.py::test_cds_grammar[strings32-unit32]",
"astropy/units/tests/test_format.py::test_unicode[\\u03a9-unit9]",
"astropy/units/tests/test_format.py::test_fits_units_available",
"astropy/units/tests/test_format.py::test_unit_grammar_fail[dB(dB(mW))]",
"astropy/units/tests/test_units.py::test_suggestions",
"astropy/units/tests/test_format.py::test_powers[-0.015625-1 / m(1/64)]",
"astropy/units/tests/test_format.py::test_cds_grammar_fail[m---]",
"astropy/units/tests/test_format.py::test_percent",
"astropy/units/tests/test_format.py::test_unicode[\\xb0-unit18]",
"astropy/units/tests/test_format.py::test_unicode_failures[m\\u2212\\xb9]",
"astropy/units/tests/test_format.py::test_unit_grammar_fail[dex()]",
"astropy/units/tests/test_format.py::test_fits_scale_factor_errors",
"astropy/units/tests/test_format.py::test_cds_grammar_fail[mag(s-1)]",
"astropy/units/tests/test_format.py::test_fits_function[dB(mW)]",
"astropy/units/tests/test_format.py::test_fits_scale_factor[10^(-20)-1e-20-10**-20]",
"astropy/units/tests/test_format.py::TestRoundtripCDS::test_roundtrip_dex[unit1]",
"astropy/units/tests/test_format.py::test_fraction_repr",
"astropy/units/tests/test_format.py::test_unit_grammar[strings4-unit4]",
"astropy/units/tests/test_format.py::test_unit_grammar[strings11-unit11]",
"astropy/units/tests/test_format.py::test_vounit_details",
"astropy/units/tests/test_format.py::test_cds_grammar_fail[dex(cm s-2)]",
"astropy/units/tests/test_format.py::test_ogip_grammar[strings2-unit2]",
"astropy/units/tests/test_format.py::test_fits_scale_factor[10^+2-100-10**2]",
"astropy/units/tests/test_format.py::test_fits_scale_factor[10+2-100-10**2]",
"astropy/units/tests/test_format.py::test_cds_grammar[strings25-unit25]",
"astropy/units/tests/test_format.py::test_cds_grammar[strings12-unit12]",
"astropy/units/tests/test_format.py::test_cds_grammar_fail[km**2]",
"astropy/units/tests/test_format.py::test_unicode[\\u03bcg-unit1]",
"astropy/units/tests/test_format.py::test_cds_grammar_fail[pix/(0.1nm)]",
"astropy/units/tests/test_format.py::test_unicode_failures[g\\xb5]",
"astropy/units/tests/test_format.py::test_flexible_float",
"astropy/units/tests/test_format.py::test_unicode_failures[m\\u207b1]",
"astropy/units/tests/test_format.py::test_fits_function[mag(ct/s)]",
"astropy/units/tests/test_format.py::test_fits_scale_factor[10**+2-100-10**2]",
"astropy/units/tests/test_format.py::test_unicode[m\\u207a\\xb2-unit6]",
"astropy/units/tests/test_format.py::test_ogip_grammar[strings8-unit8]",
"astropy/units/tests/test_format.py::test_cds_log10_dimensionless",
"astropy/units/tests/test_format.py::test_cds_grammar[strings1-unit1]",
"astropy/units/tests/test_format.py::test_unit_grammar[strings9-unit9]",
"astropy/units/tests/test_format.py::test_cds_grammar[strings30-unit30]",
"astropy/units/tests/test_format.py::test_ogip_grammar[strings6-unit6]",
"astropy/units/tests/test_format.py::test_cds_grammar_fail[0.1---]",
"astropy/units/tests/test_format.py::test_ogip_grammar_fail[log(photon /m**2 /s /Hz)]",
"astropy/units/tests/test_format.py::test_cds_dimensionless",
"astropy/units/tests/test_format.py::test_unicode[\\u212b-unit12]",
"astropy/units/tests/test_format.py::test_ogip_grammar[strings7-unit7]",
"astropy/units/tests/test_format.py::test_fits_scale_factor[10^(+2)-100-10**2]",
"astropy/units/tests/test_format.py::test_powers[1.0-m]",
"astropy/units/tests/test_format.py::test_powers[-10-1 / m10]",
"astropy/units/tests/test_format.py::TestRoundtripCDS::test_roundtrip_dex[unit0]",
"astropy/units/tests/test_format.py::test_unit_grammar[strings1-unit1]",
"astropy/units/tests/test_format.py::test_ogip_grammar_fail[log(photon /cm**2 /s /Hz) (sin( /pixel /s))**(-1)]",
"astropy/units/tests/test_format.py::test_fits_scale_factor[10**-20-1e-20-10**-20]",
"astropy/units/tests/test_format.py::test_unit_grammar[strings7-unit7]",
"astropy/units/tests/test_format.py::test_ogip_grammar_fail[dex(cm/s**2)]",
"astropy/units/tests/test_format.py::test_cds_units_available",
"astropy/units/tests/test_format.py::test_console_out",
"astropy/units/tests/test_format.py::test_unicode[m\\xb9\\u2070-unit8]",
"astropy/units/tests/test_format.py::test_vounit_unknown",
"astropy/units/tests/test_format.py::test_cds_grammar_fail[--]",
"astropy/units/tests/test_format.py::test_cds_grammar_fail[---m]",
"astropy/units/tests/test_format.py::test_cds_grammar[strings0-unit0]",
"astropy/units/tests/test_format.py::TestRoundtripCDS::test_roundtrip_dex[unit2]",
"astropy/units/tests/test_format.py::test_powers[0.01-m(1/100)]",
"astropy/units/tests/test_format.py::test_cds_grammar[strings13-unit13]",
"astropy/units/tests/test_format.py::test_powers[0.6363636363636364-m(7/11)]",
"astropy/units/tests/test_format.py::test_powers[2.0-m2]",
"astropy/units/tests/test_format.py::test_cds_grammar_fail[5x8+3m]",
"astropy/units/tests/test_format.py::test_format_styles[latex-$\\\\mathrm{\\\\frac{erg}{s\\\\,cm^{2}}}$]",
"astropy/units/tests/test_format.py::test_cds_grammar_fail[[--]]",
"astropy/units/tests/test_format.py::test_cds_grammar[strings7-unit7]",
"astropy/units/tests/test_format.py::test_vounit_custom",
"astropy/units/tests/test_format.py::test_fits_function[dex(cm s**-2)]",
"astropy/units/tests/test_format.py::test_unicode[m\\u212b-unit16]",
"astropy/units/tests/test_format.py::test_cds_grammar[strings17-unit17]",
"astropy/units/tests/test_format.py::test_fits_scale_factor[10^(2)-100-10**2]",
"astropy/units/tests/test_format.py::test_unit_grammar[strings6-unit6]",
"astropy/units/tests/test_format.py::test_unicode[\\xb0C-unit17]",
"astropy/units/tests/test_format.py::test_cds_grammar_fail[km s-1]",
"astropy/units/tests/test_format.py::test_unicode[\\u212b \\u2126-unit13]",
"astropy/units/tests/test_format.py::test_cds_grammar[strings19-unit19]",
"astropy/units/tests/test_format.py::test_unicode_failures[g\\u2212]",
"astropy/units/tests/test_format.py::test_unicode_failures[m+\\xb9]",
"astropy/units/tests/test_format.py::test_cds_grammar[strings8-unit8]",
"astropy/units/tests/test_format.py::test_cds_grammar[strings21-unit21]",
"astropy/units/tests/test_format.py::test_cds_grammar[strings29-unit29]",
"astropy/units/tests/test_format.py::test_fits_scale_factor[10**(-20)-1e-20-10**-20]",
"astropy/units/tests/test_format.py::test_latex",
"astropy/units/tests/test_format.py::test_vounit_binary_prefix",
"astropy/units/tests/test_format.py::test_cds_grammar_fail[0.1-]",
"astropy/units/tests/test_format.py::test_unicode[\\xb5\\u03a9-unit11]",
"astropy/units/tests/test_format.py::test_unit_grammar[strings8-unit8]",
"astropy/units/tests/test_format.py::test_cds_grammar_fail[m-]",
"astropy/units/tests/test_format.py::test_vounit_implicit_custom",
"astropy/units/tests/test_format.py::test_cds_grammar[strings3-unit3]",
"astropy/units/tests/test_format.py::test_flatten_to_known",
"astropy/units/tests/test_format.py::test_format_styles[s-erg / (cm2 s)]",
"astropy/units/tests/test_format.py::test_latex_inline_scale",
"astropy/units/tests/test_format.py::test_powers[1.5-m(3/2)]",
"astropy/units/tests/test_format.py::test_unicode[m s\\u207b\\xb9-unit4]",
"astropy/units/tests/test_format.py::test_cds_grammar_fail[dB(mW)]",
"astropy/units/tests/test_format.py::test_unit_grammar[strings12-unit12]",
"astropy/units/tests/test_format.py::test_cds_grammar[strings6-unit6]",
"astropy/units/tests/test_format.py::test_unit_grammar[strings2-unit2]",
"astropy/units/tests/test_format.py::test_format_styles[generic-erg / (cm2 s)]",
"astropy/units/tests/test_format.py::test_new_style_latex",
"astropy/units/tests/test_format.py::test_cds_grammar[strings10-unit10]",
"astropy/units/tests/test_format.py::test_unicode[m\\xb3-unit7]",
"astropy/units/tests/test_format.py::test_powers[power9-m(2/101)]",
"astropy/units/tests/test_format.py::TestRoundtripOGIP::test_roundtrip[unit51]",
"astropy/units/tests/test_format.py::test_fits_scale_factor[10**(2)-100-10**2]",
"astropy/units/tests/test_format.py::test_powers[0.019801980198019802-m(0.019801980198019802)]",
"astropy/units/tests/test_format.py::test_fits_scale_factor[10**(+2)-100-10**2]",
"astropy/units/tests/test_format.py::test_unicode_failures[k\\u212b]",
"astropy/units/tests/test_format.py::test_cds_grammar[strings15-unit15]",
"astropy/units/tests/test_format.py::test_fits_scale_factor[10-20-1e-20-10**-20]",
"astropy/units/tests/test_format.py::test_cds_grammar[strings16-unit16]",
"astropy/units/tests/test_format.py::test_cds_grammar_fail[-m]",
"astropy/units/tests/test_format.py::test_ogip_grammar[strings4-unit4]",
"astropy/units/tests/test_format.py::test_unicode[m\\xb2-unit5]",
"astropy/units/tests/test_format.py::test_vo_units_available",
"astropy/units/tests/test_format.py::test_latex_scale",
"astropy/units/tests/test_format.py::test_ogip_grammar[strings3-unit3]",
"astropy/units/tests/test_format.py::test_unicode[\\xc5-unit14]",
"astropy/units/tests/test_format.py::test_unicode[m\\u207b\\xb9-unit3]",
"astropy/units/tests/test_format.py::test_unicode[\\u2126-unit10]",
"astropy/units/tests/test_format.py::test_cds_grammar[strings4-unit4]",
"astropy/units/tests/test_format.py::test_flatten_impossible",
"astropy/units/tests/test_format.py::test_cds_grammar[strings18-unit18]",
"astropy/units/tests/test_format.py::test_unit_grammar[strings10-unit10]",
"astropy/units/tests/test_format.py::test_cds_grammar[strings23-unit23]",
"astropy/units/tests/test_format.py::TestRoundtripOGIP::test_roundtrip[unit38]",
"astropy/units/tests/test_format.py::test_unit_grammar[strings0-unit0]",
"astropy/units/tests/test_format.py::test_cds_grammar[strings27-unit27]",
"astropy/units/tests/test_format.py::test_unicode[A\\u030a-unit15]",
"astropy/units/tests/test_format.py::test_powers[0.6666666666666666-m(2/3)]",
"astropy/units/tests/test_format.py::test_ogip_grammar_fail[log(photon /cm**2 /s /Hz) /(sin( /pixel /s))]",
"astropy/units/tests/test_format.py::test_cds_grammar[strings5-unit5]",
"astropy/units/tests/test_format.py::test_cds_non_ascii_unit",
"astropy/units/tests/test_format.py::test_fits_scale_factor[10^2-100-10**2]"
] |
[
{
"path": "docs/changes/units/#####.feature.rst",
"old_path": "/dev/null",
"new_path": "b/docs/changes/units/#####.feature.rst",
"metadata": "diff --git a/docs/changes/units/#####.feature.rst b/docs/changes/units/#####.feature.rst\nnew file mode 100644\nindex 0000000000..8431c639a3\n--- /dev/null\n+++ b/docs/changes/units/#####.feature.rst\n@@ -0,0 +1,1 @@\n+The milli- prefix has been added to ``astropy.units.Angstrom``.\n"
},
{
"path": "docs/units/format.rst",
"old_path": "a/docs/units/format.rst",
"new_path": "b/docs/units/format.rst",
"metadata": "diff --git a/docs/units/format.rst b/docs/units/format.rst\nindex 90d85c50d3..1d83f2496f 100644\n--- a/docs/units/format.rst\n+++ b/docs/units/format.rst\n@@ -273,11 +273,11 @@ particular alias is used::\n >>> u.Unit(\"Angstroem\") == u.Angstrom\n Traceback (most recent call last):\n ...\n- ValueError: 'Angstroem' did not parse as unit: At col 0, Angstroem is not a\n- valid unit. Did you mean Angstrom or angstrom? If this is meant to be a\n- custom unit, define it with 'u.def_unit'. To have it recognized inside a\n- file reader or other code, enable it with 'u.add_enabled_units'. For\n- details, see\n+ ValueError: 'Angstroem' did not parse as unit: At col 0, Angstroem is not\n+ a valid unit. Did you mean Angstrom, angstrom, mAngstrom or mangstrom? If\n+ this is meant to be a custom unit, define it with 'u.def_unit'. To have it\n+ recognized inside a file reader or other code, enable it with\n+ 'u.add_enabled_units'. For details, see\n https://docs.astropy.org/en/latest/units/combining_and_defining.html\n \n .. EXAMPLE END\n"
}
] |
{
"header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:",
"data": []
}
|
diff --git a/docs/changes/units/#####.feature.rst b/docs/changes/units/#####.feature.rst
new file mode 100644
index 0000000000..8431c639a3
--- /dev/null
+++ b/docs/changes/units/#####.feature.rst
@@ -0,0 +1,1 @@
+The milli- prefix has been added to ``astropy.units.Angstrom``.
diff --git a/docs/units/format.rst b/docs/units/format.rst
index 90d85c50d3..1d83f2496f 100644
--- a/docs/units/format.rst
+++ b/docs/units/format.rst
@@ -273,11 +273,11 @@ particular alias is used::
>>> u.Unit("Angstroem") == u.Angstrom
Traceback (most recent call last):
...
- ValueError: 'Angstroem' did not parse as unit: At col 0, Angstroem is not a
- valid unit. Did you mean Angstrom or angstrom? If this is meant to be a
- custom unit, define it with 'u.def_unit'. To have it recognized inside a
- file reader or other code, enable it with 'u.add_enabled_units'. For
- details, see
+ ValueError: 'Angstroem' did not parse as unit: At col 0, Angstroem is not
+ a valid unit. Did you mean Angstrom, angstrom, mAngstrom or mangstrom? If
+ this is meant to be a custom unit, define it with 'u.def_unit'. To have it
+ recognized inside a file reader or other code, enable it with
+ 'u.add_enabled_units'. For details, see
https://docs.astropy.org/en/latest/units/combining_and_defining.html
.. EXAMPLE END
|
astropy/astropy
|
astropy__astropy-11691
|
https://github.com/astropy/astropy/pull/11691
|
diff --git a/astropy/units/physical.py b/astropy/units/physical.py
index c19c6e8f2b01..5c13020da786 100644
--- a/astropy/units/physical.py
+++ b/astropy/units/physical.py
@@ -3,6 +3,7 @@
"""Defines the physical types that correspond to different units."""
import numbers
+import sys
import warnings
from . import core
@@ -129,6 +130,8 @@
_physical_unit_mapping = {}
_unit_physical_mapping = {}
_name_physical_mapping = {}
+# mapping from attribute-accessible name (no spaces, etc.) to the actual name.
+_attrname_physical_mapping = {}
def _physical_type_from_str(name):
@@ -139,7 +142,9 @@ def _physical_type_from_str(name):
if name == "unknown":
raise ValueError("cannot uniquely identify an 'unknown' physical type.")
- if name in _name_physical_mapping:
+ elif name in _attrname_physical_mapping:
+ return _attrname_physical_mapping[name] # convert attribute-accessible
+ elif name in _name_physical_mapping:
return _name_physical_mapping[name]
else:
raise ValueError(f"{name!r} is not a known physical type.")
@@ -476,6 +481,9 @@ def def_physical_type(unit, name):
for ptype_name in physical_type_names:
_name_physical_mapping[ptype_name] = physical_type
+ # attribute-accessible name
+ attr_name = ptype_name.replace(' ', '_').replace('(', '').replace(')', '')
+ _attrname_physical_mapping[attr_name] = physical_type
def get_physical_type(obj):
@@ -542,10 +550,48 @@ def get_physical_type(obj):
return PhysicalType(unit, "unknown")
+# ------------------------------------------------------------------------------
+# Script section creating the physical types and the documentation
+
+# define the physical types
for unit, physical_type in _units_and_physical_types:
def_physical_type(unit, physical_type)
+# For getting the physical types.
+def __getattr__(name):
+ """Checks for physical types using lazy import.
+
+ This also allows user-defined physical types to be accessible from the
+ :mod:`astropy.units.physical` module.
+ See `PEP 562 <https://www.python.org/dev/peps/pep-0562/>`_
+
+ Parameters
+ ----------
+ name : str
+ The name of the attribute in this module. If it is already defined,
+ then this function is not called.
+
+ Returns
+ -------
+ ptype : `~astropy.units.physical.PhysicalType`
+
+ Raises
+ ------
+ AttributeError
+ If the ``name`` does not correspond to a physical type
+ """
+ if name in _attrname_physical_mapping:
+ return _attrname_physical_mapping[name]
+
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
+
+
+def __dir__():
+ """Return contents directory (__all__ + all physical type names)."""
+ return list(set(__all__) | set(_attrname_physical_mapping.keys()))
+
+
# This generates a docstring addition for this module that describes all of the
# standard physical types defined here.
if __doc__ is not None:
diff --git a/docs/changes/units/11691.feature.rst b/docs/changes/units/11691.feature.rst
new file mode 100644
index 000000000000..fd8a04efed7b
--- /dev/null
+++ b/docs/changes/units/11691.feature.rst
@@ -0,0 +1,4 @@
+Each physical type is added to ``astropy.units.physical``
+(e.g., ``physical.length`` or ``physical.electrical_charge_ESU``).
+The attribute-accessible names (underscored, without parenthesis) also
+work with ``astropy.units.physical.get_physical_type``.
|
diff --git a/astropy/units/tests/test_physical.py b/astropy/units/tests/test_physical.py
index ce285464ccc9..506fc573988e 100644
--- a/astropy/units/tests/test_physical.py
+++ b/astropy/units/tests/test_physical.py
@@ -153,7 +153,9 @@ def test_physical_type_names(unit, physical_type):
(u.m, "length"),
("work", "work"),
(5 * u.m, "length"),
- (length, length)
+ (length, length),
+ (u.Pa, "energy_density"), # attribute-accessible name
+ ("energy_density", "energy_density") # attribute-accessible name
],
)
def test_getting_physical_type(physical_type_representation, physical_type_name):
@@ -439,16 +441,31 @@ def test_expanding_names_for_physical_type(self):
weird_name = "weird name"
strange_name = "strange name"
- physical.def_physical_type(self.weird_unit, weird_name)
- assert (
- self.weird_unit.physical_type == weird_name
- ), f"unable to set physical type for {self.weird_unit}"
-
- physical.def_physical_type(self.weird_unit, strange_name)
- assert set((self.weird_unit).physical_type) == {
- weird_name,
- strange_name,
- }, f"did not correctly append a new physical type name."
+ try:
+ physical.def_physical_type(self.weird_unit, weird_name)
+ assert (
+ self.weird_unit.physical_type == weird_name
+ ), f"unable to set physical type for {self.weird_unit}"
+ except Exception:
+ raise
+ finally: # cleanup added name
+ physical._attrname_physical_mapping.pop(weird_name.replace(' ', '_'), None)
+ physical._name_physical_mapping.pop(weird_name, None)
+
+ # add both strange_name and weird_name
+ try:
+ physical.def_physical_type(self.weird_unit, strange_name)
+ assert set((self.weird_unit).physical_type) == {
+ weird_name,
+ strange_name,
+ }, f"did not correctly append a new physical type name."
+ except Exception:
+ raise
+ finally: # cleanup added names
+ physical._attrname_physical_mapping.pop(strange_name.replace(' ', '_'), None)
+ physical._name_physical_mapping.pop(strange_name, None)
+ physical._attrname_physical_mapping.pop(weird_name.replace(' ', '_'), None)
+ physical._name_physical_mapping.pop(weird_name, None)
def test_redundant_physical_type(self):
"""
@@ -513,3 +530,19 @@ def test_pickling(ptype_name):
pkl = pickle.dumps(ptype)
other = pickle.loads(pkl)
assert other == ptype
+
+
+def test_physical_types_module_access():
+ # all physical type names in dir
+ assert set(dir(physical)).issuperset(physical._attrname_physical_mapping.keys())
+ assert set(dir(physical)).issuperset(physical.__all__)
+
+ # all physical type can be accessed by name
+ for pname in physical._attrname_physical_mapping.keys():
+ ptype = physical._attrname_physical_mapping[pname]
+ assert hasattr(physical, pname) # make sure works in lazy load
+ assert getattr(physical, pname) is ptype
+
+ # a failed access
+ with pytest.raises(AttributeError, match="has no attribute"):
+ physical.not_a_valid_physical_type_name
|
[
{
"path": "docs/changes/units/11691.feature.rst",
"old_path": "/dev/null",
"new_path": "b/docs/changes/units/11691.feature.rst",
"metadata": "diff --git a/docs/changes/units/11691.feature.rst b/docs/changes/units/11691.feature.rst\nnew file mode 100644\nindex 000000000000..fd8a04efed7b\n--- /dev/null\n+++ b/docs/changes/units/11691.feature.rst\n@@ -0,0 +1,4 @@\n+Each physical type is added to ``astropy.units.physical``\n+(e.g., ``physical.length`` or ``physical.electrical_charge_ESU``).\n+The attribute-accessible names (underscored, without parenthesis) also\n+work with ``astropy.units.physical.get_physical_type``.\n",
"update": null
}
] |
5.0
|
77607ae8846038f8244e244ac90e9b2976044e9d
|
[
"astropy/units/tests/test_physical.py::test_physical_type_str[physical_type0-length]",
"astropy/units/tests/test_physical.py::test_physical_type_in",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit10-data quantity]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit55-electrical field strength]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit102-volumetric flow rate]",
"astropy/units/tests/test_physical.py::test_that_str_methods_work_with_physical_types[isnumeric-False]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit88-jerk]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit14-electrical current]",
"astropy/units/tests/test_physical.py::TestDefPhysType::test_attempt_to_define_unknown_physical_type",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit41-angular momentum]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit56-electrical flux density]",
"astropy/units/tests/test_physical.py::test_physical_type_instance_inequality[unit12-unit22]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit67-radiant intensity]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit104-compressibility]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit46-wavenumber]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit19-dimensionless]",
"astropy/units/tests/test_physical.py::test_physical_type_operations[3.2-right27-__truediv__-expected27]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit90-crackle]",
"astropy/units/tests/test_physical.py::test_physical_type_operations[left23-4-__pow__-expected23]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit50-electrical resistance]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit71-data quantity]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit63-inductance]",
"astropy/units/tests/test_physical.py::test_physical_type_instance_equality[unit12-unit22]",
"astropy/units/tests/test_physical.py::test_physical_type_operations[left44-length-__truediv__-expected44]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit57-electrical charge density]",
"astropy/units/tests/test_physical.py::test_missing_physical_type_attribute",
"astropy/units/tests/test_physical.py::test_physical_type_operations[left30-right30-__mul__-expected30]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit83-electrical resistivity]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit96-reaction rate]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit39-molar concentration]",
"astropy/units/tests/test_physical.py::test_physical_type_operations[left22-0.5-__pow__-expected22]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit30-temperature]",
"astropy/units/tests/test_physical.py::test_getting_physical_type[physical_type_representation4-physical_type_name4]",
"astropy/units/tests/test_physical.py::test_physical_type_instance_equality[unit13-unit23]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit31-temperature]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit32-temperature_gradient]",
"astropy/units/tests/test_physical.py::test_getting_physical_type[work-work]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit18-angular speed]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit36-power]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit91-pop]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit92-temperature gradient]",
"astropy/units/tests/test_physical.py::test_getting_physical_type[1.0-dimensionless]",
"astropy/units/tests/test_physical.py::test_physical_type_instance_equality[unit17-unit27]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit1-volume]",
"astropy/units/tests/test_physical.py::test_physical_type_operations[left4-right4-__eq__-True]",
"astropy/units/tests/test_physical.py::test_physical_type_operations[left15-right15-__rmul__-expected15]",
"astropy/units/tests/test_physical.py::test_physical_type_operations[left19-right19-__mul__-expected19]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit7-spectral flux density wav]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit87-volumetric rate]",
"astropy/units/tests/test_physical.py::test_getting_physical_type_exceptions[argument2-TypeError]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit59-magnetic flux]",
"astropy/units/tests/test_physical.py::test_get_physical_type_equivalent_pairs[unit18-unit28]",
"astropy/units/tests/test_physical.py::test_physical_type_instance_inequality[unit13-unit23]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit42-angular speed]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit44-dynamic viscosity]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit49-electrical potential]",
"astropy/units/tests/test_physical.py::test_physical_type_operations[3.2-right25-__mul__-expected25]",
"astropy/units/tests/test_physical.py::test_physical_type_operations[left20-right20-__truediv__-expected20]",
"astropy/units/tests/test_physical.py::test_physical_type_operations[left17-right17-__truediv__-expected17]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit20-area]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit65-luminous flux]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit80-energy flux]",
"astropy/units/tests/test_physical.py::test_physical_type_as_set[unit1-expected_set1]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit61-magnetic field strength]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit4-unknown]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit26-mass]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit25-frequency]",
"astropy/units/tests/test_physical.py::test_physical_type_operations[left6-energy_density-__eq__-True]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit98-catalytic activity]",
"astropy/units/tests/test_physical.py::test_physical_type_operations[left41--1-__rtruediv__-expected41]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit6-angular momentum]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit13-power]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit16-magnetic flux]",
"astropy/units/tests/test_physical.py::test_physical_type_operations[left40-3.2-__truediv__-expected40]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit35-pressure]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit64-luminous intensity]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit97-moment of inertia]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit72-bandwidth]",
"astropy/units/tests/test_physical.py::test_physical_type_instance_equality[unit16-unit26]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit15-electrical current density]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit5-dimensionless]",
"astropy/units/tests/test_physical.py::test_physical_type_operations[left18-right18-__rtruediv__-expected18]",
"astropy/units/tests/test_physical.py::test_physical_type_instance_inequality[unit10-unit20]",
"astropy/units/tests/test_physical.py::test_physical_type_multiplication[0]",
"astropy/units/tests/test_physical.py::test_physical_type_operations[left16-right16-__truediv__-expected16]",
"astropy/units/tests/test_physical.py::test_physical_type_operations[left2-length-__eq__-True]",
"astropy/units/tests/test_physical.py::test_physical_type_as_set[unit0-expected_set0]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit79-specific heat capacity]",
"astropy/units/tests/test_physical.py::test_get_physical_type_equivalent_pairs[unit14-unit24]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit70-photon flux]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit51-electrical conductance]",
"astropy/units/tests/test_physical.py::test_physical_type_operations[left14-right14-__mul__-expected14]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit81-energy flux]",
"astropy/units/tests/test_physical.py::test_physical_type_operations[left10-right10-__ne__-True]",
"astropy/units/tests/test_physical.py::test_physical_type_operations[left13-right13-__mul__-expected13]",
"astropy/units/tests/test_physical.py::test_physical_type_operations[left28-right28-__mul__-expected28]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit23-solid angle]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit82-molar volume]",
"astropy/units/tests/test_physical.py::test_getting_physical_type[physical_type_representation3-length]",
"astropy/units/tests/test_physical.py::test_physical_type_multiplication[multiplicand0]",
"astropy/units/tests/test_physical.py::test_physical_type_instance_equality[unit15-unit25]",
"astropy/units/tests/test_physical.py::test_physical_type_instance_equality[unit10-unit20]",
"astropy/units/tests/test_physical.py::test_that_str_methods_work_with_physical_types[upper-LENGTH]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit17-energy]",
"astropy/units/tests/test_physical.py::test_get_physical_type_equivalent_pairs[unit11-unit21]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit101-absement]",
"astropy/units/tests/test_physical.py::test_physical_type_operations[left32-1-__rmul__-expected32]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit99-molar heat capacity]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit58-permittivity]",
"astropy/units/tests/test_physical.py::test_physical_type_operations[left12-right12-__eq__-expected12]",
"astropy/units/tests/test_physical.py::test_getting_physical_type_exceptions[not a name of a physical type-ValueError]",
"astropy/units/tests/test_physical.py::test_physical_type_operations[left39-0-__rmul__-expected39]",
"astropy/units/tests/test_physical.py::test_physical_type_multiplication[42]",
"astropy/units/tests/test_physical.py::test_physical_type_operations[left1-right1-__eq__-False]",
"astropy/units/tests/test_physical.py::test_physical_type_operations[left21-2-__pow__-expected21]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit34-energy]",
"astropy/units/tests/test_physical.py::test_physical_type_operations[left7-unknown-__eq__-True]",
"astropy/units/tests/test_physical.py::test_physical_type_operations[left8-right8-__eq__-False]",
"astropy/units/tests/test_physical.py::test_physical_type_operations[left35-right35-__rtruediv__-expected35]",
"astropy/units/tests/test_physical.py::test_physical_type_operations[left37-2-__pow__-expected37]",
"astropy/units/tests/test_physical.py::test_pickling[length]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit48-electrical charge]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit52-electrical capacitance]",
"astropy/units/tests/test_physical.py::test_physical_type_operations[left34-1-__truediv__-expected34]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit76-electrical charge (EMU)]",
"astropy/units/tests/test_physical.py::test_get_physical_type_equivalent_pairs[unit12-unit22]",
"astropy/units/tests/test_physical.py::test_physical_type_instance_equality[unit14-unit24]",
"astropy/units/tests/test_physical.py::test_physical_type_hash",
"astropy/units/tests/test_physical.py::test_get_physical_type_equivalent_pairs[unit16-unit26]",
"astropy/units/tests/test_physical.py::test_physical_type_multiplication[-1]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit103-frequency drift]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit27-amount of substance]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit0-length]",
"astropy/units/tests/test_physical.py::test_that_str_methods_work_with_physical_types[title-Length]",
"astropy/units/tests/test_physical.py::test_physical_type_operations[left45-area-__rtruediv__-expected45]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit21-time]",
"astropy/units/tests/test_physical.py::test_physical_type_cannot_become_quantity",
"astropy/units/tests/test_physical.py::test_physical_type_instance_equality[unit11-unit21]",
"astropy/units/tests/test_physical.py::test_physical_type_str[physical_type2-energy density/pressure/stress]",
"astropy/units/tests/test_physical.py::test_physical_type_str[physical_type4-specific entropy/specific heat capacity]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit22-angle]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit93-temperature gradient]",
"astropy/units/tests/test_physical.py::test_physical_type_operations[left29-right29-__rmul__-expected29]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit43-angular acceleration]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit100-molality]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit85-magnetic moment]",
"astropy/units/tests/test_physical.py::test_getting_physical_type[physical_type_representation5-energy_density]",
"astropy/units/tests/test_physical.py::test_pickling[entropy]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit74-electrical current (ESU)]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit2-speed]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit40-momentum/impulse]",
"astropy/units/tests/test_physical.py::test_physical_type_operations[left26-right26-__truediv__-expected26]",
"astropy/units/tests/test_physical.py::test_physical_type_operations[left5-momentum/impulse-__eq__-True]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit45-kinematic viscosity]",
"astropy/units/tests/test_physical.py::test_get_physical_type_equivalent_pairs[unit15-unit25]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit24-acceleration]",
"astropy/units/tests/test_physical.py::test_getting_physical_type[physical_type_representation1-length]",
"astropy/units/tests/test_physical.py::test_that_str_methods_work_with_physical_types[isalpha-True]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit11-data quantity]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit78-heat capacity]",
"astropy/units/tests/test_physical.py::test_physical_type_instance_inequality[unit11-unit21]",
"astropy/units/tests/test_physical.py::test_get_physical_type_equivalent_pairs[unit13-unit23]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit94-temperature gradient]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit62-electromagnetic field strength]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit12-speed]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit37-mass density]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit60-magnetic flux density]",
"astropy/units/tests/test_physical.py::test_invalid_physical_types[invalid_input0]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit33-force]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit75-electrical current (EMU)]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit105-dimensionless]",
"astropy/units/tests/test_physical.py::test_physical_type_operations[left33-right33-__truediv__-expected33]",
"astropy/units/tests/test_physical.py::TestDefPhysType::test_multiple_same_physical_type_names",
"astropy/units/tests/test_physical.py::test_physical_type_operations[left36-1.0-__rtruediv__-expected36]",
"astropy/units/tests/test_physical.py::test_physical_type_operations[left42-length-__mul__-expected42]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit84-electrical conductivity]",
"astropy/units/tests/test_physical.py::test_physical_type_operations[left43-length-__rmul__-expected43]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit68-luminance]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit73-electrical charge (ESU)]",
"astropy/units/tests/test_physical.py::test_get_physical_type_equivalent_pairs[unit10-unit20]",
"astropy/units/tests/test_physical.py::test_physical_type_operations[left31-1-__mul__-expected31]",
"astropy/units/tests/test_physical.py::test_physical_type_operations[left11-right11-__ne__-True]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit3-volume]",
"astropy/units/tests/test_physical.py::test_physical_type_as_set[unit2-expected_set2]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit69-spectral flux density]",
"astropy/units/tests/test_physical.py::test_unrecognized_unit_physical_type",
"astropy/units/tests/test_physical.py::test_physical_type_instance_equality[unit18-unit28]",
"astropy/units/tests/test_physical.py::test_pickling[speed]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit9-photon flux density]",
"astropy/units/tests/test_physical.py::test_physical_type_str[physical_type1-speed/velocity]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit89-snap]",
"astropy/units/tests/test_physical.py::test_get_physical_type_equivalent_pairs[unit17-unit27]",
"astropy/units/tests/test_physical.py::TestDefPhysType::test_redundant_physical_type",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit77-thermal conductivity]",
"astropy/units/tests/test_physical.py::test_physical_type_operations[left9-right9-__ne__-False]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit8-photon flux density wav]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit29-temperature]",
"astropy/units/tests/test_physical.py::test_invalid_physical_types[invalid_input1]",
"astropy/units/tests/test_physical.py::test_getting_physical_type_exceptions[unknown-ValueError]",
"astropy/units/tests/test_physical.py::test_physical_type_operations[length-right3-__eq__-expected3]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit38-specific volume]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit53-electrical dipole moment]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit86-magnetic moment]",
"astropy/units/tests/test_physical.py::test_physical_type_str[physical_type3-temperature]",
"astropy/units/tests/test_physical.py::test_physical_type_iteration",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit66-luminous emittance/illuminance]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit54-electrical current density]",
"astropy/units/tests/test_physical.py::test_physical_type_operations[left24-right24-__mul__-expected24]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit47-electrical current]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit28-temperature]",
"astropy/units/tests/test_physical.py::test_physical_type_operations[left0-right0-__eq__-True]",
"astropy/units/tests/test_physical.py::test_physical_type_operations[left38-32-__mul__-expected38]",
"astropy/units/tests/test_physical.py::test_physical_type_names[unit95-specific energy]"
] |
[
"astropy/units/tests/test_physical.py::test_getting_physical_type[energy_density-energy_density]",
"astropy/units/tests/test_physical.py::TestDefPhysType::test_expanding_names_for_physical_type",
"astropy/units/tests/test_physical.py::test_physical_types_module_access"
] |
[
{
"path": "docs/changes/units/#####.feature.rst",
"old_path": "/dev/null",
"new_path": "b/docs/changes/units/#####.feature.rst",
"metadata": "diff --git a/docs/changes/units/#####.feature.rst b/docs/changes/units/#####.feature.rst\nnew file mode 100644\nindex 0000000000..fd8a04efed\n--- /dev/null\n+++ b/docs/changes/units/#####.feature.rst\n@@ -0,0 +1,4 @@\n+Each physical type is added to ``astropy.units.physical``\n+(e.g., ``physical.length`` or ``physical.electrical_charge_ESU``).\n+The attribute-accessible names (underscored, without parenthesis) also\n+work with ``astropy.units.physical.get_physical_type``.\n"
}
] |
{
"header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:",
"data": [
{
"type": "field",
"name": "_attrname_physical_mapping"
}
]
}
|
diff --git a/docs/changes/units/#####.feature.rst b/docs/changes/units/#####.feature.rst
new file mode 100644
index 0000000000..fd8a04efed
--- /dev/null
+++ b/docs/changes/units/#####.feature.rst
@@ -0,0 +1,4 @@
+Each physical type is added to ``astropy.units.physical``
+(e.g., ``physical.length`` or ``physical.electrical_charge_ESU``).
+The attribute-accessible names (underscored, without parenthesis) also
+work with ``astropy.units.physical.get_physical_type``.
If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:
[{'type': 'field', 'name': '_attrname_physical_mapping'}]
|
astropy/astropy
|
astropy__astropy-11954
|
https://github.com/astropy/astropy/pull/11954
|
diff --git a/astropy/table/operations.py b/astropy/table/operations.py
index 9ef574d66aae..0850f646012a 100644
--- a/astropy/table/operations.py
+++ b/astropy/table/operations.py
@@ -336,7 +336,8 @@ def join_func(col1, col2):
return join_func
-def join(left, right, keys=None, join_type='inner',
+def join(left, right, keys=None, join_type='inner', *,
+ keys_left=None, keys_right=None,
uniq_col_name='{col_name}_{table_name}',
table_names=['1', '2'], metadata_conflicts='warn',
join_funcs=None):
@@ -354,6 +355,12 @@ def join(left, right, keys=None, join_type='inner',
Default is to use all columns which are common to both tables.
join_type : str
Join type ('inner' | 'outer' | 'left' | 'right' | 'cartesian'), default is 'inner'
+ keys_left : str or list of str or list of column-like, optional
+ Left column(s) used to match rows instead of ``keys`` arg. This can be
+ be a single left table column name or list of column names, or a list of
+ column-like values with the same lengths as the left table.
+ keys_right : str or list of str or list of column-like, optional
+ Same as ``keys_left``, but for the right side of the join.
uniq_col_name : str or None
String generate a unique output column name in case of a conflict.
The default is '{col_name}_{table_name}'.
@@ -384,7 +391,8 @@ def join(left, right, keys=None, join_type='inner',
col_name_map = OrderedDict()
out = _join(left, right, keys, join_type,
uniq_col_name, table_names, col_name_map, metadata_conflicts,
- join_funcs)
+ join_funcs,
+ keys_left=keys_left, keys_right=keys_right)
# Merge the column and table meta data. Table subclasses might override
# these methods for custom merge behavior.
@@ -1047,7 +1055,8 @@ def _join(left, right, keys=None, join_type='inner',
uniq_col_name='{col_name}_{table_name}',
table_names=['1', '2'],
col_name_map=None, metadata_conflicts='warn',
- join_funcs=None):
+ join_funcs=None,
+ keys_left=None, keys_right=None):
"""
Perform a join of the left and right Tables on specified keys.
@@ -1112,12 +1121,23 @@ def _join(left, right, keys=None, join_type='inner',
right[cartesian_index_name] = np.uint8(0)
keys = (cartesian_index_name, )
- # If we have a single key, put it in a tuple
+ # Handle the case of join key columns that are different between left and
+ # right via keys_left/keys_right args. This is done by saving the original
+ # input tables and making new left and right tables that contain only the
+ # key cols but with common column names ['0', '1', etc]. This sets `keys` to
+ # those fake key names in the left and right tables
+ if keys_left is not None or keys_right is not None:
+ left_orig = left
+ right_orig = right
+ left, right, keys = _join_keys_left_right(
+ left, right, keys, keys_left, keys_right, join_funcs)
+
if keys is None:
keys = tuple(name for name in left.colnames if name in right.colnames)
if len(keys) == 0:
raise TableMergeError('No keys in common between left and right tables')
elif isinstance(keys, str):
+ # If we have a single key, put it in a tuple
keys = (keys,)
# Check the key columns
@@ -1141,15 +1161,24 @@ def _join(left, right, keys=None, join_type='inner',
if len_left == 0 or len_right == 0:
raise ValueError('input tables for join must both have at least one row')
- # Joined array dtype as a list of descr (name, type_str, shape) tuples
- col_name_map = get_col_name_map([left, right], keys, uniq_col_name, table_names)
- out_descrs = get_descrs([left, right], col_name_map)
-
try:
idxs, idx_sort = _get_join_sort_idxs(keys, left, right)
except NotImplementedError:
raise TypeError('one or more key columns are not sortable')
+ # Now that we have idxs and idx_sort, revert to the original table args to
+ # carry on with making the output joined table. `keys` is set to to an empty
+ # list so that all original left and right columns are included in the
+ # output table.
+ if keys_left is not None or keys_right is not None:
+ keys = []
+ left = left_orig
+ right = right_orig
+
+ # Joined array dtype as a list of descr (name, type_str, shape) tuples
+ col_name_map = get_col_name_map([left, right], keys, uniq_col_name, table_names)
+ out_descrs = get_descrs([left, right], col_name_map)
+
# Main inner loop in Cython to compute the cartesian product
# indices for the given join type
int_join_type = {'inner': 0, 'outer': 1, 'left': 2, 'right': 3,
@@ -1224,6 +1253,58 @@ def _join(left, right, keys=None, join_type='inner',
return out
+def _join_keys_left_right(left, right, keys, keys_left, keys_right, join_funcs):
+ """Do processing to handle keys_left / keys_right args for join.
+
+ This takes the keys_left/right inputs and turns them into a list of left/right
+ columns corresponding to those inputs (which can be column names or column
+ data values). It also generates the list of fake key column names (strings
+ of "1", "2", etc.) that correspond to the input keys.
+ """
+ def _keys_to_cols(keys, table, label):
+ # Process input `keys`, which is a str or list of str column names in
+ # `table` or a list of column-like objects. The `label` is just for
+ # error reporting.
+ if isinstance(keys, str):
+ keys = [keys]
+ cols = []
+ for key in keys:
+ if isinstance(key, str):
+ try:
+ cols.append(table[key])
+ except KeyError:
+ raise ValueError(f'{label} table does not have key column {key!r}')
+ else:
+ if len(key) != len(table):
+ raise ValueError(f'{label} table has different length from key {key}')
+ cols.append(key)
+ return cols
+
+ if join_funcs is not None:
+ raise ValueError('cannot supply join_funcs arg and keys_left / keys_right')
+
+ if keys_left is None or keys_right is None:
+ raise ValueError('keys_left and keys_right must both be provided')
+
+ if keys is not None:
+ raise ValueError('keys arg must be None if keys_left and keys_right are supplied')
+
+ cols_left = _keys_to_cols(keys_left, left, 'left')
+ cols_right = _keys_to_cols(keys_right, right, 'right')
+
+ if len(cols_left) != len(cols_right):
+ raise ValueError('keys_left and keys_right args must have same length')
+
+ # Make two new temp tables for the join with only the join columns and
+ # key columns in common.
+ keys = [f'{ii}' for ii in range(len(cols_left))]
+
+ left = left.__class__(cols_left, names=keys, copy=False)
+ right = right.__class__(cols_right, names=keys, copy=False)
+
+ return left, right, keys
+
+
def _check_join_type(join_type, func_name):
"""Check join_type arg in hstack and vstack.
diff --git a/docs/changes/table/11954.api.rst b/docs/changes/table/11954.api.rst
new file mode 100644
index 000000000000..4f43558ec025
--- /dev/null
+++ b/docs/changes/table/11954.api.rst
@@ -0,0 +1,3 @@
+The table ``join`` function now accepts only the first four arguments ``left``,
+``right``, ``keys``, and ``join_type`` as positional arguments. All other
+arguments must be supplied as keyword arguments.
diff --git a/docs/changes/table/11954.feature.rst b/docs/changes/table/11954.feature.rst
new file mode 100644
index 000000000000..cf1d327aba9c
--- /dev/null
+++ b/docs/changes/table/11954.feature.rst
@@ -0,0 +1,5 @@
+Added new keyword arguments ``keys_left`` and ``keys_right`` to the table ``join``
+function to support joining tables on key columns with different names. In
+addition the new keywords can accept a list of column-like objects which are
+used as the match keys. This allows joining on arbitrary data which are not part
+of the tables being joined.
diff --git a/docs/table/operations.rst b/docs/table/operations.rst
index 5e1591a5160b..a2804717037c 100644
--- a/docs/table/operations.rst
+++ b/docs/table/operations.rst
@@ -855,40 +855,31 @@ Non-Identical Key Column Names
.. EXAMPLE START: Joining Tables with Unique Key Column Names
-The |join| function requires the key column names to be identical in the
-two tables. However, in the following, one table has a ``'name'`` column
-while the other has an ``'obj_id'`` column::
+To use the |join| function with non-identical key column names, use the
+``keys_left`` and ``keys_right`` arguments. In the following example one table
+has a ``'name'`` column while the other has an ``'obj_id'`` column::
>>> optical = Table.read("""name obs_date mag_b mag_v
... M31 2012-01-02 17.0 16.0
... M82 2012-10-29 16.2 15.2
... M101 2012-10-31 15.1 15.5""", format='ascii')
- >>> xray_1 = Table.read(""" obj_id obs_date logLx
- ... NGC3516 2011-11-11 42.1
- ... M31 1999-01-05 43.1
- ... M82 2012-10-29 45.0""", format='ascii')
-
-In order to perform a match based on the names of the objects, you have to
-temporarily rename one of the columns mentioned above, right before creating
-the new table::
-
- >>> xray_1.rename_column('obj_id', 'name')
- >>> opt_xray_1 = join(optical, xray_1, keys='name')
- >>> xray_1.rename_column('name', 'obj_id')
- >>> print(opt_xray_1)
- name obs_date_1 mag_b mag_v obs_date_2 logLx
- ---- ---------- ----- ----- ---------- -----
- M31 2012-01-02 17.0 16.0 1999-01-05 43.1
- M82 2012-10-29 16.2 15.2 2012-10-29 45.0
-
-The original ``xray_1`` table remains unchanged after the operation::
-
- >>> print(xray_1)
- obj_id obs_date logLx
- ------- ---------- -----
- NGC3516 2011-11-11 42.1
- M31 1999-01-05 43.1
- M82 2012-10-29 45.0
+ >>> xray_1 = Table.read("""obj_id obs_date logLx
+ ... NGC3516 2011-11-11 42.1
+ ... M31 1999-01-05 43.1
+ ... M82 2012-10-29 45.0""", format='ascii')
+
+In order to perform a match based on the names of the objects, do the
+following::
+
+ >>> print(join(optical, xray_1, keys_left='name', keys_right='obj_id'))
+ name obs_date_1 mag_b mag_v obj_id obs_date_2 logLx
+ ---- ---------- ----- ----- ------ ---------- -----
+ M31 2012-01-02 17.0 16.0 M31 1999-01-05 43.1
+ M82 2012-10-29 16.2 15.2 M82 2012-10-29 45.0
+
+The ``keys_left`` and ``keys_right`` arguments can also take a list of column
+names or even a list of column-like objects. The latter case allows specifying
+the matching key column values independent of the tables being joined.
.. EXAMPLE END
|
diff --git a/astropy/table/tests/test_operations.py b/astropy/table/tests/test_operations.py
index 2b9488393af2..8b2fcd93bd39 100644
--- a/astropy/table/tests/test_operations.py
+++ b/astropy/table/tests/test_operations.py
@@ -721,6 +721,73 @@ def test_join_with_join_distance_2d(self):
' 5 -- .. -- 0.5 .. 0.0']
assert str(t12).splitlines() == exp
+ def test_keys_left_right_basic(self):
+ """Test using the keys_left and keys_right args to specify different
+ join keys. This takes the standard test case but renames column 'a'
+ to 'x' and 'y' respectively for tables 1 and 2. Then it compares the
+ normal join on 'a' to the new join on 'x' and 'y'."""
+ self._setup()
+
+ for join_type in ('inner', 'left', 'right', 'outer'):
+ t1 = self.t1.copy()
+ t2 = self.t2.copy()
+ # Expected is same as joining on 'a' but with names 'x', 'y' instead
+ t12_exp = table.join(t1, t2, keys='a', join_type=join_type)
+ t12_exp.add_column(t12_exp['a'], name='x', index=1)
+ t12_exp.add_column(t12_exp['a'], name='y', index=len(t1.colnames) + 1)
+ del t12_exp['a']
+
+ # Different key names
+ t1.rename_column('a', 'x')
+ t2.rename_column('a', 'y')
+ keys_left_list = ['x'] # Test string key name
+ keys_right_list = [['y']] # Test list of string key names
+ if join_type == 'outer':
+ # Just do this for the outer join (others are the same)
+ keys_left_list.append([t1['x'].tolist()]) # Test list key column
+ keys_right_list.append([t2['y']]) # Test Column key column
+
+ for keys_left, keys_right in zip(keys_left_list, keys_right_list):
+ t12 = table.join(t1, t2, keys_left=keys_left, keys_right=keys_right,
+ join_type=join_type)
+
+ assert t12.colnames == t12_exp.colnames
+ for col in t12.values_equal(t12_exp).itercols():
+ assert np.all(col)
+ assert t12_exp.meta == t12.meta
+
+ def test_keys_left_right_exceptions(self):
+ """Test exceptions using the keys_left and keys_right args to specify
+ different join keys.
+ """
+ self._setup()
+ t1 = self.t1
+ t2 = self.t2
+
+ msg = r"left table does not have key column 'z'"
+ with pytest.raises(ValueError, match=msg):
+ table.join(t1, t2, keys_left='z', keys_right=['a'])
+
+ msg = r"left table has different length from key \[1, 2\]"
+ with pytest.raises(ValueError, match=msg):
+ table.join(t1, t2, keys_left=[[1, 2]], keys_right=['a'])
+
+ msg = r"keys arg must be None if keys_left and keys_right are supplied"
+ with pytest.raises(ValueError, match=msg):
+ table.join(t1, t2, keys_left='z', keys_right=['a'], keys='a')
+
+ msg = r"keys_left and keys_right args must have same length"
+ with pytest.raises(ValueError, match=msg):
+ table.join(t1, t2, keys_left=['a', 'b'], keys_right=['a'])
+
+ msg = r"keys_left and keys_right must both be provided"
+ with pytest.raises(ValueError, match=msg):
+ table.join(t1, t2, keys_left=['a', 'b'])
+
+ msg = r"cannot supply join_funcs arg and keys_left / keys_right"
+ with pytest.raises(ValueError, match=msg):
+ table.join(t1, t2, keys_left=['a'], keys_right=['a'], join_funcs={})
+
class TestSetdiff():
|
[
{
"path": "docs/changes/table/11954.api.rst",
"old_path": "/dev/null",
"new_path": "b/docs/changes/table/11954.api.rst",
"metadata": "diff --git a/docs/changes/table/11954.api.rst b/docs/changes/table/11954.api.rst\nnew file mode 100644\nindex 000000000000..4f43558ec025\n--- /dev/null\n+++ b/docs/changes/table/11954.api.rst\n@@ -0,0 +1,3 @@\n+The table ``join`` function now accepts only the first four arguments ``left``,\n+``right``, ``keys``, and ``join_type`` as positional arguments. All other\n+arguments must be supplied as keyword arguments.\n",
"update": null
},
{
"path": "docs/changes/table/11954.feature.rst",
"old_path": "/dev/null",
"new_path": "b/docs/changes/table/11954.feature.rst",
"metadata": "diff --git a/docs/changes/table/11954.feature.rst b/docs/changes/table/11954.feature.rst\nnew file mode 100644\nindex 000000000000..cf1d327aba9c\n--- /dev/null\n+++ b/docs/changes/table/11954.feature.rst\n@@ -0,0 +1,5 @@\n+Added new keyword arguments ``keys_left`` and ``keys_right`` to the table ``join``\n+function to support joining tables on key columns with different names. In\n+addition the new keywords can accept a list of column-like objects which are\n+used as the match keys. This allows joining on arbitrary data which are not part\n+of the tables being joined.\n",
"update": null
},
{
"path": "docs/table/operations.rst",
"old_path": "a/docs/table/operations.rst",
"new_path": "b/docs/table/operations.rst",
"metadata": "diff --git a/docs/table/operations.rst b/docs/table/operations.rst\nindex 5e1591a5160b..a2804717037c 100644\n--- a/docs/table/operations.rst\n+++ b/docs/table/operations.rst\n@@ -855,40 +855,31 @@ Non-Identical Key Column Names\n \n .. EXAMPLE START: Joining Tables with Unique Key Column Names\n \n-The |join| function requires the key column names to be identical in the\n-two tables. However, in the following, one table has a ``'name'`` column\n-while the other has an ``'obj_id'`` column::\n+To use the |join| function with non-identical key column names, use the\n+``keys_left`` and ``keys_right`` arguments. In the following example one table\n+has a ``'name'`` column while the other has an ``'obj_id'`` column::\n \n >>> optical = Table.read(\"\"\"name obs_date mag_b mag_v\n ... M31 2012-01-02 17.0 16.0\n ... M82 2012-10-29 16.2 15.2\n ... M101 2012-10-31 15.1 15.5\"\"\", format='ascii')\n- >>> xray_1 = Table.read(\"\"\" obj_id obs_date logLx\n- ... NGC3516 2011-11-11 42.1\n- ... M31 1999-01-05 43.1\n- ... M82 2012-10-29 45.0\"\"\", format='ascii')\n-\n-In order to perform a match based on the names of the objects, you have to\n-temporarily rename one of the columns mentioned above, right before creating\n-the new table::\n-\n- >>> xray_1.rename_column('obj_id', 'name')\n- >>> opt_xray_1 = join(optical, xray_1, keys='name')\n- >>> xray_1.rename_column('name', 'obj_id')\n- >>> print(opt_xray_1)\n- name obs_date_1 mag_b mag_v obs_date_2 logLx\n- ---- ---------- ----- ----- ---------- -----\n- M31 2012-01-02 17.0 16.0 1999-01-05 43.1\n- M82 2012-10-29 16.2 15.2 2012-10-29 45.0\n-\n-The original ``xray_1`` table remains unchanged after the operation::\n-\n- >>> print(xray_1)\n- obj_id obs_date logLx\n- ------- ---------- -----\n- NGC3516 2011-11-11 42.1\n- M31 1999-01-05 43.1\n- M82 2012-10-29 45.0\n+ >>> xray_1 = Table.read(\"\"\"obj_id obs_date logLx\n+ ... NGC3516 2011-11-11 42.1\n+ ... M31 1999-01-05 43.1\n+ ... M82 2012-10-29 45.0\"\"\", format='ascii')\n+\n+In order to perform a match based on the names of the objects, do the\n+following::\n+\n+ >>> print(join(optical, xray_1, keys_left='name', keys_right='obj_id'))\n+ name obs_date_1 mag_b mag_v obj_id obs_date_2 logLx\n+ ---- ---------- ----- ----- ------ ---------- -----\n+ M31 2012-01-02 17.0 16.0 M31 1999-01-05 43.1\n+ M82 2012-10-29 16.2 15.2 M82 2012-10-29 45.0\n+\n+The ``keys_left`` and ``keys_right`` arguments can also take a list of column\n+names or even a list of column-like objects. The latter case allows specifying\n+the matching key column values independent of the tables being joined.\n \n .. EXAMPLE END\n \n",
"update": null
}
] |
5.0
|
cda344a7cb707a0500c2b3d59f871d37562bdea6
|
[
"astropy/table/tests/test_operations.py::TestSetdiff::test_keys[QTable]",
"astropy/table/tests/test_operations.py::TestHStack::test_bad_input_type[QTable]",
"astropy/table/tests/test_operations.py::TestJoin::test_no_common_keys[Table]",
"astropy/table/tests/test_operations.py::TestHStack::test_stack_columns[QTable]",
"astropy/table/tests/test_operations.py::TestVStack::test_mixin_functionality[sphericalrepdiff]",
"astropy/table/tests/test_operations.py::TestVStack::test_stack_basic_inner[Table]",
"astropy/table/tests/test_operations.py::TestSetdiff::test_default_same_columns[Table]",
"astropy/table/tests/test_operations.py::TestDStack::test_dstack_basic_inner[QTable]",
"astropy/table/tests/test_operations.py::TestVStack::test_col_meta_merge_inner[Table]",
"astropy/table/tests/test_operations.py::TestHStack::test_mixin_functionality[time]",
"astropy/table/tests/test_operations.py::TestJoin::test_bad_join_type[Table]",
"astropy/table/tests/test_operations.py::TestJoin::test_mixin_functionality[ndarraybig]",
"astropy/table/tests/test_operations.py::TestVStack::test_vstack_one_table[Table]",
"astropy/table/tests/test_operations.py::TestHStack::test_mixin_functionality[sphericalrepdiff]",
"astropy/table/tests/test_operations.py::TestJoin::test_both_unmasked_single_key_inner[Table]",
"astropy/table/tests/test_operations.py::TestJoin::test_join_with_join_distance_1d_quantity",
"astropy/table/tests/test_operations.py::TestJoin::test_col_rename[QTable]",
"astropy/table/tests/test_operations.py::TestVStack::test_validate_join_type",
"astropy/table/tests/test_operations.py::TestHStack::test_stack_incompatible[Table]",
"astropy/table/tests/test_operations.py::TestJoin::test_rename_conflict[QTable]",
"astropy/table/tests/test_operations.py::TestDStack::test_dstack_table_column[QTable]",
"astropy/table/tests/test_operations.py::TestJoin::test_table_meta_merge[QTable]",
"astropy/table/tests/test_operations.py::TestDStack::test_dstack_basic_outer[Table]",
"astropy/table/tests/test_operations.py::TestDStack::test_dstack_multi_dimension_column[QTable]",
"astropy/table/tests/test_operations.py::test_argsort_time_column",
"astropy/table/tests/test_operations.py::TestHStack::test_mixin_functionality[longitude]",
"astropy/table/tests/test_operations.py::TestHStack::test_mixin_functionality[timedelta]",
"astropy/table/tests/test_operations.py::TestHStack::test_mixin_functionality[quantity]",
"astropy/table/tests/test_operations.py::TestJoin::test_no_common_keys[QTable]",
"astropy/table/tests/test_operations.py::TestVStack::test_mixin_functionality[longitude]",
"astropy/table/tests/test_operations.py::TestDStack::test_dstack_representation",
"astropy/table/tests/test_operations.py::test_stack_columns",
"astropy/table/tests/test_operations.py::TestDStack::test_dstack_different_length_table[Table]",
"astropy/table/tests/test_operations.py::TestSetdiff::test_missing_key[Table]",
"astropy/table/tests/test_operations.py::TestHStack::test_stack_basic[QTable]",
"astropy/table/tests/test_operations.py::TestJoin::test_join_with_join_distance_2d",
"astropy/table/tests/test_operations.py::TestVStack::test_mixin_functionality[ndarraylil]",
"astropy/table/tests/test_operations.py::TestVStack::test_mixin_functionality[sphericaldiff]",
"astropy/table/tests/test_operations.py::TestHStack::test_mixin_functionality[latitude]",
"astropy/table/tests/test_operations.py::test_vstack_bytes[Table]",
"astropy/table/tests/test_operations.py::test_join_non_1d_key_column",
"astropy/table/tests/test_operations.py::TestJoin::test_classes",
"astropy/table/tests/test_operations.py::TestVStack::test_stack_basic_inner[QTable]",
"astropy/table/tests/test_operations.py::TestJoin::test_mixin_functionality[quantity]",
"astropy/table/tests/test_operations.py::TestVStack::test_mixin_functionality[arrayswap]",
"astropy/table/tests/test_operations.py::TestDStack::test_dstack_skycoord",
"astropy/table/tests/test_operations.py::TestSetdiff::test_missing_key[QTable]",
"astropy/table/tests/test_operations.py::TestDStack::test_validate_join_type",
"astropy/table/tests/test_operations.py::TestJoin::test_rename_conflict[Table]",
"astropy/table/tests/test_operations.py::TestVStack::test_stack_basic_outer[Table]",
"astropy/table/tests/test_operations.py::TestVStack::test_mixin_functionality[ndarraybig]",
"astropy/table/tests/test_operations.py::TestVStack::test_bad_input_type[QTable]",
"astropy/table/tests/test_operations.py::TestJoin::test_mixin_functionality[sphericalrepdiff]",
"astropy/table/tests/test_operations.py::TestJoin::test_both_unmasked_left_right_outer[Table]",
"astropy/table/tests/test_operations.py::TestHStack::test_mixin_functionality[skycoord]",
"astropy/table/tests/test_operations.py::test_masking_required_exception",
"astropy/table/tests/test_operations.py::TestHStack::test_table_meta_merge[QTable]",
"astropy/table/tests/test_operations.py::TestHStack::test_validate_join_type",
"astropy/table/tests/test_operations.py::TestJoin::test_mixin_functionality[latitude]",
"astropy/table/tests/test_operations.py::TestJoin::test_col_rename[Table]",
"astropy/table/tests/test_operations.py::TestJoin::test_col_meta_merge[Table]",
"astropy/table/tests/test_operations.py::TestVStack::test_mixin_functionality[earthlocation]",
"astropy/table/tests/test_operations.py::TestVStack::test_col_meta_merge_outer[Table]",
"astropy/table/tests/test_operations.py::TestHStack::test_stack_same_table[QTable]",
"astropy/table/tests/test_operations.py::TestHStack::test_mixin_functionality[arraywrap]",
"astropy/table/tests/test_operations.py::TestJoin::test_masked_unmasked[Table]",
"astropy/table/tests/test_operations.py::TestVStack::test_stack_incompatible[QTable]",
"astropy/table/tests/test_operations.py::TestHStack::test_hstack_one_masked[Table]",
"astropy/table/tests/test_operations.py::TestHStack::test_mixin_functionality[arrayswap]",
"astropy/table/tests/test_operations.py::TestJoin::test_mixin_functionality[longitude]",
"astropy/table/tests/test_operations.py::TestJoin::test_mixin_functionality[ndarraylil]",
"astropy/table/tests/test_operations.py::TestVStack::test_table_meta_merge_conflict[QTable]",
"astropy/table/tests/test_operations.py::TestDStack::test_dstack_table_column[Table]",
"astropy/table/tests/test_operations.py::test_unique[QTable]",
"astropy/table/tests/test_operations.py::TestJoin::test_mixin_functionality[cartesianrep]",
"astropy/table/tests/test_operations.py::TestJoin::test_masked_masked[Table]",
"astropy/table/tests/test_operations.py::TestJoin::test_missing_keys[QTable]",
"astropy/table/tests/test_operations.py::TestVStack::test_mixin_functionality[skycoord]",
"astropy/table/tests/test_operations.py::TestDStack::test_dstack_different_length_table[QTable]",
"astropy/table/tests/test_operations.py::TestVStack::test_stack_incompatible[Table]",
"astropy/table/tests/test_operations.py::TestHStack::test_col_meta_merge[QTable]",
"astropy/table/tests/test_operations.py::TestSetdiff::test_extra_col_left_table[Table]",
"astropy/table/tests/test_operations.py::TestHStack::test_bad_input_type[Table]",
"astropy/table/tests/test_operations.py::test_mixin_join_regression",
"astropy/table/tests/test_operations.py::TestHStack::test_mixin_functionality[cartesianrep]",
"astropy/table/tests/test_operations.py::TestHStack::test_mixin_functionality[sphericalrep]",
"astropy/table/tests/test_operations.py::TestSetdiff::test_extra_col_right_table[QTable]",
"astropy/table/tests/test_operations.py::TestHStack::test_mixin_functionality[earthlocation]",
"astropy/table/tests/test_operations.py::TestDStack::test_dstack_single_table",
"astropy/table/tests/test_operations.py::TestJoin::test_mixin_functionality[skycoord]",
"astropy/table/tests/test_operations.py::TestVStack::test_mixin_functionality[cartesianrep]",
"astropy/table/tests/test_operations.py::TestJoin::test_both_unmasked_single_key_left_right_outer[Table]",
"astropy/table/tests/test_operations.py::TestVStack::test_vstack_one_table[QTable]",
"astropy/table/tests/test_operations.py::test_sort_indexed_table",
"astropy/table/tests/test_operations.py::TestJoin::test_mixin_functionality[timedelta]",
"astropy/table/tests/test_operations.py::TestJoin::test_join_multidimensional[QTable]",
"astropy/table/tests/test_operations.py::TestJoin::test_mixin_functionality[sphericalrep]",
"astropy/table/tests/test_operations.py::TestVStack::test_mixin_functionality[arraywrap]",
"astropy/table/tests/test_operations.py::test_unique[Table]",
"astropy/table/tests/test_operations.py::TestJoin::test_join_multidimensional_masked[Table]",
"astropy/table/tests/test_operations.py::TestHStack::test_stack_rows[QTable]",
"astropy/table/tests/test_operations.py::TestVStack::test_table_meta_merge[QTable]",
"astropy/table/tests/test_operations.py::TestHStack::test_mixin_functionality[ndarraybig]",
"astropy/table/tests/test_operations.py::TestHStack::test_table_col_rename[QTable]",
"astropy/table/tests/test_operations.py::test_get_out_class",
"astropy/table/tests/test_operations.py::TestHStack::test_mixin_functionality[ndarraylil]",
"astropy/table/tests/test_operations.py::TestSetdiff::test_extra_col_left_table[QTable]",
"astropy/table/tests/test_operations.py::TestHStack::test_stack_incompatible[QTable]",
"astropy/table/tests/test_operations.py::TestJoin::test_mixin_functionality[arraywrap]",
"astropy/table/tests/test_operations.py::TestVStack::test_stack_rows[Table]",
"astropy/table/tests/test_operations.py::TestJoin::test_mixin_functionality[earthlocation]",
"astropy/table/tests/test_operations.py::TestVStack::test_bad_input_type[Table]",
"astropy/table/tests/test_operations.py::TestDStack::test_dstack_multi_dimension_column[Table]",
"astropy/table/tests/test_operations.py::TestJoin::test_both_unmasked_single_key_inner[QTable]",
"astropy/table/tests/test_operations.py::TestSetdiff::test_extra_col_right_table[Table]",
"astropy/table/tests/test_operations.py::TestHStack::test_stack_same_table[Table]",
"astropy/table/tests/test_operations.py::TestHStack::test_table_meta_merge[Table]",
"astropy/table/tests/test_operations.py::TestJoin::test_mixin_functionality[time]",
"astropy/table/tests/test_operations.py::TestHStack::test_stack_rows[Table]",
"astropy/table/tests/test_operations.py::TestJoin::test_join_with_join_skycoord_3d[search_around_3d1]",
"astropy/table/tests/test_operations.py::TestJoin::test_join_with_join_distance_1d",
"astropy/table/tests/test_operations.py::TestHStack::test_table_meta_merge_conflict[QTable]",
"astropy/table/tests/test_operations.py::TestVStack::test_stack_table_column[QTable]",
"astropy/table/tests/test_operations.py::TestHStack::test_col_meta_merge[Table]",
"astropy/table/tests/test_operations.py::TestJoin::test_table_meta_merge_conflict[QTable]",
"astropy/table/tests/test_operations.py::TestVStack::test_table_meta_merge_conflict[Table]",
"astropy/table/tests/test_operations.py::TestHStack::test_stack_basic[Table]",
"astropy/table/tests/test_operations.py::TestJoin::test_both_unmasked_inner[QTable]",
"astropy/table/tests/test_operations.py::TestVStack::test_mixin_functionality[sphericalrep]",
"astropy/table/tests/test_operations.py::test_vstack_bytes[QTable]",
"astropy/table/tests/test_operations.py::TestVStack::test_col_meta_merge_inner[QTable]",
"astropy/table/tests/test_operations.py::TestHStack::test_stack_columns[Table]",
"astropy/table/tests/test_operations.py::TestSetdiff::test_keys[Table]",
"astropy/table/tests/test_operations.py::test_vstack_unicode",
"astropy/table/tests/test_operations.py::TestJoin::test_bad_join_type[QTable]",
"astropy/table/tests/test_operations.py::TestJoin::test_join_with_join_distance_1d_multikey",
"astropy/table/tests/test_operations.py::TestVStack::test_vstack_one_masked[Table]",
"astropy/table/tests/test_operations.py::TestDStack::test_dstack_basic_inner[Table]",
"astropy/table/tests/test_operations.py::TestJoin::test_table_meta_merge_conflict[Table]",
"astropy/table/tests/test_operations.py::TestVStack::test_table_meta_merge[Table]",
"astropy/table/tests/test_operations.py::TestJoin::test_masked_key_column[Table]",
"astropy/table/tests/test_operations.py::TestJoin::test_missing_keys[Table]",
"astropy/table/tests/test_operations.py::TestVStack::test_mixin_functionality[latitude]",
"astropy/table/tests/test_operations.py::TestSetdiff::test_default_same_tables[QTable]",
"astropy/table/tests/test_operations.py::TestJoin::test_cartesian_join[Table]",
"astropy/table/tests/test_operations.py::TestJoin::test_join_with_join_skycoord_3d[search_around_3d0]",
"astropy/table/tests/test_operations.py::TestSetdiff::test_default_same_tables[Table]",
"astropy/table/tests/test_operations.py::TestVStack::test_mixin_functionality[quantity]",
"astropy/table/tests/test_operations.py::TestHStack::test_table_meta_merge_conflict[Table]",
"astropy/table/tests/test_operations.py::TestJoin::test_both_unmasked_inner[Table]",
"astropy/table/tests/test_operations.py::TestJoin::test_table_meta_merge[Table]",
"astropy/table/tests/test_operations.py::TestHStack::test_mixin_functionality[sphericaldiff]",
"astropy/table/tests/test_operations.py::TestJoin::test_mixin_functionality[sphericaldiff]",
"astropy/table/tests/test_operations.py::TestVStack::test_mixin_functionality[time]",
"astropy/table/tests/test_operations.py::TestJoin::test_join_multidimensional[Table]",
"astropy/table/tests/test_operations.py::TestJoin::test_mixin_functionality[arrayswap]",
"astropy/table/tests/test_operations.py::TestJoin::test_col_meta_merge[QTable]",
"astropy/table/tests/test_operations.py::TestJoin::test_join_with_join_skycoord_sky",
"astropy/table/tests/test_operations.py::TestVStack::test_mixin_functionality[timedelta]",
"astropy/table/tests/test_operations.py::test_join_mixins_not_sortable",
"astropy/table/tests/test_operations.py::TestHStack::test_table_col_rename[Table]",
"astropy/table/tests/test_operations.py::TestJoin::test_cartesian_join[QTable]",
"astropy/table/tests/test_operations.py::TestVStack::test_stack_table_column[Table]",
"astropy/table/tests/test_operations.py::TestSetdiff::test_default_same_columns[QTable]",
"astropy/table/tests/test_operations.py::TestHStack::test_hstack_one_table[QTable]",
"astropy/table/tests/test_operations.py::TestVStack::test_stack_rows[QTable]",
"astropy/table/tests/test_operations.py::TestVStack::test_vstack_different_representation",
"astropy/table/tests/test_operations.py::TestHStack::test_hstack_one_table[Table]"
] |
[
"astropy/table/tests/test_operations.py::TestJoin::test_keys_left_right_basic",
"astropy/table/tests/test_operations.py::TestJoin::test_keys_left_right_exceptions"
] |
[
{
"path": "docs/changes/table/#####.api.rst",
"old_path": "/dev/null",
"new_path": "b/docs/changes/table/#####.api.rst",
"metadata": "diff --git a/docs/changes/table/#####.api.rst b/docs/changes/table/#####.api.rst\nnew file mode 100644\nindex 0000000000..4f43558ec0\n--- /dev/null\n+++ b/docs/changes/table/#####.api.rst\n@@ -0,0 +1,3 @@\n+The table ``join`` function now accepts only the first four arguments ``left``,\n+``right``, ``keys``, and ``join_type`` as positional arguments. All other\n+arguments must be supplied as keyword arguments.\n"
},
{
"path": "docs/changes/table/#####.feature.rst",
"old_path": "/dev/null",
"new_path": "b/docs/changes/table/#####.feature.rst",
"metadata": "diff --git a/docs/changes/table/#####.feature.rst b/docs/changes/table/#####.feature.rst\nnew file mode 100644\nindex 0000000000..cf1d327aba\n--- /dev/null\n+++ b/docs/changes/table/#####.feature.rst\n@@ -0,0 +1,5 @@\n+Added new keyword arguments ``keys_left`` and ``keys_right`` to the table ``join``\n+function to support joining tables on key columns with different names. In\n+addition the new keywords can accept a list of column-like objects which are\n+used as the match keys. This allows joining on arbitrary data which are not part\n+of the tables being joined.\n"
},
{
"path": "docs/table/operations.rst",
"old_path": "a/docs/table/operations.rst",
"new_path": "b/docs/table/operations.rst",
"metadata": "diff --git a/docs/table/operations.rst b/docs/table/operations.rst\nindex 5e1591a516..a280471703 100644\n--- a/docs/table/operations.rst\n+++ b/docs/table/operations.rst\n@@ -855,40 +855,31 @@ Non-Identical Key Column Names\n \n .. EXAMPLE START: Joining Tables with Unique Key Column Names\n \n-The |join| function requires the key column names to be identical in the\n-two tables. However, in the following, one table has a ``'name'`` column\n-while the other has an ``'obj_id'`` column::\n+To use the |join| function with non-identical key column names, use the\n+``keys_left`` and ``keys_right`` arguments. In the following example one table\n+has a ``'name'`` column while the other has an ``'obj_id'`` column::\n \n >>> optical = Table.read(\"\"\"name obs_date mag_b mag_v\n ... M31 2012-01-02 17.0 16.0\n ... M82 2012-10-29 16.2 15.2\n ... M101 2012-10-31 15.1 15.5\"\"\", format='ascii')\n- >>> xray_1 = Table.read(\"\"\" obj_id obs_date logLx\n- ... NGC3516 2011-11-11 42.1\n- ... M31 1999-01-05 43.1\n- ... M82 2012-10-29 45.0\"\"\", format='ascii')\n-\n-In order to perform a match based on the names of the objects, you have to\n-temporarily rename one of the columns mentioned above, right before creating\n-the new table::\n-\n- >>> xray_1.rename_column('obj_id', 'name')\n- >>> opt_xray_1 = join(optical, xray_1, keys='name')\n- >>> xray_1.rename_column('name', 'obj_id')\n- >>> print(opt_xray_1)\n- name obs_date_1 mag_b mag_v obs_date_2 logLx\n- ---- ---------- ----- ----- ---------- -----\n- M31 2012-01-02 17.0 16.0 1999-01-05 43.1\n- M82 2012-10-29 16.2 15.2 2012-10-29 45.0\n-\n-The original ``xray_1`` table remains unchanged after the operation::\n-\n- >>> print(xray_1)\n- obj_id obs_date logLx\n- ------- ---------- -----\n- NGC3516 2011-11-11 42.1\n- M31 1999-01-05 43.1\n- M82 2012-10-29 45.0\n+ >>> xray_1 = Table.read(\"\"\"obj_id obs_date logLx\n+ ... NGC3516 2011-11-11 42.1\n+ ... M31 1999-01-05 43.1\n+ ... M82 2012-10-29 45.0\"\"\", format='ascii')\n+\n+In order to perform a match based on the names of the objects, do the\n+following::\n+\n+ >>> print(join(optical, xray_1, keys_left='name', keys_right='obj_id'))\n+ name obs_date_1 mag_b mag_v obj_id obs_date_2 logLx\n+ ---- ---------- ----- ----- ------ ---------- -----\n+ M31 2012-01-02 17.0 16.0 M31 1999-01-05 43.1\n+ M82 2012-10-29 16.2 15.2 M82 2012-10-29 45.0\n+\n+The ``keys_left`` and ``keys_right`` arguments can also take a list of column\n+names or even a list of column-like objects. The latter case allows specifying\n+the matching key column values independent of the tables being joined.\n \n .. EXAMPLE END\n \n"
}
] |
{
"header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:",
"data": []
}
|
diff --git a/docs/changes/table/#####.api.rst b/docs/changes/table/#####.api.rst
new file mode 100644
index 0000000000..4f43558ec0
--- /dev/null
+++ b/docs/changes/table/#####.api.rst
@@ -0,0 +1,3 @@
+The table ``join`` function now accepts only the first four arguments ``left``,
+``right``, ``keys``, and ``join_type`` as positional arguments. All other
+arguments must be supplied as keyword arguments.
diff --git a/docs/changes/table/#####.feature.rst b/docs/changes/table/#####.feature.rst
new file mode 100644
index 0000000000..cf1d327aba
--- /dev/null
+++ b/docs/changes/table/#####.feature.rst
@@ -0,0 +1,5 @@
+Added new keyword arguments ``keys_left`` and ``keys_right`` to the table ``join``
+function to support joining tables on key columns with different names. In
+addition the new keywords can accept a list of column-like objects which are
+used as the match keys. This allows joining on arbitrary data which are not part
+of the tables being joined.
diff --git a/docs/table/operations.rst b/docs/table/operations.rst
index 5e1591a516..a280471703 100644
--- a/docs/table/operations.rst
+++ b/docs/table/operations.rst
@@ -855,40 +855,31 @@ Non-Identical Key Column Names
.. EXAMPLE START: Joining Tables with Unique Key Column Names
-The |join| function requires the key column names to be identical in the
-two tables. However, in the following, one table has a ``'name'`` column
-while the other has an ``'obj_id'`` column::
+To use the |join| function with non-identical key column names, use the
+``keys_left`` and ``keys_right`` arguments. In the following example one table
+has a ``'name'`` column while the other has an ``'obj_id'`` column::
>>> optical = Table.read("""name obs_date mag_b mag_v
... M31 2012-01-02 17.0 16.0
... M82 2012-10-29 16.2 15.2
... M101 2012-10-31 15.1 15.5""", format='ascii')
- >>> xray_1 = Table.read(""" obj_id obs_date logLx
- ... NGC3516 2011-11-11 42.1
- ... M31 1999-01-05 43.1
- ... M82 2012-10-29 45.0""", format='ascii')
-
-In order to perform a match based on the names of the objects, you have to
-temporarily rename one of the columns mentioned above, right before creating
-the new table::
-
- >>> xray_1.rename_column('obj_id', 'name')
- >>> opt_xray_1 = join(optical, xray_1, keys='name')
- >>> xray_1.rename_column('name', 'obj_id')
- >>> print(opt_xray_1)
- name obs_date_1 mag_b mag_v obs_date_2 logLx
- ---- ---------- ----- ----- ---------- -----
- M31 2012-01-02 17.0 16.0 1999-01-05 43.1
- M82 2012-10-29 16.2 15.2 2012-10-29 45.0
-
-The original ``xray_1`` table remains unchanged after the operation::
-
- >>> print(xray_1)
- obj_id obs_date logLx
- ------- ---------- -----
- NGC3516 2011-11-11 42.1
- M31 1999-01-05 43.1
- M82 2012-10-29 45.0
+ >>> xray_1 = Table.read("""obj_id obs_date logLx
+ ... NGC3516 2011-11-11 42.1
+ ... M31 1999-01-05 43.1
+ ... M82 2012-10-29 45.0""", format='ascii')
+
+In order to perform a match based on the names of the objects, do the
+following::
+
+ >>> print(join(optical, xray_1, keys_left='name', keys_right='obj_id'))
+ name obs_date_1 mag_b mag_v obj_id obs_date_2 logLx
+ ---- ---------- ----- ----- ------ ---------- -----
+ M31 2012-01-02 17.0 16.0 M31 1999-01-05 43.1
+ M82 2012-10-29 16.2 15.2 M82 2012-10-29 45.0
+
+The ``keys_left`` and ``keys_right`` arguments can also take a list of column
+names or even a list of column-like objects. The latter case allows specifying
+the matching key column values independent of the tables being joined.
.. EXAMPLE END
|
astropy/astropy
|
astropy__astropy-11998
|
https://github.com/astropy/astropy/pull/11998
|
diff --git a/astropy/cosmology/__init__.py b/astropy/cosmology/__init__.py
index 4fc4d01ce501..a9c581e8b501 100644
--- a/astropy/cosmology/__init__.py
+++ b/astropy/cosmology/__init__.py
@@ -8,7 +8,9 @@
"""
-from . import core, funcs, realizations, units, utils
+from . import core, funcs, units, utils
+from . import io # isort: split # needed before 'realizations'
+from . import realizations
from .core import *
from .funcs import *
from .realizations import *
diff --git a/astropy/cosmology/connect.py b/astropy/cosmology/connect.py
index bfe84f2e836c..f1161eb1859d 100644
--- a/astropy/cosmology/connect.py
+++ b/astropy/cosmology/connect.py
@@ -6,10 +6,14 @@
from astropy.io import registry as io_registry
from astropy.utils.exceptions import AstropyUserWarning
-__all__ = ["CosmologyRead", "CosmologyWrite"]
+__all__ = ["CosmologyRead", "CosmologyWrite",
+ "CosmologyFromFormat", "CosmologyToFormat"]
__doctest_skip__ = __all__
+# ==============================================================================
+# Read / Write
+
class CosmologyRead(io_registry.UnifiedReadWrite):
"""Read and parse data to a `~astropy.cosmology.Cosmology`.
@@ -18,10 +22,10 @@ class CosmologyRead(io_registry.UnifiedReadWrite):
syntax such as::
>>> from astropy.cosmology import Cosmology
- >>> cosmo1 = Cosmology.read('[file name]')
+ >>> cosmo1 = Cosmology.read('<file name>')
When the ``read`` method is called from a subclass the subclass will
- provide a keyword argument ``cosmology=[class]`` to the registered read
+ provide a keyword argument ``cosmology=<class>`` 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.
@@ -29,11 +33,19 @@ class CosmologyRead(io_registry.UnifiedReadWrite):
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.help(format='<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
+ .. note::
+
+ :meth:`~astropy.cosmology.Cosmology.read` and
+ :meth:`~astropy.cosmology.Cosmology.from_format` currently access the
+ same registry. This will be deprecated and formats intended for
+ ``from_format`` should not be used here. Use ``Cosmology.read.help()``
+ to confirm that the format may be used to read a file.
+
Parameters
----------
*args
@@ -48,6 +60,9 @@ class CosmologyRead(io_registry.UnifiedReadWrite):
-------
out : `~astropy.cosmology.Cosmology` subclass instance
`~astropy.cosmology.Cosmology` corresponding to file contents.
+
+ Notes
+ -----
"""
def __init__(self, instance, cosmo_cls):
@@ -77,19 +92,27 @@ 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
+ layer. This allows easily writing a file in supported data formats
using syntax such as::
>>> from astropy.cosmology import Planck18
- >>> Planck18.write('[file name]')
+ >>> Planck18.write('<file name>')
- Get help on the available writers for ``Cosmology`` using the``help()``
+ 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.help(format='<format>') # Get detailed help on format
>>> Cosmology.write.list_formats() # Print list of available formats
+ .. note::
+
+ :meth:`~astropy.cosmology.Cosmology.write` and
+ :meth:`~astropy.cosmology.Cosmology.to_format` currently access the
+ same registry. This will be deprecated and formats intended for
+ ``to_format`` should not be used here. Use ``Cosmology.write.help()``
+ to confirm that the format may be used to write to a file.
+
Parameters
----------
*args
@@ -99,6 +122,9 @@ class CosmologyWrite(io_registry.UnifiedReadWrite):
File format specifier.
**kwargs
Keyword arguments passed through to data writer.
+
+ Notes
+ -----
"""
def __init__(self, instance, cls):
@@ -106,3 +132,129 @@ def __init__(self, instance, cls):
def __call__(self, *args, **kwargs):
io_registry.write(self._instance, *args, **kwargs)
+
+
+# ==============================================================================
+# Format Interchange
+# for transforming instances, e.g. Cosmology <-> dict
+
+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=<class>`` 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('<format>') # 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
+
+ .. note::
+
+ :meth:`~astropy.cosmology.Cosmology.from_format` and
+ :meth:`~astropy.cosmology.Cosmology.read` currently access the
+ same registry. This will be deprecated and formats intended for
+ ``read`` should not be used here. Use ``Cosmology.to_format.help()``
+ to confirm that the format may be used to convert to a Cosmology.
+
+ Parameters
+ ----------
+ obj : object
+ The object to parse according to 'format'
+ *args
+ Positional arguments passed through to data parser.
+ format : str (optional, keyword-only)
+ Object format specifier.
+ **kwargs
+ Keyword arguments passed through to data parser.
+
+ Returns
+ -------
+ out : `~astropy.cosmology.Cosmology` subclass instance
+ `~astropy.cosmology.Cosmology` corresponding to ``obj`` contents.
+
+ """
+
+ def __init__(self, instance, cosmo_cls):
+ super().__init__(instance, cosmo_cls, "read")
+
+ def __call__(self, obj, *args, **kwargs):
+ from astropy.cosmology.core import Cosmology
+
+ # so subclasses can override, also pass the class as a kwarg.
+ # allows for `FlatLambdaCDM.read` and
+ # `Cosmology.read(..., cosmology=FlatLambdaCDM)`
+ if self._cls is not Cosmology:
+ kwargs.setdefault("cosmology", self._cls) # set, if not present
+ # check that it is the correct cosmology, can be wrong if user
+ # passes in e.g. `w0wzCDM.read(..., cosmology=FlatLambdaCDM)`
+ valid = (self._cls, self._cls.__qualname__)
+ if kwargs["cosmology"] not in valid:
+ raise ValueError(
+ "keyword argument `cosmology` must be either the class "
+ f"{valid[0]} or its qualified name '{valid[1]}'")
+
+ cosmo = io_registry.read(self._cls, obj, *args, **kwargs)
+ return cosmo
+
+
+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': <Quantity 67.66 km / (Mpc s)>,
+ '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('<format>') # Get detailed help on format
+ >>> Cosmology.to_format.list_formats() # Print list of available formats
+
+ .. note::
+
+ :meth:`~astropy.cosmology.Cosmology.to_format` and
+ :meth:`~astropy.cosmology.Cosmology.write` currently access the
+ same registry. This will be deprecated and formats intended for
+ ``write`` should not be used here. Use ``Cosmology.to_format.help()``
+ to confirm that the format may be used to convert a Cosmology.
+
+ 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):
+ super().__init__(instance, cls, "write")
+
+ def __call__(self, format, *args, **kwargs):
+ return io_registry.write(self._instance, None, *args, format=format,
+ **kwargs)
diff --git a/astropy/cosmology/core.py b/astropy/cosmology/core.py
index f5fbf4d96aad..dfd48f354349 100644
--- a/astropy/cosmology/core.py
+++ b/astropy/cosmology/core.py
@@ -18,7 +18,7 @@
from astropy.utils.metadata import MetaData
from . import scalar_inv_efuncs
-from .connect import CosmologyRead, CosmologyWrite
+from .connect import CosmologyFromFormat, CosmologyRead, CosmologyToFormat, CosmologyWrite
from .utils import _float_or_none, inf_like, vectorize_if_needed
# Originally authored by Andrew Becker (becker@astro.washington.edu),
@@ -82,6 +82,10 @@ class Cosmology(metaclass=ABCMeta):
meta = MetaData()
+ # Unified I/O object interchange methods
+ from_format = UnifiedReadWriteMethod(CosmologyFromFormat)
+ to_format = UnifiedReadWriteMethod(CosmologyToFormat)
+
# Unified I/O read and write methods
read = UnifiedReadWriteMethod(CosmologyRead)
write = UnifiedReadWriteMethod(CosmologyWrite)
diff --git a/astropy/cosmology/io/__init__.py b/astropy/cosmology/io/__init__.py
new file mode 100644
index 000000000000..c7816e15805b
--- /dev/null
+++ b/astropy/cosmology/io/__init__.py
@@ -0,0 +1,9 @@
+# -*- coding: utf-8 -*-
+# Licensed under a 3-clause BSD style license - see LICENSE.rst
+
+"""
+Read/Write/Interchange methods for `astropy.cosmology`. **NOT public API**.
+"""
+
+# Import the interchange to register them into the io registry.
+from . import mapping # noqa: F403
diff --git a/astropy/cosmology/io/mapping.py b/astropy/cosmology/io/mapping.py
new file mode 100644
index 000000000000..05466305db75
--- /dev/null
+++ b/astropy/cosmology/io/mapping.py
@@ -0,0 +1,183 @@
+# Licensed under a 3-clause BSD style license - see LICENSE.rst
+
+"""
+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.
+""" # this is shown in the docs.
+
+import copy
+from collections.abc import Mapping
+
+import numpy as np
+
+from astropy.cosmology.core import _COSMOLOGY_CLASSES, Cosmology
+from astropy.io import registry as io_registry
+from astropy.table import QTable
+
+__all__ = ["from_mapping", "to_mapping"]
+
+
+def from_mapping(map, *, move_to_meta=False, cosmology=None):
+ """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': <class 'astropy.cosmology.core.FlatLambdaCDM'>,
+ 'name': 'Planck18', 'H0': <Quantity 67.66 km / (Mpc s)>, 'Om0': 0.30966,
+ 'Tcmb0': 2.7255, 'Neff': 3.046, 'm_nu': <Quantity [0. , 0. , 0.06] eV>,
+ '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.7 km / (Mpc s), Om0=0.31,
+ Tcmb0=2.725 K, Neff=3.05, m_nu=[0. 0. 0.06] eV, Ob0=0.049)
+
+ 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.7 km / (Mpc s), Om0=0.31,
+ Tcmb0=0 K, Neff=3.05, m_nu=None, Ob0=0.049)
+
+ """
+ params = copy.deepcopy(map) # so can pop
+
+ # get cosmology
+ # 1st from 'kwargs'. Allows for override of the cosmology, if on file.
+ # 2nd from params. This MUST have the cosmology if 'kwargs' did not.
+ if cosmology is None:
+ cosmology = params.pop("cosmology")
+ else:
+ params.pop("cosmology", None) # pop, but don't use
+ # if string, parse to class
+ if isinstance(cosmology, str):
+ cosmology = _COSMOLOGY_CLASSES[cosmology]
+
+ # select arguments from mapping that are in the cosmo's signature.
+ ba = cosmology._init_signature.bind_partial() # blank set of args
+ ba.apply_defaults() # fill in the defaults
+ for k in cosmology._init_signature.parameters.keys():
+ if k in params: # transfer argument, if in params
+ ba.arguments[k] = params.pop(k)
+
+ # deal with remaining params. If there is a **kwargs use that, else
+ # allow to transfer to metadata. Raise TypeError if can't.
+ lastp = tuple(cosmology._init_signature.parameters.values())[-1]
+ if lastp.kind == 4: # variable keyword-only
+ ba.arguments[lastp.name] = params
+ elif move_to_meta: # prefers current meta, which was explicitly set
+ meta = ba.arguments["meta"] or {} # (None -> dict)
+ ba.arguments["meta"] = {**params, **meta}
+ elif params:
+ raise TypeError(f"there are unused parameters {params}.")
+ # else: pass # no kwargs, no move-to-meta, and all the params are used
+
+ return cosmology(*ba.args, **ba.kwargs)
+
+
+def to_mapping(cosmology, *args):
+ """Return the cosmology class, inputs, and metadata as a `dict`.
+
+ Parameters
+ ----------
+ cosmology : `~astropy.cosmology.Cosmology` subclass instance
+ *args
+ Not used. Needed for compatibility with
+ `~astropy.io.registry.UnifiedReadWriteMethod`
+
+ Returns
+ -------
+ dict
+ with key-values for the cosmology parameters and also:
+ - 'cosmology' : the class
+ - 'meta' : the contents of the cosmology's metadata attribute
+
+ 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': <class 'astropy.cosmology.core.FlatLambdaCDM'>,
+ 'name': 'Planck18', 'H0': <Quantity 67.66 km / (Mpc s)>, 'Om0': 0.30966,
+ 'Tcmb0': 2.7255, 'Neff': 3.046, 'm_nu': <Quantity [0. , 0. , 0.06] eV>,
+ 'Ob0': 0.04897, 'meta': ...
+
+ """
+
+ m = {}
+ # start with the cosmology class & name
+ m["cosmology"] = cosmology.__class__
+ m["name"] = cosmology.name # here only for dict ordering
+ # get all the immutable inputs
+ m.update({k: v for k, v in cosmology._init_arguments.items()
+ if k not in ("meta", "name")})
+ # add the mutable metadata
+ m["meta"] = copy.deepcopy(cosmology.meta)
+
+ return m
+
+
+def mapping_identify(origin, format, *args, **kwargs):
+ """Identify if object uses the mapping format.
+
+ Returns
+ -------
+ bool
+ """
+ itis = False
+ if origin == "read":
+ itis = isinstance(args[1], Mapping) and (format in (None, "mapping"))
+
+ return itis
+
+
+# ===================================================================
+# Register
+
+io_registry.register_reader("mapping", Cosmology, from_mapping)
+io_registry.register_writer("mapping", Cosmology, to_mapping)
+io_registry.register_identifier("mapping", Cosmology, mapping_identify)
diff --git a/docs/changes/cosmology/11998.feature.rst b/docs/changes/cosmology/11998.feature.rst
new file mode 100644
index 000000000000..df78f84a93c9
--- /dev/null
+++ b/docs/changes/cosmology/11998.feature.rst
@@ -0,0 +1,5 @@
+Added ``to_format/from_format`` methods to Cosmology using the Unified I/O
+registry. Now custom format converters and format-identifier functions
+can be registered to transform Cosmology objects.
+The transformation between Cosmology and dictionaries is pre-registered.
+Details are discussed in an addition to the docs.
diff --git a/docs/cosmology/io.rst b/docs/cosmology/io.rst
index bb9f1881b4d1..db5f9509a287 100644
--- a/docs/cosmology/io.rst
+++ b/docs/cosmology/io.rst
@@ -1,25 +1,22 @@
-.. doctest-skip-all
-
.. _read_write_cosmologies:
-Reading and Writing Cosmology Objects
-*************************************
+Read, Write, and Convert Cosmology Objects
+******************************************
An easy way to serialize and deserialize a Cosmology object is using the
:mod:`pickle` module.
-.. code-block:: python
- :emphasize-lines: 1,4,8
+.. doctest-skip::
>>> import pickle
>>> from astropy.cosmology import Planck18
>>> with open("planck18.pkl", mode="wb") as file:
- ... pickle.dump(file, Planck18)
-
- And to read the file back
+ ... pickle.dump(Planck18, file)
+ >>> # and to read back
>>> with open("planck18.pkl", mode="rb") as file:
- >>> cosmo = pickle.load(file)
+ ... cosmo = pickle.load(file)
>>> cosmo
+ FlatLambdaCDM(name="Planck18", ...
However this method has all the attendant drawbacks of :mod:`pickle` — security
vulnerabilities and non-human-readable files.
@@ -43,34 +40,197 @@ framework.
Writing a cosmology instance requires only the file location and optionally,
if the file format cannot be inferred, a keyword argument "format". Additional
positional arguments and keyword arguments are passed to the reader methods.
-::
+
+.. doctest-skip::
>>> from astropy.cosmology import Planck18
- >>> Planck18.write('[file name]')
+ >>> Planck18.write('<file name>')
Reading back the cosmology is most safely done from ``Cosmology``, the base
class, as it provides no default information and therefore requires the file
to have all necessary information to describe a cosmology.
-::
+.. doctest-skip::
>>> from astropy.cosmology import Cosmology
- >>> cosmo = Cosmology.read('[file name]')
+ >>> cosmo = Cosmology.read('<file name>')
>>> cosmo == Planck18
True
When a subclass of ``Cosmology`` is used to read a file, the subclass will
-provide a keyword argument ``cosmology=[class]`` to the registered read
+provide a keyword argument ``cosmology=<class>`` 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.
-::
+.. doctest-skip::
>>> from astropy.cosmology import FlatLambdaCDM
- >>> cosmo = FlatLambdaCDM.read('[file name]')
+ >>> cosmo = FlatLambdaCDM.read('<file name>')
>>> cosmo == Planck18
True
+
+Reading and writing :class:`~astropy.cosmology.Cosmology` objects go through
+intermediate representations, often a dict or `~astropy.table.QTable` instance.
+These intermediate representations are accessible through the methods
+:meth:`~astropy.cosmology.Cosmology.to_format` /
+:meth:`~astropy.cosmology.Cosmology.from_format`.
+
+To see the a list of the available formats:
+
+ >>> from astropy.cosmology import Cosmology
+ >>> Cosmology.to_format.list_formats()
+ Format Read Write Auto-identify
+ ------- ---- ----- -------------
+ mapping Yes Yes Yes
+
+This list will include both built-in and registered 3rd-party formats.
+
+:meth:`~astropy.cosmology.Cosmology.to_format` /
+:meth:`~astropy.cosmology.Cosmology.from_format` parse a Cosmology to/from
+another python object. This can be useful for e.g., iterating through an MCMC
+of cosmological parameters or printing out a cosmological model to a journal
+format, like latex or HTML. When 3rd party cosmology packages register with
+Astropy' Cosmology I/O, ``to/from_format`` can be used to convert cosmology
+instances between packages!
+
+.. EXAMPLE START: Planck18 to mapping and back
+
+.. code-block::
+
+ >>> from astropy.cosmology import Planck18
+ >>> cm = Planck18.to_format("mapping")
+ >>> cm
+ {'cosmology': <class 'astropy.cosmology.core.FlatLambdaCDM'>,
+ 'name': 'Planck18',
+ 'H0': <Quantity 67.66 km / (Mpc s)>,
+ 'Om0': 0.30966,
+ ...
+
+Now this dict can be used to load a new cosmological instance identical
+to the ``Planck18`` cosmology from which it was created.
+
+.. code-block::
+
+ >>> from astropy.cosmology import Cosmology
+ >>> cosmo = Cosmology.from_format(cm, format="mapping")
+ >>> cosmo == Planck18
+ True
+
+.. EXAMPLE END
+
+
+
+.. _custom_cosmology_converters:
+
+Custom Cosmology To/From Formats
+================================
+
+Custom representation formats may also be registered into the Astropy Cosmology
+I/O framework for use by these methods. For details of the framework see
+:ref:`io_registry`.
+
+.. EXAMPLE START : custom to/from format
+
+As an example, the following is an implementation of an `astropy.table.Row`
+converter. Note that we can use other registered parsers -- here "mapping"
+-- to make the implementation much simpler.
+
+We start by defining the function to parse a `astropy.table.Row` into a
+`~astropy.cosmology.Cosmology`. This function should take 1 positional
+argument, the row object, and 2 keyword arguments, for how to handle
+extra metadata and which Cosmology class to use. Details about metadata
+treatment are in ``Cosmology.from_format.help("mapping")``.
+
+.. code-block:: python
+ :emphasize-lines: 12,13
+
+ >>> import copy
+ >>> from astropy.cosmology import Cosmology
+
+ >>> def from_table_row(row, *, move_to_meta=False, cosmology=None):
+ ... # get name from column
+ ... name = row['name'] if 'name' in row.columns else None
+ ... meta = copy.deepcopy(row.meta)
+ ... # turn row into mapping (dict of the arguments)
+ ... mapping = dict(row)
+ ... mapping["meta"] = meta
+ ... # build cosmology from map
+ ... return Cosmology.from_format(mapping,
+ ... move_to_meta=move_to_meta, cosmology=cosmology)
+
+The next step is a function to perform the reverse operation: parse a
+`~astropy.cosmology.Cosmology` into a `~astropy.table.Row`. This function
+requires only the cosmology object and a ``*args`` to absorb unneeded
+information passed by `astropy.io.registry.UnifiedReadWrite` (which
+implements `astropy.cosmology.Cosmology.to_format`).
+
+.. code-block:: python
+ :emphasize-lines: 4
+
+ >>> from astropy.table import QTable
+
+ >>> def to_table_row(cosmology, *args):
+ ... p = cosmology.to_format("mapping")
+ ... p["cosmology"] = p["cosmology"].__qualname__ # as string
+ ... meta = p.pop("meta")
+ ... # package parameters into lists for Table parsing
+ ... params = {k: [v] for k, v in p.items()}
+ ... return QTable(params, meta=meta)[0] # return row
+
+Last we write a function to help with format auto-identification and then
+register everything into `astropy.io.registry`.
+
+.. code-block:: python
+ :emphasize-lines: 11, 12, 13
+
+ >>> from astropy.cosmology import Cosmology
+ >>> from astropy.io import registry as io_registry
+ >>> from astropy.table import Row
+
+ >>> def row_identify(origin, format, *args, **kwargs):
+ ... """Identify if object uses the Table format."""
+ ... if origin == "read":
+ ... return isinstance(args[1], Row) and (format in (None, "row"))
+ ... return False
+
+ >>> io_registry.register_reader("row", Cosmology, from_table_row)
+ >>> io_registry.register_writer("row", Cosmology, to_table_row)
+ >>> io_registry.register_identifier("row", Cosmology, row_identify)
+
+Now the registered functions can be used in
+:meth:`astropy.cosmology.Cosmology.from_format` and
+:meth:`astropy.cosmology.Cosmology.to_format`.
+
+.. code-block:: python
+
+ >>> from astropy.cosmology import Planck18
+ >>> row = Planck18.to_format("row")
+ >>> row
+ <Row index=0>
+ cosmology name H0 Om0 Tcmb0 Neff m_nu [3] Ob0
+ km / (Mpc s) eV
+ str13 str8 float64 float64 float64 float64 float64 float64
+ ------------- -------- ------------ ------- ------- ------- ----------- -------
+ FlatLambdaCDM Planck18 67.66 0.30966 2.7255 3.046 0.0 .. 0.06 0.04897
+
+ >>> cosmo = Cosmology.from_format(row)
+ >>> cosmo == Planck18 # test it round-trips
+ True
+
+
+.. doctest::
+ :hide:
+
+ >>> io_registry.unregister_reader("row", Cosmology)
+ >>> io_registry.unregister_writer("row", Cosmology)
+ >>> io_registry.unregister_identifier("row", Cosmology)
+ >>> try:
+ ... io_registry.get_reader("row", Cosmology)
+ ... except io_registry.IORegistryError:
+ ... pass
+
+.. EXAMPLE END
.. _custom_cosmology_readers_writers:
@@ -80,35 +240,125 @@ Custom Cosmology Readers/Writers
Custom ``read`` / ``write`` formats may be registered into the Astropy Cosmology
I/O framework. For details of the framework see :ref:`io_registry`.
-As a quick example, outlining how to make a
-`~astropy.cosmology.Cosmology` <-> JSON serializer:
+
+.. EXAMPLE START : custom read/write
+
+As an example, in the following we will fully work out a
+`~astropy.cosmology.Cosmology` <-> JSON (de)serializer.
+Note that we can use other registered parsers -- here "mapping"
+-- to make the implementation much simpler.
+
+We start by defining the function to parse JSON into a
+`~astropy.cosmology.Cosmology`. This function should take 1 positional
+argument, the file object or file path. We will also pass kwargs through to
+:meth:`~astropy.cosmology.Cosmology.from_format`, which handles metadata
+and which Cosmology class to use. Details of are in
+``Cosmology.from_format.help("mapping")``.
.. code-block:: python
+ :emphasize-lines: 9,12,17
- import json
- from astropy.cosmology import Cosmology
- from astropy.io import registry as io_registry
+ >>> import json, os
+ >>> import astropy.units as u
+ >>> from astropy.cosmology import Cosmology
- def read_json(filename, **kwargs):
- cosmology = ... # read and parse file
- return cosmology
+ >>> def read_json(filename, **kwargs):
+ ... # read file, from path-like or file-like
+ ... if isinstance(filename, (str, bytes, os.PathLike)):
+ ... with open(filename, "r") as file:
+ ... data = file.read()
+ ... else: # file-like : this also handles errors in dumping
+ ... data = filename.read()
+ ... mapping = json.loads(data) # parse json mappable to dict
+ ... # deserialize Quantity
+ ... for k, v in mapping.items():
+ ... if isinstance(v, dict) and "value" in v and "unit" in v:
+ ... mapping[k] = u.Quantity(v["value"], v["unit"])
+ ... return Cosmology.from_format(mapping, **kwargs)
+
+
+The next step is a function to write a `~astropy.cosmology.Cosmology` to
+JSON. This function requires the cosmology object and a file object/path.
+We also require the boolean flag "overwrite" to set behavior for existing
+files. Note that `~astropy.units.Quantity` is not natively compatible with
+JSON. In both the ``write`` and ``read`` methods we have to create custom
+parsers.
+
+.. code-block:: python
+ :emphasize-lines: 2,15
+
+ >>> def write_json(cosmology, file, *, overwrite=False, **kwargs):
+ ... data = cosmology.to_format("mapping") # start by turning into dict
+ ... data["cosmology"] = data["cosmology"].__name__ # change class field to str
+ ... # serialize Quantity
+ ... for k, v in data.items():
+ ... if isinstance(v, u.Quantity):
+ ... data[k] = {"value": v.value.tolist(),
+ ... "unit": str(v.unit)}
+ ...
+ ... if isinstance(file, (str, bytes, os.PathLike)):
+ ... # check that file exists and whether to overwrite.
+ ... if os.path.exists(file) and not overwrite:
+ ... raise IOError(f"{file} exists. Set 'overwrite' to write over.")
+ ... with open(file, "w") as write_file:
+ ... json.dump(data, write_file)
+ ... else:
+ ... json.dump(data, file)
+
+Last we write a function to help with format auto-identification and then
+register everything into `astropy.io.registry`.
+
+.. code-block:: python
+ :emphasize-lines: 7,8,9
- def write_json(cosmology, file, **kwargs):
- data = ... # parse cosmology to dict
- with open(file, "w") as write_file:
- json.dump(data, write_file)
+ >>> from astropy.io import registry as io_registry
- def json_identify(origin, filepath, fileobj, *args, **kwargs):
- """Identify if object uses the JSON format."""
- return filepath is not None and filepath.endswith(".json")
+ >>> def json_identify(origin, filepath, fileobj, *args, **kwargs):
+ ... """Identify if object uses the JSON format."""
+ ... return filepath is not None and filepath.endswith(".json")
- # register the read/write methods
- io_registry.register_reader("json", Cosmology, read_json)
- io_registry.register_writer("json", Cosmology, write_json)
- io_registry.register_identifier("json", Cosmology, json_identify)
+ >>> io_registry.register_reader("json", Cosmology, read_json)
+ >>> io_registry.register_writer("json", Cosmology, write_json)
+ >>> io_registry.register_identifier("json", Cosmology, json_identify)
+
+Now the registered functions can be used in
+:meth:`astropy.cosmology.Cosmology.read` and
+:meth:`astropy.cosmology.Cosmology.write`.
+.. doctest-skip:: win32
+
+ >>> import tempfile
+ >>> from astropy.cosmology import Planck18
+ >>>
+ >>> file = tempfile.NamedTemporaryFile()
+ >>> Planck18.write(file.name, format="json", overwrite=True)
+ >>> with open(file.name) as f: f.readlines()
+ ['{"cosmology": "FlatLambdaCDM", "name": "Planck18",
+ "H0": {"value": 67.66, "unit": "km / (Mpc s)"}, "Om0": 0.30966,
+ ...
+ >>>
+ >>> cosmo = Cosmology.read(file.name, format="json")
+ >>> file.close()
+ >>> cosmo == Planck18 # test it round-trips
+ True
+
+
+.. doctest::
+ :hide:
+
+ >>> io_registry.unregister_reader("json", Cosmology)
+ >>> io_registry.unregister_writer("json", Cosmology)
+ >>> io_registry.unregister_identifier("json", Cosmology)
+ >>> try:
+ ... io_registry.get_reader("json", Cosmology)
+ ... except io_registry.IORegistryError:
+ ... pass
+
+.. EXAMPLE END
Reference/API
=============
.. automodapi:: astropy.cosmology.connect
+
+.. automodapi:: astropy.cosmology.io.mapping
diff --git a/docs/whatsnew/5.0.rst b/docs/whatsnew/5.0.rst
index b8c135bb606f..a224b149c972 100644
--- a/docs/whatsnew/5.0.rst
+++ b/docs/whatsnew/5.0.rst
@@ -9,6 +9,47 @@ What's New in Astropy 5.0?
Overview
========
+.. _whatsnew-5.0-cosmology:
+
+Support for reading, writing, and converting ``Cosmology``
+==========================================================
+
+Four new methods -- ``read``, ``write``, ``to_format``, ``from_format`` -- have
+been added to the ``Cosmology`` class, enabling reading from and writing to
+files and converting between different python objects.
+The methods use Astropy's Unified I/O registry so custom formats can be
+registered. Details are discussed in an addition to the docs.
+
+Currently no file formats are registered, but the syntax is as follows:
+
+.. doctest-skip::
+
+ >>> from astropy.cosmology import Planck18
+ >>> Planck18.write('<file name>.<format>')
+ >>>
+ >>> from astropy.cosmology import Cosmology
+ >>> cosmo = Cosmology.read('<file name>.<format>')
+ >>> cosmo == Planck18
+ True
+
+
+The transformation between ``Cosmology`` and `dict` is pre-registered,
+e.g. enabling::
+
+ >>> from astropy.cosmology import Planck18
+ >>> cm = Planck18.to_format("mapping")
+ >>> cm
+ {'cosmology': <class 'astropy.cosmology.core.FlatLambdaCDM'>,
+ 'name': 'Planck18',
+ 'H0': <Quantity 67.66 km / (Mpc s)>,
+ 'Om0': 0.30966,
+ ...
+
+ >>> from astropy.cosmology import Cosmology
+ >>> cosmo = Cosmology.from_format(cm, format="mapping")
+ >>> cosmo == Planck18
+ True
+
Full change log
===============
|
diff --git a/astropy/cosmology/io/tests/__init__.py b/astropy/cosmology/io/tests/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/astropy/cosmology/io/tests/test_mapping.py b/astropy/cosmology/io/tests/test_mapping.py
new file mode 100644
index 000000000000..df584ecc1ed5
--- /dev/null
+++ b/astropy/cosmology/io/tests/test_mapping.py
@@ -0,0 +1,79 @@
+# Licensed under a 3-clause BSD style license - see LICENSE.rst
+
+import pytest
+
+from astropy import cosmology
+from astropy.cosmology import Cosmology
+from astropy.cosmology.core import _COSMOLOGY_CLASSES
+from astropy.table import QTable, vstack
+from astropy.utils.compat import optional_deps
+from astropy.utils.exceptions import AstropyUserWarning
+
+
+class CosmologyWithKwargs(Cosmology):
+ def __init__(self, name="cosmology with kwargs", meta=None, **kwargs):
+ super().__init__(name=name, meta=meta, **kwargs)
+
+
+cosmo_instances = [
+ getattr(cosmology.realizations, name) for name in cosmology.parameters.available
+]
+cosmo_instances.append(CosmologyWithKwargs())
+
+
+def teardown_module(module):
+ # pop CosmologyWithKwargs from registered classes
+ # but don't error b/c it fails in parallel
+ _COSMOLOGY_CLASSES.pop(CosmologyWithKwargs.__qualname__, None)
+
+
+###############################################################################
+
+@pytest.mark.parametrize("expected", cosmo_instances)
+def test_to_from_mapping_instance(expected):
+ # ------------
+ # To Mapping
+ params = expected.to_format('mapping')
+
+ assert isinstance(params, dict)
+ assert params["cosmology"] is expected.__class__
+ assert params["name"] == expected.name
+
+ # ------------
+ # From Mapping
+ params["mismatching"] = "will error"
+
+ # tests are different if the last argument is a **kwarg
+ if tuple(expected._init_signature.parameters.values())[-1].kind == 4:
+ got = Cosmology.from_format(params, format="mapping")
+
+ assert got.__class__ == expected.__class__
+ assert got.name == expected.name
+ assert "mismatching" not in got.meta
+
+ return # don't continue testing
+
+ # read with mismatching parameters errors
+ with pytest.raises(TypeError, match="there are unused parameters"):
+ Cosmology.from_format(params, format="mapping")
+
+ # unless mismatched are moved to meta
+ got = Cosmology.from_format(params, format="mapping", move_to_meta=True)
+ assert got.__class__ == expected.__class__
+ assert got == expected
+ assert got.meta["mismatching"] == "will error"
+
+ # it won't error if everything matches up
+ params.pop("mismatching")
+ got = Cosmology.from_format(params, format="mapping")
+ assert got.__class__ == expected.__class__
+ assert got == expected
+
+ # and it will also work if the cosmology is a string
+ params["cosmology"] = params["cosmology"].__name__
+ got = Cosmology.from_format(params, format="mapping")
+ assert got == expected
+
+ # also it auto-identifies 'format'
+ got = Cosmology.from_format(params)
+ assert got == expected
diff --git a/astropy/cosmology/tests/test_connect.py b/astropy/cosmology/tests/test_connect.py
index 49620acea346..e2f7e6c282d8 100644
--- a/astropy/cosmology/tests/test_connect.py
+++ b/astropy/cosmology/tests/test_connect.py
@@ -1,6 +1,7 @@
# Licensed under a 3-clause BSD style license - see LICENSE.rst
import copy
+import inspect
import json
import os
@@ -16,46 +17,14 @@
from astropy.io import registry as io_registry
cosmo_instances = cosmology.parameters.available
-save_formats = ["json"]
+readwrite_formats = ["json"]
+tofrom_formats = [("mapping", dict)] # (format, data type)
###############################################################################
# Setup
-def from_mapping(map, **kwargs):
- params = copy.deepcopy(map) # so can pop
-
- # get cosmology. if string, parse to class
- # 1st from 'kwargs'. Allows for override of the cosmology, if on file.
- # 2nd from params. This MUST have the cosmology if 'kwargs' did not.
- if "cosmology" in kwargs:
- cosmology = kwargs.pop("cosmology")
- else:
- cosmology = params.pop("cosmology")
- if isinstance(cosmology, str):
- cosmology = _COSMOLOGY_CLASSES[cosmology]
-
- # select arguments from mapping that are in the cosmo's signature.
- ba = cosmology._init_signature.bind_partial() # blank set of args
- ba.apply_defaults() # fill in the defaults
- for k in cosmology._init_signature.parameters.keys(): # iter thru sig
- if k in params: # transfer argument, if in params
- ba.arguments[k] = params.pop(k)
-
- return cosmology(*ba.args, **ba.kwargs)
-
-
-def to_mapping(cosmology, *args, **kwargs):
- m = {}
- m["cosmology"] = cosmology.__class__
- m.update({k: v for k, v in cosmology._init_arguments.items()
- if k not in ("meta",)})
- m["meta"] = copy.deepcopy(cosmology.meta)
-
- return m
-
-
-def read_json(filename, key=None, **kwargs):
+def read_json(filename, **kwargs):
with open(filename, "r") as file:
data = file.read()
mapping = json.loads(data) # parse json mappable to dict
@@ -63,11 +32,19 @@ def read_json(filename, key=None, **kwargs):
for k, v in mapping.items():
if isinstance(v, dict) and "value" in v and "unit" in v:
mapping[k] = u.Quantity(v["value"], v["unit"])
- return from_mapping(mapping, **kwargs)
+ return Cosmology.from_format(mapping, **kwargs)
-def write_json(cosmology, file, *, overwrite=False, **kwargs):
- data = to_mapping(cosmology) # start by turning into dict
+def write_json(cosmology, file, *, overwrite=False):
+ """Write Cosmology to JSON.
+
+ Parameters
+ ----------
+ cosmology : `astropy.cosmology.Cosmology` subclass instance
+ file : path-like or file-like
+ overwrite : bool (optional, keyword-only)
+ """
+ data = cosmology.to_format("mapping") # start by turning into dict
data["cosmology"] = data["cosmology"].__name__ # change class field to str
# serialize Quantity
for k, v in data.items():
@@ -95,10 +72,9 @@ def setup_module(module):
def teardown_module(module):
"""clean up module after tests."""
- with pytest.warns(FutureWarning): # idk
- io_registry.unregister_reader("json", Cosmology)
- io_registry.unregister_writer("json", Cosmology)
- io_registry.unregister_identifier("json", Cosmology)
+ io_registry.unregister_reader("json", Cosmology)
+ io_registry.unregister_writer("json", Cosmology)
+ io_registry.unregister_identifier("json", Cosmology)
###############################################################################
@@ -106,7 +82,17 @@ def teardown_module(module):
class TestReadWriteCosmology:
- @pytest.mark.parametrize("format", save_formats)
+ @pytest.mark.parametrize("format", readwrite_formats)
+ def test_write_methods_have_explicit_kwarg_overwrite(self, format):
+ writer = io_registry.get_writer(format, Cosmology)
+ # test in signature
+ sig = inspect.signature(writer)
+ assert "overwrite" in sig.parameters
+
+ # also in docstring
+ assert "overwrite : bool" in writer.__doc__
+
+ @pytest.mark.parametrize("format", readwrite_formats)
@pytest.mark.parametrize("instance", cosmo_instances)
def test_complete_info(self, tmpdir, instance, format):
"""
@@ -132,7 +118,7 @@ def test_complete_info(self, tmpdir, instance, format):
assert got == cosmo
assert got.meta == cosmo.meta
- @pytest.mark.parametrize("format", save_formats)
+ @pytest.mark.parametrize("format", readwrite_formats)
@pytest.mark.parametrize("instance", cosmo_instances)
def test_from_subclass_complete_info(self, tmpdir, instance, format):
"""
@@ -200,7 +186,7 @@ def test_from_subclass_partial_info(self, tmpdir, instance):
# but the metadata is the same
assert got.meta == cosmo.meta
- @pytest.mark.parametrize("format", save_formats)
+ @pytest.mark.parametrize("format", readwrite_formats)
@pytest.mark.parametrize("instance", cosmo_instances)
def test_reader_class_mismatch(self, tmpdir, instance, format):
"""Test when the reader class doesn't match the file."""
@@ -219,3 +205,118 @@ def test_reader_class_mismatch(self, tmpdir, instance, format):
# when specifying the class
with pytest.raises(ValueError, match="`cosmology` must be either"):
w0wzCDM.read(fname, format=format, cosmology="FlatLambdaCDM")
+
+
+class TestCosmologyToFromFormat:
+ """Test methods ``astropy.cosmology.Cosmology.to/from_format``."""
+
+ @pytest.mark.parametrize("format_type", tofrom_formats)
+ @pytest.mark.parametrize("instance", cosmo_instances)
+ def test_format_complete_info(self, instance, format_type):
+ """Read tests happen later."""
+ format, objtype = format_type
+ cosmo = getattr(cosmology.realizations, instance)
+
+ # test to_format
+ obj = cosmo.to_format(format)
+ assert isinstance(obj, objtype)
+
+ # test from_format
+ got = Cosmology.from_format(obj, format=format)
+ # and autodetect
+ got2 = Cosmology.from_format(obj)
+
+ assert got2 == got # internal consistency
+ assert got == cosmo # external consistency
+ assert got.meta == cosmo.meta
+
+ @pytest.mark.parametrize("format_type", tofrom_formats)
+ @pytest.mark.parametrize("instance", cosmo_instances)
+ def test_from_subclass_complete_info(self, instance, format_type):
+ """
+ Test transforming an instance and parsing from that class, when there's
+ full information available.
+ """
+ format, objtype = format_type
+ cosmo = getattr(cosmology.realizations, instance)
+
+ # test to_format
+ obj = cosmo.to_format(format)
+ assert isinstance(obj, objtype)
+
+ # read with the same class that wrote.
+ got = cosmo.__class__.from_format(obj, format=format)
+ got2 = Cosmology.from_format(obj) # and autodetect
+
+ assert got2 == got # internal consistency
+ assert got == cosmo # external consistency
+ assert got.meta == cosmo.meta
+
+ # this should be equivalent to
+ got = Cosmology.from_format(obj, format=format, cosmology=cosmo.__class__)
+ assert got == cosmo
+ assert got.meta == cosmo.meta
+
+ # and also
+ got = Cosmology.from_format(obj, format=format, cosmology=cosmo.__class__.__qualname__)
+ assert got == cosmo
+ assert got.meta == cosmo.meta
+
+ @pytest.mark.parametrize("instance", cosmo_instances)
+ def test_from_subclass_partial_info(self, instance):
+ """
+ Test writing from an instance and reading from that class.
+ This requires partial information.
+
+ .. todo::
+
+ generalize over all formats for this test.
+ """
+ format, objtype = ("mapping", dict)
+ cosmo = getattr(cosmology.realizations, instance)
+
+ # test to_format
+ obj = cosmo.to_format(format)
+ assert isinstance(obj, objtype)
+
+ # partial information
+ tempobj = copy.deepcopy(obj)
+ del tempobj["cosmology"]
+ del tempobj["Tcmb0"]
+
+ # read with the same class that wrote fills in the missing info with
+ # the default value
+ got = cosmo.__class__.from_format(tempobj, format=format)
+ got2 = Cosmology.from_format(tempobj, format=format, cosmology=cosmo.__class__)
+ got3 = Cosmology.from_format(tempobj, format=format, cosmology=cosmo.__class__.__qualname__)
+
+ assert (got == got2) and (got2 == got3) # internal consistency
+
+ # not equal, because Tcmb0 is changed
+ assert got != cosmo
+ assert got.Tcmb0 == cosmo.__class__._init_signature.parameters["Tcmb0"].default
+ assert got.clone(name=cosmo.name, Tcmb0=cosmo.Tcmb0.value) == cosmo
+ # but the metadata is the same
+ assert got.meta == cosmo.meta
+
+ @pytest.mark.parametrize("format_type", tofrom_formats)
+ @pytest.mark.parametrize("instance", cosmo_instances)
+ def test_reader_class_mismatch(self, instance, format_type):
+ """Test when the reader class doesn't match the object."""
+ format, objtype = format_type
+ cosmo = getattr(cosmology.realizations, instance)
+
+ # test to_format
+ obj = cosmo.to_format(format)
+ assert isinstance(obj, objtype)
+
+ # class mismatch
+ with pytest.raises(TypeError, match="missing 1 required"):
+ w0wzCDM.from_format(obj, format=format)
+
+ with pytest.raises(TypeError, match="missing 1 required"):
+ Cosmology.from_format(obj, format=format, cosmology=w0wzCDM)
+
+ # when specifying the class
+ with pytest.raises(ValueError, match="`cosmology` must be either"):
+ w0wzCDM.from_format(obj, format=format, cosmology="FlatLambdaCDM")
|
[
{
"path": "docs/changes/cosmology/11998.feature.rst",
"old_path": "/dev/null",
"new_path": "b/docs/changes/cosmology/11998.feature.rst",
"metadata": "diff --git a/docs/changes/cosmology/11998.feature.rst b/docs/changes/cosmology/11998.feature.rst\nnew file mode 100644\nindex 000000000000..df78f84a93c9\n--- /dev/null\n+++ b/docs/changes/cosmology/11998.feature.rst\n@@ -0,0 +1,5 @@\n+Added ``to_format/from_format`` methods to Cosmology using the Unified I/O\n+registry. Now custom format converters and format-identifier functions\n+can be registered to transform Cosmology objects.\n+The transformation between Cosmology and dictionaries is pre-registered.\n+Details are discussed in an addition to the docs.\n",
"update": null
},
{
"path": "docs/cosmology/io.rst",
"old_path": "a/docs/cosmology/io.rst",
"new_path": "b/docs/cosmology/io.rst",
"metadata": "diff --git a/docs/cosmology/io.rst b/docs/cosmology/io.rst\nindex bb9f1881b4d1..db5f9509a287 100644\n--- a/docs/cosmology/io.rst\n+++ b/docs/cosmology/io.rst\n@@ -1,25 +1,22 @@\n-.. doctest-skip-all\n-\n .. _read_write_cosmologies:\n \n-Reading and Writing Cosmology Objects\n-*************************************\n+Read, Write, and Convert Cosmology Objects\n+******************************************\n \n An easy way to serialize and deserialize a Cosmology object is using the\n :mod:`pickle` module.\n \n-.. code-block:: python\n- :emphasize-lines: 1,4,8\n+.. doctest-skip::\n \n >>> import pickle\n >>> from astropy.cosmology import Planck18\n >>> with open(\"planck18.pkl\", mode=\"wb\") as file:\n- ... pickle.dump(file, Planck18)\n-\n- And to read the file back\n+ ... pickle.dump(Planck18, file)\n+ >>> # and to read back\n >>> with open(\"planck18.pkl\", mode=\"rb\") as file:\n- >>> cosmo = pickle.load(file)\n+ ... cosmo = pickle.load(file)\n >>> cosmo\n+ FlatLambdaCDM(name=\"Planck18\", ...\n \n However this method has all the attendant drawbacks of :mod:`pickle` — security\n vulnerabilities and non-human-readable files.\n@@ -43,34 +40,197 @@ framework.\n Writing a cosmology instance requires only the file location and optionally,\n if the file format cannot be inferred, a keyword argument \"format\". Additional\n positional arguments and keyword arguments are passed to the reader methods.\n-::\n+\n+.. doctest-skip::\n \n >>> from astropy.cosmology import Planck18\n- >>> Planck18.write('[file name]')\n+ >>> Planck18.write('<file name>')\n \n Reading back the cosmology is most safely done from ``Cosmology``, the base\n class, as it provides no default information and therefore requires the file\n to have all necessary information to describe a cosmology.\n \n-::\n+.. doctest-skip::\n \n >>> from astropy.cosmology import Cosmology\n- >>> cosmo = Cosmology.read('[file name]')\n+ >>> cosmo = Cosmology.read('<file name>')\n >>> cosmo == Planck18\n True\n \n When a subclass of ``Cosmology`` is used to read a file, the subclass will\n-provide a keyword argument ``cosmology=[class]`` to the registered read\n+provide a keyword argument ``cosmology=<class>`` to the registered read\n method. The method uses this cosmology class, regardless of the class\n indicated in the file, and sets parameters' default values from the class'\n signature.\n \n-::\n+.. doctest-skip::\n \n >>> from astropy.cosmology import FlatLambdaCDM\n- >>> cosmo = FlatLambdaCDM.read('[file name]')\n+ >>> cosmo = FlatLambdaCDM.read('<file name>')\n >>> cosmo == Planck18\n True\n+ \n+Reading and writing :class:`~astropy.cosmology.Cosmology` objects go through\n+intermediate representations, often a dict or `~astropy.table.QTable` instance.\n+These intermediate representations are accessible through the methods\n+:meth:`~astropy.cosmology.Cosmology.to_format` /\n+:meth:`~astropy.cosmology.Cosmology.from_format`.\n+\n+To see the a list of the available formats:\n+\n+ >>> from astropy.cosmology import Cosmology\n+ >>> Cosmology.to_format.list_formats()\n+ Format Read Write Auto-identify\n+ ------- ---- ----- -------------\n+ mapping Yes Yes Yes\n+\n+This list will include both built-in and registered 3rd-party formats.\n+\n+:meth:`~astropy.cosmology.Cosmology.to_format` /\n+:meth:`~astropy.cosmology.Cosmology.from_format` parse a Cosmology to/from\n+another python object. This can be useful for e.g., iterating through an MCMC\n+of cosmological parameters or printing out a cosmological model to a journal\n+format, like latex or HTML. When 3rd party cosmology packages register with\n+Astropy' Cosmology I/O, ``to/from_format`` can be used to convert cosmology\n+instances between packages!\n+\n+.. EXAMPLE START: Planck18 to mapping and back\n+\n+.. code-block::\n+\n+ >>> from astropy.cosmology import Planck18\n+ >>> cm = Planck18.to_format(\"mapping\")\n+ >>> cm\n+ {'cosmology': <class 'astropy.cosmology.core.FlatLambdaCDM'>,\n+ 'name': 'Planck18',\n+ 'H0': <Quantity 67.66 km / (Mpc s)>,\n+ 'Om0': 0.30966,\n+ ...\n+\n+Now this dict can be used to load a new cosmological instance identical\n+to the ``Planck18`` cosmology from which it was created.\n+\n+.. code-block::\n+\n+ >>> from astropy.cosmology import Cosmology\n+ >>> cosmo = Cosmology.from_format(cm, format=\"mapping\")\n+ >>> cosmo == Planck18\n+ True\n+\n+.. EXAMPLE END\n+\n+\n+\n+.. _custom_cosmology_converters:\n+\n+Custom Cosmology To/From Formats\n+================================\n+\n+Custom representation formats may also be registered into the Astropy Cosmology\n+I/O framework for use by these methods. For details of the framework see\n+:ref:`io_registry`.\n+\n+.. EXAMPLE START : custom to/from format\n+\n+As an example, the following is an implementation of an `astropy.table.Row`\n+converter. Note that we can use other registered parsers -- here \"mapping\"\n+-- to make the implementation much simpler.\n+\n+We start by defining the function to parse a `astropy.table.Row` into a\n+`~astropy.cosmology.Cosmology`. This function should take 1 positional\n+argument, the row object, and 2 keyword arguments, for how to handle\n+extra metadata and which Cosmology class to use. Details about metadata\n+treatment are in ``Cosmology.from_format.help(\"mapping\")``.\n+\n+.. code-block:: python\n+ :emphasize-lines: 12,13\n+\n+ >>> import copy\n+ >>> from astropy.cosmology import Cosmology\n+ \n+ >>> def from_table_row(row, *, move_to_meta=False, cosmology=None):\n+ ... # get name from column\n+ ... name = row['name'] if 'name' in row.columns else None\n+ ... meta = copy.deepcopy(row.meta)\n+ ... # turn row into mapping (dict of the arguments)\n+ ... mapping = dict(row)\n+ ... mapping[\"meta\"] = meta\n+ ... # build cosmology from map\n+ ... return Cosmology.from_format(mapping,\n+ ... move_to_meta=move_to_meta, cosmology=cosmology)\n+\n+The next step is a function to perform the reverse operation: parse a\n+`~astropy.cosmology.Cosmology` into a `~astropy.table.Row`. This function\n+requires only the cosmology object and a ``*args`` to absorb unneeded\n+information passed by `astropy.io.registry.UnifiedReadWrite` (which\n+implements `astropy.cosmology.Cosmology.to_format`).\n+\n+.. code-block:: python\n+ :emphasize-lines: 4\n+\n+ >>> from astropy.table import QTable\n+ \n+ >>> def to_table_row(cosmology, *args):\n+ ... p = cosmology.to_format(\"mapping\")\n+ ... p[\"cosmology\"] = p[\"cosmology\"].__qualname__ # as string\n+ ... meta = p.pop(\"meta\")\n+ ... # package parameters into lists for Table parsing\n+ ... params = {k: [v] for k, v in p.items()}\n+ ... return QTable(params, meta=meta)[0] # return row\n+\n+Last we write a function to help with format auto-identification and then\n+register everything into `astropy.io.registry`.\n+\n+.. code-block:: python\n+ :emphasize-lines: 11, 12, 13\n+\n+ >>> from astropy.cosmology import Cosmology\n+ >>> from astropy.io import registry as io_registry\n+ >>> from astropy.table import Row\n+\n+ >>> def row_identify(origin, format, *args, **kwargs):\n+ ... \"\"\"Identify if object uses the Table format.\"\"\"\n+ ... if origin == \"read\":\n+ ... return isinstance(args[1], Row) and (format in (None, \"row\"))\n+ ... return False\n+\n+ >>> io_registry.register_reader(\"row\", Cosmology, from_table_row)\n+ >>> io_registry.register_writer(\"row\", Cosmology, to_table_row)\n+ >>> io_registry.register_identifier(\"row\", Cosmology, row_identify)\n+\n+Now the registered functions can be used in\n+:meth:`astropy.cosmology.Cosmology.from_format` and\n+:meth:`astropy.cosmology.Cosmology.to_format`.\n+\n+.. code-block:: python\n+\n+ >>> from astropy.cosmology import Planck18\n+ >>> row = Planck18.to_format(\"row\")\n+ >>> row\n+ <Row index=0>\n+ cosmology name H0 Om0 Tcmb0 Neff m_nu [3] Ob0 \n+ km / (Mpc s) eV \n+ str13 str8 float64 float64 float64 float64 float64 float64\n+ ------------- -------- ------------ ------- ------- ------- ----------- -------\n+ FlatLambdaCDM Planck18 67.66 0.30966 2.7255 3.046 0.0 .. 0.06 0.04897\n+\n+ >>> cosmo = Cosmology.from_format(row)\n+ >>> cosmo == Planck18 # test it round-trips\n+ True\n+\n+\n+.. doctest::\n+ :hide:\n+\n+ >>> io_registry.unregister_reader(\"row\", Cosmology)\n+ >>> io_registry.unregister_writer(\"row\", Cosmology)\n+ >>> io_registry.unregister_identifier(\"row\", Cosmology)\n+ >>> try:\n+ ... io_registry.get_reader(\"row\", Cosmology)\n+ ... except io_registry.IORegistryError:\n+ ... pass\n+\n+.. EXAMPLE END\n \n \n .. _custom_cosmology_readers_writers:\n@@ -80,35 +240,125 @@ Custom Cosmology Readers/Writers\n \n Custom ``read`` / ``write`` formats may be registered into the Astropy Cosmology\n I/O framework. For details of the framework see :ref:`io_registry`.\n-As a quick example, outlining how to make a\n-`~astropy.cosmology.Cosmology` <-> JSON serializer:\n+\n+.. EXAMPLE START : custom read/write\n+\n+As an example, in the following we will fully work out a\n+`~astropy.cosmology.Cosmology` <-> JSON (de)serializer.\n+Note that we can use other registered parsers -- here \"mapping\"\n+-- to make the implementation much simpler.\n+\n+We start by defining the function to parse JSON into a\n+`~astropy.cosmology.Cosmology`. This function should take 1 positional\n+argument, the file object or file path. We will also pass kwargs through to\n+:meth:`~astropy.cosmology.Cosmology.from_format`, which handles metadata\n+and which Cosmology class to use. Details of are in\n+``Cosmology.from_format.help(\"mapping\")``.\n \n .. code-block:: python\n+ :emphasize-lines: 9,12,17\n \n- import json\n- from astropy.cosmology import Cosmology\n- from astropy.io import registry as io_registry\n+ >>> import json, os\n+ >>> import astropy.units as u\n+ >>> from astropy.cosmology import Cosmology\n \n- def read_json(filename, **kwargs):\n- cosmology = ... # read and parse file\n- return cosmology\n+ >>> def read_json(filename, **kwargs):\n+ ... # read file, from path-like or file-like\n+ ... if isinstance(filename, (str, bytes, os.PathLike)):\n+ ... with open(filename, \"r\") as file:\n+ ... data = file.read()\n+ ... else: # file-like : this also handles errors in dumping\n+ ... data = filename.read()\n+ ... mapping = json.loads(data) # parse json mappable to dict\n+ ... # deserialize Quantity\n+ ... for k, v in mapping.items():\n+ ... if isinstance(v, dict) and \"value\" in v and \"unit\" in v:\n+ ... mapping[k] = u.Quantity(v[\"value\"], v[\"unit\"])\n+ ... return Cosmology.from_format(mapping, **kwargs)\n+\n+\n+The next step is a function to write a `~astropy.cosmology.Cosmology` to\n+JSON. This function requires the cosmology object and a file object/path.\n+We also require the boolean flag \"overwrite\" to set behavior for existing\n+files. Note that `~astropy.units.Quantity` is not natively compatible with\n+JSON. In both the ``write`` and ``read`` methods we have to create custom\n+parsers.\n+\n+.. code-block:: python\n+ :emphasize-lines: 2,15\n+\n+ >>> def write_json(cosmology, file, *, overwrite=False, **kwargs):\n+ ... data = cosmology.to_format(\"mapping\") # start by turning into dict\n+ ... data[\"cosmology\"] = data[\"cosmology\"].__name__ # change class field to str\n+ ... # serialize Quantity\n+ ... for k, v in data.items():\n+ ... if isinstance(v, u.Quantity):\n+ ... data[k] = {\"value\": v.value.tolist(),\n+ ... \"unit\": str(v.unit)}\n+ ...\n+ ... if isinstance(file, (str, bytes, os.PathLike)):\n+ ... # check that file exists and whether to overwrite.\n+ ... if os.path.exists(file) and not overwrite:\n+ ... raise IOError(f\"{file} exists. Set 'overwrite' to write over.\")\n+ ... with open(file, \"w\") as write_file:\n+ ... json.dump(data, write_file)\n+ ... else:\n+ ... json.dump(data, file)\n+\n+Last we write a function to help with format auto-identification and then\n+register everything into `astropy.io.registry`.\n+\n+.. code-block:: python\n+ :emphasize-lines: 7,8,9\n \n- def write_json(cosmology, file, **kwargs):\n- data = ... # parse cosmology to dict\n- with open(file, \"w\") as write_file:\n- json.dump(data, write_file)\n+ >>> from astropy.io import registry as io_registry\n \n- def json_identify(origin, filepath, fileobj, *args, **kwargs):\n- \"\"\"Identify if object uses the JSON format.\"\"\"\n- return filepath is not None and filepath.endswith(\".json\")\n+ >>> def json_identify(origin, filepath, fileobj, *args, **kwargs):\n+ ... \"\"\"Identify if object uses the JSON format.\"\"\"\n+ ... return filepath is not None and filepath.endswith(\".json\")\n \n- # register the read/write methods \n- io_registry.register_reader(\"json\", Cosmology, read_json)\n- io_registry.register_writer(\"json\", Cosmology, write_json)\n- io_registry.register_identifier(\"json\", Cosmology, json_identify)\n+ >>> io_registry.register_reader(\"json\", Cosmology, read_json)\n+ >>> io_registry.register_writer(\"json\", Cosmology, write_json)\n+ >>> io_registry.register_identifier(\"json\", Cosmology, json_identify)\n+ \n+Now the registered functions can be used in\n+:meth:`astropy.cosmology.Cosmology.read` and\n+:meth:`astropy.cosmology.Cosmology.write`.\n \n+.. doctest-skip:: win32\n+\n+ >>> import tempfile\n+ >>> from astropy.cosmology import Planck18\n+ >>>\n+ >>> file = tempfile.NamedTemporaryFile()\n+ >>> Planck18.write(file.name, format=\"json\", overwrite=True)\n+ >>> with open(file.name) as f: f.readlines()\n+ ['{\"cosmology\": \"FlatLambdaCDM\", \"name\": \"Planck18\",\n+ \"H0\": {\"value\": 67.66, \"unit\": \"km / (Mpc s)\"}, \"Om0\": 0.30966,\n+ ...\n+ >>>\n+ >>> cosmo = Cosmology.read(file.name, format=\"json\")\n+ >>> file.close()\n+ >>> cosmo == Planck18 # test it round-trips\n+ True\n+\n+\n+.. doctest::\n+ :hide:\n+\n+ >>> io_registry.unregister_reader(\"json\", Cosmology)\n+ >>> io_registry.unregister_writer(\"json\", Cosmology)\n+ >>> io_registry.unregister_identifier(\"json\", Cosmology)\n+ >>> try:\n+ ... io_registry.get_reader(\"json\", Cosmology)\n+ ... except io_registry.IORegistryError:\n+ ... pass\n+\n+.. EXAMPLE END\n \n Reference/API\n =============\n \n .. automodapi:: astropy.cosmology.connect\n+\n+.. automodapi:: astropy.cosmology.io.mapping\n",
"update": null
},
{
"path": "docs/whatsnew/5.0.rst",
"old_path": "a/docs/whatsnew/5.0.rst",
"new_path": "b/docs/whatsnew/5.0.rst",
"metadata": "diff --git a/docs/whatsnew/5.0.rst b/docs/whatsnew/5.0.rst\nindex b8c135bb606f..a224b149c972 100644\n--- a/docs/whatsnew/5.0.rst\n+++ b/docs/whatsnew/5.0.rst\n@@ -9,6 +9,47 @@ What's New in Astropy 5.0?\n Overview\n ========\n \n+.. _whatsnew-5.0-cosmology:\n+\n+Support for reading, writing, and converting ``Cosmology``\n+==========================================================\n+\n+Four new methods -- ``read``, ``write``, ``to_format``, ``from_format`` -- have\n+been added to the ``Cosmology`` class, enabling reading from and writing to\n+files and converting between different python objects.\n+The methods use Astropy's Unified I/O registry so custom formats can be\n+registered. Details are discussed in an addition to the docs.\n+\n+Currently no file formats are registered, but the syntax is as follows:\n+\n+.. doctest-skip::\n+\n+ >>> from astropy.cosmology import Planck18\n+ >>> Planck18.write('<file name>.<format>')\n+ >>>\n+ >>> from astropy.cosmology import Cosmology\n+ >>> cosmo = Cosmology.read('<file name>.<format>')\n+ >>> cosmo == Planck18\n+ True\n+\n+\n+The transformation between ``Cosmology`` and `dict` is pre-registered,\n+e.g. enabling::\n+\n+ >>> from astropy.cosmology import Planck18\n+ >>> cm = Planck18.to_format(\"mapping\")\n+ >>> cm\n+ {'cosmology': <class 'astropy.cosmology.core.FlatLambdaCDM'>,\n+ 'name': 'Planck18',\n+ 'H0': <Quantity 67.66 km / (Mpc s)>,\n+ 'Om0': 0.30966,\n+ ...\n+\n+ >>> from astropy.cosmology import Cosmology\n+ >>> cosmo = Cosmology.from_format(cm, format=\"mapping\")\n+ >>> cosmo == Planck18\n+ True\n+\n \n Full change log\n ===============\n",
"update": null
}
] |
5.0
|
2631ed5eec34fb74c3f6826f6fef8ca9be0cbfcf
|
[
"astropy/cosmology/tests/test_connect.py::TestReadWriteCosmology::test_write_methods_have_explicit_kwarg_overwrite[json]"
] |
[
"astropy/cosmology/tests/test_connect.py::TestReadWriteCosmology::test_reader_class_mismatch[Planck13-json]",
"astropy/cosmology/tests/test_connect.py::TestReadWriteCosmology::test_from_subclass_partial_info[Planck15]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_from_subclass_complete_info[WMAP5-format_type0]",
"astropy/cosmology/tests/test_connect.py::TestReadWriteCosmology::test_from_subclass_partial_info[WMAP9]",
"astropy/cosmology/tests/test_connect.py::TestReadWriteCosmology::test_complete_info[Planck18_arXiv_v2-json]",
"astropy/cosmology/tests/test_connect.py::TestReadWriteCosmology::test_reader_class_mismatch[Planck18-json]",
"astropy/cosmology/tests/test_connect.py::TestReadWriteCosmology::test_from_subclass_partial_info[Planck13]",
"astropy/cosmology/io/tests/test_mapping.py::test_to_from_mapping_instance[expected4]",
"astropy/cosmology/tests/test_connect.py::TestReadWriteCosmology::test_complete_info[WMAP9-json]",
"astropy/cosmology/tests/test_connect.py::TestReadWriteCosmology::test_from_subclass_complete_info[Planck13-json]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_from_subclass_complete_info[WMAP9-format_type0]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_from_subclass_complete_info[Planck15-format_type0]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_format_complete_info[WMAP5-format_type0]",
"astropy/cosmology/io/tests/test_mapping.py::test_to_from_mapping_instance[expected0]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_format_complete_info[WMAP7-format_type0]",
"astropy/cosmology/tests/test_connect.py::TestReadWriteCosmology::test_complete_info[Planck18-json]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_from_subclass_complete_info[Planck13-format_type0]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_format_complete_info[Planck18-format_type0]",
"astropy/cosmology/tests/test_connect.py::TestReadWriteCosmology::test_from_subclass_complete_info[Planck18-json]",
"astropy/cosmology/tests/test_connect.py::TestReadWriteCosmology::test_from_subclass_complete_info[WMAP5-json]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_format_complete_info[Planck18_arXiv_v2-format_type0]",
"astropy/cosmology/tests/test_connect.py::TestReadWriteCosmology::test_from_subclass_partial_info[Planck18_arXiv_v2]",
"astropy/cosmology/io/tests/test_mapping.py::test_to_from_mapping_instance[expected2]",
"astropy/cosmology/tests/test_connect.py::TestReadWriteCosmology::test_complete_info[WMAP5-json]",
"astropy/cosmology/io/tests/test_mapping.py::test_to_from_mapping_instance[expected5]",
"astropy/cosmology/tests/test_connect.py::TestReadWriteCosmology::test_complete_info[WMAP7-json]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_format_complete_info[Planck15-format_type0]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_from_subclass_partial_info[Planck18]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_from_subclass_partial_info[Planck13]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_from_subclass_partial_info[WMAP7]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_reader_class_mismatch[Planck18-format_type0]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_from_subclass_partial_info[WMAP9]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_from_subclass_complete_info[WMAP7-format_type0]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_reader_class_mismatch[WMAP5-format_type0]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_from_subclass_partial_info[WMAP5]",
"astropy/cosmology/tests/test_connect.py::TestReadWriteCosmology::test_from_subclass_partial_info[Planck18]",
"astropy/cosmology/tests/test_connect.py::TestReadWriteCosmology::test_from_subclass_complete_info[WMAP7-json]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_reader_class_mismatch[Planck18_arXiv_v2-format_type0]",
"astropy/cosmology/io/tests/test_mapping.py::test_to_from_mapping_instance[expected6]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_reader_class_mismatch[WMAP7-format_type0]",
"astropy/cosmology/tests/test_connect.py::TestReadWriteCosmology::test_from_subclass_complete_info[WMAP9-json]",
"astropy/cosmology/tests/test_connect.py::TestReadWriteCosmology::test_complete_info[Planck15-json]",
"astropy/cosmology/tests/test_connect.py::TestReadWriteCosmology::test_from_subclass_complete_info[Planck18_arXiv_v2-json]",
"astropy/cosmology/tests/test_connect.py::TestReadWriteCosmology::test_from_subclass_partial_info[WMAP7]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_from_subclass_complete_info[Planck18-format_type0]",
"astropy/cosmology/tests/test_connect.py::TestReadWriteCosmology::test_from_subclass_complete_info[Planck15-json]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_format_complete_info[WMAP9-format_type0]",
"astropy/cosmology/tests/test_connect.py::TestReadWriteCosmology::test_reader_class_mismatch[WMAP9-json]",
"astropy/cosmology/io/tests/test_mapping.py::test_to_from_mapping_instance[expected7]",
"astropy/cosmology/tests/test_connect.py::TestReadWriteCosmology::test_reader_class_mismatch[Planck15-json]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_reader_class_mismatch[Planck13-format_type0]",
"astropy/cosmology/tests/test_connect.py::TestReadWriteCosmology::test_reader_class_mismatch[WMAP5-json]",
"astropy/cosmology/io/tests/test_mapping.py::test_to_from_mapping_instance[expected1]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_from_subclass_partial_info[Planck15]",
"astropy/cosmology/tests/test_connect.py::TestReadWriteCosmology::test_from_subclass_partial_info[WMAP5]",
"astropy/cosmology/tests/test_connect.py::TestReadWriteCosmology::test_reader_class_mismatch[Planck18_arXiv_v2-json]",
"astropy/cosmology/tests/test_connect.py::TestReadWriteCosmology::test_reader_class_mismatch[WMAP7-json]",
"astropy/cosmology/io/tests/test_mapping.py::test_to_from_mapping_instance[expected3]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_reader_class_mismatch[WMAP9-format_type0]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_format_complete_info[Planck13-format_type0]",
"astropy/cosmology/tests/test_connect.py::TestReadWriteCosmology::test_complete_info[Planck13-json]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_from_subclass_partial_info[Planck18_arXiv_v2]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_reader_class_mismatch[Planck15-format_type0]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_from_subclass_complete_info[Planck18_arXiv_v2-format_type0]"
] |
[
{
"path": "docs/changes/cosmology/#####.feature.rst",
"old_path": "/dev/null",
"new_path": "b/docs/changes/cosmology/#####.feature.rst",
"metadata": "diff --git a/docs/changes/cosmology/#####.feature.rst b/docs/changes/cosmology/#####.feature.rst\nnew file mode 100644\nindex 0000000000..df78f84a93\n--- /dev/null\n+++ b/docs/changes/cosmology/#####.feature.rst\n@@ -0,0 +1,5 @@\n+Added ``to_format/from_format`` methods to Cosmology using the Unified I/O\n+registry. Now custom format converters and format-identifier functions\n+can be registered to transform Cosmology objects.\n+The transformation between Cosmology and dictionaries is pre-registered.\n+Details are discussed in an addition to the docs.\n"
},
{
"path": "docs/cosmology/io.rst",
"old_path": "a/docs/cosmology/io.rst",
"new_path": "b/docs/cosmology/io.rst",
"metadata": "diff --git a/docs/cosmology/io.rst b/docs/cosmology/io.rst\nindex bb9f1881b4..db5f9509a2 100644\n--- a/docs/cosmology/io.rst\n+++ b/docs/cosmology/io.rst\n@@ -1,25 +1,22 @@\n-.. doctest-skip-all\n-\n .. _read_write_cosmologies:\n \n-Reading and Writing Cosmology Objects\n-*************************************\n+Read, Write, and Convert Cosmology Objects\n+******************************************\n \n An easy way to serialize and deserialize a Cosmology object is using the\n :mod:`pickle` module.\n \n-.. code-block:: python\n- :emphasize-lines: 1,4,8\n+.. doctest-skip::\n \n >>> import pickle\n >>> from astropy.cosmology import Planck18\n >>> with open(\"planck18.pkl\", mode=\"wb\") as file:\n- ... pickle.dump(file, Planck18)\n-\n- And to read the file back\n+ ... pickle.dump(Planck18, file)\n+ >>> # and to read back\n >>> with open(\"planck18.pkl\", mode=\"rb\") as file:\n- >>> cosmo = pickle.load(file)\n+ ... cosmo = pickle.load(file)\n >>> cosmo\n+ FlatLambdaCDM(name=\"Planck18\", ...\n \n However this method has all the attendant drawbacks of :mod:`pickle` — security\n vulnerabilities and non-human-readable files.\n@@ -43,34 +40,197 @@ framework.\n Writing a cosmology instance requires only the file location and optionally,\n if the file format cannot be inferred, a keyword argument \"format\". Additional\n positional arguments and keyword arguments are passed to the reader methods.\n-::\n+\n+.. doctest-skip::\n \n >>> from astropy.cosmology import Planck18\n- >>> Planck18.write('[file name]')\n+ >>> Planck18.write('<file name>')\n \n Reading back the cosmology is most safely done from ``Cosmology``, the base\n class, as it provides no default information and therefore requires the file\n to have all necessary information to describe a cosmology.\n \n-::\n+.. doctest-skip::\n \n >>> from astropy.cosmology import Cosmology\n- >>> cosmo = Cosmology.read('[file name]')\n+ >>> cosmo = Cosmology.read('<file name>')\n >>> cosmo == Planck18\n True\n \n When a subclass of ``Cosmology`` is used to read a file, the subclass will\n-provide a keyword argument ``cosmology=[class]`` to the registered read\n+provide a keyword argument ``cosmology=<class>`` to the registered read\n method. The method uses this cosmology class, regardless of the class\n indicated in the file, and sets parameters' default values from the class'\n signature.\n \n-::\n+.. doctest-skip::\n \n >>> from astropy.cosmology import FlatLambdaCDM\n- >>> cosmo = FlatLambdaCDM.read('[file name]')\n+ >>> cosmo = FlatLambdaCDM.read('<file name>')\n >>> cosmo == Planck18\n True\n+ \n+Reading and writing :class:`~astropy.cosmology.Cosmology` objects go through\n+intermediate representations, often a dict or `~astropy.table.QTable` instance.\n+These intermediate representations are accessible through the methods\n+:meth:`~astropy.cosmology.Cosmology.to_format` /\n+:meth:`~astropy.cosmology.Cosmology.from_format`.\n+\n+To see the a list of the available formats:\n+\n+ >>> from astropy.cosmology import Cosmology\n+ >>> Cosmology.to_format.list_formats()\n+ Format Read Write Auto-identify\n+ ------- ---- ----- -------------\n+ mapping Yes Yes Yes\n+\n+This list will include both built-in and registered 3rd-party formats.\n+\n+:meth:`~astropy.cosmology.Cosmology.to_format` /\n+:meth:`~astropy.cosmology.Cosmology.from_format` parse a Cosmology to/from\n+another python object. This can be useful for e.g., iterating through an MCMC\n+of cosmological parameters or printing out a cosmological model to a journal\n+format, like latex or HTML. When 3rd party cosmology packages register with\n+Astropy' Cosmology I/O, ``to/from_format`` can be used to convert cosmology\n+instances between packages!\n+\n+.. EXAMPLE START: Planck18 to mapping and back\n+\n+.. code-block::\n+\n+ >>> from astropy.cosmology import Planck18\n+ >>> cm = Planck18.to_format(\"mapping\")\n+ >>> cm\n+ {'cosmology': <class 'astropy.cosmology.core.FlatLambdaCDM'>,\n+ 'name': 'Planck18',\n+ 'H0': <Quantity 67.66 km / (Mpc s)>,\n+ 'Om0': 0.30966,\n+ ...\n+\n+Now this dict can be used to load a new cosmological instance identical\n+to the ``Planck18`` cosmology from which it was created.\n+\n+.. code-block::\n+\n+ >>> from astropy.cosmology import Cosmology\n+ >>> cosmo = Cosmology.from_format(cm, format=\"mapping\")\n+ >>> cosmo == Planck18\n+ True\n+\n+.. EXAMPLE END\n+\n+\n+\n+.. _custom_cosmology_converters:\n+\n+Custom Cosmology To/From Formats\n+================================\n+\n+Custom representation formats may also be registered into the Astropy Cosmology\n+I/O framework for use by these methods. For details of the framework see\n+:ref:`io_registry`.\n+\n+.. EXAMPLE START : custom to/from format\n+\n+As an example, the following is an implementation of an `astropy.table.Row`\n+converter. Note that we can use other registered parsers -- here \"mapping\"\n+-- to make the implementation much simpler.\n+\n+We start by defining the function to parse a `astropy.table.Row` into a\n+`~astropy.cosmology.Cosmology`. This function should take 1 positional\n+argument, the row object, and 2 keyword arguments, for how to handle\n+extra metadata and which Cosmology class to use. Details about metadata\n+treatment are in ``Cosmology.from_format.help(\"mapping\")``.\n+\n+.. code-block:: python\n+ :emphasize-lines: 12,13\n+\n+ >>> import copy\n+ >>> from astropy.cosmology import Cosmology\n+ \n+ >>> def from_table_row(row, *, move_to_meta=False, cosmology=None):\n+ ... # get name from column\n+ ... name = row['name'] if 'name' in row.columns else None\n+ ... meta = copy.deepcopy(row.meta)\n+ ... # turn row into mapping (dict of the arguments)\n+ ... mapping = dict(row)\n+ ... mapping[\"meta\"] = meta\n+ ... # build cosmology from map\n+ ... return Cosmology.from_format(mapping,\n+ ... move_to_meta=move_to_meta, cosmology=cosmology)\n+\n+The next step is a function to perform the reverse operation: parse a\n+`~astropy.cosmology.Cosmology` into a `~astropy.table.Row`. This function\n+requires only the cosmology object and a ``*args`` to absorb unneeded\n+information passed by `astropy.io.registry.UnifiedReadWrite` (which\n+implements `astropy.cosmology.Cosmology.to_format`).\n+\n+.. code-block:: python\n+ :emphasize-lines: 4\n+\n+ >>> from astropy.table import QTable\n+ \n+ >>> def to_table_row(cosmology, *args):\n+ ... p = cosmology.to_format(\"mapping\")\n+ ... p[\"cosmology\"] = p[\"cosmology\"].__qualname__ # as string\n+ ... meta = p.pop(\"meta\")\n+ ... # package parameters into lists for Table parsing\n+ ... params = {k: [v] for k, v in p.items()}\n+ ... return QTable(params, meta=meta)[0] # return row\n+\n+Last we write a function to help with format auto-identification and then\n+register everything into `astropy.io.registry`.\n+\n+.. code-block:: python\n+ :emphasize-lines: 11, 12, 13\n+\n+ >>> from astropy.cosmology import Cosmology\n+ >>> from astropy.io import registry as io_registry\n+ >>> from astropy.table import Row\n+\n+ >>> def row_identify(origin, format, *args, **kwargs):\n+ ... \"\"\"Identify if object uses the Table format.\"\"\"\n+ ... if origin == \"read\":\n+ ... return isinstance(args[1], Row) and (format in (None, \"row\"))\n+ ... return False\n+\n+ >>> io_registry.register_reader(\"row\", Cosmology, from_table_row)\n+ >>> io_registry.register_writer(\"row\", Cosmology, to_table_row)\n+ >>> io_registry.register_identifier(\"row\", Cosmology, row_identify)\n+\n+Now the registered functions can be used in\n+:meth:`astropy.cosmology.Cosmology.from_format` and\n+:meth:`astropy.cosmology.Cosmology.to_format`.\n+\n+.. code-block:: python\n+\n+ >>> from astropy.cosmology import Planck18\n+ >>> row = Planck18.to_format(\"row\")\n+ >>> row\n+ <Row index=0>\n+ cosmology name H0 Om0 Tcmb0 Neff m_nu [3] Ob0 \n+ km / (Mpc s) eV \n+ str13 str8 float64 float64 float64 float64 float64 float64\n+ ------------- -------- ------------ ------- ------- ------- ----------- -------\n+ FlatLambdaCDM Planck18 67.66 0.30966 2.7255 3.046 0.0 .. 0.06 0.04897\n+\n+ >>> cosmo = Cosmology.from_format(row)\n+ >>> cosmo == Planck18 # test it round-trips\n+ True\n+\n+\n+.. doctest::\n+ :hide:\n+\n+ >>> io_registry.unregister_reader(\"row\", Cosmology)\n+ >>> io_registry.unregister_writer(\"row\", Cosmology)\n+ >>> io_registry.unregister_identifier(\"row\", Cosmology)\n+ >>> try:\n+ ... io_registry.get_reader(\"row\", Cosmology)\n+ ... except io_registry.IORegistryError:\n+ ... pass\n+\n+.. EXAMPLE END\n \n \n .. _custom_cosmology_readers_writers:\n@@ -80,35 +240,125 @@ Custom Cosmology Readers/Writers\n \n Custom ``read`` / ``write`` formats may be registered into the Astropy Cosmology\n I/O framework. For details of the framework see :ref:`io_registry`.\n-As a quick example, outlining how to make a\n-`~astropy.cosmology.Cosmology` <-> JSON serializer:\n+\n+.. EXAMPLE START : custom read/write\n+\n+As an example, in the following we will fully work out a\n+`~astropy.cosmology.Cosmology` <-> JSON (de)serializer.\n+Note that we can use other registered parsers -- here \"mapping\"\n+-- to make the implementation much simpler.\n+\n+We start by defining the function to parse JSON into a\n+`~astropy.cosmology.Cosmology`. This function should take 1 positional\n+argument, the file object or file path. We will also pass kwargs through to\n+:meth:`~astropy.cosmology.Cosmology.from_format`, which handles metadata\n+and which Cosmology class to use. Details of are in\n+``Cosmology.from_format.help(\"mapping\")``.\n \n .. code-block:: python\n+ :emphasize-lines: 9,12,17\n \n- import json\n- from astropy.cosmology import Cosmology\n- from astropy.io import registry as io_registry\n+ >>> import json, os\n+ >>> import astropy.units as u\n+ >>> from astropy.cosmology import Cosmology\n \n- def read_json(filename, **kwargs):\n- cosmology = ... # read and parse file\n- return cosmology\n+ >>> def read_json(filename, **kwargs):\n+ ... # read file, from path-like or file-like\n+ ... if isinstance(filename, (str, bytes, os.PathLike)):\n+ ... with open(filename, \"r\") as file:\n+ ... data = file.read()\n+ ... else: # file-like : this also handles errors in dumping\n+ ... data = filename.read()\n+ ... mapping = json.loads(data) # parse json mappable to dict\n+ ... # deserialize Quantity\n+ ... for k, v in mapping.items():\n+ ... if isinstance(v, dict) and \"value\" in v and \"unit\" in v:\n+ ... mapping[k] = u.Quantity(v[\"value\"], v[\"unit\"])\n+ ... return Cosmology.from_format(mapping, **kwargs)\n+\n+\n+The next step is a function to write a `~astropy.cosmology.Cosmology` to\n+JSON. This function requires the cosmology object and a file object/path.\n+We also require the boolean flag \"overwrite\" to set behavior for existing\n+files. Note that `~astropy.units.Quantity` is not natively compatible with\n+JSON. In both the ``write`` and ``read`` methods we have to create custom\n+parsers.\n+\n+.. code-block:: python\n+ :emphasize-lines: 2,15\n+\n+ >>> def write_json(cosmology, file, *, overwrite=False, **kwargs):\n+ ... data = cosmology.to_format(\"mapping\") # start by turning into dict\n+ ... data[\"cosmology\"] = data[\"cosmology\"].__name__ # change class field to str\n+ ... # serialize Quantity\n+ ... for k, v in data.items():\n+ ... if isinstance(v, u.Quantity):\n+ ... data[k] = {\"value\": v.value.tolist(),\n+ ... \"unit\": str(v.unit)}\n+ ...\n+ ... if isinstance(file, (str, bytes, os.PathLike)):\n+ ... # check that file exists and whether to overwrite.\n+ ... if os.path.exists(file) and not overwrite:\n+ ... raise IOError(f\"{file} exists. Set 'overwrite' to write over.\")\n+ ... with open(file, \"w\") as write_file:\n+ ... json.dump(data, write_file)\n+ ... else:\n+ ... json.dump(data, file)\n+\n+Last we write a function to help with format auto-identification and then\n+register everything into `astropy.io.registry`.\n+\n+.. code-block:: python\n+ :emphasize-lines: 7,8,9\n \n- def write_json(cosmology, file, **kwargs):\n- data = ... # parse cosmology to dict\n- with open(file, \"w\") as write_file:\n- json.dump(data, write_file)\n+ >>> from astropy.io import registry as io_registry\n \n- def json_identify(origin, filepath, fileobj, *args, **kwargs):\n- \"\"\"Identify if object uses the JSON format.\"\"\"\n- return filepath is not None and filepath.endswith(\".json\")\n+ >>> def json_identify(origin, filepath, fileobj, *args, **kwargs):\n+ ... \"\"\"Identify if object uses the JSON format.\"\"\"\n+ ... return filepath is not None and filepath.endswith(\".json\")\n \n- # register the read/write methods \n- io_registry.register_reader(\"json\", Cosmology, read_json)\n- io_registry.register_writer(\"json\", Cosmology, write_json)\n- io_registry.register_identifier(\"json\", Cosmology, json_identify)\n+ >>> io_registry.register_reader(\"json\", Cosmology, read_json)\n+ >>> io_registry.register_writer(\"json\", Cosmology, write_json)\n+ >>> io_registry.register_identifier(\"json\", Cosmology, json_identify)\n+ \n+Now the registered functions can be used in\n+:meth:`astropy.cosmology.Cosmology.read` and\n+:meth:`astropy.cosmology.Cosmology.write`.\n \n+.. doctest-skip:: win32\n+\n+ >>> import tempfile\n+ >>> from astropy.cosmology import Planck18\n+ >>>\n+ >>> file = tempfile.NamedTemporaryFile()\n+ >>> Planck18.write(file.name, format=\"json\", overwrite=True)\n+ >>> with open(file.name) as f: f.readlines()\n+ ['{\"cosmology\": \"FlatLambdaCDM\", \"name\": \"Planck18\",\n+ \"H0\": {\"value\": 67.66, \"unit\": \"km / (Mpc s)\"}, \"Om0\": 0.30966,\n+ ...\n+ >>>\n+ >>> cosmo = Cosmology.read(file.name, format=\"json\")\n+ >>> file.close()\n+ >>> cosmo == Planck18 # test it round-trips\n+ True\n+\n+\n+.. doctest::\n+ :hide:\n+\n+ >>> io_registry.unregister_reader(\"json\", Cosmology)\n+ >>> io_registry.unregister_writer(\"json\", Cosmology)\n+ >>> io_registry.unregister_identifier(\"json\", Cosmology)\n+ >>> try:\n+ ... io_registry.get_reader(\"json\", Cosmology)\n+ ... except io_registry.IORegistryError:\n+ ... pass\n+\n+.. EXAMPLE END\n \n Reference/API\n =============\n \n .. automodapi:: astropy.cosmology.connect\n+\n+.. automodapi:: astropy.cosmology.io.mapping\n"
},
{
"path": "docs/whatsnew/5.0.rst",
"old_path": "a/docs/whatsnew/5.0.rst",
"new_path": "b/docs/whatsnew/5.0.rst",
"metadata": "diff --git a/docs/whatsnew/5.0.rst b/docs/whatsnew/5.0.rst\nindex b8c135bb60..a224b149c9 100644\n--- a/docs/whatsnew/5.0.rst\n+++ b/docs/whatsnew/5.0.rst\n@@ -9,6 +9,47 @@ What's New in Astropy 5.0?\n Overview\n ========\n \n+.. _whatsnew-5.0-cosmology:\n+\n+Support for reading, writing, and converting ``Cosmology``\n+==========================================================\n+\n+Four new methods -- ``read``, ``write``, ``to_format``, ``from_format`` -- have\n+been added to the ``Cosmology`` class, enabling reading from and writing to\n+files and converting between different python objects.\n+The methods use Astropy's Unified I/O registry so custom formats can be\n+registered. Details are discussed in an addition to the docs.\n+\n+Currently no file formats are registered, but the syntax is as follows:\n+\n+.. doctest-skip::\n+\n+ >>> from astropy.cosmology import Planck18\n+ >>> Planck18.write('<file name>.<format>')\n+ >>>\n+ >>> from astropy.cosmology import Cosmology\n+ >>> cosmo = Cosmology.read('<file name>.<format>')\n+ >>> cosmo == Planck18\n+ True\n+\n+\n+The transformation between ``Cosmology`` and `dict` is pre-registered,\n+e.g. enabling::\n+\n+ >>> from astropy.cosmology import Planck18\n+ >>> cm = Planck18.to_format(\"mapping\")\n+ >>> cm\n+ {'cosmology': <class 'astropy.cosmology.core.FlatLambdaCDM'>,\n+ 'name': 'Planck18',\n+ 'H0': <Quantity 67.66 km / (Mpc s)>,\n+ 'Om0': 0.30966,\n+ ...\n+\n+ >>> from astropy.cosmology import Cosmology\n+ >>> cosmo = Cosmology.from_format(cm, format=\"mapping\")\n+ >>> cosmo == Planck18\n+ True\n+\n \n Full change log\n ===============\n"
}
] |
{
"header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:",
"data": [
{
"type": "field",
"name": "_init_signature"
},
{
"type": "file",
"name": "astropy/cosmology/io/mapping.py"
},
{
"type": "file",
"name": "astropy/cosmology/io/__init__.py"
},
{
"type": "field",
"name": "kind"
},
{
"type": "field",
"name": "tuple"
},
{
"type": "field",
"name": "_COSMOLOGY_CLASSES"
},
{
"type": "field",
"name": "TypeError"
},
{
"type": "field",
"name": "__class__"
}
]
}
|
diff --git a/docs/changes/cosmology/#####.feature.rst b/docs/changes/cosmology/#####.feature.rst
new file mode 100644
index 0000000000..df78f84a93
--- /dev/null
+++ b/docs/changes/cosmology/#####.feature.rst
@@ -0,0 +1,5 @@
+Added ``to_format/from_format`` methods to Cosmology using the Unified I/O
+registry. Now custom format converters and format-identifier functions
+can be registered to transform Cosmology objects.
+The transformation between Cosmology and dictionaries is pre-registered.
+Details are discussed in an addition to the docs.
diff --git a/docs/cosmology/io.rst b/docs/cosmology/io.rst
index bb9f1881b4..db5f9509a2 100644
--- a/docs/cosmology/io.rst
+++ b/docs/cosmology/io.rst
@@ -1,25 +1,22 @@
-.. doctest-skip-all
-
.. _read_write_cosmologies:
-Reading and Writing Cosmology Objects
-*************************************
+Read, Write, and Convert Cosmology Objects
+******************************************
An easy way to serialize and deserialize a Cosmology object is using the
:mod:`pickle` module.
-.. code-block:: python
- :emphasize-lines: 1,4,8
+.. doctest-skip::
>>> import pickle
>>> from astropy.cosmology import Planck18
>>> with open("planck18.pkl", mode="wb") as file:
- ... pickle.dump(file, Planck18)
-
- And to read the file back
+ ... pickle.dump(Planck18, file)
+ >>> # and to read back
>>> with open("planck18.pkl", mode="rb") as file:
- >>> cosmo = pickle.load(file)
+ ... cosmo = pickle.load(file)
>>> cosmo
+ FlatLambdaCDM(name="Planck18", ...
However this method has all the attendant drawbacks of :mod:`pickle` — security
vulnerabilities and non-human-readable files.
@@ -43,34 +40,197 @@ framework.
Writing a cosmology instance requires only the file location and optionally,
if the file format cannot be inferred, a keyword argument "format". Additional
positional arguments and keyword arguments are passed to the reader methods.
-::
+
+.. doctest-skip::
>>> from astropy.cosmology import Planck18
- >>> Planck18.write('[file name]')
+ >>> Planck18.write('<file name>')
Reading back the cosmology is most safely done from ``Cosmology``, the base
class, as it provides no default information and therefore requires the file
to have all necessary information to describe a cosmology.
-::
+.. doctest-skip::
>>> from astropy.cosmology import Cosmology
- >>> cosmo = Cosmology.read('[file name]')
+ >>> cosmo = Cosmology.read('<file name>')
>>> cosmo == Planck18
True
When a subclass of ``Cosmology`` is used to read a file, the subclass will
-provide a keyword argument ``cosmology=[class]`` to the registered read
+provide a keyword argument ``cosmology=<class>`` 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.
-::
+.. doctest-skip::
>>> from astropy.cosmology import FlatLambdaCDM
- >>> cosmo = FlatLambdaCDM.read('[file name]')
+ >>> cosmo = FlatLambdaCDM.read('<file name>')
>>> cosmo == Planck18
True
+
+Reading and writing :class:`~astropy.cosmology.Cosmology` objects go through
+intermediate representations, often a dict or `~astropy.table.QTable` instance.
+These intermediate representations are accessible through the methods
+:meth:`~astropy.cosmology.Cosmology.to_format` /
+:meth:`~astropy.cosmology.Cosmology.from_format`.
+
+To see the a list of the available formats:
+
+ >>> from astropy.cosmology import Cosmology
+ >>> Cosmology.to_format.list_formats()
+ Format Read Write Auto-identify
+ ------- ---- ----- -------------
+ mapping Yes Yes Yes
+
+This list will include both built-in and registered 3rd-party formats.
+
+:meth:`~astropy.cosmology.Cosmology.to_format` /
+:meth:`~astropy.cosmology.Cosmology.from_format` parse a Cosmology to/from
+another python object. This can be useful for e.g., iterating through an MCMC
+of cosmological parameters or printing out a cosmological model to a journal
+format, like latex or HTML. When 3rd party cosmology packages register with
+Astropy' Cosmology I/O, ``to/from_format`` can be used to convert cosmology
+instances between packages!
+
+.. EXAMPLE START: Planck18 to mapping and back
+
+.. code-block::
+
+ >>> from astropy.cosmology import Planck18
+ >>> cm = Planck18.to_format("mapping")
+ >>> cm
+ {'cosmology': <class 'astropy.cosmology.core.FlatLambdaCDM'>,
+ 'name': 'Planck18',
+ 'H0': <Quantity 67.66 km / (Mpc s)>,
+ 'Om0': 0.30966,
+ ...
+
+Now this dict can be used to load a new cosmological instance identical
+to the ``Planck18`` cosmology from which it was created.
+
+.. code-block::
+
+ >>> from astropy.cosmology import Cosmology
+ >>> cosmo = Cosmology.from_format(cm, format="mapping")
+ >>> cosmo == Planck18
+ True
+
+.. EXAMPLE END
+
+
+
+.. _custom_cosmology_converters:
+
+Custom Cosmology To/From Formats
+================================
+
+Custom representation formats may also be registered into the Astropy Cosmology
+I/O framework for use by these methods. For details of the framework see
+:ref:`io_registry`.
+
+.. EXAMPLE START : custom to/from format
+
+As an example, the following is an implementation of an `astropy.table.Row`
+converter. Note that we can use other registered parsers -- here "mapping"
+-- to make the implementation much simpler.
+
+We start by defining the function to parse a `astropy.table.Row` into a
+`~astropy.cosmology.Cosmology`. This function should take 1 positional
+argument, the row object, and 2 keyword arguments, for how to handle
+extra metadata and which Cosmology class to use. Details about metadata
+treatment are in ``Cosmology.from_format.help("mapping")``.
+
+.. code-block:: python
+ :emphasize-lines: 12,13
+
+ >>> import copy
+ >>> from astropy.cosmology import Cosmology
+
+ >>> def from_table_row(row, *, move_to_meta=False, cosmology=None):
+ ... # get name from column
+ ... name = row['name'] if 'name' in row.columns else None
+ ... meta = copy.deepcopy(row.meta)
+ ... # turn row into mapping (dict of the arguments)
+ ... mapping = dict(row)
+ ... mapping["meta"] = meta
+ ... # build cosmology from map
+ ... return Cosmology.from_format(mapping,
+ ... move_to_meta=move_to_meta, cosmology=cosmology)
+
+The next step is a function to perform the reverse operation: parse a
+`~astropy.cosmology.Cosmology` into a `~astropy.table.Row`. This function
+requires only the cosmology object and a ``*args`` to absorb unneeded
+information passed by `astropy.io.registry.UnifiedReadWrite` (which
+implements `astropy.cosmology.Cosmology.to_format`).
+
+.. code-block:: python
+ :emphasize-lines: 4
+
+ >>> from astropy.table import QTable
+
+ >>> def to_table_row(cosmology, *args):
+ ... p = cosmology.to_format("mapping")
+ ... p["cosmology"] = p["cosmology"].__qualname__ # as string
+ ... meta = p.pop("meta")
+ ... # package parameters into lists for Table parsing
+ ... params = {k: [v] for k, v in p.items()}
+ ... return QTable(params, meta=meta)[0] # return row
+
+Last we write a function to help with format auto-identification and then
+register everything into `astropy.io.registry`.
+
+.. code-block:: python
+ :emphasize-lines: 11, 12, 13
+
+ >>> from astropy.cosmology import Cosmology
+ >>> from astropy.io import registry as io_registry
+ >>> from astropy.table import Row
+
+ >>> def row_identify(origin, format, *args, **kwargs):
+ ... """Identify if object uses the Table format."""
+ ... if origin == "read":
+ ... return isinstance(args[1], Row) and (format in (None, "row"))
+ ... return False
+
+ >>> io_registry.register_reader("row", Cosmology, from_table_row)
+ >>> io_registry.register_writer("row", Cosmology, to_table_row)
+ >>> io_registry.register_identifier("row", Cosmology, row_identify)
+
+Now the registered functions can be used in
+:meth:`astropy.cosmology.Cosmology.from_format` and
+:meth:`astropy.cosmology.Cosmology.to_format`.
+
+.. code-block:: python
+
+ >>> from astropy.cosmology import Planck18
+ >>> row = Planck18.to_format("row")
+ >>> row
+ <Row index=0>
+ cosmology name H0 Om0 Tcmb0 Neff m_nu [3] Ob0
+ km / (Mpc s) eV
+ str13 str8 float64 float64 float64 float64 float64 float64
+ ------------- -------- ------------ ------- ------- ------- ----------- -------
+ FlatLambdaCDM Planck18 67.66 0.30966 2.7255 3.046 0.0 .. 0.06 0.04897
+
+ >>> cosmo = Cosmology.from_format(row)
+ >>> cosmo == Planck18 # test it round-trips
+ True
+
+
+.. doctest::
+ :hide:
+
+ >>> io_registry.unregister_reader("row", Cosmology)
+ >>> io_registry.unregister_writer("row", Cosmology)
+ >>> io_registry.unregister_identifier("row", Cosmology)
+ >>> try:
+ ... io_registry.get_reader("row", Cosmology)
+ ... except io_registry.IORegistryError:
+ ... pass
+
+.. EXAMPLE END
.. _custom_cosmology_readers_writers:
@@ -80,35 +240,125 @@ Custom Cosmology Readers/Writers
Custom ``read`` / ``write`` formats may be registered into the Astropy Cosmology
I/O framework. For details of the framework see :ref:`io_registry`.
-As a quick example, outlining how to make a
-`~astropy.cosmology.Cosmology` <-> JSON serializer:
+
+.. EXAMPLE START : custom read/write
+
+As an example, in the following we will fully work out a
+`~astropy.cosmology.Cosmology` <-> JSON (de)serializer.
+Note that we can use other registered parsers -- here "mapping"
+-- to make the implementation much simpler.
+
+We start by defining the function to parse JSON into a
+`~astropy.cosmology.Cosmology`. This function should take 1 positional
+argument, the file object or file path. We will also pass kwargs through to
+:meth:`~astropy.cosmology.Cosmology.from_format`, which handles metadata
+and which Cosmology class to use. Details of are in
+``Cosmology.from_format.help("mapping")``.
.. code-block:: python
+ :emphasize-lines: 9,12,17
- import json
- from astropy.cosmology import Cosmology
- from astropy.io import registry as io_registry
+ >>> import json, os
+ >>> import astropy.units as u
+ >>> from astropy.cosmology import Cosmology
- def read_json(filename, **kwargs):
- cosmology = ... # read and parse file
- return cosmology
+ >>> def read_json(filename, **kwargs):
+ ... # read file, from path-like or file-like
+ ... if isinstance(filename, (str, bytes, os.PathLike)):
+ ... with open(filename, "r") as file:
+ ... data = file.read()
+ ... else: # file-like : this also handles errors in dumping
+ ... data = filename.read()
+ ... mapping = json.loads(data) # parse json mappable to dict
+ ... # deserialize Quantity
+ ... for k, v in mapping.items():
+ ... if isinstance(v, dict) and "value" in v and "unit" in v:
+ ... mapping[k] = u.Quantity(v["value"], v["unit"])
+ ... return Cosmology.from_format(mapping, **kwargs)
+
+
+The next step is a function to write a `~astropy.cosmology.Cosmology` to
+JSON. This function requires the cosmology object and a file object/path.
+We also require the boolean flag "overwrite" to set behavior for existing
+files. Note that `~astropy.units.Quantity` is not natively compatible with
+JSON. In both the ``write`` and ``read`` methods we have to create custom
+parsers.
+
+.. code-block:: python
+ :emphasize-lines: 2,15
+
+ >>> def write_json(cosmology, file, *, overwrite=False, **kwargs):
+ ... data = cosmology.to_format("mapping") # start by turning into dict
+ ... data["cosmology"] = data["cosmology"].__name__ # change class field to str
+ ... # serialize Quantity
+ ... for k, v in data.items():
+ ... if isinstance(v, u.Quantity):
+ ... data[k] = {"value": v.value.tolist(),
+ ... "unit": str(v.unit)}
+ ...
+ ... if isinstance(file, (str, bytes, os.PathLike)):
+ ... # check that file exists and whether to overwrite.
+ ... if os.path.exists(file) and not overwrite:
+ ... raise IOError(f"{file} exists. Set 'overwrite' to write over.")
+ ... with open(file, "w") as write_file:
+ ... json.dump(data, write_file)
+ ... else:
+ ... json.dump(data, file)
+
+Last we write a function to help with format auto-identification and then
+register everything into `astropy.io.registry`.
+
+.. code-block:: python
+ :emphasize-lines: 7,8,9
- def write_json(cosmology, file, **kwargs):
- data = ... # parse cosmology to dict
- with open(file, "w") as write_file:
- json.dump(data, write_file)
+ >>> from astropy.io import registry as io_registry
- def json_identify(origin, filepath, fileobj, *args, **kwargs):
- """Identify if object uses the JSON format."""
- return filepath is not None and filepath.endswith(".json")
+ >>> def json_identify(origin, filepath, fileobj, *args, **kwargs):
+ ... """Identify if object uses the JSON format."""
+ ... return filepath is not None and filepath.endswith(".json")
- # register the read/write methods
- io_registry.register_reader("json", Cosmology, read_json)
- io_registry.register_writer("json", Cosmology, write_json)
- io_registry.register_identifier("json", Cosmology, json_identify)
+ >>> io_registry.register_reader("json", Cosmology, read_json)
+ >>> io_registry.register_writer("json", Cosmology, write_json)
+ >>> io_registry.register_identifier("json", Cosmology, json_identify)
+
+Now the registered functions can be used in
+:meth:`astropy.cosmology.Cosmology.read` and
+:meth:`astropy.cosmology.Cosmology.write`.
+.. doctest-skip:: win32
+
+ >>> import tempfile
+ >>> from astropy.cosmology import Planck18
+ >>>
+ >>> file = tempfile.NamedTemporaryFile()
+ >>> Planck18.write(file.name, format="json", overwrite=True)
+ >>> with open(file.name) as f: f.readlines()
+ ['{"cosmology": "FlatLambdaCDM", "name": "Planck18",
+ "H0": {"value": 67.66, "unit": "km / (Mpc s)"}, "Om0": 0.30966,
+ ...
+ >>>
+ >>> cosmo = Cosmology.read(file.name, format="json")
+ >>> file.close()
+ >>> cosmo == Planck18 # test it round-trips
+ True
+
+
+.. doctest::
+ :hide:
+
+ >>> io_registry.unregister_reader("json", Cosmology)
+ >>> io_registry.unregister_writer("json", Cosmology)
+ >>> io_registry.unregister_identifier("json", Cosmology)
+ >>> try:
+ ... io_registry.get_reader("json", Cosmology)
+ ... except io_registry.IORegistryError:
+ ... pass
+
+.. EXAMPLE END
Reference/API
=============
.. automodapi:: astropy.cosmology.connect
+
+.. automodapi:: astropy.cosmology.io.mapping
diff --git a/docs/whatsnew/5.0.rst b/docs/whatsnew/5.0.rst
index b8c135bb60..a224b149c9 100644
--- a/docs/whatsnew/5.0.rst
+++ b/docs/whatsnew/5.0.rst
@@ -9,6 +9,47 @@ What's New in Astropy 5.0?
Overview
========
+.. _whatsnew-5.0-cosmology:
+
+Support for reading, writing, and converting ``Cosmology``
+==========================================================
+
+Four new methods -- ``read``, ``write``, ``to_format``, ``from_format`` -- have
+been added to the ``Cosmology`` class, enabling reading from and writing to
+files and converting between different python objects.
+The methods use Astropy's Unified I/O registry so custom formats can be
+registered. Details are discussed in an addition to the docs.
+
+Currently no file formats are registered, but the syntax is as follows:
+
+.. doctest-skip::
+
+ >>> from astropy.cosmology import Planck18
+ >>> Planck18.write('<file name>.<format>')
+ >>>
+ >>> from astropy.cosmology import Cosmology
+ >>> cosmo = Cosmology.read('<file name>.<format>')
+ >>> cosmo == Planck18
+ True
+
+
+The transformation between ``Cosmology`` and `dict` is pre-registered,
+e.g. enabling::
+
+ >>> from astropy.cosmology import Planck18
+ >>> cm = Planck18.to_format("mapping")
+ >>> cm
+ {'cosmology': <class 'astropy.cosmology.core.FlatLambdaCDM'>,
+ 'name': 'Planck18',
+ 'H0': <Quantity 67.66 km / (Mpc s)>,
+ 'Om0': 0.30966,
+ ...
+
+ >>> from astropy.cosmology import Cosmology
+ >>> cosmo = Cosmology.from_format(cm, format="mapping")
+ >>> cosmo == Planck18
+ True
+
Full change log
===============
If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:
[{'type': 'field', 'name': '_init_signature'}, {'type': 'file', 'name': 'astropy/cosmology/io/mapping.py'}, {'type': 'file', 'name': 'astropy/cosmology/io/__init__.py'}, {'type': 'field', 'name': 'kind'}, {'type': 'field', 'name': 'tuple'}, {'type': 'field', 'name': '_COSMOLOGY_CLASSES'}, {'type': 'field', 'name': 'TypeError'}, {'type': 'field', 'name': '__class__'}]
|
astropy/astropy
|
astropy__astropy-11470
|
https://github.com/astropy/astropy/pull/11470
|
diff --git a/astropy/coordinates/representation.py b/astropy/coordinates/representation.py
index 76e5dde236e5..a806523a993a 100644
--- a/astropy/coordinates/representation.py
+++ b/astropy/coordinates/representation.py
@@ -1048,9 +1048,6 @@ def _scale_operation(self, op, *args):
Any arguments required for the operator (typically, what is to
be multiplied with, divided by).
"""
-
- self._raise_if_has_differentials(op.__name__)
-
results = []
for component, cls in self.attr_classes.items():
value = getattr(self, component)
@@ -1063,10 +1060,16 @@ def _scale_operation(self, op, *args):
# as operations that returned NotImplemented or a representation
# instead of a quantity (as would happen for, e.g., rep * rep).
try:
- return self.__class__(*results)
+ result = self.__class__(*results)
except Exception:
return NotImplemented
+ for key, differential in self.differentials.items():
+ diff_result = differential._scale_operation(op, *args, scaled_base=True)
+ result.differentials[key] = diff_result
+
+ return result
+
def _combine_operation(self, op, other, reverse=False):
"""Combine two representation.
@@ -1655,19 +1658,23 @@ def transform(self, matrix):
return rep
- def __mul__(self, other):
- self._raise_if_has_differentials('multiplication')
- return self._dimensional_representation(lon=self.lon, lat=self.lat,
- distance=1. * other)
-
- def __truediv__(self, other):
- self._raise_if_has_differentials('division')
- return self._dimensional_representation(lon=self.lon, lat=self.lat,
- distance=1. / other)
+ def _scale_operation(self, op, *args):
+ return self._dimensional_representation(
+ lon=self.lon, lat=self.lat, distance=1.,
+ differentials=self.differentials)._scale_operation(op, *args)
def __neg__(self):
- self._raise_if_has_differentials('negation')
- return self.__class__(self.lon + 180. * u.deg, -self.lat, copy=False)
+ if any(differential.base_representation is not self.__class__
+ for differential in self.differentials.values()):
+ return super().__neg__()
+
+ result = self.__class__(self.lon + 180. * u.deg, -self.lat, copy=False)
+ for key, differential in self.differentials.items():
+ new_comps = (op(getattr(differential, comp))
+ for op, comp in zip((operator.pos, operator.neg),
+ differential.components))
+ result.differentials[key] = differential.__class__(*new_comps, copy=False)
+ return result
def norm(self):
"""Vector norm.
@@ -1805,9 +1812,11 @@ def from_cartesian(cls, cart):
"""
return cls(distance=cart.norm(), copy=False)
- def _scale_operation(self, op, *args):
- self._raise_if_has_differentials(op.__name__)
- return op(self.distance, *args)
+ def __mul__(self, other):
+ if isinstance(other, BaseRepresentation):
+ return self.distance * other
+ else:
+ return super().__mul__(other)
def norm(self):
"""Vector norm.
@@ -1838,6 +1847,23 @@ def transform(self, matrix):
)
+def _spherical_op_funcs(op, *args):
+ """For given operator, return functions that adjust lon, lat, distance."""
+ if op is operator.neg:
+ return lambda x: x+180*u.deg, operator.neg, operator.pos
+
+ try:
+ scale_sign = np.sign(args[0])
+ except Exception:
+ # This should always work, even if perhaps we get a negative distance.
+ return operator.pos, operator.pos, lambda x: op(x, *args)
+
+ scale = abs(args[0])
+ return (lambda x: x + 180*u.deg*np.signbit(scale_sign),
+ lambda x: x * scale_sign,
+ lambda x: op(x, scale))
+
+
class SphericalRepresentation(BaseRepresentation):
"""
Representation of points in 3D spherical coordinates.
@@ -2021,10 +2047,22 @@ def norm(self):
"""
return np.abs(self.distance)
- def __neg__(self):
- self._raise_if_has_differentials('negation')
- return self.__class__(self.lon + 180. * u.deg, -self.lat, self.distance,
- copy=False)
+ def _scale_operation(self, op, *args):
+ # TODO: expand special-casing to UnitSpherical and RadialDifferential.
+ if any(differential.base_representation is not self.__class__
+ for differential in self.differentials.values()):
+ return super()._scale_operation(op, *args)
+
+ lon_op, lat_op, distance_op = _spherical_op_funcs(op, *args)
+
+ result = self.__class__(lon_op(self.lon), lat_op(self.lat),
+ distance_op(self.distance), copy=False)
+ for key, differential in self.differentials.items():
+ new_comps = (op(getattr(differential, comp)) for op, comp in zip(
+ (operator.pos, lat_op, distance_op),
+ differential.components))
+ result.differentials[key] = differential.__class__(*new_comps, copy=False)
+ return result
class PhysicsSphericalRepresentation(BaseRepresentation):
@@ -2214,6 +2252,24 @@ def norm(self):
"""
return np.abs(self.r)
+ def _scale_operation(self, op, *args):
+ if any(differential.base_representation is not self.__class__
+ for differential in self.differentials.values()):
+ return super()._scale_operation(op, *args)
+
+ phi_op, adjust_theta_sign, r_op = _spherical_op_funcs(op, *args)
+ # Also run phi_op on theta to ensure theta remains between 0 and 180:
+ # any time the scale is negative, we do -theta + 180 degrees.
+ result = self.__class__(phi_op(self.phi),
+ phi_op(adjust_theta_sign(self.theta)),
+ r_op(self.r), copy=False)
+ for key, differential in self.differentials.items():
+ new_comps = (op(getattr(differential, comp)) for op, comp in zip(
+ (operator.pos, adjust_theta_sign, r_op),
+ differential.components))
+ result.differentials[key] = differential.__class__(*new_comps, copy=False)
+ return result
+
class CylindricalRepresentation(BaseRepresentation):
"""
@@ -2317,6 +2373,22 @@ def to_cartesian(self):
return CartesianRepresentation(x=x, y=y, z=z, copy=False)
+ def _scale_operation(self, op, *args):
+ if any(differential.base_representation is not self.__class__
+ for differential in self.differentials.values()):
+ return super()._scale_operation(op, *args)
+
+ phi_op, _, rho_op = _spherical_op_funcs(op, *args)
+ z_op = lambda x: op(x, *args)
+
+ result = self.__class__(rho_op(self.rho), phi_op(self.phi),
+ z_op(self.z), copy=False)
+ for key, differential in self.differentials.items():
+ new_comps = (op(getattr(differential, comp)) for op, comp in zip(
+ (rho_op, operator.pos, z_op), differential.components))
+ result.differentials[key] = differential.__class__(*new_comps, copy=False)
+ return result
+
class BaseDifferential(BaseRepresentationOrDifferential):
r"""A base class representing differentials of representations.
@@ -2561,7 +2633,7 @@ class is a differential representation, the base will be converted
diff = cdiff.represent_as(self.__class__, transformed_base)
return diff
- def _scale_operation(self, op, *args):
+ def _scale_operation(self, op, *args, scaled_base=False):
"""Scale all components.
Parameters
@@ -2571,6 +2643,11 @@ def _scale_operation(self, op, *args):
*args
Any arguments required for the operator (typically, what is to
be multiplied with, divided by).
+ scaled_base : bool, optional
+ Whether the base was scaled the same way. This affects whether
+ differential components should be scaled. For instance, a differential
+ in longitude should not be scaled if its spherical base is scaled
+ in radius.
"""
scaled_attrs = [op(getattr(self, c), *args) for c in self.components]
return self.__class__(*scaled_attrs, copy=False)
@@ -2913,6 +2990,12 @@ class is a differential representation, the base will be converted
return diff
+ def _scale_operation(self, op, *args, scaled_base=False):
+ if scaled_base:
+ return self.copy()
+ else:
+ return super()._scale_operation(op, *args)
+
class SphericalDifferential(BaseSphericalDifferential):
"""Differential(s) of points in 3D spherical coordinates.
@@ -2965,6 +3048,12 @@ def from_representation(cls, representation, base=None):
return super().from_representation(representation, base)
+ def _scale_operation(self, op, *args, scaled_base=False):
+ if scaled_base:
+ return self.__class__(self.d_lon, self.d_lat, op(self.d_distance, *args))
+ else:
+ return super()._scale_operation(op, *args)
+
class BaseSphericalCosLatDifferential(BaseDifferential):
"""Differentials from points on a spherical base representation.
@@ -3156,6 +3245,12 @@ class is a differential representation, the base will be converted
return diff
+ def _scale_operation(self, op, *args, scaled_base=False):
+ if scaled_base:
+ return self.copy()
+ else:
+ return super()._scale_operation(op, *args)
+
class SphericalCosLatDifferential(BaseSphericalCosLatDifferential):
"""Differential(s) of points in 3D spherical coordinates.
@@ -3213,6 +3308,12 @@ def from_representation(cls, representation, base=None):
return super().from_representation(representation, base)
+ def _scale_operation(self, op, *args, scaled_base=False):
+ if scaled_base:
+ return self.__class__(self.d_lon_coslat, self.d_lat, op(self.d_distance, *args))
+ else:
+ return super()._scale_operation(op, *args)
+
class RadialDifferential(BaseDifferential):
"""Differential(s) of radial distances.
@@ -3325,6 +3426,12 @@ def from_representation(cls, representation, base=None):
return super().from_representation(representation, base)
+ def _scale_operation(self, op, *args, scaled_base=False):
+ if scaled_base:
+ return self.__class__(self.d_phi, self.d_theta, op(self.d_r, *args))
+ else:
+ return super()._scale_operation(op, *args)
+
class CylindricalDifferential(BaseDifferential):
"""Differential(s) of points in cylindrical coordinates.
diff --git a/docs/changes/coordinates/11470.feature.rst b/docs/changes/coordinates/11470.feature.rst
new file mode 100644
index 000000000000..51927b0b0a47
--- /dev/null
+++ b/docs/changes/coordinates/11470.feature.rst
@@ -0,0 +1,7 @@
+Allow negation, multiplication and division also of representations that
+include a differential (e.g., ``SphericalRepresentation`` with a
+``SphericalCosLatDifferential``). For all operations, the outcome is
+equivalent to transforming the representation and differential to cartesian,
+then operating on those, and transforming back to the original representation
+(except for ``UnitSphericalRepresentation``, which will return a
+``SphericalRepresentation`` if there is a scale change).
|
diff --git a/astropy/coordinates/tests/test_representation_arithmetic.py b/astropy/coordinates/tests/test_representation_arithmetic.py
index 1979dbbb9c30..18815959cd04 100644
--- a/astropy/coordinates/tests/test_representation_arithmetic.py
+++ b/astropy/coordinates/tests/test_representation_arithmetic.py
@@ -1,18 +1,20 @@
# Licensed under a 3-clause BSD style license - see LICENSE.rst
import functools
+import operator
import pytest
import numpy as np
from astropy import units as u
-from astropy.coordinates import (PhysicsSphericalRepresentation, CartesianRepresentation,
- CylindricalRepresentation, SphericalRepresentation,
- UnitSphericalRepresentation, SphericalDifferential,
- CartesianDifferential, UnitSphericalDifferential,
- SphericalCosLatDifferential, UnitSphericalCosLatDifferential,
- PhysicsSphericalDifferential, CylindricalDifferential,
- RadialRepresentation, RadialDifferential, Longitude, Latitude)
+from astropy.coordinates import (
+ PhysicsSphericalRepresentation, CartesianRepresentation,
+ CylindricalRepresentation, SphericalRepresentation,
+ UnitSphericalRepresentation, SphericalDifferential,
+ CartesianDifferential, UnitSphericalDifferential,
+ SphericalCosLatDifferential, UnitSphericalCosLatDifferential,
+ PhysicsSphericalDifferential, CylindricalDifferential,
+ RadialRepresentation, RadialDifferential, Longitude, Latitude)
from astropy.coordinates.representation import DIFFERENTIAL_CLASSES
from astropy.coordinates.angle_utilities import angular_separation
from astropy.tests.helper import assert_quantity_allclose, quantity_allclose
@@ -150,7 +152,8 @@ def test_mul_div(self, representation):
assert_quantity_allclose(r2.norm(),
self.distance * np.array([[1.], [2.]]))
r3 = -in_rep
- assert np.all(representation_equal(r3, in_rep * -1.))
+ assert_representation_allclose(r3.to_cartesian(),
+ (in_rep * -1.).to_cartesian(), atol=1e-5*u.pc)
with pytest.raises(TypeError):
in_rep * in_rep
with pytest.raises(TypeError):
@@ -669,16 +672,16 @@ def test_differential_init_errors(self, omit_coslat):
self.SD_cls(1.*u.arcsec, 0., 0.)
with pytest.raises(TypeError):
self.SD_cls(1.*u.arcsec, 0.*u.arcsec, 0.*u.kpc,
- False, False)
+ False, False)
with pytest.raises(TypeError):
self.SD_cls(1.*u.arcsec, 0.*u.arcsec, 0.*u.kpc,
- copy=False, d_lat=0.*u.arcsec)
+ copy=False, d_lat=0.*u.arcsec)
with pytest.raises(TypeError):
self.SD_cls(1.*u.arcsec, 0.*u.arcsec, 0.*u.kpc,
- copy=False, flying='circus')
+ copy=False, flying='circus')
with pytest.raises(ValueError):
self.SD_cls(np.ones(2)*u.arcsec,
- np.zeros(3)*u.arcsec, np.zeros(2)*u.kpc)
+ np.zeros(3)*u.arcsec, np.zeros(2)*u.kpc)
with pytest.raises(u.UnitsError):
self.SD_cls(1.*u.arcsec, 1.*u.s, 0.*u.kpc)
with pytest.raises(u.UnitsError):
@@ -1190,6 +1193,127 @@ def test_combinations(self, sd_cls):
assert_representation_allclose(self.s + (uo+ro), self.s+so1)
+@pytest.mark.parametrize('op,args', [
+ (operator.neg, ()),
+ (operator.pos, ()),
+ (operator.mul, (-8.,)),
+ (operator.truediv, ([4., 8.]*u.s,))], scope='class')
+class TestArithmeticWithDifferentials:
+ def setup_class(self):
+ self.cr = CartesianRepresentation([1, 2, 3]*u.kpc)
+ self.cd = CartesianDifferential([.1, -.2, .3]*u.km/u.s)
+ self.c = self.cr.with_differentials(self.cd)
+
+ def test_operation_cartesian(self, op, args):
+ ncr = op(self.c, *args)
+ expected = (op(self.cr, *args)).with_differentials(op(self.cd, *args))
+ assert np.all(ncr == expected)
+
+ def test_operation_radial(self, op, args):
+ rep = self.c.represent_as(RadialRepresentation, {'s': RadialDifferential})
+ result = op(rep, *args)
+ expected_distance = op(self.cr.norm(), *args)
+ expected_rv = op((self.cr/self.cr.norm()).dot(self.cd), *args)
+ assert u.allclose(result.distance, expected_distance)
+ assert u.allclose(result.differentials['s'].d_distance, expected_rv)
+
+ @pytest.mark.parametrize('diff_cls', [
+ SphericalDifferential,
+ SphericalCosLatDifferential,
+ PhysicsSphericalDifferential,
+ CylindricalDifferential])
+ def test_operation_other(self, diff_cls, op, args):
+ rep_cls = diff_cls.base_representation
+ rep = self.c.represent_as(rep_cls, {'s': diff_cls})
+ result = op(rep, *args)
+
+ expected_c = op(self.c, *args)
+ expected = expected_c.represent_as(rep_cls, {'s': diff_cls})
+ # Check that we match in the representation itself.
+ assert_representation_allclose(result, expected)
+ assert_differential_allclose(result.differentials['s'],
+ expected.differentials['s'])
+
+ # Check that we compare correctly in cartesian as well, just to be sure.
+ result_c = result.represent_as(CartesianRepresentation,
+ {'s': CartesianDifferential})
+ assert_representation_allclose(result_c, expected_c)
+ assert_differential_allclose(result_c.differentials['s'],
+ expected_c.differentials['s'])
+
+ @pytest.mark.parametrize('rep_cls', [
+ SphericalRepresentation,
+ PhysicsSphericalRepresentation,
+ CylindricalRepresentation])
+ def test_operation_cartesian_differential(self, rep_cls, op, args):
+ rep = self.c.represent_as(rep_cls, {'s': CartesianDifferential})
+ result = op(rep, *args)
+
+ expected_c = op(self.c, *args)
+ expected = expected_c.represent_as(rep_cls, {'s': CartesianDifferential})
+ # Check that we match in the representation itself.
+ assert_representation_allclose(result, expected)
+ assert_differential_allclose(result.differentials['s'],
+ expected.differentials['s'])
+
+ @pytest.mark.parametrize('diff_cls', [
+ UnitSphericalDifferential,
+ UnitSphericalCosLatDifferential])
+ def test_operation_unit_spherical(self, diff_cls, op, args):
+ rep_cls = diff_cls.base_representation
+ rep = self.c.represent_as(rep_cls, {'s': diff_cls})
+ result = op(rep, *args)
+
+ if op not in (operator.neg, operator.pos):
+ expected_cls = rep._dimensional_representation
+ else:
+ expected_cls = rep_cls
+
+ assert type(result) is expected_cls
+ assert type(result.differentials['s']) is diff_cls
+
+ # Have lost information, so unlike above we convert our initial
+ # unit-spherical back to Cartesian, and check that applying
+ # the operation on that cartesian representation gives the same result.
+ # We do not compare the output directly, since for multiplication
+ # and division there will be sign flips in the spherical distance.
+ expected_c = op(rep.represent_as(CartesianRepresentation,
+ {'s': CartesianDifferential}), *args)
+ result_c = result.represent_as(CartesianRepresentation,
+ {'s': CartesianDifferential})
+ assert_representation_allclose(result_c, expected_c)
+ assert_differential_allclose(result_c.differentials['s'],
+ expected_c.differentials['s'])
+
+ @pytest.mark.parametrize('diff_cls', [
+ RadialDifferential,
+ UnitSphericalDifferential,
+ UnitSphericalCosLatDifferential])
+ def test_operation_spherical_with_rv_or_pm(self, diff_cls, op, args):
+ rep = self.c.represent_as(SphericalRepresentation, {'s': diff_cls})
+ result = op(rep, *args)
+ assert type(result) is SphericalRepresentation
+ assert type(result.differentials['s']) is diff_cls
+
+ expected_c = op(rep.represent_as(CartesianRepresentation,
+ {'s': CartesianDifferential}), *args)
+ result_c = result.represent_as(CartesianRepresentation,
+ {'s': CartesianDifferential})
+ assert_representation_allclose(result_c, expected_c)
+ assert_differential_allclose(result_c.differentials['s'],
+ expected_c.differentials['s'])
+
+
+@pytest.mark.parametrize('op,args', [
+ (operator.neg, ()),
+ (operator.mul, (10.,))])
+def test_operation_unitspherical_with_rv_fails(op, args):
+ rep = UnitSphericalRepresentation(
+ 0*u.deg, 0*u.deg, differentials={'s': RadialDifferential(10*u.km/u.s)})
+ with pytest.raises(ValueError, match='unit key'):
+ op(rep, *args)
+
+
@pytest.mark.parametrize('rep,dif', [
[CartesianRepresentation([1, 2, 3]*u.kpc),
CartesianDifferential([.1, .2, .3]*u.km/u.s)],
@@ -1211,12 +1335,3 @@ def test_arithmetic_with_differentials_fail(rep, dif):
with pytest.raises(TypeError):
rep / rep
-
- with pytest.raises(TypeError):
- 10. * rep
-
- with pytest.raises(TypeError):
- rep / 10.
-
- with pytest.raises(TypeError):
- -rep
|
[
{
"path": "docs/changes/coordinates/11470.feature.rst",
"old_path": "/dev/null",
"new_path": "b/docs/changes/coordinates/11470.feature.rst",
"metadata": "diff --git a/docs/changes/coordinates/11470.feature.rst b/docs/changes/coordinates/11470.feature.rst\nnew file mode 100644\nindex 000000000000..51927b0b0a47\n--- /dev/null\n+++ b/docs/changes/coordinates/11470.feature.rst\n@@ -0,0 +1,7 @@\n+Allow negation, multiplication and division also of representations that\n+include a differential (e.g., ``SphericalRepresentation`` with a\n+``SphericalCosLatDifferential``). For all operations, the outcome is\n+equivalent to transforming the representation and differential to cartesian,\n+then operating on those, and transforming back to the original representation\n+(except for ``UnitSphericalRepresentation``, which will return a\n+``SphericalRepresentation`` if there is a scale change).\n",
"update": null
}
] |
5.0
|
505c02d0282a2199d4e6c2894469a46bbee3bc14
|
[
"astropy/coordinates/tests/test_representation_arithmetic.py::TestSphericalDifferential::test_name_coslat[False]",
"astropy/coordinates/tests/test_representation_arithmetic.py::TestUnitSphericalDifferential::test_name_coslat[False]",
"astropy/coordinates/tests/test_representation_arithmetic.py::TestArithmeticWithDifferentials::test_operation_spherical_with_rv_or_pm[UnitSphericalCosLatDifferential-pos-args1]",
"astropy/coordinates/tests/test_representation_arithmetic.py::TestSphericalDifferential::test_differential_arithmetic[True]",
"astropy/coordinates/tests/test_representation_arithmetic.py::TestRadialDifferential::test_name",
"astropy/coordinates/tests/test_representation_arithmetic.py::TestArithmeticWithDifferentials::test_operation_unit_spherical[UnitSphericalDifferential-pos-args1]",
"astropy/coordinates/tests/test_representation_arithmetic.py::TestUnitSphericalDifferential::test_name_coslat[True]",
"astropy/coordinates/tests/test_representation_arithmetic.py::TestUnitSphericalDifferential::test_differential_arithmetic[False]",
"astropy/coordinates/tests/test_representation_arithmetic.py::TestUnitVectorsAndScales::test_cartesian",
"astropy/coordinates/tests/test_representation_arithmetic.py::TestUnitVectorsAndScales::test_radial",
"astropy/coordinates/tests/test_representation_arithmetic.py::TestArithmeticWithDifferentials::test_operation_cartesian_differential[SphericalRepresentation-pos-args1]",
"astropy/coordinates/tests/test_representation_arithmetic.py::TestDifferentialConversion::test_represent_as_own_class[SphericalDifferential]",
"astropy/coordinates/tests/test_representation_arithmetic.py::TestSphericalDifferential::test_simple_differentials[False]",
"astropy/coordinates/tests/test_representation_arithmetic.py::TestUnitSphericalDifferential::test_simple_differentials[True]",
"astropy/coordinates/tests/test_representation_arithmetic.py::TestArithmeticWithDifferentials::test_operation_other[SphericalCosLatDifferential-pos-args1]",
"astropy/coordinates/tests/test_representation_arithmetic.py::test_arithmetic_with_differentials_fail[rep1-dif1]",
"astropy/coordinates/tests/test_representation_arithmetic.py::TestArithmeticWithDifferentials::test_operation_other[PhysicsSphericalDifferential-pos-args1]",
"astropy/coordinates/tests/test_representation_arithmetic.py::TestArithmeticWithDifferentials::test_operation_spherical_with_rv_or_pm[UnitSphericalDifferential-pos-args1]",
"astropy/coordinates/tests/test_representation_arithmetic.py::TestUnitVectorsAndScales::test_cylindrical",
"astropy/coordinates/tests/test_representation_arithmetic.py::TestPhysicsSphericalDifferential::test_name",
"astropy/coordinates/tests/test_representation_arithmetic.py::TestArithmeticWithDifferentials::test_operation_other[CylindricalDifferential-pos-args1]",
"astropy/coordinates/tests/test_representation_arithmetic.py::TestSphericalDifferential::test_differential_init_errors[False]",
"astropy/coordinates/tests/test_representation_arithmetic.py::TestUnitSphericalDifferential::test_simple_differentials[False]",
"astropy/coordinates/tests/test_representation_arithmetic.py::TestPhysicsSphericalDifferential::test_differential_init_errors",
"astropy/coordinates/tests/test_representation_arithmetic.py::TestUnitSphericalDifferential::test_differential_init_errors[False]",
"astropy/coordinates/tests/test_representation_arithmetic.py::TestSphericalDifferential::test_name_coslat[True]",
"astropy/coordinates/tests/test_representation_arithmetic.py::TestUnitSphericalDifferential::test_differential_arithmetic[True]",
"astropy/coordinates/tests/test_representation_arithmetic.py::TestSphericalDifferential::test_differential_init_errors[True]",
"astropy/coordinates/tests/test_representation_arithmetic.py::TestUnitSphericalDifferential::test_differential_init_errors[True]",
"astropy/coordinates/tests/test_representation_arithmetic.py::TestArithmeticWithDifferentials::test_operation_cartesian[pos-args1]",
"astropy/coordinates/tests/test_representation_arithmetic.py::TestUnitVectorsAndScales::test_spherical",
"astropy/coordinates/tests/test_representation_arithmetic.py::TestCylindricalDifferential::test_name",
"astropy/coordinates/tests/test_representation_arithmetic.py::TestSphericalDifferential::test_differential_arithmetic[False]",
"astropy/coordinates/tests/test_representation_arithmetic.py::TestUnitVectorsAndScales::test_physical_spherical",
"astropy/coordinates/tests/test_representation_arithmetic.py::TestArithmeticWithDifferentials::test_operation_cartesian_differential[PhysicsSphericalRepresentation-pos-args1]",
"astropy/coordinates/tests/test_representation_arithmetic.py::TestArithmeticWithDifferentials::test_operation_spherical_with_rv_or_pm[RadialDifferential-pos-args1]",
"astropy/coordinates/tests/test_representation_arithmetic.py::TestArithmeticWithDifferentials::test_operation_cartesian_differential[CylindricalRepresentation-pos-args1]",
"astropy/coordinates/tests/test_representation_arithmetic.py::TestDifferentialConversion::test_represent_as_own_class[SphericalCosLatDifferential]",
"astropy/coordinates/tests/test_representation_arithmetic.py::TestArithmeticWithDifferentials::test_operation_unit_spherical[UnitSphericalCosLatDifferential-pos-args1]",
"astropy/coordinates/tests/test_representation_arithmetic.py::TestUnitVectorsAndScales::test_unit_spherical",
"astropy/coordinates/tests/test_representation_arithmetic.py::test_arithmetic_with_differentials_fail[rep0-dif0]",
"astropy/coordinates/tests/test_representation_arithmetic.py::TestCartesianDifferential::test_name",
"astropy/coordinates/tests/test_representation_arithmetic.py::TestArithmeticWithDifferentials::test_operation_other[SphericalDifferential-pos-args1]",
"astropy/coordinates/tests/test_representation_arithmetic.py::TestSphericalDifferential::test_simple_differentials[True]",
"astropy/coordinates/tests/test_representation_arithmetic.py::TestArithmeticWithDifferentials::test_operation_radial[pos-args1]",
"astropy/coordinates/tests/test_representation_arithmetic.py::TestCartesianDifferential::test_init_failures",
"astropy/coordinates/tests/test_representation_arithmetic.py::TestCylindricalDifferential::test_differential_init_errors"
] |
[
"astropy/coordinates/tests/test_representation_arithmetic.py::TestArithmeticWithDifferentials::test_operation_radial[truediv-args3]",
"astropy/coordinates/tests/test_representation_arithmetic.py::TestArithmeticWithDifferentials::test_operation_spherical_with_rv_or_pm[UnitSphericalCosLatDifferential-neg-args0]",
"astropy/coordinates/tests/test_representation_arithmetic.py::TestArithmeticWithDifferentials::test_operation_cartesian_differential[PhysicsSphericalRepresentation-mul-args2]",
"astropy/coordinates/tests/test_representation_arithmetic.py::TestArithmeticWithDifferentials::test_operation_spherical_with_rv_or_pm[RadialDifferential-neg-args0]",
"astropy/coordinates/tests/test_representation_arithmetic.py::TestArithmeticWithDifferentials::test_operation_unit_spherical[UnitSphericalDifferential-neg-args0]",
"astropy/coordinates/tests/test_representation_arithmetic.py::TestArithmeticWithDifferentials::test_operation_other[PhysicsSphericalDifferential-truediv-args3]",
"astropy/coordinates/tests/test_representation_arithmetic.py::TestArithmeticWithDifferentials::test_operation_unit_spherical[UnitSphericalDifferential-mul-args2]",
"astropy/coordinates/tests/test_representation_arithmetic.py::TestArithmeticWithDifferentials::test_operation_other[SphericalDifferential-truediv-args3]",
"astropy/coordinates/tests/test_representation_arithmetic.py::TestArithmeticWithDifferentials::test_operation_spherical_with_rv_or_pm[RadialDifferential-mul-args2]",
"astropy/coordinates/tests/test_representation_arithmetic.py::TestArithmeticWithDifferentials::test_operation_other[SphericalCosLatDifferential-neg-args0]",
"astropy/coordinates/tests/test_representation_arithmetic.py::TestArithmeticWithDifferentials::test_operation_cartesian_differential[SphericalRepresentation-mul-args2]",
"astropy/coordinates/tests/test_representation_arithmetic.py::TestArithmeticWithDifferentials::test_operation_cartesian_differential[CylindricalRepresentation-neg-args0]",
"astropy/coordinates/tests/test_representation_arithmetic.py::TestArithmeticWithDifferentials::test_operation_other[SphericalDifferential-neg-args0]",
"astropy/coordinates/tests/test_representation_arithmetic.py::TestArithmeticWithDifferentials::test_operation_spherical_with_rv_or_pm[UnitSphericalCosLatDifferential-mul-args2]",
"astropy/coordinates/tests/test_representation_arithmetic.py::TestArithmeticWithDifferentials::test_operation_spherical_with_rv_or_pm[RadialDifferential-truediv-args3]",
"astropy/coordinates/tests/test_representation_arithmetic.py::TestArithmeticWithDifferentials::test_operation_other[PhysicsSphericalDifferential-mul-args2]",
"astropy/coordinates/tests/test_representation_arithmetic.py::TestArithmeticWithDifferentials::test_operation_cartesian[truediv-args3]",
"astropy/coordinates/tests/test_representation_arithmetic.py::test_operation_unitspherical_with_rv_fails[neg-args0]",
"astropy/coordinates/tests/test_representation_arithmetic.py::TestArithmeticWithDifferentials::test_operation_spherical_with_rv_or_pm[UnitSphericalDifferential-neg-args0]",
"astropy/coordinates/tests/test_representation_arithmetic.py::TestArithmeticWithDifferentials::test_operation_radial[neg-args0]",
"astropy/coordinates/tests/test_representation_arithmetic.py::TestArithmeticWithDifferentials::test_operation_cartesian_differential[PhysicsSphericalRepresentation-neg-args0]",
"astropy/coordinates/tests/test_representation_arithmetic.py::TestArithmeticWithDifferentials::test_operation_unit_spherical[UnitSphericalCosLatDifferential-mul-args2]",
"astropy/coordinates/tests/test_representation_arithmetic.py::TestArithmeticWithDifferentials::test_operation_other[SphericalCosLatDifferential-truediv-args3]",
"astropy/coordinates/tests/test_representation_arithmetic.py::TestArithmeticWithDifferentials::test_operation_other[CylindricalDifferential-truediv-args3]",
"astropy/coordinates/tests/test_representation_arithmetic.py::TestArithmeticWithDifferentials::test_operation_spherical_with_rv_or_pm[UnitSphericalCosLatDifferential-truediv-args3]",
"astropy/coordinates/tests/test_representation_arithmetic.py::TestArithmeticWithDifferentials::test_operation_cartesian_differential[CylindricalRepresentation-mul-args2]",
"astropy/coordinates/tests/test_representation_arithmetic.py::TestArithmeticWithDifferentials::test_operation_cartesian_differential[CylindricalRepresentation-truediv-args3]",
"astropy/coordinates/tests/test_representation_arithmetic.py::TestArithmeticWithDifferentials::test_operation_cartesian_differential[SphericalRepresentation-neg-args0]",
"astropy/coordinates/tests/test_representation_arithmetic.py::TestArithmeticWithDifferentials::test_operation_spherical_with_rv_or_pm[UnitSphericalDifferential-truediv-args3]",
"astropy/coordinates/tests/test_representation_arithmetic.py::TestArithmeticWithDifferentials::test_operation_other[SphericalDifferential-mul-args2]",
"astropy/coordinates/tests/test_representation_arithmetic.py::TestArithmeticWithDifferentials::test_operation_other[CylindricalDifferential-neg-args0]",
"astropy/coordinates/tests/test_representation_arithmetic.py::TestArithmeticWithDifferentials::test_operation_cartesian[neg-args0]",
"astropy/coordinates/tests/test_representation_arithmetic.py::TestArithmeticWithDifferentials::test_operation_spherical_with_rv_or_pm[UnitSphericalDifferential-mul-args2]",
"astropy/coordinates/tests/test_representation_arithmetic.py::TestArithmeticWithDifferentials::test_operation_cartesian_differential[SphericalRepresentation-truediv-args3]",
"astropy/coordinates/tests/test_representation_arithmetic.py::TestArithmeticWithDifferentials::test_operation_radial[mul-args2]",
"astropy/coordinates/tests/test_representation_arithmetic.py::TestArithmeticWithDifferentials::test_operation_cartesian_differential[PhysicsSphericalRepresentation-truediv-args3]",
"astropy/coordinates/tests/test_representation_arithmetic.py::TestArithmeticWithDifferentials::test_operation_unit_spherical[UnitSphericalDifferential-truediv-args3]",
"astropy/coordinates/tests/test_representation_arithmetic.py::TestArithmeticWithDifferentials::test_operation_unit_spherical[UnitSphericalCosLatDifferential-neg-args0]",
"astropy/coordinates/tests/test_representation_arithmetic.py::TestArithmeticWithDifferentials::test_operation_unit_spherical[UnitSphericalCosLatDifferential-truediv-args3]",
"astropy/coordinates/tests/test_representation_arithmetic.py::TestArithmeticWithDifferentials::test_operation_cartesian[mul-args2]",
"astropy/coordinates/tests/test_representation_arithmetic.py::TestArithmeticWithDifferentials::test_operation_other[SphericalCosLatDifferential-mul-args2]",
"astropy/coordinates/tests/test_representation_arithmetic.py::test_operation_unitspherical_with_rv_fails[mul-args1]",
"astropy/coordinates/tests/test_representation_arithmetic.py::TestArithmeticWithDifferentials::test_operation_other[PhysicsSphericalDifferential-neg-args0]",
"astropy/coordinates/tests/test_representation_arithmetic.py::TestArithmeticWithDifferentials::test_operation_other[CylindricalDifferential-mul-args2]"
] |
[
{
"path": "docs/changes/coordinates/#####.feature.rst",
"old_path": "/dev/null",
"new_path": "b/docs/changes/coordinates/#####.feature.rst",
"metadata": "diff --git a/docs/changes/coordinates/#####.feature.rst b/docs/changes/coordinates/#####.feature.rst\nnew file mode 100644\nindex 0000000000..51927b0b0a\n--- /dev/null\n+++ b/docs/changes/coordinates/#####.feature.rst\n@@ -0,0 +1,7 @@\n+Allow negation, multiplication and division also of representations that\n+include a differential (e.g., ``SphericalRepresentation`` with a\n+``SphericalCosLatDifferential``). For all operations, the outcome is\n+equivalent to transforming the representation and differential to cartesian,\n+then operating on those, and transforming back to the original representation\n+(except for ``UnitSphericalRepresentation``, which will return a\n+``SphericalRepresentation`` if there is a scale change).\n"
}
] |
{
"header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:",
"data": [
{
"type": "field",
"name": "pos"
}
]
}
|
diff --git a/docs/changes/coordinates/#####.feature.rst b/docs/changes/coordinates/#####.feature.rst
new file mode 100644
index 0000000000..51927b0b0a
--- /dev/null
+++ b/docs/changes/coordinates/#####.feature.rst
@@ -0,0 +1,7 @@
+Allow negation, multiplication and division also of representations that
+include a differential (e.g., ``SphericalRepresentation`` with a
+``SphericalCosLatDifferential``). For all operations, the outcome is
+equivalent to transforming the representation and differential to cartesian,
+then operating on those, and transforming back to the original representation
+(except for ``UnitSphericalRepresentation``, which will return a
+``SphericalRepresentation`` if there is a scale change).
If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:
[{'type': 'field', 'name': 'pos'}]
|
astropy/astropy
|
astropy__astropy-11843
|
https://github.com/astropy/astropy/pull/11843
|
diff --git a/astropy/io/fits/connect.py b/astropy/io/fits/connect.py
index ddeadde4f1f2..c792aff28205 100644
--- a/astropy/io/fits/connect.py
+++ b/astropy/io/fits/connect.py
@@ -112,7 +112,7 @@ def _decode_mixins(tbl):
def read_table_fits(input, hdu=None, astropy_native=False, memmap=False,
- character_as_bytes=True):
+ character_as_bytes=True, unit_parse_strict='warn'):
"""
Read a Table object from an FITS file
@@ -152,6 +152,12 @@ def read_table_fits(input, hdu=None, astropy_native=False, memmap=False,
``U``) internally, you should set this to `False`, but note that this
will use more memory. If set to `False`, string columns will not be
memory-mapped even if ``memmap`` is `True`.
+ unit_parse_strict: str, optional
+ Behaviour when encountering invalid column units in the FITS header.
+ Default is "silent", which will create a
+ :class:`~astropy.units.core.UnrecognizedUnit`.
+ Values are the ones allowed by the ``parse_strict`` argument of
+ :class:`~astropy.units.core.Unit`.
"""
if isinstance(input, HDUList):
@@ -211,8 +217,11 @@ def read_table_fits(input, hdu=None, astropy_native=False, memmap=False,
memmap=memmap)
try:
- return read_table_fits(hdulist, hdu=hdu,
- astropy_native=astropy_native)
+ return read_table_fits(
+ hdulist, hdu=hdu,
+ astropy_native=astropy_native,
+ unit_parse_strict=unit_parse_strict,
+ )
finally:
hdulist.close()
@@ -249,7 +258,7 @@ def read_table_fits(input, hdu=None, astropy_native=False, memmap=False,
# Copy over units
if col.unit is not None:
- column.unit = u.Unit(col.unit, format='fits', parse_strict='silent')
+ column.unit = u.Unit(col.unit, format='fits', parse_strict=unit_parse_strict)
# Copy over display format
if col.disp is not None:
diff --git a/docs/changes/io.fits/11843.feature.rst b/docs/changes/io.fits/11843.feature.rst
new file mode 100644
index 000000000000..5f84c63ac195
--- /dev/null
+++ b/docs/changes/io.fits/11843.feature.rst
@@ -0,0 +1,4 @@
+Add option ``unit_parse_strict`` to `~astropy.io.fits.connect.read_table_fits`
+to enable warnings or errors about invalid FITS units when using `~astropy.table.Table.read`.
+The default for this new option is ``"warn"``, which means warnings are now raised for
+columns with invalid units.
diff --git a/docs/timeseries/index.rst b/docs/timeseries/index.rst
index e9c8c5a769bb..34fa7a5674fe 100644
--- a/docs/timeseries/index.rst
+++ b/docs/timeseries/index.rst
@@ -49,7 +49,7 @@ source::
We can then use the |TimeSeries| class to read in this file::
>>> from astropy.timeseries import TimeSeries
- >>> ts = TimeSeries.read(filename, format='kepler.fits') # doctest: +REMOTE_DATA
+ >>> ts = TimeSeries.read(filename, format='kepler.fits') # doctest: +REMOTE_DATA +IGNORE_WARNINGS
Time series are specialized kinds of |Table| objects::
|
diff --git a/astropy/io/fits/tests/test_connect.py b/astropy/io/fits/tests/test_connect.py
index b2396bc4f398..0090c7abbb6a 100644
--- a/astropy/io/fits/tests/test_connect.py
+++ b/astropy/io/fits/tests/test_connect.py
@@ -234,7 +234,8 @@ def test_read_with_nonstandard_units(self):
hdu.columns[0].unit = 'RADIANS'
hdu.columns[1].unit = 'spam'
hdu.columns[2].unit = 'millieggs'
- t = Table.read(hdu)
+ with pytest.warns(u.UnitsWarning, match="did not parse as fits unit"):
+ t = Table.read(hdu)
assert equal_data(t, self.data)
@pytest.mark.parametrize('table_type', (Table, QTable))
@@ -657,7 +658,8 @@ def test_unit_warnings_read_write(tmpdir):
t1.write(filename, overwrite=True)
assert len(w) == 1
- Table.read(filename, hdu=1)
+ with pytest.warns(u.UnitsWarning, match="'not-a-unit' did not parse as fits unit") as w:
+ Table.read(filename, hdu=1)
def test_convert_comment_convention(tmpdir):
diff --git a/astropy/io/fits/tests/test_table.py b/astropy/io/fits/tests/test_table.py
index b1a055bc4fa5..3150258a28aa 100644
--- a/astropy/io/fits/tests/test_table.py
+++ b/astropy/io/fits/tests/test_table.py
@@ -18,7 +18,7 @@
from astropy.io import fits
from astropy.table import Table
-from astropy.units import UnitsWarning
+from astropy.units import UnitsWarning, Unit, UnrecognizedUnit
from astropy.utils.exceptions import AstropyDeprecationWarning, AstropyUserWarning
from astropy.io.fits.column import Delayed, NUMPY2FITS
@@ -3515,3 +3515,31 @@ def test_invalid_file(tmp_path):
hdu.writeto(testfile, output_verify='ignore')
with fits.open(testfile) as hdul:
assert hdul[1].data is not None
+
+
+def test_unit_parse_strict(tmp_path):
+ path = tmp_path / 'invalid_unit.fits'
+
+ # this is a unit parseable by the generic format but invalid for FITS
+ invalid_unit = '1 / (MeV sr s)'
+ unit = Unit(invalid_unit)
+
+ t = Table({'a': [1, 2, 3]})
+ t.write(path)
+ with fits.open(path, mode='update') as hdul:
+ hdul[1].header['TUNIT1'] = invalid_unit
+
+ # default is "warn"
+ with pytest.warns(UnitsWarning):
+ t = Table.read(path)
+
+ assert isinstance(t['a'].unit, UnrecognizedUnit)
+
+ t = Table.read(path, unit_parse_strict='silent')
+ assert isinstance(t['a'].unit, UnrecognizedUnit)
+
+ with pytest.raises(ValueError):
+ Table.read(path, unit_parse_strict='raise')
+
+ with pytest.warns(UnitsWarning):
+ Table.read(path, unit_parse_strict='warn')
diff --git a/astropy/table/tests/test_showtable.py b/astropy/table/tests/test_showtable.py
index 928062dd983d..83fb579ebfb2 100644
--- a/astropy/table/tests/test_showtable.py
+++ b/astropy/table/tests/test_showtable.py
@@ -1,5 +1,6 @@
import os
import re
+import pytest
from astropy.table.scripts import showtable
@@ -53,8 +54,13 @@ def test_fits(capsys):
def test_fits_hdu(capsys):
- showtable.main([os.path.join(FITS_ROOT, 'data/zerowidth.fits'),
- '--hdu', 'AIPS OF'])
+ from astropy.units import UnitsWarning
+ with pytest.warns(UnitsWarning):
+ showtable.main([
+ os.path.join(FITS_ROOT, 'data/zerowidth.fits'),
+ '--hdu', 'AIPS OF',
+ ])
+
out, err = capsys.readouterr()
assert out.startswith(
' TIME SOURCE ID ANTENNA NO. SUBARRAY FREQ ID ANT FLAG STATUS 1\n'
diff --git a/astropy/timeseries/io/tests/test_kepler.py b/astropy/timeseries/io/tests/test_kepler.py
index 214a5046da22..b5dd7c945744 100644
--- a/astropy/timeseries/io/tests/test_kepler.py
+++ b/astropy/timeseries/io/tests/test_kepler.py
@@ -68,8 +68,13 @@ def test_raise_timesys_tess(mock_file):
@pytest.mark.remote_data(source='astropy')
def test_kepler_astropy():
+ from astropy.units import UnitsWarning
+
filename = get_pkg_data_filename('timeseries/kplr010666592-2009131110544_slc.fits')
- timeseries = kepler_fits_reader(filename)
+
+ with pytest.warns(UnitsWarning):
+ timeseries = kepler_fits_reader(filename)
+
assert timeseries["time"].format == 'isot'
assert timeseries["time"].scale == 'tdb'
assert timeseries["sap_flux"].unit.to_string() == 'electron / s'
diff --git a/astropy/timeseries/tests/test_sampled.py b/astropy/timeseries/tests/test_sampled.py
index 68f8715256e5..bcc06d929ee6 100644
--- a/astropy/timeseries/tests/test_sampled.py
+++ b/astropy/timeseries/tests/test_sampled.py
@@ -323,8 +323,13 @@ def test_read():
@pytest.mark.remote_data(source='astropy')
def test_kepler_astropy():
+ from astropy.units import UnitsWarning
+
filename = get_pkg_data_filename('timeseries/kplr010666592-2009131110544_slc.fits')
- timeseries = TimeSeries.read(filename, format='kepler.fits')
+
+ with pytest.warns(UnitsWarning):
+ timeseries = TimeSeries.read(filename, format='kepler.fits')
+
assert timeseries["time"].format == 'isot'
assert timeseries["time"].scale == 'tdb'
assert timeseries["sap_flux"].unit.to_string() == 'electron / s'
|
[
{
"path": "docs/changes/io.fits/11843.feature.rst",
"old_path": "/dev/null",
"new_path": "b/docs/changes/io.fits/11843.feature.rst",
"metadata": "diff --git a/docs/changes/io.fits/11843.feature.rst b/docs/changes/io.fits/11843.feature.rst\nnew file mode 100644\nindex 000000000000..5f84c63ac195\n--- /dev/null\n+++ b/docs/changes/io.fits/11843.feature.rst\n@@ -0,0 +1,4 @@\n+Add option ``unit_parse_strict`` to `~astropy.io.fits.connect.read_table_fits`\n+to enable warnings or errors about invalid FITS units when using `~astropy.table.Table.read`.\n+The default for this new option is ``\"warn\"``, which means warnings are now raised for\n+columns with invalid units.\n",
"update": null
},
{
"path": "docs/timeseries/index.rst",
"old_path": "a/docs/timeseries/index.rst",
"new_path": "b/docs/timeseries/index.rst",
"metadata": "diff --git a/docs/timeseries/index.rst b/docs/timeseries/index.rst\nindex e9c8c5a769bb..34fa7a5674fe 100644\n--- a/docs/timeseries/index.rst\n+++ b/docs/timeseries/index.rst\n@@ -49,7 +49,7 @@ source::\n We can then use the |TimeSeries| class to read in this file::\n \n >>> from astropy.timeseries import TimeSeries\n- >>> ts = TimeSeries.read(filename, format='kepler.fits') # doctest: +REMOTE_DATA\n+ >>> ts = TimeSeries.read(filename, format='kepler.fits') # doctest: +REMOTE_DATA +IGNORE_WARNINGS\n \n Time series are specialized kinds of |Table| objects::\n \n",
"update": null
}
] |
5.1
|
eb6dd707c06115b2ceb91c69ff50e33d20586aac
|
[
"astropy/io/fits/tests/test_table.py::TestTableFunctions::test_constructor_name_arg",
"astropy/timeseries/tests/test_sampled.py::test_initialization_with_table",
"astropy/io/fits/tests/test_table.py::test_a3dtable",
"astropy/io/fits/tests/test_connect.py::TestMultipleHDU::test_read_from_hdulist_with_hdu_missing[]",
"astropy/io/fits/tests/test_connect.py::test_fortran_to_python_format[L8-{:>8}]",
"astropy/io/fits/tests/test_connect.py::TestSingleTable::test_mask_nans_on_read",
"astropy/io/fits/tests/test_connect.py::test_fits_mixins_per_column[Table-name_col6]",
"astropy/timeseries/tests/test_sampled.py::test_initialization_with_time_in_data",
"astropy/io/fits/tests/test_table.py::TestTableFunctions::test_unicode_colname",
"astropy/timeseries/tests/test_sampled.py::test_initialization_n_samples",
"astropy/io/fits/tests/test_connect.py::TestMultipleHDU::test_read_with_hdu_missing[second]",
"astropy/timeseries/tests/test_sampled.py::test_empty_initialization_invalid",
"astropy/io/fits/tests/test_table.py::TestVLATables::test_tolist",
"astropy/io/fits/tests/test_connect.py::TestSingleTable::test_write_drop_nonstandard_units[Table]",
"astropy/io/fits/tests/test_connect.py::TestMultipleHDU::test_read_with_hdu_3[3]",
"astropy/io/fits/tests/test_connect.py::test_fits_mixins_per_column[Table-name_col0]",
"astropy/timeseries/tests/test_sampled.py::test_read_time_wrong",
"astropy/io/fits/tests/test_connect.py::test_logical_python_to_tdisp",
"astropy/io/fits/tests/test_table.py::TestColumnFunctions::test_p_column_deepcopy",
"astropy/io/fits/tests/test_table.py::test_empty_table",
"astropy/table/tests/test_showtable.py::test_hide_unit",
"astropy/io/fits/tests/test_connect.py::test_fits_mixins_per_column[QTable-name_col10]",
"astropy/io/fits/tests/test_table.py::TestTableFunctions::test_removing_a_column_inplace",
"astropy/io/fits/tests/test_connect.py::TestSingleTable::test_with_custom_units_qtable",
"astropy/io/fits/tests/test_table.py::TestColumnFunctions::test_coldefs_init_from_array",
"astropy/io/fits/tests/test_connect.py::test_fits_mixins_per_column[QTable-name_col13]",
"astropy/io/fits/tests/test_table.py::TestColumnFunctions::test_x_column_deepcopy",
"astropy/io/fits/tests/test_table.py::TestColumnFunctions::test_column_verify_formats[keys4]",
"astropy/io/fits/tests/test_connect.py::TestSingleTable::test_memmap",
"astropy/io/fits/tests/test_table.py::test_table_to_hdu",
"astropy/io/fits/tests/test_connect.py::test_python_to_tdisp[{:>4}-A4]",
"astropy/io/fits/tests/test_table.py::TestTableFunctions::test_assign_multiple_rows_to_table",
"astropy/io/fits/tests/test_table.py::TestTableFunctions::test_adding_a_column_inplace",
"astropy/io/fits/tests/test_connect.py::TestMultipleHDU::test_read_from_hdulist_with_hdu_missing[3]",
"astropy/io/fits/tests/test_table.py::TestTableFunctions::test_bin_table_hdu_constructor",
"astropy/io/fits/tests/test_connect.py::TestMultipleHDU::test_read_with_hdu_warning[2]",
"astropy/timeseries/tests/test_sampled.py::test_periodogram[LombScargle]",
"astropy/io/fits/tests/test_connect.py::test_fortran_to_python_format[I6.5-{:6d}]",
"astropy/io/fits/tests/test_connect.py::TestSingleTable::test_simple_pathlib",
"astropy/io/fits/tests/test_connect.py::TestMultipleHDU::test_read_from_hdulist_in_last_hdu[1]",
"astropy/io/fits/tests/test_connect.py::test_fits_mixins_per_column[Table-name_col2]",
"astropy/timeseries/tests/test_sampled.py::test_read",
"astropy/io/fits/tests/test_connect.py::TestSingleTable::test_mask_null_on_read",
"astropy/io/fits/tests/test_connect.py::test_python_to_tdisp[%5.3g-G5.3]",
"astropy/io/fits/tests/test_connect.py::test_fits_mixins_per_column[Table-name_col13]",
"astropy/timeseries/tests/test_sampled.py::test_initialization_invalid_time_delta",
"astropy/timeseries/tests/test_sampled.py::test_fold_invalid_options",
"astropy/io/fits/tests/test_connect.py::TestMultipleHDU::test_read_from_hdulist_with_hdu_1[1]",
"astropy/io/fits/tests/test_connect.py::TestSingleTable::test_oned_single_element",
"astropy/io/fits/tests/test_connect.py::TestMultipleHDU::test_read_in_last_hdu[0]",
"astropy/timeseries/io/tests/test_kepler.py::test_raise_extversion_kepler",
"astropy/io/fits/tests/test_connect.py::TestMultipleHDU::test_read_with_hdu_2[2]",
"astropy/io/fits/tests/test_connect.py::TestMultipleHDU::test_read_from_hdulist_with_hdu_warning[0]",
"astropy/io/fits/tests/test_connect.py::TestMultipleHDU::test_read_in_last_hdu[third]",
"astropy/io/fits/tests/test_connect.py::test_fits_mixins_per_column[QTable-name_col9]",
"astropy/io/fits/tests/test_connect.py::TestMultipleHDU::test_read_from_hdulist_with_hdu_2[second]",
"astropy/io/fits/tests/test_table.py::TestColumnFunctions::test_column_verify_keywords",
"astropy/io/fits/tests/test_connect.py::TestSingleTable::test_masked_nan[True]",
"astropy/io/fits/tests/test_connect.py::TestSingleTable::test_masked",
"astropy/io/fits/tests/test_connect.py::test_fits_mixins_per_column[QTable-name_col8]",
"astropy/io/fits/tests/test_connect.py::TestMultipleHDU::test_read_from_hdulist_with_hdu_3[third]",
"astropy/table/tests/test_showtable.py::test_csv",
"astropy/timeseries/tests/test_sampled.py::test_initialization_invalid_both_time_and_time_delta",
"astropy/io/fits/tests/test_connect.py::test_fits_mixins_per_column[QTable-name_col5]",
"astropy/io/fits/tests/test_connect.py::test_fits_mixins_per_column[Table-name_col1]",
"astropy/timeseries/io/tests/test_kepler.py::test_raise_timesys_kepler",
"astropy/timeseries/tests/test_sampled.py::test_required_columns",
"astropy/io/fits/tests/test_table.py::TestColumnFunctions::test_column_verify_formats[keys0]",
"astropy/io/fits/tests/test_table.py::TestTableFunctions::test_add_data_by_rows",
"astropy/io/fits/tests/test_table.py::TestTableFunctions::test_table_from_bool_fields2",
"astropy/io/fits/tests/test_connect.py::TestSingleTable::test_with_format[QTable]",
"astropy/io/fits/tests/test_connect.py::TestMultipleHDU::test_read_from_hdulist_with_single_table[None]",
"astropy/io/fits/tests/test_connect.py::test_parse_tdisp_format[EN10.5-format_return0]",
"astropy/io/fits/tests/test_connect.py::TestSingleTable::test_character_as_bytes[True]",
"astropy/io/fits/tests/test_connect.py::test_fortran_to_python_format[Z5.10-{:5x}]",
"astropy/io/fits/tests/test_connect.py::test_fits_mixins_per_column[QTable-name_col6]",
"astropy/io/fits/tests/test_table.py::TestVLATables::test_extend_variable_length_array",
"astropy/io/fits/tests/test_connect.py::test_fits_mixins_per_column[QTable-name_col14]",
"astropy/io/fits/tests/test_table.py::test_regression_scalar_indexing",
"astropy/timeseries/tests/test_sampled.py::test_periodogram[BoxLeastSquares]",
"astropy/io/fits/tests/test_connect.py::TestMultipleHDU::test_read_from_hdulist_with_hdu_warning[third]",
"astropy/io/fits/tests/test_connect.py::TestSingleTable::test_write_append",
"astropy/table/tests/test_showtable.py::test_max_lines",
"astropy/io/fits/tests/test_connect.py::TestMultipleHDU::test_read_with_hdu_missing[2]",
"astropy/timeseries/io/tests/test_kepler.py::test_raise_timesys_tess",
"astropy/io/fits/tests/test_table.py::TestTableFunctions::test_adding_a_column",
"astropy/io/fits/tests/test_connect.py::TestMultipleHDU::test_read_with_hdu_missing[]",
"astropy/io/fits/tests/test_connect.py::test_fits_mixins_as_one[QTable]",
"astropy/io/fits/tests/test_connect.py::test_fits_mixins_per_column[Table-name_col16]",
"astropy/io/fits/tests/test_table.py::TestTableFunctions::test_attribute_field_shadowing",
"astropy/io/fits/tests/test_table.py::TestColumnFunctions::test_column_verify_formats[keys2]",
"astropy/io/fits/tests/test_connect.py::TestMultipleHDU::test_read_with_hdu_2[second]",
"astropy/io/fits/tests/test_connect.py::test_parse_tdisp_format[B5.10-format_return2]",
"astropy/io/fits/tests/test_connect.py::test_fits_mixins_per_column[Table-name_col5]",
"astropy/io/fits/tests/test_connect.py::test_parse_tdisp_format[F6.2-format_return1]",
"astropy/io/fits/tests/test_connect.py::test_round_trip_masked_table_serialize_mask[names]",
"astropy/io/fits/tests/test_connect.py::TestMultipleHDU::test_read_from_hdulist_with_single_table[first]",
"astropy/io/fits/tests/test_table.py::TestColumnFunctions::test_column_verify_formats[keys1]",
"astropy/table/tests/test_showtable.py::test_votable",
"astropy/io/fits/tests/test_connect.py::TestMultipleHDU::test_read_with_hdu_1[1]",
"astropy/io/fits/tests/test_connect.py::test_fits_mixins_per_column[QTable-name_col7]",
"astropy/io/fits/tests/test_connect.py::TestSingleTable::test_with_format[Table]",
"astropy/io/fits/tests/test_connect.py::test_scale_error",
"astropy/table/tests/test_showtable.py::test_missing_file",
"astropy/timeseries/tests/test_sampled.py::test_empty_initialization",
"astropy/io/fits/tests/test_connect.py::TestSingleTable::test_simple_meta_conflicting",
"astropy/io/fits/tests/test_connect.py::TestMultipleHDU::test_read_with_hdu_warning[third]",
"astropy/io/fits/tests/test_connect.py::test_fits_mixins_per_column[QTable-name_col16]",
"astropy/timeseries/io/tests/test_kepler.py::test_raise_extversion_tess",
"astropy/io/fits/tests/test_connect.py::TestMultipleHDU::test_read_from_hdulist_with_hdu_3[3]",
"astropy/timeseries/tests/test_sampled.py::test_initialize_only_time",
"astropy/io/fits/tests/test_connect.py::test_fits_mixins_per_column[Table-name_col7]",
"astropy/io/fits/tests/test_connect.py::test_convert_comment_convention",
"astropy/io/fits/tests/test_table.py::TestTableFunctions::test_constructor_copies_header",
"astropy/table/tests/test_showtable.py::test_ascii_format",
"astropy/io/fits/tests/test_connect.py::test_python_to_tdisp[3d-I3]",
"astropy/io/fits/tests/test_connect.py::TestSingleTable::test_read_with_unit_aliases[Table]",
"astropy/io/fits/tests/test_table.py::test_invalid_file",
"astropy/table/tests/test_showtable.py::test_ascii_delimiter",
"astropy/io/fits/tests/test_connect.py::TestMultipleHDU::test_read_from_hdulist_with_single_table[1]",
"astropy/io/fits/tests/test_connect.py::test_fits_mixins_per_column[Table-name_col14]",
"astropy/timeseries/io/tests/test_kepler.py::test_raise_telescop_wrong",
"astropy/io/fits/tests/test_table.py::TestTableFunctions::test_zero_length_table",
"astropy/io/fits/tests/test_connect.py::test_fits_mixins_per_column[QTable-name_col15]",
"astropy/io/fits/tests/test_table.py::TestColumnFunctions::test_column_attribute_change_after_removal",
"astropy/table/tests/test_showtable.py::test_info",
"astropy/timeseries/tests/test_sampled.py::test_initialization_invalid_time_and_time_start",
"astropy/io/fits/tests/test_connect.py::TestSingleTable::test_read_from_fileobj",
"astropy/io/fits/tests/test_connect.py::TestMultipleHDU::test_read_from_hdulist_with_hdu_1[first]",
"astropy/io/fits/tests/test_connect.py::test_unicode_column",
"astropy/io/fits/tests/test_table.py::TestColumnFunctions::test_new_coldefs_with_invalid_seqence",
"astropy/io/fits/tests/test_connect.py::TestSingleTable::test_character_as_bytes[False]",
"astropy/io/fits/tests/test_table.py::TestTableFunctions::test_column_array_type_mismatch",
"astropy/io/fits/tests/test_connect.py::test_fits_mixins_per_column[QTable-name_col2]",
"astropy/io/fits/tests/test_connect.py::test_round_trip_masked_table_serialize_mask[set_cols]",
"astropy/io/fits/tests/test_connect.py::test_parse_tdisp_format[E10.5E3-format_return3]",
"astropy/io/fits/tests/test_connect.py::test_fits_mixins_per_column[QTable-name_col12]",
"astropy/io/fits/tests/test_connect.py::test_fits_mixins_per_column[QTable-name_col3]",
"astropy/table/tests/test_showtable.py::test_stats",
"astropy/io/fits/tests/test_connect.py::TestSingleTable::test_write_overwrite",
"astropy/io/fits/tests/test_connect.py::test_fits_mixins_per_column[Table-name_col4]",
"astropy/io/fits/tests/test_connect.py::test_fits_mixins_per_column[QTable-name_col11]",
"astropy/io/fits/tests/test_connect.py::test_fits_mixins_per_column[QTable-name_col4]",
"astropy/io/fits/tests/test_connect.py::TestMultipleHDU::test_read_from_hdulist",
"astropy/io/fits/tests/test_connect.py::test_bool_column",
"astropy/timeseries/tests/test_sampled.py::test_read_time_missing",
"astropy/io/fits/tests/test_connect.py::test_python_to_tdisp[{:7.4f}-F7.4]",
"astropy/io/fits/tests/test_connect.py::TestMultipleHDU::test_read_from_single_hdu[None]",
"astropy/io/fits/tests/test_connect.py::TestSingleTable::test_masked_serialize_data_mask",
"astropy/io/fits/tests/test_connect.py::test_python_to_tdisp[7.3f-F7.3]",
"astropy/io/fits/tests/test_connect.py::test_fits_mixins_per_column[QTable-name_col0]",
"astropy/io/fits/tests/test_connect.py::TestSingleTable::test_simple_noextension",
"astropy/io/fits/tests/test_connect.py::TestSingleTable::test_with_units[QTable]",
"astropy/io/fits/tests/test_connect.py::TestMultipleHDU::test_read_with_hdu_3[third]",
"astropy/io/fits/tests/test_connect.py::TestMultipleHDU::test_read_from_hdulist_with_hdu_missing[2]",
"astropy/io/fits/tests/test_connect.py::test_python_to_tdisp[%10s-A10]",
"astropy/io/fits/tests/test_table.py::TestTableFunctions::test_bin_table_with_logical_array",
"astropy/io/fits/tests/test_connect.py::TestMultipleHDU::test_read_in_last_hdu[1]",
"astropy/io/fits/tests/test_connect.py::TestMultipleHDU::test_read_from_single_hdu[first]",
"astropy/io/fits/tests/test_table.py::TestColumnFunctions::test_column_verify_start",
"astropy/io/fits/tests/test_connect.py::TestSingleTable::test_simple_meta",
"astropy/timeseries/tests/test_sampled.py::test_initialize_only_data",
"astropy/io/fits/tests/test_connect.py::TestMultipleHDU::test_read_from_hdulist_in_last_hdu[0]",
"astropy/io/fits/tests/test_connect.py::TestMultipleHDU::test_read_from_hdulist_with_hdu_2[2]",
"astropy/io/fits/tests/test_connect.py::TestMultipleHDU::test_read_from_hdulist_with_hdu_warning[2]",
"astropy/io/fits/tests/test_connect.py::test_fits_mixins_per_column[QTable-name_col1]",
"astropy/io/fits/tests/test_connect.py::TestMultipleHDU::test_read_from_single_hdu[1]",
"astropy/io/fits/tests/test_connect.py::test_parse_tdisp_format[A21-format_return4]",
"astropy/io/fits/tests/test_connect.py::TestSingleTable::test_read_with_unit_aliases[QTable]",
"astropy/io/fits/tests/test_connect.py::TestMultipleHDU::test_read_from_hdulist_with_hdu_0",
"astropy/io/fits/tests/test_connect.py::TestSingleTable::test_with_units[Table]",
"astropy/io/fits/tests/test_connect.py::TestSingleTable::test_write_drop_nonstandard_units[QTable]",
"astropy/io/fits/tests/test_connect.py::test_python_to_tdisp[%.4f-F13.4]",
"astropy/io/fits/tests/test_connect.py::test_meta_not_modified",
"astropy/io/fits/tests/test_connect.py::test_fits_mixins_per_column[Table-name_col12]",
"astropy/io/fits/tests/test_connect.py::TestMultipleHDU::test_read_with_hdu_0",
"astropy/table/tests/test_showtable.py::test_fits",
"astropy/io/fits/tests/test_connect.py::TestMultipleHDU::test_read",
"astropy/io/fits/tests/test_connect.py::test_python_to_tdisp[{:3d}-I3]",
"astropy/io/fits/tests/test_connect.py::test_info_attributes_with_no_mixins",
"astropy/io/fits/tests/test_connect.py::TestSingleTable::test_simple",
"astropy/io/fits/tests/test_connect.py::test_fits_mixins_qtable_to_table",
"astropy/io/fits/tests/test_table.py::test_regression_5383",
"astropy/io/fits/tests/test_connect.py::TestMultipleHDU::test_read_with_hdu_missing[3]",
"astropy/io/fits/tests/test_connect.py::test_fits_mixins_per_column[Table-name_col3]",
"astropy/io/fits/tests/test_connect.py::TestMultipleHDU::test_read_with_hdu_warning[0]",
"astropy/io/fits/tests/test_connect.py::TestMultipleHDU::test_read_with_hdu_missing[1]",
"astropy/io/fits/tests/test_connect.py::test_fortran_to_python_format[E20.7-{:20.7e}]",
"astropy/io/fits/tests/test_table.py::TestColumnFunctions::test_column_verify_formats[keys3]",
"astropy/io/fits/tests/test_connect.py::test_fortran_to_python_format[G15.4E2-{:15.4g}]",
"astropy/io/fits/tests/test_table.py::TestTableFunctions::test_constructor_ver_arg",
"astropy/io/fits/tests/test_table.py::TestColumnFunctions::test_column_array_type_mismatch",
"astropy/io/fits/tests/test_connect.py::test_round_trip_masked_table_serialize_mask[class]",
"astropy/io/fits/tests/test_connect.py::TestMultipleHDU::test_read_with_hdu_4",
"astropy/io/fits/tests/test_connect.py::TestMultipleHDU::test_read_from_hdulist_in_last_hdu[third]",
"astropy/io/fits/tests/test_connect.py::TestMultipleHDU::test_read_with_hdu_1[first]",
"astropy/io/fits/tests/test_connect.py::test_fits_mixins_as_one[Table]",
"astropy/io/fits/tests/test_connect.py::test_fits_mixins_per_column[Table-name_col15]",
"astropy/io/fits/tests/test_table.py::TestColumnFunctions::test_column_lookup_by_name",
"astropy/timeseries/tests/test_sampled.py::test_fold",
"astropy/io/fits/tests/test_table.py::TestColumnFunctions::test_column_format_interpretation",
"astropy/io/fits/tests/test_connect.py::TestMultipleHDU::test_read_from_hdulist_with_hdu_missing[second]",
"astropy/io/fits/tests/test_connect.py::test_masking_regression_1795",
"astropy/timeseries/tests/test_sampled.py::test_initialization_missing_time_delta",
"astropy/io/fits/tests/test_connect.py::TestSingleTable::test_masked_nan[False]",
"astropy/timeseries/tests/test_sampled.py::test_initialization_with_data",
"astropy/table/tests/test_showtable.py::test_show_dtype",
"astropy/io/fits/tests/test_connect.py::TestMultipleHDU::test_read_from_hdulist_with_hdu_missing[1]",
"astropy/timeseries/tests/test_sampled.py::test_initialization_length_mismatch"
] |
[
"astropy/table/tests/test_showtable.py::test_fits_hdu",
"astropy/io/fits/tests/test_connect.py::TestSingleTable::test_read_with_nonstandard_units",
"astropy/io/fits/tests/test_connect.py::test_unit_warnings_read_write",
"astropy/io/fits/tests/test_table.py::test_unit_parse_strict"
] |
[
{
"path": "docs/changes/io.fits/#####.feature.rst",
"old_path": "/dev/null",
"new_path": "b/docs/changes/io.fits/#####.feature.rst",
"metadata": "diff --git a/docs/changes/io.fits/#####.feature.rst b/docs/changes/io.fits/#####.feature.rst\nnew file mode 100644\nindex 0000000000..5f84c63ac1\n--- /dev/null\n+++ b/docs/changes/io.fits/#####.feature.rst\n@@ -0,0 +1,4 @@\n+Add option ``unit_parse_strict`` to `~astropy.io.fits.connect.read_table_fits`\n+to enable warnings or errors about invalid FITS units when using `~astropy.table.Table.read`.\n+The default for this new option is ``\"warn\"``, which means warnings are now raised for\n+columns with invalid units.\n"
},
{
"path": "docs/timeseries/index.rst",
"old_path": "a/docs/timeseries/index.rst",
"new_path": "b/docs/timeseries/index.rst",
"metadata": "diff --git a/docs/timeseries/index.rst b/docs/timeseries/index.rst\nindex e9c8c5a769..34fa7a5674 100644\n--- a/docs/timeseries/index.rst\n+++ b/docs/timeseries/index.rst\n@@ -49,7 +49,7 @@ source::\n We can then use the |TimeSeries| class to read in this file::\n \n >>> from astropy.timeseries import TimeSeries\n- >>> ts = TimeSeries.read(filename, format='kepler.fits') # doctest: +REMOTE_DATA\n+ >>> ts = TimeSeries.read(filename, format='kepler.fits') # doctest: +REMOTE_DATA +IGNORE_WARNINGS\n \n Time series are specialized kinds of |Table| objects::\n \n"
}
] |
{
"header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:",
"data": []
}
|
diff --git a/docs/changes/io.fits/#####.feature.rst b/docs/changes/io.fits/#####.feature.rst
new file mode 100644
index 0000000000..5f84c63ac1
--- /dev/null
+++ b/docs/changes/io.fits/#####.feature.rst
@@ -0,0 +1,4 @@
+Add option ``unit_parse_strict`` to `~astropy.io.fits.connect.read_table_fits`
+to enable warnings or errors about invalid FITS units when using `~astropy.table.Table.read`.
+The default for this new option is ``"warn"``, which means warnings are now raised for
+columns with invalid units.
diff --git a/docs/timeseries/index.rst b/docs/timeseries/index.rst
index e9c8c5a769..34fa7a5674 100644
--- a/docs/timeseries/index.rst
+++ b/docs/timeseries/index.rst
@@ -49,7 +49,7 @@ source::
We can then use the |TimeSeries| class to read in this file::
>>> from astropy.timeseries import TimeSeries
- >>> ts = TimeSeries.read(filename, format='kepler.fits') # doctest: +REMOTE_DATA
+ >>> ts = TimeSeries.read(filename, format='kepler.fits') # doctest: +REMOTE_DATA +IGNORE_WARNINGS
Time series are specialized kinds of |Table| objects::
|
astropy/astropy
|
astropy__astropy-12590
|
https://github.com/astropy/astropy/pull/12590
|
diff --git a/astropy/cosmology/flrw.py b/astropy/cosmology/flrw.py
index 0ca7b1300cd6..7479bfa01375 100644
--- a/astropy/cosmology/flrw.py
+++ b/astropy/cosmology/flrw.py
@@ -285,6 +285,11 @@ def Ob0(self, param, value):
# ---------------------------------------------------------------
# properties
+ @property
+ def Otot0(self):
+ """Omega total; the total density/critical density at z=0."""
+ return self._Om0 + self._Ogamma0 + self._Onu0 + self._Ode0 + self._Ok0
+
@property
def Odm0(self):
"""Omega dark matter; dark matter density/critical density at z=0."""
@@ -365,6 +370,22 @@ def w(self, z):
"""
raise NotImplementedError("w(z) is not implemented")
+ 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.
+ """
+ return self.Om(z) + self.Ogamma(z) + self.Onu(z) + self.Ode(z) + self.Ok(z)
+
def Om(self, z):
"""
Return the density parameter for non-relativistic matter
@@ -1433,6 +1454,26 @@ def __init__(self, *args, **kw):
self._Ode0 = 1.0 - self._Om0 - self._Ogamma0 - self._Onu0
self._Ok0 = 0.0
+ @property
+ def Otot0(self):
+ """Omega total; the total density/critical density at z=0."""
+ return 1.0
+
+ 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
+ Returns float if input scalar. Value of 1.
+ """
+ return 1.0 if isinstance(z, (Number, np.generic)) else np.ones_like(z, subok=False)
+
def __equiv__(self, other):
"""flat-FLRW equivalence. Use ``.is_equivalent()`` for actual check!
diff --git a/docs/changes/cosmology/12590.feature.rst b/docs/changes/cosmology/12590.feature.rst
new file mode 100644
index 000000000000..41520e99612a
--- /dev/null
+++ b/docs/changes/cosmology/12590.feature.rst
@@ -0,0 +1,2 @@
+Add methods ``Otot`` and ``Otot0`` to FLRW cosmologies to calculate the total
+energy density of the Universe.
|
diff --git a/astropy/cosmology/tests/test_cosmology.py b/astropy/cosmology/tests/test_cosmology.py
index 4945368417f9..7e4f40a3f026 100644
--- a/astropy/cosmology/tests/test_cosmology.py
+++ b/astropy/cosmology/tests/test_cosmology.py
@@ -15,26 +15,6 @@
from astropy.utils.exceptions import AstropyDeprecationWarning, AstropyUserWarning
-def test_basic():
- cosmo = flrw.FlatLambdaCDM(H0=70, Om0=0.27, Tcmb0=2.0, Neff=3.04,
- Ob0=0.05, name="test", meta={"a": "b"})
- # This next test will fail if astropy.const starts returning non-mks
- # units by default; see the comment at the top of core.py
- assert allclose(cosmo.Om0 + cosmo.Ode0 + cosmo.Ogamma0 + cosmo.Onu0,
- 1.0, rtol=1e-6)
- assert allclose(cosmo.Om(1) + cosmo.Ode(1) + cosmo.Ogamma(1) +
- cosmo.Onu(1), 1.0, rtol=1e-6)
-
- # Make sure setting them as quantities gives the same results
- H0 = u.Quantity(70, u.km / (u.s * u.Mpc))
- T = u.Quantity(2.0, u.K)
- cosmo = flrw.FlatLambdaCDM(H0=H0, Om0=0.27, Tcmb0=T, Neff=3.04, Ob0=0.05)
- assert allclose(cosmo.Om0 + cosmo.Ode0 + cosmo.Ogamma0 + cosmo.Onu0,
- 1.0, rtol=1e-6)
- assert allclose(cosmo.Om(1) + cosmo.Ode(1) + cosmo.Ogamma(1) +
- cosmo.Onu(1), 1.0, rtol=1e-6)
-
-
@pytest.mark.skipif('not HAS_SCIPY')
def test_units():
""" Test if the right units are being returned"""
diff --git a/astropy/cosmology/tests/test_flrw.py b/astropy/cosmology/tests/test_flrw.py
index 0244d59fd699..6086092d3b3a 100644
--- a/astropy/cosmology/tests/test_flrw.py
+++ b/astropy/cosmology/tests/test_flrw.py
@@ -463,6 +463,7 @@ def test_init(self, cosmo_cls):
# TODO! transfer tests for initializing neutrinos
# ---------------------------------------------------------------
+ # Properties
def test_Odm0(self, cosmo_cls, cosmo):
"""Test property ``Odm0``."""
@@ -593,6 +594,32 @@ def test_Onu0(self, cosmo_cls, cosmo):
# and check compatibility with nu_relative_density
assert np.allclose(cosmo.nu_relative_density(0), 0.22710731766 * cosmo._Neff)
+ def test_Otot0(self, cosmo):
+ """Test :attr:`astropy.cosmology.FLRW.Otot0`."""
+ assert cosmo.Otot0 == cosmo.Om0 + cosmo.Ogamma0 + cosmo.Onu0 + cosmo.Ode0 + cosmo.Ok0
+
+ # ---------------------------------------------------------------
+ # Methods
+
+ def test_Otot(self, cosmo):
+ """Test :meth:`astropy.cosmology.FLRW.Otot`."""
+ exception = NotImplementedError if HAS_SCIPY else ModuleNotFoundError
+ with pytest.raises(exception):
+ assert cosmo.Otot(1)
+
+ def test_efunc_vs_invefunc(self, cosmo):
+ """
+ Test that efunc and inv_efunc give inverse values.
+ Here they just fail b/c no ``w(z)`` or no scipy.
+ """
+ exception = NotImplementedError if HAS_SCIPY else ModuleNotFoundError
+
+ with pytest.raises(exception):
+ cosmo.efunc(0.5)
+
+ with pytest.raises(exception):
+ cosmo.inv_efunc(0.5)
+
# ---------------------------------------------------------------
# from Cosmology
@@ -653,21 +680,6 @@ def test_is_equivalent(self, cosmo):
assert not cosmo.is_equivalent(Planck18)
assert not Planck18.is_equivalent(cosmo)
- # ---------------------------------------------------------------
-
- def test_efunc_vs_invefunc(self, cosmo):
- """
- Test that efunc and inv_efunc give inverse values.
- Here they just fail b/c no ``w(z)`` or no scipy.
- """
- exception = NotImplementedError if HAS_SCIPY else ModuleNotFoundError
-
- with pytest.raises(exception):
- cosmo.efunc(0.5)
-
- with pytest.raises(exception):
- cosmo.inv_efunc(0.5)
-
class FLRWSubclassTest(TestFLRW):
"""
@@ -682,6 +694,20 @@ def setup_class(self):
pass
# ===============================================================
+ # Method & Attribute Tests
+
+ # ---------------------------------------------------------------
+ # Densities
+
+ @pytest.mark.skipif(HAS_SCIPY, reason="scipy is not installed")
+ def test_Otot(self, cosmo):
+ """Test :meth:`astropy.cosmology.FLRW.Otot`."""
+ z = np.arange(0, 1e4, int(1e3))
+ assert np.allclose(
+ cosmo.Otot(z),
+ cosmo.Om(z) + cosmo.Ogamma(z) + cosmo.Onu(z) + cosmo.Ode(z) + cosmo.Ok(z))
+
+ # ---------------------------------------------------------------
def test_efunc_vs_invefunc(self, cosmo):
"""Test that ``efunc`` and ``inv_efunc`` give inverse values.
@@ -766,6 +792,27 @@ def test_Ok0(self, cosmo_cls, cosmo):
# for flat cosmologies, Ok0 is not *close* to 0, it *is* 0
assert cosmo.Ok0 == 0.0
+ def test_Otot0(self, cosmo):
+ """Test :attr:`astropy.cosmology.FLRW.Otot0`. Should always be 1."""
+ super().test_Otot0(cosmo)
+
+ assert cosmo.Otot0 == 1.0
+
+ @pytest.mark.skipif(HAS_SCIPY, reason="scipy is not installed")
+ def test_Otot(self, cosmo):
+ """Test :meth:`astropy.cosmology.FLRW.Otot`. Should always be 1."""
+ super().test_Otot(cosmo)
+
+ # scalar
+ assert cosmo.Otot(1049.5) == 1.0
+ assert cosmo.Otot(np.float64(1345.3)) == 1.0
+
+ # array
+ z = np.arange(0, 1e4, int(1e3))
+ assert np.allclose(cosmo.Otot(z), np.ones_like(z, subok=False))
+
+ # ---------------------------------------------------------------
+
def test_is_equivalent(self, cosmo, nonflatcosmo):
"""Test :meth:`astropy.cosmology.FLRW.is_equivalent`."""
super().test_is_equivalent(cosmo) # pass to TestFLRW
diff --git a/astropy/cosmology/tests/test_funcs.py b/astropy/cosmology/tests/test_funcs.py
index 96080ee4653b..470688d456d0 100644
--- a/astropy/cosmology/tests/test_funcs.py
+++ b/astropy/cosmology/tests/test_funcs.py
@@ -228,7 +228,7 @@ def test_z_at_value_roundtrip(cosmo):
# special handling
# clone is not a redshift-dependent method
# nu_relative_density is not redshift-dependent in the WMAP cosmologies
- skip = ('Ok',
+ skip = ('Ok', 'Otot',
'angular_diameter_distance_z1z2',
'clone', 'is_equivalent',
'de_density_scale', 'w')
|
[
{
"path": "docs/changes/cosmology/12590.feature.rst",
"old_path": "/dev/null",
"new_path": "b/docs/changes/cosmology/12590.feature.rst",
"metadata": "diff --git a/docs/changes/cosmology/12590.feature.rst b/docs/changes/cosmology/12590.feature.rst\nnew file mode 100644\nindex 000000000000..41520e99612a\n--- /dev/null\n+++ b/docs/changes/cosmology/12590.feature.rst\n@@ -0,0 +1,2 @@\n+Add methods ``Otot`` and ``Otot0`` to FLRW cosmologies to calculate the total\n+energy density of the Universe.\n",
"update": null
}
] |
5.1
|
2158c36979a5c8e4890a64947cfc631d1e928a72
|
[
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_to_ecsv_bad_index",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_tofromformat_model_instance",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_init_subclass",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_Neff",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_Tcmb0",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_to_ecsv_cls[QTable]",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_init_Ode0",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_fromformat_table_subclass_partial_info",
"astropy/cosmology/tests/test_funcs.py::Test_ZatValue::test_bad_broadcast",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_equality",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_astropy_table[Table-True]",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_fromformat_ecsv_subclass_partial_info",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_astropy_table[QTable-False]",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_h",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_tofrom_table_mutlirow[False]",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_tofrom_row_instance",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_Onu0",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_meta_mutable",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_to_ecsv_in_meta[False]",
"astropy/cosmology/tests/test_cosmology.py::test_comoving_distance_iterable_argument[z2-cosmo2]",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_to_row_in_meta[False]",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_init",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_Parameter_listed",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_to_row_in_meta[True]",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_equality",
"astropy/cosmology/tests/test_cosmology.py::test_comoving_distance_broadcast[cosmo2]",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_astropy_table[Table-False]",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_Neff",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_tofrom_yaml_instance",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_Odm0",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_Ogamma0",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_meta_on_instance",
"astropy/cosmology/tests/test_cosmology.py::test_de_subclass",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_toformat_model",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_init_signature",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_init_signature",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_to_ecsv_cls[QTable]",
"astropy/cosmology/tests/test_cosmology.py::test_comoving_distance_iterable_argument[z0-cosmo0]",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_tofrom_row_instance",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_hubble_distance",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_fromformat_model_wrong_cls",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_Ok0",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_astropy_table[Table-False]",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_to_table_cls[Table]",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_critical_density0",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_fromformat_subclass_partial_info_mapping",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_m_nu",
"astropy/cosmology/tests/test_cosmology.py::test_distance_in_special_cosmologies",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_tofrom_yaml_instance",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_to_mapping_cls[OrderedDict]",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_toformat_model",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_Parameter_listed",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_clone_change_param",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_make_from_Parameter",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_init",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_Parameter_instance_attributes",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_to_ecsv_in_meta[True]",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_to_table_in_meta[True]",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_tofromformat_model_instance",
"astropy/cosmology/tests/test_cosmology.py::test_tcmb",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_init",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_toformat_model",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_name",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_to_ecsv_failed_cls",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_Parameter_listed",
"astropy/cosmology/tests/test_cosmology.py::test_varyde_lumdist_mathematica",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_to_ecsv_cls[Table]",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_readwrite_complete_info[json]",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_tofrom_table_mutlirow[True]",
"astropy/cosmology/tests/test_cosmology.py::test_neg_distmod",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_init_signature",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_init_subclass",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_wp",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_Parameter_Ode0_validation",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_Parameter_listed",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_clone_fail_unexpected_arg",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_to_table_cls[QTable]",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_efunc_vs_invefunc",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_init_Ob0",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_toformat_model_not_method",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_Parameter_Ode0",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_Om0",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_tofrom_mapping_instance",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_Neff",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_fromformat_subclass_partial_info_mapping",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_Ob0",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_fromformat_ecsv_subclass_partial_info",
"astropy/cosmology/tests/test_funcs.py::test_z_at_value_roundtrip[wCDM]",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_astropy_table[QTable-True]",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_Parameter_unit",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_to_table_failed_cls",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_clone_identical",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_Odm0",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_init_Tcmb0",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_Parameter_not_unique",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_Parameter_derived",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_clone_identical",
"astropy/cosmology/tests/test_cosmology.py::test_comoving_distance_iterable_argument[z2-cosmo3]",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_to_ecsv_failed_cls",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_astropy_table[QTable-False]",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_init_m_nu",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_tofrom_mapping_instance",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_H0",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_wa",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_Tnu0",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_repr",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_fromformat_row_subclass_partial_info",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_Ode0",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_tofrom_table_mutlirow[False]",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_tofrom_table_instance",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_efunc_vs_invefunc",
"astropy/cosmology/tests/test_cosmology.py::test_comoving_distance_iterable_argument[z2-cosmo0]",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_tofrom_yaml_instance",
"astropy/cosmology/tests/test_cosmology.py::test_comoving_distance_iterable_argument[z0-cosmo3]",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_toformat_model_not_callable",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_clone_name",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_Tnu0",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_tofrom_table_mutlirow[True]",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_has_massive_nu",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_fromformat_model_subclass_partial_info",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_init_subclass",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_hubble_distance",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_fromformat_subclass_complete_info[format_type1]",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_tofrom_yaml_instance",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_from_not_table",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_init_wa",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_Parameter_descriptor_get",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_from_not_table",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_hubble_time",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_hubble_distance",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_fromformat_table_subclass_partial_info",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_tofrom_row_instance",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_Ob0",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_m_nu",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_Onu0",
"astropy/cosmology/tests/test_cosmology.py::test_comoving_distance_iterable_argument[z1-cosmo2]",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_init_subclass",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_to_ecsv_in_meta[False]",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_Parameter_Ode0_validation",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_to_ecsv_in_meta[False]",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_tofromformat_model_instance",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_has_massive_nu",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_clone_meta",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_to_mapping_cls[dict]",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_to_table_failed_cls",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_astropy_table[QTable-True]",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_to_table_in_meta[True]",
"astropy/cosmology/tests/test_cosmology.py::test_distance_broadcast",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_init_Ode0",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_to_table_cls[Table]",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_meta_mutable",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_toformat_model_not_method",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_Parameter_descriptor_set",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_init_w0",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_readwrite_complete_info[json]",
"astropy/cosmology/tests/test_cosmology.py::test_integral",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_fromformat_model_wrong_cls",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_init_H0",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_meta_on_instance",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_astropy_table[Table-True]",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_fromformat_model_wrong_cls",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_toformat_model_not_method",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_make_from_Parameter",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_has_massive_nu",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_fromformat_row_subclass_partial_info",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_hubble_distance",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_clone_fail_positional_arg",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_init_subclass",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_Parameter_equivalencies",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_make_from_Parameter",
"astropy/cosmology/tests/test_cosmology.py::test_wz",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_h",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_init_Ode0",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_to_row_in_meta[True]",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_Parameter_Ode0",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_tofromformat_complete_info[format_type0]",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_tofrom_row_instance",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_Ok0",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_Parameter_name",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_readwrite_from_subclass_complete_info[json]",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_to_ecsv_in_meta[True]",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_Parameter_descriptor_get",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_tofrom_ecsv_mutlirow",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_clone_identical",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_tofromformat_model_instance",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_fromformat_table_subclass_partial_info",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_hubble_distance",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_Parameter_equivalencies",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_init_Ode0",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_to_ecsv_cls[QTable]",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_tofromformat_complete_info[format_type1]",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_to_mapping_cls[dict]",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_init_m_nu",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_fromformat_subclass_partial_info_mapping",
"astropy/cosmology/tests/test_cosmology.py::test_comoving_distance_iterable_argument[z1-cosmo0]",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_to_row_in_meta[False]",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_clone_name",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_Ok0",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_to_ecsv_bad_index",
"astropy/cosmology/tests/test_cosmology.py::test_absorption_distance",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_to_mapping_cls[OrderedDict]",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_Ob0",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_astropy_table[QTable-True]",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_readwrite_complete_info[json]",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_w0",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_init_Om0",
"astropy/cosmology/tests/test_cosmology.py::test_comoving_volume",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_Parameter_descriptor_set",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_from_not_mapping",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_failed_cls_to_mapping",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_meta_mutable",
"astropy/cosmology/tests/test_cosmology.py::test_tnu",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_tofrom_ecsv_instance",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_name",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_tofromformat_complete_info[format_type1]",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_Parameter_init",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_Parameter_descriptor_get",
"astropy/cosmology/tests/test_cosmology.py::test_comoving_distance_iterable_argument[z1-cosmo3]",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_to_ecsv_in_meta[False]",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_Tcmb0",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_init_Ob0",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_is_equivalent",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_to_ecsv_failed_cls",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_to_table_cls[QTable]",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_init_Om0",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_to_table_in_meta[True]",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_Parameter_unit",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_init",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_meta_on_class",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_Tcmb0",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_efunc_vs_invefunc",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_from_not_mapping",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_toformat_model_not_callable",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_init_Ob0",
"astropy/cosmology/tests/test_cosmology.py::test_elliptic_comoving_distance_z1z2",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_clone_identical",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_fromformat_subclass_complete_info[format_type1]",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_equality",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_tofromformat_complete_info[format_type1]",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_from_not_row",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_clone_name",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_from_not_table",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_Parameter_fvalidate",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_to_ecsv_in_meta[False]",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_Om0",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_Parameter_init",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_clone_meta",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_tofrom_yaml_instance",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_to_table_failed_cls",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_fromformat_subclass_complete_info[format_type0]",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_Parameter_Ode0",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_astropy_table[QTable-False]",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_immutability",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_tofrom_ecsv_mutlirow",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_to_ecsv_failed_cls",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_to_ecsv_in_meta[True]",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_parameter_related_attributes_on_Cosmology",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_init_Ode0",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_astropy_table[QTable-True]",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_tofrom_yaml_autoidentify",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_init_signature",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_init_signature",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_to_ecsv_in_meta[True]",
"astropy/cosmology/tests/test_cosmology.py::test_comoving_distance_z1z2",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_fromformat_subclass_complete_info[format_type0]",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_init_m_nu",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_Parameter_derived",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_equality",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_tofrom_ecsv_instance",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_clone_fail_positional_arg",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_Parameter_not_unique",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_to_table_cls[Table]",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_Parameter_derived",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_meta_on_class",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_repr",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_Parameter_instance_attributes",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_init_w0",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_to_table_in_meta[False]",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_clone_meta",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_tofrom_table_mutlirow[False]",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_init_signature",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_tofrom_mapping_instance",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_init_Tcmb0",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_Ob0",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_clone_fail_unexpected_arg",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_tofrom_yaml_instance",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_to_row_in_meta[True]",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_to_row_in_meta[False]",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_astropy_table[Table-True]",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_Tnu0",
"astropy/cosmology/tests/test_cosmology.py::test_efunc_vs_invefunc_flrw",
"astropy/cosmology/tests/test_cosmology.py::test_comoving_distance_broadcast[cosmo3]",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_Parameter_class_attributes",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_from_not_mapping",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_m_nu",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_Ogamma0",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_to_ecsv_in_meta[True]",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_w0",
"astropy/cosmology/tests/test_cosmology.py::test_ode",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_clone_identical",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_to_table_cls[Table]",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_clone_fail_positional_arg",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_to_table_bad_index",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_fromformat_row_subclass_partial_info",
"astropy/cosmology/tests/test_cosmology.py::test_comoving_distance_iterable_argument[z0-cosmo2]",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_meta_on_class",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_to_table_cls[Table]",
"astropy/cosmology/tests/test_cosmology.py::test_ocurv",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_Onu0",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_Tnu0",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_Parameter_descriptor_get",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_wz",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_Parameter_unit",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_clone_fail_positional_arg",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_to_row_in_meta[True]",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_parameter_related_attributes_on_Cosmology",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_init_subclass",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_Tcmb0",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_hubble_time",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_to_ecsv_failed_cls",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_tofromformat_complete_info[format_type1]",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_make_from_Parameter",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_Ogamma0",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_init_Neff",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_Parameter_name",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_to_table_cls[Table]",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_astropy_table[QTable-True]",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_clone_name",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_fromformat_subclass_complete_info[format_type0]",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_to_table_failed_cls",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_from_not_row",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_readwrite_complete_info[json]",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_to_ecsv_in_meta[True]",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_init_m_nu",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_critical_density0",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_to_table_cls[Table]",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_init_wz",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_Parameter_unit",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_clone_change_param",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_Parameter_listed",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_parameter_related_attributes_on_Cosmology",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_Parameter_name",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_fromformat_ecsv_subclass_partial_info",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_meta_on_class",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_to_mapping_cls[dict]",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_tofromformat_model_instance",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_fromformat_subclass_partial_info_mapping",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_to_table_bad_index",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_clone_change_param",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_Onu0",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_tofromformat_complete_info[format_type1]",
"astropy/cosmology/tests/test_cosmology.py::test_matter",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_Om0",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_to_table_in_meta[False]",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_tofrom_row_instance",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_readwrite_complete_info[json]",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_critical_density0",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_to_table_cls[Table]",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_init_Neff",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_clone_name",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_to_ecsv_cls[Table]",
"astropy/cosmology/tests/test_cosmology.py::test_de_densityscale",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_Tcmb0",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_toformat_model_not_callable",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_to_table_cls[QTable]",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_toformat_model_not_callable",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_Parameter_init",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_Parameter_init",
"astropy/cosmology/tests/test_funcs.py::test_z_at_value_roundtrip[wpwaCDM]",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_fromformat_ecsv_subclass_partial_info",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_efunc_vs_invefunc",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_fromformat_subclass_complete_info[format_type1]",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_H0",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_to_table_in_meta[False]",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_tofromformat_complete_info[format_type0]",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_to_row_in_meta[False]",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_tofrom_mapping_instance",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_init_wp",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_Parameter_format_spec",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_Neff",
"astropy/cosmology/tests/test_cosmology.py::test_age",
"astropy/cosmology/tests/test_cosmology.py::test_comoving_distance_iterable_argument[z0-cosmo1]",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_tofrom_ecsv_instance",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_Parameter_class_attributes",
"astropy/cosmology/tests/test_funcs.py::test_z_at_value_unconverged[Bounded]",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_to_row_in_meta[False]",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_fromformat_subclass_complete_info[format_type1]",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_tofromformat_complete_info[format_type0]",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_to_ecsv_cls[Table]",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_Parameters_reorder_by_signature",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_clone_meta",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_fromformat_row_subclass_partial_info",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_m_nu",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_Parameter_fvalidate",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_to_ecsv_bad_index",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_from_not_row",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_meta_on_instance",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_Tcmb0",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_clone_identical",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_fromformat_ecsv_subclass_partial_info",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_failed_cls_to_mapping",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_failed_cls_to_mapping",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_tofrom_table_mutlirow[True]",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_fromformat_model_wrong_cls",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_astropy_table[QTable-True]",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_hubble_time",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_to_table_in_meta[True]",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_Parameter_descriptor_get",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_Parameter_instance_attributes",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_Parameter_derived",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_parameter_related_attributes_on_Cosmology",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_name",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_Parameter_format_spec",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_toformat_model",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_m_nu",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_immutability",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_tofrom_table_instance",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_clone_name",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_Ogamma0",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_init_Om0",
"astropy/cosmology/tests/test_cosmology.py::test_distmod",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_init_m_nu",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_critical_density0",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_to_ecsv_in_meta[True]",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_tofrom_ecsv_instance",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_clone_fail_positional_arg",
"astropy/cosmology/tests/test_cosmology.py::test_comoving_distance_broadcast[cosmo0]",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_to_mapping_cls[OrderedDict]",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_astropy_table[QTable-False]",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_init_H0",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_to_ecsv_cls[QTable]",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_from_not_table",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_toformat_model",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_Ok0",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_init_Tcmb0",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_to_ecsv_cls[Table]",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_tofrom_table_mutlirow[True]",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_to_mapping_cls[OrderedDict]",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_has_massive_nu",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_Odm0",
"astropy/cosmology/tests/test_cosmology.py::test_zeroing",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_fromformat_subclass_complete_info[format_type1]",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_Parameter_instance_attributes",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_Parameter_equivalencies",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_hubble_time",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_Parameter_instance_attributes",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_clone_meta",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_Ogamma0",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_to_table_in_meta[False]",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_clone_change_param",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_tofrom_mapping_instance",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_failed_cls_to_mapping",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_immutability",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_tofrom_table_instance",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_to_ecsv_cls[Table]",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_meta_on_instance",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_to_table_cls[Table]",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_fromformat_subclass_complete_info[format_type1]",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_astropy_table[QTable-False]",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_Parameter_fvalidate",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_Ok0",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_astropy_table[Table-True]",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_H0",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_to_mapping_cls[OrderedDict]",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_to_ecsv_in_meta[False]",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_wa",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_to_table_bad_index",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_Parameter_not_unique",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_Odm0",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_Parameter_name",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_Parameter_format_spec",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_meta_on_class",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_fromformat_model_subclass_partial_info",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_init_Ob0",
"astropy/cosmology/tests/test_cosmology.py::test_massivenu_density",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_tofrom_table_instance",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_init_m_nu",
"astropy/cosmology/tests/test_funcs.py::test_z_at_value_numpyvectorize",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_tofrom_ecsv_mutlirow",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_Om0",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_tofrom_row_instance",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_h",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_tofrom_row_instance",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_tofrom_yaml_autoidentify",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_Odm0",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_tofrom_row_instance",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_init_signature",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_Odm0",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_meta_on_instance",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_name",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_toformat_model_not_callable",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_tofrom_ecsv_instance",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_to_row_in_meta[True]",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_Parameter_unit",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_readwrite_complete_info[json]",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_init_H0",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_clone_identical",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_fromformat_row_subclass_partial_info",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_Ode0",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_to_ecsv_cls[QTable]",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_fromformat_model_subclass_partial_info",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_failed_cls_to_mapping",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_astropy_table[QTable-False]",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_meta_on_class",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_Ok0",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_fromformat_model_subclass_partial_info",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_Parameter_Ode0_validation",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_parameter_related_attributes_on_Cosmology",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_name",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_Om0",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_efunc_vs_invefunc",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_fromformat_subclass_complete_info[format_type1]",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_Parameter_format_spec",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_readwrite_from_subclass_complete_info[json]",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_tofrom_table_instance",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_Odm0",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_from_not_row",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_efunc_vs_invefunc",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_init_Neff",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_Parameter_descriptor_get",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_init_Om0",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_init_Tcmb0",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_Neff",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_H0",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_is_equivalent",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_to_table_failed_cls",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_astropy_table[QTable-True]",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_clone_meta",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_tofrom_table_mutlirow[False]",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_is_equivalent",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_clone_name",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_tofrom_yaml_autoidentify",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_hubble_distance",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_Parameter_format_spec",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_Parameter_unit",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_tofrom_table_mutlirow[True]",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_hubble_distance",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_Parameter_not_unique",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_m_nu",
"astropy/cosmology/tests/test_cosmology.py::test_critical_density",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_has_massive_nu",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_Parameter_Ode0_validation",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_init_Ob0",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_from_not_row",
"astropy/cosmology/tests/test_cosmology.py::test_angular_diameter_distance_z1z2",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_Parameter_format_spec",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_to_table_in_meta[False]",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_Ob0",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_toformat_model_not_method",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_to_ecsv_in_meta[True]",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_Tcmb0",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_to_mapping_cls[dict]",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_repr",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_to_row_in_meta[False]",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_to_table_bad_index",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_astropy_table[QTable-True]",
"astropy/cosmology/tests/test_cosmology.py::test_flat_z1",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_meta_mutable",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_name",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_to_mapping_cls[OrderedDict]",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_tofromformat_model_instance",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_Parameter_Ode0_validation",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_to_mapping_cls[dict]",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_init_H0",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_to_row_in_meta[True]",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_fromformat_subclass_complete_info[format_type0]",
"astropy/cosmology/tests/test_cosmology.py::test_differential_comoving_volume",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_efunc_vs_invefunc",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_to_table_cls[QTable]",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_init_Neff",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_clone_change_param",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_init_signature",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_Parameter_descriptor_get",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_astropy_table[QTable-False]",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_init_H0",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_Parameter_equivalencies",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_Ok0",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_astropy_table[Table-True]",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_astropy_table[Table-False]",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_efunc_vs_invefunc",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_Parameter_class_attributes",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_immutability",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_from_not_mapping",
"astropy/cosmology/tests/test_cosmology.py::test_age_in_special_cosmologies",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_toformat_model_not_method",
"astropy/cosmology/tests/test_funcs.py::test_z_at_value_roundtrip[Flatw0waCDM]",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_from_not_table",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_is_equivalent",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_Parameter_Ode0_validation",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_readwrite_complete_info[json]",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_tofrom_table_mutlirow[True]",
"astropy/cosmology/tests/test_cosmology.py::test_ogamma",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_Parameter_init",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_meta_mutable",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_tofrom_ecsv_mutlirow",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_failed_cls_to_mapping",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_make_from_Parameter",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_toformat_model_not_method",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_to_row_in_meta[True]",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_Parameters_reorder_by_signature",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_init_subclass",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_has_massive_nu",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_to_ecsv_in_meta[False]",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_Ob0",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_Parameter_equivalencies",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_tofrom_ecsv_instance",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_toformat_model",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_Parameter_class_attributes",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_tofrom_ecsv_mutlirow",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_meta_on_instance",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_repr",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_tofrom_ecsv_mutlirow",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_init_H0",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_hubble_distance",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_meta_mutable",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_to_ecsv_in_meta[False]",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_H0",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_init_Ob0",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_has_massive_nu",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_astropy_table[Table-False]",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_Parameter_descriptor_get",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_Parameter_init",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_parameter_related_attributes_on_Cosmology",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_fromformat_model_wrong_cls",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_Parameter_not_unique",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_m_nu",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_fromformat_row_subclass_partial_info",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_critical_density0",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_meta_mutable",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_Parameter_instance_attributes",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_tofrom_yaml_autoidentify",
"astropy/cosmology/tests/test_cosmology.py::test_massivenu_basic",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_immutability",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_toformat_model_not_callable",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_fromformat_ecsv_subclass_partial_info",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_init_zp",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_meta_on_class",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_Ob0",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_Ok0",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_h",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_meta_on_instance",
"astropy/cosmology/tests/test_cosmology.py::test_distances",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_init",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_Parameter_Ode0",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_init_Tcmb0",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_clone_identical",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_init_Tcmb0",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_tofrom_yaml_autoidentify",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_Parameter_init",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_to_table_failed_cls",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_astropy_table[Table-True]",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_repr",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_tofromformat_model_instance",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_tofromformat_complete_info[format_type0]",
"astropy/cosmology/tests/test_cosmology.py::test_units",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_fromformat_row_subclass_partial_info",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_Tnu0",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_is_equivalent",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_Parameter_class_attributes",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_tofrom_yaml_autoidentify",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_tofrom_table_instance",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_has_massive_nu",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_fromformat_subclass_partial_info_mapping",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_make_from_Parameter",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_tofromformat_complete_info[format_type1]",
"astropy/cosmology/tests/test_cosmology.py::test_xtfuncs",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_m_nu",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_toformat_model_not_method",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_init",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_clone_change_param",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_is_equivalent",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_tofromformat_model_instance",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_from_not_mapping",
"astropy/cosmology/tests/test_cosmology.py::test_comoving_distance_iterable_argument[z2-cosmo1]",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_toformat_model",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_astropy_table[Table-True]",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_readwrite_from_subclass_complete_info[json]",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_Parameter_Ode0",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_Onu0",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_astropy_table[QTable-False]",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_Parameter_instance_attributes",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_hubble_time",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_Ob0",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_fromformat_subclass_complete_info[format_type0]",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_to_table_failed_cls",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_fromformat_subclass_complete_info[format_type1]",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_Parameter_Ode0",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_fromformat_subclass_complete_info[format_type1]",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_Neff",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_Odm0",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_failed_cls_to_mapping",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_critical_density0",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_Parameter_unit",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_fromformat_row_subclass_partial_info",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_to_table_cls[QTable]",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_parameter_related_attributes_on_Cosmology",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_to_table_cls[QTable]",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_to_ecsv_cls[Table]",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_astropy_table[Table-False]",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_tofrom_table_instance",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_tofrom_table_mutlirow[False]",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_clone_identical",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_equality",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_hubble_time",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_Parameter_name",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_Parameter_derived",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_hubble_distance",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_immutability",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_tofrom_yaml_autoidentify",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_fromformat_subclass_complete_info[format_type0]",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_Parameter_descriptor_set",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_tofrom_mapping_instance",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_tofrom_mapping_instance",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_Onu0",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_Ode0",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_Parameter_descriptor_set",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_Parameter_listed",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_clone_fail_positional_arg",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_is_equivalent",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_repr",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_from_not_row",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_toformat_model_not_callable",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_failed_cls_to_mapping",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_Tcmb0",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_tofrom_ecsv_mutlirow",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_init",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_Parameters_reorder_by_signature",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_to_ecsv_cls[Table]",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_tofromformat_model_instance",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_tofrom_table_mutlirow[False]",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_to_table_bad_index",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_to_table_in_meta[True]",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_init_H0",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_toformat_model",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_H0",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_fromformat_subclass_partial_info_mapping",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_Parameter_descriptor_set",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_tofrom_table_mutlirow[False]",
"astropy/cosmology/tests/test_funcs.py::test_z_at_value_roundtrip[w0waCDM]",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_clone_fail_positional_arg",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_Parameter_listed",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_Tnu0",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_fromformat_subclass_partial_info_mapping",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_to_ecsv_bad_index",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_tofrom_table_instance",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_readwrite_complete_info[json]",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_tofrom_yaml_autoidentify",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_to_mapping_cls[OrderedDict]",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_parameter_related_attributes_on_Cosmology",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_Parameter_derived",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_from_not_table",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_init_Neff",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_to_table_in_meta[False]",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_wa",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_init_signature",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_tofrom_table_instance",
"astropy/cosmology/tests/test_cosmology.py::test_kpc_methods",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_fromformat_subclass_complete_info[format_type0]",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_immutability",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_Parameter_instance_attributes",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_astropy_table[Table-False]",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_clone_fail_positional_arg",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_fromformat_model_subclass_partial_info",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_init_w0",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_astropy_table[Table-True]",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_to_mapping_cls[OrderedDict]",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_from_not_table",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_failed_cls_to_mapping",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_to_ecsv_failed_cls",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_Parameter_class_attributes",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_Ode0",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_init_wa",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_tofrom_table_mutlirow[False]",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_init_Om0",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_Parameter_format_spec",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_meta_on_instance",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_critical_density0",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_Parameter_instance_attributes",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_to_table_bad_index",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_Ode0",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_Parameter_init",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_H0",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_equality",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_init_m_nu",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_Ogamma0",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_init_wa",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_clone_fail_unexpected_arg",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_to_ecsv_cls[QTable]",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_Ogamma0",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_from_not_mapping",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_to_mapping_cls[dict]",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_Parameter_not_unique",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_Parameter_format_spec",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_Tnu0",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_fromformat_subclass_partial_info_mapping",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_fromformat_model_wrong_cls",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_init_Om0",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_to_table_in_meta[True]",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_to_table_bad_index",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_readwrite_from_subclass_complete_info[json]",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_clone_change_param",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_Parameter_unit",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_Parameter_Ode0",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_Parameter_equivalencies",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_init_Neff",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_init_Om0",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_to_mapping_cls[dict]",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_Parameter_fvalidate",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_w0",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_repr",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_clone_fail_unexpected_arg",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_Parameter_Ode0",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_Ode0",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_fromformat_model_wrong_cls",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_fromformat_subclass_partial_info_mapping",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_Parameter_descriptor_set",
"astropy/cosmology/tests/test_funcs.py::test_z_at_value_roundtrip[FlatwCDM]",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_Parameter_name",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_Onu0",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_tofromformat_complete_info[format_type1]",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_init_Ob0",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_to_ecsv_bad_index",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_fromformat_model_subclass_partial_info",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_meta_on_instance",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_Parameter_format_spec",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_Ode0",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_Parameter_class_attributes",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_readwrite_from_subclass_complete_info[json]",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_init_subclass",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_to_mapping_cls[OrderedDict]",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_from_not_table",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_Parameter_not_unique",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_tofromformat_complete_info[format_type1]",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_from_not_row",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_name",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_to_ecsv_cls[QTable]",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_Parameters_reorder_by_signature",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_hubble_time",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_fromformat_model_wrong_cls",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_tofrom_mapping_instance",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_to_ecsv_failed_cls",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_Ogamma0",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_astropy_table[Table-False]",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_fromformat_table_subclass_partial_info",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_tofrom_row_instance",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_to_ecsv_in_meta[True]",
"astropy/cosmology/tests/test_funcs.py::test_z_at_value_roundtrip[FlatLambdaCDM]",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_init_Tcmb0",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_astropy_table[Table-False]",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_to_table_cls[QTable]",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_Om0",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_m_nu",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_init",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_from_not_mapping",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_Tnu0",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_init_Om0",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_init_Neff",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_to_ecsv_cls[Table]",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_toformat_model",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_from_not_row",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_to_table_in_meta[True]",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_init_Om0",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_Parameter_name",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_Parameter_equivalencies",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_fromformat_table_subclass_partial_info",
"astropy/cosmology/tests/test_funcs.py::test_z_at_value_roundtrip[w0wzCDM]",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_Parameter_equivalencies",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_tofrom_ecsv_mutlirow",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_hubble_time",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_fromformat_subclass_complete_info[format_type0]",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_toformat_model_not_callable",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_h",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_Neff",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_Parameter_descriptor_set",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_meta_mutable",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_Parameter_fvalidate",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_astropy_table[QTable-True]",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_init_w0",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_clone_fail_unexpected_arg",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_to_table_in_meta[False]",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_equality",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_fromformat_ecsv_subclass_partial_info",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_tofromformat_complete_info[format_type0]",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_immutability",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_zp",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_Parameter_name",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_w0",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_Tcmb0",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_hubble_time",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_tofrom_table_mutlirow[True]",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_fromformat_ecsv_subclass_partial_info",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_Parameter_Ode0_validation",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_tofrom_ecsv_mutlirow",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_Ogamma0",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_tofrom_yaml_instance",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_fromformat_ecsv_subclass_partial_info",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_init_Tcmb0",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_init_Ode0",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_tofromformat_complete_info[format_type1]",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_tofromformat_complete_info[format_type0]",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_clone_fail_positional_arg",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_clone_fail_unexpected_arg",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_Parameter_unit",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_to_ecsv_cls[Table]",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_Neff",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_Ok0",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_Parameter_Ode0",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_init_m_nu",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_to_row_in_meta[False]",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_tofrom_table_mutlirow[True]",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_tofrom_yaml_instance",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_to_table_in_meta[True]",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_equality",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_Ob0",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_Om0",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_equality",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_tofrom_table_mutlirow[True]",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_fromformat_model_subclass_partial_info",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_clone_meta",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_is_equivalent",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_readwrite_complete_info[json]",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_init_Ob0",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_to_ecsv_bad_index",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_Parameter_class_attributes",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_meta_on_class",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_tofrom_mapping_instance",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_Parameters_reorder_by_signature",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_to_table_bad_index",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_readwrite_from_subclass_complete_info[json]",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_Ode0",
"astropy/cosmology/tests/test_cosmology.py::test_equality",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_fromformat_model_subclass_partial_info",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_tofromformat_complete_info[format_type0]",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_Parameters_reorder_by_signature",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_readwrite_from_subclass_complete_info[json]",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_init_Tcmb0",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_Parameter_class_attributes",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_Parameters_reorder_by_signature",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_init_H0",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_Odm0",
"astropy/cosmology/tests/test_cosmology.py::test_comoving_transverse_distance_z1z2",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_to_table_in_meta[False]",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_name",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_to_mapping_cls[dict]",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_Onu0",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_tofrom_ecsv_instance",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_clone_fail_unexpected_arg",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_readwrite_from_subclass_complete_info[json]",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_from_not_table",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_init_Ob0",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_Om0",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_readwrite_from_subclass_complete_info[json]",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_init_subclass",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_to_row_in_meta[False]",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_Parameter_descriptor_get",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_astropy_table[Table-False]",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_Parameter_derived",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_parameter_related_attributes_on_Cosmology",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_Ode0",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_fromformat_table_subclass_partial_info",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_make_from_Parameter",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_astropy_table[Table-True]",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_init_Ode0",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_Parameter_derived",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_tofromformat_complete_info[format_type0]",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_to_row_in_meta[True]",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_Parameter_derived",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_init_w0",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_to_ecsv_bad_index",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_to_row_in_meta[False]",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_fromformat_row_subclass_partial_info",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_tofromformat_complete_info[format_type0]",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_h",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_to_ecsv_cls[QTable]",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_from_not_mapping",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_clone_meta",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_H0",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_Parameter_listed",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_fromformat_subclass_complete_info[format_type0]",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_to_table_failed_cls",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_Parameter_equivalencies",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_critical_density0",
"astropy/cosmology/tests/test_cosmology.py::test_comoving_distance_iterable_argument[z1-cosmo1]",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_to_ecsv_in_meta[False]",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_fromformat_table_subclass_partial_info",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_Parameter_not_unique",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_Onu0",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_toformat_model_not_callable",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_fromformat_table_subclass_partial_info",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_h",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_meta_mutable",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_h",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_fromformat_model_wrong_cls",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_init_m_nu",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_repr",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_Parameter_listed",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_init_Ode0",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_to_table_bad_index",
"astropy/cosmology/tests/test_funcs.py::test_z_at_value_roundtrip[LambdaCDM]",
"astropy/cosmology/tests/test_cosmology.py::test_flat_open_closed_icosmo",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_Parameter_fvalidate",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_clone_fail_unexpected_arg",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_init_H0",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_fromformat_model_subclass_partial_info",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_init",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_tofrom_yaml_autoidentify",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_init_Neff",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_to_table_cls[QTable]",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_to_table_in_meta[True]",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_to_row_in_meta[True]",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_tofrom_yaml_instance",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_Parameters_reorder_by_signature",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_make_from_Parameter",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_h",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_efunc_vs_invefunc",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_critical_density0",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_to_ecsv_failed_cls",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_H0",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_to_ecsv_bad_index",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_Parameter_Ode0_validation",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_to_ecsv_bad_index",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_clone_fail_unexpected_arg",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_name",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_Parameters_reorder_by_signature",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_Parameter_fvalidate",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_to_table_cls[QTable]",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_clone_name",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_clone_change_param",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_Parameter_not_unique",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_immutability",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_clone_name",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_make_from_Parameter",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_to_mapping_cls[dict]",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_clone_meta",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_to_table_in_meta[False]",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_Tnu0",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_to_ecsv_cls[QTable]",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_Parameter_descriptor_set",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_to_table_failed_cls",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_from_not_mapping",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_tofrom_ecsv_instance",
"astropy/cosmology/tests/test_cosmology.py::test_comoving_distance_broadcast[cosmo1]",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_meta_on_class",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_from_not_row",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_fromformat_table_subclass_partial_info",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_w0",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_Om0",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_Parameter_name",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_repr",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_Parameter_Ode0_validation",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_has_massive_nu",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_toformat_model_not_method",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_astropy_table[QTable-False]",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_tofrom_table_mutlirow[False]",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_is_equivalent",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_tofrom_ecsv_instance",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_init_Neff",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_toformat_model_not_method",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_to_ecsv_failed_cls",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_Parameter_fvalidate",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_Parameter_fvalidate",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_Parameter_descriptor_set",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_Neff",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_init_Ode0",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_clone_change_param",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_Parameter_init"
] |
[
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_Otot0",
"astropy/cosmology/tests/test_flrw.py::TestwpwaCDM::test_Otot0",
"astropy/cosmology/tests/test_flrw.py::TestFlatLambdaCDM::test_Otot0",
"astropy/cosmology/tests/test_flrw.py::Testw0wzCDM::test_Otot0",
"astropy/cosmology/tests/test_flrw.py::TestLambdaCDM::test_Otot0",
"astropy/cosmology/tests/test_flrw.py::TestFlatw0waCDM::test_Otot0",
"astropy/cosmology/tests/test_flrw.py::TestFlatwCDM::test_Otot0",
"astropy/cosmology/tests/test_flrw.py::Testw0waCDM::test_Otot0",
"astropy/cosmology/tests/test_flrw.py::TestFLRW::test_Otot",
"astropy/cosmology/tests/test_flrw.py::TestwCDM::test_Otot0"
] |
[
{
"path": "docs/changes/cosmology/#####.feature.rst",
"old_path": "/dev/null",
"new_path": "b/docs/changes/cosmology/#####.feature.rst",
"metadata": "diff --git a/docs/changes/cosmology/#####.feature.rst b/docs/changes/cosmology/#####.feature.rst\nnew file mode 100644\nindex 0000000000..41520e9961\n--- /dev/null\n+++ b/docs/changes/cosmology/#####.feature.rst\n@@ -0,0 +1,2 @@\n+Add methods ``Otot`` and ``Otot0`` to FLRW cosmologies to calculate the total\n+energy density of the Universe.\n"
}
] |
{
"header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:",
"data": [
{
"type": "field",
"name": "Ode"
},
{
"type": "field",
"name": "Onu"
},
{
"type": "field",
"name": "ones_like"
},
{
"type": "field",
"name": "Om"
},
{
"type": "field",
"name": "Ok"
},
{
"type": "field",
"name": "subok"
}
]
}
|
diff --git a/docs/changes/cosmology/#####.feature.rst b/docs/changes/cosmology/#####.feature.rst
new file mode 100644
index 0000000000..41520e9961
--- /dev/null
+++ b/docs/changes/cosmology/#####.feature.rst
@@ -0,0 +1,2 @@
+Add methods ``Otot`` and ``Otot0`` to FLRW cosmologies to calculate the total
+energy density of the Universe.
If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:
[{'type': 'field', 'name': 'Ode'}, {'type': 'field', 'name': 'Onu'}, {'type': 'field', 'name': 'ones_like'}, {'type': 'field', 'name': 'Om'}, {'type': 'field', 'name': 'Ok'}, {'type': 'field', 'name': 'subok'}]
|
astropy/astropy
|
astropy__astropy-12313
|
https://github.com/astropy/astropy/pull/12313
|
diff --git a/astropy/cosmology/io/row.py b/astropy/cosmology/io/row.py
new file mode 100644
index 000000000000..1581e050b09d
--- /dev/null
+++ b/astropy/cosmology/io/row.py
@@ -0,0 +1,139 @@
+# Licensed under a 3-clause BSD style license - see LICENSE.rst
+
+import copy
+
+import numpy as np
+
+from astropy.table import Row
+from astropy.cosmology.connect import convert_registry
+from astropy.cosmology.core import Cosmology
+
+from .mapping import from_mapping
+
+
+def from_row(row, *, move_to_meta=False, cosmology=None):
+ """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
+ <Row index=0>
+ cosmology name H0 Om0 Tcmb0 Neff m_nu [3] Ob0
+ km / (Mpc s) K eV
+ str13 str8 float64 float64 float64 float64 float64 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.7 km / (Mpc s), Om0=0.31,
+ Tcmb0=2.725 K, Neff=3.05, m_nu=[0. 0. 0.06] eV, Ob0=0.049)
+ """
+ # special values
+ name = row['name'] if 'name' in row.columns else None # get name from column
+ meta = copy.deepcopy(row.meta)
+
+ # turn row into mapping, filling cosmo if not in a column
+ mapping = dict(row)
+ mapping["name"] = name
+ mapping.setdefault("cosmology", meta.pop("cosmology", None))
+ mapping["meta"] = meta
+
+ # build cosmology from map
+ return from_mapping(mapping, move_to_meta=move_to_meta, cosmology=cosmology)
+
+
+def to_row(cosmology, *args, cosmology_in_meta=False):
+ """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`
+ 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
+ <Row index=0>
+ cosmology name H0 Om0 Tcmb0 Neff m_nu [3] Ob0
+ km / (Mpc s) K eV
+ str13 str8 float64 float64 float64 float64 float64 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.
+ """
+ from .table import to_table
+
+ table = to_table(cosmology, cosmology_in_meta=cosmology_in_meta)
+ return table[0] # extract row from table
+
+
+def row_identify(origin, format, *args, **kwargs):
+ """Identify if object uses the `~astropy.table.Row` format.
+
+ Returns
+ -------
+ bool
+ """
+ itis = False
+ if origin == "read":
+ itis = isinstance(args[1], Row) and (format in (None, "astropy.row"))
+ return itis
+
+
+# ===================================================================
+# Register
+
+convert_registry.register_reader("astropy.row", Cosmology, from_row)
+convert_registry.register_writer("astropy.row", Cosmology, to_row)
+convert_registry.register_identifier("astropy.row", Cosmology, row_identify)
diff --git a/astropy/cosmology/io/table.py b/astropy/cosmology/io/table.py
index 7c7490d8cbfa..9adbb4d438bc 100644
--- a/astropy/cosmology/io/table.py
+++ b/astropy/cosmology/io/table.py
@@ -8,7 +8,8 @@
from astropy.cosmology.core import Cosmology
from astropy.table import QTable, Table
-from .mapping import from_mapping, to_mapping
+from .mapping import to_mapping
+from .row import from_row
def from_table(table, index=None, *, move_to_meta=False, cosmology=None):
@@ -136,18 +137,7 @@ def from_table(table, index=None, *, move_to_meta=False, cosmology=None):
# ------------------
# parse row to cosmo
- # special values
- name = row['name'] if 'name' in row.columns else None # get name from column
- meta = copy.deepcopy(row.meta)
-
- # turn row into mapping, filling cosmo if not in a column
- mapping = dict(row)
- mapping["name"] = name
- mapping.setdefault("cosmology", meta.pop("cosmology", None))
- mapping["meta"] = meta
-
- # build cosmology from map
- return from_mapping(mapping, move_to_meta=move_to_meta, cosmology=cosmology)
+ return from_row(row, move_to_meta=move_to_meta, cosmology=cosmology)
def to_table(cosmology, *args, cls=QTable, cosmology_in_meta=True):
diff --git a/docs/changes/cosmology/12313.feature.rst b/docs/changes/cosmology/12313.feature.rst
new file mode 100644
index 000000000000..fa7179584dd6
--- /dev/null
+++ b/docs/changes/cosmology/12313.feature.rst
@@ -0,0 +1,2 @@
+Register "astropy.row" into Cosmology's to/from format I/O, allowing a
+Cosmology instance to be parse from or converted to an Astropy Table Row.
diff --git a/docs/cosmology/io.rst b/docs/cosmology/io.rst
index 4dc1353ade82..4d3989e0b4d4 100644
--- a/docs/cosmology/io.rst
+++ b/docs/cosmology/io.rst
@@ -102,6 +102,7 @@ To see the a list of the available conversion formats:
Format Read Write Auto-identify
------------- ---- ----- -------------
astropy.model Yes Yes Yes
+ astropy.row Yes Yes Yes
astropy.table Yes Yes Yes
mapping Yes Yes Yes
mypackage Yes Yes Yes
@@ -249,6 +250,7 @@ class to use. Details about metadata treatment are in
... # turn row into mapping (dict of the arguments)
... mapping = dict(row)
... mapping['name'] = name
+ ... mapping.setdefault("cosmology", meta.pop("cosmology", None))
... mapping["meta"] = meta
... # build cosmology from map
... return Cosmology.from_format(mapping, move_to_meta=move_to_meta,
@@ -286,12 +288,13 @@ register everything into `astropy.io.registry`.
>>> def row_identify(origin, format, *args, **kwargs):
... """Identify if object uses the Table format."""
... if origin == "read":
- ... return isinstance(args[1], Row) and (format in (None, "row"))
+ ... return isinstance(args[1], Row) and (format in (None, "astropy.row"))
... return False
- >>> convert_registry.register_reader("row", Cosmology, from_table_row)
- >>> convert_registry.register_writer("row", Cosmology, to_table_row)
- >>> convert_registry.register_identifier("row", Cosmology, row_identify)
+ >>> # These exact functions are already registered in astropy
+ >>> # convert_registry.register_reader("astropy.row", Cosmology, from_table_row)
+ >>> # convert_registry.register_writer("astropy.row", Cosmology, to_table_row)
+ >>> # convert_registry.register_identifier("astropy.row", Cosmology, row_identify)
Now the registered functions can be used in
:meth:`astropy.cosmology.Cosmology.from_format` and
@@ -300,7 +303,7 @@ Now the registered functions can be used in
.. code-block:: python
>>> from astropy.cosmology import Planck18
- >>> row = Planck18.to_format("row")
+ >>> row = Planck18.to_format("astropy.row")
>>> row
<Row index=0>
cosmology name H0 Om0 Tcmb0 Neff m_nu [3] Ob0
@@ -313,19 +316,6 @@ Now the registered functions can be used in
>>> cosmo == Planck18 # test it round-trips
True
-
-.. doctest::
- :hide:
-
- >>> from astropy.io.registry import IORegistryError
- >>> convert_registry.unregister_reader("row", Cosmology)
- >>> convert_registry.unregister_writer("row", Cosmology)
- >>> convert_registry.unregister_identifier("row", Cosmology)
- >>> try:
- ... convert_registry.get_reader("row", Cosmology)
- ... except IORegistryError:
- ... pass
-
.. EXAMPLE END
|
diff --git a/astropy/cosmology/io/tests/test_row.py b/astropy/cosmology/io/tests/test_row.py
new file mode 100644
index 000000000000..9ad1b7f151ce
--- /dev/null
+++ b/astropy/cosmology/io/tests/test_row.py
@@ -0,0 +1,117 @@
+# Licensed under a 3-clause BSD style license - see LICENSE.rst
+
+# THIRD PARTY
+import pytest
+
+# LOCAL
+import astropy.units as u
+from astropy import cosmology
+from astropy.cosmology import Cosmology, realizations, Planck18
+from astropy.cosmology.core import _COSMOLOGY_CLASSES, Parameter
+from astropy.cosmology.io.row import from_row, to_row
+from astropy.table import Row
+from astropy.cosmology.parameters import available
+
+from .base import IOTestMixinBase, IOFormatTestBase
+
+cosmo_instances = [getattr(realizations, name) for name in available]
+cosmo_instances.append("TestToFromRow.setup.<locals>.CosmologyWithKwargs")
+
+###############################################################################
+
+
+class ToFromRowTestMixin(IOTestMixinBase):
+ """
+ Tests for a Cosmology[To/From]Format with ``format="astropy.row"``.
+ This class will not be directly called by :mod:`pytest` since its name does
+ not begin with ``Test``. To activate the contained tests this class must
+ be inherited in a subclass. Subclasses must define a :func:`pytest.fixture`
+ ``cosmo`` that returns/yields an instance of a |Cosmology|.
+ See ``TestCosmologyToFromFormat`` or ``TestCosmology`` for examples.
+ """
+
+ @pytest.mark.parametrize("in_meta", [True, False])
+ def test_to_row_in_meta(self, cosmo, in_meta):
+ """Test where the cosmology class is placed."""
+ row = cosmo.to_format('astropy.row', cosmology_in_meta=in_meta)
+
+ # if it's in metadata, it's not a column. And vice versa.
+ if in_meta:
+ assert row.meta["cosmology"] == cosmo.__class__.__qualname__
+ assert "cosmology" not in row.colnames # not also a column
+ else:
+ assert row["cosmology"] == cosmo.__class__.__qualname__
+ assert "cosmology" not in row.meta
+
+ # -----------------------
+
+ def test_tofrom_row_instance(self, cosmo, to_format, from_format):
+ """Test cosmology -> astropy.row -> cosmology."""
+ # ------------
+ # To Row
+
+ row = to_format("astropy.row")
+ assert isinstance(row, Row)
+ assert row["cosmology"] == cosmo.__class__.__qualname__
+ assert row["name"] == cosmo.name
+
+ # ------------
+ # From Row
+
+ row.table["mismatching"] = "will error"
+
+ # tests are different if the last argument is a **kwarg
+ if tuple(cosmo._init_signature.parameters.values())[-1].kind == 4:
+ got = from_format(row, format="astropy.row")
+
+ assert got.__class__ is cosmo.__class__
+ assert got.name == cosmo.name
+ assert "mismatching" not in got.meta
+
+ return # don't continue testing
+
+ # read with mismatching parameters errors
+ with pytest.raises(TypeError, match="there are unused parameters"):
+ from_format(row, format="astropy.row")
+
+ # unless mismatched are moved to meta
+ got = from_format(row, format="astropy.row", move_to_meta=True)
+ assert got == cosmo
+ assert got.meta["mismatching"] == "will error"
+
+ # it won't error if everything matches up
+ row.table.remove_column("mismatching")
+ got = from_format(row, format="astropy.row")
+ assert got == cosmo
+
+ # and it will also work if the cosmology is a class
+ # Note this is not the default output of ``to_format``.
+ cosmology = _COSMOLOGY_CLASSES[row["cosmology"]]
+ row.table.remove_column("cosmology")
+ row.table["cosmology"] = cosmology
+ got = from_format(row, format="astropy.row")
+ assert got == cosmo
+
+ # also it auto-identifies 'format'
+ got = from_format(row)
+ assert got == cosmo
+
+ def test_fromformat_row_subclass_partial_info(self, cosmo):
+ """
+ Test writing from an instance and reading from that class.
+ This works with missing information.
+ """
+ pass # there are no partial info options
+
+
+class TestToFromTable(IOFormatTestBase, ToFromRowTestMixin):
+ """
+ Directly test ``to/from_row``.
+ These are not public API and are discouraged from use, in favor of
+ ``Cosmology.to/from_format(..., format="astropy.row")``, but should be
+ tested regardless b/c 3rd party packages might use these in their Cosmology
+ I/O. Also, it's cheap to test.
+ """
+
+ def setup_class(self):
+ self.functions = {"to": to_row, "from": from_row}
diff --git a/astropy/cosmology/tests/test_connect.py b/astropy/cosmology/tests/test_connect.py
index 5407d8dea55d..ff9f78ee0d86 100644
--- a/astropy/cosmology/tests/test_connect.py
+++ b/astropy/cosmology/tests/test_connect.py
@@ -10,7 +10,7 @@
from astropy.cosmology import Cosmology, w0wzCDM
from astropy.cosmology.connect import CosmologyRead, readwrite_registry
from astropy.cosmology.core import Cosmology
-from astropy.cosmology.io.tests import test_ecsv, test_mapping, test_model, test_table
+from astropy.cosmology.io.tests import test_ecsv, test_mapping, test_model, test_row, test_table
from astropy.table import QTable
from .conftest import json_identify, read_json, write_json
@@ -205,7 +205,7 @@ def test_readwrite_reader_class_mismatch(self, cosmo, tmpdir, format):
class ToFromFormatTestMixin(
# convert
test_mapping.ToFromMappingTestMixin, test_model.ToFromModelTestMixin,
- test_table.ToFromTableTestMixin,
+ test_row.ToFromRowTestMixin, test_table.ToFromTableTestMixin,
# read/write
test_ecsv.ReadWriteECSVTestMixin,
):
|
[
{
"path": "docs/changes/cosmology/12313.feature.rst",
"old_path": "/dev/null",
"new_path": "b/docs/changes/cosmology/12313.feature.rst",
"metadata": "diff --git a/docs/changes/cosmology/12313.feature.rst b/docs/changes/cosmology/12313.feature.rst\nnew file mode 100644\nindex 000000000000..fa7179584dd6\n--- /dev/null\n+++ b/docs/changes/cosmology/12313.feature.rst\n@@ -0,0 +1,2 @@\n+Register \"astropy.row\" into Cosmology's to/from format I/O, allowing a\n+Cosmology instance to be parse from or converted to an Astropy Table Row.\n",
"update": null
},
{
"path": "docs/cosmology/io.rst",
"old_path": "a/docs/cosmology/io.rst",
"new_path": "b/docs/cosmology/io.rst",
"metadata": "diff --git a/docs/cosmology/io.rst b/docs/cosmology/io.rst\nindex 4dc1353ade82..4d3989e0b4d4 100644\n--- a/docs/cosmology/io.rst\n+++ b/docs/cosmology/io.rst\n@@ -102,6 +102,7 @@ To see the a list of the available conversion formats:\n Format Read Write Auto-identify\n ------------- ---- ----- -------------\n astropy.model Yes Yes Yes\n+ astropy.row Yes Yes Yes\n astropy.table Yes Yes Yes\n mapping Yes Yes Yes\n mypackage Yes Yes Yes\n@@ -249,6 +250,7 @@ class to use. Details about metadata treatment are in\n ... # turn row into mapping (dict of the arguments)\n ... mapping = dict(row)\n ... mapping['name'] = name\n+ ... mapping.setdefault(\"cosmology\", meta.pop(\"cosmology\", None))\n ... mapping[\"meta\"] = meta\n ... # build cosmology from map\n ... return Cosmology.from_format(mapping, move_to_meta=move_to_meta,\n@@ -286,12 +288,13 @@ register everything into `astropy.io.registry`.\n >>> def row_identify(origin, format, *args, **kwargs):\n ... \"\"\"Identify if object uses the Table format.\"\"\"\n ... if origin == \"read\":\n- ... return isinstance(args[1], Row) and (format in (None, \"row\"))\n+ ... return isinstance(args[1], Row) and (format in (None, \"astropy.row\"))\n ... return False\n \n- >>> convert_registry.register_reader(\"row\", Cosmology, from_table_row)\n- >>> convert_registry.register_writer(\"row\", Cosmology, to_table_row)\n- >>> convert_registry.register_identifier(\"row\", Cosmology, row_identify)\n+ >>> # These exact functions are already registered in astropy\n+ >>> # convert_registry.register_reader(\"astropy.row\", Cosmology, from_table_row)\n+ >>> # convert_registry.register_writer(\"astropy.row\", Cosmology, to_table_row)\n+ >>> # convert_registry.register_identifier(\"astropy.row\", Cosmology, row_identify)\n \n Now the registered functions can be used in\n :meth:`astropy.cosmology.Cosmology.from_format` and\n@@ -300,7 +303,7 @@ Now the registered functions can be used in\n .. code-block:: python\n \n >>> from astropy.cosmology import Planck18\n- >>> row = Planck18.to_format(\"row\")\n+ >>> row = Planck18.to_format(\"astropy.row\")\n >>> row\n <Row index=0>\n cosmology name H0 Om0 Tcmb0 Neff m_nu [3] Ob0\n@@ -313,19 +316,6 @@ Now the registered functions can be used in\n >>> cosmo == Planck18 # test it round-trips\n True\n \n-\n-.. doctest::\n- :hide:\n-\n- >>> from astropy.io.registry import IORegistryError\n- >>> convert_registry.unregister_reader(\"row\", Cosmology)\n- >>> convert_registry.unregister_writer(\"row\", Cosmology)\n- >>> convert_registry.unregister_identifier(\"row\", Cosmology)\n- >>> try:\n- ... convert_registry.get_reader(\"row\", Cosmology)\n- ... except IORegistryError:\n- ... pass\n-\n .. EXAMPLE END\n \n \n",
"update": null
}
] |
5.1
|
546219ca17648b763e2a8632a29a410f49e81340
|
[] |
[
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_ecsv_bad_index[Planck18_arXiv_v2]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_table_cls[WMAP5-Table]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_table_cls[WMAP3-Table]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_fromformat_row_subclass_partial_info[WMAP1]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyReadWrite::test_readwrite_reader_class_mismatch[WMAP7-json]",
"astropy/cosmology/io/tests/test_row.py::TestToFromTable::test_fromformat_row_subclass_partial_info[cosmo2]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_fromformat_ecsv_subclass_partial_info[Planck15]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_fromformat_class_mismatch[WMAP5-format_type1]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofrom_mapping_instance[WMAP5]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_fromformat_subclass_complete_info[WMAP3-format_type0]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_mapping_cls[WMAP7-OrderedDict]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_fromformat_class_mismatch[WMAP3-format_type1]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofromformat_complete_info[WMAP3-format_type1]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofrom_ecsv_instance[WMAP3]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofromformat_complete_info[WMAP9-format_type0]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_ecsv_in_meta[WMAP9-True]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyReadWrite::test_readwrite_from_subclass_partial_info[WMAP5]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_mapping_cls[WMAP5-OrderedDict]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_ecsv_cls[WMAP1-Table]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_failed_cls_to_mapping[Planck15]",
"astropy/cosmology/io/tests/test_row.py::TestToFromTable::test_to_row_in_meta[cosmo3-False]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_fromformat_row_subclass_partial_info[Planck13]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofrom_table_mutlirow[Planck13-True]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_toformat_model_not_method[WMAP9]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_toformat_model[WMAP3]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofromformat_model_instance[WMAP9]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_ecsv_cls[Planck18-QTable]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofrom_table_mutlirow[Planck15-True]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofrom_table_mutlirow[WMAP3-False]",
"astropy/cosmology/io/tests/test_row.py::TestToFromTable::test_fromformat_row_subclass_partial_info[cosmo0]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyReadWrite::test_readwrite_complete_info[WMAP7-json]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_mapping_cls[Planck18_arXiv_v2-OrderedDict]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_fromformat_subclass_partial_info_mapping[WMAP1]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofrom_mapping_instance[Planck15]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_row_in_meta[WMAP3-False]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyReadWrite::test_readwrite_from_subclass_partial_info[WMAP1]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_fromformat_row_subclass_partial_info[Planck18]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_ecsv_cls[WMAP9-QTable]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_table_failed_cls[WMAP3]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_table_failed_cls[Planck15]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_table_cls[WMAP5-QTable]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_fromformat_subclass_partial_info_mapping[WMAP9]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_toformat_model_not_callable[WMAP7]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofrom_ecsv_mutlirow[WMAP1]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_table_in_meta[WMAP5-True]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_fromformat_class_mismatch[Planck15-format_type1]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyReadWrite::test_readwrite_from_subclass_complete_info[WMAP3-json]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_mapping_cls[WMAP9-dict]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_toformat_model_not_method[Planck13]",
"astropy/cosmology/io/tests/test_row.py::TestToFromTable::test_to_row_in_meta[cosmo2-True]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofrom_ecsv_mutlirow[Planck18_arXiv_v2]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofromformat_complete_info[Planck15-format_type0]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofrom_mapping_instance[Planck18_arXiv_v2]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_fromformat_row_subclass_partial_info[WMAP9]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_table_bad_index[Planck18]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_toformat_model_not_method[WMAP5]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_table_cls[Planck18-QTable]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyReadWrite::test_readwrite_from_subclass_complete_info[WMAP9-json]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_table_cls[WMAP7-QTable]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_toformat_model[WMAP5]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_table_cls[WMAP7-Table]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_ecsv_in_meta[WMAP7-False]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_table_failed_cls[Planck13]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_fromformat_row_subclass_partial_info[WMAP5]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_fromformat_row_subclass_partial_info[WMAP7]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofrom_table_instance[WMAP9]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyReadWrite::test_readwrite_complete_info[WMAP3-json]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_ecsv_failed_cls[Planck18]",
"astropy/cosmology/io/tests/test_row.py::TestToFromTable::test_to_row_in_meta[cosmo0-False]",
"astropy/cosmology/io/tests/test_row.py::TestToFromTable::test_tofrom_row_instance[cosmo2]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofrom_mapping_instance[WMAP3]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_fromformat_class_mismatch[WMAP5-format_type0]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_table_in_meta[Planck13-False]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyReadWrite::test_readwrite_complete_info[WMAP5-json]",
"astropy/cosmology/io/tests/test_row.py::TestToFromTable::test_tofrom_row_instance[cosmo1]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_fromformat_subclass_complete_info[Planck18_arXiv_v2-format_type0]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_fromformat_subclass_complete_info[Planck15-format_type0]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofrom_row_instance[WMAP7]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofrom_ecsv_mutlirow[WMAP9]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofrom_ecsv_mutlirow[Planck18]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_table_in_meta[WMAP7-False]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_fromformat_class_mismatch[Planck18_arXiv_v2-format_type0]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofrom_row_instance[WMAP3]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_failed_cls_to_mapping[WMAP3]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_row_in_meta[WMAP5-False]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_ecsv_in_meta[WMAP1-False]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_ecsv_in_meta[Planck15-False]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofrom_row_instance[Planck18_arXiv_v2]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyReadWrite::test_readwrite_from_subclass_partial_info[Planck18]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofrom_table_instance[WMAP3]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyReadWrite::test_readwrite_from_subclass_partial_info[Planck15]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_ecsv_cls[WMAP5-QTable]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_table_cls[Planck18_arXiv_v2-Table]",
"astropy/cosmology/io/tests/test_row.py::TestToFromTable::test_to_row_in_meta[cosmo3-True]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_row_in_meta[Planck18-True]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofrom_row_instance[Planck18]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyReadWrite::test_readwrite_reader_class_mismatch[WMAP3-json]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_ecsv_in_meta[WMAP3-False]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_ecsv_cls[WMAP5-Table]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_fromformat_subclass_complete_info[Planck18-format_type0]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofrom_table_mutlirow[WMAP7-False]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_table_in_meta[Planck18_arXiv_v2-True]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofrom_row_instance[WMAP9]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofromformat_complete_info[Planck13-format_type0]",
"astropy/cosmology/io/tests/test_row.py::TestToFromTable::test_to_row_in_meta[cosmo8-True]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_toformat_model_not_method[WMAP1]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_row_in_meta[Planck13-False]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyReadWrite::test_readwrite_reader_class_mismatch[Planck18_arXiv_v2-json]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_table_cls[WMAP9-Table]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_fromformat_class_mismatch[WMAP1-format_type1]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_ecsv_in_meta[WMAP9-False]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_table_failed_cls[WMAP5]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofrom_row_instance[WMAP1]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_fromformat_subclass_complete_info[WMAP3-format_type1]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_ecsv_cls[Planck18-Table]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_table_in_meta[Planck18-True]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofromformat_model_instance[Planck13]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofrom_table_mutlirow[WMAP1-False]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofromformat_complete_info[Planck18_arXiv_v2-format_type0]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyReadWrite::test_readwrite_reader_class_mismatch[Planck18-json]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_ecsv_cls[Planck13-Table]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_ecsv_in_meta[WMAP5-False]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_fromformat_subclass_complete_info[Planck18-format_type1]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofrom_table_mutlirow[Planck13-False]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_mapping_cls[Planck18-OrderedDict]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_fromformat_row_subclass_partial_info[Planck15]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_ecsv_cls[WMAP1-QTable]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofrom_ecsv_instance[WMAP7]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_fromformat_subclass_partial_info_mapping[Planck18]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_toformat_model[WMAP1]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_fromformat_subclass_complete_info[WMAP1-format_type1]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_row_in_meta[Planck18-False]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofrom_table_instance[Planck18]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_toformat_model_not_method[Planck15]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_ecsv_failed_cls[WMAP3]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_row_in_meta[WMAP1-True]",
"astropy/cosmology/io/tests/test_row.py::TestToFromTable::test_fromformat_row_subclass_partial_info[cosmo8]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyReadWrite::test_readwrite_reader_class_mismatch[Planck15-json]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofrom_table_instance[Planck18_arXiv_v2]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_toformat_model_not_callable[WMAP9]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_ecsv_failed_cls[WMAP1]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyReadWrite::test_readwrite_reader_class_mismatch[Planck13-json]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_fromformat_subclass_partial_info_mapping[Planck18_arXiv_v2]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofrom_table_mutlirow[Planck18_arXiv_v2-False]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofrom_table_mutlirow[WMAP3-True]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_table_in_meta[Planck13-True]",
"astropy/cosmology/io/tests/test_row.py::TestToFromTable::test_to_row_in_meta[cosmo0-True]",
"astropy/cosmology/io/tests/test_row.py::TestToFromTable::test_fromformat_row_subclass_partial_info[cosmo4]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_table_cls[Planck18-Table]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_failed_cls_to_mapping[WMAP1]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_row_in_meta[WMAP9-True]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofrom_table_mutlirow[Planck18_arXiv_v2-True]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_fromformat_class_mismatch[Planck15-format_type0]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofromformat_complete_info[WMAP1-format_type1]",
"astropy/cosmology/io/tests/test_row.py::TestToFromTable::test_to_row_in_meta[cosmo8-False]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_ecsv_cls[WMAP9-Table]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofrom_row_instance[WMAP5]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyReadWrite::test_readwrite_complete_info[Planck13-json]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyReadWrite::test_readwrite_complete_info[Planck15-json]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyReadWrite::test_readwrite_from_subclass_complete_info[WMAP5-json]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_failed_cls_to_mapping[Planck18_arXiv_v2]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_failed_cls_to_mapping[Planck13]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_fromformat_table_subclass_partial_info[Planck13]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_table_bad_index[WMAP1]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofrom_table_mutlirow[WMAP1-True]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_ecsv_cls[Planck18_arXiv_v2-QTable]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_ecsv_bad_index[Planck15]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofrom_table_instance[WMAP1]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_table_in_meta[Planck18-False]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_table_in_meta[WMAP1-False]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofromformat_complete_info[WMAP7-format_type1]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_table_in_meta[WMAP3-True]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofrom_ecsv_mutlirow[Planck15]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_fromformat_subclass_complete_info[WMAP7-format_type1]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofromformat_model_instance[Planck18_arXiv_v2]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofrom_table_instance[Planck13]",
"astropy/cosmology/io/tests/test_row.py::TestToFromTable::test_fromformat_row_subclass_partial_info[cosmo3]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyReadWrite::test_readwrite_complete_info[Planck18_arXiv_v2-json]",
"astropy/cosmology/io/tests/test_row.py::TestToFromTable::test_tofrom_row_instance[cosmo0]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofrom_table_mutlirow[Planck18-False]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofromformat_complete_info[Planck18_arXiv_v2-format_type1]",
"astropy/cosmology/io/tests/test_row.py::TestToFromTable::test_tofrom_row_instance[cosmo7]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_table_in_meta[WMAP3-False]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofrom_table_mutlirow[WMAP7-True]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyReadWrite::test_readwrite_from_subclass_partial_info[WMAP3]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_fromformat_subclass_complete_info[Planck18_arXiv_v2-format_type1]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_row_in_meta[WMAP7-False]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_mapping_cls[WMAP3-OrderedDict]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_table_in_meta[WMAP9-True]",
"astropy/cosmology/io/tests/test_row.py::TestToFromTable::test_to_row_in_meta[cosmo6-False]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_mapping_cls[WMAP9-OrderedDict]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_row_in_meta[WMAP5-True]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_mapping_cls[Planck13-dict]",
"astropy/cosmology/io/tests/test_row.py::TestToFromTable::test_to_row_in_meta[cosmo5-False]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_toformat_model_not_callable[WMAP5]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_fromformat_model_wrong_cls",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofromformat_complete_info[WMAP9-format_type1]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofrom_ecsv_mutlirow[WMAP5]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofrom_row_instance[Planck13]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofromformat_model_instance[WMAP1]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_fromformat_ecsv_subclass_partial_info[WMAP3]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofrom_table_mutlirow[WMAP9-False]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyReadWrite::test_readwrite_from_subclass_complete_info[Planck13-json]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_fromformat_ecsv_subclass_partial_info[WMAP5]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofrom_ecsv_mutlirow[Planck13]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofrom_table_instance[Planck15]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyReadWrite::test_readwrite_complete_info[WMAP1-json]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofrom_ecsv_mutlirow[WMAP7]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_toformat_model[WMAP7]",
"astropy/cosmology/io/tests/test_row.py::TestToFromTable::test_tofrom_row_instance[cosmo5]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_mapping_cls[Planck15-dict]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyReadWrite::test_readwrite_from_subclass_complete_info[Planck15-json]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_fromformat_class_mismatch[Planck13-format_type1]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_toformat_model_not_callable[Planck15]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_mapping_cls[Planck18-dict]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_fromformat_table_subclass_partial_info[WMAP9]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofrom_mapping_instance[WMAP9]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_ecsv_in_meta[Planck13-True]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_table_in_meta[WMAP5-False]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_toformat_model_not_method[WMAP7]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_table_bad_index[Planck13]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofrom_table_mutlirow[Planck15-False]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_row_in_meta[Planck15-True]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_ecsv_in_meta[Planck18_arXiv_v2-False]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_fromformat_subclass_complete_info[WMAP1-format_type0]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_table_failed_cls[WMAP9]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_fromformat_model_subclass_partial_info",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_fromformat_subclass_complete_info[WMAP9-format_type1]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofrom_ecsv_instance[Planck15]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_toformat_model[WMAP9]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofromformat_complete_info[WMAP5-format_type0]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyReadWrite::test_readwrite_from_subclass_partial_info[Planck13]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_fromformat_class_mismatch[WMAP7-format_type1]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_ecsv_cls[WMAP7-Table]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_fromformat_table_subclass_partial_info[Planck18_arXiv_v2]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_row_in_meta[WMAP3-True]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_toformat_model[Planck18_arXiv_v2]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_ecsv_cls[Planck18_arXiv_v2-Table]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_ecsv_failed_cls[WMAP7]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyReadWrite::test_readwrite_from_subclass_partial_info[Planck18_arXiv_v2]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_fromformat_row_subclass_partial_info[Planck18_arXiv_v2]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_table_bad_index[Planck15]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_ecsv_bad_index[Planck18]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_fromformat_class_mismatch[Planck18-format_type0]",
"astropy/cosmology/io/tests/test_row.py::TestToFromTable::test_tofrom_row_instance[cosmo8]",
"astropy/cosmology/io/tests/test_row.py::TestToFromTable::test_fromformat_row_subclass_partial_info[cosmo7]",
"astropy/cosmology/io/tests/test_row.py::TestToFromTable::test_to_row_in_meta[cosmo7-False]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_fromformat_table_subclass_partial_info[WMAP5]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofromformat_model_instance[WMAP3]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_fromformat_subclass_partial_info_mapping[WMAP3]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_fromformat_subclass_complete_info[WMAP7-format_type0]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_mapping_cls[WMAP7-dict]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_toformat_model[Planck13]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_ecsv_cls[Planck15-QTable]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_table_bad_index[WMAP5]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofromformat_complete_info[Planck18-format_type1]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_table_bad_index[WMAP9]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_toformat_model_not_callable[Planck18_arXiv_v2]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_ecsv_in_meta[WMAP7-True]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofrom_table_instance[WMAP5]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_row_in_meta[Planck15-False]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyReadWrite::test_readwrite_from_subclass_complete_info[WMAP1-json]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_mapping_cls[WMAP1-OrderedDict]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_ecsv_failed_cls[WMAP9]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_fromformat_ecsv_subclass_partial_info[Planck13]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyReadWrite::test_readwrite_reader_class_mismatch[WMAP9-json]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_failed_cls_to_mapping[WMAP9]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_fromformat_table_subclass_partial_info[WMAP7]",
"astropy/cosmology/io/tests/test_row.py::TestToFromTable::test_to_row_in_meta[cosmo1-True]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_fromformat_table_subclass_partial_info[Planck18]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_ecsv_in_meta[WMAP3-True]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_ecsv_in_meta[WMAP1-True]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_fromformat_subclass_partial_info_mapping[WMAP5]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_toformat_model_not_callable[WMAP1]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_fromformat_class_mismatch[Planck18_arXiv_v2-format_type1]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_toformat_model_not_method[Planck18]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofromformat_complete_info[Planck15-format_type1]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_ecsv_bad_index[Planck13]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_ecsv_bad_index[WMAP7]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofrom_row_instance[Planck15]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_fromformat_class_mismatch[WMAP1-format_type0]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_table_cls[WMAP3-QTable]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_table_in_meta[WMAP1-True]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_ecsv_bad_index[WMAP1]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_toformat_model_not_method[WMAP3]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_failed_cls_to_mapping[WMAP7]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_table_bad_index[Planck18_arXiv_v2]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_toformat_model_not_callable[Planck13]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyReadWrite::test_readwrite_from_subclass_partial_info[WMAP7]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyReadWrite::test_readwrite_from_subclass_complete_info[Planck18_arXiv_v2-json]",
"astropy/cosmology/io/tests/test_row.py::TestToFromTable::test_to_row_in_meta[cosmo1-False]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofrom_table_mutlirow[Planck18-True]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_fromformat_subclass_partial_info_mapping[Planck13]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_row_in_meta[Planck18_arXiv_v2-True]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofrom_ecsv_instance[Planck18_arXiv_v2]",
"astropy/cosmology/io/tests/test_row.py::TestToFromTable::test_to_row_in_meta[cosmo5-True]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_fromformat_class_mismatch[Planck13-format_type0]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_mapping_cls[WMAP3-dict]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_table_cls[Planck18_arXiv_v2-QTable]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_mapping_cls[Planck15-OrderedDict]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_mapping_cls[WMAP1-dict]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofrom_table_mutlirow[WMAP9-True]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_ecsv_failed_cls[Planck18_arXiv_v2]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_ecsv_cls[Planck13-QTable]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofrom_mapping_instance[WMAP1]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_toformat_model[Planck18]",
"astropy/cosmology/io/tests/test_row.py::TestToFromTable::test_fromformat_row_subclass_partial_info[cosmo1]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_mapping_cls[WMAP5-dict]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_fromformat_subclass_complete_info[WMAP5-format_type0]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_table_in_meta[WMAP9-False]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_table_cls[WMAP1-Table]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_table_cls[WMAP1-QTable]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofromformat_complete_info[WMAP5-format_type1]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_fromformat_table_subclass_partial_info[Planck15]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_ecsv_in_meta[Planck18-False]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_failed_cls_to_mapping[Planck18]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_row_in_meta[Planck18_arXiv_v2-False]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_table_bad_index[WMAP7]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyReadWrite::test_readwrite_complete_info[Planck18-json]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyReadWrite::test_readwrite_complete_info[WMAP9-json]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofrom_table_mutlirow[WMAP5-True]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_fromformat_subclass_complete_info[WMAP5-format_type1]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_row_in_meta[WMAP9-False]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_table_cls[Planck13-Table]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_ecsv_cls[WMAP3-QTable]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyReadWrite::test_readwrite_from_subclass_complete_info[WMAP7-json]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_failed_cls_to_mapping[WMAP5]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofrom_ecsv_instance[WMAP5]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_ecsv_bad_index[WMAP3]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_fromformat_subclass_complete_info[Planck13-format_type0]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_table_failed_cls[WMAP1]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_table_cls[Planck15-Table]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_table_failed_cls[WMAP7]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_table_cls[Planck13-QTable]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_row_in_meta[WMAP7-True]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_fromformat_ecsv_subclass_partial_info[Planck18]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofrom_mapping_instance[WMAP7]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_fromformat_ecsv_subclass_partial_info[WMAP9]",
"astropy/cosmology/io/tests/test_row.py::TestToFromTable::test_fromformat_row_subclass_partial_info[cosmo6]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_ecsv_bad_index[WMAP5]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_fromformat_ecsv_subclass_partial_info[WMAP7]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofromformat_complete_info[WMAP3-format_type0]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_fromformat_ecsv_subclass_partial_info[Planck18_arXiv_v2]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_fromformat_table_subclass_partial_info[WMAP1]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_row_in_meta[WMAP1-False]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_fromformat_table_subclass_partial_info[WMAP3]",
"astropy/cosmology/io/tests/test_row.py::TestToFromTable::test_to_row_in_meta[cosmo4-False]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_row_in_meta[Planck13-True]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofrom_ecsv_mutlirow[WMAP3]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_table_cls[Planck15-QTable]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_table_failed_cls[Planck18]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofrom_ecsv_instance[WMAP9]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_fromformat_subclass_partial_info_mapping[Planck15]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_ecsv_cls[WMAP3-Table]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofrom_table_mutlirow[WMAP5-False]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofromformat_complete_info[WMAP1-format_type0]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_fromformat_class_mismatch[WMAP9-format_type1]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_ecsv_cls[Planck15-Table]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_table_in_meta[Planck15-True]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_fromformat_class_mismatch[WMAP3-format_type0]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_mapping_cls[Planck18_arXiv_v2-dict]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyReadWrite::test_readwrite_from_subclass_partial_info[WMAP9]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_ecsv_in_meta[Planck15-True]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_fromformat_subclass_complete_info[Planck15-format_type1]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofromformat_model_instance[WMAP7]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_ecsv_in_meta[Planck18-True]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofrom_mapping_instance[Planck18]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofrom_ecsv_instance[Planck13]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_ecsv_cls[WMAP7-QTable]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_fromformat_class_mismatch[WMAP7-format_type0]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyReadWrite::test_write_methods_have_explicit_kwarg_overwrite[json]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_table_in_meta[Planck18_arXiv_v2-False]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofrom_table_instance[WMAP7]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_fromformat_class_mismatch[Planck18-format_type1]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_ecsv_failed_cls[Planck15]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_table_in_meta[Planck15-False]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_table_bad_index[WMAP3]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofrom_ecsv_instance[WMAP1]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_toformat_model_not_method[Planck18_arXiv_v2]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofromformat_complete_info[Planck13-format_type1]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_fromformat_row_subclass_partial_info[WMAP3]",
"astropy/cosmology/io/tests/test_row.py::TestToFromTable::test_fromformat_row_subclass_partial_info[cosmo5]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_fromformat_subclass_partial_info_mapping[WMAP7]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofromformat_model_instance[Planck18]",
"astropy/cosmology/io/tests/test_row.py::TestToFromTable::test_to_row_in_meta[cosmo2-False]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_fromformat_subclass_complete_info[Planck13-format_type1]",
"astropy/cosmology/io/tests/test_row.py::TestToFromTable::test_to_row_in_meta[cosmo7-True]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_ecsv_failed_cls[WMAP5]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyReadWrite::test_readwrite_from_subclass_complete_info[Planck18-json]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_toformat_model_not_callable[Planck18]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofrom_mapping_instance[Planck13]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyReadWrite::test_readwrite_reader_class_mismatch[WMAP5-json]",
"astropy/cosmology/io/tests/test_row.py::TestToFromTable::test_tofrom_row_instance[cosmo4]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofromformat_complete_info[Planck18-format_type0]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofrom_ecsv_instance[Planck18]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_toformat_model[Planck15]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_table_cls[WMAP9-QTable]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_ecsv_failed_cls[Planck13]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_fromformat_class_mismatch[WMAP9-format_type0]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_table_failed_cls[Planck18_arXiv_v2]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_ecsv_in_meta[Planck13-False]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_fromformat_ecsv_subclass_partial_info[WMAP1]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofromformat_complete_info[WMAP7-format_type0]",
"astropy/cosmology/io/tests/test_row.py::TestToFromTable::test_tofrom_row_instance[cosmo6]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofromformat_model_instance[Planck15]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_toformat_model_not_callable[WMAP3]",
"astropy/cosmology/io/tests/test_row.py::TestToFromTable::test_tofrom_row_instance[cosmo3]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyReadWrite::test_readwrite_reader_class_mismatch[WMAP1-json]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_ecsv_in_meta[Planck18_arXiv_v2-True]",
"astropy/cosmology/io/tests/test_row.py::TestToFromTable::test_to_row_in_meta[cosmo6-True]",
"astropy/cosmology/io/tests/test_row.py::TestToFromTable::test_to_row_in_meta[cosmo4-True]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_fromformat_subclass_complete_info[WMAP9-format_type0]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_ecsv_in_meta[WMAP5-True]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_ecsv_bad_index[WMAP9]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_tofromformat_model_instance[WMAP5]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_mapping_cls[Planck13-OrderedDict]",
"astropy/cosmology/tests/test_connect.py::TestCosmologyToFromFormat::test_to_table_in_meta[WMAP7-True]"
] |
[
{
"path": "docs/changes/cosmology/#####.feature.rst",
"old_path": "/dev/null",
"new_path": "b/docs/changes/cosmology/#####.feature.rst",
"metadata": "diff --git a/docs/changes/cosmology/#####.feature.rst b/docs/changes/cosmology/#####.feature.rst\nnew file mode 100644\nindex 0000000000..fa7179584d\n--- /dev/null\n+++ b/docs/changes/cosmology/#####.feature.rst\n@@ -0,0 +1,2 @@\n+Register \"astropy.row\" into Cosmology's to/from format I/O, allowing a\n+Cosmology instance to be parse from or converted to an Astropy Table Row.\n"
},
{
"path": "docs/cosmology/io.rst",
"old_path": "a/docs/cosmology/io.rst",
"new_path": "b/docs/cosmology/io.rst",
"metadata": "diff --git a/docs/cosmology/io.rst b/docs/cosmology/io.rst\nindex 4dc1353ade..4d3989e0b4 100644\n--- a/docs/cosmology/io.rst\n+++ b/docs/cosmology/io.rst\n@@ -102,6 +102,7 @@ To see the a list of the available conversion formats:\n Format Read Write Auto-identify\n ------------- ---- ----- -------------\n astropy.model Yes Yes Yes\n+ astropy.row Yes Yes Yes\n astropy.table Yes Yes Yes\n mapping Yes Yes Yes\n mypackage Yes Yes Yes\n@@ -249,6 +250,7 @@ class to use. Details about metadata treatment are in\n ... # turn row into mapping (dict of the arguments)\n ... mapping = dict(row)\n ... mapping['name'] = name\n+ ... mapping.setdefault(\"cosmology\", meta.pop(\"cosmology\", None))\n ... mapping[\"meta\"] = meta\n ... # build cosmology from map\n ... return Cosmology.from_format(mapping, move_to_meta=move_to_meta,\n@@ -286,12 +288,13 @@ register everything into `astropy.io.registry`.\n >>> def row_identify(origin, format, *args, **kwargs):\n ... \"\"\"Identify if object uses the Table format.\"\"\"\n ... if origin == \"read\":\n- ... return isinstance(args[1], Row) and (format in (None, \"row\"))\n+ ... return isinstance(args[1], Row) and (format in (None, \"astropy.row\"))\n ... return False\n \n- >>> convert_registry.register_reader(\"row\", Cosmology, from_table_row)\n- >>> convert_registry.register_writer(\"row\", Cosmology, to_table_row)\n- >>> convert_registry.register_identifier(\"row\", Cosmology, row_identify)\n+ >>> # These exact functions are already registered in astropy\n+ >>> # convert_registry.register_reader(\"astropy.row\", Cosmology, from_table_row)\n+ >>> # convert_registry.register_writer(\"astropy.row\", Cosmology, to_table_row)\n+ >>> # convert_registry.register_identifier(\"astropy.row\", Cosmology, row_identify)\n \n Now the registered functions can be used in\n :meth:`astropy.cosmology.Cosmology.from_format` and\n@@ -300,7 +303,7 @@ Now the registered functions can be used in\n .. code-block:: python\n \n >>> from astropy.cosmology import Planck18\n- >>> row = Planck18.to_format(\"row\")\n+ >>> row = Planck18.to_format(\"astropy.row\")\n >>> row\n <Row index=0>\n cosmology name H0 Om0 Tcmb0 Neff m_nu [3] Ob0\n@@ -313,19 +316,6 @@ Now the registered functions can be used in\n >>> cosmo == Planck18 # test it round-trips\n True\n \n-\n-.. doctest::\n- :hide:\n-\n- >>> from astropy.io.registry import IORegistryError\n- >>> convert_registry.unregister_reader(\"row\", Cosmology)\n- >>> convert_registry.unregister_writer(\"row\", Cosmology)\n- >>> convert_registry.unregister_identifier(\"row\", Cosmology)\n- >>> try:\n- ... convert_registry.get_reader(\"row\", Cosmology)\n- ... except IORegistryError:\n- ... pass\n-\n .. EXAMPLE END\n \n \n"
}
] |
{
"header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:",
"data": [
{
"type": "field",
"name": "to_row"
},
{
"type": "file",
"name": "astropy/cosmology/io/row.py"
},
{
"type": "field",
"name": "cosmology_in_meta"
},
{
"type": "function",
"name": "to_row"
},
{
"type": "field",
"name": "from_row"
},
{
"type": "function",
"name": "from_row"
},
{
"type": "field",
"name": "from_row"
},
{
"type": "field",
"name": "core"
}
]
}
|
diff --git a/docs/changes/cosmology/#####.feature.rst b/docs/changes/cosmology/#####.feature.rst
new file mode 100644
index 0000000000..fa7179584d
--- /dev/null
+++ b/docs/changes/cosmology/#####.feature.rst
@@ -0,0 +1,2 @@
+Register "astropy.row" into Cosmology's to/from format I/O, allowing a
+Cosmology instance to be parse from or converted to an Astropy Table Row.
diff --git a/docs/cosmology/io.rst b/docs/cosmology/io.rst
index 4dc1353ade..4d3989e0b4 100644
--- a/docs/cosmology/io.rst
+++ b/docs/cosmology/io.rst
@@ -102,6 +102,7 @@ To see the a list of the available conversion formats:
Format Read Write Auto-identify
------------- ---- ----- -------------
astropy.model Yes Yes Yes
+ astropy.row Yes Yes Yes
astropy.table Yes Yes Yes
mapping Yes Yes Yes
mypackage Yes Yes Yes
@@ -249,6 +250,7 @@ class to use. Details about metadata treatment are in
... # turn row into mapping (dict of the arguments)
... mapping = dict(row)
... mapping['name'] = name
+ ... mapping.setdefault("cosmology", meta.pop("cosmology", None))
... mapping["meta"] = meta
... # build cosmology from map
... return Cosmology.from_format(mapping, move_to_meta=move_to_meta,
@@ -286,12 +288,13 @@ register everything into `astropy.io.registry`.
>>> def row_identify(origin, format, *args, **kwargs):
... """Identify if object uses the Table format."""
... if origin == "read":
- ... return isinstance(args[1], Row) and (format in (None, "row"))
+ ... return isinstance(args[1], Row) and (format in (None, "astropy.row"))
... return False
- >>> convert_registry.register_reader("row", Cosmology, from_table_row)
- >>> convert_registry.register_writer("row", Cosmology, to_table_row)
- >>> convert_registry.register_identifier("row", Cosmology, row_identify)
+ >>> # These exact functions are already registered in astropy
+ >>> # convert_registry.register_reader("astropy.row", Cosmology, from_table_row)
+ >>> # convert_registry.register_writer("astropy.row", Cosmology, to_table_row)
+ >>> # convert_registry.register_identifier("astropy.row", Cosmology, row_identify)
Now the registered functions can be used in
:meth:`astropy.cosmology.Cosmology.from_format` and
@@ -300,7 +303,7 @@ Now the registered functions can be used in
.. code-block:: python
>>> from astropy.cosmology import Planck18
- >>> row = Planck18.to_format("row")
+ >>> row = Planck18.to_format("astropy.row")
>>> row
<Row index=0>
cosmology name H0 Om0 Tcmb0 Neff m_nu [3] Ob0
@@ -313,19 +316,6 @@ Now the registered functions can be used in
>>> cosmo == Planck18 # test it round-trips
True
-
-.. doctest::
- :hide:
-
- >>> from astropy.io.registry import IORegistryError
- >>> convert_registry.unregister_reader("row", Cosmology)
- >>> convert_registry.unregister_writer("row", Cosmology)
- >>> convert_registry.unregister_identifier("row", Cosmology)
- >>> try:
- ... convert_registry.get_reader("row", Cosmology)
- ... except IORegistryError:
- ... pass
-
.. EXAMPLE END
If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:
[{'type': 'field', 'name': 'to_row'}, {'type': 'file', 'name': 'astropy/cosmology/io/row.py'}, {'type': 'field', 'name': 'cosmology_in_meta'}, {'type': 'function', 'name': 'to_row'}, {'type': 'field', 'name': 'from_row'}, {'type': 'function', 'name': 'from_row'}, {'type': 'field', 'name': 'from_row'}, {'type': 'field', 'name': 'core'}]
|
astropy/astropy
|
astropy__astropy-12479
|
https://github.com/astropy/astropy/pull/12479
|
diff --git a/astropy/cosmology/flrw.py b/astropy/cosmology/flrw.py
index a36c150ae34c..0ca7b1300cd6 100644
--- a/astropy/cosmology/flrw.py
+++ b/astropy/cosmology/flrw.py
@@ -1420,8 +1420,7 @@ class FlatFLRWMixin(FlatCosmologyMixin):
but ``FlatLambdaCDM`` **will** be flat.
"""
- Ode0 = Parameter(doc="Omega dark energy; dark energy density/critical density at z=0.",
- derived=True, fvalidate="float") # no longer a Parameter
+ Ode0 = FLRW.Ode0.clone(derived=True) # same as FLRW, but now a derived param.
def __init_subclass__(cls):
super().__init_subclass__()
diff --git a/astropy/cosmology/parameter.py b/astropy/cosmology/parameter.py
index 56475f3e3978..49a27ec4d77e 100644
--- a/astropy/cosmology/parameter.py
+++ b/astropy/cosmology/parameter.py
@@ -13,31 +13,31 @@ class Parameter:
Parameters
----------
- fvalidate : callable[[object, object, Any], Any] or str, optional
+ 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`.
- doc : str or None, optional
- Parameter description.
- 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.
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
- 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}`).
+ doc : str or None (optional, keyword-only)
+ Parameter description.
Examples
--------
@@ -46,9 +46,24 @@ class Parameter:
_registry_validators = {}
- def __init__(self, fvalidate="default", doc=None, *,
- unit=None, equivalencies=[], fmt=".3g", derived=False):
- # parse registered fvalidate
+ def __init__(self, *, derived=False, unit=None, equivalencies=[],
+ fvalidate="default", fmt=".3g", doc=None):
+
+ # attribute name on container cosmology class.
+ # really set in __set_name__, but if Parameter is not init'ed as a
+ # descriptor this ensures that the attributes exist.
+ self._attr_name = self._attr_name_private = None
+
+ self._derived = derived
+ self._fmt = str(fmt) # @property is `format_spec`
+ self.__doc__ = doc
+
+ # units stuff
+ self._unit = u.Unit(unit) if unit is not None else None
+ self._equivalencies = equivalencies
+
+ # Parse registered `fvalidate`
+ self._fvalidate_in = fvalidate # Always store input fvalidate.
if callable(fvalidate):
pass
elif fvalidate in self._registry_validators:
@@ -59,20 +74,10 @@ def __init__(self, fvalidate="default", doc=None, *,
else:
raise TypeError("`fvalidate` must be a function or "
f"{self._registry_validators.keys()}")
-
- self.__doc__ = doc
self._fvalidate = fvalidate
- # units stuff
- self._unit = u.Unit(unit) if unit is not None else None
- self._equivalencies = equivalencies
-
- # misc
- self._fmt = str(fmt)
- self._derived = derived
-
def __set_name__(self, cosmo_cls, name):
- # attribute name
+ # attribute name on container cosmology class
self._attr_name = name
self._attr_name_private = "_" + name
@@ -142,11 +147,7 @@ def validator(self, fvalidate):
`~astropy.cosmology.Parameter`
Copy of this Parameter but with custom ``fvalidate``.
"""
- desc = type(self)(fvalidate=fvalidate,
- doc=self.__doc__, fmt=self.format_spec,
- unit=self.unit, equivalencies=self.equivalencies,
- derived=self.derived)
- return desc
+ return self.clone(fvalidate=fvalidate)
def validate(self, cosmology, value):
"""Run the validator on this Parameter.
@@ -210,8 +211,100 @@ def register(fvalidate):
# -------------------------------------------
+ def _get_init_arguments(self, processed=False):
+ """Initialization arguments.
+
+ Parameters
+ ----------
+ interpreted : bool
+ Whether to more closely reproduce the input arguments (`False`,
+ default) or the processed arguments (`True`). The former is better
+ for string representations and round-tripping with ``eval(repr())``.
+
+ Returns
+ -------
+ dict[str, Any]
+ """
+ # The keys are added in this order because `repr` prints them in order.
+ kw = {"derived": self.derived,
+ "unit": self.unit,
+ "equivalencies": self.equivalencies,
+ # Validator is always turned into a function, but for ``repr`` it's nice
+ # to know if it was originally a string.
+ "fvalidate": self.fvalidate if processed else self._fvalidate_in,
+ "fmt": self.format_spec,
+ "doc": self.__doc__}
+ return kw
+
+ def clone(self, **kw):
+ """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', fmt='.3g', doc=None)
+
+ >>> p.clone(unit="km")
+ Parameter(derived=False, unit=Unit("km"), equivalencies=[],
+ fvalidate='default', fmt='.3g', doc=None)
+ """
+ # Start with defaults, update from kw.
+ kwargs = {**self._get_init_arguments(), **kw}
+ # All initialization failures, like incorrect input are handled by init
+ cloned = type(self)(**kwargs)
+ # Transfer over the __set_name__ stuff. If `clone` is used to make a
+ # new descriptor, __set_name__ will be called again, overwriting this.
+ cloned._attr_name = self._attr_name
+ cloned._attr_name_private = self._attr_name_private
+
+ return cloned
+
+ def __eq__(self, other):
+ """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
+ """
+ if not isinstance(other, Parameter):
+ return NotImplemented
+ # Check equality on all `_init_arguments` & `name`.
+ # Need to compare the processed arguments because the inputs are many-
+ # to-one, e.g. `fvalidate` can be a string or the equivalent function.
+ return ((self._get_init_arguments(True) == other._get_init_arguments(True))
+ and (self.name == other.name))
+
def __repr__(self):
- return f"<Parameter {self._attr_name!r} at {hex(id(self))}>"
+ """String representation.
+
+ ``eval(repr())`` should work, depending if contents like ``fvalidate``
+ can be similarly round-tripped.
+ """
+ return "Parameter({})".format(", ".join(f"{k}={v!r}" for k, v in
+ self._get_init_arguments().items()))
# ===================================================================
diff --git a/docs/changes/cosmology/12479.feature.rst b/docs/changes/cosmology/12479.feature.rst
new file mode 100644
index 000000000000..f48871bb0f1f
--- /dev/null
+++ b/docs/changes/cosmology/12479.feature.rst
@@ -0,0 +1,6 @@
+A method ``clone`` has been added to ``Parameter`` to quickly deep copy the
+object and change any constructor argument.
+A supporting equality method is added, and ``repr`` is enhanced to be able to
+roundtrip -- ``eval(repr(Parameter()))`` -- if the Parameter's arguments can
+similarly roundtrip.
+Parameter's arguments are made keyword-only.
diff --git a/docs/cosmology/dev.rst b/docs/cosmology/dev.rst
index 1014d727d3b3..6228691a94ce 100644
--- a/docs/cosmology/dev.rst
+++ b/docs/cosmology/dev.rst
@@ -140,6 +140,17 @@ The last thing to note is pretty formatting for the |Cosmology|. Each
<https://docs.python.org/3/library/string.html#formatspec>`_ ".3g", but this
may be overridden, like :attr:`~astropy.cosmology.FLRW.Tcmb0` does.
+If a new cosmology modifies an existing Parameter, then the
+`Parameter.clone() <astropy.cosmology.Parameter.clone>`_ method is useful
+to deep-copy the parameter and change any constructor argument. For example,
+see ``FlatFLRWMixin`` in ``astropy.cosmology.flrw`` (also shown below).
+
+.. code-block:: python
+
+ class FlatFLRWMixin(FlatCosmologyMixin):
+ ...
+
+ Ode0 = FLRW.Ode0.clone(derived=True) # now a derived param.
Mixins
------
|
diff --git a/astropy/cosmology/tests/test_parameter.py b/astropy/cosmology/tests/test_parameter.py
index 4660e95dae2d..f6a1bce59d4d 100644
--- a/astropy/cosmology/tests/test_parameter.py
+++ b/astropy/cosmology/tests/test_parameter.py
@@ -6,7 +6,9 @@
# IMPORTS
# STDLIB
+import ast
import inspect
+import sys
# THIRD PARTY
import pytest
@@ -70,6 +72,7 @@ def test_Parameter_init(self):
assert parameter.equivalencies == []
assert parameter.format_spec == ".3g"
assert parameter.derived is False
+ assert parameter.name is None
# setting all kwargs
parameter = Parameter(fvalidate="float", doc="DOCSTRING",
@@ -166,15 +169,6 @@ def test_Parameter_descriptor_set(self, cosmo, all_parameter):
# validate value
# tested later.
- # -------------------------------------------
-
- def test_Parameter_repr(self, cosmo_cls, all_parameter):
- """Test Parameter repr."""
- r = repr(getattr(cosmo_cls, all_parameter.name))
-
- assert all_parameter._attr_name in r
- assert hex(id(all_parameter)) in r
-
# ===============================================================
# Usage Tests
@@ -249,7 +243,7 @@ class TestParameter(ParameterTestMixin):
def setup_class(self):
class Example1(Cosmology):
- param = Parameter(doc="example parameter",
+ param = Parameter(doc="Description of example parameter.",
unit=u.m, equivalencies=u.mass_energy())
def __init__(self, param=15):
@@ -293,7 +287,7 @@ def test_Parameter_instance_attributes(self, param):
super().test_Parameter_instance_attributes(param)
# property
- assert param.__doc__ == "example parameter"
+ assert param.__doc__ == "Description of example parameter."
# custom from init
assert param._unit == u.m
@@ -406,6 +400,67 @@ def func(cosmology, param, value):
finally:
param.__class__._registry_validators.pop("newvalidator", None)
+ # -------------------------------------------
+
+ def test_Parameter_clone(self, param):
+ """Test :meth:`astropy.cosmology.Parameter.clone`."""
+ # this implicitly relies on `__eq__` testing properly. Which is tested.
+
+ # basic test that nothing changes
+ assert param.clone() == param
+ assert param.clone() is not param # but it's not a 'singleton'
+
+ # passing kwargs will change stuff
+ newparam = param.clone(unit="km/(yr sr)")
+ assert newparam.unit == u.km / u.yr / u.sr
+ assert param.unit != u.km / u.yr / u.sr # original is unchanged
+
+ # expected failure for not-an-argument
+ with pytest.raises(TypeError):
+ param.clone(not_a_valid_parameter=True)
+
+ # -------------------------------------------
+
+ def test_Parameter_equality(self):
+ """
+ Test Parameter equality.
+ Determined from the processed initialization args (including defaults).
+ """
+ p1 = Parameter(unit="km / (s Mpc)")
+ p2 = Parameter(unit="km / (s Mpc)")
+ assert p1 == p2
+
+ # not equal parameters
+ p3 = Parameter(unit="km / s")
+ assert p3 != p1
+
+ # misc
+ assert p1 != 2 # show doesn't error
+
+ # -------------------------------------------
+
+ def test_Parameter_repr(self, cosmo_cls, param):
+ """Test Parameter repr."""
+ r = repr(param)
+
+ assert "Parameter(" in r
+ for subs in ("derived=False", 'unit=Unit("m")', 'equivalencies=[(Unit("kg"), Unit("J")',
+ "fmt='.3g'", "doc='Description of example parameter.'"):
+ assert subs in r, subs
+
+ # `fvalidate` is a little tricker b/c one of them is custom!
+ if param.fvalidate in param._registry_validators.values(): # not custom
+ assert "fvalidate='default'" in r
+ else:
+ assert "fvalidate=<" in r # Some function, don't care about details.
+
+ def test_Parameter_repr_roundtrip(self, param):
+ """Test ``eval(repr(Parameter))`` can round trip to ``Parameter``."""
+ P = Parameter(doc="A description of this parameter.", derived=True)
+ NP = eval(repr(P)) # Evaluate string representation back into a param.
+
+ assert P == NP
+
# ==============================================================
def test_Parameter_doesnt_change_with_generic_class(self):
|
[
{
"path": "docs/changes/cosmology/12479.feature.rst",
"old_path": "/dev/null",
"new_path": "b/docs/changes/cosmology/12479.feature.rst",
"metadata": "diff --git a/docs/changes/cosmology/12479.feature.rst b/docs/changes/cosmology/12479.feature.rst\nnew file mode 100644\nindex 000000000000..f48871bb0f1f\n--- /dev/null\n+++ b/docs/changes/cosmology/12479.feature.rst\n@@ -0,0 +1,6 @@\n+A method ``clone`` has been added to ``Parameter`` to quickly deep copy the\n+object and change any constructor argument.\n+A supporting equality method is added, and ``repr`` is enhanced to be able to\n+roundtrip -- ``eval(repr(Parameter()))`` -- if the Parameter's arguments can\n+similarly roundtrip.\n+Parameter's arguments are made keyword-only.\n",
"update": null
},
{
"path": "docs/cosmology/dev.rst",
"old_path": "a/docs/cosmology/dev.rst",
"new_path": "b/docs/cosmology/dev.rst",
"metadata": "diff --git a/docs/cosmology/dev.rst b/docs/cosmology/dev.rst\nindex 1014d727d3b3..6228691a94ce 100644\n--- a/docs/cosmology/dev.rst\n+++ b/docs/cosmology/dev.rst\n@@ -140,6 +140,17 @@ The last thing to note is pretty formatting for the |Cosmology|. Each\n <https://docs.python.org/3/library/string.html#formatspec>`_ \".3g\", but this\n may be overridden, like :attr:`~astropy.cosmology.FLRW.Tcmb0` does.\n \n+If a new cosmology modifies an existing Parameter, then the\n+`Parameter.clone() <astropy.cosmology.Parameter.clone>`_ method is useful\n+to deep-copy the parameter and change any constructor argument. For example,\n+see ``FlatFLRWMixin`` in ``astropy.cosmology.flrw`` (also shown below).\n+\n+.. code-block:: python\n+\n+ class FlatFLRWMixin(FlatCosmologyMixin):\n+ ...\n+\n+ Ode0 = FLRW.Ode0.clone(derived=True) # now a derived param.\n \n Mixins\n ------\n",
"update": null
}
] |
5.1
|
bf35e6f60b644fe305f806b891630079bcd1d321
|
[
"astropy/cosmology/tests/test_parameter.py::TestParameter::test_Parameter_validate[Example2]",
"astropy/cosmology/tests/test_parameter.py::TestParameter::test_Parameter_doesnt_change_with_generic_class",
"astropy/cosmology/tests/test_parameter.py::TestParameter::test_Parameter_not_unique[Example1]",
"astropy/cosmology/tests/test_parameter.py::TestParameter::test_Parameter_descriptor_set[Example2]",
"astropy/cosmology/tests/test_parameter.py::TestParameter::test_Parameter_register_validator[Example1]",
"astropy/cosmology/tests/test_parameter.py::TestParameter::test_Parameter_descriptor_get[Example2]",
"astropy/cosmology/tests/test_parameter.py::TestParameter::test_Parameter_doesnt_change_with_cosmology[Example1]",
"astropy/cosmology/tests/test_parameter.py::TestParameter::test_Parameter_equivalencies[Example2]",
"astropy/cosmology/tests/test_parameter.py::TestParameter::test_Parameter_validate[Example1]",
"astropy/cosmology/tests/test_parameter.py::TestParameter::test_Parameter_descriptor_set[Example1]",
"astropy/cosmology/tests/test_parameter.py::TestParameter::test_Parameter_class_attributes[Example2]",
"astropy/cosmology/tests/test_parameter.py::TestParameter::test_Parameter_instance_attributes[Example1]",
"astropy/cosmology/tests/test_parameter.py::TestParameter::test_Parameter_name[Example2]",
"astropy/cosmology/tests/test_parameter.py::TestParameter::test_make_from_Parameter[Example2]",
"astropy/cosmology/tests/test_parameter.py::TestParameter::test_Parameter_name[Example1]",
"astropy/cosmology/tests/test_parameter.py::TestParameter::test_Parameters_reorder_by_signature[Example2]",
"astropy/cosmology/tests/test_parameter.py::TestParameter::test_Parameter_instance_attributes[Example2]",
"astropy/cosmology/tests/test_parameter.py::TestParameter::test_Parameter_listed[Example2]",
"astropy/cosmology/tests/test_parameter.py::TestParameter::test_Parameter_descriptor_get[Example1]",
"astropy/cosmology/tests/test_parameter.py::TestParameter::test_parameter_related_attributes_on_Cosmology[Example1]",
"astropy/cosmology/tests/test_parameter.py::TestParameter::test_Parameter_register_validator[Example2]",
"astropy/cosmology/tests/test_parameter.py::TestParameter::test_Parameter_format_spec[Example1]",
"astropy/cosmology/tests/test_parameter.py::TestParameter::test_Parameter_format_spec[Example2]",
"astropy/cosmology/tests/test_parameter.py::TestParameter::test_Parameter_equivalencies[Example1]",
"astropy/cosmology/tests/test_parameter.py::TestParameter::test_Parameter_validator[Example2]",
"astropy/cosmology/tests/test_parameter.py::TestParameter::test_Parameter_doesnt_change_with_cosmology[Example2]",
"astropy/cosmology/tests/test_parameter.py::TestParameter::test_Parameter_derived[Example1]",
"astropy/cosmology/tests/test_parameter.py::TestParameter::test_Parameter_class_attributes[Example1]",
"astropy/cosmology/tests/test_parameter.py::TestParameter::test_Parameter_validator[Example1]",
"astropy/cosmology/tests/test_parameter.py::TestParameter::test_Parameter_not_unique[Example2]",
"astropy/cosmology/tests/test_parameter.py::TestParameter::test_Parameters_reorder_by_signature[Example1]",
"astropy/cosmology/tests/test_parameter.py::TestParameter::test_Parameter_fvalidate[Example2]",
"astropy/cosmology/tests/test_parameter.py::TestParameter::test_Parameter_fvalidate[Example1]",
"astropy/cosmology/tests/test_parameter.py::TestParameter::test_Parameter_unit[Example2]",
"astropy/cosmology/tests/test_parameter.py::TestParameter::test_make_from_Parameter[Example1]",
"astropy/cosmology/tests/test_parameter.py::TestParameter::test_Parameter_listed[Example1]",
"astropy/cosmology/tests/test_parameter.py::TestParameter::test_Parameter_unit[Example1]",
"astropy/cosmology/tests/test_parameter.py::TestParameter::test_Parameter_derived[Example2]",
"astropy/cosmology/tests/test_parameter.py::TestParameter::test_parameter_related_attributes_on_Cosmology[Example2]"
] |
[
"astropy/cosmology/tests/test_parameter.py::TestParameter::test_Parameter_clone[Example2]",
"astropy/cosmology/tests/test_parameter.py::TestParameter::test_Parameter_repr_roundtrip[Example1]",
"astropy/cosmology/tests/test_parameter.py::TestParameter::test_Parameter_repr[Example1]",
"astropy/cosmology/tests/test_parameter.py::TestParameter::test_Parameter_clone[Example1]",
"astropy/cosmology/tests/test_parameter.py::TestParameter::test_Parameter_repr[Example2]",
"astropy/cosmology/tests/test_parameter.py::TestParameter::test_Parameter_equality",
"astropy/cosmology/tests/test_parameter.py::TestParameter::test_Parameter_repr_roundtrip[Example2]",
"astropy/cosmology/tests/test_parameter.py::TestParameter::test_Parameter_init"
] |
[
{
"path": "docs/changes/cosmology/#####.feature.rst",
"old_path": "/dev/null",
"new_path": "b/docs/changes/cosmology/#####.feature.rst",
"metadata": "diff --git a/docs/changes/cosmology/#####.feature.rst b/docs/changes/cosmology/#####.feature.rst\nnew file mode 100644\nindex 0000000000..f48871bb0f\n--- /dev/null\n+++ b/docs/changes/cosmology/#####.feature.rst\n@@ -0,0 +1,6 @@\n+A method ``clone`` has been added to ``Parameter`` to quickly deep copy the\n+object and change any constructor argument.\n+A supporting equality method is added, and ``repr`` is enhanced to be able to\n+roundtrip -- ``eval(repr(Parameter()))`` -- if the Parameter's arguments can\n+similarly roundtrip.\n+Parameter's arguments are made keyword-only.\n"
},
{
"path": "docs/cosmology/dev.rst",
"old_path": "a/docs/cosmology/dev.rst",
"new_path": "b/docs/cosmology/dev.rst",
"metadata": "diff --git a/docs/cosmology/dev.rst b/docs/cosmology/dev.rst\nindex 1014d727d3..6228691a94 100644\n--- a/docs/cosmology/dev.rst\n+++ b/docs/cosmology/dev.rst\n@@ -140,6 +140,17 @@ The last thing to note is pretty formatting for the |Cosmology|. Each\n <https://docs.python.org/3/library/string.html#formatspec>`_ \".3g\", but this\n may be overridden, like :attr:`~astropy.cosmology.FLRW.Tcmb0` does.\n \n+If a new cosmology modifies an existing Parameter, then the\n+`Parameter.clone() <astropy.cosmology.Parameter.clone>`_ method is useful\n+to deep-copy the parameter and change any constructor argument. For example,\n+see ``FlatFLRWMixin`` in ``astropy.cosmology.flrw`` (also shown below).\n+\n+.. code-block:: python\n+\n+ class FlatFLRWMixin(FlatCosmologyMixin):\n+ ...\n+\n+ Ode0 = FLRW.Ode0.clone(derived=True) # now a derived param.\n \n Mixins\n ------\n"
}
] |
{
"header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:",
"data": []
}
|
diff --git a/docs/changes/cosmology/#####.feature.rst b/docs/changes/cosmology/#####.feature.rst
new file mode 100644
index 0000000000..f48871bb0f
--- /dev/null
+++ b/docs/changes/cosmology/#####.feature.rst
@@ -0,0 +1,6 @@
+A method ``clone`` has been added to ``Parameter`` to quickly deep copy the
+object and change any constructor argument.
+A supporting equality method is added, and ``repr`` is enhanced to be able to
+roundtrip -- ``eval(repr(Parameter()))`` -- if the Parameter's arguments can
+similarly roundtrip.
+Parameter's arguments are made keyword-only.
diff --git a/docs/cosmology/dev.rst b/docs/cosmology/dev.rst
index 1014d727d3..6228691a94 100644
--- a/docs/cosmology/dev.rst
+++ b/docs/cosmology/dev.rst
@@ -140,6 +140,17 @@ The last thing to note is pretty formatting for the |Cosmology|. Each
<https://docs.python.org/3/library/string.html#formatspec>`_ ".3g", but this
may be overridden, like :attr:`~astropy.cosmology.FLRW.Tcmb0` does.
+If a new cosmology modifies an existing Parameter, then the
+`Parameter.clone() <astropy.cosmology.Parameter.clone>`_ method is useful
+to deep-copy the parameter and change any constructor argument. For example,
+see ``FlatFLRWMixin`` in ``astropy.cosmology.flrw`` (also shown below).
+
+.. code-block:: python
+
+ class FlatFLRWMixin(FlatCosmologyMixin):
+ ...
+
+ Ode0 = FLRW.Ode0.clone(derived=True) # now a derived param.
Mixins
------
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.