-
Notifications
You must be signed in to change notification settings - Fork 101
Expand file tree
/
Copy pathbase.jl
More file actions
3433 lines (3013 loc) · 106 KB
/
base.jl
File metadata and controls
3433 lines (3013 loc) · 106 KB
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
const SKIP_PM_VALIDATION = false
const SYSTEM_KWARGS = Set((
:area_name_formatter,
:branch_name_formatter,
:xfrm_3w_name_formatter,
:switched_shunt_name_formatter,
:transformer_control_objective_formatter,
:dcline_name_formatter,
:vscline_name_formatter,
:bus_name_formatter,
:config_path,
:frequency,
:gen_name_formatter,
:generator_mapping,
:internal,
:load_name_formatter,
:loadzone_name_formatter,
:runchecks,
:shunt_name_formatter,
:time_series_directory,
:time_series_in_memory,
:time_series_read_only,
:timeseries_metadata_file,
:unit_system,
:pm_data_corrections,
:import_all,
:enable_compression,
:compression,
:name,
:description,
))
# This will be used in the future to handle serialization changes.
const DATA_FORMAT_VERSION = "5.0.0"
mutable struct SystemMetadata <: IS.InfrastructureSystemsType
name::Union{Nothing, String}
description::Union{Nothing, String}
end
"""
A power system
`System` is the main data container in `PowerSystems.jl`, including basic metadata (base
power, frequency), components (network topology, loads, generators, and services), and
time series data.
```julia
System(base_power)
System(base_power, buses, components...)
System(base_power, buses, generators, loads, branches, storage, services; kwargs...)
System(base_power, buses, generators, loads; kwargs...)
System(file; kwargs...)
System(; buses, generators, loads, branches, storage, base_power, services, kwargs...)
System(; kwargs...)
```
# Arguments
- `base_power::Float64`: the base power value for the system
- `buses::Vector{ACBus}`: an array of buses
- `components...`: Each element (e.g., `buses`, `generators`, ...) must be an iterable
containing subtypes of `Component`.
- `file::AbstractString`: Path to a Matpower, PSSE, or JSON file ending with .m, .raw, or .json
# Keyword arguments
- `name::String`: System name.
- `description::String`: System description.
- `frequency::Float64`: (default = 60.0) Operating frequency (Hz).
- `runchecks::Bool`: Run available checks on input fields and when add_component! is called.
Throws InvalidValue if an error is found.
- `generator_mapping`: A dictionary mapping generator names to their corresponding topologies. This is used to associate generators with their respective buses when parsing from CSV.
- `time_series_in_memory::Bool=false`: Store time series data in memory instead of HDF5.
- `time_series_directory::Union{Nothing, String}`: Directory for the time series HDF5 file.
Defaults to the tmp file system.
- `timeseries_metadata_file`: Path to a file containing time series metadata descriptors. This is used to add time series data to the system from files.
- `time_series_read_only::Bool=false`: Open the time series store in read-only mode.
This is useful for reading time series data without modifying it.
- `enable_compression::Bool=false`: Enable compression of time series data in HDF5.
- `compression::CompressionSettings`: Allows customization of HDF5 compression settings.
- `config_path::String`: specify path to validation config file
- `unit_system::String`: (Default = `"SYSTEM_BASE"`) Set the unit system for
[per-unitization](@ref per_unit) while getting and setting data (`"SYSTEM_BASE"`,
`"DEVICE_BASE"`, or `"NATURAL_UNITS"`)
- `bus_name_formatter`: A function that takes a [`Bus`](@ref) and returns a string to use as the bus name when [parsing PSSe or Matpower files](@ref pm_data).
- `load_name_formatter`: A function that takes an [`ElectricLoad`](@ref) and returns a string to use as the load names when [parsing PSSe or Matpower files](@ref pm_data).
- `loadzone_name_formatter`: A function that takes a [`LoadZone`](@ref) and returns a string to use as the load zone name when [parsing PSSe or Matpower files](@ref pm_data).
- `gen_name_formatter`: A function that takes a [`Generator`](@ref) and returns a string to use as the generator name when [parsing PSSe or Matpower files](@ref pm_data).
- `shunt_name_formatter`: A function that takes the fixed shunt data and returns a string to use as the [`FixedAdmittance`](@ref) name when [parsing PSSe or Matpower files](@ref pm_data).
- `branch_name_formatter`: A function that takes a [`Branch`](@ref) and returns a string to use as the branch name when [parsing PSSe or Matpower files](@ref pm_data).
- `pm_data_corrections::Bool`: A function that applies the correction to the data from [`PowerModels.jl`](https://lanl-ansi.github.io/PowerModels.jl/stable/).
- `import_all::Bool`: A boolean flag to indicate whether to import all available data when [parsing PSSe or Matpower files](@ref pm_data). The additional data will be stored in the `ext` dictionary and can be retrieved using [`get_ext`](@ref)
- `internal::IS.InfrastructureSystemsInternal`: Internal structure for [`InfrastructureSystems.jl`](https://nrel-sienna.github.io/InfrastructureSystems.jl/stable/). This is used only during JSON de-seralization, do not pass it when building a `System` manually.
By default, time series data is stored in an HDF5 file in the tmp file system to prevent
large datasets from overwhelming system memory (see [Data Storage](@ref)).
**If the system's time series data will be larger than the amount of tmp space available**, use the
`time_series_directory` parameter to change its location.
You can also override the location by setting the environment
variable `SIENNA_TIME_SERIES_DIRECTORY` to another directory.
HDF5 compression is not enabled by default, but you can enable
it with `enable_compression` to get significant storage savings at the cost of CPU time.
[`CompressionSettings`](@ref) can be used to customize the HDF5 compression.
If you know that your dataset will fit in your computer's memory, then you can increase
performance by storing it in memory with `time_series_in_memory`.
# Examples
```julia
sys = System(100.0; name = "My Power System")
sys = System(100.0; name = "My Power System", description = "System corresponds to scenario A")
sys= System(path_to_my_psse_raw_file; # PSSE file bus names are not unique
bus_name_formatter = x -> strip(string(x["name"])) * "-" * string(x["index"]),
)
sys = System(100.0; enable_compression = true)
sys = System(100.0; compression = CompressionSettings(
enabled = true,
type = CompressionTypes.DEFLATE, # BLOSC is also supported
level = 3,
shuffle = true)
)
sys = System(100.0; time_series_in_memory = true)
```
"""
struct System <: IS.ComponentContainer
data::IS.SystemData
frequency::Float64 # [Hz]
bus_numbers::Set{Int}
runchecks::Base.RefValue{Bool}
units_settings::SystemUnitsSettings
time_series_directory::Union{Nothing, String}
metadata::SystemMetadata
internal::IS.InfrastructureSystemsInternal
function System(
data,
units_settings::SystemUnitsSettings,
internal::IS.InfrastructureSystemsInternal;
runchecks = true,
frequency = DEFAULT_SYSTEM_FREQUENCY,
time_series_directory = nothing,
name = nothing,
description = nothing,
kwargs...,
)
# Note to devs: if you add parameters to kwargs then consider whether they need
# special handling in the deserialization function in this file.
# See deserialize for System.
# Implement a strict check here to make sure that SYSTEM_KWARGS can be used
# elsewhere.
unsupported = setdiff(keys(kwargs), SYSTEM_KWARGS)
!isempty(unsupported) && error("Unsupported kwargs = $unsupported")
if !isnothing(get(kwargs, :unit_system, nothing))
@warn(
"unit_system kwarg ignored. The value in SystemUnitsSetting takes precedence"
)
end
bus_numbers = Set(get_number.(IS.get_components(ACBus, data)))
return new(
data,
frequency,
bus_numbers,
Base.RefValue{Bool}(runchecks),
units_settings,
time_series_directory,
SystemMetadata(name, description),
internal,
)
end
end
function System(data, base_power::Number, internal; kwargs...)
unit_system_ = get(kwargs, :unit_system, "SYSTEM_BASE")
unit_system = UNIT_SYSTEM_MAPPING[unit_system_]
units_settings = SystemUnitsSettings(base_power, unit_system)
return System(data, units_settings, internal; kwargs...)
end
"""Construct an empty `System`. Useful for building a System while parsing raw data."""
function System(base_power::Number; kwargs...)
return System(_create_system_data_from_kwargs(; kwargs...), base_power; kwargs...)
end
"""Construct a `System` from `InfrastructureSystems.SystemData`"""
function System(
data,
base_power::Number;
internal = IS.InfrastructureSystemsInternal(),
kwargs...,
)
return System(data, base_power, internal; kwargs...)
end
"""
System constructor when components are constructed externally.
"""
function System(base_power::Float64, buses::Vector{ACBus}, components...; kwargs...)
data = _create_system_data_from_kwargs(; kwargs...)
sys = System(data, base_power; kwargs...)
for bus in buses
add_component!(sys, bus)
end
for component in Iterators.flatten(components)
add_component!(sys, component)
end
if get(kwargs, :runchecks, true)
check(sys)
end
return sys
end
"""Constructs a non-functional System for demo purposes."""
function System(
::Nothing;
buses = [
ACBus(;
number = 0,
name = "init",
bustype = ACBusTypes.REF,
available = true,
angle = 0.0,
magnitude = 0.0,
voltage_limits = (min = 0.0, max = 0.0),
base_voltage = nothing,
area = nothing,
load_zone = nothing,
ext = Dict{String, Any}(),
),
],
generators = [ThermalStandard(nothing), RenewableNonDispatch(nothing)],
loads = [PowerLoad(nothing)],
branches = nothing,
storage = nothing,
base_power::Float64 = 100.0,
services = nothing,
kwargs...,
)
for component in Iterators.flatten((generators, loads))
if get_name(component) == "init"
set_bus!(component, first(buses))
end
end
_services = isnothing(services) ? [] : services
_branches = isnothing(branches) ? [] : branches
_storage = isnothing(storage) ? [] : storage
return System(
base_power,
buses,
generators,
loads,
_branches,
_storage,
_services;
kwargs...,
)
end
function system_via_power_models(file_path::AbstractString; kwargs...)
pm_kwargs = Dict(k => v for (k, v) in kwargs if !in(k, SYSTEM_KWARGS))
sys_kwargs = Dict(k => v for (k, v) in kwargs if in(k, SYSTEM_KWARGS))
return System(PowerModelsData(file_path; pm_kwargs...); sys_kwargs...)
end
"""Constructs a System from a file path ending with .m, .raw, or .json
If the file is JSON, then `assign_new_uuids = true` will generate new UUIDs for the system
and all components. If the file is .raw, then `try_reimport = false` will skip searching for
a `<name>_export_metadata.json` file in the same directory.
"""
function System(
file_path::AbstractString;
assign_new_uuids = false,
try_reimport = true,
kwargs...,
)
ext = lowercase(splitext(file_path)[2])
if ext == ".m"
return system_via_power_models(file_path; kwargs...)
elseif ext == ".raw"
try_reimport && return system_from_psse_reimport(file_path; kwargs...)
return system_via_power_models(file_path; kwargs...)
elseif ext == ".json"
unsupported = setdiff(keys(kwargs), SYSTEM_KWARGS)
!isempty(unsupported) && error("Unsupported kwargs = $unsupported")
runchecks = get(kwargs, :runchecks, true)
time_series_read_only = get(kwargs, :time_series_read_only, false)
time_series_directory = get(kwargs, :time_series_directory, nothing)
config_path = get(kwargs, :config_path, POWER_SYSTEM_STRUCT_DESCRIPTOR_FILE)
sys = deserialize(
System,
file_path;
time_series_read_only = time_series_read_only,
runchecks = runchecks,
time_series_directory = time_series_directory,
config_path = config_path,
)
_post_deserialize_handling(
sys;
runchecks = runchecks,
assign_new_uuids = assign_new_uuids,
)
return sys
else
throw(DataFormatError("$file_path is not a supported file type"))
end
end
"""
If assign_new_uuids = true, generate new UUIDs for the system and all components.
Warning: time series data is not restored by this method. If that is needed, use the normal
process to construct the system from a serialized JSON file instead, such as with
`System("sys.json")`.
"""
function IS.from_json(
io::Union{IO, String},
::Type{System};
runchecks = true,
assign_new_uuids = false,
kwargs...,
)
data = JSON3.read(io, Dict)
sys = from_dict(System, data; kwargs...)
_post_deserialize_handling(
sys;
runchecks = runchecks,
assign_new_uuids = assign_new_uuids,
)
return sys
end
function _post_deserialize_handling(sys::System; runchecks = true, assign_new_uuids = false)
runchecks && check(sys)
if assign_new_uuids
IS.assign_new_uuid!(sys)
for component in get_components(Component, sys)
IS.assign_new_uuid!(sys, component)
end
for component in
IS.get_masked_components(InfrastructureSystemsComponent, sys.data)
IS.assign_new_uuid!(sys, component)
end
# Note: this does not change UUIDs for time series data because they are
# shared with components.
end
end
"""
Parse static and dynamic data directly from PSS/e text files. Automatically generates
all the relationships between the available dynamic injection models and the static counterpart
Each dictionary indexed by id contains a vector with 5 of its components:
* Machine
* Shaft
* AVR
* TurbineGov
* PSS
Files must be parsed from a .raw file (PTI data format) and a .dyr file.
## Examples:
```julia
raw_file = "Example.raw"
dyr_file = "Example.dyr"
sys = System(raw_file, dyr_file)
```
"""
function System(sys_file::AbstractString, dyr_file::AbstractString; kwargs...)
ext = splitext(sys_file)[2]
if lowercase(ext) in [".raw"]
pm_kwargs = Dict(k => v for (k, v) in kwargs if !in(k, SYSTEM_KWARGS))
sys = System(PowerModelsData(sys_file; pm_kwargs...); kwargs...)
else
throw(DataFormatError("$sys_file is not a .raw file type"))
end
add_dyn_injectors!(sys, dyr_file)
return sys
end
"""
Construct a System from a subsystem of an existing system.
# Arguments
- `sys::System`: the base system from which the subsystems are derived
- `subsystem::String`: the name of the subsystem to extract from the original system
# Keyword arguments
- `runchecks::Bool`: (default = true) whether to run system validation checks.
"""
function from_subsystem(sys::System, subsystem::AbstractString; runchecks = true)
if !in(subsystem, get_subsystems(sys))
error("subsystem = $subsystem is not stored")
end
# It would be faster to create an empty system and then populate it with
# deep copies of each component in the subsystem. It would also result in a "clean" HDF5
# file (the result here will have deleted entries that need to repacked through
# serialization/de-serialization). That is not implemented because
# 1. The performance loss should not be too large.
# 2. We haven't yet implemented deepcopy(Component).
# 3. There is extra code complexity in adding copied components in the correct order
# as well as copying time series data.
new_sys = deepcopy(sys)
filter_components_by_subsystem!(new_sys, subsystem; runchecks = runchecks)
IS.assign_new_uuid!(new_sys)
for component in get_components(Component, new_sys)
IS.assign_new_uuid!(new_sys, component)
end
return new_sys
end
"""
Filter out all components that are not part of the subsystem.
"""
function filter_components_by_subsystem!(
sys::System,
subsystem::AbstractString;
runchecks = true,
)
component_uuids = get_component_uuids(sys, subsystem)
for component in get_components(Component, sys)
if !in(IS.get_uuid(component), component_uuids)
remove_component!(sys, component)
end
end
for component in IS.get_masked_components(Component, sys.data)
if !in(IS.get_uuid(component), component_uuids)
IS.remove_masked_component!(sys.data, component)
end
end
if runchecks
check(sys)
check_components(sys)
end
end
"""
Serializes a system to a JSON file and saves time series to an HDF5 file.
# Arguments
- `sys::System`: system
- `filename::AbstractString`: filename to write
# Keyword arguments
- `user_data::Union{Nothing, Dict} = nothing`: optional metadata to record
- `pretty::Bool = false`: whether to pretty-print the JSON
- `force::Bool = false`: whether to overwrite existing files
- `check::Bool = false`: whether to run system validation checks
Refer to [`check_component`](@ref) for exceptions thrown if `check = true`.
"""
function IS.to_json(
sys::System,
filename::AbstractString;
user_data = nothing,
pretty = false,
force = false,
runchecks = false,
)
if runchecks
check(sys)
check_components(sys)
end
IS.prepare_for_serialization_to_file!(sys.data, filename; force = force)
data = to_json(sys; pretty = pretty)
open(filename, "w") do io
write(io, data)
end
mfile = joinpath(dirname(filename), splitext(basename(filename))[1] * "_metadata.json")
@info "Serialized System to $filename"
_serialize_system_metadata_to_file(sys, mfile, user_data)
return
end
function _serialize_system_metadata_to_file(sys::System, filename, user_data)
name = get_name(sys)
description = get_description(sys)
resolutions = [x.value for x in get_time_series_resolutions(sys)]
metadata = OrderedDict(
"name" => isnothing(name) ? "" : name,
"description" => isnothing(description) ? "" : description,
"frequency" => sys.frequency,
"time_series_resolutions_milliseconds" => resolutions,
"component_counts" => IS.get_component_counts_by_type(sys.data),
"time_series_counts" => IS.get_time_series_counts_by_type(sys.data),
)
if !isnothing(user_data)
metadata["user_data"] = user_data
end
open(filename, "w") do io
JSON3.pretty(io, metadata)
end
@info "Serialized System metadata to $filename"
end
IS.assign_new_uuid!(sys::System) = IS.assign_new_uuid_internal!(sys)
"""
Return the internal of the system
"""
IS.get_internal(sys::System) = sys.internal
"""
Return a user-modifiable dictionary to store extra information.
"""
get_ext(sys::System) = IS.get_ext(sys.internal)
"""
Return the system's base power.
"""
get_base_power(sys::System) = sys.units_settings.base_value
"""
Return the system's frequency.
"""
get_frequency(sys::System) = sys.frequency
"""
Clear any value stored in ext.
"""
clear_ext!(sys::System) = IS.clear_ext!(sys.internal)
"""
Return true if checks are enabled on the system.
"""
get_runchecks(sys::System) = sys.runchecks[]
"""
Enable or disable system checks.
Applies to component addition as well as overall system consistency.
"""
function set_runchecks!(sys::System, value::Bool)
sys.runchecks[] = value
@info "Set runchecks to $value"
end
function set_units_setting!(
component::Component,
settings::Union{SystemUnitsSettings, Nothing},
)
set_units_info!(get_internal(component), settings)
return
end
function _set_units_base!(system::System, settings::UnitSystem)
to_change = (system.units_settings.unit_system != settings)
to_change && (system.units_settings.unit_system = settings)
return (to_change, settings)
end
_set_units_base!(system::System, settings::String) =
_set_units_base!(system::System, UNIT_SYSTEM_MAPPING[uppercase(settings)])
"""
Sets the units base for the getter functions on the devices. It modifies the behavior of all getter functions
# Examples
```julia
set_units_base_system!(sys, "NATURAL_UNITS")
```
```julia
set_units_base_system!(sys, UnitSystem.SYSTEM_BASE)
```
"""
function set_units_base_system!(system::System, units::Union{UnitSystem, String})
changed, new_units = _set_units_base!(system::System, units)
changed && @info "Unit System changed to $new_units"
return
end
_get_units_base(system::System) = system.units_settings.unit_system
"""
Get the system's [unit base](@ref per_unit))
"""
function get_units_base(system::System)
return string(_get_units_base(system))
end
"""
A "context manager" that sets the [`System`](@ref)'s [units base](@ref per_unit) to the
given value, executes the function, then sets the units base back.
# Examples
```julia
active_power_mw = with_units_base(sys, UnitSystem.NATURAL_UNITS) do
get_active_power(gen)
end
# now active_power_mw is in natural units no matter what units base the system is in
```
"""
function with_units_base(f::Function, sys::System, units::Union{UnitSystem, String})
old_units = _get_units_base(sys)
_set_units_base!(sys, units)
try
f()
finally
_set_units_base!(sys, old_units)
end
end
_set_units_base!(c::Component, settings::String) =
_set_units_base!(c::Component, UNIT_SYSTEM_MAPPING[uppercase(settings)])
function _set_units_base!(c::Component, settings::UnitSystem)
units_info = get_internal(c).units_info
old_base_value = units_info.base_value
set_units_setting!(
c,
SystemUnitsSettings(old_base_value, settings),
)
return
end
"""
A "context manager" that sets the [`Component`](@ref)'s [units base](@ref per_unit) to the
given value, executes the function, then sets the units base back.
# Examples
```julia
active_power_mw = with_units_base(component, UnitSystem.NATURAL_UNITS) do
get_active_power(component)
end
# now active_power_mw is in natural units no matter what units base the system is in
```
"""
function with_units_base(f::Function, c::Component, units::Union{UnitSystem, String})
internal = get_internal(c)
old_units_info = internal.units_info # Save reference to restore later
_set_units_base!(c, units)
temp_units_info = internal.units_info # The temporary object we just created
try
f()
finally
# Only restore if units_info is still temp_units_info.
# The user may have changed it in the function body, by e.g. removing the component
# and then attaching it to a different system.
internal.units_info === temp_units_info || error(
"Units info was modified during with_units_base.")
IS.set_units_info!(internal, old_units_info)
end
end
function get_units_setting(component::T) where {T <: Component}
return get_units_info(get_internal(component))
end
function has_units_setting(component::T) where {T <: Component}
return !isnothing(get_units_setting(component))
end
"""
Set the name of the system.
"""
set_name!(sys::System, name::AbstractString) = sys.metadata.name = name
"""
Get the name of the system.
"""
get_name(sys::System) = sys.metadata.name
"""
Set the description of the system.
"""
set_description!(sys::System, description::AbstractString) =
sys.metadata.description = description
"""
Get the description of the system.
"""
get_description(sys::System) = sys.metadata.description
"""
Add a component to the system.
A component cannot be added to more than one `System`.
Throws ArgumentError if the component's name is already stored for its concrete type.
Throws ArgumentError if any Component-specific rule is violated.
Throws InvalidValue if any of the component's field values are outside of defined valid
range.
# Examples
```julia
sys = System(100.0)
# Add a single component.
add_component!(sys, bus)
# Add many at once.
buses = [bus1, bus2, bus3]
generators = [gen1, gen2, gen3]
foreach(x -> add_component!(sys, x), Iterators.flatten((buses, generators)))
```
See also [`add_components!`](@ref).
"""
function add_component!(
sys::System,
component::T;
skip_validation = false,
kwargs...,
) where {T <: Component}
set_units_setting!(component, sys.units_settings)
@assert has_units_setting(component)
check_topology(sys, component)
check_component_addition(sys, component; kwargs...)
deserialization_in_progress = _is_deserialization_in_progress(sys)
if !deserialization_in_progress
# Services are attached to devices at deserialization time.
check_for_services_on_addition(sys, component)
end
skip_validation = _validate_or_skip!(sys, component, skip_validation)
_kwargs = Dict(k => v for (k, v) in kwargs if k !== :static_injector)
IS.add_component!(
sys.data,
component;
allow_existing_time_series = deserialization_in_progress,
skip_validation = skip_validation,
_kwargs...,
)
if !deserialization_in_progress
# Whatever this may change should have been validated above in
# check_component_addition, so this should not fail.
# Doesn't run at deserialization time because the changes made by this function
# occurred when the original addition ran and do not apply to that scenario.
handle_component_addition!(sys, component; kwargs...)
# Special condition required to populate the bus numbers in the system after
elseif component isa Bus
handle_component_addition!(sys, component; kwargs...)
end
return
end
"""
Add many components to the system at once.
A component cannot be added to more than one `System`.
Throws ArgumentError if the component's name is already stored for its concrete type.
Throws ArgumentError if any Component-specific rule is violated.
Throws InvalidValue if any of the component's field values are outside of defined valid
range.
# Examples
```julia
sys = System(100.0)
buses = [bus1, bus2, bus3]
generators = [gen1, gen2, gen3]
add_components!(sys, Iterators.flatten((buses, generators))
```
"""
function add_components!(sys::System, components)
foreach(x -> add_component!(sys, x), components)
return
end
"""
Add a dynamic injector to the system.
A component cannot be added to more than one `System`.
Throws ArgumentError if the name does not match the `static_injector` name.
Throws ArgumentError if the `static_injector` is not attached to the system.
All rules for the generic `add_component!` method also apply.
"""
function add_component!(
sys::System,
dyn_injector::DynamicInjection,
static_injector::StaticInjection;
kwargs...,
)
add_component!(sys, dyn_injector; static_injector = static_injector, kwargs...)
return
end
"""
Replace the dynamic injector in a static component.
Safely removes the old dynamic injector from the system if no other component references it.
If another component references the old dynamic injector, it is kept in the system and an
info message is logged.
Throws ArgumentError if the static injector is not attached to the system.
Throws ArgumentError if the static injector does not have a dynamic injector.
Throws ArgumentError if the new dynamic injector name does not match the static injector name.
"""
function replace_dynamic_injector!(
sys::System,
static_injector::StaticInjection,
new_dynamic_injector::DynamicInjection,
)
throw_if_not_attached(static_injector, sys)
old_dynamic_injector = get_dynamic_injector(static_injector)
if isnothing(old_dynamic_injector)
throw(
ArgumentError(
"$(get_name(static_injector)) does not have a dynamic injector to replace",
),
)
end
if get_name(new_dynamic_injector) != get_name(static_injector)
throw(
ArgumentError(
"new_dynamic_injector must have the same name as the static_injector",
),
)
end
# Unlink old dynamic injector from this static component
set_dynamic_injector!(static_injector, nothing)
# Check if any other static injector in the system references the old dynamic injector
is_referenced_elsewhere = false
for si in get_components(StaticInjection, sys)
si === static_injector && continue
dyn = get_dynamic_injector(si)
if dyn === old_dynamic_injector
is_referenced_elsewhere = true
break
end
end
if is_referenced_elsewhere
@info "The dynamic injector $(get_name(old_dynamic_injector)) is referenced by " *
"another component and will not be removed from the system."
else
# Safely remove old dynamic injector from the system
_handle_component_removal_common!(old_dynamic_injector)
IS.remove_component!(sys.data, old_dynamic_injector)
end
# Add the new dynamic injector, linked to the static component
add_component!(sys, new_dynamic_injector, static_injector)
return
end
function _add_service!(
sys::System,
service::Service,
contributing_devices;
skip_validation = false,
kwargs...,
)
skip_validation = _validate_or_skip!(sys, service, skip_validation)
for device in contributing_devices
device_type = typeof(device)
if !(device_type <: Device)
throw(ArgumentError("contributing_devices must be of type Device"))
end
throw_if_not_attached(device, sys)
end
set_units_setting!(service, sys.units_settings)
# Since this isn't atomic, order is important. Add to system before adding to devices.
IS.add_component!(sys.data, service; skip_validation = skip_validation, kwargs...)
for device in contributing_devices
add_service_internal!(device, service)
end
end
function _validate_types_for_interface(sys::System, contributing_devices)
device_types = Set{DataType}()
for device in contributing_devices
device_type = typeof(device)
if !(device_type <: Branch)
throw(ArgumentError("contributing_devices must be of type Branch"))
end
push!(device_types, device_type)
throw_if_not_attached(device, sys)
end
if length(device_types) > 1 && AreaInterchange in device_types
throw(
ArgumentError(
"contributing_devices can't mix AreaInterchange with other Branch types",
),
)
end
return
end
function _validate_types_for_agc(contributing_devices)
for device in contributing_devices
device_type = typeof(device)
if !(device_type <: Reserve)
throw(ArgumentError("contributing_devices of AGC must be of type Reserve"))
end
end
return
end
function _add_service!(
sys::System,
service::TransmissionInterface,
contributing_devices;
skip_validation = false,
kwargs...,
)
skip_validation = _validate_or_skip!(sys, service, skip_validation)
_validate_types_for_interface(sys, contributing_devices)
set_units_setting!(service, sys.units_settings)
# Since this isn't atomic, order is important. Add to system before adding to devices.
IS.add_component!(sys.data, service; skip_validation = skip_validation, kwargs...)
for device in contributing_devices
add_service_internal!(device, service)
end
end
function _add_service!(
sys::System,
service::AGC,
contributing_devices;
skip_validation = false,
kwargs...,
)
skip_validation = _validate_or_skip!(sys, service, skip_validation)
_validate_types_for_agc(contributing_devices)
set_units_setting!(service, sys.units_settings)
# Since this isn't atomic, order is important. Add to system before adding to devices.
IS.add_component!(sys.data, service; skip_validation = skip_validation, kwargs...)
for device in contributing_devices
add_service_internal!(service, device)
end
end
"""
Similar to [`add_component!`](@ref) but for services.
# Arguments
- `sys::System`: system
- `service::Service`: service to add
- `contributing_devices`: Must be an iterable of type Device
"""
function add_service!(sys::System, service::Service, contributing_devices; kwargs...)
_add_service!(sys, service, contributing_devices; kwargs...)
return
end
"""
Similar to [`add_component!`](@ref) but for services.
# Arguments
- `sys::System`: system
- `service::Service`: service to add
- `contributing_device::Device`: Valid Device
"""
function add_service!(sys::System, service::Service, contributing_device::Device; kwargs...)
_add_service!(sys, service, [contributing_device]; kwargs...)
return
end
"""
Similar to [`add_service!`](@ref) but for Service and Device already stored in the system.
Performs validation checks on the device and the system
# Arguments
- `device::Device`: Device
- `service::Service`: Service
- `sys::System`: system
"""
function add_service!(device::Device, service::Service, sys::System)
throw_if_not_attached(service, sys)
throw_if_not_attached(device, sys)
add_service_internal!(device, service)
return
end
"""
Similar to [`add_component!`](@ref) but for ConstantReserveGroup.
# Arguments
- `sys::System`: system
- `service::ConstantReserveGroup`: service to add
"""