def greedy_approx(G): vis = set() pq = PQDict() tot_length = 0 seq = [] start = 1 curr = start vis.add(curr) seq.append(curr) while len(seq) != len(G.nodes()): next = [ list for list in ( sorted(G.edges(curr, data=True), key=lambda (source, target, data): data['weight'])) if list[1] not in vis ][0] curr = next[1] vis.add(curr) seq.append(curr) tot_length += next[2]['weight'] next = [ list for list in (sorted(G.edges(curr, data=True), key=lambda (source, target, data): data['weight'])) if list[1] == start ][0] seq.append(next[1]) tot_length += next[2]['weight'] # print optimal, tot_length, tot_length/float(int(optimal)) return tot_length # print greed()[1]
def __init__(self, id, dynamic_model, reactions, species, dynamic_compartments, local_species_population, options=None): """ Initialize an NRM submodel object Args: id (:obj:`str`): unique id of this dynamic NRM submodel dynamic_model (:obj:`DynamicModel`): the aggregate state of a simulation reactions (:obj:`list` of :obj:`Reaction`): the reactions modeled by this NRM submodel species (:obj:`list` of :obj:`Species`): the species that participate in the reactions modeled by this NRM submodel, with their initial concentrations dynamic_compartments (:obj:`dict`): :obj:`DynamicCompartment`\ s, keyed by id, that contain species which participate in reactions that this NRM submodel models, including adjacent compartments used by its transfer reactions local_species_population (:obj:`LocalSpeciesPopulation`): the store that maintains this NRM submodel's species population options (:obj:`dict`, optional): NRM submodel options Raises: :obj:`MultialgorithmError`: if the initial NRM wait exponential moving average is not positive """ super().__init__(id, dynamic_model, reactions, species, dynamic_compartments, local_species_population) self.random_state = RandomStateManager.instance() self.execution_time_priority_queue = PQDict() self.options = options # to enable testing of uninitialized instances auto_initialize controls initialization here # auto_initialize defaults to True auto_initialize = True if options is not None and 'auto_initialize' in options: auto_initialize = options['auto_initialize'] if auto_initialize: self.initialize()
def djikstra(G, start): ''' Djikstra's algorithm determines the length from `start` to every other vertex in the graph. The graph argument `G` should be a dict indexed by nodes. The value of each item `G[v]` should also a dict indexed by predecessor nodes. In other words, for any node `v`, `G[v]` is itself a dict, indexed by the predecessors of `v`. For any directed edge `w -> v`, `G[v][w]` is the length of the edge from `w` to `v`. ''' inf = float('inf') dist = {start: 0} # track shortest path distances from `start` E = set([start]) # explored U = set(G.keys()) - E # unexplored while U: # unexplored nodes D = PQDict() # frontier candidates for u in U: # unexplored nodes for v in G[u]: # neighbors of u if v in E: # then u is a frontier node l = dist[v] + G[u][v] # start -> v -> u D[u] = min(l, D.get(u, inf)) # choose minimum for u (x, d) = D.popitem() # node w/ min dist on frontier dist[x] = d # assign djikstra greedy score U.remove(x) # remove from unexplored E.add(x) # add to explored return dist # shortest path distances
def dijkstra(g, s): vis = [False for i in range(len(g))] dist = [float('inf') for i in range(len(g))] prev = [None for i in range(len(g))] dist[s] = 0 ipq = PQDict() ipq.additem(s, 0) while len(ipq) != 0: index, minValue = ipq.popitem() vis[index] = True # mica optimizare, daca deja avem distanda mai buna pe alt drum fata de drumul direct dintre 2 noduri, pass if dist[index] < minValue: continue for edge in g[index]: # ia toate nodurile vecine nevizitate if vis[edge[0]]: continue # le calculaeza distanta newDist = dist[index] + edge[1] # si o modifica doar daca este mai mica decat cea care era deja if newDist < dist[edge[0]]: dist[edge[0]] = newDist # apoi modifica si in indexed priority queue, daca nu e, il adauga, daca e, ii updateaza valoarea if ipq.get(edge[0]) is None: ipq.additem(edge[0], newDist) else: ipq[edge[0]] = newDist # si seteaza si tatal de fiecare data pentru a ramane ultimul adica cel cu costul cel mai mic prev[edge[0]] = index return dist, prev
def dijkstra(graph, start, end): inf = float('inf') shortest_distances = {start: 0} # mapping of nodes to their dist from start queue_sd = PQDict(shortest_distances) # priority queue for tracking min shortest path predecessors = {} # mapping of nodes to their direct predecessors unexplored = set(graph.keys()) # unexplored nodes path = [] while unexplored: # nodes yet to explore (minNode, minDistance) = queue_sd.popitem() # node w/ min dist d on frontier shortest_distances[minNode] = minDistance # est dijkstra greedy score unexplored.remove(minNode) # remove from unexplored if minNode == end: break # end if goal already reached # now consider the edges from minNode with an unexplored head - # we may need to update the dist of unexplored successors for neighbor in graph[minNode]: # successors to v if neighbor in unexplored: # then neighbor is a frontier node minDistance = shortest_distances[minNode] + graph[minNode][neighbor] if minDistance < queue_sd.get(neighbor, inf): queue_sd[neighbor] = minDistance predecessors[neighbor] = minNode # set/update predecessor currentNode = end while currentNode != start: try: path.insert(0,currentNode) currentNode = predecessors[currentNode] except KeyError: print('Path not reachable') break path.insert(0,start) if shortest_distances[end] != inf: return shortest_distances[end], path
def prim(G, start): """Function recives a graph and a starting node, and returns a MST""" stopN = G.number_of_nodes() - 1 current = start closedSet = set() pq = PQDict() mst = [] while len(mst) < stopN: # print " " # print "Current node :", current for node in G.neighbors(current): if node not in closedSet and current not in closedSet: # print " neigbors: ", node if (current, node) not in pq and (node, current) not in pq: w = G.edge[current][node]['weight'] pq.additem((current, node), w) closedSet.add(current) tup, wght = pq.popitem() while (tup[1] in closedSet): tup, wght = pq.popitem() mst.append(tup) current = tup[1] return mst
def gillespie_nrm(tspan, initial_amounts, reactions, dep_graph): """ Implementation of the "Next-Reaction Method" variant of the Gillespie stochastic simulation algorithm, described by Gibson and Bruck. The main enhancements are: - Use of dependency graph connecting the reaction channels to prevent needless rescheduling of reactions that are unaffected by an event. - Use of an indexed priority queue (pqdict) as a scheduler to achieve O(log(M)) rescheduling on each iteration, where M is the number of reactions, assuming the dependency graph is sparse. The paper describes an additional modification to cut down on the amount of random number generation which was not implemented here for simplicity. """ # initialize state t = tspan[0] x = initial_amounts T = [t] X = [x] # initialize scheduler scheduler = PQDict() for rxn in reactions: tau = -log(rand())/rxn.propensity(x) scheduler[rxn] = t + tau # first event rnext, tnext = scheduler.topitem() t = tnext x += rnext.stoich T.append( t ) X.append( x.copy() ) # main loop while t < tspan[1]: # reschedule tau = -log(rand())/rnext.propensity(x) scheduler[rnext] = t + tau # reschedule dependent reactions for rxn in dep_graph[rnext]: tau = -log(rand())/rxn.propensity(x) scheduler[rxn] = t + tau # fire the next one! rnext, tnext = scheduler.topitem() t = tnext x += rnext.stoich T.append( t ) X.append( x.copy() ) return array(T), array(X)
def djp(grafo, n): #Se determina el nodo inicial de forma aleatoria, mediante un random en entre el numero #nodos inicio = random.randint(0, n - 1) print("Nodo inicial: ", inicio) visitado = set() camino_mst = [] #Se genera una cola de prioridad para generar el orden optimizado de los resultados de los #caminos cola_prioridad = PQDict() actual = inicio return recorre_djp(camino_mst, grafo, actual, cola_prioridad, visitado)
def plan(self, start_state, goal_state): #PQ = pqdict() V = {} self.goal_state = goal_state h0 = self.heuristic(start_state, goal_state) n0 = node(start_state, None, None, 0, h0) key0 = np.around(n0.state, decimals=1).tostring() PQ = PQDict(key0=n0) i = 0 while PQ and i < 100000: current = PQ.popitem()[1] #print '\n' #print current.state[2] if (self.state_is_equal(current.path, goal_state)): path = self.reconstruct_path(current) return (path, current.f) V[np.around(current.state, decimals=1).tostring()] = copy.deepcopy(current) #get children children = self.getChildren( current) #do set parent, should return an array of nodes for child in children: i += 1 if i % 100 == 0: print 'A* iteration ' + str(i) child_key = np.around(child.state, decimals=1).tostring() if child_key in V: if child.f >= V[child_key].f: continue if (child_key in PQ): existing_child = PQ[child_key] if (child.g >= existing_child.g): continue else: PQ.updateitem(child_key, child) else: #print child.state, current.state #pdb.set_trace() #if(child.state[2] < 0): # pdb.set_trace() PQ.additem(child_key, child) print 'A* Failed' return (None, None)
def __init__(self): self.query = input("Enter search query: ") self.webpages_limit = input( "Set total number of webpages to be crawled: ") self.limit = input( "Set limits on how many webpages be crawled from single site: ") self.priority_queue = PQDict().maxpq() self.queue = queue.Queue() self.downloader = Downloader() self.parser = Parser(self.query) self.calculator = Calculator(self.query) self.relevance = Relevance() self.webpages_crawled = 0 self.logger = logging.getLogger(__name__) self.visited_urls = set() self.sites_times = {}
def branchAndBound(G, cutoff, ftrace): queue = PQDict() bestSolution = INFINITY bestTour = [] totalNodes = len(G.nodes()) startNode = G.nodes()[0] nodeList = G.nodes() nodeList.remove(startNode) queue.additem(tuple([startNode]), lowerBound(G, [startNode])) start_time = time.time() while (len(queue) != 0): # print count # count+=1 coveredNodes, lowerBoundCurrent = queue.popitem() # coveredNodes=list(coveredNodes) elapsed_time = time.time() - start_time if elapsed_time > cutoff: if bestSolution == INFINITY: return -1, [] return bestTour, bestSolution for neighbor in G.neighbors(coveredNodes[-1]): if not neighbor in coveredNodes: tempNodes = list(coveredNodes) tempNodes.append(neighbor) if (len(tempNodes) == totalNodes): cost = findCost(G, tempNodes) + G.get_edge_data( neighbor, startNode)['weight'] if (cost < bestSolution): bestSolution = cost bestTour = tempNodes ftrace.write("{0:.2f}".format(elapsed_time * 1.0) + ',' + str(bestSolution) + '\n') else: tempLowerBound = lowerBound(G, tempNodes) if tempLowerBound < bestSolution: queue.additem(tuple(tempNodes), tempLowerBound) # else: # print 'prune' return bestTour, bestSolution
def dijkstra(G, start, end=None): inf = float('inf') D = {start: 0} # mapping of nodes to their dist from start Q = PQDict(D) # priority queue for tracking min shortest path P = {} # mapping of nodes to their direct predecessors U = set(G.keys()) # unexplored nodes while U: # nodes yet to explore (v, d) = Q.popitem() # node w/ min dist d on frontier D[v] = d # est dijkstra greedy score U.remove(v) # remove from unexplored if v == end: break # now consider the edges from v with an unexplored head - # we may need to update the dist of unexplored successors for w in G[v]: # successors to v if w in U: # then w is a frontier node d = int(D[v]) + int(G[v][w]) # dgs: dist of start -> v -> w if d < Q.get(w, inf): Q[w] = d # set/update dgs P[w] = v # set/update predecessor return D, P
def dijkstra(self, src, dst): """dijkstras algorithm used to calculate the shortest path between two nodes a Priority queue is used in this implementation""" inf = float('inf') D = {src: 0} Q = PQDict(D) P = {} U = set(self.router_list) while U: (v, d) = Q.popitem() D[v] = d U.remove(v) if str(v) == dst: break for w in self.router_list[v]: if w in U: d = D[v] + self.router_list[v][w] if d < Q.get(w, inf): Q[w] = d P[w] = v return D, P
from pqdict import PQDict graph = [[(0, 1, 10), (0, 2, 1), (0, 3, 4)], [(1, 0, 10), (1, 2, 3), (1, 4, 0)], [(2, 0, 1), (2, 1, 3), (2, 3, 2), (2, 5, 8)], [(3, 0, 4), (3, 2, 2), (3, 5, 2), (3, 6, 7)], [(4, 1, 0), (4, 5, 1), (4, 7, 8)], [(5, 2, 8), (5, 3, 2), (5, 4, 1), (5, 6, 6), (5, 7, 9)], [(6, 3, 7), (6, 5, 6), (6, 7, 12)], [(7, 4, 8), (7, 5, 9), (7, 6, 12)]] n = len(graph) m = n - 1 pq = PQDict() visited = [False] * n # s e indicele nodului de start def lazyPrim(s=0): global m edgeCount, mstCost = 0, 0 mstEdges = [None] * m addEdges(s) while len(pq) > 0 and edgeCount != m: edge, priority = pq.popitem() nodeIndex = edge[1] if visited[nodeIndex]: continue