utils

utils - Support code for :mod:upoints

upoints.utils.BODIES = {'Mercury': 2440, 'Sun': 696000, 'Neptune': 24622, 'Moon': 1738, 'Mars': 3390, 'Venus': 6052, 'Ceres': 475, 'Eris': 1200, 'Pluto': 1153, 'Jupiter': 69911, 'Uranus': 25362, 'Earth': 6367, 'Saturn': 58232}

Body radii of various solar system objects

upoints.utils.BODY_RADIUS = 6367

Default body radius to use for calculations

exception upoints.utils.FileFormatError(site=None)[source]

Bases: exceptions.ValueError

Error object for data parsing error.

New in version 0.3.0.

Initialise a new FileFormatError object.

Parameters:site (str) – Remote site name to display in error message
upoints.utils.LONGITUDE_FIELD = 20

Maidenhead locator constants

upoints.utils.NAUTICAL_MILE = 1.852

Number of kilometres per nautical mile

upoints.utils.STATUTE_MILE = 1.609

Number of kilometres per statute mile

class upoints.utils.Timestamp[source]

Bases: datetime.datetime

Class for representing an OSM timestamp value.

isoformat()[source]

Generate an ISO 8601 formatted time stamp.

Return type:str
Returns:ISO 8601 formatted time stamp
static parse_isoformat(timestamp)[source]

Parse an ISO 8601 formatted time stamp.

Parameters:timestamp (str) – Timestamp to parse
Return type:Timestamp
Returns:Parsed timestamp
class upoints.utils.TzOffset(tzstring)[source]

Bases: datetime.tzinfo

Time offset from UTC.

Initialise a new TzOffset object.

Parameters:tzstring (str) – ISO 8601 style timezone definition
as_timezone()[source]

Create a human-readable timezone string.

Return type:str
Returns:Human-readable timezone definition
dst(dt=None)[source]

Daylight Savings Time offset.

Note

This method is only for compatibility with the tzinfo interface, and does nothing

Parameters:dt – For compatibility with parent classes
utcoffset(dt=None)[source]

Return the offset in minutes from UTC.

Parameters:dt – For compatibility with parent classes
upoints.utils.ZENITH = {'civil': -6, None: -0.8333333333333334, 'astronomical': -18, 'nautical': -12}

Sunrise/-set mappings from name to angle

upoints.utils.angle_to_distance(angle, units='metric')[source]

Convert angle in to distance along a great circle.

Parameters:
  • angle (float) – Angle in degrees to convert to distance
  • units (str) – Unit type to be used for distances
Return type:

float

Returns:

Distance in units

Raises ValueError:
 

Unknown value for units

upoints.utils.angle_to_name(angle, segments=8, abbr=False)[source]

Convert angle in to direction name.

Parameters:
  • angle (float) – Angle in degrees to convert to direction name
  • segments (int) – Number of segments to split compass in to
  • abbr (bool) – Whether to return abbreviated direction string
Return type:

str

Returns:

Direction name for angle

upoints.utils.calc_radius(latitude, ellipsoid='WGS84')[source]

Calculate earth radius for a given latitude.

This function is most useful when dealing with datasets that are very localised and require the accuracy of an ellipsoid model without the complexity of code necessary to actually use one. The results are meant to be used as a BODY_RADIUS replacement when the simple geocentric value is not good enough.

The original use for calc_radius is to set a more accurate radius value for use with trigpointing databases that are keyed on the OSGB36 datum, but it has been expanded to cover other ellipsoids.

Parameters:
  • latitude (float) – Latitude to calculate earth radius for
  • ellipsoid (tuple of float objects) – Ellipsoid model to use for calculation
Return type:

float

Returns:

Approximated Earth radius at the given latitude

upoints.utils.distance_to_angle(distance, units='metric')[source]

Convert a distance in to an angle along a great circle.

Parameters:
  • distance (float) – Distance to convert to degrees
  • units (str) – Unit type to be used for distances
Return type:

float

Returns:

Angle in degrees

Raises ValueError:
 

Unknown value for units

upoints.utils.dump_xearth_markers(markers, name='identifier')[source]

Generate an Xearth compatible marker file.

