Пример #1
0
 def setVector(self, vector=None):
     self.__vector__ = None
     if vector is None:
         try:
             self.__vector__ = list(\
                     array(self.__atoms__[1].position) - \
                     array(self.__atoms__[0].position)\
                     )
         except AttributeError, msg:
             loki.debug('Bond.setVector(): ' + repr(msg))
Пример #2
0
 def setVector(self, vector=None):
     self.__vector__ = None
     if vector is None:
         try:
             self.__vector__ = list(\
                     array(self.__atoms__[1].position) - \
                     array(self.__atoms__[0].position)\
                     )
         except AttributeError, msg:
             loki.debug('Bond.setVector(): ' + repr(msg))
Пример #3
0
 def getAverage(self, normalise=False):
     r = zeros((3), float)
     for bond in self.__bonds__:
         v = bond.getVector()
         if v:
             loki.debug('v=' + repr(v))
             r += array(v)
     if normalise:
         r /= sqrt(sum(r**2))
     else:
         r /= float(len(self))
     return r
Пример #4
0
 def getAverage(self, normalise=False):
     r = zeros((3), float)
     for bond in self.__bonds__:
         v = bond.getVector()
         if v:
             loki.debug('v=' + repr(v))
             r += array(v)
     if normalise:
         r /= sqrt(sum(r**2))
     else:
         r /= float(len(self))
     return r
Пример #5
0
def parse_option_hash(hash, translator=None, default_keys=None, \
        default_value=None, default_function=None, translator_target='mara'):
    """
    Parse and fix/append an option hash.

    Arguments:
        hash             -- an unformatted option hash or a default value
        translator       -- a translator to format hash keys
                            (default: as is)
        default_keys     -- a list of keys to include
                            (default: keys of the original hash)
        default_value    -- a default value to use in the absense of a
                            proper input hash
        default_function -- a default function to apply to values
                            (default: as is)
    Returns:
        out              -- a formatted option hash
    """
    loki.debug('hash(in)=%s' % repr(hash))
    # a do-nothing translator will be used if none given
    if not translator:
        translator = lambda x, y: x
    # a do-nothing function will be used if none given
    if not default_function:
        default_function = lambda x: x
    # translate each key & apply default function to the value
    if isinstance(hash, dict):
        out = {}
        for key in hash.keys():
            if translator_target is not None:
                k = translator(key, translator_target)
            else:
                k = translator(key)
            out[k] = default_function(hash[key])
    # or create a hash from the default keys & the given value
    elif hash in [int, float, str]:
        out = {}.fromkeys(default_keys, default_function(hash))
    # or create a hash from the default keys & the default value
    else:
        loki.info('Incomprehensible hash -> using %s' % repr(default_value))
        out = {}.fromkeys(default_keys, default_value)
    loki.debug('hash(out)=%s' % repr(out))
    return out
Пример #6
0
 def getDCouplingVectors(self, dcouplings, include='all', exclude=[]):
     if include == 'all':
         inc = range(1, len(self) + 1)
     else:
         inc = []
         for i in include:
             if type(i) is int:
                 inc.append(i)
             else:
                 loki.warn("discarding invalid residue '%s'", repr(i))
         inc = intersection(inc, range(1, len(self) + 1))
     exc = []
     for i in exclude:
         if type(i) is int:
             exc.append(i)
         else:
             loki.warn("discarding invalid residue '%s'", repr(i))
     include = sublist(inc, exc)
     loki.debug('include=' + repr(include))
     dcouplings = deepcopy(dcouplings)
     loki.debug('dcouplings=' + repr(dcouplings))  # REMOVE
     record = {}
     for i in range(len(dcouplings)):
         if type(dcouplings[i]) == str:
             dcouplings[i] = DCouplings[dcouplings[i]]
         dc = dcouplings[i]
         record.setdefault(dc.atoms[0], {})
         record.setdefault(dc.atoms[1], {})
     if 'HN' in record.keys():
         record.setdefault('H', {})
     wanted = record.keys()
     for i in include:
         for atom in self[i - 1]:
             if str(atom) in wanted:
                 record[str(atom)][int(self[i - 1])] = atom.position
     if 'H' in wanted and len(record['H'].keys()):
         for k in record['H'].keys():
             if not record['HN'].has_key(k):
                 record['HN'][k] = record['H'][k]
                 loki.info('using H for HN in residue %d.', k)
     loki.debug('record=%s', repr(record))
     table = {}
     for dc in dcouplings:
         x, y = dc.atoms
         residues = intersection(record[x].keys(), record[y].keys())
         for i in residues:
             tag = (i, str(dc))
             table[tag] = [
                 m - n for m, n in zip(record[x][i], record[y][i])
             ]
     tags = table.keys()
     tags.sort()
     vectors = [table[x] for x in tags]
     return tags, vectors
