Example #1
0
 def __init__(self, data=None, **attr):
     # the init could be
     # graph = Graph(g) where g is a Graph
     # graph = Graph((v,e)) where v is Graph.v like and e is Graph.e like
     # graph = Graph(({},e)) for an edgelist with no specified nodes
     # others with classmethods like
     # Graph.from_adjacency_matrix(m)
     # Graph.from_adjacency_list(l)
     #
     # should abstract the data here
     self._nodedata = {}  # empty node attribute dict
     self._adjacency = {}  # empty adjacency dict
     # the interface is n,e,a,data
     self.n = Nodes(self._nodedata, self._adjacency) # rename to self.nodes
     self.e = Edges(self._nodedata, self._adjacency) # rename to self.edges
     self.a = Adjacency(self._adjacency) # rename to self.adjacency
     self.data = {}   # dictionary for graph attributes
     # load with data
     if hasattr(data,'n') and not hasattr(data,'name'): # it is a new graph
         self.n.update(data.n)
         self.e.update(data.e)
         self.data.update(data.data)
         data = None
     try:
         nodes,edges = data # containers of edges and nodes
         self.n.update(nodes)
         self.e.update(edges)
     except: # old style
         if data is not None:
             convert.to_networkx_graph(data, create_using=self)
     # load __init__ graph attribute keywords
     self.data.update(attr)
Example #2
0
class Scene:
    def __init__(self):
        self.reset(gen_uuid())

    def update(self, nodes):
        current_time = rospy.Time.now()
        for node in nodes:
            node.last_update.data = current_time
            if node.parent not in self.__nodes:
                node.parent = self.root_id()
        self.__nodes.update(nodes)
        return [n.id for n in nodes if n.name != "root"]

    def remove(self, ids):
        self.__nodes.remove(ids)
        return ids

    def root_id(self):
        return self.__root_id

    def nodes(self):
        return self.__nodes

    def reset(self, root_id):
        self.__root_id = root_id
        if not hasattr(self, '__nodes'):
            node_ids = []
            self.__nodes = Nodes()
        else:
            node_ids = self.__nodes.ids()
            self.__nodes.reset()
        root = Node(id=self.__root_id, name="root")
        root.position.pose.orientation.w = 1.0
        self.__nodes.update([root])
        return node_ids
 def test_remove_table(self):
     nodes = Nodes()
     nodes.tables.append({"BBBBBBBB": {"BBBBBBBB": 1}})
     EXPECTED = [{"nodeself": {"nodeself": 0}}]
     ARG1 = "BBBBBBBB"
     nodes.remove_table(ARG1)
     actual = nodes.tables
     self.assertEqual(EXPECTED, actual)
Example #4
0
def NodeInitialization (x_rob,x_ped,weight,theta,p1_goal,p2_goal,v):

    gScore_ = [0,0]
    gScore = np.dot(gScore_,weight)

    initial_node = Nodes()
    initial_node.parent = 0
    initial_node.
 def test_add_table_byte(self):
     nodes = Nodes()
     EXPECTED = [{"nodeself": {"nodeself": 0}},
                 {"BBBBBBBB": {"BBBBBBBB": 1}}]
     ARG1 = bytearray("\x42\x42\x42\x42\x42\x42\x42\x42\x30\x30")
     ARG2 = 1
     nodes.add_table_byte(ARG1, ARG2)
     actual = nodes.tables
     self.assertEqual(EXPECTED, actual)
Example #6
0
 def reset(self, root_id):
     self.__root_id = root_id
     if not hasattr(self, '__nodes'):
         node_ids = []
         self.__nodes = Nodes()
     else:
         node_ids = self.__nodes.ids()
         self.__nodes.reset()
     root = Node(id=self.__root_id, name="root")
     root.position.pose.orientation.w = 1.0
     self.__nodes.update([root])
     return node_ids
 def test_get_nearest_neighbor(self):
     nodes = Nodes()
     TABLES = [{"BBBBBBBB": {"BBBBBBBB": 1,
                             "CCCCCCCC": 4,
                             "DDDDDDDD": 2,
                             "EEEEEEEE": 3}},
               {"CCCCCCCC": {"BBBBBBBB": 4,
                             "CCCCCCCC": 1,
                             "DDDDDDDD": 3,
                             "EEEEEEEE": 2}}]
     TARGET = "EEEEEEEE"
     nodes.tables.extend(TABLES)
     EXPECTED = "CCCCCCCC"
     actual = nodes.get_nearest_neighbor(TARGET)
     self.assertEqual(EXPECTED, actual)
 def __init__(self, name=None):
     self.log_color = 'red'
     self.name = name or random_string(8)
     self.events = Events()
     events.e = self.events
     self.nodes = Nodes()
     self.register = Register(machine=self, events=self.events)
Example #9
0
def logout():
    body = request.get_json()
    res = Nodes().remove_node(body['username'], body['password'])
    if type(res) is dict:
        return jsonify(res['message']), res['code']
    else:
        return res["message"], res['code']
Example #10
0
    def __init__(self, parent=None):
        QtWidgets.QDialog.__init__(self, parent,
                                   QtCore.Qt.WindowStaysOnTopHint)

        self._cfg = Config.get()
        self._nodes = Nodes.instance()
        self._db = Database.instance()

        self._notification_callback.connect(self._cb_notification_callback)
        self._notifications_sent = {}

        self.setupUi(self)

        self.dbFileButton.setVisible(False)
        self.dbLabel.setVisible(False)

        self.acceptButton.clicked.connect(self._cb_accept_button_clicked)
        self.applyButton.clicked.connect(self._cb_apply_button_clicked)
        self.cancelButton.clicked.connect(self._cb_cancel_button_clicked)
        self.popupsCheck.clicked.connect(self._cb_popups_check_toggled)
        self.dbFileButton.clicked.connect(self._cb_file_db_clicked)

        if QtGui.QIcon.hasThemeIcon("emblem-default") == False:
            self.applyButton.setIcon(self.style().standardIcon(
                getattr(QtWidgets.QStyle, "SP_DialogApplyButton")))
            self.cancelButton.setIcon(self.style().standardIcon(
                getattr(QtWidgets.QStyle, "SP_DialogCloseButton")))
            self.acceptButton.setIcon(self.style().standardIcon(
                getattr(QtWidgets.QStyle, "SP_DialogSaveButton")))
            self.dbFileButton.setIcon(self.style().standardIcon(
                getattr(QtWidgets.QStyle, "SP_DirOpenIcon")))
