def load(self, filename, known_frames=None, translate=True, v2_version=<NUM_LIT:4>):

if not v2_version in (<NUM_LIT:3>, <NUM_LIT:4>):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>from os.path import getsize<EOL>self.filename = filename<EOL>self.__known_frames = known_frames<EOL>self._fileobj = open(filename, '<STR_LIT:rb>')<EOL>self.__filesize = getsize(filename)<EOL>try:<EOL><INDENT>try:<EOL><INDENT>self._load_header()<EOL><DEDENT>except EOFError:<EOL><INDENT>self.size = <NUM_LIT:0><EOL>raise ID3NoHeaderError("<STR_LIT>" % (<EOL>filename, self.__filesize))<EOL><DEDENT>except (ID3NoHeaderError, ID3UnsupportedVersionError) as err:<EOL><INDENT>self.size = <NUM_LIT:0><EOL>import sys<EOL>stack = sys.exc_info()[<NUM_LIT:2>]<EOL>try:<EOL><INDENT>self._fileobj.seek(-<NUM_LIT>, <NUM_LIT:2>)<EOL><DEDENT>except EnvironmentError:<EOL><INDENT>reraise(err, None, stack)<EOL><DEDENT>else:<EOL><INDENT>frames = ParseID3v1(self._fileobj.read(<NUM_LIT>))<EOL>if frames is not None:<EOL><INDENT>self.version = self._V11<EOL>for v in frames.values():<EOL><INDENT>self.add(v)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>reraise(err, None, stack)<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>frames = self.__known_frames<EOL>if frames is None:<EOL><INDENT>if self._V23 <= self.version:<EOL><INDENT>frames = Frames<EOL><DEDENT>elif self._V22 <= self.version:<EOL><INDENT>frames = Frames_2_2<EOL><DEDENT><DEDENT>data = self.__fullread(self.size - <NUM_LIT:10>)<EOL>for frame in self.__read_frames(data, frames=frames):<EOL><INDENT>if isinstance(frame, Frame):<EOL><INDENT>self.add(frame)<EOL><DEDENT>else:<EOL><INDENT>self.unknown_frames.append(frame)<EOL><DEDENT><DEDENT>self.__unknown_version = self.version<EOL><DEDENT><DEDENT>finally:<EOL><INDENT>self._fileobj.close()<EOL>del self._fileobj<EOL>del self.__filesize<EOL>if translate:<EOL><INDENT>if v2_version == <NUM_LIT:3>:<EOL><INDENT>self.update_to_v23()<EOL><DEDENT>else:<EOL><INDENT>self.update_to_v24()<EOL><DEDENT><DEDENT><DEDENT>

Load tags from a filename.

        Keyword arguments:

        * filename -- filename to load tag data from
        * known_frames -- dict mapping frame IDs to Frame objects
        * translate -- Update all tags to ID3v2.3/4 internally. If you
                       intend to save, this must be true or you have to
                       call update_to_v23() / update_to_v24() manually.
        * v2_version -- if update_to_v23 or update_to_v24 get called (3 or 4)

        Example of loading a custom frame::

            my_frames = dict(mutagen.id3.Frames)
            class XMYF(Frame): ...
            my_frames["XMYF"] = XMYF
            mutagen.id3.ID3(filename, known_frames=my_frames)


if filename is None:<EOL><INDENT>filename = self.filename<EOL><DEDENT>self.tags.clear()<EOL>fileobj = open(filename, "<STR_LIT>")<EOL>try:<EOL><INDENT>try:<EOL><INDENT>self.tags._inject(fileobj)<EOL><DEDENT>except error as e:<EOL><INDENT>reraise(self._Error, e, sys.exc_info()[<NUM_LIT:2>])<EOL><DEDENT>except EOFError:<EOL><INDENT>raise self._Error("<STR_LIT>")<EOL><DEDENT><DEDENT>finally:<EOL><INDENT>fileobj.close()<EOL><DEDENT>

Remove tags from a file.

        If no filename is given, the one most recently loaded is used.


self.filename = filename<EOL>fileobj = open(filename, "<STR_LIT:rb>")<EOL>try:<EOL><INDENT>try:<EOL><INDENT>self.info = self._Info(fileobj)<EOL>self.tags = self._Tags(fileobj, self.info)<EOL>self.info._post_tags(fileobj)<EOL><DEDENT>except error as e:<EOL><INDENT>reraise(self._Error, e, sys.exc_info()[<NUM_LIT:2>])<EOL><DEDENT>except EOFError:<EOL><INDENT>raise self._Error("<STR_LIT>")<EOL><DEDENT><DEDENT>finally:<EOL><INDENT>fileobj.close()<EOL><DEDENT>


try:<EOL><INDENT>return (self.write() == other.write())<EOL><DEDENT>except AttributeError:<EOL><INDENT>return False<EOL><DEDENT>

Two Ogg pages are the same if they write the same data.


serial = pages[<NUM_LIT:0>].serial<EOL>sequence = pages[<NUM_LIT:0>].sequence<EOL>packets = []<EOL>if strict:<EOL><INDENT>if pages[<NUM_LIT:0>].continued:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if not pages[-<NUM_LIT:1>].complete:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT><DEDENT>elif pages and pages[<NUM_LIT:0>].continued:<EOL><INDENT>packets.append([b"<STR_LIT>"])<EOL><DEDENT>for page in pages:<EOL><INDENT>if serial != page.serial:<EOL><INDENT>raise ValueError("<STR_LIT>" % page)<EOL><DEDENT>elif sequence != page.sequence:<EOL><INDENT>raise ValueError("<STR_LIT>" % page)<EOL><DEDENT>else:<EOL><INDENT>sequence += <NUM_LIT:1><EOL><DEDENT>if page.continued:<EOL><INDENT>packets[-<NUM_LIT:1>].append(page.packets[<NUM_LIT:0>])<EOL><DEDENT>else:<EOL><INDENT>packets.append([page.packets[<NUM_LIT:0>]])<EOL><DEDENT>packets.extend([p] for p in page.packets[<NUM_LIT:1>:])<EOL><DEDENT>return [b"<STR_LIT>".join(p) for p in packets]<EOL>

Construct a list of packet data from a list of Ogg pages.

        If strict is true, the first page must start a new packet,
        and the last page must end the last packet.


if filename is None:<EOL><INDENT>filename = self.filename<EOL><DEDENT>fileobj = open(filename, "<STR_LIT>")<EOL>try:<EOL><INDENT>try:<EOL><INDENT>self.tags._inject(fileobj)<EOL><DEDENT>except error as e:<EOL><INDENT>reraise(self._Error, e, sys.exc_info()[<NUM_LIT:2>])<EOL><DEDENT>except EOFError:<EOL><INDENT>raise self._Error("<STR_LIT>")<EOL><DEDENT><DEDENT>finally:<EOL><INDENT>fileobj.close()<EOL><DEDENT>

Save a tag to a file.

        If no filename is given, the one most recently loaded is used.


OggOpus(filename).delete()<EOL>


d = {}<EOL>for key, value in self._internal:<EOL><INDENT>d.setdefault(key.lower(), []).append(value)<EOL><DEDENT>return d<EOL>

Return a copy of the comment data in a real dict.


def __update_parents(self, fileobj, path, delta):

for atom in path:<EOL><INDENT>fileobj.seek(atom.offset)<EOL>size = cdata.uint_be(fileobj.read(<NUM_LIT:4>))<EOL>if size == <NUM_LIT:1>:  <EOL><INDENT>size = cdata.ulonglong_be(fileobj.read(<NUM_LIT:12>)[<NUM_LIT:4>:])<EOL>fileobj.seek(atom.offset + <NUM_LIT:8>)<EOL>fileobj.write(cdata.to_ulonglong_be(size + delta))<EOL><DEDENT>else:  <EOL><INDENT>fileobj.seek(atom.offset)<EOL>fileobj.write(cdata.to_uint_be(size + delta))<EOL><DEDENT><DEDENT>

Update all parent atoms with the new size.


path = [self]<EOL>for name in names:<EOL><INDENT>path.append(path[-<NUM_LIT:1>][name, ])<EOL><DEDENT>return path[<NUM_LIT:1>:]<EOL>

Look up and return the complete path of an atom.

        For example, atoms.path('moov', 'udta', 'meta') will return a
        list of three atoms, corresponding to the moov, udta, and meta
        atoms.


def findall(self, name, recursive=False):

if self.children is not None:<EOL><INDENT>for child in self.children:<EOL><INDENT>if child.name == name:<EOL><INDENT>yield child<EOL><DEDENT>if recursive:<EOL><INDENT>for atom in child.findall(name, True):<EOL><INDENT>yield atom<EOL><DEDENT><DEDENT><DEDENT><DEDENT>

Recursively find all child atoms by specified name.


@lru_cache(maxsize=<NUM_LIT:200>)<EOL><INDENT>def selectPolicy(self, origin, request_method=None):<DEDENT>

ret_origin = None<EOL>policyname = None<EOL>if self.matchstrategy in ("<STR_LIT>", "<STR_LIT>"):<EOL><INDENT>for pol in self.activepolicies:<EOL><INDENT>policy=self.policies[pol]<EOL>ret_origin = None<EOL>policyname = policy.name<EOL>if policyname == "<STR_LIT>":<EOL><INDENT>break<EOL><DEDENT>if self.matchstrategy == "<STR_LIT>":<EOL><INDENT>if policy.methods != "<STR_LIT:*>" and not CORS.matchlist(request_method, policy.methods, case_sensitive=True):<EOL><INDENT>continue<EOL><DEDENT><DEDENT>if origin and policy.match:<EOL><INDENT>if CORS.matchlist(origin, policy.match):<EOL><INDENT>ret_origin = origin<EOL><DEDENT><DEDENT>elif policy.origin == "<STR_LIT>":<EOL><INDENT>ret_origin = origin<EOL><DEDENT>elif policy.origin:<EOL><INDENT>ret_origin = policy.origin<EOL><DEDENT>if ret_origin:<EOL><INDENT>break<EOL><DEDENT><DEDENT><DEDENT>return policyname, ret_origin<EOL>

Based on the matching strategy and the origin and optionally the requested method a tuple of policyname and origin to pass back is returned.


req = prepRequest(hdr)<EOL>res = req.get_response(corsed)<EOL>assert res.body.decode("<STR_LIT:utf-8>") == "<STR_LIT>", "<STR_LIT>" % res.body<EOL>

requests that don't match preflight criteria are ignored


@wraps(func)<EOL>def wrapper(*args, **kwargs):<EOL><INDENT>res = func(*args, **kwargs)<EOL>project_command = args[<NUM_LIT:0>]<EOL>project_handler = project_command.vcp.project_handler<EOL>if not project_handler:<EOL><INDENT>return res<EOL><DEDENT>kwargs['<STR_LIT>'] = res<EOL>getattr(project_handler, func.__name__)(**kwargs)<EOL>return res<EOL><DEDENT>return wrapper<EOL>

Calls the project handler same named function

    Note: the project handler may add some extra arguments to the command,
          so when use this decorator, add **kwargs to the end of the arguments


@abstractmethod<EOL><INDENT>def install_to(self, project, env):<DEDENT>

pass<EOL>

Install current (self.project) project to the argument one.

        Args:
            project (Project): the target project
            env (EnvironmentBase): the target environment

        Returns:
            True if the install is succeeded, else False


with open( self.file_name, '<STR_LIT:w>') as fh:<EOL><INDENT>for k,v in self.args.iteritems():<EOL><INDENT>buf = StringIO.StringIO()<EOL>buf.write(k)<EOL>self._append_vals(buf,v)<EOL>fh.write(buf.getvalue() + '<STR_LIT:\n>')<EOL>buf.close()<EOL><DEDENT><DEDENT>


return items<EOL>

perform data modification of any values, after unpacking from a buffer.


