当前位置: 首页>>代码示例>>Python>>正文


Python AGraph.get_edge方法代码示例

本文整理汇总了Python中pygraphviz.AGraph.get_edge方法的典型用法代码示例。如果您正苦于以下问题:Python AGraph.get_edge方法的具体用法?Python AGraph.get_edge怎么用?Python AGraph.get_edge使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在pygraphviz.AGraph的用法示例。


在下文中一共展示了AGraph.get_edge方法的6个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: build_graph

# 需要导入模块: from pygraphviz import AGraph [as 别名]
# 或者: from pygraphviz.AGraph import get_edge [as 别名]
def build_graph(score):
    corpus= create_corpus(score)
    calc_tf_idf(corpus, log_tf, log_idf)

    #corpus= group_corpus(corpus, log_tf, log_idf)
    g= AGraph(strict=False)
    for i, d1 in enumerate(corpus):
        d1_name= str(d1)
        edges= [(d2, d2.similarity(d1)) for d2 in corpus[i+1:]] 
        edges.sort(key=lambda x:x[1], reverse=True)
        edges= edges[:5]
        for d2, weight in edges:
            d2_name= str(d2)
            g.add_edge(d1_name, d2_name)
            e= g.get_edge(d1_name, d2_name)
            e.attr['label']= str(weight)[:5]
   
    #import ipdb;ipdb.set_trace()
    return g
开发者ID:johndpope,项目名称:automusica,代码行数:21,代码来源:tfidf.py

示例2: dot_layout

# 需要导入模块: from pygraphviz import AGraph [as 别名]
# 或者: from pygraphviz.AGraph import get_edge [as 别名]

#.........这里部分代码省略.........
    sorted_nodes = [y for idx, y in sorted_nodes]
    node_key = dict((id, idx) for idx, id in enumerate(sorted_nodes))

    if node_gt is None:
        node_gt = lambda X, y: False
    else:
        node_gt = lambda x, y: node_key[x] > node_key[y]

    # add nodes to the graph
    for e in elements:
        if e["group"] == "nodes" and e["classes"] != "non_existing":
            g.add_node(e["data"]["id"], label=e["data"]["label"].replace("\n", "\\n"))

    # TODO: remove this, it's specific to leader_demo
    weight = {"reach": 10, "le": 10, "id": 1}
    constraint = {"pending": False}

    # add edges to the graph
    for e in elements:
        if e["group"] == "edges":
            #            kwargs = {'weight': weight.get(e["data"]["obj"], 0)},
            kwargs = {"label": e["data"]["label"]} if edge_labels else {}
            if node_gt(e["data"]["source"], e["data"]["target"]):
                g.add_edge(
                    e["data"]["target"],
                    e["data"]["source"],
                    e["data"]["id"],
                    dir="back",
                    **kwargs
                    # constraint=constraint.get(e["data"]["obj"], True),
                )
            else:
                g.add_edge(
                    e["data"]["source"],
                    e["data"]["target"],
                    e["data"]["id"],
                    **kwargs
                    # constraint=constraint.get(e["data"]["obj"], True),
                )

    # add clusters
    clusters = defaultdict(list)
    for e in elements:
        if e["group"] == "nodes" and e["data"]["cluster"] is not None and e["classes"] != "non_existing":
            clusters[e["data"]["cluster"]].append(e["data"]["id"])
    for i, k in enumerate(sorted(clusters.keys())):
        g.add_subgraph(name="cluster_{}".format(i), nbunch=clusters[k], rank="min")

    # now get positions, heights, widths, and bsplines
    g.layout(prog="dot")

    # get the y origin. we want the top left of the graph to be a
    # fixed coordinate (hopefully (0,0)) so the graph doesn't jump when
    # its height changes. Unfortunately, pygraphviz has a bug a gives
    # the wrong bbox, so we compute the max y coord.

    #    bbox = pygraphviz.graphviz.agget(g.handle,'bb')

    global y_origin
    y_origin = 0.0
    for n in g.nodes():
        top = float(n.attr["pos"].split(",")[1]) + float(n.attr["height"]) / 2
        if top > y_origin:
            y_origin = top
    if subgraph_boxes:
        for sg in g.subgraphs():
            top = float(sg.graph_attr["bb"].split(",")[3])
            if top > y_origin:
                y_origin = top

    for e in elements:
        if e["group"] == "nodes" and e["classes"] != "non_existing":
            attr = g.get_node(e["data"]["id"]).attr
            e["position"] = _to_position(attr["pos"])
            e["data"]["width"] = 72 * float(attr["width"])
            e["data"]["height"] = 72 * float(attr["height"])

        elif e["group"] == "edges":
            if node_gt(e["data"]["source"], e["data"]["target"]):
                attr = g.get_edge(e["data"]["target"], e["data"]["source"], e["data"]["id"]).attr
                pos = attr["pos"]
                pe = pos.split()
                ppe = pe[1:]
                ppe.reverse()
                pos = " ".join([pe[0].replace("s", "e")] + ppe)
            else:
                attr = g.get_edge(e["data"]["source"], e["data"]["target"], e["data"]["id"]).attr
                pos = attr["pos"]
            e["data"].update(_to_edge_position(pos))
            if edge_labels and e["data"]["label"] != "":
                e["data"]["lp"] = _to_position(attr["lp"])
    #    g.draw('g.png')

    if subgraph_boxes:
        for sg in g.subgraphs():
            box = cy_elements.add_shape(sg.name, classes="subgraphs")
            coords = _to_coord_list(sg.graph_attr["bb"])
            box["data"]["coords"] = coords

    return cy_elements
