Пример #1
0
class TestIntegration(TestCase):
    @classmethod
    def setUpClass(self):
        timezone = pytz.timezone('America/Los_Angeles')
        start = timezone.localize(datetime(2018, 9, 5))
        end = timezone.localize(datetime(2018, 9, 6))
        period = 5  # minute
        voltage = 220  # volts
        default_battery_power = 32 * voltage / 1000 # kW
        site = 'caltech'

        cn = sites.caltech_acn(basic_evse=True, voltage=voltage)

        API_KEY = 'DEMO_TOKEN'
        events = acndata_events.generate_events(API_KEY, site, start, end, period, voltage, default_battery_power)

        self.sch = EarliestDeadlineFirstAlgoStateful(increment=1)

        self.sim = Simulator(deepcopy(cn), self.sch, deepcopy(events), start, period=period, verbose=False)
        self.sim.run()

        with open(os.path.join(os.path.dirname(__file__), 'edf_algo_true_analysis_fields.json'), 'r') as infile:
            self.edf_algo_true_analysis_dict = json.load(infile)

        with open(os.path.join(os.path.dirname(__file__), 'edf_algo_true_info_fields.json'), 'r') as infile:
            self.edf_algo_true_info_dict = json.load(infile)

    def test_aggregate_current(self):
        np.testing.assert_allclose(acnsim.aggregate_current(self.sim),
            np.array(self.edf_algo_true_analysis_dict['aggregate_current']))

    def compare_array_dicts(self, array_dict1, array_dict2):
        self.assertEqual(sorted(list(array_dict1.keys())), sorted(list(array_dict2.keys())))
        for key in array_dict1.keys():
            np.testing.assert_allclose(array_dict1[key], array_dict2[key])

    def test_constraint_currents_all_magnitudes(self):
        self.compare_array_dicts(
            acnsim.constraint_currents(self.sim),
            to_array_dict(
                self.edf_algo_true_analysis_dict['constraint_currents_all_linear']))

    def test_constraint_currents_some_magnitudes(self):
        self.compare_array_dicts(
            acnsim.constraint_currents(self.sim, constraint_ids=['Primary A', 'Secondary C']),
            to_array_dict(
                self.edf_algo_true_analysis_dict['constraint_currents_some_linear']))

    def test_proportion_of_energy_delivered(self):
        self.assertEqual(
            acnsim.proportion_of_energy_delivered(self.sim),
            self.edf_algo_true_analysis_dict['proportion_of_energy_delivered'])

    def test_proportion_of_demands_met(self):
        self.assertEqual(
            acnsim.proportion_of_demands_met(self.sim),
            self.edf_algo_true_analysis_dict['proportion_of_demands_met'])

    def test_current_unbalance_nema(self):
        np.testing.assert_allclose(
            acnsim.current_unbalance(self.sim, ['Primary A', 'Primary B', 'Primary C']),
            np.array(self.edf_algo_true_analysis_dict['primary_current_unbalance_nema']))
        np.testing.assert_allclose(
            acnsim.current_unbalance(self.sim, ['Secondary A', 'Secondary B', 'Secondary C']),
            np.array(self.edf_algo_true_analysis_dict['secondary_current_unbalance_nema']))
    
    def test_tutorial_2(self):
        old_evse_keys = list(self.edf_algo_true_info_dict['pilot_signals'].keys())
        new_evse_keys = self.sim.network.station_ids
        self.assertEqual(sorted(new_evse_keys), sorted(old_evse_keys))

        edf_algo_new_info_dict = {field : self.sim.__dict__[field] for field in self.edf_algo_true_info_dict.keys()}
        edf_algo_new_info_dict['charging_rates'] = {self.sim.network.station_ids[i] : list(edf_algo_new_info_dict['charging_rates'][i]) for i in range(len(self.sim.network.station_ids))}
        edf_algo_new_info_dict['pilot_signals'] = {self.sim.network.station_ids[i] : list(edf_algo_new_info_dict['pilot_signals'][i]) for i in range(len(self.sim.network.station_ids))}
        
        for evse_key in new_evse_keys:
            np.testing.assert_allclose(np.array(self.edf_algo_true_info_dict['pilot_signals'][evse_key]),
                np.array(edf_algo_new_info_dict['pilot_signals'][evse_key])[:len(self.edf_algo_true_info_dict['pilot_signals'][evse_key])])
            np.testing.assert_allclose(np.array(self.edf_algo_true_info_dict['charging_rates'][evse_key]),
                np.array(edf_algo_new_info_dict['charging_rates'][evse_key])[:len(self.edf_algo_true_info_dict['charging_rates'][evse_key])])
        self.assertEqual(edf_algo_new_info_dict['peak'], self.edf_algo_true_info_dict['peak'])

    def test_lap_interface_func(self):
        with open(os.path.join(os.path.dirname(__file__), 'edf_algo_pilot_signals.json'), 'r') as infile:
            self.edf_algo_true_lap = json.load(infile)

        self.assertDictEqual(self.edf_algo_true_lap, self.sch.polled_pilots)

    def test_cr_interface_func(self):
        with open(os.path.join(os.path.dirname(__file__), 'edf_algo_charging_rates.json'), 'r') as infile:
            self.edf_algo_true_cr = json.load(infile)

        self.assertDictEqual(self.edf_algo_true_cr, self.sch.polled_charging_rates)
