utils

utils - Support code for upoints.

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

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.

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

Parse an ISO 8601 formatted time stamp.

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

Bases: datetime.tzinfo

Time offset from UTC.

Initialise a new TzOffset object.

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

Create a human-readable timezone string.

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

Daylight Savings Time offset.

Note

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

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

Return the offset in minutes from UTC.

Parameters:dt (any) – For compatibility with parent classes
upoints.utils.ZENITH = {None: -0.8333333333333334, 'astronomical': -18, 'civil': -6, '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
Returns:

Distance in units

Return type:

float

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
Returns:

Direction name for angle

Return type:

str

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) – Ellipsoid model to use for calculation
Returns:

Approximated Earth radius at the given latitude

Return type:

float

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
Returns:

Angle in degrees

Return type:

float

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"

Note

xplanet also supports xearth marker files, and as such can use the output from this function.

See also

upoints.xearth.Xearths.import_locations

Parameters:
  • markers (dict) – Dictionary of identifier keys, with Trigpoint values
  • name (str) – Value to use as Xearth display string
Returns:

List of strings representing an Xearth marker file

Return type:

list

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
Returns:Namespace-aware element creator
Return type:function
upoints.utils.from_grid_locator(locator)[source]

Calculate geodesic latitude/longitude from Maidenhead locator.

Parameters:

locator (str) – Maidenhead locator string

Returns:

Geodesic latitude and longitude values

Return type:

tuple of float

Raises:
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

Parameters:

coordinates (str) – ISO 6709 coordinates string

Returns:

A tuple consisting of latitude and longitude in degrees, along

with the elevation in metres

Return type:

tuple

Raises:
upoints.utils.parse_location(location)[source]

Parse latitude and longitude from string location.

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

Prepare various input types for CSV parsing.

Parameters:
  • data (iter) – Data to read
  • field_names (tuple of str) – Ordered names to assign to fields
Returns:

CSV reader suitable for parsing

Return type:

csv.DictReader

Raises:

TypeError – Invalid value for data

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

Prepare various input types for parsing.

Parameters:
  • data (iter) – Data to read
  • method (str) – Method to process data with
  • mode (str) – Custom mode to process with, if data is a file
Returns:

List suitable for parsing

Return type:

list

Raises:

TypeError – Invalid value for data

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

Prepare various input types for XML parsing.

Parameters:
  • data (iter) – Data to read
  • objectify (bool) – Parse using lxml’s objectify data binding
Returns:

Tree suitable for parsing

Return type:

etree.ElementTree

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
Returns:

Self-documenting representation of value

Return type:

str

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
Returns:

The time for the given events in the specified

timezone

Return type:

tuple of datetime.time

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
Returns:

The time for the given event in the specified

timezone, or None if the event doesn’t occur on the given date

Return type:

datetime.time or None

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
Returns:

Angle converted to decimal degrees

Return type:

float

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
Returns:

Angle converted to degrees, minutes and possibly seconds

Return type:

tuple of int

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
Returns:

Maidenhead locator for latitude and longitude

Return type:

str

Raise:
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
Returns:

ISO 6709 coordinates string

Return type:

str

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
Returns:String representation of value
Return type:str