Package Bio :: Package NeuralNetwork :: Package Gene :: Module Pattern
[hide private]
[frames] | no frames]

Source Code for Module Bio.NeuralNetwork.Gene.Pattern

  1  # This code is part of the Biopython distribution and governed by its 
  2  # license.  Please see the LICENSE file that should have been included 
  3  # as part of this package. 
  4  # 
  5   
  6  """Generic functionality useful for all gene representations. 
  7   
  8  This module contains classes which can be used for all the different 
  9  types of patterns available for representing gene information (ie. motifs, 
 10  signatures and schemas). These are the general classes which should be 
 11  handle any of the different specific patterns. 
 12  """ 
 13  # standard library 
 14  import random 
 15   
 16  # biopython 
 17  from Bio.Alphabet import _verify_alphabet 
 18  from Bio.Seq import Seq, MutableSeq 
 19   
 20   
21 -class PatternIO(object):
22 """Allow reading and writing of patterns to files. 23 24 This just defines a simple persistence class for patterns, making 25 it easy to write them to a file and read 'em back. 26 """ 27
28 - def __init__(self, alphabet=None):
29 """Intialize the reader and writer class. 30 31 Arguments: 32 - alphabet - An optional argument specifying the alphabet 33 which patterns should follow. If an alphabet is set it'll be used 34 to verify that all patterns follow it. 35 36 Attributes: 37 - separator - A character to use in separating items in a signature 38 when it is written to a file and read back. This character should 39 not be in the possible alphabet of the sequences, or there will 40 be trouble. 41 42 """ 43 self._alphabet = alphabet 44 45 self.separator = ";"
46
47 - def write(self, pattern_list, output_handle):
48 """Write a list of patterns to the given handle.""" 49 for pattern in pattern_list: 50 # deal with signatures, concatentate them with the separator 51 if isinstance(pattern, (list, tuple)): 52 string_pattern = self.separator.join(pattern) 53 # deal with the normal cases 54 else: 55 string_pattern = pattern 56 57 output_handle.write("%s\n" % string_pattern)
58
59 - def write_seq(self, seq_pattern_list, output_handle):
60 """Convenience function to write Seq objects to a file. 61 62 This can take Seqs and MutableSeqs, and write them to a file 63 as strings. 64 """ 65 # convert the seq patterns into just string patterns 66 all_patterns = [] 67 68 for seq_pattern in seq_pattern_list: 69 if isinstance(seq_pattern, MutableSeq): 70 seq = seq_pattern.toseq() 71 all_patterns.append(str(seq)) 72 elif isinstance(seq_pattern, Seq): 73 all_patterns.append(str(seq_pattern)) 74 else: 75 raise ValueError("Unexpected pattern type %r" % seq_pattern) 76 77 self.write(all_patterns, output_handle)
78
79 - def read(self, input_handle):
80 """Read patterns from the specified handle.""" 81 all_patterns = [] 82 83 while True: 84 cur_line = input_handle.readline() 85 86 if not(cur_line): 87 break 88 89 cur_pattern = cur_line.rstrip() 90 # split up signatures 91 if self.separator in cur_pattern: 92 cur_pattern = tuple(cur_pattern.split(self.separator)) 93 94 if self._alphabet is not None: 95 # make single patterns (not signatures) into lists, so we 96 # can check signatures and single patterns the same 97 if not isinstance(cur_pattern, tuple): 98 test_pattern = [cur_pattern] 99 else: 100 test_pattern = cur_pattern 101 for pattern_item in test_pattern: 102 pattern_seq = Seq(pattern_item, self._alphabet) 103 if not(_verify_alphabet(pattern_seq)): 104 raise ValueError("Pattern %s not matching alphabet %s" 105 % (cur_pattern, self._alphabet)) 106 107 all_patterns.append(cur_pattern) 108 109 return all_patterns
110 111
112 -class PatternRepository(object):
113 """Hold a list of specific patterns found in sequences. 114 115 This is designed to be a general holder for a set of patterns and 116 should be subclassed for specific implementations (ie. holding Motifs 117 or Signatures. 118 """ 119
120 - def __init__(self, pattern_info):
121 """Initialize a repository with patterns, 122 123 Arguments: 124 - pattern_info - A representation of all of the patterns found in 125 a finder search. This should be a dictionary, where the keys 126 are patterns, and the values are the number of times a pattern 127 is found. 128 129 The patterns are represented interally as a list of two 130 tuples, where the first element is the number of times a pattern 131 occurs, and the second is the pattern itself. This makes it easy 132 to sort the list and return the top N patterns. 133 """ 134 self._pattern_dict = pattern_info 135 136 # create the list representation 137 self._pattern_list = [] 138 for pattern_name in self._pattern_dict: 139 self._pattern_list.append((self._pattern_dict[pattern_name], 140 pattern_name)) 141 142 self._pattern_list.sort() 143 self._pattern_list.reverse()
144
145 - def get_all(self):
146 """Retrieve all of the patterns in the repository.""" 147 patterns = [] 148 for pattern_info in self._pattern_list: 149 patterns.append(pattern_info[1]) 150 151 return patterns
152
153 - def get_random(self, num_patterns):
154 """Retrieve the specified number of patterns randomly. 155 156 Randomly selects patterns from the list and returns them. 157 158 Arguments: 159 - num_patterns - The total number of patterns to return. 160 161 """ 162 all_patterns = [] 163 164 while len(all_patterns) < num_patterns: 165 # pick a pattern, and only add it if it is not already present 166 new_pattern_info = random.choice(self._pattern_list) 167 168 if new_pattern_info[1] not in all_patterns: 169 all_patterns.append(new_pattern_info[1]) 170 171 return all_patterns
172
173 - def get_top_percentage(self, percent):
174 """Return a percentage of the patterns. 175 176 This returns the top 'percent' percentage of the patterns in the 177 repository. 178 """ 179 all_patterns = self.get_all() 180 181 num_to_return = int(len(all_patterns) * percent) 182 183 return all_patterns[:num_to_return]
184
185 - def get_top(self, num_patterns):
186 """Return the specified number of most frequently occurring patterns 187 188 Arguments: 189 - num_patterns - The number of patterns to return. 190 191 """ 192 all_patterns = [] 193 for pattern_info in self._pattern_list[:num_patterns]: 194 all_patterns.append(pattern_info[1]) 195 196 return all_patterns
197
198 - def get_differing(self, top_num, bottom_num):
199 """Retrieve patterns that are at the extreme ranges. 200 201 This returns both patterns at the top of the list (ie. the same as 202 returned by get_top) and at the bottom of the list. This 203 is especially useful for patterns that are the differences between 204 two sets of patterns. 205 206 Arguments: 207 - top_num - The number of patterns to take from the top of the list. 208 - bottom_num - The number of patterns to take from the bottom of 209 the list. 210 211 """ 212 all_patterns = [] 213 # first get from the top of the list 214 for pattern_info in self._pattern_list[:top_num]: 215 all_patterns.append(pattern_info[1]) 216 217 # then from the bottom 218 for pattern_info in self._pattern_list[-bottom_num:]: 219 all_patterns.append(pattern_info[1]) 220 221 return all_patterns
222
223 - def remove_polyA(self, at_percentage=.9):
224 """Remove patterns which are likely due to polyA tails from the lists. 225 226 This is just a helper function to remove pattenrs which are likely 227 just due to polyA tails, and thus are not really great motifs. 228 This will also get rid of stuff like ATATAT, which might be a 229 useful motif, so use at your own discretion. 230 231 XXX Could we write a more general function, based on info content 232 or something like that? 233 234 Arguments: 235 - at_percentage - The percentage of A and T residues in a pattern 236 that qualifies it for being removed. 237 238 """ 239 remove_list = [] 240 # find all of the really AT rich patterns 241 for pattern_info in self._pattern_list: 242 pattern_at = float(pattern_info[1].count('A') + pattern_info[1].count('T')) / len(pattern_info[1]) 243 if pattern_at > at_percentage: 244 remove_list.append(pattern_info) 245 246 # now remove them from the master list 247 for to_remove in remove_list: 248 self._pattern_list.remove(to_remove)
249
250 - def count(self, pattern):
251 """Return the number of times the specified pattern is found.""" 252 try: 253 return self._pattern_dict[pattern] 254 except KeyError: 255 return 0
256