CityLearn 3.2.0__tar.gz → 3.3.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (198) hide show
  1. {citylearn-3.2.0 → citylearn-3.3.0}/LICENSE +21 -21
  2. {citylearn-3.2.0/citylearn.egg-info → citylearn-3.3.0}/PKG-INFO +4 -3
  3. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/__init__.py +1 -1
  4. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/agents/marlisa.py +102 -26
  5. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/agents/q_learning.py +4 -6
  6. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/agents/rlc.py +18 -2
  7. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/agents/sac.py +163 -15
  8. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/base.py +8 -0
  9. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/building.py +127 -57
  10. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/citylearn.py +19 -1
  11. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/data.py +186 -31
  12. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/electric_vehicle_charger.py +8 -6
  13. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/energy_model.py +76 -47
  14. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/exporter.py +2 -2
  15. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/internal/balance_audit.py +1 -0
  16. citylearn-3.3.0/citylearn/internal/baseline.py +226 -0
  17. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/internal/building_ops.py +33 -11
  18. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/internal/comparison.py +159 -12
  19. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/internal/entity_interface.py +3 -2
  20. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/internal/ev_departure_audit.py +8 -8
  21. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/internal/kpi.py +192 -40
  22. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/internal/kpi_energy.py +28 -13
  23. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/internal/loading.py +19 -4
  24. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/internal/loading_components.py +17 -4
  25. citylearn-3.3.0/citylearn/internal/occupant_models.py +286 -0
  26. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/internal/provenance.py +1 -0
  27. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/internal/robustness.py +41 -5
  28. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/internal/robustness_spaces.py +3 -2
  29. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/internal/runtime.py +237 -146
  30. citylearn-3.3.0/citylearn/internal/scalars.py +52 -0
  31. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/internal/topology.py +39 -14
  32. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/multi_community.py +24 -1
  33. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/occupant.py +12 -9
  34. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/power_outage.py +13 -2
  35. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/reward_function.py +20 -19
  36. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/rl.py +20 -4
  37. {citylearn-3.2.0 → citylearn-3.3.0/citylearn.egg-info}/PKG-INFO +4 -3
  38. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn.egg-info/SOURCES.txt +10 -0
  39. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn.egg-info/requires.txt +3 -2
  40. {citylearn-3.2.0 → citylearn-3.3.0}/requirements.txt +3 -2
  41. citylearn-3.3.0/tests/test_dataset_download_robustness.py +226 -0
  42. {citylearn-3.2.0 → citylearn-3.3.0}/tests/test_deferrable_appliance_integration.py +1 -1
  43. {citylearn-3.2.0 → citylearn-3.3.0}/tests/test_documentation_examples.py +18 -18
  44. {citylearn-3.2.0 → citylearn-3.3.0}/tests/test_dynamic_topology_entity_mode.py +251 -1
  45. {citylearn-3.2.0 → citylearn-3.3.0}/tests/test_ev_arrivals.py +161 -0
  46. citylearn-3.3.0/tests/test_ev_battery_parameters.py +52 -0
  47. citylearn-3.3.0/tests/test_ev_single_charger_association.py +67 -0
  48. {citylearn-3.2.0 → citylearn-3.3.0}/tests/test_evaluation_progress.py +3 -1
  49. citylearn-3.3.0/tests/test_kpi_reference_comparability.py +179 -0
  50. citylearn-3.3.0/tests/test_kpi_reference_consistency.py +373 -0
  51. {citylearn-3.2.0 → citylearn-3.3.0}/tests/test_long_run_audit.py +7 -0
  52. {citylearn-3.2.0 → citylearn-3.3.0}/tests/test_multi_community_env.py +57 -0
  53. citylearn-3.3.0/tests/test_numpy_version_independence.py +99 -0
  54. citylearn-3.3.0/tests/test_portable_pairing_evidence.py +236 -0
  55. citylearn-3.3.0/tests/test_rl_agent_regressions.py +122 -0
  56. {citylearn-3.2.0 → citylearn-3.3.0}/tests/test_rl_temporal_semantics.py +57 -0
  57. {citylearn-3.2.0 → citylearn-3.3.0}/tests/test_robustness_composition.py +89 -0
  58. citylearn-3.3.0/tests/test_sac_marlisa_regressions.py +400 -0
  59. {citylearn-3.2.0 → citylearn-3.3.0}/tests/test_storage_reserve_conservation.py +48 -1
  60. {citylearn-3.2.0 → citylearn-3.3.0}/tests/test_subhourly_unit_conversion.py +39 -0
  61. {citylearn-3.2.0 → citylearn-3.3.0}/tests/test_temporal_reproducibility.py +44 -0
  62. citylearn-3.2.0/citylearn/internal/baseline.py +0 -138
  63. citylearn-3.2.0/citylearn/internal/scalars.py +0 -21
  64. {citylearn-3.2.0 → citylearn-3.3.0}/MANIFEST.in +0 -0
  65. {citylearn-3.2.0 → citylearn-3.3.0}/README.md +0 -0
  66. {citylearn-3.2.0 → citylearn-3.3.0}/README_PYPI.md +0 -0
  67. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/__main__.py +0 -0
  68. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/agents/__init__.py +0 -0
  69. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/agents/base.py +0 -0
  70. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/agents/baseline.py +0 -0
  71. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/agents/rbc.py +0 -0
  72. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/assets/building-0-charge-0.png +0 -0
  73. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/assets/building-0-charge-1.png +0 -0
  74. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/assets/building-0-charge-2.png +0 -0
  75. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/assets/building-0-charge-3.png +0 -0
  76. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/assets/building-1-charge-0.png +0 -0
  77. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/assets/building-1-charge-1.png +0 -0
  78. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/assets/building-1-charge-2.png +0 -0
  79. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/assets/building-1-charge-3.png +0 -0
  80. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/assets/glow.png +0 -0
  81. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/assets/grid.png +0 -0
  82. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/community_dataset.py +0 -0
  83. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/cost_function.py +0 -0
  84. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/dynamics.py +0 -0
  85. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/electric_vehicle.py +0 -0
  86. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/end_use_load_profiles/__init__.py +0 -0
  87. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/end_use_load_profiles/clustering.py +0 -0
  88. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/end_use_load_profiles/lstm_model/__init__.py +0 -0
  89. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/end_use_load_profiles/lstm_model/model.py +0 -0
  90. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/end_use_load_profiles/lstm_model/model_generation.py +0 -0
  91. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/end_use_load_profiles/lstm_model/model_generation_wrapper.py +0 -0
  92. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/end_use_load_profiles/lstm_model/preprocessing.py +0 -0
  93. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/end_use_load_profiles/neighborhood.py +0 -0
  94. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/end_use_load_profiles/simulate.py +0 -0
  95. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/internal/__init__.py +0 -0
  96. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/internal/capabilities.py +0 -0
  97. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/internal/deferrable_cycles.py +0 -0
  98. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/internal/deferrable_service_audit.py +0 -0
  99. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/internal/demand_response.py +0 -0
  100. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/internal/electrical_limits.py +0 -0
  101. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/internal/entity_layout.py +0 -0
  102. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/internal/entity_observations.py +0 -0
  103. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/internal/evaluation_progress.py +0 -0
  104. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/internal/experiment.py +0 -0
  105. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/internal/kpi_community.py +0 -0
  106. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/internal/kpi_equipment.py +0 -0
  107. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/internal/kpi_family_audit.py +0 -0
  108. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/internal/kpi_population.py +0 -0
  109. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/internal/kpi_service_metrics.py +0 -0
  110. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/internal/loading_inputs.py +0 -0
  111. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/internal/market_history.py +0 -0
  112. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/internal/observation_contract.py +0 -0
  113. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/internal/physics_invariants.py +0 -0
  114. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/internal/robustness_audit.py +0 -0
  115. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/internal/robustness_history.py +0 -0
  116. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/internal/robustness_targets.py +0 -0
  117. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/internal/temporal.py +0 -0
  118. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/internal/units.py +0 -0
  119. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/misc/queries/create_zone_metadata.sql +0 -0
  120. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/misc/queries/select_citylearn_energy_simulation.sql +0 -0
  121. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/misc/queries/select_citylearn_weather.sql +0 -0
  122. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/misc/queries/select_ideal_loads.sql +0 -0
  123. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/misc/queries/select_lstm_training_data.sql +0 -0
  124. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/misc/queries/select_zone_conditioning_metadata.sql +0 -0
  125. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/misc/settings.yaml +0 -0
  126. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/preprocessing.py +0 -0
  127. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/utilities.py +0 -0
  128. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/utils/__init__.py +0 -0
  129. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/utils/file_handler.py +0 -0
  130. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/utils/noise.py +0 -0
  131. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/utils/paths.py +0 -0
  132. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn/wrappers.py +0 -0
  133. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn.egg-info/dependency_links.txt +0 -0
  134. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn.egg-info/entry_points.txt +0 -0
  135. {citylearn-3.2.0 → citylearn-3.3.0}/citylearn.egg-info/top_level.txt +0 -0
  136. {citylearn-3.2.0 → citylearn-3.3.0}/setup.cfg +0 -0
  137. {citylearn-3.2.0 → citylearn-3.3.0}/setup.py +0 -0
  138. {citylearn-3.2.0 → citylearn-3.3.0}/tests/test_15_second_power_fixture.py +0 -0
  139. {citylearn-3.2.0 → citylearn-3.3.0}/tests/test_agent_observation_contract.py +0 -0
  140. {citylearn-3.2.0 → citylearn-3.3.0}/tests/test_audit_entrypoints.py +0 -0
  141. {citylearn-3.2.0 → citylearn-3.3.0}/tests/test_audit_verification.py +0 -0
  142. {citylearn-3.2.0 → citylearn-3.3.0}/tests/test_charging_constraints_dataset.py +0 -0
  143. {citylearn-3.2.0 → citylearn-3.3.0}/tests/test_charging_constraints_e2e.py +0 -0
  144. {citylearn-3.2.0 → citylearn-3.3.0}/tests/test_community_dataset.py +0 -0
  145. {citylearn-3.2.0 → citylearn-3.3.0}/tests/test_dataset_loader_window_parquet.py +0 -0
  146. {citylearn-3.2.0 → citylearn-3.3.0}/tests/test_deferrable_cycle_index.py +0 -0
  147. {citylearn-3.2.0 → citylearn-3.3.0}/tests/test_deferrable_service_audit.py +0 -0
  148. {citylearn-3.2.0 → citylearn-3.3.0}/tests/test_deferrable_service_ledger.py +0 -0
  149. {citylearn-3.2.0 → citylearn-3.3.0}/tests/test_demand_response.py +0 -0
  150. {citylearn-3.2.0 → citylearn-3.3.0}/tests/test_dynamic_topology_assets_only_dataset.py +0 -0
  151. {citylearn-3.2.0 → citylearn-3.3.0}/tests/test_dynamic_topology_full_timeline.py +0 -0
  152. {citylearn-3.2.0 → citylearn-3.3.0}/tests/test_dynamics_observation_timing.py +0 -0
  153. {citylearn-3.2.0 → citylearn-3.3.0}/tests/test_electrical_limits.py +0 -0
  154. {citylearn-3.2.0 → citylearn-3.3.0}/tests/test_electrical_service_allocation_regressions.py +0 -0
  155. {citylearn-3.2.0 → citylearn-3.3.0}/tests/test_electrical_service_and_market.py +0 -0
  156. {citylearn-3.2.0 → citylearn-3.3.0}/tests/test_energy_provenance.py +0 -0
  157. {citylearn-3.2.0 → citylearn-3.3.0}/tests/test_energy_provenance_toggle.py +0 -0
  158. {citylearn-3.2.0 → citylearn-3.3.0}/tests/test_entity_interface_contract.py +0 -0
  159. {citylearn-3.2.0 → citylearn-3.3.0}/tests/test_entity_observation_bundles.py +0 -0
  160. {citylearn-3.2.0 → citylearn-3.3.0}/tests/test_episode_reset_state.py +0 -0
  161. {citylearn-3.2.0 → citylearn-3.3.0}/tests/test_episode_split_configuration.py +0 -0
  162. {citylearn-3.2.0 → citylearn-3.3.0}/tests/test_ev_charger_unit.py +0 -0
  163. {citylearn-3.2.0 → citylearn-3.3.0}/tests/test_ev_departure_audit.py +0 -0
  164. {citylearn-3.2.0 → citylearn-3.3.0}/tests/test_ev_feasibility_replay.py +0 -0
  165. {citylearn-3.2.0 → citylearn-3.3.0}/tests/test_ev_replay_batch.py +0 -0
  166. {citylearn-3.2.0 → citylearn-3.3.0}/tests/test_ev_soc_behavior.py +0 -0
  167. {citylearn-3.2.0 → citylearn-3.3.0}/tests/test_evs.py +0 -0
  168. {citylearn-3.2.0 → citylearn-3.3.0}/tests/test_experiment_comparison.py +0 -0
  169. {citylearn-3.2.0 → citylearn-3.3.0}/tests/test_gymnasium_compatibility.py +0 -0
  170. {citylearn-3.2.0 → citylearn-3.3.0}/tests/test_independent_balances.py +0 -0
  171. {citylearn-3.2.0 → citylearn-3.3.0}/tests/test_internal_refactor_parity.py +0 -0
  172. {citylearn-3.2.0 → citylearn-3.3.0}/tests/test_internal_service_contracts.py +0 -0
  173. {citylearn-3.2.0 → citylearn-3.3.0}/tests/test_inventory_ev_battery.py +0 -0
  174. {citylearn-3.2.0 → citylearn-3.3.0}/tests/test_kpi_family_audit.py +0 -0
  175. {citylearn-3.2.0 → citylearn-3.3.0}/tests/test_kpi_golden.py +0 -0
  176. {citylearn-3.2.0 → citylearn-3.3.0}/tests/test_kpi_population.py +0 -0
  177. {citylearn-3.2.0 → citylearn-3.3.0}/tests/test_kpi_v2.py +0 -0
  178. {citylearn-3.2.0 → citylearn-3.3.0}/tests/test_kpis.py +0 -0
  179. {citylearn-3.2.0 → citylearn-3.3.0}/tests/test_lstm_hvac_action_scaling.py +0 -0
  180. {citylearn-3.2.0 → citylearn-3.3.0}/tests/test_market_counterfactual.py +0 -0
  181. {citylearn-3.2.0 → citylearn-3.3.0}/tests/test_market_history.py +0 -0
  182. {citylearn-3.2.0 → citylearn-3.3.0}/tests/test_market_phase_invariants.py +0 -0
  183. {citylearn-3.2.0 → citylearn-3.3.0}/tests/test_observation_definitions.py +0 -0
  184. {citylearn-3.2.0 → citylearn-3.3.0}/tests/test_observation_preparation.py +0 -0
  185. {citylearn-3.2.0 → citylearn-3.3.0}/tests/test_offline_initialization.py +0 -0
  186. {citylearn-3.2.0 → citylearn-3.3.0}/tests/test_provenance_runtime.py +0 -0
  187. {citylearn-3.2.0 → citylearn-3.3.0}/tests/test_refactor_references.py +0 -0
  188. {citylearn-3.2.0 → citylearn-3.3.0}/tests/test_reproducibility_and_agent_learn.py +0 -0
  189. {citylearn-3.2.0 → citylearn-3.3.0}/tests/test_reward_function_wiring.py +0 -0
  190. {citylearn-3.2.0 → citylearn-3.3.0}/tests/test_robustness.py +0 -0
  191. {citylearn-3.2.0 → citylearn-3.3.0}/tests/test_robustness_contracts.py +0 -0
  192. {citylearn-3.2.0 → citylearn-3.3.0}/tests/test_robustness_history.py +0 -0
  193. {citylearn-3.2.0 → citylearn-3.3.0}/tests/test_runtime_event_regressions.py +0 -0
  194. {citylearn-3.2.0 → citylearn-3.3.0}/tests/test_scenario_smoke.py +0 -0
  195. {citylearn-3.2.0 → citylearn-3.3.0}/tests/test_schema_root_compatibility.py +0 -0
  196. {citylearn-3.2.0 → citylearn-3.3.0}/tests/test_series_integrity.py +0 -0
  197. {citylearn-3.2.0 → citylearn-3.3.0}/tests/test_thermal_storage_first_step.py +0 -0
  198. {citylearn-3.2.0 → citylearn-3.3.0}/tests/test_wrapper_cli_occupant_regressions.py +0 -0
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2020 Jose Ramon Vazquez-Canteli, Intelligent Environments Laboratory
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
1
+ MIT License
2
+
3
+ Copyright (c) 2020 Jose Ramon Vazquez-Canteli, Intelligent Environments Laboratory
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: citylearn
3
- Version: 3.2.0
3
+ Version: 3.3.0
4
4
  Summary: CityLearn: an energy-community reinforcement-learning environment focused on EV/BESS/PV, electrical-service constraints, dynamic topology and community-market experimentation.