Пример #7
0
 def getDCouplingVectors(self, dcouplings, include='all', exclude=[]):
     if include == 'all':
         inc = range(1, len(self) + 1)
     else:
         inc = []
         for i in include:
             if type(i) is int:
                 inc.append(i)
             else:
                 loki.warn("discarding invalid residue '%s'", repr(i))
         inc = intersection(inc, range(1, len(self) + 1))
     exc = []
     for i in exclude:
         if type(i) is int:
             exc.append(i)
         else:
             loki.warn("discarding invalid residue '%s'", repr(i))
     include = sublist(inc, exc)
     loki.debug('include=' + repr(include))
     dcouplings = deepcopy(dcouplings)
     loki.debug('dcouplings=' + repr(dcouplings)) # REMOVE
     record = {}
     for i in range(len(dcouplings)):
         if type(dcouplings[i]) == str:
             dcouplings[i] = DCouplings[dcouplings[i]]
         dc = dcouplings[i]
         record.setdefault(dc.atoms[0], {})
         record.setdefault(dc.atoms[1], {})
     if 'HN' in record.keys():
         record.setdefault('H', {})
     wanted = record.keys()
     for i in include:
         for atom in self[i-1]:
             if str(atom) in wanted:
                 record[str(atom)][int(self[i-1])] = atom.position
     if 'H' in wanted and len(record['H'].keys()):
         for k in record['H'].keys():
             if not record['HN'].has_key(k):
                 record['HN'][k] = record['H'][k]
                 loki.info('using H for HN in residue %d.', k)
     loki.debug('record=%s', repr(record))
     table = {}
     for dc in dcouplings:
         x, y = dc.atoms
         residues = intersection(record[x].keys(), record[y].keys())
         for i in residues:
             tag = (i, str(dc))
             table[tag] = [m-n for m,n in zip(record[x][i], record[y][i])]
     tags = table.keys()
     tags.sort()
     vectors = [table[x] for x in tags]
     return tags, vectors
Пример #8
0
    def __call__(self, word, target=None, attributes=None, find_best=True):
        """
        Translate a word into a target language matching desired attributes.

        arguments:
          word       -- word of interest
          target     -- target language (default: None == self.default)
          attributes -- list of desired attributes (default: [])
          find_best  -- whether to actually search for a best match
                        (default: True)

        TODO: find_best redundant, remove print statements etc.
        """
        if target == None:
            target = self.default
        if attributes is None:
            attributes = []
        elif type(attributes) is str:
            attributes = [attributes]
        loki.debug('attributes=%s', attributes)
        loki.debug('word=%s' % repr(word))
        if not self.__dictionaries__.has_key(target):
            raise ArgumentError, "Unknown target language '%s'." % target
        if not self.__links__.has_key(target):
            raise ArgumentError, "No known links to target language '%s'." \
                    % target
        if word in self.__dictionaries__[target]:
            return word
        else:
            name = None
            original = None
            for dictionary in self.__dictionaries__.values():
                if word in dictionary:
                    name = str(dictionary)
                    original = dictionary[word]
                    for a in original.attributes:
                        if a not in attributes:
                            attributes.append(a)
                    break
            loki.debug('original=%s' % repr(original))
            loki.debug('attributes=%s', attributes)
            loki.debug('name=%s' % repr(name))
            if name != None:
                path = self.__paths__[name][target]
                loki.debug('path=%s' % repr(path))
                if path != None:
                    # start from the base form
                    if original.base:
                        word = original.base
                    loki.debug('word=%s' % repr(word))
                    # traverse through the links to find the target word
                    for p in path:
                        word = str(self.__links__[name][p][word])
                        loki.debug('word=%s @ %s' % (repr(word), repr(p)))
                        name = p
                    # find the best match for the original form
                    if find_best:
                        new = self.__dictionaries__[target][word]
                        loki.debug('new=%s' % repr(new))
                        matches, mismatches = self.__match_attributes__(
                                attributes, new.attributes)
                        loki.debug('matches=%s', matches)
                        loki.debug('mismatches=%s', mismatches)
                        if mismatches:
                            alt = [word] + new.synonyms + new.conjugates
                            loki.debug('alt=%s' % repr(alt))
                            record = []
                            best = None
                            for a in alt:
                                m, mm = self.__match_attributes__( \
                                        attributes, \
                                        self.__dictionaries__\
                                                [target][a].attributes)
                                record.append((m,mm))
                                if best == None or m > record[best][0] or \
                                        (m == record[best][0] and \
                                        mm < record[best][1]):
                                    best = len(record)-1
                            loki.debug('record=%s', record)
                            loki.debug('best=%s', best)
                            if record[best][0] > matches or \
                                    (record[best][0] == matches and \
                                    record[best][1] < mismatches):
                                return alt[best]
                    return word
            return self.unknown
