Beispiel #1
0
def compute_graph(edges, x, y, precision, tollerance):

    if booldebug: print(x, y)
    graph = Graph('image')
    q = Queue('nodes')
    p_node = Point(x, y)
    node = Node(p_node)
    graph.nodes.append(node)
    q.push(node)

    while not q.empty():
        node = q.top()
        q.pop()
        links = []

        p_node = node.get_point()
        x = p_node.get_x()
        y = p_node.get_y()
        cell = generate_cell(edges, p_node, precision)
        links = find_lines(cell, edges, x - precision, y - precision,
                           tollerance)
        #if booldebug: print(links)
        delete(edges, cell, x - precision, y - precision)

        for p in links:
            graph.nodes.append(Node(p))
            q.push(Node(p))

        graph.manage_links(node, links)

    if len(graph.nodes) > 2:
        return DPS(graph)
Beispiel #2
0
def createKnightGraph(boardSize):             #this function creates the graph that
    knightGraph = Graph()                     #will be used in the tour.  "boardSize" is the length of 
    for row in range(boardSize):              #a row or column of the chess board
        for col in range(boardSize):
            nodeId = assignNodeId(row,col,boardSize)         #calls helper function to create nodes in the graph
            newPositions = genLegalMoves(row,col,boardSize)  #calls helper function to generate legal moves from a node
            for e in newPositions:
                nid = assignNodeId(e[0],e[1],boardSize)
                knightGraph.addEdge(nodeId,nid)              #adds edge between initial node and all legal knight's moves
    return knightGraph
Beispiel #3
0
def extended_popularity_similarity_optimisation_model(N,
                                                      m,
                                                      L=0,
                                                      beta=1 / 2,
                                                      T=0):
    def distance(i, j):
        r_i, phi_i, r_j, phi_j = r[i], phi[i], r[j], phi[j]
        r_j = beta * r_i + (1 - beta) * r_j
        d_phi = pi - abs(pi - abs(phi_i - phi_j))
        return cosh(r_i) * cosh(r_j) + sinh(r_i) * sinh(r_j) * cos(d_phi)

    if beta == 0:

        def cutoff(r_i):
            return r_i - 2 * log(T / sin(T * pi) * (1 - exp(-r_i / 2)) / m)
    elif beta == 1:

        def cutoff(r_i):
            return r_i - 2 * log(T / sin(T * pi) * r_i / m)
    else:

        def cutoff(r_i):
            return r_i - 2 * log(T / sin(T * pi) *
                                 (1 - exp(-r_i *
                                          (1 - beta) / 2)) / m / (1 - beta))

    def connection_probability(d_ij, cutoff_i):
        return 1 / (1 + exp((d_ij - cutoff_i) / 2 / T))

    G = Graph()
    r = [2 * math.log(i + 1) for i in range(N)]
    phi = [2 * math.pi * random.random() for _ in range(N)]

    for i in range(N):
        G.add_vertex(i, r=r[i], phi=phi[i])
        #G.add_vertex(i, x=r[i]*math.cos(phi[i]), y=r[i]*math.sin(phi[i]))

        m += 2 * L * (1 - beta) / (1 - N**(beta - 1))**2 / (2 * beta - 1) * (
            (N / i)**(2 * beta - 1) - 1) * (1 - i**(beta - 1))
        if i <= m:
            for j in range(i):
                G.add_edge(i, j)

        elif T == 0:
            neighbours = sorted(range(i), key=lambda j: distance(i, j))[m]
            for j in neighbours:
                G.add_edge(i, j)
        else:
            cutoff_i = cutoff(r[i])
            for j in range(i):
                d_ij = distance(r[i], phi[i], r[j], phi[j])
                if random.random() < connection_probability(d_ij, cutoff_i):
                    G.add_edge(i, j)

    return G