5
5
  Home-page: https://github.com/citylearn-project/CityLearn
6
6
  Author: Soft-CPS Research Group, Jose Ramon Vazquez-Canteli, Kingsley Nweye, Zoltan Nagy
@@ -16,13 +16,14 @@ Classifier: Operating System :: OS Independent
16
16
  Requires-Python: >=3.9
17
17
  Description-Content-Type: text/markdown
18
18
  License-File: LICENSE
19
+ Requires-Dist: filelock
19
20
  Requires-Dist: gymnasium<2.0.0,>=0.28.1
20
- Requires-Dist: numpy<2.0.0
21
+ Requires-Dist: numpy<3.0.0
21
22
  Requires-Dist: pandas
22
23
  Requires-Dist: platformdirs
23
24
  Requires-Dist: pyyaml
24
25
  Requires-Dist: requests
25
- Requires-Dist: scikit-learn<=1.2.2
26
+ Requires-Dist: scikit-learn
26
27
  Requires-Dist: simplejson
27
28
  Requires-Dist: torch
28
29
  Provides-Extra: parquet
@@ -1,4 +1,4 @@
1
- __version__ = '3.2.0'
1
+ __version__ = '3.3.0'
2
2
 
3
3
  __all__ = ["MultiCommunityEnv", "__version__"]
