File size: 4,977 Bytes
1baf215
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
import numpy as np
import pytest

from tfm.data import FIELD_INDEX, generate_episode, generate_exogenous
from tfm.simulators import counterfactual_rollout, make_simulator


@pytest.mark.parametrize("family", ["thermal", "tank", "battery"])
def test_seeded_snapshots_and_common_noise(family):
    a = make_simulator(family, 42)
    b = make_simulator(family, 42)
    assert a.parameters == b.parameters
    np.testing.assert_array_equal(a.state, b.state)
    snapshot = a.snapshot()
    controls = {"thermal": [[5.0]] * 8, "tank": [[0.8, 0.5]] * 8, "battery": [[3.0]] * 8}[family]
    exposure = generate_exogenous(family, 8, 9)
    first = counterfactual_rollout(a, snapshot, controls, exposure)
    second = counterfactual_rollout(a, snapshot, controls, exposure)
    np.testing.assert_array_equal(first, second)
    np.testing.assert_array_equal(a.state, snapshot["state"])
    assert a.rng.bit_generator.state == snapshot["rng_state"]
    # Different actions still consume precisely the same disturbance stream.
    a.restore(snapshot)
    b.restore(snapshot)
    for action, e in zip(controls, exposure):
        a.step(action, e)
        b.step(np.zeros(len(action)), e)
        assert a.rng.bit_generator.state == b.rng.bit_generator.state


@pytest.mark.parametrize("family", ["thermal", "tank", "battery"])
def test_generation_replay_and_physical_constraints(family):
    ep = generate_episode(family, "test", days=2, seed=13)
    sim = make_simulator(family, ep.seed)
    state_names = [
        n
        for n in sim.schema
        if n
        in (
            "indoor_temp",
            "mass_temp",
            "energy_kwh",
            "water_level",
            "water_temp",
            "flow",
            "pressure",
            "state_of_charge",
            "battery_temp",
            "terminal_voltage",
        )
    ]
    indices = [FIELD_INDEX[n] for n in state_names]
    np.testing.assert_array_equal(sim.state, ep.values[0, indices])
    for t in range(len(ep.actions)):
        np.testing.assert_array_equal(sim.step(ep.actions[t], ep.exogenous[t]), ep.values[t + 1, indices])
    if family == "thermal":
        assert np.all(np.diff(ep.values[:, FIELD_INDEX["energy_kwh"]]) >= 0)
        assert np.all(
            (-30 <= ep.values[:, FIELD_INDEX["indoor_temp"]])
            & (ep.values[:, FIELD_INDEX["indoor_temp"]] <= 70)
        )
    elif family == "tank":
        levels = ep.values[:, FIELD_INDEX["water_level"]]
        assert np.all((levels >= 0) & (levels <= ep.hidden_parameters["capacity"]))
        assert np.all(ep.values[:, FIELD_INDEX["pressure"]] >= 0)
    else:
        soc = ep.values[:, FIELD_INDEX["state_of_charge"]]
        assert np.all((soc >= 0) & (soc <= 1))


def test_one_and_two_node_thermal_and_invalid_inputs():
    counts = {len(make_simulator("thermal", seed).state) for seed in range(30)}
    assert counts == {2, 3}
    sim = make_simulator("thermal", 1)
    with pytest.raises(ValueError):
        sim.step([float("nan")], [20.0, 0.0, 0.0])
    with pytest.raises(ValueError):
        sim.step([0.0], [20.0, 0.0, 0.0], dt_minutes=0)
    with pytest.raises(ValueError):
        make_simulator("unknown", 0)


def test_tank_balance_and_battery_direction():
    tank = make_simulator("tank", 2)
    tank.parameters["process_noise_std"] = 0
    initial = tank.state[0]
    state = tank.step([0.0, 0.0], [0.0, 20.0])
    np.testing.assert_allclose(state[0], initial * np.exp(-tank.parameters["leakage_rate"] * 0.25))
    battery = make_simulator("battery", 2)
    battery.parameters["process_noise_std"] = 0
    snapshot = battery.snapshot()
    positive = battery.step([5.0], [20.0])[0]
    battery.restore(snapshot)
    negative = battery.step([-5.0], [20.0])[0]
    assert positive > snapshot["state"][0] > negative


def test_public_control_validation_and_hidden_thermal_saturation():
    sim = make_simulator("thermal", 31)
    with pytest.raises(ValueError, match="exactly"):
        sim.step({"wrong": 0.0}, {"outdoor_temp": 20.0, "solar_gain": 0.0, "occupancy_gain": 0.0})
    with pytest.raises(ValueError, match="exactly"):
        sim.step({"hvac_power": 0.0}, {"outdoor_temp": 20.0})
    with pytest.raises(ValueError, match="bounds"):
        sim.step([16.0], [20.0, 0.0, 0.0])
    assert 3 <= sim.parameters["max_cooling_power"] <= 14
    assert 4 <= sim.parameters["max_heating_power"] <= 15
    sim.parameters["process_noise_std"] = 0.0
    before = sim.state[-1]
    sim.step([15.0], [20.0, 0.0, 0.0])
    assert sim.state[-1] - before == pytest.approx(sim.parameters["max_heating_power"] * 0.25)


def test_battery_temperature_dependent_efficiency():
    warm = make_simulator("battery", 21)
    cold = make_simulator("battery", 21)
    warm.parameters["process_noise_std"] = cold.parameters["process_noise_std"] = 0.0
    warm.state[1], cold.state[1] = 25.0, 0.0
    warm_change = warm.step([2.0], [25.0])[0]
    cold_change = cold.step([2.0], [0.0])[0]
    assert warm_change > cold_change