Beispiel #4
0
def popularity_similarity_optimisation_model(N, m, beta=1 / 2, T=0):
    def distance(i, j):
        r_i, phi_i, r_j, phi_j = r[i], phi[i], r[j], phi[j]
        r_j = beta * r_i + (1 - beta) * r_j
        d_phi = pi - abs(pi - abs(phi_i - phi_j))
        return acosh(
            cosh(r_i) * cosh(r_j) + sinh(r_i) * sinh(r_j) * cos(d_phi))

    if beta == 0:

        def cutoff(r_i):
            return r_i - 2 * log(T / sin(T * pi) * (1 - exp(-r_i / 2)) / m)
    elif beta == 1:

        def cutoff(r_i):
            return r_i - 2 * log(T / sin(T * pi) * r_i / m)
    else:

        def cutoff(r_i):
            return r_i - 2 * log(T / sin(T * pi) *
                                 (1 - exp(-r_i *
                                          (1 - beta) / 2)) / m / (1 - beta))

    def connection_probability(d_ij, cutoff_i):
        return 1 / (1 + exp((d_ij - cutoff_i) / 2 / T))

    G = Graph()
    r = [2 * math.log(i) for i in range(1, N + 1)]
    phi = [2 * math.pi * random.random() for _ in range(N)]

    for i in range(N):

        G.add_vertex(i,
                     r=geometry.native_disk_to_hyperboloid(r[i]),
                     phi=phi[i])

        if i <= m:
            for j in range(i):
                G.add_edge(i, j)
        elif T == 0:
            print(i)
            print(sorted(range(i), key=lambda v: v))
            neighbours = sorted(range(i), key=lambda j: distance(i, j))[:m]
            for j in neighbours:
                G.add_edge(i, j)
        else:
            cutoff_i = cutoff(r[i])
            for j in range(i):
                d_ij = distance(r[i], phi[i], r[j], phi[j])
                if random.random() < connection_probability(d_ij, cutoff_i):
                    G.add_edge(i, j)

    return G
Beispiel #5
0
    def setUp(self):
        self.test_graph = Graph()
        self.test_node_0 = Node(0, 0.1, 1, 1, 1, 1, 1, 1)
        self.test_node_1 = Node(1, 0.2, 2, 2, 2, 2, 2, 2)
        self.test_node_2 = Node(2, 0.3, 1, 2, 3, 4, 5, 6)
        self.test_graph.add_vertex(self.test_node_0)
        self.test_graph.add_vertex(self.test_node_1)
        self.test_graph.add_vertex(self.test_node_2)
        self.test_graph.add_edge(self.test_node_0, self.test_node_1, 30)
        self.test_graph.add_edge(self.test_node_1, self.test_node_2, 50)

        self.test_sim = Simulation()
        self.test_sim.load_graph(self.test_graph)
Beispiel #6
0
def main():

    number_of_ant = 10  #numarul de furnici
    generations = 100  #numarul de generatii
    alpha = 1.0  #controleaza importanta urmei (cate furnici au mai trecut pe muchia respectiva)
    beta = 10.0  #controleaza importanaa vizibilitatii (cat de aproape se afla următorul oras)
    rho = 0.5  #coeficient de degradare a feronomului
    q = 10  #intensitatea(cantitatea) unui feromon lasata de o furnica

    aco = ACO(number_of_ant, generations, alpha, beta, rho, q)
    graph = Graph(cost_matrix, rank)

    path, cost = aco.solve(graph)
    print('cost: {}, path: {}'.format(cost, path))
Beispiel #7
0
def empty_graph(N=0, directed=False):
    '''
    Create an empty graph of given size.
    Parameters
    ----------
    N:int
        Number of vertices.
    Returns
    -------
    G : Graph
        Generated empty graph
    '''
    G = Graph() if not directed else DiGraph()
    for i in range(N):
        G.add_vertex(i)
    return G
Beispiel #8
0
 def setUp(self):
     self.g = Graph()
     self.g.add_node("A")
     self.g.add_node("B")
     self.g.add_node("C")
     self.g.add_node("D")
     self.g.add_node("E")
     self.g.add_distance("A", "B", 5)
     self.g.add_distance("B", "C", 4)
     self.g.add_distance("C", "D", 8)
     self.g.add_distance("D", "C", 8)
     self.g.add_distance("D", "E", 6)
     self.g.add_distance("A", "D", 5)
     self.g.add_distance("C", "E", 2)
     self.g.add_distance("E", "B", 3)
     self.g.add_distance("A", "E", 7)