Пример #9
0
def parse_sequence(args):
    """
    Parse an amino acid sequence.

    Arguments:
        args     -- a list of sequence items or a name of a file containing
                    them, e.g. 'GLU PRO GLU CYS' or 'EPEC GLK C EEK'
    Returns:
        sequence -- a list of 3-letter amino acid symbols
    """
    loki.debug('parse_sequence < %s' % repr(args))
    if isinstance(args, str) and os.path.isfile(args):
        fname = args
    elif len(args) == 1 and isinstance(args[0], str):
        if os.path.isfile(args[0]):
            fname = args[0]
        else:
            if args[0].count(' '):
                args = args[0].split()
            else:
                args = args[0]
            fname = None
    else:
        fname = None
    if fname:
        f = open(fname)
        seq = f.read()
        f.close()
        loki.info("Read sequence from file '%s'." % fname)
        args = seq.strip().split()
        loki.debug('args=%s' % repr(args))


#        sequence = []
#        for aa in seq.strip().split():
#            try:
#                sequence.append(omniTranslator(aa.capitalize(), \
#                        '3-letter-aminoacids'))
#            except KeyError:
#                loki.warn("Discarding unknown aminoacid '%s'." % repr(aa))
#    else:
# check whether all the sequence items are separated from each other
    args = [x.capitalize() for x in args]
    separated = True
    for a in args:
        if not (a in libLingua.dictionaryAmino1 or \
                a in libLingua.dictionaryAmino3):
            separated = False
    loki.debug('separated=%s' % repr(separated))
    sequence = []
    if separated:
        # append each item after converting it to a 3-letter symbol
        for a in args:
            try:
                sequence.append(omniTranslator(a.capitalize(), \
                        '3-letter-aminoacids'))
            except KeyError:
                loki.warn("Discarding unknown aminoacid '%s'." % repr(a))
    else:
        # jam all symbols together (hope they are all 1-letter symbols)
        aa = ''
        for a in args:
            aa += str(a)
        aa = aa.replace(' ', '')
        loki.debug('aa=%s' % repr(aa))
        # append each item after converting it to a 3-letter symbol
        for a in list(aa):
            try:
                sequence.append(omniTranslator(a, '3-letter-aminoacids'))
            except KeyError:
                loki.warn("Discarding unknown aminoacid '%s'." % repr(a))
    loki.debug('parse_sequence > %s' % repr(sequence))
    return sequence
