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 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_swap_priority(self): pq = PQDict(A=5, B=8, C=1) pq.swap_priority('A', 'C') self.check_index(pq) self.assertEqual(pq['A'], 1) self.assertEqual(pq['C'], 5) self.assertEqual(pq.top(), 'A') self.assertRaises(KeyError, pq.swap_priority, 'A', 'Z')
def test_top(self): # empty pq = PQDict() self.assertRaises(KeyError, pq.top) # non-empty for num_items in range(1,30): items = generateData('float', num_items) pq = PQDict(items) self.assertEqual(pq.top(), min(items, key=lambda x: x[1])[0])
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
class AdaptiveSampler(object): def __init__(self, f, a, b, sample_over=None, min_angle=0.1, init_points=7, epsilon=0, max_points=700, yscale=None, measure_at=None, scalefactor=5, min_delta=1e-3): self.f = f self.a = a self.b = b self.sample_over = sample_over self.init_points = init_points self.min_angle = min_angle self.epsilon = epsilon if max_points < 3: raise ValueError('max_points must be at least three') self.max_points = max_points self.yscale = yscale self.scalefactor = scalefactor self.measure_at = measure_at self.min_delta = min_delta self.scale_to_x = lambda x: a + x * (b - a) def get_prior(self, x, y, xp, yp, xn, yn): a1 = atan2(y - yp, x - xp + self.epsilon) a2 = atan2(yn - y, xn - x + self.epsilon) prior = -(min(np.abs(a1 - a2), 2 * pi - np.abs((a1 - a2)))) return prior def getf(self, x): xret = self.scale_to_x(x) yret = self.f(xret) y = self.scale_from_y(self.get_y(yret)) return xret, yret, y def get_y(self, yret): if self.sample_over is not None: return yret[self.sample_over] else: return yret def evalx(self, x, y, xp, yp, xn, yn): lx = (x + xp) / 2. rx = (xn + x) / 2. lxret, lyret, ly = self.getf(lx) yield lxret, lyret rxret, ryret, ry = self.getf(rx) yield rxret, ryret ldata = [ly, xp, yp, x, y] rdata = [ry, x, y, xn, yn] self.update_data(lx, ldata) self.update_data(rx, rdata) try: xpd = self.data[xp] except KeyError: pass else: xpd[3] = lx xpd[4] = ly self.update_data(xp, xpd) try: xnd = self.data[xn] except KeyError: pass else: xnd[1] = rx xnd[2] = ry self.update_data(xn, xnd) xd = [y, lx, ly, rx, ry] self.update_data(x, xd) def update_data(self, x, data): prior = self.get_prior(x, *data) mind = min((x - data[1], data[3] - x)) if -prior > self.min_angle and self.min_delta < mind: self.data[x] = data self.heapdict[x] = prior elif x in self.data: del self.data[x] del self.heapdict[x] def run(self): self.heapdict = PQDict() self.data = {} initx = np.linspace(0, 1, self.init_points) n_points = self.init_points if self.measure_at is not None: xm = [(x - self.a) / (self.b - self.a) for x in self.measure_at] initx = np.concatenate((initx, xm)) initx.sort() n_points += len(self.measure_at) #initdelta = (initx[1] - initx[0])/2. inity = [] for x in initx: xret = self.scale_to_x(x) yret = self.f(xret) yield (xret, yret) inity.append(self.get_y(yret)) if self.yscale is None: self.yscale = max(inity) - min(inity) #self.scale_from_y = lambda y: (y-min(inity))/(max(inity)-min(inity)) self.scale_from_y = lambda y: (y) / self.yscale / self.scalefactor inity = [self.scale_from_y(y) for y in inity] for (i, x) in enumerate(initx[1:-1], 1): d = [ inity[i], initx[i - 1], inity[i - 1], initx[i + 1], inity[i + 1] ] self.update_data(x, d) while n_points < self.max_points: try: x = self.heapdict.top() except KeyError: return else: d = self.data[x] for point in self.evalx(x, *d): yield point n_points += 2 def __call__(self): return self.run()
class AdaptiveSampler(object): def __init__(self, f, a ,b, sample_over = None, min_angle = 0.1, init_points = 7, epsilon = 0, max_points = 700, yscale = None, measure_at = None, scalefactor = 5, min_delta = 1e-3): self.f = f self.a = a self.b = b self.sample_over = sample_over self.init_points = init_points self.min_angle = min_angle self.epsilon = epsilon if max_points < 3: raise ValueError('max_points must be at least three') self.max_points = max_points self.yscale = yscale self.scalefactor = scalefactor self.measure_at = measure_at self.min_delta = min_delta self.scale_to_x = lambda x: a + x*(b-a) def get_prior(self, x, y ,xp, yp, xn, yn): a1 = atan2(y-yp,x-xp + self.epsilon) a2 = atan2(yn-y,xn-x + self.epsilon) prior = -(min(np.abs(a1-a2), 2*pi-np.abs((a1-a2)))) return prior def getf(self, x): xret = self.scale_to_x(x) yret = self.f(xret) y = self.scale_from_y(self.get_y(yret)) return xret, yret, y def get_y(self,yret): if self.sample_over is not None: return yret[self.sample_over] else: return yret def evalx(self, x, y, xp, yp, xn, yn): lx = (x+xp)/2. rx = (xn+x)/2. lxret, lyret, ly = self.getf(lx) yield lxret, lyret rxret, ryret, ry = self.getf(rx) yield rxret, ryret ldata = [ly, xp, yp, x, y] rdata = [ry, x, y, xn, yn] self.update_data(lx, ldata) self.update_data(rx, rdata) try: xpd = self.data[xp] except KeyError: pass else: xpd[3] = lx xpd[4] = ly self.update_data(xp, xpd) try: xnd = self.data[xn] except KeyError: pass else: xnd[1] = rx xnd[2] = ry self.update_data(xn, xnd) xd = [y, lx, ly, rx, ry] self.update_data(x, xd) def update_data(self, x, data): prior = self.get_prior(x, *data) mind = min((x-data[1], data[3]-x)) if -prior > self.min_angle and self.min_delta < mind: self.data[x] = data self.heapdict[x] = prior elif x in self.data: del self.data[x] del self.heapdict[x] def run(self): self.heapdict = PQDict() self.data = {} initx = np.linspace(0, 1, self.init_points) n_points = self.init_points if self.measure_at is not None: xm = [(x-self.a)/(self.b-self.a) for x in self.measure_at] initx = np.concatenate((initx, xm)) initx.sort() n_points += len(self.measure_at) #initdelta = (initx[1] - initx[0])/2. inity = [] for x in initx: xret = self.scale_to_x(x) yret = self.f(xret) yield (xret, yret) inity.append(self.get_y(yret)) if self.yscale is None: self.yscale = max(inity)-min(inity) #self.scale_from_y = lambda y: (y-min(inity))/(max(inity)-min(inity)) self.scale_from_y = lambda y: (y) / self.yscale / self.scalefactor inity = [self.scale_from_y(y) for y in inity] for (i, x) in enumerate(initx[1:-1],1): d = [inity[i], initx[i-1], inity[i-1], initx[i+1], inity[i+1]] self.update_data(x, d) while n_points < self.max_points: try: x = self.heapdict.top() except KeyError: return else: d = self.data[x] for point in self.evalx(x, *d): yield point n_points += 2 def __call__(self): return self.run()