if len(data) == <NUM_LIT:0>:<EOL><INDENT>return False<EOL><DEDENT>crc = VProCRC.get(data)<EOL>if crc:<EOL><INDENT>log.info("<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>log.debug("<STR_LIT>")<EOL><DEDENT>return not crc<EOL>

perform CRC check on raw serial data, return true if valid.
a valid CRC == 0.


year = (date & <NUM_LIT>) + <NUM_LIT>  <EOL>day = (date >> <NUM_LIT:7>) & <NUM_LIT>  <EOL>month = (date >> <NUM_LIT:12>) & <NUM_LIT>  <EOL>return "<STR_LIT>" % (year, month, day)<EOL>

given a packed storm date field, unpack and return 'YYYY-MM-DD' string.


<EOL>return "<STR_LIT>" % divmod(val, <NUM_LIT:100>)<EOL>

given a packed time field, unpack and return "HH:MM" string.


self.port.close()<EOL>

close serial port when object is deleted.


<EOL>temp = fields['<STR_LIT>']<EOL>hum = fields['<STR_LIT>']<EOL>wind = fields['<STR_LIT>']<EOL>wind10min = fields['<STR_LIT>']<EOL>fields['<STR_LIT>'] = calc_heat_index(temp, hum)<EOL>fields['<STR_LIT>'] = calc_wind_chill(temp, wind, wind10min)<EOL>fields['<STR_LIT>'] = calc_dewpoint(temp, hum)<EOL>now = time.localtime()<EOL>fields['<STR_LIT>'] = time.strftime("<STR_LIT>", now)<EOL>fields['<STR_LIT>'] = now[<NUM_LIT:0>]<EOL>fields['<STR_LIT>'] = str(now[<NUM_LIT:1>]).zfill(<NUM_LIT:2>)<EOL>now = time.gmtime()<EOL>fields['<STR_LIT>'] = time.strftime("<STR_LIT>", now)<EOL>fields['<STR_LIT>'] = now[<NUM_LIT:0>]<EOL>fields['<STR_LIT>'] = str(now[<NUM_LIT:1>]).zfill(<NUM_LIT:2>)<EOL>

calculates the derived fields (those fields that are calculated)


return m * <NUM_LIT><EOL>


return kts * <NUM_LIT><EOL>


return km * <NUM_LIT><EOL>


return mph<EOL>

Nautical miles/hour (nmph) to knots (kt)


return kts<EOL>

Knots (kt) to nautical miles/hour (nmph)


return mph * <NUM_LIT><EOL>


return mb * <NUM_LIT><EOL>


return inches * <NUM_LIT><EOL>

Inches of mercury @60F (inHg60) to pounds/square inch (lb/in**2)


return lbs * <NUM_LIT><EOL>

Pounds/square inch (lb/in**2) to millibars (mb)


return mb * <NUM_LIT:100><EOL>

Millibars (mb) to newtons/square meter (N/m**2)


return mb<EOL>


return atm * <NUM_LIT><EOL>


return lbs * <NUM_LIT><EOL>

Pounds/square foot (lb/ft**2) to millibars (mb)


return k * <NUM_LIT><EOL>

Degrees Kelvin (K) to degrees Rankine (R)


return f + <NUM_LIT><EOL>

Degrees Fahrenheit (F) to degrees Rankine (R)


return k - <NUM_LIT><EOL>

Degrees Kelvin (K) to degrees Celsius (C)


sites = []<EOL>for p_key in vars(opts).keys():<EOL><INDENT>args = getattr(opts,p_key)<EOL>if p_key in PUB_SERVICES and args:<EOL><INDENT>if isinstance(args,tuple):<EOL><INDENT>ps = PUB_SERVICES[p_key](*args)<EOL><DEDENT>else:<EOL><INDENT>ps = PUB_SERVICES[p_key](args)<EOL><DEDENT>sites.append( ps )<EOL><DEDENT><DEDENT>return sites<EOL>

use values in opts data to generate instances of publication services.


rec = station.fields['<STR_LIT>']<EOL>if rec:<EOL><INDENT>threshold = station.fields['<STR_LIT>'] + GUST_MPH_MIN<EOL>if rec['<STR_LIT>'] >= threshold:<EOL><INDENT>self.value = (rec['<STR_LIT>'],rec['<STR_LIT>'])<EOL>self.count = GUST_TTL * <NUM_LIT> / interval<EOL><DEDENT>else:<EOL><INDENT>self.value = self.NO_VALUE<EOL><DEDENT><DEDENT>if self.count:<EOL><INDENT>self.count -= <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>self.value = self.NO_VALUE<EOL><DEDENT>log.debug('<STR_LIT>'.format(*self.value))<EOL>return self.value<EOL>

return gust data, if above threshold value and current time is inside
reporting window period


def compress(string, mode=MODE_GENERIC, quality=<NUM_LIT:11>, lgwin=<NUM_LIT>, lgblock=<NUM_LIT:0>):

compressor = Compressor(mode=mode, quality=quality, lgwin=lgwin,<EOL>lgblock=lgblock)<EOL>return compressor.process(string) + compressor.finish()<EOL>

Compress a byte string.

    Args:
      string (bytes): The input data.
      mode (int, optional): The compression mode can be MODE_GENERIC (default),
        MODE_TEXT (for UTF-8 format text input) or MODE_FONT (for WOFF 2.0).
      quality (int, optional): Controls the compression-speed vs compression-
        density tradeoff. The higher the quality, the slower the compression.
        Range is 0 to 11. Defaults to 11.
      lgwin (int, optional): Base 2 logarithm of the sliding window size. Range
        is 10 to 24. Defaults to 22.
      lgblock (int, optional): Base 2 logarithm of the maximum input block size.
        Range is 16 to 24. If set to 0, the value will be set based on the
        quality. Defaults to 0.

    Returns:
      The compressed byte string.

    Raises:
      brotli.error: If arguments are invalid, or compressor fails.


return "<STR_LIT>".format(self.pos>><NUM_LIT:3>, self.pos&<NUM_LIT:7>)<EOL>

Representation
        >>> olleke
        BitStream(pos=0:0)


lower = self.value0+sum(<NUM_LIT:1><<x for x in self.extraTable[:index])<EOL>upper = lower+(<NUM_LIT:1><<self.extraTable[index])<EOL>return lower, upper-<NUM_LIT:1><EOL>

Give the range of possible values in a tuple
        Useful for mnemonic and explanation


if dcode<<NUM_LIT:16>:<EOL><INDENT>return [(<NUM_LIT:1>,<NUM_LIT:0>),(<NUM_LIT:2>,<NUM_LIT:0>),(<NUM_LIT:3>,<NUM_LIT:0>),(<NUM_LIT:4>,<NUM_LIT:0>),<EOL>(<NUM_LIT:1>,-<NUM_LIT:1>),(<NUM_LIT:1>,+<NUM_LIT:1>),(<NUM_LIT:1>,-<NUM_LIT:2>),(<NUM_LIT:1>,+<NUM_LIT:2>),(<NUM_LIT:1>,-<NUM_LIT:3>),(<NUM_LIT:1>,+<NUM_LIT:3>),<EOL>(<NUM_LIT:2>,-<NUM_LIT:1>),(<NUM_LIT:2>,+<NUM_LIT:1>),(<NUM_LIT:2>,-<NUM_LIT:2>),(<NUM_LIT:2>,+<NUM_LIT:2>),(<NUM_LIT:2>,-<NUM_LIT:3>),(<NUM_LIT:2>,+<NUM_LIT:3>)<EOL>][dcode]<EOL><DEDENT>if dcode<<NUM_LIT:16>+self.NDIRECT:<EOL><INDENT>return (<NUM_LIT:0>,dcode-<NUM_LIT:16>)<EOL><DEDENT>POSTFIX_MASK = (<NUM_LIT:1> << self.NPOSTFIX) - <NUM_LIT:1><EOL>ndistbits = <NUM_LIT:1> + ((dcode - self.NDIRECT - <NUM_LIT:16>) >> (self.NPOSTFIX + <NUM_LIT:1>))<EOL>hcode = (dcode - self.NDIRECT - <NUM_LIT:16>) >> self.NPOSTFIX<EOL>lcode = (dcode - self.NDIRECT - <NUM_LIT:16>) & POSTFIX_MASK<EOL>offset = ((<NUM_LIT:2> + (hcode & <NUM_LIT:1>)) << ndistbits) - <NUM_LIT:4><EOL>distance = ((offset + dextra) << self.NPOSTFIX) + lcode + self.NDIRECT + <NUM_LIT:1><EOL>return (<NUM_LIT:0>,distance)<EOL>

Decode value of symbol together with the extra bits.
        >>> d = DistanceAlphabet('D', NPOSTFIX=2, NDIRECT=10)
        >>> d[34].value(2)
        (0, 35)


if index>=len(self.extraTable):<EOL><INDENT>raise ValueError("<STR_LIT>".format(<EOL>self.__class__.__name__, index))<EOL><DEDENT>return Symbol(self, index)<EOL>


firstAddress = pos+<NUM_LIT:7>>><NUM_LIT:3><EOL>lastAddress = self.stream.pos+<NUM_LIT:7>>><NUM_LIT:3><EOL>return '<STR_LIT>'.join(map('<STR_LIT>'.format,<EOL>self.stream.data[firstAddress:lastAddress]))<EOL>

Produce hex dump of all data containing the bits
        from pos to stream.pos


def explanation(self, index, extra=None):

extraBits = <NUM_LIT:0> if extra is None else self.extraBits(index)<EOL>if not hasattr(self, '<STR_LIT>'):<EOL><INDENT>formatString = '<STR_LIT>'<EOL>lo = hi = value = self.value(index, extra)<EOL><DEDENT>elif extraBits==<NUM_LIT:0>:<EOL><INDENT>formatString = '<STR_LIT>'<EOL>lo, hi = self.span(index)<EOL>value = lo<EOL><DEDENT>else:<EOL><INDENT>formatString = '<STR_LIT>'<EOL>lo, hi = self.span(index)<EOL>value = lo+extra<EOL><DEDENT>return formatString.format(<EOL>self.description and self.description+'<STR_LIT>',<EOL>'<STR_LIT:x>'*extraBits,<EOL>self.bitPattern(index),<EOL>lo, hi,<EOL>extra,<EOL>value,<EOL>)<EOL>

Expanded version of Code.explanation supporting extra bits.
        If you don't supply extra, it is not mentioned.


self.decodeTable = decodeTable<EOL>todo = set(decodeTable)<EOL>maskLength = <NUM_LIT:0><EOL>lengthTable = {}<EOL>while todo:<EOL><INDENT>mask = (<NUM_LIT:1><<maskLength)-<NUM_LIT:1><EOL>splitSymbols = defaultdict(list)<EOL>for s in todo: splitSymbols[s&mask].append(s)<EOL>for s,subset in splitSymbols.items():<EOL><INDENT>if len(subset)==<NUM_LIT:1>:<EOL><INDENT>lengthTable[self.decodeTable[s]] = maskLength<EOL>todo.remove(s)<EOL><DEDENT><DEDENT>maskLength +=<NUM_LIT:1><EOL><DEDENT>self.lengthTable = lengthTable<EOL>self.minLength = min(lengthTable.values())<EOL>self.maxLength = max(lengthTable.values())<EOL>self.switchToPrefix()<EOL>

Store decodeTable,
        and compute lengthTable, minLength, maxLength from encodings.


<EOL>return int.from_bytes(<EOL>self.data[self.pos>><NUM_LIT:3>:self.pos+n+<NUM_LIT:7>>><NUM_LIT:3>],<EOL>'<STR_LIT>')>>(self.pos&<NUM_LIT:7>) & (<NUM_LIT:1><<n)-<NUM_LIT:1><EOL>

Peek an n bit integer from the stream without updating the pointer.
        It is not an error to read beyond the end of the stream.
        >>> olleke.data[:2]==b'\x1b\x2e' and 0x2e1b==11803
        True
        >>> olleke.peek(15)
        11803
        >>> hex(olleke.peek(32))
        '0x2e1b'


<EOL>U = self.upperCase1<EOL>return eval(self.actionList[action], locals())<EOL>


result = '<STR_LIT>'<EOL>def formatSubString(s):<EOL><INDENT>for c in s:<EOL><INDENT>if c==<NUM_LIT:32>: yield '<STR_LIT:U+0020>'<EOL>else: yield outputCharFormatter(c)<EOL><DEDENT><DEDENT>if len(result)<<NUM_LIT:200>: return '<STR_LIT>'.join(formatSubString(s))<EOL>else:<EOL><INDENT>return '<STR_LIT>'.join(formatSubString(s[:<NUM_LIT:100>]))+'<STR_LIT>'+'<STR_LIT>'.join(formatSubString(s[-<NUM_LIT:100>:]))<EOL><DEDENT>


print('<STR_LIT>'.center(<NUM_LIT>, '<STR_LIT:->'))<EOL>self.literalContextModes = []<EOL>for i in range(self.numberOfBlockTypes[L]):<EOL><INDENT>self.literalContextModes.append(<EOL>self.verboseRead(LiteralContextMode(number=i)))<EOL><DEDENT>

Read literal context modes.
        LSB6: lower 6 bits of last char
        MSB6: upper 6 bits of last char
        UTF8: rougly dependent on categories:
            upper 4 bits depend on category of last char:
                control/whitespace/space/ punctuation/quote/%/open/close/
                comma/period/=/digits/ VOWEL/CONSONANT/vowel/consonant
            lower 2 bits depend on category of 2nd last char:
                space/punctuation/digit or upper/lowercase
        signed: hamming weight of last 2 chars


return str(self.value(index))<EOL>

Give mnemonic of symbol.
        Override where needed.


self.mode = PrefixDecoder<EOL>

This routine makes sure the prefix decoder is activated.


return map(partial(Symbol, self), range(len(self)))<EOL>


length, symbol = self.decodePeek(stream.peek(self.maxLength))<EOL>stream.pos += length<EOL>extraBits = self.extraBits(symbol.index)<EOL>return length, symbol, extraBits, stream.read(extraBits)<EOL>

Read symbol and extrabits from stream.
        Returns symbol length, symbol, extraBits, extra
        >>> olleke.pos = 6
        >>> MetablockLengthAlphabet().readTupleAndExtra(olleke)
        (2, Symbol(MLEN, 4), 16, 46)


<EOL>row = [<NUM_LIT:0>,<NUM_LIT:0>,<NUM_LIT:1>,<NUM_LIT:1>,<NUM_LIT:2>,<NUM_LIT:2>,<NUM_LIT:1>,<NUM_LIT:3>,<NUM_LIT:2>,<NUM_LIT:3>,<NUM_LIT:3>][index>><NUM_LIT:6>]<EOL>col = [<NUM_LIT:0>,<NUM_LIT:1>,<NUM_LIT:0>,<NUM_LIT:1>,<NUM_LIT:0>,<NUM_LIT:1>,<NUM_LIT:2>,<NUM_LIT:0>,<NUM_LIT:2>,<NUM_LIT:1>,<NUM_LIT:2>][index>><NUM_LIT:6>]<EOL>insertLengthCode = row<<<NUM_LIT:3> | index>><NUM_LIT:3>&<NUM_LIT:7><EOL>if row: insertLengthCode -= <NUM_LIT:8><EOL>copyLengthCode = col<<<NUM_LIT:3> | index&<NUM_LIT:7><EOL>return (<EOL>Symbol(self.insertLengthAlphabet, insertLengthCode),<EOL>Symbol(self.copyLengthAlphabet, copyLengthCode),<EOL>row==<NUM_LIT:0><EOL>)<EOL>

Give relevant values for computations:
        (insertSymbol, copySymbol, dist0flag)


if extra><NUM_LIT:15>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>return index, extra<<index<EOL>


def readPrefixArray(self, kind, numberOfTrees):

prefixes = []<EOL>for i in range(numberOfTrees):<EOL><INDENT>if kind==L: alphabet = LiteralAlphabet(i)<EOL>elif kind==I: alphabet = InsertAndCopyAlphabet(i)<EOL>elif kind==D: alphabet = DistanceAlphabet(<EOL>i, NPOSTFIX=self.NPOSTFIX, NDIRECT=self.NDIRECT)<EOL>self.readPrefixCode(alphabet)<EOL>prefixes.append(alphabet)<EOL><DEDENT>self.prefixCodes[kind] = prefixes<EOL>


if extra is not None:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>return index<EOL>

Get value of symbol for computations.
        Override where needed.


lower, upper = self.span(index)<EOL>value = lower+(extra or <NUM_LIT:0>)<EOL>if value>upper:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>return value<EOL>

Override if you don't define value0 and extraTable


index = index<EOL>if index==<NUM_LIT:0>: return <NUM_LIT:1>, <NUM_LIT:0><EOL>if index<=self.RLEMAX: return (<NUM_LIT:1><<index)+extra, <NUM_LIT:0><EOL>return <NUM_LIT:1>, index-self.RLEMAX<EOL>


def get_argument_key(kwargs, argument_key, index):

if isinstance(argument_key, (list, tuple)):<EOL><INDENT>return_string = '<STR_LIT>'<EOL>for element in argument_key:<EOL><INDENT>return_val = kwargs.get(element)[index]<EOL>if return_val is None:<EOL><INDENT>return_val = '<STR_LIT>'<EOL><DEDENT>return_string += str(return_val)<EOL>if len(argument_key) > <NUM_LIT:1>:<EOL><INDENT>return_string += '<STR_LIT:_>'<EOL><DEDENT><DEDENT>return return_string<EOL><DEDENT>return str(kwargs.get(argument_key)[index] or '<STR_LIT>')<EOL>

:param kwargs: keyword arguments used to kickoff the multiget
:param argument_key: Name or set of names of keyword arguments to read from
:param index: which set of arguments are considered
:return:


def map_arguments_to_objects(kwargs, objects, object_key, object_tuple_key, argument_key, result_value, default_result):

<EOL>map_ = map_objects_to_result(objects, object_key, object_tuple_key, result_value, default_result)<EOL>element_count = get_request_count(kwargs)<EOL>return [map_[get_argument_key(kwargs, argument_key, index)] for index in range(<NUM_LIT:0>, element_count)]<EOL>

:param kwargs: kwargs used to call the multiget function
:param objects: objects returned from the inner function
:param object_key: field or set of fields that map to the kwargs provided
:param object_tuple_key: A temporary shortcut until we allow dot.path traversal for object_key.
Will call getattr(getattr(result, join_table_name), object_key)
:param argument_key: field or set of fields that map to the objects provided
:param result_value: Limit the fields returned to this field or set of fields (none = whole object)
:param default_result: If the inner function returned none for a set of parameters, default to this
:return:


@abstractmethod<EOL><INDENT>def get(self, k, d=None):<DEDENT>

pass<EOL>

D.get(k[,d]) -> D[k] if k in D, else d.  d defaults to None.


pass<EOL>


@abstractmethod<EOL><INDENT>def __contains__(self, *args, **kwargs):<DEDENT>

pass<EOL>


cache = get_cache()<EOL>key = self.get_cache_key(*args)<EOL>if key in cache:<EOL><INDENT>del cache[key]<EOL><DEDENT>

Remove the key from the request cache and from memcache.


key = self.get_cache_key(*args, **kwargs)<EOL>cache = get_cache()<EOL>if key in cache:<EOL><INDENT>return cache[key]<EOL><DEDENT>else:<EOL><INDENT>self.prime(*args, **kwargs)<EOL>self._issue_gets_for_primes()<EOL>return cache[key]<EOL><DEDENT>

Pull the return value from the request cache if possible. If not,
pull the value from calling inner_f, then set the value in request cache


return [<EOL>(tag.name, "<STR_LIT>" if tag.name in tags else "<STR_LIT>")<EOL>for tag in self.model.objects.all()<EOL>]<EOL>

Generates a list of tags identifying those previously selected.

Returns a list of tuples of the form (<tag name>, <CSS class name>).

Uses the string names rather than the tags themselves in order to work
with tag lists built from forms not fully submitted.


<EOL>zone = '<STR_LIT>' if getattr(obj, '<STR_LIT>', True) else '<STR_LIT>'<EOL>return obj.isoformat() + zone<EOL>

Encode a datetime.datetime or datetime.date object as an ISO 8601 format string.


if isinstance(val, basestring) and val.count('<STR_LIT:->') == <NUM_LIT:2> and len(val) > <NUM_LIT:9>:<EOL><INDENT>try:<EOL><INDENT>dt = dateutil.parser.parse(val)<EOL>if val.endswith(('<STR_LIT>', '<STR_LIT>', '<STR_LIT>')):<EOL><INDENT>dt = dt.replace(tzinfo=None)<EOL><DEDENT>return dt<EOL><DEDENT>except (TypeError, ValueError):<EOL><INDENT>pass<EOL><DEDENT><DEDENT>return val<EOL>

Tries to decode strings that look like dates into datetime objects.


<EOL>return obj.get_async()<EOL>

Get the Entity from the ndb.Key for further encoding.


return is_host_google() and not is_default_version(version)<EOL>

True if the app is hosted by Google (appspot.com) but the version is not the default.


version = version or get_current_version_name_safe()<EOL>module = module or get_current_module_name_safe()<EOL>if version and module:<EOL><INDENT>return '<STR_LIT>'.join((version, module))<EOL><DEDENT>return None<EOL>

Returns the current version/module in -dot- notation which is used by `target:` parameters.
If there is no current version or module then None is returned.


version = version or get_current_version_name()<EOL>module = module or get_current_module_name()<EOL>return '<STR_LIT>'.join((version, module))<EOL>

Returns the current version/module in -dot- notation which is used by `target:` parameters.


Return a dictionary of all environment keys/values.


return {k: getattr(modules, k)() for k in keys}<EOL>

Return a dictionary of key/values from the modules module functions.


if self.music_folder is None:<EOL><INDENT>music_folder = os.path.join(os.path.expanduser('<STR_LIT>'), '<STR_LIT>')<EOL>if not os.path.exists(music_folder):<EOL><INDENT>os.makedirs(music_folder)<EOL><DEDENT>self.music_folder = music_folder<EOL><DEDENT>

Initializes the connection attribute with the path to the user home folder's Music folder, and creates it if it doesn't exist.


try:<EOL><INDENT>track = self.client.get('<STR_LIT>', url=url)<EOL><DEDENT>except HTTPError:<EOL><INDENT>log.error(f"<STR_LIT>")<EOL>return<EOL><DEDENT>r = requests.get(self.client.get(track.stream_url, allow_redirects=False).location, stream=True)<EOL>total_size = int(r.headers['<STR_LIT>'])<EOL>chunk_size = <NUM_LIT><EOL>file_name = track.title + '<STR_LIT>'<EOL>with open(file_name, '<STR_LIT:wb>') as f:<EOL><INDENT>for data in tqdm(r.iter_content(chunk_size), desc=track.title, total=total_size / chunk_size, unit='<STR_LIT>', file=sys.stdout):<EOL><INDENT>f.write(data)<EOL><DEDENT><DEDENT>return file_name<EOL>

Downloads a MP3 file that is associated with the track at the URL passed.

:param str url: URL of the track to be downloaded


SCOPES = '<STR_LIT>'<EOL>store = file.Storage('<STR_LIT>')<EOL>creds = store.get()<EOL>if not creds or creds.invalid:<EOL><INDENT>try:<EOL><INDENT>flow = client.flow_from_clientsecrets('<STR_LIT>', SCOPES)<EOL><DEDENT>except InvalidClientSecretsError:<EOL><INDENT>log.error('<STR_LIT>')<EOL>return<EOL><DEDENT>creds = tools.run_flow(flow, store)<EOL><DEDENT>self.connection = build('<STR_LIT>', '<STR_LIT>', http=creds.authorize(Http()))<EOL>response = self.connection.files().list(q="<STR_LIT>").execute()<EOL>try:<EOL><INDENT>folder_id = response.get('<STR_LIT>', [])[<NUM_LIT:0>]['<STR_LIT:id>']<EOL><DEDENT>except IndexError:<EOL><INDENT>log.warning('<STR_LIT>')<EOL>folder_metadata = {'<STR_LIT:name>': '<STR_LIT>', '<STR_LIT>': '<STR_LIT>'}<EOL>folder = self.connection.files().create(body=folder_metadata, fields='<STR_LIT:id>').execute()<EOL><DEDENT>

Creates connection to the Google Drive API, sets the connection attribute to make requests, and creates the Music folder if it doesn't exist.


def cost(self, t_node, branch_length, multiplicity=<NUM_LIT>):

merger_time = t_node+branch_length<EOL>return self.integral_merger_rate(merger_time) - self.integral_merger_rate(t_node)- np.log(self.total_merger_rate(merger_time))*(multiplicity-<NUM_LIT:1.0>)/multiplicity<EOL>

returns the cost associated with a branch starting at t_node
t_node is time before present, the branch goes back in time

Args:
    - t_node:           time of the node
    - branch_length:    branch length, determines when this branch merges with sister
    - multiplicity:     2 if merger is binary, higher if this is a polytomy


for clade in self.tree.find_clades():<EOL><INDENT>if clade.up is not None:<EOL><INDENT>clade.branch_length_interpolator.merger_cost = self.cost<EOL><DEDENT><DEDENT>

attaches the the merger cost to each branch length interpolator in the tree.


<EOL>self.tree_events = np.array(sorted([(n.time_before_present, len(n.clades)-<NUM_LIT:1>)<EOL>for n in self.tree.find_clades() if not n.bad_branch],<EOL>key=lambda x:-x[<NUM_LIT:0>]))<EOL>from collections import defaultdict<EOL>dn_branch = defaultdict(int)<EOL>for (t, dn) in self.tree_events:<EOL><INDENT>dn_branch[t]+=dn<EOL><DEDENT>unique_mergers = np.array(sorted(dn_branch.items(), key = lambda x:-x[<NUM_LIT:0>]))<EOL>nbranches = [[ttconf.BIG_NUMBER, <NUM_LIT:1>], [unique_mergers[<NUM_LIT:0>,<NUM_LIT:0>]+ttconf.TINY_NUMBER, <NUM_LIT:1>]]<EOL>for ti, (t, dn) in enumerate(unique_mergers[:-<NUM_LIT:1>]):<EOL><INDENT>new_n = nbranches[-<NUM_LIT:1>][<NUM_LIT:1>]+dn<EOL>next_t = unique_mergers[ti+<NUM_LIT:1>,<NUM_LIT:0>]+ttconf.TINY_NUMBER<EOL>nbranches.append([t, new_n])<EOL>nbranches.append([next_t, new_n])<EOL><DEDENT>new_n += unique_mergers[-<NUM_LIT:1>,<NUM_LIT:1>]<EOL>nbranches.append([next_t, new_n])<EOL>nbranches.append([-ttconf.BIG_NUMBER, new_n])<EOL>nbranches=np.array(nbranches)<EOL>self.nbranches = interp1d(nbranches[:,<NUM_LIT:0>], nbranches[:,<NUM_LIT:1>], kind='<STR_LIT>')<EOL>

calculates an interpolation object that maps time to the number of
concurrent branches in the tree. The result is stored in self.nbranches


<EOL>if os.path.isfile(params.states):<EOL><INDENT>states = pd.read_csv(params.states, sep='<STR_LIT:\t>' if params.states[-<NUM_LIT:3>:]=='<STR_LIT>' else '<STR_LIT:U+002C>',<EOL>skipinitialspace=True)<EOL><DEDENT>else:<EOL><INDENT>print("<STR_LIT>")<EOL>return <NUM_LIT:1><EOL><DEDENT>outdir = get_outdir(params, '<STR_LIT>')<EOL>taxon_name = '<STR_LIT:name>' if '<STR_LIT:name>' in states.columns else states.columns[<NUM_LIT:0>]<EOL>if params.attribute:<EOL><INDENT>if params.attribute in states.columns:<EOL><INDENT>attr = params.attribute<EOL><DEDENT>else:<EOL><INDENT>print("<STR_LIT>"+params.states, file=sys.stderr)<EOL>print("<STR_LIT>"+"<STR_LIT:U+002CU+0020>".join(states.columns), file=sys.stderr)<EOL>return <NUM_LIT:1><EOL><DEDENT><DEDENT>else:<EOL><INDENT>attr = states.columns[<NUM_LIT:1>]<EOL>print("<STR_LIT>"+attr, file=sys.stderr)<EOL><DEDENT>leaf_to_attr = {x[taxon_name]:x[attr] for xi, x in states.iterrows()<EOL>if x[attr]!=params.missing_data}<EOL>unique_states = sorted(set(leaf_to_attr.values()))<EOL>nc = len(unique_states)<EOL>if nc><NUM_LIT>:<EOL><INDENT>print("<STR_LIT>", file=sys.stderr)<EOL>return <NUM_LIT:1><EOL><DEDENT>elif nc<<NUM_LIT:2>:<EOL><INDENT>print("<STR_LIT>", file=sys.stderr)<EOL>return <NUM_LIT:1><EOL><DEDENT>alphabet = [chr(<NUM_LIT>+i) for i,state in enumerate(unique_states)]<EOL>missing_char = chr(<NUM_LIT>+nc)<EOL>letter_to_state = {a:unique_states[i] for i,a in enumerate(alphabet)}<EOL>letter_to_state[missing_char]=params.missing_data<EOL>reverse_alphabet = {v:k for k,v in letter_to_state.items()}<EOL>if params.weights:<EOL><INDENT>params.infer_gtr = True<EOL>tmp_weights = pd.read_csv(params.weights, sep='<STR_LIT:\t>' if params.states[-<NUM_LIT:3>:]=='<STR_LIT>' else '<STR_LIT:U+002C>',<EOL>skipinitialspace=True)<EOL>weights = {row[<NUM_LIT:0>]:row[<NUM_LIT:1>] for ri,row in tmp_weights.iterrows()}<EOL>mean_weight = np.mean(list(weights.values()))<EOL>weights = np.array([weights[c] if c in weights else mean_weight for c in unique_states], dtype=float)<EOL>weights/=weights.sum()<EOL><DEDENT>else:<EOL><INDENT>weights = np.ones(nc, dtype=float)/nc<EOL><DEDENT>W = np.ones((nc,nc), dtype=float)<EOL>mugration_GTR = GTR.custom(pi = weights, W=W, alphabet = np.array(alphabet))<EOL>mugration_GTR.profile_map[missing_char] = np.ones(nc)<EOL>mugration_GTR.ambiguous=missing_char<EOL>treeanc = TreeAnc(params.tree, gtr=mugration_GTR, verbose=params.verbose,<EOL>convert_upper=False, one_mutation=<NUM_LIT>)<EOL>pseudo_seqs = [SeqRecord(id=n.name,name=n.name,<EOL>seq=Seq(reverse_alphabet[leaf_to_attr[n.name]]<EOL>if n.name in leaf_to_attr else missing_char))<EOL>for n in treeanc.tree.get_terminals()]<EOL>treeanc.aln = MultipleSeqAlignment(pseudo_seqs)<EOL>ndiff = treeanc.infer_ancestral_sequences(method='<STR_LIT>', infer_gtr=True,<EOL>store_compressed=False, pc=params.pc, marginal=True, normalized_rate=False,<EOL>fixed_pi=weights if params.weights else None)<EOL>if ndiff==ttconf.ERROR: <EOL><INDENT>return <NUM_LIT:1><EOL><DEDENT>print("<STR_LIT>"%attr,params.tree)<EOL>basename = get_basename(params, outdir)<EOL>gtr_name = basename + '<STR_LIT>'<EOL>with open(gtr_name, '<STR_LIT:w>') as ofile:<EOL><INDENT>ofile.write('<STR_LIT>')<EOL>for state in unique_states:<EOL><INDENT>ofile.write('<STR_LIT>'%(reverse_alphabet[state], state))<EOL><DEDENT>ofile.write('<STR_LIT>'+str(treeanc.gtr)+'<STR_LIT:\n>')<EOL>print("<STR_LIT>", gtr_name)<EOL><DEDENT>terminal_count = <NUM_LIT:0><EOL>for n in treeanc.tree.find_clades():<EOL><INDENT>if n.up is None:<EOL><INDENT>continue<EOL><DEDENT>n.confidence=None<EOL>if n.is_terminal() and len(n.name)><NUM_LIT> and bioversion<"<STR_LIT>":<EOL><INDENT>n.name = n.name[:<NUM_LIT>]+'<STR_LIT>'%terminal_count<EOL>terminal_count+=<NUM_LIT:1><EOL><DEDENT>n.comment= '<STR_LIT>'%attr + letter_to_state[n.sequence[<NUM_LIT:0>]] +'<STR_LIT:">'<EOL><DEDENT>if params.confidence:<EOL><INDENT>conf_name = basename+'<STR_LIT>'<EOL>with open(conf_name, '<STR_LIT:w>') as ofile:<EOL><INDENT>ofile.write('<STR_LIT>'+'<STR_LIT:U+002CU+0020>'.join(unique_states)+'<STR_LIT:\n>')<EOL>for n in treeanc.tree.find_clades():<EOL><INDENT>ofile.write(n.name + '<STR_LIT:U+002CU+0020>'+'<STR_LIT:U+002CU+0020>'.join([str(x) for x in n.marginal_profile[<NUM_LIT:0>]])+'<STR_LIT:\n>')<EOL><DEDENT><DEDENT>print("<STR_LIT>", conf_name)<EOL><DEDENT>outtree_name = basename+'<STR_LIT>'<EOL>Phylo.write(treeanc.tree, outtree_name, '<STR_LIT>')<EOL>print("<STR_LIT>",outtree_name)<EOL>return <NUM_LIT:0><EOL>


model = params.gtr<EOL>gtr_params = params.gtr_params<EOL>if model == '<STR_LIT>':<EOL><INDENT>gtr = GTR.standard('<STR_LIT>', alphabet='<STR_LIT>' if params.aa else '<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>kwargs = {}<EOL>if gtr_params is not None:<EOL><INDENT>for param in gtr_params:<EOL><INDENT>keyval = param.split('<STR_LIT:=>')<EOL>if len(keyval)!=<NUM_LIT:2>: continue<EOL>if keyval[<NUM_LIT:0>] in ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>keyval[<NUM_LIT:0>] = '<STR_LIT>'<EOL>keyval[<NUM_LIT:1>] = list(map(float, keyval[<NUM_LIT:1>].split('<STR_LIT:U+002C>')))<EOL><DEDENT>elif keyval[<NUM_LIT:0>] not in ['<STR_LIT>']:<EOL><INDENT>keyval[<NUM_LIT:1>] = float(keyval[<NUM_LIT:1>])<EOL><DEDENT>kwargs[keyval[<NUM_LIT:0>]] = keyval[<NUM_LIT:1>]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>print ("<STR_LIT>")<EOL><DEDENT>gtr = GTR.standard(model, **kwargs)<EOL>infer_gtr = False<EOL><DEDENT>except:<EOL><INDENT>print ("<STR_LIT>")<EOL>gtr = GTR.standard('<STR_LIT>', alphabet='<STR_LIT>' if params.aa else '<STR_LIT>')<EOL>infer_gtr = False<EOL><DEDENT><DEDENT>return gtr<EOL>

parse the arguments referring to the GTR model and return a GTR structure


@classmethod<EOL><INDENT>def custom(cls, mu=<NUM_LIT:1.0>, pi=None, W=None, **kwargs):<DEDENT>

gtr = cls(**kwargs)<EOL>gtr.assign_rates(mu=mu, pi=pi, W=W)<EOL>return gtr<EOL>

Create a GTR model by specifying the matrix explicitly

Parameters
----------

 mu : float
    Substitution rate

 W : nxn matrix
    Substitution matrix

 pi : n vector
    Equilibrium frequencies

 **kwargs:
    Key word arguments to be passed

Keyword Args
------------

 alphabet : str
    Specify alphabet when applicable. If the alphabet specification is
    required, but no alphabet is specified, the nucleotide alphabet will be used as
    default.


if isinstance(distribution, interp1d):<EOL><INDENT>if is_neg_log:<EOL><INDENT>ymin = distribution.y.min()<EOL>log_prob = distribution.y-ymin<EOL><DEDENT>else:<EOL><INDENT>log_prob = -np.log(distribution.y)<EOL>log_prob -= log_prob.min()<EOL><DEDENT>xvals = distribution.x<EOL><DEDENT>elif isinstance(distribution, Distribution):<EOL><INDENT>xvals = distribution._func.x<EOL>log_prob = distribution._func.y<EOL><DEDENT>else:<EOL><INDENT>raise TypeError("<STR_LIT>"<EOL>"<STR_LIT>");<EOL><DEDENT>L = xvals.shape[<NUM_LIT:0>]<EOL>tmp = np.where(log_prob < <NUM_LIT>)[<NUM_LIT:0>]<EOL>x_l, x_u = tmp[<NUM_LIT:0>], tmp[-<NUM_LIT:1>]<EOL>if L < <NUM_LIT:2>:<EOL><INDENT>print ("<STR_LIT>")<EOL>return min(TINY_NUMBER, distribution.xmax - distribution.xmin)<EOL><DEDENT>else:<EOL><INDENT>return max(TINY_NUMBER, xvals[min(x_u+<NUM_LIT:1>,L-<NUM_LIT:1>)] - xvals[max(<NUM_LIT:0>,x_l-<NUM_LIT:1>)])<EOL><DEDENT>

Assess the width of the probability distribution. This returns
full-width-half-max


@classmethod<EOL><INDENT>def delta_function(cls, x_pos, weight=<NUM_LIT:1.>, min_width=MIN_INTEGRATION_PEAK):<DEDENT>

distribution = cls(x_pos,<NUM_LIT:0.>,is_log=True, min_width=min_width)<EOL>distribution.weight  = weight<EOL>return distribution<EOL>


self.tree.root.branch_length = <NUM_LIT><EOL>self.tree.root.mutation_length = self.tree.root.branch_length<EOL>self.tree.root.mutations = []<EOL>self.tree.ladderize()<EOL>self._prepare_nodes()<EOL>self._leaves_lookup = {node.name:node for node in self.tree.get_terminals()}<EOL>

Set link to parent and calculate distance to root for all tree nodes.
Should be run once the tree is read and after every rerooting,
topology change or branch length optimizations.


def optimize_branch_length(self, mode='<STR_LIT>', **kwargs):

self.logger("<STR_LIT>"%mode,<NUM_LIT:1>)<EOL>if (self.tree is None) or (self.aln is None):<EOL><INDENT>self.logger("<STR_LIT>", <NUM_LIT:0>)<EOL>return ttconf.ERROR<EOL><DEDENT>store_old_dist = False<EOL>if '<STR_LIT>' in kwargs:<EOL><INDENT>store_old_dist = kwargs['<STR_LIT>']<EOL><DEDENT>if mode=='<STR_LIT>':<EOL><INDENT>if not hasattr(self.tree.root, "<STR_LIT>"):<EOL><INDENT>self.infer_ancestral_sequences(marginal=True)<EOL><DEDENT><DEDENT>max_bl = <NUM_LIT:0><EOL>for node in self.tree.find_clades(order='<STR_LIT>'):<EOL><INDENT>if node.up is None: continue <EOL>if store_old_dist:<EOL><INDENT>node._old_length = node.branch_length<EOL><DEDENT>if mode=='<STR_LIT>':<EOL><INDENT>new_len = self.optimal_marginal_branch_length(node)<EOL><DEDENT>elif mode=='<STR_LIT>':<EOL><INDENT>new_len = self.optimal_branch_length(node)<EOL><DEDENT>else:<EOL><INDENT>self.logger("<STR_LIT>",<NUM_LIT:4>, warn=True)<EOL>new_len = node.branch_length<EOL><DEDENT>if new_len < <NUM_LIT:0>:<EOL><INDENT>continue<EOL><DEDENT>self.logger("<STR_LIT>"<EOL>"<STR_LIT>"%(node.branch_length, new_len, len(node.mutations)*self.one_mutation), <NUM_LIT:5>)<EOL>node.branch_length = new_len<EOL>node.mutation_length=new_len<EOL>max_bl = max(max_bl, new_len)<EOL><DEDENT>self.tree.root.up = None<EOL>self.tree.root.dist2root = <NUM_LIT:0.0><EOL>if max_bl><NUM_LIT> and mode=='<STR_LIT>':<EOL><INDENT>self.logger("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>", <NUM_LIT:0>, warn=True)<EOL><DEDENT>self._prepare_nodes()<EOL>return ttconf.SUCCESS<EOL>

Perform optimization for the branch lengths of the entire tree.
This method only does a single path and needs to be iterated.

**Note** this method assumes that each node stores information
about its sequence as numpy.array object (node.sequence attribute).
Therefore, before calling this method, sequence reconstruction with
either of the available models must be performed.

Parameters
----------

 mode : str
    Optimize branch length assuming the joint ML sequence assignment
    of both ends of the branch (:code:`joint`), or trace over all possible sequence
    assignments on both ends of the branch (:code:`marginal`) (slower, experimental).

 **kwargs :
    Keyword arguments

Keyword Args
------------

 verbose : int
    Output level

 store_old : bool
    If True, the old lengths will be saved in :code:`node._old_dist` attribute.
    Useful for testing, and special post-processing.


<EOL>nseq = len(self.aln)<EOL>inv_map = defaultdict(list)<EOL>for k,v in self.aln.items():<EOL><INDENT>for pos, bs in v.items():<EOL><INDENT>inv_map[pos].append(bs)<EOL><DEDENT><DEDENT>self.nonref_positions = np.sort(list(inv_map.keys()))<EOL>self.inferred_const_sites = []<EOL>ambiguous_char = self.gtr.ambiguous<EOL>nonref_const = []<EOL>nonref_alleles = []<EOL>ambiguous_const = []<EOL>variable_pos = []<EOL>for pos, bs in inv_map.items(): <EOL><INDENT>bases = "<STR_LIT>".join(np.unique(bs))<EOL>if len(bs) == nseq:<EOL><INDENT>if (len(bases)<=<NUM_LIT:2> and ambiguous_char in bases) or len(bases)==<NUM_LIT:1>:<EOL><INDENT>nonref_const.append(pos)<EOL>nonref_alleles.append(bases.replace(ambiguous_char, '<STR_LIT>'))<EOL>if ambiguous_char in bases: <EOL><INDENT>self.inferred_const_sites.append(pos)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>variable_pos.append(pos)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if bases==ambiguous_char:<EOL><INDENT>ambiguous_const.append(pos)<EOL>self.inferred_const_sites.append(pos) <EOL><DEDENT>else:<EOL><INDENT>variable_pos.append(pos)<EOL><DEDENT><DEDENT><DEDENT>refMod = np.array(list(self.ref))<EOL>refMod[nonref_const] = nonref_alleles<EOL>states = self.gtr.alphabet<EOL>refMod[variable_pos] = '<STR_LIT:.>'<EOL>reduced_alignment_const = []<EOL>alignment_patterns_const = {}<EOL>for base in states:<EOL><INDENT>p = base*nseq<EOL>pos = list(np.where(refMod==base)[<NUM_LIT:0>])<EOL>if len(pos):<EOL><INDENT>alignment_patterns_const[p] = [len(reduced_alignment_const), pos]<EOL>reduced_alignment_const.append(list(p))<EOL><DEDENT><DEDENT>return reduced_alignment_const, alignment_patterns_const, variable_pos<EOL>

prepare the dictionary specifying differences from a reference sequence
to construct the reduced alignment with variable sites only. NOTE:
    - sites can be constant but different from the reference
    - sites can be constant plus a ambiguous sites

assigns
-------
- self.nonref_positions: at least one sequence is different from ref

Returns
-------
reduced_alignment_const
    reduced alignment accounting for non-variable postitions

alignment_patterns_const
    dict pattern -> (pos in reduced alignment, list of pos in full alignment)

ariable_positions
    list of variable positions needed to construct remaining


state = self._fitch_intersect([k.state[pos] for k in node.clades])<EOL>if len(state) == <NUM_LIT:0>:<EOL><INDENT>state = np.concatenate([k.state[pos] for k in node.clades])<EOL><DEDENT>return state<EOL>

Determine the Fitch profile for a single character of the node's sequence.
The profile is essentially the intersection between the children's
profiles or, if the former is empty, the union of the profiles.

Parameters
----------

 node : PhyloTree.Clade:
    Internal node which the profiles are to be determined

 pos : int
    Position in the node's sequence which the profiles should
    be determinedf for.

Returns
-------
 state : numpy.array
    Fitch profile for the character at position pos of the given node.


return self._leaves_lookup<EOL>

The :code:`{leaf-name:leaf-node}` dictionary. It enables fast
search of a tree leaf object by its name.


def pairwise_intersect(arr1, arr2):<EOL><INDENT>s2 = set(arr2)<EOL>b3 = [val for val in arr1 if val in s2]<EOL>return b3<EOL><DEDENT>arrays = list(arrays) <EOL>N = len(arrays)<EOL>while N > <NUM_LIT:1>:<EOL><INDENT>arr1 = arrays.pop()<EOL>arr2 = arrays.pop()<EOL>arr = pairwise_intersect(arr1, arr2)<EOL>arrays.append(arr)<EOL>N = len(arrays)<EOL><DEDENT>return arrays[<NUM_LIT:0>]<EOL>

Find the intersection of any number of 1D arrays.
Return the sorted, unique values that are in all of the input arrays.
Adapted from numpy.lib.arraysetops.intersect1d


def dict_sequence(self, node, keep_var_ambigs=False):

seq = {}<EOL>node_seq = node.cseq<EOL>if keep_var_ambigs and hasattr(node, "<STR_LIT>") and node.is_terminal():<EOL><INDENT>node_seq = node.original_cseq<EOL><DEDENT>for pos in self.nonref_positions:<EOL><INDENT>cseqLoc = self.full_to_reduced_sequence_map[pos]<EOL>base = node_seq[cseqLoc]<EOL>if self.ref[pos] != base:<EOL><INDENT>seq[pos] = base<EOL><DEDENT><DEDENT>return seq<EOL>

For VCF-based TreeAnc objects, we do not want to store the entire
sequence on every node, as they could be large. Instead, this returns the dict
of variants & their positions for this sequence. This is used in place of
:py:meth:`treetime.TreeAnc.expanded_sequence` for VCF-based objects throughout TreeAnc. However, users can still
call :py:meth:`expanded_sequence` if they require the full sequence.

Parameters
----------
 node  : PhyloTree.Clade
    Tree node

Returns
-------
 seq : dict
    dict where keys are the basepair position (numbering from 0) and value is the variant call


return self._gtr<EOL>

The current GTR object.

:setter: Sets the GTR object passed in
:getter: Returns the current GTR object


return self._ref<EOL>

Get the str reference nucleotide sequence currently used by TreeAnc.
When having read alignment in from a VCF, this is what variants map to.

:setter: Sets the string reference sequence
:getter: Returns the string reference sequence


self.logger("<STR_LIT>",<NUM_LIT:2>)<EOL>for node in self.tree.find_clades():<EOL><INDENT>if node.up is None:<EOL><INDENT>continue<EOL><DEDENT>self._store_compressed_sequence_to_node(node)<EOL><DEDENT>self.logger("<STR_LIT>",<NUM_LIT:3>)<EOL>

Traverse the tree, and for each node store the compressed sequence pair.
**Note** sequence reconstruction should be performed prior to calling
this method.


self.logger("<STR_LIT>", <NUM_LIT:1>)<EOL>for node in self.tree.find_clades():<EOL><INDENT>if node.up is None or node.is_terminal():<EOL><INDENT>continue<EOL><DEDENT>if self.gtr.prob_t(node.up.cseq, node.cseq, <NUM_LIT:0.0>,<EOL>pattern_multiplicity=self.multiplicity) > <NUM_LIT:0.1>:<EOL><INDENT>node.up.clades = [k for k in node.up.clades if k != node] + node.clades<EOL>for clade in node.clades:<EOL><INDENT>clade.up = node.up<EOL><DEDENT><DEDENT><DEDENT>

If the branch length is less than the minimal value, remove the branch
from the tree. **Requires** ancestral sequence reconstruction


def expanded_sequence(self, node, include_additional_constant_sites=False):

if include_additional_constant_sites:<EOL><INDENT>L = self.seq_len<EOL><DEDENT>else:<EOL><INDENT>L = self.seq_len - self.additional_constant_sites<EOL><DEDENT>return node.cseq[self.full_to_reduced_sequence_map[:L]]<EOL>

Expand a nodes compressed sequence into the real sequence

Parameters
----------
node : PhyloTree.Clade
   Tree node

Returns
-------
seq : np.array
   Sequence as np.array of chars


def date_uncertainty_due_to_rate(self, node, interval=(<NUM_LIT>, <NUM_LIT>)):

if hasattr(node, "<STR_LIT>"):<EOL><INDENT>from scipy.special import erfinv<EOL>nsig = [np.sqrt(<NUM_LIT>)*erfinv(-<NUM_LIT:1.0> + <NUM_LIT>*x) if x*(<NUM_LIT:1.0>-x) else <NUM_LIT:0><EOL>for x in interval]<EOL>l,c,u = [x[<NUM_LIT:1>] for x in node.numdate_rate_variation]<EOL>return np.array([c + x*np.abs(y-c) for x,y in zip(nsig, (l,u))])<EOL><DEDENT>else:<EOL><INDENT>return None<EOL><DEDENT>

use previously calculated variation of the rate to estimate
        the uncertainty in a particular numdate due to rate variation.

        Parameters
        ----------
        node : PhyloTree.Clade
            node for which the confidence interval is to be calculated
        interval : tuple, optional
            Array of length two, or tuple, defining the bounds of the confidence interval


LH = <NUM_LIT:0><EOL>for node in self.tree.find_clades(order='<STR_LIT>'):  <EOL><INDENT>if node.up is None: <EOL><INDENT>continue<EOL><DEDENT>LH -= node.branch_length_interpolator(node.branch_length)<EOL><DEDENT>if self.aln:<EOL><INDENT>LH += self.gtr.sequence_logLH(self.tree.root.cseq, pattern_multiplicity=self.multiplicity)<EOL><DEDENT>return LH<EOL>

Return the likelihood of the data given the current branch length in the tree


def get_confidence_interval(self, node, interval = (<NUM_LIT>, <NUM_LIT>)):

rate_contribution = self.date_uncertainty_due_to_rate(node, interval)<EOL>if hasattr(node, "<STR_LIT>"):<EOL><INDENT>min_date, max_date = [self.date2dist.to_numdate(x) for x in<EOL>(node.marginal_pos_LH.xmax, node.marginal_pos_LH.xmin)]<EOL>if node.marginal_inverse_cdf=="<STR_LIT>":<EOL><INDENT>return np.array([node.numdate, node.numdate])<EOL><DEDENT>else:<EOL><INDENT>mutation_contribution = self.date2dist.to_numdate(node.marginal_inverse_cdf(np.array(interval))[::-<NUM_LIT:1>])<EOL><DEDENT><DEDENT>else:<EOL><INDENT>min_date, max_date = [-np.inf, np.inf]<EOL><DEDENT>return self.combine_confidence(node.numdate, (min_date, max_date),<EOL>c1=rate_contribution, c2=mutation_contribution)<EOL>

If temporal reconstruction was done using the marginal ML mode, the entire distribution of
times is available. This function determines the 90% (or other) confidence interval, defined as the
range where 5% of probability is below and above. Note that this does not necessarily contain
the highest probability position.
In absense of marginal reconstruction, it will return uncertainty based on rate
variation. If both are present, the wider interval will be returned.

Parameters
----------

 node : PhyloTree.Clade
    The node for which the confidence interval is to be calculated

 interval : tuple, list
    Array of length two, or tuple, defining the bounds of the confidence interval

Returns
-------

 confidence_interval : numpy array
    Array with two numerical dates delineating the confidence interval


if self.tree is None:<EOL><INDENT>self.logger("<STR_LIT>", <NUM_LIT:0>)<EOL>return ttconf.ERROR<EOL><DEDENT>bad_branch_counter = <NUM_LIT:0><EOL>for node in self.tree.find_clades(order='<STR_LIT>'):<EOL><INDENT>if node.name in self.date_dict:<EOL><INDENT>tmp_date = self.date_dict[node.name]<EOL>if np.isscalar(tmp_date) and np.isnan(tmp_date):<EOL><INDENT>self.logger("<STR_LIT>"%(node.name, str(tmp_date)), <NUM_LIT:2>, warn=True)<EOL>node.raw_date_constraint = None<EOL>node.bad_branch = True<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>tmp = np.mean(tmp_date)<EOL>node.raw_date_constraint = tmp_date<EOL>node.bad_branch = False<EOL><DEDENT>except:<EOL><INDENT>self.logger("<STR_LIT>"%(node.name, str(tmp_date)), <NUM_LIT:2>, warn=True)<EOL>node.raw_date_constraint = None<EOL>node.bad_branch = True<EOL><DEDENT><DEDENT><DEDENT>else: <EOL><INDENT>node.raw_date_constraint = None<EOL>if node.is_terminal():<EOL><INDENT>node.bad_branch = True<EOL><DEDENT>else:<EOL><INDENT>node.bad_branch = np.all([x.bad_branch for x in node])<EOL><DEDENT><DEDENT>if node.is_terminal() and node.bad_branch:<EOL><INDENT>bad_branch_counter += <NUM_LIT:1><EOL><DEDENT><DEDENT>if bad_branch_counter>self.tree.count_terminals()-<NUM_LIT:3>:<EOL><INDENT>self.logger("<STR_LIT>", <NUM_LIT:1>, warn=True)<EOL>return ttconf.ERROR<EOL><DEDENT>return ttconf.SUCCESS<EOL>

assign dates to nodes

        Returns
        -------
        str
            success/error code


self.tree.root._v=<NUM_LIT:0><EOL>for n in self.tree.get_nonterminals(order='<STR_LIT>'):<EOL><INDENT>for c in n:<EOL><INDENT>c._v = n._v + self.branch_value(c)<EOL><DEDENT><DEDENT>raw = np.array([(self.tip_value(n), n._v) for n in self.tree.get_terminals()<EOL>if self.tip_value(n) is not None])<EOL>return np.corrcoef(raw.T)[<NUM_LIT:0>,<NUM_LIT:1>]<EOL>

calculate standard explained variance

        Returns
        -------
        float
            r-value of the root-to-tip distance and time.
            independent of regression model, but dependent on root choice


for n in self.tree.get_nonterminals(order='<STR_LIT>'):<EOL><INDENT>n_leaves = len(n._ii)<EOL>if full_matrix: M = np.zeros((n_leaves, n_leaves), dtype=float)<EOL>r = np.zeros(n_leaves, dtype=float)<EOL>c_count = <NUM_LIT:0><EOL>for c in n:<EOL><INDENT>ssq = self.branch_variance(c)<EOL>nc = len(c._ii)<EOL>if c.is_terminal():<EOL><INDENT>if full_matrix:<EOL><INDENT>M[c_count, c_count] = <NUM_LIT:1.0>/ssq<EOL><DEDENT>r[c_count] = <NUM_LIT:1.0>/ssq<EOL><DEDENT>else:<EOL><INDENT>if full_matrix:<EOL><INDENT>M[c_count:c_count+nc, c_count:c_count+nc] = c.cinv - ssq*np.outer(c.r,c.r)/(<NUM_LIT:1>+ssq*c.s)<EOL><DEDENT>r[c_count:c_count+nc] = c.r/(<NUM_LIT:1>+ssq*c.s)<EOL><DEDENT>c_count += nc<EOL><DEDENT>if full_matrix: n.cinv = M<EOL>n.r = r <EOL>n.s = n.r.sum()<EOL><DEDENT>

recursion to calculate inverse covariance matrix

Parameters
----------
full_matrix : bool, optional
    if True, the entire inverse matrix is calculated. otherwise, only the weighing vector.


def __init__(self, tree_in, tip_value = None,<EOL>branch_value = None, branch_variance = None):

super(TreeRegression, self).__init__()<EOL>self.tree = tree_in<EOL>for li, l in enumerate(self.tree.get_terminals()):<EOL><INDENT>l._ii = np.array([li])<EOL><DEDENT>total_bl = <NUM_LIT:0><EOL>for n in self.tree.get_nonterminals(order='<STR_LIT>'):<EOL><INDENT>n._ii = np.concatenate([c._ii for c in n])<EOL>n._ii.sort()<EOL>for c in n:<EOL><INDENT>c.up=n<EOL>total_bl+=c.branch_length<EOL><DEDENT><DEDENT>self.tree.root.up=None<EOL>self.N = self.tree.root._ii.shape[<NUM_LIT:0>]<EOL>if tip_value is None:<EOL><INDENT>self.tip_value = lambda x:np.mean(x.numdate) if x.is_terminal() else None<EOL><DEDENT>else:<EOL><INDENT>self.tip_value = tip_value<EOL><DEDENT>if branch_value is None:<EOL><INDENT>self.branch_value = lambda x:x.branch_length<EOL><DEDENT>else:<EOL><INDENT>self.branch_value = branch_value<EOL><DEDENT>if branch_variance is None:<EOL><INDENT>self.branch_variance = lambda x:x.branch_length + <NUM_LIT>*total_bl/self.N<EOL><DEDENT>else:<EOL><INDENT>self.branch_variance = branch_variance<EOL><DEDENT>

Parameters
----------
 T : (Bio.Phylo.tree)
    Tree for which the covariances and regression
    are to be calculated.

 tip_value : (callable)
    function that for each tip returns the value to
    be used in the regression.

 branch_value : (callable)
    function that for each node of the tree returns
    the contribution of this branch to the value of
    the subtending tips.

 variance_function : (callable)
    function that for each node of the tree returns
    the accumulated variance


def optimal_reroot(self, force_positive=True, slope=None):

best_root = self.find_best_root(force_positive=force_positive, slope=slope)<EOL>best_node = best_root["<STR_LIT>"]<EOL>x = best_root["<STR_LIT>"]<EOL>if x<<NUM_LIT>:<EOL><INDENT>new_node = best_node<EOL><DEDENT>elif x><NUM_LIT:1.0>-<NUM_LIT>:<EOL><INDENT>new_node = best_node.up<EOL><DEDENT>else:<EOL><INDENT>new_node = Phylo.BaseTree.Clade()<EOL>new_node.branch_length = best_node.branch_length*(<NUM_LIT:1>-x)<EOL>new_node.up = best_node.up<EOL>new_node.clades = [best_node]<EOL>new_node.up.clades = [k if k!=best_node else new_node<EOL>for k in best_node.up.clades]<EOL>best_node.branch_length *= x<EOL>best_node.up = new_node<EOL><DEDENT>new_node.rtt_regression = best_root<EOL>self.tree.root_with_outgroup(new_node)<EOL>self.tree.ladderize()<EOL>for n in self.tree.get_nonterminals(order='<STR_LIT>'):<EOL><INDENT>for c in n:<EOL><INDENT>c.up=n<EOL><DEDENT><DEDENT>return best_root<EOL>

determine the best root and reroot the tree to this value.
Note that this can change the parent child relations of the tree
and values associated with branches rather than nodes
(e.g. confidence) might need to be re-evaluated afterwards

Parameters
----------
force_positive : bool, optional
    if True, the search for a root will only consider positive rate estimates

slope : float, optional
    if given, it will find the optimal root given a fixed rate. If slope==0, this
    corresponds to minimal root-to-tip variance rooting (min_dev)

Returns
-------
dict
    regression parameters


<EOL>M = np.zeros((self.N, self.N))<EOL>for n in self.tree.find_clades():<EOL><INDENT>if n == self.tree.root:<EOL><INDENT>continue<EOL><DEDENT>M[np.meshgrid(n._ii, n._ii)] += self.branch_variance(n)<EOL><DEDENT>return M<EOL>

calculate the covariance matrix of the tips assuming variance
has accumulated along branches of the tree accoriding to the
the provided
Returns
-------

 M : (np.array)
    covariance matrix with tips arranged standard transersal order.


self.recurse(full_matrix=True)<EOL>return self.tree.root.cinv<EOL>

Inverse of the covariance matrix

Returns
-------

 H : (np.array)
    inverse of the covariance matrix.


self._calculate_averages()<EOL>clock_model = base_regression(self.tree.root.Q, slope)<EOL>clock_model['<STR_LIT>'] = self.explained_variance()<EOL>return clock_model<EOL>

regress tip values against branch values

        Parameters
        ----------
        slope : None, optional
            if given, the slope isn't optimized

        Returns
        -------
        dict
            regression parameters


return (d2r-self.intercept)/self.clock_rate<EOL>

estimate the numerical date based on the distance to root.
-> crude dating of internal nodes


return abs_t / abs(self.clock_rate)<EOL>

Convert the time before present measured in branch length units to years


return (numeric_date() - numdate) * abs(self.clock_rate)<EOL>

Convert the numeric date to the branch-len scale


def F81(mu=<NUM_LIT:1.0>, pi=None, alphabet="<STR_LIT>", **kwargs):

if pi is None:<EOL><INDENT>pi=<NUM_LIT>*np.ones(<NUM_LIT:4>, dtype=float)<EOL><DEDENT>num_chars = len(alphabets[alphabet])<EOL>pi = np.array(pi, dtype=float)<EOL>if num_chars != len(pi) :<EOL><INDENT>pi = np.ones((num_chars, ), dtype=float)<EOL>print ("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>W = np.ones((num_chars,num_chars))<EOL>pi /= (<NUM_LIT:1.0> * np.sum(pi))<EOL>gtr = GTR(alphabet=alphabets[alphabet])<EOL>gtr.assign_rates(mu=mu, pi=pi, W=W)<EOL>return gtr<EOL>

Felsenstein 1981 model. Assumes non-equal concentrations across nucleotides,
but the transition rate between all states is assumed to be equal. See
Felsenstein (1981), J. Mol. Evol. 17  (6): 368–376. doi:10.1007/BF01734359
for details.

Current implementation of the model does not account for the gaps (treatment of
gaps as characters is possible if specify alphabet='nuc_gap').

Parameters
-----------

 mu : float
    Substitution rate

 pi : numpy.array
    Nucleotide concentrations

 alphabet : str
    Alphabet to use. POsiible values are: ['nuc', 'nuc_gap'] Default 'nuc', which discounts al gaps.
    'nuc_gap' alphabet enables treatmen of gaps as characters.


def K80(mu=<NUM_LIT:1.>, kappa=<NUM_LIT:0.1>, **kwargs):

num_chars = len(alphabets['<STR_LIT>'])<EOL>pi = np.ones(len(alphabets['<STR_LIT>']), dtype=float)/len(alphabets['<STR_LIT>'])<EOL>W = _create_transversion_transition_W(kappa)<EOL>gtr = GTR(alphabet=alphabets['<STR_LIT>'])<EOL>gtr.assign_rates(mu=mu, pi=pi, W=W)<EOL>return gtr<EOL>

Kimura 1980 model. Assumes equal concentrations across nucleotides, but
allows different rates between transitions and transversions. The ratio
of the transversion/transition rates is given by kappa parameter.
For more info, see
Kimura (1980),  J. Mol. Evol. 16 (2): 111–120. doi:10.1007/BF01731581.

Current implementation of the model does not account for the gaps.

Parameters
-----------

 mu : float
    Overall substitution rate

 kappa : float
    Ratio of transversion/transition rates


def HKY85(mu=<NUM_LIT:1.0>, pi=None, kappa=<NUM_LIT:0.1>, **kwargs):

if pi is None:<EOL><INDENT>pi=<NUM_LIT>*np.ones(<NUM_LIT:4>, dtype=float)<EOL><DEDENT>num_chars = len(alphabets['<STR_LIT>'])<EOL>if num_chars != pi.shape[<NUM_LIT:0>] :<EOL><INDENT>pi = np.ones((num_chars, ), dtype=float)<EOL>print ("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>W = _create_transversion_transition_W(kappa)<EOL>pi /= pi.sum()<EOL>gtr = GTR(alphabet=alphabets['<STR_LIT>'])<EOL>gtr.assign_rates(mu=mu, pi=pi, W=W)<EOL>return gtr<EOL>

Hasegawa, Kishino and Yano 1985 model. Allows different concentrations of the
nucleotides (as in F81) + distinguishes between transition/transversionsubstitutions
(similar to K80). Link:
Hasegawa, Kishino, Yano (1985), J. Mol. Evol. 22 (2): 160–174. doi:10.1007/BF02101694

Current implementation of the model does not account for the gaps

Parameters
-----------

 mu : float
    Substitution rate

 pi : numpy.array
    Nucleotide concentrations

 kappa : float
    Ratio of transversion/transition substitution rates


def optimal_t(self, seq_p, seq_ch, pattern_multiplicity=None, ignore_gaps=False):

seq_pair, multiplicity = self.compress_sequence_pair(seq_p, seq_ch,<EOL>pattern_multiplicity = pattern_multiplicity,<EOL>ignore_gaps=ignore_gaps)<EOL>return self.optimal_t_compressed(seq_pair, multiplicity)<EOL>

Find the optimal distance between the two sequences

Parameters
----------

 seq_p : character array
    Parent sequence

 seq_c : character array
    Child sequence

 pattern_multiplicity : numpy array
    If sequences are reduced by combining identical alignment patterns,
    these multplicities need to be accounted for when counting the number
    of mutations across a branch. If None, all pattern are assumed to
    occur exactly once.

 ignore_gaps : bool
    If True, ignore gaps in distance calculations


<EOL>tmpp = np.sqrt(self.Pi)<EOL>symQ = self.W*np.outer(tmpp, tmpp)<EOL>eigvals, eigvecs = np.linalg.eigh(symQ)<EOL>tmp_v = eigvecs.T*tmpp<EOL>one_norm = np.sum(np.abs(tmp_v), axis=<NUM_LIT:1>)<EOL>self.v = tmp_v.T/one_norm<EOL>self.v_inv = (eigvecs*one_norm).T/tmpp<EOL>self.eigenvals = eigvals<EOL>

Perform eigendecompositon of the rate matrix and stores the left- and right-
matrices to convert the sequence profiles to the GTR matrix eigenspace
and hence to speed-up the computations.


def prob_t_compressed(self, seq_pair, multiplicity, t, return_log=False):

if t<<NUM_LIT:0>:<EOL><INDENT>logP = -ttconf.BIG_NUMBER<EOL><DEDENT>else:<EOL><INDENT>tmp_eQT = self.expQt(t)<EOL>bad_indices=(tmp_eQT==<NUM_LIT:0>)<EOL>logQt = np.log(tmp_eQT + ttconf.TINY_NUMBER*(bad_indices))<EOL>logQt[np.isnan(logQt) | np.isinf(logQt) | bad_indices] = -ttconf.BIG_NUMBER<EOL>logP = np.sum(logQt[seq_pair[:,<NUM_LIT:1>], seq_pair[:,<NUM_LIT:0>]]*multiplicity)<EOL><DEDENT>return logP if return_log else np.exp(logP)<EOL>

Calculate the probability of observing a sequence pair at a distance t,
for compressed sequences

Parameters
----------

  seq_pair : numpy array
    :code:`np.array([(0,1), (2,2), ()..])` as indicies of
    pairs of aligned positions. (e.g. 'A'==0, 'C'==1 etc).
    This only lists all occuring parent-child state pairs, order is irrelevant

  multiplicity : numpy array
    The number of times a parent-child state pair is observed.
    This allows compression of the sequence representation

  t : float
    Length of the branch separating parent and child

  return_log : bool
    Whether or not to exponentiate the result


multi_site = len(self.Pi.shape)==<NUM_LIT:2><EOL>if multi_site:<EOL><INDENT>eq_freq_str = "<STR_LIT>"+str(np.round(self.average_rate,<NUM_LIT:6>))+'<STR_LIT:\n>'<EOL><DEDENT>else:<EOL><INDENT>eq_freq_str = "<STR_LIT>"+str(np.round(self.mu,<NUM_LIT:6>))+'<STR_LIT:\n>'<EOL><DEDENT>if not multi_site:<EOL><INDENT>eq_freq_str += "<STR_LIT>"<EOL>for a,p in zip(self.alphabet, self.Pi):<EOL><INDENT>eq_freq_str+='<STR_LIT:U+0020>'+str(a)+'<STR_LIT>'+str(np.round(p,<NUM_LIT:4>))+'<STR_LIT:\n>'<EOL><DEDENT><DEDENT>W_str = "<STR_LIT>"<EOL>W_str+='<STR_LIT:\t>'+'<STR_LIT:\t>'.join(map(str, self.alphabet))+'<STR_LIT:\n>'<EOL>for a,Wi in zip(self.alphabet, self.W):<EOL><INDENT>W_str+= '<STR_LIT:U+0020>'+str(a)+'<STR_LIT:\t>'+'<STR_LIT:\t>'.join([str(np.round(max(<NUM_LIT:0>,p),<NUM_LIT:4>)) for p in Wi])+'<STR_LIT:\n>'<EOL><DEDENT>if not multi_site:<EOL><INDENT>Q_str = "<STR_LIT>"<EOL>Q_str+='<STR_LIT:\t>'+'<STR_LIT:\t>'.join(map(str, self.alphabet))+'<STR_LIT:\n>'<EOL>for a,Qi in zip(self.alphabet, self.Q):<EOL><INDENT>Q_str+= '<STR_LIT:U+0020>'+str(a)+'<STR_LIT:\t>'+'<STR_LIT:\t>'.join([str(np.round(max(<NUM_LIT:0>,p),<NUM_LIT:4>)) for p in Qi])+'<STR_LIT:\n>'<EOL><DEDENT><DEDENT>return eq_freq_str + W_str + Q_str<EOL>

String representation of the GTR model for pretty printing


<EOL>self.Pi /= self.Pi.sum() <EOL>self.W += self.break_degen + self.break_degen.T<EOL>np.fill_diagonal(self.W, <NUM_LIT:0>)<EOL>Wdiag = -(self.Q).sum(axis=<NUM_LIT:0>)/self.Pi<EOL>np.fill_diagonal(self.W, Wdiag)<EOL>scale_factor = -np.sum(np.diagonal(self.Q)*self.Pi)<EOL>self.W /= scale_factor<EOL>if not fixed_mu:<EOL><INDENT>self.mu *= scale_factor<EOL><DEDENT>if (self.Q.sum(axis=<NUM_LIT:0>) < <NUM_LIT>).sum() <  self.alphabet.shape[<NUM_LIT:0>]: <EOL><INDENT>print ("<STR_LIT>", self.Q.sum(axis=<NUM_LIT:0>))<EOL>import ipdb; ipdb.set_trace()<EOL>raise ArithmeticError("<STR_LIT>")<EOL><DEDENT>

Check the main diagonal of Q and fix it in case it does not corresond
the definition of the rate matrix. Should be run every time when creating
custom GTR model.


def prob_t(self, seq_p, seq_ch, t, pattern_multiplicity = None,<EOL>return_log=False, ignore_gaps=True):

seq_pair, multiplicity = self.compress_sequence_pair(seq_p, seq_ch,<EOL>pattern_multiplicity=pattern_multiplicity, ignore_gaps=ignore_gaps)<EOL>return self.prob_t_compressed(seq_pair, multiplicity, t, return_log=return_log)<EOL>

Compute the probability to observe seq_ch (child sequence) after time t starting from seq_p
(parent sequence).

Parameters
----------

 seq_p : character array
    Parent sequence

 seq_c : character array
    Child sequence

 t : double
    Time (branch len) separating the profiles.

 pattern_multiplicity : numpy array
    If sequences are reduced by combining identical alignment patterns,
    these multplicities need to be accounted for when counting the number
    of mutations across a branch. If None, all pattern are assumed to
    occur exactly once.

 return_log : bool
    It True, return log-probability.

Returns
-------
 prob : np.array
    Resulting probability


eLambdaT = np.diag(self._exp_lt(t)) <EOL>Qs = self.v.dot(eLambdaT.dot(self.v_inv))   <EOL>return np.maximum(<NUM_LIT:0>,Qs)<EOL>

Parameters
----------

 t : float
    Time to propagate

Returns
--------

 expQt : numpy.array
    Matrix exponential of exo(Qt)


def run(self, root=None, infer_gtr=True, relaxed_clock=None, n_iqd = None,<EOL>resolve_polytomies=True, max_iter=<NUM_LIT:0>, Tc=None, fixed_clock_rate=None,<EOL>time_marginal=False, sequence_marginal=False, branch_length_mode='<STR_LIT>',<EOL>vary_rate=False, use_covariation=False, **kwargs):

<EOL>self.use_covariation = use_covariation<EOL>if (self.tree is None) or (self.aln is None and self.seq_len is None):<EOL><INDENT>self.logger("<STR_LIT>", <NUM_LIT:0>)<EOL>return ttconf.ERROR<EOL><DEDENT>if (self.aln is None):<EOL><INDENT>branch_length_mode='<STR_LIT:input>'<EOL><DEDENT>self._set_branch_length_mode(branch_length_mode)<EOL>seq_kwargs = {"<STR_LIT>":sequence_marginal or (self.branch_length_mode=='<STR_LIT>'),<EOL>"<STR_LIT>":"<STR_LIT:root>"}<EOL>tt_kwargs = {'<STR_LIT>':fixed_clock_rate, '<STR_LIT>':False}<EOL>tt_kwargs.update(kwargs)<EOL>seq_LH = <NUM_LIT:0><EOL>if "<STR_LIT>" in kwargs:<EOL><INDENT>seq_kwargs["<STR_LIT>"] = kwargs["<STR_LIT>"]<EOL><DEDENT>if "<STR_LIT>" in kwargs:<EOL><INDENT>time_marginal=kwargs["<STR_LIT>"]<EOL><DEDENT>if self.branch_length_mode=='<STR_LIT:input>':<EOL><INDENT>if self.aln:<EOL><INDENT>self.infer_ancestral_sequences(infer_gtr=infer_gtr, **seq_kwargs)<EOL>self.prune_short_branches()<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self.optimize_sequences_and_branch_length(infer_gtr=infer_gtr,<EOL>max_iter=<NUM_LIT:1>, prune_short=True, **seq_kwargs)<EOL><DEDENT>avg_root_to_tip = np.mean([x.dist2root for x in self.tree.get_terminals()])<EOL>if n_iqd or root=='<STR_LIT>':<EOL><INDENT>if "<STR_LIT>" in kwargs and kwargs["<STR_LIT>"]:<EOL><INDENT>plot_rtt=True<EOL><DEDENT>else:<EOL><INDENT>plot_rtt=False<EOL><DEDENT>reroot_mechanism = '<STR_LIT>' if root=='<STR_LIT>' else root<EOL>if self.clock_filter(reroot=reroot_mechanism, n_iqd=n_iqd, plot=plot_rtt)==ttconf.ERROR:<EOL><INDENT>return ttconf.ERROR<EOL><DEDENT><DEDENT>elif root is not None:<EOL><INDENT>if self.reroot(root=root)==ttconf.ERROR:<EOL><INDENT>return ttconf.ERROR<EOL><DEDENT><DEDENT>if self.branch_length_mode=='<STR_LIT:input>':<EOL><INDENT>if self.aln:<EOL><INDENT>self.infer_ancestral_sequences(**seq_kwargs)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self.optimize_sequences_and_branch_length(max_iter=<NUM_LIT:1>, prune_short=False,<EOL>**seq_kwargs)<EOL><DEDENT>self.logger("<STR_LIT>",<NUM_LIT:0>)<EOL>self.make_time_tree(**tt_kwargs)<EOL>if self.aln:<EOL><INDENT>seq_LH = self.tree.sequence_marginal_LH if seq_kwargs['<STR_LIT>'] else self.tree.sequence_joint_LH<EOL><DEDENT>self.LH =[[seq_LH, self.tree.positional_joint_LH, <NUM_LIT:0>]]<EOL>if root is not None and max_iter:<EOL><INDENT>if self.reroot(root='<STR_LIT>' if root=='<STR_LIT>' else root)==ttconf.ERROR:<EOL><INDENT>return ttconf.ERROR<EOL><DEDENT><DEDENT>niter = <NUM_LIT:0><EOL>ndiff = <NUM_LIT:0><EOL>need_new_time_tree=False<EOL>while niter < max_iter:<EOL><INDENT>self.logger("<STR_LIT>"%(niter+<NUM_LIT:1>,max_iter),<NUM_LIT:0>)<EOL>if Tc:<EOL><INDENT>if Tc=='<STR_LIT>' and niter<max_iter-<NUM_LIT:1>:<EOL><INDENT>tmpTc='<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>tmpTc=Tc<EOL><DEDENT>self.add_coalescent_model(tmpTc, **kwargs)<EOL>need_new_time_tree = True<EOL><DEDENT>if relaxed_clock:<EOL><INDENT>print("<STR_LIT>", relaxed_clock)<EOL>self.relaxed_clock(**relaxed_clock)<EOL>need_new_time_tree = True<EOL><DEDENT>n_resolved=<NUM_LIT:0><EOL>if resolve_polytomies:<EOL><INDENT>n_resolved = self.resolve_polytomies()<EOL>if n_resolved:<EOL><INDENT>self.prepare_tree()<EOL>if self.branch_length_mode!='<STR_LIT:input>': <EOL><INDENT>self.optimize_sequences_and_branch_length(prune_short=False,<EOL>max_iter=<NUM_LIT:0>, **seq_kwargs)<EOL><DEDENT>need_new_time_tree = True<EOL><DEDENT><DEDENT>if need_new_time_tree:<EOL><INDENT>self.make_time_tree(**tt_kwargs)<EOL>if self.aln:<EOL><INDENT>ndiff = self.infer_ancestral_sequences('<STR_LIT>',**seq_kwargs)<EOL><DEDENT><DEDENT>else: <EOL><INDENT>if self.aln:<EOL><INDENT>ndiff = self.infer_ancestral_sequences('<STR_LIT>',**seq_kwargs)<EOL><DEDENT>self.make_time_tree(**tt_kwargs)<EOL><DEDENT>self.tree.coalescent_joint_LH = self.merger_model.total_LH() if Tc else <NUM_LIT:0.0><EOL>if self.aln:<EOL><INDENT>seq_LH = self.tree.sequence_marginal_LH if seq_kwargs['<STR_LIT>'] else self.tree.sequence_joint_LH<EOL><DEDENT>self.LH.append([seq_LH, self.tree.positional_joint_LH, self.tree.coalescent_joint_LH])<EOL>niter+=<NUM_LIT:1><EOL>if ndiff==<NUM_LIT:0> and n_resolved==<NUM_LIT:0> and Tc!='<STR_LIT>':<EOL><INDENT>self.logger("<STR_LIT>",<NUM_LIT:0>)<EOL>break<EOL><DEDENT><DEDENT>if vary_rate:<EOL><INDENT>if type(vary_rate)==float:<EOL><INDENT>res = self.calc_rate_susceptibility(rate_std=vary_rate, params=tt_kwargs)<EOL><DEDENT>elif self.clock_model['<STR_LIT>']:<EOL><INDENT>res = self.calc_rate_susceptibility(params=tt_kwargs)<EOL><DEDENT>else:<EOL><INDENT>res = ttconf.ERROR<EOL><DEDENT>if res==ttconf.ERROR:<EOL><INDENT>self.logger("<STR_LIT>", <NUM_LIT:1>, warn=True)<EOL><DEDENT><DEDENT>if time_marginal:<EOL><INDENT>self.logger("<STR_LIT>", <NUM_LIT:0>)<EOL>tt_kwargs['<STR_LIT>']=time_marginal<EOL>self.make_time_tree(**tt_kwargs)<EOL><DEDENT>bad_branches =[n for n in self.tree.get_terminals()<EOL>if n.bad_branch and n.raw_date_constraint]<EOL>if bad_branches:<EOL><INDENT>self.logger("<STR_LIT>"<EOL>"<STR_LIT>",<NUM_LIT:0>,warn=True)<EOL>for n in bad_branches:<EOL><INDENT>self.logger("<STR_LIT>"%(n.name, str(n.raw_date_constraint), n.numdate),<NUM_LIT:0>,warn=True)<EOL><DEDENT><DEDENT>return ttconf.SUCCESS<EOL>

Run TreeTime reconstruction. Based on the input parameters, it divides
the analysis into semi-independent jobs and conquers them one-by-one,
gradually optimizing the tree given the temporal constarints and leaf
node sequences.

Parameters
----------
root : str
   Try to find better root position on a given tree. If string is passed,
   the root will be searched according to the specified method. If none,
   use tree as-is.

   See :py:meth:`treetime.TreeTime.reroot` for available rooting methods.

infer_gtr : bool
   If True, infer GTR model

relaxed_clock : dic
   If not None, use autocorrelated molecular clock model. Specify the
   clock parameters as :code:`{slack:<slack>, coupling:<coupling>}` dictionary.

n_iqd : int
   If not None, filter tree nodes which do not obey the molecular clock
   for the particular tree. The nodes, which deviate more than
   :code:`n_iqd` interquantile intervals from the molecular clock
   regression will be marked as 'BAD' and not used in the TreeTime
   analysis

resolve_polytomies : bool
   If True, attempt to resolve multiple mergers

max_iter : int
   Maximum number of iterations to optimize the tree

Tc : float, str
   If not None, use coalescent model to correct the branch lengths by
   introducing merger costs.

   If Tc is float, it is interpreted as the coalescence time scale

   If Tc is str, it should be one of (:code:`opt`, :code:`const`, :code:`skyline`)

fixed_clock_rate : float
   Fixed clock rate to be used. If None, infer clock rate from the molecular clock.

time_marginal : bool
   If True, perform a final round of marginal reconstruction of the node's positions.

sequence_marginal : bool, optional
    use marginal reconstruction for ancestral sequences

branch_length_mode : str
   Should be one of: :code:`joint`, :code:`marginal`, :code:`input`.

   If 'input', rely on the branch lengths in the input tree and skip directly
   to the maximum-likelihood ancestral sequence reconstruction.
   Otherwise, perform preliminary sequence reconstruction using parsimony
   algorithm and do branch length optimization

vary_rate : bool or float, optional
    redo the time tree estimation for rates +/- one standard deviation.
    if a float is passed, it is interpreted as standard deviation,
    otherwise this standard deviation is estimated from the root-to-tip regression

use_covariation : bool, optional
    default False, if False, rate estimates will be performed using simple
    regression ignoring phylogenetic covaration between nodes.

**kwargs
   Keyword arguments needed by the downstream functions

Returns
-------
TreeTime error/succces code : str
    return value depending on success or error


def _find_best_root(self, covariation=True, force_positive=True, slope=<NUM_LIT:0>, **kwarks):

for n in self.tree.find_clades():<EOL><INDENT>n.branch_length=n.mutation_length<EOL><DEDENT>self.logger("<STR_LIT>",<NUM_LIT:2>)<EOL>Treg = self.setup_TreeRegression(covariation=covariation)<EOL>return Treg.optimal_reroot(force_positive=force_positive, slope=slope)['<STR_LIT>']<EOL>

Determine the node that, when the tree is rooted on this node, results
in the best regression of temporal constraints and root to tip distances.

Parameters
----------

 infer_gtr : bool
    If True, infer new GTR model after re-root

 covariation : bool
    account for covariation structure when rerooting the tree

 force_positive : bool
    only accept positive evolutionary rate estimates when rerooting the tree


def plot_vs_years(tt, step = None, ax=None, confidence=None, ticks=True, **kwargs):

import matplotlib.pyplot as plt<EOL>tt.branch_length_to_years()<EOL>nleafs = tt.tree.count_terminals()<EOL>if ax is None:<EOL><INDENT>fig = plt.figure(figsize=(<NUM_LIT:12>,<NUM_LIT:10>))<EOL>ax = plt.subplot(<NUM_LIT>)<EOL><DEDENT>else:<EOL><INDENT>fig = None<EOL><DEDENT>if "<STR_LIT>" not in kwargs:<EOL><INDENT>kwargs["<STR_LIT>"] = lambda x:x.name if (x.is_terminal() and nleafs<<NUM_LIT:30>) else "<STR_LIT>"<EOL><DEDENT>Phylo.draw(tt.tree, axes=ax, **kwargs)<EOL>offset = tt.tree.root.numdate - tt.tree.root.branch_length<EOL>date_range = np.max([n.numdate for n in tt.tree.get_terminals()])-offset<EOL>if step is None or (step><NUM_LIT:0> and date_range/step><NUM_LIT:100>):<EOL><INDENT>step = <NUM_LIT:10>**np.floor(np.log10(date_range))<EOL>if date_range/step<<NUM_LIT:2>:<EOL><INDENT>step/=<NUM_LIT:5><EOL><DEDENT>elif date_range/step<<NUM_LIT:5>:<EOL><INDENT>step/=<NUM_LIT:2><EOL><DEDENT>step = max(<NUM_LIT:1.0>/<NUM_LIT:12>,step)<EOL><DEDENT>if step:<EOL><INDENT>dtick = step<EOL>min_tick = step*(offset//step)<EOL>extra = dtick if dtick<date_range else dtick<EOL>tick_vals = np.arange(min_tick, min_tick+date_range+extra, dtick)<EOL>xticks = tick_vals - offset<EOL><DEDENT>else:<EOL><INDENT>xticks = ax.get_xticks()<EOL>dtick = xticks[<NUM_LIT:1>]-xticks[<NUM_LIT:0>]<EOL>shift = offset - dtick*(offset//dtick)<EOL>xticks -= shift<EOL>tick_vals = [x+offset-shift for x in xticks]<EOL><DEDENT>ax.set_xticks(xticks)<EOL>ax.set_xticklabels(map(str, tick_vals))<EOL>ax.set_xlabel('<STR_LIT>')<EOL>ax.set_ylabel('<STR_LIT>')<EOL>ax.set_xlim((<NUM_LIT:0>,date_range))<EOL>if step:<EOL><INDENT>ylim = ax.get_ylim()<EOL>xlim = ax.get_xlim()<EOL>from matplotlib.patches import Rectangle<EOL>for yi,year in enumerate(np.arange(np.floor(tick_vals[<NUM_LIT:0>]), tick_vals[-<NUM_LIT:1>]+<NUM_LIT>, step)):<EOL><INDENT>pos = year - offset<EOL>r = Rectangle((pos, ylim[<NUM_LIT:1>]-<NUM_LIT:5>),<EOL>step, ylim[<NUM_LIT:0>]-ylim[<NUM_LIT:1>]+<NUM_LIT:10>,<EOL>facecolor=[<NUM_LIT>+<NUM_LIT:0.1>*(<NUM_LIT:1>+yi%<NUM_LIT:2>)] * <NUM_LIT:3>,<EOL>edgecolor=[<NUM_LIT:1>,<NUM_LIT:1>,<NUM_LIT:1>])<EOL>ax.add_patch(r)<EOL>if year in tick_vals and pos>=xlim[<NUM_LIT:0>] and pos<=xlim[<NUM_LIT:1>] and ticks:<EOL><INDENT>label_str = str(step*(year//step)) if step<<NUM_LIT:1> else  str(int(year))<EOL>ax.text(pos,ylim[<NUM_LIT:0>]-<NUM_LIT>*(ylim[<NUM_LIT:1>]-ylim[<NUM_LIT:0>]), label_str,<EOL>horizontalalignment='<STR_LIT>')<EOL><DEDENT><DEDENT>ax.set_axis_off()<EOL><DEDENT>if confidence:<EOL><INDENT>tree_layout(tt.tree)<EOL>if not hasattr(tt.tree.root, "<STR_LIT>"):<EOL><INDENT>print("<STR_LIT>")<EOL>return ttconf.ERROR<EOL><DEDENT>elif type(confidence) is float:<EOL><INDENT>cfunc = tt.get_max_posterior_region<EOL><DEDENT>elif len(confidence)==<NUM_LIT:2>:<EOL><INDENT>cfunc = tt.get_confidence_interval<EOL><DEDENT>else:<EOL><INDENT>print("<STR_LIT>")<EOL>return ttconf.ERROR<EOL><DEDENT>for n in tt.tree.find_clades():<EOL><INDENT>pos = cfunc(n, confidence)<EOL>ax.plot(pos-offset, np.ones(len(pos))*n.ypos, lw=<NUM_LIT:3>, c=(<NUM_LIT:0.5>,<NUM_LIT:0.5>,<NUM_LIT:0.5>))<EOL><DEDENT><DEDENT>return fig, ax<EOL>

Converts branch length to years and plots the time tree on a time axis.

Parameters
----------
 tt : TreeTime object
    A TreeTime instance after a time tree is inferred

 step : int
    Width of shaded boxes indicating blocks of years. Will be inferred if not specified.
    To switch off drawing of boxes, set to 0

 ax : matplotlib axes
    Axes to be used to plot, will create new axis if None

 confidence : tuple, float
    Draw confidence intervals. This assumes that marginal time tree inference was run.
    Confidence intervals are either specified as an interval of the posterior distribution
    like (0.05, 0.95) or as the weight of the maximal posterior region , e.g. 0.9

 **kwargs : dict
    Key word arguments that are passed down to Phylo.draw


if branch_length_mode in ['<STR_LIT>', '<STR_LIT>', '<STR_LIT:input>']:<EOL><INDENT>self.branch_length_mode = branch_length_mode<EOL><DEDENT>elif self.aln:<EOL><INDENT>bl_dis = [n.branch_length for n in self.tree.find_clades() if n.up]<EOL>max_bl = np.max(bl_dis)<EOL>if max_bl><NUM_LIT:0.1>:<EOL><INDENT>bl_mode = '<STR_LIT:input>'<EOL><DEDENT>else:<EOL><INDENT>bl_mode = '<STR_LIT>'<EOL><DEDENT>self.logger("<STR_LIT>"%(max_bl, bl_mode),<NUM_LIT:1>)<EOL>self.branch_length_mode = bl_mode<EOL><DEDENT>else:<EOL><INDENT>self.branch_length_mode = '<STR_LIT:input>'<EOL><DEDENT>

if branch_length mode is not explicitly set, set according to
empirical branch length distribution in input tree

Parameters
----------

 branch_length_mode : str, 'input', 'joint', 'marginal'
    if the maximal branch length in the tree is longer than 0.05, this will
    default to 'input'. Otherwise set to 'joint'


result = False<EOL>self.setContext("<STR_LIT>")<EOL>try:<EOL><INDENT>if len(password) != <NUM_LIT:8>:<EOL><INDENT>self.writeCmdMsg("<STR_LIT>")<EOL>self.setContext("<STR_LIT>")<EOL>return result<EOL><DEDENT>if not self.request(False):<EOL><INDENT>self.writeCmdMsg("<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>if not self.serialCmdPwdAuth(password):<EOL><INDENT>self.writeCmdMsg("<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>req_str = "<STR_LIT>" + binascii.hexlify(str(<NUM_LIT:0>).zfill(<NUM_LIT:6>)) + "<STR_LIT>"<EOL>req_str += self.calc_crc16(req_str[<NUM_LIT:2>:].decode("<STR_LIT>"))<EOL>self.m_serial_port.write(req_str.decode("<STR_LIT>"))<EOL>if self.m_serial_port.getResponse(self.getContext()).encode("<STR_LIT>") == "<STR_LIT>":<EOL><INDENT>self.writeCmdMsg("<STR_LIT>")<EOL>result = True<EOL><DEDENT><DEDENT><DEDENT>self.serialPostEnd()<EOL><DEDENT>except:<EOL><INDENT>ekm_log(traceback.format_exc(sys.exc_info()))<EOL><DEDENT>self.setContext("<STR_LIT>")<EOL>return result<EOL>

Serial call zero max demand (Dash Now button)

        Args:
            password (str): Optional password

        Returns:
            bool: True on completion with ACK.


result = namedtuple("<STR_LIT:result>", ["<STR_LIT>", "<STR_LIT>"])<EOL>result.Weekend = self.m_hldy["<STR_LIT>"][MeterData.StringValue]<EOL>result.Holiday = self.m_hldy["<STR_LIT>"][MeterData.StringValue]<EOL>return result<EOL>

extract holiday and weekend :class:`~ekmmeters.Schedule` from meter object buffer.

        Returns:
            tuple: Holiday and weekend :class:`~ekmmeters.Schedule` values, as strings.

            ======= ======================================
            Holiday :class:`~ekmmeters.Schedule` as string
            Weekend :class:`~ekmmeters.Schedule` as string
            ======= ======================================


try:<EOL><INDENT>self.m_ser = serial.Serial(port=self.m_ttyport,<EOL>baudrate=self.m_baudrate,<EOL>timeout=<NUM_LIT:0>,<EOL>parity=serial.PARITY_EVEN,<EOL>stopbits=serial.STOPBITS_ONE,<EOL>bytesize=serial.SEVENBITS,<EOL>rtscts=False)<EOL>ekm_log("<STR_LIT>" + serial.VERSION)<EOL>ekm_log("<STR_LIT>" + self.m_ttyport)<EOL>ekm_log("<STR_LIT>" + str(self.m_baudrate))<EOL>time.sleep(self.m_init_wait)<EOL>return True<EOL><DEDENT>except:<EOL><INDENT>ekm_log(traceback.format_exc(sys.exc_info()))<EOL><DEDENT>return False<EOL>

Required initialization call, wraps pyserial constructor.


self.m_connection_string = connection_string<EOL>pass<EOL>

Setter for connection string.
        Args:
            connection_string (str): Connection string.


ekm_log("<STR_LIT>")<EOL>empty  = SerialBlock()<EOL>return empty<EOL>

Required override to fetch the read serial block.

        Returns:
            SerialBlock: Every supported field (A or A+B, includes all fields)


d = {}<EOL>for idx, col in enumerate(cursor.description):<EOL><INDENT>val = row[idx]<EOL>name = col[<NUM_LIT:0>]<EOL>if name == Field.Time_Stamp:<EOL><INDENT>d[col[<NUM_LIT:0>]] = str(val)<EOL>continue<EOL><DEDENT>if name == "<STR_LIT>" or name == "<STR_LIT>":  <EOL><INDENT>continue<EOL><DEDENT>if name not in self.m_all_fields:<EOL><INDENT>continue<EOL><DEDENT>if (str(val) != "<STR_LIT:None>") and ((val > <NUM_LIT:0>) or (val < <NUM_LIT:0>)):<EOL><INDENT>d[name] = str(val)<EOL><DEDENT><DEDENT>return d<EOL>

Sqlite callback accepting the cursor and the original row as a tuple.

        Simple return of JSON safe types.

        Args:
            cursor (sqlite cursor):  Original cursory
            row (sqlite row tuple): Original row.

        Returns:
            dict: modified row.


ret = namedtuple("<STR_LIT>", ["<STR_LIT>", Field.kWh_Tariff_1, Field.kWh_Tariff_2, Field.kWh_Tariff_3,<EOL>Field.kWh_Tariff_4, Field.kWh_Tot, Field.Rev_kWh_Tariff_1,<EOL>Field.Rev_kWh_Tariff_2, Field.Rev_kWh_Tariff_3,<EOL>Field.Rev_kWh_Tariff_4, Field.Rev_kWh_Tot])<EOL>month += <NUM_LIT:1><EOL>ret.Month = str(month)<EOL>if (month < <NUM_LIT:1>) or (month > Extents.Months):<EOL><INDENT>ret.kWh_Tariff_1 = ret.kWh_Tariff_2 = ret.kWh_Tariff_3 = ret.kWh_Tariff_4 = str(<NUM_LIT:0>)<EOL>ret.Rev_kWh_Tariff_1 = ret.Rev_kWh_Tariff_2 = ret.Rev_kWh_Tariff_3 = ret.Rev_kWh_Tariff_4 = str(<NUM_LIT:0>)<EOL>ret.kWh_Tot = ret.Rev_kWh_Tot = str(<NUM_LIT:0>)<EOL>ekm_log("<STR_LIT>" + str(month))<EOL>return ret<EOL><DEDENT>base_str = "<STR_LIT>" + str(month) + "<STR_LIT:_>"<EOL>ret.kWh_Tariff_1 = self.m_mons[base_str + "<STR_LIT>"][MeterData.StringValue]<EOL>ret.kWh_Tariff_2 = self.m_mons[base_str + "<STR_LIT>"][MeterData.StringValue]<EOL>ret.kWh_Tariff_3 = self.m_mons[base_str + "<STR_LIT>"][MeterData.StringValue]<EOL>ret.kWh_Tariff_4 = self.m_mons[base_str + "<STR_LIT>"][MeterData.StringValue]<EOL>ret.kWh_Tot = self.m_mons[base_str + "<STR_LIT>"][MeterData.StringValue]<EOL>ret.Rev_kWh_Tariff_1 = self.m_rev_mons[base_str + "<STR_LIT>"][MeterData.StringValue]<EOL>ret.Rev_kWh_Tariff_2 = self.m_rev_mons[base_str + "<STR_LIT>"][MeterData.StringValue]<EOL>ret.Rev_kWh_Tariff_3 = self.m_rev_mons[base_str + "<STR_LIT>"][MeterData.StringValue]<EOL>ret.Rev_kWh_Tariff_4 = self.m_rev_mons[base_str + "<STR_LIT>"][MeterData.StringValue]<EOL>ret.Rev_kWh_Tot = self.m_rev_mons[base_str + "<STR_LIT>"][MeterData.StringValue]<EOL>return ret<EOL>

Extract the tariff for a single month from the meter object buffer.

        Args:
            month (int):  A :class:`~ekmmeters.Months` value or range(Extents.Months).

        Returns:
            tuple: The eight tariff period totals for month. The return tuple breaks out as follows:

            ================= ======================================
            kWh_Tariff_1      kWh for tariff period 1 over month.
            kWh_Tariff_2      kWh for tariff period 2 over month
            kWh_Tariff_3      kWh for tariff period 3 over month
            kWh_Tariff_4      kWh for tariff period 4 over month
            kWh_Tot           Total kWh over requested month
            Rev_kWh_Tariff_1  Rev kWh for tariff period 1 over month
            Rev_kWh_Tariff_3  Rev kWh for tariff period 2 over month
            Rev_kWh_Tariff_3  Rev kWh for tariff period 3 over month
            Rev_kWh_Tariff_4  Rev kWh for tariff period 4 over month
            Rev_kWh_Tot       Total Rev kWh over requested month
            ================= ======================================


return self.m_meter_address<EOL>

Getter for meter object 12 character address.

        Returns:
            str: 12 character address on front of meter


result = "<STR_LIT>"<EOL>if fld_name in self.m_req:<EOL><INDENT>result = self.m_req[fld_name][MeterData.StringValue]<EOL><DEDENT>else:<EOL><INDENT>ekm_log("<STR_LIT>" + fld_name)<EOL><DEDENT>return result<EOL>

Return :class:`~ekmmeters.Field` content, scaled and formatted.

        Args:
            fld_name (str): A `:class:~ekmmeters.Field` value which is on your meter.

        Returns:
            str: String value (scaled if numeric) for the field.


if meter_db:<EOL><INDENT>meter_db.dbInsert(self.m_req, self.m_raw_read_a, self.m_raw_read_b)<EOL><DEDENT>else:<EOL><INDENT>ekm_log("<STR_LIT>")<EOL><DEDENT>pass<EOL>

Insert to :class:`~ekmmeters.MeterDB`  subclass.

        Please note MeterDB subclassing is only for simplest-case.

        Args:
            meter_db (MeterDB): Instance of subclass of MeterDB.


work_context = self.getContext()<EOL>self.setContext("<STR_LIT>")<EOL>self.m_serial_port.write("<STR_LIT>".decode("<STR_LIT>") + self.m_meter_address + "<STR_LIT>".decode("<STR_LIT>"))<EOL>self.m_raw_read_b = self.m_serial_port.getResponse(self.getContext())<EOL>unpacked_read_b = self.unpackStruct(self.m_raw_read_b, self.m_blk_b)<EOL>self.convertData(unpacked_read_b, self.m_blk_b, self.m_kwh_precision)<EOL>self.m_b_crc = self.crcMeterRead(self.m_raw_read_b, self.m_blk_b)<EOL>self.setContext(work_context)<EOL>return self.m_b_crc<EOL>

Issue a B read on V4 meter.

        Returns:
            bool: True if CRC match at end of call.


ekm_log("<STR_LIT>" + self.getContext() + "<STR_LIT>" + msg)<EOL>self.m_command_msg = msg<EOL>

Internal method to set the command result string.

        Args:
            msg (str): Message built during command.


count = <NUM_LIT:0><EOL>for fld in self.m_all_fields:<EOL><INDENT>fld_type = self.m_all_fields[fld][MeterData.TypeValue]<EOL>fld_len = self.m_all_fields[fld][MeterData.SizeValue]<EOL>qry_spec = self.mapTypeToSql(fld_type, fld_len)<EOL>if count > <NUM_LIT:0>:<EOL><INDENT>qry_str += "<STR_LIT>"<EOL><DEDENT>qry_str = qry_str + '<STR_LIT:U+0020>' + fld + '<STR_LIT:U+0020>' + qry_spec<EOL>count += <NUM_LIT:1><EOL><DEDENT>qry_str += ("<STR_LIT>" + Field.Time_Stamp + "<STR_LIT>" +<EOL>"<STR_LIT>" +<EOL>"<STR_LIT>")<EOL>return qry_str<EOL>

Return query portion below CREATE.
        Args:
            qry_str (str): String as built.

        Returns:
            string: Passed string with fields appended.


self.m_observers.append(observer)<EOL>pass<EOL>

Place an observer in the meter update() chain.

        Args:
            observer (MeterObserver): Subclassed MeterObserver.


return self.m_ttyport<EOL>

Getter for serial port name

        Returns:
            string: name of serial port (ex: 'COM3', '/dev/ttyS0')


empty_return = SerialBlock()<EOL>if period_group == ReadSchedules.Schedules_1_To_4:<EOL><INDENT>return self.m_schd_1_to_4<EOL><DEDENT>elif period_group == ReadSchedules.Schedules_5_To_6:<EOL><INDENT>return self.m_schd_5_to_6<EOL><DEDENT>else:<EOL><INDENT>return empty_return<EOL><DEDENT>

Return the requested tariff schedule :class:`~ekmmeters.SerialBlock` for meter.

        Args:
            period_group (int):  A :class:`~ekmmeters.ReadSchedules` value.

        Returns:
            SerialBlock: The requested tariff schedules for meter.


if (len(self.m_context) == <NUM_LIT:0>) and (len(context_str) >= <NUM_LIT:7>):<EOL><INDENT>if context_str[<NUM_LIT:0>:<NUM_LIT:7>] != "<STR_LIT>":<EOL><INDENT>ekm_log("<STR_LIT>" + context_str)<EOL><DEDENT><DEDENT>self.m_context = context_str<EOL>

Set context string for serial command.  Private setter.

        Args:
            context_str (str): Command specific string.


result = False<EOL>try:<EOL><INDENT>req_start = "<STR_LIT>" + binascii.hexlify(password_str) + "<STR_LIT>"<EOL>req_crc = self.calc_crc16(req_start[<NUM_LIT:2>:].decode("<STR_LIT>"))<EOL>req_str = req_start + req_crc<EOL>self.m_serial_port.write(req_str.decode("<STR_LIT>"))<EOL>if self.m_serial_port.getResponse(self.getContext()).encode("<STR_LIT>") == "<STR_LIT>":<EOL><INDENT>ekm_log("<STR_LIT>" + self.getContext() + "<STR_LIT:)>")<EOL>result = True<EOL><DEDENT>else:<EOL><INDENT>ekm_log("<STR_LIT>" + self.getContext() + "<STR_LIT:)>")<EOL><DEDENT><DEDENT>except:<EOL><INDENT>ekm_log("<STR_LIT>" + self.getContext() + "<STR_LIT:)>")<EOL>ekm_log(traceback.format_exc(sys.exc_info()))<EOL><DEDENT>return result<EOL>

Password step of set commands

        This method is normally called within another serial command, so it
        does not issue a termination string.  Any default password is set
        in the caller parameter list, never here.

        Args:
            password_str (str): Required password.

        Returns:
            bool: True on completion and ACK.


self.m_serial_port = serial_port<EOL>pass<EOL>

Attach required :class:`~ekmmeters.SerialPort`.

        Args:
            serial_port (SerialPort): Serial port object, does not need to be initialized.


result = False<EOL>self.setContext("<STR_LIT>")<EOL>try:<EOL><INDENT>if not self.requestA():<EOL><INDENT>self.writeCmdMsg("<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>if not self.serialCmdPwdAuth(password):<EOL><INDENT>self.writeCmdMsg("<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>req_str = "<STR_LIT>"<EOL>req_str += self.calc_crc16(req_str[<NUM_LIT:2>:].decode("<STR_LIT>"))<EOL>self.m_serial_port.write(req_str.decode("<STR_LIT>"))<EOL>if self.m_serial_port.getResponse(self.getContext()).encode("<STR_LIT>") == "<STR_LIT>":<EOL><INDENT>self.writeCmdMsg("<STR_LIT>")<EOL>result = True<EOL><DEDENT><DEDENT><DEDENT>self.serialPostEnd()<EOL><DEDENT>except:<EOL><INDENT>ekm_log(traceback.format_exc(sys.exc_info()))<EOL><DEDENT>self.setContext("<STR_LIT>")<EOL>return result<EOL>

Serial call to zero resettable kWh registers.

        Args:
            password (str): Optional password.

        Returns:
            bool: True on completion and ACK.


view_str = output.encode('<STR_LIT:ascii>', '<STR_LIT:ignore>')<EOL>if (len(view_str) > <NUM_LIT:0>):<EOL><INDENT>self.m_ser.write(view_str)<EOL>self.m_ser.flush()<EOL>self.m_ser.reset_input_buffer()<EOL>time.sleep(self.m_force_wait)<EOL><DEDENT>pass<EOL>

Passthrough for pyserial Serial.write().

        Args:
            output (str): Block to write to port


Required override to attach the port to the meter.

        Args:
            serial_port (SerialPort): Declared serial port.  Does not need to be initialized.


super(IntervalObserver, self).__init__()<EOL>self.m_interval = interval<EOL>self.m_summary = SerialBlock()<EOL>pass<EOL>

Args:
    interval (int): Interval to summarize


def __init__(self, ttyport, baudrate=<NUM_LIT>, force_wait = <NUM_LIT:0.1>):

self.m_ttyport = ttyport<EOL>self.m_baudrate = baudrate<EOL>self.m_ser = None<EOL>self.m_fd = None<EOL>self.m_max_waits = <NUM_LIT:100><EOL>self.m_wait_sleep = <NUM_LIT><EOL>self.m_force_wait = force_wait<EOL>self.m_init_wait = <NUM_LIT><EOL>pass<EOL>

Args:
    ttyport (str): port name, ex 'COM3' '/dev/ttyUSB0'
    baudrate (int): optional, 9600 default and recommended
    force_wait(float) : optional post commnd sleep, if required


ekm_log("<STR_LIT>" + self.m_context + "<STR_LIT:)>")<EOL>self.m_serial_port.write("<STR_LIT>".decode("<STR_LIT>"))<EOL>pass<EOL>

Post termination code to implicitly current meter.


self.m_connection_string = connection_string<EOL>self.m_all_fields = SerialBlock()<EOL>self.combineAB()<EOL>pass<EOL>

Args:
    connection_string (str): database appropriate connection string