-
Notifications
You must be signed in to change notification settings - Fork 27
/
repopackpy-output.txt
24180 lines (9718 loc) · 541 KB
/
repopackpy-output.txt
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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
================================================================
RepopackPy Output File
================================================================
This file was generated by RepopackPy on: 2024-11-18T14:32:21.374737
Purpose:
--------
This file contains a packed representation of the entire repository's contents.
It is designed to be easily consumable by AI systems for analysis, code review,
or other automated processes.
File Format:
------------
The content is organized as follows:
1. This header section
2. Repository structure
3. Multiple file entries, each consisting of:
a. A separator line (================)
b. The file path (File: path/to/file)
c. Another separator line
d. The full contents of the file
e. A blank line
Usage Guidelines:
-----------------
1. This file should be treated as read-only. Any changes should be made to the
original repository files, not this packed version.
2. When processing this file, use the separators and "File:" markers to
distinguish between different files in the repository.
3. Be aware that this file may contain sensitive information. Handle it with
the same level of security as you would the original repository.
Notes:
------
- Some files may have been excluded based on .gitignore rules and RepopackPy's
configuration.
- Binary files are not included in this packed representation. Please refer to
the Repository Structure section for a complete list of file paths, including
binary files.
For more information about RepopackPy, visit: https://github.com/abinthomasonline/repopack-py
================================================================
Repository Structure
================================================================
.github\workflows\test.yml
.readthedocs.yml
LICENSE
MANIFEST.in
README.md
build_test_data.py
docs\Makefile
docs\make.bat
docs\requirements.txt
docs\source\Spot.html
docs\source\conf.py
docs\source\examples.rst
docs\source\historical.rst
docs\source\index.rst
docs\source\installation.rst
docs\source\intro.rst
docs\source\markets.rst
docs\source\publications.rst
docs\source\time_sequential.rst
nempy\__init__.py
nempy\help_functions\__init__.py
nempy\help_functions\helper_functions.py
nempy\markets.py
nempy\spot_markert_backend\__init__.py
nempy\spot_markert_backend\check.py
nempy\spot_markert_backend\dataframe_validator.py
nempy\spot_markert_backend\elastic_constraints.py
nempy\spot_markert_backend\fcas_constraints.py
nempy\spot_markert_backend\interconnectors.py
nempy\spot_markert_backend\market_constraints.py
nempy\spot_markert_backend\objective_function.py
nempy\spot_markert_backend\solver_interface.py
nempy\spot_markert_backend\unit_constraints.py
nempy\spot_markert_backend\variable_ids.py
nempy\time_sequential.py
publications\all_features_example.py
publications\energy_only_market.py
pyproject.toml
pytest.ini
tests\build_historical_test_data_cache_and_db.py
tests\get_violation_times.py
tests\historical_market_builder.py
tests\test_constraint_equation_calc.py
tests\test_historical.py
tests\test_historical_spot_market_inputs.py
tests\test_interconnector_loss_functions.py
tests\test_market_constraints.py
tests\test_markets.py
tests\test_objective_function.py
tests\test_rpn_calc.py
tests\test_solver_interface.py
tests\test_unit_constraints.py
tests\test_variable_ids.py
================================================================
Repository Files
================================================================
================
File: .readthedocs.yml
================
# .readthedocs.yaml
# Read the Docs configuration file
# See https://docs.readthedocs.io/en/stable/config-file/v2.html for details
# Required
version: 2
# Set the version of Python and other tools you might need
build:
os: ubuntu-20.04
tools:
python: "3.9"
jobs:
post_install:
- pip install poetry
- poetry config virtualenvs.create false
- poetry install --with=docs
# Build documentation in the docs/ directory with Sphinx
sphinx:
configuration: docs/source/conf.py
# If using Sphinx, optionally build your docs in additional formats such as PDFf
formats:
- pdf
================
File: build_test_data.py
================
import sqlite3
from nempy.historical_inputs import mms_db, xml_cache
con = sqlite3.connect('market_management_system.db')
mms_db_manager = mms_db.DBManager(connection=con)
xml_cache_manager = xml_cache.XMLCacheManager('test_nemde_cache')
mms_db_manager.populate(start_year=2019, start_month=1, end_year=2019, end_month=1)
mms_db_manager._create_sample_database('2019/01/10 12:05:00')
xml_cache_manager.populate(start_year=2019, start_month=1, end_year=2019, end_month=1)
================
File: LICENSE
================
BSD 3-Clause License
Copyright (c) 2008-2011, AQR Capital Management, LLC, Lambda Foundry, Inc. and PyData Development Team
All rights reserved.
Copyright (c) 2011-2020, Open source contributors.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
================
File: MANIFEST.in
================
include *.txt
include LICENSE
include pytest.ini
recursive-include docs *.bat
recursive-include docs *.html
recursive-include docs *.pdf
recursive-include docs *.py
recursive-include docs *.rst
recursive-include docs *.txt
recursive-include docs Makefile
recursive-include examples *.py
recursive-include nempy *.py
recursive-include publications *.py
recursive-include tests *.csv
recursive-include tests *.py
recursive-include tests *.zip
recursive-exclude tests/test_files/historical_xml_files *.loaded
================
File: pyproject.toml
================
[project]
name = "nempy"
version = "2.2.0"
description="A flexible tool kit for modelling Australia's National Electricity Market dispatch procedure."
authors = [
{ name = "nick-gorman", email = "n.gorman305@gmail.com" },
]
dependencies = [
"mip==1.16rc0",
"pandas>=2.2.2",
"xmltodict==0.12.0",
"requests>=2.0.0",
"repopack>=0.1.4",
]
readme = "README.md"
requires-python = ">= 3.9"
[build-system]
requires = ["setuptools>=61.0", "wheel"]
build-backend = "setuptools.build_meta"
[tool.uv]
managed = true
dev-dependencies = [
"Sphinx>=5.0.0",
"autodocsumm>=0.2.11",
"sphinx-rtd-theme>=1.3.0",
"pytest>=8.3.2",
]
[tool.pytest.ini_options]
# path to tests for pytest
testpaths = ["nempy", "tests"]
# addopts = add options
addopts = "-ra --doctest-modules"
[tool.setuptools.packages.find]
where = ["nempy"]
================
File: pytest.ini
================
[pytest]
addopts = --doctest-modules --ignore=tests/test_historical.py --ignore=tests/get_violation_times.py --ignore=tests/build_historical_test_data_cache_and_db.py --ignore=tests/test_files --ignore=nempy/historical_inputs/test_nemde_cache
testpaths = tests nempy
================
File: README.md
================
# Nempy
[![Current build](https://github.com/UNSW-CEEM/nempy/actions/workflows/test.yml/badge.svg)](https://github.com/UNSW-CEEM/nempy/actions/workflows/test.yml)
[![Documentation](https://readthedocs.org/projects/nempy/badge/?version=latest)](https://nempy.readthedocs.io/en/latest/?badge=latest)
[![DOI](https://joss.theoj.org/papers/10.21105/joss.03596/status.svg)](https://doi.org/10.21105/joss.03596)
## Table of Contents
- [Introduction](https://github.com/UNSW-CEEM/nempy#introduction)
- [Installation](https://github.com/UNSW-CEEM/nempy#installation)
- [Documentation](https://github.com/UNSW-CEEM/nempy#documentation)
- [Community](https://github.com/UNSW-CEEM/nempy#community)
- [Author](https://github.com/UNSW-CEEM/nempy#author)
- [Citation](https://github.com/UNSW-CEEM/nempy#citation)
- [License](https://github.com/UNSW-CEEM/nempy#license)
- [Examples](https://github.com/UNSW-CEEM/nempy#examples)
## Introduction
Nempy is a Python package for modelling the dispatch procedure of the Australian National Electricity Market (NEM). The idea is
that you can start simple and grow the complexity of your model by adding features such as
ramping constraints, interconnectors, FCAS markets and more. See the [examples](https://github.com/UNSW-CEEM/nempy#examples) below.
| ![nempy-accuracy](https://github.com/prakaa/nempy/assets/40549624/6a994cee-3255-4e3d-b04b-6d4d7e155065) |
|:--:|
| *Dispatch price results from the New South Wales region for 1000 randomly selected intervals in the 2019 calendar year. The actual prices, prior to scaling or capping, are also shown for comparison. Results from two Nempy models are shown, one with a full set of dispatch features, and one without FCAS markets or generic constraints (network and security constraints). Actual prices, results from the full featured model, and the simpler model are shown in descending order for actual prices, results from the simpler model are also shown resorted.* |
For further details, refer to the [documentation](https://nempy.readthedocs.io/en/latest/intro.html#).
For a brief introduction to the NEM, refer to this [ document](https://aemo.com.au/-/media/Files/Electricity/NEM/National-Electricity-Market-Fact-Sheet.pdf).
## Installation
Installing Nempy to use in your project is easy.
```bash
pip install nempy
```
## Documentation
A more detailed introduction to Nempy, examples, and reference documentation can be found on the
[readthedocs](https://nempy.readthedocs.io/en/latest/) page.
## Community
Nempy is open-source and we welcome all forms of community engagement.
### Support
You can seek support for using Nempy using the [discussion tab on GitHub](https://github.com/UNSW-CEEM/nempy/discussions), checking the [issues register](https://github.com/UNSW-CEEM/nempy/issues), or by contacting Nick directly (n.gorman at unsw.edu.au).
If you cannot find a pre-existing issue related to your enquiry, you can submit a new one via the [issues register](https://github.com/UNSW-CEEM/nempy/issues). Issue submissions do not need to adhere to any particular format.
### Future support and maintenance
Planning to continue support and maintenance for Nempy after the PhD project is complete is currently underway. If Nempy
is useful to your work, research, or business, please reach out and inform us so we can consider your use case and
needs.
### Contributing
Contributions via pull requests are welcome. Contributions should:
1. Follow the PEP8 style guide (with exception of line length up to 120 rather than 80)
2. Ensure that all existing automated tests continue to pass (unless you are explicitly changing intended behavour; if you are, please highlight this in your pull request description)
3. Implement automated tests for new features
4. Provide doc strings for public interfaces
#### Installation for development
Nempy uses [`poetry`](https://python-poetry.org/docs/) as a dependency and project management tool. To install Nempy for development, clone or fork the repo and then run the following command in the main directory to install required dependencies and the source code as an editable project:
```bash
poetry install --with=dev
```
You can then work within the virtual environment using `poetry shell` or run commands within it using `poetry run`.
## Author
Nempy's development is being led by Nick Gorman as part of his PhD candidature at the Collaboration on Energy and Environmental
Markets at the University of New South Wales' School of Photovoltaics and Renewable Energy Engineering. (https://www.ceem.unsw.edu.au/).
## Citation
If you use Nempy, please cite the package via the [JOSS paper](https://doi.org/10.5281/zenodo.7397514) (suggested citation below):
> Gorman et al., (2022). Nempy: A Python package for modelling the Australian National Electricity Market dispatch procedure. Journal of Open Source Software, 7(70), 3596, https://doi.org/10.21105/joss.03596
## License
Nempy was created by Nicholas Gorman. It is licensed under the terms of [the BSD 3-Clause Licence](./LICENSE).
## Examples
<details>
<summary>A simple example</summary>
```python
import pandas as pd
from nempy import markets
# Volume of each bid, number of bands must equal number of bands in price_bids.
volume_bids = pd.DataFrame({
'unit': ['A', 'B'],
'1': [20.0, 50.0], # MW
'2': [20.0, 30.0], # MW
'3': [5.0, 10.0] # More bid bands could be added.
})
# Price of each bid, bids must be monotonically increasing.
price_bids = pd.DataFrame({
'unit': ['A', 'B'],
'1': [50.0, 50.0], # $/MW
'2': [60.0, 55.0], # $/MW
'3': [100.0, 80.0] # . . .
})
# Other unit properties
unit_info = pd.DataFrame({
'unit': ['A', 'B'],
'region': ['NSW', 'NSW'], # MW
})
# The demand in the region\s being dispatched
demand = pd.DataFrame({
'region': ['NSW'],
'demand': [120.0] # MW
})
# Create the market model
market = markets.SpotMarket(unit_info=unit_info,
market_regions=['NSW'])
market.set_unit_volume_bids(volume_bids)
market.set_unit_price_bids(price_bids)
market.set_demand_constraints(demand)
# Calculate dispatch and pricing
market.dispatch()
# Return the total dispatch of each unit in MW.
print(market.get_unit_dispatch())
# unit service dispatch
# 0 A energy 40.0
# 1 B energy 80.0
# Return the price of energy in each region.
print(market.get_energy_prices())
# region price
# 0 NSW 60.0
```
</details>
<details>
<summary>A detailed example</summary>
The example demonstrates the broad range of market features that can be implemented with Nempy and the use of auxiliary
modelling tools for accessing historical market data published by AEMO and preprocessing it for compatibility with Nempy.
> [!WARNING]
> This example downloads approximately 54 GB of data from AEMO.
```python
# Notice:
# - This script downloads large volumes of historical market data (~54 GB) from AEMO's nemweb
# portal. You can also reduce the data usage by restricting the time window given to the
# xml_cache_manager and in the get_test_intervals function. The boolean on line 23 can
# also be changed to prevent this happening repeatedly once the data has been downloaded.
import sqlite3
from datetime import datetime, timedelta
import random
import pandas as pd
from nempy import markets
from nempy.historical_inputs import loaders, mms_db, \
xml_cache, units, demand, interconnectors, constraints, rhs_calculator
from nempy.help_functions.helper_functions import update_rhs_values
con = sqlite3.connect('D:/nempy_2021/historical_mms.db')
mms_db_manager = mms_db.DBManager(connection=con)
xml_cache_manager = xml_cache.XMLCacheManager('D:/nempy_2021/xml_cache')
# The second time this example is run on a machine this flag can
# be set to false to save downloading the data again.
download_inputs = True
if download_inputs:
# This requires approximately 4 GB of storage.
mms_db_manager.populate(start_year=2021, start_month=12,
end_year=2022, end_month=1)
# This requires approximately 50 GB of storage.
xml_cache_manager.populate_by_day(start_year=2021, start_month=12, start_day=1,
end_year=2021, end_month=12, end_day=31)
raw_inputs_loader = loaders.RawInputsLoader(
nemde_xml_cache_manager=xml_cache_manager,
market_management_system_database=mms_db_manager)
# A list of intervals we want to recreate historical dispatch for.
def get_test_intervals(number=100):
start_time = datetime(year=2021, month=12, day=1, hour=0, minute=0)
end_time = datetime(year=2021, month=12, day=31, hour=0, minute=0)
difference = end_time - start_time
difference_in_5_min_intervals = difference.days * 12 * 24
random.seed(1)
intervals = random.sample(range(1, difference_in_5_min_intervals), number)
times = [start_time + timedelta(minutes=5 * i) for i in intervals]
times_formatted = [t.isoformat().replace('T', ' ').replace('-', '/') for t in times]
return times_formatted
# List for saving outputs to.
outputs = []
c = 0
# Create and dispatch the spot market for each dispatch interval.
for interval in get_test_intervals(number=100):
c += 1
print(str(c) + ' ' + str(interval))
raw_inputs_loader.set_interval(interval)
unit_inputs = units.UnitData(raw_inputs_loader)
interconnector_inputs = interconnectors.InterconnectorData(raw_inputs_loader)
constraint_inputs = constraints.ConstraintData(raw_inputs_loader)
demand_inputs = demand.DemandData(raw_inputs_loader)
rhs_calculation_engine = rhs_calculator.RHSCalc(xml_cache_manager)
unit_info = unit_inputs.get_unit_info()
market = markets.SpotMarket(market_regions=['QLD1', 'NSW1', 'VIC1',
'SA1', 'TAS1'],
unit_info=unit_info)
# Set bids
volume_bids, price_bids = unit_inputs.get_processed_bids()
market.set_unit_volume_bids(volume_bids)
market.set_unit_price_bids(price_bids)
# Set bid in capacity limits
unit_bid_limit = unit_inputs.get_unit_bid_availability()
market.set_unit_bid_capacity_constraints(unit_bid_limit)
cost = constraint_inputs.get_constraint_violation_prices()['unit_capacity']
market.make_constraints_elastic('unit_bid_capacity', violation_cost=cost)
# Set limits provided by the unconstrained intermittent generation
# forecasts. Primarily for wind and solar.
unit_uigf_limit = unit_inputs.get_unit_uigf_limits()
market.set_unconstrained_intermitent_generation_forecast_constraint(
unit_uigf_limit)
cost = constraint_inputs.get_constraint_violation_prices()['uigf']
market.make_constraints_elastic('uigf_capacity', violation_cost=cost)
# Set unit ramp rates.
def set_ramp_rates(run_type):
ramp_rates = unit_inputs.get_ramp_rates_used_for_energy_dispatch(run_type=run_type)
market.set_unit_ramp_up_constraints(
ramp_rates.loc[:, ['unit', 'initial_output', 'ramp_up_rate']])
market.set_unit_ramp_down_constraints(
ramp_rates.loc[:, ['unit', 'initial_output', 'ramp_down_rate']])
cost = constraint_inputs.get_constraint_violation_prices()['ramp_rate']
market.make_constraints_elastic('ramp_up', violation_cost=cost)
market.make_constraints_elastic('ramp_down', violation_cost=cost)
set_ramp_rates(run_type='fast_start_first_run')
# Set unit FCAS trapezium constraints.
unit_inputs.add_fcas_trapezium_constraints()
cost = constraint_inputs.get_constraint_violation_prices()['fcas_max_avail']
fcas_availability = unit_inputs.get_fcas_max_availability()
market.set_fcas_max_availability(fcas_availability)
market.make_constraints_elastic('fcas_max_availability', cost)
cost = constraint_inputs.get_constraint_violation_prices()['fcas_profile']
regulation_trapeziums = unit_inputs.get_fcas_regulation_trapeziums()
market.set_energy_and_regulation_capacity_constraints(regulation_trapeziums)
market.make_constraints_elastic('energy_and_regulation_capacity', cost)
contingency_trapeziums = unit_inputs.get_contingency_services()
market.set_joint_capacity_constraints(contingency_trapeziums)
market.make_constraints_elastic('joint_capacity', cost)
def set_joint_ramping_constraints(run_type):
cost = constraint_inputs.get_constraint_violation_prices()['fcas_profile']
scada_ramp_down_rates = unit_inputs.get_scada_ramp_down_rates_of_lower_reg_units(
run_type=run_type)
market.set_joint_ramping_constraints_lower_reg(scada_ramp_down_rates)
market.make_constraints_elastic('joint_ramping_lower_reg', cost)
scada_ramp_up_rates = unit_inputs.get_scada_ramp_up_rates_of_raise_reg_units(
run_type=run_type)
market.set_joint_ramping_constraints_raise_reg(scada_ramp_up_rates)
market.make_constraints_elastic('joint_ramping_raise_reg', cost)
set_joint_ramping_constraints(run_type="fast_start_first_run")
# Set interconnector definitions, limits and loss models.
interconnectors_definitions = \
interconnector_inputs.get_interconnector_definitions()
loss_functions, interpolation_break_points = \
interconnector_inputs.get_interconnector_loss_model()
market.set_interconnectors(interconnectors_definitions)
market.set_interconnector_losses(loss_functions,
interpolation_break_points)
# Calculate rhs constraint values that depend on the basslink frequency controller from scratch so there is
# consistency between the basslink switch runs.
# Find the constraints that need to be calculated because they depend on the frequency controller status.
constraints_to_update = (
rhs_calculation_engine.get_rhs_constraint_equations_that_depend_value('BL_FREQ_ONSTATUS', 'W'))
initial_bl_freq_onstatus = rhs_calculation_engine.scada_data['W']['BL_FREQ_ONSTATUS'][0]['@Value']
# Calculate new rhs values for the constraints that need updating.
new_rhs_values = rhs_calculation_engine.compute_constraint_rhs(constraints_to_update)
# Add generic constraints and FCAS market constraints.
fcas_requirements = constraint_inputs.get_fcas_requirements()
fcas_requirements = update_rhs_values(fcas_requirements, new_rhs_values)
market.set_fcas_requirements_constraints(fcas_requirements)
violation_costs = constraint_inputs.get_violation_costs()
market.make_constraints_elastic('fcas', violation_cost=violation_costs)
generic_rhs = constraint_inputs.get_rhs_and_type_excluding_regional_fcas_constraints()
generic_rhs = update_rhs_values(generic_rhs, new_rhs_values)
market.set_generic_constraints(generic_rhs)
market.make_constraints_elastic('generic', violation_cost=violation_costs)
unit_generic_lhs = constraint_inputs.get_unit_lhs()
market.link_units_to_generic_constraints(unit_generic_lhs)
interconnector_generic_lhs = constraint_inputs.get_interconnector_lhs()
market.link_interconnectors_to_generic_constraints(
interconnector_generic_lhs)
# Set the operational demand to be met by dispatch.
regional_demand = demand_inputs.get_operational_demand()
market.set_demand_constraints(regional_demand)
# Set tiebreak constraint to equalise dispatch of equally priced bids.
cost = constraint_inputs.get_constraint_violation_prices()['tiebreak']
market.set_tie_break_constraints(cost)
# Get unit dispatch without fast start constraints and use it to
# make fast start unit commitment decisions.
market.dispatch()
dispatch = market.get_unit_dispatch()
fast_start_profiles = unit_inputs.get_fast_start_profiles_for_dispatch(dispatch)
set_ramp_rates(run_type='fast_start_second_run')
set_joint_ramping_constraints(run_type='fast_start_second_run')
market.set_fast_start_constraints(fast_start_profiles)
if 'fast_start' in market.get_constraint_set_names.keys():
cost = constraint_inputs.get_constraint_violation_prices()['fast_start']
market.make_constraints_elastic('fast_start', violation_cost=cost)
# First run of Basslink switch runs
market.dispatch() # First dispatch without allowing over constrained dispatch re-run to get objective function.
objective_value_run_one = market.objective_value
if constraint_inputs.is_over_constrained_dispatch_rerun():
market.dispatch(allow_over_constrained_dispatch_re_run=True,
energy_market_floor_price=-1000.0,
energy_market_ceiling_price=15000.0,
fcas_market_ceiling_price=1000.0)
prices_run_one = market.get_energy_prices() # If this is the lowest cost run these will be the market prices.
# Re-run dispatch with Basslink Frequency controller off.
# Set frequency controller to off in rhs calculations
rhs_calculation_engine.update_spd_id_value('BL_FREQ_ONSTATUS', 'W', '0')
new_bl_freq_onstatus = rhs_calculation_engine.scada_data['W']['BL_FREQ_ONSTATUS'][0]['@Value']
# Find the constraints that need to be updated because they depend on the frequency controller status.
constraints_to_update = (
rhs_calculation_engine.get_rhs_constraint_equations_that_depend_value('BL_FREQ_ONSTATUS', 'W'))
# Calculate new rhs values for the constraints that need updating.
new_rhs_values = rhs_calculation_engine.compute_constraint_rhs(constraints_to_update)
# Update the constraints in the market.
fcas_requirements = update_rhs_values(fcas_requirements, new_rhs_values)
violation_costs = constraint_inputs.get_violation_costs()
market.set_fcas_requirements_constraints(fcas_requirements)
market.make_constraints_elastic('fcas', violation_cost=violation_costs)
generic_rhs = update_rhs_values(generic_rhs, new_rhs_values)
market.set_generic_constraints(generic_rhs)
market.make_constraints_elastic('generic', violation_cost=violation_costs)
# Reset ramp rate constraints for first run of second Basslink switchrun
set_ramp_rates(run_type='fast_start_first_run')
set_joint_ramping_constraints(run_type='fast_start_first_run')
# Get unit dispatch without fast start constraints and use it to
# make fast start unit commitment decisions.
market.remove_fast_start_constraints()
market.dispatch()
dispatch = market.get_unit_dispatch()
fast_start_profiles = unit_inputs.get_fast_start_profiles_for_dispatch(dispatch)
set_ramp_rates(run_type='fast_start_second_run')
set_joint_ramping_constraints(run_type='fast_start_second_run')
market.set_fast_start_constraints(fast_start_profiles)
if 'fast_start' in market.get_constraint_set_names():
cost = constraint_inputs.get_constraint_violation_prices()['fast_start']
market.make_constraints_elastic('fast_start', violation_cost=cost)
market.dispatch() # First dispatch without allowing over constrained dispatch re-run to get objective function.
objective_value_run_two = market.objective_value
if constraint_inputs.is_over_constrained_dispatch_rerun():
market.dispatch(allow_over_constrained_dispatch_re_run=True,
energy_market_floor_price=-1000.0,
energy_market_ceiling_price=15000.0,
fcas_market_ceiling_price=1000.0)
prices_run_two = market.get_energy_prices() # If this is the lowest cost run these will be the market prices.
prices_run_one['time'] = interval
prices_run_two['time'] = interval
# Getting historical prices for comparison. Note, ROP price, which is
# the regional reference node price before the application of any
# price scaling by AEMO, is used for comparison.
historical_prices = mms_db_manager.DISPATCHPRICE.get_data(interval)
# The prices from the run with the lowest objective function value are used.
if objective_value_run_one < objective_value_run_two:
prices = prices_run_one
else:
prices = prices_run_two
prices['time'] = interval
prices = pd.merge(prices, historical_prices,
left_on=['time', 'region'],
right_on=['SETTLEMENTDATE', 'REGIONID'])
outputs.append(prices)
con.close()
outputs = pd.concat(outputs)
outputs['error'] = outputs['price'] - outputs['ROP']
print('\n Summary of error in energy price volume weighted average price. \n'
'Comparison is against ROP, the price prior to \n'
'any post dispatch adjustments, scaling, capping etc.')
print('Mean price error: {}'.format(outputs['error'].mean()))
print('Median price error: {}'.format(outputs['error'].quantile(0.5)))
print('5% percentile price error: {}'.format(outputs['error'].quantile(0.05)))
print('95% percentile price error: {}'.format(outputs['error'].quantile(0.95)))
# Summary of error in energy price volume weighted average price.
# Comparison is against ROP, the price prior to
# any post dispatch adjustments, scaling, capping etc.
# Mean price error: -0.3284696359015098
# Median price error: 0.0
# 5% percentile price error: -0.5389930178124978
# 95% percentile price error: 0.13746097842649457
```
</details>
================
File: .github\workflows\test.yml
================
name: Run Nempy Tests
on:
push:
branches:
- master
pull_request:
branches:
- master
release:
types: [ created ]
workflow_dispatch: # manual trigger
jobs:
test:
# Matrix testing to test across OSs and Python versions
# Fail-fast: fail the entire job as soon as anything fails
strategy:
fail-fast: true
matrix:
os: ["ubuntu-latest", "macos-latest", "windows-latest"]
python-version: ["3.8", "3.9", "3.10", "3.11", "3.12"]
# Necessary for poetry & Windows
defaults:
run:
shell: bash
runs-on: ${{ matrix.os }}
steps:
- name: Checkout
uses: actions/checkout@v3
- name: Get poetry
uses: snok/install-poetry@v1
with:
virtualenvs-create: true
virtualenvs-in-project: true
- name: Load cached venv
id: cached-poetry-dependencies
uses: actions/cache@v3
with:
path: ~/.cache
key: venv-${{ runner.os }}-${{ steps.setup-python.outputs.python-version }}-${{ hashFiles('**/poetry.lock') }}
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v4
with:
python-version: ${{ matrix.python-version }}
- name: Install poetry env with dev group
run: poetry install --with=dev
- name: Run tests with pytest
run: |
source $VENV
python -m pytest
publish:
if: github.event_name == 'release' && github.event.action == 'created'
needs: test
runs-on: ubuntu-latest
steps:
# Checkout the repo so the workflow can access it
- name: Checkout
uses: actions/checkout@v3
# Set up Python
- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: '3.9'
# Install the specified version of poetry
- name: Get poetry
uses: snok/install-poetry@v1
with:
version: 1.4.0
virtualenvs-create: true
virtualenvs-in-project: true
# Load cached poetry env if it exists
- name: Load cached venv
id: cached-poetry-dependencies
uses: actions/cache@v2
with:
path: .venv
key: venv-${{ runner.os }}-${{ steps.setup-python.outputs.python-version }}-${{ hashFiles('**/poetry.lock') }}
# Build and publish to PyPI
- name: Build and publish # publish tsgen to PyPI
env:
PYPI_USERNAME: ${{ secrets.PYPI_USERNAME }}
PYPI_PASSWORD: ${{ secrets.PYPI_PASSWORD }}
run: poetry publish -u $PYPI_USERNAME -p $PYPI_PASSWORD --build
================
File: docs\make.bat
================
@ECHO OFF
pushd %~dp0
REM Command file for Sphinx documentation
if "%SPHINXBUILD%" == "" (
set SPHINXBUILD=sphinx-build
)
set SOURCEDIR=source
set BUILDDIR=build
if "%1" == "" goto help
%SPHINXBUILD% >NUL 2>NUL
if errorlevel 9009 (
echo.
echo.The 'sphinx-build' command was not found. Make sure you have Sphinx
echo.installed, then set the SPHINXBUILD environment variable to point
echo.to the full path of the 'sphinx-build' executable. Alternatively you
echo.may add the Sphinx directory to PATH.
echo.
echo.If you don't have Sphinx installed, grab it from
echo.http://sphinx-doc.org/
exit /b 1
)
%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%
goto end
:help
%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%
:end
popd
================
File: docs\Makefile
================
# Minimal makefile for Sphinx documentation
#
# You can set these variables from the command line, and also
# from the environment for the first two.
SPHINXOPTS ?=
SPHINXBUILD ?= sphinx-build
SOURCEDIR = source
BUILDDIR = build
# Put it first so that "make" without argument is like "make help".
help:
@$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
.PHONY: help Makefile
# Catch-all target: route all unknown targets to Sphinx using the new
# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
%: Makefile
@$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
================
File: docs\requirements.txt
================
autodocsumm==0.1.13
================
File: docs\source\conf.py
================
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
import os
import sys
sys.path.insert(0, os.path.abspath('../../'))
# -- Project information -----------------------------------------------------
project = 'nempy'
copyright = '2020, Nick Gorman'
author = 'Nick Gorman'
# The full version, including alpha/beta/rc tags
release = '0.0.1'
# -- General configuration ---------------------------------------------------
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = ['sphinx_rtd_theme', 'sphinx.ext.autosectionlabel', "sphinx.ext.autodoc", 'sphinx.ext.napoleon',
'sphinx.ext.autosummary', 'autodocsumm']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path.
exclude_patterns = []
# -- Options for HTML output -------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = 'sphinx_rtd_theme'
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
master_doc = 'index'
autodoc_mock_imports = ["pandas", "numpy", "mip", "xmltodict"]
autodoc_member_order = 'bysource'
napoleon_custom_sections = ['Multiple Returns']
================
File: docs\source\examples.rst
================
.. _examples1:
Examples
====================
A number of examples of how to use Nempy are provided below. Examples 1 to 5 are simple and aim introduce various
market features that can be modelled with Nempy in an easy to understand way, the dispatch and pricing outcomes are
explained in inline comments where the results are printed. Examples 6 and 7 show how to use the historical data input
preparation tools provided with Nempy to recreate historical dispatch intervals. Historical dispatch and pricing
outcomes can be difficult to interpret as they are usually the result of complex interactions between the many features
of the dispatch process, for these example the results are plotted in comparison to historical price outcomes.
Example 8 demonstrates how the outputs of one dispatch interval can be used as the initial conditions of the
next dispatch interval to create a time sequential model, additionally the current limitations with the approach are
briefly discussed.
1. Bid stack equivalent market
---------------------------
This example implements a one region bid stack model of an electricity market. Under the bid stack model, generators are
dispatched according to their bid prices, from cheapest to most expensive, until all demand is satisfied. No loss factors,
ramping constraints or other factors are considered.
.. literalinclude:: ../../examples/bidstack.py
:linenos:
:language: python
2. Unit loss factors, capacities and ramp rates
-----------------------------------------------
A simple example with two units in a one region market, units are given loss factors, capacity values and ramp rates.
The effects of loss factors on dispatch and market prices are explained.
.. literalinclude:: ../../examples/ramp_rates_and_loss_factors.py
:linenos:
:language: python
3. Interconnector with losses
-----------------------------
A simple example demonstrating how to implement a two region market with an interconnector. The interconnector is
modelled simply, with a fixed percentage of losses. To make the interconnector flow and loss calculation easy to
understand a single unit is modelled in the NSW region, NSW demand is set zero, and VIC region demand is set to 90 MW,
thus all the power to meet VIC demand must flow across the interconnetcor.
.. literalinclude:: ../../examples/interconnector_constant_loss_percentage.py
:linenos:
:language: python
4. Dynamic non-linear interconnector losses
----------------------------------------
This example demonstrates how to model regional demand dependant interconnector loss functions as decribed in the AEMO
:download:`Marginal Loss Factors documentation section 3 to 5 <../../docs/pdfs/Marginal Loss Factors for the 2020-21 Financial year.pdf>`.
To make the interconnector flow and loss calculation easy to understand a single unit is modelled in the NSW region,
NSW demand is set zero, and VIC region demand is set to 800 MW, thus all the power to meet VIC demand must flow across
the interconnetcor.
.. literalinclude:: ../../examples/interconnector_dynamic_losses.py
:linenos:
:language: python
5. Simple FCAS markets
----------------------------------------