4
4
 
@@ -1,5 +1,5 @@
1
1
  from copy import deepcopy
2
- from typing import Any, List, Tuple
2
+ from typing import Any, List, Mapping, Tuple
3
3
  import numpy as np
4
4
  from citylearn.agents.rbc import RBC
5
5
  from citylearn.agents.sac import SACRBC
@@ -28,6 +28,8 @@ class MARLISA(SAC):
28
28
  regression_frequency: int = None, information_sharing: bool = None, pca_compression: float = None, iterations: int = None, **kwargs
29
29
  ):
30
30
  self.__coordination_variables_history = None
31
+ self.__pending_transitions = None
32
+ self.__start_regression_time_step = None
31
33
  self.information_sharing = information_sharing
32
34
 
33
35
  super().__init__(*args, **kwargs)
@@ -44,11 +46,16 @@ class MARLISA(SAC):
44
46
  self.pca = [None for _ in self.action_space]
45
47
  self.pca_flag = [False for _ in self.action_dimension]
46
48
  self.regression_flag = [0 for _ in self.action_dimension]
49
+ self.__regression_sample_count = [0 for _ in self.action_dimension]
47
50
  self.energy_size_coefficient = None
48
51
  self.total_coefficient = None
49
52
  self.regression_encoders = self.set_regression_encoders()