Example #11
0
 def __init__(self, data=None, **attr):
     # the init could be
     # graph = Graph(g) where g is a Graph
     # graph = Graph((v,e)) where v is Graph.v like and e is Graph.e like
     # graph = Graph(({},e)) for an edgelist with no specified nodes
     # others with classmethods like
     # Graph.from_adjacency_matrix(m)
     # Graph.from_adjacency_list(l)
     #
     # should abstract the data here
     self._nodedata = {}  # empty node attribute dict
     self._adjacency = {}  # empty adjacency dict
     # the interface is n,e,a,data
     self.n = Nodes(self._nodedata, self._adjacency)  # rename to self.nodes
     self.e = Edges(self._nodedata, self._adjacency)  # rename to self.edges
     self.a = Adjacency(self._adjacency)  # rename to self.adjacency
     self.data = {}  # dictionary for graph attributes
     # load with data
     if hasattr(data, "n") and not hasattr(data, "name"):  # it is a new graph
         self.n.update(data.n)
         self.e.update(data.e)
         self.data.update(data.data)
         data = None
     try:
         nodes, edges = data  # containers of edges and nodes
         self.n.update(nodes)
         self.e.update(edges)
     except:  # old style
         if data is not None:
             convert.to_networkx_graph(data, create_using=self)
     # load __init__ graph attribute keywords
     self.data.update(attr)
def run_route_planner():
    """Runs the whole program."""
    # Initialize global settings and screen.
    settings = Settings()
    pygame.init()
    screen = pygame.display.set_mode(
        (settings.screen_width, settings.screen_height))
    pygame.display.set_caption("Route Planner 1.1")

    # Make a next button.
    next_button = Button(settings, screen, "Next")

    # Hard coded map.
    world = World(settings.map_width, settings.map_height)

    """world.matrix = [["601000", "100100", "100010", "100001", "100000", "100000"],
                    ["100000", "100000", "100100", "100000", "100000", "100000"],
                    ["100000", "100000", "100000", "100000", "100000", "100000"],
                    ["100000", "100000", "100000", "100000", "100000", "100000"],
                    ["100000", "100000", "100000", "100000", "100000", "100000"],
                    ["100000", "100000", "100000", "100000", "100000", "100000"]]"""

    world.matrix = [["601000", "500100", "310010", "610001", "600000", "610000"],
                    ["530000", "400000", "310000", "510000", "530000", "100000"],
                    ["100000", "100000", "100000", "530000", "620000", "100000"],
                    ["100000", "100000", "100000", "100000", "100000", "100000"],
                    ["100000", "100000", "100000", "100000", "100000", "100000"],
                    ["100000", "100000", "100000", "100000", "100000", "100000"]]

    # Create nodes for the world matrix.
    nodes = Nodes(world.matrix)

    # Make a new robot instance.
    robot = Robot()

    # Init and subscribe to mqtt broker.
    mqtt = Mqtt(settings.broker, settings.get_client_id(),
                settings.username, settings.password, settings.topic)

    buttons = []

    # Print out nodes to check if algoritm is correct.
    """   for node in nodes.nodes_dict:
        print(node + " : ", nodes.nodes_dict[node]) """

    while True:
        # main loop
        rf.update_map(world.matrix, nodes, mqtt.msgs, robot)
        rf.check_events(settings, robot, buttons, next_button, mqtt)
        rf.update_robot_route(world.matrix, nodes.nodes_dict, robot)
        buttons = rf.update_screen(screen, settings, world.matrix,
                                   nodes, next_button, robot)
        """for node in nodes.nodes_dict:
            print(node + " : ", nodes.nodes_dict[node])"""
        # if no more tasks are left, the mission is complete.
        if len(robot.goals) == 0:
            print("Mission Complete!")
            mqtt.client.loop_stop()
            mqtt.client.disconnect()
            break