Beispiel #9
0
def generate_graph():
    """ Generate the graph """
    edges: set = set()
    total_refs: int = 0
    successful_refs: int = 0
    errors_dict = init_errors_dict()
    laws, frbr_work_uri_to_law = build_laws_mapping()
    vertexes_map = {hash(law): law for law in laws}

    for from_law in laws:
        law_edges: set = set()
        for ref_element in from_law.get_ref_elements():
            from_vertex: Vertex = get_from_vertex(from_law, ref_element,
                                                  law_edges, vertexes_map)

            to_vertex: Vertex = get_to_vertex(from_law, ref_element,
                                              errors_dict,
                                              frbr_work_uri_to_law, law_edges,
                                              vertexes_map)
            if not to_vertex:
                total_refs += 1
                continue

            # setup an edge and maintain metadata
            edge: Edge = Edge(from_vertex, to_vertex, ref_element)
            law_edges.add(edge)
            from_vertex.add_out_edge(edge)
            to_vertex.add_in_edge(edge)

            successful_refs += 1
            total_refs += 1
            logging.info(
                f"{total_refs}. Succeed to handle href {ref_element.attrib[HREF]} in from_law {from_law.path}"
            )

        edges.update(law_edges)

    logging.info(
        f'{total_refs = }, {successful_refs = }, failed_not_handled_refs = {total_refs - successful_refs}'
    )
    write_to_errors_file(errors_dict)

    nodes = set(vertexes_map.values())

    edges_cleaned = clean_edges(edges)

    return Graph(nodes, edges_cleaned)
Beispiel #10
0
def main():
    g = Graph()
    g = g.from_file('./graph.txt')

    # # Resolvemos primer grupo de preguntas 1-5
    print "The distance of the route A-B-C", distance(g, "A", "B", "C")
    print "The distance of the route A-D", distance(g, "A", "D")
    print "The distance of the route A-D-C", distance(g, "A", "D", "C")
    print "The distance of the route A-E-B-C-D", distance(
        g, "A", "E", "B", "C", "D")
    print "The distance of the route A-E-D", distance(g, "A", "E", "D")
    print

    # # Respondemos preguntas 8 y 9
    print "The length of the shortest route from A to C.", dist_to(g, "A", "C")
    print "The length of the shortest route from B to B.", dist_to(g, "B", "B")
    print "The length of the shortest route from E to A.", dist_to(g, "E", "A")
    print
Beispiel #11
0
    def __init__(self, bins, items, population, evaporation, limit=10000):
        self.bins = bins
        self.items = items

        self.ants = []
        for i in range(population):
            self.ants.append(Ant())

        self.graph = Graph(len(bins), len(items))

        self.evaporation = evaporation
        self.limit = limit

        self.numOfEvaluations = 0
        self.ran = False
        self.runtime = 0
        self.bestRun = None
        self.avgFitness = []
Beispiel #12
0
def addpoi():
    data = json.load(open('projects/' + project + '/pois.json'))
    graph = Graph(project, auto_connect=False)

    level = int(request.form.get('level'))
    x = int(request.form.get('x'))
    y = int(request.form.get('y'))
    name = request.form.get('name')
    room = graph.get_room(Position(level, x, y))
    if room is None:
        return json.dumps({'success': False})

    data[name] = {'level': level, 'x': x, 'y': y}
    json.dump(data,
              open('projects/' + project + '/pois.json', 'w'),
              indent=4,
              sort_keys=True)

    return 'ok'
Beispiel #13
0
def main():

    screen_width, screen_height = 1440, 810
    screen = pygame.display.set_mode((screen_width, screen_height))
    pygame.display.set_caption('Sorting algorithm visualization')
    clock = pygame.time.Clock()

    graph = Graph(screen)  # pass surface to draw graph on
    graph.gen_array(rand_colors=True)

    running = True
    while running:

        running = events.keypress(
            graph)  # keypress calls some graph object methods
        graph.draw_bars()
        graph.display_helptext()
        clock.tick(6)

    pygame.quit()