开发者ID:odedp,项目名称:ivy,代码行数:104,代码来源:dot_layout.py

示例3: main

# 需要导入模块: from pygraphviz import AGraph [as 别名]
# 或者: from pygraphviz.AGraph import get_edge [as 别名]
def main():
    usage= 'usage: %prog [options] midis'
    parser= OptionParser(usage=usage)
    parser.add_option('--n-measures', dest='n_measures', default=1, type='int', help='if the partition algorithm is MEASURE, especifies the number of measures to take as a unit')
    parser.add_option('-o', dest='outfname', help='the output file')


    options, args= parser.parse_args(argv[1:])
    if len(args) < 1: parser.error('not enaught args')

    outfname= options.outfname
    if outfname is None:
        parser.error('missing outfname')

    infnames= args[:]

    parser= MidiScoreParser()
    models= []
    for infname in infnames: 
        score= parser.parse(infname)
        if not score: import ipdb;ipdb.set_trace() # por que podria devolver None?

        #########
        # AJUSTES DE PARSING
        notes= score.get_first_voice()
        notes= [n for n in notes if n.duration > 0]
        instr= score.notes_per_instrument.keys()[0]
        patch= instr.patch
        channel= instr.channel
        score.notes_per_instrument= {instr:notes}
        #########


        interval_size= measure_interval_size(score, options.n_measures)
        algorithm= HarmonyHMM(interval_size, instrument=patch, channel=channel)
        algorithm.train(score)
        algorithm.create_model()
        models.append(algorithm.model)


    def sim(m1, m2):
        """
        calcula H(m1|m2)
        """
        from math import log
        ans= 0
        for s1 in m2.state_transition:
            for s2, prob in m1.state_transition.get(s1, {}).iteritems():
                ans+= m2.pi[s1]*prob*log(prob)
        
        return -ans


    from os import path
    def get_node_name(ticks):
        n_quarters= 0
        while ticks >= score.divisions:
            ticks-= score.divisions
            n_quarters+= 1

        if ticks > 0:
            f= Fraction(ticks, score.divisions)
            if n_quarters > 0: return "%s + %s" % (n_quarters, f)
            else: return repr(f)
        return "%s" % n_quarters 
    for i, m in enumerate(models):
        m.pi= m.calc_stationationary_distr()

        from pygraphviz import AGraph
        from utils.fraction import Fraction
            
           
        g= AGraph(directed=True, strict=False)
        for n1, adj in m.state_transition.iteritems():
            n1_name= get_node_name(n1)
            for n2, prob in adj.iteritems():
                n2_name= get_node_name(n2)
                g.add_edge(n1_name, n2_name)
                e= g.get_edge(n1_name, n2_name)
                e.attr['label']= str(prob)[:5]
        model_fname= path.basename(infnames[i]).replace('mid', 'png')
        g.draw(model_fname, prog='dot', args='-Grankdir=LR')                

    sims= defaultdict(dict)
    for i, m1 in enumerate(models):
        for j in xrange(i+1, len(models)):
            m2= models[j]
            sims[path.basename(infnames[i])][path.basename(infnames[j])]= sim(m1, m2)
            sims[path.basename(infnames[j])][path.basename(infnames[i])]= sim(m2, m1)
    
    import csv

    f= open(outfname, 'w')
    writer= csv.writer(f)
    head= sorted(sims)
    head.insert(0, "-")
    writer.writerow(head)
    for (k, row) in sorted(sims.iteritems(), key=lambda x:x[0]):
        row= sorted(row.iteritems(), key=lambda x:x[0])
        row= [t[1] for t in row]