Example #13
0
 def setUp(self):
     self.Graph = nxGraph
     # build dict-of-dict-of-dict K3
     ed1, ed2, ed3 = ({}, {}, {})
     self.k3adj = {
         0: {
             1: ed1,
             2: ed2
         },
         1: {
             0: ed1,
             2: ed3
         },
         2: {
             0: ed2,
             1: ed3
         }
     }
     self.k3edges = [(0, 1), (0, 2), (1, 2)]
     self.k3nodes = [0, 1, 2]
     self.K3 = self.Graph()
     self.K3.adj = self.K3._adjacency = self.K3.edge = self.k3adj
     self.K3.node = self.K3._nodedata = {}
     self.K3.node[0] = {}
     self.K3.node[1] = {}
     self.K3.node[2] = {}
     self.K3.n = Nodes(self.K3._nodedata, self.K3._adjacency)
     self.K3.e = Edges(self.K3._nodedata, self.K3._adjacency)
     self.K3.a = Adjacency(self.K3._adjacency)
 def test_get_full_table_byte(self):
     nodes = Nodes()
     TABLES = [{"BBBBBBBB": {"BBBBBBBB": 1,
                             "CCCCCCCC": 4,
                             "DDDDDDDD": 2,
                             "EEEEEEEE": 3}},
               {"CCCCCCCC": {"BBBBBBBB": 4,
                             "CCCCCCCC": 1,
                             "DDDDDDDD": 3,
                             "EEEEEEEE": 2}}]
     nodes.tables.extend(TABLES)
     EXPECTED = b"\x42\x42\x42\x42\x42\x42\x42\x42\x30\x31"
     EXPECTED += b"\x43\x43\x43\x43\x43\x43\x43\x43\x30\x31"
     EXPECTED += b"\x44\x44\x44\x44\x44\x44\x44\x44\x30\x32"
     EXPECTED += b"\x45\x45\x45\x45\x45\x45\x45\x45\x30\x32"
     actual = nodes.get_full_table_byte()
     self.assertEqual(EXPECTED, actual)
 def test_get_full_table(self):
     nodes = Nodes()
     TABLES = [{"BBBBBBBB": {"BBBBBBBB": 1,
                             "CCCCCCCC": 4,
                             "DDDDDDDD": 2,
                             "EEEEEEEE": 3}},
               {"CCCCCCCC": {"BBBBBBBB": 4,
                             "CCCCCCCC": 1,
                             "DDDDDDDD": 3,
                             "EEEEEEEE": 2}}]
     nodes.tables.extend(TABLES)
     EXPECTED = {"BBBBBBBB": 1,
                 "CCCCCCCC": 1,
                 "DDDDDDDD": 2,
                 "EEEEEEEE": 2}
     actual = nodes.get_full_table()
     self.assertEqual(EXPECTED, actual)
Example #16
0
    def start(self):
        logging.info('Start')

        self.nodes = Nodes()
        self.worker_q = queue.Queue()
        self.worker = threading.Thread(target=node_worker,
                                       args=(self, self._addr, 'slave',
                                             self.worker_q))
        self.worker.daemon = True

        self._syncObjConf = SyncObjConf(
            onReady=lambda: self._onReady(),
            onStateChanged=lambda os, ns: self._stateChanged(os, ns))
        self._syncObj = SyncObj(
            f'{self._addr}:{self._raft_port}',
            [f'{p}:{self._raft_port}' for p in self._peers],
            consumers=[self.logs, self.nodes],
            conf=self._syncObjConf)
Example #17
0
def parse(filename):
    """
    Parse a OSM file
    """
    with open(filename, "rb") as osm:
        # Find element
        # http://stackoverflow.com/questions/222375/elementtree-xpath-select-element-based-on-attribute
        tree = ET.parse(osm)

        nodes_tree = tree.findall(".//node")
        ways_tree = tree.findall(".//way")
        bounds_elem = tree.find(".//bounds")
        bounds = [bounds_elem.get("minlat"), bounds_elem.get("minlon"), bounds_elem.get("maxlat"), bounds_elem.get("maxlon")]

    # Parse nodes and ways. Only read the ways that have the tags specified in valid_highways
    streets = Streets()
    street_nodes = Nodes()
    street_network = OSM(street_nodes, streets, bounds)
    for node in nodes_tree:
        mynode = Node(node.get("id"), node.get("lat"), node.get("lon"))
        street_network.add_node(mynode)

    valid_highways = {'primary', 'secondary', 'tertiary', 'residential'}
    for way in ways_tree:
        highway_tag = way.find(".//tag[@k='highway']")
        oneway_tag = way.find(".//tag[@k='oneway']")
        ref_tag = way.find(".//tag[@k='ref']")
        if highway_tag is not None and highway_tag.get("v") in valid_highways:
            node_elements = filter(lambda elem: elem.tag == "nd", list(way))
            nids = [node.get("ref") for node in node_elements]

            # Sort the nodes by longitude.
            if street_nodes.get(nids[0]).lng > street_nodes.get(nids[-1]).lng:
                nids = nids[::-1]

            street = Street(way.get("id"), nids)
            if oneway_tag is not None:
                street.set_oneway_tag('yes')
            else:
                street.set_oneway_tag('no')
            street.set_ref_tag(ref_tag)
            street_network.add_way(street)

    return street_network
Example #18
0
 def __init__(self, graph, subnodes):
     # TODO Can we replace nbunch_iter with set(subnodes) & set(graph)?
     #      We lose the Error messages...
     self._subnodes = set(self._nbunch_iter(graph, subnodes))
     self._nodedata = SubNbrDict(self._subnodes, graph._nodedata)
     self._adjacency = SubAdjacency(self._subnodes, graph._adjacency)
     self.data = graph.data
     self.n = Nodes(self._nodedata, self._adjacency)
     self.e = Edges(self._nodedata, self._adjacency)
     self.a = self._adjacency
Example #19
0
def init_nodes(locations):
    nodes = []
    for i in range(lnt):
        nodes.append(Nodes(locations[i][0], locations[i][1], i, lnt))
    for i in range(lnt):
        current_node = nodes[i]
        print("node", str(i), "'s distance sort started")
        for j in range(lnt):
            dst_sqr_x = (current_node.x - nodes[j].x) * (current_node.x -
                                                         nodes[j].x)
            dst_sqr_y = (current_node.y - nodes[j].y) * (current_node.y -
                                                         nodes[j].y)
            dst = sqrt(dst_sqr_x + dst_sqr_y)
            nodes[i].fill_distance(int(round(dst)), j)
    return nodes
