### Setup Pre-commit Hooks Source: https://github.com/pyproj4/pyproj/blob/main/CONTRIBUTING.md Install pre-commit hooks to automatically format code and run checks before commits. ```bash pre-commit install ``` -------------------------------- ### Install pyproj from GitHub using pip Source: https://github.com/pyproj4/pyproj/blob/main/docs/installation.rst Install pyproj directly from its GitHub repository using pip. ```bash pip install git+https://github.com/pyproj4/pyproj.git ``` -------------------------------- ### Install Development Requirements Source: https://github.com/pyproj4/pyproj/blob/main/CONTRIBUTING.md Install packages listed in the development requirements file. ```bash python -m pip install -r requirements-dev.txt ``` -------------------------------- ### Development installation from cloned repo Source: https://github.com/pyproj4/pyproj/blob/main/docs/installation.rst Install pyproj in editable mode from a cloned GitHub repository, suitable for development. ```bash pip install -e . ``` -------------------------------- ### Install pyproj Source: https://context7.com/pyproj4/pyproj/llms.txt Shows the commands to install the pyproj library using pip or conda. It also notes the PROJ version requirement and availability of pre-built wheels. ```bash pip install pyproj # or conda install -c conda-forge pyproj ``` -------------------------------- ### Install pyproj from PyPI Source: https://github.com/pyproj4/pyproj/blob/main/docs/installation.rst Use this command to install pyproj from the Python Package Index. The --no-binary flag ensures it's built from source. ```bash pip install pyproj --no-binary pyproj ``` -------------------------------- ### Editable Install pyproj Source: https://github.com/pyproj4/pyproj/blob/main/CONTRIBUTING.md Install pyproj in editable mode, allowing changes to be reflected immediately. ```bash python -m pip install -e . ``` -------------------------------- ### Install PROJ Data with Conda Source: https://github.com/pyproj4/pyproj/blob/main/docs/transformation_grids.rst Install PROJ transformation grids using conda from the conda-forge channel. This command installs the world dataset. ```bash conda install -c conda-forge proj-data ``` -------------------------------- ### Install nightly pyproj wheels Source: https://github.com/pyproj4/pyproj/blob/main/docs/installation.rst Install nightly wheels from Anaconda's scientific-python-nightly-wheels repository. Use the --pre flag to include pre-release versions. ```python python -m pip install pyproj --pre --extra-index-url https://pypi.anaconda.org/scientific-python-nightly-wheels/simple ``` -------------------------------- ### Set PROJ_DIR on Linux Source: https://github.com/pyproj4/pyproj/blob/main/docs/installation.rst Example of setting the PROJ_DIR environment variable on Linux to specify the PROJ installation path for building pyproj from source. ```bash export PROJ_DIR=/usr/local ``` -------------------------------- ### Set PROJ_DIR on Windows Source: https://github.com/pyproj4/pyproj/blob/main/docs/installation.rst Example of setting the PROJ_DIR environment variable on Windows to specify the PROJ installation path for building pyproj from source. ```batch set PROJ_DIR=C:\OSGeo4W\ ``` -------------------------------- ### Debugging Internal PROJ with Logging Source: https://github.com/pyproj4/pyproj/blob/main/docs/advanced_examples.rst Example of setting up logging for pyproj to capture debugging information from the internal PROJ library. Requires setting the PROJ_DEBUG environment variable. ```python import logging # Add handler to the `pyproj` logger: ``` -------------------------------- ### Example Test Function (String Return) Source: https://github.com/pyproj4/pyproj/blob/main/CONTRIBUTING.md A test case for a function that returns a string representation of the result. Asserts the expected string output. ```python def test_add_as_float_or_string_string_return(): res = add_as_float_or_string(3, 4, as_string=True) assert(res, '7') ``` -------------------------------- ### Install pyproj using pip Source: https://github.com/pyproj4/pyproj/blob/main/docs/installation.rst Use this command to install pyproj from PyPI. Ensure pip is version 19.3+ for manylinux2014 wheels. pyproj 3+ wheels do not include transformation grids. ```bash python -m pip install pyproj ``` -------------------------------- ### Run All Tests Source: https://github.com/pyproj4/pyproj/blob/main/CONTRIBUTING.md Execute the entire test suite using pytest. Ensure test dependencies are installed first. ```bash python -m pip install -r requirements-test.txt ``` ```bash python -m pytest ``` -------------------------------- ### Query PROJ Database Information Source: https://context7.com/pyproj4/pyproj/llms.txt Demonstrates how to list authorities, get EPSG projected CRS codes, find UTM CRS for a location, query CRS by type and area of interest, retrieve unit mappings, and get PROJ database metadata. ```python from pyproj import CRS, get_authorities, get_codes, get_units_map from pyproj.database import ( query_utm_crs_info, query_crs_info, get_database_metadata, query_geodetic_crs_from_datum, ) from pyproj.aoi import AreaOfInterest from pyproj.enums import PJType # List all authorities in the PROJ database authorities = get_authorities() print(authorities) # ['EPSG', 'ESRI', 'IAU_2015', 'IGNF', ...] # List all EPSG projected CRS codes epsg_projected_codes = get_codes("EPSG", PJType.PROJECTED_CRS) print(f"Number of EPSG projected CRS: {len(epsg_projected_codes)}") # Find the UTM CRS for a specific location (Iowa City, Iowa, USA) utm_crs_list = query_utm_crs_info( datum_name="WGS 84", area_of_interest=AreaOfInterest( west_lon_degree=-91.54, south_lat_degree=41.65, east_lon_degree=-91.54, north_lat_degree=41.65, ), ) utm_crs = CRS.from_epsg(utm_crs_list[0].code) print(utm_crs.name) # 'WGS 84 / UTM zone 15N' # Query CRS by type, authority, and area of interest crs_list = query_crs_info( auth_name="EPSG", pj_types=PJType.PROJECTED_CRS, area_of_interest=AreaOfInterest(-80, 35, -75, 40), contains=False, ) for info in crs_list[:5]: print(f" {info.auth_name}:{info.code} - {info.name}") # Unit mappings units = get_units_map() for name, unit in list(units.items())[:5]: print(f" {name}: {unit.to_meters} m") # PROJ database version info meta = get_database_metadata("EPSG.VERSION") print(f"PROJ DB EPSG version: {meta}") ``` -------------------------------- ### Example Test Function (Float Return) Source: https://github.com/pyproj4/pyproj/blob/main/CONTRIBUTING.md A basic test case for a function that returns a float. Asserts the expected numerical result. ```python def test_add_as_float_or_string_defaults(): res = add_as_float_or_string(3, 4) assert(res, 7) ``` -------------------------------- ### Find and Download Missing Grids Source: https://github.com/pyproj4/pyproj/blob/main/docs/transformation_grids.rst Use TransformerGroup to identify missing transformation grids and then download them. This example demonstrates finding grids for a transformation between EPSG:4326 and EPSG:2964 and then initiating the download. ```python from pyproj.transformer import TransformerGroup tg = trans_group = TransformerGroup(4326, 2964) UserWarning: Best transformation is not available due to missing Grid(short_name=us_noaa_alaska.tif, full_name=, package_name=, url=https://cdn.proj.org/us_noaa_alaska.tif, direct_download=True, open_license=True, available=False) tg - transformers: 8 - unavailable_operations: 2 tg.transformers[0].description 'Inverse of NAD27 to WGS 84 (7) + Alaska Albers' tg.unavailable_operations[0].name 'Inverse of NAD27 to WGS 84 (85) + Alaska Albers' tg.unavailable_operations[0].grids[0].url 'https://cdn.proj.org/us_noaa_alaska.tif' tg.download_grids(verbose=True) # pyproj 3+ Downloading: https://cdn.proj.org/us_noaa_alaska.tif Downloading: https://cdn.proj.org/ca_nrc_ntv2_0.tif ``` -------------------------------- ### Unit Mappings and Database Metadata Source: https://context7.com/pyproj4/pyproj/llms.txt Shows how to retrieve unit conversion mappings and get metadata about the PROJ database version. ```APIDOC ## Unit Mappings and Database Metadata ### Description Provides access to unit conversion factors and information about the PROJ database version. ### Functions - `get_units_map()`: Returns a dictionary mapping unit names to their corresponding `Unit` objects, including conversion factors to meters. - `get_database_metadata(key)`: Retrieves specific metadata from the PROJ database using a given key (e.g., "EPSG.VERSION"). ### Example Usage ```python from pyproj import get_units_map from pyproj.database import get_database_metadata # Get unit mappings units = get_units_map() print("Sample Unit Mappings:") for name, unit in list(units.items())[:5]: print(f" {name}: {unit.to_meters} m") # Get PROJ database version info meta = get_database_metadata("EPSG.VERSION") print(f"PROJ DB EPSG version: {meta}") ``` ``` -------------------------------- ### Install pyproj using conda Source: https://github.com/pyproj4/pyproj/blob/main/docs/installation.rst Install pyproj within a new conda environment using the conda-forge channel. It is recommended to use environments for stability and easier debugging. ```bash conda config --prepend channels conda-forge conda config --set channel_priority strict conda create -n pyproj_env pyproj conda activate pyproj_env ``` -------------------------------- ### Install Specific PROJ Datum Grids with Conda Source: https://github.com/pyproj4/pyproj/blob/main/docs/transformation_grids.rst Install specific PROJ datum grid packages using conda from the conda-forge channel. This is for PROJ versions 6 and earlier. ```bash conda install -c conda-forge proj-datumgrid-europe proj-datumgrid-north-america proj-datumgrid-oceania proj-datumgrid-world ``` -------------------------------- ### Optimizing Single-Threaded Applications with Global Context Source: https://github.com/pyproj4/pyproj/blob/main/docs/advanced_examples.rst Example showing how enabling the global context in pyproj can enhance performance for single-threaded applications that frequently create CRS objects. ```python import pyproj codes = pyproj.get_codes("EPSG", pyproj.enums.PJType.PROJECTED_CRS, False) crs_list = [pyproj.CRS.from_epsg(code) for code in codes] ``` -------------------------------- ### Compare CRS objects Source: https://github.com/pyproj4/pyproj/blob/main/docs/gotchas.rst This example demonstrates the difference in representation and equality between two CRS objects, one initialized with a deprecated parameter and another with the standard approach. ```python Name: CGCS2000 / 3-degree Gauss-Kruger CM 105E Axis Info [cartesian]: - E[east]: Easting (metre) - N[north]: Northing (metre) Area of Use: - name: China - 103.5°E to 106.5°E - bounds: (103.5, 22.5, 106.5, 42.21) Coordinate Operation: - name: Gauss-Kruger CM 105E - method: Transverse Mercator Datum: China 2000 - Ellipsoid: CGCS2000 - Prime Meridian: Greenwich Name: CGCS2000 / 3-degree Gauss-Kruger CM 105E Axis Info [cartesian]: - X[north]: Northing (metre) - Y[east]: Easting (metre) Area of Use: - name: China - 103.5°E to 106.5°E - bounds: (103.5, 22.5, 106.5, 42.21) Coordinate Operation: - name: Gauss-Kruger CM 105E - method: Transverse Mercator Datum: China 2000 - Ellipsoid: CGCS2000 - Prime Meridian: Greenwich ``` -------------------------------- ### Explore Available Transformations with TransformerGroup Source: https://github.com/pyproj4/pyproj/blob/main/docs/advanced_examples.rst Utilize pyproj.transformer.TransformerGroup to find available and unavailable transformations between two CRS. The example demonstrates accessing and using individual transformers from the group. ```python from pyproj.transformer import TransformerGroup trans_group = TransformerGroup("EPSG:4326","EPSG:2964") print(trans_group) print(trans_group.best_available) print(trans_group.transformers[0].transform(66, -153)) print(trans_group.transformers[1].transform(66, -153)) print(trans_group.transformers[2].transform(66, -153)) ``` -------------------------------- ### Caching pyproj Transformers Source: https://github.com/pyproj4/pyproj/blob/main/docs/advanced_examples.rst Demonstrates how to use functools.lru_cache to cache Transformer objects, significantly reducing the cost of re-creating them. Includes timeit examples comparing cached vs. non-cached creation. ```python from functools import lru_cache from pyproj import Transformer TransformerFromCRS = lru_cache(Transformer.from_crs) Transformer.from_crs(2263, 4326) # no cache TransformerFromCRS(2263, 4326) # cache ``` ```python from timeit import timeit timeit( "CachedTransformer(2263, 4326)", setup=( "from pyproj import Transformer; " "from functools import lru_cache; " "CachedTransformer = lru_cache(Transformer.from_crs)" ), number=1000000, ) timeit( "Transformer.from_crs(2263, 4326)", setup=("from pyproj import Transformer"), number=100, ) ``` -------------------------------- ### Promote 2D CRS to 3D for Height Consideration Source: https://github.com/pyproj4/pyproj/blob/main/docs/advanced_examples.rst Shows how to explicitly convert 2D Coordinate Reference Systems (CRS) to 3D using CRS.to_3d() when using PROJ 6+ to ensure ellipsoidal height is taken into account during transformations. The example includes transformations with and without the 3D conversion. ```python from pyproj import CRS, Transformer transformer = Transformer.from_crs("EPSG:4326", "EPSG:2056", always_xy=True) print(transformer.transform(8.37909, 47.01987, 1000)) ``` ```python transformer_3d = Transformer.from_crs( CRS("EPSG:4326").to_3d(), CRS("EPSG:2056").to_3d(), always_xy=True, ) print(transformer_3d.transform(8.37909, 47.01987, 1000)) ``` -------------------------------- ### Create a Compound CRS Source: https://github.com/pyproj4/pyproj/blob/main/docs/build_crs.rst Combine a VerticalCRS and a ProjectedCRS to form a CompoundCRS. This example demonstrates creating a compound CRS with specific vertical datum and geoid model information. ```python from pyproj.crs import CompoundCRS, GeographicCRS, ProjectedCRS, VerticalCRS from pyproj.crs.coordinate_system import Cartesian2DCS, VerticalCS from pyproj.crs.coordinate_operation import LambertConformalConic2SPConversion vertcrs = VerticalCRS( name="NAVD88 height", datum="North American Vertical Datum 1988", vertical_cs=VerticalCS(), geoid_model="GEOID12B", ) projcrs = ProjectedCRS( name="NAD83 / Pennsylvania South", conversion=LambertConformalConic2SPConversion( latitude_false_origin=39.3333333333333, longitude_false_origin=-77.75, latitude_first_parallel=40.9666666666667, latitude_second_parallel=39.9333333333333, ``` -------------------------------- ### Build Documentation Locally Source: https://github.com/pyproj4/pyproj/blob/main/CONTRIBUTING.md Commands to build the project documentation locally. 'make docs-browser' also opens it in a browser. ```bash make install-docs make docs make docs-browser ``` -------------------------------- ### Modify CRS with Coordinate System Units Source: https://github.com/pyproj4/pyproj/blob/main/docs/build_crs_cf.rst When units are not meters, use `cf_units.Unit` to get the conversion factor and define the coordinate system. This example shows how to handle 'US_Survey_Foot' units. ```python from cf_units import Unit from pyproj import CRS cf_unit = Unit("US_Survey_Foot") unit = { "type": "LinearUnit", "name": "US Survey Foot", "conversion_factor": cf_unit.convert(1, "m"), } cartesian_cs = { "$schema": "https://proj.org/schemas/v0.2/projjson.schema.json", "type": "CoordinateSystem", ``` -------------------------------- ### Initialize and Inspect CRS Objects Source: https://context7.com/pyproj4/pyproj/llms.txt Demonstrates various ways to initialize CRS objects using EPSG codes, PROJ strings, or keyword arguments. Shows how to inspect properties like name, type, axis information, bounds, and ellipsoid parameters. Also covers conversion to different formats and 3D/2D CRS transformations. ```python from pyproj import CRS from pyproj.enums import WktVersion # Multiple initialization styles crs_epsg = CRS.from_epsg(4326) crs_str = CRS.from_string("EPSG:26917") crs_proj4 = CRS.from_proj4("+proj=utm +zone=10 +ellps=WGS84") crs_int = CRS.from_user_input(4326) # bare integer crs_kwargs = CRS(proj="utm", zone=10, ellps="WGS84") # Inspect axis order, bounds, datum crs = CRS.from_epsg(4326) print(crs.name) # 'WGS 84' print(crs.type_name) # 'Geographic 2D CRS' print(crs.is_geographic) # True print(crs.is_projected) # False print(crs.axis_info) # [Axis(name=Geodetic latitude,...), Axis(name=Geodetic longitude,...)] print(crs.area_of_use.bounds) # (-180.0, -90.0, 180.0, 180.0) print(crs.ellipsoid.semi_major_metre) # 6378137.0 print(crs.ellipsoid.inverse_flattening) # 298.257223563 # Convert to various formats print(crs.to_epsg()) # 4326 print(crs.to_authority()) # ('EPSG', '4326') print(crs.to_proj4()) # '+proj=longlat +datum=WGS84 ...' wkt = crs.to_wkt(WktVersion.WKT2_2019, pretty=True) json_str = crs.to_json(pretty=True) cf_dict = crs.to_cf() # CF-1.8 grid mapping dict # 3D / 2D conversion crs_3d = CRS.from_epsg(4326).to_3d() crs_2d = crs_3d.to_2d() # Equality and deprecation crs_a = CRS.from_epsg(4326) crs_b = CRS.from_user_input("WGS 84") print(crs_a.equals(crs_b)) # True print(crs_a.equals(crs_b, ignore_axis_order=True)) # True print(crs_a.is_deprecated) # False ``` -------------------------------- ### Initialize CRS in pyproj Source: https://github.com/pyproj4/pyproj/blob/main/docs/examples.rst Demonstrates multiple ways to initialize a CRS object using EPSG codes, PROJ strings, and user input. ```python >>> from pyproj import CRS >>> crs = CRS.from_epsg(4326) >>> crs = CRS.from_string("EPSG:4326") >>> crs = CRS.from_proj4("+proj=latlon") >>> crs = CRS.from_user_input(4326) ``` -------------------------------- ### Download Grids using wget Source: https://github.com/pyproj4/pyproj/blob/main/docs/transformation_grids.rst Download transformation grid files from the PROJ CDN using wget with the mirror option. Ensure PROJ_DOWNLOAD_DIR is set to the desired download location. ```bash wget --mirror https://cdn.proj.org/ -P ${PROJ_DOWNLOAD_DIR} ``` -------------------------------- ### Navigate to Repository Directory Source: https://github.com/pyproj4/pyproj/blob/main/CONTRIBUTING.md Change the current directory to the cloned pyproj repository. ```bash cd pyproj ``` -------------------------------- ### Build PROJ from Source Source: https://github.com/pyproj4/pyproj/blob/main/CONTRIBUTING.md Compile the PROJ library from source if the minimum required version is not available. Sets PROJ_DIR to a local directory. ```bash export PROJ_DIR=$PWD/pyproj/proj_dir mkdir $PROJ_DIR bash ci/proj-compile.sh git ``` -------------------------------- ### Create Development Environment Source: https://github.com/pyproj4/pyproj/blob/main/CONTRIBUTING.md Create a conda environment named 'devel' with necessary development packages. ```bash conda create -n devel -c conda-forge cython proj numpy shapely xarray pandas ``` -------------------------------- ### Geod.fwd_intermediate Source: https://context7.com/pyproj4/pyproj/llms.txt Computes intermediate points along a geodesic starting from a point in a given direction and distance. ```APIDOC ## Geod.fwd_intermediate ### Description Computes intermediate points along a geodesic starting from a point in a given direction and distance. ### Method `geod.fwd_intermediate(lon, lat, az, npts, del_s, return_back_azimuth)` ### Parameters - **lon** (float) - Longitude of the starting point. - **lat** (float) - Latitude of the starting point. - **az** (float) - Initial azimuth (in degrees). - **npts** (int) - The number of intermediate points to compute. - **del_s** (float) - The distance between intermediate points. - **return_back_azimuth** (bool) - Whether to return back azimuths. ### Response Returns a `GeodIntermediateReturn` object containing `lons`, `lats`, and optionally `back_azimuths`. ### Request Example ```python from pyproj import Geod geod = Geod(ellps="clrk66") boston_lon, boston_lat = -71.1167, 42.25 portland_lon, portland_lat = -123.6833, 45.5167 az12, _, dist = geod.inv(boston_lon, boston_lat, portland_lon, portland_lat) n = 5 del_s = dist / (n + 1) result_fwd = geod.fwd_intermediate( boston_lon, boston_lat, az12, npts=n, del_s=del_s, return_back_azimuth=False ) print(list(zip(result_fwd.lons, result_fwd.lats))) ``` ``` -------------------------------- ### Geod.fwd Source: https://context7.com/pyproj4/pyproj/llms.txt Calculates the destination point given a starting point, azimuth, and distance along a geodesic. ```APIDOC ## Geod.fwd ### Description Calculates the destination point given a starting point, azimuth, and distance along a geodesic. ### Method `geod.fwd(lons, lats, az, dist)` ### Parameters - **lons** (array-like) - Longitudes of the starting points. - **lats** (array-like) - Latitudes of the starting points. - **az** (array-like) - Azimuths (in degrees) from the starting points. - **dist** (array-like) - Distances along the geodesic. ### Response Returns a tuple of (end_lons, end_lats, back_azimuths). ### Request Example ```python from pyproj import Geod geod = Geod(ellps="clrk66") boston_lon, boston_lat = -71.1167, 42.25 azimuths = [0, 90, 180, 270] distances = [100_000] * 4 end_lons, end_lats, _ = geod.fwd( lons=[boston_lon]*4, lats=[boston_lat]*4, az=azimuths, dist=distances, ) for az, eln, ela in zip(azimuths, end_lons, end_lats): print(f" az={az:3d}° → lat={ela:.3f}°, lon={eln:.3f}°") ``` ``` -------------------------------- ### Activate Default Logging Configuration Source: https://github.com/pyproj4/pyproj/blob/main/docs/advanced_examples.rst Activate the default logging configuration using basicConfig. This is a simpler way to set up logging for the application. ```python import logging logging.basicConfig(format="%(levelname)s:%(message)s", level=logging.DEBUG) ``` -------------------------------- ### Geod.fwd Source: https://context7.com/pyproj4/pyproj/llms.txt Computes the terminus point longitude, latitude, and back azimuth given a starting point, forward azimuth, and distance. ```APIDOC ## Geod.fwd ### Description Computes the terminus point longitude, latitude, and back azimuth given a starting point, forward azimuth, and distance. ### Method `fwd(lons, lats, az, dist, **kwargs)` ### Parameters #### Path Parameters - **lons** (float or list) - Longitude(s) of the starting point(s). - **lats** (float or list) - Latitude(s) of the starting point(s). - **az** (float or list) - Forward azimuth(s) in degrees. - **dist** (float or list) - Distance(s) in meters. ### Request Example ```python from pyproj import Geod geod = Geod(ellps="clrk66") # Clarke 1866 ellipsoid boston_lon, boston_lat = -71.1167, 42.25 # Travel 4164192.708 m at azimuth -66.531° from Boston end_lon, end_lat, back_az = geod.fwd( lons=boston_lon, lats=boston_lat, az=-66.531, dist=4164192.708, ) print(f"End lat={end_lat:.3f}°, End lon={end_lon:.3f}°, Back az={back_az:.3f}°") ``` ### Response #### Success Response (200) - **end_lon** (float or list) - Longitude(s) of the terminus point(s). - **end_lat** (float or list) - Latitude(s) of the terminus point(s). - **back_az** (float or list) - Back azimuth(s) from the terminus point to the starting point. #### Response Example ``` End lat=45.517°, End lon=-123.683°, Back az=75.654° ``` ``` -------------------------------- ### Deprecated +init syntax for CRS Source: https://github.com/pyproj4/pyproj/blob/main/docs/gotchas.rst Avoid using the deprecated `+init=:` syntax for initializing Coordinate Reference Systems. Use the direct `:` format instead to prevent potential initialization issues. ```python >>> from pyproj import CRS >>> CRS("ESRI:54009") Name: World_Mollweide Axis Info [cartesian]: - E[east]: Easting (metre) - N[north]: Northing (metre) Area of Use: - name: World - bounds: (-180.0, -90.0, 180.0, 90.0) Coordinate Operation: - name: World_Mollweide - method: Mollweide Datum: World Geodetic System 1984 - Ellipsoid: WGS 84 - Prime Meridian: Greenwich >>> CRS("+init=ESRI:54009") ... pyproj.exceptions.CRSError: Invalid projection: +init=ESRI:54009 +type=crs: (Internal Proj Error: proj_create: cannot expand +init=ESRI:54009 +type=crs) ``` -------------------------------- ### Download Grids using AWS S3 Sync Source: https://github.com/pyproj4/pyproj/blob/main/docs/transformation_grids.rst Download transformation grid files from the PROJ CDN using the AWS S3 sync command. Ensure PROJ_DOWNLOAD_DIR is set to the desired download location. ```bash aws s3 sync s3://cdn.proj.org ${PROJ_DOWNLOAD_DIR} ``` -------------------------------- ### CRS Initialization and Inspection Source: https://context7.com/pyproj4/pyproj/llms.txt Demonstrates various ways to initialize a CRS object and inspect its properties, including conversion to different formats. ```APIDOC ## CRS Initialization and Inspection ### Description The `CRS` class is a pythonic manager for coordinate reference systems, accepting EPSG codes, PROJ strings, WKT strings, authority strings, JSON dicts, or `(auth_name, code)` tuples. Key properties expose axis info, datum, ellipsoid, prime meridian, coordinate system, and coordinate operation. ### Method `CRS.from_epsg(code: int)` `CRS.from_string(crs_string: str)` `CRS.from_proj4(proj4_string: str)` `CRS.from_user_input(user_input)` `CRS(**kwargs)` `crs.name` `crs.type_name` `crs.is_geographic` `crs.is_projected` `crs.axis_info` `crs.area_of_use.bounds` `crs.ellipsoid.semi_major_metre` `crs.ellipsoid.inverse_flattening` `crs.to_epsg()` `crs.to_authority()` `crs.to_proj4()` `crs.to_wkt(version: WktVersion, pretty: bool)` `crs.to_json(pretty: bool)` `crs.to_cf()` `crs.to_3d()` `crs.to_2d()` `crs.equals(other_crs, ignore_axis_order: bool)` `crs.is_deprecated` ### Example ```python from pyproj import CRS from pyproj.enums import WktVersion # Multiple initialization styles crs_epsg = CRS.from_epsg(4326) crs_str = CRS.from_string("EPSG:26917") crs_proj4 = CRS.from_proj4("+proj=utm +zone=10 +ellps=WGS84") crs_int = CRS.from_user_input(4326) # bare integer crs_kwargs = CRS(proj="utm", zone=10, ellps="WGS84") # Inspect axis order, bounds, datum crs = CRS.from_epsg(4326) print(crs.name) # 'WGS 84' print(crs.type_name) # 'Geographic 2D CRS' print(crs.is_geographic) # True print(crs.is_projected) # False print(crs.axis_info) # [Axis(name=Geodetic latitude,...), Axis(name=Geodetic longitude,...)] print(crs.area_of_use.bounds) # (-180.0, -90.0, 180.0, 180.0) print(crs.ellipsoid.semi_major_metre) # 6378137.0 print(crs.ellipsoid.inverse_flattening) # 298.257223563 # Convert to various formats print(crs.to_epsg()) # 4326 print(crs.to_authority()) # ('EPSG', '4326') print(crs.to_proj4()) # '+proj=longlat +datum=WGS84 ...' wkt = crs.to_wkt(WktVersion.WKT2_2019, pretty=True) json_str = crs.to_json(pretty=True) cf_dict = crs.to_cf() # CF-1.8 grid mapping dict # 3D / 2D conversion crs_3d = CRS.from_epsg(4326).to_3d() crs_2d = crs_3d.to_2d() # Equality and deprecation crs_a = CRS.from_epsg(4326) crs_b = CRS.from_user_input("WGS 84") print(crs_a.equals(crs_b)) # True print(crs_a.equals(crs_b, ignore_axis_order=True)) # True print(crs_a.is_deprecated) # False ``` ``` -------------------------------- ### Calculate Geodesic Area and Perimeter of a Polygon Source: https://github.com/pyproj4/pyproj/blob/main/docs/examples.rst Use `pyproj.Geod.geometry_area_perimeter` to calculate the geodesic area and perimeter of a shapely polygon. Ensure pyproj and shapely are installed. ```python from pyproj import Geod from shapely.geometry import LineString, Point, Polygon geod = Geod('+a=6378137 +f=0.0033528106647475126') poly_area, poly_perimeter = geod.geometry_area_perimeter( Polygon( LineString([Point(1, 1), Point(1, 10), Point(10, 10), Point(10, 1)]), holes=[LineString([Point(1, 2), Point(3, 4), Point(5, 2)])], ) ) f"{poly_area:.3f} {poly_perimeter:.3f}" '-944373881400.339 3979008.036' ``` -------------------------------- ### Create Lightweight Git Tag Source: https://github.com/pyproj4/pyproj/blob/main/HOW_TO_RELEASE.md Create a lightweight git tag on the main branch that matches the release candidate version. ```bash git checkout main git tag 3.7.2rc0 ``` -------------------------------- ### Querying CRS Information Source: https://context7.com/pyproj4/pyproj/llms.txt Demonstrates how to list authorities, get CRS codes by type, and query for specific CRS definitions based on authority and area of interest. ```APIDOC ## Querying CRS Information ### Description Functions in `pyproj.database` allow querying the PROJ database for various Coordinate Reference System (CRS) related information. ### Functions - `get_authorities()`: Lists all available authorities in the PROJ database. - `get_codes(auth_name, pj_types)`: Retrieves a list of CRS codes for a given authority and projection type. - `query_utm_crs_info(datum_name, area_of_interest)`: Finds UTM CRS definitions for a specified datum and geographic area. - `query_crs_info(auth_name, pj_types, area_of_interest, contains)`: Queries for CRS definitions matching specified criteria, including authority, type, and area of interest. ### Example Usage ```python from pyproj import CRS, get_authorities, get_codes from pyproj.database import query_utm_crs_info, query_crs_info from pyproj.aoi import AreaOfInterest from pyproj.enums import PJType # List all authorities authorities = get_authorities() print(f"Authorities: {authorities}") # List EPSG projected CRS codes epsg_projected_codes = get_codes("EPSG", PJType.PROJECTED_CRS) print(f"Number of EPSG projected CRS: {len(epsg_projected_codes)}") # Find UTM CRS for a location utm_crs_list = query_utm_crs_info( datum_name="WGS 84", area_of_interest=AreaOfInterest( west_lon_degree=-91.54, south_lat_degree=41.65, east_lon_degree=-91.54, north_lat_degree=41.65 ), ) if utm_crs_list: utm_crs = CRS.from_epsg(utm_crs_list[0].code) print(f"UTM CRS Name: {utm_crs.name}") # Query CRS by type, authority, and area of interest crs_list = query_crs_info( auth_name="EPSG", pj_types=PJType.PROJECTED_CRS, area_of_interest=AreaOfInterest(-80, 35, -75, 40), contains=False, ) print("Sample CRS found:") for info in crs_list[:5]: print(f" {info.auth_name}:{info.code} - {info.name}") ``` ``` -------------------------------- ### Retrieve Geodetic CRS from Projected CRS Source: https://github.com/pyproj4/pyproj/blob/main/docs/examples.rst Demonstrates how to get the underlying geodetic CRS from a projected CRS. This is the first step when converting between projected and geographic coordinates. ```python >>> from pyproj import CRS >>> crs = CRS.from_epsg(3857) >>> crs.geodetic_crs Name: WGS 84 Axis Info [ellipsoidal]: - Lat[north]: Geodetic latitude (degree) - Lon[east]: Geodetic longitude (degree) Area of Use: - name: World - bounds: (-180.0, -90.0, 180.0, 90.0) Datum: World Geodetic System 1984 - Ellipsoid: WGS 84 - Prime Meridian: Greenwich ``` -------------------------------- ### Export CRS to CF Grid Mapping Source: https://github.com/pyproj4/pyproj/blob/main/docs/build_crs_cf.rst Use `crs.to_cf()` to get the grid mapping representation of a CRS. This is useful for exporting CRS information to CF-compliant files. ```python from pyproj import CRS crs = CRS("EPSG:4326") cf_grid_mapping = crs.to_cf() ``` -------------------------------- ### Add Upstream Remote Source: https://github.com/pyproj4/pyproj/blob/main/CONTRIBUTING.md Connect your local repository to the main pyproj project repository. ```bash git remote add upstream https://github.com/pyproj4/pyproj.git ``` -------------------------------- ### Caching pyproj CRS Objects Source: https://github.com/pyproj4/pyproj/blob/main/docs/advanced_examples.rst Illustrates caching CRS objects using functools.lru_cache to improve performance when repeatedly creating the same CRS instances. Includes timeit examples for comparison. ```python from functools import lru_cache from pyproj import CRS CachedCRS = lru_cache(CRS) crs = CRS(4326) # no cache crs = CachedCRS(4326) # cache ``` ```python from timeit import timeit timeit( "CachedCRS(4326)", setup=( "from pyproj import CRS; " "from functools import lru_cache; " "CachedCRS = lru_cache(CRS)" ), number=1000000, ) timeit( "CRS(4326)", setup=("from pyproj import CRS"), number=1000, ) ``` -------------------------------- ### Check Code Style Locally Source: https://github.com/pyproj4/pyproj/blob/main/CONTRIBUTING.md Verify code style compliance using flake8 and Ruff formatter. Pre-commit hooks can automate this process. ```bash pre-commit run --all ``` -------------------------------- ### Forward Geodetic Problem with Geod.fwd Source: https://context7.com/pyproj4/pyproj/llms.txt Computes the terminus point longitude, latitude, and back azimuth given a starting point, forward azimuth, and distance. Uses the specified ellipsoid for calculations. ```python from pyproj import Geod geod = Geod(ellps="clrk66") # Clarke 1866 ellipsoid boston_lon, boston_lat = -71.1167, 42.25 # Travel 4164192.708 m at azimuth -66.531° from Boston end_lon, end_lat, back_az = geod.fwd( lons=boston_lon, lats=boston_lat, az=-66.531, dist=4164192.708, ) print(f"End lat={end_lat:.3f}°, End lon={end_lon:.3f}°, Back az={back_az:.3f}°") # End lat=45.517°, End lon=-123.683°, Back az=75.654° ``` -------------------------------- ### Set PROJ_DOWNLOAD_DIR for Main PROJ Data Directory Source: https://github.com/pyproj4/pyproj/blob/main/docs/transformation_grids.rst Set the PROJ_DOWNLOAD_DIR environment variable to the main PROJ data directory using Python. This is for downloading grids to the system-wide PROJ data location. ```bash export PROJ_DOWNLOAD_DIR=$(python -c "import pyproj; print(pyproj.datadir.get_data_dir())") ``` -------------------------------- ### Activate Development Environment Source: https://github.com/pyproj4/pyproj/blob/main/CONTRIBUTING.md Activate the 'devel' conda environment for development. Use 'activate devel' on Windows. ```bash conda activate devel ``` -------------------------------- ### Check Best Transformation Availability with TransformerGroup Source: https://github.com/pyproj4/pyproj/blob/main/docs/advanced_examples.rst Use pyproj.transformer.TransformerGroup to check if the best transformation is available and to inspect unavailable operations and their required grids. This example uses a custom CRS definition and enables always_xy. ```python from pyproj.transformer import TransformerGroup tg = TransformerGroup("EPSG:4326", "+proj=aea +lat_0=50 +lon_0=-154 +lat_1=55 +lat_2=65 +x_0=0 +y_0=0 +datum=NAD27 +no_defs +type=crs +units=m", always_xy=True) print(tg) print(tg.transformers[0].description) print(tg.unavailable_operations[0].name) print(tg.unavailable_operations[0].grids[0].url) ``` -------------------------------- ### Apply Area of Interest for Transformation Selection Source: https://github.com/pyproj4/pyproj/blob/main/docs/advanced_examples.rst Demonstrates how to use the AreaOfInterest class with pyproj.transformer.Transformer to influence the selection of transformation operations based on geographic location. The example shows default behavior and then with a specified area of interest. ```python from pyproj.transformer import Transformer, AreaOfInterest transformer = Transformer.from_crs("EPSG:4326", "EPSG:2694") print(transformer) ``` ```python transformer = Transformer.from_crs( "EPSG:4326", "EPSG:2694", area_of_interest=AreaOfInterest(-136.46, 49.0, -60.72, 83.17), ) print(transformer) ``` -------------------------------- ### Transformer.transform — Inverse and Error Checking Source: https://context7.com/pyproj4/pyproj/llms.txt Shows how to perform an inverse transformation and how to handle errors for invalid coordinates when `errcheck=True` is set. ```python # Inverse transform (EPSG:3857 -> EPSG:4326) from pyproj.enums import TransformDirection lons_back, lats_back = transformer.transform( xs_arr, ys_arr, direction=TransformDirection.INVERSE ) # Error checking: inf returned for invalid coords unless errcheck=True try: x_err, y_err = transformer.transform(999.0, 999.0, errcheck=True) except Exception as e: print(f"Transform error: {e}") ``` -------------------------------- ### Create Geod Class Instance Source: https://github.com/pyproj4/pyproj/blob/main/docs/examples.rst Shows how to create a Geod class instance using either an ellipsoid name or by deriving it from a CRS object. This is used for geodesic calculations. ```python >>> from pyproj import CRS, Geod >>> geod_clrk = Geod(ellps='clrk66') # Use Clarke 1866 ellipsoid. >>> geod_clrk Geod(ellps='clrk66') >>> geod_wgs84 = CRS("EPSG:4326").get_geod() >>> geod_wgs84 Geod('+a=6378137 +f=0.0033528106647475126') ``` -------------------------------- ### Get EPSG code with minimum confidence Source: https://github.com/pyproj4/pyproj/blob/main/docs/gotchas.rst The `to_epsg` method allows specifying a minimum confidence level to retrieve the closest matching EPSG code. Lowering this threshold can help find approximate matches when an exact one is not available. ```python crs_deprecated = CRS("+init=epsg:4326") crs_deprecated.to_epsg(100) crs_latlon = CRS("+proj=latlon") crs_latlon.to_epsg(70) 4326 crs_epsg = CRS.from_epsg(4326) crs_epsg.to_epsg(100) 4326 crs_wkt = CRS(crs_epsg.to_wkt()) crs_wkt.to_epsg(100) 4326 crs_wkt == crs_epsg True crs_epsg == crs_latlon False crs_epsg == crs_deprecated False ``` -------------------------------- ### Create Annotated Git Tag Source: https://github.com/pyproj4/pyproj/blob/main/HOW_TO_RELEASE.md Use this command to create an annotated git tag for a specific version. This is a standard practice for marking release points in the repository history. ```bash git tag -a 3.7.2 -m "Version 3.7.2" ``` -------------------------------- ### Run Tests in a Specific Directory Source: https://github.com/pyproj4/pyproj/blob/main/CONTRIBUTING.md Focus testing on a particular module or directory within the project. ```bash python -m pytest pyproj/calc ``` -------------------------------- ### Create a Bound CRS with towgs84 parameters Source: https://github.com/pyproj4/pyproj/blob/main/docs/build_crs.rst Construct a BoundCRS by defining a source ProjectedCRS and a target CRS ('WGS 84'), along with a ToWGS84Transformation. This is useful for transformations involving older datums. ```python from pyproj.crs import BoundCRS, Ellipsoid, GeographicCRS, ProjectedCRS from pyproj.crs.coordinate_operation import ( TransverseMercatorConversion, ToWGS84Transformation, ) from pyproj.crs.datum import CustomDatum import pyproj proj_crs = ProjectedCRS( conversion=TransverseMercatorConversion( latitude_natural_origin=0, longitude_natural_origin=15, false_easting=2520000, false_northing=0, scale_factor_natural_origin=0.9996, ), geodetic_crs=GeographicCRS( datum=CustomDatum(ellipsoid="International 1924 (Hayford 1909, 1910)") ), ) bound_crs = BoundCRS( source_crs=proj_crs, target_crs="WGS 84", transformation=ToWGS84Transformation( proj_crs.geodetic_crs, -122.74, -34.27, -22.83, -1.884, -3.4, -3.03, -15.62 ), ) crs_wkt = bound_crs.to_wkt() ``` -------------------------------- ### Run Unit Tests and Linters Source: https://github.com/pyproj4/pyproj/blob/main/CONTRIBUTING.md Automated testing includes running unit tests and the flake8 code linter via Travis CI for pull requests. ```bash Running both the unit tests as well as the `flake8` code linter. ``` -------------------------------- ### Set PROJ_DOWNLOAD_DIR for User Data Directory Source: https://github.com/pyproj4/pyproj/blob/main/docs/transformation_grids.rst Set the PROJ_DOWNLOAD_DIR environment variable to the user-writable data directory using Python. This is for downloading grids to a location managed by the user. ```bash export PROJ_DOWNLOAD_DIR=$(python -c "import pyproj; print(pyproj.datadir.get_user_data_dir())") ``` -------------------------------- ### Initialize CRS with deprecated init parameter Source: https://github.com/pyproj4/pyproj/blob/main/docs/gotchas.rst When initializing a CRS, using the deprecated `init` parameter can lead to different results compared to the modern approach. This is often due to differences in axis order. ```python from pyproj import CRS crs_deprecated = CRS(init="epsg:4544") crs = CRS("EPSG:4544") crs == crs_deprecated False ``` -------------------------------- ### Build Custom Projected and Compound CRS Source: https://context7.com/pyproj4/pyproj/llms.txt Demonstrates how to define a custom Transverse Mercator ProjectedCRS and a CompoundCRS combining geographic and vertical CRSs. ```python from pyproj import CRS, ProjectedCRS, GeographicCRS, CompoundCRS, VerticalCRS from pyproj.crs.coordinate_operation import TransverseMercatorConversion # Build a custom Projected CRS (Transverse Mercator) projected = ProjectedCRS( name="My TM CRS", conversion=TransverseMercatorConversion( latitude_natural_origin=0, longitude_natural_origin=-75, false_easting=500000, false_northing=0, scale_factor_natural_origin=0.9996, ), geodetic_crs=GeographicCRS(), ) print(projected.is_projected) # True print(projected.coordinate_operation.method_name) # 'Transverse Mercator' # Compound CRS (horizontal + vertical) vertical = VerticalCRS( name="NAVD88 height", datum="EPSG:5103", geoid_model="GEOID12B", ) compound = CompoundCRS(name="NAD83 + NAVD88", components=["EPSG:4269", vertical]) print(compound.is_compound) # True print(len(compound.sub_crs_list)) # 2 ``` -------------------------------- ### Clone pyproj Repository Source: https://github.com/pyproj4/pyproj/blob/main/CONTRIBUTING.md Clone your fork of the pyproj repository to your local machine. ```bash git clone https://github.com/your-user-name/pyproj.git ```