Пример #2
0
class TestSimulator(TestCase):
    def setUp(self):
        start = Mock(datetime)
        network = ChargingNetwork()
        evse1 = EVSE("PS-001", max_rate=32)
        network.register_evse(evse1, 240, 0)
        evse2 = EVSE("PS-002", max_rate=32)
        network.register_evse(evse2, 240, 0)
        evse3 = EVSE("PS-003", max_rate=32)
        network.register_evse(evse3, 240, 0)
        self.scheduler = BaseAlgorithm()
        self.scheduler.max_recompute = None
        events = EventQueue(events=[Event(1), Event(2)])
        self.simulator = Simulator(network, self.scheduler, events, start)
        self.simulator_no_schedule = Simulator(network, None, events, start)

    def test_no_schedule_init(self):
        self.assertIsNone(self.simulator_no_schedule.scheduler)

    def test_no_schedule_error(self):
        with self.assertRaises(TypeError):
            self.simulator_no_schedule.run()

    def test_correct_on_init_pilot_signals(self):
        np.testing.assert_allclose(
            self.simulator.pilot_signals,
            np.zeros(
                (
                    len(self.simulator.network.station_ids),
                    self.simulator.event_queue.get_last_timestamp() + 1,
                )
            ),
        )

    def test_correct_on_init_charging_rates(self):
        np.testing.assert_allclose(
            self.simulator.charging_rates,
            np.zeros(
                (
                    len(self.simulator.network.station_ids),
                    self.simulator.event_queue.get_last_timestamp() + 1,
                )
            ),
        )

    def test_correct_on_init_scheduler_data(self):
        self.assertIsInstance(self.simulator.scheduler, BaseAlgorithm)
        self.assertIsInstance(self.scheduler.interface, Interface)
        self.assertIsNone(self.simulator.max_recompute)

    def test_update_schedules_not_in_network(self):
        new_schedule = {"PS-001": [24, 16], "PS-004": [16, 24]}
        with self.assertRaises(KeyError):
            self.simulator._update_schedules(new_schedule)

    def test_update_schedules_valid_schedule(self):
        new_schedule = {"PS-001": [24, 16], "PS-002": [16, 24]}
        self.simulator._update_schedules(new_schedule)
        np.testing.assert_allclose(
            self.simulator.pilot_signals[:, :2], np.array([[24, 16], [16, 24], [0, 0]])
        )

    def test_index_of_evse_error(self):
        with self.assertRaises(KeyError):
            _ = self.simulator.index_of_evse("PS-004")

    def test_index_of_evse(self):
        idx = self.simulator.index_of_evse("PS-002")
        self.assertEqual(idx, 1)

    def test_pilot_signals_as_df(self):
        self.simulator.pilot_signals = np.array([[1, 2], [3, 4], [5, 6]])
        outframe = self.simulator.pilot_signals_as_df()
        pd.testing.assert_frame_equal(
            outframe,
            pd.DataFrame(
                np.array([[1, 3, 5], [2, 4, 6]]), columns=["PS-001", "PS-002", "PS-003"]
            ),
        )

    def test_charging_rates_as_df(self):
        self.simulator.charging_rates = np.array([[1.1, 2.1], [3.1, 4.1], [5.1, 6.1]])
        outframe = self.simulator.charging_rates_as_df()
        pd.testing.assert_frame_equal(
            outframe,
            pd.DataFrame(
                np.array([[1.1, 3.1, 5.1], [2.1, 4.1, 6.1]]),
                columns=["PS-001", "PS-002", "PS-003"],
            ),
        )

    def test_update_scheduler(self):
        new_scheduler = UncontrolledCharging()
        self.assertIsNone(new_scheduler._interface)
        self.simulator.update_scheduler(new_scheduler)
        self.assertIsInstance(self.simulator.scheduler, UncontrolledCharging)
        self.assertIsInstance(new_scheduler.interface, Interface)
        self.assertEqual(self.simulator.max_recompute, 1)
