def searchRange(nums, target): """ Binary search (INCORRECT) Time: ?? worst case O(n): e.g. find 2 in [2,2,2,2,2,2], best case O(logn) Space: O(1) (no copies of input created) """ n = len(nums) curr_ind = binary_search(nums, target, 0, n - 1) if curr_ind == -1: return -1, -1 left_ind, right_ind = curr_ind, curr_ind if left_ind != 0: while nums[left_ind - 1] == nums[left_ind]: left_ind = binary_search(nums, target, 0, left_ind - 1) if left_ind == 0: break first_occur = left_ind if right_ind != n - 1: while nums[right_ind + 1] == nums[right_ind]: right_ind = binary_search(nums, target, right_ind + 1, n - 1) if right_ind == n - 1: break last_occur = right_ind return first_occur, last_occur
def get_child(self, ch, word): # Find the next word after this one, to mark the end of the span. next_word = utils.make_next_word(word) # Starting at the current span, narrow the low and high independently. (new_low, low_found) = utils.binary_search(self.words, word, self.low, self.high) (new_high, _) = utils.binary_search(self.words, next_word, self.low, self.high) # The high binary search will find the next word off the end, so back up one. new_high -= 1 if new_low <= new_high: return ProgressiveBinarySearchDictionary(self.words, low_found, new_low, new_high) else: return None
def get_best_radar_position(self, time, guess = [0.0, 0.0, 0.0]): camera_angle = self.calc_camera_angle(time) camera_distance = self.calc_camera_distance(time) #if abs(camera_distance) > 0.1: # print time, camera_angle, camera_distance idx = utils.binary_search(time, self.radar_times) points = self.radar_points[idx] debug = False res = self.get_best_radar_position_full(points, camera_angle, camera_distance, guess, debug) #print camera_distance, utils.distance_2d(res, [0, 0, 0]) if False and camera_distance > 0.1: print "------------------------" print time print points print camera_distance, camera_angle print res return res
def get_closest_lidar(self, time, guess): if utils.isempty(guess): return [0.0, 0.0, 0.0] idx = utils.binary_search(time, self.lidar_times) #print "Lidar---> ", self.lidar_data[idx] points = self.lidar_data[idx] #print "lidar: ", points #print idx best = 10.0 res = [0.0, 0.0, 0.0] #print points for elem in points: d = utils.distance_ang(elem, guess) #print d if d < best: best = d res = elem return list(res)
def prime_sieve(n): """ Returns the primes below a specified number with the choice of prime sieve depending on the size of the number. Arguments: n (:int) - the number to list primes under Returns: the primes under 'n' in a list Examples: >>> prime_sieve(9) >>> [2, 3, 5, 7] >>> len(prime_sieve(10**9)) >>> 50847534 """ if n <= constants.SMALL_THRESHOLD: return under60[:utils.binary_search(n, under60)] elif n <= constants.ERAT_THRESHOLD: return small_sieve(n) elif n <= constants.ATKIN_THERSHOLD: return sieve_of_atkin(n) else: return segmented_sieve(2, n)
def reducing(self, data1, data2): # returns a list reduced1 = self.fill_reduced(data1) reduced2 = self.fill_reduced(data2) if len(reduced1) < len(reduced2): main = reduced1 secondary = reduced2 else: main = reduced2 secondary = reduced1 arr = [] for i, elem in enumerate(main): str_find = elem[0] index = binary_search(secondary, 0, len(secondary) - 1, str_find) if index != -1: second_item = secondary[index] second_value = second_item[1] secondary.remove(second_item) temp = main[i] temp_str = temp[0] final_value = temp[1] + second_value arr.append((temp_str, final_value)) else: arr.append(elem) if len(secondary) != 0: arr.extend(secondary) merge_sort(arr) return arr
def find_track(self, target): found_index = binary_search(self.search_space, target) if found_index is None: return None self.search_done = True i = found_index current_track = self.search_space[i].lower() result = [] while current_track.startswith(target.lower()): result.append(current_track) if i == len(self.search_space) - 1: break i += 1 current_track = self.search_space[i].lower() i = found_index if i > 0: i -= 1 current_track = self.search_space[i].lower() while current_track.startswith(target.lower()): result.append(current_track) if i == 0: break i -= 1 current_track = self.search_space[i].lower() return result
def _right_transfer(self, v: Position, w: Position) -> None: """ Resolves v's underflow with a transfer with the right sibling of v, i.e. w :param v: the Position of the node in underflow :param w: the right sibling of v :return: None """ # Validate v_node = self._validate(v) w_node = self._validate(w) # Let k' be the key saved in the parent p that is between the keys contained in w and v p = self.parent(v) # Since w is the right sibling of v, the binary search will return the index of k' _, index = binary_search(p.keys(), w_node.elements[0].key) # Let new_item be the Item in p with key k' new_item = p.elements[index] # Let k'' be the smallest key saved in w # Let leftmost_item be the item in w with key k'' leftmost_item = w_node.elements[0] # Let leftmost_child be the node child of w to the left of k'' leftmost_child = w_node.children[0] # Delete k from v, and add k' in v v_node._elements = v_node.elements + [new_item] # w transfered leftmost_child to v, so v keeps leftmost_child to its right, since w is the right sibling of v v_node._children = v_node.children + [leftmost_child] if leftmost_child is not None: leftmost_child.parent = v_node # Delete k'' from w w_node.elements.pop(0) # Also delete the leftmost child w_node.children.pop(0) # Replace k' with k'' in p p.elements[index] = leftmost_item
def _left_transfer(self, v: Position, w: Position) -> None: """ Resolves v's underflow with a transfer with the left sibling of v, i.e. w :param v: the Position of the node in underflow :param w: the left sibling of v :return: None """ # Validate v_node = self._validate(v) w_node = self._validate(w) # Let k' be the key saved in the parent p that is between the keys contained in w and v p = self.parent(v) # Since w is the left sibling of v, the binary search will return the index of the key to the left of k' _, index = binary_search(p.keys(), w_node.elements[0].key) # So, we increment index index = index + 1 # Let new_item be the Item in p with key k' new_item = p.elements[index] # Let k'' be the largest key saved in w # Let rightmost_item be the item in w with key k'' rightmost_item = w_node.elements[-1] # Let rightmost_child be the node child of w to the right of k'' rightmost_child = w_node.children[-1] # Add k' in v v_node.elements = [new_item] + v_node.elements # w transfered rightmost_item to v, so v keeps rightmost_child to its left, since w is the left sibling of v v_node._children = [rightmost_child] + v_node.children if rightmost_child is not None: rightmost_child.parent = v_node # Delete k'' from w w_node.elements.pop() # Also delete the rightmost child w_node.children.pop() # Replace k' with k'' in p p.elements[index] = rightmost_item
def cluster_evaluation(self): for cp in self.list_of_cp: demonstration = self.map_cp2demonstrations[cp] frm = self.map_cp2frm[cp] + 2 * self.sr curr_surgeme = self.map_frm2surgeme[demonstration][frm] self.map_cp2surgemes[cp] = curr_surgeme ranges = sorted(utils.get_annotation_segments(constants.PATH_TO_DATA + constants.ANNOTATIONS_FOLDER + demonstration + "_" + constants.CAMERA + ".p")) bin = utils.binary_search(ranges, frm) map_frm2surgeme_demonstration = self.map_frm2surgeme[demonstration] prev_end = bin[0] - 1 next_start = bin[1] + 1 prev_surgeme = map_frm2surgeme_demonstration[prev_end] if prev_end in map_frm2surgeme_demonstration else "start" next_surgeme = map_frm2surgeme_demonstration[next_start] if next_start in map_frm2surgeme_demonstration else "end" surgemetransition = None if abs(frm - (bin[0] - 1)) < abs(bin[1] + 1 - frm): surgemetransition = str(prev_surgeme) + "->" + str(curr_surgeme) else: surgemetransition = str(curr_surgeme) + "->" + str(next_surgeme) self.map_cp2surgemetransitions[cp] = surgemetransition self.cp_surgemes = set(self.map_cp2surgemes.values())
def cluster_evaluation(self): for cp in self.list_of_cp: demonstration = self.map_cp2demonstrations[cp] frm = self.map_cp2frm[cp] curr_surgeme = self.map_frm2surgeme[demonstration][frm] self.map_cp2surgemes[cp] = curr_surgeme ranges = sorted(utils.get_annotation_segments(constants.PATH_TO_DATA + constants.ANNOTATIONS_FOLDER + demonstration + "_" + constants.CAMERA + ".p")) bin = utils.binary_search(ranges, frm) map_frm2surgeme_demonstration = self.map_frm2surgeme[demonstration] prev_end = bin[0] - 1 next_start = bin[1] + 1 prev_surgeme = map_frm2surgeme_demonstration[prev_end] if prev_end in map_frm2surgeme_demonstration else "start" next_surgeme = map_frm2surgeme_demonstration[next_start] if next_start in map_frm2surgeme_demonstration else "end" surgemetransition = None if abs(frm - (bin[0] - 1)) < abs(bin[1] + 1 - frm): surgemetransition = str(prev_surgeme) + "->" + str(curr_surgeme) else: surgemetransition = str(curr_surgeme) + "->" + str(next_surgeme) self.map_cp2surgemetransitions[cp] = surgemetransition self.cp_surgemes = set(self.map_cp2surgemes.values())
def calc_camera_angle(self, time): if len(self.camera_times) == 0: return 100.0 idx_camera = utils.binary_search(time, self.camera_times) nxt_idx_camera = idx_camera + 1 if idx_camera == len(self.camera_times)-1: nxt_idx_camera = idx_camera if idx_camera > 0: idx_camera = idx_camera - 1 angle_value = self.camera_angles_predicted[idx_camera] angle_value_nxt = self.camera_angles_predicted[nxt_idx_camera] if self.debug: self.out.write(str(angle_value) + " " + str(angle_value_nxt) + "\n") self.out.write(str(self.camera_angles_predicted[-1]) + "\n") self.out.flush() if abs(angle_value) > 10.0: return angle_value_nxt if abs(angle_value_nxt) > 10.0: return angle_value angle = utils.interpolate_aprox(time, self.camera_times[idx_camera], \ self.camera_angles_predicted[idx_camera], \ self.camera_times[nxt_idx_camera], \ self.camera_angles_predicted[nxt_idx_camera]) return angle
def get_x(y): _, l = binary_search(partial(get_state, y=y), 0.5, 1, upper_search_increment=lambda x: x + y // 10) # r, _ = binary_search(lambda x: 1-get_state(x, y), 0.5, l, upper_search_increment=lambda x: x + y // 5) # print(l, r) return l
def remove_node(self, name): ring_pos = self.ring_position(name) node_pos = utils.binary_search(self.nodes, ring_pos, lambda t: t[1]) print( "Removing node {}, ring_pos {} reponsible node pos {} all nodes {}" .format(name, ring_pos, node_pos, self.nodes)) if self.nodes[node_pos][0] == name: del self.nodes[node_pos]
def discover_password(): global password charset = string.ascii_letters + string.digits charset = "".join(sorted(charset)) for char_position in range(1, password_length + 1): index, _ = binary_search( (0, len(charset) - 1), lambda index, char_position: sql_inject( sqli.get("password_char").format(username, charset[ index], char_position)), char_position) password += charset[index]
def get_child(self, ch, word): pos, found = utils.binary_search(self.words, word) if found: # Found word. return BinarySearchDictionary(self.words, True) else: if pos < len(self.words) and self.words[pos].startswith(word): # Found prefix. return BinarySearchDictionary(self.words, False) else: return None
def _subtree_find_gt(self, p: Position, k: type(Position.Node.Item.key), i: int) ->\ Tuple[Optional[Position], Optional[Position.Node.Item]]: """ Returns the position and the element with the smallest key that is > k in the subtree rooted at p. k is supposed to be the i-th key in p. """ # If p is an in internal node if not self.is_leaf(p): # Then the key greater than k is the minimum in key in the subtree rooted at the child to the right of k p, _ = self._subtree_min(self._make_position(p.node.children[i])) return p, p.elements[0] else: # If p is a leaf # If k is not the last key in p if i < len(p): # Return the key to the right of k return p, p.elements[i] # If k is the last key in p, we go up walk = p # We go up until walk is the last child of its parent (above) above = self.parent(walk) # We stop when we reach the root while above is not None and walk == list(self.children(above))[-1]: # If none of the two conditions is met yet, keep going up walk = above above = self.parent(walk) # If we reached the root if above is None: # We have to return a key of root _, i = binary_search(walk.keys(), k) # If k is not greater than all the keys in the root if i < len(walk) - 1: # Then return the smallest key greater than k (increment the return value of binary_search) return walk, walk.elements[i + 1] else: # If k is greater than all the keys in the root, then no "greater then" exists return None, None # If we didn't reach the root _, i = binary_search(above.keys(), k) # Just return the smallest key in above greater than key return above, above.elements[i + 1]
def _expand_hypo(self, hypo): self.set_predictor_states(hypo.predictor_states) next_word = self.trgt_sentence[len(hypo.trgt_sentence)] ids, posterior, _ = self.apply_predictor() ind = utils.binary_search(ids, k) max_score = utils.max_(posterior) hypo.predictor_states = self.get_predictor_states() hypo.score += posterior[ind] hypo.score_breakdown.append(posterior[ind]) hypo.trgt_sentence += [next_word] self.consume(next_word)
def FMM(dicpath, textpath): # read text from file textlines = readFile(textpath) # read dic from file oriDic = readFile(dicpath) # new a dic for running code and the origin dic won't be destroy dic = [] # count the maxlen of a word maxWordLen = 0 dicSize = len(oriDic) for i in range(dicSize): tmp = oriDic[i].split(" ") # the dic format: word POS times dic.append(tmp[0]) # only needs word if (len(tmp[0]) > maxWordLen): maxWordLen = len(tmp[0]) # count time startTime = time.time() # Do FMM textSize = len(textlines) seg = [] # count = 0 for i in range(textSize): text = textlines[i].strip() wordList = [] if not len(text) == 0: linebegin = text[:19] text = text[19:] wordList.append(linebegin) while len(text) > 0: # True_statements if expression else False_statements lenTryWord = maxWordLen if len(text) > maxWordLen else len(text) tryWord = text[:lenTryWord] while not binary_search(dic, tryWord): if len(tryWord) == 1: break tryWord = tryWord[:len(tryWord) - 1] # match successfully wordList.append(tryWord) # start match the remain part text = text[len(tryWord):] seg.append(wordList) # count += 1 # print(count) endTime = time.time() print((endTime - startTime)) return seg
def right_sibling( self, p: Position, k: type(Position.Node.Item.key) = None) -> Optional[Position]: """Returns the Position of the node to the right of p""" # Validate self._validate(p) # Let parent be the parent of p parent = self.parent(p) if k is None: k = p.elements[0].key _, i = binary_search(parent.keys(), k) if i >= len(parent) - 1: # p is the rightmost child of parent return None # right sibling of p does not exist return self._make_position(parent.node.children[i + 2])
def __setitem__(self, k, v): """ Assigns value v to key k, overwriting the old value if k is already present. :param k: key to insert :param v: value associated to k :return: None """ self._count_collisions = not self._is_resizing j = self._h(k) self._bucket_setitem(j, k, v) # subroutine maintains self._n if self._n > self._load_factor[-1] * self.capacity( ): # keep maximum load factor new_maximum_capacity = self.capacity( ) * self._load_factor[-1] / self._load_factor[0] new_capacity = (self.capacity() + new_maximum_capacity) // 2 primes = load_primes() _, index = binary_search(primes, new_capacity) self._resize(primes[index])
def calc_camera_coordinates(self, time): if len(self.camera_times) == 0: return [0.0, 0.0, 0.0] idx_camera = utils.binary_search(time, self.camera_times) nxt_idx_camera = idx_camera + 1 if idx_camera == len(self.camera_times)-1: nxt_idx_camera = idx_camera if idx_camera > 0: idx_camera = idx_camera - 1 #print len(self.camera_times), len(self.camera_coordinates_predicted), idx_camera coordinates = [utils.interpolate_aprox(time, self.camera_times[idx_camera], \ self.camera_coordinates_predicted[idx_camera][i], \ self.camera_times[nxt_idx_camera], \ self.camera_coordinates_predicted[nxt_idx_camera][i]) for i in range(3)] return coordinates
def __delitem__(self, k): """ If k exists, deletes both key k and its value, otherwise it throws and exception. :param k: key to delete :return: None """ self._count_collisions = False j = self._h(k) self._bucket_delitem(j, k) # may raise KeyError self._n -= 1 # keep minimum load factor if self._n < self._load_factor[0] * self.capacity() and self.capacity( ) > DoubleHashingHashMap._MIN_CAPACITY: new_minimum_capacity = self.capacity( ) * self._load_factor[0] / self._load_factor[-1] new_capacity = (self.capacity() + new_minimum_capacity) // 2 primes = load_primes() _, index = binary_search(primes, new_capacity) self._resize(max(primes[index], DoubleHashingHashMap._MIN_CAPACITY))
def showResults(self, path): from PIL import Image, ImageFont, ImageDraw import os # print self.object_positions for filename in sorted(os.listdir(path)): if filename.endswith(".png"): print filename[:-4] t = int(filename[:-4]) print t idx = utils.binary_search(t, self.camera_times) if idx+1 == len(self.camera_times): nxtidx = idx idx = idx - 1 else: nxtidx = idx + 1 print idx pos = [utils.interpolate_aprox(t, self.camera_times[idx], \ self.object_positions[idx][i], \ self.camera_times[nxtidx], \ self.object_positions[nxtidx][i]) for i in range(3)] IMAGE_HEIGHT = 701 IMAGE_WIDTH = 801 BIN = 0.1 row = int(round(math.floor(((((IMAGE_HEIGHT*BIN)/2.0) - pos[0])/(IMAGE_HEIGHT*BIN)) * IMAGE_HEIGHT))) column = int(round(math.floor(((((IMAGE_WIDTH*BIN)/2.0) - pos[1])/(IMAGE_WIDTH*BIN)) * IMAGE_WIDTH))) print pos, row, column source_img = Image.open(path + filename) draw = ImageDraw.Draw(source_img) draw.rectangle(((column-10, row-10), (column+10, row+10))) newimgpath = path + "res/" + filename source_img.save(newimgpath, "PNG")
def find_nodes_in_range( self, start: str, stop: str) -> Set[MultiWaySearchTree.Position.Node]: retval = set() if not self.is_empty(): if start is None: # If start is None, then the first item to yield is the first item of the tree p = self.first() item = p.elements[0] else: # Search for the smallest key >= start found, p, i = self._subtree_search(self.root(), start) if found: item = p.elements[i] else: p, item = self._subtree_find_gt(p, start, i) while p is not None and (stop is None or item.key <= stop): retval.add(p.node) _, i = binary_search(p.keys(), item.key) p, item = self._subtree_find_gt(p, item.key, i + 1) return retval
def find_range( self, start: type(Position.Node.Item.key) = None, stop: type(Position.Node.Item.key) = None ) -> Iterator[Position.Node.Item]: """Returns all the elements with (key, value) such that start <= key < stop.""" if not self.is_empty(): if start is None: # If start is None, then the first item to yield is the first item of the tree p = self.first() item = p.elements[0] else: # Search for the smallest key >= start found, p, i = self._subtree_search(self.root(), start) if found: item = p.elements[i] else: p, item = self._subtree_find_gt(p, start, i) while p is not None and (stop is None or item.key < stop): yield item _, i = binary_search(p.keys(), item.key) p, item = self._subtree_find_gt(p, item.key, i + 1)
def initialize_activations_and_pointers_for_phase_one(idx_of_idx, input_sample_id, group_sample, neuron_group, act, idx_act): pointer_list = list() activations_with_idx_list = list() for i, neuron_idx in enumerate(neuron_group.neuron_idx_list): idx = idx_of_idx[neuron_idx] activations = act[idx] idx_activations = idx_act[idx] activations_with_idx = [(activations[i], idx_activations[i]) for i in range(len(activations))] activations_with_idx_list.append(activations_with_idx) sample_activation = group_sample[i] x = (sample_activation, input_sample_id) loc = binary_search(activations_with_idx, x) if loc == -1: pointer_list.append(None) else: pointer_list.append([loc + 1, loc]) return activations_with_idx_list, pointer_list
def _fusion(self, v: Position, w: Position, left=True) -> Position: """ Resolves v's underflow with a fusion with the sibling of v, i.e. w :param v: the Posiion of the node in underflow :param w: the sibling of v :param left: Whether w is the left sibling of v (default True) :return: the new node as the result of the fusion between v and w """ # Validate v_node = self._validate(v) w_node = self._validate(w) # Let p be the parent of v and w p = self.parent(v) # Let k' be the key saved in p in between the keys of v and w _, index = binary_search(p.keys(), w_node.elements[0].key) # If w is the left sibling of v, the binary search will return the index of the key to the left of k' if left: index = index + 1 # Let new_item be the Item in p with key k' new_item = p.elements[index] # Create a new node containing all keys of v except k, all keys of w and key k' new_node = self.Position.Node( self._a, self._b, w_node.elements + [new_item] + v_node.elements if left else v_node.elements + [new_item] + w_node.elements, parent=p.node, children=w_node.children + v_node.children if left else v_node.children + w_node.children) # Remove new_item from p p.elements.pop(index) # Also remove the child to the right of k' p.node.children.pop(index) # Substitute that child with new_node p.node.children[index] = new_node # v and w do not belong to the tree anymore v = w = None return self._make_position(new_node)
def find_num_bin(suma, ar=None, is_sorted=False, prnt=False): # if not is_sorted or ar is None: # ar = get_sorted_array(ar) l = len(ar) - 1 k = 0 for v in ar: b = suma - v if b < v or k == l: return False # if ar[l] == b: # if prnt: # print('b: Found a&b @', k, ',', l, ' = ', v, ',', ar[l]) # return True l = binary_search(ar, k + 1, l, b, True) if ar[l] == b and k != l: # if prnt: # print('b: Found a&b @', k, ',', l, ' = ', v, ',', ar[l]) return True k += 1 # if prnt: # print("b: 404 Not Found") return False
def find_num_evb(suma, ar=None, is_sorted=False, prnt=False): # if not is_sorted or ar is None: # ar = get_sorted_array(ar) b = binary_search(ar, 0, len(ar) - 1, suma - ar[0], True) if b <= 0: # if prnt: # print('e: 404 Not Found') return False a = 0 while True: s1 = ar[a] + ar[b] if s1 == suma: # if prnt: # print('e: Found a&b @', a, ',', b, ' = ', ar[a], ',', ar[b]) return True elif s1 < suma: a += 1 else: b -= 1 if b <= a: # if prnt: # print('e: 404 Not Found') return False
def calc_camera_distance(self, time): #print "--------> Dist_", len(self.camera_times) if len(self.camera_times) == 0: return 0.0 idx_camera = utils.binary_search(time, self.camera_times) nxt_idx_camera = idx_camera + 1 if idx_camera == len(self.camera_times)-1: nxt_idx_camera = idx_camera if idx_camera > 0: idx_camera = idx_camera - 1 #print idx_camera, nxt_idx_camera distance_val = self.camera_distances_predicted[idx_camera] distance_val_nxt = self.camera_distances_predicted[nxt_idx_camera] # print time, distance_val, distance_val_nxt # print idx_camera # print self.camera_times # print self.camera_distances_predicted # print self.camera_angles_predicted if abs(distance_val) < eps: return distance_val_nxt if abs(distance_val_nxt) < eps: return distance_val distance = utils.interpolate_aprox(time, self.camera_times[idx_camera], \ self.camera_distances_predicted[idx_camera], \ self.camera_times[nxt_idx_camera], \ self.camera_distances_predicted[nxt_idx_camera]) return distance
def _subtree_search( self, p: Position, k: type(Position.Node.Item.key) ) -> Tuple[bool, Position, int]: """ Searches key k in the subtree rooted at p. Returns: True if k is found, False otherwise Position of p's subtree having key k, index of the key k in the keys list of the position, or last node and index searched. """ # Validate node = self._validate(p) # Binary-search k in node p found, index = binary_search(p.keys(), k) # Successful search if found: return True, p, index # Next position to search in is the child next to p.keys()[index] next_position = self._make_position(node.children[index + 1]) # If this child does not exist, the search is unsuccessful if next_position is None: return False, p, index + 1 return self._subtree_search(next_position, k)
def search(track_list, target): found_index = binary_search(track_list, target) if found_index is None: return None i = found_index current_track = track_list[i].lower() result = [] while current_track.startswith(target.lower()): result.append(current_track) if i == len(track_list) - 1: break i += 1 current_track = track_list[i].lower() i = found_index if i > 0: i -= 1 current_track = track_list[i].lower() while current_track.startswith(target.lower()): result.append(current_track) if i == 0: break i -= 1 current_track = track_list[i].lower() return result
def cluster_evaluation(self): for cp in self.list_of_cp: demonstration = self.map_cp2demonstrations[cp] frm = self.map_cp2frm[cp] curr_surgeme = self.map_frm2surgeme[demonstration][frm] self.map_cp2surgemes[cp] = curr_surgeme ranges = sorted(parser.get_annotation_segments(constants.PATH_TO_DATA + constants.ANNOTATIONS_FOLDER + demonstration + "_capture2.p")) bin = utils.binary_search(ranges, frm) map_frm2surgeme_demonstration = self.map_frm2surgeme[demonstration] prev_end = bin[0] - 1 next_start = bin[1] + 1 prev_surgeme = map_frm2surgeme_demonstration[prev_end] if prev_end in map_frm2surgeme_demonstration else "start" next_surgeme = map_frm2surgeme_demonstration[next_start] if next_start in map_frm2surgeme_demonstration else "end" surgemetransition = None if abs(frm - (bin[0] - 1)) < abs(bin[1] + 1 - frm): surgemetransition = str(prev_surgeme) + "->" + str(curr_surgeme) else: surgemetransition = str(curr_surgeme) + "->" + str(prev_surgeme) self.map_cp2surgemetransitions[cp] = surgemetransition self.cp_surgemes = set(self.map_cp2surgemes.values()) # Initialize data structures table = {} for L1_cluster in self.map_level1_cp.keys(): new_dict = {} for surgeme in self.cp_surgemes: new_dict[surgeme] = 0 table[L1_cluster] = new_dict surgeme_count = {} for surgeme in self.cp_surgemes: surgeme_count[surgeme] = 0 for L1_cluster in self.map_level1_cp.keys(): list_of_cp_key = self.map_level1_cp[L1_cluster] for cp in list_of_cp_key: surgeme = self.map_frm2surgeme[self.map_cp2demonstrations[cp]][self.map_cp2frm[cp]] surgeme_count[surgeme] += 1 curr_dict = table[L1_cluster] curr_dict[surgeme] += 1 table[L1_cluster] = curr_dict final_clusters = list(set(self.map_level1_cp.keys()) - set(self.pruned_L1_clusters)) confusion_matrix = " " for surgeme in self.cp_surgemes: confusion_matrix = confusion_matrix + str(surgeme) + " " # print confusion_matrix self.file.write('\n\n ---Confusion Matrix--- \n\n') self.file.write(confusion_matrix) confusion_matrix = "" for L1_cluster in final_clusters: confusion_matrix = confusion_matrix + "\n" + L1_cluster + " " for surgeme in self.cp_surgemes: # confusion_matrix += str(float("{0:.2f}".format(table[L1_cluster][surgeme] / float(surgeme_count[surgeme])))) + " " confusion_matrix += str(round(Decimal(table[L1_cluster][surgeme] / float(surgeme_count[surgeme])), 2)) + " " confusion_matrix += '\n' # print confusion_matrix self.file.write(confusion_matrix) self.file.write("\n\n ---Surgeme Count--- \n\n") self.file.write(repr(surgeme_count)) self.file.write("\n\n")
def test(self): self.assertEqual(0, binary_search([], 9)) self.assertEqual(0, binary_search([1], 2)) self.assertEqual(1, binary_search([1], 1)) self.assertEqual(0, binary_search([2, 1], 3)) self.assertEqual(1, binary_search([2, 1], 2)) self.assertEqual(1, binary_search([2, 1], 1.5)) self.assertEqual(2, binary_search([2, 1], 1)) self.assertEqual(2, binary_search([2, 1], 0)) self.assertEqual(0, binary_search([3, 2, 1], 4)) self.assertEqual(1, binary_search([3, 2, 1], 3)) self.assertEqual(2, binary_search([3, 2, 1], 2)) self.assertEqual(3, binary_search([3, 2, 1], 0)) self.assertEqual(0, binary_search([6, 5, 4, 3, 2, 1], 7)) self.assertEqual(4, binary_search([6, 5, 4, 3, 2, 1], 3)) self.assertEqual(6, binary_search([6, 5, 4, 3, 2, 1], 0)) self.assertEqual(0, binary_search([7, 6, 5, 4, 3, 2, 1], 8)) self.assertEqual(1, binary_search([7, 6, 5, 4, 3, 2, 1], 7)) self.assertEqual(5, binary_search([7, 6, 5, 4, 3, 2, 1], 3)) self.assertEqual(7, binary_search([7, 6, 5, 4, 3, 2, 1], 0)) self.assertEqual(4, binary_search([2, 2, 2, 2, 1], 2)) self.assertEqual(5, binary_search([2, 2, 2, 2, 1], 1))