#.........这里部分代码省略.........
开发者ID:johndpope,项目名称:automusica,代码行数:103,代码来源:do.py

示例4: recalculate

# 需要导入模块: from pygraphviz import AGraph [as 别名]
# 或者: from pygraphviz.AGraph import get_edge [as 别名]
def recalculate(user):
    # remove old ranking
    RankedTeam.objects.filter(team__user = user).delete()
    for pic in RankingPicture.objects.all():
        pic.image.delete()
        pic.delete()
    color_index = 0

    team_graph = Graph()
    gvfull = AGraph(directed = True)
    for team in user.teams.all():
        gvfull.add_node(asciiname(team), label = team.name)
        team_graph.add_node(team)
    for game in Game.objects.filter(team_1__user = user, team_2__user = user):
        team_graph.add_edge(game.winner(), game.loser(), game.jugg_diff())
    for source, dest, weight in team_graph.edges():
        gvfull.add_edge(asciiname(source), asciiname(dest), label = str(weight))

    current_place = 1
    gvcircles = AGraph(directed = True)
    gvtiebreaker = AGraph(directed = True)
    for place in team_graph.topological_sort():
        place_list = []
        relevant_teams = set()
        for circle in place:
            relevant_teams |= circle
            if len(circle) == 1:
                continue
            color_index, current_color = getcolor(color_index)
            for team in circle:
                gvcircles.add_node(asciiname(team), label = team.name, color = current_color, fontcolor = current_color)
                gvfull.get_node(asciiname(team)).attr['color'] = current_color
                gvfull.get_node(asciiname(team)).attr['fontcolor'] = current_color
            for source, dest, weight in team_graph.edges():
                if source in circle and dest in circle:
                    gvcircles.add_edge(asciiname(source), asciiname(dest), label = str(weight), color = current_color, fontcolor = current_color)
                    gvfull.get_edge(asciiname(source), asciiname(dest)).attr['color'] = current_color
                    gvfull.get_edge(asciiname(source), asciiname(dest)).attr['fontcolor'] = current_color
        place = [[(team.normalized_jugg_diff(relevant_teams), team.name, team) for team in circle] for circle in place]
        for circle in place:
            circle.sort(reverse = True)
        while place:
            place_list.append(set())
            i = 0
            while i < len(place):
                circle = place[i]
                jd = circle[0][0]
                while circle and circle[0][0] == jd:
                    place_list[-1].add(circle.pop(0))
                if not circle:
                    place.remove(circle)
                else:
                    i += 1
        for same_place_set in place_list:
            # tie breaker
            if len(same_place_set) > 1:
                # teams that everyone on this place played against
                relevant_teams = team_graph.nodes()
                for circ_jugg_diff, name, team in same_place_set:
                    opponents = set()
                    for game in team.games():
                        if game.team_1 == team:
                            opponents.add(game.team_2)
                        else:
                            opponents.add(game.team_1)
                    relevant_teams &= opponents
                if len(relevant_teams) > 0:
                    color_index, current_color_a = getcolor(color_index)
                    color_index, current_color_b = getcolor(color_index)
                    for team in relevant_teams:
                        gvtiebreaker.add_node("b-" + asciiname(team), label = team.name, color = current_color_b, fontcolor = current_color_b)
                    for void, void, team in same_place_set:
                        gvtiebreaker.add_node("a-" + asciiname(team), label = team.name, color = current_color_a, fontcolor = current_color_a)
                        for game in team.games():
                            if game.team_1 == team and game.team_2 in relevant_teams:
                                if game.winner() == team:
                                    gvtiebreaker.add_edge("a-" + asciiname(team), "b-" + asciiname(game.team_2), label = game.jugg_diff(), color = current_color_a, fontcolor = current_color_a)
                                else:
                                    gvtiebreaker.add_edge("b-" + asciiname(game.team_2), "a-" + asciiname(team), label = game.jugg_diff(), color = current_color_b, fontcolor = current_color_b)
                            elif game.team_2 == team and game.team_1 in relevant_teams:
                                if game.winner() == team:
                                    gvtiebreaker.add_edge("a-" + asciiname(team), "b-" + asciiname(game.team_1), label = game.jugg_diff(), color = current_color_a, fontcolor = current_color_a)
                                else:
                                    gvtiebreaker.add_edge("b-" + asciiname(game.team_1), "a-" + asciiname(team), label = game.jugg_diff(), color = current_color_b, fontcolor = current_color_b)
                # jugg differences against relevant teams
                rel_jugg_diffs = set()
                for team_tuple in same_place_set:
                    rel_jugg_diffs.add((team_tuple, team_tuple[2].normalized_jugg_diff(relevant_teams)))
                # pop all teams, highest relevant jugg difference first
                while rel_jugg_diffs:
                    # current maximum
                    max_rel_jugg_diff = None
                    # teams with maximum jugg difference
                    to_remove = None
                    for team_tuple, rel_jugg_diff in rel_jugg_diffs:
                        # new maximum
                        if max_rel_jugg_diff is None or rel_jugg_diff > max_rel_jugg_diff[0]:
                            max_rel_jugg_diff = (rel_jugg_diff, {team_tuple})
                            to_remove = {(team_tuple, rel_jugg_diff)}
                        # same as maximum
