def init_switch_admitted_traffic(self):

        print "Computing Transfer Function for switch:", self.sw.node_id

        # Inject wildcard traffic at each ingress port of the switch's non-host ports
        for port in self.sw.non_host_port_iter():

            egress_node = self.get_egress_node(self.sw.node_id,
                                               port.port_number)
            dst_traffic_at_succ = Traffic(init_wildcard=True)
            end_to_end_modified_edges = []
            self.propagate_admitted_traffic(egress_node, dst_traffic_at_succ,
                                            None, egress_node,
                                            end_to_end_modified_edges)

        # Inject wildcard traffic at each ingress port of the switch
        for port in self.sw.host_port_iter():

            egress_node = self.get_egress_node(self.sw.node_id,
                                               port.port_number)

            dst_traffic_at_succ = Traffic(init_wildcard=True)
            dst_traffic_at_succ.set_field(
                "ethernet_destination",
                int(port.attached_host.mac_addr.replace(":", ""), 16))
            end_to_end_modified_edges = []
            self.propagate_admitted_traffic(egress_node, dst_traffic_at_succ,
                                            None, egress_node,
                                            end_to_end_modified_edges)
示例#2
0
    def init_port_graph_state(self):

        self.traffic_element = TrafficElement(init_match=self.match)
        self.traffic = Traffic()
        self.complement_traffic = Traffic()
        self.applied_traffic = None

        self.traffic.add_traffic_elements([self.traffic_element])
        self.complement_traffic.add_traffic_elements(self.traffic_element.get_complement_traffic_elements())
示例#3
0
 def getThere(self):
     if self.name1.get() != userId or self.pwd1.get() != password:
         tkinter.messagebox.showinfo(
             "Window Title",
             "Wrong Username or Password Entered.Can't Proceed Further")
     else:
         there = Traffic()
示例#4
0
    def __init__(self):
        # Internet topology
        self.generator = Generator(20, 5)
        self.generator.build_topology()
        self.generator.build_matrix()
        # self.generator_v0 = copy.deepcopy(self.generator)

        self.RLs = self.generator.Ts + self.generator.Cs + self.generator.Ms + self.generator.CPs
        # self.RLs_v0 = self.generator_v0.Ts + self.generator_v0.Cs + self.generator_v0.Ms + self.generator_v0.CPs

        self.N = 25
        self.Ns = self.generator.Ts + self.generator.Ms + self.generator.CPs + self.generator.Cs
        # self.Ns_v0 = self.generator_v0.Ts + self.generator_v0.Cs + self.generator_v0.Ms + self.generator_v0.CPs

        self.MAX = 100000
        self.ids = self.generator.ids
        # self.ids_v0 = self.generator_v0.ids

        # for each agent, add [s,a,r,s'] as element. size
        self.experience_pool = collections.defaultdict(list)
        # self.experience_pool_v0 = collections.defaultdict(list)
        self.pool_size = 10
        self.global_optimal = 0
        self.int_optimal = 0

        # TODO, define TF, Matrix, Linprog
        self.traffic = Traffic(0.5)
        self.TF = self.traffic.inject_traffic()
示例#5
0
    def init_port_graph_state(self):

        # Need port_number parsed in before this is called
        self.switch_port_graph_ingress_node = PortGraphNode(self.sw,
                                                            PortGraph.get_ingress_node_id(self.sw.node_id,
                                                                                          self.port_number),
                                                            "ingress")

        self.switch_port_graph_egress_node = PortGraphNode(self.sw,
                                                           PortGraph.get_egress_node_id(self.sw.node_id,
                                                                                        self.port_number),
                                                           "egress")

        self.network_port_graph_ingress_node = PortGraphNode(self.sw,
                                                             PortGraph.get_ingress_node_id(self.sw.node_id,
                                                                                           self.port_number),
                                                             "ingress")

        self.network_port_graph_egress_node = PortGraphNode(self.sw,
                                                            PortGraph.get_egress_node_id(self.sw.node_id,
                                                                                         self.port_number),
                                                            "egress")

        self.switch_port_graph_ingress_node.parent_obj = self
        self.switch_port_graph_egress_node.parent_obj = self
        self.network_port_graph_ingress_node.parent_obj = self
        self.network_port_graph_egress_node.parent_obj = self

        self.ingress_node_traffic = Traffic(init_wildcard=True)
        self.ingress_node_traffic.set_field("in_port", int(self.port_number))