Example #20
0
    def __init__(self, system_settings, websocket, snmp_websocket, **kwargs):
        super(SleepyMeshBase, self).__init__(**kwargs)

        if 'last_syncs' not in self._defaults:
            self._defaults.update({'last_syncs': list()})

        # Internal Members #
        self._mesh_awake = True
        self._sync_type = 'timeout'

        self._save_in_progress = False

        self._sync_average = None
        self._delay_average = None

        # Instances #
        # TODO: Eliminate as many dependencies as possible
        self.system_settings = system_settings
        self.websocket = websocket
        self.snmp_websocket = snmp_websocket

        self.modbus_server = ModbusServer()
        self.snmp_server = SNMPTrapServer(self)
        self.update_interfaces = UpdateInterfaces(self)
        self.update_in_progress = self.update_interfaces.update_in_progress

        self.bridge = Bridge(self.system_settings)
        self.uploader = Uploader(self)

        self.nodes = Nodes(self.system_settings)
        self.platforms = Platforms(self.nodes)
        self.networks = Networks(self)

        self.error = BaseError(self.system_settings)

        if self.system_settings.modbus_enable:
            system_settings_dict = self.system_settings.attr_dict()
            # LOGGER.debug('Modbus Attribute Dictionary: ' + str(system_settings_dict))
            self.modbus_server.start(system_settings_dict)

        if self.system_settings.snmp_enable:
            self.snmp_server.start()

            # Overload Node Error Methods (SNMP Error Methods)#
            NodeError.send_snmp = self.snmp_server.send_snmp
            NodeError.clear_snmp = self.snmp_server.clear_snmp
Example #21
0
    def __init__(self, parent=None, _rule=None):
        super(RulesEditorDialog, self).__init__(parent)
        QtWidgets.QDialog.__init__(self, parent,
                                   QtCore.Qt.WindowStaysOnTopHint)

        self._notifications_sent = {}
        self._nodes = Nodes.instance()
        self._db = Database.instance()
        self._notification_callback.connect(self._cb_notification_callback)
        self._old_rule_name = None

        self.setupUi(self)

        self.buttonBox.button(
            QtWidgets.QDialogButtonBox.Reset).clicked.connect(
                self._cb_reset_clicked)
        self.buttonBox.button(
            QtWidgets.QDialogButtonBox.Close).clicked.connect(
                self._cb_close_clicked)
        self.buttonBox.button(
            QtWidgets.QDialogButtonBox.Apply).clicked.connect(
                self._cb_apply_clicked)
        self.buttonBox.button(QtWidgets.QDialogButtonBox.Help).clicked.connect(
            self._cb_help_clicked)
        self.selectListButton.clicked.connect(
            self._cb_select_list_button_clicked)
        self.protoCheck.toggled.connect(self._cb_proto_check_toggled)
        self.procCheck.toggled.connect(self._cb_proc_check_toggled)
        self.cmdlineCheck.toggled.connect(self._cb_cmdline_check_toggled)
        self.dstPortCheck.toggled.connect(self._cb_dstport_check_toggled)
        self.uidCheck.toggled.connect(self._cb_uid_check_toggled)
        self.dstIPCheck.toggled.connect(self._cb_dstip_check_toggled)
        self.dstHostCheck.toggled.connect(self._cb_dsthost_check_toggled)
        self.dstListsCheck.toggled.connect(self._cb_dstlists_check_toggled)

        if QtGui.QIcon.hasThemeIcon("emblem-default") == False:
            self.actionAllowRadio.setIcon(self.style().standardIcon(
                getattr(QtWidgets.QStyle, "SP_DialogApplyButton")))
            self.actionDenyRadio.setIcon(self.style().standardIcon(
                getattr(QtWidgets.QStyle, "SP_DialogCancelButton")))

        if _rule != None:
            self._load_rule(rule=_rule)
Example #22
0
    def __init__(self, app, on_exit):
        super(UIService, self).__init__()

        self._cfg = Config.init()
        self._db = Database.instance()
        self._db.initialize(
            dbfile=self._cfg.getSettings(self._cfg.DEFAULT_DB_FILE_KEY)
        )
        self._db_sqlite = self._db.get_db()
        self._last_ping = None
        self._version_warning_shown = False
        self._asking = False
        self._connected = False
        self._path = os.path.abspath(os.path.dirname(__file__))
        self._app = app
        self._on_exit = on_exit
        self._exit = False
        self._msg = QtWidgets.QMessageBox()
        self._prompt_dialog = PromptDialog()
        self._stats_dialog = StatsDialog(dbname="general", db=self._db)
        self._remote_lock = Lock()
        self._remote_stats = {}

        self._setup_interfaces()
        self._setup_slots()
        self._setup_icons()
        self._setup_tray()

        self.check_thread = Thread(target=self._async_worker)
        self.check_thread.daemon = True
        self.check_thread.start()

        self._nodes = Nodes.instance()

        self._last_stats = {}
        self._last_items = {
                'hosts':{},
                'procs':{},
                'addrs':{},
                'ports':{},
                'users':{}
                }
Example #23
0
    def __init__(self, parent=None):
        super(ProcessDetailsDialog, self).__init__(parent)
        QtWidgets.QDialog.__init__(self, parent,
                                   QtCore.Qt.WindowStaysOnTopHint)
        self.setWindowFlags(QtCore.Qt.Window)
        self.setupUi(self)

        self._app_name = None
        self._app_icon = None
        self._apps_parser = LinuxDesktopParser()
        self._nodes = Nodes.instance()
        self._notification_callback.connect(self._cb_notification_callback)

        self._nid = None
        self._pid = ""
        self._notifications_sent = {}

        self.cmdClose.clicked.connect(self._cb_close_clicked)
        self.cmdAction.clicked.connect(self._cb_action_clicked)
        self.comboPids.currentIndexChanged.connect(self._cb_combo_pids_changed)

        self.TABS[self.TAB_STATUS]['text'] = self.textStatus
        self.TABS[self.TAB_DESCRIPTORS]['text'] = self.textOpenedFiles
        self.TABS[self.TAB_IOSTATS]['text'] = self.textIOStats
        self.TABS[self.TAB_MAPS]['text'] = self.textMappedFiles
        self.TABS[self.TAB_STACK]['text'] = self.textStack
        self.TABS[self.TAB_ENVS]['text'] = self.textEnv

        self.TABS[self.TAB_DESCRIPTORS]['text'].setFont(
            QtGui.QFont("monospace"))

        self.iconStart = QtGui.QIcon.fromTheme("media-playback-start")
        self.iconPause = QtGui.QIcon.fromTheme("media-playback-pause")

        if QtGui.QIcon.hasThemeIcon("window-close") == False:
            self.cmdClose.setIcon(self.style().standardIcon(
                getattr(QtWidgets.QStyle, "SP_DialogCloseButton")))
            self.iconStart = self.style().standardIcon(
                getattr(QtWidgets.QStyle, "SP_MediaPlay"))
            self.iconPause = self.style().standardIcon(
                getattr(QtWidgets.QStyle, "SP_MediaPause"))