Beispiel #14
0
def addconnection():
    data = json.load(open('projects/' + project + '/graph.json'))
    graph = Graph(project, auto_connect=False)

    node1 = graph.nodes[graph.nodes_by_name[request.form.get('node1')]]
    node2 = graph.nodes[graph.nodes_by_name[request.form.get('node2')]]

    directed = request.form.get('directed') == '1'
    ctype = request.form.get('ctype')

    if graph.get_connection(node1, node2)[0] is not None:
        return json.dumps({'success': False})

    cdata = {
        'node0': request.form.get('node1'),
        'node1': request.form.get('node2'),
    }
    if ctype != 'default':
        cdata['ctype'] = ctype

    if directed:
        cdata['directed'] = True

    data['connections'].append(cdata)
    json.dump(data,
              open('projects/' + project + '/graph.json', 'w'),
              indent=4,
              sort_keys=True)

    return json.dumps({
        'success': True,
        'x1': node1.x,
        'y1': node1.y,
        'x2': node2.x,
        'y2': node2.y,
        'node1': node1.name,
        'node2': node2.name,
        'directed': directed,
        'ctype': ctype,
        'levels': list(set((node1.level, node2.level)))
    })
def test_badness_real():
    #networks = ['data/protein_interaction.adj']
    networks = ['data/food_web.adj', 'data/protein_interaction.adj', 'data/pierre_auger.adj']
    for filename in networks:
        G = Graph(readwrite.read_adjacency_list(filename))
        G = G.largest_component()
        G.defragment_indices()
        G.embed_ncMCE()
        badness = G.greedy_routing_badness()
        max_badness = max(badness.values())
        for vertex, attributes in G.vert.items():
            attributes.update({'color':badness[vertex]/max_badness})
            attributes.update({'size':badness[vertex]/max_badness})
        G.draw(representation='hyperbolic_polar', vertex_scale=50)
        G.embed_ncMCE(angular_adjustment=embedding.circular_adjustment)
        badness = G.greedy_routing_badness()
        max_badness = max(badness.values())
        for vertex, attributes in G.vert.items():
            attributes.update({'color':badness[vertex]/max_badness})
            attributes.update({'size':badness[vertex]/max_badness})
        G.draw(representation='hyperbolic_polar', vertex_scale=50)
    return
Beispiel #16
0
def addnode():
    data = json.load(open('projects/' + project + '/graph.json'))
    graph = Graph(project, auto_connect=False)

    level = int(request.form.get('level'))
    x = int(request.form.get('x'))
    y = int(request.form.get('y'))
    room = graph.get_room(Node(None, None, level, x, y))
    if room is None:
        return json.dumps({'success': False})

    newname = hex(int(time.time() * 100))[2:]
    data['nodes'][newname] = {'level': level, 'x': x, 'y': y}
    json.dump(data,
              open('projects/' + project + '/graph.json', 'w'),
              indent=4,
              sort_keys=True)

    return json.dumps({
        'success': True,
        'name': newname,
        'room': room.name,
        'node': data['nodes'][newname]
    })
Beispiel #17
0
	def test_new_edge(self):
		graph = new Graph()

		node1 = 'prev'
		node2 = 'next'
		graph.add_edge(node1, node2, weight=1)
Beispiel #18
0
	def test_new_instance(self):
		graph = new Graph()
		assertTrue(graph.nodes)
Beispiel #19
0
#!/usr/bin/env python

from classes import Node, Graph

graphobj = Graph()

n1 = Node(name="test")
graphobj.addNode(n1)
n2 = Node(name="Child1", parent=n1)
graphobj.addNode(n2)
n3 = Node(name="Child2", parent=n1)
graphobj.addNode(n3)
n1.addChildren(n2)
n1.addChildren(n3)

nodes = graphobj.nodes

print "^^^^^^^^^^^^^^^^"
selectnode = graphobj.getNode("Child2")
print selectnode.name
print "^^^^^^^^^^^^^^^^"