dump_xearth_markers() writes a simple Xearth marker file from a dictionary of trigpoints.Trigpoint objects.

It expects a dictionary in one of the following formats. For support of Trigpoint that is:

{500936: Trigpoint(52.066035, -0.281449, 37.0, "Broom Farm"),
 501097: Trigpoint(52.010585, -0.173443, 97.0, "Bygrave"),
 505392: Trigpoint(51.910886, -0.186462, 136.0, "Sish Lane")}

And generates output of the form:

52.066035 -0.281449 "500936" # Broom Farm, alt 37m
52.010585 -0.173443 "501097" # Bygrave, alt 97m
51.910886 -0.186462 "205392" # Sish Lane, alt 136m

Or similar to the following if the name parameter is set to name:

52.066035 -0.281449 "Broom Farm" # 500936 alt 37m
52.010585 -0.173443 "Bygrave" # 501097 alt 97m
51.910886 -0.186462 "Sish Lane" # 205392 alt 136m

Point objects should be provided in the following format:

{"Broom Farm": Point(52.066035, -0.281449),
 "Bygrave": Point(52.010585, -0.173443),
 "Sish Lane": Point(51.910886, -0.186462)}

And generates output of the form:

52.066035 -0.281449 "Broom Farm"
52.010585 -0.173443 "Bygrave"
51.910886 -0.186462 "Sish Lane"
Parameters:
  • markers (dict) – Dictionary of identifier keys, with Trigpoint values
  • name (str) – Value to use as Xearth display string
Return type:

list

Returns:

List of strings representing an Xearth marker file

Raises ValueError:
 

Unsupported value for name

upoints.utils.element_creator(namespace=None)[source]

Create a simple namespace-aware objectify element creator.

Parameters:namespace (str) – Namespace to work in
Return type:function
Returns:Namespace-aware element creator
upoints.utils.from_grid_locator(locator)[source]

Calculate geodesic latitude/longitude from Maidenhead locator.

Parameters:

locator (str) – Maidenhead locator string

Return type:

tuple of float objects

Returns:

Geodesic latitude and longitude values

Raises:
  • ValueError – Incorrect grid locator length
  • ValueError – Invalid values in locator string
upoints.utils.from_iso6709(coordinates)[source]

Parse ISO 6709 coordinate strings.

This function will parse ISO 6709-1983(E) “Standard representation of latitude, longitude and altitude for geographic point locations” elements. Unfortunately, the standard is rather convoluted and this implementation is incomplete, but it does support most of the common formats in the wild.

The W3C has a simplified profile for ISO 6709 in Latitude, Longitude and Altitude format for geospatial information. It unfortunately hasn’t received widespread support as yet, but hopefully it will grow just as the simplified ISO 8601 profile has.

See also

to_iso6709()

Page str coordinates:
 

ISO 6709 coordinates string

Return type:

tuple

Returns:

A tuple consisting of latitude and longitude in degrees, along with the elevation in metres

Raises:
  • ValueError – Input string is not ISO 6709 compliant
  • ValueError – Invalid value for latitude
  • ValueError – Invalid value for longitude
upoints.utils.parse_location(location)[source]

Parse latitude and longitude from string location.

Parameters:location (str) – String to parse
Return type:tuple of float objects
Returns:Latitude and longitude of location
upoints.utils.prepare_csv_read(data, field_names, *args, **kwargs)[source]

Prepare various input types for CSV parsing.

Parameters:
  • data (file like object, list, str) – Data to read
  • field_names (tuple of str) – Ordered names to assign to fields
Return type:

csv.DictReader

Returns:

CSV reader suitable for parsing

Raises TypeError:
 

Invalid value for data

upoints.utils.prepare_read(data, method='readlines', mode='r')[source]

Prepare various input types for parsing.

Parameters:
  • data (file like object, list, str) – Data to read
  • method (str) – Method to process data with
  • mode (str) – Custom mode to process with, if data is a file
Return type:

list

Returns:

List suitable for parsing

Raises TypeError:
 

Invalid value for data

upoints.utils.prepare_xml_read(data, objectify=False)[source]

Prepare various input types for XML parsing.