Example #24
0
def make_sidewalks(street_network):
    # Go through each street and create sidewalks on both sides of the road.
    sidewalks = Sidewalks()
    sidewalk_nodes = Nodes()
    sidewalk_network = OSM(sidewalk_nodes, sidewalks, street_network.bounds)

    for street in street_network.ways.get_list():
        sidewalk_1_nodes = []
        sidewalk_2_nodes = []

        # Create sidewalk nodes
        for prev_nid, curr_nid, next_nid in window(street.nids, 3, padding=1):
            curr_node = street_network.nodes.get(curr_nid)
            prev_node = street_network.nodes.get(prev_nid)
            next_node = street_network.nodes.get(next_nid)

            n1, n2 = make_sidewalk_nodes(street, prev_node, curr_node, next_node)

            sidewalk_network.add_node(n1)
            sidewalk_network.add_node(n2)

            sidewalk_1_nodes.append(n1)
            sidewalk_2_nodes.append(n2)

        # Keep track of parent-child relationship between streets and sidewalks.
        # And set nodes' adjacency information
        sidewalk_1_nids = [node.id for node in sidewalk_1_nodes]
        sidewalk_2_nids = [node.id for node in sidewalk_2_nodes]
        sidewalk_1 = Sidewalk(None, sidewalk_1_nids, "footway")
        sidewalk_2 = Sidewalk(None, sidewalk_2_nids, "footway")
        sidewalk_1.set_street_id(street.id)
        sidewalk_2.set_street_id(street.id)
        street.append_sidewalk_id(sidewalk_1.id)
        street.append_sidewalk_id(sidewalk_2.id)

        # Add sidewalks to the network
        sidewalk_network.add_way(sidewalk_1)
        sidewalk_network.add_way(sidewalk_2)

    return sidewalk_network
class Machine(Base):
    '''
    The machine connects the nodes and manages the addition
    and removal of nodes to the network.
    '''
    def __init__(self, name=None):
        self.log_color = 'red'
        self.name = name or random_string(8)
        self.events = Events()
        events.e = self.events
        self.nodes = Nodes()
        self.register = Register(machine=self, events=self.events)

    def set_listeners(self):
        '''
        provide machine event listeners
        '''
        self.events.listen('add_conditions')


    def activate_node(self, node):
        _n = node.integrate(self)
        self.nodes.append(_n)
        self.log('Integrating node', _n)

        '''
        Loop an iterable to add Conditiond into the
        network for a node
        '''

        # Write node into register.
        # n=node.get_name()

        # add weak reference in register.
        self.register.add_node(_n)
        _n.react(self)
        return _n


    def render_nodes(self, nodes):
        self.log('Add nodes to network')

        for node in nodes:
            n = node
            # Create the node is the element is not an instance
            if inspect.isclass(node):
                n = node()
            self.activate_node(n)

    def start(self, nodes=None):
        if nodes is not None:
            self.render_nodes(nodes)
        print '\n--- Run ---\n'
        self.started(nodes)

    def started(self, nodes):
        '''
        Override for easy start reference. Passed are the initial
        nodes provides to the machine.
        '''
        pass


    def __str__(self):
        return '%s "%s"' % (self.__class__.__name__, self.name, )
Example #26
0
from nodes import Nodes
import numpy as np
import time

# mapper_dict = {0: 1,
#                1: 2}

# callibration_dict = {0: 0.05,
#                      1: 0.042}

active_robots = ['3803', '3735']

nodes = Nodes(active_robots)

nodes.callibrate()
nodes.pendle_experiment()

# for tag in nodes.nodes:
#     # tag = 1
#     # print(nodes.nodes[tag].orien)
#     # start_pose = nodes.nodes[tag].pose
#     # start_time = nodes.nodes[tag].odomMsg_time
#     # nodes.nodes[tag].publish_greenLed(np.array([30]))
#     # nodes.nodes[tag].publish_motor_vlt(np.array([10, 10]))
#     # time.sleep(2)
#     # end_pose = nodes.nodes[tag].pose
#     # end_time = nodes.nodes[tag].odomMsg_time
#     # nodes.nodes[tag].publish_motor_vlt()
#     # nodes.nodes[tag].publish_greenLed()
#     # print(nodes.nodes[tag].orien)
#
Example #27
0
class DHTClient(threading.Thread):
    def __init__(self, max_node_qsize):
        threading.Thread.__init__(self)
        self.setDaemon(True)
        self.max_node_qsize = max_node_qsize
        self.nid = random_id()
        self.nodes = Nodes(self.nid)

    def send_krpc(self, msg, address):
        try:
            self.ufd.sendto(bencode(msg), address)
        except Exception as msg:
            print("DHTClient.send_krpc error: ", msg)

    def send_find_node(self, address, target_id=random_id()):
        nid = self.nid
        tid = entropy(TID_LENGTH)
        target_id = nid
        msg = {
            't': tid,
            'y': 'q',
            'q': 'find_node',
            'a': {
                'id': nid,
                'target': target_id
            }
        }
        self.send_krpc(msg, address)

    def auto_send_find_node(self):
        while True:
            try:
                if self.nodes.mutex.acquire(1):
                    for bucket in self.nodes.buckets:
                        for node in bucket:
                            self.send_find_node((node.ip, node.port))
                    self.nodes.mutex.release()
            except Exception as msg:
                if DEBUG: print("re_join_find_node: ", msg)
            time.sleep(0.1)

    def join_DHT(self):
        for address in BOOTSTRAP_NODES:
            self.send_find_node(address)

    def send_ping(self, address, nid):
        tid = entropy(TID_LENGTH)
        msg = {
            't': tid,
            'y': 'q',
            'q': 'ping',
            'a': {
                'id': self.nid,
            }
        } 
        self.send_krpc(msg, address)


    def process_find_node_response(self, msg, address): 
        nodes = decode_nodes(msg['r']['nodes'])
        for node in nodes:
            (nid, ip, port) = node
            if len(nid) != 20: continue
            if ip == self.bind_ip: continue
            n = KNode(nid, ip, port)
            self.nodes.store(n)
