def test_retrieving_single_greenyellow_interval(self):
        """ test retrieving a single greenyellow interval of a signal group """
        # GIVEN
        input_dict = TestFTSMethods.get_default_fts_inputs()
        sg1 = SignalGroup(
            id="sg1",
            traffic_lights=[TrafficLight(capacity=800, lost_time=1)],
            min_greenyellow=10,
            max_greenyellow=80,
            min_red=10,
            max_red=80)
        sg2 = SignalGroup(
            id="sg2",
            traffic_lights=[TrafficLight(capacity=800, lost_time=1)],
            min_greenyellow=10,
            max_greenyellow=80,
            min_red=10,
            max_red=80)

        # WHEN
        fts = FixedTimeSchedule(**input_dict)

        # THEN
        self.assertEqual(fts.get_greenyellow_interval(signalgroup=sg1, k=0),
                         input_dict["greenyellow_intervals"]["sg1"][0])
        self.assertEqual(fts.get_greenyellow_interval(signalgroup=sg1, k=1),
                         input_dict["greenyellow_intervals"]["sg1"][1])
        self.assertEqual(fts.get_greenyellow_interval(signalgroup=sg2, k=0),
                         input_dict["greenyellow_intervals"]["sg2"][0])
    def test_retrieving_single_interval_with_id(self):
        # GIVEN
        input_dict = TestFTSMethods.get_default_fts_inputs()
        sg1 = SignalGroup(
            id="sg1",
            traffic_lights=[TrafficLight(capacity=800, lost_time=1)],
            min_greenyellow=10,
            max_greenyellow=80,
            min_red=10,
            max_red=80)
        sg2 = SignalGroup(
            id="sg2",
            traffic_lights=[TrafficLight(capacity=800, lost_time=1)],
            min_greenyellow=10,
            max_greenyellow=80,
            min_red=10,
            max_red=80)

        # WHEN
        fts = FixedTimeSchedule(**input_dict)

        # THEN using id should give the same information
        self.assertEqual(fts.get_greenyellow_interval(signalgroup=sg1, k=0),
                         fts.get_greenyellow_interval(signalgroup=sg1.id, k=0))
        self.assertEqual(fts.get_greenyellow_interval(signalgroup=sg1, k=1),
                         fts.get_greenyellow_interval(signalgroup=sg1.id, k=1))
        self.assertEqual(fts.get_greenyellow_interval(signalgroup=sg2, k=0),
                         fts.get_greenyellow_interval(signalgroup=sg2.id, k=0))
Exemplo n.º 3
0
    def test_getting_non_existing_signal_group(self):
        """ Test retrieving signal group by id when this id does not exist """
        # GIVEN
        signalgroup1 = SignalGroup(id="sg1", traffic_lights=[TrafficLight(capacity=1800, lost_time=1)],
                                   min_greenyellow=10, max_greenyellow=80, min_red=10, max_red=80)
        signalgroup2 = SignalGroup(id="sg2", traffic_lights=[TrafficLight(capacity=1800, lost_time=1)],
                                   min_greenyellow=10, max_greenyellow=80, min_red=10, max_red=80)
        intersection = Intersection(signalgroups=[signalgroup1, signalgroup2], conflicts=[], sync_starts=[],
                                    offsets=[], greenyellow_leads=[])

        with self.assertRaises(ValueError):
            # WHEN
            intersection.get_signalgroup(signalgroup_id="sg3")
Exemplo n.º 4
0
    def test_getting_signal_group(self):
        """ Test retrieving signal group by id """
        # GIVEN
        signalgroup1 = SignalGroup(id="sg1", traffic_lights=[TrafficLight(capacity=1800, lost_time=1)],
                                   min_greenyellow=10, max_greenyellow=80, min_red=10, max_red=80)
        signalgroup2 = SignalGroup(id="sg2", traffic_lights=[TrafficLight(capacity=1800, lost_time=1)],
                                   min_greenyellow=10, max_greenyellow=80, min_red=10, max_red=80)

        intersection = Intersection(signalgroups=[signalgroup1, signalgroup2], conflicts=[], sync_starts=[],
                                    offsets=[], greenyellow_leads=[])

        # WHEN/THEN
        self.assertEqual(intersection.get_signalgroup(signalgroup_id="sg1"), signalgroup1)
        self.assertEqual(intersection.get_signalgroup(signalgroup_id="sg2"), signalgroup2)
    def test_retrieving_for_unkown_signalgroup(self):
        """ test retrieving greenyellow intervals of an unkown signal group """
        # GIVEN
        input_dict = TestFTSMethods.get_default_fts_inputs()
        # unkown signal group
        sg3 = SignalGroup(
            id="sg3",
            traffic_lights=[TrafficLight(capacity=800, lost_time=1)],
            min_greenyellow=10,
            max_greenyellow=80,
            min_red=10,
            max_red=80)

        fts = FixedTimeSchedule(**input_dict)

        with self.assertRaises(ValueError):
            # WHEN trying to access greenyellow intervals of an unkown signal group
            fts.get_greenyellow_intervals(sg3)

            # THEN an error should be raised

        # same but using id
        with self.assertRaises(ValueError):
            # WHEN trying to access greenyellow intervals of an unkown signal group
            fts.get_greenyellow_intervals(sg3.id)
