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

Implement Projection classes to encapsulate arguments #379

Draft
wants to merge 31 commits into
base: main
Choose a base branch
from
Draft
Changes from 1 commit
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
0c969bb
Initial commit for pygmt/projection.py; Contains a generic design/lay…
Nov 17, 2019
16819cc
Updated docstrings for class projection definitions.
Nov 18, 2019
979d057
Initial run of Black to reformat code.
Nov 18, 2019
c1161a3
Renamed lon0 to central_longitude and lat0 to central_latitude.
Nov 19, 2019
29e263d
Added the attribute to give meaning to the width argument (inches or…
Nov 19, 2019
129ae99
Updated example, and cleaned up docstring for unit description.
Nov 19, 2019
adef7ad
Removed center attribute from printed example.
Dec 7, 2019
97c836b
Specifying the projection code directly in the attrib creation, rathe…
Dec 7, 2019
a414f7e
Added the miscellaneous projections group; Mollweide, Sinusoidal, Eck…
Dec 7, 2019
c7ee1a2
Capitalised projection names where required, eg when named after the …
Dec 7, 2019
db7aca6
Added the Polyconic projection.
Dec 7, 2019
825cd66
Added the Miller and oblique 1, 2, 3 projections.
Dec 7, 2019
acaca7d
Added the Transverse Mercator and Universal Transverse Mercator Proje…
Dec 7, 2019
919102d
Added the equidistant cylindrical projection.
Dec 7, 2019
f5897a8
Fixed as per @leouieda suggestions.
Dec 7, 2019
7abe416
Missed one of the fixes as suggested by @leouieda
Dec 8, 2019
45abd59
Changed the default unit of inches to centimetres.
Dec 8, 2019
b9997c1
Removed superfluous comments regarding the private variables.
Dec 8, 2019
f92c7d1
Run Black formatting.
Dec 8, 2019
4161f9e
Update keyword args for the GeneralPerspective projection.
Jan 14, 2020
968b2cd
Initial unittests for the projection class configurations.
Jan 14, 2020
a77fd13
Added Polar and Linear projections. General cleanup.
Dec 18, 2022
d030593
Apply black formatting
Dec 18, 2022
cd38f61
Various reconfigs; some projs have updated, updated some that specifi…
Dec 19, 2022
4793155
Added a bunch more projections to the test suite.
Dec 19, 2022
0f24da2
Reworked the cylindrical projections to cater for the default and non…
Dec 20, 2022
a43d4c8
Added tests for the 3 oblique mercator projection options.
Dec 20, 2022
f39053a
Added tests for UTM, mercator, equidistant cylindrical. Minor additio…
Dec 21, 2022
f386b09
Applied black formatting.
Dec 21, 2022
8995715
Merge branch 'main' into proj-classes
Dec 23, 2022
20693e7
Caught test fails and updated.
Dec 23, 2022
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
Prev Previous commit
Next Next commit
Various reconfigs; some projs have updated, updated some that specifi…
…ed optional params. General cleanup.
  • Loading branch information
Josh Sixsmith committed Dec 19, 2022
commit cd38f61e64819cfaf7290169cf0c5d69495b2b20
115 changes: 82 additions & 33 deletions pygmt/projection.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"""

import numbers
from typing import Union
import attr
Copy link
Member

Choose a reason for hiding this comment

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

attr is a good choice for this 👍



Expand All @@ -20,7 +21,7 @@ def __str__(self):
"Convert to the GMT-style projection code."
exclude = attr.fields(self.__class__)._fmt
kwargs = attr.asdict(self, filter=attr.filters.exclude(exclude))
Copy link
Member

Choose a reason for hiding this comment

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

Does _code or other _ arguments not need to be excluded as well?

Copy link
Author

Choose a reason for hiding this comment

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

_code is required for the string formatter to work. But I thought it best to keep the attribute hidden from the user, and let the class populate by default the required GMT code.

return f"-J{self._fmt.format(**kwargs)}"
return f"{self._fmt.format(**kwargs)}"


@attr.s(kw_only=True)
Expand Down Expand Up @@ -146,15 +147,25 @@ class _Miscellaneous(_Projection):
Default is ``c``.
"""

central_meridian: float = attr.ib()
central_meridian: Union[float, str] = attr.ib(default="")
width: float = attr.ib()
unit: str = attr.ib(default="c")

_fmt: str = attr.ib(
init=False,
repr=False,
default="{_code}{central_meridian}/{width}{unit}",
default="{_code}{_central_meridian}{width}{unit}",
)
_central_meridian: str = attr.ib(init=False, repr=False, default="")

def __attrs_post_init__(self):
"""Handling the default case; not supplying a central meridian."""
if self.central_meridian:
cm_fmt = f"{self.central_meridian}/"
else:
cm_fmt = ""

object.__setattr__(self, "_central_meridian", cm_fmt)


@attr.s(frozen=True)
Expand Down Expand Up @@ -688,17 +699,33 @@ class Polyconic(_Projection):
Default is ``c``.
"""

central_longitude: float = attr.ib()
central_latitude: float = attr.ib()
# whilst this proj is part of the conic family, the params are different:
# central lon/lat are optionals
# two standard parallels are not defined in the proj code string
central_longitude: float = attr.ib(default=None)
central_latitude: float = attr.ib(default=None)
width: float = attr.ib()
unit: str = attr.ib(default="c")

_fmt: str = attr.ib(
init=False,
repr=False,
default="{_code}{central_longitude}/{central_latitude}/{width}{unit}",
default="{_code}{_central_lon}{_central_lat}{width}{unit}",
)
_code: str = attr.ib(init=False, repr=False, default="Poly")
_code: str = attr.ib(init=False, repr=False, default="Poly/")
_central_lon = attr.ib(init=False, repr=False, default="")
_central_lat = attr.ib(init=False, repr=False, default="")

def __attrs_post_init__(self):
"""
For frozen instances, we have to set using the traditonal way
using object.__setattr__(self, key, value).
"""
if self.central_longitude:
object.__setattr__(self, "_central_lon", f"{self.central_longitude}/")

if self.central_latitude:
object.__setattr__(self, "_central_lat", f"{self.central_latitude}/")


@attr.s(frozen=True)
Expand All @@ -717,6 +744,8 @@ class Miller(_Miscellaneous):
Default is ``c``.
"""

# a cylindrical proj, but we're basing of miscellaneous as the
# standard parallel param isn't defined in the code string for Miller
_code: str = attr.ib(init=False, repr=False, default="J")


Expand All @@ -738,19 +767,42 @@ class ObliqueMercator1(_Projection):
unit : str
The unit for the figure width in ``i`` for inch, ``c`` for centimetre.
Default is ``c``.
allow_southern_hemisphere : bool
If set to True, then allow projection poles in the southern hemisphere.
Default is to map any such poles to their antipodes in the northern
hemisphere.
align_yaxis : bool
If set to True, then align the oblique with the y-axis.
Default is to align with the x-axis.
"""

central_longitude: float = attr.ib()
central_latitude: float = attr.ib()
azimuth: float = attr.ib()
width: float = attr.ib()
unit: str = attr.ib(default="c")
allow_southern_hemisphere: bool = attr.ib(default=False)
align_yaxis: bool = attr.ib(default=False)

_fmt: str = attr.ib(
init=False,
repr=False,
default="{_code}{central_longitude}/{central_latitude}/{azimuth}/{width}{unit}",
default="{_code}{_sth_hem}{central_longitude}/{central_latitude}/{azimuth}/{width}{unit}{_align_y}",
)
_code: str = attr.ib(init=False, repr=False, default="Oa")
_code: str = attr.ib(init=False, repr=False, default="O")
_sth_hem: str = attr.ib(init=False, repr=False, default="")
_align_y: str = attr.ib(init=False, repr=False, default="")

def __attrs_post_init__(self):
"""
For frozen instances, we have to set using the traditonal way
using object.__setattr__(self, key, value).
"""
if self.allow_southern_hemisphere:
object.__setattr__(self, "_sth_hem", "A")

if self.align_yaxis:
object.__setattr__(self, "_align_y", "+v")


@attr.s(frozen=True, kw_only=True)
Expand Down Expand Up @@ -936,21 +988,17 @@ class Polar(_Projection):
depth_options : str | int | float
The string ``p`` indicates that your data are actually depths.
A numerical value ti get radial annotations ``r = radius - z`` instead.

radial : str
Set to ``r`` if radial is elevations in degrees, or ``z`` if
annotations are depth. Default is '' (radius).
"""

clockwise: bool = attr.ib(default=False, kw_only=True)
flip: bool = attr.ib(default=False, kw_only=True)
flip_options = attr.ib(default="", kw_only=True)
clockwise: bool = attr.ib(default=False)
flip: bool = attr.ib(default=False)
flip_options = attr.ib(default="")
width: float = attr.ib()
unit: str = attr.ib(default="c")
origin: float = attr.ib(default=0, kw_only=True)
offset: float = attr.ib(default=0, kw_only=True)
depth = attr.ib(default=False, kw_only=True)
depth_options = attr.ib(default=False, kw_only=True)
origin: float = attr.ib(default=0)
offset: float = attr.ib(default=0)
depth: bool = attr.ib(default=False)
depth_options = attr.ib(default=False)

_code: str = attr.ib(init=False, repr=False, default="P")
_fmt: str = attr.ib(
Expand Down Expand Up @@ -996,9 +1044,8 @@ def __attrs_post_init__(self):
For frozen instances, we have to set using the traditonal way
using object.__setattr__(self, key, value).
"""
# cw_value = "+a" if self.clockwise else ""
if self.clockwise:
object.__setattr__(self, "_clockwise", self.clockwise)
object.__setattr__(self, "_clockwise", "+a")

if self.offset:
object.__setattr__(self, "_offset", f"+r{self.offset}")
Expand All @@ -1007,15 +1054,17 @@ def __attrs_post_init__(self):
object.__setattr__(self, "_origin", f"+t{self.origin}")

# flip and depth have an options field
# two options;
# 1. override with an empty str,
# two options if the user has provided options without depth=True;
# 1. override user input with an empty str,
# 2. raise an exception if the associated bool is not set to True

if self.flip:
flip_str = "+f"

if self.flip_options:
flip_str += f"{self.flip_options}"

object.__setattr__(self, "_flip", flip_str)
else:
object.__setattr__(self, "_flip", "") # override

Expand All @@ -1034,7 +1083,7 @@ def _time_check(self, attribute, value):
"""
Validate the time field for the linear projection.
"""
msg = "time must be 't' 'T' (relative to TIME_EPOCH or absolute time)."
msg = "time must be 't' or 'T' (relative to TIME_EPOCH or absolute time)."
if isinstance(value, str):
if value not in ["t", "T", ""]: # empty str caters for default value
raise ValueError(msg)
Expand All @@ -1053,15 +1102,15 @@ class Linear(_Projection):
"""

width: float = attr.ib()
height: float = attr.ib(default=False, kw_only=True)
height: float = attr.ib(default=False)
unit: str = attr.ib(default="c")
geographic: bool = attr.ib(default=False, kw_only=True)
log_x: bool = attr.ib(default=False, kw_only=True)
log_y: bool = attr.ib(default=False, kw_only=True)
power_x: float = attr.ib(default=False, kw_only=True)
power_y: float = attr.ib(default=False, kw_only=True)
time_x: str = attr.ib(default="", kw_only=True, validator=_time_check)
time_y: str = attr.ib(default="", kw_only=True, validator=_time_check)
geographic: bool = attr.ib(default=False)
log_x: bool = attr.ib(default=False)
log_y: bool = attr.ib(default=False)
power_x: float = attr.ib(default=False)
power_y: float = attr.ib(default=False)
time_x: str = attr.ib(default="", validator=_time_check)
time_y: str = attr.ib(default="", validator=_time_check)

_code: str = attr.ib(init=False, repr=False, default="X")
_fmt: str = attr.ib(
Expand Down