Example #28
0
 def __init__(self, max_node_qsize):
     threading.Thread.__init__(self)
     self.setDaemon(True)
     self.max_node_qsize = max_node_qsize
     self.nid = random_id()
     self.nodes = Nodes(self.nid)
Example #29
0
def NavigationActionSampling(parent, dt, traj_duration, agentID, v, sm,
                             p1_goal, p2_goal, ang_num, sp_num, num_obs):
    t = np.dot(range(0, int(traj_duration / dt)), dt)
    ang_del = 37.5 / 360 * np.pi
    sp_del = 0.4

    count = 0
    act_num = (2 * ang_num + 1) * (2 * sp_num + 1)
    Actions = []

    dv_ = np.dot(range(-sp_num, sp_num + 1), sp_del)
    ang_accel_ = np.dot(range(-ang_num, ang_num + 1), ang_del)
    dv_mesh, ang_mesh = np.meshgrid(dv_, ang_accel_)
    dv_sampled = dv_mesh.reshape(1, len(dv_) * len(ang_accel_))
    ang_sampled = ang_mesh.reshape(1, len(dv_) * len(ang_accel_))

    #plt.cla()
    #plt.axis('equal')

    #plt.grid(True)
    #plt.autoscale(False)

    #print 'len(dv_), len(ang_accel_) = {},{}'.format(len(dv_),len(ang_accel_))
    for i in range(len(dv_) * len(ang_accel_)):
        action = Nodes(parent, parent.end_time,
                       parent.end_time + traj_duration, [], [], [],
                       parent.theta_new)
        dv = dv_sampled[0][i]
        #print 'dv = {}'.format(dv)
        ang_accel = ang_sampled[0][i]
        count = count + 1
        #initialization
        if (agentID == 1):
            init_x_ped = parent.x_ped[0]
            init_y_ped = parent.x_ped[1]
            pos = [init_x_ped, init_y_ped, 0, 0]
            vx_ind = 2
            vy_ind = 3
            #vTravellerx = pos[2]
            #vTravellery = pos[3]
            vTx = p1_goal[0][0] - pos[0]
            vTy = p1_goal[0][1] - pos[1]
            vTx = parent.x_ped[2]
            vTy = parent.x_ped[3]
        else:
            init_x_rob = parent.x_rob[0]
            init_y_rob = parent.x_rob[1]
            pos = [init_x_rob, init_y_rob, 0, 0]
            vx_ind = 5
            vy_ind = 6
            #vTravellerx = pos[5]
            #vTravellery = pos[6]
            vTx = p2_goal[0][0] - pos[0]
            vTy = p2_goal[0][1] - pos[1]
            vTx = parent.x_rob[2]
            vTy = parent.x_rob[3]

        #print 'x_rob = {},{}'.format(parent.x_rob[2],parent.x_rob[3])
        vTx_ = vTx / np.sqrt(vTx**2 + vTy**2) * (v + dv)
        vTy_ = vTy / np.sqrt(vTx**2 + vTy**2) * (v + dv)
        trajx = []
        #trajx.append(pos[0])
        trajy = []
        #trajy.append(pos[1])
        velx = np.dot(vTx_, np.cos(np.dot(t, ang_accel))) + np.dot(
            vTy_, np.sin(np.dot(t, ang_accel)))
        vely = -np.dot(vTx_, np.sin(np.dot(t, ang_accel))) + np.dot(
            vTy_, np.cos(np.dot(t, ang_accel)))

        for j in range(0, len(t)):
            pos[0] = pos[0] + velx[j] * dt
            pos[1] = pos[1] + vely[j] * dt
            trajx.append(pos[0])
            trajy.append(pos[1])

            #plt.plot(pos[0],pos[1],'ok')

        time = np.add(t, parent.end_time)
        action.trajt = time

        if dv < 0:
            action.intent = 1
        else:
            action.intent = 0

        if agentID == 1:
            action.human_trajx = trajx
            action.human_trajy = trajy
            action.human_velx = velx
            action.human_vely = vely
            x_ped_ = []
            x_ped_.append(pos[0])
            x_ped_.append(pos[1])
            x_ped_.append(velx[-1])
            x_ped_.append(vely[-1])
            action.x_ped = x_ped_
        else:
            action.robot_trajx = trajx
            action.robot_trajy = trajy
            action.robot_velx = velx
            action.robot_vely = vely
            action.robot_angz = [ang_accel for k in range(len(t))]
            x_rob_ = []
            x_rob_.append(pos[0])
            x_rob_.append(pos[1])
            x_rob_.append(velx[-1])
            x_rob_.append(vely[-1])
            action.x_rob = x_rob_

        Actions.append(action)

    Actions_ = []

    for i in range(max(num_obs, 1)):
        Actions_.append(Actions)
    #print 'Actions_[0][0].rob_pos = {}'

    plt.pause(0.01)
    return Actions_
