Skip to content

Commit

Permalink
add deprecation warning when using +init= syntax (#358)
Browse files Browse the repository at this point in the history
* add deprecation warning when using +init= syntax

* removed change allowing more flexibility to initializing transform

* lint fixes

* rename pyproj.warnings to pyproj.warn for compatibility with python2

* updated history & added warnings to API docs

* lint fixes
  • Loading branch information
snowman2 authored Jul 2, 2019
1 parent d0500f7 commit d7978fa
Show file tree
Hide file tree
Showing 18 changed files with 223 additions and 132 deletions.
2 changes: 1 addition & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ install:
- pip install coveralls

script:
- python -c "import pyproj; pyproj.Proj(init='epsg:4269')"
- python -c "import pyproj; pyproj.Proj('epsg:4269')"
- make test-coverage
# Building and uploading docs with doctr
- set -e
Expand Down
4 changes: 2 additions & 2 deletions appveyor.yml
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ install:

test_script:
# Run the project tests
- "%CMD_IN_ENV% python -c \"import pyproj; pyproj.Proj(init='epsg:4269')\""
- "%CMD_IN_ENV% python -c \"import pyproj; pyproj.Proj('epsg:4269')\""
- "%CMD_IN_ENV% py.test --cov-report term-missing --cov=pyproj -v -s"

after_test:
Expand All @@ -140,7 +140,7 @@ after_test:
# - "%CMD_IN_ENV% python setup.py bdist_msi"
# test wheel
- pip install pyproj --ignore-installed -f dist
- python -c "import pyproj; pyproj.Proj(init='epsg:4269')"
- python -c "import pyproj; pyproj.Proj('epsg:4269')"
# cleanup for test dir
- if %PROJSOURCE% == git del /F /Q dist\*
- ps: "ls dist"
Expand Down
1 change: 1 addition & 0 deletions docs/api/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,5 @@ API Documentation
datadir
enums
exceptions
warn
show_versions
5 changes: 5 additions & 0 deletions docs/api/warn.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
Warnings
========

.. automodule:: pyproj.warn
:members:
5 changes: 5 additions & 0 deletions docs/history.rst
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
Change Log
==========

2.2.1
~~~~~
* Added custom warnings for pyproj (pull #358)
* Add deprecation warning when using +init= syntax (pull #358)

2.2.1
~~~~~
* Added :meth:`~pyproj.show_versions()` (issue #334)
Expand Down
13 changes: 9 additions & 4 deletions pyproj/_crs.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ from pyproj.compat import cstrencode, pystrdecode
from pyproj._datadir cimport get_pyproj_context
from pyproj.enums import WktVersion, ProjVersion
from pyproj.exceptions import CRSError
from pyproj.warn import PyProjDeprecationWarning


cdef cstrdecode(const char *instring):
Expand Down Expand Up @@ -1527,7 +1528,8 @@ cdef class _CRS(Base):
pyproj.CRS: The geodetic CRS from this CRS.
"""
warnings.warn(
"This method is deprecated an has been replaced with `CRS.geodetic_crs`."
"This method is deprecated an has been replaced with `CRS.geodetic_crs`.",
PyProjDeprecationWarning,
)
return self.geodetic_crs

Expand All @@ -1547,7 +1549,7 @@ cdef class _CRS(Base):
the source CRS:
>>> from pyproj import CRS
>>> ccs = CRS("+init=epsg:4328 +towgs84=0,0,0")
>>> ccs = CRS("+proj=geocent +datum=WGS84 +towgs84=0,0,0")
>>> ccs.to_epsg()
>>> ccs.source_crs.to_epsg()
4978
Expand Down Expand Up @@ -1587,7 +1589,7 @@ cdef class _CRS(Base):
the source CRS:
>>> from pyproj import CRS
>>> ccs = CRS("+init=epsg:4328 +towgs84=0,0,0")
>>> ccs = CRS("+proj=geocent +datum=WGS84 +towgs84=0,0,0")
>>> ccs.to_authority()
>>> ccs.source_crs.to_authority()
('EPSG', '4978')
Expand Down Expand Up @@ -1765,7 +1767,10 @@ cdef class _CRS(Base):
-------
bool: True if CRS is valid.
"""
warnings.warn("CRS.is_valid is deprecated.")
warnings.warn(
"CRS.is_valid is deprecated.",
PyProjDeprecationWarning,
)
return self._type != PJ_TYPE_UNKNOWN

@property
Expand Down
4 changes: 3 additions & 1 deletion pyproj/_proj.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import warnings
from pyproj.compat import cstrencode, pystrdecode
from pyproj._datadir cimport get_pyproj_context
from pyproj.exceptions import ProjError
from pyproj.warn import PyProjDeprecationWarning


# # version number string for PROJ
Expand Down Expand Up @@ -41,7 +42,8 @@ cdef class Proj:
def proj_version(self):
warnings.warn(
"'Proj.proj_version' is deprecated. "
"Please use `pyproj.proj_version_str` instead."
"Please use `pyproj.proj_version_str` instead.",
PyProjDeprecationWarning,
)
return self._proj_version

Expand Down
53 changes: 31 additions & 22 deletions pyproj/crs.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,9 +48,10 @@
from pyproj.compat import string_types
from pyproj.exceptions import CRSError
from pyproj.geod import Geod
from pyproj.warn import ProjDeprecationWarning, PyProjWarning


def _from_dict(projparams):
def _prepare_from_dict(projparams):
# convert a dict to a proj string.
pjargs = []
for key, value in projparams.items():
Expand All @@ -64,10 +65,10 @@ def _from_dict(projparams):
pass
else:
pjargs.append("+{key}={value}".format(key=key, value=value))
return _from_string(" ".join(pjargs))
return _prepare_from_string(" ".join(pjargs))


def _from_string(in_crs_string):
def _prepare_from_string(in_crs_string):
if not in_crs_string:
raise CRSError("CRS is empty or invalid: {!r}".format(in_crs_string))
elif "{" in in_crs_string:
Expand All @@ -79,12 +80,12 @@ def _from_string(in_crs_string):

if not crs_dict:
raise CRSError("CRS is empty JSON")
return _from_dict(crs_dict)
return _prepare_from_dict(crs_dict)
elif not is_wkt(in_crs_string) and "=" in in_crs_string:
in_crs_string = re.sub(r"[\s+]?=[\s+]?", "=", in_crs_string)
in_crs_string = re.sub(r"[\s+]?=[\s+]?", "=", in_crs_string.lstrip())
# make sure the projection starts with +proj or +init
starting_params = ("+init", "+proj", "init", "proj")
if not in_crs_string.lstrip().startswith(starting_params):
if not in_crs_string.startswith(starting_params):
kvpairs = []
first_item_inserted = False
for kvpair in in_crs_string.split():
Expand All @@ -108,15 +109,21 @@ def _from_string(in_crs_string):
# remove no_defs as it does nothing as of PROJ 6.0.0 and breaks
# initialization with +init=epsg:...
in_crs_string = re.sub(r"\s\+?no_defs([\w=]+)?", "", in_crs_string)
if in_crs_string.startswith(("+init", "init")):
warnings.warn(
"'+init=<authority>:<code>' syntax is deprecated."
" '<authority>:<code>' is the preferred initialization method.",
ProjDeprecationWarning,
)
return in_crs_string


def _from_authority(auth_name, auth_code):
def _prepare_from_authority(auth_name, auth_code):
return "{}:{}".format(auth_name, auth_code)


def _from_epsg(auth_code):
return _from_authority("epsg", auth_code)
def _prepare_from_epsg(auth_code):
return _prepare_from_authority("epsg", auth_code)


class CRS(_CRS):
Expand Down Expand Up @@ -281,15 +288,15 @@ def __init__(self, projparams=None, **kwargs):
False
"""
if isinstance(projparams, string_types):
projstring = _from_string(projparams)
projstring = _prepare_from_string(projparams)
elif isinstance(projparams, dict):
projstring = _from_dict(projparams)
projstring = _prepare_from_dict(projparams)
elif kwargs:
projstring = _from_dict(kwargs)
projstring = _prepare_from_dict(kwargs)
elif isinstance(projparams, int):
projstring = _from_epsg(projparams)
projstring = _prepare_from_epsg(projparams)
elif isinstance(projparams, (list, tuple)) and len(projparams) == 2:
projstring = _from_authority(*projparams)
projstring = _prepare_from_authority(*projparams)
elif hasattr(projparams, "to_wkt"):
projstring = projparams.to_wkt()
else:
Expand All @@ -312,7 +319,7 @@ def from_authority(cls, auth_name, code):
-------
CRS
"""
return cls(_from_authority(auth_name, code))
return cls(_prepare_from_authority(auth_name, code))

@classmethod
def from_epsg(cls, code):
Expand All @@ -327,7 +334,7 @@ def from_epsg(cls, code):
-------
CRS
"""
return cls(_from_epsg(code))
return cls(_prepare_from_epsg(code))

@classmethod
def from_proj4(cls, in_proj_string):
Expand All @@ -344,7 +351,7 @@ def from_proj4(cls, in_proj_string):
"""
if is_wkt(in_proj_string) or "=" not in in_proj_string:
raise CRSError("Invalid PROJ string: {}".format(in_proj_string))
return cls(_from_string(in_proj_string))
return cls(_prepare_from_string(in_proj_string))

@classmethod
def from_wkt(cls, in_wkt_string):
Expand All @@ -361,7 +368,7 @@ def from_wkt(cls, in_wkt_string):
"""
if not is_wkt(in_wkt_string):
raise CRSError("Invalid WKT string: {}".format(in_wkt_string))
return cls(_from_string(in_wkt_string))
return cls(_prepare_from_string(in_wkt_string))

@classmethod
def from_string(cls, in_crs_string):
Expand All @@ -382,7 +389,7 @@ def from_string(cls, in_crs_string):
-------
CRS
"""
return cls(_from_string(in_crs_string))
return cls(_prepare_from_string(in_crs_string))

def to_string(self):
"""Convert the CRS to a string.
Expand Down Expand Up @@ -457,7 +464,7 @@ def from_dict(cls, proj_dict):
-------
CRS
"""
return cls(_from_dict(proj_dict))
return cls(_prepare_from_dict(proj_dict))

def to_dict(self):
"""
Expand Down Expand Up @@ -577,7 +584,8 @@ def to_cf(self, wkt_version="WKT2_2018", errcheck=False):

if errcheck and skipped_params:
warnings.warn(
"PROJ parameters not mapped to CF: {}".format(tuple(skipped_params))
"PROJ parameters not mapped to CF: {}".format(tuple(skipped_params)),
PyProjWarning,
)
return cf_dict

Expand Down Expand Up @@ -648,7 +656,8 @@ def from_cf(in_cf, errcheck=False):

if errcheck and skipped_params:
warnings.warn(
"CF parameters not mapped to PROJ: {}".format(tuple(skipped_params))
"CF parameters not mapped to PROJ: {}".format(tuple(skipped_params)),
PyProjWarning,
)

return CRS(proj_dict)
Expand Down
8 changes: 4 additions & 4 deletions pyproj/proj.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,14 +129,14 @@ def __init__(self, projparams=None, preserve_units=True, **kwargs):
>>> x,y = p2(-120.108, 34.36116666)
>>> 'x=%9.3f y=%11.3f' % (x,y)
'x=765975.641 y=3805993.134'
>>> p = Proj(init="epsg:32667", preserve_units=False)
>>> p = Proj("epsg:32667", preserve_units=False)
>>> 'x=%12.3f y=%12.3f (meters)' % p(-114.057222, 51.045)
'x=-1783506.250 y= 6193827.033 (meters)'
>>> p = Proj("+init=epsg:32667")
>>> p = Proj("epsg:32667")
>>> 'x=%12.3f y=%12.3f (feet)' % p(-114.057222, 51.045)
'x=-5851386.754 y=20320914.191 (feet)'
>>> # test data with radian inputs
>>> p1 = Proj(init="epsg:4214")
>>> p1 = Proj("epsg:4214")
>>> x1, y1 = p1(116.366, 39.867)
>>> '{:.3f} {:.3f}'.format(x1, y1)
'2.031 0.696'
Expand Down Expand Up @@ -193,7 +193,7 @@ def __call__(self, *args, **kw):
def definition_string(self):
"""Returns formal definition string for projection
>>> Proj('+init=epsg:4326').definition_string()
>>> Proj("epsg:4326").definition_string()
'proj=longlat datum=WGS84 no_defs ellps=WGS84 towgs84=0,0,0'
>>>
"""
Expand Down
27 changes: 16 additions & 11 deletions pyproj/transformer.py
Original file line number Diff line number Diff line change
Expand Up @@ -229,7 +229,8 @@ def transform(
'120.321 0.057'
>>> transproj = Transformer.from_crs(
... {"proj":'geocent', "ellps":'WGS84', "datum":'WGS84'},
... '+init=EPSG:4326'
... "EPSG:4326",
... always_xy=True,
... )
>>> xpj, ypj, zpj = transproj.transform(
... -2704026.010,
Expand All @@ -240,8 +241,9 @@ def transform(
>>> "%.3f %.3f %.3f" % (xpj, ypj, zpj)
'-2.137 0.661 -20.531'
>>> transprojr = Transformer.from_crs(
... '+init=EPSG:4326',
... "EPSG:4326",
... {"proj":'geocent', "ellps":'WGS84', "datum":'WGS84'},
... always_xy=True,
... )
>>> xpjr, ypjr, zpjr = transprojr.transform(xpj, ypj, zpj, radians=True)
>>> "%.3f %.3f %.3f" % (xpjr, ypjr, zpjr)
Expand Down Expand Up @@ -337,17 +339,19 @@ def itransform(
'120.321 0.057'
>>> transproj = Transformer.from_crs(
... {"proj":'geocent', "ellps":'WGS84', "datum":'WGS84'},
... '+init=EPSG:4326',
... "EPSG:4326",
... always_xy=True,
... )
>>> for pt in transproj.itransform(
... [(-2704026.010, -4253051.810, 3895878.820)],
... radians=True,
... ):
... '{:.3f} {:.3f} {:.3f}'.format(*pt)
'-2.137 0.661 -20.531'
>>> transprojr = Transformer.from_proj(
... '+init=EPSG:4326',
>>> transprojr = Transformer.from_crs(
... "EPSG:4326",
... {"proj":'geocent', "ellps":'WGS84', "datum":'WGS84'},
... always_xy=True,
... )
>>> for pt in transprojr.itransform(
... [(-2.137, 0.661, -20.531)],
Expand All @@ -356,8 +360,9 @@ def itransform(
... '{:.3f} {:.3f} {:.3f}'.format(*pt)
'-2704214.394 -4254414.478 3894270.731'
>>> transproj_eq = Transformer.from_proj(
... '+init=EPSG:4326',
... 'EPSG:4326',
... '+proj=longlat +datum=WGS84 +no_defs +type=crs',
... always_xy=True,
... skip_equivalent=True
... )
>>> for pt in transproj_eq.itransform([(-2.137, 0.661)]):
Expand Down Expand Up @@ -494,9 +499,9 @@ def transform(
>>> from pyproj import Proj, transform
>>> # projection 1: UTM zone 15, grs80 ellipse, NAD83 datum
>>> # (defined by epsg code 26915)
>>> p1 = Proj(init='epsg:26915', preserve_units=False)
>>> p1 = Proj('epsg:26915', preserve_units=False)
>>> # projection 2: UTM zone 15, clrk66 ellipse, NAD27 datum
>>> p2 = Proj(init='epsg:26715', preserve_units=False)
>>> p2 = Proj('epsg:26715', preserve_units=False)
>>> # find x,y of Jefferson City, MO.
>>> x1, y1 = p1(-92.199881,38.56694)
>>> # transform this point to projection 2 coordinates.
Expand Down Expand Up @@ -595,13 +600,13 @@ def itransform(
>>> from pyproj import Proj, itransform
>>> # projection 1: WGS84
>>> # (defined by epsg code 4326)
>>> p1 = Proj(init='epsg:4326', preserve_units=False)
>>> p1 = Proj('epsg:4326', preserve_units=False)
>>> # projection 2: GGRS87 / Greek Grid
>>> p2 = Proj(init='epsg:2100', preserve_units=False)
>>> p2 = Proj('epsg:2100', preserve_units=False)
>>> # Three points with coordinates lon, lat in p1
>>> points = [(22.95, 40.63), (22.81, 40.53), (23.51, 40.86)]
>>> # transform this point to projection 2 coordinates.
>>> for pt in itransform(p1,p2,points): '%6.3f %7.3f' % pt
>>> for pt in itransform(p1,p2,points, always_xy=True): '%6.3f %7.3f' % pt
'411050.470 4497928.574'
'399060.236 4486978.710'
'458553.243 4523045.485'
Expand Down
Loading

0 comments on commit d7978fa

Please sign in to comment.