-
Notifications
You must be signed in to change notification settings - Fork 70
/
base.jl
2083 lines (1810 loc) · 61 KB
/
base.jl
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((
:branch_name_formatter,
:bus_name_formatter,
:config_path,
:frequency,
:gen_name_formatter,
:generator_mapping,
:internal,
:load_name_formatter,
:load_zone_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 = "3.0.0"
mutable struct SystemMetadata <: IS.InfrastructureSystemsType
name::Union{Nothing, String}
description::Union{Nothing, String}
end
"""
System
A power system defined by fields for base_power, components, and time series.
```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 must be an iterable containing subtypes of Component.
# Keyword arguments
- `ext::Dict`: Contains user-defined parameters. Should only contain standard types.
- `runchecks::Bool`: Run available checks on input fields and when add_component! is called.
Throws InvalidValue if an error is found.
- `time_series_in_memory::Bool=false`: Store time series data in memory instead of HDF5.
- `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
"""
struct System <: IS.InfrastructureSystemsType
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{Int}()
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,
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), RenewableFix(nothing)],
loads = [PowerLoad(nothing)],
branches = nothing,
storage = nothing,
base_power::Float64 = 100.0,
services = nothing,
kwargs...,
)
_services = isnothing(services) ? [] : services
return System(base_power, buses, generators, loads, _services; 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.
"""
function System(file_path::AbstractString; assign_new_uuids = false, kwargs...)
ext = splitext(file_path)[2]
if lowercase(ext) in [".m", ".raw"]
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...)
elseif lowercase(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)
sys = deserialize(
System,
file_path;
time_series_read_only = time_series_read_only,
runchecks = runchecks,
time_series_directory = time_series_directory,
)
runchecks && check(sys)
if assign_new_uuids
IS.assign_new_uuid!(sys)
for component in get_components(Component, sys)
IS.assign_new_uuid!(component)
end
for component in
IS.get_masked_components(InfrastructureSystemsComponent, sys.data)
IS.assign_new_uuid!(component)
end
# Note: this does not change UUIDs for time series data because they are
# shared with components.
end
return sys
else
throw(DataFormatError("$file_path is not a supported file type"))
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
bus_dict_gen = _parse_dyr_components(dyr_file)
add_dyn_injectors!(sys, bus_dict_gen)
return sys
end
"""
Serializes a system to a JSON string.
# 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!(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)
resolution = get_time_series_resolution(sys).value
metadata = OrderedDict(
"name" => isnothing(name) ? "" : name,
"description" => isnothing(description) ? "" : description,
"frequency" => sys.frequency,
"time_series_resolution_milliseconds" => resolution,
"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
function Base.deepcopy(sys::System)
sys2 = Base.deepcopy_internal(sys, IdDict())
if sys.data.time_series_storage isa IS.InMemoryTimeSeriesStorage
return sys2
end
IS.copy_to_new_file!(sys2.data.time_series_storage, sys.time_series_directory)
return sys2
end
"""
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
"""
Sets the units base for the getter functions on the devices. It modifies the behavior of all getter functions
"""
function set_units_base_system!(system::System, settings::String)
set_units_base_system!(system::System, UNIT_SYSTEM_MAPPING[uppercase(settings)])
return
end
function set_units_base_system!(system::System, settings::UnitSystem)
if system.units_settings.unit_system != settings
system.units_settings.unit_system = settings
@info "Unit System changed to $settings"
end
return
end
function get_units_base(system::System)
return string(system.units_settings.unit_system)
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.
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)))
```
"""
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_attached_buses(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 ACBus
handle_component_addition!(sys, component; kwargs...)
end
return
end
"""
Add many components to the system at once.
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]
foreach(x -> add_component!(sys, x), 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.
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
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
"""
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 StaticReserveGroup.
# Arguments
- `sys::System`: system
- `service::StaticReserveGroup`: service to add
"""
function add_service!(
sys::System,
service::StaticReserveGroup;
skip_validation = false,
kwargs...,
)
skip_validation = _validate_or_skip!(sys, service, skip_validation)
for _service in get_contributing_services(service)
throw_if_not_attached(_service, sys)
end
set_units_setting!(service, sys.units_settings)
IS.add_component!(sys.data, service; skip_validation = skip_validation, kwargs...)
return
end
"""Set StaticReserveGroup contributing_services with check"""
function set_contributing_services!(
sys::System,
service::StaticReserveGroup,
val::Vector{<:Service},
)
for _service in val
throw_if_not_attached(_service, sys)
end
service.contributing_services = val
return
end
"""
Similar to [`add_component!`](@ref) but for StaticReserveGroup.
# Arguments
- `sys::System`: system
- `service::StaticReserveGroup`: service to add
- `contributing_services`: contributing services to the group
"""
function add_service!(
sys::System,
service::StaticReserveGroup,
contributing_services::Vector{<:Service};
skip_validation = false,
kwargs...,
)
skip_validation = _validate_or_skip!(sys, service, skip_validation)
set_contributing_services!(sys, service, contributing_services)
set_units_setting!(service, sys.units_settings)
IS.add_component!(sys.data, service; skip_validation = skip_validation, kwargs...)
return
end
"""
Add time series data from a metadata file or metadata descriptors.
# Arguments
- `sys::System`: system
- `metadata_file::AbstractString`: metadata file for timeseries
that includes an array of IS.TimeSeriesFileMetadata instances or a vector.
- `resolution::DateTime.Period=nothing`: skip time series that don't match this resolution.
"""
function add_time_series!(sys::System, metadata_file::AbstractString; resolution = nothing)
return IS.add_time_series_from_file_metadata!(
sys.data,
Component,
metadata_file;
resolution = resolution,
)
end
"""
Add time series data from a metadata file or metadata descriptors.
# Arguments
- `sys::System`: system
- `timeseries_metadata::Vector{IS.TimeSeriesFileMetadata}`: metadata for timeseries
- `resolution::DateTime.Period=nothing`: skip time series that don't match this resolution.
"""
function add_time_series!(
sys::System,
file_metadata::Vector{IS.TimeSeriesFileMetadata};
resolution = nothing,
)
return IS.add_time_series_from_file_metadata!(
sys.data,
Component,
file_metadata;
resolution = resolution,
)
end
function IS.add_time_series_from_file_metadata_internal!(
data::IS.SystemData,
::Type{<:Component},
cache::IS.TimeSeriesParsingCache,
file_metadata::IS.TimeSeriesFileMetadata,
)
IS.set_component!(file_metadata, data, PowerSystems)
component = file_metadata.component
if isnothing(component)
return
end
ts = IS.make_time_series!(cache, file_metadata)
if component isa AggregationTopology && file_metadata.scaling_factor_multiplier in
["get_max_active_power", "get_max_reactive_power"]
uuids = Set{UUIDs.UUID}()
for bus in _get_buses(data, component)
push!(uuids, IS.get_uuid(bus))
end
for _component in (
load for load in IS.get_components(ElectricLoad, data) if
IS.get_uuid(get_bus(load)) in uuids
)
IS.add_time_series!(data, _component, ts; skip_if_present = true)
end
file_metadata.scaling_factor_multiplier =
replace(file_metadata.scaling_factor_multiplier, "max" => "peak")
area_ts = IS.make_time_series!(cache, file_metadata)
IS.add_time_series!(data, component, area_ts; skip_if_present = true)
else
IS.add_time_series!(data, component, ts)
end
return
end
"""
Iterates over all components.
# Examples
```julia
for component in iterate_components(sys)
@show component
end
```
See also: [`get_components`](@ref)
"""
function iterate_components(sys::System)
return IS.iterate_components(sys.data)
end
"""
Remove all components from the system.
"""
function clear_components!(sys::System)
return IS.clear_components!(sys.data)
end
"""
Remove all components of type T from the system.
Throws ArgumentError if the type is not stored.
"""
# the argument order in this function is un-julian and should be deprecated in 2.0
function remove_components!(::Type{T}, sys::System) where {T <: Component}
return remove_components!(sys, T)
end
function remove_components!(sys::System, ::Type{T}) where {T <: Component}
components = IS.remove_components!(T, sys.data)
for component in components
handle_component_removal!(sys, component)
end
return components
end
function remove_components!(
filter_func::Function,
sys::System,
::Type{T},
) where {T <: Component}
components = collect(get_components(filter_func, T, sys))
for component in components
remove_component!(sys, component)
end
return components
end
"""
Set the name for a component that is attached to the system.
"""
set_name!(sys::System, component::Component, name::AbstractString) =
set_name!(sys.data, component, name)
"""
Set the name of a component.
Throws an exception if the component is attached to a system.
"""
function set_name!(component::Component, name::AbstractString)
# The units setting is nothing until the component is attached to the system.
if get_units_setting(component) !== nothing
# This is not allowed because components are stored in the system in a Dict
# keyed by name.
error(
"The component is attached to a system. " *
"Call set_name!(system, component, name) instead.",
)
end
component.name = name
end
function clear_units!(component::Component)
get_internal(component).units_info = nothing
return
end
"""
Remove a component from the system by its value.
Throws ArgumentError if the component is not stored.
"""
function remove_component!(sys::System, component::T) where {T <: Component}
check_component_removal(sys, component)
IS.remove_component!(sys.data, component)
handle_component_removal!(sys, component)
return
end
"""
Throws ArgumentError if a PowerSystems rule blocks removal from the system.
"""
function check_component_removal(sys::System, service::T) where {T <: Service}
if T == StaticReserveGroup
return
end
groupservices = get_components(StaticReserveGroup, sys)
for groupservice in groupservices
if service ∈ get_contributing_services(groupservice)
throw(
ArgumentError(
"service $(get_name(service)) cannot be removed with an attached StaticReserveGroup",
),
)
return
end
end
end
"""
Remove a component from the system by its name.
Throws ArgumentError if the component is not stored.
"""
function remove_component!(
::Type{T},
sys::System,
name::AbstractString,
) where {T <: Component}
component = IS.remove_component!(T, sys.data, name)
handle_component_removal!(sys, component)
return
end
"""
Check to see if the component of type T with name exists.
"""
function has_component(::Type{T}, sys::System, name::AbstractString) where {T <: Component}
return IS.has_component(T, sys.data.components, name)
end
"""
Get the component of type T with name. Returns nothing if no component matches. If T is an abstract
type then the names of components across all subtypes of T must be unique.
See [`get_components_by_name`](@ref) for abstract types with non-unique names across subtypes.
Throws ArgumentError if T is not a concrete type and there is more than one component with
requested name
"""
function get_component(::Type{T}, sys::System, name::AbstractString) where {T <: Component}
return IS.get_component(T, sys.data, name)
end
"""
Returns an iterator of components. T can be concrete or abstract.
Call collect on the result if an array is desired.
# Examples
```julia
iter = PowerSystems.get_components(ThermalStandard, sys)
iter = PowerSystems.get_components(Generator, sys)
iter = PowerSystems.get_components(x -> PowerSystems.get_available(x), Generator, sys)
thermal_gens = get_components(ThermalStandard, sys) do gen
get_available(gen)
end
generators = collect(PowerSystems.get_components(Generator, sys))
```
See also: [`iterate_components`](@ref)
"""
function get_components(::Type{T}, sys::System) where {T <: Component}
return IS.get_components(T, sys.data, nothing)
end
function get_components(
filter_func::Function,
::Type{T},
sys::System,
) where {T <: Component}
return IS.get_components(T, sys.data, filter_func)
end
# These are helper functions for debugging problems.
# Searches components linearly, and so is slow compared to the other get_component functions
get_component(sys::System, uuid::Base.UUID) = IS.get_component(sys.data, uuid)
get_component(sys::System, uuid::String) = IS.get_component(sys.data, Base.UUID(uuid))
function _get_components_by_name(abstract_types, data::IS.SystemData, name::AbstractString)
_components = []
for subtype in abstract_types
component = IS.get_component(subtype, data, name)
if !isnothing(component)
push!(_components, component)
end
end
return _components
end
"""
Get the components of abstract type T with name. Note that PowerSystems enforces unique
names on each concrete type but not across concrete types.
See [`get_component`](@ref) if the concrete type is known.
Throws ArgumentError if T is not an abstract type.
"""
function get_components_by_name(
::Type{T},
sys::System,
name::AbstractString,
) where {T <: Component}
return IS.get_components_by_name(T, sys.data, name)
end
"""
Gets components availability. Requires type T to have the method get_available implemented.
"""
function get_available_components(::Type{T}, sys::System) where {T <: Component}
return get_components(x -> get_available(x), T, sys)
end
"""
Return true if the component is attached to the system.
"""
function is_attached(component::T, sys::System) where {T <: Component}
return is_attached(T, get_name(component), sys)
end
function is_attached(::Type{T}, name, sys::System) where {T <: Component}
return !isnothing(get_component(T, sys, name))
end
"""
Throws ArgumentError if the component is not attached to the system.
"""
function throw_if_not_attached(component::Component, sys::System)
if !is_attached(component, sys)
throw(ArgumentError("$(summary(component)) is not attached to the system"))
end
end
"""
Return a vector of devices contributing to the service.
"""
function get_contributing_devices(sys::System, service::T) where {T <: Service}
throw_if_not_attached(service, sys)
return [x for x in get_components(Device, sys) if has_service(x, service)]
end
struct ServiceContributingDevices
service::Service
contributing_devices::Vector{Device}
end
const ServiceContributingDevicesKey = NamedTuple{(:type, :name), Tuple{DataType, String}}
const ServiceContributingDevicesMapping =
Dict{ServiceContributingDevicesKey, ServiceContributingDevices}
"""
Returns a ServiceContributingDevices object.
"""
function _get_contributing_devices(sys::System, service::T) where {T <: Service}
uuid = IS.get_uuid(service)
devices = ServiceContributingDevices(service, Vector{Device}())