def __init__(self, site, timeout, delay, depth, threads): super(Spider, self).__init__(site, timeout, delay, threads) self.depth = depth self.visited = [] self.tasks_queue = PriorityQueue()
from Queue import PriorityQueue from fractions import Fraction nums = {} seen = set() pq = PriorityQueue() frac = Fraction(1, 2), Fraction(1, 2) pq.put_nowait(((frac[0] + frac[1]).denominator, (frac[0], frac[1]))) while not pq.empty(): weight, (frac1, frac2) = pq.get_nowait() hashing = frac1.denominator, frac2.denominator if hashing not in seen: seen.add(hashing) if weight not in nums: nums[weight] = 0 nums[weight] += 1 print '{} + {} = {}'.format(frac1, frac2, frac1 + frac2) if nums[weight] > 5: print weight print nums break fracp = Fraction(1, frac1.denominator + 1), frac2 fracpp = frac1, Fraction(1, frac2.denominator + 1) pq.put_nowait( (((fracp[0] + fracp[1]).denominator), (fracp[0], fracp[1]))) pq.put_nowait( (((fracpp[0] + fracpp[1]).denominator), (fracpp[0], fracpp[1])))
def goap(goal, cws, my_pos, action_list, child_list, current_left_layer, current_right_layer): goal_expands = [] available_paths = [] p_queue = PriorityQueue() search_done = False for successor in get_successors(goal, action_list): successor.req_world_state_change(cws, goal, goal) successor.calculate_priority(my_pos) if len(successor.required_world_state) == 0: successor.path.append(successor) available_paths.append(successor) else: goal_expands.append(successor) for expand in goal_expands: p_queue.put((expand.priority, expand)) while search_done is False: if p_queue.empty() is True: search_done = True continue top = copy.deepcopy(p_queue.get()[1]) top.path.append(top) for successor in get_successors(top.required_world_state, action_list): successor.req_world_state_change(cws, top.required_world_state, goal) calculate_successor_priority(top, successor) successor.path = top.path '''if 'stop' in successor.required_world_state: successor.path.append(successor) successor.path.reverse() available_paths.append(successor)''' if len(successor.required_world_state) == 0: successor.path.append(successor) successor.path.reverse() available_paths.append(successor) search_done = True else: p_queue.put((successor.priority, successor)) '''if p_queue.empty() is True: search_done = True''' if len(available_paths) > 0: available_paths.sort() for object in available_paths: print(object.name + '-->' + str(object.priority)) output_path = available_paths[0].path output_path_processor(goal, output_path, cws) for act in output_path: if act.name == 'put_cups': put_cup_processor(act, cws, child_list, current_left_layer, current_right_layer) dominant_processor(output_path, 'cup_get') for child in output_path: print(child.name) print(child.result_world_state) print('====================') child_action_processor(output_path, action_list) return output_path else: print('cant find path') null = [] return null
def __init__(self, title, occupancyGrid): CellBasedForwardSearch.__init__(self, title, occupancyGrid) self.aStarQueue = PriorityQueue() self.temporaryQueue = PriorityQueue()
point = Point(x * resolution + offsetPose.position.x, y * resolution + offsetPose.position.y, 0) frontier_maarray.data[index] = point expanded_maarray.data[index] = point unexplored_maarray.data[index] = point frontier_maarray.mask[index] = 1 expanded_maarray.mask[index] = 1 if currentMap.data[index] < 50 and currentMap.data[index] != -1: unexplored_maarray.mask[index] = 0 else: unexplored_maarray.mask[index] = 1 addToFrontier(start_x, start_y) print "Creating Priority Queues" frontier = PriorityQueue() expanded = PriorityQueue() # add start node print "Creating Start Node" current = Node(0, start_x, start_y, None) frontier.put((0, current)) while 1 and not rospy.is_shutdown(): try: current = frontier.get()[1] except Empty, e: print "Goal position is unreachable" return AstarResponse(None) print "i_x: %s" % current.i_x
# initialize root of the tree for beam search total_predicted_time_initialization = 0 search_node_root = NodePrediction( encode(cropped_line, cropped_times, cropped_times3, maxlen, chars, char_indices, divisor, divisor2), cropped_line, total_predicted_time_initialization) ground_truth = ''.join(line[prefix_size:prefix_size + predict_size]) ground_truth_t = times2[prefix_size - 1] case_end_time = times2[len(times2) - 1] ground_truth_t = case_end_time - ground_truth_t predicted = '' queue_next_steps = PriorityQueue() queue_next_steps.put( (-search_node_root.probability_of, search_node_root)) queue_next_steps_future = PriorityQueue() start_of_the_cycle_symbol = " " found_sattisfying_constraint = False current_beam_size = beam_size for i in range(predict_size): for k in range(current_beam_size): if queue_next_steps.empty(): break _, current_prediction_premis = queue_next_steps.get()
def __main__(): #check aruguments if len(sys.argv) == 1: details() sys.exit() if len(sys.argv) < 3: usage() try: opts, args = getopt.getopt(sys.argv[3:], "l:") except getopt.GetoptError: usage() for opt, arg in opts: if opt == "-l": global _log _log = str(arg) else: print("Unrecognized option: " + opt + "\n") usage() reference = open(sys.argv[1], "r") if (reference == None): print("Bad reference name: " + sys.argv[1]) sys.exit() annotation = open(sys.argv[2], "r") if (annotation == None): print("Bad annotation file name: " + sys.argv[1]) sys.exit() logfile = open(_log, "w") if (logfile == None): print("Bad logfile name: " + _log) sys.exit() print(codes) #patterns to extract data from input files #1 = scaffold refpat = re.compile(">(\S+)") #1 = scaffold, 2 = start, 3 = end, 4 = model, 5 = +/- annotpat = re.compile("(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)") annot = {} #read in the entire annotation for line in annotation: line = line.rstrip() m = annotpat.match(line) if (m == None): sys.stderr.write("Non-standard line (annotation):\n\t" + line + "\n") continue else: scaf = m.group(1) start = int(m.group(2)) end = int(m.group(3)) name = m.group(5) dir = m.group(4) if scaf not in annot.keys(): annot[scaf] = [] gene = Gene(name, dir) gene.putExon((start, end)) annot[scaf].append(gene) elif annot[scaf][-1].name == name: #same gene, new exon annot[scaf][-1].putExon((start, end)) else: #new gene gene = Gene(name, dir) gene.putExon((start, end)) annot[scaf].append(gene) #sort the genes in the annotation for k in annot.keys(): annot[k].sort() #read the reference file... fullQueue = PriorityQueue( ) #items are: (baseNum, scaf, code, gene_name, gene_direction) exonQueue = [] #items are: (baseNum, base) scaf = "" for line in reference: line = line.rstrip() m = refpat.match(line) if (m == None): # we're at a line of bases if scaf not in annot.keys(): sys.stderr.write("Missing scaffold from annotation: " + scaf + "\n") continue for base in line: #print (base) baseNum += 1 if len(annot[scaf]) > 0: gene = annot[scaf][0] #print(gene.getStart()) #print(baseNum) if baseNum < gene.getStart( ): #we havent reached a gene yet! fullQueue.put((baseNum, scaf, base, codes['intergene'], 'N', '0')) #print('not gene yet') elif baseNum >= gene.getNextStart( ) and baseNum < gene.getNextEnd( ): #middle of the exon stick it on the to-process queue! exonQueue.append((baseNum, base)) #print('exon') elif baseNum == gene.getNextEnd(): #end of the exon #print('end of exon '+str(gene.name)) exonQueue.append((baseNum, base)) annot[scaf][0].popExon() if annot[scaf][0].empty(): #end of the gene #print('end of gene') #sys.stderr.write("tiger "+str(baseNum)+"\n") results = process(exonQueue, scaf, gene.name, gene.dir) for i in results: fullQueue.put(i) fullQueue = printQueue(fullQueue) exonQueue = [] annot[scaf].pop( 0) #get rid of the gene in our list while len( annot[scaf] ) > 0 and annot[scaf][0].getStart() <= baseNum: sys.stderr.write( "Gene start before the end of previous gene (skipping)! " + str(annot[scaf][0]) + "\n") annot[scaf].pop( 0) #get rid of the gene in our list #sys.stderr.write("next: "+str(annot[scaf][0])+"\n") else: #after the start of the gene, but not within the next exon == intron fullQueue.put((baseNum, scaf, base, codes['intron'], gene.name, '0')) #print('intron') else: #no genes left on this scaffold, it must be intergenic! fullQueue.put( (baseNum, scaf, base, codes['intergene'], 'N', '0')) #print('end of scaffold') else: #we're at a title line fullQueue = printQueue(fullQueue) scaf = m.group(1) baseNum = 0 #print the leftovers fullQueue = printQueue(fullQueue)
class MulticastChat: multicast_group = ('224.3.29.71', 10000) multicast_ip = '224.3.29.71' hostIp = '0.0.0.0' pid = os.getpid() queueMsg = PriorityQueue() numberAckList = {} pid_list = [pid] time = 0 server_address = ((hostIp, 10000)) conversationList = [] sendDelay = 0 def __init__(self, numberOfProcesses): self.numberOfProcesses = numberOfProcesses self.sock = self.initConnection() self.synchronize(self.numberOfProcesses) self.pid_list.sort() self.pid = self.pid_list.index(self.pid) thread.start_new_thread(self.recvListener, ()) print "Ready - " + self.presentationMsg() print "Send your message:" while True: msg = raw_input() if msg[:5] == "DELAY": stopPid = int(msg[5:].split("-s")[0]) seconds = int(msg[5:].split("-s")[1]) self.sendDelayMsg(stopPid, seconds) elif msg[:4] == "LIST": self.printConversationLog() elif msg[:3] == "PID": print self.presentationMsg() elif msg[:3] == "STP": pidStop = int(msg[4:].split("-s")[0]) seconds = int(msg[4:].split("-s")[1]) self.sendStopMsg(pidStop, seconds) else: self.sendMsg(msg) print "end" def presentationMsg(self): return "I'm the process no: " + str(self.pid) def printConversationLog(self): for i in self.conversationList: print i def sendDelayMsg(self, pidDelay, seconds): msg = "DELAY " + str(pidDelay) + " -s" + str(seconds) self.sock.sendto(msg, self.multicast_group) def initConnection(self): sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) membership = socket.inet_aton(self.multicast_ip) + socket.inet_aton( self.hostIp) sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, membership) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) sock.bind(self.server_address) return sock def synchronize(self, numberOfProcesses): print '\nSynchronizing..' #print 'Recv %s'%self.pid synchroMsg = 'SYN ' + str(self.pid) while len(self.pid_list) < self.numberOfProcesses: self.sock.sendto(synchroMsg, self.multicast_group) data, address = self.sock.recvfrom(1024) pidRecv = int(data[4:]) if not (pidRecv in self.pid_list): self.pid_list.append(pidRecv) #print 'Recv %s'%data self.sock.sendto(synchroMsg, self.multicast_group) def sendStopMsg(self, pidNo, seconds): msg = "STP " + str(pidNo) + " -s " + str(seconds) self.sock.sendto(msg, self.multicast_group) def sendMsg(self, msg): self.time += 1 msgTosend = "MSG ID:" + str(self.time) + "-" + str( self.pid) + "\r\nContent:" + msg #print "sended: "+msgTosend if self.sendDelay > 0: print "delaying on send for %d seconds" % self.sendDelay time.sleep(self.sendDelay) self.sendDelay = 0 self.sock.sendto(msgTosend, self.multicast_group) def recvMsg(self, msg, msgId, timestamp, senderId): msgGuard = str(senderId) + " - Time " + str( timestamp) + ": " + msg.split(":")[1] self.queueMsg.put((msgId, msgGuard)) self.time = 1 + max(self.time, timestamp) self.ackMsg(msgId) def ackMsg(self, msgId): self.time += 1 ack = "ACK " + str(msgId) + ":" + str(self.time) if self.sendDelay > 0: print "delaying on ACK for %d seconds" % self.sendDelay time.sleep(self.sendDelay) print "sending" self.sendDelay = 0 self.sock.sendto(ack, self.multicast_group) def recvAck(self, msgId, timestamp): self.time = 1 + max(self.time, timestamp) if msgId in self.numberAckList: self.numberAckList[msgId] += 1 else: self.numberAckList[msgId] = 1 def deliverMsg(self, msgId): if self.numberAckList[msgId] < self.numberOfProcesses: return time, msg = self.queueMsg.get(False) if time != msgId: self.queueMsg.put((time, msg)) return self.conversationList.append(msg) print msg self.time += 1 del self.numberAckList[msgId] while not (self.queueMsg.empty()): time, msg = self.queueMsg.get(False) if (self.numberAckList[time] < self.numberOfProcesses): self.queueMsg.put((time, msg)) break self.conversationList.append(msg) print msg self.time += 1 del self.numberAckList[time] def recvListener(self): while True: data, address = self.sock.recvfrom(1024) cmd = data[:3] if data[:5] == "DELAY": stopPid = int(data[5:].split("-s")[0]) seconds = int(data[5:].split("-s")[1]) if (stopPid == self.pid): self.sendDelay = seconds print "Delayed on send" elif cmd == "ACK": msgID = int(data.split(":")[0][4:]) timestamp = int(data.split(":")[1]) self.recvAck(msgID, timestamp) self.deliverMsg(msgID) elif cmd == "MSG": msgId, contentMsg = data.split("\r\n") timeRecv = int(msgId[7:].split("-")[0]) senderId = int(msgId[7:].split("-")[1]) msgId = int("".join(msgId[7:].split("-"))) content = str(msgId) + ": " + contentMsg[8:] self.recvMsg(content, msgId, timeRecv, senderId) elif cmd == "STP": stopPid = int(data[4:].split("-s")[0]) seconds = int(data[4:].split("-s")[1]) if stopPid != self.pid: continue print "Stopped to listen for %d seconds" % seconds time.sleep(seconds) print "Woke up"
from pritunl import logger from pritunl import mongo from pritunl import listener from Queue import PriorityQueue import pymongo import random import bson import datetime import threading import time import bson import collections running_queues = {} runner_queues = [PriorityQueue() for _ in xrange(3)] thread_limits = [ threading.Semaphore(x) for x in ( settings.app.queue_low_thread_limit, settings.app.queue_med_thread_limit, settings.app.queue_high_thread_limit, ) ] def add_queue_item(queue_item): if queue_item.id in running_queues: return running_queues[queue_item.id] = queue_item logger.debug(
def __init__(self): self._queue = PriorityQueue()
def __init__(self, maxlength=0, length_tol=1000): self.pq = PriorityQueue() self.decrease_length = multiprocessing.Lock() self.maxlength = maxlength self.length_tol = length_tol
def __init__(self, title, occupancyGrid): CellBasedForwardSearch.__init__(self, title, occupancyGrid) self.priorityQueue = PriorityQueue()
def __init__(self): self._pending_nodes = LifoQueue() self._pending_nodes_best_bound = PriorityQueue()
def reset_ctxt_tasks(self): with self._lock: self.ctxt_tasks = PriorityQueue()
def findOptimalPath(ghostCrd, pManCrd, scene): global graph drc = isAdjacent(Node(pManCrd),Node(ghostCrd),scene) if drc: return [(Node(ghostCrd),drc),(Node(ghostCrd),None)] graph = generateStateGraph(ghostCrd, pManCrd, scene) frontier = PriorityQueue() # create start node start = graph[repr(Node(ghostCrd))] start.g = 0 # create frontier frontier.put(start) # keep track of visited states and previous min cost with # dictionary visited = {repr(start):start} while not frontier.empty(): current_node = frontier.get() # if node has already been pruned, ignore if current_node.pruned: continue # check if node represents solution if current_node == Node(pManCrd): # reconstruct path using parent attribute path = [] dest = current_node while dest.parent: path.append((dest.parent,[e.drc for e in dest.parent.edges if e.adjNode == dest][0])) dest = path[-1][0] return list(reversed(path)) # expand node by generating child nodes from legal moves for edge in current_node.edges: c = edge.adjNode c.edges = graph[str(c)].edges if any(c == edge.adjNode for edge in graph[repr(Node(pManCrd))].edges): if c.crd[1] == pManCrd[1]: minDist = min((abs(c.crd[0]-pManCrd[0]),'LEFT'), (len(scene[0])-abs(c.crd[0]-pManCrd[0]),'RIGHT')) else: if c.crd[1] < pManCrd[1]: minDist = (pManCrd[1]-c.crd[1],'DOWN') else: minDist = (c.crd[1]-pManCrd[1],'UP') c.edges.add(Edge(graph[repr(Node(pManCrd))], *minDist)) c.g = current_node.g+edge.weight c.h = heuristic(c, pManCrd,scene) c.f = c.g+c.h c.parent = current_node # ignore if visited or path is not more efficient # if path is more efficient, prune previous node if repr(c) in visited: if c.g >= visited[repr(c)].g: continue else: visited[repr(c)].pruned = True # add to visited nodes visited[repr(c)] = c # add to frontier frontier.put(c)
def calc_max_coverage_coor(xmin, ymin, zmin, xmax, ymax, zmax, rmax): def bot_clips_bbox(bot, bbox_xmin, bbox_ymin, bbox_zmin, bbox_xmax, bbox_ymax, bbox_zmax): ## test if this bot's octahedral sensor-volume ## intersects the bbox {x,y,z}min - {x,y,z}max assert (bbox_xmin <= bbox_xmax) assert (bbox_ymin <= bbox_ymax) assert (bbox_zmin <= bbox_zmax) dist = 0 dist += (bbox_xmin - bot[0]) * (bot[0] < bbox_xmin) dist += (bot[0] - bbox_xmax) * (bot[0] > bbox_xmax) dist += (bbox_ymin - bot[1]) * (bot[1] < bbox_ymin) dist += (bot[1] - bbox_ymax) * (bot[1] > bbox_ymax) dist += (bbox_zmin - bot[2]) * (bot[2] < bbox_zmin) dist += (bot[2] - bbox_zmax) * (bot[2] > bbox_zmax) return (dist <= bot[3]) def pq_add(pq, bbox_xmin, bbox_ymin, bbox_zmin, cur_bbox_size): bbox_xmax = bbox_xmin + cur_bbox_size - 1 bbox_ymax = bbox_ymin + cur_bbox_size - 1 bbox_zmax = bbox_zmin + cur_bbox_size - 1 num_bots_in_bbox = 0 for bot in bots: num_bots_in_bbox += bot_clips_bbox(bot, bbox_xmin, bbox_ymin, bbox_zmin, bbox_xmax, bbox_ymax, bbox_zmax) if (num_bots_in_bbox == 0): return False ## find Manhattan distance from origin to the closest corner of the bounding-box ## box with largest number of bots clipping it should be processed first, negate ## the count since PQ is constructed as a min-heap ## in case of ties, PQ will yield the box with smallest origin distance and size ## (ordering by size first and distance second also works and is slightly faster ## on the given input) ## this processing order ensures the problem is solved when reaching a 1x1x1 box ## since 1) no larger box can intersect more bot sensor-volumes, and 2) no other ## 1x1x1 box intersecting as many sensor-volumes can be closer to the origin ## min_orig_dist_x = min(abs(bbox_xmin), abs(bbox_xmax)) min_orig_dist_y = min(abs(bbox_ymin), abs(bbox_ymax)) min_orig_dist_z = min(abs(bbox_zmin), abs(bbox_zmax)) min_orig_dist = min_orig_dist_x + min_orig_dist_y + min_orig_dist_z ##!! pq.put((-num_bots_in_bbox, min_orig_dist, cur_bbox_size, bbox_xmin, bbox_ymin, bbox_zmin)) pq.put((-num_bots_in_bbox, cur_bbox_size, min_orig_dist, bbox_xmin, bbox_ymin, bbox_zmin)) return True ## determine size of the power-of-two bounding cube max_size = max(xmax - xmin, ymax - ymin, zmax - zmin, rmax) bbox_size = next_power_of_two(max_size) bbox_queue = PriorityQueue() pq_add(bbox_queue, xmin, ymin, zmin, bbox_size) while (bbox_queue.qsize() > 0): ##!! (num_bots, orig_dist, bb_size, x, y, z) = bbox_queue.get() (num_bots, bb_size, orig_dist, x, y, z) = bbox_queue.get() if (bb_size == 1): return ((x, y, z), orig_dist, -num_bots) bb_size >>= 1 ## insert top-left corner coordinates of each child bounding-box pq_add(bbox_queue, x, y, z, bb_size) pq_add(bbox_queue, x, y, z + bb_size, bb_size) pq_add(bbox_queue, x, y + bb_size, z, bb_size) pq_add(bbox_queue, x, y + bb_size, z + bb_size, bb_size) pq_add(bbox_queue, x + bb_size, y, z, bb_size) pq_add(bbox_queue, x + bb_size, y, z + bb_size, bb_size) pq_add(bbox_queue, x + bb_size, y + bb_size, z, bb_size) pq_add(bbox_queue, x + bb_size, y + bb_size, z + bb_size, bb_size) return ((0, 0, 0), 0, 0)
def main(): total_service_time = 0 clock = 0 time_limit = 2000 total_inter_arrival_time = 0 max_queue_length = 0 customer_count = 0 maximum_customer_wait_time = 0 total_customer_wait_time = 0 # input number on tellers number_of_tellers = raw_input("Enter number of tellers ") queue_of_events = PriorityQueue() # place an arrival node onto the Event Queue #generate service time inter_arrival = randint(1, 5) total_inter_arrival_time += inter_arrival tmp_arrival = EventItem(inter_arrival + clock, randint(5, 11), -1) queue_of_events.put((tmp_arrival.time_of_day, tmp_arrival)) total_service_time += tmp_arrival.service_time #generating tellers tellers = [] first_snapshot = False second_snapshot = False third_snapshot = False for number in range(0, int(number_of_tellers)): tellers.append(Teller(number)) while clock < time_limit: if not first_snapshot and clock > 500: print_snapshot(clock, queue_of_events, tellers) first_snapshot = True elif not second_snapshot and clock > 1000: print_snapshot(clock, queue_of_events, tellers) second_snapshot = True elif not third_snapshot and clock > 1500: print_snapshot(clock, queue_of_events, tellers) third_snapshot = True temp_event = queue_of_events.get()[1] # remove first item of queue for teller in tellers: if teller.line_of_customers.empty( ): # checking if queue of teller is empty teller.idle_time += (temp_event.time_of_day - clock) clock = temp_event.time_of_day # updating clock to time of day if temp_event.type_of_event == -1: shortest_teller_line = tellers[0] for teller in tellers: if shortest_teller_line.line_of_customers.qsize( ) > teller.line_of_customers.qsize(): shortest_teller_line = teller # shortest_teller_line.line_of_customers.put(shortest_teller_line, teller) #check this statement shortest_teller_line.line_of_customers.put( (temp_event.time_of_day, temp_event)) if shortest_teller_line.line_of_customers.qsize() == 1: time_of_day = clock + temp_event.service_time departure = EventItem( time_of_day, temp_event.service_time, shortest_teller_line.number) # placing event inside queue queue_of_events.put((departure.time_of_day, departure)) #generating new arrival inter_arrival = randint(1, 5) total_inter_arrival_time += inter_arrival tmp_arrival = EventItem(inter_arrival + clock, randint(5, 11), -1) queue_of_events.put((tmp_arrival.time_of_day, tmp_arrival)) total_service_time += tmp_arrival.service_time if shortest_teller_line.line_of_customers.qsize( ) > max_queue_length: max_queue_length = shortest_teller_line.line_of_customers.qsize( ) #next departure node else: # add 1 to the customer customer_count += 1 # remove customer from the indicated queue teller = tellers[temp_event.type_of_event] customer = teller.line_of_customers.get()[1] # calculate the wait time for this customer as customer_wait_time = clock - (customer.time_of_day + customer.service_time) total_customer_wait_time += customer_wait_time if customer_wait_time > maximum_customer_wait_time: maximum_customer_wait_time = customer_wait_time if not teller.line_of_customers.empty(): time_of_day = clock + queue_peek( teller.line_of_customers)[1].service_time departure = EventItem( time_of_day, temp_event.service_time, teller.number) # placing event inside queue queue_of_events.put((departure.time_of_day, departure)) customers_left_in_queue = 0 for teller in tellers: customers_left_in_queue += teller.line_of_customers.qsize() print_snapshot(clock, queue_of_events, tellers) print_results(customer_count, total_inter_arrival_time, total_service_time, tellers, maximum_customer_wait_time, max_queue_length, customers_left_in_queue, total_customer_wait_time)
def __init__(self, _k): self.q = PriorityQueue() self.k = _k self.s = 0 self.min = 0
def knn_search(knn_graph, distance_metric, d, m, k): """ :param knn_graph: existing graph :param distance_metric: metric using which the nearest neighbors should be determined :param d: new data point :param m: number of searches to be performed :param k: number of neighbors to be searched for :return: a list of k neighbors for the data point d """ neighbor_set = PriorityQueue() result = PriorityQueue() non_visited_set = set(knn_graph) - {d} # m searches are needed for i in range(m): if len(non_visited_set) == 0: break elif len(non_visited_set) == 1: random_vertex_index = 0 else: random_vertex_index = random.randint(0, len(non_visited_set) - 1) # once we have the index of random vertex, retrieve the vertex random_vertex = list(non_visited_set)[random_vertex_index] # print "search number: ", i, " random vertex chosen", random_vertex.id if distance_metric == "euclidean": random_vertex.dist = compute_euclidean_distance(d, random_vertex) elif distance_metric == "manhattan": random_vertex.dist = compute_manhattan_distance(d, random_vertex) neighbor_set.put((random_vertex.dist, random_vertex)) temp_set = PriorityQueue() while True: if neighbor_set.qsize() == 0: break cn = neighbor_set.get() closest_neighbor = cn[1] closest_neighbor.dist = cn[0] # print "closest_neighbor distance from data point", closest_neighbor.id, closest_neighbor.dist # get kth smallest element from result, i.e., element at (k-1)th position in result temp_result = [] kth_element = None if temp_set.qsize() >= k: # pop 0 to k-2 elements for j in range(k - 1): temp_result.append(temp_set.get()) # get (k-1)th element e = temp_set.get() kth_element = e[1] kth_element.dist = e[0] # push back popped elements into result for element in temp_result: temp_set.put((element[0], element[1])) temp_set.put((kth_element.dist, kth_element)) # check stop condition if kth_element is not None and closest_neighbor.dist > kth_element.dist: break neighbors_of_closest_neighbor = knn_graph[closest_neighbor] for neighbor in neighbors_of_closest_neighbor: if neighbor in non_visited_set: non_visited_set.remove(neighbor) if distance_metric == "euclidean": neighbor.dist = compute_euclidean_distance(d, neighbor) elif distance_metric == "manhattan": neighbor.dist = compute_manhattan_distance(d, neighbor) neighbor_set.put((neighbor.dist, neighbor)) temp_set.put((neighbor.dist, neighbor)) for data_point in temp_set.queue: result.put((data_point[0], data_point[1])) # return the k best neighbors of query point k_neighbors = [] for i in range(k): neighbor = result.get() k_neighbors.append(neighbor[1]) # print len(k_neighbors) return k_neighbors
def aStar(self, start, goal): visited = [] goal = [int(goal[0]), int(goal[1])] start = [int(start[0]), int(start[1])] frontier = PriorityQueue() path = [] bestPathSoFar = [9999999, []] found = False mult = 75 print(goal) #if (self.gridToInd(start) == False): # print("Robot is out of map!") # return None H = self.heuristic(start, goal) frontier.put((H, 0, start, [start])) print("H:", H, "*", mult, "=", H * mult) #if (self.gridToInd(goal) == False): # print("Goal is out of map!") # return None #goalInd = self.tmp dist = [[1, 0], [-1, 0], [0, 1], [0, -1], [1, 1], [-1, 1], [1, -1], [-1, -1]] print(self.width * self.height) print(self.grid[start[0]][start[1]]) print(self.grid[goal[0]][goal[1]]) H = H * mult while not frontier.empty(): #for i in range(0,10): current = frontier.get() #print("New iter #") #print(current) #print(frontier.qsize()) #print(current[2], goal) if current[2] == goal: path = current[3] break if (current[2] in visited): continue else: visited.append(current[2]) if (len(visited) > H): break for k in range(len(dist)): try: #print("Cons: ", current[2][0] + dist[k][0], current[2][1] + dist[k][1]) if ([ current[2][0] + dist[k][0], current[2][1] + dist[k][1] ] == goal): print("GOAL IS FOUND!") found = True cost = current[1] + 1 if (k >= 4): cost += 0.41 #ind_cp = path_cp = current[3][:] path_cp.append(goal) frontier = PriorityQueue() frontier.put((priority, cost, goal, path_cp)) else: #print(current[2][0] + dist[k][0], current[2][1] + dist[k][1], dist[k], self.grid[current[2][0] + dist[k][0]][current[2][1] + dist[k][1]]) if (not found and ((self.grid[current[2][0] + dist[k][0]][current[2][1] + dist[k][1]] < 26 and self.grid[current[2][0] + dist[k][0]][ current[2][1] + dist[k][1]] >= 0) or len(current[3]) < self.threshould)): ind = [ current[2][0] + dist[k][0], current[2][1] + dist[k][1] ] if (ind not in visited): cost = current[1] + 1 if (k >= 4): cost += 0.41 #print("HERE") heur = self.heuristic(ind, goal) priority = cost + heur path_cp = current[3][:] path_cp.append(ind) frontier.put((priority, cost, ind, path_cp)) #print("ADDED: ", priority, cost, ind, path_cp) if bestPathSoFar[0] > heur: bestPathSoFar = [heur, path_cp] #visited.append(ind) if (self.toPlot): self.plotPlan(ind) except: pass print(frontier.qsize(), len(visited)) path_fin = [] # else: # print("WTF IS GOING ON???") if (len(path) == 0): print("CANNOT FIND A PATH!") print(bestPathSoFar) #return bestPathSoFar[1] if (bestPathSoFar[0] < 35 and len(bestPathSoFar[1]) > 12): #self.threshould+5 path = bestPathSoFar[1] if (len(path) <= 10 or len(path) > 75): path = [] for ind2, n in enumerate(path): # if (self.indToGrid(n)): #print(self.grid[n[0]][n[1]]) print(ind2, n, self.grid[n[0]][n[1]]) #path_fin.append(np.array((n[0],n[1]), dtype=float)) if (ind2 < (self.threshould) or (self.grid[n[0]][n[1]] <= 26 and self.grid[n[0]][n[1]] >= 0)): path_fin.append(np.array((int(n[0]), int(n[1])), dtype=int)) return path_fin
def solveProblem(self,filename, algo): graph = self.parseInput(filename) if graph == None: return if algo == "unicost": q = PriorityQueue() for edge in graph.sensors: q.put(self.ucs(graph,edge)) finalTuple = q.get() # print finalTuple cost = finalTuple[0] path = finalTuple[1][0] queueSize = finalTuple[1][2] visitedSize = finalTuple[1][3] time = finalTuple[1][4] print "Uniform Cost Search Result for ", filename print "Assignments: " for i in range(0, len(path), 2): sensor = path[i] target = path[i + 1] print sensor, " -> ", target print "Time: ", time print "Max Frontier Size: ", queueSize print "Max Visited Size: ", visitedSize print "Cost: ", -cost elif algo == "astar": q = PriorityQueue() for edge in graph.sensors: q.put(self.astar(graph,edge)) finalTuple = q.get() # print finalTuple cost = finalTuple[0] path = finalTuple[1][0] queueSize = finalTuple[1][2] visitedSize = finalTuple[1][3] time = finalTuple[1][4] print "AStar Result for ", filename print "Assignments: " for i in range(0, len(path), 2): sensor = path[i] target = path[i + 1] print sensor, " -> ", target print "Time: ", time print "Max Frontier Size: ", queueSize print "Max Visited Size: ", visitedSize print "Cost: ", -cost elif algo == "greedy": q = PriorityQueue() for edge in graph.sensors: q.put(self.greedy(graph,edge)) finalTuple = q.get() # print finalTuple cost = finalTuple[0] path = finalTuple[1][0] queueSize = finalTuple[1][2] visitedSize = finalTuple[1][3] time = finalTuple[1][4] print "Greedy Result for ", filename print "Assignments: " for i in range(0, len(path), 2): sensor = path[i] target = path[i + 1] print sensor, " -> ", target print "Time: ", time print "Max Frontier Size: ", queueSize print "Max Visited Size: ", visitedSize print "Cost: ", -cost elif algo == "iddfs": q = PriorityQueue() for edge in graph.sensors: q.put(self.id_dfs(graph,edge)) finalTuple = q.get() # print finalTuple expansion = finalTuple[0] cost = finalTuple[1][4] path = finalTuple[1][0] queueSize = finalTuple[1][2] visitedSize = finalTuple[1][3] time = finalTuple[1][2] print "IDDFS Result for ", filename print "Assignments: " for i in range(0, len(path), 2): sensor = path[i] target = path[i + 1] print sensor, " -> ", target print "Time: ", time print "Max Frontier Size: ", queueSize print "Max Visited Size: ", visitedSize print "Max Expansion: ", expansion print "Cost: ", cost elif algo == "bfs": q = PriorityQueue() for edge in graph.sensors: q.put(self.bfs(graph,edge)) finalTuple = q.get() path = finalTuple[0] queueSize = finalTuple[3] visitedSize = finalTuple[2] time = finalTuple[1] print "BFS Result for ", filename print "Assignments: " for p in path: print p print "Time: ", time print "Max Frontier Size: ", queueSize print "Max Visited Size: ", visitedSize
GLOBAL_FLOOD_COOLDOWN = timedelta( seconds=config.getint('regexbot', 'global_flood_cooldown')) MAX_MESSAGES = config.getint('regexbot', 'max_messages') MAX_MESSAGE_SIZE = config.getint('regexbot', 'max_message_size') try: NICKSERV_PASS = str(config.get('regexbot', 'nickserv_pass')) except: NICKSERV_PASS = None message_buffer = {} last_message = datetime.now() last_message_times = {} flooders = {} ignore_list = [] channel_list = [] user_timeouts = PriorityQueue() channel_timeouts = PriorityQueue() if config.has_section('ignore'): for k, v in config.items('ignore'): try: ignore_list.append(regex.compile(str(v), regex.I)) except Exception, ex: print "Error compiling regular expression in ignore list (%s):" % k print " %s" % v print ex exit(1) for channel in CHANNELS: c = channel.lower() message_buffer[c] = []
def __init__(self): self._timers = PriorityQueue() self._map = {}
def find_path(source, destination, mesh): print "I'm in the method" sx, sy = source dx, dy = destination sourcebox = None destbox = None visited = [] path = [] detail_points = {} for box in mesh['boxes']: x1, x2, y1, y2 = box if x1 < sx and x2 > sx and y1 < sy and y2 > sy: #visited.append(box) sourcebox = box if x1 < dx and x2 > dx and y1 < dy and y2 > dy: #visited.append(box) destbox = box if sourcebox == destbox: return [(source, destination)], [sourcebox] #Dijkstra's Algorithm/ANY SEARCH THINGY HERE dist = {} prev = {} dist[sourcebox] = 0 prev[sourcebox] = None firstboxsource = (dist[sourcebox], sourcebox) priorityQ = PriorityQueue() priorityQ.put(firstboxsource) standing_point = source path = [] while not priorityQ.empty(): #print "I'm in an infinite loop!" current = priorityQ.get() visited.append(current[1]) if current[1] == destbox: end = current[1] boxes = [] while end is not None: boxes.append(end) #print prev[end] end = prev[end] stand = source print boxes for box in boxes: path.append((stand, find_point(stand, box))) stand = find_point(stand, box) path.append((stand, destination)) print path return path, visited neighbors = mesh['adj'][current[1]] for n in neighbors: alt = dist[current[1]] + point_distance( standing_point, find_point(standing_point, current[1])) if n not in dist or alt < dist[n]: standing_point = find_point(standing_point, current[1]) dist[n] = alt prior = alt + heuristic_basic(destbox, current[1]) priorityQ.put((prior, n)) prev[n] = current[1] '''#breadth first search vertex = None prev = {} counter = 0 q = Queue() q.put(sourcebox) prev[sourcebox] = None visited.append(sourcebox) finalbox = None while not q.empty(): v = q.get() if box_equal(v, destbox): finalbox = v break for n in mesh['adj'][v]: if n not in visited: q.put(n) visited.append(n) prev[n] = v''' '''end = finalbox path.append(((dx, dy), (get_midpoint(end)))) while prev[end] is not None: path.append((get_midpoint(prev[end]), get_midpoint(end))) end = prev[end] path.append(((sx, sy), get_midpoint(end)))''' print "No path!" return [], visited
""" author: Yijun Zhang [email protected] Xinyi Ma [email protected] """ import sys import fileinput from Queue import PriorityQueue openlist = PriorityQueue() closelist = [] insertion_order = 0 class Node: def __init__(self, state, cost, path, order): self.state = state self.cost = cost self.heuristic = sum(state[:-1]) self.path = path self.order = order def __lt__(self, other): myf = self.cost + self.heuristic otherf = other.cost + other.heuristic if myf != otherf: return myf < otherf else: return self.order < other.order
def compute(self, start, goal): frontier = PriorityQueue() frontier.put((0, start)) frontier_nodes = [start] already_explored = [start] came_from = {start: None} cost_so_far = {start: 0} while not frontier.empty(): queue_entry = frontier.get() current = queue_entry[1] if self.draw and (current in frontier_nodes): frontier_nodes.remove(current) for next_node in current.neighbors: # Get the current node from the graph next_node = self._graph[next_node] new_cost = cost_so_far[current] + 1 #self._costmap.data[current.y * self._costmap.info.height + current.x] if (next_node not in cost_so_far) or (new_cost < cost_so_far[next_node]): cost_so_far[next_node] = new_cost priority = new_cost + self.heuristic(next_node, goal) frontier.put((priority, next_node)) came_from[next_node] = current if self.draw and (next_node not in frontier_nodes): frontier_nodes.append(next_node) if current not in already_explored: already_explored.append(current) # Update visualization if self.draw: self.drawNodes(frontier_nodes, "frontier") self.drawNodes(already_explored, "explored") if current == goal: break # Work our way back through the came_from chain from the goal to the start path = [goal] previous_node = came_from[goal] while previous_node is not None: path.insert(0, previous_node) previous_node = came_from[previous_node] self.drawNodes(path, "path") # Compute ros Path waypoints = [] index = 0 current_dir = None for node in path: try: next_node = path[index + 1] # If we've changed directions, and add a waypoint if so this_dir = math.atan2((next_node.y - node.y), (next_node.x - node.x)) if current_dir == None or this_dir != current_dir: current_dir = this_dir # copied some stuff from # https://www.programcreek.com/python/example/70252/geometry_msgs.msg.PoseStamped pose = PoseStamped() pose.header.seq = len(waypoints) pose.header.frame_id = "map" pose.header.stamp = rospy.Time.now() (xc, yc) = self.mapCoordsToWorld(node.x, node.y) pose.pose.position.x = xc pose.pose.position.y = yc pose.pose.position.z = 0 q = quaternion_from_euler(0.0, 0.0, current_dir) pose.pose.orientation = Quaternion(*q) waypoints.append(pose) index += 1 except IndexError: # We've reached the end of the loop, add last waypoint pose = PoseStamped() pose.header.seq = len(waypoints) pose.header.frame_id = "map" pose.header.stamp = rospy.Time.now() (xc, yc) = self.mapCoordsToWorld(node.x, node.y) pose.pose.position.x = xc pose.pose.position.y = yc pose.pose.position.z = 0 q = quaternion_from_euler(0.0, 0.0, current_dir) pose.pose.orientation = Quaternion(*q) waypoints.append(pose) path_msg = Path() path_msg.header.frame_id = "map" path_msg.header.stamp = rospy.Time.now() path_msg.poses = waypoints return path_msg
def setUp(self): self.queue = PriorityQueue()
def __init__(self, start, goal): self.path = [] self.visitedQueue = [] self.priorityQueue = PriorityQueue() self.start = start self.goal = goal
def solveLabyrinth(): seed(None) startX = 0 startY = 0 while True: (r, g, b, a) = bg.get_at((startX, startY)) if r == g == b == 255: break else: startX += 1 startY += 1 (endX, endY) = bg.get_size() endX -= 1 endY -= 1 while True: (r, g, b, a) = bg.get_at((endX, endY)) if r == g == b == 255: break else: endX -= 1 endY -= 1 queue = PriorityQueue() queue.put((randint(0, 100), (startX, startY))) pixel(bg, startX, startY, Color(START_COLOR)) while not queue.empty(): (a, (x, y)) = queue.get() if (endX == x and endY == y): break # left (r, g, b, a) = bg.get_at((x - 1, y)) if r == g == b == 255: queue.put((randint(0, 100), (x - 1, y))) pixel(bg, x - 1, y, Color(LEFT_COLOR)) # right (r, g, b, a) = bg.get_at((x + 1, y)) if r == g == b == 255: queue.put((randint(0, 100), (x + 1, y))) pixel(bg, x + 1, y, Color(RIGHT_COLOR)) # up (r, g, b, a) = bg.get_at((x, y - 1)) if r == g == b == 255: queue.put((randint(0, 100), (x, y - 1))) pixel(bg, x, y - 1, Color(UP_COLOR)) # down (r, g, b, a) = bg.get_at((x, y + 1)) if r == g == b == 255: queue.put((randint(0, 100), (x, y + 1))) pixel(bg, x, y + 1, Color(DOWN_COLOR)) screen.blit(bg, (0, 0)) pygame.display.update() while endX != startX and endY != startY: color = bg.get_at((endX, endY)) pixel(bg, endX, endY, Color('#ff0000')) if Color(RIGHT_COLOR) == color: endX -= 1 if Color(LEFT_COLOR) == color: endX += 1 if Color(UP_COLOR) == color: endY += 1 if Color(DOWN_COLOR) == color: endY -= 1 screen.blit(bg, (0, 0)) pygame.display.update()
def play_video(BASE, video_uri = common.args.url, media_base = VIDEOURL): video_url = media_base + video_uri try: qbitrate = common.args.quality except: qbitrate = None video_url2 = 'stack://' closedcaption = [] exception = False queue = PriorityQueue() segments = [] if 'feed' in video_uri: feed_url = video_uri else: swf_url = connection.getRedirect(video_url, header = {'Referer' : BASE}) params = dict(item.split("=") for item in swf_url.split('?')[1].split("&")) uri = urllib.unquote_plus(params['uri']) config_url = urllib.unquote_plus(params['CONFIG_URL'].replace('Other', DEVICE)) config_data = connection.getURL(config_url, header = {'Referer' : video_url, 'X-Forwarded-For' : '12.13.14.15'}) config_tree = BeautifulSoup(config_data, 'html.parser') if not config_tree.error: feed_url = config_tree.feed.string uri = urllib.quote_plus(uri) feed_url = feed_url.replace('{uri}', uri).replace('&', '&').replace('{device}', DEVICE).replace('{ref}', 'None').replace('{type}', 'network').strip() else: exception = True error_text = config_tree.error.string.split('/')[-1].split('_') if error_text[1] == 'loc': params = dict(item.split("=") for item in config_url.split('?')[-1].split('&')) common.show_exception('Geo', params['geo']) if not exception: feed_data = connection.getURL(feed_url, header = {'X-Forwarded-For' : '12.13.14.15'}) video_tree = BeautifulSoup(feed_data, 'html.parser', parse_only = SoupStrainer('media:group')) video_segments = video_tree.find_all('media:content') if not video_segments: video_tree = BeautifulSoup(feed_data, 'html.parser') common.show_exception(video_tree.find('meta', property = "og:site_name")['content'], video_tree.find('meta', property = "og:url")['content']) exception = True threads = [] for i, video_item in enumerate(video_segments): try: threads.append(Thread(get_videos, queue, i, video_item, qbitrate)) except Exception, e: print e [i.start() for i in threads] [i.join() for i in threads] while not queue.empty(): video_data2 = queue.get() video_url2 += video_data2[1] + ' , ' segments.append(video_data2[2]) closedcaption.append((video_data2[3], video_data2[2], video_data2[0])) player._segments_array = segments filestring = 'XBMC.RunScript(' + os.path.join(ustvpaths.LIBPATH,'proxy.py') + ', 12345)' xbmc.executebuiltin(filestring) finalurl = video_url2[:-3] localhttpserver = True time.sleep(20) if (addon.getSetting('enablesubtitles') == 'true') and closedcaption: convert_subtitles(closedcaption) player._subtitles_Enabled = True item = xbmcgui.ListItem(path = finalurl) queue.task_done() try: item.setThumbnailImage(common.args.thumb) except: pass try: item.setInfo('Video', { 'title' : common.args.name, 'season' : common.args.season_number, 'episode' : common.args.episode_number, 'TVShowTitle' : common.args.show_title }) except: pass xbmcplugin.setResolvedUrl(pluginHandle, True, item) while player.is_active: player.sleep(250)