signature
stringlengths
8
3.44k
body
stringlengths
0
1.41M
docstring
stringlengths
1
122k
id
stringlengths
5
17
def parse_latitude(latitude, hemisphere):
latitude = int(latitude[:<NUM_LIT:2>]) + float(latitude[<NUM_LIT:2>:]) / <NUM_LIT><EOL>if hemisphere == '<STR_LIT:S>':<EOL><INDENT>latitude = -latitude<EOL><DEDENT>elif not hemisphere == '<STR_LIT:N>':<EOL><INDENT>raise ValueError('<STR_LIT>' % hemisphere)<EOL><DEDENT>return latitude<EOL>
Parse a NMEA-formatted latitude pair. Args: latitude (str): Latitude in DDMM.MMMM hemisphere (str): North or South Returns: float: Decimal representation of latitude
f12196:m3
def parse_longitude(longitude, hemisphere):
longitude = int(longitude[:<NUM_LIT:3>]) + float(longitude[<NUM_LIT:3>:]) / <NUM_LIT><EOL>if hemisphere == '<STR_LIT>':<EOL><INDENT>longitude = -longitude<EOL><DEDENT>elif not hemisphere == '<STR_LIT:E>':<EOL><INDENT>raise ValueError('<STR_LIT>' % hemisphere)<EOL><DEDENT>return longitude<EOL>
Parse a NMEA-formatted longitude pair. Args: longitude (str): Longitude in DDDMM.MMMM hemisphere (str): East or West Returns: float: Decimal representation of longitude
f12196:m4
def __init__(self, latitude, longitude, time, status, mode=None):
super(LoranPosition, self).__init__(latitude, longitude)<EOL>self.time = time<EOL>self.status = status<EOL>self.mode = mode<EOL>
Initialise a new ``LoranPosition`` object. Args: latitude (float): Fix's latitude longitude (float): Fix's longitude time (datetime.time): Time the fix was taken status (bool): Whether the data is active mode (str): Type of reading
f12196:c0:m0
def __str__(self, talker='<STR_LIT>'):
if not len(talker) == <NUM_LIT:2>:<EOL><INDENT>raise ValueError('<STR_LIT>' % talker)<EOL><DEDENT>data = ['<STR_LIT>' % talker]<EOL>data.extend(nmea_latitude(self.latitude))<EOL>data.extend(nmea_longitude(self.longitude))<EOL>data.append('<STR_LIT>' % (self.time.strftime('<STR_LIT>'),<EOL>self.time.microsecond / <NUM_LIT>))<EOL>data.append('<STR_LIT:A>' if self.status else '<STR_LIT>')<EOL>if self.mode:<EOL><INDENT>data.append(self.mode)<EOL><DEDENT>data = '<STR_LIT:U+002C>'.join(data)<EOL>return '<STR_LIT>' % (data, calc_checksum(data))<EOL>
Pretty printed position string. Args: talker (str): Talker ID Returns: str: Human readable string representation of ``Position`` object
f12196:c0:m1
def mode_string(self):
return MODE_INDICATOR.get(self.mode, '<STR_LIT>')<EOL>
Return a string version of the reading mode information. Returns: str: Quality information as string
f12196:c0:m2
@staticmethod<EOL><INDENT>def parse_elements(elements):<DEDENT>
if not len(elements) in (<NUM_LIT:6>, <NUM_LIT:7>):<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>latitude = parse_latitude(elements[<NUM_LIT:0>], elements[<NUM_LIT:1>])<EOL>longitude = parse_longitude(elements[<NUM_LIT:2>], elements[<NUM_LIT:3>])<EOL>hour, minute, second = [int(elements[<NUM_LIT:4>][i:i + <NUM_LIT:2>])<EOL>for i in range(<NUM_LIT:0>, <NUM_LIT:6>, <NUM_LIT:2>)]<EOL>usecond = int(elements[<NUM_LIT:4>][<NUM_LIT:6>:<NUM_LIT:8>]) * <NUM_LIT><EOL>time = datetime.time(hour, minute, second, usecond)<EOL>active = True if elements[<NUM_LIT:5>] == '<STR_LIT:A>' else False<EOL>mode = elements[<NUM_LIT:6>] if len(elements) == <NUM_LIT:7> else None<EOL>return LoranPosition(latitude, longitude, time, active, mode)<EOL>
Parse position data elements. Args: elements (list): Data values for fix Returns: Fix: Fix object representing data
f12196:c0:m3
def __init__(self, time, status, latitude, longitude, speed, track, date,<EOL>variation, mode=None):
super(Position, self).__init__(latitude, longitude)<EOL>self.time = time<EOL>self.status = status<EOL>self.speed = speed<EOL>self.track = track<EOL>self.date = date<EOL>self.variation = variation<EOL>self.mode = mode<EOL>
Initialise a new ``Position`` object. Args: time (datetime.time): Time the fix was taken status (bool): Whether the data is active latitude (float): Fix's latitude longitude (float): Fix's longitude speed (float): Ground speed track (float): Track angle date (datetime.date): Date when position was taken variation (float): Magnetic variation mode (str): Type of reading
f12196:c1:m0
def __str__(self):
data = ['<STR_LIT>']<EOL>data.append(self.time.strftime('<STR_LIT>'))<EOL>data.append('<STR_LIT:A>' if self.status else '<STR_LIT>')<EOL>data.extend(nmea_latitude(self.latitude))<EOL>data.extend(nmea_longitude(self.longitude))<EOL>data.append('<STR_LIT>' % self.speed)<EOL>data.append('<STR_LIT>' % self.track)<EOL>data.append(self.date.strftime('<STR_LIT>'))<EOL>if self.variation == int(self.variation):<EOL><INDENT>data.append('<STR_LIT>' % abs(self.variation))<EOL><DEDENT>else:<EOL><INDENT>data.append('<STR_LIT>' % abs(self.variation))<EOL><DEDENT>data.append('<STR_LIT:E>' if self.variation >= <NUM_LIT:0> else '<STR_LIT>')<EOL>if self.mode:<EOL><INDENT>data.append(self.mode)<EOL><DEDENT>data = '<STR_LIT:U+002C>'.join(data)<EOL>return '<STR_LIT>' % (data, calc_checksum(data))<EOL>
Pretty printed position string. Returns: str: Human readable string representation of ``Position`` object
f12196:c1:m1
def mode_string(self):
return MODE_INDICATOR.get(self.mode, '<STR_LIT>')<EOL>
Return a string version of the reading mode information. Returns: str: Quality information as string
f12196:c1:m2
@staticmethod<EOL><INDENT>def parse_elements(elements):<DEDENT>
if not len(elements) in (<NUM_LIT:11>, <NUM_LIT:12>):<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>time = datetime.time(*[int(elements[<NUM_LIT:0>][i:i + <NUM_LIT:2>])<EOL>for i in range(<NUM_LIT:0>, <NUM_LIT:6>, <NUM_LIT:2>)])<EOL>active = True if elements[<NUM_LIT:1>] == '<STR_LIT:A>' else False<EOL>latitude = parse_latitude(elements[<NUM_LIT:2>], elements[<NUM_LIT:3>])<EOL>longitude = parse_longitude(elements[<NUM_LIT:4>], elements[<NUM_LIT:5>])<EOL>speed = float(elements[<NUM_LIT:6>])<EOL>track = float(elements[<NUM_LIT:7>])<EOL>date = datetime.date(<NUM_LIT> + int(elements[<NUM_LIT:8>][<NUM_LIT:4>:<NUM_LIT:6>]),<EOL>int(elements[<NUM_LIT:8>][<NUM_LIT:2>:<NUM_LIT:4>]), int(elements[<NUM_LIT:8>][:<NUM_LIT:2>]))<EOL>variation = float(elements[<NUM_LIT:9>]) if not elements[<NUM_LIT:9>] == '<STR_LIT>' else None<EOL>if elements[<NUM_LIT:10>] == '<STR_LIT>':<EOL><INDENT>variation = -variation<EOL><DEDENT>elif variation and not elements[<NUM_LIT:10>] == '<STR_LIT:E>':<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>% elements[<NUM_LIT:10>])<EOL><DEDENT>mode = elements[<NUM_LIT:11>] if len(elements) == <NUM_LIT:12> else None<EOL>return Position(time, active, latitude, longitude, speed, track, date,<EOL>variation, mode)<EOL>
Parse position data elements. Args: elements (list): Data values for position Returns: Position: Position object representing data
f12196:c1:m3
def __init__(self, time, latitude, longitude, quality, satellites,<EOL>dilution, altitude, geoid_delta, dgps_delta=None,<EOL>dgps_station=None, mode=None):
super(Fix, self).__init__(latitude, longitude)<EOL>self.time = time<EOL>self.quality = quality<EOL>self.satellites = satellites<EOL>self.dilution = dilution<EOL>self.altitude = altitude<EOL>self.geoid_delta = geoid_delta<EOL>self.dgps_delta = dgps_delta<EOL>self.dgps_station = dgps_station<EOL>self.mode = mode<EOL>
Initialise a new ``Fix`` object. Args: time (datetime.time): Time the fix was taken latitude (float): Fix's latitude longitude (float): Fix's longitude quality (int): Mode under which the fix was taken satellites (int): Number of tracked satellites dilution (float): Horizontal dilution at reported position altitude (float): Altitude above MSL geoid_delta (float): Height of geoid's MSL above WGS84 ellipsoid dgps_delta (float): Number of seconds since last DGPS sync dgps_station (int): Identifier of the last synced DGPS station mode (str): Type of reading
f12196:c2:m0
def __str__(self):
data = ['<STR_LIT>']<EOL>data.append(self.time.strftime('<STR_LIT>'))<EOL>data.extend(nmea_latitude(self.latitude))<EOL>data.extend(nmea_longitude(self.longitude))<EOL>data.append(str(self.quality))<EOL>data.append('<STR_LIT>' % self.satellites)<EOL>data.append('<STR_LIT>' % self.dilution)<EOL>data.append('<STR_LIT>' % self.altitude)<EOL>data.append('<STR_LIT:M>')<EOL>data.append('<STR_LIT:->' if not self.geoid_delta else '<STR_LIT>' % self.geoid_delta)<EOL>data.append('<STR_LIT:M>')<EOL>data.append('<STR_LIT>' % self.dgps_delta if self.dgps_delta else '<STR_LIT>')<EOL>data.append('<STR_LIT>' % self.dgps_station if self.dgps_station else '<STR_LIT>')<EOL>data = '<STR_LIT:U+002C>'.join(data)<EOL>return '<STR_LIT>' % (data, calc_checksum(data))<EOL>
Pretty printed location string. Returns: str: Human readable string representation of ``Fix`` object
f12196:c2:m1
def quality_string(self):
return self.fix_quality[self.quality]<EOL>
Return a string version of the quality information. Returns:: str: Quality information as string
f12196:c2:m2
@staticmethod<EOL><INDENT>def parse_elements(elements):<DEDENT>
if not len(elements) in (<NUM_LIT>, <NUM_LIT:15>):<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>time = datetime.time(*[int(elements[<NUM_LIT:0>][i:i + <NUM_LIT:2>])<EOL>for i in range(<NUM_LIT:0>, <NUM_LIT:6>, <NUM_LIT:2>)])<EOL>latitude = parse_latitude(elements[<NUM_LIT:1>], elements[<NUM_LIT:2>])<EOL>longitude = parse_longitude(elements[<NUM_LIT:3>], elements[<NUM_LIT:4>])<EOL>quality = int(elements[<NUM_LIT:5>])<EOL>if not <NUM_LIT:0> <= quality <= <NUM_LIT:9>:<EOL><INDENT>raise ValueError('<STR_LIT>' % quality)<EOL><DEDENT>satellites = int(elements[<NUM_LIT:6>])<EOL>if not <NUM_LIT:0> <= satellites <= <NUM_LIT:12>:<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>% satellites)<EOL><DEDENT>dilution = float(elements[<NUM_LIT:7>])<EOL>altitude = float(elements[<NUM_LIT:8>])<EOL>if elements[<NUM_LIT:9>] == '<STR_LIT:F>':<EOL><INDENT>altitude = altitude * <NUM_LIT><EOL><DEDENT>elif not elements[<NUM_LIT:9>] == '<STR_LIT:M>':<EOL><INDENT>raise ValueError('<STR_LIT>' % elements[<NUM_LIT:9>])<EOL><DEDENT>if elements[<NUM_LIT:10>] in ('<STR_LIT:->', '<STR_LIT>'):<EOL><INDENT>geoid_delta = False<EOL>logging.warning('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>geoid_delta = float(elements[<NUM_LIT:10>])<EOL><DEDENT>if elements[<NUM_LIT:11>] == '<STR_LIT:F>':<EOL><INDENT>geoid_delta = geoid_delta * <NUM_LIT><EOL><DEDENT>elif geoid_delta and not elements[<NUM_LIT:11>] == '<STR_LIT:M>':<EOL><INDENT>raise ValueError('<STR_LIT>' % elements[<NUM_LIT:11>])<EOL><DEDENT>dgps_delta = float(elements[<NUM_LIT:12>]) if elements[<NUM_LIT:12>] else None<EOL>dgps_station = int(elements[<NUM_LIT>]) if elements[<NUM_LIT>] else None<EOL>mode = elements[<NUM_LIT>] if len(elements) == <NUM_LIT:15> else None<EOL>return Fix(time, latitude, longitude, quality, satellites, dilution,<EOL>altitude, geoid_delta, dgps_delta, dgps_station, mode)<EOL>
Parse essential fix's data elements. Args: elements (list): Data values for fix Returns: Fix: Fix object representing data
f12196:c2:m3
def __init__(self, latitude, longitude, name):
super(Waypoint, self).__init__(latitude, longitude)<EOL>self.name = name.upper()<EOL>
Initialise a new ``Waypoint`` object. Args: latitude (float): Waypoint's latitude longitude (float): Waypoint's longitude name (str): Comment for waypoint
f12196:c3:m0
def __str__(self):
data = ['<STR_LIT>']<EOL>data.extend(nmea_latitude(self.latitude))<EOL>data.extend(nmea_longitude(self.longitude))<EOL>data.append(self.name)<EOL>data = '<STR_LIT:U+002C>'.join(data)<EOL>text = '<STR_LIT>' % (data, calc_checksum(data))<EOL>if len(text) > <NUM_LIT>:<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>return text<EOL>
Pretty printed location string. Returns: str: Human readable string representation of ``Waypoint`` object
f12196:c3:m1
@staticmethod<EOL><INDENT>def parse_elements(elements):<DEDENT>
if not len(elements) == <NUM_LIT:5>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>latitude = parse_latitude(elements[<NUM_LIT:0>], elements[<NUM_LIT:1>])<EOL>longitude = parse_longitude(elements[<NUM_LIT:2>], elements[<NUM_LIT:3>])<EOL>name = elements[<NUM_LIT:4>]<EOL>return Waypoint(latitude, longitude, name)<EOL>
Parse waypoint data elements. Args: elements (list): Data values for fix Returns: nmea.Waypoint: Object representing data
f12196:c3:m2
def __init__(self, gpsdata_file=None):
super(Locations, self).__init__()<EOL>self._gpsdata_file = gpsdata_file<EOL>if gpsdata_file:<EOL><INDENT>self.import_locations(gpsdata_file)<EOL><DEDENT>
Initialise a new ``Locations`` object.
f12196:c4:m0
def import_locations(self, gpsdata_file, checksum=True):
self._gpsdata_file = gpsdata_file<EOL>data = utils.prepare_read(gpsdata_file)<EOL>parsers = {<EOL>'<STR_LIT>': Fix,<EOL>'<STR_LIT>': Position,<EOL>'<STR_LIT>': Waypoint,<EOL>'<STR_LIT>': LoranPosition,<EOL>'<STR_LIT>': LoranPosition,<EOL>}<EOL>if not checksum:<EOL><INDENT>logging.warning('<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>for line in data:<EOL><INDENT>if not line[<NUM_LIT:1>:<NUM_LIT:6>] in parsers:<EOL><INDENT>continue<EOL><DEDENT>if checksum:<EOL><INDENT>values, checksum = line[<NUM_LIT:1>:].split('<STR_LIT:*>')<EOL>if not calc_checksum(values) == int(checksum, <NUM_LIT:16>):<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT><DEDENT>else:<EOL><INDENT>values = line[<NUM_LIT:1>:].split('<STR_LIT:*>')[<NUM_LIT:0>]<EOL><DEDENT>elements = values.split('<STR_LIT:U+002C>')<EOL>parser = getattr(parsers[elements[<NUM_LIT:0>]], '<STR_LIT>')<EOL>self.append(parser(elements[<NUM_LIT:1>:]))<EOL><DEDENT>
r"""Import GPS NMEA-formatted data files. ``import_locations()`` returns a list of `Fix` objects representing the fix sentences found in the GPS data. It expects data files in NMEA 0183 format, as specified in `the official documentation`_, which is ASCII text such as:: $GPGSV,6,6,21,32,65,170,35*48 $GPGGA,142058,5308.6414,N,00300.9257,W,1,04,5.6,1374.6,M,34.5,M,,*6B $GPRMC,142058,A,5308.6414,N,00300.9257,W,109394.7,202.9,191107,5,E,A*2C $GPGSV,6,1,21,02,76,044,43,03,84,156,49,06,89,116,51,08,60,184,30*7C $GPGSV,6,2,21,09,87,321,50,10,77,243,44,11,85,016,49,12,89,100,52*7A $GPGSV,6,3,21,13,70,319,39,14,90,094,52,16,85,130,49,17,88,136,51*7E $GPGSV,6,4,21,18,57,052,27,24,65,007,34,25,62,142,32,26,88,031,51*73 $GPGSV,6,5,21,27,64,343,33,28,45,231,16,30,84,198,49,31,90,015,52*7C $GPGSV,6,6,21,32,65,170,34*49 $GPWPL,5200.9000,N,00013.2600,W,HOME*5E $GPGGA,142100,5200.9000,N,00316.6600,W,1,04,5.6,1000.0,M,34.5,M,,*68 $GPRMC,142100,A,5200.9000,N,00316.6600,W,123142.7,188.1,191107,5,E,A*21 The reader only imports the GGA, or GPS fix, sentences currently but future versions will probably support tracks and waypoints. Other than that the data is out of scope for ``upoints``. The above file when processed by ``import_locations()`` will return the following ``list`` object:: [Fix(datetime.time(14, 20, 58), 53.1440233333, -3.01542833333, 1, 4, 5.6, 1374.6, 34.5, None, None), Position(datetime.time(14, 20, 58), True, 53.1440233333, -3.01542833333, 109394.7, 202.9, datetime.date(2007, 11, 19), 5.0, 'A'), Waypoint(52.015, -0.221, 'Home'), Fix(datetime.time(14, 21), 52.015, -3.27766666667, 1, 4, 5.6, 1000.0, 34.5, None, None), Position(datetime.time(14, 21), True, 52.015, -3.27766666667, 123142.7, 188.1, datetime.date(2007, 11, 19), 5.0, 'A')] Note: The standard is quite specific in that sentences *must* be less than 82 bytes, while it would be nice to add yet another validity check it isn't all that uncommon for devices to break this requirement in their "extensions" to the standard. .. todo:: Add optional check for message length, on by default Args: gpsdata_file (iter): NMEA data to read checksum (bool): Whether checksums should be tested Returns: list: Series of locations taken from the data .. _the official documentation: http://en.wikipedia.org/wiki/NMEA_0183
f12196:c4:m1
def __init__(self, ident, latitude, longitude, mcc, mnc, lac, cellid,<EOL>crange, samples, created, updated):
super(Cell, self).__init__(latitude, longitude)<EOL>self.ident = ident<EOL>self.mcc = mcc<EOL>self.mnc = mnc<EOL>self.lac = lac<EOL>self.cellid = cellid<EOL>self.crange = crange<EOL>self.samples = samples<EOL>self.created = created<EOL>self.updated = updated<EOL>
Initialise a new ``Cell`` object. Args: ident (int): OpenCellID database identifier latitude (float): Cell's latitude longitude (float): Cell's longitude mcc (int): Cell's country code mnc (int): Cell's network code lac (int): Cell's local area code cellid (int): Cell's identifier crange (int): Cell's range samples (int): Number of samples for the cell created (datetime.datetime): Date the cell was first entered updated (datetime.datetime): Date of the last update
f12198:c0:m0
def __str__(self):
return '<STR_LIT>'% (self.ident, self.latitude, self.longitude, self.mcc, self.mnc,<EOL>self.lac, self.cellid, self.crange, self.samples,<EOL>self.created.strftime('<STR_LIT>'),<EOL>self.updated.strftime('<STR_LIT>'))<EOL>
OpenCellID.org-style location string. See also: point.Point Returns: str: OpenCellID.org-style string representation of ``Cell`` object
f12198:c0:m1
def __init__(self, cells_file=None):
super(Cells, self).__init__()<EOL>self._cells_file = cells_file<EOL>if cells_file:<EOL><INDENT>self.import_locations(cells_file)<EOL><DEDENT>
Initialise a new ``Cells`` object.
f12198:c1:m0
def __str__(self):
return '<STR_LIT:\n>'.join(map(str, sorted(self.values(),<EOL>key=attrgetter('<STR_LIT>'))))<EOL>
``Cells`` objects rendered as export from OpenCellID.org. Returns: str: OpenCellID.org formatted output
f12198:c1:m1
def import_locations(self, cells_file):
self._cells_file = cells_file<EOL>field_names = ('<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>')<EOL>parse_date = lambda s: datetime.datetime.strptime(s,<EOL>'<STR_LIT>')<EOL>field_parsers = (int, float, float, int, int, int, int, int, int,<EOL>parse_date, parse_date)<EOL>data = utils.prepare_csv_read(cells_file, field_names)<EOL>for row in data:<EOL><INDENT>try:<EOL><INDENT>cell = dict((n, p(row[n]))<EOL>for n, p in zip(field_names, field_parsers))<EOL><DEDENT>except ValueError:<EOL><INDENT>if r"<STR_LIT>" in row.values():<EOL><INDENT>logging.debug('<STR_LIT>' % row)<EOL>break<EOL><DEDENT>else:<EOL><INDENT>raise utils.FileFormatError('<STR_LIT>')<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self[row['<STR_LIT>']] = Cell(**cell)<EOL><DEDENT><DEDENT>
Parse OpenCellID.org data files. ``import_locations()`` returns a dictionary with keys containing the OpenCellID.org_ database identifier, and values consisting of a ``Cell`` objects. It expects cell files in the following format:: 22747,52.0438995361328,-0.2246370017529,234,33,2319,647,0,1, 2008-04-05 21:32:40,2008-04-05 21:32:40 22995,52.3305015563965,-0.2255620062351,234,10,20566,4068,0,1, 2008-04-05 21:32:59,2008-04-05 21:32:59 23008,52.3506011962891,-0.2234109938145,234,10,10566,4068,0,1, 2008-04-05 21:32:59,2008-04-05 21:32:59 The above file processed by ``import_locations()`` will return the following ``dict`` object:: {23008: Cell(23008, 52.3506011963, -0.223410993814, 234, 10, 10566, 4068, 0, 1, datetime.datetime(2008, 4, 5, 21, 32, 59), datetime.datetime(2008, 4, 5, 21, 32, 59)), 22747: Cell(22747, 52.0438995361, -0.224637001753, 234, 33, 2319, 647, 0, 1, datetime.datetime(2008, 4, 5, 21, 32, 40), datetime.datetime(2008, 4, 5, 21, 32, 40)), 22995: Cell(22995, 52.3305015564, -0.225562006235, 234, 10, 20566, 4068, 0, 1, datetime.datetime(2008, 4, 5, 21, 32, 59), datetime.datetime(2008, 4, 5, 21, 32, 59))} Args: cells_file (iter): Cell data to read Returns: dict: Cell data with their associated database identifier .. _OpenCellID.org: http://opencellid.org/
f12198:c1:m2
def __init__(self, latitude, longitude, antenna=None, direction=None,<EOL>frequency=None, height=None, locator=None, mode=None,<EOL>operator=None, power=None, qth=None):
if latitude is not None:<EOL><INDENT>super(Baken, self).__init__(latitude, longitude)<EOL><DEDENT>elif locator is not None:<EOL><INDENT>latitude, longitude = utils.from_grid_locator(locator)<EOL>super(Baken, self).__init__(latitude, longitude)<EOL><DEDENT>else:<EOL><INDENT>raise LookupError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>self.antenna = antenna<EOL>self.direction = direction<EOL>self.frequency = frequency<EOL>self.height = height<EOL>self._locator = locator<EOL>self.mode = mode<EOL>self.operator = operator<EOL>self.power = power<EOL>self.qth = qth<EOL>
Initialise a new ``Baken`` object. Args: latitude (float): Location's latitude longitude (float): Location's longitude antenna (str): Location's antenna type direction (tuple of int): Antenna's direction frequency (float): Transmitter's frequency height (float): Antenna's height locator (str): Location's Maidenhead locator string mode (str): Transmitter's mode operator (tuple of str): Transmitter's operator power (float): Transmitter's power qth (str): Location's qth Raises: LookupError: No position data to use
f12199:c0:m0
@locator.setter<EOL><INDENT>def locator(self, value):<DEDENT>
self._locator = value<EOL>self._latitude, self._longitude = utils.from_grid_locator(value)<EOL>
Update the locator, and trigger a latitude and longitude update. Args: value (str): New Maidenhead locator string
f12199:c0:m2
def __str__(self):
text = super(Baken, self).__format__('<STR_LIT>')<EOL>if self._locator:<EOL><INDENT>text = '<STR_LIT>' % (self._locator, text)<EOL><DEDENT>return text<EOL>
Pretty printed location string. Args: mode (str): Coordinate formatting system to use Returns: str: Human readable string representation of ``Baken`` object
f12199:c0:m3
def __init__(self, baken_file=None):
super(Bakens, self).__init__()<EOL>if baken_file:<EOL><INDENT>self.import_locations(baken_file)<EOL><DEDENT>
Initialise a new `Bakens` object.
f12199:c1:m0
def import_locations(self, baken_file):
self._baken_file = baken_file<EOL>data = ConfigParser()<EOL>if hasattr(baken_file, '<STR_LIT>'):<EOL><INDENT>data.readfp(baken_file)<EOL><DEDENT>elif isinstance(baken_file, list):<EOL><INDENT>data.read(baken_file)<EOL><DEDENT>elif isinstance(baken_file, basestring):<EOL><INDENT>data.readfp(open(baken_file))<EOL><DEDENT>else:<EOL><INDENT>raise TypeError('<STR_LIT>'<EOL>% type(baken_file))<EOL><DEDENT>valid_locator = re.compile(r"<STR_LIT>")<EOL>for name in data.sections():<EOL><INDENT>elements = {}<EOL>for item in ('<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>if data.has_option(name, item):<EOL><INDENT>if item in ('<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>elements[item] = data.get(name, item)<EOL><DEDENT>elif item == '<STR_LIT>':<EOL><INDENT>elements[item] = elements[item].split('<STR_LIT:U+002C>')<EOL><DEDENT>elif item == '<STR_LIT>':<EOL><INDENT>elements[item] = data.get(name, item).split('<STR_LIT:U+002C>')<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>elements[item] = data.getfloat(name, item)<EOL><DEDENT>except ValueError:<EOL><INDENT>logging.debug('<STR_LIT>'<EOL>'<STR_LIT>' % name)<EOL>elements[item] =map(float, data.get(name, item).split('<STR_LIT:U+002C>'))<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>elements[item] = None<EOL><DEDENT><DEDENT>if elements['<STR_LIT>'] is Noneand not valid_locator.match(elements['<STR_LIT>']):<EOL><INDENT>logging.info('<STR_LIT>'<EOL>'<STR_LIT:data>' % name)<EOL>continue<EOL><DEDENT>self[name] = Baken(**elements)<EOL><DEDENT>
Import baken data files. ``import_locations()`` returns a dictionary with keys containing the section title, and values consisting of a collection :class:`Baken` objects. It expects data files in the format used by the baken_ amateur radio package, which is Windows INI style files such as: .. code-block:: ini [Abeche, Chad] latitude=14.460000 longitude=20.680000 height=0.000000 [GB3BUX] frequency=50.000 locator=IO93BF power=25 TX antenna=2 x Turnstile height=460 mode=A1A The reader uses the :mod:`configparser` module, so should be reasonably robust against encodings and such. The above file processed by ``import_locations()`` will return the following ``dict`` object:: {"Abeche, Chad": Baken(14.460, 20.680, None, None, None, 0.000, None, None, None, None, None), "GB3BUX": : Baken(None, None, "2 x Turnstile", None, 50.000, 460.000, "IO93BF", "A1A", None, 25, None)} Args:: baken_file (iter): Baken data to read Returns: dict: Named locations and their associated values .. _baken: http://www.qsl.net:80/g4klx/
f12199:c1:m1
def __init__(self, location, country, zone, comments=None):
latitude, longitude = utils.from_iso6709(location + '<STR_LIT:/>')[:<NUM_LIT:2>]<EOL>super(Zone, self).__init__(latitude, longitude)<EOL>self.country = country<EOL>self.zone = zone<EOL>self.comments = comments<EOL>
Initialise a new ``Zone`` object. Args: location (str): Primary location in ISO 6709 format country (str): Location's ISO 3166 country code zone (str): Location's zone name as used in zoneinfo database comments (list): Location's alternate names
f12200:c0:m0
def __repr__(self):
location = utils.to_iso6709(self.latitude, self.longitude,<EOL>format='<STR_LIT>')[:-<NUM_LIT:1>]<EOL>return utils.repr_assist(self, {'<STR_LIT:location>': location})<EOL>
Self-documenting string representation. Returns: str: String to recreate ``Zone`` object
f12200:c0:m1
def __str__(self):
text = ['<STR_LIT>' % (self.zone, self.country,<EOL>super(Zone, self).__format__('<STR_LIT>')), ]<EOL>if self.comments:<EOL><INDENT>text.append('<STR_LIT>' + '<STR_LIT:U+002CU+0020>'.join(self.comments))<EOL><DEDENT>text.append('<STR_LIT:)>')<EOL>return '<STR_LIT>'.join(text)<EOL>
Pretty printed location string. Args: mode (str): Coordinate formatting system to use Returns: str: Human readable string representation of ``Zone`` object
f12200:c0:m2
def __init__(self, zone_file=None):
super(Zones, self).__init__()<EOL>self._zone_file = zone_file<EOL>if zone_file:<EOL><INDENT>self.import_locations(zone_file)<EOL><DEDENT>
Initialise a new Zones object.
f12200:c1:m0
def import_locations(self, zone_file):
self._zone_file = zone_file<EOL>field_names = ('<STR_LIT>', '<STR_LIT:location>', '<STR_LIT>', '<STR_LIT>')<EOL>data = utils.prepare_csv_read(zone_file, field_names, delimiter=r"<STR_LIT:U+0020>")<EOL>for row in (x for x in data if not x['<STR_LIT>'].startswith('<STR_LIT:#>')):<EOL><INDENT>if row['<STR_LIT>']:<EOL><INDENT>row['<STR_LIT>'] = row['<STR_LIT>'].split('<STR_LIT:U+002CU+0020>')<EOL><DEDENT>self.append(Zone(**row))<EOL><DEDENT>
Parse zoneinfo zone description data files. ``import_locations()`` returns a list of :class:`Zone` objects. It expects data files in one of the following formats:: AN +1211-06900 America/Curacao AO -0848+01314 Africa/Luanda AQ -7750+16636 Antarctica/McMurdo McMurdo Station, Ross Island Files containing the data in this format can be found in the :file:`zone.tab` file that is normally found in :file:`/usr/share/zoneinfo` on UNIX-like systems, or from the `standard distribution site`_. When processed by ``import_locations()`` a ``list`` object of the following style will be returned:: [Zone(None, None, "AN", "America/Curacao", None), Zone(None, None, "AO", "Africa/Luanda", None), Zone(None, None, "AO", "Antartica/McMurdo", ["McMurdo Station", "Ross Island"])] Args: zone_file (iter): ``zone.tab`` data to read Returns: list: Locations as :class:`Zone` objects Raises: FileFormatError: Unknown file format .. _standard distribution site: ftp://elsie.nci.nih.gov/pub/
f12200:c1:m1
def dump_zone_file(self):
data = []<EOL>for zone in sorted(self, key=attrgetter('<STR_LIT>')):<EOL><INDENT>text = ['<STR_LIT>'<EOL>% (zone.country,<EOL>utils.to_iso6709(zone.latitude, zone.longitude,<EOL>format='<STR_LIT>')[:-<NUM_LIT:1>],<EOL>zone.zone), ]<EOL>if zone.comments:<EOL><INDENT>text.append('<STR_LIT>' % '<STR_LIT:U+002CU+0020>'.join(zone.comments))<EOL><DEDENT>data.append('<STR_LIT>'.join(text))<EOL><DEDENT>return data<EOL>
Generate a zoneinfo compatible zone description table. Returns: list: zoneinfo descriptions
f12200:c1:m2
def __init__(self, geonameid, name, asciiname, alt_names, latitude,<EOL>longitude, feature_class, feature_code, country, alt_country,<EOL>admin1, admin2, admin3, admin4, population, altitude, gtopo30,<EOL>tzname, modified_date, timezone=None):
super(Location, self).__init__(latitude, longitude, altitude, name)<EOL>self.geonameid = geonameid<EOL>self.name = name<EOL>self.asciiname = asciiname<EOL>self.alt_names = alt_names<EOL>self.latitude = latitude<EOL>self.longitude = longitude<EOL>self.feature_class = feature_class<EOL>self.feature_code = feature_code<EOL>self.country = country<EOL>self.alt_country = alt_country<EOL>self.admin1 = admin1<EOL>self.admin2 = admin2<EOL>self.admin3 = admin3<EOL>self.admin4 = admin4<EOL>self.population = population<EOL>self.altitude = altitude<EOL>self.gtopo30 = gtopo30<EOL>self.tzname = tzname<EOL>self.modified_date = modified_date<EOL>if timezone is not None:<EOL><INDENT>self.timezone = timezone<EOL><DEDENT>elif tz:<EOL><INDENT>if tzname in Location.__TIMEZONES:<EOL><INDENT>self.timezone = Location.__TIMEZONES[tzname]<EOL><DEDENT>else:<EOL><INDENT>self.timezone = int(tz.gettz(tzname)._ttinfo_std.offset / <NUM_LIT>)<EOL>Location.__TIMEZONES[tzname] = self.timezone<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self.timezone = None<EOL><DEDENT>
Initialise a new ``Location`` object. Args: geonameid (int): ID of record in geonames database name (unicode): Name of geographical location asciiname (str): Name of geographical location in ASCII encoding alt_names (list of unicode): Alternate names for the location latitude (float): Location's latitude longitude (float): Location's longitude feature_class (str): Location's type feature_code (str): Location's code country (str): Location's country alt_country (str): Alternate country codes for location admin1 (str): FIPS code (subject to change to ISO code), ISO code for the US and CH admin2 (str): Code for the second administrative division, a county in the US admin3 (str): Code for third level administrative division admin4 (str): Code for fourth level administrative division population (int): Location's population, if applicable altitude (int): Location's elevation gtopo30 (int): Average elevation of 900 square metre region, if available tzname (str): The timezone identifier using POSIX timezone names modified_date (datetime.date): Location's last modification date in the geonames databases timezone (int): The non-DST timezone offset from UTC in minutes
f12201: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 ``Location`` object
f12201:c0:m1
def __format__(self, format_spec='<STR_LIT>'):
text = super(Location.__base__, self).__format__(format_spec)<EOL>if self.alt_names:<EOL><INDENT>return '<STR_LIT>' % (self.name, '<STR_LIT:U+002CU+0020>'.join(self.alt_names),<EOL>text)<EOL><DEDENT>else:<EOL><INDENT>return '<STR_LIT>' % (self.name, text)<EOL><DEDENT>
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``
f12201:c0:m2
def __init__(self, data=None, tzfile=None):
super(Locations, self).__init__()<EOL>if tzfile:<EOL><INDENT>self.import_timezones_file(tzfile)<EOL><DEDENT>else:<EOL><INDENT>self.timezones = {}<EOL><DEDENT>self._data = data<EOL>self._tzfile = tzfile<EOL>if data:<EOL><INDENT>self.import_locations(data)<EOL><DEDENT>
Initialise a new ``Locations`` object.
f12201:c1:m0
def import_locations(self, data):
self._data = data<EOL>field_names = ('<STR_LIT>', '<STR_LIT:name>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>')<EOL>comma_split = lambda s: s.split('<STR_LIT:U+002C>')<EOL>date_parse = lambda s: datetime.date(*map(int, s.split('<STR_LIT:->')))<EOL>or_none = lambda x, s: x(s) if s else None<EOL>str_or_none = lambda s: or_none(str, s)<EOL>float_or_none = lambda s: or_none(float, s)<EOL>int_or_none = lambda s: or_none(int, s)<EOL>tz_parse = lambda s: self.timezones[s][<NUM_LIT:0>] if self.timezones else None<EOL>field_parsers = (int_or_none, str_or_none, str_or_none, comma_split,<EOL>float_or_none, float_or_none, str_or_none,<EOL>str_or_none, str_or_none, comma_split, str_or_none,<EOL>str_or_none, str_or_none, str_or_none, int_or_none,<EOL>int_or_none, int_or_none, tz_parse, date_parse)<EOL>data = utils.prepare_csv_read(data, field_names, delimiter=r"<STR_LIT:U+0020>")<EOL>for row in data:<EOL><INDENT>try:<EOL><INDENT>for name, parser in zip(field_names, field_parsers):<EOL><INDENT>row[name] = parser(row[name])<EOL><DEDENT><DEDENT>except ValueError:<EOL><INDENT>raise utils.FileFormatError('<STR_LIT>')<EOL><DEDENT>self.append(Location(**row))<EOL><DEDENT>
Parse geonames.org country database exports. ``import_locations()`` returns a list of :class:`trigpoints.Trigpoint` objects generated from the data exported by geonames.org_. It expects data files in the following tab separated format:: 2633441 Afon Wyre Afon Wyre River Wayrai,River Wyrai,Wyre 52.3166667 -4.1666667 H STM GB GB 00 0 -9999 Europe/London 1994-01-13 2633442 Wyre Wyre Viera 59.1166667 -2.9666667 T ISL GB GB V9 0 1 Europe/London 2004-09-24 2633443 Wraysbury Wraysbury Wyrardisbury 51.45 -0.55 P PPL GB P9 0 28 Europe/London 2006-08-21 Files containing the data in this format can be downloaded from the geonames.org_ site in their `database export page`_. Files downloaded from the geonames site when processed by ``import_locations()`` will return ``list`` objects of the following style:: [Location(2633441, "Afon Wyre", "Afon Wyre", ['River Wayrai', 'River Wyrai', 'Wyre'], 52.3166667, -4.1666667, "H", "STM", "GB", ['GB'], "00", None, None, None, 0, None, -9999, "Europe/London", datetime.date(1994, 1, 13)), Location(2633442, "Wyre", "Wyre", ['Viera'], 59.1166667, -2.9666667, "T", "ISL", "GB", ['GB'], "V9", None, None, None, 0, None, 1, "Europe/London", datetime.date(2004, 9, 24)), Location(2633443, "Wraysbury", "Wraysbury", ['Wyrardisbury'], 51.45, -0.55, "P", "PPL", "GB", None, "P9", None, None, None, 0, None, 28, "Europe/London", datetime.date(2006, 8, 21))] Args: data (iter): geonames.org locations data to read Returns: list: geonames.org identifiers with :class:`Location` objects Raises: FileFormatError: Unknown file format .. _geonames.org: http://www.geonames.org/ .. _database export page: http://download.geonames.org/export/dump/
f12201:c1:m1
def import_timezones_file(self, data):
self._tzfile = data<EOL>field_names = ('<STR_LIT>', '<STR_LIT>', '<STR_LIT>')<EOL>time_parse = lambda n: int(float(n) * <NUM_LIT>)<EOL>data = utils.prepare_csv_read(data, field_names, delimiter=r"<STR_LIT:U+0020>")<EOL>self.timezones = {}<EOL>for row in data:<EOL><INDENT>if row['<STR_LIT>'] == '<STR_LIT>':<EOL><INDENT>continue<EOL><DEDENT>try:<EOL><INDENT>delta = list(map(time_parse,<EOL>(row['<STR_LIT>'], row['<STR_LIT>'])))<EOL><DEDENT>except ValueError:<EOL><INDENT>raise utils.FileFormatError('<STR_LIT>')<EOL><DEDENT>self.timezones[row['<STR_LIT>']] = delta<EOL><DEDENT>
Parse geonames.org_ timezone exports. ``import_timezones_file()`` returns a dictionary with keys containing the timezone identifier, and values consisting of a UTC offset and UTC offset during daylight savings time in minutes. It expects data files in the following format:: Europe/Andorra 1.0 2.0 Asia/Dubai 4.0 4.0 Asia/Kabul 4.5 4.5 Files containing the data in this format can be downloaded from the geonames site in their `database export page`_ Files downloaded from the geonames site when processed by ``import_timezones_file()`` will return ``dict`` object of the following style:: {"Europe/Andorra": (60, 120), "Asia/Dubai": (240, 240), "Asia/Kabul": (270, 270)} Args: data (iter): geonames.org timezones data to read Returns: list: geonames.org timezone identifiers with their UTC offsets Raises: FileFormatError: Unknown file format .. _geonames.org: http://www.geonames.org/ .. _database export page: http://download.geonames.org/export/dump/
f12201:c1:m2
def __init__(self, identifier, name, ptype, region, country, location,<EOL>population, size, latitude, longitude, altitude, date,<EOL>entered):
super(City, self).__init__(latitude, longitude, altitude, name)<EOL>self.identifier = identifier<EOL>self.ptype = ptype<EOL>self.region = region<EOL>self.country = country<EOL>self.location = location<EOL>self.population = population<EOL>self.size = size<EOL>self.date = date<EOL>self.entered = entered<EOL>
Initialise a new ``City`` object. Args: identifier (int): Numeric identifier for object name (str): Place name ptype (str): Type of place region (str): Region place can be found country (str): Country name place can be found location (str): Body place can be found population (int): Place's population size (int): Place's area latitude (float): Station's latitude longitude (float): Station's longitude altitude (int): Station's elevation date (time.struct_time): Date the entry was added entered (str): Entry's author
f12203:c0:m0
def __str__(self):
values = map(utils.value_or_empty,<EOL>(self.identifier, self.ptype,<EOL>self.population, self.size,<EOL>self.name, self.country,<EOL>self.region, self.location,<EOL>self.latitude, self.longitude,<EOL>self.altitude,<EOL>time.strftime('<STR_LIT>', self.date) if self.date else '<STR_LIT>',<EOL>self.entered))<EOL>return TEMPLATE % tuple(values)<EOL>
Pretty printed location string. Returns: str: Human readable string representation of ``City`` object
f12203:c0:m1
def __init__(self, data=None):
super(Cities, self).__init__()<EOL>self._data = data<EOL>if data:<EOL><INDENT>self.import_locations(data)<EOL><DEDENT>
Initialise a new ``Cities`` object.
f12203:c1:m0
def import_locations(self, data):
self._data = data<EOL>if hasattr(data, '<STR_LIT>'):<EOL><INDENT>data = data.read().split('<STR_LIT>')<EOL><DEDENT>elif isinstance(data, list):<EOL><INDENT>pass<EOL><DEDENT>elif isinstance(data, basestring):<EOL><INDENT>data = open(data).read().split('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>raise TypeError('<STR_LIT>' % type(data))<EOL><DEDENT>keys = ('<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT:size>', '<STR_LIT:name>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT:location>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT:date>', '<STR_LIT>')<EOL>for record in data:<EOL><INDENT>data = [i.split('<STR_LIT::>')[<NUM_LIT:1>].strip() for i in record.splitlines()[:<NUM_LIT>]]<EOL>entries = dict(zip(keys, data))<EOL>if entries['<STR_LIT>'] == '<STR_LIT>':<EOL><INDENT>logging.debug("<STR_LIT>"<EOL>'<STR_LIT>' % record)<EOL>entries['<STR_LIT>'] = '<STR_LIT>'<EOL><DEDENT>for i in ('<STR_LIT>', '<STR_LIT>', '<STR_LIT:size>', '<STR_LIT>'):<EOL><INDENT>entries[i] = int(entries[i]) if entries[i] else None<EOL><DEDENT>for i in ('<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>entries[i] = float(entries[i]) if entries[i] else None<EOL><DEDENT>entries['<STR_LIT:date>'] = time.strptime(entries['<STR_LIT:date>'], '<STR_LIT>')<EOL>self.append(City(**entries))<EOL><DEDENT>
Parse `GNU miscfiles`_ cities data files. ``import_locations()`` returns a list containing :class:`City` objects. It expects data files in the same format that `GNU miscfiles`_ provides, that is:: ID : 1 Type : City Population : 210700 Size : Name : Aberdeen Country : UK Region : Scotland Location : Earth Longitude : -2.083 Latitude : 57.150 Elevation : Date : 19961206 Entered-By : Rob.Hooft@EMBL-Heidelberg.DE // ID : 2 Type : City Population : 1950000 Size : Name : Abidjan Country : Ivory Coast Region : Location : Earth Longitude : -3.867 Latitude : 5.333 Elevation : Date : 19961206 Entered-By : Rob.Hooft@EMBL-Heidelberg.DE When processed by ``import_locations()`` will return ``list`` object in the following style:: [City(1, "City", 210700, None, "Aberdeen", "UK", "Scotland", "Earth", -2.083, 57.15, None, (1996, 12, 6, 0, 0, 0, 4, 341, -1), "Rob.Hooft@EMBL-Heidelberg.DE"), City(2, "City", 1950000, None, "Abidjan", "Ivory Coast", "", "Earth", -3.867, 5.333, None, (1996, 12, 6, 0, 0, 0, 4, 341, -1), "Rob.Hooft@EMBL-Heidelberg.DE")]) Args: data (iter): :abbr:`NOAA (National Oceanographic and Atmospheric Administration)` station data to read Returns: list: Places as ``City`` objects Raises: TypeError: Invalid value for data .. _GNU miscfiles: http://directory.fsf.org/project/miscfiles/
f12203:c1:m1
def _parse_flags(element):
visible = True if element.get('<STR_LIT>') else False<EOL>user = element.get('<STR_LIT:user>')<EOL>timestamp = element.get('<STR_LIT>')<EOL>if timestamp:<EOL><INDENT>timestamp = utils.Timestamp.parse_isoformat(timestamp)<EOL><DEDENT>tags = {}<EOL>try:<EOL><INDENT>for tag in element['<STR_LIT>']:<EOL><INDENT>key = tag.get('<STR_LIT:k>')<EOL>value = tag.get('<STR_LIT:v>')<EOL>tags[key] = value<EOL><DEDENT><DEDENT>except AttributeError:<EOL><INDENT>pass<EOL><DEDENT>return visible, user, timestamp, tags<EOL>
Parse OSM XML element for generic data. Args: element (etree.Element): Element to parse Returns: tuple: Generic OSM data for object instantiation
f12204:m0
def _get_flags(osm_obj):
flags = []<EOL>if osm_obj.visible:<EOL><INDENT>flags.append('<STR_LIT>')<EOL><DEDENT>if osm_obj.user:<EOL><INDENT>flags.append('<STR_LIT>' % osm_obj.user)<EOL><DEDENT>if osm_obj.timestamp:<EOL><INDENT>flags.append('<STR_LIT>' % osm_obj.timestamp.isoformat())<EOL><DEDENT>if osm_obj.tags:<EOL><INDENT>flags.append('<STR_LIT:U+002CU+0020>'.join('<STR_LIT>' % (k, v)<EOL>for k, v in sorted(osm_obj.tags.items())))<EOL><DEDENT>return flags<EOL>
Create element independent flags output. Args: osm_obj (Node): Object with OSM-style metadata Returns: list: Human readable flags output
f12204:m1
def get_area_url(location, distance):
locations = [location.destination(i, distance) for i in range(<NUM_LIT:0>, <NUM_LIT>, <NUM_LIT>)]<EOL>latitudes = list(map(attrgetter('<STR_LIT>'), locations))<EOL>longitudes = list(map(attrgetter('<STR_LIT>'), locations))<EOL>bounds = (min(longitudes), min(latitudes), max(longitudes), max(latitudes))<EOL>return ('<STR_LIT>'<EOL>+ '<STR_LIT:U+002C>'.join(map(str, bounds)))<EOL>
Generate URL for downloading OSM data within a region. This function defines a boundary box where the edges touch a circle of ``distance`` kilometres in radius. It is important to note that the box is neither a square, nor bounded within the circle. The bounding box is strictly a trapezoid whose north and south edges are different lengths, which is longer is dependant on whether the box is calculated for a location in the Northern or Southern hemisphere. You will get a shorter north edge in the Northern hemisphere, and vice versa. This is simply because we are applying a flat transformation to a spherical object, however for all general cases the difference will be negligible. Args: location (Point): Centre of the region distance (int): Boundary distance in kilometres Returns: str: URL that can be used to fetch the OSM data within ``distance`` of ``location``
f12204:m2
def __init__(self, ident, latitude, longitude, visible=False, user=None,<EOL>timestamp=None, tags=None):
super(Node, self).__init__(latitude, longitude)<EOL>self.ident = ident<EOL>self.visible = visible<EOL>self.user = user<EOL>self.timestamp = timestamp<EOL>self.tags = tags<EOL>
Initialise a new ``Node`` object. Args: ident (int): Unique identifier for the node latitude (float): Nodes's latitude longitude (float): Node's longitude visible (bool): Whether the node is visible user (str): User who logged the node timestamp (str): The date and time a node was logged tags (dict): Tags associated with the node
f12204:c0:m0
def __str__(self):
text = ['<STR_LIT>' % (self.ident,<EOL>super(Node, self).__format__('<STR_LIT>')), ]<EOL>flags = _get_flags(self)<EOL>if flags:<EOL><INDENT>text.append('<STR_LIT>' % '<STR_LIT:U+002CU+0020>'.join(flags))<EOL><DEDENT>return '<STR_LIT:U+0020>'.join(text)<EOL>
Pretty printed location string. Returns: str: Human readable string representation of ``Node`` object
f12204:c0:m1
def toosm(self):
node = create_elem('<STR_LIT>', {'<STR_LIT:id>': str(self.ident),<EOL>'<STR_LIT>': str(self.latitude),<EOL>'<STR_LIT>': str(self.longitude)})<EOL>node.set('<STR_LIT>', '<STR_LIT:true>' if self.visible else '<STR_LIT:false>')<EOL>if self.user:<EOL><INDENT>node.set('<STR_LIT:user>', self.user)<EOL><DEDENT>if self.timestamp:<EOL><INDENT>node.set('<STR_LIT>', self.timestamp.isoformat())<EOL><DEDENT>if self.tags:<EOL><INDENT>for key, value in sorted(self.tags.items()):<EOL><INDENT>node.append(create_elem('<STR_LIT>', {'<STR_LIT:k>': key, '<STR_LIT:v>': value}))<EOL><DEDENT><DEDENT>return node<EOL>
Generate a OSM node element subtree. Returns: etree.Element: OSM node element
f12204:c0:m2
def get_area_url(self, distance):
return get_area_url(self, distance)<EOL>
Generate URL for downloading OSM data within a region. Args: distance (int): Boundary distance in kilometres Returns: str: URL that can be used to fetch the OSM data within ``distance`` of ``location``
f12204:c0:m3
def fetch_area_osm(self, distance):
return Osm(urlopen(get_area_url(self, distance)))<EOL>
Fetch, and import, an OSM region. Args: distance (int): Boundary distance in kilometres Returns: Osm: All the data OSM has on a region imported for use
f12204:c0:m4
@staticmethod<EOL><INDENT>def parse_elem(element):<DEDENT>
ident = int(element.get('<STR_LIT:id>'))<EOL>latitude = element.get('<STR_LIT>')<EOL>longitude = element.get('<STR_LIT>')<EOL>flags = _parse_flags(element)<EOL>return Node(ident, latitude, longitude, *flags)<EOL>
Parse a OSM node XML element. Args: element (etree.Element): XML Element to parse Returns: Node: Object representing parsed element
f12204:c0:m5
def __init__(self, ident, nodes, visible=False, user=None, timestamp=None,<EOL>tags=None):
super(Way, self).__init__()<EOL>self.extend(nodes)<EOL>self.ident = ident<EOL>self.visible = visible<EOL>self.user = user<EOL>self.timestamp = timestamp<EOL>self.tags = tags<EOL>
Initialise a new ``Way`` object. Args: ident (int): Unique identifier for the way nodes (list of str): Identifiers of the nodes that form this way visible (bool): Whether the way is visible user (str): User who logged the way timestamp (str): The date and time a way was logged tags (dict): Tags associated with the way
f12204:c1:m0
def __repr__(self):
return utils.repr_assist(self, {'<STR_LIT>': self[:]})<EOL>
Self-documenting string representation. Returns:: str: String to recreate ``Way`` object
f12204:c1:m1
def __str__(self, nodes=False):
text = ['<STR_LIT>' % (self.ident), ]<EOL>if not nodes:<EOL><INDENT>text.append('<STR_LIT>' % str(self[:])[<NUM_LIT:1>:-<NUM_LIT:1>])<EOL><DEDENT>flags = _get_flags(self)<EOL>if flags:<EOL><INDENT>text.append('<STR_LIT>' % '<STR_LIT:U+002CU+0020>'.join(flags))<EOL><DEDENT>if nodes:<EOL><INDENT>text.append('<STR_LIT:\n>')<EOL>text.append('<STR_LIT:\n>'.join('<STR_LIT>' % nodes[node] for node in self[:]))<EOL><DEDENT>return '<STR_LIT>'.join(text)<EOL>
Pretty printed location string. Args: nodes (list): Nodes to be used in expanding references Returns: str: Human readable string representation of ``Way`` object
f12204:c1:m2
def toosm(self):
way = create_elem('<STR_LIT>', {'<STR_LIT:id>': str(self.ident)})<EOL>way.set('<STR_LIT>', '<STR_LIT:true>' if self.visible else '<STR_LIT:false>')<EOL>if self.user:<EOL><INDENT>way.set('<STR_LIT:user>', self.user)<EOL><DEDENT>if self.timestamp:<EOL><INDENT>way.set('<STR_LIT>', self.timestamp.isoformat())<EOL><DEDENT>if self.tags:<EOL><INDENT>for key, value in sorted(self.tags.items()):<EOL><INDENT>way.append(create_elem('<STR_LIT>', {'<STR_LIT:k>': key, '<STR_LIT:v>': value}))<EOL><DEDENT><DEDENT>for node in self:<EOL><INDENT>way.append(create_elem('<STR_LIT>', {'<STR_LIT>': str(node)}))<EOL><DEDENT>return way<EOL>
Generate a OSM way element subtree. Returns: etree.Element: OSM way element
f12204:c1:m3
@staticmethod<EOL><INDENT>def parse_elem(element):<DEDENT>
ident = int(element.get('<STR_LIT:id>'))<EOL>flags = _parse_flags(element)<EOL>nodes = [node.get('<STR_LIT>') for node in element.findall('<STR_LIT>')]<EOL>return Way(ident, nodes, *flags)<EOL>
Parse a OSM way XML element. Args: element (etree.Element): XML Element to parse Returns: Way: `Way` object representing parsed element
f12204:c1:m4
def __init__(self, osm_file=None):
super(Osm, self).__init__()<EOL>self._osm_file = osm_file<EOL>if osm_file:<EOL><INDENT>self.import_locations(osm_file)<EOL><DEDENT>self.generator = ua_string<EOL>self.version = '<STR_LIT>'<EOL>
Initialise a new ``Osm`` object.
f12204:c2:m0
def import_locations(self, osm_file):
self._osm_file = osm_file<EOL>data = utils.prepare_xml_read(osm_file, objectify=True)<EOL>if not data.tag == '<STR_LIT>':<EOL><INDENT>raise ValueError("<STR_LIT>" % data.tag)<EOL><DEDENT>self.version = data.get('<STR_LIT:version>')<EOL>if not self.version:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>elif not self.version == '<STR_LIT>':<EOL><INDENT>raise ValueError('<STR_LIT>' % data)<EOL><DEDENT>self.generator = data.get('<STR_LIT>')<EOL>for elem in data.getchildren():<EOL><INDENT>if elem.tag == '<STR_LIT>':<EOL><INDENT>self.append(Node.parse_elem(elem))<EOL><DEDENT>elif elem.tag == '<STR_LIT>':<EOL><INDENT>self.append(Way.parse_elem(elem))<EOL><DEDENT><DEDENT>
Import OSM data files. ``import_locations()`` returns a list of ``Node`` and ``Way`` objects. It expects data files conforming to the `OpenStreetMap 0.5 DTD`_, which is XML such as:: <?xml version="1.0" encoding="UTF-8"?> <osm version="0.5" generator="upoints/0.9.0"> <node id="0" lat="52.015749" lon="-0.221765" user="jnrowe" visible="true" timestamp="2008-01-25T12:52:11+00:00" /> <node id="1" lat="52.015761" lon="-0.221767" visible="true" timestamp="2008-01-25T12:53:00+00:00"> <tag k="created_by" v="hand" /> <tag k="highway" v="crossing" /> </node> <node id="2" lat="52.015754" lon="-0.221766" user="jnrowe" visible="true" timestamp="2008-01-25T12:52:30+00:00"> <tag k="amenity" v="pub" /> </node> <way id="0" visible="true" timestamp="2008-01-25T13:00:00+0000"> <nd ref="0" /> <nd ref="1" /> <nd ref="2" /> <tag k="ref" v="My Way" /> <tag k="highway" v="primary" /> </way> </osm> 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 `Osm` object:: Osm([ Node(0, 52.015749, -0.221765, True, "jnrowe", utils.Timestamp(2008, 1, 25, 12, 52, 11), None), Node(1, 52.015761, -0.221767, True, utils.Timestamp(2008, 1, 25, 12, 53), None, {"created_by": "hand", "highway": "crossing"}), Node(2, 52.015754, -0.221766, True, "jnrowe", utils.Timestamp(2008, 1, 25, 12, 52, 30), {"amenity": "pub"}), Way(0, [0, 1, 2], True, None, utils.Timestamp(2008, 1, 25, 13, 00), {"ref": "My Way", "highway": "primary"})], generator="upoints/0.9.0") Args: osm_file (iter): OpenStreetMap data to read Returns: Osm: Nodes and ways from the data .. _OpenStreetMap 0.5 DTD: http://wiki.openstreetmap.org/wiki/OSM_Protocol_Version_0.5/DTD
f12204:c2:m1
def export_osm_file(self):
osm = create_elem('<STR_LIT>', {'<STR_LIT>': self.generator,<EOL>'<STR_LIT:version>': self.version})<EOL>osm.extend(obj.toosm() for obj in self)<EOL>return etree.ElementTree(osm)<EOL>
Generate OpenStreetMap element tree from ``Osm``.
f12204:c2:m2
def value_or_empty(value):
return value if value else '<STR_LIT>'<EOL>
Return an empty string for display when value is ``None``. Args: value (str): Value to prepare for display Returns: str: String representation of ``value``
f12205:m0
def repr_assist(obj, remap=None):
if not remap:<EOL><INDENT>remap = {}<EOL><DEDENT>data = []<EOL>for arg in inspect.getargspec(getattr(obj.__class__, '<STR_LIT>'))[<NUM_LIT:0>]:<EOL><INDENT>if arg == '<STR_LIT>':<EOL><INDENT>continue<EOL><DEDENT>elif arg in remap:<EOL><INDENT>value = remap[arg]<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>value = getattr(obj, arg)<EOL><DEDENT>except AttributeError:<EOL><INDENT>value = getattr(obj, '<STR_LIT>' % arg)<EOL><DEDENT><DEDENT>if isinstance(value, (type(None), list, basestring, datetime.date,<EOL>datetime.time)):<EOL><INDENT>data.append(repr(value))<EOL><DEDENT>else:<EOL><INDENT>data.append(str(value))<EOL><DEDENT><DEDENT>return "<STR_LIT>" % (obj.__class__.__name__, '<STR_LIT:U+002CU+0020>'.join(data))<EOL>
Helper function to simplify ``__repr__`` methods. Args: obj: Object to pull argument values for remap (dict): Argument pairs to remap before output Returns: str: Self-documenting representation of ``value``
f12205:m1
def prepare_read(data, method='<STR_LIT>', mode='<STR_LIT:r>'):
if hasattr(data, '<STR_LIT>'):<EOL><INDENT>data = getattr(data, method)()<EOL><DEDENT>elif isinstance(data, list):<EOL><INDENT>if method == '<STR_LIT>':<EOL><INDENT>return '<STR_LIT>'.join(data)<EOL><DEDENT><DEDENT>elif isinstance(data, basestring):<EOL><INDENT>data = getattr(open(data, mode), method)()<EOL><DEDENT>else:<EOL><INDENT>raise TypeError('<STR_LIT>' % type(data))<EOL><DEDENT>return data<EOL>
Prepare various input types for parsing. Args: 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: List suitable for parsing Raises: TypeError: Invalid value for data
f12205:m2
def prepare_csv_read(data, field_names, *args, **kwargs):
if hasattr(data, '<STR_LIT>') or isinstance(data, list):<EOL><INDENT>pass<EOL><DEDENT>elif isinstance(data, basestring):<EOL><INDENT>data = open(data)<EOL><DEDENT>else:<EOL><INDENT>raise TypeError('<STR_LIT>' % type(data))<EOL><DEDENT>return csv.DictReader(data, field_names, *args, **kwargs)<EOL>
Prepare various input types for CSV parsing. Args: data (iter): Data to read field_names (tuple of str): Ordered names to assign to fields Returns: csv.DictReader: CSV reader suitable for parsing Raises: TypeError: Invalid value for data
f12205:m3
def prepare_xml_read(data, objectify=False):
mod = _objectify if objectify else etree<EOL>if hasattr(data, '<STR_LIT>'):<EOL><INDENT>data = mod.parse(data).getroot()<EOL><DEDENT>elif isinstance(data, list):<EOL><INDENT>data = mod.fromstring('<STR_LIT>'.join(data))<EOL><DEDENT>elif isinstance(data, basestring):<EOL><INDENT>data = mod.parse(open(data)).getroot()<EOL><DEDENT>else:<EOL><INDENT>raise TypeError('<STR_LIT>' % type(data))<EOL><DEDENT>return data<EOL>
Prepare various input types for XML parsing. Args: data (iter): Data to read objectify (bool): Parse using lxml's objectify data binding Returns: etree.ElementTree: Tree suitable for parsing Raises: TypeError: Invalid value for data
f12205:m4
def element_creator(namespace=None):
ELEMENT_MAKER = _objectify.ElementMaker(namespace=namespace,<EOL>annotate=False)<EOL>def create_elem(tag, attr=None, text=None):<EOL><INDENT>"""<STR_LIT>"""<EOL>if not attr:<EOL><INDENT>attr = {}<EOL><DEDENT>if text:<EOL><INDENT>element = getattr(ELEMENT_MAKER, tag)(text, **attr)<EOL><DEDENT>else:<EOL><INDENT>element = getattr(ELEMENT_MAKER, tag)(**attr)<EOL><DEDENT>return element<EOL><DEDENT>return create_elem<EOL>
Create a simple namespace-aware objectify element creator. Args: namespace (str): Namespace to work in Returns: function: Namespace-aware element creator
f12205:m5
def to_dms(angle, style='<STR_LIT>'):
sign = <NUM_LIT:1> if angle >= <NUM_LIT:0> else -<NUM_LIT:1><EOL>angle = abs(angle) * <NUM_LIT><EOL>minutes, seconds = divmod(angle, <NUM_LIT>)<EOL>degrees, minutes = divmod(minutes, <NUM_LIT>)<EOL>if style == '<STR_LIT>':<EOL><INDENT>return tuple(sign * abs(i) for i in (int(degrees), int(minutes),<EOL>seconds))<EOL><DEDENT>elif style == '<STR_LIT>':<EOL><INDENT>return tuple(sign * abs(i) for i in (int(degrees),<EOL>(minutes + seconds / <NUM_LIT>)))<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>' % style)<EOL><DEDENT>
Convert decimal angle to degrees, minutes and possibly seconds. Args: angle (float): Angle to convert style (str): Return fractional or whole minutes values Returns: tuple of int: Angle converted to degrees, minutes and possibly seconds Raises: ValueError: Unknown value for ``style``
f12205:m6
def to_dd(degrees, minutes, seconds=<NUM_LIT:0>):
sign = -<NUM_LIT:1> if any(i < <NUM_LIT:0> for i in (degrees, minutes, seconds)) else <NUM_LIT:1><EOL>return sign * (abs(degrees) + abs(minutes) / <NUM_LIT> + abs(seconds) / <NUM_LIT>)<EOL>
Convert degrees, minutes and optionally seconds to decimal angle. Args: degrees (float): Number of degrees minutes (float): Number of minutes seconds (float): Number of seconds Returns: float: Angle converted to decimal degrees
f12205:m7
def __chunk(segment, abbr=False):
names = ('<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>')<EOL>if not abbr:<EOL><INDENT>sjoin = '<STR_LIT:->'<EOL><DEDENT>else:<EOL><INDENT>names = [s[<NUM_LIT:0>].upper() for s in names]<EOL>sjoin = '<STR_LIT>'<EOL><DEDENT>if segment % <NUM_LIT:2> == <NUM_LIT:0>:<EOL><INDENT>return (names[segment].capitalize(),<EOL>sjoin.join((names[segment].capitalize(), names[segment],<EOL>names[segment + <NUM_LIT:1>])),<EOL>sjoin.join((names[segment].capitalize(), names[segment + <NUM_LIT:1>])),<EOL>sjoin.join((names[segment + <NUM_LIT:1>].capitalize(), names[segment],<EOL>names[segment + <NUM_LIT:1>])))<EOL><DEDENT>else:<EOL><INDENT>return (names[segment].capitalize(),<EOL>sjoin.join((names[segment].capitalize(), names[segment + <NUM_LIT:1>],<EOL>names[segment])),<EOL>sjoin.join((names[segment + <NUM_LIT:1>].capitalize(), names[segment])),<EOL>sjoin.join((names[segment + <NUM_LIT:1>].capitalize(),<EOL>names[segment + <NUM_LIT:1>], names[segment])))<EOL><DEDENT>
Generate a ``tuple`` of compass direction names. Args: segment (list): Compass segment to generate names for abbr (bool): Names should use single letter abbreviations Returns: bool: Direction names for compass segment
f12205:m8
def angle_to_name(angle, segments=<NUM_LIT:8>, abbr=False):
if segments == <NUM_LIT:4>:<EOL><INDENT>string = COMPASS_NAMES[int((angle + <NUM_LIT>) / <NUM_LIT>) % <NUM_LIT:4> * <NUM_LIT:2>]<EOL><DEDENT>elif segments == <NUM_LIT:8>:<EOL><INDENT>string = COMPASS_NAMES[int((angle + <NUM_LIT>) / <NUM_LIT>) % <NUM_LIT:8> * <NUM_LIT:2>]<EOL><DEDENT>elif segments == <NUM_LIT:16>:<EOL><INDENT>string = COMPASS_NAMES[int((angle + <NUM_LIT>) / <NUM_LIT>) % <NUM_LIT:16>]<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>% segments)<EOL><DEDENT>if abbr:<EOL><INDENT>return '<STR_LIT>'.join(i[<NUM_LIT:0>].capitalize() for i in string.split('<STR_LIT:->'))<EOL><DEDENT>else:<EOL><INDENT>return string<EOL><DEDENT>
Convert angle in to direction name. Args: 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: str: Direction name for ``angle``
f12205:m9
def from_iso6709(coordinates):
matches = iso6709_matcher.match(coordinates)<EOL>if matches:<EOL><INDENT>latitude, longitude, altitude = matches.groups()<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>sign = <NUM_LIT:1> if latitude[<NUM_LIT:0>] == '<STR_LIT:+>' else -<NUM_LIT:1><EOL>latitude_head = len(latitude.split('<STR_LIT:.>')[<NUM_LIT:0>])<EOL>if latitude_head == <NUM_LIT:3>: <EOL><INDENT>latitude = float(latitude)<EOL><DEDENT>elif latitude_head == <NUM_LIT:5>: <EOL><INDENT>latitude = float(latitude[:<NUM_LIT:3>]) + (sign * (float(latitude[<NUM_LIT:3>:]) / <NUM_LIT>))<EOL><DEDENT>elif latitude_head == <NUM_LIT:7>: <EOL><INDENT>latitude = float(latitude[:<NUM_LIT:3>]) + (sign * (float(latitude[<NUM_LIT:3>:<NUM_LIT:5>]) / <NUM_LIT>))+ (sign * (float(latitude[<NUM_LIT:5>:]) / <NUM_LIT>))<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>' % latitude)<EOL><DEDENT>sign = <NUM_LIT:1> if longitude[<NUM_LIT:0>] == '<STR_LIT:+>' else -<NUM_LIT:1><EOL>longitude_head = len(longitude.split('<STR_LIT:.>')[<NUM_LIT:0>])<EOL>if longitude_head == <NUM_LIT:4>: <EOL><INDENT>longitude = float(longitude)<EOL><DEDENT>elif longitude_head == <NUM_LIT:6>: <EOL><INDENT>longitude = float(longitude[:<NUM_LIT:4>]) + (sign * (float(longitude[<NUM_LIT:4>:]) / <NUM_LIT>))<EOL><DEDENT>elif longitude_head == <NUM_LIT:8>: <EOL><INDENT>longitude = float(longitude[:<NUM_LIT:4>])+ (sign * (float(longitude[<NUM_LIT:4>:<NUM_LIT:6>]) / <NUM_LIT>))+ (sign * (float(longitude[<NUM_LIT:6>:]) / <NUM_LIT>))<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>' % longitude)<EOL><DEDENT>if altitude:<EOL><INDENT>altitude = float(altitude)<EOL><DEDENT>return latitude, longitude, altitude<EOL>
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 Args: coordinates (str): ISO 6709 coordinates string Returns: tuple: 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 .. _simplified ISO 8601 profile: http://www.w3.org/TR/NOTE-datetime
f12205:m10
def to_iso6709(latitude, longitude, altitude=None, format='<STR_LIT>', precision=<NUM_LIT:4>):
text = []<EOL>if format == '<STR_LIT:d>':<EOL><INDENT>text.append('<STR_LIT>' % (latitude, longitude))<EOL><DEDENT>elif format == '<STR_LIT>':<EOL><INDENT>text.append('<STR_LIT>' % (precision + <NUM_LIT:4>, precision, latitude,<EOL>precision + <NUM_LIT:5>, precision, longitude))<EOL><DEDENT>elif format in ('<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>if format == '<STR_LIT>':<EOL><INDENT>latitude_dms = to_dms(latitude, '<STR_LIT>')<EOL>longitude_dms = to_dms(longitude, '<STR_LIT>')<EOL><DEDENT>elif format == '<STR_LIT>':<EOL><INDENT>latitude_dms = to_dms(latitude)<EOL>longitude_dms = to_dms(longitude)<EOL><DEDENT>latitude_sign = '<STR_LIT:->' if any(i < <NUM_LIT:0> for i in latitude_dms) else '<STR_LIT:+>'<EOL>latitude_dms = tuple(abs(i) for i in latitude_dms)<EOL>longitude_sign = '<STR_LIT:->' if any(i < <NUM_LIT:0> for i in longitude_dms) else '<STR_LIT:+>'<EOL>longitude_dms = tuple(abs(i) for i in longitude_dms)<EOL>if format == '<STR_LIT>':<EOL><INDENT>text.append('<STR_LIT>' % ((latitude_sign, ) + latitude_dms))<EOL>text.append('<STR_LIT>' % ((longitude_sign, ) + longitude_dms))<EOL><DEDENT>elif format == '<STR_LIT>':<EOL><INDENT>text.append('<STR_LIT>' % ((latitude_sign, ) + latitude_dms))<EOL>text.append('<STR_LIT>'<EOL>% ((longitude_sign, ) + longitude_dms))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>' % format)<EOL><DEDENT>if altitude and int(altitude) == altitude:<EOL><INDENT>text.append('<STR_LIT>' % altitude)<EOL><DEDENT>elif altitude:<EOL><INDENT>text.append('<STR_LIT>' % altitude)<EOL><DEDENT>text.append('<STR_LIT:/>')<EOL>return '<STR_LIT>'.join(text)<EOL>
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 Args: 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: str: ISO 6709 coordinates string Raises: ValueError: Unknown value for ``format`` .. _Latitude, Longitude and Altitude format for geospatial information: http://www.w3.org/2005/Incubator/geo/Wiki/LatitudeLongitudeAltitude .. _wikipedia ISO 6709 page: http://en.wikipedia.org/wiki/ISO_6709
f12205:m11
def angle_to_distance(angle, units='<STR_LIT>'):
distance = math.radians(angle) * BODY_RADIUS<EOL>if units in ('<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>return distance<EOL><DEDENT>elif units in ('<STR_LIT>', '<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>return distance / STATUTE_MILE<EOL><DEDENT>elif units in ('<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>return distance / NAUTICAL_MILE<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>' % units)<EOL><DEDENT>
Convert angle in to distance along a great circle. Args: angle (float): Angle in degrees to convert to distance units (str): Unit type to be used for distances Returns: float: Distance in ``units`` Raises: ValueError: Unknown value for ``units``
f12205:m12
def distance_to_angle(distance, units='<STR_LIT>'):
if units in ('<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>pass<EOL><DEDENT>elif units in ('<STR_LIT>', '<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>distance *= STATUTE_MILE<EOL><DEDENT>elif units in ('<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>distance *= NAUTICAL_MILE<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>' % units)<EOL><DEDENT>return math.degrees(distance / BODY_RADIUS)<EOL>
Convert a distance in to an angle along a great circle. Args: distance (float): Distance to convert to degrees units (str): Unit type to be used for distances Returns: float: Angle in degrees Raises: ValueError: Unknown value for ``units``
f12205:m13
def from_grid_locator(locator):
if not len(locator) in (<NUM_LIT:4>, <NUM_LIT:6>, <NUM_LIT:8>):<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>% locator)<EOL><DEDENT>locator = list(locator)<EOL>locator[<NUM_LIT:0>] = ord(locator[<NUM_LIT:0>]) - <NUM_LIT><EOL>locator[<NUM_LIT:1>] = ord(locator[<NUM_LIT:1>]) - <NUM_LIT><EOL>locator[<NUM_LIT:2>] = int(locator[<NUM_LIT:2>])<EOL>locator[<NUM_LIT:3>] = int(locator[<NUM_LIT:3>])<EOL>if len(locator) >= <NUM_LIT:6>:<EOL><INDENT>locator[<NUM_LIT:4>] = ord(locator[<NUM_LIT:4>].lower()) - <NUM_LIT><EOL>locator[<NUM_LIT:5>] = ord(locator[<NUM_LIT:5>].lower()) - <NUM_LIT><EOL><DEDENT>if len(locator) == <NUM_LIT:8>:<EOL><INDENT>locator[<NUM_LIT:6>] = int(locator[<NUM_LIT:6>])<EOL>locator[<NUM_LIT:7>] = int(locator[<NUM_LIT:7>])<EOL><DEDENT>if not <NUM_LIT:0> <= locator[<NUM_LIT:0>] <= <NUM_LIT>or not <NUM_LIT:0> <= locator[<NUM_LIT:1>] <= <NUM_LIT>or not <NUM_LIT:0> <= locator[<NUM_LIT:2>] <= <NUM_LIT:9>or not <NUM_LIT:0> <= locator[<NUM_LIT:3>] <= <NUM_LIT:9>:<EOL><INDENT>raise ValueError('<STR_LIT>' % locator)<EOL><DEDENT>if len(locator) >= <NUM_LIT:6>:<EOL><INDENT>if not <NUM_LIT:0> <= locator[<NUM_LIT:4>] <= <NUM_LIT>or not <NUM_LIT:0> <= locator[<NUM_LIT:5>] <= <NUM_LIT>:<EOL><INDENT>raise ValueError('<STR_LIT>' % locator)<EOL><DEDENT><DEDENT>if len(locator) == <NUM_LIT:8>:<EOL><INDENT>if not <NUM_LIT:0> <= locator[<NUM_LIT:6>] <= <NUM_LIT:9>or not <NUM_LIT:0> <= locator[<NUM_LIT:7>] <= <NUM_LIT:9>:<EOL><INDENT>raise ValueError('<STR_LIT>' % locator)<EOL><DEDENT><DEDENT>longitude = LONGITUDE_FIELD * locator[<NUM_LIT:0>]+ LONGITUDE_SQUARE * locator[<NUM_LIT:2>]<EOL>latitude = LATITUDE_FIELD * locator[<NUM_LIT:1>]+ LATITUDE_SQUARE * locator[<NUM_LIT:3>]<EOL>if len(locator) >= <NUM_LIT:6>:<EOL><INDENT>longitude += LONGITUDE_SUBSQUARE * locator[<NUM_LIT:4>]<EOL>latitude += LATITUDE_SUBSQUARE * locator[<NUM_LIT:5>]<EOL><DEDENT>if len(locator) == <NUM_LIT:8>:<EOL><INDENT>longitude += LONGITUDE_EXTSQUARE * locator[<NUM_LIT:6>] + LONGITUDE_EXTSQUARE / <NUM_LIT:2><EOL>latitude += LATITUDE_EXTSQUARE * locator[<NUM_LIT:7>] + LATITUDE_EXTSQUARE / <NUM_LIT:2><EOL><DEDENT>else:<EOL><INDENT>longitude += LONGITUDE_EXTSQUARE * <NUM_LIT:5><EOL>latitude += LATITUDE_EXTSQUARE * <NUM_LIT:5><EOL><DEDENT>longitude -= <NUM_LIT><EOL>latitude -= <NUM_LIT><EOL>return latitude, longitude<EOL>
Calculate geodesic latitude/longitude from Maidenhead locator. Args: locator (str): Maidenhead locator string Returns: tuple of float: Geodesic latitude and longitude values Raises: ValueError: Incorrect grid locator length ValueError: Invalid values in locator string
f12205:m14
def to_grid_locator(latitude, longitude, precision='<STR_LIT>'):
if precision not in ('<STR_LIT>', '<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>raise ValueError('<STR_LIT>' % precision)<EOL><DEDENT>if not -<NUM_LIT> <= latitude <= <NUM_LIT>:<EOL><INDENT>raise ValueError('<STR_LIT>' % latitude)<EOL><DEDENT>if not -<NUM_LIT> <= longitude <= <NUM_LIT>:<EOL><INDENT>raise ValueError('<STR_LIT>' % longitude)<EOL><DEDENT>latitude += <NUM_LIT><EOL>longitude += <NUM_LIT><EOL>locator = []<EOL>field = int(longitude / LONGITUDE_FIELD)<EOL>locator.append(chr(field + <NUM_LIT>))<EOL>longitude -= field * LONGITUDE_FIELD<EOL>field = int(latitude / LATITUDE_FIELD)<EOL>locator.append(chr(field + <NUM_LIT>))<EOL>latitude -= field * LATITUDE_FIELD<EOL>square = int(longitude / LONGITUDE_SQUARE)<EOL>locator.append(str(square))<EOL>longitude -= square * LONGITUDE_SQUARE<EOL>square = int(latitude / LATITUDE_SQUARE)<EOL>locator.append(str(square))<EOL>latitude -= square * LATITUDE_SQUARE<EOL>if precision in ('<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>subsquare = int(longitude / LONGITUDE_SUBSQUARE)<EOL>locator.append(chr(subsquare + <NUM_LIT>))<EOL>longitude -= subsquare * LONGITUDE_SUBSQUARE<EOL>subsquare = int(latitude / LATITUDE_SUBSQUARE)<EOL>locator.append(chr(subsquare + <NUM_LIT>))<EOL>latitude -= subsquare * LATITUDE_SUBSQUARE<EOL><DEDENT>if precision == '<STR_LIT>':<EOL><INDENT>extsquare = int(longitude / LONGITUDE_EXTSQUARE)<EOL>locator.append(str(extsquare))<EOL>extsquare = int(latitude / LATITUDE_EXTSQUARE)<EOL>locator.append(str(extsquare))<EOL><DEDENT>return '<STR_LIT>'.join(locator)<EOL>
Calculate Maidenhead locator from latitude and longitude. Args: latitude (float): Position's latitude longitude (float): Position's longitude precision (str): Precision with which generate locator string Returns: str: Maidenhead locator for latitude and longitude Raise: ValueError: Invalid precision identifier ValueError: Invalid latitude or longitude value
f12205:m15
def parse_location(location):
def split_dms(text, hemisphere):<EOL><INDENT>"""<STR_LIT>"""<EOL>out = []<EOL>sect = []<EOL>for i in text:<EOL><INDENT>if i.isdigit():<EOL><INDENT>sect.append(i)<EOL><DEDENT>else:<EOL><INDENT>out.append(sect)<EOL>sect = []<EOL><DEDENT><DEDENT>d, m, s = [float('<STR_LIT>'.join(i)) for i in out]<EOL>if hemisphere in '<STR_LIT>':<EOL><INDENT>d, m, s = [-<NUM_LIT:1> * x for x in (d, m, s)]<EOL><DEDENT>return to_dd(d, m, s)<EOL><DEDENT>for sep in '<STR_LIT>':<EOL><INDENT>chunks = location.split(sep)<EOL>if len(chunks) == <NUM_LIT:2>:<EOL><INDENT>if chunks[<NUM_LIT:0>].endswith('<STR_LIT:N>'):<EOL><INDENT>latitude = float(chunks[<NUM_LIT:0>][:-<NUM_LIT:1>])<EOL><DEDENT>elif chunks[<NUM_LIT:0>].endswith('<STR_LIT:S>'):<EOL><INDENT>latitude = -<NUM_LIT:1> * float(chunks[<NUM_LIT:0>][:-<NUM_LIT:1>])<EOL><DEDENT>else:<EOL><INDENT>latitude = float(chunks[<NUM_LIT:0>])<EOL><DEDENT>if chunks[<NUM_LIT:1>].endswith('<STR_LIT:E>'):<EOL><INDENT>longitude = float(chunks[<NUM_LIT:1>][:-<NUM_LIT:1>])<EOL><DEDENT>elif chunks[<NUM_LIT:1>].endswith('<STR_LIT>'):<EOL><INDENT>longitude = -<NUM_LIT:1> * float(chunks[<NUM_LIT:1>][:-<NUM_LIT:1>])<EOL><DEDENT>else:<EOL><INDENT>longitude = float(chunks[<NUM_LIT:1>])<EOL><DEDENT>return latitude, longitude<EOL><DEDENT>elif len(chunks) == <NUM_LIT:4>:<EOL><INDENT>if chunks[<NUM_LIT:0>].endswith(('<STR_LIT:s>', '<STR_LIT:">')):<EOL><INDENT>latitude = split_dms(chunks[<NUM_LIT:0>], chunks[<NUM_LIT:1>])<EOL><DEDENT>else:<EOL><INDENT>latitude = float(chunks[<NUM_LIT:0>])<EOL>if chunks[<NUM_LIT:1>] == '<STR_LIT:S>':<EOL><INDENT>latitude = -<NUM_LIT:1> * latitude<EOL><DEDENT><DEDENT>if chunks[<NUM_LIT:2>].endswith(('<STR_LIT:s>', '<STR_LIT:">')):<EOL><INDENT>longitude = split_dms(chunks[<NUM_LIT:2>], chunks[<NUM_LIT:3>])<EOL><DEDENT>else:<EOL><INDENT>longitude = float(chunks[<NUM_LIT:2>])<EOL>if chunks[<NUM_LIT:3>] == '<STR_LIT>':<EOL><INDENT>longitude = -<NUM_LIT:1> * longitude<EOL><DEDENT><DEDENT>return latitude, longitude<EOL><DEDENT><DEDENT>
Parse latitude and longitude from string location. Args: location (str): String to parse Returns: tuple of float: Latitude and longitude of location
f12205:m16
def sun_rise_set(latitude, longitude, date, mode='<STR_LIT>', timezone=<NUM_LIT:0>,<EOL>zenith=None):
if not date:<EOL><INDENT>date = datetime.date.today()<EOL><DEDENT>zenith = ZENITH[zenith]<EOL>n = (date - datetime.date(date.year - <NUM_LIT:1>, <NUM_LIT:12>, <NUM_LIT>)).days<EOL>lng_hour = longitude / <NUM_LIT:15><EOL>if mode == '<STR_LIT>':<EOL><INDENT>t = n + ((<NUM_LIT:6> - lng_hour) / <NUM_LIT>)<EOL><DEDENT>elif mode == '<STR_LIT>':<EOL><INDENT>t = n + ((<NUM_LIT> - lng_hour) / <NUM_LIT>)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>' % mode)<EOL><DEDENT>m = (<NUM_LIT> * t) - <NUM_LIT><EOL>l = m + <NUM_LIT> * math.sin(math.radians(m)) + <NUM_LIT>* math.sin(<NUM_LIT:2> * math.radians(m)) + <NUM_LIT><EOL>l = abs(l) % <NUM_LIT><EOL>ra = math.degrees(math.atan(<NUM_LIT> * math.tan(math.radians(l))))<EOL>l_quandrant = (math.floor(l / <NUM_LIT>)) * <NUM_LIT><EOL>ra_quandrant = (math.floor(ra / <NUM_LIT>)) * <NUM_LIT><EOL>ra = ra + (l_quandrant - ra_quandrant)<EOL>ra = ra / <NUM_LIT:15><EOL>sin_dec = <NUM_LIT> * math.sin(math.radians(l))<EOL>cos_dec = math.cos(math.asin(sin_dec))<EOL>cos_h = (math.radians(zenith) -<EOL>(sin_dec * math.sin(math.radians(latitude))))/ (cos_dec * math.cos(math.radians(latitude)))<EOL>if cos_h > <NUM_LIT:1>:<EOL><INDENT>return None<EOL><DEDENT>elif cos_h < -<NUM_LIT:1>:<EOL><INDENT>return None<EOL><DEDENT>if mode == '<STR_LIT>':<EOL><INDENT>h = <NUM_LIT> - math.degrees(math.acos(cos_h))<EOL><DEDENT>else:<EOL><INDENT>h = math.degrees(math.acos(cos_h))<EOL><DEDENT>h = h / <NUM_LIT:15><EOL>t = h + ra - (<NUM_LIT> * t) - <NUM_LIT><EOL>utc = t - lng_hour<EOL>local_t = utc + timezone / <NUM_LIT><EOL>if local_t < <NUM_LIT:0>:<EOL><INDENT>local_t += <NUM_LIT><EOL><DEDENT>elif local_t > <NUM_LIT>:<EOL><INDENT>local_t -= <NUM_LIT><EOL><DEDENT>hour = int(local_t)<EOL>if hour == <NUM_LIT:0>:<EOL><INDENT>minute = int(<NUM_LIT> * local_t)<EOL><DEDENT>else:<EOL><INDENT>minute = int(<NUM_LIT> * (local_t % hour))<EOL><DEDENT>if minute < <NUM_LIT:0>:<EOL><INDENT>minute += <NUM_LIT><EOL><DEDENT>return datetime.time(hour, minute)<EOL>
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 Args: 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: datetime.time or None: 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``
f12205:m17
def sun_events(latitude, longitude, date, timezone=<NUM_LIT:0>, zenith=None):
return (sun_rise_set(latitude, longitude, date, '<STR_LIT>', timezone, zenith),<EOL>sun_rise_set(latitude, longitude, date, '<STR_LIT>', timezone, zenith))<EOL>
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. Args: 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: tuple of datetime.time: The time for the given events in the specified timezone
f12205:m18
def dump_xearth_markers(markers, name='<STR_LIT>'):
output = []<EOL>for identifier, point in markers.items():<EOL><INDENT>line = ['<STR_LIT>' % (point.latitude, point.longitude), ]<EOL>if hasattr(point, '<STR_LIT:name>') and point.name:<EOL><INDENT>if name == '<STR_LIT>':<EOL><INDENT>line.append('<STR_LIT>' % (identifier, point.name))<EOL><DEDENT>elif name == '<STR_LIT:name>':<EOL><INDENT>line.append('<STR_LIT>' % (point.name, identifier))<EOL><DEDENT>elif name == '<STR_LIT>':<EOL><INDENT>line.append('<STR_LIT>' % (identifier, point.comment))<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>' % name)<EOL><DEDENT>if hasattr(point, '<STR_LIT>') and point.altitude:<EOL><INDENT>line.append('<STR_LIT>' % point.altitude)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>line.append('<STR_LIT>' % identifier)<EOL><DEDENT>output.append('<STR_LIT>'.join(line))<EOL><DEDENT>return sorted(output, key=lambda x: x.split()[<NUM_LIT:2>])<EOL>
Generate an Xearth compatible marker file. ``dump_xearth_markers()`` writes a simple Xearth_ marker file from a dictionary of :class:`trigpoints.Trigpoint` objects. It expects a dictionary in one of the following formats. For support of :class:`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 Args: markers (dict): Dictionary of identifier keys, with :class:`Trigpoint` values name (str): Value to use as Xearth display string Returns: list: List of strings representing an Xearth marker file Raises: ValueError: Unsupported value for ``name`` .. _xearth: http://hewgill.com/xearth/original/ .. _xplanet: http://xplanet.sourceforge.net/
f12205:m19
def calc_radius(latitude, ellipsoid='<STR_LIT>'):
ellipsoids = {<EOL>'<STR_LIT>': (<NUM_LIT>, <NUM_LIT>), <EOL>'<STR_LIT>': (<NUM_LIT>, <NUM_LIT>),<EOL>'<STR_LIT>': (<NUM_LIT>, <NUM_LIT>),<EOL>'<STR_LIT>': (<NUM_LIT>, <NUM_LIT>), <EOL>'<STR_LIT>': (<NUM_LIT>, <NUM_LIT>),<EOL>'<STR_LIT>': (<NUM_LIT>, <NUM_LIT>),<EOL>'<STR_LIT>': (<NUM_LIT>, <NUM_LIT>),<EOL>'<STR_LIT>': (<NUM_LIT>, <NUM_LIT>),<EOL>'<STR_LIT>': (<NUM_LIT>, <NUM_LIT>),<EOL>'<STR_LIT>': (<NUM_LIT>, <NUM_LIT>),<EOL>'<STR_LIT>': (<NUM_LIT>, <NUM_LIT>), <EOL>}<EOL>major, minor = ellipsoids[ellipsoid]<EOL>eccentricity = <NUM_LIT:1> - (minor ** <NUM_LIT:2> / major ** <NUM_LIT:2>)<EOL>sl = math.sin(math.radians(latitude))<EOL>return (major * (<NUM_LIT:1> - eccentricity)) / (<NUM_LIT:1> - eccentricity * sl ** <NUM_LIT:2>) ** <NUM_LIT><EOL>
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 :data:`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. Args: latitude (float): Latitude to calculate earth radius for ellipsoid (tuple of float): Ellipsoid model to use for calculation Returns: float: Approximated Earth radius at the given latitude
f12205:m20
def __init__(self, site=None):
super(FileFormatError, self).__init__()<EOL>self.site = site<EOL>
Initialise a new ``FileFormatError`` object. Args: site (str): Remote site name to display in error message
f12205:c0:m0
def __str__(self):
if self.site:<EOL><INDENT>return ("<STR_LIT>"<EOL>'<STR_LIT>' % (self.site,<EOL>__bug_report__))<EOL><DEDENT>else:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>
Pretty printed error string. Returns: str: Human readable error string
f12205:c0:m1
def __init__(self, tzstring):
super(TzOffset, self).__init__()<EOL>hours, minutes = map(int, tzstring.split('<STR_LIT::>'))<EOL>self.__offset = datetime.timedelta(hours=hours, minutes=minutes)<EOL>
Initialise a new ``TzOffset`` object. Args:: tzstring (str): `ISO 8601`_ style timezone definition .. _ISO 8601: http://www.cl.cam.ac.uk/~mgk25/iso-time.html
f12205:c1:m0
def __repr__(self):
return repr_assist(self, {'<STR_LIT>': self.as_timezone()})<EOL>
Self-documenting string representation. Returns: str: String to recreate ``TzOffset`` object
f12205:c1:m1
def dst(self, dt=None):
return datetime.timedelta(<NUM_LIT:0>)<EOL>
Daylight Savings Time offset. Note: This method is only for compatibility with the ``tzinfo`` interface, and does nothing Args: dt (any): For compatibility with parent classes
f12205:c1:m2
def as_timezone(self):
offset = self.utcoffset()<EOL>hours, minutes = divmod(offset.seconds / <NUM_LIT>, <NUM_LIT>)<EOL>if offset.days == -<NUM_LIT:1>:<EOL><INDENT>hours = -<NUM_LIT> + hours<EOL><DEDENT>return '<STR_LIT>' % (hours, minutes)<EOL>
Create a human-readable timezone string. Returns: str: Human-readable timezone definition
f12205:c1:m3
def utcoffset(self, dt=None):
return self.__offset<EOL>
Return the offset in minutes from UTC. Args: dt (any): For compatibility with parent classes
f12205:c1:m4
def isoformat(self):
text = [self.strftime('<STR_LIT>'), ]<EOL>if self.tzinfo:<EOL><INDENT>text.append(self.tzinfo.as_timezone())<EOL><DEDENT>else:<EOL><INDENT>text.append('<STR_LIT>')<EOL><DEDENT>return '<STR_LIT>'.join(text)<EOL>
Generate an ISO 8601 formatted time stamp. Returns: str: `ISO 8601`_ formatted time stamp .. _ISO 8601: http://www.cl.cam.ac.uk/~mgk25/iso-time.html
f12205:c2:m0
@staticmethod<EOL><INDENT>def parse_isoformat(timestamp):<DEDENT>
if len(timestamp) == <NUM_LIT:20>:<EOL><INDENT>zone = TzOffset('<STR_LIT>')<EOL>timestamp = timestamp[:-<NUM_LIT:1>]<EOL><DEDENT>elif len(timestamp) == <NUM_LIT>:<EOL><INDENT>zone = TzOffset('<STR_LIT>' % (timestamp[-<NUM_LIT:5>:-<NUM_LIT:2>], timestamp[-<NUM_LIT:2>:]))<EOL>timestamp = timestamp[:-<NUM_LIT:5>]<EOL><DEDENT>elif len(timestamp) == <NUM_LIT>:<EOL><INDENT>zone = TzOffset(timestamp[-<NUM_LIT:6>:])<EOL>timestamp = timestamp[:-<NUM_LIT:6>]<EOL><DEDENT>timestamp = Timestamp.strptime(timestamp, '<STR_LIT>')<EOL>timestamp = timestamp.replace(tzinfo=zone)<EOL>return timestamp<EOL>
Parse an ISO 8601 formatted time stamp. Args: timestamp (str): Timestamp to parse Returns: Timestamp: Parsed timestamp
f12205:c2:m1
def __init__(self, alt_id, name, state, country, wmo, latitude, longitude,<EOL>ua_latitude, ua_longitude, altitude, ua_altitude, rbsn):
super(Station, self).__init__(latitude, longitude, altitude, name)<EOL>self.alt_id = alt_id<EOL>self.state = state<EOL>self.country = country<EOL>self.wmo = wmo<EOL>self.ua_latitude = ua_latitude<EOL>self.ua_longitude = ua_longitude<EOL>self.ua_altitude = ua_altitude<EOL>self.rbsn = rbsn<EOL>
Initialise a new ``Station`` object. Args: alt_id (str): Alternate location identifier name (str): Station's name state (str): State name, if station is in the US country (str): Country name wmo (int): WMO region code latitude (float): Station's latitude longitude (float): Station's longitude ua_latitude (float): Station's upper air latitude ua_longitude (float): Station's upper air longitude altitude (int): Station's elevation ua_altitude (int): Station's upper air elevation rbsn (bool): True if station belongs to RSBN
f12206: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
f12206:c0:m1
def __format__(self, format_spec='<STR_LIT>'):
text = super(Station.__base__, self).__format__(format_spec)<EOL>if self.alt_id:<EOL><INDENT>return '<STR_LIT>' % (self.name, self.alt_id, text)<EOL><DEDENT>else:<EOL><INDENT>return '<STR_LIT>' % (self.name, text)<EOL><DEDENT>
Extended pretty printing for location strings. Args: format_spec str: Coordinate formatting system to use Returns: Human readable string representation of ``Point`` object Raises: ValueError: Unknown value for ``format_spec``
f12206:c0:m2
def __init__(self, data=None, index='<STR_LIT>'):
super(Stations, self).__init__()<EOL>self._data = data<EOL>self._index = index<EOL>if data:<EOL><INDENT>self.import_locations(data, index)<EOL><DEDENT>
Initialise a new `Stations` object.
f12206:c1:m0
def import_locations(self, data, index='<STR_LIT>'):
self._data = data<EOL>data = utils.prepare_read(data)<EOL>for line in data:<EOL><INDENT>line = line.strip()<EOL>chunk = line.split('<STR_LIT:;>')<EOL>if not len(chunk) == <NUM_LIT>:<EOL><INDENT>if index == '<STR_LIT>':<EOL><INDENT>logging.debug('<STR_LIT>'<EOL>'<STR_LIT>' % line)<EOL>chunk.extend(['<STR_LIT>', '<STR_LIT>'])<EOL><DEDENT>elif index == '<STR_LIT>' and len(chunk) == <NUM_LIT>:<EOL><INDENT>logging.debug('<STR_LIT>'<EOL>'<STR_LIT>' % line)<EOL>chunk.append('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>raise utils.FileFormatError('<STR_LIT>')<EOL><DEDENT><DEDENT>if index == '<STR_LIT>':<EOL><INDENT>identifier = '<STR_LIT>'.join(chunk[:<NUM_LIT:2>])<EOL>alt_id = chunk[<NUM_LIT:2>]<EOL><DEDENT>elif index == '<STR_LIT>':<EOL><INDENT>identifier = chunk[<NUM_LIT:0>]<EOL>alt_id = '<STR_LIT>'.join(chunk[<NUM_LIT:1>:<NUM_LIT:3>])<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>' % index)<EOL><DEDENT>if alt_id in ('<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>alt_id = None<EOL><DEDENT>name = chunk[<NUM_LIT:3>]<EOL>state = chunk[<NUM_LIT:4>] if chunk[<NUM_LIT:4>] else None<EOL>country = chunk[<NUM_LIT:5>]<EOL>wmo = int(chunk[<NUM_LIT:6>]) if chunk[<NUM_LIT:6>] else None<EOL>point_data = []<EOL>for i in chunk[<NUM_LIT:7>:<NUM_LIT:11>]:<EOL><INDENT>if not i:<EOL><INDENT>point_data.append(None)<EOL>continue<EOL><DEDENT>if '<STR_LIT:U+0020>' in i:<EOL><INDENT>logging.debug('<STR_LIT>'<EOL>% line)<EOL>i = i.replace('<STR_LIT:U+0020>', '<STR_LIT:0>')<EOL><DEDENT>values = map(int, i[:-<NUM_LIT:1>].split('<STR_LIT:->'))<EOL>if i[-<NUM_LIT:1>] in ('<STR_LIT:S>', '<STR_LIT>'):<EOL><INDENT>values = [-x for x in values]<EOL><DEDENT>point_data.append(point.utils.to_dd(*values))<EOL><DEDENT>latitude, longitude, ua_latitude, ua_longitude = point_data<EOL>altitude = int(chunk[<NUM_LIT:11>]) if chunk[<NUM_LIT:11>] else None<EOL>ua_altitude = int(chunk[<NUM_LIT:12>]) if chunk[<NUM_LIT:12>] else None<EOL>rbsn = False if not chunk[<NUM_LIT>] else True<EOL>self[identifier] = Station(alt_id, name, state, country, wmo,<EOL>latitude, longitude, ua_latitude,<EOL>ua_longitude, altitude, ua_altitude,<EOL>rbsn)<EOL><DEDENT>
Parse NOAA weather station data files. ``import_locations()`` returns a dictionary with keys containing either the WMO or ICAO identifier, and values that are ``Station`` objects that describes the large variety of data exported by NOAA_. It expects data files in one of the following formats:: 00;000;PABL;Buckland, Buckland Airport;AK;United States;4;65-58-56N;161-09-07W;;;7;; 01;001;ENJA;Jan Mayen;;Norway;6;70-56N;008-40W;70-56N;008-40W;10;9;P 01;002;----;Grahuken;;Norway;6;79-47N;014-28E;;;;15; or:: AYMD;94;014;Madang;;Papua New Guinea;5;05-13S;145-47E;05-13S;145-47E;3;5;P AYMO;--;---;Manus Island/Momote;;Papua New Guinea;5;02-03-43S;147-25-27E;;;4;; AYPY;94;035;Moresby;;Papua New Guinea;5;09-26S;147-13E;09-26S;147-13E;38;49;P Files containing the data in this format can be downloaded from the :abbr:`NOAA (National Oceanographic and Atmospheric Administration)`'s site in their `station location page`_. WMO indexed files downloaded from the :abbr:`NOAA (National Oceanographic and Atmospheric Administration)` site when processed by ``import_locations()`` will return ``dict`` object of the following style:: {'00000': Station('PABL', 'Buckland, Buckland Airport', 'AK', 'United States', 4, 65.982222. -160.848055, None, None, 7, False), '01001'; Station('ENJA', Jan Mayen, None, 'Norway', 6, 70.933333, -7.333333, 70.933333, -7.333333, 10, 9, True), '01002': Station(None, 'Grahuken', None, 'Norway', 6, 79.783333, 13.533333, None, None, 15, False)} And ``dict`` objects such as the following will be created when ICAO indexed data files are processed:: {'AYMD': Station("94", "014", "Madang", None, "Papua New Guinea", 5, -5.216666, 145.783333, -5.216666, 145.78333333333333, 3, 5, True, 'AYMO': Station(None, None, "Manus Island/Momote", None, "Papua New Guinea", 5, -2.061944, 147.424166, None, None, 4, False, 'AYPY': Station("94", "035", "Moresby", None, "Papua New Guinea", 5, -9.433333, 147.216667, -9.433333, 147.216667, 38, 49, True} Args: data (iter): NOAA station data to read index (str): The identifier type used in the file Returns: dict: WMO locations with `Station` objects Raises: FileFormatError: Unknown file format .. _NOAA: http://weather.noaa.gov/ .. _station location page: http://weather.noaa.gov/tg/site.shtml
f12206:c1:m1
@cli.command()<EOL>@click.option('<STR_LIT>', '<STR_LIT>', is_flag=True, help='<STR_LIT>')<EOL>@click.pass_obj<EOL>def bearing(globs, string):
globs.locations.bearing('<STR_LIT>', string)<EOL>
Calculate initial bearing between locations.
f12207:m1
@cli.command()<EOL>@click.option('<STR_LIT>', '<STR_LIT>',<EOL>type=click.Choice(['<STR_LIT>', '<STR_LIT>', '<STR_LIT>']),<EOL>default='<STR_LIT>',<EOL>help='<STR_LIT>')<EOL>@click.argument('<STR_LIT>', type=float)<EOL>@click.argument('<STR_LIT>', type=float)<EOL>@click.pass_obj<EOL>def destination(globs, locator, distance, bearing):
globs.locations.destination(distance, bearing, locator)<EOL>
Calculate destination from locations.
f12207:m2
@cli.command()<EOL>@click.option('<STR_LIT>', '<STR_LIT>',<EOL>type=click.Choice(['<STR_LIT>', '<STR_LIT>', '<STR_LIT>']),<EOL>help='<STR_LIT>')<EOL>@click.pass_obj<EOL>def display(globs, locator):
globs.locations.display(locator)<EOL>
Pretty print the locations.
f12207:m3