50
53
  self.set_energy_coefficients()
51
54
  self.set_pca()
55
+ self.set_training_schedule(
56
+ batch_size=kwargs.get('batch_size'), standardize_start_time_step=kwargs.get('standardize_start_time_step'),
57
+ end_exploration_time_step=kwargs.get('end_exploration_time_step'),
58
+ )
52
59
 
53
60
  @property
54
61
  def regression_buffer_capacity(self) -> int:
@@ -137,14 +144,24 @@ class MARLISA(SAC):
137
144
  # Run once the regression model has been fitted
138
145
  # Normalize all the observations using periodical normalization, one-hot encoding, or -1, 1 scaling. It also removes observations that are not necessary (solar irradiance if there are no solar PV panels).
139
146
 
140
- for i, (o, a, r, n, c0, c1) in enumerate(zip(observations, actions, reward, next_observations, self.coordination_variables_history[0], self.coordination_variables_history[1])):
147
+ # The coordination variables in history[1] were computed with the actions for `observations` (latest predict),
148
+ # so they belong to `observations`, and to the next observation of the transition held back at the last step.
149
+ for i, (o, a, r, n, c) in enumerate(zip(observations, actions, reward, next_observations, self.coordination_variables_history[1])):
141
150
  if self.information_sharing:
142
151
  # update regression buffer
143
152
  variables = np.hstack(np.concatenate((self.get_encoded_regression_variables(i, o), a)))
144
153
  # The targets are the net electricity consumption.
145
154
  target = self.get_encoded_regression_targets(i, n)
146
155
  self.regression_buffer[i].push(variables, target)
147
-
156
+
157
+ if self.__pending_transitions[i] is not None:
158
+ po, pa, pr, pn, pd = self.__pending_transitions[i]
159
+ self.__pending_transitions[i] = None
160
+ self.__push_transition(i, po, pa, pr, np.hstack(np.concatenate((pn, c), dtype=float)), pd)
161
+
162
+ else:
163
+ pass
164
+
148
165
  else:
149
166
  pass
150
167
 
@@ -152,34 +169,37 @@ class MARLISA(SAC):
152
169
  o = self.get_encoded_observations(i, o)
153
170
  n = self.get_encoded_observations(i, n)
154
171
 
155
- # Only executed during the random exploration phase. Pushes unnormalized tuples into the replay buffer.
156
172
  if self.information_sharing:
157
- o = np.hstack(np.concatenate((o, c0), dtype=float))
158
- n = np.hstack(np.concatenate((n, c1), dtype=float))
159
-
160
- else:
161
- pass
173
+ o = np.hstack(np.concatenate((o, c), dtype=float))
162
174
 
163
- # Executed during the training phase. States and rewards pushed into the replay buffer are normalized and processed using PCA.
164
- if self.pca_flag[i]:
165
- o = self.get_normalized_observations(i, o)
166
- o = self.pca[i].transform(o.reshape(1, -1))[0]
167
- n = self.get_normalized_observations(i, n)
168
- n = self.pca[i].transform(n.reshape(1, -1))[0]
169
- r = self.get_normalized_reward(i, r)
170
- else:
171
- pass
175
+ if terminated or truncated:
176
+ # No action, hence no coordination variables, is computed for the episode's final observation,
177
+ # so c stands in for them (as before); they do not enter the TD target when terminated.
178
+ self.__push_transition(i, o, a, r, np.hstack(np.concatenate((n, c), dtype=float)), terminated)
172
179
 
173
- self.replay_buffer[i].push(o, a, r, n, terminated)
180
+ else:
181
+ # The coordination variables of n are computed with the next action: push at the next update.
182
+ self.__pending_transitions[i] = (o, a, r, n, terminated)
183
+
184
+ else:
185
+ self.__push_transition(i, o, a, r, n, terminated)
174
186
 
175
187
  else:
176
188
  pass
177
189
 
190
+ # Refit whenever the regression buffer has doubled since the last fit, until a fit has used
191
+ # regression_frequency samples; from then on every regression_frequency time steps.
192
+ sample_count = len(self.regression_buffer[i])
193
+ sparse_refit = self.information_sharing\
194
+ and self.__regression_sample_count[i] < self.regression_frequency\
195
+ and sample_count >= 2*self.__regression_sample_count[i]
196
+
178
197
  if self.time_step >= self.start_regression_time_step\
179
- and (self.regression_flag[i] < 2 or self.time_step%self.regression_frequency == 0):
198
+ and (self.regression_flag[i] < 2 or self.time_step%self.regression_frequency == 0 or sparse_refit):
180
199
  if self.information_sharing:
181
200
  self.state_estimator[i].fit(self.regression_buffer[i].x, self.regression_buffer[i].y)
182
-
201
+ self.__regression_sample_count[i] = sample_count
202
+
183
203
  else:
184
204
  pass
185
205
 
@@ -198,13 +218,13 @@ class MARLISA(SAC):
198
218
  # calculate normalized observations and rewards
199
219
  X = np.array([j[0] for j in self.replay_buffer[i].buffer], dtype=float)
200
220
  self.norm_mean[i] = np.nanmean(X, axis=0)
201
- self.norm_std[i] = np.nanstd(X, axis=0) + 1e-5
221
+ self.norm_std[i] = self.get_normalization_scale(np.nanstd(X, axis=0))
202
222
  X = self.get_normalized_observations(i, X)
203
223
  self.pca[i].fit(X)
204
224
 
205
225
  R = np.array([j[2] for j in self.replay_buffer[i].buffer], dtype=float)
206
226
  self.r_norm_mean[i] = np.nanmean(R, dtype=float)
207
- self.r_norm_std[i] = np.nanstd(R, dtype=float)/self.reward_scaling + 1e-5
227
+ self.r_norm_std[i] = self.get_normalization_scale(np.nanstd(R, dtype=float)/self.reward_scaling)
208
228
 
209
229
  # update buffer with normalization