for eachnode in nodes:
    print eachnode.name
    children = eachnode.getChildren()
    if len(children) > 0:
        for i in children:
            print "name"
            print i.name
            print "Parent"
            print i.parent.name
Beispiel #20
0
 def __init__(self):
     self.g = Graph()
     self.vehiclesByZip = {}
     pass
Beispiel #21
0
import Tkinter as tk
import sys
import pyscreeze
import pygame
import os
from classes import Node, Graph
import termios
import tty

#Global Variables
childOffsetX = 20
screenWidth, screenHeight = pyautogui.size()
print screenHeight
print screenWidth

graphMaster = Graph()
parentRoot = Node(name="Root")
graphMaster.addNode(parentRoot)


class Application(tk.Frame):
    def __init__(self, master=None):
        tk.Frame.__init__(self, master=None)
        self.grid()
        self.master.minsize(width=200, height=100)
        self.master.bind("<Key>", self.show)
        self.filename = ""
        self.height = 0
        self.width = 0
        self.listele = ()
        self.createWidjet()
Beispiel #22
0
    project = os.environ['C3NAVPROJECT']
elif len(sys.argv) > 1:
    project = sys.argv[1]
else:
    print(
        'Please specify project: run.py <project> or environment variable C3NAVPROJECT'
    )
    sys.exit(1)

if len(sys.argv) != 3:
    print('select language!')
    sys.exit(1)
lang = sys.argv[2]
print('translating into %s…' % lang)

data = Graph(project, auto_connect=False).data
rooms = list(data['rooms'].keys())
pois = list(data['pois'].keys())
superrooms = [
    room['superroom'] for room in data['rooms'].values() if 'superroom' in room
]
roomgroups = list(
    sum((room.get('groups', []) for room in data['rooms'].values()), []))
roomgroups += [(':' + s) for s in roomgroups]
poigroups = list(
    sum((poi.get('groups', []) for poi in data['pois'].values()), []))
poigroups += [(':' + s) for s in poigroups]

for name in set(pois + roomgroups + rooms + superrooms + poigroups):
    data = json.load(open('projects/' + project + '/titles.json'))
    titles = data.get(name, {})
Beispiel #23
0
        FIN = 30
    elif nombre == 1:
        filename = "kept_map/newmap1.txt"
        FIN = 65
    elif nombre == 2:
        filename = "kept_map/newmap2.txt"
        FIN = 32
    else:
        sys.exit()

    ###
    t0 = time.time()
    #translation file to list[list]
    maze = file2map(open(filename, 'r'))
    create_edges(maze)  #create the file to create the graph after
    g = Graph()
    g.read(
        "graph.txt")  #read the file created just before to complete the graph
    try:
        pi = g.dijkstra()  #apply dijsktra
    except:
        print("No way found to solve the maze")
        sys.exit(1)
    Path = backtrack_pred(pi, g._vertices[FIN])  #path from start to end
    print("temps ==> ", time.time() - t0)
    ###

    #Object representing the Robot
    #Firstly just the display
    #Then a real continue model
    Rob = RobotSimple(0, 0, 'S')
Beispiel #24
0
import classes.Graph as Gr
import classes.Algorithms as Algs
import random as rnd
import pandas as pd

city = 'NY'

gr = Gr.Graph()
print('read graph')
gr.read_graph_from_csv(city + '_nodes.csv', city + '_roads.csv')

print('init ALT')

# amount of marks хардкод этой константы есть в конструкторе Node и в heuristic альта
k = 16
print('Amount of landmarks:', k)
marks = rnd.sample(list(gr.nodes.values()), k)

# поиск всех кротчайших путей
counter = 0
for mark in marks:
    dists = Algs.dijkstra_alt(gr, mark)
    for node in list(gr.nodes.values()):
        node.dist_to_mark[counter] = dists[node.id]
    counter += 1
    print(counter, 'of', k)

