-
Notifications
You must be signed in to change notification settings - Fork 81
/
base.jl
2630 lines (2294 loc) · 78.5 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,
: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 = "4.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`.
# Keyword arguments
- `ext::Dict`: Contains user-defined parameters. Should only contain standard types.
- `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.
- `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
- `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"`)
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; 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.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), 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
"""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)
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
bus_dict_gen = _parse_dyr_components(dyr_file)
add_dyn_injectors!(sys, bus_dict_gen)
return sys
end
"""
Construct a System from a subsystem of an existing system.
"""
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
"""
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
"""
Get the system's [unit base](@ref per_unit))
"""
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.
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 ACBus
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
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 ConstantReserveGroup.
# Arguments
- `sys::System`: system
- `service::ConstantReserveGroup`: service to add
"""
function add_service!(
sys::System,
service::ConstantReserveGroup;
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 ConstantReserveGroup contributing_services with check"""
function set_contributing_services!(
sys::System,
service::ConstantReserveGroup,
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 ConstantReserveGroup.
# Arguments
- `sys::System`: system
- `service::ConstantReserveGroup`: service to add
- `contributing_services`: contributing services to the group
"""
function add_service!(
sys::System,
service::ConstantReserveGroup,
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
"""
Open the time series store for bulk additions or reads
This is recommended before calling `add_time_series!` many times because of the overhead
associated with opening and closing an HDF5 file.
This is not necessary for an in-memory time series store.
# Examples
```julia
# Assume there is a system with an array of Components and SingleTimeSeries
# stored in the variables components and single_time_series, respectively
open_time_series_store!(sys, "r+") do
for (component, ts) in zip(components, single_time_series)
add_time_series!(sys, component, ts)
end
end
```
You can also use this function to make reads faster. Change the mode from `"r+"` to `"r"` to open
the file read-only.
See also: [`bulk_add_time_series!`](@ref)
"""
function open_time_series_store!(
func::Function,
sys::System,
mode = "r",
args...;
kwargs...,
)
IS.open_time_series_store!(func, sys.data, mode, args...; kwargs...)
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,
)
associations = TimeSeriesAssociation[]
IS.set_component!(file_metadata, data, PowerSystems)
component = file_metadata.component
if isnothing(component)
return associations
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{Base.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
)
file_metadata.component = _component
if !IS.has_assignment(cache, file_metadata)
IS.add_assignment!(cache, file_metadata)
push!(associations, TimeSeriesAssociation(_component, ts))
end
end
file_metadata.component = component
orig_sf = file_metadata.scaling_factor_multiplier
try
file_metadata.scaling_factor_multiplier = replace(orig_sf, "max" => "peak")
area_ts = IS.make_time_series!(cache, file_metadata)
IS.add_assignment!(cache, file_metadata)
push!(associations, TimeSeriesAssociation(component, area_ts))
finally
file_metadata.scaling_factor_multiplier = orig_sf
end
else
push!(associations, TimeSeriesAssociation(component, ts))
IS.add_assignment!(cache, file_metadata)
end
return associations
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)