signature
stringlengths
8
3.44k
body
stringlengths
0
1.41M
docstring
stringlengths
1
122k
id
stringlengths
5
17
def is_multicast(mac):
octet = int(mac.split('<STR_LIT::>')[<NUM_LIT:0>], base=<NUM_LIT:16>)<EOL>return octet & <NUM_LIT> > <NUM_LIT:0><EOL>
Whether a MAC address is IPV4/V6 multicast address. See https://en.wikipedia.org/wiki/Multicast_address#Ethernet ARgs: mac (str): MAC address Returns: bool >>> is_multicast('01:80:C2:00:00:08') True
f14105:m3
def is_lowest_rate(rate):
return rate_to_mcs(rate) == <NUM_LIT:0><EOL>
Whether or not the rate is the lowest rate in rate table. Args: rate (int): rate in Mbps . Can be 802.11g/n rate. Returns: bool: ``True`` if the rate is lowest, otherwise ``False``. Note that if ``rate`` is not valid, this function returns ``False``, instead of raising an exception.
f14105:m4
def is_highest_rate(rate):
return rate_to_mcs(rate) == <NUM_LIT:7><EOL>
Whether or not the rate is the highest rate (single spatial stream) in rate table. Args: rate (int): rate in Mbps. Can be 802.11g/n rate. Returns: bool: ``True`` if the rate is highest, otherwise ``False``. Note that if ``rate`` is not valid, this function returns ``False``, instead of raising an exception.
f14105:m5
def is_ack(pkt):
return pkt.type == DOT11_TYPE_CONTROL and pkt.subtype == DOT11_SUBTYPE_ACK<EOL>
Whether or not the packet is an ack packet. Args: pkt (:class:`wltrace.dot11.Dot11Packet`): the packet. Returns: bool: ``True`` if it is an ack packet, otherwise ``False``.
f14105:m6
def is_block_ack(pkt):
return pkt.type == DOT11_TYPE_CONTROL andpkt.subtype == DOT11_SUBTYPE_BLOCK_ACK<EOL>
Whether a packet is a Block Ack packet.
f14105:m7
def is_beacon(pkt):
return pkt.type == DOT11_TYPE_MANAGEMENT andpkt.subtype == DOT11_SUBTYPE_BEACON<EOL>
Whether a packet is a Beacon packet.
f14105:m8
def is_qos_data(pkt):
return pkt.type == DOT11_TYPE_DATA and pkt.subtype == DOT11_SUBTYPE_QOS_DATA<EOL>
Whether a packet is a QoS Data packet.
f14105:m9
def next_seq(seq):
return (seq + <NUM_LIT:1>) % SEQ_NUM_MODULO<EOL>
Next sequence number. Args: seq (int): current sequence number Returns: int: next sequence number, may wrap around >>> next_seq(3) 4 >>> next_seq(4095) 0
f14105:m10
@property<EOL><INDENT>def src(self):<DEDENT>
return getattr(self, '<STR_LIT>', None)<EOL>
Shortcut to ``pkt.addr2``.
f14105:c2:m4
@property<EOL><INDENT>def dest(self):<DEDENT>
return getattr(self, '<STR_LIT>', None)<EOL>
Shortcut to ``pkt.addr1``.
f14105:c2:m6
@property<EOL><INDENT>def ts(self):<DEDENT>
return datetime.datetime.fromtimestamp(self.phy.epoch_ts)<EOL>
Shortcut to ``pkt.phy.timestamp``.
f14105:c2:m8
def air_time(self):
return self.phy.len * <NUM_LIT:8> / self.phy.rate * <NUM_LIT><EOL>
Duration of the packet in air. Returns: float: duration in seconds.
f14105:c2:m14
def calc_padding(fmt, align):
remain = struct.calcsize(fmt) % align<EOL>if remain == <NUM_LIT:0>:<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>return '<STR_LIT:x>' * (align - remain)<EOL>
Calculate how many padding bytes needed for ``fmt`` to be aligned to ``align``. Args: fmt (str): :mod:`struct` format. align (int): alignment (2, 4, 8, etc.) Returns: str: padding format (e.g., various number of 'x'). >>> calc_padding('b', 2) 'x' >>> calc_padding('b', 3) 'xx'
f14108:m0
def align_up(offset, align):
remain = offset % align<EOL>if remain == <NUM_LIT:0>:<EOL><INDENT>return offset<EOL><DEDENT>else:<EOL><INDENT>return offset + (align - remain)<EOL><DEDENT>
Align ``offset`` up to ``align`` boundary. Args: offset (int): value to be aligned. align (int): alignment boundary. Returns: int: aligned offset. >>> align_up(3, 2) 4 >>> align_up(3, 1) 3
f14108:m1
def win_ts_to_unix_epoch(high, low):
return high * ((<NUM_LIT:2> ** <NUM_LIT:32>) / <NUM_LIT>) + low / <NUM_LIT> - <NUM_LIT><EOL>
Convert Windows timestamp to POSIX timestamp. See https://goo.gl/VVX0nk Args: high (int): high 32 bits of windows timestamp. low (int): low 32 bits of windows timestamp. Returns: float
f14108:m2
def win_ts(high, low):
return datetime.datetime.fromtimestamp(win_ts_to_unix_epoch(high, low))<EOL>
Convert Windows timestamp to Unix timestamp. Windows timestamp is a 64-bit integer, the value of which is the number of 100 ns intervals from 1/1/1601-UTC. Args: high (int): high 32 bits of windows timestamp. low (int): low 32 bits of windows timestamp. Returns: Python timestamp (``datetime.datetime`` object).
f14108:m3
def bin_to_mac(bin, size=<NUM_LIT:6>):
if len(bin) != size:<EOL><INDENT>raise Exception("<STR_LIT>" % (bin))<EOL><DEDENT>return '<STR_LIT::>'.join([binascii.hexlify(o) for o in bin])<EOL>
Convert 6 bytes into a MAC string. Args: bin (str): hex string of lenth 6. Returns: str: String representation of the MAC address in lower case. Raises: Exception: if ``len(bin)`` is not 6.
f14108:m4
def assertSequenceAlmostEqual(self, first, second, places=None, msg=None, delta=None):
if first == second:<EOL><INDENT>return True<EOL><DEDENT>self.assertEqual(len(first), len(second))<EOL>for one, two in zip(first, second):<EOL><INDENT>self.assertAlmostEqual(one, two, places, msg, delta)<EOL><DEDENT>
Fail if the contents of two sequences are not "almost equal".
f14113:c0:m0
@with_settings(warn_only=True)<EOL>def pep8():
local('<STR_LIT>')<EOL>
Check source for PEP8 conformance.
f14115:m1
def precommit():
pep8()<EOL>local('<STR_LIT>')<EOL>local('<STR_LIT>')<EOL>test()<EOL>
Run pre-commit unit tests and lint checks.
f14115:m2
def lint(fmt='<STR_LIT>'):
if fmt == '<STR_LIT:html>':<EOL><INDENT>outfile = '<STR_LIT>'<EOL>local('<STR_LIT>' % (fmt, outfile))<EOL>local('<STR_LIT>' % outfile)<EOL><DEDENT>else:<EOL><INDENT>local('<STR_LIT>' % fmt)<EOL><DEDENT>
Run verbose PyLint on source. Optionally specify fmt=html for HTML output.
f14115:m3
def clean():
local('<STR_LIT>')<EOL>local('<STR_LIT>')<EOL>local('<STR_LIT>')<EOL>with lcd('<STR_LIT>'):<EOL><INDENT>local('<STR_LIT>')<EOL><DEDENT>
Clean up generated files.
f14115:m4
def release(version):
clean()<EOL>local('<STR_LIT>')<EOL>local('<STR_LIT>')<EOL>local('<STR_LIT>' % version)<EOL>local('<STR_LIT>')<EOL>
Perform git-flow release merging and PyPI upload.
f14115:m5
def doc(fmt='<STR_LIT:html>'):
with lcd('<STR_LIT>'):<EOL><INDENT>local('<STR_LIT>' % fmt)<EOL><DEDENT>if fmt == '<STR_LIT:html>':<EOL><INDENT>local('<STR_LIT>')<EOL><DEDENT>
Build Sphinx HTML documentation.
f14115:m6
def __init__(self, parent, id, title, project=None):
wx.Frame.__init__(self, parent, id, title, wx.DefaultPosition, wx.Size(<NUM_LIT>, <NUM_LIT>))<EOL>self.CreateStatusBar()<EOL>menubar = wx.MenuBar()<EOL>file_menu = wx.Menu()<EOL>file_menu_new = file_menu.Append(wx.ID_NEW, '<STR_LIT>', '<STR_LIT>')<EOL>file_menu_open = file_menu.Append(wx.ID_OPEN, '<STR_LIT>', '<STR_LIT>')<EOL>file_menu_save = file_menu.Append(wx.ID_SAVE, '<STR_LIT>', '<STR_LIT>')<EOL>file_menu_quit = file_menu.Append(wx.ID_EXIT, '<STR_LIT>', '<STR_LIT>')<EOL>menubar.Append(file_menu, '<STR_LIT>')<EOL>self.SetMenuBar(menubar)<EOL>self.Bind(wx.EVT_MENU, self.OnOpen, file_menu_open)<EOL>self.Bind(wx.EVT_MENU, self.OnQuit, file_menu_quit)<EOL>self.splitter = wx.SplitterWindow(self, -<NUM_LIT:1>)<EOL>self.leftPanel = leftPanel = TestPanel(self.splitter, project)<EOL>self.dvc = leftPanel.dvc<EOL>leftBox = wx.BoxSizer(wx.VERTICAL)<EOL>self.dvc.Bind(dv.EVT_DATAVIEW_SELECTION_CHANGED, self.OnSelChanged)<EOL>leftPanel.SetSizer(leftBox)<EOL>rightPanel = wx.Panel(self.splitter, -<NUM_LIT:1>)<EOL>rightBox = wx.BoxSizer(wx.VERTICAL)<EOL>self.display = wx.StaticText(rightPanel, -<NUM_LIT:1>, '<STR_LIT>', (<NUM_LIT:10>, <NUM_LIT:10>), style=wx.ALIGN_LEFT)<EOL>rightBox.Add(self.display, -<NUM_LIT:1>, wx.EXPAND)<EOL>rightPanel.SetSizer(rightBox)<EOL>self.splitter.SplitVertically(leftPanel, rightPanel)<EOL>self.Centre()<EOL>
Initialize our window
f14116:c2:m0
def OnSelChanged(self, event):
<EOL>item = event.GetItem()<EOL>obj = self.leftPanel.model.ItemToObject(item)<EOL>if isinstance(obj, compass.Survey):<EOL><INDENT>l = [<EOL>'<STR_LIT>' % obj.name,<EOL>'<STR_LIT>' % obj.date,<EOL>'<STR_LIT>' % obj.comment,<EOL>'<STR_LIT>' % '<STR_LIT:U+002CU+0020>'.join(obj.team),<EOL>'<STR_LIT>' % obj.length,<EOL>'<STR_LIT>',<EOL>]<EOL>l.extend(['<STR_LIT:U+0020>'.join(['<STR_LIT>' % (k,v) for (k,v) in shot.items()]) for shot in obj.shots])<EOL>self.display.SetLabel(str('<STR_LIT:\n>'.join(l)))<EOL><DEDENT>else:<EOL><INDENT>self.display.SetLabel('<STR_LIT>')<EOL><DEDENT>
Method called when selected item is changed
f14116:c2:m1
def OnInit(self):
project = compass.CompassProjectParser(sys.argv[<NUM_LIT:1>]).parse()<EOL>frame = MyFrame(None, -<NUM_LIT:1>, '<STR_LIT>', project)<EOL>frame.Show(True)<EOL>self.SetTopWindow(frame)<EOL>return True<EOL>
Initialize by creating the split window with the tree
f14116:c3:m0
@event<EOL><INDENT>def survey_selected(self, datfilename, surveyname):<DEDENT>
Event fired when a Survey node has been selected
f14117:c2:m5
@event<EOL><INDENT>def datfile_selected(self, datfilename):<DEDENT>
Event fired when a DatFile node has been selected
f14117:c2:m6
@event<EOL><INDENT>def project_selected(self):<DEDENT>
Event fired when the Project top-level node has been selected
f14117:c2:m7
@event<EOL><INDENT>def OnProjectOpen(self, makfilename):<DEDENT>
Event fired when user has selected a new Project file to open
f14117:c3:m2
@event<EOL><INDENT>def OnSurveySelected(self, datfilename, surveyname):<DEDENT>
Event fired when user clicks a Survey node
f14117:c3:m3
def find_candidate_splays(splays, azm, inc, delta=LRUD_DELTA):
return [splay for splay in splays<EOL>if<EOL>angle_delta(splay['<STR_LIT>'], azm) <= delta/<NUM_LIT:2><EOL>and<EOL>angle_delta(splay['<STR_LIT>'], inc) <= delta/<NUM_LIT:2><EOL>]<EOL>
Given a list of splay shots, find candidate LEFT or RIGHT given target AZM and INC
f14119:m0
def find_candidate_vert_splays(splays, inc, delta=LRUD_DELTA):
<EOL>if inc == <NUM_LIT>:<EOL><INDENT>return [splay for splay in splays if splay['<STR_LIT>'] >= <NUM_LIT:30>]<EOL><DEDENT>elif inc == -<NUM_LIT>:<EOL><INDENT>return [splay for splay in splays if splay['<STR_LIT>'] <= -<NUM_LIT:30>]<EOL><DEDENT>
Given a list of splay shots, find candidate UP or DOWN given target INC (90, or -90)
f14119:m1
def shot2shot(insurvey, inshot, calculate_lrud=True):
<EOL>splays = insurvey.splays[inshot['<STR_LIT>']]<EOL>if calculate_lrud and not inshot.is_splay and splays:<EOL><INDENT>print('<STR_LIT>' '<STR_LIT>' % (inshot['<STR_LIT>'], len(splays)))<EOL>left_azm, right_azm = (inshot['<STR_LIT>'] - <NUM_LIT>) % <NUM_LIT>, (inshot['<STR_LIT>'] + <NUM_LIT>) % <NUM_LIT><EOL>left_shot, right_shot = None, None<EOL>left_candidates = find_candidate_splays(splays, left_azm, <NUM_LIT:0>)<EOL>if left_candidates:<EOL><INDENT>left_shot = max(left_candidates, key=lambda shot: hd(shot['<STR_LIT>'], shot['<STR_LIT>']))<EOL>left = hd(left_shot['<STR_LIT>'], left_shot['<STR_LIT>'])<EOL><DEDENT>else:<EOL><INDENT>left = <NUM_LIT:0><EOL><DEDENT>right_candidates = find_candidate_splays(splays, right_azm, <NUM_LIT:0>)<EOL>if right_candidates:<EOL><INDENT>right_shot = max(right_candidates, key=lambda shot: hd(shot['<STR_LIT>'], shot['<STR_LIT>']))<EOL>right = hd(right_shot['<STR_LIT>'], right_shot['<STR_LIT>'])<EOL><DEDENT>else:<EOL><INDENT>right = <NUM_LIT:0><EOL><DEDENT>print('<STR_LIT:\t>' '<STR_LIT>' % (left_azm, inshot['<STR_LIT>'], right_azm))<EOL>print('<STR_LIT:\t>' '<STR_LIT>' % len(left_candidates))<EOL>for splay in left_candidates:<EOL><INDENT>print('<STR_LIT>' + str(splay))<EOL><DEDENT>print('<STR_LIT>' '<STR_LIT>' % (left, str(left_shot)))<EOL>print('<STR_LIT:\t>' '<STR_LIT>' % len(right_candidates))<EOL>for splay in right_candidates:<EOL><INDENT>print('<STR_LIT>' + str(splay))<EOL><DEDENT>print('<STR_LIT>' '<STR_LIT>' % (right, str(right_shot)))<EOL>up_candidates = find_candidate_vert_splays(splays, <NUM_LIT>)<EOL>if up_candidates:<EOL><INDENT>up_shot = max(up_candidates, key=lambda splay: vd(splay['<STR_LIT>'], splay['<STR_LIT>']))<EOL>up = vd(up_shot['<STR_LIT>'], up_shot['<STR_LIT>'])<EOL><DEDENT>else:<EOL><INDENT>up = <NUM_LIT:0><EOL><DEDENT>down_candidates = find_candidate_vert_splays(splays, -<NUM_LIT>)<EOL>if down_candidates:<EOL><INDENT>down_shot = max(down_candidates, key=lambda splay: vd(splay['<STR_LIT>'], splay['<STR_LIT>'])) <EOL>down = vd(down_shot['<STR_LIT>'], down_shot['<STR_LIT>'])<EOL><DEDENT>else:<EOL><INDENT>down = <NUM_LIT:0><EOL><DEDENT>print('<STR_LIT:\t>', inshot, '<STR_LIT>', '<STR_LIT:U+002CU+0020>'.join(('<STR_LIT>' % v) for v in (left, right, up, down)))<EOL>assert(all(v >=<NUM_LIT:0> for v in (left, right, up, down)))<EOL><DEDENT>else:<EOL><INDENT>up, down, left, right = None, None, None, None<EOL><DEDENT>return compass.Shot([<EOL>('<STR_LIT>', inshot['<STR_LIT>']),<EOL>('<STR_LIT>', inshot['<STR_LIT>'] or '<STR_LIT>' % (inshot['<STR_LIT>'], random.randint(<NUM_LIT:0>,<NUM_LIT:1000>))),<EOL>('<STR_LIT>', m2ft(inshot.length)),<EOL>('<STR_LIT>', inshot['<STR_LIT>']),<EOL>('<STR_LIT>', inshot.inc),<EOL>('<STR_LIT>', m2ft(left) if left is not None else -<NUM_LIT>),<EOL>('<STR_LIT>', m2ft(up) if left is not None else -<NUM_LIT>),<EOL>('<STR_LIT>', m2ft(down) if left is not None else -<NUM_LIT>),<EOL>('<STR_LIT>', m2ft(right) if left is not None else -<NUM_LIT>), <EOL>('<STR_LIT>', (compass.Exclude.LENGTH, compass.Exclude.PLOT) if inshot.is_splay else ()),<EOL>('<STR_LIT>', inshot['<STR_LIT>'])<EOL>])<EOL>
Convert a PocketTopo `Shot` to a Compass `Shot`
f14119:m2
def pockettopo2compass(txtfilename, exclude_splays=False, calculate_lrud=False):
print('<STR_LIT>' % txtfilename)<EOL>infile = pockettopo.TxtFile.read(txtfilename, merge_duplicate_shots=True)<EOL>cave_name = os.path.basename(txtfilename).rsplit('<STR_LIT:.>', <NUM_LIT:1>)[<NUM_LIT:0>].replace('<STR_LIT:_>', '<STR_LIT:U+0020>')<EOL>outfilename = txtfilename.rsplit('<STR_LIT:.>', <NUM_LIT:1>)[<NUM_LIT:0>] + '<STR_LIT>'<EOL>outfile = compass.DatFile(cave_name)<EOL>for insurvey in infile:<EOL><INDENT>outsurvey = compass.Survey(<EOL>insurvey.name, insurvey.date, comment=insurvey.comment, cave_name=cave_name, declination=insurvey.declination<EOL>)<EOL>outsurvey.length_units = '<STR_LIT:M>'<EOL>outsurvey.passage_units = '<STR_LIT:M>'<EOL>for inshot in insurvey:<EOL><INDENT>if inshot.is_splay and exclude_splays:<EOL><INDENT>continue <EOL><DEDENT>outshot = shot2shot(insurvey, inshot, calculate_lrud)<EOL>outsurvey.add_shot(outshot)<EOL><DEDENT>outfile.add_survey(outsurvey)<EOL><DEDENT>outfile.write(outfilename)<EOL>print('<STR_LIT>' % outfilename)<EOL>
Main function which converts a PocketTopo .TXT file to a Compass .DAT file
f14119:m3
def convert_filename(txtfilename, outdir='<STR_LIT:.>'):
return os.path.join(outdir, os.path.basename(txtfilename)).rsplit('<STR_LIT:.>', <NUM_LIT:1>)[<NUM_LIT:0>] + '<STR_LIT>'<EOL>
Convert a .TXT filename to a Therion .TH filename
f14122:m0
def pockettopo2therion(txtfilename):
print('<STR_LIT>' % txtfilename)<EOL>infile = pockettopo.TxtFile.read(txtfilename, merge_duplicate_shots=True)<EOL>outfilename = convert_filename(txtfilename)<EOL>with open(outfilename, '<STR_LIT:w>') as outfile:<EOL><INDENT>print('<STR_LIT>', file=outfile)<EOL>for insurvey in infile:<EOL><INDENT>print(file=outfile)<EOL>print('<STR_LIT>', file=outfile)<EOL>print('<STR_LIT:\t>' '<STR_LIT>' + insurvey.date.strftime('<STR_LIT>'), file=outfile)<EOL>print('<STR_LIT:\t>' '<STR_LIT>', file=outfile)<EOL>for shot in insurvey:<EOL><INDENT>print('<STR_LIT:\t>' '<STR_LIT>' %(shot['<STR_LIT>'], shot.get('<STR_LIT>', None) or '<STR_LIT:->',<EOL>shot.azm, shot.inc, shot.length), file=outfile)<EOL><DEDENT>print('<STR_LIT>', file=outfile)<EOL><DEDENT>print('<STR_LIT>' % outfilename)<EOL><DEDENT>
Main function which converts a PocketTopo .TXT file to a Compass .DAT file
f14122:m1
def thconfig(txtfiles, cavename='<STR_LIT>'):
fmts_model = ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>']<EOL>outfilename = '<STR_LIT>'<EOL>with open(outfilename, '<STR_LIT:w>') as outfile:<EOL><INDENT>for txtfilename in txtfiles:<EOL><INDENT>print('<STR_LIT>' % convert_filename(txtfilename), file=outfile)<EOL><DEDENT>print(file=outfile)<EOL>for fmt in fmts_model:<EOL><INDENT>print('<STR_LIT>' % os.path.join('<STR_LIT>', '<STR_LIT>' % (cavename, fmt)), file=outfile)<EOL><DEDENT>print('<STR_LIT>' % os.path.join('<STR_LIT>', '<STR_LIT>'), file=outfile)<EOL>print('<STR_LIT>' % outfilename)<EOL><DEDENT>
Write `thconfig` file for the Therion project
f14122:m2
def plt2xyz(fname):
parser = CompassPltParser(fname)<EOL>plt = parser.parse()<EOL>for segment in plt:<EOL><INDENT>for command in segment:<EOL><INDENT>if command.cmd == '<STR_LIT:d>':<EOL><INDENT>if plt.utm_zone:<EOL><INDENT>x, y, z = command.x * FT_TO_M, command.y * FT_TO_M, command.z * FT_TO_M<EOL><DEDENT>else:<EOL><INDENT>x, y, z = command.x, command.y, command.z<EOL><DEDENT>print('<STR_LIT>' % (x, y, z))<EOL><DEDENT><DEDENT><DEDENT>
Convert a Compass plot file to XYZ pointcloud
f14125:m0
def set_bounds(self, ymin, ymax, xmin, xmax, zmin, zmax):
self.xmin, self.xmax = xmin, xmax<EOL>self.ymin, self.ymax = ymin, ymax<EOL>self.zmin, self.zmax = zmin, zmax<EOL>
Set Y,X,Z bounds for the segment.
f14128:c3:m1
def add_command(self, command):
self.commands.append(command)<EOL>
Add a :class:`Command` to :attr:`commands`.
f14128:c3:m2
def set_bounds(self, ymin, ymax, xmin, xmax, zmin, zmax, edist=None):
self.ymin, self.ymax = ymin, ymax<EOL>self.xmin, self.xmax = xmin, xmax<EOL>self.zmin, self.zmax = zmin, zmax<EOL>self.edist = None<EOL>
Set Y,X,Z bounds for the plot.
f14128:c4:m1
def add_segment(self, segment):
self.segments.append(segment)<EOL>
Add a :class:`Segment` to :attr:`segments`.
f14128:c4:m2
def add_fixed_point(self, name, coordinate):
self.fixed_points[name] = coordinate<EOL>
Add a (Y, X, Z) tuple to :attr:`fixed_points`.
f14128:c4:m3
def add_loop(self, n, common_sta, from_sta, to_sta, stations):
self.loops.append((n, common_sta, from_sta, to_sta, stations))<EOL>
Add a loop tuple to :attr:`loops`.
f14128:c4:m4
def __init__(self, pltfilename, strict_mode=False):
self.pltfilename = pltfilename<EOL>self.strict_mode = strict_mode<EOL>
:param pltfilename: string filename
f14128:c5:m0
def parse(self):
plt = Plot(name_from_filename(self.pltfilename))<EOL>with open(self.pltfilename, '<STR_LIT:rb>') as pltfile:<EOL><INDENT>segment = None<EOL>for line in pltfile:<EOL><INDENT>if not line:<EOL><INDENT>continue<EOL><DEDENT>c, val = line[:<NUM_LIT:1>], line[<NUM_LIT:1>:]<EOL>if c == '<STR_LIT>':<EOL><INDENT>edist = None<EOL>try:<EOL><INDENT>ymin, ymax, xmin, xmax, zmin, zmax = (float(v) for v in val.split())<EOL><DEDENT>except ValueError:<EOL><INDENT>ymin, ymax, xmin, xmax, zmin, zmax, _, edist = val.split()<EOL>ymin, ymax, xmin, xmax, zmin, zmax, edist =(float(v) for v in (ymin, ymax, xmin, xmax, zmin, zmax, edist))<EOL><DEDENT>plt.set_bounds(ymin, ymax, xmin, xmax, zmin, zmax, edist)<EOL><DEDENT>elif c == '<STR_LIT:S>':<EOL><INDENT>if not plt.name:<EOL><INDENT>plt.name = val.strip()<EOL><DEDENT><DEDENT>elif c == '<STR_LIT>':<EOL><INDENT>plt.utm_zone = int(val)<EOL><DEDENT>elif c == '<STR_LIT:O>':<EOL><INDENT>plt.datum = val<EOL><DEDENT>elif c == '<STR_LIT:N>':<EOL><INDENT>date, comment = None, '<STR_LIT>' <EOL>try:<EOL><INDENT>name, _, m, d, y, comment = val.split(None, <NUM_LIT:5>)<EOL>date = datetime.date(int(y), int(m), int(d))<EOL><DEDENT>except ValueError:<EOL><INDENT>try:<EOL><INDENT>name, _, m, d, y = val.split()<EOL>date = datetime.date(int(y), int(m), int(d))<EOL><DEDENT>except ValueError:<EOL><INDENT>name = val<EOL><DEDENT><DEDENT>comment = comment[<NUM_LIT:1>:].strip()<EOL>segment = Segment(name, date, comment)<EOL><DEDENT>elif c == '<STR_LIT:M>':<EOL><INDENT>flags = None <EOL>try:<EOL><INDENT>y, x, z, name, _, l, u, d, r, _, edist = val.split()<EOL><DEDENT>except ValueError:<EOL><INDENT>y, x, z, name, _, l, u, d, r, _, edist, flags = val.split()<EOL><DEDENT>cmd = MoveCommand(float(y), float(x), float(z), name[<NUM_LIT:1>:],<EOL>float(l), float(r), float(u), float(d), float(edist), flags)<EOL>segment.add_command(cmd)<EOL><DEDENT>elif c in ('<STR_LIT:D>', '<STR_LIT:d>'):<EOL><INDENT>flags = None<EOL>try:<EOL><INDENT>y, x, z, name, _, l, u, d, r, _, edist = val.split()<EOL><DEDENT>except ValueError:<EOL><INDENT>y, x, z, name, _, l, u, d, r, _, edist, flags = val.split()<EOL><DEDENT>cmd = DrawCommand(float(y), float(x), float(z), name[<NUM_LIT:1>:],<EOL>float(l), float(r), float(u), float(d), float(edist), flags)<EOL>cmd.cmd = c<EOL>segment.add_command(cmd)<EOL><DEDENT>elif c == '<STR_LIT:X>':<EOL><INDENT>segment.set_bounds(*(float(v) for v in val.split()))<EOL>plt.add_segment(segment)<EOL>segment = None<EOL><DEDENT>elif c == '<STR_LIT:P>':<EOL><INDENT>name, y, x, z = val.split()<EOL>plt.add_fixed_point(name, (float(y), float(x), float(z)))<EOL><DEDENT>elif c == '<STR_LIT:C>':<EOL><INDENT>plt.loop_count = int(val)<EOL><DEDENT>elif c == '<STR_LIT:R>':<EOL><INDENT>count, common, from_sta, to_sta, stations = val.split(None, <NUM_LIT:4>)<EOL>plt.add_loop(int(count), common, from_sta, to_sta, stations.split())<EOL><DEDENT>elif c == '<STR_LIT>':<EOL><INDENT>continue <EOL><DEDENT>else:<EOL><INDENT>msg = "<STR_LIT>" % (c, val)<EOL>if self.strict_mode:<EOL><INDENT>raise ParseException(msg)<EOL><DEDENT>else:<EOL><INDENT>log.warning(msg)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>return plt<EOL>
Parse our .PLT file and return :class:`Plot` object or raise :exc:`ParseException`.
f14128:c5:m1
def __init__(self, *args, **kwargs):
self.declination = kwargs.pop('<STR_LIT>', <NUM_LIT:0.0>)<EOL>OrderedDict.__init__(self, *args, **kwargs)<EOL>
:kwarg FROM: (str) from station :kwarg TO: (str) to station :kwarg BEARING: (float) forward compass in **decimal degrees** :kwarg AZM2: (float) back compass in **decimal degrees** :kwarg INC: (float) forward inclination in **decimal degrees** :kwarg INC2: (float) back inclination in **decimal degrees** :kwarg LENGTH: (float) distance in **decimal feet** :kwarg FLAGS: (collection of :class:`Exclude`) shot exclusion flags :kwarg COMMENTS: (str) text comments, up to 80 characters long :kwarg declination: (float) magnetic declination in decimal degrees :ivar declination: (float) set or get magnetic declination adjustment
f14129:c1:m0
@property<EOL><INDENT>def azm(self):<DEDENT>
azm1 = self.get('<STR_LIT>', None)<EOL>azm2 = self.get('<STR_LIT>', None)<EOL>if azm1 is None and azm2 is None:<EOL><INDENT>return None<EOL><DEDENT>if azm2 is None:<EOL><INDENT>return azm1 + self.declination<EOL><DEDENT>if azm1 is None:<EOL><INDENT>return (azm2 + <NUM_LIT>) % <NUM_LIT> + self.declination<EOL><DEDENT>return (azm1 + (azm2 + <NUM_LIT>) % <NUM_LIT>) / <NUM_LIT> + self.declination<EOL>
Corrected azimuth, taking into account backsight, declination, and compass corrections.
f14129:c1:m1
@property<EOL><INDENT>def inc(self):<DEDENT>
inc1 = self.get('<STR_LIT>', None)<EOL>inc2 = self.get('<STR_LIT>', None)<EOL>if inc1 is None and inc2 is None:<EOL><INDENT>return None<EOL><DEDENT>if inc2 is None:<EOL><INDENT>return inc1<EOL><DEDENT>if inc1 is None:<EOL><INDENT>return -<NUM_LIT:1> * inc2<EOL><DEDENT>return (inc1 - inc2) / <NUM_LIT><EOL>
Corrected inclination, taking into account backsight and clino corrections.
f14129:c1:m2
@property<EOL><INDENT>def flags(self):<DEDENT>
return set(self.get('<STR_LIT>', '<STR_LIT>'))<EOL>
Shot exclusion flags as a `set`
f14129:c1:m3
@property<EOL><INDENT>def length(self):<DEDENT>
return self.get('<STR_LIT>', None)<EOL>
Corrected distance, taking into account tape correction.
f14129:c1:m4
def add_shot(self, shot):
shot.declination = self.declination<EOL>self.shots.append(shot)<EOL>
Add a shot dictionary to :attr:`shots`, applying this survey's magnetic declination
f14129:c2:m3
@property<EOL><INDENT>def length(self):<DEDENT>
return sum([shot.length for shot in self.shots])<EOL>
Total surveyed length, regardless of exclusion flags.
f14129:c2:m4
@property<EOL><INDENT>def included_length(self):<DEDENT>
return sum([shot.length for shot in self.shots if shot.is_included])<EOL>
Surveyed length, not including "excluded" shots
f14129:c2:m5
@property<EOL><INDENT>def excluded_length(self):<DEDENT>
return sum([shot.length for shot in self.shots if Exclude.LENGTH in shot.flags or Exclude.TOTAL in shot.flags])<EOL>
Surveyed length which does not count toward the included total
f14129:c2:m6
def add_survey(self, survey):
self.surveys.append(survey)<EOL>
Add a :class:`Survey` to :attr:`surveys`.
f14129:c3:m1
@property<EOL><INDENT>def length(self):<DEDENT>
return sum([survey.length for survey in self.surveys])<EOL>
Total surveyed length.
f14129:c3:m2
@property<EOL><INDENT>def included_length(self):<DEDENT>
return sum([survey.included_length for survey in self.surveys])<EOL>
Surveyed length, not including "excluded" shots
f14129:c3:m3
@property<EOL><INDENT>def excluded_length(self):<DEDENT>
return sum([survey.excluded_length for survey in self.surveys])<EOL>
Surveyed length which does not count toward the included total
f14129:c3:m4
@staticmethod<EOL><INDENT>def read(fname):<DEDENT>
return CompassDatParser(fname).parse()<EOL>
Read a .DAT file and produce a `Survey`
f14129:c3:m9
def write(self, outfname=None):
outfname = outfname or self.filename<EOL>with codecs.open(outfname, '<STR_LIT:wb>', '<STR_LIT>') as outf:<EOL><INDENT>for survey in self.surveys:<EOL><INDENT>outf.write('<STR_LIT:\r\n>'.join(survey._serialize()))<EOL>outf.write('<STR_LIT:\r\n>'+'<STR_LIT>'+'<STR_LIT:\r\n>') <EOL><DEDENT>outf.write('<STR_LIT>')<EOL><DEDENT>
Write or overwrite a `Survey` to the specified .DAT file
f14129:c3:m10
def set_base_location(self, location):
self.base_location = location<EOL>self._utm_zone = location.zone<EOL>self._utm_datum = location.datum<EOL>self._utm_convergence = location.convergence<EOL>
Configure the project's base location
f14129:c6:m1
def add_linked_file(self, datfile):
self.linked_files.append(datfile)<EOL>
Add a :class:`DatFile` to :attr:`linked_files`.
f14129:c6:m2
def add_linked_station(self, datfile, station, location=None):
if datfile not in self.fixed_stations:<EOL><INDENT>self.fixed_stations[datfile] = {station: location}<EOL><DEDENT>else:<EOL><INDENT>self.fixed_stations[datfile][station] = location<EOL><DEDENT>if location and not self.base_location:<EOL><INDENT>self._utm_zone = location.zone<EOL>self._utm_datum = location.datum<EOL>self._utm_convergence = location.convergence<EOL><DEDENT>
Add a linked or fixed station
f14129:c6:m3
@staticmethod<EOL><INDENT>def read(fname):<DEDENT>
return CompassProjectParser(fname).parse()<EOL>
Read a .MAK file and produce a `Project`
f14129:c6:m7
def write(self, outfilename=None):
outfilename = outfilename or self.filename<EOL>if not outfilename:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>with codecs.open(outfilename, '<STR_LIT:wb>', '<STR_LIT>') as outf:<EOL><INDENT>outf.write('<STR_LIT:\r\n>'.join(self._serialize()))<EOL><DEDENT>
Write or overwrite this .MAK file
f14129:c6:m9
def __init__(self, survey_str):
self.survey_str = survey_str<EOL>
:param survey_str: string multiline representation of survey as found in .DAT file
f14129:c8:m0
def parse(self):
if not self.survey_str:<EOL><INDENT>return None<EOL><DEDENT>lines = self.survey_str.splitlines()<EOL>if len(lines) < <NUM_LIT:10>:<EOL><INDENT>raise ParseException("<STR_LIT>" % (len(lines), lines))<EOL><DEDENT>first_line = lines.pop(<NUM_LIT:0>).strip()<EOL>if first_line.startswith('<STR_LIT>'):<EOL><INDENT>cave_name = '<STR_LIT>'<EOL>name = first_line.strip('<STR_LIT>').strip()<EOL><DEDENT>else:<EOL><INDENT>cave_name = first_line<EOL>name = lines.pop(<NUM_LIT:0>).split('<STR_LIT>', <NUM_LIT:1>)[<NUM_LIT:1>].strip()<EOL><DEDENT>date_comment_toks = lines.pop(<NUM_LIT:0>).split('<STR_LIT>', <NUM_LIT:1>)[<NUM_LIT:1>].split('<STR_LIT>')<EOL>date = CompassSurveyParser._parse_date(date_comment_toks[<NUM_LIT:0>])<EOL>comment = date_comment_toks[<NUM_LIT:1>].strip() if len(date_comment_toks) > <NUM_LIT:1> else '<STR_LIT>'<EOL>lines.pop(<NUM_LIT:0>) <EOL>team = [member.strip() for member in lines.pop(<NUM_LIT:0>).split('<STR_LIT:U+002C>')] <EOL>dec_fmt_corr = lines.pop(<NUM_LIT:0>)<EOL>declination, fmt, corrections, corrections2 = CompassSurveyParser._parse_declination_line(dec_fmt_corr)<EOL>lines.pop(<NUM_LIT:0>)<EOL>shot_header = lines.pop(<NUM_LIT:0>).split()<EOL>val_count = len(shot_header) - <NUM_LIT:2> if '<STR_LIT>' in shot_header else len(shot_header) <EOL>lines.pop(<NUM_LIT:0>)<EOL>survey = Survey(name=name, date=date, comment=comment, team=team, cave_name=cave_name,<EOL>shot_header=shot_header, declination=declination,<EOL>file_format=fmt, corrections=corrections, corrections2=corrections2)<EOL>shots = []<EOL>shot_lines = lines<EOL>for shot_line in shot_lines:<EOL><INDENT>shot_vals = shot_line.split(None, val_count)<EOL>if len(shot_vals) > val_count: <EOL><INDENT>flags_comment = shot_vals.pop()<EOL>if not flags_comment.startswith('<STR_LIT>'):<EOL><INDENT>flags, comment = '<STR_LIT>', flags_comment<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>flags, comment = flags_comment.split('<STR_LIT>', <NUM_LIT:1>)[<NUM_LIT:1>].split('<STR_LIT:#>', <NUM_LIT:1>)<EOL><DEDENT>except ValueError:<EOL><INDENT>raise ParseException('<STR_LIT>' % (name, flags_comment)) <EOL><DEDENT><DEDENT>shot_vals += [flags, comment.strip()]<EOL><DEDENT>shot_vals = [(header, self._coerce(header, val)) for (header, val) in zip(shot_header, shot_vals)]<EOL>shot = Shot(shot_vals)<EOL>survey.add_shot(shot)<EOL><DEDENT>return survey<EOL>
Parse our string and return a Survey object, None, or raise :exc:`ParseException`
f14129:c8:m4
def __init__(self, datfilename):
self.datfilename = datfilename<EOL>
:param datfilename: (string) filename
f14129:c9:m0
def parse(self):
log.debug("<STR_LIT>", self.datfilename)<EOL>datobj = DatFile(name_from_filename(self.datfilename), filename=self.datfilename)<EOL>with codecs.open(self.datfilename, '<STR_LIT:rb>', '<STR_LIT>') as datfile:<EOL><INDENT>full_contents = datfile.read()<EOL>survey_strs = [survey_str.strip() for survey_str in full_contents.split('<STR_LIT>')]<EOL>if survey_strs[-<NUM_LIT:1>] == '<STR_LIT>':<EOL><INDENT>survey_strs.pop() <EOL><DEDENT>log.debug("<STR_LIT>", len(survey_strs), self.datfilename)<EOL>for survey_str in survey_strs:<EOL><INDENT>if not survey_str:<EOL><INDENT>continue<EOL><DEDENT>survey = CompassSurveyParser(survey_str).parse()<EOL>datobj.add_survey(survey)<EOL><DEDENT><DEDENT>return datobj<EOL>
Parse our data file and return a :class:`DatFile` or raise :exc:`ParseException`.
f14129:c9:m1
def __init__(self, projectfile):
self.makfilename = projectfile<EOL>
:param projectfile: (string) filename
f14129:c10:m0
def parse(self):
log.debug("<STR_LIT>", self.makfilename)<EOL>base_location = None<EOL>linked_files = []<EOL>file_params = set()<EOL>def parse_linked_file(value):<EOL><INDENT>log.debug("<STR_LIT>", value)<EOL>value = value.rstrip('<STR_LIT:;>')<EOL>toks = value.split('<STR_LIT:U+002C>', <NUM_LIT:1>)<EOL>if len(toks) == <NUM_LIT:1>:<EOL><INDENT>return toks[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>return toks[<NUM_LIT:0>] <EOL><DEDENT><DEDENT>with codecs.open(self.makfilename, '<STR_LIT:rb>', '<STR_LIT>') as makfile:<EOL><INDENT>prev = None<EOL>for line in makfile:<EOL><INDENT>line = line.strip()<EOL>if not line:<EOL><INDENT>continue<EOL><DEDENT>header, value = line[<NUM_LIT:0>], line[<NUM_LIT:1>:]<EOL>if prev:<EOL><INDENT>if line.endswith('<STR_LIT:;>'):<EOL><INDENT>linked_file = parse_linked_file(prev + line.rstrip('<STR_LIT:;>'))<EOL>linked_files.append(linked_file)<EOL>prev = None<EOL><DEDENT>else:<EOL><INDENT>prev += value<EOL><DEDENT>continue<EOL><DEDENT>if header == '<STR_LIT:/>':<EOL><INDENT>pass <EOL><DEDENT>elif header == '<STR_LIT:@>':<EOL><INDENT>value = value.rstrip('<STR_LIT:;>')<EOL>base_location = UTMLocation(*(float(v) for v in value.split('<STR_LIT:U+002C>')))<EOL><DEDENT>elif header == '<STR_LIT:&>':<EOL><INDENT>value = value.rstrip('<STR_LIT:;>')<EOL>base_location.datum = value<EOL><DEDENT>elif header == '<STR_LIT:%>':<EOL><INDENT>value = value.rstrip('<STR_LIT:;>')<EOL>base_location.convergence = float(value)<EOL><DEDENT>elif header == '<STR_LIT:!>':<EOL><INDENT>value = value.rstrip('<STR_LIT:;>')<EOL><DEDENT>elif header == '<STR_LIT:#>':<EOL><INDENT>if value.endswith('<STR_LIT:;>'):<EOL><INDENT>linked_files.append(parse_linked_file(value))<EOL>prev = None<EOL><DEDENT>else:<EOL><INDENT>prev = value<EOL><DEDENT><DEDENT><DEDENT>log.debug("<STR_LIT>", base_location, linked_files)<EOL>project = Project(name_from_filename(self.makfilename), filename=self.makfilename)<EOL>project.set_base_location(base_location)<EOL>for linked_file in linked_files:<EOL><INDENT>linked_file_path = os.path.join(os.path.dirname(self.makfilename), os.path.normpath(linked_file.replace('<STR_LIT:\\>', '<STR_LIT:/>')))<EOL>datfile = CompassDatParser(linked_file_path).parse()<EOL>project.add_linked_file(datfile)<EOL><DEDENT>return project<EOL><DEDENT>
Parse our project file and return :class:`Project` object or raise :exc:`ParseException`.
f14129:c10:m1
@property<EOL><INDENT>def azm(self):<DEDENT>
return self.get('<STR_LIT>', -<NUM_LIT:0.0>) + self.declination<EOL>
Corrected azimuth, taking into account declination.
f14130:c0:m1
@property<EOL><INDENT>def inc(self):<DEDENT>
return self.get('<STR_LIT>', -<NUM_LIT:0.0>)<EOL>
Corrected inclination.
f14130:c0:m2
@property<EOL><INDENT>def length(self):<DEDENT>
return self.get('<STR_LIT>', -<NUM_LIT:0.0>)<EOL>
Corrected distance.
f14130:c0:m3
@property<EOL><INDENT>def is_splay(self):<DEDENT>
return self.get('<STR_LIT>', None) in (None, '<STR_LIT>')<EOL>
Is this shot a "splay shot"?
f14130:c0:m4
def add_shot(self, shot):
shot.declination = self.declination<EOL>if shot.is_splay:<EOL><INDENT>self.splays[shot['<STR_LIT>']].append(shot)<EOL><DEDENT>self.shots.append(shot)<EOL>
Add a Shot to :attr:`shots`, applying our survey's :attr:`declination` to it.
f14130:c1:m1
@property<EOL><INDENT>def length(self):<DEDENT>
return sum([shot.length for shot in self.shots if not shot.is_splay])<EOL>
Total surveyed cave length, not including splays.
f14130:c1:m2
@property<EOL><INDENT>def total_length(self):<DEDENT>
return sum([shot.length for shot in self.shots])<EOL>
Total surveyed length including splays.
f14130:c1:m3
def _inverse_azm(self, azm):
return (azm + self.angle_units/<NUM_LIT:2>) % self.angle_units<EOL>
Convert forward AZM to back AZM and vice versa
f14130:c2:m0
def _inverse_inc(self, inc):
return -<NUM_LIT:1> * inc<EOL>
Convert forward INC to back INC and vice versa
f14130:c2:m1
def add_shot(self, shot):
if not self.shots or not shot.get('<STR_LIT>', None) or not self.shots[-<NUM_LIT:1>].get('<STR_LIT>', None):<EOL><INDENT>return super(MergingSurvey, self).add_shot(shot)<EOL><DEDENT>from_, to = shot['<STR_LIT>'], shot['<STR_LIT>']<EOL>prev_shot = self.shots[-<NUM_LIT:1>]<EOL>prev_from, prev_to = prev_shot['<STR_LIT>'], prev_shot['<STR_LIT>']<EOL>if from_ == prev_from and to == prev_to:<EOL><INDENT>total_count = prev_shot.dupe_count + <NUM_LIT:1><EOL>log.debug('<STR_LIT>', total_count, prev_shot, shot)<EOL>if abs(shot['<STR_LIT>'] - prev_shot['<STR_LIT>']) > <NUM_LIT>:<EOL><INDENT>log.warning('<STR_LIT>', abs(shot['<STR_LIT>'] - prev_shot['<STR_LIT>']), prev_shot, shot)<EOL><DEDENT>if abs(shot['<STR_LIT>'] - prev_shot['<STR_LIT>']) > <NUM_LIT>:<EOL><INDENT>log.warning('<STR_LIT>', abs(shot['<STR_LIT>'] - prev_shot['<STR_LIT>']), prev_shot, shot)<EOL><DEDENT>if abs(shot['<STR_LIT>'] - prev_shot['<STR_LIT>']) > <NUM_LIT:1.0>:<EOL><INDENT>log.warning('<STR_LIT>', abs(shot['<STR_LIT>'] - prev_shot['<STR_LIT>']), prev_shot, shot)<EOL><DEDENT>avg_length = (prev_shot['<STR_LIT>'] * prev_shot.dupe_count + shot['<STR_LIT>']) / total_count<EOL>avg_azm = (prev_shot['<STR_LIT>'] * prev_shot.dupe_count + shot['<STR_LIT>']) / total_count<EOL>avg_inc = (prev_shot['<STR_LIT>'] * prev_shot.dupe_count + shot['<STR_LIT>']) / total_count<EOL>merged_comments = ('<STR_LIT>' % (prev_shot.get('<STR_LIT>', '<STR_LIT>') or '<STR_LIT>', shot.get('<STR_LIT>', '<STR_LIT>') or '<STR_LIT>')).strip() or None<EOL>prev_shot['<STR_LIT>'], prev_shot['<STR_LIT>'], prev_shot['<STR_LIT>'], prev_shot['<STR_LIT>'] = avg_length, avg_azm, avg_inc, merged_comments<EOL>prev_shot.dupe_count += <NUM_LIT:1><EOL><DEDENT>elif from_ == prev_to and to == prev_from:<EOL><INDENT>total_count = prev_shot.dupe_count + <NUM_LIT:1><EOL>inv_azm, inv_inc = self._inverse_azm(shot['<STR_LIT>']), self._inverse_inc(shot['<STR_LIT>'])<EOL>log.debug('<STR_LIT>', total_count, prev_shot, shot)<EOL>if abs(inv_azm - prev_shot['<STR_LIT>']) > <NUM_LIT>:<EOL><INDENT>log.warning('<STR_LIT>', abs(inv_azm - prev_shot['<STR_LIT>']), prev_shot, shot)<EOL><DEDENT>if abs(inv_inc - prev_shot['<STR_LIT>']) > <NUM_LIT>:<EOL><INDENT>log.warning('<STR_LIT>', abs(inv_inc - prev_shot['<STR_LIT>']), prev_shot, shot)<EOL><DEDENT>if abs(shot['<STR_LIT>'] - prev_shot['<STR_LIT>']) > <NUM_LIT:1.0>:<EOL><INDENT>log.warning('<STR_LIT>', abs(shot['<STR_LIT>'] - prev_shot['<STR_LIT>']), prev_shot, shot)<EOL><DEDENT>avg_length = (prev_shot['<STR_LIT>'] * prev_shot.dupe_count + shot['<STR_LIT>']) / total_count<EOL>avg_azm = (prev_shot['<STR_LIT>'] * prev_shot.dupe_count + inv_azm) / total_count<EOL>avg_inc = (prev_shot['<STR_LIT>'] * prev_shot.dupe_count + inv_inc) / total_count<EOL>merged_comments = ('<STR_LIT>' % (prev_shot.get('<STR_LIT>', '<STR_LIT>') or '<STR_LIT>', shot.get('<STR_LIT>', '<STR_LIT>') or '<STR_LIT>')).strip() or None<EOL>prev_shot['<STR_LIT>'], prev_shot['<STR_LIT>'], prev_shot['<STR_LIT>'], prev_shot['<STR_LIT>'] = avg_length, avg_azm, avg_inc, merged_comments<EOL>prev_shot.dupe_count += <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>return super(MergingSurvey, self).add_shot(shot)<EOL><DEDENT>
Add a shot dictionary to :attr:`shots`, applying our survey's :attr:`declination`, and optionally averaging and merging with duplicate previous shot.
f14130:c2:m2
def add_survey(self, survey):
survey.length_units = self.length_units<EOL>survey.angle_units = self.angle_units<EOL>self.surveys.append(survey)<EOL>
Add a :class:`Survey` to :attr:`surveys`.
f14130:c4:m1
def add_reference_point(self, station, utm_location):
self.reference_points[station] = utm_location<EOL>
Add a :class:`UTMLocation` to :attr:`reference_points`.
f14130:c4:m2
@property<EOL><INDENT>def length(self):<DEDENT>
return sum([survey.length for survey in self.surveys])<EOL>
Total surveyed length.
f14130:c4:m3
@staticmethod<EOL><INDENT>def read(fname, merge_duplicate_shots=False, encoding='<STR_LIT>'):<DEDENT>
return PocketTopoTxtParser(fname, merge_duplicate_shots, encoding).parse()<EOL>
Read a PocketTopo .TXT file and produce a `TxtFile` object which represents it
f14130:c4:m8
def parse(self):
log.debug('<STR_LIT>', self.txtfilename)<EOL>SurveyClass = MergingSurvey if self.merge_duplicate_shots else Survey<EOL>txtobj = None<EOL>with codecs.open(self.txtfilename, '<STR_LIT:rb>', self.encoding) as txtfile:<EOL><INDENT>lines = txtfile.read().splitlines()<EOL>first_line_re = re.compile(r'<STR_LIT>')<EOL>first_line = lines.pop(<NUM_LIT:0>)<EOL>cave_name, length_units, angle_units = first_line_re.search(first_line).groups()<EOL>cave_name, angle_units = cave_name.strip(), int(angle_units)<EOL>txtobj = TxtFile(cave_name, length_units, angle_units)<EOL>while not lines[<NUM_LIT:0>]:<EOL><INDENT>lines.pop(<NUM_LIT:0>) <EOL><DEDENT>while lines[<NUM_LIT:0>].startswith('<STR_LIT:[>'):<EOL><INDENT>toks = lines.pop(<NUM_LIT:0>).split(None, <NUM_LIT:3>)<EOL>id, date, declination = toks[:<NUM_LIT:3>]<EOL>id = id.strip('<STR_LIT>')<EOL>date = datetime.strptime(date, '<STR_LIT>').date()<EOL>declination = float(declination)<EOL>comment = toks[<NUM_LIT:3>].strip('<STR_LIT:">') if len(toks) == <NUM_LIT:4> else '<STR_LIT>'<EOL>survey = SurveyClass(id, date, comment, declination, cave_name)<EOL>txtobj.add_survey(survey)<EOL><DEDENT>while not lines[<NUM_LIT:0>]:<EOL><INDENT>lines.pop(<NUM_LIT:0>) <EOL><DEDENT>while lines:<EOL><INDENT>line = lines.pop(<NUM_LIT:0>).strip()<EOL>if not line:<EOL><INDENT>continue<EOL><DEDENT>if '<STR_LIT:">' in line:<EOL><INDENT>line, comment = line.split('<STR_LIT:">', <NUM_LIT:1>)<EOL>comment = comment.rstrip('<STR_LIT:">')<EOL><DEDENT>else:<EOL><INDENT>comment = None<EOL><DEDENT>if '<STR_LIT:[>' not in line:<EOL><INDENT>toks = line.split()<EOL>if len(toks) != <NUM_LIT:4>: <EOL><INDENT>log.debug('<STR_LIT>', line, '<STR_LIT>' % comment if comment else '<STR_LIT>')<EOL>continue<EOL><DEDENT>station, vals = toks[<NUM_LIT:0>], list(map(float, toks[<NUM_LIT:1>:]))<EOL>if vals[<NUM_LIT:0>] == <NUM_LIT:0.0>: <EOL><INDENT>log.debug('<STR_LIT>', line, '<STR_LIT>' % comment if comment else '<STR_LIT>')<EOL><DEDENT>else: <EOL><INDENT>easting, northing, altitude = vals<EOL>reference_point = UTMLocation(easting, northing, altitude, comment)<EOL>log.debug('<STR_LIT>', reference_point)<EOL>txtobj.add_reference_point(station, reference_point)<EOL><DEDENT>continue<EOL><DEDENT>line, survey_id = line.split('<STR_LIT:[>')<EOL>survey_id = survey_id.rstrip().rstrip('<STR_LIT:]>')<EOL>toks = line.split()<EOL>from_to, (length, azm, inc) = toks[:-<NUM_LIT:3>], (float(tok) for tok in toks[-<NUM_LIT:3>:])<EOL>if len(from_to) == <NUM_LIT:2>:<EOL><INDENT>from_, to = tuple(from_to) <EOL><DEDENT>elif len(from_to) == <NUM_LIT:1>:<EOL><INDENT>from_, to = from_to[<NUM_LIT:0>], None <EOL><DEDENT>elif not from_to and length == <NUM_LIT:0.0>:<EOL><INDENT>continue <EOL><DEDENT>else:<EOL><INDENT>raise Exception()<EOL><DEDENT>shot = Shot([('<STR_LIT>',from_), ('<STR_LIT>',to), ('<STR_LIT>',length), ('<STR_LIT>',azm), ('<STR_LIT>',inc), ('<STR_LIT>',comment)])<EOL>txtobj[survey_id].add_shot(shot)<EOL><DEDENT><DEDENT>return txtobj<EOL>
Produce a `TxtFile` object from the .TXT file
f14130:c5:m1
def m2ft(m):
return m * <NUM_LIT><EOL>
Convert meters to feet
f14131:m0
def ft2m(ft):
return ft * <NUM_LIT><EOL>
Convert feet to meters
f14131:m1
def hd(inc, sd):
return sd * math.cos(math.radians(inc))<EOL>
Calculate horizontal distance. :param inc: (float) inclination angle in degrees :param sd: (float) slope distance in any units
f14131:m2
def vd(inc, sd):
return abs(sd * math.sin(math.radians(inc)))<EOL>
Calculate vertical distance. :param inc: (float) inclination angle in degrees :param sd: (float) slope distance in any units
f14131:m3
def cartesian_offset(azm, inc, sd, origin=(<NUM_LIT:0>, <NUM_LIT:0>)):
hd = sd * math.cos(math.radians(inc))<EOL>x = hd * math.sin(math.radians(azm))<EOL>y = hd * math.cos(math.radians(azm))<EOL>return (x, y) if not origin else (x+origin[<NUM_LIT:0>], y+origin[<NUM_LIT:1>])<EOL>
Calculate the (X, Y) cartesian coordinate offset. :param azm: (float) azimuth angle in degrees :param inc: (float) inclination angle in degrees :param sd: (float) slope distance in any units :param origin: (tuple(float, float)) optional origin coordinate
f14131:m4
def angle_delta(a1, a2):
return <NUM_LIT> - abs(abs(a1 - a2) - <NUM_LIT>)<EOL>
Calculate the absolute difference between two angles in degrees :param a1: (float) angle in degrees :param a2: (float) angle in degrees
f14131:m5
def skip(app, what, name, obj, skip, options):
if name == '<STR_LIT>' and obj.__doc__:<EOL><INDENT>return False<EOL><DEDENT>return skip<EOL>
Custom skip function which includes `__init__` in autodocumentation. See: http://stackoverflow.com/a/5599712
f14133:m0
def get_decorators(self, node):
if node.parent is None:<EOL><INDENT>return []<EOL><DEDENT>results = {}<EOL>if not self.decorated.match(node.parent, results):<EOL><INDENT>return []<EOL><DEDENT>decorators = results.get('<STR_LIT>') or [results['<STR_LIT:d>']]<EOL>decs = []<EOL>for d in decorators:<EOL><INDENT>for child in d.children:<EOL><INDENT>if isinstance(child, Leaf) and child.type == token.NAME:<EOL><INDENT>decs.append(child.value)<EOL><DEDENT><DEDENT><DEDENT>return decs<EOL>
Return a list of decorators found on a function definition. This is a list of strings; only simple decorators (e.g. @staticmethod) are returned. If the function is undecorated or only non-simple decorators are found, return [].
f14134:c0:m6
def is_method(self, node):
node = node.parent<EOL>while node is not None:<EOL><INDENT>if node.type == syms.classdef:<EOL><INDENT>return True<EOL><DEDENT>if node.type == syms.funcdef:<EOL><INDENT>return False<EOL><DEDENT>node = node.parent<EOL><DEDENT>return False<EOL>
Return whether the node occurs (directly) inside a class.
f14134:c0:m7
def has_return_exprs(self, node):
results = {}<EOL>if self.return_expr.match(node, results):<EOL><INDENT>return True<EOL><DEDENT>for child in node.children:<EOL><INDENT>if child.type not in (syms.funcdef, syms.classdef):<EOL><INDENT>if self.has_return_exprs(child):<EOL><INDENT>return True<EOL><DEDENT><DEDENT><DEDENT>return False<EOL>
Traverse the tree below node looking for 'return expr'. Return True if at least 'return expr' is found, False if not. (If both 'return' and 'return expr' are found, return True.)
f14134:c0:m8
def is_generator(self, node):
results = {}<EOL>if self.yield_expr.match(node, results):<EOL><INDENT>return True<EOL><DEDENT>for child in node.children:<EOL><INDENT>if child.type not in (syms.funcdef, syms.classdef):<EOL><INDENT>if self.is_generator(child):<EOL><INDENT>return True<EOL><DEDENT><DEDENT><DEDENT>return False<EOL>
Traverse the tree below node looking for 'yield [expr]'.
f14134:c0:m9