210
230
  self.replay_buffer[i].buffer = [(
@@ -313,7 +333,8 @@ class MARLISA(SAC):
313
333
  o = self.get_normalized_observations(c, o)
314
334
  o = self.pca[c].transform(o.reshape(1,-1))[0]
315
335
  o = torch.FloatTensor(o).unsqueeze(0).to(self.device)
316
- result = self.policy_net[i].sample(o)
336
+ # `i` counts coordination iterations; `c` is the building whose policy acts.
337
+ result = self.policy_net[c].sample(o)
317
338
  a = result[2] if deterministic else result[0]
318
339
  a = list(a.detach().cpu().numpy()[0])
319
340
  actions[c] = a
@@ -399,7 +420,7 @@ class MARLISA(SAC):
399
420
 
400
421
  for i, s in enumerate(self.observation_space):
401
422
  n_components = int((self.pca_compression)*(addition + len(self.get_encoded_observations(i, s.low))))
402
- self.pca[i] = PCA(n_components=n_components)
423
+ self.pca[i] = PCA(n_components=n_components, random_state=self._get_seed(3, i))
403
424
 
404
425
  def set_energy_coefficients(self):
405
426
  self.energy_size_coefficient = []
@@ -463,11 +484,66 @@ class MARLISA(SAC):
463
484
  internal_observation_count = self.__COORDINATION_VARIABLE_COUNT if self.information_sharing else 0
464
485
  return super().set_networks(internal_observation_count=internal_observation_count)
465
486
 
487
+ def set_training_schedule(self, *args, **kwargs):
488
+ # SAC.__init__ calls this before start_regression_time_step exists; MARLISA.__init__ calls it again afterwards.
489
+ if self.start_regression_time_step is not None:
490
+ super().set_training_schedule(*args, **kwargs)
491
+
492
+ else:
493
+ pass
494
+
495
+ @property
496
+ def _replay_buffer_delay(self) -> int:
497
+ # Transitions enter the replay buffer once the state estimator has been fitted twice (regression_flag > 1),
498
+ # i.e. from the update at time step max(start_regression_time_step, 1) + 2; with information sharing, each
499
+ # waits one more update for the coordination variables of its next observation.
500
+ return max(self.start_regression_time_step, 1) + 1 + int(self.information_sharing)
501
+
502
+ @property
503
+ def _minimum_standardization_size(self) -> int:
504
+ # PCA is fitted on the standardized replay buffer and needs at least n_components samples.
505
+ return max([1] + [p.n_components for p in self.pca])
506
+
507
+ def __push_transition(self, index: int, o, a, r, n, terminated: bool):
508
+ # Executed during the training phase. States and rewards pushed into the replay buffer are normalized and processed using PCA.
509
+ if self.pca_flag[index]:
510
+ o = self.get_normalized_observations(index, o)
511
+ o = self.pca[index].transform(o.reshape(1, -1))[0]
512
+ n = self.get_normalized_observations(index, n)
513
+ n = self.pca[index].transform(n.reshape(1, -1))[0]
514
+ r = self.get_normalized_reward(index, r)
515
+
516
+ else:
517
+ pass
518
+
519
+ self.replay_buffer[index].push(o, a, r, n, terminated)
520
+
521
+ def __setstate__(self, state: Mapping[str, Any]):
522
+ super().__setstate__(state)
523
+
524
+ # Older scikit-learn checkpoints lack constructor parameters added since they were saved.
525
+ # Restore the installed defaults while keeping the fitted coefficients and saved settings.
526
+ defaults = LinearRegression().get_params(deep=False)
527
+ for estimator in self.state_estimator:
528
+ if type(estimator) is LinearRegression:
529
+ for parameter, default in defaults.items():
530
+ vars(estimator).setdefault(parameter, default)
531
+
532
+ # Checkpoints from CityLearn <= 3.2.0 lack these. Their state estimator may have been fitted on as few as 2
533
+ # samples: with no fit counted, it is refitted on the whole regression buffer at the next update, then as the
534
+ # buffer grows. No transition is held back.
535
+ if '_MARLISA__regression_sample_count' not in state:
536
+ self.__regression_sample_count = [0 for _ in self.action_dimension]
537
+
538
+ if '_MARLISA__pending_transitions' not in state:
539
+ self.__pending_transitions = [None for _ in self.action_dimension]
540
+
466
541
  def reset(self):
467
542
  super().reset()
468
543
  self.__coordination_variables_history = [
469
544
  [[0.0]*self.__COORDINATION_VARIABLE_COUNT for _ in self.action_dimension] for _ in range(2)
470
545
  ]
546
+ self.__pending_transitions = [None for _ in self.action_dimension]
471
547
 
472
548
  class MARLISARBC(MARLISA, SACRBC):
473
549
  r"""Uses :py:class:`citylearn.agents.rbc.RBC` to select action during exploration before using :py:class:`citylearn.agents.marlisa.MARLISA`.
@@ -492,4 +568,4 @@ class MARLISARBC(MARLISA, SACRBC):
492
568
  _, coordination_variables = super().get_exploration_prediction_without_information_sharing(observations)
493
569
  actions = super(SACRBC, self).get_exploration_prediction(observations)
494
570
 
495
- return actions, coordination_variables
571
+ return actions, coordination_variables
@@ -136,12 +136,10 @@ class TabularQLearning(Agent):
136
136
  current_q = self.q[i][o, a]
137
137
  current_q = 0.0 if math.isnan(current_q) else current_q
138
138
 
139
- try:
140
- next_max_q = np.nanargmax(self.q[i][n])
141
-
142
- except ValueError:
143
- # when all values for observation are still NaN
144
- next_max_q = 0.0
139
+ next_q = self.q[i][n]
140
+ # Bellman target uses the best next-state value, not its action index;
141
+ # unvisited (all-NaN) states contribute zero.
142
+ next_max_q = 0.0 if np.all(np.isnan(next_q)) else float(np.nanmax(next_q))
145
143
 
146
144
  # update q
147
145
  new_q = current_q + self.learning_rate*(r + self.discount_factor*next_max_q - current_q)
@@ -1,4 +1,5 @@
1
1
  from typing import Any, List
2
+ import warnings
2
3
  import numpy as np
3
4
  from citylearn.citylearn import CityLearnEnv
4
5
  from citylearn.preprocessing import Encoder, PeriodicNormalization, Normalize, OnehotEncoding
@@ -53,9 +54,24 @@ class RLC(Agent):
53
54
  self, env: CityLearnEnv, hidden_dimension: List[float] = None,
54
55
  discount: float = None, tau: float = None, alpha: float = None, lr: float = None, batch_size: int = None,
55
56
  replay_buffer_capacity: int = None, standardize_start_time_step: int = None, end_exploration_time_step: int = None,
56
- action_scaling_coefficienct: float = None, reward_scaling: float = None,
57
+ action_scaling_coefficient: float = None, reward_scaling: float = None,
57
58
  update_per_time_step: int = None, **kwargs: Any
58
59
  ):
60
+ # Earlier releases only accepted the misspelled keyword, so the documented
61
+ # spelling was swallowed by **kwargs and the 0.5 default always applied.
62
+ misspelled = kwargs.pop('action_scaling_coefficienct', None)
63
+ if misspelled is not None:
64
+ warnings.warn(
65
+ '`action_scaling_coefficienct` is deprecated; use `action_scaling_coefficient`.',
66
+ DeprecationWarning,
67
+ stacklevel=2,
68
+ )
69
+ if action_scaling_coefficient is not None and action_scaling_coefficient != misspelled:
70
+ raise TypeError(
71
+ 'Got conflicting `action_scaling_coefficient` and deprecated `action_scaling_coefficienct` values.'
72
+ )
73
+ action_scaling_coefficient = misspelled
74
+
59
75
  super().__init__(env, **kwargs)
60
76
  self.hidden_dimension = hidden_dimension
61
77
  self.discount = discount
@@ -66,7 +82,7 @@ class RLC(Agent):
66
82
  self.replay_buffer_capacity = replay_buffer_capacity
67
83
  self.standardize_start_time_step = standardize_start_time_step
68
84
  self.end_exploration_time_step = end_exploration_time_step
69
- self.action_scaling_coefficient = action_scaling_coefficienct
85
+ self.action_scaling_coefficient = action_scaling_coefficient
70
86
  self.reward_scaling = reward_scaling
71
87
  self.update_per_time_step = update_per_time_step
72
88
  self.encoders = self.set_encoders()
@@ -1,5 +1,5 @@
1
- import logging
2
- from typing import Any, List, Union
1
+ import random
2
+ from typing import Any, List, Mapping, Union
3
3
  import numpy as np
4
4
  import numpy.typing as npt
5
5
 
@@ -29,6 +29,17 @@ class SAC(RLC):
29
29
  ----------------
30
30
  **kwargs : Any
31
31
  Other keyword arguments used to initialize super class.
32
+
33
+ Notes
34
+ -----
35
+ Defaults adapt to short episodes. If the default schedule cannot standardize the replay buffer before
36
+ exploration ends, the default `batch_size` shrinks to the transitions collected by
37
+ `standardize_start_time_step`, and the default `end_exploration_time_step` (and, for MARLISA's PCA, the
38
+ default `standardize_start_time_step`) moves later as needed. Given values are never changed; an
39
+ inconsistent combination raises :py:class:`ValueError` (see :meth:`set_training_schedule`).
40
+
41
+ Exploration actions (from action spaces that are not already seeded), replay mini-batches and policy noise
42
+ are drawn from generators derived from :attr:`random_seed`, the environment's seed, so runs are repeatable.
32
43
  """
33
44
 
34
45
  super().__init__(env, **kwargs)
@@ -37,7 +48,11 @@ class SAC(RLC):
37
48
  self.normalized = [False for _ in self.action_space]
38
49
  self.soft_q_criterion = nn.SmoothL1Loss()
39
50
  self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
40
- self.replay_buffer = [ReplayBuffer(int(self.replay_buffer_capacity)) for _ in self.action_space]
51
+ self._seed_action_spaces()
52
+ self.replay_buffer = [
53
+ ReplayBuffer(int(self.replay_buffer_capacity), seed=self._get_seed(1, i)) for i in range(len(self.action_space))
54
+ ]
55
+ self._torch_generator = torch.Generator(device=self.device).manual_seed(self._get_seed(2))
41
56
  self.soft_q_net1 = [None for _ in self.action_space]
42
57
  self.soft_q_net2 = [None for _ in self.action_space]
43
58
  self.target_soft_q_net1 = [None for _ in self.action_space]
@@ -52,6 +67,10 @@ class SAC(RLC):
52
67
  self.r_norm_mean = [None for _ in self.action_space]
53
68
  self.r_norm_std = [None for _ in self.action_space]
54
69
  self.set_networks()
70
+ self.set_training_schedule(
71
+ batch_size=kwargs.get('batch_size'), standardize_start_time_step=kwargs.get('standardize_start_time_step'),
72
+ end_exploration_time_step=kwargs.get('end_exploration_time_step'),
73
+ )
55
74
 
56
75
  def update(self, observations: List[List[float]], actions: List[List[float]], reward: List[float], next_observations: List[List[float]], terminated: bool, truncated: bool):
57
76
  r"""Update replay buffer.
@@ -93,10 +112,10 @@ class SAC(RLC):
93
112
  # calculate normalized observations and rewards
94
113
  X = np.array([j[0] for j in self.replay_buffer[i].buffer], dtype = float)
95
114
  self.norm_mean[i] = np.nanmean(X, axis=0)
96
- self.norm_std[i] = np.nanstd(X, axis=0) + 1e-5
115
+ self.norm_std[i] = self.get_normalization_scale(np.nanstd(X, axis=0))
97
116
  R = np.array([j[2] for j in self.replay_buffer[i].buffer], dtype = float)
98
117
  self.r_norm_mean[i] = np.nanmean(R, dtype = float)
99
- self.r_norm_std[i] = np.nanstd(R, dtype = float)/self.reward_scaling + 1e-5
118
+ self.r_norm_std[i] = self.get_normalization_scale(np.nanstd(R, dtype = float)/self.reward_scaling)
100
119
 
101
120
  # update buffer with normalization
102
121
  self.replay_buffer[i].buffer = [(
@@ -220,15 +239,144 @@ class SAC(RLC):
220
239
  return (reward - self.r_norm_mean[index])/self.r_norm_std[index]
221
240
 
222
241
  def get_normalized_observations(self, index: int, observations: List[float]) -> npt.NDArray[np.float64]:
223
- try:
224
- return (np.array(observations, dtype = float) - self.norm_mean[index])/self.norm_std[index]
225
- except:
226
- # self.time_step >= self.standardize_start_time_step and self.batch_size <= len(self.replay_buffer[i])
227
- logging.debug('obs:',observations)
228
- logging.debug('mean:',self.norm_mean[index])
229
- logging.debug('std:',self.norm_std[index])
230
- logging.debug(self.time_step, self.standardize_start_time_step, self.batch_size, len(self.replay_buffer[0]))
231
- assert False
242
+ if self.norm_mean[index] is None:
243
+ raise RuntimeError(
244
+ f'{type(self).__name__} cannot use its policy at time step {self.time_step}: the policy needs observations'
245
+ f' standardized with statistics from the replay buffer, which are computed once time step >='
246
+ f' standardize_start_time_step ({self.standardize_start_time_step}) and the buffer holds batch_size'
247
+ f' ({self.batch_size}) transitions, i.e. at time step {self._get_standardization_time_step()} when learning'
248
+ ' from every time step. Learn with deterministic=False until then.'
249
+ )
250
+
251
+ return (np.array(observations, dtype = float) - self.norm_mean[index])/self.norm_std[index]
252
+
253
+ @staticmethod
254
+ def get_normalization_scale(std: Union[float, npt.NDArray[np.float64]]) -> Union[float, npt.NDArray[np.float64]]:
255
+ r"""Divisor used to standardize observations and rewards: `std` + 1e-5, or 1 where `std` <= 1e-5.
256
+
257
+ A feature (or reward) that does not vary in the replay buffer when the statistics are computed, e.g. `month`
258
+ in a warm-up that stays within one month, has no usable scale. Dividing by ~1e-5 would turn any later change
259
+ into a z-score of ~1e5 and saturate the policy, so such features are centred but not rescaled.
260
+ """
261
+
262
+ std = np.asarray(std, dtype=float)
263
+ return np.where(std > 1e-5, std + 1e-5, 1.0)[()]
264
+
265
+ def _get_seed(self, *key: int) -> int:
266
+ """Seed of one of the agent's random streams, derived from :attr:`random_seed` and `key`."""
267
+
268
+ return int(np.random.SeedSequence(int(self.random_seed), spawn_key=key).generate_state(1)[0])
269
+
270
+ def _seed_action_spaces(self):
271
+ """Seed the action spaces that exploration samples from, unless they are already seeded.
272
+
273
+ An unseeded gymnasium space seeds itself from OS entropy on first use. Spaces the caller has seeded keep
274
+ their stream.
275
+ """
276
+
277
+ for i, space in enumerate(self.action_space):
278
+ if getattr(space, '_np_random', None) is None:
279
+ space.seed(self._get_seed(0, i))
280
+
281
+ def __setstate__(self, state: Mapping[str, Any]):
282
+ self.__dict__.update(state)
283
+
284
+ if '_torch_generator' not in state:
285
+ # Saved before the agent had its own random streams (CityLearn <= 3.2.0): derive them from random_seed as
286
+ # __init__ does, so that training resumed from the checkpoint is repeatable.
287
+ self._seed_action_spaces()
288
+ self._torch_generator = torch.Generator(device=self.device).manual_seed(self._get_seed(2))
289
+
290
+ for i, (buffer, policy) in enumerate(zip(self.replay_buffer, self.policy_net)):
291
+ buffer.random = random.Random(self._get_seed(1, i))
292
+ policy.generator = self._torch_generator
293
+
294
+ @property
295
+ def _replay_buffer_delay(self) -> int:
296
+ """Number of initial :meth:`update` calls that add no transition to the replay buffer."""
297
+
298
+ return 0
299
+
300
+ @property
301
+ def _minimum_standardization_size(self) -> int:
302
+ """Fewest transitions the replay buffer must hold when it is standardized."""
303
+
304
+ return 1
305
+
306
+ def _get_standardization_time_step(self) -> int:
307
+ """Time step of the :meth:`update` that standardizes the replay buffer, when every time step is learned from."""
308
+
309
+ return max(self.standardize_start_time_step, self.batch_size + self._replay_buffer_delay)
310
+
311
+ def set_training_schedule(
312
+ self, batch_size: int = None, standardize_start_time_step: int = None, end_exploration_time_step: int = None
313
+ ):
314
+ r"""Adapt the default training schedule to the episode, then validate it.
315
+
316
+ The policy acts from time step `end_exploration_time_step` + 1 and needs the standardization statistics,
317
+ which :meth:`update` computes at the first time step >= `standardize_start_time_step` at which the replay
318
+ buffer holds `batch_size` transitions (and, for MARLISA, at least as many as its PCA has components).
319
+ Only if the schedule cannot meet this are defaults adapted, in order: the default
320
+ `standardize_start_time_step` waits for the minimum number of transitions, the default `batch_size` shrinks
321
+ to the transitions collected by `standardize_start_time_step`, and the default `end_exploration_time_step`
322
+ moves to the time step before standardization. Schedules that already meet it are left unchanged.
323
+
324
+ Parameters
325
+ ----------
326
+ batch_size: int, optional
327
+ User-given batch size, None if it is the default.
328
+ standardize_start_time_step: int, optional
329
+ User-given earliest standardization time step, None if it is the default.
330
+ end_exploration_time_step: int, optional
331
+ User-given end of exploration, None if it is the default.
332
+
333
+ Raises
334
+ ------
335
+ ValueError
336
+ If the schedule cannot be met without changing given values.
337
+ """
338
+
339
+ delay = self._replay_buffer_delay
340
+ minimum = self._minimum_standardization_size
341
+ capacity = int(self.replay_buffer_capacity)
342
+
343
+ def is_consistent() -> bool:
344
+ time_step = self._get_standardization_time_step()
345
+
346
+ return 1 <= self.batch_size <= capacity\
347
+ and time_step <= self.end_exploration_time_step + 1\
348
+ and min(time_step - delay, capacity) >= minimum
349
+
350
+ if standardize_start_time_step is None and not is_consistent():
351
+ self.standardize_start_time_step = max(self.standardize_start_time_step, minimum + delay)
352
+
353
+ if batch_size is None and not is_consistent():
354
+ self.batch_size = int(min(self.batch_size, capacity, max(self.standardize_start_time_step - delay, 1)))
355
+
356
+ if end_exploration_time_step is None and not is_consistent():
357
+ self.end_exploration_time_step = max(self.end_exploration_time_step, self._get_standardization_time_step() - 1)
358
+
359
+ name = type(self).__name__
360
+ time_step = self._get_standardization_time_step()
361
+
362
+ if not 1 <= self.batch_size <= capacity:
363
+ raise ValueError(f'{name}: batch_size ({self.batch_size}) must be between 1 and replay_buffer_capacity ({capacity}).')
364
+
365
+ if time_step > self.end_exploration_time_step + 1:
366
+ raise ValueError(
367
+ f'{name} uses its policy after end_exploration_time_step ({self.end_exploration_time_step}) but cannot'
368
+ f' standardize observations before time step {time_step}: that needs time step >= standardize_start_time_step'
369
+ f' ({self.standardize_start_time_step}) and batch_size ({self.batch_size}) transitions in the replay buffer'
370
+ + (f', which receives its first transition at time step {delay + 1}' if delay > 0 else '')
371
+ + f'. Set end_exploration_time_step >= {time_step - 1}, or lower standardize_start_time_step or batch_size.'
372
+ )
373
+
374
+ if min(time_step - delay, capacity) < minimum:
375
+ raise ValueError(
376
+ f'{name} would standardize its replay buffer at time step {time_step} with'
377
+ f' {min(time_step - delay, capacity)} transitions, but needs at least {minimum} (PCA n_components).'
378
+ ' Raise standardize_start_time_step, batch_size or replay_buffer_capacity, or lower pca_compression.'
379
+ )
232
380
 
233
381
  def get_encoded_observations(self, index: int, observations: List[float]) -> npt.NDArray[np.float64]:
234
382
  return np.array([j for j in np.hstack(self.encoders[index]*np.array(observations, dtype=float)) if j != None], dtype = float)
@@ -251,7 +399,7 @@ class SAC(RLC):
251
399
  target_param.data.copy_(param.data)
252
400
 
253
401
  # Policy
254
- self.policy_net[i] = PolicyNetwork(observation_dimension, self.action_dimension[i], self.action_space[i], self.action_scaling_coefficient, self.hidden_dimension).to(self.device)
402
+ self.policy_net[i] = PolicyNetwork(observation_dimension, self.action_dimension[i], self.action_space[i], self.action_scaling_coefficient, self.hidden_dimension, generator=self._torch_generator).to(self.device)
255
403
  self.soft_q_optimizer1[i] = optim.Adam(self.soft_q_net1[i].parameters(), lr=self.lr)
256
404
  self.soft_q_optimizer2[i] = optim.Adam(self.soft_q_net2[i].parameters(), lr=self.lr)
257
405
  self.policy_optimizer[i] = optim.Adam(self.policy_net[i].parameters(), lr=self.lr)
@@ -28,6 +28,7 @@ class EpisodeTracker:
28
28
  self.__episode = None
29
29
  self.__episode_start_time_step = None
30
30
  self.__episode_end_time_step = None
31
+ self.__episode_random_seed = None
31
32
  self.__simulation_start_time_step = simulation_start_time_step
32
33
  self.__simulation_end_time_step = simulation_end_time_step
33
34
  self.reset_episode_index()
@@ -37,6 +38,12 @@ class EpisodeTracker:
37
38
  """Current episode index"""
38
39
 
39
40
  return self.__episode
41
+
42
+ @property
43
+ def episode_random_seed(self) -> Union[int, None]:
44
+ """Environment seed captured when the current episode was selected."""
45
+
46
+ return getattr(self, '_EpisodeTracker__episode_random_seed', None)
40
47
 
41
48
  @property
42
49
  def episode_time_steps(self):
@@ -97,6 +104,7 @@ class EpisodeTracker:
97
104
  random_episode_split,
98
105
  random_seed,
99
106
  )
107
+ self.__episode_random_seed = random_seed
100
108
 
101
109
  def __next_episode_time_steps(self, episode_time_steps: Union[int, List[Tuple[int, int]]], rolling_episode_split: bool, random_episode_split: bool, random_seed: int):
102
110
  """Sets `episode_start_time_step` and `episode_end_time_step` for reading data files."""