Repository navigation
Register format ascii.html to Cosmology.write - #13075
Conversation
|
Hello @JefftheCloudDog 👋! It looks like you've made some changes in your pull request, so I've checked the code again for style. There are no PEP8 style issues with this pull request - thanks! 🎉 Comment last updated at 2022-07-09 20:53:40 UTC |
There was a problem hiding this comment.
Welcome to Astropy 👋 and congratulations on your first pull request! 🎉
A project member will respond to you as soon as possible; in the meantime, please have a look over the Checklist for Contributed Code and make sure you've addressed as many of the questions there as possible.
If you feel that this pull request has not been responded to in a timely manner, please leave a comment mentioning our software support engineer @embray, or send a message directly to the development mailing list. If the issue is urgent or sensitive in nature (e.g., a security vulnerability) please send an e-mail directly to the private e-mail [email protected].
|
👋 Thank you for your draft pull request! Do you know that you can use |
|
@JefftheCloudDog the issue appears to be that the HTML table writer doesn't work with units. Here's how I found the relevant documentation, which includes all the various things the HTML writer can do: from astropy.cosmology import Planck18
tbl = Planck18.to_format("astropy.table")
tbl.writer.help("html")While mildly annoying, there is an easy fix for the unit issue: every Parameter on a Cosmology stores the preferred unit, so you can convert each column to its unitless equivalent. This is a quick and dirty method, there's probably something cleaner. import astropy.units as u
from astropy.cosmology import Planck18, Parameter
cosmo_cls = type(Planck18)
tbl = Planck18.to_format("astropy.table")
for n, col in zip(tbl.colnames, tbl.itercols()): # Iter thru name and column
param = getattr(cosmo_cls, n) # Get parameter, and check it
if not isinstance(param, Parameter) or param.unit in (None, u.one):
continue
# Replace column with unitless version
tbl.replace_column(n, col.to_value(param.unit), copy=False)
tbl |
ascii.html to Cosmology.write
|
@JefftheCloudDog the CI isn't fully running because the Code Style Check runs first and it's currently failing. There's usually an easy fix and that's to run |
nstarman
left a comment
There was a problem hiding this comment.
This is looking like a great start. Some hopefully helpful suggestions.
Also, there will be a few other files to edit. See astropy/cosmology/io/__init__.py and astropy/cosmology/tests/test_connect.py
nstarman
left a comment
There was a problem hiding this comment.
Just passing through... Thanks for connecting up the tests in test_connect.py.
The test suite is now picking up all the failed tests. This is good as solving each one should get this PR basically ready to merge. You can either look through the logs of each test or, to tackle them one at a time use
pytest -P cosmology -v -x
in the command line (while in astropy's folder and your development environment). This will only run the cosmology tests, list each test, and stop at the first failure.
If you want to enter a debugging mode, add --pdb.
|
I am a little stuck on the fix. From my testing, it appears that metadata is not stored properly as part of a cosmology object's metadata. There are two fail cases:
Perhaps I am reading the documentation wrong, but is there a built in method for HTML that automatically converts a HTML metadata column to metadata? I was not able to find documentation about any such methods. |
|
@JefftheCloudDog, a good observation. I just did some testing and it doesn't look like the table -> HTML writer keeps any of a table's metadata! Fixing this is out of the scope of this PR, so let's just make the Cosmology <-> HTML work as well as possible within these restrictions. Don't worry about a Cosmology's metadata. I think one thing to be careful about is the |
|
@nstarman I set the cosmology_in_meta to be False for now because of the metadata issues. The tests should all pass now, I commented out the offending assert statements. |
|
@JefftheCloudDog, it looks like the CI didn't start. Can you rebase and re-push? That should get it going. Thanks! |
12d4905 to
6bea378
Compare
|
@nstarman I rebased and repushed. Looks like there are still some errors listed, like |
|
@JefftheCloudDog If you click on the former it will take you to the full traceback, which is very useful for diagnosing problems. The changelog error is because this PR does not yet have a changelog. See https://docs.astropy.org/en/latest/development/workflow/development_workflow.html#add-a-changelog-entry for details. To get an easier diagnosis, try in the command line >>> pytest -P cosmology -v -x --pdb |
|
I updated init.py to include html as an import, looks like I am getting this circular import error regarding this line in init.py: and html.py: Seems like the error could be popping up because of the order of importing Parameter from astropy.cosmology, but rearanging the import order does not seem to fix this issue. |
nstarman
left a comment
There was a problem hiding this comment.
The circular import issue is because astropy.cosmology is not fully initialized. Import the class directly from its defining module — astropy.cosmology.parameter.
|
@JefftheCloudDog, please rebase on the main branch instead of merging. |
|
@nstarman My mistake. I tried reverting back the previous commits and rebasing on main, but it looks like the feature branch is already up to date. |
2121141 to
25b14da
Compare
|
@nstarman I am a little new to rebasing, but I think I got it mostly figured out. Locally, I tried reverting back to before the merge and rebasing with the main branch from there. I did modify a few more files regarding testing, such as I also want to note that some files were not added during the rebase, such as I also think there are rather a lot of commits at this point, and in the end, squashing might be required. |
25b14da to
cc247c9
Compare
73d26f1 to
7d54ea2
Compare
|
@nstarman The code should be updated. I added extra |
nstarman
left a comment
There was a problem hiding this comment.
This PR is getting close! Well done @JefftheCloudDog.
I think this merits a what's new entry (see https://github.com/astropy/astropy/blob/main/docs/whatsnew/5.2.rst), which is done by modifying the file 5.2.rst in the docs.
7d54ea2 to
d006187
Compare
|
There seems to be an issue with test_readwrite_html_mutlirow. I am also still working on the TestReadWriteHTML tests and adding an entry to the rst. Is there an example of analogous tests for TestReadWriteHTML? Looks like there are no such tests for other test files in cosmology/io/tests. |
This error occurs when a quantity with units is converted to a python scalar. On your machine try Looking at the log, it appears that some units aren't being stripped. For instance, I looked and saw error messages like this: The source of this problem is that HTML tables don't support units. Recall in the PR there is to strip units. This is applied when calling The solution is to for-loop over the combined table and remove units, like is done above. If you are interested in a followup PR, you could add a flag to In the meantime, just remove the units in
The ECSV I/O is a good example of read/write tests Also when writing tests, take a look at the code coverage. That's the best way to see what needs a test! |
6a41225 to
d21ceb0
Compare
nstarman
left a comment
There was a problem hiding this comment.
@JefftheCloudDog this PR is looking good. A few small changes and then it should be good to merge.
573f5a2 to
29205ec
Compare
|
Thanks @JefftheCloudDog for all the hard work! I squashed the PR and made a few necessary changes so this could get into v5.2. |
|
@mhvk, I contributed heavily to this PR, so a second set of eyes would be appreciated. Thanks! |
mhvk
left a comment
There was a problem hiding this comment.
Mostly small points, many just nitpicks, but also a query or two.
| if not isinstance(param, Parameter) or param.unit in (None, u.one): | ||
| continue | ||
| # Replace column with unitless version | ||
| table.replace_column(n, (col << param.unit).value, copy=False) |
There was a problem hiding this comment.
I don't think it is necessary to get the unitless version, rather you can just change the unit. This might be nicer if the html output gets the option to show units.
There was a problem hiding this comment.
I don't think that works. The HTML table breaks for columns with units.
@pytest.mark.skipif(not HAS_BS4, reason="requires beautifulsoup4")
def test_to_html_table_bad_index(self, read, write, tmp_path):
"""Test if argument ``index`` is incorrect"""
fp = tmp_path / "test_to_html_table_bad_index.html"
> write(fp, format="ascii.html")
astropy/cosmology/io/tests/test_html.py:33:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
astropy/cosmology/connect.py:121: in __call__
self.registry.write(self._instance, *args, **kwargs)
astropy/io/registry/core.py:367: in write
return writer(data, *args, **kwargs)
astropy/cosmology/io/html.py:129: in write_html_table
table.write(file, overwrite=overwrite, **kwargs)
astropy/table/connect.py:129: in __call__
self.registry.write(instance, *args, **kwargs)
astropy/io/registry/core.py:367: in write
return writer(data, *args, **kwargs)
astropy/io/ascii/connect.py:26: in io_write
return write(table, filename, **kwargs)
astropy/io/ascii/ui.py:849: in write
lines = writer.write(table)
astropy/io/ascii/html.py:433: in write
new_col = Column([el[i] for el in col])
astropy/table/column.py:1164: in __new__
self = super().__new__(
astropy/table/column.py:514: in __new__
self_data = np.array(data, dtype=dtype, copy=copy)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
self = <Quantity 0. eV>
def __float__(self):
try:
return float(self.to_value(dimensionless_unscaled))
except (UnitsError, TypeError):
> raise TypeError('only dimensionless scalar quantities can be '
'converted to Python scalars')
E TypeError: only dimensionless scalar quantities can be converted to Python scalars
There was a problem hiding this comment.
Is this a bug in the HTML writer for table?
There was a problem hiding this comment.
Weird, I tried a simpler version yesterday which did work:
qt = QTable([np.arange(3.)*u.m])
qt.write('a.html', format='ascii.html', overwrite=True)
However, the html file does not contain the unit, so there is no real benefit. So, best to just leave it for now, I guess.
| table.rename_column(n, new_name) | ||
|
|
||
| # Write HTML, using table I/O | ||
| kwargs["format"] = "ascii.html" # force the format |
There was a problem hiding this comment.
I don't think one should ignore possibly wrong format input, so I'd suggest either using kwargs.setdefault("format", "ascii.html"), i.e., if the user wants to screw this up, let them, or pass on format="ascii.html" in the actual call and get an error if kwargs contains format too.
There was a problem hiding this comment.
I tried both. The latter prevents the user from passing format="ascii.html". So I'm adding a more informative ValueError instead.
|
|
||
| # Collect the registered read/write formats. | ||
| readwrite_formats = {"ascii.ecsv", "json"} | ||
| readwrite_formats = { |
There was a problem hiding this comment.
Probably good to describe what these options are (maybe even namedtuple).
|
|
||
| assert got == cosmo | ||
| assert dict(got.meta) == dict(cosmo.meta) | ||
| assert (not metaio) ^ (dict(got.meta) == dict(cosmo.meta)) |
There was a problem hiding this comment.
Is it guaranteed that the metadata do not match if not metaio? My tendency would be if metaio: assert ...
There was a problem hiding this comment.
It should be guaranteed. And if it ever starts failing that means the metadata is supported, which would be excellent. This test can't become out of date.
| If the following is added to the file's header, the column names will render | ||
| nicely. | ||
| :: | ||
| <script |
There was a problem hiding this comment.
This doc makes me wonder: should it be an option to have the column names as latex? After all, the html looks OK without it if you keep the regular column names.
There was a problem hiding this comment.
I agree. That only needs to be a flag in write_html_table.
There was a problem hiding this comment.
And for a followup PR, it would be good to also have the flag in to/from_table.
11ecfde to
7d0d86e
Compare
Co-authored-by: JefftheCloudDog <[email protected]> Signed-off-by: Nathaniel Starkman (@nstarman) <[email protected]>
Co-authored-by: JefftheCloudDog <[email protected]> Signed-off-by: Nathaniel Starkman (@nstarman) <[email protected]>
Co-authored-by: JefftheCloudDog <[email protected]> Signed-off-by: Nathaniel Starkman (@nstarman) <[email protected]>
Signed-off-by: Nathaniel Starkman (@nstarman) <[email protected]>
7d0d86e to
73443da
Compare
|
CI passed, so I pushed the hopefully last small doc change. GTG? |

Description
This is a draft pull request for issue #12356 .
This draft pull requests adds two python files in astropy/cosmology/io and astropy/cosmology/io/tests .
Fixes #12356
Checklist for package maintainer(s)
This checklist is meant to remind the package maintainer(s) who will review this pull request of some common things to look for. This list is not exhaustive.
Extra CIlabel.no-changelog-entry-neededlabel. If this is a manual backport, use theskip-changelog-checkslabel unless special changelog handling is necessary.astropy-botcheck might be missing; do not let the green checkmark fool you.backport-X.Y.xlabel(s) before merge.