Exemplo n.º 6
0
 def get_default_signalgroup(name: str, min_greenyellow: float = 10.0, max_greenyellow: float = 80.0,
                             min_red: float = 10.0, max_red: float = 80.0) -> SignalGroup:
     """ Get a default signalgroup object"""
     traffic_light = TrafficLight(capacity=0.5, lost_time=0.0)
     return SignalGroup(id=name, traffic_lights=[traffic_light],
                        min_greenyellow=min_greenyellow, max_greenyellow=max_greenyellow, min_red=min_red,
                        max_red=max_red, min_nr=1, max_nr=3)
 def _add_signalgroup(self, name: str) -> None:
     traffic_light = TrafficLight(capacity=0.5, lost_time=0.0)
     self._signal_groups.append(
         SignalGroup(id=name,
                     traffic_lights=[traffic_light],
                     min_greenyellow=2,
                     max_greenyellow=20,
                     min_red=2,
                     max_red=50,
                     min_nr=1,
                     max_nr=3))
Exemplo n.º 8
0
 def get_default_inputs() -> Dict:
     """ Function to get default (valid) inputs for Intersection() """
     signalgroups = [SignalGroup(id=f"sg{i+1}", traffic_lights=[TrafficLight(capacity=1800, lost_time=1)],
                                 min_greenyellow=10, max_greenyellow=80, min_red=10, max_red=80) for i in range(6)]
     conflicts = [Conflict(id1="sg1", id2="sg2", setup12=1, setup21=2),
                  Conflict(id1="sg1", id2="sg6", setup12=1, setup21=2),
                  Conflict(id1="sg2", id2="sg6", setup12=1, setup21=2)]
     sync_starts = [SyncStart(from_id="sg1", to_id="sg3")]
     offsets = [Offset(from_id="sg1", to_id="sg4", seconds=10)]
     periodic_orders = [PeriodicOrder(order=["sg1", "sg2", "sg6"])]
     greenyellow_leads = [GreenyellowLead(from_id="sg1", to_id="sg5", min_seconds=1, max_seconds=10)]
     greenyellow_trails = [GreenyellowTrail(from_id="sg5", to_id="sg1", min_seconds=2, max_seconds=8)]
     return dict(signalgroups=signalgroups, conflicts=conflicts, sync_starts=sync_starts,
                 offsets=offsets, greenyellow_leads=greenyellow_leads, greenyellow_trails=greenyellow_trails,
                 periodic_orders=periodic_orders)
    def test_retrieving_unkown_interval(self):
        """ test retrieving greenyellow intervals of an unkown signal group """
        # GIVEN
        input_dict = TestFTSMethods.get_default_fts_inputs()
        # unkown signal group
        sg1 = SignalGroup(
            id="sg1",
            traffic_lights=[TrafficLight(capacity=800, lost_time=1)],
            min_greenyellow=10,
            max_greenyellow=80,
            min_red=10,
            max_red=80)

        fts = FixedTimeSchedule(**input_dict)

        with self.assertRaises(ValueError):
            # WHEN trying to access greenyellow intervals of an unkown signal group
            fts.get_greenyellow_interval(
                sg1, k=2)  # has only 2 intervals (with indices k=0 and k=1)