示例#6
0
    def get_admitted_traffic_via_succ(self, node, dst, succ):
        try:
            admitted_traffic_via_succ = node.admitted_traffic[dst][succ]
        except KeyError:
            admitted_traffic_via_succ = Traffic(init_wildcard=False)

        return admitted_traffic_via_succ
示例#7
0
    def compute_edge_admitted_traffic(self, traffic_to_propagate, edge):

        pred_admitted_traffic = Traffic()

        for ed in edge.edge_data_list:

            # At succ edges, set the in_port of the admitted match for destination to wildcard
            if edge.edge_type == "outside":
                traffic_to_propagate.set_field("in_port", is_wildcard=True)
                traffic_to_propagate.clear_switch_modifications()

            # If there were modifications along the way...
            if ed.applied_modifications:
                ttp = traffic_to_propagate.get_orig_traffic(
                    ed.applied_modifications)
            else:
                ttp = traffic_to_propagate

            i = ed.edge_filter_traffic.intersect(ttp)
            i.set_enabling_edge_data(ed)

            if not i.is_empty():
                pred_admitted_traffic.union(i)

        return pred_admitted_traffic
示例#8
0
    def get_admitted_traffic(self, node, dst):

        dst_admitted_traffic = Traffic()

        if dst in node.admitted_traffic:
            for succ in node.admitted_traffic[dst]:
                dst_admitted_traffic.union(node.admitted_traffic[dst][succ])

        return dst_admitted_traffic
示例#9
0
def create_traffic(traffic, screen, ai_settings, road):
    """Create vehicles for traffic."""
    for i in range(4):
        new_car = Traffic(screen, ai_settings, road)
        traffic.add(new_car)
    shuffle(list(traffic))
    for num, car in enumerate(traffic):
        car.rect.x = road.rect.left + randint(
            35, 40) + (car.rect.width + randint(45, 55)) * num
    set_y_pos(traffic, road)
示例#10
0
 def __init__(self, init_n_ego_dict, logdir):
     self.init_n_ego_dict = init_n_ego_dict
     self.multiego = MultiEgo(copy.deepcopy(self.init_n_ego_dict))
     self.traffic = Traffic(100, 'display', self.init_n_ego_dict)
     self.n_ego_traj_trans = {}
     plt.ion()
     self.fig = plt.figure(figsize=(8, 8))
     self.hist_posi = {egoID: [] for egoID in self.init_n_ego_dict.keys()}
     self.episode_counter = -1
     self.step_counter = -1
     self.logdir = logdir
     self.reset()
    def update_admitted_traffic_due_to_port_state_change(
            self, port_num, event_type):

        end_to_end_modified_edges = []

        egress_node = self.get_egress_node(self.sw.node_id, port_num)

        # This will keep track of all the edges due to flow tables that were modified due to port event
        # This assumes that ports are always successors on these edges.
        all_modified_flow_table_edges = []

        # First the egress node causes bunch of changes
        for pred in self.predecessors_iter(egress_node):

            edge = self.get_edge(pred, egress_node)
            flow_table = pred.parent_obj

            # First get the modified edges in this flow_table (edges added/deleted/modified)
            modified_flow_table_edges = flow_table.update_port_graph_edges()

            self.modify_flow_table_edges(flow_table, modified_flow_table_edges)

            self.update_admitted_traffic(modified_flow_table_edges,
                                         end_to_end_modified_edges)

            all_modified_flow_table_edges.extend(modified_flow_table_edges)

        # Take care of the ingress node which holds the traffic that can get from here to others nodes
        ingress_node = self.get_ingress_node(self.sw.node_id, port_num)
        ingress_node_succ = self.sw.flow_tables[0].port_graph_node
        ingress_node_succ_edge = self.get_edge(ingress_node, ingress_node_succ)

        for other_port in self.sw.ports:

            dst = self.get_egress_node(self.sw.node_id, other_port)

            dst_traffic_at_succ = Traffic()
            if event_type == "port_down":
                pass
            elif event_type == "port_up":
                dst_traffic_at_succ = self.get_admitted_traffic(
                    ingress_node_succ, dst)
            else:
                raise Exception("Unknown event")

            ingress_node_traffic = self.compute_edge_admitted_traffic(
                dst_traffic_at_succ, ingress_node_succ_edge)
            self.propagate_admitted_traffic(ingress_node, ingress_node_traffic,
                                            ingress_node_succ, dst,
                                            end_to_end_modified_edges)

        return end_to_end_modified_edges