#.........这里部分代码省略.........
开发者ID:frederikmoellers,项目名称:jugger-ranking,代码行数:103,代码来源:logic.py

示例5: DotGraphSearchProblem

# 需要导入模块: from pygraphviz import AGraph [as 别名]
# 或者: from pygraphviz.AGraph import get_edge [as 别名]
class DotGraphSearchProblem(Problem):
    """
    Playground for stuff in the library... eats a .dot graph and allows you
    to try it with the search methods.
    """
    def __init__(self, filename):
        self.G = AGraph(filename)
        xs = [(nodo, nodo.attr.get("initial", None))
              for nodo in self.G.iternodes()]
        xs = [x for x in xs if x[1]]
        if len(xs) == 0:
            raise BadInputGraph("Missing 'initial' node")
        elif len(xs) > 1:
            raise BadInputGraph("Cannot have two initial nodes")
        if not any(nodo.attr.get("goal", None) for nodo in self.G.iternodes()):
            raise BadInputGraph("Missing a goal state '[goal=\"1\"]'")
        super(DotGraphSearchProblem, self).__init__(xs[0][0])
        self.initial_state.attr["shape"] = "doublecircle"
        for node in self.G.iternodes():
            if self.is_goal(node):
                node.attr["shape"] = "hexagon"
                node.attr["color"] = "blue"
        self.seen = set()
        self.visit(self.initial_state)
        for edge in self.G.iteredges():
            edge.attr["style"] = "dotted"
            x = edge.attr.get("weight", None)
            if x:
                x = int(x)
            else:
                x = 1
            edge.attr["weight"] = x
            edge.attr["label"] = x

    def actions(self, state):
        assert state in self.G
        if self.G.is_directed():
            return self.G.itersucc(state)
        else:
            assert self.G.is_undirected()
            return self.G.iterneighbors(state)

    def result(self, state, action):
        assert state in self.G and action in self.G
        self.visit(state)
        return action

    def cost(self, state1, action, state2):
        assert state1 in self.G and action in self.G and action == state2
        x = self.G.get_edge(state1, state2).attr["weight"]
        if float(x) == int(x):
            return int(x)
        else:
            return float(x)

    def visit(self, state):
        if state in self.seen:
            return
        self.seen.add(state)
        attr = self.G.get_node(state).attr
        attr["color"] = "firebrick"

    def is_goal(self, state):
        return bool(state.attr.get("goal", False))

    def value(self, state):
        assert state in self.G
        value = self.G.get_node(state).attr.get("value", None)
        if not value:
            return 0
        return float(value)
