def prim(graph) : #0.最小生成树的边集ret和图graph的所有顶点列表 ret = [] vertexs = graph.get_vertexs() length = len(vertexs) temp_graph = graph.get_attribute() #1.选择任意一个顶点,加入到生成树定点集合中,此处选择第一个顶点 graph.visite(vertexs[0]) visited_vertexs = [vertexs[0]] #2.在所有的u属于U,v属于V-U的边(u,v)属于E中找出一条代价最小的边(u',v'),并入TE,同时将v'并入U #2.1.进行n-1次操作,每次操作找出一条满足步骤2中条件的边 for count in range(length-1) : #2.2.遍历已经访问过的的顶点 min_weight_edge = Edge('A','B',100000) #记录最小权值的边 for item in visited_vertexs : #2.3.遍历每个i顶点的邻接表,找出权值最小的边,加入到最小生成树的边集中 neighbours = temp_graph[item]['neighbour'] #获取该节点的邻接点列表 for edge in neighbours : start, end, weight = edge.get_attribute() #end未访问过 if end not in visited_vertexs : if weight < min_weight_edge.weight : min_weight_edge.set_attribute(start,end,weight) graph.visite(min_weight_edge.end) visited_vertexs.append(min_weight_edge.end) ret.append(min_weight_edge.get_attribute()) return ret
def problemToGraphs(problem): """ Returns a dictionary: Keys: 'arg', 'init', 'goal' Values: arg dictionary, (elements, edges), (elements, edges) """ Args = {object.name: Argument(name=object.name, typ=object.typeName) for object in problem.objects if not object.typeName.lower() in {'character', 'actor', 'person', 'agent'}} Args.update({object.name: Actor(typ=object.typeName.lower(), name=object.name) for object in problem.objects if object.typeName.lower() in {'character', 'actor', 'person', 'agent'}}) goal_elements, goal_edges = getGoalSet(problem.goal.formula, Args) goal_op = Operator(name='dummy_goal', stepnumber=1, num_args=0) goal_graph = Action(name='dummy_goal', root_element=goal_op) goal_graph.elements.update(goal_elements) goal_graph.edges.update(goal_edges) goal_graph.edges.update({Edge(goal_op, goal_lit, 'precond-of') for goal_lit in goal_elements if type(goal_lit) is Literal}) init_op = Operator(name='dummy_init', stepnumber=0, num_args=0) init_graph = Action(name='dummy_init', root_element=init_op) for condition in problem.init.predicates: lit = Literal(name=condition.name, num_args=len(condition.parameters), truth=True) init_graph.elements.add(lit) init_graph.edges.add(Edge(init_op, lit, 'effect-of')) for i, p in enumerate(condition.parameters): init_graph.edges.add(Edge(lit, Args[p], i)) return Args, init_graph, goal_graph
def addNegativeInitStates(predicates, initAction, objects): init_tups = defaultdict(set) effects = initAction.getNeighbors(initAction.root) for eff in effects: nontup = sorted([(edge.sink, edge.label) for edge in initAction.getIncidentEdges(eff)], key=lambda x: x[1]) init_tups[eff.name].add(tuple(nontup[i][0] for i in range(len(nontup)))) objs_by_type_dict = defaultdict(set) for obj in objects: objs_by_type_dict[obj.typ].add(obj) for p in predicates: param_object_pairs = [[obj for obj in objs_by_type_dict[param.types[0]]] for param in p.parameters if not p.parameters[0].types is None] param_tuples = {i for i in itertools.product(*param_object_pairs)} pred = Literal(name=p.name, arg_name='init_effect', num_args=len( p.parameters), truth=False) for pt in param_tuples: if pt in init_tups[p.name]: continue pc = copy.deepcopy(pred) pc.ID = uuid4() for i, arg in enumerate(pt): initAction.edges.add(Edge(pc, arg, i)) if len(pt) > 0: initAction.elements.add(pc) initAction.edges.add(Edge(initAction.root, pc, 'effect-of'))
def problemToGraphs(problem): """ Returns a dictionary: Keys: 'arg', 'init', 'goal' Values: arg dictionary, (elements, edges), (elements, edges) """ if problem.goalAction is not None: action = problem.goalAction gop = Operator(name=action.name, num_args=len(action.parameters)) GoalAction = Action(name=action.name, root_element=gop) evalActionParams(action.parameters, GoalAction) getFormulaGraph(action.precond.formula, GoalAction, parent=gop, relationship='precond-of', elements=GoalAction.elements, edges=GoalAction.edges) decomp_graph = PlanElementGraph(name=action.name, type_graph='decomp') getDecompGraph(action.decomp.formula, decomp_graph, action.parameters) GoalAction.subgraphs.add(decomp_graph) goal_graph = GoalAction init_op = Operator(name='dummy_init', stepnumber=0, num_args=0) init_graph = Action(name='dummy_init', root_element=init_op) Args = dict() else: Args = { object.name: Argument(name=object.name, typ=object.typeName) for object in problem.objects if not object.typeName.lower() in {'character', 'actor'} } Args.update({ object.name: Actor(name=object.name) for object in problem.objects if object.typeName.lower() in {'character', 'actor'} }) goal_elements, goal_edges = getGoalSet(problem.goal.formula, Args) goal_op = Operator(name='dummy_goal', stepnumber=1, num_args=0) goal_graph = Action(name='dummy_goal', root_element=goal_op) goal_graph.elements.update(goal_elements) goal_graph.edges.update(goal_edges) goal_graph.edges.update({ Edge(goal_op, goal_lit, 'precond-of') for goal_lit in goal_elements if type(goal_lit) is Literal }) init_op = Operator(name='dummy_init', stepnumber=0, num_args=0) init_graph = Action(name='dummy_init', root_element=init_op) for condition in problem.init.predicates: lit = Literal(name=condition.name, num_args=len(condition.parameters), truth=True) init_graph.elements.add(lit) init_graph.edges.add(Edge(init_op, lit, 'effect-of')) for i, p in enumerate(condition.parameters): init_graph.edges.add(Edge(lit, Args[p], ARGLABELS[i])) return (Args, init_graph, goal_graph)
def get_test_graph(): """ Creates and returns a simple test graph :return: a Graph.py representation of a set graph """ one = Vertex(0, 0, 0) two = Vertex(1, 10, 2) one_two = Edge(one, two, 5) three = Vertex(2, 20, 65) two_three = Edge(two, three, 3) four = Vertex(3, 32, 30) one_four = Edge(one, four, 1) five = Vertex(4, 9, 40) four_five = Edge(four, five, 6) six = Vertex(5, 50, 44) four_six = Edge(four, six, 4) seven = Vertex(6, 60, 5) six_seven = Edge(six, seven, 9) eight = Vertex(7, 0, 70) five_eight = Edge(five, eight, 1) nine = Vertex(8, 9, 80) eight_nine = Edge(eight, nine, 3) three_nine = Edge(three, nine, 2) return Graph([ one_two, one_four, two_three, four_five, four_six, six_seven, five_eight, eight_nine, three_nine ])
def main(): n: int = 0 try: n = int(stdin.readline()) except ValueError: print('Wrong \'n\' format') return G: Graph = Graph(n, directed=False) m: int = n * (n - 1) // 2 try: for _ in range(m): line = stdin.readline() u, v, w = getEdge(line) edge = Edge(u, v, w) G.add_edge(edge) except ValueError: print("Wrong \'u v w\' input format") return results: List[Salesman.Result] = [ Salesman.random_walk(G), Salesman.greedy_edge(G), Salesman.use_mst(G) ] for result in results: print(result) print(result.path, file=stderr)
def getSubFormulaNoParent(formula, objects): elements = set() edges = set() if formula.key == 'not': formula = next(iter(formula.children)) if formula.key == 'intends': raise NameError('no intends yet') else: lit = Literal(name=formula.key, num_args=len(formula.children), truth=False) elements.add(lit) elif formula.key == 'intends': raise NameError('no intends yet') elif formula.type > 0: raise ValueError('not sure why formula.type > 0') else: lit = Literal(name=formula.key, num_args=len(formula.children), truth=True) elements.add(lit) for i, child in enumerate(formula.children): #children are list arg = next(ob_element for ob_name, ob_element in objects.items() if child.key == ob_name) edges.add(Edge(lit, arg, ARGLABELS[i])) elements.add(arg) return (elements, edges)
def __init__(self, label, input, output, mapping=None, compound=None): self.Label = label self.Input = input self.Output = output if mapping is None: self.InOutMapping = VertexMapping( {i: i for i in self.Input.V if i in self.Output.V}) else: self.InOutMapping = mapping self.Input, in_mapping = self.Input.clone() self.Output, out_mapping = self.Output.clone() self.InOutMapping = ~(~self.InOutMapping * in_mapping) * out_mapping self.ToRemove = set(v for v in self.Input.V if v not in self.InOutMapping) #this is used to track what actions/mappings are needed to complete a "compound action" if compound is None: compound = [] self.CompoundActionTracker = compound + [ (self.Label, self.InOutMapping * ~out_mapping) ] self.ActionGraph = Graph([*self.Input.E, *self.Output.E]) for i, o in self.InOutMapping.AtoB.items(): self.ActionGraph.add_edge(Edge('*', (i, o))) self.ActionGraph.process()
def replace(self, subset): """Takes a subset of Edges and replaces them randomly.""" for e in subset: v = e[0] self.remove_edge(e) choices = list(set(self.vertices()) - set([v])) new = random.choice(choices) self.add_edge(Edge(v, new))
def add_random_edges(self, p): if p < 0 and p > 1: raise ValueError, 'p must be less or equal to 1 and greater or equal to 0' l = self.vertices() for i in range(len(l)): for j in range(i + 1, len(l)): if p > random.random(): self.add(Graph([l[i], l[j]], [Edge(l[i], l[j])]))
def test_graph(self): v = Vertex('v') w = Vertex('w') self.assertEqual(repr(v), "Vertex('v')") e = Edge(v, w) self.assertEqual(repr(e), "Edge(Vertex('v'), Vertex('w'))") g = Graph([v, w], [e]) self.assertEqual( repr(g), "{Vertex('w'): {Vertex('v'): Edge(Vertex('v'), Vertex('w'))}, Vertex('v'): {Vertex('w'): Edge(Vertex('v'), Vertex('w'))}}" ) e2 = g.get_edge(v, w) self.assertEqual(e, e2) e3 = g.get_edge(v, v) self.assertEqual(e3, None) vs = [Vertex(c) for c in 'abcd'] g = Graph(vs) g.add_regular_edges(3) for v in g.vertices(): es = g.out_edges(v) self.assertEqual(len(es), 3) vs = g.out_vertices(v) self.assertEqual(len(vs), 3) g.remove_edge(Edge(Vertex('a'), Vertex('c'))) vs = g.vertices() self.assertEqual(len(vs), 4) es = g.edges() self.assertEqual(len(es), 5) g.add_all_edges() es = g.edges() self.assertEqual(len(es), 6) g2 = eval(repr(g)) self.assertEqual(g, g2)
def stepFromArg(arg, DG): step_elm = whichElm(arg.children[0].key.name, DG) # step type op_type = arg.children[1].key step_elm.name = op_type args = [whichElm(child.key.name, DG) for child in arg.children[1].children] # args = [whichElm(child.key.name, DG) for child in arg.children[0].children] for i, arg in enumerate(args): DG.edges.add(Edge(step_elm, arg, i))
def getPotentialLinkConditions(self, src, snk): from Graph import Edge cndts = [] for pre in self[snk.stepnumber].preconditions: if src.stepnumber not in self.id_dict[pre.replaced_ID]: continue cndts.add(Edge(src, snk, copy.deepcopy(pre))) return cndts
def main(): algorithm: str = "" if len(argv) < 2: print('Not enough arguments!') print('Usage: main (-k|-p)') return elif argv[1] == '-k': algorithm = KRUSKAL elif argv[1] == "-p": algorithm = PRIM else: print('Unknown algorithm') return n: int = 0 try: n = int(stdin.readline()) except ValueError: print("Wrong \'n\' input format") return G: Graph = Graph(n, directed=False) m: int = 0 try: m = int(stdin.readline()) except ValueError: print("Wrong \'m\' input format") return try: for _ in range(m): line = stdin.readline() u, v, w = getEdge(line) edge = Edge(u, v, w) G.add_edge(edge) except ValueError: print("Wrong \'u v w\' input format") return mst: List[Edge] = None weight: float = 0 if algorithm == KRUSKAL: mst, weight = MST.kruskal(G) elif algorithm == PRIM: mst, weight = MST.prim(G, 1) else: raise Exception('Unsupported algorithm') for e in mst: fst, snd, w = e.unpack() u, v = (fst, snd) if fst < snd else (snd, fst) print(u, v, w) print(weight)
def add_prefer_vert(self, vid): vs = self.vertices() vert = Vertex(vid) self.add_vertex(vert) for v in vs: k_i = len(self[v]) if random.random() > k_i/float(self.sum_k): continue self.add_edge(Edge(vert, v)) self.sum_k += 1
def add_random_edges(self, p): if self.edges() != []: print 'This method only takes an edgeless graph' else: for v in self.vertices(): for w in self.vertices(): if v != w: rand = random.uniform(0, 1) if rand < p: self.add_edge(Edge(v, w))
def getSubFormulaGraph(formula, op_graph, parent=None, relationship=None, elements=None, edges=None): if elements is None: elements = set() if edges is None: edges = set() '''make new literal representing subformula''' if formula.key == 'not': formula = next(iter(formula.children)) if formula.key == 'intends': pass raise NameError('no intends yet') elif formula.key in {'equals', '=', 'equal'}: getNonEquals(formula, op_graph, elements, edges) return else: lit, formula = makeLit(formula, parent, relationship, elements, edges, False) elif formula.key == 'intends': raise NameError('no intends yet') elif formula.key == 'for-all' or formula.key == 'forall': raise NameError('no for-all yet') elif formula.type > 0: raise ValueError('not sure why formula.type > 0') else: lit, formula = makeLit(formula, parent, relationship, elements, edges, True) '''for each variable, find existing argument in action parameters and add Edge''' for i, child in enumerate(formula.children): arg = next(element for element in elements if child.key.name == element.arg_name) if relationship == 'actor-of': edges.add(Edge(parent, arg, 'actor-of')) else: edges.add(Edge(lit, arg, ARGLABELS[i])) return elements, edges
def rewireNodes(self, v1, v2, e, debug=False): if debug: print("rewiring %r-%r" % (v1, v2)) # loop unti getting a random unconnected node while True: randV = random.choice(list(self)) if randV != v1 and randV != v2 and randV not in self[v1]: break self.remove_edge(e) self.add_edge(Edge(v1, randV)) if debug: print("%r: edge rewired to %r-%r \n" % (e, v1, randV))
def litFromArg(arg, DG): neg = True if arg.key == 'not': neg = False arg = arg.children[0] # arg 2 is written out lit_name = arg.key lit_elm = Literal(name=lit_name, arg_name=lit_name + str(uuid4())[19:23], num_args=len(arg.children), truth=neg) for i, ch in enumerate(arg.children): e_i = whichElm(ch.key.name, DG) DG.edges.add(Edge(lit_elm, e_i, i)) return lit_elm
def makeLit(formula, parent, relationship, elements, edges, bit=None, noAdd=None): if bit == None: bit = True if noAdd == None: noAdd = False num_children = len(formula.children) lit = Literal(name=formula.key, num_args=num_children, truth=bit) if not noAdd: elements.add(lit) edges.add(Edge(parent, lit, relationship)) return lit, formula
def add_random_edges(self, p): """Erdos-Renyi G(n, p) model. n is given by number of vertices in the graph. Pass p to add edges randomly until there is a probability of p that there is an edge between any two graphs.""" vs = self.vertices() while vs: v = vs.pop() for w in vs: if random.random() <= p: self.add_edge(Edge(v, w))
def getPotentialEffectLinkConditions(self, src, snk): """ Given source and sink steps, return {eff(src) \cap pre(snk)} But, let those conditions be those of the src. """ cndts = [] for eff in self[src.stepnumber].effects: for pre in self[snk.stepnumber].preconditions: if eff.replaced_ID not in self.id_dict[pre.replaced_ID]: continue cndts.append(Edge(src, snk, copy.deepcopy(eff))) return cndts
def rewire(this, p): rep = int(p * len(this.edges())) for x in range(0, rep): edges = this.edges() nodes = this.nodes() e = edges[int(math.floor(random.random() * len(edges)))] n1, n2 = e this.remove_edge(e) r = int(random.random() * len(nodes)) n3 = nodes[r] e1 = Edge(n1, n3) this.add_edge(e1) return rep
def rewire(self, p): for v in self: for e in list(self.out_edges(v)): if random.random() < p: new_edge = Edge( v, random.choice([ w for w in self.vertices() if w is not v and self.get_edge(v, w) == None ])) self.add_edge( new_edge) #print 'Adding: %s\n' % ([new_edge]) self.remove_edge(e) #print 'Removing: %s' % [e]
def test_detect_cycle(self): Elms = [Element(ID=0, name = '0'), Element(ID=1, name='1'), Element(ID=2, name='2'), Element(ID=3, name='3')] edges = {Edge(Elms[0], Elms[1], '<'), Edge(Elms[0], Elms[2], '<'), Edge(Elms[0], Elms[3], '<'), Edge(Elms[2], Elms[1], '<'), Edge(Elms[3], Elms[1], '<')} G = Graph(ID=10, typ='test', Elements=set(Elms), Edges=edges) OG = OrderingGraph(ID = 5, Elements = G.elements, Edges = G.edges) assert(not OG.detectCycle()) OG.edges.add(Edge(Elms[1], Elms[0], '<')) assert (OG.detectCycle())
def add_random_edges(self, p): if p < 0 or p > 1: raise ValueError("p is a probability which range is [0, 1]") verticies = self.vertices() visitedVerticies = set() for vertexA in verticies: visitedVerticies.add(vertexA) for vertexB in verticies: if vertexB == vertexA: continue if vertexB in visitedVerticies: continue if random.random() <= p: edge = Edge(vertexA, vertexB) self.add_edge(edge)
def clustering_coefficient(self): """Average Cluster ratio of all vertices. Cluster ratio per vertex is actual number of neighbours connectivity divided by maximum possible number of neighbours connectivity""" res = [] # list for storing ratios for each vertex edges = set(edge for sublist in self.edges() for edge in sublist) for v in self.vertices(): # iterate through all vertices out = self.out_vertices(v) # store the out vertices k_v = len(out) # len of out vertices is number of neighbours # compute the maximum number of neighbour connectedness: most = float(k_v) * (k_v - 1.0) / 2.0 actual = 0 # initiate count of actual neighbour connectedness # iterate through all possible combinations of vs neighbours: for w in out: for x in out: # If the Edge between the neighbour pair exists, # incresae the actual count by 1: if Edge(w, x) in edges or Edge(x, w) in edges: actual += 1 # calculate vs ratio as actual divided by most: ratio = float(actual) / most res.append(ratio) # append to list of ratios return np.average(res) # use numpy to compute the mean ratio
def evalActionParams(params, op_graph): for i, parameter in enumerate(params): # parameters are list if 'character' in parameter.types or 'actor' in parameter.types: arg = Actor(arg_name=parameter.name) op_graph.elements.add(arg) # elif 'literal' in parameter.types or 'lit' in parameter.types: # lit = Literal(arg_name=parameter.name, typ='Condition') # op_graph.elements.add(lit) else: arg_type = next(iter(parameter.types)) if arg_type in {'lit', 'literal'}: arg_type = 'Condition' arg = Argument(typ=arg_type, arg_name=parameter.name) op_graph.elements.add(arg) op_graph.edges.add(Edge(op_graph.root, arg, ARGLABELS[i]))
def filter_and_add_orderings(planets, RQ): orderings = RQ.OrderingGraph.edges indices = [] for i in range(len(planets)): # filter None Planets, which are scratched possible worlds if planets[i] is None: continue # add orderings if len(orderings) > 0: GtElm = planets[i].getElementById planets[i].OrderingGraph.edges = {Edge(GtElm(ord.source.ID), GtElm(ord.sink.ID), '<') for ord in orderings} indices.append(i) planets[:] = [planets[i] for i in indices]
def add_random_edges_fixed(this, p): total = len(this) edges = total * (total - 1) / 2 * p edge = 0 nodes = this.nodes() print edges / len(nodes) * 2 while (edge < edges): r1 = nodes[int(math.floor(random.random() * total))] r2 = nodes[int(math.floor(random.random() * total))] if (r1 != r2): try: this[r1][r2] except: this.add_edge(Edge(r1, r2)) edge = edge + 1 return None
def rewire(self, p): es = self.edges() vs = self.vertices() # Try to make this not random at some point random.shuffle(es) for e in es: if random.random() > p: continue v, w = e self.remove_edge(e) while True: w = random.choice(vs) if (w is not v) and (not self.has_edge(v, w)): break self.add_edge(Edge(v,w))