示例#12
0
    def __init__(
            self,
            training_task,  # 'left', 'straight', 'right'
            num_future_data=0,
            display=False,
            **kwargs):
        metadata = {'render.modes': ['human']}
        self.dynamics = VehicleDynamics()
        self.interested_vehs = None
        self.training_task = training_task
        self.ref_path = ReferencePath(self.training_task, **kwargs)
        self.detected_vehicles = None
        self.all_vehicles = None
        self.ego_dynamics = None
        self.num_future_data = num_future_data
        self.env_model = EnvironmentModel(training_task, num_future_data)
        self.init_state = {}
        self.action_number = 2
        self.exp_v = EXPECTED_V  #TODO: temp
        self.ego_l, self.ego_w = L, W
        self.action_space = gym.spaces.Box(low=-1,
                                           high=1,
                                           shape=(self.action_number, ),
                                           dtype=np.float32)

        self.seed()
        self.v_light = None
        self.step_length = 100  # ms

        self.step_time = self.step_length / 1000.0
        self.init_state = self._reset_init_state()
        self.obs = None
        self.action = None
        self.veh_mode_dict = VEHICLE_MODE_DICT[self.training_task]
        self.veh_num = VEH_NUM[self.training_task]
        self.virtual_red_light_vehicle = False

        self.done_type = 'not_done_yet'
        self.reward_info = None
        self.ego_info_dim = None
        self.per_tracking_info_dim = None
        self.per_veh_info_dim = None
        if not display:
            self.traffic = Traffic(self.step_length,
                                   mode='training',
                                   init_n_ego_dict=self.init_state,
                                   training_task=self.training_task)
            self.reset()
            action = self.action_space.sample()
            observation, _reward, done, _info = self.step(action)
            self._set_observation_space(observation)
            plt.ion()
示例#13
0
    def get_edge_from_admitted_traffic(self,
                                       pred,
                                       succ,
                                       admitted_traffic,
                                       edge_sw=None,
                                       exclude_inactive=False):

        edge = PortGraphEdge(pred, succ)

        # If the edge filter became empty, reflect that.
        if admitted_traffic.is_empty():
            pass
        else:
            # Each traffic element has its own edge_data, because of how it might have
            # traveled through the switch and what modifications it may have accumulated
            for i, te in enumerate(admitted_traffic.traffic_elements):

                t = Traffic()
                t.add_traffic_elements([te])
                traffic_paths = None

                if edge_sw:

                    # Check to see the exact path of this traffic through the switch
                    traffic_paths = edge_sw.port_graph.get_paths(
                        pred, succ, t, [pred], [], [])

                    if len(traffic_paths) == 0:
                        print "Found traffic but no paths to back it up."
                        #raise Exception("Found traffic but no paths to back it up.")
                    else:
                        # IF asked to exclude in-active...
                        # As long as there a single active path and carries the te, then we are good,
                        # otherwise, continue
                        if exclude_inactive:
                            active_path = False
                            for p in traffic_paths:
                                if p.get_max_active_rank() == 0:
                                    active_path = True
                                    break

                            if not active_path:
                                continue

                edge_data = NetworkPortGraphEdgeData(t,
                                                     te.switch_modifications,
                                                     traffic_paths)

                edge.add_edge_data(edge_data)

        return edge