开发者ID:bx5974,项目名称:simpleai,代码行数:73,代码来源:dotsearch.py

示例6: dot_layout

# 需要导入模块: from pygraphviz import AGraph [as 别名]
# 或者: from pygraphviz.AGraph import get_edge [as 别名]
def dot_layout(cy_elements):
    """
    Get a CyElements object and augment it (in-place) with positions,
    widths, heights, and spline data from a dot based layout.

    Returns the object.
    """
    elements = cy_elements.elements
    g = AGraph(directed=True, strict=False)

    # make transitive relations appear top to bottom
    # TODO: make this not specific to leader example
    elements = list(elements)
    nodes_by_id = dict(
        (e["data"]["id"], e)
        for e in elements if e["group"] == "nodes"
    )
    order = [
        (nodes_by_id[e["data"]["source"]], nodes_by_id[e["data"]["target"]])
        for e in elements if
        e["group"] == "edges" and
        e["data"]["obj"] in ('reach', 'le')
    ]
    elements = topological_sort(elements, order, lambda e: e["data"]["id"])

    # add nodes to the graph
    for e in elements:
        if e["group"] == "nodes":
            g.add_node(e["data"]["id"], label=e["data"]["label"].replace('\n', '\\n'))

    # TODO: remove this, it's specific to leader_demo
    weight = {
        'reach': 10,
        'le': 10,
        'id': 1,
    }
    constraint = {
        'pending': False,
    }

    # add edges to the graph
    for e in elements:
        if e["group"] == "edges":
            g.add_edge(
                e["data"]["source"],
                e["data"]["target"],
                e["data"]["id"],
                weight=weight.get(e["data"]["obj"], 0),
                #constraint=constraint.get(e["data"]["obj"], True),
            )

    # add clusters
    clusters = defaultdict(list)
    for e in elements:
        if e["group"] == "nodes" and e["data"]["cluster"] is not None:
            clusters[e["data"]["cluster"]].append(e["data"]["id"])
    for i, k in enumerate(sorted(clusters.keys())):
        g.add_subgraph(
            name='cluster_{}'.format(i),
            nbunch=clusters[k],
        )

    # now get positions, heights, widths, and bsplines
    g.layout(prog='dot')
    for e in elements:
        if e["group"] == "nodes":
            attr = g.get_node(e["data"]["id"]).attr
            e["position"] = _to_position(attr['pos'])
            e["data"]["width"] = 72 * float(attr['width'])
            e["data"]["height"] = 72 * float(attr['height'])

        elif e["group"] == "edges":
            attr = g.get_edge(e["data"]["source"], e["data"]["target"], e["data"]["id"]).attr
            e["data"].update(_to_edge_position(attr['pos']))
    g.draw('g.png')

    return cy_elements
开发者ID:asyaf,项目名称:ivy,代码行数:79,代码来源:dot_layout.py


注:本文中的pygraphviz.AGraph.get_edge方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。