# создание DataFrame нодов для записи в csv
ids = []
x = []
y = []
Beispiel #25
0
        active_time = graph.active_time / running_time
        active_time = round(100 * active_time, 2)
        var_active.set("Active Time : {}%".format(active_time))
    keys_clicks = graph.keypresses / max((graph.clicks + graph.keypresses), 1)
    keys_clicks = round(100 * keys_clicks, 2)
    var_cur.set("Current : {} APM".format(cur_apm))
    var_cur_hover.set("{} APM".format(cur_apm))
    var_max.set("Max : {} APM".format(max_apm))
    var_avg.set("Avg : {} APM".format(avg_apm))
    var_kc.set("Keypresses : {}%".format(keys_clicks))

    Fenetre.update_idletasks()

    if graph.active != "inactive":
        stats.after(100, update_stats)


# Real-time moving average apm graphing
graph = Graph(Fenetre,
              bg="black",
              width=width,
              height=3 * height // 4,
              max_x=10,
              max_y=10)
graph.place(x=0, y=height // 4)
graph.display(intro=True)

Fenetre.mainloop()
klistener.stop()
mlistener.stop()
Beispiel #26
0
from classes import Graph
import sys

if __name__ == "__main__":
    if len(sys.argv) > 1:
        output = Graph(sys.argv[1])
    else:
        output = Graph()
Beispiel #27
0
def map():
    graph = Graph(project, auto_connect=False, load_wifi=True)
    return render_template('wificollect.html',
                           fakemobile=('fakemobile' in request.args),
                           graph=graph)
Beispiel #28
0
from classes import Graph

if 'C3NAVPROJECT' in os.environ:
    project = os.environ['C3NAVPROJECT']
elif len(sys.argv) > 1:
    project = sys.argv[1]
else:
    print(
        'Please specify project: run.py <project> or environment variable C3NAVPROJECT'
    )
    sys.exit(1)

starttime = time.time()

graph = Graph(project, auto_connect=False, load_wifi=True)

for sid in graph.wifi.sids:
    while True:
        print('')
        print(sid)
        f, axes = plt.subplots(graph.levels)

        vmin = graph.wifi.w_to_dbm(
            np.min(graph.wifi.matrix[:, :, :, graph.wifi.sid_ids[sid]]))
        vmax = graph.wifi.w_to_dbm(
            np.max(graph.wifi.matrix[:, :, :, graph.wifi.sid_ids[sid]]))
        for i, ax in enumerate(axes):
            ax.imshow(
                imread('static/img/levels/dev/level%d.jpg' %
                       i)[::graph.wifi.divide_by, ::graph.wifi.divide_by])
Beispiel #29
0
#!/usr/bin/env python
"""
Description : Test runner Module. Constructs the Tree from inputCollection

"""
import pymongo
from classes import Node, Graph
import os
from TestCases import TestCase, Gene
import Tkinter as tk
import sys, math
import random

#Global Variables
graphmaster = Graph()
population = Gene()
maxRun = 1
matingPool = []

#1 . Reconstruct Tree based on information from input collection
client = pymongo.MongoClient()
db = client.input

rootNodeCursor = db.inputCollection.find({"name": "Root"})
rootNode = Node(name="Root")
graphmaster.addNode(rootNode)
## Create the root Node
rootEle = rootNodeCursor[0]["children"]
for child in rootEle:
    newchild = Node(name=child, parent=rootNode)
    rootNode.addChildren(newchild)
Beispiel #30
0
assets = Environment(app)
babel = Babel(app)

if 'C3NAVPROJECT' in os.environ:
    project = os.environ['C3NAVPROJECT']
elif len(sys.argv) > 1:
    project = sys.argv[1]
else:
    print(
        'Please specify project: run.py <project> or environment variable C3NAVPROJECT'
    )
    sys.exit(1)

starttime = time.time()
graph = Graph(project,
              auto_connect=True,
              load_wifi=(not os.environ.get('ROUTEONLY')))
print('Graph loaded in %.3fs' % (time.time() - starttime))


@babel.localeselector
def get_locale():
    locale = 'en'  # request.accept_languages.best_match(LANGUAGES.keys())
    if request.cookies.get('lang') in LANGUAGES.keys():
        locale = request.cookies.get('lang')
    if request.args.get('lang') in LANGUAGES.keys():
        locale = request.args.get('lang')
    return locale


@app.before_request