示例#14
0
def main() -> None:
    """
    Main method prompting for iterations and road length for plotting the steady state
    average speed graph, and also prompting for car density to show animation of the
    particular traffic model.
    """
    road_length = float(input('Provide the length of the road: '))
    car_density = float(input('Provide the density of the cars: '))
    iterations = float(input('Provide the number of iterations: '))

    Traffic.density_graph(road_length, iterations)

    model = Traffic(road_length, car_density, iterations)
    model.visualize_traffic()
    def init_switch_port_graph(self):

        print "Initializing Port Graph for switch:", self.sw.node_id

        # Initialize switch ports' port graph state
        for port_num in self.sw.ports:

            if port_num == 1 and self.sw.node_id == "s1":
                pass

            self.sw.ports[port_num].init_port_graph_state()

        # Initialize port graph state per table and add its node to switch port graph
        for flow_table in self.sw.flow_tables:
            flow_table.init_port_graph_state()
            self.add_node(flow_table.port_graph_node)

        # Add two nodes per physical port in port graph one for incoming and outgoing direction
        # Connect incoming direction port to table 0's port
        for port_num in self.sw.ports:

            port = self.sw.ports[port_num]

            self.add_node(port.switch_port_graph_ingress_node)
            self.add_node(port.switch_port_graph_egress_node)

            self.boundary_ingress_nodes.append(
                port.switch_port_graph_ingress_node)
            self.boundary_egress_nodes.append(
                port.switch_port_graph_egress_node)

            edge = PortGraphEdge(port.switch_port_graph_ingress_node,
                                 self.sw.flow_tables[0].port_graph_node)
            edge_traffic_filter = Traffic()
            edge_traffic_filter.union(port.ingress_node_traffic)
            edge_data = SwitchPortGraphEdgeData(edge_traffic_filter, None,
                                                None, None)
            edge.add_edge_data(edge_data)
            self.add_edge(port.switch_port_graph_ingress_node,
                          self.sw.flow_tables[0].port_graph_node, edge)

        # Try passing a wildcard through the flow table
        for flow_table in self.sw.flow_tables:
            flow_table.compute_flow_table_port_graph_edges()
            self.add_flow_table_edges(flow_table)

        # Initialize all groups' active buckets
        for group_id in self.sw.group_table.groups:
            self.sw.group_table.groups[group_id].set_active_bucket()
示例#16
0
    def init_network_admitted_traffic_for_sw(self, sw):
        for non_host_port in sw.non_host_port_iter():

            # Accumulate traffic that is admitted for each host
            admitted_host_traffic = Traffic()
            for host_port in sw.host_port_iter():
                at = sw.port_graph.get_admitted_traffic(
                    non_host_port.switch_port_graph_ingress_node,
                    host_port.switch_port_graph_egress_node)
                admitted_host_traffic.union(at)

            end_to_end_modified_edges = []
            self.propagate_admitted_traffic(
                non_host_port.network_port_graph_ingress_node,
                admitted_host_traffic, None,
                non_host_port.network_port_graph_ingress_node,
                end_to_end_modified_edges)

            admitted_host_traffic.set_field("in_port",
                                            int(non_host_port.port_number))
示例#17
0
    def _get_port_graph_edges_dict(self):
        port_graph_edges = defaultdict(list)

        remaining_traffic = Traffic(init_wildcard=True)

        for flow in self.flows:

            intersection = flow.traffic.intersect(remaining_traffic)

            if not intersection.is_empty():

                # See what is left after this rule is through
                prev_remaining_traffic = remaining_traffic
                remaining_traffic = flow.complement_traffic.intersect(remaining_traffic)
                flow.applied_traffic = intersection

                flow.get_port_graph_edges(port_graph_edges)

            else:
                # Say that this flow does not matter
                flow.applied_traffic = None

        return port_graph_edges
    def compute_edge_admitted_traffic(self, traffic_to_propagate, edge):

        pred_admitted_traffic = Traffic()

        for ed in edge.edge_data_list:

            if edge.edge_type == "egress":

                # if the output_action type is applied, no written modifications take effect.
                if ed.edge_action.instruction_type == "applied":
                    traffic_to_propagate.set_written_modifications_apply(False)
                else:
                    traffic_to_propagate.set_written_modifications_apply(True)

            # Always roll-back applied modifications if the edge has any...
            if ed.applied_modifications:
                ttp = traffic_to_propagate.get_orig_traffic(
                    ed.applied_modifications)
            else:
                ttp = traffic_to_propagate

            # At ingress edges, first roll-back any accumulated written modifications
            if edge.edge_type == "ingress":
                ttp = ttp.get_orig_traffic(
                    use_embedded_written_modifications=True)

            i = ed.edge_filter_traffic.intersect(ttp)
            i.set_enabling_edge_data(ed)

            if not i.is_empty():
                # At all the non-ingress edges accumulate written modifications
                if edge.edge_type != "ingress" and ed.written_modifications:
                    i.set_written_modifications(ed.written_modifications)

                pred_admitted_traffic.union(i)

        return pred_admitted_traffic
