signature
stringlengths
8
3.44k
body
stringlengths
0
1.41M
docstring
stringlengths
1
122k
id
stringlengths
5
17
def xml_compare(elem1, elem2, ellipsis=False):
assert elem1.tag == elem2.tag<EOL>for key, value in elem1.attrib.items():<EOL><INDENT>assert elem2.attrib.get(key) == value<EOL><DEDENT>for key in elem2.attrib.keys():<EOL><INDENT>assert key in elem1.attrib<EOL><DEDENT>text1 = elem1.text.strip() if elem1.text else '<STR_LIT>'<EOL>text2 = elem2.text.strip() if elem2.text else '<STR_LIT>'<EOL>tail1 = elem1.tail.strip() if elem1.tail else '<STR_LIT>'<EOL>tail2 = elem2.tail.strip() if elem2.tail else '<STR_LIT>'<EOL>if ellipsis:<EOL><INDENT>if not ellipsis_match(text1, text2):<EOL><INDENT>raise ValueError('<STR_LIT>' % (elem1.text,<EOL>elem2.text))<EOL><DEDENT>if not ellipsis_match(tail1, tail2):<EOL><INDENT>raise ValueError('<STR_LIT>' % (elem1.text,<EOL>elem2.text))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>assert text1 == text2<EOL>assert tail1 == tail2<EOL><DEDENT>children1 = elem1.getchildren()<EOL>children2 = elem2.getchildren()<EOL>assert len(children1) == len(children2)<EOL>for child1, child2 in zip(children1, children2):<EOL><INDENT>xml_compare(child1, child2, ellipsis)<EOL><DEDENT>
Compare XML elements :param bool ellipsis: Support ellipsis for 'any' match
f12181:m0
def xml_str_compare(string1, string2, ellipsis=False):
doc1 = etree.fromstring(string1)<EOL>doc2 = etree.fromstring(string2)<EOL>xml_compare(doc1, doc2, ellipsis)<EOL>
Compare XML string representations :param bool ellipsis: Support ellipsis for 'any' match
f12181:m1
@click.command(context_settings={'<STR_LIT>': ['<STR_LIT>', '<STR_LIT>']})<EOL>@click.option('<STR_LIT>', '<STR_LIT>', help='<STR_LIT>')<EOL>def main(force):
click.secho('<STR_LIT>', nl=False, fg='<STR_LIT>', bold=True, blink=True)<EOL>click.echo("""<STR_LIT>""")<EOL>cached = <NUM_LIT:0><EOL>for filename, url in SOURCES.items():<EOL><INDENT>filename = os.path.join(os.path.dirname(__file__), '<STR_LIT:data>', filename)<EOL>if not force and os.path.exists(filename):<EOL><INDENT>print('<STR_LIT>' % filename)<EOL>cached += <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>print('<STR_LIT>' % url)<EOL>if url.endswith('<STR_LIT>'):<EOL><INDENT>temp = tempfile.mkstemp()[<NUM_LIT:1>]<EOL>try:<EOL><INDENT>urlretrieve(url, temp)<EOL>data = gzip.GzipFile(temp).read()<EOL><DEDENT>finally:<EOL><INDENT>os.unlink(temp)<EOL><DEDENT>with click.open_file(filename, '<STR_LIT:w>') as f:<EOL><INDENT>f.write(data)<EOL><DEDENT><DEDENT>elif url.endswith('<STR_LIT>'):<EOL><INDENT>data = bz2.decompress(urlopen(url).read())<EOL>with click.open_file(filename, '<STR_LIT:w>') as f:<EOL><INDENT>f.write(data)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>urlretrieve(url, filename)<EOL><DEDENT><DEDENT><DEDENT>if cached > <NUM_LIT:1>:<EOL><INDENT>click.secho(<EOL>"<STR_LIT>",<EOL>fg='<STR_LIT>'<EOL>)<EOL><DEDENT>
Fetch non-free data files.
f12182:m0
def __init__(self, latitude, longitude, altitude=None, name=None,<EOL>description=None):
super(Placemark, self).__init__(latitude, longitude, altitude, name)<EOL>if altitude:<EOL><INDENT>self.altitude = float(altitude)<EOL><DEDENT>self.description = description<EOL>
Initialise a new ``Placemark`` object. Args: latitude (float): Placemarks's latitude longitude (float): Placemark's longitude altitude (float): Placemark's altitude name (str): Name for placemark description (str): Placemark's description
f12190:c0:m0
def __str__(self):
location = super(Placemark, self).__format__('<STR_LIT>')<EOL>if self.description:<EOL><INDENT>return '<STR_LIT>' % (location, self.description)<EOL><DEDENT>else:<EOL><INDENT>return location<EOL><DEDENT>
Pretty printed location string. Returns: str: Human readable string representation of ``Placemark`` object
f12190:c0:m1
def tokml(self):
placemark = create_elem('<STR_LIT>')<EOL>if self.name:<EOL><INDENT>placemark.set('<STR_LIT:id>', self.name)<EOL>placemark.name = create_elem('<STR_LIT:name>', text=self.name)<EOL><DEDENT>if self.description:<EOL><INDENT>placemark.description = create_elem('<STR_LIT:description>',<EOL>text=self.description)<EOL><DEDENT>placemark.Point = create_elem('<STR_LIT>')<EOL>data = [str(self.longitude), str(self.latitude)]<EOL>if self.altitude:<EOL><INDENT>if int(self.altitude) == self.altitude:<EOL><INDENT>data.append('<STR_LIT>' % self.altitude)<EOL><DEDENT>else:<EOL><INDENT>data.append(str(self.altitude))<EOL><DEDENT><DEDENT>placemark.Point.coordinates = create_elem('<STR_LIT>',<EOL>text='<STR_LIT:U+002C>'.join(data))<EOL>return placemark<EOL>
Generate a KML Placemark element subtree. Returns: etree.Element: KML Placemark element
f12190:c0:m2
def __init__(self, kml_file=None):
super(Placemarks, self).__init__()<EOL>self._kml_file = kml_file<EOL>if kml_file:<EOL><INDENT>self.import_locations(kml_file)<EOL><DEDENT>
Initialise a new ``Placemarks`` object.
f12190:c1:m0
def import_locations(self, kml_file):
self._kml_file = kml_file<EOL>data = utils.prepare_xml_read(kml_file, objectify=True)<EOL>for place in data.Document.Placemark:<EOL><INDENT>name = place.name.text<EOL>coords = place.Point.coordinates.text<EOL>if coords is None:<EOL><INDENT>logging.info('<STR_LIT>' % name)<EOL>continue<EOL><DEDENT>coords = coords.split('<STR_LIT:U+002C>')<EOL>if len(coords) == <NUM_LIT:2>:<EOL><INDENT>longitude, latitude = coords<EOL>altitude = None<EOL><DEDENT>elif len(coords) == <NUM_LIT:3>:<EOL><INDENT>longitude, latitude, altitude = coords<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>% coords)<EOL><DEDENT>try:<EOL><INDENT>description = place.description<EOL><DEDENT>except AttributeError:<EOL><INDENT>description = None<EOL><DEDENT>self[name] = Placemark(latitude, longitude, altitude, name,<EOL>description)<EOL><DEDENT>
Import KML data files. ``import_locations()`` returns a dictionary with keys containing the section title, and values consisting of :class:`Placemark` objects. It expects data files in KML format, as specified in `KML Reference`_, which is XML such as:: <?xml version="1.0" encoding="utf-8"?> <kml xmlns="http://earth.google.com/kml/2.1"> <Document> <Placemark id="Home"> <name>Home</name> <Point> <coordinates>-0.221,52.015,60</coordinates> </Point> </Placemark> <Placemark id="Cambridge"> <name>Cambridge</name> <Point> <coordinates>0.390,52.167</coordinates> </Point> </Placemark> </Document> </kml> The reader uses the :mod:`ElementTree` module, so should be very fast when importing data. The above file processed by ``import_locations()`` will return the following ``dict`` object:: {"Home": Placemark(52.015, -0.221, 60), "Cambridge": Placemark(52.167, 0.390, None)} Args: kml_file (iter): KML data to read Returns: dict: Named locations with optional comments .. _KML Reference: http://code.google.com/apis/kml/documentation/kmlreference.html
f12190:c1:m1
def export_kml_file(self):
kml = create_elem('<STR_LIT>')<EOL>kml.Document = create_elem('<STR_LIT>')<EOL>for place in sorted(self.values(), key=lambda x: x.name):<EOL><INDENT>kml.Document.append(place.tokml())<EOL><DEDENT>return etree.ElementTree(kml)<EOL>
Generate KML element tree from ``Placemarks``. Returns: etree.ElementTree: KML element tree depicting ``Placemarks``
f12190:c1:m2
def __init__(self, latitude, longitude, name=None, description=None,<EOL>elevation=None, time=None):
super(_GpxElem, self).__init__(latitude, longitude, time=time)<EOL>self.name = name<EOL>self.description = description<EOL>self.elevation = elevation<EOL>
Initialise a new ``_GpxElem`` object. Args: latitude (float): Element's latitude longitude (float): Element's longitude name (str): Name for Element description (str): Element's description elevation (float): Element's elevation time (utils.Timestamp): Time the data was generated
f12191:c0:m0
def __str__(self):
location = super(_GpxElem, self).__format__('<STR_LIT>')<EOL>if self.elevation:<EOL><INDENT>location += '<STR_LIT>' % self.elevation<EOL><DEDENT>if self.time:<EOL><INDENT>location += '<STR_LIT>' % self.time.isoformat()<EOL><DEDENT>if self.name:<EOL><INDENT>text = ['<STR_LIT>' % (self.name, location), ]<EOL><DEDENT>else:<EOL><INDENT>text = [location, ]<EOL><DEDENT>if self.description:<EOL><INDENT>text.append('<STR_LIT>' % self.description)<EOL><DEDENT>return '<STR_LIT:U+0020>'.join(text)<EOL>
Pretty printed location string. Returns: str: Human readable string representation of :class:`_GpxElem` object
f12191:c0:m1
def togpx(self):
element = create_elem(self.__class__._elem_name,<EOL>{'<STR_LIT>': str(self.latitude),<EOL>'<STR_LIT>': str(self.longitude)})<EOL>if self.name:<EOL><INDENT>element.append(create_elem('<STR_LIT:name>', text=self.name))<EOL><DEDENT>if self.description:<EOL><INDENT>element.append(create_elem('<STR_LIT>', text=self.description))<EOL><DEDENT>if self.elevation:<EOL><INDENT>element.append(create_elem('<STR_LIT>', text=str(self.elevation)))<EOL><DEDENT>if self.time:<EOL><INDENT>element.append(create_elem('<STR_LIT:time>', text=self.time.isoformat()))<EOL><DEDENT>return element<EOL>
Generate a GPX waypoint element subtree. Returns: etree.Element: GPX element
f12191:c0:m2
def __init__(self, gpx_file=None, metadata=None):
super(_SegWrap, self).__init__()<EOL>self.metadata = metadata if metadata else _GpxMeta()<EOL>self._gpx_file = gpx_file<EOL>if gpx_file:<EOL><INDENT>self.import_locations(gpx_file)<EOL><DEDENT>
Initialise a new ``_SegWrap`` object.
f12191:c1:m0
def distance(self, method='<STR_LIT>'):
distances = []<EOL>for segment in self:<EOL><INDENT>if len(segment) < <NUM_LIT:2>:<EOL><INDENT>distances.append([])<EOL><DEDENT>else:<EOL><INDENT>distances.append(segment.distance(method))<EOL><DEDENT><DEDENT>return distances<EOL>
Calculate distances between locations in segments. Args: method (str): Method used to calculate distance Returns: list of list of float: Groups of distance between points in segments
f12191:c1:m1
def bearing(self, format='<STR_LIT>'):
bearings = []<EOL>for segment in self:<EOL><INDENT>if len(segment) < <NUM_LIT:2>:<EOL><INDENT>bearings.append([])<EOL><DEDENT>else:<EOL><INDENT>bearings.append(segment.bearing(format))<EOL><DEDENT><DEDENT>return bearings<EOL>
Calculate bearing between locations in segments. Args: format (str): Format of the bearing string to return Returns: list of list of float: Groups of bearings between points in segments
f12191:c1:m2
def final_bearing(self, format='<STR_LIT>'):
bearings = []<EOL>for segment in self:<EOL><INDENT>if len(segment) < <NUM_LIT:2>:<EOL><INDENT>bearings.append([])<EOL><DEDENT>else:<EOL><INDENT>bearings.append(segment.final_bearing(format))<EOL><DEDENT><DEDENT>return bearings<EOL>
Calculate final bearing between locations in segments. Args: format (str): Format of the bearing string to return Returns: list of list of float: Groups of bearings between points in segments
f12191:c1:m3
def inverse(self):
inverses = []<EOL>for segment in self:<EOL><INDENT>if len(segment) < <NUM_LIT:2>:<EOL><INDENT>inverses.append([])<EOL><DEDENT>else:<EOL><INDENT>inverses.append(segment.inverse())<EOL><DEDENT><DEDENT>return inverses<EOL>
Calculate the inverse geodesic between locations in segments. Returns: list of 2-tuple of float: Groups in bearing and distance between points in segments
f12191:c1:m4
def midpoint(self):
midpoints = []<EOL>for segment in self:<EOL><INDENT>if len(segment) < <NUM_LIT:2>:<EOL><INDENT>midpoints.append([])<EOL><DEDENT>else:<EOL><INDENT>midpoints.append(segment.midpoint())<EOL><DEDENT><DEDENT>return midpoints<EOL>
Calculate the midpoint between locations in segments. Returns: list of Point: Groups of midpoint between points in segments
f12191:c1:m5
def range(self, location, distance):
return (segment.range(location, distance) for segment in self)<EOL>
Test whether locations are within a given range of ``location``. Args: location (Point): Location to test range against distance (float): Distance to test location is within Returns: list of list of Point: Groups of points in range per segment
f12191:c1:m6
def destination(self, bearing, distance):
return (segment.destination(bearing, distance) for segment in self)<EOL>
Calculate destination locations for given distance and bearings. Args: bearing (float): Bearing to move on in degrees distance (float): Distance in kilometres Returns: list of list of Point: Groups of points shifted by ``distance`` and ``bearing``
f12191:c1:m7
def sunrise(self, date=None, zenith=None):
return (segment.sunrise(date, zenith) for segment in self)<EOL>
Calculate sunrise times for locations. Args: date (datetime.date): Calculate rise or set for given date zenith (str): Calculate sunrise events, or end of twilight Returns: list of list of datetime.datetime: The time for the sunrise for each point in each segment
f12191:c1:m8
def sunset(self, date=None, zenith=None):
return (segment.sunset(date, zenith) for segment in self)<EOL>
Calculate sunset times for locations. Args: date (datetime.date): Calculate rise or set for given date zenith (str): Calculate sunset events, or start of twilight times Returns: list of list of datetime.datetime: The time for the sunset for each point in each segment
f12191:c1:m9
def sun_events(self, date=None, zenith=None):
return (segment.sun_events(date, zenith) for segment in self)<EOL>
Calculate sunrise/sunset times for locations. Args: date (datetime.date): Calculate rise or set for given date zenith (str): Calculate rise/set events, or twilight times Returns: list of list of 2-tuple of datetime.datetime: The time for the sunrise and sunset events for each point in each segment
f12191:c1:m10
def to_grid_locator(self, precision='<STR_LIT>'):
return (segment.to_grid_locator(precision) for segment in self)<EOL>
Calculate Maidenhead locator for locations. Args: precision (str): Precision with which generate locator string Returns: list of list of str: Groups of Maidenhead locator for each point in segments
f12191:c1:m11
def speed(self):
return (segment.speed() for segment in self)<EOL>
Calculate speed between locations per segment. Returns: list of list of float: Speed between points in each segment in km/h
f12191:c1:m12
def __init__(self, name=None, desc=None, author=None, copyright=None,<EOL>link=None, time=None, keywords=None, bounds=None,<EOL>extensions=None):
super(_GpxMeta, self).__init__()<EOL>self.name = name<EOL>self.desc = desc<EOL>self.author = author if author else {}<EOL>self.copyright = copyright if copyright else {}<EOL>self.link = link if link else []<EOL>self.time = time<EOL>self.keywords = keywords<EOL>self.bounds = bounds<EOL>self.extensions = extensions<EOL>
Initialise a new `_GpxMeta` object. Args: name (str): Name for the export desc (str): Description for the GPX export author (dict): Author of the entire GPX data copyright (dict): Copyright data for the exported data link (list of str or dict): Links associated with the data time (utils.Timestamp):Time the data was generated keywords (str): Keywords associated with the data bounds (dict or list of Point): Area used in the data extensions (list of etree.Element): Any external data associated with the export
f12191:c2:m0
def togpx(self):
metadata = create_elem('<STR_LIT>')<EOL>if self.name:<EOL><INDENT>metadata.append(create_elem('<STR_LIT:name>', text=self.name))<EOL><DEDENT>if self.desc:<EOL><INDENT>metadata.append(create_elem('<STR_LIT>', text=self.desc))<EOL><DEDENT>if self.author:<EOL><INDENT>element = create_elem('<STR_LIT>')<EOL>if self.author['<STR_LIT:name>']:<EOL><INDENT>element.append(create_elem('<STR_LIT:name>', text=self.author['<STR_LIT:name>']))<EOL><DEDENT>if self.author['<STR_LIT:email>']:<EOL><INDENT>attr = dict(zip(self.author['<STR_LIT:email>'].split('<STR_LIT:@>'),<EOL>('<STR_LIT:id>', '<STR_LIT>')))<EOL>element.append(create_elem('<STR_LIT:email>', attr))<EOL><DEDENT>if self.author['<STR_LIT>']:<EOL><INDENT>element.append(create_elem('<STR_LIT>', text=self.author['<STR_LIT>']))<EOL><DEDENT>metadata.append(element)<EOL><DEDENT>if self.copyright:<EOL><INDENT>if self.copyright['<STR_LIT:name>']:<EOL><INDENT>author = {'<STR_LIT>': self.copyright['<STR_LIT:name>']}<EOL><DEDENT>else:<EOL><INDENT>author = None<EOL><DEDENT>element = create_elem('<STR_LIT>', author)<EOL>if self.copyright['<STR_LIT>']:<EOL><INDENT>element.append(create_elem('<STR_LIT>',<EOL>text=self.copyright['<STR_LIT>']))<EOL><DEDENT>if self.copyright['<STR_LIT>']:<EOL><INDENT>license = create_elem('<STR_LIT>')<EOL>element.append(license)<EOL><DEDENT>metadata.append(element)<EOL><DEDENT>if self.link:<EOL><INDENT>for link in self.link:<EOL><INDENT>if isinstance(link, basestring):<EOL><INDENT>element = create_elem('<STR_LIT>', {'<STR_LIT>': link})<EOL><DEDENT>else:<EOL><INDENT>element = create_elem('<STR_LIT>', {'<STR_LIT>': link['<STR_LIT>']})<EOL>if link['<STR_LIT:text>']:<EOL><INDENT>element.append(create_elem('<STR_LIT:text>', text=link['<STR_LIT:text>']))<EOL><DEDENT>if link['<STR_LIT:type>']:<EOL><INDENT>element.append(create_elem('<STR_LIT:type>', text=link['<STR_LIT:type>']))<EOL><DEDENT><DEDENT>metadata.append(element)<EOL><DEDENT><DEDENT>if isinstance(self.time, (time.struct_time, tuple)):<EOL><INDENT>text = time.strftime('<STR_LIT>', self.time)<EOL><DEDENT>elif isinstance(self.time, utils.Timestamp):<EOL><INDENT>text = self.time.isoformat()<EOL><DEDENT>else:<EOL><INDENT>text = time.strftime('<STR_LIT>')<EOL><DEDENT>metadata.append(create_elem('<STR_LIT:time>', text=text))<EOL>if self.keywords:<EOL><INDENT>metadata.append(create_elem('<STR_LIT>', text=self.keywords))<EOL><DEDENT>if self.bounds:<EOL><INDENT>if not isinstance(self.bounds, dict):<EOL><INDENT>latitudes = list(map(attrgetter('<STR_LIT>'), self.bounds))<EOL>longitudes = list(map(attrgetter('<STR_LIT>'), self.bounds))<EOL>bounds = {<EOL>'<STR_LIT>': str(min(latitudes)),<EOL>'<STR_LIT>': str(max(latitudes)),<EOL>'<STR_LIT>': str(min(longitudes)),<EOL>'<STR_LIT>': str(max(longitudes)),<EOL>}<EOL><DEDENT>else:<EOL><INDENT>bounds = dict((k, str(v)) for k, v in self.bounds.items())<EOL><DEDENT>metadata.append(create_elem('<STR_LIT>', bounds))<EOL><DEDENT>if self.extensions:<EOL><INDENT>element = create_elem('<STR_LIT>')<EOL>for i in self.extensions:<EOL><INDENT>element.append(i)<EOL><DEDENT>metadata.append(self.extensions)<EOL><DEDENT>return metadata<EOL>
Generate a GPX metadata element subtree. Returns: etree.Element: GPX metadata element
f12191:c2:m1
def import_metadata(self, elements):
metadata_elem = lambda name: etree.QName(GPX_NS, name)<EOL>for child in elements.getchildren():<EOL><INDENT>tag_ns, tag_name = child.tag[<NUM_LIT:1>:].split('<STR_LIT:}>')<EOL>if not tag_ns == GPX_NS:<EOL><INDENT>continue<EOL><DEDENT>if tag_name in ('<STR_LIT:name>', '<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>setattr(self, tag_name, child.text)<EOL><DEDENT>elif tag_name == '<STR_LIT:time>':<EOL><INDENT>self.time = utils.Timestamp.parse_isoformat(child.text)<EOL><DEDENT>elif tag_name == '<STR_LIT>':<EOL><INDENT>self.author['<STR_LIT:name>'] = child.findtext(metadata_elem('<STR_LIT:name>'))<EOL>aemail = child.find(metadata_elem('<STR_LIT:email>'))<EOL>if aemail:<EOL><INDENT>self.author['<STR_LIT:email>'] = '<STR_LIT>' % (aemail.get('<STR_LIT:id>'),<EOL>aemail.get('<STR_LIT>'))<EOL><DEDENT>self.author['<STR_LIT>'] = child.findtext(metadata_elem('<STR_LIT>'))<EOL><DEDENT>elif tag_name == '<STR_LIT>':<EOL><INDENT>self.bounds = {<EOL>'<STR_LIT>': child.get('<STR_LIT>'),<EOL>'<STR_LIT>': child.get('<STR_LIT>'),<EOL>'<STR_LIT>': child.get('<STR_LIT>'),<EOL>'<STR_LIT>': child.get('<STR_LIT>'),<EOL>}<EOL><DEDENT>elif tag_name == '<STR_LIT>':<EOL><INDENT>self.extensions = child.getchildren()<EOL><DEDENT>elif tag_name == '<STR_LIT>':<EOL><INDENT>if child.get('<STR_LIT>'):<EOL><INDENT>self.copyright['<STR_LIT:name>'] = child.get('<STR_LIT>')<EOL><DEDENT>self.copyright['<STR_LIT>'] = child.findtext(metadata_elem('<STR_LIT>'))<EOL>self.copyright['<STR_LIT>'] = child.findtext(metadata_elem('<STR_LIT>'))<EOL><DEDENT>elif tag_name == '<STR_LIT>':<EOL><INDENT>link = {<EOL>'<STR_LIT>': child.get('<STR_LIT>'),<EOL>'<STR_LIT:type>': child.findtext(metadata_elem('<STR_LIT:type>')),<EOL>'<STR_LIT:text>': child.findtext(metadata_elem('<STR_LIT:text>')),<EOL>}<EOL>self.link.append(link)<EOL><DEDENT><DEDENT>
Import information from GPX metadata. Args: elements (etree.Element): GPX metadata subtree
f12191:c2:m2
def __init__(self, gpx_file=None, metadata=None):
super(Waypoints, self).__init__()<EOL>self.metadata = metadata if metadata else _GpxMeta()<EOL>self._gpx_file = gpx_file<EOL>if gpx_file:<EOL><INDENT>self.import_locations(gpx_file)<EOL><DEDENT>
Initialise a new ``Waypoints`` object.
f12191:c4:m0
def import_locations(self, gpx_file):
self._gpx_file = gpx_file<EOL>data = utils.prepare_xml_read(gpx_file, objectify=True)<EOL>try:<EOL><INDENT>self.metadata.import_metadata(data.metadata)<EOL><DEDENT>except AttributeError:<EOL><INDENT>pass<EOL><DEDENT>for waypoint in data.wpt:<EOL><INDENT>latitude = waypoint.get('<STR_LIT>')<EOL>longitude = waypoint.get('<STR_LIT>')<EOL>try:<EOL><INDENT>name = waypoint.name.text<EOL><DEDENT>except AttributeError:<EOL><INDENT>name = None<EOL><DEDENT>try:<EOL><INDENT>description = waypoint.desc.text<EOL><DEDENT>except AttributeError:<EOL><INDENT>description = None<EOL><DEDENT>try:<EOL><INDENT>elevation = float(waypoint.ele.text)<EOL><DEDENT>except AttributeError:<EOL><INDENT>elevation = None<EOL><DEDENT>try:<EOL><INDENT>time = utils.Timestamp.parse_isoformat(waypoint.time.text)<EOL><DEDENT>except AttributeError:<EOL><INDENT>time = None<EOL><DEDENT>self.append(Waypoint(latitude, longitude, name, description,<EOL>elevation, time))<EOL><DEDENT>
Import GPX data files. ``import_locations()`` returns a list with :class:`~gpx.Waypoint` objects. It expects data files in GPX format, as specified in `GPX 1.1 Schema Documentation`_, which is XML such as:: <?xml version="1.0" encoding="utf-8" standalone="no"?> <gpx version="1.1" creator="PocketGPSWorld.com" xmlns="http://www.topografix.com/GPX/1/1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd"> <wpt lat="52.015" lon="-0.221"> <name>Home</name> <desc>My place</desc> </wpt> <wpt lat="52.167" lon="0.390"> <name>MSR</name> <desc>Microsoft Research, Cambridge</desc> </wpt> </gpx> The reader uses the :mod:`ElementTree` module, so should be very fast when importing data. The above file processed by ``import_locations()`` will return the following ``list`` object:: [Waypoint(52.015, -0.221, "Home", "My place"), Waypoint(52.167, 0.390, "MSR", "Microsoft Research, Cambridge")] Args: gpx_file (iter): GPX data to read Returns: list: Locations with optional comments .. _GPX 1.1 Schema Documentation: http://www.topografix.com/GPX/1/1/
f12191:c4:m1
def export_gpx_file(self):
gpx = create_elem('<STR_LIT>', GPX_ELEM_ATTRIB)<EOL>if not self.metadata.bounds:<EOL><INDENT>self.metadata.bounds = self[:]<EOL><DEDENT>gpx.append(self.metadata.togpx())<EOL>for place in self:<EOL><INDENT>gpx.append(place.togpx())<EOL><DEDENT>return etree.ElementTree(gpx)<EOL>
Generate GPX element tree from ``Waypoints`` object. Returns: etree.ElementTree: GPX element tree depicting ``Waypoints`` object
f12191:c4:m2
def import_locations(self, gpx_file):
self._gpx_file = gpx_file<EOL>data = utils.prepare_xml_read(gpx_file, objectify=True)<EOL>try:<EOL><INDENT>self.metadata.import_metadata(data.metadata)<EOL><DEDENT>except AttributeError:<EOL><INDENT>pass<EOL><DEDENT>for segment in data.trk.trkseg:<EOL><INDENT>points = point.TimedPoints()<EOL>for trackpoint in segment.trkpt:<EOL><INDENT>latitude = trackpoint.get('<STR_LIT>')<EOL>longitude = trackpoint.get('<STR_LIT>')<EOL>try:<EOL><INDENT>name = trackpoint.name.text<EOL><DEDENT>except AttributeError:<EOL><INDENT>name = None<EOL><DEDENT>try:<EOL><INDENT>description = trackpoint.desc.text<EOL><DEDENT>except AttributeError:<EOL><INDENT>description = None<EOL><DEDENT>try:<EOL><INDENT>elevation = float(trackpoint.ele.text)<EOL><DEDENT>except AttributeError:<EOL><INDENT>elevation = None<EOL><DEDENT>try:<EOL><INDENT>time = utils.Timestamp.parse_isoformat(trackpoint.time.text)<EOL><DEDENT>except AttributeError:<EOL><INDENT>time = None<EOL><DEDENT>points.append(Trackpoint(latitude, longitude, name,<EOL>description, elevation, time))<EOL><DEDENT>self.append(points)<EOL><DEDENT>
Import GPX data files. ``import_locations()`` returns a series of lists representing track segments with :class:`Trackpoint` objects as contents. It expects data files in GPX format, as specified in `GPX 1.1 Schema Documentation`_, which is XML such as:: <?xml version="1.0" encoding="utf-8" standalone="no"?> <gpx version="1.1" creator="upoints/0.12.2" xmlns="http://www.topografix.com/GPX/1/1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd"> <trk> <trkseg> <trkpt lat="52.015" lon="-0.221"> <name>Home</name> <desc>My place</desc> </trkpt> <trkpt lat="52.167" lon="0.390"> <name>MSR</name> <desc>Microsoft Research, Cambridge</desc> </trkpt> </trkseg> </trk> </gpx> The reader uses the :mod:`ElementTree` module, so should be very fast when importing data. The above file processed by ``import_locations()`` will return the following ``list`` object:: [[Trackpoint(52.015, -0.221, "Home", "My place"), Trackpoint(52.167, 0.390, "MSR", "Microsoft Research, Cambridge")], ] Args: gpx_file (iter): GPX data to read Returns: list: Locations with optional comments .. _GPX 1.1 Schema Documentation: http://www.topografix.com/GPX/1/1/
f12191:c6:m0
def export_gpx_file(self):
gpx = create_elem('<STR_LIT>', GPX_ELEM_ATTRIB)<EOL>if not self.metadata.bounds:<EOL><INDENT>self.metadata.bounds = [j for i in self for j in i]<EOL><DEDENT>gpx.append(self.metadata.togpx())<EOL>track = create_elem('<STR_LIT>')<EOL>gpx.append(track)<EOL>for segment in self:<EOL><INDENT>chunk = create_elem('<STR_LIT>')<EOL>track.append(chunk)<EOL>for place in segment:<EOL><INDENT>chunk.append(place.togpx())<EOL><DEDENT><DEDENT>return etree.ElementTree(gpx)<EOL>
Generate GPX element tree from ``Trackpoints``. Returns: etree.ElementTree: GPX element tree depicting ``Trackpoints`` objects
f12191:c6:m1
def import_locations(self, gpx_file):
self._gpx_file = gpx_file<EOL>data = utils.prepare_xml_read(gpx_file, objectify=True)<EOL>try:<EOL><INDENT>self.metadata.import_metadata(data.metadata)<EOL><DEDENT>except AttributeError:<EOL><INDENT>pass<EOL><DEDENT>for route in data.rte:<EOL><INDENT>points = point.TimedPoints()<EOL>for routepoint in route.rtept:<EOL><INDENT>latitude = routepoint.get('<STR_LIT>')<EOL>longitude = routepoint.get('<STR_LIT>')<EOL>try:<EOL><INDENT>name = routepoint.name.text<EOL><DEDENT>except AttributeError:<EOL><INDENT>name = None<EOL><DEDENT>try:<EOL><INDENT>description = routepoint.desc.text<EOL><DEDENT>except AttributeError:<EOL><INDENT>description = None<EOL><DEDENT>try:<EOL><INDENT>elevation = float(routepoint.ele.text)<EOL><DEDENT>except AttributeError:<EOL><INDENT>elevation = None<EOL><DEDENT>try:<EOL><INDENT>time = utils.Timestamp.parse_isoformat(routepoint.time.text)<EOL><DEDENT>except AttributeError:<EOL><INDENT>time = None<EOL><DEDENT>points.append(Routepoint(latitude, longitude, name,<EOL>description, elevation, time))<EOL><DEDENT>self.append(points)<EOL><DEDENT>
Import GPX data files. ``import_locations()`` returns a series of lists representing track segments with :class:`Routepoint` objects as contents. It expects data files in GPX format, as specified in `GPX 1.1 Schema Documentation`_, which is XML such as:: <?xml version="1.0" encoding="utf-8" standalone="no"?> <gpx version="1.1" creator="upoints/0.12.2" xmlns="http://www.topografix.com/GPX/1/1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd"> <rte> <rtept lat="52.015" lon="-0.221"> <name>Home</name> <desc>My place</desc> </rtept> <rtept lat="52.167" lon="0.390"> <name>MSR</name> <desc>Microsoft Research, Cambridge</desc> </rtept> </rte> </gpx> The reader uses the :mod:`ElementTree` module, so should be very fast when importing data. The above file processed by ``import_locations()`` will return the following ``list`` object:: [[Routepoint(52.015, -0.221, "Home", "My place"), Routepoint(52.167, 0.390, "MSR", "Microsoft Research, Cambridge")], ] Args: gpx_file (iter): GPX data to read Returns: list: Locations with optional comments .. _GPX 1.1 Schema Documentation: http://www.topografix.com/GPX/1/1/
f12191:c8:m0
def export_gpx_file(self):
gpx = create_elem('<STR_LIT>', GPX_ELEM_ATTRIB)<EOL>if not self.metadata.bounds:<EOL><INDENT>self.metadata.bounds = [j for i in self for j in i]<EOL><DEDENT>gpx.append(self.metadata.togpx())<EOL>for rte in self:<EOL><INDENT>chunk = create_elem('<STR_LIT>')<EOL>gpx.append(chunk)<EOL>for place in rte:<EOL><INDENT>chunk.append(place.togpx())<EOL><DEDENT><DEDENT>return etree.ElementTree(gpx)<EOL>
Generate GPX element tree from :class:`Routepoints`. Returns: etree.ElementTree: GPX element tree depicting :class:`Routepoints` objects
f12191:c8:m1
def __init__(self, latitude, longitude, comment=None):
super(Xearth, self).__init__(latitude, longitude)<EOL>self.comment = comment<EOL>
Initialise a new ``Xearth`` object. Args: latitude (float): Location's latitude longitude (float): Location's longitude comment (str): Comment for location
f12192:c0:m0
def __str__(self):
text = super(Xearth, self).__str__()<EOL>if self.comment:<EOL><INDENT>return '<STR_LIT>' % (self.comment, text)<EOL><DEDENT>else:<EOL><INDENT>return text<EOL><DEDENT>
Pretty printed location string. See also: ``point.Point`` Returns: str: Human readable string representation of ``Xearth`` object
f12192:c0:m1
def __init__(self, marker_file=None):
super(Xearths, self).__init__()<EOL>self._marker_file = marker_file<EOL>if marker_file:<EOL><INDENT>self.import_locations(marker_file)<EOL><DEDENT>
Initialise a new ``Xearths`` object.
f12192:c1:m0
def __str__(self):
return '<STR_LIT:\n>'.join(utils.dump_xearth_markers(self, '<STR_LIT>'))<EOL>
``Xearth`` objects rendered for use with Xearth/Xplanet. Returns: str: Xearth/Xplanet marker file formatted output
f12192:c1:m1
def import_locations(self, marker_file):
self._marker_file = marker_file<EOL>data = utils.prepare_read(marker_file)<EOL>for line in data:<EOL><INDENT>line = line.strip()<EOL>if not line or line.startswith('<STR_LIT:#>'):<EOL><INDENT>continue<EOL><DEDENT>chunk = line.split('<STR_LIT:#>')<EOL>data = chunk[<NUM_LIT:0>]<EOL>comment = chunk[<NUM_LIT:1>].strip() if len(chunk) == <NUM_LIT:2> else None<EOL>latitude, longitude, name = data.split(None, <NUM_LIT:2>)<EOL>name = name.strip()<EOL>name = name[<NUM_LIT:1>:name.find(name[<NUM_LIT:0>], <NUM_LIT:1>)]<EOL>self[name.strip()] = Xearth(latitude, longitude, comment)<EOL><DEDENT>
Parse Xearth data files. ``import_locations()`` returns a dictionary with keys containing the xearth_ name, and values consisting of a :class:`Xearth` object and a string containing any comment found in the marker file. It expects Xearth marker files in the following format:: # Comment 52.015 -0.221 "Home" # James Rowe's home 52.6333 -2.5 "Telford" Any empty line or line starting with a '#' is ignored. All data lines are whitespace-normalised, so actual layout should have no effect. The above file processed by ``import_locations()`` will return the following ``dict`` object:: {'Home': point.Point(52.015, -0.221, "James Rowe's home"), 'Telford': point.Point(52.6333, -2.5, None)} Note: This function also handles the extended xplanet_ marker files whose points can optionally contain added xplanet specific keywords for defining colours and fonts. Args: marker_file (iter): Xearth marker data to read Returns: dict: Named locations with optional comments .. _xearth: http://hewgill.com/xearth/original/ .. _xplanet: http://xplanet.sourceforge.net/
f12192:c1:m2
def __init__(self, latitude, longitude, altitude, name=None,<EOL>identity=None):
super(Trigpoint, self).__init__(latitude, longitude)<EOL>self.altitude = altitude<EOL>self.name = name<EOL>self.identity = identity<EOL>
Initialise a new ``Trigpoint`` object. Args: latitude (float): Location's latitude longitude (float): Location's longitude altitude (float): Location's altitude name (str): Name for location identity (int): Database identifier, if known
f12193:c0:m0
def __str__(self):
return self.__format__()<EOL>
Pretty printed location string. See also: trigpoints.point.Point Returns: str: Human readable string representation of ``Station`` object
f12193:c0:m1
def __format__(self, format_spec='<STR_LIT>'):
location = [super(Trigpoint, self).__format__(format_spec), ]<EOL>if self.altitude:<EOL><INDENT>location.append('<STR_LIT>' % self.altitude)<EOL><DEDENT>if self.name:<EOL><INDENT>return '<STR_LIT>' % (self.name, '<STR_LIT:U+0020>'.join(location))<EOL><DEDENT>else:<EOL><INDENT>return '<STR_LIT:U+0020>'.join(location)<EOL><DEDENT>
Extended pretty printing for location strings. Args: format_spec (str): Coordinate formatting system to use Returns: str: Human readable string representation of ``Trigpoint`` object Raises: ValueError: Unknown value for ``format_spec``
f12193:c0:m2
def __init__(self, marker_file=None):
super(Trigpoints, self).__init__()<EOL>self._marker_file = marker_file<EOL>if marker_file:<EOL><INDENT>self.import_locations(marker_file)<EOL><DEDENT>
Initialise a new ``Trigpoints`` object.
f12193:c1:m0
def import_locations(self, marker_file):
self._marker_file = marker_file<EOL>field_names = ('<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT:name>')<EOL>pos_parse = lambda x, s: float(s[<NUM_LIT:1>:]) if s[<NUM_LIT:0>] == x else <NUM_LIT:0> - float(s[<NUM_LIT:1>:])<EOL>latitude_parse = partial(pos_parse, '<STR_LIT:N>')<EOL>longitude_parse = partial(pos_parse, '<STR_LIT:E>')<EOL>altitude_parse = lambda s: None if s.strip() == '<STR_LIT>' else float(s)<EOL>field_parsers = (str, int, latitude_parse, longitude_parse,<EOL>altitude_parse, str)<EOL>data = utils.prepare_csv_read(marker_file, field_names)<EOL>for row in (x for x in data if x['<STR_LIT>'] == '<STR_LIT>'):<EOL><INDENT>for name, parser in zip(field_names, field_parsers):<EOL><INDENT>row[name] = parser(row[name])<EOL><DEDENT>del row['<STR_LIT>']<EOL>try:<EOL><INDENT>self[row['<STR_LIT>']] = Trigpoint(**row)<EOL><DEDENT>except TypeError:<EOL><INDENT>del row[None]<EOL>self[row['<STR_LIT>']] = Trigpoint(**row)<EOL><DEDENT><DEDENT>
Import trigpoint database files. ``import_locations()`` returns a dictionary with keys containing the trigpoint identifier, and values that are :class:`Trigpoint` objects. It expects trigpoint marker files in the format provided at alltrigs-wgs84.txt_, which is the following format:: H SOFTWARE NAME & VERSION I GPSU 4.04, S SymbolSet=0 ... W,500936,N52.066035,W000.281449, 37.0,Broom Farm W,501097,N52.010585,W000.173443, 97.0,Bygrave W,505392,N51.910886,W000.186462, 136.0,Sish Lane Any line not consisting of 6 comma separated fields will be ignored. The reader uses the :mod:`csv` module, so alternative whitespace formatting should have no effect. The above file processed by ``import_locations()`` will return the following ``dict`` object:: {500936: point.Point(52.066035, -0.281449, 37.0, "Broom Farm"), 501097: point.Point(52.010585, -0.173443, 97.0, "Bygrave"), 505392: point.Point(51.910886, -0.186462, 136.0, "Sish Lane")} Args: marker_file (iter): Trigpoint marker data to read Returns: dict: Named locations with :class:`Trigpoint` objects Raises: ValueError: Invalid value for ``marker_file`` .. _alltrigs-wgs84.txt: http://www.haroldstreet.org.uk/trigpoints/
f12193:c1:m1
def _manage_location(attr):
return property(lambda self: getattr(self, '<STR_LIT>' % attr),<EOL>lambda self, value: self._set_location(attr, value))<EOL>
Build managed property interface. Args: attr (str): Property's name Returns: property: Managed property interface
f12195:m0
def _dms_formatter(latitude, longitude, mode, unistr=False):
if unistr:<EOL><INDENT>chars = ('<STR_LIT>', '<STR_LIT>', '<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>chars = ('<STR_LIT>', "<STR_LIT:'>", '<STR_LIT:">')<EOL><DEDENT>latitude_dms = tuple(map(abs, utils.to_dms(latitude, mode)))<EOL>longitude_dms = tuple(map(abs, utils.to_dms(longitude, mode)))<EOL>text = []<EOL>if mode == '<STR_LIT>':<EOL><INDENT>text.append('<STR_LIT>' % chars % latitude_dms)<EOL><DEDENT>else:<EOL><INDENT>text.append('<STR_LIT>' % chars[:<NUM_LIT:2>] % latitude_dms)<EOL><DEDENT>text.append('<STR_LIT:S>' if latitude < <NUM_LIT:0> else '<STR_LIT:N>')<EOL>if mode == '<STR_LIT>':<EOL><INDENT>text.append('<STR_LIT>' % chars % longitude_dms)<EOL><DEDENT>else:<EOL><INDENT>text.append('<STR_LIT>' % chars[:<NUM_LIT:2>] % longitude_dms)<EOL><DEDENT>text.append('<STR_LIT>' if longitude < <NUM_LIT:0> else '<STR_LIT:E>')<EOL>return text<EOL>
Generate a human readable DM/DMS location string. Args: latitude (float): Location's latitude longitude (float): Location's longitude mode (str): Coordinate formatting system to use unistr (bool): Whether to use extended character set
f12195:m1
def __init__(self, latitude, longitude, units='<STR_LIT>',<EOL>angle='<STR_LIT>', timezone=<NUM_LIT:0>):
super(Point, self).__init__()<EOL>if angle in ('<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>self._angle = angle<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>' % angle)<EOL><DEDENT>self._set_location('<STR_LIT>', latitude)<EOL>self._set_location('<STR_LIT>', longitude)<EOL>if units in ('<STR_LIT>', '<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>self.units = units<EOL><DEDENT>elif units == '<STR_LIT>':<EOL><INDENT>self.units = '<STR_LIT>'<EOL><DEDENT>elif units in ('<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>self.units = '<STR_LIT>'<EOL><DEDENT>elif units == '<STR_LIT>':<EOL><INDENT>self.units = '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>' % units)<EOL><DEDENT>self.timezone = timezone<EOL>
Initialise a new ``Point`` object. Args: latitude (float, tuple or list): Location's latitude longitude (float, tuple or list): Location's longitude angle (str): Type for specified angles units (str): Units type to be used for distances timezone (int): Offset from UTC in minutes Raises: ValueError: Unknown value for ``angle`` ValueError: Unknown value for ``units`` ValueError: Invalid value for ``latitude`` or ``longitude``
f12195:c0:m0
def _set_location(self, ltype, value):
if self._angle == '<STR_LIT>':<EOL><INDENT>if isinstance(value, (tuple, list)):<EOL><INDENT>value = utils.to_dd(*value)<EOL><DEDENT>setattr(self, '<STR_LIT>' % ltype, float(value))<EOL>setattr(self, '<STR_LIT>' % ltype, math.radians(float(value)))<EOL><DEDENT>elif self._angle == '<STR_LIT>':<EOL><INDENT>setattr(self, '<STR_LIT>' % ltype, float(value))<EOL>setattr(self, '<STR_LIT>' % ltype, math.degrees(float(value)))<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>' % self._angle)<EOL><DEDENT>if ltype == '<STR_LIT>' and not -<NUM_LIT> <= self._latitude <= <NUM_LIT>:<EOL><INDENT>raise ValueError('<STR_LIT>' % value)<EOL><DEDENT>elif ltype == '<STR_LIT>' and not -<NUM_LIT> <= self._longitude <= <NUM_LIT>:<EOL><INDENT>raise ValueError('<STR_LIT>' % value)<EOL><DEDENT>
Check supplied location data for validity, and update.
f12195:c0:m1
@property<EOL><INDENT>def __dict__(self):<DEDENT>
slots = []<EOL>cls = self.__class__<EOL>while cls is not object:<EOL><INDENT>slots.extend(cls.__slots__)<EOL>cls = cls.__base__<EOL><DEDENT>return dict((item, getattr(self, item)) for item in slots)<EOL>
Emulate ``__dict__`` class attribute for class. Returns: dict: Object attributes, as would be provided by a class that didn't set ``__slots__``
f12195:c0:m2
def __repr__(self):
return utils.repr_assist(self, {'<STR_LIT>': '<STR_LIT>'})<EOL>
Self-documenting string representation. Returnns: str: String to recreate ``Point`` object
f12195:c0:m3
def __str__(self):
return format(self)<EOL>
Pretty printed location string. Returns: str: Human readable string representation of ``Point`` object
f12195:c0:m4
def __unicode__(self):
return _dms_formatter(self, '<STR_LIT>', True)<EOL>
Pretty printed Unicode location string. Returns: str: Human readable Unicode representation of ``Point`` object
f12195:c0:m5
def __format__(self, format_spec='<STR_LIT>'):
text = []<EOL>if not format_spec: <EOL><INDENT>format_spec = '<STR_LIT>'<EOL><DEDENT>if format_spec == '<STR_LIT>':<EOL><INDENT>text.append('<STR_LIT:S>' if self.latitude < <NUM_LIT:0> else '<STR_LIT:N>')<EOL>text.append('<STR_LIT>' % abs(self.latitude))<EOL>text.append('<STR_LIT>' if self.longitude < <NUM_LIT:0> else '<STR_LIT:E>')<EOL>text.append('<STR_LIT>' % abs(self.longitude))<EOL><DEDENT>elif format_spec in ('<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>text = _dms_formatter(self.latitude, self.longitude, format_spec)<EOL><DEDENT>elif format_spec == '<STR_LIT>':<EOL><INDENT>text.append(self.to_grid_locator())<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>' % format_spec)<EOL><DEDENT>return '<STR_LIT>'.join(text)<EOL>
Extended pretty printing for location strings. Args: format_spec (str): Coordinate formatting system to use Returns: str: Human readable string representation of ``Point`` object Raises: ValueError: Unknown value for ``format_spec``
f12195:c0:m6
def __eq__(self, other, accuracy=None):
if accuracy is None:<EOL><INDENT>return hash(self) == hash(other)<EOL><DEDENT>else:<EOL><INDENT>return self.distance(other) < accuracy<EOL><DEDENT>
Compare ``Point`` objects for equality with optional accuracy amount. Args: other (Point): Object to test for equality against accuracy (float): Objects are considered equal if within ``accuracy`` ``units`` distance of each other Returns: bool: True if objects are equal within given bounds
f12195:c0:m7
def __ne__(self, other, accuracy=None):
return not self.__eq__(other, accuracy)<EOL>
Compare ``Point`` objects for inequality with optional accuracy amount. Args: other (Point): Object to test for inequality against accuracy (float): Objects are considered equal if within ``accuracy`` ``units`` distance Returns: bool: True if objects are not equal within given bounds
f12195:c0:m8
def __hash__(self):
return hash(repr(self))<EOL>
Produce an object hash for equality checks. This method returns the hash of the return value from the ``__str__`` method. It guarantees equality for objects that have the same latitude and longitude. See also: __str__ Returns: int: Hash of string representation
f12195:c0:m9
def to_grid_locator(self, precision='<STR_LIT>'):
return utils.to_grid_locator(self.latitude, self.longitude, precision)<EOL>
Calculate Maidenhead locator from latitude and longitude. Args: precision (str): Precision with which generate locator string Returns: str: Maidenhead locator for latitude and longitude
f12195:c0:m10
def distance(self, other, method='<STR_LIT>'):
longitude_difference = other.rad_longitude - self.rad_longitude<EOL>latitude_difference = other.rad_latitude - self.rad_latitude<EOL>if method == '<STR_LIT>':<EOL><INDENT>temp = math.sin(latitude_difference / <NUM_LIT:2>) ** <NUM_LIT:2> +math.cos(self.rad_latitude) *math.cos(other.rad_latitude) *math.sin(longitude_difference / <NUM_LIT:2>) ** <NUM_LIT:2><EOL>distance = <NUM_LIT:2> * utils.BODY_RADIUS * math.atan2(math.sqrt(temp),<EOL>math.sqrt(<NUM_LIT:1> - temp))<EOL><DEDENT>elif method == '<STR_LIT>':<EOL><INDENT>distance = math.acos(math.sin(self.rad_latitude) *<EOL>math.sin(other.rad_latitude) +<EOL>math.cos(self.rad_latitude) *<EOL>math.cos(other.rad_latitude) *<EOL>math.cos(longitude_difference)) *utils.BODY_RADIUS<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>' % method)<EOL><DEDENT>if self.units == '<STR_LIT>':<EOL><INDENT>return distance / utils.STATUTE_MILE<EOL><DEDENT>elif self.units == '<STR_LIT>':<EOL><INDENT>return distance / utils.NAUTICAL_MILE<EOL><DEDENT>else:<EOL><INDENT>return distance<EOL><DEDENT>
Calculate the distance from self to other. As a smoke test this check uses the example from Wikipedia's `Great-circle distance entry`_ of Nashville International Airport to Los Angeles International Airport, and is correct to within 2 kilometres of the calculation there. Args: other (Point): Location to calculate distance to method (str): Method used to calculate distance Returns: float: Distance between self and other in ``units`` Raises: ValueError: Unknown value for ``method`` .. _Great-circle distance entry: http://en.wikipedia.org/wiki/Great-circle_distance
f12195:c0:m11
def bearing(self, other, format='<STR_LIT>'):
longitude_difference = other.rad_longitude - self.rad_longitude<EOL>y = math.sin(longitude_difference) * math.cos(other.rad_latitude)<EOL>x = math.cos(self.rad_latitude) * math.sin(other.rad_latitude) -math.sin(self.rad_latitude) * math.cos(other.rad_latitude) *math.cos(longitude_difference)<EOL>bearing = math.degrees(math.atan2(y, x))<EOL>bearing = (bearing + <NUM_LIT>) % <NUM_LIT><EOL>if format == '<STR_LIT>':<EOL><INDENT>return bearing<EOL><DEDENT>elif format == '<STR_LIT:string>':<EOL><INDENT>return utils.angle_to_name(bearing)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>' % format)<EOL><DEDENT>
Calculate the initial bearing from self to other. Note: Applying common plane Euclidean trigonometry to bearing calculations suggests to us that the bearing between point A to point B is equal to the inverse of the bearing from Point B to Point A, whereas spherical trigonometry is much more fun. If the ``bearing`` method doesn't make sense to you when calculating return bearings there are plenty of resources on the web that explain spherical geometry. .. todo:: Add Rhumb line calculation Args: other (Point): Location to calculate bearing to format (str): Format of the bearing string to return Returns: float: Initial bearing from self to other in degrees Raises: ValueError: Unknown value for ``format``
f12195:c0:m12
def midpoint(self, other):
longitude_difference = other.rad_longitude - self.rad_longitude<EOL>y = math.sin(longitude_difference) * math.cos(other.rad_latitude)<EOL>x = math.cos(other.rad_latitude) * math.cos(longitude_difference)<EOL>latitude = math.atan2(math.sin(self.rad_latitude)<EOL>+ math.sin(other.rad_latitude),<EOL>math.sqrt((math.cos(self.rad_latitude) + x) ** <NUM_LIT:2><EOL>+ y ** <NUM_LIT:2>))<EOL>longitude = self.rad_longitude+ math.atan2(y, math.cos(self.rad_latitude) + x)<EOL>return Point(latitude, longitude, angle='<STR_LIT>')<EOL>
Calculate the midpoint from self to other. See also: bearing Args: other (Point): Location to calculate midpoint to Returns: Point: Great circle midpoint from self to other
f12195:c0:m13
def final_bearing(self, other, format='<STR_LIT>'):
final_bearing = (other.bearing(self) + <NUM_LIT>) % <NUM_LIT><EOL>if format == '<STR_LIT>':<EOL><INDENT>return final_bearing<EOL><DEDENT>elif format == '<STR_LIT:string>':<EOL><INDENT>return utils.angle_to_name(final_bearing)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>' % format)<EOL><DEDENT>
Calculate the final bearing from self to other. See also: bearing Args: other (Point): Location to calculate final bearing to format (str): Format of the bearing string to return Returns: float: Final bearing from self to other in degrees Raises: ValueError: Unknown value for ``format``
f12195:c0:m14
def destination(self, bearing, distance):
bearing = math.radians(bearing)<EOL>if self.units == '<STR_LIT>':<EOL><INDENT>distance *= utils.STATUTE_MILE<EOL><DEDENT>elif self.units == '<STR_LIT>':<EOL><INDENT>distance *= utils.NAUTICAL_MILE<EOL><DEDENT>angular_distance = distance / utils.BODY_RADIUS<EOL>dest_latitude = math.asin(math.sin(self.rad_latitude) *<EOL>math.cos(angular_distance) +<EOL>math.cos(self.rad_latitude) *<EOL>math.sin(angular_distance) *<EOL>math.cos(bearing))<EOL>dest_longitude = self.rad_longitude +math.atan2(math.sin(bearing) *<EOL>math.sin(angular_distance) *<EOL>math.cos(self.rad_latitude),<EOL>math.cos(angular_distance) -<EOL>math.sin(self.rad_latitude) *<EOL>math.sin(dest_latitude))<EOL>return Point(dest_latitude, dest_longitude, angle='<STR_LIT>')<EOL>
Calculate the destination from self given bearing and distance. Args: bearing (float): Bearing from self distance (float): Distance from self in ``self.units`` Returns: Point: Location after travelling ``distance`` along ``bearing``
f12195:c0:m15
def sunrise(self, date=None, zenith=None):
return utils.sun_rise_set(self.latitude, self.longitude, date, '<STR_LIT>',<EOL>self.timezone, zenith)<EOL>
Calculate the sunrise time for a ``Point`` object. See also: utils.sun_rise_set Args: date (datetime.date): Calculate rise or set for given date zenith (str): Calculate rise/set events, or twilight times Returns: datetime.datetime: The time for the given event in the specified timezone
f12195:c0:m16
def sunset(self, date=None, zenith=None):
return utils.sun_rise_set(self.latitude, self.longitude, date, '<STR_LIT>',<EOL>self.timezone, zenith)<EOL>
Calculate the sunset time for a ``Point`` object. See also: utils.sun_rise_set Args: date (datetime.date): Calculate rise or set for given date zenith (str): Calculate rise/set events, or twilight times Returns: datetime.datetime: The time for the given event in the specified timezone
f12195:c0:m17
def sun_events(self, date=None, zenith=None):
return utils.sun_events(self.latitude, self.longitude, date,<EOL>self.timezone, zenith)<EOL>
Calculate the sunrise time for a ``Point`` object. See also: utils.sun_rise_set Args: date (datetime.date): Calculate rise or set for given date zenith (str): Calculate rise/set events, or twilight times Returns: tuple of datetime.datetime: The time for the given events in the specified timezone
f12195:c0:m18
def inverse(self, other):
return (self.bearing(other), self.distance(other))<EOL>
Calculate the inverse geodesic from self to other. Args: other (Point): Location to calculate inverse geodesic to Returns: tuple of float objects: Bearing and distance from self to other
f12195:c0:m19
def __init__(self, latitude, longitude, units='<STR_LIT>',<EOL>angle='<STR_LIT>', timezone=<NUM_LIT:0>, time=None):
super(TimedPoint, self).__init__(latitude, longitude, units, angle,<EOL>timezone)<EOL>self.time = time<EOL>
Initialise a new ``TimedPoint`` object. Args: latitude (float, tuple or list): Location's latitude longitude (float, tuple or list): Location's longitude angle (str): Type for specified angles units (str): Units type to be used for distances timezone (int): Offset from UTC in minutes time (datetime.datetime): Time associated with the location
f12195:c1:m0
def __init__(self, points=None, parse=False, units='<STR_LIT>'):
super(Points, self).__init__()<EOL>self._parse = parse<EOL>self.units = units<EOL>if points:<EOL><INDENT>if parse:<EOL><INDENT>self.import_locations(points)<EOL><DEDENT>else:<EOL><INDENT>if not all(x for x in points if isinstance(x, Point)):<EOL><INDENT>raise TypeError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>self.extend(points)<EOL><DEDENT><DEDENT>
Initialise a new ``Points`` object. Args: points (list of Point): :class:`Point` objects to wrap parse (bool): Whether to attempt import of ``points`` units (str): Unit type to be used for distances when parsing string locations
f12195:c2:m0
def __repr__(self):
return utils.repr_assist(self, {'<STR_LIT>': self[:]})<EOL>
Self-documenting string representation. Returns: str: String to recreate ``Points`` object
f12195:c2:m1
def import_locations(self, locations):
for location in locations:<EOL><INDENT>data = utils.parse_location(location)<EOL>if data:<EOL><INDENT>latitude, longitude = data<EOL><DEDENT>else:<EOL><INDENT>latitude, longitude = utils.from_grid_locator(location)<EOL><DEDENT>self.append(Point(latitude, longitude, self.units))<EOL><DEDENT>
Import locations from arguments. Args: locations (list of str or tuple): Location identifiers
f12195:c2:m2
def distance(self, method='<STR_LIT>'):
if not len(self) > <NUM_LIT:1>:<EOL><INDENT>raise RuntimeError('<STR_LIT>')<EOL><DEDENT>return (self[i].distance(self[i + <NUM_LIT:1>], method)<EOL>for i in range(len(self) - <NUM_LIT:1>))<EOL>
Calculate distances between locations. Args: method (str): Method used to calculate distance Returns: list of float: Distance between points in series
f12195:c2:m3
def bearing(self, format='<STR_LIT>'):
if not len(self) > <NUM_LIT:1>:<EOL><INDENT>raise RuntimeError('<STR_LIT>')<EOL><DEDENT>return (self[i].bearing(self[i + <NUM_LIT:1>], format)<EOL>for i in range(len(self) - <NUM_LIT:1>))<EOL>
Calculate bearing between locations. Args: format (str): Format of the bearing string to return Returns: list of float: Bearing between points in series
f12195:c2:m4
def final_bearing(self, format='<STR_LIT>'):
if len(self) == <NUM_LIT:1>:<EOL><INDENT>raise RuntimeError('<STR_LIT>')<EOL><DEDENT>return (self[i].final_bearing(self[i + <NUM_LIT:1>], format)<EOL>for i in range(len(self) - <NUM_LIT:1>))<EOL>
Calculate final bearing between locations. Args: format (str): Format of the bearing string to return Returns: list of float: Bearing between points in series
f12195:c2:m5
def inverse(self):
return ((self[i].bearing(self[i + <NUM_LIT:1>]), self[i].distance(self[i + <NUM_LIT:1>]))<EOL>for i in range(len(self) - <NUM_LIT:1>))<EOL>
Calculate the inverse geodesic between locations. Returns: list of 2-tuple of float: Bearing and distance between points in series
f12195:c2:m6
def midpoint(self):
return (self[i].midpoint(self[i + <NUM_LIT:1>]) for i in range(len(self) - <NUM_LIT:1>))<EOL>
Calculate the midpoint between locations. Returns: list of Point: Midpoint between points in series
f12195:c2:m7
def range(self, location, distance):
return (x for x in self if location.__eq__(x, distance))<EOL>
Test whether locations are within a given range of ``location``. Args: location (Point): Location to test range against distance (float): Distance to test location is within Returns: list of Point: Points within range of the specified location
f12195:c2:m8
def destination(self, bearing, distance):
return (x.destination(bearing, distance) for x in self)<EOL>
Calculate destination locations for given distance and bearings. Args: bearing (float): Bearing to move on in degrees distance (float): Distance in kilometres Returns: list of Point: Points shifted by ``distance`` and ``bearing``
f12195:c2:m9
def sunrise(self, date=None, zenith=None):
return (x.sunrise(date, zenith) for x in self)<EOL>
Calculate sunrise times for locations. Args: date (datetime.date): Calculate sunrise for given date zenith (str): Calculate sunrise events, or end of twilight Returns: list of datetime.datetime: The time for the sunrise for each point
f12195:c2:m10
def sunset(self, date=None, zenith=None):
return (x.sunset(date, zenith) for x in self)<EOL>
Calculate sunset times for locations. Args: date (datetime.date): Calculate sunset for given date zenith (str): Calculate sunset events, or start of twilight Returns: list of datetime.datetime: The time for the sunset for each point
f12195:c2:m11
def sun_events(self, date=None, zenith=None):
return (x.sun_events(date, zenith) for x in self)<EOL>
Calculate sunrise/sunset times for locations. Args: date (datetime.date): Calculate rise or set for given date zenith (str): Calculate rise/set events, or twilight times Returns: list of 2-tuple of datetime.datetime: The time for the sunrise and sunset events for each point
f12195:c2:m12
def to_grid_locator(self, precision='<STR_LIT>'):
return (x.to_grid_locator(precision) for x in self)<EOL>
Calculate Maidenhead locator for locations. Args: precision (str): Precision with which generate locator string Returns: list of str: Maidenhead locator for each point
f12195:c2:m13
def speed(self):
if not len(self) > <NUM_LIT:1>:<EOL><INDENT>raise RuntimeError('<STR_LIT>')<EOL><DEDENT>try:<EOL><INDENT>times = [i.time for i in self]<EOL><DEDENT>except AttributeError:<EOL><INDENT>raise NotImplementedError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>return (distance / ((times[i + <NUM_LIT:1>] - times[i]).seconds / <NUM_LIT>)<EOL>for i, distance in enumerate(self.distance()))<EOL>
Calculate speed between :class:`Points`. Returns: list of float: Speed between :class:`Point` elements in km/h
f12195:c3:m0
def __init__(self, points=None, parse=False, units='<STR_LIT>'):
super(KeyedPoints, self).__init__()<EOL>self._parse = parse<EOL>self.units = units<EOL>if points:<EOL><INDENT>if parse:<EOL><INDENT>self.import_locations(points)<EOL><DEDENT>else:<EOL><INDENT>if not all(x for x in points.values() if isinstance(x, Point)):<EOL><INDENT>raise TypeError("<STR_LIT>"<EOL>'<STR_LIT>')<EOL><DEDENT>self.update(points)<EOL><DEDENT><DEDENT>
Initialise a new ``KeyedPoints`` object. Args: points (dict of Point): :class:`Point` objects to wrap points (bool): Whether to attempt import of ``points`` units (str): Unit type to be used for distances when parsing string locations
f12195:c4:m0
def __repr__(self):
return utils.repr_assist(self, {'<STR_LIT>': dict(self.items())})<EOL>
Self-documenting string representation. Returns: str: String to recreate ``KeyedPoints`` object
f12195:c4:m1
def import_locations(self, locations):
for identifier, location in locations:<EOL><INDENT>data = utils.parse_location(location)<EOL>if data:<EOL><INDENT>latitude, longitude = data<EOL><DEDENT>else:<EOL><INDENT>latitude, longitude = utils.from_grid_locator(location)<EOL><DEDENT>self[identifier] = Point(latitude, longitude, self.units)<EOL><DEDENT>
Import locations from arguments. Args: locations (list of 2-tuple of str): Identifiers and locations
f12195:c4:m2
def distance(self, order, method='<STR_LIT>'):
if not len(self) > <NUM_LIT:1>:<EOL><INDENT>raise RuntimeError('<STR_LIT>')<EOL><DEDENT>return (self[order[i]].distance(self[order[i + <NUM_LIT:1>]], method)<EOL>for i in range(len(order) - <NUM_LIT:1>))<EOL>
Calculate distances between locations. Args: order (list): Order to process elements in method (str): Method used to calculate distance Returns: list of float: Distance between points in ``order``
f12195:c4:m3
def bearing(self, order, format='<STR_LIT>'):
if not len(self) > <NUM_LIT:1>:<EOL><INDENT>raise RuntimeError('<STR_LIT>')<EOL><DEDENT>return (self[order[i]].bearing(self[order[i + <NUM_LIT:1>]], format)<EOL>for i in range(len(order) - <NUM_LIT:1>))<EOL>
Calculate bearing between locations. Args: order (list): Order to process elements in format (str): Format of the bearing string to return Returns: list of float: Bearing between points in series
f12195:c4:m4
def final_bearing(self, order, format='<STR_LIT>'):
if len(self) == <NUM_LIT:1>:<EOL><INDENT>raise RuntimeError('<STR_LIT>')<EOL><DEDENT>return (self[order[i]].final_bearing(self[order[i + <NUM_LIT:1>]], format)<EOL>for i in range(len(order) - <NUM_LIT:1>))<EOL>
Calculate final bearing between locations. Args: order (list): Order to process elements in format (str): Format of the bearing string to return Returns: list of float: Bearing between points in series
f12195:c4:m5
def inverse(self, order):
return ((self[order[i]].bearing(self[order[i + <NUM_LIT:1>]]),<EOL>self[order[i]].distance(self[order[i + <NUM_LIT:1>]]))<EOL>for i in range(len(order) - <NUM_LIT:1>))<EOL>
Calculate the inverse geodesic between locations. Args: order (list): Order to process elements in Returns: list of 2-tuple of float: Bearing and distance between points in series
f12195:c4:m6
def midpoint(self, order):
return (self[order[i]].midpoint(self[order[i + <NUM_LIT:1>]])<EOL>for i in range(len(order) - <NUM_LIT:1>))<EOL>
Calculate the midpoint between locations. Args: order (list): Order to process elements in Returns: list of Point: Midpoint between points in series
f12195:c4:m7
def range(self, location, distance):
return (x for x in self.items() if location.__eq__(x[<NUM_LIT:1>], distance))<EOL>
Test whether locations are within a given range of the first. Args: location (Point): Location to test range against distance (float): Distance to test location is within Returns: list of Point: Objects within specified range
f12195:c4:m8
def destination(self, bearing, distance):
return ((x[<NUM_LIT:0>], x[<NUM_LIT:1>].destination(bearing, distance))<EOL>for x in self.items())<EOL>
Calculate destination locations for given distance and bearings. Args: bearing (float): Bearing to move on in degrees distance (float): Distance in kilometres
f12195:c4:m9
def sunrise(self, date=None, zenith=None):
return ((x[<NUM_LIT:0>], x[<NUM_LIT:1>].sunrise(date, zenith)) for x in self.items())<EOL>
Calculate sunrise times for locations. Args: date (datetime.date): Calculate sunrise for given date zenith (str): Calculate sunrise events, or end of twilight Returns: list of datetime.datetime: The time for the sunrise for each point
f12195:c4:m10
def sunset(self, date=None, zenith=None):
return ((x[<NUM_LIT:0>], x[<NUM_LIT:1>].sunset(date, zenith)) for x in self.items())<EOL>
Calculate sunset times for locations. Args: date (datetime.date): Calculate sunset for given date zenith (str): Calculate sunset events, or start of twilight Returns: list of datetime.datetime: The time for the sunset for each point
f12195:c4:m11
def sun_events(self, date=None, zenith=None):
return ((x[<NUM_LIT:0>], x[<NUM_LIT:1>].sun_events(date, zenith)) for x in self.items())<EOL>
Calculate sunrise/sunset times for locations. Args: date (datetime.date): Calculate rise or set for given date zenith (str): Calculate rise/set events, or twilight times Returns: list of 2-tuple of datetime.datetime: The time for the sunrise and sunset events for each point
f12195:c4:m12
def to_grid_locator(self, precision='<STR_LIT>'):
return ((x[<NUM_LIT:0>], x[<NUM_LIT:1>].to_grid_locator(precision)) for x in self.items())<EOL>
Calculate Maidenhead locator for locations. Args: precision (str): Precision with which generate locator string Returns: list of str: Maidenhead locator for each point
f12195:c4:m13
def calc_checksum(sentence):
if sentence.startswith('<STR_LIT:$>'):<EOL><INDENT>sentence = sentence[<NUM_LIT:1>:]<EOL><DEDENT>sentence = sentence.split('<STR_LIT:*>')[<NUM_LIT:0>]<EOL>return reduce(xor, map(ord, sentence))<EOL>
Calculate a NMEA 0183 checksum for the given sentence. NMEA checksums are a simple XOR of all the characters in the sentence between the leading "$" symbol, and the "*" checksum separator. Args: sentence (str): NMEA 0183 formatted sentence
f12196:m0
def nmea_latitude(latitude):
return ('<STR_LIT>' % utils.to_dms(abs(latitude), '<STR_LIT>'),<EOL>'<STR_LIT:N>' if latitude >= <NUM_LIT:0> else '<STR_LIT:S>')<EOL>
Generate a NMEA-formatted latitude pair. Args: latitude (float): Latitude to convert Returns: tuple: NMEA-formatted latitude values
f12196:m1
def nmea_longitude(longitude):
return ('<STR_LIT>' % utils.to_dms(abs(longitude), '<STR_LIT>'),<EOL>'<STR_LIT:E>' if longitude >= <NUM_LIT:0> else '<STR_LIT>')<EOL>
Generate a NMEA-formatted longitude pair. Args: longitude (float): Longitude to convert Returns: tuple: NMEA-formatted longitude values
f12196:m2