Example #30
0
class Graph(object):
    def __init__(self, data=None, **attr):
        # the init could be
        # graph = Graph(g) where g is a Graph
        # graph = Graph((v,e)) where v is Graph.v like and e is Graph.e like
        # graph = Graph(({},e)) for an edgelist with no specified nodes
        # others with classmethods like
        # Graph.from_adjacency_matrix(m)
        # Graph.from_adjacency_list(l)
        #
        # should abstract the data here
        self._nodedata = {}  # empty node attribute dict
        self._adjacency = {}  # empty adjacency dict
        # the interface is n,e,a,data
        self.n = Nodes(self._nodedata, self._adjacency) # rename to self.nodes
        self.e = Edges(self._nodedata, self._adjacency) # rename to self.edges
        self.a = Adjacency(self._adjacency) # rename to self.adjacency
        self.data = {}   # dictionary for graph attributes
        # load with data
        if hasattr(data,'n') and not hasattr(data,'name'): # it is a new graph
            self.n.update(data.n)
            self.e.update(data.e)
            self.data.update(data.data)
            data = None
        try:
            nodes,edges = data # containers of edges and nodes
            self.n.update(nodes)
            self.e.update(edges)
        except: # old style
            if data is not None:
                convert.to_networkx_graph(data, create_using=self)
        # load __init__ graph attribute keywords
        self.data.update(attr)


    def s(self, nbunch):
        H = Subgraph(self, nbunch)
        return H

    # crazy use of call - get subgraph?
    def __call__(self, nbunch):
        return self.s(nbunch)

    # rewrite these in terms of new interface
    def __iter__(self):
        return iter(self.n)

    def __len__(self):
        return len(self.n)

    def clear(self):
        self.name = ''
        self.n.clear()
        self.e.clear()
        self.data.clear()

    def copy(self, with_data=True):
        if with_data:
            return deepcopy(self)
        G = self.__class__()
        G.n.update(self.n)
        G.e.update(self.e)
        return G

    def is_multigraph(self):
        """Return True if graph is a multigraph, False otherwise."""
        return False

    def is_directed(self):
        """Return True if graph is directed, False otherwise."""
        return False

    def order(self):
        return len(self.n)

    def size(self, weight=None):
        s = sum(d for v, d in self.n.degree(weight=weight))
        # If `weight` is None, the sum of the degrees is guaranteed to be
        # even, so we can perform integer division and hence return an
        # integer. Otherwise, the sum of the weighted degrees is not
        # guaranteed to be an integer, so we perform "real" division.
        return s // 2 if weight is None else s / 2

    @classmethod
    def from_adjacency_matrix(self, matrix):
        import numpy as np
        kind_to_python_type={'f':float,
                             'i':int,
                             'u':int,
                             'b':bool,
                             'c':complex,
                             'S':str,
                             'V':'void'}
        try: # Python 3.x
            blurb = chr(1245) # just to trigger the exception
            kind_to_python_type['U']=str
        except ValueError: # Python 2.6+
            kind_to_python_type['U']=unicode
        n,m=matrix.shape
        if n!=m:
            raise nx.NetworkXError("Adjacency matrix is not square.",
                               "nx,ny=%s"%(matrix.shape,))
        dt=matrix.dtype
        try:
            python_type=kind_to_python_type[dt.kind]
        except:
            raise TypeError("Unknown numpy data type: %s"%dt)

        # Make sure we get even the isolated nodes of the graph.
        nodes = range(n)
        # Get a list of all the entries in the matrix with nonzero entries. These
        # coordinates will become the edges in the graph.
        edges = zip(*(np.asarray(matrix).nonzero()))
        # handle numpy constructed data type
        if python_type is 'void':
        # Sort the fields by their offset, then by dtype, then by name.
            fields = sorted((offset, dtype, name) for name, (dtype, offset) in
                            matrix.dtype.fields.items())
            triples = ((u, v, {name: kind_to_python_type[dtype.kind](val)
                               for (_, dtype, name), val in zip(fields, matrix[u, v])})
                       for u, v in edges)
        else:  # basic data type
            triples = ((u, v, dict(weight=python_type(matrix[u, v])))
                       for u, v in edges)
        graph = self((nodes, triples))
        return graph

    @classmethod
    def from_adjacency_list(self, adjlist):
        nodes = range(len(adjlist))
        edges = [(node,n) for node,nbrlist in enumerate(adjlist) for n in nbrlist]
        return self((nodes,edges))
Example #31
0
ndtags = ['23', '21']
count = 0
for ndvote in ndvotes:
    count += int(ndvote['type'])