示例#19
0
    def run(self, carID):
        """
        Executes the Traci client and the environment representation
        """
        ego = carID
        step = 0

        while traci.simulation.getTime() < 60:
            traci.simulationStep()

            fw = Framework()

            if carID in traci.vehicle.getIDList():

                ego_trajectory = fw.getTrajectory(carID)

                intersections = fw.getIntersectingTrajectories(
                    carID, ego_trajectory)

                if intersections is not None:
                    #if len(ego_trajectory) > 1:
                    framework = fw.getTensorFramework(carID, intersections,
                                                      ego_trajectory)

                    auto = Autonomous(carID, framework, ego_trajectory)

                    distances = auto.getDistanceToIntercept()

                    tfc = Traffic(distances)

                    vehicles = tfc.getConflictoryTraffic()

                    distances_tfc = tfc.getDistanceToIntercept(vehicles)

                    safe = Safety(carID, framework, distances, distances_tfc)

                    trc_safety = safe.getTrafficSafetyMeasures()
                    #print(len(distances), len(trc_safety))

                    ego_safety = safe.getEgoSafetyMeasures()
                    #print(ego_safety)

                    prio = safe.getPriotizedTraffic(ego_safety, trc_safety)

                    rel = safe.getRelevantTraffic(prio)
                    #print(rel)

                    # for i in range(len(rel)):
                    #     if rel[i][1]:
                    #         safe.getEgoSecurityDistance(carID, rel[i][1][0][0])

                    env = Tensor(carID, distances, rel, ego_safety,
                                 ego_trajectory)
                    env.createEnvironmentTensor()
                    #print(env.createEnvironmentTensor())
                else:
                    corridor = np.full((200, 3), fill_value=-1.0)

                    corridor[0:200, 2] = 100 / np.maximum(
                        traci.vehicle.getSpeed(self.carID), 0.001)

                    #print(corridor)

            step += 1
        traci.close()
        sys.stdout.flush()
示例#20
0
from db.models import Stop
from dijkstra import shortest_path
from network import Network
from parser import parse_route
from time import perf_counter
from traffic import Traffic
"""
Command-line interface for the Lakbay algorithm.

:Author:     Maded Batara III
:Version:    v3.0 (2015-04-07)
"""

print("Loading databases...")
start_load = perf_counter()
with Network("sqlite:///db/app.db") as network, Traffic(
        "sqlite:///db/traffic.db") as traffic:
    end_load = perf_counter()
    print("Databases loaded, took {0:.2} seconds".format(end_load -
                                                         start_load))

    # Query program
    print("Graph loaded.")
    print()
    src = int(input("Source: "))
    dest = int(input("Destination: "))
    print("Calculating shortest path from '{0}' to '{1}'".format(
        network.stops.filter(Stop.id == src).first().name,
        network.stops.filter(Stop.id == dest).first().name,
    ))

    start_dijk = perf_counter()
