Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New and updated reprs for Variable, ParticleFile, Field, VectorField, and ParticleSet #1743

Merged
merged 17 commits into from
Oct 28, 2024
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 28 additions & 6 deletions docs/examples/parcels_tutorial.ipynb
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The _warn_outputdt_release_desync() call should be fixed by #1744

But it would be nice if the particles are listed one per line in the other cells?

Original file line number Diff line number Diff line change
Expand Up @@ -152,8 +152,12 @@
"name": "stdout",
"output_type": "stream",
"text": [
"P[0](lon=330000.000000, lat=100000.000000, depth=0.000000, time=not_yet_set)\n",
"P[1](lon=330000.000000, lat=280000.000000, depth=0.000000, time=not_yet_set)\n"
"<ParticleSet>\n",
" fieldset : <parcels.fieldset.FieldSet object at 0x15f033530>\n",
" pclass : False\n",
" repeatdt : None\n",
" # particles: 2\n",
" particles : [P[0](lon=330000.000000, lat=100000.000000, depth=0.000000, time=not_yet_set), P[1](lon=330000.000000, lat=280000.000000, depth=0.000000, time=not_yet_set)]\n"
]
}
],
Expand Down Expand Up @@ -220,8 +224,22 @@
"name": "stdout",
"output_type": "stream",
"text": [
"INFO: Output files are stored in EddyParticles.zarr.\n",
"100%|██████████| 518400.0/518400.0 [00:03<00:00, 172443.78it/s]\n"
"INFO: Output files are stored in EddyParticles.zarr.\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"/Users/erik/Codes/ParcelsCode/parcels/particleset.py:1082: FileWarning: Some of the particles have a start time that is not a multiple of outputdt. This could cause the first output to be at a different time than expected.\n",
" _warn_outputdt_release_desync(outputdt, self.particledata.data[\"time_nextloop\"])\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"100%|██████████| 518400.0/518400.0 [00:05<00:00, 95421.55it/s] \n"
]
}
],
Expand Down Expand Up @@ -13228,8 +13246,12 @@
"name": "stdout",
"output_type": "stream",
"text": [
"P[0](lon=329983.281250, lat=100495.609375, depth=0.000000, time=300.000000)\n",
"P[1](lon=330289.968750, lat=280418.906250, depth=0.000000, time=300.000000)\n"
"<ParticleSet>\n",
" fieldset : <parcels.fieldset.FieldSet object at 0x15f033530>\n",
" pclass : False\n",
" repeatdt : None\n",
" # particles: 2\n",
" particles : [P[0](lon=329983.281250, lat=100495.609375, depth=0.000000, time=300.000000), P[1](lon=330289.968750, lat=280418.906250, depth=0.000000, time=300.000000)]\n"
]
},
{
Expand Down
5 changes: 4 additions & 1 deletion parcels/field.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
assert_valid_gridindexingtype,
assert_valid_interp_method,
)
from parcels.tools._helpers import deprecated_made_private
from parcels.tools._helpers import deprecated_made_private, pretty_field
VeckoTheGecko marked this conversation as resolved.
Show resolved Hide resolved
from parcels.tools.converters import (
Geographic,
GeographicPolar,
Expand Down Expand Up @@ -312,6 +312,9 @@ def __init__(
if len(kwargs) > 0:
raise SyntaxError(f'Field received an unexpected keyword argument "{list(kwargs.keys())[0]}"')

def __repr__(self) -> str:
return pretty_field(self)

@property
@deprecated_made_private # TODO: Remove 6 months after v3.1.0
def dataFiles(self):
Expand Down
2 changes: 1 addition & 1 deletion parcels/particle.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ def __set__(self, instance, value):
setattr(instance, f"_{self.name}", value)

def __repr__(self):
return f"PVar<{self.name}|{self.dtype}>"
return f"Variable(name={self._name}, dtype={self.dtype}, initial={self.initial}, to_write={self.to_write})"

def is64bit(self):
"""Check whether variable is 64-bit."""
Expand Down
12 changes: 11 additions & 1 deletion parcels/particlefile.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@

import parcels
from parcels._compat import MPI
from parcels.tools._helpers import deprecated, deprecated_made_private
from parcels.tools._helpers import default_repr, deprecated, deprecated_made_private
from parcels.tools.warnings import FileWarning

__all__ = ["ParticleFile"]
Expand Down Expand Up @@ -116,6 +116,16 @@
fname = name if extension in [".zarr"] else f"{name}.zarr"
self._fname = fname

def __repr__(self) -> str:
return (
f"{type(self).__name__}("
f"name={self.fname!r}, "
f"particleset={default_repr(self.particleset)}, "

Check warning on line 123 in parcels/particlefile.py

View check run for this annotation

Codecov / codecov/patch

parcels/particlefile.py#L123

Added line #L123 was not covered by tests
f"outputdt={self.outputdt!r}, "
f"chunks={self.chunks!r}, "
f"create_new_zarrfile={self.create_new_zarrfile!r})"
)

@property
def create_new_zarrfile(self):
return self._create_new_zarrfile
Expand Down
4 changes: 2 additions & 2 deletions parcels/particleset.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
from parcels.particle import JITParticle, Variable
from parcels.particledata import ParticleData, ParticleDataIterator
from parcels.particlefile import ParticleFile
from parcels.tools._helpers import deprecated, deprecated_made_private
from parcels.tools._helpers import deprecated, deprecated_made_private, pretty_particleset
from parcels.tools.converters import _get_cftime_calendars, convert_to_flat_array
from parcels.tools.global_statics import get_package_dir
from parcels.tools.loggers import logger
Expand Down Expand Up @@ -386,7 +386,7 @@ def size(self):
return len(self.particledata)

def __repr__(self):
return "\n".join([str(p) for p in self])
return pretty_particleset(self)

def __len__(self):
return len(self.particledata)
Expand Down
40 changes: 40 additions & 0 deletions parcels/tools/_helpers.py
VeckoTheGecko marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -1,9 +1,15 @@
"""Internal helpers for Parcels."""

from __future__ import annotations

import functools
import warnings
from collections.abc import Callable
from textwrap import dedent
from typing import TYPE_CHECKING, Any

if TYPE_CHECKING:
from parcels import Field, ParticleSet
PACKAGE = "Parcels"


Expand Down Expand Up @@ -56,3 +62,37 @@

def patch_docstring(obj: Callable, extra: str) -> None:
obj.__doc__ = f"{obj.__doc__ or ''}{extra}".strip()


def pretty_field(field: Field) -> str:
"""Return a pretty repr for Field"""
out = f"""<{type(field).__name__}>
grid : {field.grid!r }

Check warning on line 70 in parcels/tools/_helpers.py

View check run for this annotation

Codecov / codecov/patch

parcels/tools/_helpers.py#L70

Added line #L70 was not covered by tests
extrapolate time: {field.allow_time_extrapolation!r}
time_periodic : {field.time_periodic!r }
gridindexingtype: {field.gridindexingtype!r }
to_write : {field.to_write!r }

Check warning on line 74 in parcels/tools/_helpers.py

View check run for this annotation

Codecov / codecov/patch

parcels/tools/_helpers.py#L73-L74

Added lines #L73 - L74 were not covered by tests
"""
return dedent(out).strip()


def pretty_particleset(pset: ParticleSet) -> str:
"""Return a pretty repr for ParticleSet"""
if len(pset) < 10:
particles = repr(list(pset))
else:
lst = [repr(pset[i]) for i in range(7)] + ["..."]
particles = f"[{', '.join(lst)}]"

out = f"""<{type(pset).__name__}>
fieldset : {pset.fieldset}
pclass : {pset.pclass}
repeatdt : {pset.repeatdt}

Check warning on line 90 in parcels/tools/_helpers.py

View check run for this annotation

Codecov / codecov/patch

parcels/tools/_helpers.py#L88-L90

Added lines #L88 - L90 were not covered by tests
# particles: {len(pset)}
particles : {particles}
VeckoTheGecko marked this conversation as resolved.
Show resolved Hide resolved
"""
return dedent(out).strip()


def default_repr(obj: Any):
return object.__repr__(obj)
62 changes: 61 additions & 1 deletion tests/test_reprs.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
import re
from datetime import timedelta
from typing import Any

import numpy as np

from parcels import Grid, TimeConverter
from parcels import Grid, ParticleFile, TimeConverter, Variable
from parcels.grid import RectilinearGrid
from tests.utils import create_fieldset_unit_mesh, create_simple_pset


def validate_simple_repr(class_: type, kwargs: dict[str, Any]):
Expand All @@ -17,6 +20,36 @@
assert class_.__name__ in obj_repr


def valid_indentation(s: str) -> bool:
"""Make sure that all lines in string is indented with a multiple of 4 spaces."""
if s.startswith(" "):
return False

Check warning on line 26 in tests/test_reprs.py

View check run for this annotation

Codecov / codecov/patch

tests/test_reprs.py#L26

Added line #L26 was not covered by tests

lines = s.split("\n")
for line in lines:
line = re.sub("^( {4})+", "", line)
if line.startswith(" "):
return False
return True


def test_check_indentation():
valid = """
test
test
test
test
test
test"""
assert valid_indentation(valid)
invalid = """
test
test
invalid!
"""
assert not valid_indentation(invalid)


def test_grid_repr():
"""Test arguments are in the repr of a Grid object"""
kwargs = dict(
Expand All @@ -25,6 +58,12 @@
validate_simple_repr(Grid, kwargs)


def test_variable_repr():
"""Test arguments are in the repr of the Variable object."""
kwargs = dict(name="test", dtype=np.float32, initial=0, to_write=False)
validate_simple_repr(Variable, kwargs)


def test_rectilineargrid_repr():
"""
Test arguments are in the repr of a RectilinearGrid object.
Expand All @@ -35,3 +74,24 @@
lon=np.array([1, 2, 3]), lat=np.array([4, 5, 6]), time=None, time_origin=TimeConverter(), mesh="spherical"
)
validate_simple_repr(RectilinearGrid, kwargs)


def test_particlefile_repr():
pset = create_simple_pset()
kwargs = dict(
name="file.zarr", particleset=pset, outputdt=timedelta(hours=1), chunks=None, create_new_zarrfile=False
)
validate_simple_repr(ParticleFile, kwargs)


def test_field_repr():
field = create_fieldset_unit_mesh().U
assert valid_indentation(repr(field))


def test_particleset_repr():
pset = create_simple_pset()
valid_indentation(repr(pset))

pset = create_simple_pset(n=15)
valid_indentation(repr(pset))
13 changes: 13 additions & 0 deletions tests/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

import numpy as np

import parcels
from parcels import FieldSet

PROJECT_ROOT = Path(__file__).resolve().parents[1]
Expand Down Expand Up @@ -47,6 +48,18 @@ def create_fieldset_zeros_conversion(mesh="spherical", xdim=200, ydim=100, mesh_
return FieldSet.from_data(data, dimensions, mesh=mesh)


def create_simple_pset(n=1):
zeros = np.zeros(n)
return parcels.ParticleSet(
fieldset=create_fieldset_unit_mesh(),
pclass=parcels.ScipyParticle,
lon=zeros,
lat=zeros,
depth=zeros,
time=zeros,
)


def create_spherical_positions(n_particles, max_depth=100000):
yrange = 2 * np.random.rand(n_particles)
lat = 180 * (np.arccos(1 - yrange) - 0.5 * np.pi) / np.pi
Expand Down
Loading