input = {
    'nodeDisplay': 'TestNode4',
    'nodeDescription': 'Third node for Nodes Class',
    'nodeTags': ndtags,
    'nodeParents': ndparents,
    'nodeChildren': ndchildren,
    'nodeVotes': ndvotes,
    'nodeStatus': count
}
"""
client = Nodes()
# client.create(**input)

# node = client.retrieveById('0cd16aed4e20f18b')
# for ent in node:
#    print ent, ': ', node[ent]
'''
list = client.retrieveAll()
for node in list:
    for ent in node:
        print ent, ': ', node[ent]
    print
'''
'''
update_input = {
    '_id': '0cd16aed4e20f18b',
Example #32
0
 def nodes(s):
     return Nodes(s.__maas, uri=u'/tags/%s/' % s.name, op='nodes')
Example #33
0
 def nodes_allocated(s):
     return Nodes(s, op='list_allocated')
Example #34
0
 def nodes(s):
     return Nodes(s)
Example #35
0
display_width = 800
display_height = 600

gameDisplay = pygame.display.set_mode((display_width, display_height))
pygame.display.set_caption('Visual Path Finder')

black = (40, 40, 40)
white = (255, 255, 255)
shadow = (192, 192, 192)
green = (0, 200, 0)
red = (255, 0, 0)
blue = (0, 220, 255)
yellow = (255, 255, 125)

Nodes.create_nodes()

clock = pygame.time.Clock()
gameExit = False

left_Mouse = False
right_Mouse = False
old_left_Mouse = False

# Maybe I should initialize the Menu with the first menu titles and then have it going by itself?
Menu.create_menu()

while not gameExit:
    old_left_Mouse = left_Mouse

    gameDisplay.fill(shadow)
Example #36
0
 def __init__(self, nodes_file):
     self.nodes = Nodes(nodes_file=nodes_file)
     self.multi_client = MultiClient(self.nodes)
Example #37
0
from flask import Flask, jsonify, request

from blockchain import Blockchain
from consensus import Consensus
from hash import Hash
from nodes import Nodes
from proof import Proof

# Initialise a Node and generate a globally unique address
app = Flask(__name__)
node_id = str(uuid4()).replace('-', '')

blockchain = Blockchain()
proof = Proof()
nodes = Nodes()
consensus = Consensus()


@app.route('/mine', methods=['GET'])
def mine():
    '''
        Mine a new block.
    '''

    # Get the previous block and proof and find the new proof.
    previous_block = blockchain.last_block
    previous_proof = previous_block["proof"]
    new_proof = proof.proof_of_work(previous_proof)

    # Because the user is mining a block, we want to reward them with a block,
Example #38
0
class Graph(object):
    def __init__(self, data=None, **attr):
        # the init could be
        # graph = Graph(g) where g is a Graph
        # graph = Graph((v,e)) where v is Graph.v like and e is Graph.e like
        # graph = Graph(({},e)) for an edgelist with no specified nodes
        # others with classmethods like
        # Graph.from_adjacency_matrix(m)
        # Graph.from_adjacency_list(l)
        #
        # should abstract the data here
        self._nodedata = {}  # empty node attribute dict
        self._adjacency = {}  # empty adjacency dict
        # the interface is n,e,a,data
        self.n = Nodes(self._nodedata, self._adjacency)  # rename to self.nodes
        self.e = Edges(self._nodedata, self._adjacency)  # rename to self.edges
        self.a = Adjacency(self._adjacency)  # rename to self.adjacency
        self.data = {}  # dictionary for graph attributes
        # load with data
        if hasattr(data, "n") and not hasattr(data, "name"):  # it is a new graph
            self.n.update(data.n)
            self.e.update(data.e)
            self.data.update(data.data)
            data = None
        try:
            nodes, edges = data  # containers of edges and nodes
            self.n.update(nodes)
            self.e.update(edges)
        except:  # old style
            if data is not None:
                convert.to_networkx_graph(data, create_using=self)
        # load __init__ graph attribute keywords
        self.data.update(attr)

    def s(self, nbunch):
        H = Subgraph(self, nbunch)
        return H

    # crazy use of call - get subgraph?
    def __call__(self, nbunch):
        return self.s(nbunch)

    # rewrite these in terms of new interface
    def __iter__(self):
        return iter(self.n)

    def __len__(self):
        return len(self.n)

    def clear(self):
        self.name = ""
        self.n.clear()
        self.e.clear()
        self.data.clear()

    def copy(self, with_data=True):
        if with_data:
            return deepcopy(self)
        G = self.__class__()
        G.n.update(self.n)
        G.e.update(self.e)
        return G

    def is_multigraph(self):
        """Return True if graph is a multigraph, False otherwise."""
        return False

    def is_directed(self):
        """Return True if graph is directed, False otherwise."""
        return False

    def order(self):
        return len(self.n)

    def size(self, weight=None):
        s = sum(d for v, d in self.n.degree(weight=weight))
        # If `weight` is None, the sum of the degrees is guaranteed to be
        # even, so we can perform integer division and hence return an
        # integer. Otherwise, the sum of the weighted degrees is not
        # guaranteed to be an integer, so we perform "real" division.
        return s // 2 if weight is None else s / 2

    @classmethod
    def from_adjacency_matrix(self, matrix):
        import numpy as np

        kind_to_python_type = {"f": float, "i": int, "u": int, "b": bool, "c": complex, "S": str, "V": "void"}
        try:  # Python 3.x
            blurb = chr(1245)  # just to trigger the exception
            kind_to_python_type["U"] = str
        except ValueError:  # Python 2.6+
            kind_to_python_type["U"] = unicode
        n, m = matrix.shape
        if n != m:
            raise nx.NetworkXError("Adjacency matrix is not square.", "nx,ny=%s" % (matrix.shape,))
        dt = matrix.dtype
        try:
            python_type = kind_to_python_type[dt.kind]
        except:
            raise TypeError("Unknown numpy data type: %s" % dt)

        # Make sure we get even the isolated nodes of the graph.
        nodes = range(n)
        # Get a list of all the entries in the matrix with nonzero entries. These
        # coordinates will become the edges in the graph.
        edges = zip(*(np.asarray(matrix).nonzero()))
        # handle numpy constructed data type
        if python_type is "void":
            # Sort the fields by their offset, then by dtype, then by name.
            fields = sorted((offset, dtype, name) for name, (dtype, offset) in matrix.dtype.fields.items())
            triples = (
                (
                    u,
                    v,
                    {name: kind_to_python_type[dtype.kind](val) for (_, dtype, name), val in zip(fields, matrix[u, v])},
                )
                for u, v in edges
            )
        else:  # basic data type
            triples = ((u, v, dict(weight=python_type(matrix[u, v]))) for u, v in edges)
        graph = self((nodes, triples))
        return graph

    @classmethod
    def from_adjacency_list(self, adjlist):
        nodes = range(len(adjlist))
        edges = [(node, n) for node, nbrlist in enumerate(adjlist) for n in nbrlist]
        return self((nodes, edges))