示例#21
0
    def getTensor(self):
        fw = Framework()

        if self.carID in traci.vehicle.getIDList():

            ego_trajectory = fw.getTrajectory(self.carID)

            intersections = fw.getIntersectingTrajectories(
                self.carID, ego_trajectory)

            if intersections is not None:
                #if len(ego_trajectory) > 1:
                framework = fw.getTensorFramework(self.carID, intersections,
                                                  ego_trajectory)

                auto = Autonomous(self.carID, framework, ego_trajectory)

                distances = auto.getDistanceToIntercept()

                tfc = Traffic(distances)

                vehicles = tfc.getConflictoryTraffic()

                distances_tfc = tfc.getDistanceToIntercept(vehicles)
                self.distances_tfc = distances_tfc

                safe = Safety(self.carID, framework, distances, distances_tfc)

                trc_safety = safe.getTrafficSafetyMeasures()
                # print(len(distances), len(trc_safety))

                ego_safety = safe.getEgoSafetyMeasures()
                # print(ego_safety)

                prio = safe.getPriotizedTraffic(ego_safety, trc_safety)

                rel = safe.getRelevantTraffic(prio)
                #print('\n', prio)
                #print(rel)
                self.rel = rel

                # print(rel)

                # for i in range(len(rel)):
                #     if rel[i][1]:
                #         safe.getEgoSecurityDistance(carID, rel[i][1][0][0])

                env = Tensor(self.carID, distances, rel, ego_safety,
                             ego_trajectory)
                #print(env.createEnvironmentTensor())

                return env.createEnvironmentTensor()
            else:
                corridor = np.full((200, 3), fill_value=-1.0)

                #corridor[0:199, 2] = 0
                corridor[0:200, 2] = 100 / np.maximum(
                    traci.vehicle.getSpeed(self.carID), 0.001)

                #tensor = np.reshape(corridor[0:200], 600)

                return corridor
    #network = getSingleRoadNetwork(106, 660, 106, 0, 40)  ## - US101 data set
    #print network
    numberOfTracks = 1
    numberOfPointsPerTrack = 100
    numberOfVehicles = 1000
    for i in range(0, numberOfTracks, numberOfVehicles):
        #vehicles = getVehicles(numberOfVehicles, network)
        #vehicles = getVehiclesFromFile("/Users/gramag`uru/Desktop/car_videos/output_sing_sequences_appended_double.txt", network)
        #vehicles = getVehiclesFromFile("/Users/gramaguru/Desktop/car_videos/output_sing_sequences_appended_double_nonewline.txt", network)
        #vehicles = getVehiclesFromFileReal("/Users/gramaguru/Desktop/car_videos/sing_cropped_vehicle_generated_double.txt", network)
        vehicles = getVehiclesSumoBasic(numberOfVehicles, network)
        #vehicles = getMixedVehicles(numberOfVehicles, network, 0.2)
        ## Calculate homography and send it accross for using it while printing.
        print "Traffic Start"
        #traffic = Traffic(network, vehicles, (1000,1000,3), 10000)
        #traffic = Traffic(network, vehicles, (384,512,3), 86400)  ## - Singapore video
        traffic = Traffic(network, vehicles, (660, 212, 3),
                          10000)  ## - Sumo video
    #traffic = Traffic(network, vehicles, (660,360,3), 10000)  ## - Sumo video
    #traffic = Traffic(network, vehicles, (660,60,3), 1000)  ## - US101 video

    #straight_road_points = np.array([[200, 100],[300, 100],[300, 484],[200, 484]], dtype=float);
    #straight_road_points = np.array([[100, 0],[200, 0],[200, 384],[100, 384]], dtype=float);
    #perspective_road_points = np.array([[202, 105], [240, 105], [255, 300], [0, 300]], dtype=float);
    #H, status = cv2.findHomography(straight_road_points, perspective_road_points);

    #traffic.simulateAndVisualizeWithHomography(H, straight_road_points, perspective_road_points)
    traffic.simulateAndVisualize()
    #traffic.export()
    #traffic.simulateAndExport()