Пример #10
0
def parse_sequence(args):
    """
    Parse an amino acid sequence.

    Arguments:
        args     -- a list of sequence items or a name of a file containing
                    them, e.g. 'GLU PRO GLU CYS' or 'EPEC GLK C EEK'
    Returns:
        sequence -- a list of 3-letter amino acid symbols
    """
    loki.debug("parse_sequence < %s" % repr(args))
    if isinstance(args, str) and os.path.isfile(args):
        fname = args
    elif len(args) == 1 and isinstance(args[0], str):
        if os.path.isfile(args[0]):
            fname = args[0]
        else:
            if args[0].count(" "):
                args = args[0].split()
            else:
                args = args[0]
            fname = None
    else:
        fname = None
    if fname:
        f = open(fname)
        seq = f.read()
        f.close()
        loki.info("Read sequence from file '%s'." % fname)
        args = seq.strip().split()
        loki.debug("args=%s" % repr(args))
    #        sequence = []
    #        for aa in seq.strip().split():
    #            try:
    #                sequence.append(omniTranslator(aa.capitalize(), \
    #                        '3-letter-aminoacids'))
    #            except KeyError:
    #                loki.warn("Discarding unknown aminoacid '%s'." % repr(aa))
    #    else:
    # check whether all the sequence items are separated from each other
    args = [x.capitalize() for x in args]
    separated = True
    for a in args:
        if not (a in libLingua.dictionaryAmino1 or a in libLingua.dictionaryAmino3):
            separated = False
    loki.debug("separated=%s" % repr(separated))
    sequence = []
    if separated:
        # append each item after converting it to a 3-letter symbol
        for a in args:
            try:
                sequence.append(omniTranslator(a.capitalize(), "3-letter-aminoacids"))
            except KeyError:
                loki.warn("Discarding unknown aminoacid '%s'." % repr(a))
    else:
        # jam all symbols together (hope they are all 1-letter symbols)
        aa = ""
        for a in args:
            aa += str(a)
        aa = aa.replace(" ", "")
        loki.debug("aa=%s" % repr(aa))
        # append each item after converting it to a 3-letter symbol
        for a in list(aa):
            try:
                sequence.append(omniTranslator(a, "3-letter-aminoacids"))
            except KeyError:
                loki.warn("Discarding unknown aminoacid '%s'." % repr(a))
    loki.debug("parse_sequence > %s" % repr(sequence))
    return sequence
Пример #11
0
    def __call__(self, word, target=None, attributes=None, find_best=True):
        """
        Translate a word into a target language matching desired attributes.

        arguments:
          word       -- word of interest
          target     -- target language (default: None == self.default)
          attributes -- list of desired attributes (default: [])
          find_best  -- whether to actually search for a best match
                        (default: True)

        TODO: find_best redundant, remove print statements etc.
        """
        if target == None:
            target = self.default
        if attributes is None:
            attributes = []
        elif type(attributes) is str:
            attributes = [attributes]
        loki.debug('attributes=%s', attributes)
        loki.debug('word=%s' % repr(word))
        if not self.__dictionaries__.has_key(target):
            raise ArgumentError, "Unknown target language '%s'." % target
        if not self.__links__.has_key(target):
            raise ArgumentError, "No known links to target language '%s'." \
                    % target
        if word in self.__dictionaries__[target]:
            return word
        else:
            name = None
            original = None
            for dictionary in self.__dictionaries__.values():
                if word in dictionary:
                    name = str(dictionary)
                    original = dictionary[word]
                    for a in original.attributes:
                        if a not in attributes:
                            attributes.append(a)
                    break
            loki.debug('original=%s' % repr(original))
            loki.debug('attributes=%s', attributes)
            loki.debug('name=%s' % repr(name))
            if name != None:
                path = self.__paths__[name][target]
                loki.debug('path=%s' % repr(path))
                if path != None:
                    # start from the base form
                    if original.base:
                        word = original.base
                    loki.debug('word=%s' % repr(word))
                    # traverse through the links to find the target word
                    for p in path:
                        word = str(self.__links__[name][p][word])
                        loki.debug('word=%s @ %s' % (repr(word), repr(p)))
                        name = p
                    # find the best match for the original form
                    if find_best:
                        new = self.__dictionaries__[target][word]
                        loki.debug('new=%s' % repr(new))
                        matches, mismatches = self.__match_attributes__(
                            attributes, new.attributes)
                        loki.debug('matches=%s', matches)
                        loki.debug('mismatches=%s', mismatches)
                        if mismatches:
                            alt = [word] + new.synonyms + new.conjugates
                            loki.debug('alt=%s' % repr(alt))
                            record = []
                            best = None
                            for a in alt:
                                m, mm = self.__match_attributes__( \
                                        attributes, \
                                        self.__dictionaries__\
                                                [target][a].attributes)
                                record.append((m, mm))
                                if best == None or m > record[best][0] or \
                                        (m == record[best][0] and \
                                        mm < record[best][1]):
                                    best = len(record) - 1
                            loki.debug('record=%s', record)
                            loki.debug('best=%s', best)
                            if record[best][0] > matches or \
                                    (record[best][0] == matches and \
                                    record[best][1] < mismatches):
                                return alt[best]
                    return word
            return self.unknown