Exemplo n.º 10
0
def create_intersection_and_optimize():
    """
    Example showing how to:
    - create traffic lights, signal groups and intersections, ...
    - optimize a fixed-time schedule for this intersection

    NOTE:
    To run the example below you need credentials to invoke the swift mobility cloud api.
    To this end, you need to specify the following environment variables:
    - smc_api_key: the access key of your swift mobility cloud api account
    - smc_api_secret: the secret access key of your swift mobility cloud api account
    If you do not have such an account yet, please contact [email protected].
    """
    logging.info(f"Running example '{os.path.basename(__file__)}'")
    # signal group consisting of two traffic light allowing 1 or 2 greenyellow intervals per repeating period.
    traffic_light1 = TrafficLight(capacity=1800, lost_time=2.2)
    traffic_light2 = TrafficLight(capacity=1810, lost_time=2.1)
    signalgroup1 = SignalGroup(id="2",
                               traffic_lights=[traffic_light1, traffic_light2],
                               min_greenyellow=10,
                               max_greenyellow=100,
                               min_red=10,
                               max_red=100,
                               min_nr=1,
                               max_nr=2)

    # signal group consisting of one traffic light allowing 1 greenyellow interval (default) per repeating period.
    traffic_light3 = TrafficLight(capacity=1650, lost_time=3.0)
    signalgroup2 = SignalGroup(id="5",
                               traffic_lights=[traffic_light3],
                               min_greenyellow=10,
                               max_greenyellow=100,
                               min_red=10,
                               max_red=100)

    # signal group consisting of one traffic light allowing 1 greenyellow interval (default) per repeating period.
    traffic_light4 = TrafficLight(capacity=1800, lost_time=2.1)
    signalgroup3 = SignalGroup(id="8",
                               traffic_lights=[traffic_light4],
                               min_greenyellow=10,
                               max_greenyellow=100,
                               min_red=10,
                               max_red=100)

    # conflicts & clearance times
    conflict12 = Conflict(id1=signalgroup1.id,
                          id2=signalgroup2.id,
                          setup12=1,
                          setup21=2)
    conflict13 = Conflict(id1=signalgroup1.id,
                          id2=signalgroup3.id,
                          setup12=1,
                          setup21=2)
    conflict23 = Conflict(id1=signalgroup2.id,
                          id2=signalgroup3.id,
                          setup12=2,
                          setup21=3)

    # initialize intersection object
    intersection = Intersection(
        signalgroups=[signalgroup1, signalgroup2, signalgroup3],
        conflicts=[conflict12, conflict13, conflict23])

    # set associated arrival rates
    arrival_rates = ArrivalRates(id_to_arrival_rates={
        "2": [800, 700],
        "5": [150],
        "8": [180]
    })

    logging.info(f"Minimizing average experienced delay")
    # optimize fixed-time schedule
    fixed_time_schedule, phase_diagram, objective_value, _ = SwiftMobilityCloudApi.get_optimized_fts(
        intersection=intersection,
        arrival_rates=arrival_rates,
        objective=ObjectiveEnum.min_delay)

    logging.info(f"Average experienced delay {objective_value: .3f} seconds")
    logging.info(fixed_time_schedule)
    logging.info(phase_diagram)

    # the following code indicates how to compute a phase diagram from a fixed-time schedule (note that now it makes
    #  no sense to do so as it was already computed above)
    logging.info(
        "Computing phase diagram from fixed-time schedule. Should be the same as before"
    )
    phase_diagram = SwiftMobilityCloudApi.get_phase_diagram(
        intersection=intersection, fixed_time_schedule=fixed_time_schedule)
    logging.info(phase_diagram)
Exemplo n.º 11
0
    def from_json(intersection_dict: Dict) -> Intersection:
        """
        Loading intersection from json (expected same json structure as generated with to_json)
        :param intersection_dict:
        :return: intersection object
        """
        # load signal groups
        signalgroups = [
            SignalGroup.from_json(signalgroup_dict=signalgroup_dict)
            for signalgroup_dict in intersection_dict["signalgroups"]
        ]

        if "periodic_orders" in intersection_dict:
            periodic_orders = [
                PeriodicOrder.from_json(order_dict=order_dict)
                for order_dict in intersection_dict["periodic_orders"]
            ]
        else:
            periodic_orders = []

        # load conflicts
        conflicts = [
            Conflict.from_json(conflict_dict=conflict_dict)
            for conflict_dict in intersection_dict["conflicts"]
        ]

        # load other relations (synchronous starts, offsets and greenyellow_lead)
        sync_starts = []
        offsets = []
        greenyellow_leads = []
        greenyellow_trails = []
        for other_relation_dict in intersection_dict["other_relations"]:
            assert other_relation_dict["from_start_gy"] == other_relation_dict["to_start_gy"], \
                "besides conflicts, at the moment the cloud api can only handle synchronous starts, offsets, " \
                "greenyellow-leads and greenyellow-trails."
            if other_relation_dict[
                    "from_start_gy"] is True and other_relation_dict[
                        "to_start_gy"] is True:
                if other_relation_dict["min_time"] == other_relation_dict[
                        "max_time"]:
                    if other_relation_dict["min_time"] == 0:  # sync start
                        sync_starts.append(
                            SyncStart.from_json(
                                sync_start_dict=other_relation_dict))
                    else:  # offset
                        offsets.append(
                            Offset.from_json(offset_dict=other_relation_dict))
                else:  # greenyellow-leads
                    greenyellow_leads.append(
                        GreenyellowLead.from_json(
                            json_dict=other_relation_dict))
            elif other_relation_dict[
                    "from_start_gy"] is False and other_relation_dict[
                        "to_start_gy"] is False:
                greenyellow_trails.append(
                    GreenyellowTrail.from_json(json_dict=other_relation_dict))

        return Intersection(signalgroups=signalgroups,
                            conflicts=conflicts,
                            sync_starts=sync_starts,
                            offsets=offsets,
                            greenyellow_leads=greenyellow_leads,
                            greenyellow_trails=greenyellow_trails,
                            periodic_orders=periodic_orders)