示例#23
0
    def update_admitted_traffic(self, modified_edges,
                                end_to_end_modified_edges):

        # This object holds for each pred/dst combinations
        # that have changed as keys and list of succ ports as values
        admitted_traffic_changes = defaultdict(defaultdict)

        for modified_edge in modified_edges:

            pred = self.get_node(modified_edge[0])
            succ = self.get_node(modified_edge[1])

            # TODO Limit the destinations by using markers in modified_flow_table_edges
            # Right now, just take all the destinations at succ and marking them as having been modified...

            for dst in self.get_admitted_traffic_dsts(succ):
                if dst not in admitted_traffic_changes[pred]:
                    admitted_traffic_changes[pred][dst] = [succ]
                else:
                    if succ not in admitted_traffic_changes[pred][dst]:
                        admitted_traffic_changes[pred][dst].append(succ)

        # Do this for each pred port that has changed
        for pred in admitted_traffic_changes:

            # For each destination that may have been affected at the pred port
            for dst in admitted_traffic_changes[pred]:

                now_pred_traffic = Traffic()

                # Check the fate of traffic from changed successors in this loop
                for succ in admitted_traffic_changes[pred][dst]:

                    edge = self.get_edge(pred, succ)

                    succ_traffic = self.get_admitted_traffic(succ, dst)

                    # Update admitted traffic at successor node to reflect changes
                    pred_traffic_via_succ = self.compute_edge_admitted_traffic(
                        succ_traffic, edge)
                    self.set_admitted_traffic_via_succ(pred, dst, succ,
                                                       pred_traffic_via_succ)

                    # Accumulate total traffic admitted at this pred
                    now_pred_traffic.union(pred_traffic_via_succ)

                # Collect traffic from any succs that was not changed
                for succ in self.get_admitted_traffic_succs(pred, dst):
                    if succ not in admitted_traffic_changes[pred][dst]:
                        now_pred_traffic.union(
                            self.get_admitted_traffic_via_succ(
                                pred, dst, succ))

                # Propagate the net unioned traffic to all of predecessors of the predecessor itself.
                for pred_pred in self.predecessors_iter(pred):

                    edge = self.get_edge(pred_pred, pred)
                    pred_pred_traffic = self.compute_edge_admitted_traffic(
                        now_pred_traffic, edge)

                    self.propagate_admitted_traffic(pred_pred,
                                                    pred_pred_traffic, pred,
                                                    dst,
                                                    end_to_end_modified_edges)
示例#24
0
def green_light():
    trafficlight = Traffic()
    trafficlight.setStand(0)
    trafficlight.update_light()
    return 'Hello, World!'
示例#25
0
def red_light():
    trafficlight = Traffic()
    trafficlight.setStand(3)
    trafficlight.update_light()
    return 'Hello, World!'
示例#26
0
def amber_light():
    trafficlight = Traffic()
    trafficlight.setStand(1)
    trafficlight.update_light()
    return 'Hello, World!'
示例#27
0
import numpy as np
from traffic import Traffic
from random import randrange
if __name__ == "__main__":
    """
    Main method
    """
    size = int(input("size of the road: "))  #  size of the road
    if (size <= 0):
        raise ValueError("Illegal Size")
    road = np.zeros(shape=size)  #  initalizing an empty zero array
    density = float(input("density of the road: "))  #  density of the cars
    if density > 1 or density < 0:
        raise ValueError("Illegal density")
    cars = size * density  #  number of cars
    iterations = int(input("number of interations: "))  #  nubmer of iterations
    if iterations <= 0:
        raise ValueError("Illegal number of iterations")
    i = 0
    while (i < cars):
        pos = randrange(len(road))  #  getting random position in the road
        if (road[pos] == 0
            ):  #  if the positions is zero then place the car there
            road[pos] = 1
            i += 1  #  increase car numbers placed
    tr = Traffic(cars, road, iterations)  #  creating object
    tr.update()
