Debian Codegraph @

scripts/k3000/sorted_list.py

raw symbols SCIP
1 import sys
2 import K3000_common as kc
3
4 # allele_value = lambda x: int(x.split('_')[0])
5 # distance_string_value = lambda x: x.split('_')
6
7 # def list_of_list_to_allele_only(ll):
8 # res = []
9 # for list_ in ll:
10 # res.append([allele_value(x) for x in list_])
11 # return res
12
13
14 #
15 # ad=["0_0","1_12","2_13","3_13","4_12","5_123","6_1"]
16 # bd=["0_1","1_12","2_13","3_13","4_12","5_123","6_1"]
17 #
18 # ll=[ad,bd]
19 #
20 # print(d_list_sort(ad, bd))
21 #
22 # print(ll)
23 # print(list_of_list_to_allele_only(ll))
24
25 zero_d_key = lambda x: x.split('_')[0]+'_0'
26
27 def unique(s): # from http://code.activestate.com/recipes/52560-remove-duplicates-from-a-sequence/
28 """Return a list of the elements in s, but without duplicates.
29
30 For example, unique([1,2,3,1,2,3]) is some permutation of [1,2,3],
31 unique("abcabc") some permutation of ["a", "b", "c"], and
32 unique(([1, 2], [2, 3], [1, 2])) some permutation of
33 [[2, 3], [1, 2]].
34
35 For best speed, all sequence elements should be hashable. Then
36 unique() will usually work in linear time.
37
38 If not possible, the sequence elements should enjoy a total
39 ordering, and if list(s).sort() doesn't raise TypeError it's
40 assumed that they do enjoy a total ordering. Then unique() will
41 usually work in O(N*log2(N)) time.
42
43 If that's not possible either, the sequence elements must support
44 equality-testing. Then unique() will usually work in quadratic
45 time.
46 """
47
48 n = len(s)
49 if n == 0:
50 return []
51
52 # Try using a dict first, as that's the fastest and will usually
53 # work. If it doesn't work, it will usually fail quickly, so it
54 # usually doesn't cost much to *try* it. It requires that all the
55 # sequence elements be hashable, and support equality comparison.
56 # u = {}
57 # try:
58 # for x in s:
59 # u[x] = 1
60 # except TypeError:
61 # del u # move on to the next method
62 # else:
63 # return u.keys()
64
65 # We can't hash all the elements. Second fastest is to sort,
66 # which brings the equal elements together; then duplicates are
67 # easy to weed out in a single pass.
68 # NOTE: Python's list.sort() was designed to be efficient in the
69 # presence of many duplicate elements. This isn't true of all
70 # sort functions in all languages or libraries, so this approach
71 # is more effective in Python than it may be elsewhere.
72
73 try:
74 t = list(s)
75 # print()
76 # print(t)
77 t.sort(key=kc.allele_values) # sort only on the allele ids not on their distance
78 # print(t)
79 # sys.exit(0)
80 except TypeError:
81
82 del t # move on to the next method
83 else:
84 # assert n > 0
85 last = t[0]
86 lasti = i = 1
87 while i < n:
88 if not kc.d_list_equal(t[i],last): # compare only on allele ids not on their distance
89 # if t[i] != last:
90 t[lasti] = last = t[i]
91 lasti += 1
92 i += 1
93 # print(t[:lasti])
94 return t[:lasti]
95
96 assert(0==1) # check that we do not pass here.
97 # print("Bla")
98 # sys.exit(0)
99 # Brute force is all that's left.
100 # u = []
101 # for x in s:
102 # if x not in u:
103 # u.append(x)
104 return u
105
106 #ll= [['-30493_13', '-51619_15', '2593_28', '-31345_10'], ['-30493_13', '-51619_15', '2593_28', '-31345_10', '-1959_80'], ['-30493_13', '-51619_15', '2593_28', '-31345_7'], ['-51618_28', '2593_28', '-31345_10'], ['-51619_28', '2593_28', '-31345_10']]
107 # ll= [['-30493_13', '-51619_15', '2593_28', '-31345_10'], ['-30493_13', '-51619_15', '2593_28', '-31345_7'], ['-30493_13', '-51619_15', '2593_28', '-31345_10', '-1959_80'], ['-30493_13', '-51619_15', '2593_28', '-31345_7'], ['-51618_28', '2593_28', '-31345_10'], ['-51619_28', '2593_28', '-31345_10']]
108 # print(ll)
109 # print (unique(ll))
110
111 def compare (tuple1,tuple2): # TOCHECK
112 '''
113 if tuple1 starts with tuple2: return 0
114 if tuple1<tuple2: return -1
115 if tuple1>tuple2: return 1
116 '''
117 # remove path id ("i_indexid")
118 if len(tuple1) > 0 and tuple1[-1][0] == 'i' :
119 tuple1=tuple1[:-1] # TODO: optimization feasible in calling functions for avoiding those systematic tests
120 if len(tuple2) > 0 and tuple2[-1][0] == 'i' :
121 tuple2=tuple2[:-1] # TODO: optimization feasible in calling functions for avoiding those systematic tests
122 tmp_tuple1=tuple1[0:len(tuple2)]
123 return kc.d_list_order(tmp_tuple1,tuple2) #
124 # if tmp_tuple1 < tuple2: return -1
125 # if tmp_tuple1 > tuple2: return 1
126 # return 0
127
128 class sorted_list(object):
129 """Class sorted list
130 Contains a sorted set of list of allele+distance "a_b" (a is positive or negative, not equal to 0), b is an integer >= 0
131 Divided into buckets. Each first value is a bucket.
132 """
133
134 def __init__(self):
135 self.main_dict={}
136 self.size=0
137
138
139 def add(self, mylist):
140 """add a new list"""
141 self.size+=1
142 zdk = zero_d_key(mylist[0])
143 if zdk not in self.main_dict: # key is always a_0
144 self.main_dict[zdk]=[]
145 self.main_dict[zdk]+=[mylist[1:]]
146
147
148 def sorted_add(self,mylist):
149 """add a new list"""
150 self.add(mylist)
151
152 # we added the element at the last position of the list. We will bring it back to the good position:
153 # example the list is: 4,N,7,13,N,N,5 (we have to put back 5 in its good location). Note that in practice we
154 # pos_current = 6, previous = 5, 4, 3. current_list[3]<current_list[6]: yes, so we swap, and obtain 4,N,7,5,N,N,13
155 # pos_current = 3, previous = 2 current_list[2]<current_list[3]: yes, so we swap, and obtain 4,N,5,7,N,N,13
156 # pos_current = 2, previous = 1, 0 current_list[0]<current_list[2]; no, this is finished.
157 current_list = self.main_dict[zero_d_key(mylist[0])]
158 pos_current = len(current_list)-1
159 while True:
160 previous = pos_current-1
161 while current_list[previous]==None and previous>=0:
162 previous-=1
163
164 if previous==-1: break # end of the list, nothing to do.
165
166 if kc.d_list_order(current_list[previous],current_list[pos_current]) <=0: break# bubble sort of the last element finished. Note that the "equal case" should not happen in our situation.
167 # current_list[previous] <= current_list[pos_current] : break # bubble sort of the last element finished. Note that the "equal case" should not happen in our situation.
168 else : # we swap the two values
169 current_list[previous], current_list[pos_current] = current_list[pos_current], current_list[previous]
170 pos_current = previous;
171
172
173
174
175 def sort(self):
176 """sort the whole structure - feasible only before removing elements"""
177 for key, value in self.main_dict.items():
178 value.sort(key=kc.allele_values)
179
180 def traverse(self):
181 for key, value in self.main_dict.items():
182 # mylists = value
183 for mylist in value:
184 if mylist != None:
185 yield [key]+mylist
186
187 def index_nodes(self):
188 ''' For each element in the structure, we add its id as a last value, stored as i_14, for instance for node 14.'''
189 index_id=1
190 for key, value in self.main_dict.items():
191 for mylist in value:
192 if mylist != None:
193 mylist+=['i_'+str(index_id)]
194 index_id+=1
195
196
197 def remove(self,mylist):
198 '''remove an element from the structure'''
199 ''' if the element is not in a structure a warning is raised'''
200 zero_d_key = mylist[0].split('_')[0]+'_0'
201 try:
202 tormindex=self.main_dict[zero_d_key].index(mylist[1:])
203 del self.main_dict[zero_d_key][tormindex]
204 except :
205 # sys.stderr.write("\n WARNING: "+str(mylist)+"\n")
206 # sys.stderr.write("\n WARNING: Tried to remove "+str(mylist)+" absent from the list "+str(self.main_dict[mylist[0]])+".\n")
207 return 0
208 self.size-=1
209 return 1
210
211 def get_node_id(self, search_sr):
212 list_nodes = self.get_lists_starting_with_given_prefix(search_sr)
213 # print ("search_sr", search_sr,"list_nodes",list_nodes)
214 for node in list_nodes:
215 if node[:-1]==search_sr:
216 return node[-1].split("_")[-1]
217 return None
218
219
220 def get_lists_starting_with_given_prefix(self, prefix):
221 ''' given a prefix of a list, return all lists in the set starting with this prefix
222 Dichotomy. log(|self|/size(alphabet)) comparisons
223 O(|prefix|*log(|self|/size(alphabet)))
224 '''
225 #TODO: optimizable if len(prefix==1): return the self.main_dict[prefix[0]] adding prefix[0] to each value.
226 # assert prefix[0].split('_')[-1] == "0", prefix
227 zkd = zero_d_key(prefix[0])
228 if zkd not in self.main_dict: return []
229 #OPTIMIZATION IF len(prefix==1): return the self.main_dict[prefix[0]] adding prefix[0] to each value.
230 if len(prefix)==1:
231 res = []
232 for l in self.main_dict[zkd]:
233 res.append([prefix[0]]+l)
234 # print()
235 # print(prefix)
236 # print(res)
237 return res
238
239 first=prefix[0]
240
241 current_list = self.main_dict[zkd]
242 # print(prefix)
243 prefix = prefix[1:]
244 start=0
245 n=len(current_list)-1
246 stop=n
247
248
249 # print ("search", prefix, "in ",current_list)
250 while start <=stop:
251 # print (start,stop)
252 middle = start+int((stop-start)/2)
253 if middle>n: break
254 ## Search for a non empty middle value
255 while middle<=stop:
256 tuple1 = current_list[middle]
257 if tuple1 == None: middle+=1 # Empty value
258 else: break # Found a non empty value
259 if middle == stop+1: # for instance looking for [1] in [1, None, None] we didn't find any middle with a avlue, thus we come back
260 middle = start+int((stop-start)/2)-1
261 while middle>=start:
262 tuple1 = current_list[middle]
263 if tuple1 == None: middle-=1 # Empty value
264 else: break # Found a non empty value
265 if middle == start-1: return [] # nothing found (empty sub-list)
266
267 ## a non empty middle value was found
268 cmp_val = compare(tuple1,prefix)
269 if cmp_val == -1: # prefix may start in the remaining part of the current_list array
270 start = middle+1
271 continue
272 if cmp_val == 1: # prefix may start in the starting part of the current_list array
273 stop = middle-1
274 continue
275 # if cmp_val == 0: # we found a tuple starting with the prefix. We need to check other tuples starting with prefix before and after in the array.
276 res=[[first]+tuple1]
277 # print ("res before all = ",res)
278 i=middle-1
279 while i>-1:
280 if current_list[i]!=None:
281 if compare(current_list[i],prefix)==0: res.append([first]+current_list[i])
282 else: break
283 i-=1
284
285 i=middle+1
286 while i<=n:
287 if current_list[i]!=None:
288 if compare(current_list[i],prefix)==0: res.append([first]+current_list[i])
289 else: break
290 i+=1
291
292 # print ("res after all = ",res)
293 return res
294 # print ("return rien")
295 return []
296
297 def contains (self,mylist):
298 ''' if sr is in SR: return True, else return False.
299 faster (O(log(|SR|)) that the 'in' function from non ordered array (O(|SR|))
300 '''
301 X=self.get_lists_starting_with_given_prefix(mylist)
302 if X==mylist: return True # if X is composed of a unique list
303 if mylist in X: return True # O(|X|) which can be considered as constant
304 return False
305
306 def __len__(self):
307 return self.size
308
309
310 def contains(self,query):
311 """only for debug purpose, no need to be optimized"""
312 for key, value in self.main_dict.items():
313 if key==query:
314 print("key", key, "query",query)
315 return True
316 for followup in value:
317 for unitig_id in followup:
318 if unitig_id==query:
319 return True
320 return False
321
322 def unique(self):
323 for key, value in self.main_dict.items():
324 size_before=len(value)
325 value=unique(value)
326 size_after=len(value)
327 self.main_dict[key]=value
328 self.size-=(size_before-size_after)
329
330 def __str__(self):
331 str_SR=""
332 for key, value in self.main_dict.items():
333 for followup in value:
334 str_SR+=str(key)
335 for unitig_id in followup:
336 str_SR+=","+str(unitig_id)
337 str_SR+="\n"
338 return str_SR
339
340 # SR = sorted_list()
341 # SR.add([1,2,3])
342 # SR.add([1,2,3])
343 # SR.remove([1,2])
344 # # SR.remove([1])
345 # # SR.remove([1,2,4,5])
346 # SR.add([1,2,3,5])
347 # # SR.add([5])
348 # # SR.add([5,6])
349 # print(SR)
350 # SR.unique()
351 # print(SR)