Parameters:
  • data (file like object, list, str) – Data to read
  • objectify (bool) – Parse using lxml’s objectify data binding
Return type:

etree.ElementTree

Returns:

Tree suitable for parsing

Raises TypeError:
 

Invalid value for data

upoints.utils.repr_assist(obj, remap=None)[source]

Helper function to simplify __repr__ methods.

Parameters:
  • obj – Object to pull argument values for
  • remap (dict) – Argument pairs to remap before output
Return type:

str

Returns:

Self-documenting representation of value

upoints.utils.sun_events(latitude, longitude, date, timezone=0, zenith=None)[source]

Convenience function for calculating sunrise and sunset.

Civil twilight starts/ends when the Sun’s centre is 6 degrees below the horizon.

Nautical twilight starts/ends when the Sun’s centre is 12 degrees below the horizon.

Astronomical twilight starts/ends when the Sun’s centre is 18 degrees below the horizon.

Parameters:
  • latitude (float) – Location’s latitude
  • longitude (float) – Location’s longitude
  • date (datetime.date) – Calculate rise or set for given date
  • timezone (int) – Offset from UTC in minutes
  • zenith (str) – Calculate rise/set events, or twilight times
Return type:

tuple of datetime.time

Returns:

The time for the given events in the specified timezone

upoints.utils.sun_rise_set(latitude, longitude, date, mode='rise', timezone=0, zenith=None)[source]

Calculate sunrise or sunset for a specific location.

This function calculates the time sunrise or sunset, or optionally the beginning or end of a specified twilight period.

Source:

Almanac for Computers, 1990
published by Nautical Almanac Office
United States Naval Observatory
Washington, DC 20392
Parameters:
  • latitude (float) – Location’s latitude
  • longitude (float) – Location’s longitude
  • date (datetime.date) – Calculate rise or set for given date
  • mode (str) – Which time to calculate
  • timezone (int) – Offset from UTC in minutes
  • zenith (str) – Calculate rise/set events, or twilight times
Return type:

datetime.time or None

Returns:

The time for the given event in the specified timezone, or None if the event doesn’t occur on the given date

Raises ValueError:
 

Unknown value for mode

upoints.utils.to_dd(degrees, minutes, seconds=0)[source]

Convert degrees, minutes and optionally seconds to decimal angle.

Parameters:
  • degrees (float) – Number of degrees
  • minutes (float) – Number of minutes
  • seconds (float) – Number of seconds
Return type:

float

Returns:

Angle converted to decimal degrees

upoints.utils.to_dms(angle, style='dms')[source]

Convert decimal angle to degrees, minutes and possibly seconds.

Parameters:
  • angle (float) – Angle to convert
  • style (str) – Return fractional or whole minutes values
Return type:

tuple of int objects for values

Returns:

Angle converted to degrees, minutes and possibly seconds

Raises ValueError:
 

Unknown value for style

upoints.utils.to_grid_locator(latitude, longitude, precision='square')[source]

Calculate Maidenhead locator from latitude and longitude.

Parameters:
  • latitude (float) – Position’s latitude
  • longitude (float) – Position’s longitude
  • precision (str) – Precision with which generate locator string
Return type:

str

Returns:

Maidenhead locator for latitude and longitude

Raises:
  • ValueError – Invalid precision identifier
  • ValueError – Invalid latitude or longitude value
upoints.utils.to_iso6709(latitude, longitude, altitude=None, format='dd', precision=4)[source]

Produce ISO 6709 coordinate strings.

This function will produce ISO 6709-1983(E) “Standard representation of latitude, longitude and altitude for geographic point locations” elements.

See also

from_iso6709()

Parameters:
  • latitude (float) – Location’s latitude
  • longitude (float) – Location’s longitude
  • altitude (float) – Location’s altitude
  • format (str) – Format type for string
  • precision (int) – Latitude/longitude precision
Return type:

str

Returns:

ISO 6709 coordinates string

Raises ValueError:
 

Unknown value for format

upoints.utils.value_or_empty(value)[source]

Return an empty string for display when value is None.

Parameters:value (str) – Value to prepare for display
Return type:str
Returns:String representation of value