示例#28
0
    def _create_actor(self, carla_actor):  # pylint: disable=too-many-branches,too-many-statements
        """
        create an actor
        """
        parent = None
        if carla_actor.parent:
            if carla_actor.parent.id in self.actors:
                parent = self.actors[carla_actor.parent.id]
            else:
                parent = self._create_actor(carla_actor.parent)

        actor = None
        pseudo_actors = []
        #print("typeid")
        #print(carla_actor.type_id)
        if carla_actor.type_id.startswith('traffic'):
            if carla_actor.type_id == "traffic.traffic_light":
                actor = TrafficLight(carla_actor, parent, self.comm)
            else:
                actor = Traffic(carla_actor, parent, self.comm)
        elif carla_actor.type_id.startswith("vehicle"):
            print(carla_actor.attributes.get('role_name'))
            print(carla_actor.type_id)
            print(carla_actor.id)
            if carla_actor.attributes.get('role_name')\
                    in self.parameters['ego_vehicle']['role_name']:
                actor = EgoVehicle(
                    carla_actor, parent, self.comm, self._ego_vehicle_control_applied_callback)
                pseudo_actors.append(ObjectSensor(parent=actor,
                                                  communication=self.comm,
                                                  actor_list=self.actors,
                                                  filtered_id=carla_actor.id))

            else:
                actor = Vehicle(carla_actor, parent, self.comm)
        elif carla_actor.type_id.startswith("sensor"):
            if carla_actor.type_id.startswith("sensor.camera"):
                if carla_actor.type_id.startswith("sensor.camera.rgb"):
                    actor = RgbCamera(
                        carla_actor, parent, self.comm, self.carla_settings.synchronous_mode)
                elif carla_actor.type_id.startswith("sensor.camera.depth"):
                    actor = DepthCamera(
                        carla_actor, parent, self.comm, self.carla_settings.synchronous_mode)
                elif carla_actor.type_id.startswith("sensor.camera.semantic_segmentation"):
                    actor = SemanticSegmentationCamera(
                        carla_actor, parent, self.comm, self.carla_settings.synchronous_mode)
                else:
                    actor = Camera(
                        carla_actor, parent, self.comm, self.carla_settings.synchronous_mode)
            elif carla_actor.type_id.startswith("sensor.lidar"):
                actor = Lidar(carla_actor, parent, self.comm, self.carla_settings.synchronous_mode)
            elif carla_actor.type_id.startswith("sensor.other.gnss"):
                actor = Gnss(carla_actor, parent, self.comm, self.carla_settings.synchronous_mode)
            elif carla_actor.type_id.startswith("sensor.other.collision"):
                actor = CollisionSensor(
                    carla_actor, parent, self.comm, self.carla_settings.synchronous_mode)
            elif carla_actor.type_id.startswith("sensor.other.lane_invasion"):
                actor = LaneInvasionSensor(
                    carla_actor, parent, self.comm, self.carla_settings.synchronous_mode)
            else:
                actor = Sensor(carla_actor, parent, self.comm, self.carla_settings.synchronous_mode)
        elif carla_actor.type_id.startswith("spectator"):
            actor = Spectator(carla_actor, parent, self.comm)
        elif carla_actor.type_id.startswith("walker"):
            actor = Walker(carla_actor, parent, self.comm)
        else:
            actor = Actor(carla_actor, parent, self.comm)


        with self.update_lock:
            self.actors[carla_actor.id] = actor

        for pseudo_actor in pseudo_actors:

            with self.update_lock:
                self.pseudo_actors.append(pseudo_actor)

        return actor
示例#29
0
#!/usr/bin/python3

# -- @Autora: Andrea del Nido García

import os
from traffic import Traffic

file_list = os.listdir("/home/buhohacker/Documentos/apks")
print("The list of APKs is: ")
print(file_list)
act_path = os.getcwd()

print("Script trafficAll.py is in directory " + str(act_path))

# Llamar a traffic.py con todas las apks
for file_name in file_list:
    print("The actual APK for analyze traffic is: " + file_name)
    apk = "/home/buhohacker/Documentos/apks/" + str(file_name)
    t = Traffic("192.168.1.53", "4000", "192.168.3.20", apk, "Label_PinningTest")
    print(t.configure())
    print(t.upload())
    print(t.phaseOne(25,False, False))
    print(t.phaseTwo(25, True))
    print(t.analysis())
    print(t.result())
    print(t.sanitize())
示例#30
0
define = Define(TRAFFIC_DEMAND, HOLDING_TIME, TOTAL_TRAFFIC, MAX_ROUTE,
                AVERAGE_REPAIRED_TIME, node_size, get_shape(), scale)
# print(show_links(link_list))
traffic_list = []
traffic_count = 0
second = 0

while True:
    traffic_per_second = numpy.random.poisson(TRAFFIC_DEMAND)
    traffic_list.append([])
    for num in range(0, traffic_per_second - 1):
        nodes = get_nodes_rand(node_size)
        traffic_list[second].append(
            Traffic(traffic_count, nodes[0], nodes[1],
                    round(numpy.random.exponential(HOLDING_TIME - 1)) + 1,
                    get_bandwidth_rand(), get_quality_rand()))
        traffic_count += 1
        if traffic_count == TOTAL_TRAFFIC:
            break

    second += 1
    if traffic_count >= TOTAL_TRAFFIC:
        break

print("second: %d" % second)

with open('link_list.dat', mode='wb') as f:
    pickle.dump(link_list, f)

with open('traffic_list.dat', mode='wb') as f: