def primMST(G): """ Return MST of the given undirected graph""" vis = set() tot_weight = 0 pq = PQDict() Gprime = nx.Graph() ''' Add all nodes to PQDict with infinite distance''' for node in G.nodes(): pq.additem(node, float("inf")) curr = pq.pop() #Select initial node vis.add(curr) while len(pq) > 0: for s,nod, wt in G.edges(curr, data=True): if nod not in vis and wt['weight'] < pq[nod]: pq.updateitem(nod, wt['weight']) if len(pq)>0: top = pq.top() source,destination, dist = [data for data in sorted(G.edges(top, data=True), key=lambda (source,target,data): data['weight']) if data[1] in vis][0] Gprime.add_edge(source, destination, weight = dist['weight']) vis.add(top) tot_weight += pq[top] curr = pq.pop() return Gprime, tot_weight
def greedy_approx(G): """ Return MST of the given undirected graph""" vis = set() tot_weight = 0 pq = PQDict() path = [] '''Initialize Priority Queue which will help us find Farthest node after distance is calcualted from visited node''' for node in G.nodes(): pq.additem(node, float("-inf")) curr = pq.pop() vis.add(curr) path.append(curr) while len(pq) > 0: for s, nod, wt in G.edges(curr, data=True): '''Distance calculation''' if nod not in vis and -wt['weight'] > pq[nod]: pq.updateitem(nod, -wt['weight']) if len(pq) > 0: ''' Selection Step''' top = pq.top() vis.add(top) curr = pq.pop() ''' Insertion Step''' loc, cost = minCost(G, path, top) '''Insert into the location found by minCost()''' path.insert(loc, top) tot_weight += cost return path, tot_weight
def primMST(G): """ Return MST of the given undirected graph""" vis = set() tot_weight = 0 pq = PQDict() Gprime = nx.Graph() ''' Add all nodes to PQDict with infinite distance''' for node in G.nodes(): pq.additem(node, float("inf")) curr = pq.pop() #Select initial node vis.add(curr) while len(pq) > 0: for s, nod, wt in G.edges(curr, data=True): if nod not in vis and wt['weight'] < pq[nod]: pq.updateitem(nod, wt['weight']) if len(pq) > 0: top = pq.top() source, destination, dist = [ data for data in sorted(G.edges(top, data=True), key=lambda (source, target, data): data['weight']) if data[1] in vis ][0] Gprime.add_edge(source, destination, weight=dist['weight']) vis.add(top) tot_weight += pq[top] curr = pq.pop() return Gprime, tot_weight
def greedy_approx(G): """ Return MST of the given undirected graph""" vis = set() tot_weight = 0 pq = PQDict() path = [] '''Initialize Priority Queue which will help us find Farthest node after distance is calcualted from visited node''' for node in G.nodes(): pq.additem(node, float("-inf")) curr = pq.pop() vis.add(curr) path.append(curr) while len(pq) > 0: for s,nod, wt in G.edges(curr, data=True): '''Distance calculation''' if nod not in vis and -wt['weight'] > pq[nod]: pq.updateitem(nod, -wt['weight']) if len(pq)>0: ''' Selection Step''' top = pq.top() vis.add(top) curr = pq.pop() ''' Insertion Step''' loc,cost = minCost(G,path,top) '''Insert into the location found by minCost()''' path.insert(loc, top) tot_weight += cost return path,tot_weight
def test_updateitem(self): pq = PQDict(self.items) dkey, pkey = random.choice(self.items) # assign same value pq.updateitem(dkey, pkey) self.assertEqual(pq[dkey], pkey) # assign new value pq.updateitem(dkey, pkey + 1.0) self.assertEqual(pq[dkey], pkey + 1.0) # can only update existing dkeys self.assertRaises(KeyError, pq.updateitem, 'does_not_exist', 99.0)
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 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 primWeight(G): """ Return MST of the given undirected graph""" vis = set() tot_weight = 0 pq = PQDict() for node in G.nodes(): pq.additem(node, float("inf")) curr = pq.pop() vis.add(curr) while len(pq) > 0: for s,nod, wt in G.edges(curr, data=True): if nod not in vis and wt['weight'] < pq[nod]: pq.updateitem(nod, wt['weight']) if len(pq)>0: top = pq.top() vis.add(top) tot_weight += pq[top] curr = pq.pop() return tot_weight
def primWeight(G): """ Return MST of the given undirected graph""" vis = set() tot_weight = 0 pq = PQDict() for node in G.nodes(): pq.additem(node, float("inf")) curr = pq.pop() vis.add(curr) while len(pq) > 0: for s, nod, wt in G.edges(curr, data=True): if nod not in vis and wt['weight'] < pq[nod]: pq.updateitem(nod, wt['weight']) if len(pq) > 0: top = pq.top() vis.add(top) tot_weight += pq[top] curr = pq.pop() return tot_weight
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 between reactions to prevent needless rescheduling of reaction channels that are unaffected by an event. - Use of an indexed priority queue (pqdict) as a scheduler to achieve log(N) rescheduling. 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] a = {} # initialize scheduler scheduler = PQDict() for rxn in reactions: a[rxn] = rxn.propensity(x) tau = -log(rand())/a[rxn] scheduler[rxn] = t + tau # first event rnext, tmin = scheduler.topitem() t = tmin x += rnext.stoich T.append( t ) X.append( x.copy() ) # main loop while t < tspan[1]: # reschedule a[rnext] = rnext.propensity(x) tau = -log(rand())/a[rnext] scheduler.updateitem(rnext, t + tau) for rxn in dep_graph[rnext]: a_old = a[rxn] a[rxn] = rxn.propensity(x) if isfinite(scheduler[rxn]): tau = (a_old/a[rxn])*(scheduler[rxn] - t) else: tau = -log(rand())/a[rxn] scheduler.updateitem(rxn, t + tau) rnext, tmin = scheduler.topitem() # fire! t = tmin x += rnext.stoich T.append( t ) X.append( x.copy() ) return array(T), array(X)
if test: print "next_node is %d" % next_node[0] cost_sum = cost_sum + next_node[1] if test: print "current cost_sum is %d" % cost_sum mst.append(next_node[0]) if test: print "current mst is", mst for edge in edges: node1 = edge[0] node2 = edge[1] cost = edge[2] if (node1 == next_node[0]) and (node2 not in mst): if costs[node2] > cost: if test: print "node %d needs update, old cost is %d, new cost is %d" % (node2, costs[node2], cost) heap.updateitem(node2, cost) costs[node2] = cost elif (node2 == next_node[0]) and (node1 not in mst): if costs[node1] > cost: if test: print "node %d needs update, old cost is %d, new cost is %d" % (node1, costs[node1], cost) heap.updateitem(node1, cost) costs[node1] = cost if test: print "the mst is", mst print "mst size is %d" % len(mst) print "the total cost is %d" %cost_sum f.close()