Exemplo n.º 12
0
def fix_order_and_optimize():
    """
    This example shows how to ask for a fixed-time schedule that adheres to a specified fix order in which
    the signalgroups should receive their greenyellow interval.
    """
    logging.info(f"Running example '{os.path.basename(__file__)}'")
    # signal group consisting of two traffic light allowing 1 or 2 greenyellow intervals per repeating period.
    traffic_light1 = TrafficLight(capacity=1800, lost_time=2.2)
    traffic_light2 = TrafficLight(capacity=1810, lost_time=2.1)
    signalgroup1 = SignalGroup(id="2",
                               traffic_lights=[traffic_light1, traffic_light2],
                               min_greenyellow=10,
                               max_greenyellow=100,
                               min_red=10,
                               max_red=100,
                               min_nr=1,
                               max_nr=2)

    # signal group consisting of one traffic light allowing 1 greenyellow interval (default) per repeating period.
    traffic_light3 = TrafficLight(capacity=1650, lost_time=3.0)
    signalgroup2 = SignalGroup(id="5",
                               traffic_lights=[traffic_light3],
                               min_greenyellow=10,
                               max_greenyellow=100,
                               min_red=10,
                               max_red=100)

    # signal group consisting of one traffic light allowing 1 greenyellow interval (default) per repeating period.
    traffic_light4 = TrafficLight(capacity=1800, lost_time=2.1)
    signalgroup3 = SignalGroup(id="8",
                               traffic_lights=[traffic_light4],
                               min_greenyellow=10,
                               max_greenyellow=100,
                               min_red=10,
                               max_red=100)

    # conflicts & clearance times
    conflict12 = Conflict(id1=signalgroup1.id,
                          id2=signalgroup2.id,
                          setup12=1,
                          setup21=2)
    conflict13 = Conflict(id1=signalgroup1.id,
                          id2=signalgroup3.id,
                          setup12=2,
                          setup21=1)
    conflict23 = Conflict(id1=signalgroup2.id,
                          id2=signalgroup3.id,
                          setup12=2,
                          setup21=3)

    # initialize intersection object
    intersection = Intersection(
        signalgroups=[signalgroup1, signalgroup2, signalgroup3],
        conflicts=[conflict12, conflict13, conflict23])

    # set associated arrival rates
    arrival_rates = ArrivalRates(id_to_arrival_rates={
        "2": [800, 700],
        "5": [150],
        "8": [180]
    })
    logging.info(
        f"Not yet requesting any fixed order of greenyellow intervals")
    logging.info(f"Minimizing average experienced delay")
    # optimize fixed-time schedule
    fixed_time_schedule, phase_diagram, objective_value, _ = SwiftMobilityCloudApi.get_optimized_fts(
        intersection=intersection,
        arrival_rates=arrival_rates,
        objective=ObjectiveEnum.min_delay)

    logging.info(f"Average experienced delay {objective_value: .3f} seconds")
    logging.info(fixed_time_schedule)
    logging.info(phase_diagram)

    logging.info(f"Requesting order: 2 -> 8 -> 5 -> ")
    # initialize intersection object
    intersection = Intersection(
        signalgroups=[signalgroup1, signalgroup2, signalgroup3],
        conflicts=[conflict12, conflict13, conflict23],
        periodic_orders=[PeriodicOrder(order=["2", "8", "5"])])
    logging.info(f"Minimizing average experienced delay")
    # optimize fixed-time schedule
    fixed_time_schedule, phase_diagram, objective_value, _ = SwiftMobilityCloudApi.get_optimized_fts(
        intersection=intersection,
        arrival_rates=arrival_rates,
        objective=ObjectiveEnum.min_delay)

    logging.info(f"Average experienced delay {objective_value: .3f} seconds")
    logging.info(fixed_time_schedule)
    logging.info(phase_diagram)