Пример #3
0
class TestIntegration(TestCase):
    @classmethod
    def setUpClass(self):
        timezone = pytz.timezone("America/Los_Angeles")
        start = timezone.localize(datetime(2018, 9, 5))
        end = timezone.localize(datetime(2018, 9, 6))
        period = 5  # minute
        voltage = 220  # volts
        default_battery_power = 32 * voltage / 1000  # kW
        site = "caltech"

        cn = sites.caltech_acn(basic_evse=True, voltage=voltage)

        API_KEY = "DEMO_TOKEN"
        events = acndata_events.generate_events(API_KEY, site, start, end,
                                                period, voltage,
                                                default_battery_power)

        self.sch = EarliestDeadlineFirstAlgoStateful(increment=1)

        self.sim = Simulator(
            deepcopy(cn),
            self.sch,
            deepcopy(events),
            start,
            period=period,
            verbose=False,
        )
        self.sim.run()

        with open(
                os.path.join(os.path.dirname(__file__),
                             "edf_algo_true_analysis_fields.json"),
                "r",
        ) as infile:
            self.edf_algo_true_analysis_dict = json.load(infile)

        with open(
                os.path.join(os.path.dirname(__file__),
                             "edf_algo_true_datetimes_array.json"),
                "r",
        ) as infile:
            self.edf_algo_true_datetimes_array = json.load(infile)

        with open(
                os.path.join(os.path.dirname(__file__),
                             "edf_algo_true_info_fields.json"),
                "r",
        ) as infile:
            self.edf_algo_true_info_dict = json.load(infile)

    def test_aggregate_current(self):
        np.testing.assert_allclose(
            acnsim.aggregate_current(self.sim),
            np.array(self.edf_algo_true_analysis_dict["aggregate_current"]),
        )

    def compare_array_dicts(self, array_dict1, array_dict2):
        self.assertEqual(sorted(list(array_dict1.keys())),
                         sorted(list(array_dict2.keys())))
        for key in array_dict1.keys():
            np.testing.assert_allclose(array_dict1[key], array_dict2[key])

    def test_constraint_currents_all_magnitudes(self):
        self.compare_array_dicts(
            acnsim.constraint_currents(self.sim),
            to_array_dict(
                self.
                edf_algo_true_analysis_dict["constraint_currents_all_linear"]),
        )

    def test_constraint_currents_some_magnitudes(self):
        self.compare_array_dicts(
            acnsim.constraint_currents(
                self.sim, constraint_ids=["Primary A", "Secondary C"]),
            to_array_dict(self.edf_algo_true_analysis_dict[
                "constraint_currents_some_linear"]),
        )

    def test_proportion_of_energy_delivered(self):
        self.assertEqual(
            acnsim.proportion_of_energy_delivered(self.sim),
            self.edf_algo_true_analysis_dict["proportion_of_energy_delivered"],
        )

    def test_proportion_of_demands_met(self):
        self.assertEqual(
            acnsim.proportion_of_demands_met(self.sim),
            self.edf_algo_true_analysis_dict["proportion_of_demands_met"],
        )

    def test_current_unbalance_nema_error(self):
        with self.assertRaises(ValueError):
            acnsim.current_unbalance(self.sim,
                                     ["Primary A", "Primary B", "Primary C"],
                                     unbalance_type="ABC")

    def test_current_unbalance_nema_warning(self):
        with self.assertWarns(DeprecationWarning):
            acnsim.current_unbalance(self.sim,
                                     ["Primary A", "Primary B", "Primary C"],
                                     type="NEMA")

    def test_current_unbalance_nema(self):
        # A RuntimeWarning is expected to be raised in this test case as
        # of acnportal v.1.0.3. See Github issue #57 for a discussion of
        # why this occurs.
        with self.assertWarns(RuntimeWarning):
            np.testing.assert_allclose(
                acnsim.current_unbalance(
                    self.sim, ["Primary A", "Primary B", "Primary C"]),
                np.array(self.edf_algo_true_analysis_dict[
                    "primary_current_unbalance_nema"]),
            )
        with self.assertWarns(RuntimeWarning):
            np.testing.assert_allclose(
                acnsim.current_unbalance(
                    self.sim, ["Secondary A", "Secondary B", "Secondary C"]),
                np.array(self.edf_algo_true_analysis_dict[
                    "secondary_current_unbalance_nema"]),
            )

    def test_datetimes_array_tutorial_2(self):
        np.testing.assert_equal(
            acnsim.datetimes_array(self.sim),
            np.array([
                np.datetime64(date_time)
                for date_time in self.edf_algo_true_datetimes_array
            ]),
        )

    def test_tutorial_2(self):
        old_evse_keys = list(
            self.edf_algo_true_info_dict["pilot_signals"].keys())
        new_evse_keys = self.sim.network.station_ids
        self.assertEqual(sorted(new_evse_keys), sorted(old_evse_keys))

        edf_algo_new_info_dict = {
            field: self.sim.__dict__[field]
            for field in self.edf_algo_true_info_dict.keys()
        }
        edf_algo_new_info_dict["charging_rates"] = {
            self.sim.network.station_ids[i]:
            list(edf_algo_new_info_dict["charging_rates"][i])
            for i in range(len(self.sim.network.station_ids))
        }
        edf_algo_new_info_dict["pilot_signals"] = {
            self.sim.network.station_ids[i]:
            list(edf_algo_new_info_dict["pilot_signals"][i])
            for i in range(len(self.sim.network.station_ids))
        }

        for evse_key in new_evse_keys:
            np.testing.assert_allclose(
                np.array(
                    self.edf_algo_true_info_dict["pilot_signals"][evse_key]),
                np.array(edf_algo_new_info_dict["pilot_signals"][evse_key])
                [:len(self.edf_algo_true_info_dict["pilot_signals"][evse_key]
                      )],
            )
            np.testing.assert_allclose(
                np.array(
                    self.edf_algo_true_info_dict["charging_rates"][evse_key]),
                np.array(edf_algo_new_info_dict["charging_rates"][evse_key])
                [:len(self.edf_algo_true_info_dict["charging_rates"][evse_key]
                      )],
            )
        self.assertEqual(edf_algo_new_info_dict["peak"],
                         self.edf_algo_true_info_dict["peak"])

    def test_lap_interface_func(self):
        with open(
                os.path.join(os.path.dirname(__file__),
                             "edf_algo_pilot_signals.json"), "r") as infile:
            self.edf_algo_true_lap = json.load(infile)

        self.assertDictEqual(self.edf_algo_true_lap, self.sch.polled_pilots)

    def test_cr_interface_func(self):
        with open(
                os.path.join(os.path.dirname(__file__),
                             "edf_algo_charging_rates.json"), "r") as infile:
            self.edf_algo_true_cr = json.load(infile)

        self.assertDictEqual(self.edf_algo_true_cr,
                             self.sch.polled_charging_rates)