1use std::ffi::c_char;
30use std::panic::{AssertUnwindSafe, catch_unwind};
31use std::path::PathBuf;
32use std::sync::Arc;
33
34use powerio::{
35 BalancedNetwork, Destination, Diagnostic, EmitResult, EmittedOutput, PioScenarioSet,
36 PioTimeSeries, PioValue, Source,
37};
38use powerio_core::{ComponentId, HistoryEntry, HistoryId, HistoryKind, Producer};
39use powerio_matrix::{
40 AcOpfAssemblyOptions, AcOpfPreparation, AnalysisBranchSource, DcOperatorOptions, DcOperators,
41 DcOpfAssemblyOptions, DcOpfPreparation, IndexedNetwork, PreparedObjective, SensitivityOptions,
42 SensitivitySolver, SparseMatrix, Units, build_ac_opf_preparation, build_dc_opf_preparation,
43 calc_ptdf_lodf_with_options,
44};
45use powerio_prob::{
46 ActivePower, ActivePowerUnit, ApparentPower, ApparentPowerUnit, CalculationUpdate,
47 DcPfInstance, LoadAllocation, NetworkUpdate, OperatingPointUpdate, ReactivePower,
48 ReactivePowerUnit, UpdateChange, UpdatedField, apply_bus_load_active_power, apply_updates,
49};
50use powerio_tx::BranchSusceptanceFormula;
51
52use crate::diagnostics::codes;
53
54pub mod diagnostics;
55
56#[cfg(test)]
57mod parse_options_tests;
58
59pub const PIO_VERSION_MAJOR: u32 = 0;
67
68pub const PIO_VERSION_MINOR: u32 = 12;
70
71pub const PIO_VERSION_PATCH: u32 = 4;
73
74#[repr(C)]
78#[derive(Clone, Copy)]
79pub struct PioStringView {
80 pub data: *const c_char,
81 pub len: usize,
82}
83
84impl PioStringView {
85 const EMPTY: Self = Self {
86 data: std::ptr::null(),
87 len: 0,
88 };
89
90 fn new(text: &str) -> Self {
91 Self {
92 data: text.as_ptr().cast(),
93 len: text.len(),
94 }
95 }
96}
97
98#[repr(C)]
100#[derive(Clone, Copy)]
101pub struct PioVersionView {
102 pub major: u32,
103 pub minor: u32,
104 pub patch: u32,
105}
106
107#[repr(C)]
109#[derive(Clone, Copy)]
110pub struct PioDiagnosticSpanView {
111 pub source: PioStringView,
112 pub byte_start: u64,
113 pub byte_end: u64,
114}
115
116#[repr(C)]
118#[derive(Clone, Copy)]
119pub struct PioModuleProducerView {
120 pub name: PioStringView,
121 pub version: PioStringView,
122}
123
124#[repr(C)]
126#[derive(Clone, Copy)]
127pub struct PioModuleSourceView {
128 pub id: PioStringView,
129 pub name: PioStringView,
130 pub byte_length: u64,
131 pub format: PioStringView,
132 pub has_format: bool,
133 pub digest_algorithm: PioStringView,
134 pub digest: PioStringView,
135 pub has_digest: bool,
136}
137
138#[repr(C)]
140#[derive(Clone, Copy)]
141pub struct PioSourceSpanView {
142 pub source: PioStringView,
143 pub byte_start: u64,
144 pub byte_end: u64,
145}
146
147#[repr(C)]
149#[derive(Clone, Copy)]
150pub struct PioModuleSourceMapEntryView {
151 pub target: PioStringView,
152 pub relation: PioStringView,
153 pub span_count: usize,
154}
155
156#[repr(C)]
158#[derive(Clone, Copy)]
159pub struct PioModuleHistoryEntryView {
160 pub id: PioStringView,
161 pub kind: PioStringView,
162 pub name: PioStringView,
163 pub input_type: PioStringView,
164 pub has_input_type: bool,
165 pub output_type: PioStringView,
166 pub has_output_type: bool,
167 pub parameter_count: usize,
168 pub assumption_count: usize,
169 pub loss_count: usize,
170}
171
172#[repr(C)]
174#[derive(Clone, Copy)]
175pub struct PioModuleHistoryParameterView {
176 pub name: PioStringView,
177 pub value_kind: PioStringView,
178}
179
180#[repr(C)]
182#[derive(Clone, Copy)]
183pub struct PioModuleExtensionView {
184 pub namespace: PioStringView,
185 pub value_kind: PioStringView,
186}
187
188#[repr(C)]
190#[derive(Clone, Copy)]
191pub struct PioJsonValueView {
192 pub kind: PioStringView,
193 pub boolean_value: bool,
194 pub number_kind: PioStringView,
195 pub signed_integer_value: i64,
196 pub unsigned_integer_value: u64,
197 pub floating_point_value: f64,
198 pub string_value: PioStringView,
199 pub element_count: usize,
200}
201
202#[repr(C)]
204#[derive(Clone, Copy)]
205pub struct PioJsonObjectEntryView {
206 pub key: PioStringView,
207 pub value_kind: PioStringView,
208}
209
210#[repr(C)]
212#[derive(Clone, Copy)]
213pub struct PioByteView {
214 pub data: *const u8,
215 pub len: usize,
216}
217
218impl PioByteView {
219 const EMPTY: Self = Self {
220 data: std::ptr::null(),
221 len: 0,
222 };
223
224 fn new(bytes: &[u8]) -> Self {
225 Self {
226 data: bytes.as_ptr(),
227 len: bytes.len(),
228 }
229 }
230}
231
232#[repr(C)]
235#[derive(Clone, Copy)]
236pub struct PioNamedBufferView {
237 pub name: PioStringView,
238 pub bytes: PioByteView,
239}
240
241#[repr(C)]
245#[derive(Clone, Copy)]
246pub struct PioSincalReadOptions {
247 pub has_variant: bool,
248 pub variant: i64,
249 pub has_snapshot_hours: bool,
250 pub snapshot_hours: f64,
251 pub acquired_tables: PioStringView,
253 pub assume_inactive_source_controls: bool,
255}
256
257#[repr(C)]
259#[derive(Clone, Copy)]
260pub struct PioSincalBalancedReadOptions {
261 pub has_variant: bool,
262 pub variant: i64,
263 pub has_snapshot_hours: bool,
264 pub snapshot_hours: f64,
265 pub acquired_tables: PioStringView,
266}
267
268#[repr(C)]
272#[derive(Clone, Copy)]
273pub struct PioParseOptions {
274 pub acquisition_root: PioStringView,
276 pub sincal_multiconductor: *const PioSincalReadOptions,
278 pub sincal_balanced: *const PioSincalBalancedReadOptions,
280}
281
282#[repr(C)]
284#[derive(Clone, Copy)]
285pub struct PioF64View {
286 pub data: *const f64,
287 pub len: usize,
288}
289
290impl PioF64View {
291 const EMPTY: Self = Self {
292 data: std::ptr::null(),
293 len: 0,
294 };
295
296 fn new(values: &[f64]) -> Self {
297 Self {
298 data: values.as_ptr(),
299 len: values.len(),
300 }
301 }
302}
303
304#[repr(C)]
306#[derive(Clone, Copy)]
307pub struct PioSizeView {
308 pub data: *const usize,
309 pub len: usize,
310}
311
312impl PioSizeView {
313 const EMPTY: Self = Self {
314 data: std::ptr::null(),
315 len: 0,
316 };
317
318 fn new(values: &[usize]) -> Self {
319 Self {
320 data: values.as_ptr(),
321 len: values.len(),
322 }
323 }
324}
325
326#[repr(C)]
328#[derive(Clone, Copy)]
329pub struct PioBalancedLocationView {
330 pub x: f64,
331 pub y: f64,
332 pub kind: PioStringView,
333 pub has_kind: bool,
334}
335
336#[repr(C)]
338#[derive(Clone, Copy)]
339pub struct PioBalancedGeoView {
340 pub has_geo: bool,
341 pub space: PioStringView,
342 pub crs: PioStringView,
343 pub has_crs: bool,
344 pub kind: PioStringView,
345 pub has_kind: bool,
346 pub has_canvas: bool,
347 pub canvas_width: f64,
348 pub has_canvas_width: bool,
349 pub canvas_height: f64,
350 pub has_canvas_height: bool,
351 pub canvas_units: PioStringView,
352 pub has_canvas_units: bool,
353}
354
355#[repr(C)]
357#[derive(Clone, Copy)]
358pub struct PioBalancedBusView {
359 pub component_id: PioStringView,
360 pub has_component_id: bool,
361 pub id: usize,
362 pub bus_type: PioStringView,
363 pub vm_pu: f64,
364 pub va_degrees: f64,
365 pub base_kv: f64,
366 pub vmax_pu: f64,
367 pub vmin_pu: f64,
368 pub has_emergency_voltage_limits: bool,
369 pub emergency_vmax_pu: f64,
370 pub emergency_vmin_pu: f64,
371 pub area: usize,
372 pub zone: usize,
373 pub name: PioStringView,
374 pub has_name: bool,
375 pub location: PioBalancedLocationView,
376 pub has_location: bool,
377}
378
379#[repr(C)]
381#[derive(Clone, Copy)]
382pub struct PioBalancedLoadVoltageModelView {
383 pub kind: PioStringView,
384 pub p_constant_power_mw: f64,
385 pub q_constant_power_mvar: f64,
386 pub p_constant_current_mw: f64,
387 pub q_constant_current_mvar: f64,
388 pub p_constant_impedance_mw: f64,
389 pub q_constant_impedance_mvar: f64,
390 pub exponential_p_mw: f64,
391 pub exponential_q_mvar: f64,
392 pub gamma_p: f64,
393 pub gamma_q: f64,
394 pub nominal_voltage_pu: f64,
395 pub has_nominal_voltage: bool,
396 pub load_type: i32,
397 pub has_load_type: bool,
398 pub scaling: f64,
399 pub has_scaling: bool,
400}
401
402#[repr(C)]
404#[derive(Clone, Copy)]
405pub struct PioBalancedLoadView {
406 pub component_id: PioStringView,
407 pub has_component_id: bool,
408 pub bus_id: usize,
409 pub p_mw: f64,
410 pub q_mvar: f64,
411 pub in_service: bool,
412 pub voltage_model: PioBalancedLoadVoltageModelView,
413}
414
415#[repr(C)]
417#[derive(Clone, Copy)]
418pub struct PioShuntBlockView {
419 pub steps: u32,
420 pub conductance_mw: f64,
421 pub susceptance_mvar: f64,
422}
423
424#[repr(C)]
426#[derive(Clone, Copy)]
427pub struct PioBalancedShuntView {
428 pub component_id: PioStringView,
429 pub has_component_id: bool,
430 pub bus_id: usize,
431 pub conductance_mw: f64,
432 pub susceptance_mvar: f64,
433 pub in_service: bool,
434 pub section_count: u32,
435 pub has_section_count: bool,
436 pub has_control: bool,
437 pub control_mode: PioStringView,
438 pub control_vmax_pu: f64,
439 pub control_vmin_pu: f64,
440 pub control_bus_id: usize,
441 pub has_control_bus: bool,
442 pub control_reactive_range_percent: f64,
443 pub control_block_count: usize,
444}
445
446#[repr(C)]
448#[derive(Clone, Copy)]
449pub struct PioBranchRatingView {
450 pub name: PioStringView,
451 pub rate_mva: f64,
452}
453
454#[repr(C)]
456#[derive(Clone, Copy)]
457pub struct PioBalancedBranchView {
458 pub component_id: PioStringView,
459 pub has_component_id: bool,
460 pub name: PioStringView,
461 pub has_name: bool,
462 pub from_bus_id: usize,
463 pub to_bus_id: usize,
464 pub resistance_pu: f64,
465 pub reactance_pu: f64,
466 pub total_charging_susceptance_pu: f64,
467 pub terminal_charging_is_explicit: bool,
468 pub from_conductance_pu: f64,
469 pub from_susceptance_pu: f64,
470 pub to_conductance_pu: f64,
471 pub to_susceptance_pu: f64,
472 pub rate_a_mva: f64,
473 pub rate_b_mva: f64,
474 pub rate_c_mva: f64,
475 pub additional_rating_count: usize,
476 pub has_current_ratings: bool,
477 pub current_rating_a: f64,
478 pub current_rating_b: f64,
479 pub current_rating_c: f64,
480 pub tap_ratio: f64,
481 pub effective_tap_ratio: f64,
482 pub phase_shift_degrees: f64,
483 pub in_service: bool,
484 pub angle_min_degrees: f64,
485 pub angle_max_degrees: f64,
486 pub control: PioTransformerControlView,
487 pub has_control: bool,
488 pub route_point_count: usize,
489 pub has_route: bool,
490}
491
492#[repr(C)]
494#[derive(Clone, Copy)]
495pub struct PioGeneratorCostView {
496 pub model: u8,
497 pub startup: f64,
498 pub shutdown: f64,
499 pub ncost: usize,
500 pub coefficients: PioF64View,
501}
502
503#[repr(C)]
505#[derive(Clone, Copy)]
506pub struct PioGeneratorCapabilityView {
507 pub name: PioStringView,
508 pub value: f64,
509 pub has_value: bool,
510}
511
512#[repr(C)]
514#[derive(Clone, Copy)]
515pub struct PioActivePowerControlView {
516 pub participate: bool,
517 pub droop_percent: f64,
518 pub has_droop_percent: bool,
519 pub participation_factor: f64,
520 pub has_participation_factor: bool,
521 pub minimum_target_active_power_mw: f64,
522 pub has_minimum_target_active_power: bool,
523 pub maximum_target_active_power_mw: f64,
524 pub has_maximum_target_active_power: bool,
525}
526
527#[repr(C)]
529#[derive(Clone, Copy)]
530pub struct PioBalancedGeneratorView {
531 pub component_id: PioStringView,
532 pub has_component_id: bool,
533 pub bus_id: usize,
534 pub energy_source: PioStringView,
535 pub active_power_mw: f64,
536 pub reactive_power_mvar: f64,
537 pub active_power_max_mw: f64,
538 pub active_power_min_mw: f64,
539 pub reactive_power_max_mvar: f64,
540 pub reactive_power_min_mvar: f64,
541 pub voltage_setpoint_pu: f64,
542 pub machine_base_mva: f64,
543 pub in_service: bool,
544 pub has_cost: bool,
545 pub cost: PioGeneratorCostView,
546 pub regulated_bus_id: usize,
547 pub has_regulated_bus: bool,
548 pub capability_count: usize,
549 pub active_power_control: PioActivePowerControlView,
550 pub has_active_power_control: bool,
551 pub voltage_regulation_on: bool,
552 pub regulating_terminal: PioTerminalReferenceView,
553 pub has_regulating_terminal: bool,
554}
555
556#[repr(C)]
558#[derive(Clone, Copy)]
559pub struct PioBalancedStorageView {
560 pub component_id: PioStringView,
561 pub has_component_id: bool,
562 pub bus_id: usize,
563 pub active_power_mw: f64,
564 pub reactive_power_mvar: f64,
565 pub energy_mwh: f64,
566 pub energy_rating_mwh: f64,
567 pub charge_rating_mw: f64,
568 pub discharge_rating_mw: f64,
569 pub charge_efficiency: f64,
570 pub discharge_efficiency: f64,
571 pub thermal_rating_mva: f64,
572 pub current_rating: f64,
573 pub has_current_rating: bool,
574 pub reactive_power_min_mvar: f64,
575 pub reactive_power_max_mvar: f64,
576 pub resistance_pu: f64,
577 pub reactance_pu: f64,
578 pub active_power_loss_mw: f64,
579 pub reactive_power_loss_mvar: f64,
580 pub in_service: bool,
581 pub active_power_control: PioActivePowerControlView,
582 pub has_active_power_control: bool,
583}
584
585#[repr(C)]
587#[derive(Clone, Copy)]
588pub struct PioTerminalReferenceView {
589 pub equipment: PioComponentIdView,
590 pub terminal: u8,
591}
592
593#[repr(C)]
595#[derive(Clone, Copy)]
596pub struct PioTransformerControlView {
597 pub mode: PioStringView,
598 pub enabled: bool,
599 pub controlled_bus_id: usize,
600 pub has_controlled_bus: bool,
601 pub controlled_bus_on_winding_side: bool,
602 pub regulating_terminal: PioTerminalReferenceView,
603 pub has_regulating_terminal: bool,
604 pub tap_min: f64,
605 pub tap_max: f64,
606 pub band_min: f64,
607 pub band_max: f64,
608 pub tap_position_count: u32,
609 pub mva_base: f64,
610 pub winding_connection_angle: f64,
611 pub has_winding_connection_angle: bool,
612}
613
614#[repr(C)]
616#[derive(Clone, Copy)]
617pub struct PioBalancedStaticVarCompensatorView {
618 pub component_id: PioStringView,
619 pub has_component_id: bool,
620 pub bus_id: usize,
621 pub minimum_susceptance_siemens: f64,
622 pub maximum_susceptance_siemens: f64,
623 pub voltage_setpoint_kv: f64,
624 pub reactive_power_setpoint_mvar: f64,
625 pub regulation_mode: PioStringView,
626 pub regulating: bool,
627 pub regulating_terminal: PioTerminalReferenceView,
628 pub has_regulating_terminal: bool,
629 pub active_power_mw: f64,
630 pub reactive_power_mvar: f64,
631 pub in_service: bool,
632}
633
634#[repr(C)]
636#[derive(Clone, Copy)]
637pub struct PioBalancedSwitchView {
638 pub component_id: PioStringView,
639 pub has_component_id: bool,
640 pub from_bus_id: usize,
641 pub to_bus_id: usize,
642 pub closed: bool,
643 pub thermal_rating_mva: f64,
644 pub has_thermal_rating: bool,
645 pub current_rating_a: f64,
646 pub has_current_rating: bool,
647 pub from_active_power_mw: f64,
648 pub has_from_active_power: bool,
649 pub from_reactive_power_mvar: f64,
650 pub has_from_reactive_power: bool,
651 pub to_active_power_mw: f64,
652 pub has_to_active_power: bool,
653 pub to_reactive_power_mvar: f64,
654 pub has_to_reactive_power: bool,
655}
656
657#[repr(C)]
659#[derive(Clone, Copy)]
660pub struct PioBalancedHvdcConverterView {
661 pub component: PioComponentIdView,
662 pub kind: PioStringView,
663 pub loss_factor_percent: f64,
664 pub voltage_regulator_on: bool,
665 pub has_voltage_regulator_on: bool,
666 pub voltage_setpoint_kv: f64,
667 pub has_voltage_setpoint: bool,
668 pub reactive_power_setpoint_mvar: f64,
669 pub has_reactive_power_setpoint: bool,
670 pub power_factor: f64,
671 pub has_power_factor: bool,
672 pub regulating_terminal: PioTerminalReferenceView,
673 pub has_regulating_terminal: bool,
674}
675
676#[repr(C)]
678#[derive(Clone, Copy)]
679pub struct PioBalancedHvdcView {
680 pub component_id: PioStringView,
681 pub has_component_id: bool,
682 pub from_bus_id: usize,
683 pub to_bus_id: usize,
684 pub in_service: bool,
685 pub from_active_power_mw: f64,
686 pub to_active_power_mw: f64,
687 pub from_reactive_power_mvar: f64,
688 pub to_reactive_power_mvar: f64,
689 pub from_voltage_pu: f64,
690 pub to_voltage_pu: f64,
691 pub minimum_active_power_mw: f64,
692 pub maximum_active_power_mw: f64,
693 pub minimum_from_reactive_power_mvar: f64,
694 pub maximum_from_reactive_power_mvar: f64,
695 pub minimum_to_reactive_power_mvar: f64,
696 pub maximum_to_reactive_power_mvar: f64,
697 pub constant_loss_mw: f64,
698 pub proportional_loss: f64,
699 pub resistance_ohm: f64,
700 pub has_resistance: bool,
701 pub nominal_voltage_kv: f64,
702 pub has_nominal_voltage: bool,
703 pub converters_mode: PioStringView,
704 pub has_converters_mode: bool,
705 pub converter1: PioBalancedHvdcConverterView,
706 pub has_converter1: bool,
707 pub converter2: PioBalancedHvdcConverterView,
708 pub has_converter2: bool,
709 pub cost: PioGeneratorCostView,
710 pub has_cost: bool,
711}
712
713#[repr(C)]
715#[derive(Clone, Copy)]
716pub struct PioThreeWindingTransformerWindingView {
717 pub bus_id: usize,
718 pub tap_ratio: f64,
719 pub phase_shift_degrees: f64,
720 pub nominal_voltage_kv: f64,
721 pub rating_a_mva: f64,
722 pub rating_b_mva: f64,
723 pub rating_c_mva: f64,
724 pub control: PioTransformerControlView,
725 pub has_control: bool,
726}
727
728#[repr(C)]
730#[derive(Clone, Copy)]
731pub struct PioThreeWindingTransformerImpedanceView {
732 pub resistance_pu: f64,
733 pub reactance_pu: f64,
734 pub base_mva: f64,
735}
736
737#[repr(C)]
739#[derive(Clone, Copy)]
740pub struct PioBalancedThreeWindingTransformerView {
741 pub component_id: PioStringView,
742 pub has_component_id: bool,
743 pub name: PioStringView,
744 pub has_name: bool,
745 pub winding_count: usize,
746 pub impedance_count: usize,
747 pub star_voltage_magnitude_pu: f64,
748 pub star_voltage_angle_degrees: f64,
749 pub magnetizing_conductance_pu: f64,
750 pub magnetizing_susceptance_pu: f64,
751 pub in_service: bool,
752 pub magnetizing_connection: PioStringView,
756}
757
758#[repr(C)]
760#[derive(Clone, Copy)]
761pub struct PioBalancedAreaView {
762 pub number: usize,
763 pub slack_bus_id: usize,
764 pub has_slack_bus: bool,
765 pub net_interchange_mw: f64,
766 pub tolerance_mw: f64,
767 pub name: PioStringView,
768 pub has_name: bool,
769 pub component_id: PioStringView,
770 pub has_component_id: bool,
771 pub area_type: PioStringView,
772 pub has_area_type: bool,
773}
774
775#[repr(C)]
777#[derive(Clone, Copy)]
778pub struct PioDetailedConnectivityCountsView {
779 pub omitted_fields: usize,
780 pub component_metadata: usize,
781 pub subnetworks: usize,
782 pub substations: usize,
783 pub voltage_levels: usize,
784 pub bus_breaker_buses: usize,
785 pub calculated_buses: usize,
786 pub connectivity_nodes: usize,
787 pub busbar_sections: usize,
788 pub junctions: usize,
789 pub terminals: usize,
790 pub switches: usize,
791 pub internal_connections: usize,
792 pub operational_limit_groups: usize,
793 pub tap_changers: usize,
794 pub equipment_reactive_limits: usize,
795 pub boundary_lines: usize,
796 pub tie_lines: usize,
797 pub dc_converter_units: usize,
798 pub dc_topological_nodes: usize,
799 pub dc_nodes: usize,
800 pub dc_grounds: usize,
801 pub dc_busbars: usize,
802 pub dc_lines: usize,
803 pub dc_series_devices: usize,
804 pub dc_switches: usize,
805 pub voltage_source_converters: usize,
806 pub line_commutated_converters: usize,
807}
808
809#[repr(C)]
811#[derive(Clone, Copy)]
812pub struct PioOmittedFieldView {
813 pub component: PioComponentIdView,
814 pub field: PioStringView,
815}
816
817#[repr(C)]
819#[derive(Clone, Copy)]
820pub struct PioEquipmentReactiveLimitsView {
821 pub equipment: PioComponentIdView,
822 pub limits: PioReactiveLimitsView,
823}
824
825#[repr(C)]
827#[derive(Clone, Copy)]
828pub struct PioCaseMetadataView {
829 pub case_date: PioStringView,
830 pub has_case_date: bool,
831 pub forecast_distance: i32,
832 pub has_forecast_distance: bool,
833 pub source_model_format: PioStringView,
834 pub has_source_model_format: bool,
835 pub minimum_validation_level: PioStringView,
836 pub has_minimum_validation_level: bool,
837}
838
839#[repr(C)]
841#[derive(Clone, Copy)]
842pub struct PioSubnetworkView {
843 pub component: PioComponentIdView,
844 pub parent: PioComponentIdView,
845 pub case_metadata: PioCaseMetadataView,
846 pub component_count: usize,
847}
848
849#[repr(C)]
851#[derive(Clone, Copy)]
852pub struct PioReactiveCapabilityCurvePointView {
853 pub active_power_mw: f64,
854 pub minimum_reactive_power_mvar: f64,
855 pub maximum_reactive_power_mvar: f64,
856 pub property_count: usize,
857}
858
859#[repr(C)]
861#[derive(Clone, Copy)]
862pub struct PioReactiveLimitsView {
863 pub kind: PioStringView,
864 pub minimum_reactive_power_mvar: f64,
865 pub maximum_reactive_power_mvar: f64,
866 pub has_minimum_and_maximum: bool,
867 pub curve_style: PioStringView,
868 pub has_curve_style: bool,
869 pub property_count: usize,
870 pub point_count: usize,
871}
872
873#[repr(C)]
875#[derive(Clone, Copy)]
876pub struct PioBoundaryLineGenerationView {
877 pub voltage_regulation_on: bool,
878 pub minimum_active_power_mw: f64,
879 pub has_minimum_active_power: bool,
880 pub maximum_active_power_mw: f64,
881 pub has_maximum_active_power: bool,
882 pub target_active_power_mw: f64,
883 pub has_target_active_power: bool,
884 pub target_reactive_power_mvar: f64,
885 pub has_target_reactive_power: bool,
886 pub target_voltage_kv: f64,
887 pub has_target_voltage: bool,
888 pub reactive_limits: PioReactiveLimitsView,
889 pub has_reactive_limits: bool,
890}
891
892#[repr(C)]
894#[derive(Clone, Copy)]
895pub struct PioBoundaryLineView {
896 pub component: PioComponentIdView,
897 pub voltage_level: PioComponentIdView,
898 pub active_power_setpoint_mw: f64,
899 pub reactive_power_setpoint_mvar: f64,
900 pub resistance_ohm: f64,
901 pub reactance_ohm: f64,
902 pub conductance_siemens: f64,
903 pub susceptance_siemens: f64,
904 pub pairing_key: PioStringView,
905 pub has_pairing_key: bool,
906 pub generation: PioBoundaryLineGenerationView,
907 pub has_generation: bool,
908 pub calculation_load: PioComponentIdView,
909 pub has_calculation_load: bool,
910 pub calculation_generator: PioComponentIdView,
911 pub has_calculation_generator: bool,
912}
913
914#[repr(C)]
916#[derive(Clone, Copy)]
917pub struct PioTieLineView {
918 pub component: PioComponentIdView,
919 pub boundary_line1: PioComponentIdView,
920 pub boundary_line2: PioComponentIdView,
921 pub calculation_branch: PioComponentIdView,
922 pub has_calculation_branch: bool,
923}
924
925#[repr(C)]
927#[derive(Clone, Copy)]
928pub struct PioComponentMetadataView {
929 pub component: PioComponentIdView,
930 pub name: PioStringView,
931 pub has_name: bool,
932 pub equipment_container: PioComponentIdView,
933 pub has_equipment_container: bool,
934 pub fictitious: bool,
935 pub alias_count: usize,
936 pub external_identifier_count: usize,
937 pub property_count: usize,
938}
939
940#[repr(C)]
942#[derive(Clone, Copy)]
943pub struct PioComponentAliasView {
944 pub value: PioStringView,
945 pub alias_type: PioStringView,
946 pub has_alias_type: bool,
947}
948
949#[repr(C)]
951#[derive(Clone, Copy)]
952pub struct PioExternalIdentifierView {
953 pub value: PioStringView,
954 pub authority: PioStringView,
955 pub has_authority: bool,
956}
957
958#[repr(C)]
960#[derive(Clone, Copy)]
961pub struct PioStringPropertyView {
962 pub name: PioStringView,
963 pub value: PioStringView,
964}
965
966#[repr(C)]
968#[derive(Clone, Copy)]
969pub struct PioSubstationView {
970 pub component: PioComponentIdView,
971 pub country: PioStringView,
972 pub has_country: bool,
973 pub operator_name: PioStringView,
974 pub has_operator_name: bool,
975 pub geographical_tag_count: usize,
976}
977
978#[repr(C)]
980#[derive(Clone, Copy)]
981pub struct PioVoltageLevelView {
982 pub component: PioComponentIdView,
983 pub substation: PioComponentIdView,
984 pub has_substation: bool,
985 pub nominal_voltage_kv: f64,
986 pub low_voltage_limit_kv: f64,
987 pub has_low_voltage_limit: bool,
988 pub high_voltage_limit_kv: f64,
989 pub has_high_voltage_limit: bool,
990 pub topology_kind: PioStringView,
991 pub bus_count: usize,
992}
993
994#[repr(C)]
996#[derive(Clone, Copy)]
997pub struct PioConnectivityNodeView {
998 pub component: PioComponentIdView,
999 pub voltage_level: PioComponentIdView,
1000 pub node_number: i32,
1001 pub has_node_number: bool,
1002 pub calculated_bus_id: usize,
1003 pub has_calculated_bus: bool,
1004}
1005
1006#[repr(C)]
1008#[derive(Clone, Copy)]
1009pub struct PioBusBreakerBusView {
1010 pub component: PioComponentIdView,
1011 pub voltage_level: PioComponentIdView,
1012 pub calculated_bus_id: usize,
1013 pub has_calculated_bus: bool,
1014 pub voltage_kv: f64,
1015 pub has_voltage: bool,
1016 pub angle_degrees: f64,
1017 pub has_angle: bool,
1018}
1019
1020#[repr(C)]
1022#[derive(Clone, Copy)]
1023pub struct PioCalculatedBusView {
1024 pub voltage_level: PioComponentIdView,
1025 pub calculated_bus_id: usize,
1026 pub node_count: usize,
1027 pub voltage_kv: f64,
1028 pub has_voltage: bool,
1029 pub angle_degrees: f64,
1030 pub has_angle: bool,
1031}
1032
1033#[repr(C)]
1035#[derive(Clone, Copy)]
1036pub struct PioBusbarSectionView {
1037 pub component: PioComponentIdView,
1038 pub voltage_level: PioComponentIdView,
1039 pub node: PioComponentIdView,
1040}
1041
1042#[repr(C)]
1044#[derive(Clone, Copy)]
1045pub struct PioJunctionView {
1046 pub component: PioComponentIdView,
1047}
1048
1049#[repr(C)]
1051#[derive(Clone, Copy)]
1052pub struct PioDetailedTerminalView {
1053 pub component: PioComponentIdView,
1054 pub has_component: bool,
1055 pub equipment: PioComponentIdView,
1056 pub terminal: u8,
1057 pub voltage_level: PioComponentIdView,
1058 pub bus: PioComponentIdView,
1059 pub has_bus: bool,
1060 pub connectable_bus: PioComponentIdView,
1061 pub has_connectable_bus: bool,
1062 pub node: PioComponentIdView,
1063 pub has_node: bool,
1064 pub connected: bool,
1065 pub active_power_mw: f64,
1066 pub has_active_power: bool,
1067 pub reactive_power_mvar: f64,
1068 pub has_reactive_power: bool,
1069}
1070
1071#[repr(C)]
1073#[derive(Clone, Copy)]
1074pub struct PioTopologySwitchView {
1075 pub component: PioComponentIdView,
1076 pub voltage_level: PioComponentIdView,
1077 pub kind: PioStringView,
1078 pub endpoint1_kind: PioStringView,
1079 pub endpoint1: PioComponentIdView,
1080 pub endpoint2_kind: PioStringView,
1081 pub endpoint2: PioComponentIdView,
1082 pub open: bool,
1083 pub retained: bool,
1084}
1085
1086#[repr(C)]
1088#[derive(Clone, Copy)]
1089pub struct PioInternalConnectionView {
1090 pub voltage_level: PioComponentIdView,
1091 pub node1: PioComponentIdView,
1092 pub node2: PioComponentIdView,
1093}
1094
1095#[repr(C)]
1097#[derive(Clone, Copy)]
1098pub struct PioOperationalLimitGroupView {
1099 pub equipment: PioComponentIdView,
1100 pub terminal: u8,
1101 pub id: PioStringView,
1102 pub selected: bool,
1103 pub property_count: usize,
1104 pub has_current_limits: bool,
1105 pub current_permanent_limit_a: f64,
1106 pub current_permanent_limit_name: PioStringView,
1107 pub has_current_permanent_limit: bool,
1108 pub has_current_permanent_limit_name: bool,
1109 pub current_temporary_limit_count: usize,
1110 pub has_active_power_limits: bool,
1111 pub active_power_permanent_limit_mw: f64,
1112 pub active_power_permanent_limit_name: PioStringView,
1113 pub has_active_power_permanent_limit: bool,
1114 pub has_active_power_permanent_limit_name: bool,
1115 pub active_power_temporary_limit_count: usize,
1116 pub has_apparent_power_limits: bool,
1117 pub apparent_power_permanent_limit_mva: f64,
1118 pub apparent_power_permanent_limit_name: PioStringView,
1119 pub has_apparent_power_permanent_limit: bool,
1120 pub has_apparent_power_permanent_limit_name: bool,
1121 pub apparent_power_temporary_limit_count: usize,
1122}
1123
1124#[repr(C)]
1126#[derive(Clone, Copy)]
1127pub struct PioDroopCurveSegmentView {
1128 pub minimum_voltage_kv: f64,
1129 pub maximum_voltage_kv: f64,
1130 pub k: f64,
1131}
1132
1133#[repr(C)]
1135#[derive(Clone, Copy)]
1136pub struct PioTemporaryLimitView {
1137 pub name: PioStringView,
1138 pub value: f64,
1139 pub acceptable_duration_seconds: u64,
1140 pub fictitious: bool,
1141}
1142
1143#[repr(C)]
1145#[derive(Clone, Copy)]
1146pub struct PioTapChangerView {
1147 pub component: PioComponentIdView,
1148 pub has_component: bool,
1149 pub transformer: PioComponentIdView,
1150 pub winding: u8,
1151 pub kind: PioStringView,
1152 pub tap_position: i32,
1153 pub has_tap_position: bool,
1154 pub solved_tap_position: i32,
1155 pub has_solved_tap_position: bool,
1156 pub low_tap_position: i32,
1157 pub neutral_tap_position: i32,
1158 pub has_neutral_tap_position: bool,
1159 pub normal_tap_position: i32,
1160 pub has_normal_tap_position: bool,
1161 pub voltage_step_increment_percent: f64,
1162 pub has_voltage_step_increment_percent: bool,
1163 pub load_tap_changing_capabilities: bool,
1164 pub regulating: bool,
1165 pub regulation_mode: PioStringView,
1166 pub has_regulation_mode: bool,
1167 pub regulation_value: f64,
1168 pub has_regulation_value: bool,
1169 pub target_deadband: f64,
1170 pub has_target_deadband: bool,
1171 pub regulation_terminal: PioTerminalReferenceView,
1172 pub has_regulation_terminal: bool,
1173 pub step_count: usize,
1174}
1175
1176#[repr(C)]
1178#[derive(Clone, Copy)]
1179pub struct PioTapChangerStepView {
1180 pub position: i32,
1181 pub ratio_pu: f64,
1182 pub phase_shift_degrees: f64,
1183 pub resistance_deviation_percent: f64,
1184 pub reactance_deviation_percent: f64,
1185 pub conductance_deviation_percent: f64,
1186 pub susceptance_deviation_percent: f64,
1187}
1188
1189#[repr(C)]
1191#[derive(Clone, Copy)]
1192pub struct PioDcTerminalView {
1193 pub component: PioComponentIdView,
1194 pub has_component: bool,
1195 pub sequence_number: u32,
1196 pub has_sequence_number: bool,
1197 pub dc_node: PioComponentIdView,
1198 pub has_dc_node: bool,
1199 pub dc_topological_node: PioComponentIdView,
1200 pub has_dc_topological_node: bool,
1201 pub polarity: PioStringView,
1202 pub has_polarity: bool,
1203 pub connected: bool,
1204 pub has_connected: bool,
1205 pub active_power_mw: f64,
1206 pub has_active_power: bool,
1207 pub current_a: f64,
1208 pub has_current: bool,
1209}
1210
1211#[repr(C)]
1213#[derive(Clone, Copy)]
1214pub struct PioDcEquipmentView {
1215 pub component: PioComponentIdView,
1216 pub equipment_container: PioComponentIdView,
1217 pub has_equipment_container: bool,
1218 pub kind: PioStringView,
1219 pub terminal_count: usize,
1220 pub terminal1: PioDcTerminalView,
1221 pub terminal2: PioDcTerminalView,
1222 pub rated_dc_voltage_kv: f64,
1223 pub has_rated_dc_voltage: bool,
1224 pub resistance_ohm: f64,
1225 pub has_resistance: bool,
1226 pub inductance_h: f64,
1227 pub has_inductance: bool,
1228 pub capacitance_f: f64,
1229 pub has_capacitance: bool,
1230 pub length_km: f64,
1231 pub has_length: bool,
1232 pub switch_kind: PioStringView,
1233 pub has_switch_kind: bool,
1234 pub open: bool,
1235 pub has_open: bool,
1236}
1237
1238#[repr(C)]
1240#[derive(Clone, Copy)]
1241pub struct PioDcNodeView {
1242 pub component: PioComponentIdView,
1243 pub kind: PioStringView,
1244 pub nominal_voltage_kv: f64,
1245 pub has_nominal_voltage: bool,
1246 pub voltage_kv: f64,
1247 pub has_voltage: bool,
1248 pub dc_converter_unit: PioComponentIdView,
1249 pub has_dc_converter_unit: bool,
1250 pub dc_topological_node: PioComponentIdView,
1251 pub has_dc_topological_node: bool,
1252}
1253
1254#[repr(C)]
1256#[derive(Clone, Copy)]
1257pub struct PioDcConverterUnitView {
1258 pub component: PioComponentIdView,
1259 pub substation: PioComponentIdView,
1260 pub has_substation: bool,
1261 pub operation_mode: PioStringView,
1262}
1263
1264#[repr(C)]
1266#[derive(Clone, Copy)]
1267pub struct PioAcDcConverterView {
1268 pub component: PioComponentIdView,
1269 pub kind: PioStringView,
1270 pub dc_converter_unit: PioComponentIdView,
1271 pub has_dc_converter_unit: bool,
1272 pub dc_terminal1: PioDcTerminalView,
1273 pub dc_terminal2: PioDcTerminalView,
1274 pub base_apparent_power_mva: f64,
1275 pub has_base_apparent_power: bool,
1276 pub minimum_active_power_mw: f64,
1277 pub has_minimum_active_power: bool,
1278 pub maximum_active_power_mw: f64,
1279 pub has_maximum_active_power: bool,
1280 pub minimum_dc_voltage_kv: f64,
1281 pub has_minimum_dc_voltage: bool,
1282 pub maximum_dc_voltage_kv: f64,
1283 pub has_maximum_dc_voltage: bool,
1284 pub rated_dc_voltage_kv: f64,
1285 pub has_rated_dc_voltage: bool,
1286 pub valve_u0_kv: f64,
1287 pub has_valve_u0: bool,
1288 pub number_of_valves: u32,
1289 pub has_number_of_valves: bool,
1290 pub idle_loss_mw: f64,
1291 pub has_idle_loss: bool,
1292 pub switching_loss_mw_per_ampere: f64,
1293 pub has_switching_loss: bool,
1294 pub resistive_loss_ohm: f64,
1295 pub has_resistive_loss: bool,
1296 pub control_mode: PioStringView,
1297 pub has_control_mode: bool,
1298 pub active_power_at_pcc_mw: f64,
1299 pub has_active_power_at_pcc: bool,
1300 pub reactive_power_at_pcc_mvar: f64,
1301 pub has_reactive_power_at_pcc: bool,
1302 pub target_active_power_mw: f64,
1303 pub has_target_active_power: bool,
1304 pub target_dc_voltage_kv: f64,
1305 pub has_target_dc_voltage: bool,
1306 pub pcc_terminal: PioTerminalReferenceView,
1307 pub has_pcc_terminal: bool,
1308 pub droop_curve_segment_count: usize,
1309 pub has_droop_curve: bool,
1310 pub droop: f64,
1311 pub has_droop: bool,
1312 pub droop_compensation: f64,
1313 pub has_droop_compensation: bool,
1314 pub q_share: f64,
1315 pub has_q_share: bool,
1316 pub maximum_modulation_index: f64,
1317 pub has_maximum_modulation_index: bool,
1318 pub maximum_valve_current_a: f64,
1319 pub has_maximum_valve_current: bool,
1320 pub dc_current_a: f64,
1321 pub has_dc_current: bool,
1322 pub ac_voltage_kv: f64,
1323 pub has_ac_voltage: bool,
1324 pub dc_voltage_kv: f64,
1325 pub has_dc_voltage: bool,
1326 pub voltage_regulator_on: bool,
1327 pub has_voltage_regulator_on: bool,
1328 pub voltage_setpoint_kv: f64,
1329 pub has_voltage_setpoint: bool,
1330 pub reactive_power_setpoint_mvar: f64,
1331 pub has_reactive_power_setpoint: bool,
1332 pub reactive_limits: PioReactiveLimitsView,
1333 pub has_reactive_limits: bool,
1334 pub pole_loss_active_power_mw: f64,
1335 pub has_pole_loss_active_power: bool,
1336 pub reactive_model: PioStringView,
1337 pub has_reactive_model: bool,
1338 pub power_factor: f64,
1339 pub has_power_factor: bool,
1340 pub operating_mode: PioStringView,
1341 pub has_operating_mode: bool,
1342 pub rated_dc_current_a: f64,
1343 pub has_rated_dc_current: bool,
1344 pub minimum_alpha_degrees: f64,
1345 pub has_minimum_alpha: bool,
1346 pub maximum_alpha_degrees: f64,
1347 pub has_maximum_alpha: bool,
1348 pub minimum_gamma_degrees: f64,
1349 pub has_minimum_gamma: bool,
1350 pub maximum_gamma_degrees: f64,
1351 pub has_maximum_gamma: bool,
1352 pub target_alpha_degrees: f64,
1353 pub has_target_alpha: bool,
1354 pub target_gamma_degrees: f64,
1355 pub has_target_gamma: bool,
1356 pub target_dc_current_a: f64,
1357 pub has_target_dc_current: bool,
1358 pub alpha_degrees: f64,
1359 pub has_alpha: bool,
1360 pub gamma_degrees: f64,
1361 pub has_gamma: bool,
1362 pub delta_degrees: f64,
1363 pub has_delta: bool,
1364 pub uf_kv: f64,
1365 pub has_uf: bool,
1366 pub uv_kv: f64,
1367 pub has_uv: bool,
1368}
1369
1370#[repr(C)]
1372#[derive(Clone, Copy)]
1373pub struct PioMulticonductorLocationView {
1374 pub x: f64,
1375 pub y: f64,
1376 pub kind: PioStringView,
1377 pub has_kind: bool,
1378}
1379
1380#[repr(C)]
1382#[derive(Clone, Copy)]
1383pub struct PioMulticonductorGeoView {
1384 pub has_geo: bool,
1385 pub space: PioStringView,
1386 pub crs: PioStringView,
1387 pub has_crs: bool,
1388 pub kind: PioStringView,
1389 pub has_kind: bool,
1390 pub has_canvas: bool,
1391 pub canvas_width: f64,
1392 pub has_canvas_width: bool,
1393 pub canvas_height: f64,
1394 pub has_canvas_height: bool,
1395 pub canvas_units: PioStringView,
1396 pub has_canvas_units: bool,
1397}
1398
1399#[repr(C)]
1404#[derive(Clone, Copy)]
1405pub struct PioMulticonductorNetworkCountsView {
1406 pub buses: usize,
1407 pub line_codes: usize,
1408 pub lines: usize,
1409 pub switches: usize,
1410 pub transformers: usize,
1411 pub loads: usize,
1412 pub generators: usize,
1413 pub inverter_based_resources: usize,
1414 pub control_profiles: usize,
1415 pub shunts: usize,
1416 pub capacitors: usize,
1417 pub voltage_sources: usize,
1418 pub untyped_objects: usize,
1419 pub commands: usize,
1420 pub options: usize,
1421}
1422
1423#[repr(C)]
1425#[derive(Clone, Copy)]
1426pub struct PioMulticonductorBusView {
1427 pub id: PioStringView,
1428 pub terminal_count: usize,
1429 pub grounded_terminal_count: usize,
1430 pub voltage_min_v: f64,
1431 pub has_voltage_min: bool,
1432 pub voltage_max_v: f64,
1433 pub has_voltage_max: bool,
1434 pub phase_to_ground_voltage_min_v: PioF64View,
1436 pub has_phase_to_ground_voltage_min: bool,
1437 pub phase_to_ground_voltage_max_v: PioF64View,
1438 pub has_phase_to_ground_voltage_max: bool,
1439 pub phase_to_neutral_voltage_min_v: PioF64View,
1440 pub has_phase_to_neutral_voltage_min: bool,
1441 pub phase_to_neutral_voltage_max_v: PioF64View,
1442 pub has_phase_to_neutral_voltage_max: bool,
1443 pub phase_to_phase_voltage_min_v: PioF64View,
1444 pub has_phase_to_phase_voltage_min: bool,
1445 pub phase_to_phase_voltage_max_v: PioF64View,
1446 pub has_phase_to_phase_voltage_max: bool,
1447 pub positive_sequence_voltage_min_v: f64,
1448 pub has_positive_sequence_voltage_min: bool,
1449 pub positive_sequence_voltage_max_v: f64,
1450 pub has_positive_sequence_voltage_max: bool,
1451 pub negative_sequence_voltage_max_v: f64,
1452 pub has_negative_sequence_voltage_max: bool,
1453 pub zero_sequence_voltage_max_v: f64,
1454 pub has_zero_sequence_voltage_max: bool,
1455 pub neutral_to_ground_voltage_max_v: f64,
1456 pub has_neutral_to_ground_voltage_max: bool,
1457 pub location: PioMulticonductorLocationView,
1458 pub has_location: bool,
1459}
1460
1461#[repr(C)]
1463#[derive(Clone, Copy)]
1464pub struct PioMulticonductorLineCodeView {
1465 pub name: PioStringView,
1466 pub conductor_count: usize,
1467 pub resistance_matrix_row_count: usize,
1468 pub reactance_matrix_row_count: usize,
1469 pub conductance_from_matrix_row_count: usize,
1470 pub susceptance_from_matrix_row_count: usize,
1471 pub conductance_to_matrix_row_count: usize,
1472 pub susceptance_to_matrix_row_count: usize,
1473 pub current_limit_a: PioF64View,
1474 pub has_current_limit: bool,
1475 pub apparent_power_limit_va: PioF64View,
1476 pub has_apparent_power_limit: bool,
1477 pub source: PioStringView,
1478 pub has_source: bool,
1479}
1480
1481#[repr(C)]
1483#[derive(Clone, Copy)]
1484pub struct PioMulticonductorLineView {
1485 pub name: PioStringView,
1486 pub bus_from: PioStringView,
1487 pub bus_to: PioStringView,
1488 pub terminal_map_from_count: usize,
1489 pub terminal_map_to_count: usize,
1490 pub line_code: PioStringView,
1491 pub length_m: f64,
1492 pub route_point_count: usize,
1493 pub has_route: bool,
1494 pub current_limit_a: PioF64View,
1495 pub has_current_limit: bool,
1496 pub apparent_power_limit_va: PioF64View,
1497 pub has_apparent_power_limit: bool,
1498}
1499
1500#[repr(C)]
1502#[derive(Clone, Copy)]
1503pub struct PioMulticonductorSwitchView {
1504 pub name: PioStringView,
1505 pub bus_from: PioStringView,
1506 pub bus_to: PioStringView,
1507 pub terminal_map_from_count: usize,
1508 pub terminal_map_to_count: usize,
1509 pub open: bool,
1510 pub current_limit_a: PioF64View,
1511 pub has_current_limit: bool,
1512}
1513
1514#[repr(C)]
1516#[derive(Clone, Copy)]
1517pub struct PioMulticonductorTransformerView {
1518 pub name: PioStringView,
1519 pub winding_count: usize,
1520 pub short_circuit_reactance_percent: PioF64View,
1521 pub phase_count: usize,
1522}
1523
1524#[repr(C)]
1526#[derive(Clone, Copy)]
1527pub struct PioMulticonductorTransformerWindingView {
1528 pub bus: PioStringView,
1529 pub terminal_map_count: usize,
1530 pub connection: PioStringView,
1531 pub rated_voltage_v: f64,
1532 pub apparent_power_rating_va: f64,
1533 pub resistance_percent: f64,
1534 pub tap: f64,
1535 pub neutral_resistance_ohm: f64,
1536 pub has_neutral_resistance: bool,
1537 pub neutral_reactance_ohm: f64,
1538 pub has_neutral_reactance: bool,
1539}
1540
1541#[repr(C)]
1543#[derive(Clone, Copy)]
1544pub struct PioMulticonductorLoadView {
1545 pub name: PioStringView,
1546 pub bus: PioStringView,
1547 pub terminal_map_count: usize,
1548 pub configuration: PioStringView,
1549 pub active_power_nominal_w: PioF64View,
1550 pub reactive_power_nominal_var: PioF64View,
1551 pub voltage_model: PioStringView,
1552 pub nominal_voltage_v: PioF64View,
1553 pub active_power_constant_impedance: PioF64View,
1554 pub active_power_constant_current: PioF64View,
1555 pub active_power_constant_power: PioF64View,
1556 pub reactive_power_constant_impedance: PioF64View,
1557 pub reactive_power_constant_current: PioF64View,
1558 pub reactive_power_constant_power: PioF64View,
1559 pub active_power_exponent: PioF64View,
1560 pub reactive_power_exponent: PioF64View,
1561}
1562
1563#[repr(C)]
1566#[derive(Clone, Copy)]
1567pub struct PioDistLoadVoltageModelView {
1568 pub model: PioStringView,
1569 pub nominal_voltage_v: PioF64View,
1570 pub active_power_constant_impedance: PioF64View,
1571 pub active_power_constant_current: PioF64View,
1572 pub active_power_constant_power: PioF64View,
1573 pub reactive_power_constant_impedance: PioF64View,
1574 pub reactive_power_constant_current: PioF64View,
1575 pub reactive_power_constant_power: PioF64View,
1576 pub active_power_exponent: PioF64View,
1577 pub reactive_power_exponent: PioF64View,
1578 pub voltage_low_pu: f64,
1579 pub has_voltage_low: bool,
1580 pub voltage_min_pu: f64,
1581 pub has_voltage_min: bool,
1582 pub voltage_max_pu: f64,
1583 pub has_voltage_max: bool,
1584 pub cutoff_pu: f64,
1585 pub has_cutoff: bool,
1586 pub current_limit_pu: f64,
1587 pub has_current_limit: bool,
1588}
1589
1590#[repr(C)]
1593#[derive(Clone, Copy)]
1594pub struct PioMulticonductorLoadDetailsView {
1595 pub name: PioStringView,
1596 pub bus: PioStringView,
1597 pub terminal_map_count: usize,
1598 pub configuration: PioStringView,
1599 pub active_power_nominal_w: PioF64View,
1600 pub reactive_power_nominal_var: PioF64View,
1601 pub voltage_model: PioDistLoadVoltageModelView,
1602}
1603
1604#[repr(C)]
1606#[derive(Clone, Copy)]
1607pub struct PioPrescribedLoadDetailsView {
1608 pub load: PioStringView,
1609 pub terminal_count: usize,
1610 pub active_power_w: PioF64View,
1611 pub reactive_power_var: PioF64View,
1612 pub voltage_model: PioDistLoadVoltageModelView,
1613}
1614
1615#[repr(C)]
1617#[derive(Clone, Copy)]
1618pub struct PioMulticonductorGeneratorView {
1619 pub name: PioStringView,
1620 pub bus: PioStringView,
1621 pub terminal_map_count: usize,
1622 pub configuration: PioStringView,
1623 pub active_power_nominal_w: PioF64View,
1624 pub reactive_power_nominal_var: PioF64View,
1625 pub active_power_min_w: PioF64View,
1626 pub has_active_power_min: bool,
1627 pub active_power_max_w: PioF64View,
1628 pub has_active_power_max: bool,
1629 pub reactive_power_min_var: PioF64View,
1630 pub has_reactive_power_min: bool,
1631 pub reactive_power_max_var: PioF64View,
1632 pub has_reactive_power_max: bool,
1633 pub active_power_dispatch_cost_per_kwh: PioF64View,
1634 pub has_active_power_dispatch_cost: bool,
1635 pub apparent_power_limit_va: PioF64View,
1636 pub has_apparent_power_limit: bool,
1637 pub current_limit_a: PioF64View,
1638 pub has_current_limit: bool,
1639}
1640
1641#[repr(C)]
1643#[derive(Clone, Copy)]
1644pub struct PioInverterBasedResourceView {
1645 pub name: PioStringView,
1646 pub bus: PioStringView,
1647 pub terminal_map_count: usize,
1648 pub topology: PioStringView,
1649 pub prime_mover: PioStringView,
1650 pub apparent_power_limit_va: PioF64View,
1651 pub current_limit_a: PioF64View,
1652 pub has_current_limit: bool,
1653 pub active_power_available_w: f64,
1654 pub has_active_power_available: bool,
1655 pub active_power_min_w: PioF64View,
1656 pub has_active_power_min: bool,
1657 pub active_power_max_w: PioF64View,
1658 pub has_active_power_max: bool,
1659 pub reactive_power_min_var: PioF64View,
1660 pub has_reactive_power_min: bool,
1661 pub reactive_power_max_var: PioF64View,
1662 pub has_reactive_power_max: bool,
1663 pub control_profile: PioStringView,
1664 pub has_control_profile: bool,
1665 pub voltage_aggregation: PioStringView,
1666 pub has_voltage_aggregation: bool,
1667}
1668
1669#[repr(C)]
1671#[derive(Clone, Copy)]
1672pub struct PioControlProfileView {
1673 pub name: PioStringView,
1674 pub has_power_factor: bool,
1675 pub power_factor: f64,
1676 pub has_volt_var: bool,
1677 pub volt_var_voltage_reference: PioStringView,
1678 pub has_volt_var_voltage_reference: bool,
1679 pub volt_var_breakpoints: PioF64View,
1680 pub volt_var_reactive_power_limits: PioF64View,
1681 pub volt_var_reactive_power_unit: PioStringView,
1682 pub has_volt_var_reactive_power_unit: bool,
1683 pub volt_var_reactive_power_reference: PioStringView,
1684 pub has_volt_var_reactive_power_reference: bool,
1685 pub volt_var_active_power_min_for_reactive_power_w: f64,
1686 pub has_volt_var_active_power_min_for_reactive_power: bool,
1687 pub volt_var_active_power_min_for_max_reactive_power_w: f64,
1688 pub has_volt_var_active_power_min_for_max_reactive_power: bool,
1689 pub has_volt_watt: bool,
1690 pub volt_watt_voltage_reference: PioStringView,
1691 pub has_volt_watt_voltage_reference: bool,
1692 pub volt_watt_breakpoints: PioF64View,
1693 pub volt_watt_active_power_limits: PioF64View,
1694 pub volt_watt_active_power_unit: PioStringView,
1695 pub has_volt_watt_active_power_unit: bool,
1696 pub volt_watt_active_power_reference: PioStringView,
1697 pub has_volt_watt_active_power_reference: bool,
1698}
1699
1700#[repr(C)]
1702#[derive(Clone, Copy)]
1703pub struct PioMulticonductorShuntView {
1704 pub name: PioStringView,
1705 pub bus: PioStringView,
1706 pub terminal_map_count: usize,
1707 pub conductance_matrix_row_count: usize,
1708 pub susceptance_matrix_row_count: usize,
1709}
1710
1711#[repr(C)]
1713#[derive(Clone, Copy)]
1714pub struct PioMulticonductorCapacitorView {
1715 pub name: PioStringView,
1716 pub bus: PioStringView,
1717 pub terminal_map_count: usize,
1718 pub configuration: PioStringView,
1719 pub rated_reactive_power_var: f64,
1720 pub nominal_voltage_v: f64,
1721}
1722
1723#[repr(C)]
1725#[derive(Clone, Copy)]
1726pub struct PioVoltageSourceView {
1727 pub name: PioStringView,
1728 pub bus: PioStringView,
1729 pub terminal_map_count: usize,
1730 pub voltage_magnitude_v: PioF64View,
1731 pub voltage_angle_rad: PioF64View,
1732 pub energy_cost_rate_per_kwh: PioF64View,
1734 pub has_energy_cost_rate: bool,
1735}
1736
1737#[repr(C)]
1742#[derive(Clone, Copy)]
1743pub struct PioVoltageSourceBoundaryView {
1744 pub source: PioVoltageSourceView,
1745 pub reference_terminal: PioStringView,
1746 pub has_reference_terminal: bool,
1747}
1748
1749#[repr(C)]
1752#[derive(Clone, Copy)]
1753pub struct PioBranchSwitchingCost {
1754 pub id: PioStringView,
1755 pub open_cost: f64,
1756 pub close_cost: f64,
1757}
1758
1759#[repr(C)]
1763#[derive(Clone, Copy)]
1764pub struct PioBranchCurrentLimit {
1765 pub id: PioStringView,
1766 pub from_pu: f64,
1767 pub to_pu: f64,
1768 pub has_from_pu: bool,
1769 pub has_to_pu: bool,
1770}
1771
1772#[repr(C)]
1778#[derive(Clone, Copy)]
1779pub struct PioAcOtsOptions {
1780 pub switchable: PioStringView,
1781 pub identities: *const PioStringView,
1782 pub identities_len: usize,
1783 pub switching_costs: *const PioBranchSwitchingCost,
1784 pub switching_costs_len: usize,
1785 pub islanding: PioStringView,
1786 pub max_open: usize,
1787 pub has_max_open: bool,
1788 pub max_switched: usize,
1789 pub has_max_switched: bool,
1790 pub current_limits: PioStringView,
1791 pub stated_current_limits: *const PioBranchCurrentLimit,
1792 pub stated_current_limits_len: usize,
1793}
1794
1795#[repr(C)]
1799#[derive(Clone, Copy)]
1800pub struct PioAcOtsOptionsView {
1801 pub switchable: PioStringView,
1802 pub islanding: PioStringView,
1803 pub current_limits: PioStringView,
1804 pub branch_count: usize,
1805 pub max_open: usize,
1806 pub has_max_open: bool,
1807 pub max_switched: usize,
1808 pub has_max_switched: bool,
1809}
1810
1811#[repr(C)]
1816#[derive(Clone, Copy)]
1817pub struct PioAcOtsBranchView {
1818 pub id: PioStringView,
1819 pub initial_closed: bool,
1820 pub switchable: bool,
1821 pub has_switching_cost: bool,
1822 pub open_cost: f64,
1823 pub close_cost: f64,
1824 pub stated_from_pu: f64,
1825 pub stated_to_pu: f64,
1826 pub has_stated_from_pu: bool,
1827 pub has_stated_to_pu: bool,
1828 pub current_from_pu: f64,
1829 pub current_to_pu: f64,
1830 pub has_current_from_pu: bool,
1831 pub has_current_to_pu: bool,
1832}
1833
1834#[repr(C)]
1838#[derive(Clone, Copy)]
1839pub struct PioAcOtsSolutionView {
1840 pub branch_count: usize,
1841 pub branches_open: usize,
1842 pub branches_switched: usize,
1843 pub switching_cost: f64,
1844 pub objective: f64,
1845}
1846
1847fn voltage_source_view(source: &powerio_dist::VoltageSource) -> PioVoltageSourceView {
1848 PioVoltageSourceView {
1849 name: PioStringView::new(&source.name),
1850 bus: PioStringView::new(&source.bus),
1851 terminal_map_count: source.terminal_map.len(),
1852 voltage_magnitude_v: PioF64View::new(&source.v_magnitude),
1853 voltage_angle_rad: PioF64View::new(&source.v_angle),
1854 energy_cost_rate_per_kwh: PioF64View::new(
1855 source.energy_cost_rate.as_deref().unwrap_or(&[]),
1856 ),
1857 has_energy_cost_rate: source.energy_cost_rate.is_some(),
1858 }
1859}
1860
1861fn voltage_source_boundary_view(
1862 source: &powerio_dist::VoltageSource,
1863) -> PioVoltageSourceBoundaryView {
1864 PioVoltageSourceBoundaryView {
1865 source: voltage_source_view(source),
1866 reference_terminal: PioStringView::new(source.reference_terminal.as_deref().unwrap_or("")),
1867 has_reference_terminal: source.reference_terminal.is_some(),
1868 }
1869}
1870
1871#[repr(C)]
1873#[derive(Clone, Copy)]
1874pub struct PioMulticonductorUntypedObjectView {
1875 pub class_name: PioStringView,
1876 pub name: PioStringView,
1877 pub property_count: usize,
1878}
1879
1880#[repr(C)]
1882#[derive(Clone, Copy)]
1883pub struct PioMulticonductorUntypedPropertyView {
1884 pub name: PioStringView,
1885 pub has_name: bool,
1886 pub value: PioStringView,
1887}
1888
1889#[repr(C)]
1891#[derive(Clone, Copy)]
1892pub struct PioMulticonductorCommandView {
1893 pub verb: PioStringView,
1894 pub args: PioStringView,
1895}
1896
1897#[repr(C)]
1899#[derive(Clone, Copy)]
1900pub struct PioDcBusSpecificationView {
1901 pub bus_id: usize,
1902 pub kind: PioStringView,
1903 pub net_active_power_mw: f64,
1904 pub voltage_angle_degrees: f64,
1905}
1906
1907#[repr(C)]
1909#[derive(Clone, Copy)]
1910pub struct PioAcBusSpecificationView {
1911 pub bus_id: usize,
1912 pub kind: PioStringView,
1913 pub net_active_power_mw: f64,
1914 pub net_reactive_power_mvar: f64,
1915 pub voltage_magnitude_pu: f64,
1916 pub voltage_angle_degrees: f64,
1917}
1918
1919#[repr(C)]
1921#[derive(Clone, Copy)]
1922pub struct PioDcOpfPreparationView {
1923 pub name: PioStringView,
1924 pub bus_count: usize,
1925 pub generator_count: usize,
1926 pub branch_count: usize,
1927 pub source_generator_count: usize,
1928 pub source_branch_count: usize,
1929 pub base_mva: f64,
1930 pub units: PioStringView,
1931 pub branch_susceptance_formula: PioStringView,
1932 pub objective: PioStringView,
1933 pub skip_zero_impedance: bool,
1934 pub synthesize_unrated_limits: bool,
1935 pub correct_angle_difference_bounds: bool,
1936 pub reference_bus_count: usize,
1937 pub skipped_zero_impedance_count: usize,
1938}
1939
1940#[repr(C)]
1942#[derive(Clone, Copy)]
1943pub struct PioDcOpfBusView {
1944 pub bus_id: usize,
1945 pub analysis_row: usize,
1946 pub source_row: usize,
1947 pub has_source_row: bool,
1948 pub active_power_demand: f64,
1949 pub shunt_conductance: f64,
1950 pub phase_shift_injection: f64,
1951}
1952
1953#[repr(C)]
1955#[derive(Clone, Copy)]
1956pub struct PioDcOpfGeneratorView {
1957 pub component_id: PioStringView,
1958 pub bus_index: usize,
1959 pub analysis_row: usize,
1960 pub source_row: usize,
1961 pub has_source_row: bool,
1962 pub quadratic_cost: f64,
1963 pub linear_cost: f64,
1964 pub constant_cost: f64,
1965 pub has_piecewise_linear_cost: bool,
1966 pub piecewise_linear_power: PioF64View,
1967 pub piecewise_linear_value: PioF64View,
1968 pub active_power_max: f64,
1969 pub active_power_min: f64,
1970 pub capability_active: bool,
1971}
1972
1973#[repr(C)]
1975#[derive(Clone, Copy)]
1976pub struct PioDcOpfBranchView {
1977 pub component_id: PioStringView,
1978 pub from_bus_index: usize,
1979 pub to_bus_index: usize,
1980 pub susceptance_magnitude: f64,
1981 pub phase_shift_radians: f64,
1982 pub active_power_max: f64,
1983 pub angle_difference_min_radians: f64,
1984 pub angle_difference_max_radians: f64,
1985 pub analysis_row: usize,
1986 pub source_kind: PioStringView,
1987 pub source_row: usize,
1988 pub winding: usize,
1989 pub has_winding: bool,
1990 pub thermal_limit_active: bool,
1991 pub angle_bound_active: bool,
1992}
1993
1994#[repr(C)]
1996#[derive(Clone, Copy)]
1997pub struct PioAcOpfPreparationView {
1998 pub name: PioStringView,
1999 pub bus_count: usize,
2000 pub generator_count: usize,
2001 pub storage_count: usize,
2002 pub branch_count: usize,
2003 pub source_generator_count: usize,
2004 pub source_branch_count: usize,
2005 pub base_mva: f64,
2006 pub units: PioStringView,
2007 pub objective: PioStringView,
2008 pub skip_zero_impedance: bool,
2009 pub synthesize_unrated_limits: bool,
2010 pub correct_angle_difference_bounds: bool,
2011 pub reference_bus_count: usize,
2012 pub skipped_zero_impedance_count: usize,
2013}
2014
2015#[repr(C)]
2017#[derive(Clone, Copy)]
2018pub struct PioAcOpfBusView {
2019 pub bus_id: usize,
2020 pub analysis_row: usize,
2021 pub source_row: usize,
2022 pub has_source_row: bool,
2023 pub active_power_demand: f64,
2024 pub reactive_power_demand: f64,
2025 pub shunt_conductance: f64,
2026 pub shunt_susceptance: f64,
2027 pub voltage_magnitude_min_pu: f64,
2028 pub voltage_magnitude_max_pu: f64,
2029 pub initial_voltage_magnitude_pu: f64,
2030 pub initial_voltage_angle_radians: f64,
2031 pub voltage_bound_active: bool,
2032}
2033
2034#[repr(C)]
2036#[derive(Clone, Copy)]
2037pub struct PioAcOpfGeneratorView {
2038 pub component_id: PioStringView,
2039 pub bus_index: usize,
2040 pub analysis_row: usize,
2041 pub source_row: usize,
2042 pub has_source_row: bool,
2043 pub quadratic_cost: f64,
2044 pub linear_cost: f64,
2045 pub constant_cost: f64,
2046 pub has_piecewise_linear_cost: bool,
2047 pub piecewise_linear_power: PioF64View,
2048 pub piecewise_linear_value: PioF64View,
2049 pub active_power_max: f64,
2050 pub active_power_min: f64,
2051 pub reactive_power_max: f64,
2052 pub reactive_power_min: f64,
2053 pub initial_active_power: f64,
2054 pub initial_reactive_power: f64,
2055 pub voltage_magnitude_setpoint_pu: f64,
2056 pub capability_active: bool,
2057}
2058
2059#[repr(C)]
2061#[derive(Clone, Copy)]
2062pub struct PioAcOpfStorageView {
2063 pub component_id: PioStringView,
2064 pub bus_index: usize,
2065 pub source_row: usize,
2066 pub initial_active_power: f64,
2067 pub initial_reactive_power: f64,
2068 pub energy: f64,
2069 pub energy_rating: f64,
2070 pub charge_rating: f64,
2071 pub discharge_rating: f64,
2072 pub charge_efficiency: f64,
2073 pub discharge_efficiency: f64,
2074 pub apparent_power_max: f64,
2075 pub reactive_power_min: f64,
2076 pub reactive_power_max: f64,
2077 pub resistance_pu: f64,
2078 pub reactance_pu: f64,
2079 pub active_power_loss: f64,
2080 pub reactive_power_loss: f64,
2081 pub in_service: bool,
2082}
2083
2084#[repr(C)]
2086#[derive(Clone, Copy)]
2087pub struct PioAcOpfBranchView {
2088 pub component_id: PioStringView,
2089 pub from_bus_index: usize,
2090 pub to_bus_index: usize,
2091 pub series_conductance: f64,
2092 pub series_susceptance: f64,
2093 pub from_conductance: f64,
2094 pub from_susceptance: f64,
2095 pub to_conductance: f64,
2096 pub to_susceptance: f64,
2097 pub tap_ratio: f64,
2098 pub phase_shift_radians: f64,
2099 pub apparent_power_max: f64,
2100 pub angle_difference_min_radians: f64,
2101 pub angle_difference_max_radians: f64,
2102 pub analysis_row: usize,
2103 pub source_kind: PioStringView,
2104 pub source_row: usize,
2105 pub winding: usize,
2106 pub has_winding: bool,
2107 pub thermal_limit_active: bool,
2108 pub angle_bound_active: bool,
2109}
2110
2111#[repr(C)]
2113#[derive(Clone, Copy)]
2114pub struct PioObjectiveTermView {
2115 pub kind: PioStringView,
2116}
2117
2118#[repr(C)]
2120#[derive(Clone, Copy)]
2121pub struct PioActiveConstraintView {
2122 pub family: PioStringView,
2123 pub selection: PioStringView,
2124 pub identity_count: usize,
2125}
2126
2127#[repr(C)]
2129#[derive(Clone, Copy)]
2130pub struct PioPrescribedTerminalPowerView {
2131 pub load: PioStringView,
2132 pub terminal_count: usize,
2133 pub voltage_model: PioStringView,
2134}
2135
2136#[repr(C)]
2138#[derive(Clone, Copy)]
2139pub struct PioTerminalPowerView {
2140 pub terminal: PioStringView,
2141 pub active_power_w: f64,
2142 pub reactive_power_var: f64,
2143 pub nominal_voltage_v: f64,
2144 pub has_nominal_voltage: bool,
2145 pub active_impedance_fraction: f64,
2146 pub active_current_fraction: f64,
2147 pub active_power_fraction: f64,
2148 pub reactive_impedance_fraction: f64,
2149 pub reactive_current_fraction: f64,
2150 pub reactive_power_fraction: f64,
2151 pub active_power_exponent: f64,
2152 pub reactive_power_exponent: f64,
2153}
2154
2155#[repr(C)]
2157#[derive(Clone, Copy)]
2158pub struct PioPrescribedSourceVoltageView {
2159 pub source: PioStringView,
2160 pub terminal_count: usize,
2161}
2162
2163#[repr(C)]
2165#[derive(Clone, Copy)]
2166pub struct PioTerminalVoltageView {
2167 pub terminal: PioStringView,
2168 pub magnitude_v: f64,
2169 pub angle_radians: f64,
2170}
2171
2172#[repr(C)]
2174#[derive(Clone, Copy)]
2175pub struct PioIsolatedTerminalView {
2176 pub bus: PioStringView,
2177 pub terminal: PioStringView,
2178}
2179
2180#[repr(C)]
2182#[derive(Clone, Copy)]
2183pub struct PioActiveControlView {
2184 pub kind: PioStringView,
2185 pub component_id: PioStringView,
2186}
2187
2188#[repr(C)]
2190#[derive(Clone, Copy)]
2191pub struct PioScucDimensionsView {
2192 pub period_count: usize,
2193 pub device_count: usize,
2194 pub producer_count: usize,
2195 pub consumer_count: usize,
2196 pub shunt_count: usize,
2197 pub branch_switching_cost_count: usize,
2198 pub transformer_control_count: usize,
2199 pub active_reserve_zone_count: usize,
2200 pub reactive_reserve_zone_count: usize,
2201 pub contingency_count: usize,
2202}
2203
2204#[repr(C)]
2206#[derive(Clone, Copy)]
2207pub struct PioScucViolationCostView {
2208 pub active_power_balance: f64,
2209 pub reactive_power_balance: f64,
2210 pub branch_thermal_limit: f64,
2211 pub energy_requirement: f64,
2212}
2213
2214#[repr(C)]
2216#[derive(Clone, Copy)]
2217pub struct PioComponentIdView {
2218 pub component_type: PioStringView,
2219 pub local_id: PioStringView,
2220}
2221
2222#[repr(C)]
2229#[derive(Clone, Copy)]
2230pub struct PioContingencyComponentView {
2231 pub id: PioComponentIdView,
2232 pub row: usize,
2233 pub in_service: bool,
2234}
2235
2236#[repr(C)]
2238#[derive(Clone, Copy)]
2239pub struct PioScucRampLimitsView {
2240 pub up_pu_per_hour: f64,
2241 pub down_pu_per_hour: f64,
2242 pub startup_pu_per_hour: f64,
2243 pub shutdown_pu_per_hour: f64,
2244}
2245
2246#[repr(C)]
2248#[derive(Clone, Copy)]
2249pub struct PioScucReserveLimitsView {
2250 pub regulation_up_pu: f64,
2251 pub regulation_down_pu: f64,
2252 pub synchronized_pu: f64,
2253 pub nonsynchronized_pu: f64,
2254 pub ramping_up_online_pu: f64,
2255 pub ramping_down_online_pu: f64,
2256 pub ramping_up_offline_pu: f64,
2257 pub ramping_down_offline_pu: f64,
2258}
2259
2260#[repr(C)]
2262#[derive(Clone, Copy)]
2263pub struct PioScucInitialCommitmentView {
2264 pub accumulated_up_time_hours: f64,
2265 pub accumulated_down_time_hours: f64,
2266}
2267
2268#[repr(C)]
2270#[derive(Clone, Copy)]
2271pub struct PioScucReactiveCapabilityView {
2272 pub kind: PioStringView,
2273 pub reactive_power_at_zero_active_power_pu: f64,
2274 pub reactive_power_at_zero_active_power_min_pu: f64,
2275 pub reactive_power_at_zero_active_power_max_pu: f64,
2276 pub slope: f64,
2277 pub slope_min: f64,
2278 pub slope_max: f64,
2279}
2280
2281#[repr(C)]
2283#[derive(Clone, Copy)]
2284pub struct PioScucDeviceView {
2285 pub id: PioComponentIdView,
2286 pub kind: PioStringView,
2287 pub initial_on_status: bool,
2288 pub on_cost: f64,
2289 pub startup_cost: f64,
2290 pub shutdown_cost: f64,
2291 pub minimum_up_time_hours: f64,
2292 pub minimum_down_time_hours: f64,
2293 pub ramp_limits: PioScucRampLimitsView,
2294 pub reserve_limits: PioScucReserveLimitsView,
2295 pub initial_commitment: PioScucInitialCommitmentView,
2296 pub reactive_capability: PioScucReactiveCapabilityView,
2297 pub period_count: usize,
2298 pub startup_cost_adjustment_count: usize,
2299 pub startup_limit_count: usize,
2300 pub energy_upper_bound_count: usize,
2301 pub energy_lower_bound_count: usize,
2302}
2303
2304#[repr(C)]
2306#[derive(Clone, Copy)]
2307pub struct PioScucStartupCostAdjustmentView {
2308 pub cost: f64,
2309 pub maximum_down_time_hours: f64,
2310}
2311
2312#[repr(C)]
2314#[derive(Clone, Copy)]
2315pub struct PioScucDevicePeriodView {
2316 pub on_status_min: bool,
2317 pub on_status_max: bool,
2318 pub active_power_min_pu: f64,
2319 pub active_power_max_pu: f64,
2320 pub reactive_power_min_pu: f64,
2321 pub reactive_power_max_pu: f64,
2322 pub energy_cost_block_count: usize,
2323 pub reserve_costs: PioScucReserveCostsView,
2324}
2325
2326#[repr(C)]
2328#[derive(Clone, Copy)]
2329pub struct PioScucStartupLimitView {
2330 pub start_time_hours: f64,
2331 pub end_time_hours: f64,
2332 pub maximum_startups: u64,
2333}
2334
2335#[repr(C)]
2337#[derive(Clone, Copy)]
2338pub struct PioScucEnergyRequirementView {
2339 pub start_time_hours: f64,
2340 pub end_time_hours: f64,
2341 pub energy_pu: f64,
2342}
2343
2344#[repr(C)]
2346#[derive(Clone, Copy)]
2347pub struct PioScucEnergyCostBlockView {
2348 pub marginal_cost: f64,
2349 pub block_size_pu: f64,
2350}
2351
2352#[repr(C)]
2354#[derive(Clone, Copy)]
2355pub struct PioScucReserveCostsView {
2356 pub regulation_up: f64,
2357 pub regulation_down: f64,
2358 pub synchronized: f64,
2359 pub nonsynchronized: f64,
2360 pub ramping_up_online: f64,
2361 pub ramping_down_online: f64,
2362 pub ramping_up_offline: f64,
2363 pub ramping_down_offline: f64,
2364 pub reactive_up: f64,
2365 pub reactive_down: f64,
2366}
2367
2368#[repr(C)]
2370#[derive(Clone, Copy)]
2371pub struct PioScucShuntView {
2372 pub id: PioComponentIdView,
2373 pub conductance_per_step_pu: f64,
2374 pub susceptance_per_step_pu: f64,
2375 pub step_min: i64,
2376 pub step_max: i64,
2377 pub initial_step: i64,
2378}
2379
2380#[repr(C)]
2382#[derive(Clone, Copy)]
2383pub struct PioScucBranchSwitchingCostView {
2384 pub id: PioComponentIdView,
2385 pub connection_cost: f64,
2386 pub disconnection_cost: f64,
2387}
2388
2389#[repr(C)]
2391#[derive(Clone, Copy)]
2392pub struct PioScucTransformerControlView {
2393 pub id: PioComponentIdView,
2394 pub tap_ratio_min: f64,
2395 pub tap_ratio_max: f64,
2396 pub phase_shift_min_radians: f64,
2397 pub phase_shift_max_radians: f64,
2398}
2399
2400#[repr(C)]
2402#[derive(Clone, Copy)]
2403pub struct PioScucActiveReserveZoneView {
2404 pub id: PioComponentIdView,
2405 pub regulation_up_requirement_fraction: f64,
2406 pub regulation_down_requirement_fraction: f64,
2407 pub synchronized_requirement_fraction: f64,
2408 pub nonsynchronized_requirement_fraction: f64,
2409 pub regulation_up_violation_cost: f64,
2410 pub regulation_down_violation_cost: f64,
2411 pub synchronized_violation_cost: f64,
2412 pub nonsynchronized_violation_cost: f64,
2413 pub ramping_up_violation_cost: f64,
2414 pub ramping_down_violation_cost: f64,
2415 pub period_count: usize,
2416 pub bus_count: usize,
2417}
2418
2419#[repr(C)]
2421#[derive(Clone, Copy)]
2422pub struct PioScucActiveReservePeriodView {
2423 pub ramping_up_requirement_pu: f64,
2424 pub ramping_down_requirement_pu: f64,
2425}
2426
2427#[repr(C)]
2429#[derive(Clone, Copy)]
2430pub struct PioScucReactiveReserveZoneView {
2431 pub id: PioComponentIdView,
2432 pub reactive_up_violation_cost: f64,
2433 pub reactive_down_violation_cost: f64,
2434 pub period_count: usize,
2435 pub bus_count: usize,
2436}
2437
2438#[repr(C)]
2440#[derive(Clone, Copy)]
2441pub struct PioScucReactiveReservePeriodView {
2442 pub reactive_up_requirement_pu: f64,
2443 pub reactive_down_requirement_pu: f64,
2444}
2445
2446#[repr(C)]
2448#[derive(Clone, Copy)]
2449pub struct PioScucContingencyView {
2450 pub id: PioComponentIdView,
2451 pub component_count: usize,
2452}
2453
2454#[repr(C)]
2456#[derive(Clone, Copy)]
2457pub struct PioScucContingencyComponentView {
2458 pub id: PioComponentIdView,
2459}
2460
2461const fn assert_send_sync<T: Send + Sync>() {}
2466
2467#[repr(transparent)]
2468struct HandleBox<T> {
2469 inner: Arc<T>,
2470}
2471
2472fn handle_new<T>(value: T) -> *mut HandleBox<T> {
2473 Box::into_raw(Box::new(HandleBox {
2474 inner: Arc::new(value),
2475 }))
2476}
2477
2478fn handle_from_arc<T>(inner: Arc<T>) -> *mut HandleBox<T> {
2479 Box::into_raw(Box::new(HandleBox { inner }))
2480}
2481
2482unsafe fn handle_get<'a, T>(raw: *const HandleBox<T>) -> Option<&'a T> {
2483 unsafe { raw.as_ref() }.map(|handle| handle.inner.as_ref())
2484}
2485
2486unsafe fn handle_arc<T>(raw: *const HandleBox<T>) -> Option<Arc<T>> {
2487 unsafe { raw.as_ref() }.map(|handle| Arc::clone(&handle.inner))
2488}
2489
2490unsafe fn handle_retain<T>(raw: *const HandleBox<T>) -> *mut HandleBox<T> {
2491 unsafe { handle_arc(raw) }.map_or(std::ptr::null_mut(), handle_from_arc)
2492}
2493
2494unsafe fn handle_release<T>(raw: *mut HandleBox<T>) {
2495 if !raw.is_null() {
2496 drop(unsafe { Box::from_raw(raw) });
2497 }
2498}
2499
2500macro_rules! opaque_handle {
2501 ($(#[$doc:meta])* $name:ident, $inner:ty) => {
2502 $(#[$doc])*
2503 #[repr(transparent)]
2504 pub struct $name(HandleBox<$inner>);
2505 const _: () = assert_send_sync::<$inner>();
2506
2507 #[allow(dead_code)]
2508 impl $name {
2509 fn new_raw(value: $inner) -> *mut Self {
2510 handle_new(value).cast()
2511 }
2512
2513 fn from_arc(inner: Arc<$inner>) -> *mut Self {
2514 handle_from_arc(inner).cast()
2515 }
2516
2517 unsafe fn get<'a>(raw: *const Self) -> Option<&'a $inner> {
2518 unsafe { handle_get(raw.cast()) }
2519 }
2520
2521 unsafe fn arc(raw: *const Self) -> Option<Arc<$inner>> {
2522 unsafe { handle_arc(raw.cast()) }
2523 }
2524
2525 unsafe fn retain_raw(raw: *const Self) -> *mut Self {
2526 unsafe { handle_retain(raw.cast::<HandleBox<$inner>>()) }.cast::<Self>()
2527 }
2528
2529 unsafe fn release_raw(raw: *mut Self) {
2530 unsafe { handle_release(raw.cast::<HandleBox<$inner>>()) }
2531 }
2532 }
2533 };
2534}
2535
2536opaque_handle!(
2537 PioCollection,
2539 powerio::Collection
2540);
2541mod collection;
2542pub use collection::*;
2543
2544struct ErrorInner {
2547 code: String,
2548 message: String,
2549 diagnostics: Arc<DiagnosticsInner>,
2550}
2551
2552struct DiagnosticsInner {
2553 owner: DiagnosticsOwner,
2554}
2555
2556enum DiagnosticsOwner {
2557 Owned(Vec<Diagnostic>),
2558 Module(Arc<ModuleInner>),
2559}
2560
2561impl DiagnosticsInner {
2562 fn records(&self) -> &[Diagnostic] {
2563 match &self.owner {
2564 DiagnosticsOwner::Owned(records) => records,
2565 DiagnosticsOwner::Module(module) => module.module.diagnostics(),
2566 }
2567 }
2568}
2569
2570opaque_handle!(
2571 PioError,
2573 ErrorInner
2574);
2575opaque_handle!(
2576 PioDiagnostics,
2578 DiagnosticsInner
2579);
2580
2581fn boundary_diagnostic(
2582 info: &'static powerio_core::DiagnosticInfo,
2583 message: impl Into<String>,
2584) -> Diagnostic {
2585 Diagnostic::of(info, message)
2586}
2587
2588fn error_from_diagnostics(message: String, mut records: Vec<Diagnostic>) -> *mut PioError {
2589 if records.is_empty() {
2590 records.push(boundary_diagnostic(
2591 &codes::BIND_CAPI_UNCODED_FAILURE,
2592 message.clone(),
2593 ));
2594 }
2595 let code = records[0].code().to_owned();
2596 PioError::new_raw(ErrorInner {
2597 code,
2598 message,
2599 diagnostics: Arc::new(DiagnosticsInner {
2600 owner: DiagnosticsOwner::Owned(records),
2601 }),
2602 })
2603}
2604
2605fn error_from_core(error: &powerio_core::Error) -> *mut PioError {
2606 error_from_diagnostics(error.to_string(), error.diagnostics().to_vec())
2607}
2608
2609fn error_from_tx(error: &powerio_tx::Error) -> *mut PioError {
2610 let diagnostic = Diagnostic::of(error.code(), error.to_string());
2611 error_from_diagnostics(error.to_string(), vec![diagnostic])
2612}
2613
2614fn error_from_matrix(error: &powerio_matrix::Error) -> *mut PioError {
2615 let diagnostic = Diagnostic::of(error.code(), error.to_string());
2616 error_from_diagnostics(error.to_string(), vec![diagnostic])
2617}
2618
2619fn boundary_error(
2620 info: &'static powerio_core::DiagnosticInfo,
2621 message: impl Into<String>,
2622) -> *mut PioError {
2623 let diagnostic = boundary_diagnostic(info, message);
2624 error_from_diagnostics(
2625 powerio_core::render_diagnostic(&diagnostic),
2626 vec![diagnostic],
2627 )
2628}
2629
2630unsafe fn store_error(slot: *mut *mut PioError, error: *mut PioError) {
2631 if slot.is_null() {
2632 unsafe { PioError::release_raw(error) };
2633 } else {
2634 unsafe { *slot = error };
2635 }
2636}
2637
2638unsafe fn entry<R>(
2639 error: *mut *mut PioError,
2640 fallback: R,
2641 operation: impl FnOnce() -> Result<R, *mut PioError>,
2642) -> R {
2643 if !error.is_null() {
2644 unsafe { *error = std::ptr::null_mut() };
2645 }
2646 match catch_unwind(AssertUnwindSafe(operation)) {
2647 Ok(Ok(value)) => value,
2648 Ok(Err(failure)) => {
2649 unsafe { store_error(error, failure) };
2650 fallback
2651 }
2652 Err(_) => {
2653 let failure = boundary_error(
2654 &codes::BIND_CAPI_PANIC,
2655 "the operation panicked and made no C-visible change",
2656 );
2657 unsafe { store_error(error, failure) };
2658 fallback
2659 }
2660 }
2661}
2662
2663unsafe fn input_bytes<'a>(
2664 data: *const u8,
2665 len: usize,
2666 argument: &str,
2667) -> Result<&'a [u8], *mut PioError> {
2668 if data.is_null() {
2669 if len == 0 {
2670 return Ok(&[]);
2671 }
2672 return Err(boundary_error(
2673 &codes::BIND_CAPI_NULL_ARGUMENT,
2674 format!("{argument} is NULL with a nonzero length"),
2675 ));
2676 }
2677 Ok(unsafe { std::slice::from_raw_parts(data, len) })
2678}
2679
2680unsafe fn input_str<'a>(
2681 data: *const c_char,
2682 len: usize,
2683 argument: &str,
2684) -> Result<&'a str, *mut PioError> {
2685 let bytes = unsafe { input_bytes(data.cast(), len, argument) }?;
2686 std::str::from_utf8(bytes).map_err(|_| {
2687 boundary_error(
2688 &codes::BIND_CAPI_INVALID_UTF8,
2689 format!("{argument} is not valid UTF-8"),
2690 )
2691 })
2692}
2693
2694unsafe fn required_str<'a>(
2695 data: *const c_char,
2696 len: usize,
2697 argument: &str,
2698) -> Result<&'a str, *mut PioError> {
2699 if data.is_null() || len == 0 {
2700 return Err(boundary_error(
2701 &codes::BIND_CAPI_NULL_ARGUMENT,
2702 format!("{argument} is required"),
2703 ));
2704 }
2705 unsafe { input_str(data, len, argument) }
2706}
2707
2708unsafe fn optional_str<'a>(
2709 data: *const c_char,
2710 len: usize,
2711 argument: &str,
2712) -> Result<Option<&'a str>, *mut PioError> {
2713 if data.is_null() {
2714 if len == 0 {
2715 return Ok(None);
2716 }
2717 return Err(boundary_error(
2718 &codes::BIND_CAPI_NULL_ARGUMENT,
2719 format!("{argument} is NULL with a nonzero length"),
2720 ));
2721 }
2722 unsafe { input_str(data, len, argument) }.map(Some)
2723}
2724
2725#[unsafe(no_mangle)]
2727pub extern "C" fn pio_version() -> PioStringView {
2728 PioStringView::new(powerio::VERSION)
2729}
2730
2731#[unsafe(no_mangle)]
2737pub extern "C" fn pio_version_numbers() -> PioVersionView {
2738 PioVersionView {
2739 major: PIO_VERSION_MAJOR,
2740 minor: PIO_VERSION_MINOR,
2741 patch: PIO_VERSION_PATCH,
2742 }
2743}
2744
2745#[unsafe(no_mangle)]
2750pub unsafe extern "C" fn pio_error_code(error: *const PioError) -> PioStringView {
2751 unsafe { PioError::get(error) }.map_or(PioStringView::EMPTY, |error| {
2752 PioStringView::new(&error.code)
2753 })
2754}
2755
2756#[unsafe(no_mangle)]
2761pub unsafe extern "C" fn pio_error_message(error: *const PioError) -> PioStringView {
2762 unsafe { PioError::get(error) }.map_or(PioStringView::EMPTY, |error| {
2763 PioStringView::new(&error.message)
2764 })
2765}
2766
2767#[unsafe(no_mangle)]
2772pub unsafe extern "C" fn pio_error_diagnostics(error: *const PioError) -> *mut PioDiagnostics {
2773 unsafe { PioError::get(error) }.map_or(std::ptr::null_mut(), |error| {
2774 PioDiagnostics::from_arc(Arc::clone(&error.diagnostics))
2775 })
2776}
2777
2778#[unsafe(no_mangle)]
2783pub unsafe extern "C" fn pio_error_retain(error: *const PioError) -> *mut PioError {
2784 unsafe { PioError::retain_raw(error) }
2785}
2786
2787#[unsafe(no_mangle)]
2792pub unsafe extern "C" fn pio_error_release(error: *mut PioError) {
2793 unsafe { PioError::release_raw(error) };
2794}
2795
2796#[unsafe(no_mangle)]
2800pub unsafe extern "C" fn pio_diagnostics_len(diagnostics: *const PioDiagnostics) -> usize {
2801 unsafe { PioDiagnostics::get(diagnostics) }.map_or(0, |values| values.records().len())
2802}
2803
2804#[unsafe(no_mangle)]
2808pub unsafe extern "C" fn pio_diagnostic_code(
2809 diagnostics: *const PioDiagnostics,
2810 index: usize,
2811) -> PioStringView {
2812 unsafe { PioDiagnostics::get(diagnostics) }
2813 .and_then(|values| values.records().get(index))
2814 .map_or(PioStringView::EMPTY, |record| {
2815 PioStringView::new(record.code())
2816 })
2817}
2818
2819#[unsafe(no_mangle)]
2823pub unsafe extern "C" fn pio_diagnostic_severity(
2824 diagnostics: *const PioDiagnostics,
2825 index: usize,
2826) -> PioStringView {
2827 unsafe { PioDiagnostics::get(diagnostics) }
2828 .and_then(|values| values.records().get(index))
2829 .map_or(PioStringView::EMPTY, |record| {
2830 PioStringView::new(record.severity().as_str())
2831 })
2832}
2833
2834#[unsafe(no_mangle)]
2838pub unsafe extern "C" fn pio_diagnostic_message(
2839 diagnostics: *const PioDiagnostics,
2840 index: usize,
2841) -> PioStringView {
2842 unsafe { PioDiagnostics::get(diagnostics) }
2843 .and_then(|values| values.records().get(index))
2844 .map_or(PioStringView::EMPTY, |record| {
2845 PioStringView::new(record.message())
2846 })
2847}
2848
2849#[unsafe(no_mangle)]
2854pub unsafe extern "C" fn pio_diagnostic_has_id(
2855 diagnostics: *const PioDiagnostics,
2856 index: usize,
2857) -> bool {
2858 unsafe { PioDiagnostics::get(diagnostics) }
2859 .and_then(|values| values.records().get(index))
2860 .is_some_and(|record| record.id().is_some())
2861}
2862
2863#[unsafe(no_mangle)]
2868pub unsafe extern "C" fn pio_diagnostic_id(
2869 diagnostics: *const PioDiagnostics,
2870 index: usize,
2871) -> PioStringView {
2872 unsafe { PioDiagnostics::get(diagnostics) }
2873 .and_then(|values| values.records().get(index))
2874 .and_then(Diagnostic::id)
2875 .map_or(PioStringView::EMPTY, |id| PioStringView::new(id.as_str()))
2876}
2877
2878#[unsafe(no_mangle)]
2883pub unsafe extern "C" fn pio_diagnostic_has_target(
2884 diagnostics: *const PioDiagnostics,
2885 index: usize,
2886) -> bool {
2887 unsafe { PioDiagnostics::get(diagnostics) }
2888 .and_then(|values| values.records().get(index))
2889 .is_some_and(|record| record.target().is_some())
2890}
2891
2892#[unsafe(no_mangle)]
2897pub unsafe extern "C" fn pio_diagnostic_target(
2898 diagnostics: *const PioDiagnostics,
2899 index: usize,
2900) -> PioStringView {
2901 unsafe { PioDiagnostics::get(diagnostics) }
2902 .and_then(|values| values.records().get(index))
2903 .and_then(Diagnostic::target)
2904 .map_or(PioStringView::EMPTY, PioStringView::new)
2905}
2906
2907#[unsafe(no_mangle)]
2912pub unsafe extern "C" fn pio_diagnostic_has_suggested_action(
2913 diagnostics: *const PioDiagnostics,
2914 index: usize,
2915) -> bool {
2916 unsafe { PioDiagnostics::get(diagnostics) }
2917 .and_then(|values| values.records().get(index))
2918 .is_some_and(|record| record.suggested_action().is_some())
2919}
2920
2921#[unsafe(no_mangle)]
2926pub unsafe extern "C" fn pio_diagnostic_suggested_action(
2927 diagnostics: *const PioDiagnostics,
2928 index: usize,
2929) -> PioStringView {
2930 unsafe { PioDiagnostics::get(diagnostics) }
2931 .and_then(|values| values.records().get(index))
2932 .and_then(Diagnostic::suggested_action)
2933 .map_or(PioStringView::EMPTY, PioStringView::new)
2934}
2935
2936#[unsafe(no_mangle)]
2941pub unsafe extern "C" fn pio_diagnostic_n_spans(
2942 diagnostics: *const PioDiagnostics,
2943 index: usize,
2944) -> usize {
2945 unsafe { PioDiagnostics::get(diagnostics) }
2946 .and_then(|values| values.records().get(index))
2947 .map_or(0, |record| record.spans().len())
2948}
2949
2950#[unsafe(no_mangle)]
2955pub unsafe extern "C" fn pio_diagnostic_span(
2956 diagnostics: *const PioDiagnostics,
2957 index: usize,
2958 span_index: usize,
2959 output: *mut PioDiagnosticSpanView,
2960 error: *mut *mut PioError,
2961) -> bool {
2962 unsafe {
2963 entry(error, false, || {
2964 let values = PioDiagnostics::get(diagnostics).ok_or_else(|| {
2965 boundary_error(
2966 &codes::BIND_CAPI_NULL_HANDLE,
2967 "PioDiagnostics must not be NULL",
2968 )
2969 })?;
2970 let record = values.records().get(index).ok_or_else(|| {
2971 boundary_error(
2972 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
2973 format!("diagnostic index {index} is out of range"),
2974 )
2975 })?;
2976 let span = record.spans().get(span_index).ok_or_else(|| {
2977 boundary_error(
2978 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
2979 format!("diagnostic span index {span_index} is out of range"),
2980 )
2981 })?;
2982 *require_output(output, "output")? = PioDiagnosticSpanView {
2983 source: PioStringView::new(span.source().as_str()),
2984 byte_start: span.byte_start(),
2985 byte_end: span.byte_end(),
2986 };
2987 Ok(true)
2988 })
2989 }
2990}
2991
2992#[unsafe(no_mangle)]
2997pub unsafe extern "C" fn pio_diagnostic_n_related(
2998 diagnostics: *const PioDiagnostics,
2999 index: usize,
3000) -> usize {
3001 unsafe { PioDiagnostics::get(diagnostics) }
3002 .and_then(|values| values.records().get(index))
3003 .map_or(0, |record| record.related().len())
3004}
3005
3006#[unsafe(no_mangle)]
3011pub unsafe extern "C" fn pio_diagnostic_related(
3012 diagnostics: *const PioDiagnostics,
3013 index: usize,
3014 related_index: usize,
3015) -> PioStringView {
3016 unsafe { PioDiagnostics::get(diagnostics) }
3017 .and_then(|values| values.records().get(index))
3018 .and_then(|record| record.related().get(related_index))
3019 .map_or(PioStringView::EMPTY, |id| PioStringView::new(id.as_str()))
3020}
3021
3022#[unsafe(no_mangle)]
3027pub unsafe extern "C" fn pio_diagnostic_details_json(
3028 diagnostics: *const PioDiagnostics,
3029 index: usize,
3030 error: *mut *mut PioError,
3031) -> *mut PioString {
3032 unsafe {
3033 entry(error, std::ptr::null_mut(), || {
3034 let values = PioDiagnostics::get(diagnostics).ok_or_else(|| {
3035 boundary_error(
3036 &codes::BIND_CAPI_NULL_HANDLE,
3037 "PioDiagnostics must not be NULL",
3038 )
3039 })?;
3040 let record = values.records().get(index).ok_or_else(|| {
3041 boundary_error(
3042 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
3043 format!("diagnostic index {index} is out of range"),
3044 )
3045 })?;
3046 serde_json::to_string(record.details())
3047 .map(|text| PioString::new_raw(StringInner { text }))
3048 .map_err(|failure| {
3049 boundary_error(
3050 &codes::EMIT_CAPI_SERIALIZE_FAILED,
3051 format!("cannot serialize diagnostic details: {failure}"),
3052 )
3053 })
3054 })
3055 }
3056}
3057
3058#[unsafe(no_mangle)]
3063pub unsafe extern "C" fn pio_diagnostics_retain(
3064 diagnostics: *const PioDiagnostics,
3065) -> *mut PioDiagnostics {
3066 unsafe { PioDiagnostics::retain_raw(diagnostics) }
3067}
3068
3069#[unsafe(no_mangle)]
3074pub unsafe extern "C" fn pio_diagnostics_release(diagnostics: *mut PioDiagnostics) {
3075 unsafe { PioDiagnostics::release_raw(diagnostics) };
3076}
3077
3078opaque_handle!(
3081 PioSource,
3083 Source
3084);
3085
3086enum DestinationSpec {
3087 Path(PathBuf),
3088 Memory(String),
3089}
3090
3091impl DestinationSpec {
3092 fn build(&self) -> Result<Destination, powerio_core::Error> {
3093 match self {
3094 Self::Path(path) => Ok(Destination::path(path)),
3095 Self::Memory(root) => Destination::memory(root.clone()),
3096 }
3097 }
3098}
3099
3100opaque_handle!(
3101 PioDestination,
3103 DestinationSpec
3104);
3105
3106struct GeoLayerInner {
3107 layer: powerio::GeoLayer,
3108 diagnostics: Vec<Diagnostic>,
3109}
3110
3111opaque_handle!(
3112 PioGeoLayer,
3114 GeoLayerInner
3115);
3116opaque_handle!(
3117 PioGeoApplyReport,
3119 powerio::GeoApplyReport
3120);
3121
3122enum ContingencySource<T> {
3127 Owned(T),
3128 Value(ValueInner),
3129}
3130
3131struct ContingencySetInner {
3132 source: ContingencySource<powerio::ContingencySet>,
3133 diagnostics: Vec<Diagnostic>,
3136}
3137
3138impl ContingencySetInner {
3139 fn set(&self) -> Option<&powerio::ContingencySet> {
3140 match &self.source {
3141 ContingencySource::Owned(set) => Some(set),
3142 ContingencySource::Value(value) => match value.value()? {
3143 PioValue::ContingencySet(set) => Some(set),
3144 _ => None,
3145 },
3146 }
3147 }
3148}
3149
3150struct SubsystemSetInner {
3151 source: ContingencySource<powerio::SubsystemSet>,
3152}
3153
3154impl SubsystemSetInner {
3155 fn set(&self) -> Option<&powerio::SubsystemSet> {
3156 match &self.source {
3157 ContingencySource::Owned(set) => Some(set),
3158 ContingencySource::Value(value) => match value.value()? {
3159 PioValue::SubsystemSet(set) => Some(set),
3160 _ => None,
3161 },
3162 }
3163 }
3164}
3165
3166struct MonitoredSetInner {
3167 source: ContingencySource<powerio::MonitoredSet>,
3168}
3169
3170impl MonitoredSetInner {
3171 fn set(&self) -> Option<&powerio::MonitoredSet> {
3172 match &self.source {
3173 ContingencySource::Owned(set) => Some(set),
3174 ContingencySource::Value(value) => match value.value()? {
3175 PioValue::MonitoredSet(set) => Some(set),
3176 _ => None,
3177 },
3178 }
3179 }
3180}
3181
3182struct ContingencyResolutionInner {
3186 resolution: powerio::ContingencyResolution,
3187 unresolved_actions: Vec<Vec<String>>,
3188}
3189
3190impl ContingencyResolutionInner {
3191 fn new(resolution: powerio::ContingencyResolution) -> Self {
3192 let unresolved_actions = resolution
3193 .cases
3194 .iter()
3195 .map(|case| {
3196 case.unresolved
3197 .iter()
3198 .map(|unresolved| unresolved.action.to_con_statement())
3199 .collect()
3200 })
3201 .collect();
3202 Self {
3203 resolution,
3204 unresolved_actions,
3205 }
3206 }
3207}
3208
3209opaque_handle!(
3210 PioContingencySet,
3214 ContingencySetInner
3215);
3216opaque_handle!(
3217 PioSubsystemSet,
3220 SubsystemSetInner
3221);
3222opaque_handle!(
3223 PioMonitoredSet,
3226 MonitoredSetInner
3227);
3228opaque_handle!(
3229 PioContingencyResolution,
3231 ContingencyResolutionInner
3232);
3233
3234#[unsafe(no_mangle)]
3239pub unsafe extern "C" fn pio_source_open(
3240 path: *const c_char,
3241 path_len: usize,
3242 error: *mut *mut PioError,
3243) -> *mut PioSource {
3244 unsafe {
3245 entry(error, std::ptr::null_mut(), || {
3246 let path = required_str(path, path_len, "path")?;
3247 Source::open(path)
3248 .map(PioSource::new_raw)
3249 .map_err(|failure| error_from_core(&failure))
3250 })
3251 }
3252}
3253
3254#[unsafe(no_mangle)]
3259pub unsafe extern "C" fn pio_source_from_memory(
3260 name: *const c_char,
3261 name_len: usize,
3262 data: *const u8,
3263 data_len: usize,
3264 error: *mut *mut PioError,
3265) -> *mut PioSource {
3266 unsafe {
3267 entry(error, std::ptr::null_mut(), || {
3268 let name = required_str(name, name_len, "name")?;
3269 let bytes = input_bytes(data, data_len, "data")?;
3270 Source::from_memory(name, bytes.to_vec())
3271 .map(PioSource::new_raw)
3272 .map_err(|failure| error_from_core(&failure))
3273 })
3274 }
3275}
3276
3277#[unsafe(no_mangle)]
3285pub unsafe extern "C" fn pio_source_from_memory_with_buffers(
3286 name: *const c_char,
3287 name_len: usize,
3288 data: *const u8,
3289 data_len: usize,
3290 buffers: *const PioNamedBufferView,
3291 buffers_len: usize,
3292 error: *mut *mut PioError,
3293) -> *mut PioSource {
3294 unsafe {
3295 entry(error, std::ptr::null_mut(), || {
3296 let name = required_str(name, name_len, "name")?;
3297 let bytes = input_bytes(data, data_len, "data")?;
3298 let buffers = if buffers_len == 0 {
3299 &[]
3300 } else if buffers.is_null() {
3301 return Err(boundary_error(
3302 &codes::BIND_CAPI_NULL_ARGUMENT,
3303 "buffers is NULL with a nonzero length",
3304 ));
3305 } else {
3306 std::slice::from_raw_parts(buffers, buffers_len)
3307 };
3308 let mut source = Source::from_memory(name, bytes.to_vec())
3309 .map_err(|failure| error_from_core(&failure))?;
3310 for buffer in buffers {
3311 let name = required_str(buffer.name.data, buffer.name.len, "buffer name")?;
3312 let bytes = input_bytes(buffer.bytes.data, buffer.bytes.len, "buffer bytes")?;
3313 source = source
3314 .with_named_buffer(name, bytes.to_vec())
3315 .map_err(|failure| error_from_core(&failure))?;
3316 }
3317 Ok(PioSource::new_raw(source))
3318 })
3319 }
3320}
3321
3322#[unsafe(no_mangle)]
3327pub unsafe extern "C" fn pio_source_retain(source: *const PioSource) -> *mut PioSource {
3328 unsafe { PioSource::retain_raw(source) }
3329}
3330
3331#[unsafe(no_mangle)]
3336pub unsafe extern "C" fn pio_source_release(source: *mut PioSource) {
3337 unsafe { PioSource::release_raw(source) };
3338}
3339
3340#[unsafe(no_mangle)]
3345pub unsafe extern "C" fn pio_destination_path(
3346 path: *const c_char,
3347 path_len: usize,
3348 error: *mut *mut PioError,
3349) -> *mut PioDestination {
3350 unsafe {
3351 entry(error, std::ptr::null_mut(), || {
3352 let path = required_str(path, path_len, "path")?;
3353 Ok(PioDestination::new_raw(DestinationSpec::Path(
3354 PathBuf::from(path),
3355 )))
3356 })
3357 }
3358}
3359
3360#[unsafe(no_mangle)]
3365pub unsafe extern "C" fn pio_destination_memory(
3366 root: *const c_char,
3367 root_len: usize,
3368 error: *mut *mut PioError,
3369) -> *mut PioDestination {
3370 unsafe {
3371 entry(error, std::ptr::null_mut(), || {
3372 let root = required_str(root, root_len, "root")?;
3373 Destination::memory(root).map_err(|failure| error_from_core(&failure))?;
3374 Ok(PioDestination::new_raw(DestinationSpec::Memory(
3375 root.to_owned(),
3376 )))
3377 })
3378 }
3379}
3380
3381#[unsafe(no_mangle)]
3386pub unsafe extern "C" fn pio_destination_retain(
3387 destination: *const PioDestination,
3388) -> *mut PioDestination {
3389 unsafe { PioDestination::retain_raw(destination) }
3390}
3391
3392#[unsafe(no_mangle)]
3397pub unsafe extern "C" fn pio_destination_release(destination: *mut PioDestination) {
3398 unsafe { PioDestination::release_raw(destination) };
3399}
3400
3401#[unsafe(no_mangle)]
3406pub unsafe extern "C" fn pio_geo_layer_parse(
3407 source: *const PioSource,
3408 error: *mut *mut PioError,
3409) -> *mut PioGeoLayer {
3410 unsafe {
3411 entry(error, std::ptr::null_mut(), || {
3412 let source = PioSource::get(source).ok_or_else(|| {
3413 boundary_error(&codes::BIND_CAPI_NULL_HANDLE, "PioSource must not be NULL")
3414 })?;
3415 let buffer = source
3416 .primary_buffer()
3417 .map_err(|failure| error_from_core(&failure))?;
3418 let text = std::str::from_utf8(buffer.content_bytes()).map_err(|_| {
3419 boundary_error(
3420 &codes::BIND_CAPI_INVALID_UTF8,
3421 "a geographic sidecar must be valid UTF-8",
3422 )
3423 })?;
3424 powerio::GeoLayer::parse(text, Some(source.name()))
3425 .map(|parsed| {
3426 PioGeoLayer::new_raw(GeoLayerInner {
3427 layer: parsed.layer,
3428 diagnostics: parsed.diagnostics,
3429 })
3430 })
3431 .map_err(|failure| error_from_tx(&failure))
3432 })
3433 }
3434}
3435
3436#[unsafe(no_mangle)]
3441pub unsafe extern "C" fn pio_geo_layer_diagnostics(
3442 layer: *const PioGeoLayer,
3443) -> *mut PioDiagnostics {
3444 unsafe { PioGeoLayer::get(layer) }.map_or(std::ptr::null_mut(), |layer| {
3445 PioDiagnostics::new_raw(DiagnosticsInner {
3446 owner: DiagnosticsOwner::Owned(layer.diagnostics.clone()),
3447 })
3448 })
3449}
3450
3451#[unsafe(no_mangle)]
3459pub unsafe extern "C" fn pio_geo_layer_to_geojson(
3460 layer: *const PioGeoLayer,
3461 error: *mut *mut PioError,
3462) -> *mut PioString {
3463 unsafe {
3464 entry(error, std::ptr::null_mut(), || {
3465 let layer = PioGeoLayer::get(layer).ok_or_else(|| {
3466 boundary_error(
3467 &codes::BIND_CAPI_NULL_HANDLE,
3468 "PioGeoLayer must not be NULL",
3469 )
3470 })?;
3471 Ok(PioString::new_raw(StringInner {
3472 text: layer.layer.to_geojson(),
3473 }))
3474 })
3475 }
3476}
3477
3478#[unsafe(no_mangle)]
3483pub unsafe extern "C" fn pio_geo_layer_retain(layer: *const PioGeoLayer) -> *mut PioGeoLayer {
3484 unsafe { PioGeoLayer::retain_raw(layer) }
3485}
3486
3487#[unsafe(no_mangle)]
3492pub unsafe extern "C" fn pio_geo_layer_release(layer: *mut PioGeoLayer) {
3493 unsafe { PioGeoLayer::release_raw(layer) };
3494}
3495
3496unsafe fn contingency_source_text(
3499 source: *const PioSource,
3500 what: &str,
3501) -> Result<String, *mut PioError> {
3502 let source = unsafe { PioSource::get(source) }.ok_or_else(|| {
3503 boundary_error(&codes::BIND_CAPI_NULL_HANDLE, "PioSource must not be NULL")
3504 })?;
3505 let buffer = source
3506 .primary_buffer()
3507 .map_err(|failure| error_from_core(&failure))?;
3508 std::str::from_utf8(buffer.content_bytes())
3509 .map(str::to_owned)
3510 .map_err(|_| {
3511 boundary_error(
3512 &codes::BIND_CAPI_INVALID_UTF8,
3513 format!("{what} must be valid UTF-8"),
3514 )
3515 })
3516}
3517
3518unsafe fn require_contingency_set<'a>(
3519 set: *const PioContingencySet,
3520) -> Result<&'a powerio::ContingencySet, *mut PioError> {
3521 unsafe { PioContingencySet::get(set) }
3522 .and_then(ContingencySetInner::set)
3523 .ok_or_else(|| {
3524 boundary_error(
3525 &codes::BIND_CAPI_NULL_HANDLE,
3526 "PioContingencySet must not be NULL",
3527 )
3528 })
3529}
3530
3531unsafe fn require_subsystem_set<'a>(
3532 set: *const PioSubsystemSet,
3533) -> Result<&'a powerio::SubsystemSet, *mut PioError> {
3534 unsafe { PioSubsystemSet::get(set) }
3535 .and_then(SubsystemSetInner::set)
3536 .ok_or_else(|| {
3537 boundary_error(
3538 &codes::BIND_CAPI_NULL_HANDLE,
3539 "PioSubsystemSet must not be NULL",
3540 )
3541 })
3542}
3543
3544unsafe fn require_monitored_set<'a>(
3545 set: *const PioMonitoredSet,
3546) -> Result<&'a powerio::MonitoredSet, *mut PioError> {
3547 unsafe { PioMonitoredSet::get(set) }
3548 .and_then(MonitoredSetInner::set)
3549 .ok_or_else(|| {
3550 boundary_error(
3551 &codes::BIND_CAPI_NULL_HANDLE,
3552 "PioMonitoredSet must not be NULL",
3553 )
3554 })
3555}
3556
3557unsafe fn require_resolution<'a>(
3558 resolution: *const PioContingencyResolution,
3559) -> Result<&'a ContingencyResolutionInner, *mut PioError> {
3560 unsafe { PioContingencyResolution::get(resolution) }.ok_or_else(|| {
3561 boundary_error(
3562 &codes::BIND_CAPI_NULL_HANDLE,
3563 "PioContingencyResolution must not be NULL",
3564 )
3565 })
3566}
3567
3568unsafe fn require_resolved_case<'a>(
3569 resolution: *const PioContingencyResolution,
3570 index: usize,
3571) -> Result<&'a powerio::ResolvedCase, *mut PioError> {
3572 unsafe { require_resolution(resolution) }?
3573 .resolution
3574 .cases
3575 .get(index)
3576 .ok_or_else(|| {
3577 boundary_error(
3578 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
3579 format!("contingency case index {index} is out of range"),
3580 )
3581 })
3582}
3583
3584#[unsafe(no_mangle)]
3589pub unsafe extern "C" fn pio_contingency_set_parse(
3590 source: *const PioSource,
3591 error: *mut *mut PioError,
3592) -> *mut PioContingencySet {
3593 unsafe {
3594 entry(error, std::ptr::null_mut(), || {
3595 let text = contingency_source_text(source, "a contingency description file")?;
3596 powerio::ContingencySet::parse(&text)
3597 .map(|parsed| {
3598 PioContingencySet::new_raw(ContingencySetInner {
3599 source: ContingencySource::Owned(parsed.set),
3600 diagnostics: parsed.diagnostics,
3601 })
3602 })
3603 .map_err(|failure| error_from_tx(&failure))
3604 })
3605 }
3606}
3607
3608#[unsafe(no_mangle)]
3614pub unsafe extern "C" fn pio_contingency_set_diagnostics(
3615 set: *const PioContingencySet,
3616) -> *mut PioDiagnostics {
3617 unsafe { PioContingencySet::get(set) }.map_or(std::ptr::null_mut(), |set| {
3618 PioDiagnostics::new_raw(DiagnosticsInner {
3619 owner: DiagnosticsOwner::Owned(set.diagnostics.clone()),
3620 })
3621 })
3622}
3623
3624#[unsafe(no_mangle)]
3628pub unsafe extern "C" fn pio_contingency_set_case_count(set: *const PioContingencySet) -> usize {
3629 unsafe { PioContingencySet::get(set) }
3630 .and_then(ContingencySetInner::set)
3631 .map_or(0, |set| set.cases.len())
3632}
3633
3634#[unsafe(no_mangle)]
3639pub unsafe extern "C" fn pio_contingency_set_case_name(
3640 set: *const PioContingencySet,
3641 index: usize,
3642 error: *mut *mut PioError,
3643) -> PioStringView {
3644 unsafe {
3645 entry(error, PioStringView::EMPTY, || {
3646 let set = require_contingency_set(set)?;
3647 let case = set.cases.get(index).ok_or_else(|| {
3648 boundary_error(
3649 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
3650 format!("contingency case index {index} is out of range"),
3651 )
3652 })?;
3653 Ok(PioStringView::new(&case.name))
3654 })
3655 }
3656}
3657
3658#[unsafe(no_mangle)]
3665pub unsafe extern "C" fn pio_contingency_set_to_con(
3666 set: *const PioContingencySet,
3667 error: *mut *mut PioError,
3668) -> *mut PioString {
3669 unsafe {
3670 entry(error, std::ptr::null_mut(), || {
3671 let set = require_contingency_set(set)?;
3672 Ok(PioString::new_raw(StringInner { text: set.to_con() }))
3673 })
3674 }
3675}
3676
3677#[unsafe(no_mangle)]
3682pub unsafe extern "C" fn pio_contingency_set_retain(
3683 set: *const PioContingencySet,
3684) -> *mut PioContingencySet {
3685 unsafe { PioContingencySet::retain_raw(set) }
3686}
3687
3688#[unsafe(no_mangle)]
3693pub unsafe extern "C" fn pio_contingency_set_release(set: *mut PioContingencySet) {
3694 unsafe { PioContingencySet::release_raw(set) };
3695}
3696
3697#[unsafe(no_mangle)]
3701pub unsafe extern "C" fn pio_subsystem_set_count(set: *const PioSubsystemSet) -> usize {
3702 unsafe { PioSubsystemSet::get(set) }
3703 .and_then(SubsystemSetInner::set)
3704 .map_or(0, |set| set.subsystems.len())
3705}
3706
3707#[unsafe(no_mangle)]
3712pub unsafe extern "C" fn pio_subsystem_set_name(
3713 set: *const PioSubsystemSet,
3714 index: usize,
3715 error: *mut *mut PioError,
3716) -> PioStringView {
3717 unsafe {
3718 entry(error, PioStringView::EMPTY, || {
3719 let set = require_subsystem_set(set)?;
3720 let subsystem = set.subsystems.get(index).ok_or_else(|| {
3721 boundary_error(
3722 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
3723 format!("subsystem index {index} is out of range"),
3724 )
3725 })?;
3726 Ok(PioStringView::new(&subsystem.name))
3727 })
3728 }
3729}
3730
3731#[unsafe(no_mangle)]
3738pub unsafe extern "C" fn pio_subsystem_set_to_sub(
3739 set: *const PioSubsystemSet,
3740 error: *mut *mut PioError,
3741) -> *mut PioString {
3742 unsafe {
3743 entry(error, std::ptr::null_mut(), || {
3744 let set = require_subsystem_set(set)?;
3745 Ok(PioString::new_raw(StringInner { text: set.to_sub() }))
3746 })
3747 }
3748}
3749
3750#[unsafe(no_mangle)]
3755pub unsafe extern "C" fn pio_subsystem_set_retain(
3756 set: *const PioSubsystemSet,
3757) -> *mut PioSubsystemSet {
3758 unsafe { PioSubsystemSet::retain_raw(set) }
3759}
3760
3761#[unsafe(no_mangle)]
3766pub unsafe extern "C" fn pio_subsystem_set_release(set: *mut PioSubsystemSet) {
3767 unsafe { PioSubsystemSet::release_raw(set) };
3768}
3769
3770#[unsafe(no_mangle)]
3774pub unsafe extern "C" fn pio_monitored_set_statement_count(set: *const PioMonitoredSet) -> usize {
3775 unsafe { PioMonitoredSet::get(set) }
3776 .and_then(MonitoredSetInner::set)
3777 .map_or(0, |set| set.statements.len())
3778}
3779
3780#[unsafe(no_mangle)]
3787pub unsafe extern "C" fn pio_monitored_set_to_mon(
3788 set: *const PioMonitoredSet,
3789 error: *mut *mut PioError,
3790) -> *mut PioString {
3791 unsafe {
3792 entry(error, std::ptr::null_mut(), || {
3793 let set = require_monitored_set(set)?;
3794 Ok(PioString::new_raw(StringInner { text: set.to_mon() }))
3795 })
3796 }
3797}
3798
3799#[unsafe(no_mangle)]
3804pub unsafe extern "C" fn pio_monitored_set_retain(
3805 set: *const PioMonitoredSet,
3806) -> *mut PioMonitoredSet {
3807 unsafe { PioMonitoredSet::retain_raw(set) }
3808}
3809
3810#[unsafe(no_mangle)]
3815pub unsafe extern "C" fn pio_monitored_set_release(set: *mut PioMonitoredSet) {
3816 unsafe { PioMonitoredSet::release_raw(set) };
3817}
3818
3819#[unsafe(no_mangle)]
3828pub unsafe extern "C" fn pio_contingency_set_resolve(
3829 set: *const PioContingencySet,
3830 network: *const PioBalancedNetwork,
3831 error: *mut *mut PioError,
3832) -> *mut PioContingencyResolution {
3833 unsafe {
3834 entry(error, std::ptr::null_mut(), || {
3835 let set = require_contingency_set(set)?;
3836 let network = require_balanced_network(network)?;
3837 Ok(PioContingencyResolution::new_raw(
3838 ContingencyResolutionInner::new(set.resolve(network)),
3839 ))
3840 })
3841 }
3842}
3843
3844#[unsafe(no_mangle)]
3855pub unsafe extern "C" fn pio_contingency_set_expand(
3856 set: *const PioContingencySet,
3857 network: *const PioBalancedNetwork,
3858 subsystems: *const PioSubsystemSet,
3859 out_notes: *mut *mut PioDiagnostics,
3860 error: *mut *mut PioError,
3861) -> *mut PioContingencySet {
3862 unsafe {
3863 if !out_notes.is_null() {
3864 *out_notes = std::ptr::null_mut();
3865 }
3866 entry(error, std::ptr::null_mut(), || {
3867 let set = require_contingency_set(set)?;
3868 let network = require_balanced_network(network)?;
3869 let subsystems = require_subsystem_set(subsystems)?;
3870 let expanded = set.expand(network, subsystems);
3871 if !out_notes.is_null() {
3872 *out_notes = PioDiagnostics::new_raw(DiagnosticsInner {
3873 owner: DiagnosticsOwner::Owned(expanded.diagnostics),
3874 });
3875 }
3876 Ok(PioContingencySet::new_raw(ContingencySetInner {
3877 source: ContingencySource::Owned(expanded.set),
3878 diagnostics: Vec::new(),
3879 }))
3880 })
3881 }
3882}
3883
3884#[unsafe(no_mangle)]
3898pub unsafe extern "C" fn pio_balanced_network_select_subsystem_buses(
3899 network: *const PioBalancedNetwork,
3900 subsystems: *const PioSubsystemSet,
3901 name: *const c_char,
3902 name_len: usize,
3903 error: *mut *mut PioError,
3904) -> *mut PioVector {
3905 unsafe {
3906 entry(error, std::ptr::null_mut(), || {
3907 let network = require_balanced_network(network)?;
3908 let subsystems = require_subsystem_set(subsystems)?;
3909 let name = required_str(name, name_len, "name")?;
3910 let subsystem = subsystems.get(name).ok_or_else(|| {
3911 boundary_error(
3912 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
3913 format!("subsystem '{name}' is not stated by the subsystem set"),
3914 )
3915 })?;
3916 let values = subsystem
3917 .select_buses(network)
3918 .iter()
3919 .map(|bus| bus.0 as f64)
3920 .collect();
3921 Ok(PioVector::new_raw(VectorInner { values }))
3922 })
3923 }
3924}
3925
3926#[unsafe(no_mangle)]
3930pub unsafe extern "C" fn pio_contingency_resolution_case_count(
3931 resolution: *const PioContingencyResolution,
3932) -> usize {
3933 unsafe { PioContingencyResolution::get(resolution) }
3934 .map_or(0, |inner| inner.resolution.cases.len())
3935}
3936
3937#[unsafe(no_mangle)]
3942pub unsafe extern "C" fn pio_contingency_resolution_resolved_count(
3943 resolution: *const PioContingencyResolution,
3944) -> usize {
3945 unsafe { PioContingencyResolution::get(resolution) }
3946 .map_or(0, |inner| inner.resolution.resolved)
3947}
3948
3949#[unsafe(no_mangle)]
3954pub unsafe extern "C" fn pio_contingency_resolution_unresolved_count(
3955 resolution: *const PioContingencyResolution,
3956) -> usize {
3957 unsafe { PioContingencyResolution::get(resolution) }
3958 .map_or(0, |inner| inner.resolution.unresolved)
3959}
3960
3961#[unsafe(no_mangle)]
3966pub unsafe extern "C" fn pio_contingency_resolution_unrecognized_statement_count(
3967 resolution: *const PioContingencyResolution,
3968) -> usize {
3969 unsafe { PioContingencyResolution::get(resolution) }
3970 .map_or(0, |inner| inner.resolution.unrecognized_statements)
3971}
3972
3973#[unsafe(no_mangle)]
3978pub unsafe extern "C" fn pio_contingency_resolution_case_name(
3979 resolution: *const PioContingencyResolution,
3980 index: usize,
3981 error: *mut *mut PioError,
3982) -> PioStringView {
3983 unsafe {
3984 entry(error, PioStringView::EMPTY, || {
3985 let case = require_resolved_case(resolution, index)?;
3986 Ok(PioStringView::new(&case.name))
3987 })
3988 }
3989}
3990
3991#[unsafe(no_mangle)]
3998pub unsafe extern "C" fn pio_contingency_resolution_case_is_resolved(
3999 resolution: *const PioContingencyResolution,
4000 index: usize,
4001) -> bool {
4002 unsafe { PioContingencyResolution::get(resolution) }
4003 .and_then(|inner| inner.resolution.cases.get(index))
4004 .is_some_and(powerio::ResolvedCase::is_resolved)
4005}
4006
4007#[unsafe(no_mangle)]
4012pub unsafe extern "C" fn pio_contingency_resolution_case_component_count(
4013 resolution: *const PioContingencyResolution,
4014 index: usize,
4015) -> usize {
4016 unsafe { PioContingencyResolution::get(resolution) }
4017 .and_then(|inner| inner.resolution.cases.get(index))
4018 .map_or(0, |case| case.components.len())
4019}
4020
4021#[unsafe(no_mangle)]
4031pub unsafe extern "C" fn pio_contingency_resolution_case_component(
4032 resolution: *const PioContingencyResolution,
4033 case_index: usize,
4034 component_index: usize,
4035 output: *mut PioContingencyComponentView,
4036 error: *mut *mut PioError,
4037) -> bool {
4038 unsafe {
4039 entry(error, false, || {
4040 let case = require_resolved_case(resolution, case_index)?;
4041 let component = case.components.get(component_index).ok_or_else(|| {
4042 boundary_error(
4043 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
4044 format!(
4045 "contingency case {case_index} component index {component_index} is out of range"
4046 ),
4047 )
4048 })?;
4049 *require_output(output, "output")? = PioContingencyComponentView {
4050 id: PioComponentIdView {
4051 component_type: PioStringView::new(component.component_type),
4052 local_id: component
4053 .id
4054 .as_ref()
4055 .map_or(PioStringView::EMPTY, |id| PioStringView::new(id.local_id())),
4056 },
4057 row: component.row,
4058 in_service: component.in_service,
4059 };
4060 Ok(true)
4061 })
4062 }
4063}
4064
4065#[unsafe(no_mangle)]
4070pub unsafe extern "C" fn pio_contingency_resolution_case_unresolved_count(
4071 resolution: *const PioContingencyResolution,
4072 index: usize,
4073) -> usize {
4074 unsafe { PioContingencyResolution::get(resolution) }
4075 .and_then(|inner| inner.resolution.cases.get(index))
4076 .map_or(0, |case| case.unresolved.len())
4077}
4078
4079#[unsafe(no_mangle)]
4089pub unsafe extern "C" fn pio_contingency_resolution_case_unresolved_reason(
4090 resolution: *const PioContingencyResolution,
4091 case_index: usize,
4092 unresolved_index: usize,
4093 error: *mut *mut PioError,
4094) -> PioStringView {
4095 unsafe {
4096 entry(error, PioStringView::EMPTY, || {
4097 let case = require_resolved_case(resolution, case_index)?;
4098 let action = case.unresolved.get(unresolved_index).ok_or_else(|| {
4099 boundary_error(
4100 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
4101 format!(
4102 "contingency case {case_index} unresolved index {unresolved_index} is out of range"
4103 ),
4104 )
4105 })?;
4106 Ok(PioStringView::new(action.reason.name()))
4107 })
4108 }
4109}
4110
4111#[unsafe(no_mangle)]
4119pub unsafe extern "C" fn pio_contingency_resolution_case_unresolved_action(
4120 resolution: *const PioContingencyResolution,
4121 case_index: usize,
4122 unresolved_index: usize,
4123 error: *mut *mut PioError,
4124) -> PioStringView {
4125 unsafe {
4126 entry(error, PioStringView::EMPTY, || {
4127 let inner = require_resolution(resolution)?;
4128 let case = inner.unresolved_actions.get(case_index).ok_or_else(|| {
4129 boundary_error(
4130 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
4131 format!("contingency case index {case_index} is out of range"),
4132 )
4133 })?;
4134 let statement = case.get(unresolved_index).ok_or_else(|| {
4135 boundary_error(
4136 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
4137 format!(
4138 "contingency case {case_index} unresolved index {unresolved_index} is out of range"
4139 ),
4140 )
4141 })?;
4142 Ok(PioStringView::new(statement))
4143 })
4144 }
4145}
4146
4147#[unsafe(no_mangle)]
4152pub unsafe extern "C" fn pio_contingency_resolution_retain(
4153 resolution: *const PioContingencyResolution,
4154) -> *mut PioContingencyResolution {
4155 unsafe { PioContingencyResolution::retain_raw(resolution) }
4156}
4157
4158#[unsafe(no_mangle)]
4163pub unsafe extern "C" fn pio_contingency_resolution_release(
4164 resolution: *mut PioContingencyResolution,
4165) {
4166 unsafe { PioContingencyResolution::release_raw(resolution) };
4167}
4168
4169#[derive(Clone)]
4172struct ModuleInner {
4173 module: powerio::PioModule<PioValue>,
4174}
4175
4176opaque_handle!(
4177 PioModule,
4179 ModuleInner
4180);
4181
4182#[derive(Clone, Copy)]
4183enum ModuleJsonRoot {
4184 Extension(usize),
4185 HistoryParameter {
4186 history_index: usize,
4187 parameter_index: usize,
4188 },
4189}
4190
4191#[derive(Clone, Copy)]
4192enum JsonValueStep {
4193 Array(usize),
4194 Object(usize),
4195}
4196
4197struct JsonValueInner {
4198 owner: Arc<ModuleInner>,
4199 root: ModuleJsonRoot,
4200 steps: Vec<JsonValueStep>,
4201}
4202
4203impl JsonValueInner {
4204 fn child(&self, step: JsonValueStep) -> Self {
4205 let mut steps = self.steps.clone();
4206 steps.push(step);
4207 Self {
4208 owner: Arc::clone(&self.owner),
4209 root: self.root,
4210 steps,
4211 }
4212 }
4213
4214 fn value(&self) -> Option<&serde_json::Value> {
4215 let mut value = match self.root {
4216 ModuleJsonRoot::Extension(index) => {
4217 self.owner.module.extensions().values().nth(index)?
4218 }
4219 ModuleJsonRoot::HistoryParameter {
4220 history_index,
4221 parameter_index,
4222 } => self
4223 .owner
4224 .module
4225 .history()
4226 .get(history_index)?
4227 .parameters()
4228 .values()
4229 .nth(parameter_index)?,
4230 };
4231 for step in &self.steps {
4232 value = match (step, value) {
4233 (JsonValueStep::Array(index), serde_json::Value::Array(values)) => {
4234 values.get(*index)?
4235 }
4236 (JsonValueStep::Object(index), serde_json::Value::Object(values)) => {
4237 values.values().nth(*index)?
4238 }
4239 _ => return None,
4240 };
4241 }
4242 Some(value)
4243 }
4244}
4245
4246opaque_handle!(
4247 PioJsonValue,
4249 JsonValueInner
4250);
4251
4252#[derive(Clone, Copy)]
4253enum ValueStep {
4254 TimeSeries(usize),
4255 Scenario(usize),
4256}
4257
4258struct ValueInner {
4259 owner: Arc<ModuleInner>,
4260 steps: Vec<ValueStep>,
4261}
4262
4263impl ValueInner {
4264 fn root(owner: Arc<ModuleInner>) -> Self {
4265 Self {
4266 owner,
4267 steps: Vec::new(),
4268 }
4269 }
4270
4271 fn child(&self, step: ValueStep) -> Self {
4272 let mut steps = self.steps.clone();
4273 steps.push(step);
4274 Self {
4275 owner: Arc::clone(&self.owner),
4276 steps,
4277 }
4278 }
4279
4280 fn value(&self) -> Option<&PioValue> {
4281 let mut value = self.owner.module.value();
4282 for step in &self.steps {
4283 value = match (step, value) {
4284 (ValueStep::TimeSeries(index), PioValue::TimeSeries(series)) => {
4285 series.get(*index)?
4286 }
4287 (ValueStep::Scenario(index), PioValue::ScenarioSet(scenarios)) => {
4288 scenarios.get_at(*index)?
4289 }
4290 _ => return None,
4291 };
4292 }
4293 Some(value)
4294 }
4295}
4296
4297opaque_handle!(
4298 PioValueHandle,
4300 ValueInner
4301);
4302
4303#[derive(Clone, Copy)]
4304enum BalancedNetworkProjection {
4305 Direct,
4306 OperatingPoint,
4307 DcPfInstance,
4308 AcPfInstance,
4309 DcOpfInstance,
4310 AcOpfInstance,
4311 AcOtsInstance,
4312 AcScucInstance,
4313 DcPfSolution,
4314 AcPfSolution,
4315 DcOpfSolution,
4316 AcOpfSolution,
4317 AcOtsSolution,
4318 SocwrOpfSolution,
4319 AcScucSolution,
4320}
4321
4322struct BalancedNetworkInner {
4323 value: ValueInner,
4324 projection: BalancedNetworkProjection,
4325}
4326
4327impl BalancedNetworkInner {
4328 fn network(&self) -> Option<&BalancedNetwork> {
4329 match (self.projection, self.value.value()?) {
4330 (BalancedNetworkProjection::Direct, PioValue::BalancedNetwork(network)) => {
4331 Some(network)
4332 }
4333 (
4334 BalancedNetworkProjection::OperatingPoint,
4335 PioValue::BalancedOperatingPoint(point),
4336 ) => Some(point.network()),
4337 (BalancedNetworkProjection::DcPfInstance, PioValue::DcPfInstance(instance)) => {
4338 Some(instance.network())
4339 }
4340 (BalancedNetworkProjection::AcPfInstance, PioValue::AcPfInstance(instance)) => {
4341 Some(instance.network())
4342 }
4343 (BalancedNetworkProjection::DcOpfInstance, PioValue::DcOpfInstance(instance)) => {
4344 Some(instance.network())
4345 }
4346 (BalancedNetworkProjection::AcOpfInstance, PioValue::AcOpfInstance(instance)) => {
4347 Some(instance.network())
4348 }
4349 (BalancedNetworkProjection::AcOtsInstance, PioValue::AcOtsInstance(instance)) => {
4350 Some(instance.network())
4351 }
4352 (BalancedNetworkProjection::AcScucInstance, PioValue::AcScucInstance(instance)) => {
4353 Some(instance.network())
4354 }
4355 (BalancedNetworkProjection::DcPfSolution, PioValue::DcPfSolution(solution)) => {
4356 Some(solution.network())
4357 }
4358 (BalancedNetworkProjection::AcPfSolution, PioValue::AcPfSolution(solution)) => {
4359 Some(solution.network())
4360 }
4361 (BalancedNetworkProjection::DcOpfSolution, PioValue::DcOpfSolution(solution)) => {
4362 Some(solution.network())
4363 }
4364 (BalancedNetworkProjection::AcOpfSolution, PioValue::AcOpfSolution(solution)) => {
4365 Some(solution.network())
4366 }
4367 (BalancedNetworkProjection::AcOtsSolution, PioValue::AcOtsSolution(solution)) => {
4368 Some(solution.network())
4369 }
4370 (BalancedNetworkProjection::SocwrOpfSolution, PioValue::SocwrOpfSolution(solution)) => {
4371 Some(solution.network())
4372 }
4373 (BalancedNetworkProjection::AcScucSolution, PioValue::AcScucSolution(solution)) => {
4374 Some(solution.instance().network())
4375 }
4376 _ => None,
4377 }
4378 }
4379}
4380
4381#[derive(Clone, Copy)]
4382enum MulticonductorNetworkProjection {
4383 Direct,
4384 OperatingPoint,
4385 McAcPfInstance,
4386 McAcOpfInstance,
4387 LinDist3FlowOpfInstance,
4388 McAcPfSolution,
4389 McAcOpfSolution,
4390 LinDist3FlowOpfSolution,
4391}
4392
4393struct MulticonductorNetworkInner {
4394 value: ValueInner,
4395 projection: MulticonductorNetworkProjection,
4396}
4397
4398impl MulticonductorNetworkInner {
4399 fn network(&self) -> Option<&powerio::MulticonductorNetwork> {
4400 match (self.projection, self.value.value()?) {
4401 (MulticonductorNetworkProjection::Direct, PioValue::MulticonductorNetwork(network)) => {
4402 Some(network)
4403 }
4404 (
4405 MulticonductorNetworkProjection::OperatingPoint,
4406 PioValue::MulticonductorOperatingPoint(point),
4407 ) => Some(point.network()),
4408 (
4409 MulticonductorNetworkProjection::McAcPfInstance,
4410 PioValue::McAcPfInstance(instance),
4411 ) => Some(instance.network()),
4412 (
4413 MulticonductorNetworkProjection::McAcOpfInstance,
4414 PioValue::McAcOpfInstance(instance),
4415 ) => Some(instance.network()),
4416 (
4417 MulticonductorNetworkProjection::LinDist3FlowOpfInstance,
4418 PioValue::LinDist3FlowOpfInstance(instance),
4419 ) => Some(instance.network()),
4420 (
4421 MulticonductorNetworkProjection::McAcPfSolution,
4422 PioValue::McAcPfSolution(solution),
4423 ) => Some(solution.network()),
4424 (
4425 MulticonductorNetworkProjection::McAcOpfSolution,
4426 PioValue::McAcOpfSolution(solution),
4427 ) => Some(solution.network()),
4428 (
4429 MulticonductorNetworkProjection::LinDist3FlowOpfSolution,
4430 PioValue::LinDist3FlowOpfSolution(solution),
4431 ) => Some(solution.network()),
4432 _ => None,
4433 }
4434 }
4435}
4436
4437#[derive(Clone, Copy)]
4438enum OperatingPointProjection {
4439 DirectBalanced,
4440 DirectMulticonductor,
4441 DcPfInitial,
4442 AcPfInitial,
4443 DcOpfInitial,
4444 AcOpfInitial,
4445 AcOtsInitial,
4446 McAcPfInitial,
4447 McAcOpfInitial,
4448 LinDist3FlowOpfInitial,
4449 DcPfSolutionInitial,
4450 AcPfSolutionInitial,
4451 DcOpfSolutionInitial,
4452 AcOpfSolutionInitial,
4453 AcOtsSolutionInitial,
4454 SocwrOpfSolutionInitial,
4455 McAcPfSolutionInitial,
4456 McAcOpfSolutionInitial,
4457 LinDist3FlowOpfSolutionInitial,
4458}
4459
4460struct OperatingPointInner {
4461 value: ValueInner,
4462 projection: OperatingPointProjection,
4463}
4464
4465impl OperatingPointInner {
4466 fn balanced(&self) -> Option<&powerio_prob::OperatingPoint<BalancedNetwork>> {
4467 match (self.projection, self.value.value()?) {
4468 (OperatingPointProjection::DirectBalanced, PioValue::BalancedOperatingPoint(point)) => {
4469 Some(point)
4470 }
4471 (OperatingPointProjection::DcPfInitial, PioValue::DcPfInstance(instance)) => {
4472 instance.initial_point()
4473 }
4474 (OperatingPointProjection::AcPfInitial, PioValue::AcPfInstance(instance)) => {
4475 instance.initial_point()
4476 }
4477 (OperatingPointProjection::DcOpfInitial, PioValue::DcOpfInstance(instance)) => {
4478 instance.initial_point()
4479 }
4480 (OperatingPointProjection::AcOpfInitial, PioValue::AcOpfInstance(instance)) => {
4481 instance.initial_point()
4482 }
4483 (OperatingPointProjection::AcOtsInitial, PioValue::AcOtsInstance(instance)) => {
4484 instance.initial_point()
4485 }
4486 (OperatingPointProjection::DcPfSolutionInitial, PioValue::DcPfSolution(solution)) => {
4487 solution.instance().initial_point()
4488 }
4489 (OperatingPointProjection::AcPfSolutionInitial, PioValue::AcPfSolution(solution)) => {
4490 solution.instance().initial_point()
4491 }
4492 (OperatingPointProjection::DcOpfSolutionInitial, PioValue::DcOpfSolution(solution)) => {
4493 solution.instance().initial_point()
4494 }
4495 (OperatingPointProjection::AcOpfSolutionInitial, PioValue::AcOpfSolution(solution)) => {
4496 solution.instance().initial_point()
4497 }
4498 (OperatingPointProjection::AcOtsSolutionInitial, PioValue::AcOtsSolution(solution)) => {
4499 solution.instance().initial_point()
4500 }
4501 (
4502 OperatingPointProjection::SocwrOpfSolutionInitial,
4503 PioValue::SocwrOpfSolution(solution),
4504 ) => solution.instance().initial_point(),
4505 _ => None,
4506 }
4507 }
4508
4509 fn multiconductor(
4510 &self,
4511 ) -> Option<&powerio_prob::OperatingPoint<powerio::MulticonductorNetwork>> {
4512 match (self.projection, self.value.value()?) {
4513 (
4514 OperatingPointProjection::DirectMulticonductor,
4515 PioValue::MulticonductorOperatingPoint(point),
4516 ) => Some(point),
4517 (OperatingPointProjection::McAcPfInitial, PioValue::McAcPfInstance(instance)) => {
4518 instance.initial_point()
4519 }
4520 (OperatingPointProjection::McAcOpfInitial, PioValue::McAcOpfInstance(instance)) => {
4521 instance.initial_point()
4522 }
4523 (
4524 OperatingPointProjection::LinDist3FlowOpfInitial,
4525 PioValue::LinDist3FlowOpfInstance(instance),
4526 ) => instance.base_instance().initial_point(),
4527 (
4528 OperatingPointProjection::McAcPfSolutionInitial,
4529 PioValue::McAcPfSolution(solution),
4530 ) => solution.instance().initial_point(),
4531 (
4532 OperatingPointProjection::McAcOpfSolutionInitial,
4533 PioValue::McAcOpfSolution(solution),
4534 ) => solution.instance().initial_point(),
4535 (
4536 OperatingPointProjection::LinDist3FlowOpfSolutionInitial,
4537 PioValue::LinDist3FlowOpfSolution(solution),
4538 ) => solution.instance().base_instance().initial_point(),
4539 _ => None,
4540 }
4541 }
4542
4543 fn type_name(&self) -> Option<&'static str> {
4544 if self.balanced().is_some() {
4545 Some("powerio.OperatingPoint<powerio.BalancedNetwork>")
4546 } else if self.multiconductor().is_some() {
4547 Some("powerio.OperatingPoint<powerio.MulticonductorNetwork>")
4548 } else {
4549 None
4550 }
4551 }
4552
4553 fn balanced_network_projection(&self) -> Option<BalancedNetworkProjection> {
4554 self.balanced()?;
4555 Some(match self.projection {
4556 OperatingPointProjection::DirectBalanced => BalancedNetworkProjection::OperatingPoint,
4557 OperatingPointProjection::DcPfInitial => BalancedNetworkProjection::DcPfInstance,
4558 OperatingPointProjection::AcPfInitial => BalancedNetworkProjection::AcPfInstance,
4559 OperatingPointProjection::DcOpfInitial => BalancedNetworkProjection::DcOpfInstance,
4560 OperatingPointProjection::AcOpfInitial => BalancedNetworkProjection::AcOpfInstance,
4561 OperatingPointProjection::AcOtsInitial => BalancedNetworkProjection::AcOtsInstance,
4562 OperatingPointProjection::DcPfSolutionInitial => {
4563 BalancedNetworkProjection::DcPfSolution
4564 }
4565 OperatingPointProjection::AcPfSolutionInitial => {
4566 BalancedNetworkProjection::AcPfSolution
4567 }
4568 OperatingPointProjection::DcOpfSolutionInitial => {
4569 BalancedNetworkProjection::DcOpfSolution
4570 }
4571 OperatingPointProjection::AcOpfSolutionInitial => {
4572 BalancedNetworkProjection::AcOpfSolution
4573 }
4574 OperatingPointProjection::AcOtsSolutionInitial => {
4575 BalancedNetworkProjection::AcOtsSolution
4576 }
4577 OperatingPointProjection::SocwrOpfSolutionInitial => {
4578 BalancedNetworkProjection::SocwrOpfSolution
4579 }
4580 _ => return None,
4581 })
4582 }
4583
4584 fn multiconductor_network_projection(&self) -> Option<MulticonductorNetworkProjection> {
4585 self.multiconductor()?;
4586 Some(match self.projection {
4587 OperatingPointProjection::DirectMulticonductor => {
4588 MulticonductorNetworkProjection::OperatingPoint
4589 }
4590 OperatingPointProjection::McAcPfInitial => {
4591 MulticonductorNetworkProjection::McAcPfInstance
4592 }
4593 OperatingPointProjection::McAcOpfInitial => {
4594 MulticonductorNetworkProjection::McAcOpfInstance
4595 }
4596 OperatingPointProjection::LinDist3FlowOpfInitial => {
4597 MulticonductorNetworkProjection::LinDist3FlowOpfInstance
4598 }
4599 OperatingPointProjection::McAcPfSolutionInitial => {
4600 MulticonductorNetworkProjection::McAcPfSolution
4601 }
4602 OperatingPointProjection::McAcOpfSolutionInitial => {
4603 MulticonductorNetworkProjection::McAcOpfSolution
4604 }
4605 OperatingPointProjection::LinDist3FlowOpfSolutionInitial => {
4606 MulticonductorNetworkProjection::LinDist3FlowOpfSolution
4607 }
4608 _ => return None,
4609 })
4610 }
4611}
4612
4613#[derive(Clone, Copy)]
4614enum CalculationInstanceProjection {
4615 Direct,
4616 DcPfSolution,
4617 AcPfSolution,
4618 DcOpfSolution,
4619 AcOpfSolution,
4620 AcOtsSolution,
4621 SocwrOpfSolution,
4622 McAcPfSolution,
4623 McAcOpfSolution,
4624 LinDist3FlowOpfSolution,
4625 AcScucSolution,
4626}
4627
4628#[derive(Clone, Copy)]
4629enum CalculationInstanceRef<'a> {
4630 DcPf(&'a powerio_prob::DcPfInstance),
4631 AcPf(&'a powerio_prob::AcPfInstance),
4632 DcOpf(&'a powerio_prob::DcOpfInstance),
4633 AcOpf(&'a powerio_prob::AcOpfInstance),
4634 AcOts(&'a powerio_prob::AcOtsInstance),
4635 McAcPf(&'a powerio_prob::McAcPfInstance),
4636 McAcOpf(&'a powerio_prob::McAcOpfInstance),
4637 LinDist3FlowOpf(&'a powerio_prob::LinDist3FlowOpfInstance),
4638 AcScuc(&'a powerio_prob::AcScucInstance),
4639}
4640
4641impl CalculationInstanceRef<'_> {
4642 fn type_name(self) -> &'static str {
4643 match self {
4644 Self::DcPf(_) => "powerio.DcPfInstance",
4645 Self::AcPf(_) => "powerio.AcPfInstance",
4646 Self::DcOpf(_) => "powerio.DcOpfInstance",
4647 Self::AcOpf(_) => "powerio.AcOpfInstance",
4648 Self::AcOts(_) => "powerio.AcOtsInstance",
4649 Self::McAcPf(_) => "powerio.McAcPfInstance",
4650 Self::McAcOpf(_) => "powerio.McAcOpfInstance",
4651 Self::LinDist3FlowOpf(_) => "powerio.LinDist3FlowOpfInstance",
4652 Self::AcScuc(_) => "powerio.AcScucInstance",
4653 }
4654 }
4655}
4656
4657struct CalculationInstanceInner {
4658 value: ValueInner,
4659 projection: CalculationInstanceProjection,
4660}
4661
4662impl CalculationInstanceInner {
4663 fn instance(&self) -> Option<CalculationInstanceRef<'_>> {
4664 match (self.projection, self.value.value()?) {
4665 (CalculationInstanceProjection::Direct, PioValue::DcPfInstance(instance)) => {
4666 Some(CalculationInstanceRef::DcPf(instance))
4667 }
4668 (CalculationInstanceProjection::Direct, PioValue::AcPfInstance(instance)) => {
4669 Some(CalculationInstanceRef::AcPf(instance))
4670 }
4671 (CalculationInstanceProjection::Direct, PioValue::DcOpfInstance(instance)) => {
4672 Some(CalculationInstanceRef::DcOpf(instance))
4673 }
4674 (CalculationInstanceProjection::Direct, PioValue::AcOpfInstance(instance)) => {
4675 Some(CalculationInstanceRef::AcOpf(instance))
4676 }
4677 (CalculationInstanceProjection::Direct, PioValue::AcOtsInstance(instance)) => {
4678 Some(CalculationInstanceRef::AcOts(instance))
4679 }
4680 (CalculationInstanceProjection::Direct, PioValue::McAcPfInstance(instance)) => {
4681 Some(CalculationInstanceRef::McAcPf(instance))
4682 }
4683 (CalculationInstanceProjection::Direct, PioValue::McAcOpfInstance(instance)) => {
4684 Some(CalculationInstanceRef::McAcOpf(instance))
4685 }
4686 (
4687 CalculationInstanceProjection::Direct,
4688 PioValue::LinDist3FlowOpfInstance(instance),
4689 ) => Some(CalculationInstanceRef::LinDist3FlowOpf(instance)),
4690 (CalculationInstanceProjection::Direct, PioValue::AcScucInstance(instance)) => {
4691 Some(CalculationInstanceRef::AcScuc(instance))
4692 }
4693 (CalculationInstanceProjection::DcPfSolution, PioValue::DcPfSolution(solution)) => {
4694 Some(CalculationInstanceRef::DcPf(solution.instance()))
4695 }
4696 (CalculationInstanceProjection::AcPfSolution, PioValue::AcPfSolution(solution)) => {
4697 Some(CalculationInstanceRef::AcPf(solution.instance()))
4698 }
4699 (CalculationInstanceProjection::DcOpfSolution, PioValue::DcOpfSolution(solution)) => {
4700 Some(CalculationInstanceRef::DcOpf(solution.instance()))
4701 }
4702 (CalculationInstanceProjection::AcOpfSolution, PioValue::AcOpfSolution(solution)) => {
4703 Some(CalculationInstanceRef::AcOpf(solution.instance()))
4704 }
4705 (CalculationInstanceProjection::AcOtsSolution, PioValue::AcOtsSolution(solution)) => {
4706 Some(CalculationInstanceRef::AcOts(solution.instance()))
4707 }
4708 (
4709 CalculationInstanceProjection::SocwrOpfSolution,
4710 PioValue::SocwrOpfSolution(solution),
4711 ) => Some(CalculationInstanceRef::AcOpf(solution.instance())),
4712 (CalculationInstanceProjection::McAcPfSolution, PioValue::McAcPfSolution(solution)) => {
4713 Some(CalculationInstanceRef::McAcPf(solution.instance()))
4714 }
4715 (
4716 CalculationInstanceProjection::McAcOpfSolution,
4717 PioValue::McAcOpfSolution(solution),
4718 ) => Some(CalculationInstanceRef::McAcOpf(solution.instance())),
4719 (
4720 CalculationInstanceProjection::LinDist3FlowOpfSolution,
4721 PioValue::LinDist3FlowOpfSolution(solution),
4722 ) => Some(CalculationInstanceRef::LinDist3FlowOpf(solution.instance())),
4723 (CalculationInstanceProjection::AcScucSolution, PioValue::AcScucSolution(solution)) => {
4724 Some(CalculationInstanceRef::AcScuc(solution.instance()))
4725 }
4726 _ => None,
4727 }
4728 }
4729
4730 fn type_name(&self) -> Option<&'static str> {
4731 self.instance().map(CalculationInstanceRef::type_name)
4732 }
4733
4734 fn dc_pf(&self) -> Option<&powerio_prob::DcPfInstance> {
4735 match self.instance()? {
4736 CalculationInstanceRef::DcPf(instance) => Some(instance),
4737 _ => None,
4738 }
4739 }
4740
4741 fn ac_pf(&self) -> Option<&powerio_prob::AcPfInstance> {
4742 match self.instance()? {
4743 CalculationInstanceRef::AcPf(instance) => Some(instance),
4744 _ => None,
4745 }
4746 }
4747
4748 fn dc_opf(&self) -> Option<&powerio_prob::DcOpfInstance> {
4749 match self.instance()? {
4750 CalculationInstanceRef::DcOpf(instance) => Some(instance),
4751 _ => None,
4752 }
4753 }
4754
4755 fn ac_opf(&self) -> Option<&powerio_prob::AcOpfInstance> {
4756 match self.instance()? {
4757 CalculationInstanceRef::AcOpf(instance) => Some(instance),
4758 _ => None,
4759 }
4760 }
4761
4762 fn ac_ots(&self) -> Option<&powerio_prob::AcOtsInstance> {
4763 match self.instance()? {
4764 CalculationInstanceRef::AcOts(instance) => Some(instance),
4765 _ => None,
4766 }
4767 }
4768
4769 fn mc_ac_pf(&self) -> Option<&powerio_prob::McAcPfInstance> {
4770 match self.instance()? {
4771 CalculationInstanceRef::McAcPf(instance) => Some(instance),
4772 _ => None,
4773 }
4774 }
4775
4776 fn ac_scuc(&self) -> Option<&powerio_prob::AcScucInstance> {
4777 match self.instance()? {
4778 CalculationInstanceRef::AcScuc(instance) => Some(instance),
4779 _ => None,
4780 }
4781 }
4782
4783 fn has_initial_point(&self) -> bool {
4784 match self.instance() {
4785 Some(CalculationInstanceRef::DcPf(instance)) => instance.initial_point().is_some(),
4786 Some(CalculationInstanceRef::AcPf(instance)) => instance.initial_point().is_some(),
4787 Some(CalculationInstanceRef::DcOpf(instance)) => instance.initial_point().is_some(),
4788 Some(CalculationInstanceRef::AcOpf(instance)) => instance.initial_point().is_some(),
4789 Some(CalculationInstanceRef::AcOts(instance)) => instance.initial_point().is_some(),
4790 Some(CalculationInstanceRef::McAcPf(instance)) => instance.initial_point().is_some(),
4791 Some(CalculationInstanceRef::McAcOpf(instance)) => instance.initial_point().is_some(),
4792 Some(CalculationInstanceRef::LinDist3FlowOpf(instance)) => {
4793 instance.base_instance().initial_point().is_some()
4794 }
4795 _ => false,
4796 }
4797 }
4798}
4799
4800opaque_handle!(
4801 PioBalancedNetwork,
4803 BalancedNetworkInner
4804);
4805
4806struct DetailedConnectivityInner {
4807 owner: Arc<BalancedNetworkInner>,
4808}
4809
4810impl DetailedConnectivityInner {
4811 fn details(&self) -> Option<&powerio_tx::DetailedConnectivity> {
4812 self.owner.network()?.detailed_connectivity().as_deref()
4813 }
4814}
4815
4816opaque_handle!(
4817 PioDetailedConnectivity,
4819 DetailedConnectivityInner
4820);
4821opaque_handle!(
4822 PioMulticonductorNetwork,
4824 MulticonductorNetworkInner
4825);
4826opaque_handle!(
4827 PioTimeSeriesHandle,
4829 ValueInner
4830);
4831opaque_handle!(
4832 PioScenarioSetHandle,
4834 ValueInner
4835);
4836opaque_handle!(
4837 PioOperatingPoint,
4839 OperatingPointInner
4840);
4841opaque_handle!(
4842 PioCalculationInstance,
4844 CalculationInstanceInner
4845);
4846opaque_handle!(
4847 PioDcOpfPreparation,
4849 DcOpfPreparation
4850);
4851opaque_handle!(
4852 PioAcOpfPreparation,
4854 AcOpfPreparation
4855);
4856opaque_handle!(
4857 PioCalculationSolution,
4859 ValueInner
4860);
4861
4862fn module_handle(module: powerio::PioModule<PioValue>) -> *mut PioModule {
4863 PioModule::new_raw(ModuleInner { module })
4864}
4865
4866fn value_handle(value: ValueInner) -> *mut PioValueHandle {
4867 PioValueHandle::new_raw(value)
4868}
4869
4870unsafe fn require_value<'a>(value: *const PioValueHandle) -> Result<&'a ValueInner, *mut PioError> {
4871 unsafe { PioValueHandle::get(value) }.ok_or_else(|| {
4872 boundary_error(
4873 &codes::BIND_CAPI_NULL_HANDLE,
4874 "PioValueHandle must not be NULL",
4875 )
4876 })
4877}
4878
4879#[unsafe(no_mangle)]
4884pub unsafe extern "C" fn pio_parse(
4885 source: *const PioSource,
4886 format: *const c_char,
4887 format_len: usize,
4888 error: *mut *mut PioError,
4889) -> *mut PioModule {
4890 unsafe { pio_parse_with_options(source, format, format_len, std::ptr::null(), error) }
4891}
4892
4893#[unsafe(no_mangle)]
4902pub unsafe extern "C" fn pio_parse_with_options(
4903 source: *const PioSource,
4904 format: *const c_char,
4905 format_len: usize,
4906 selections: *const PioParseOptions,
4907 error: *mut *mut PioError,
4908) -> *mut PioModule {
4909 unsafe {
4910 entry(error, std::ptr::null_mut(), || {
4911 let source = PioSource::get(source).ok_or_else(|| {
4912 boundary_error(&codes::BIND_CAPI_NULL_HANDLE, "PioSource must not be NULL")
4913 })?;
4914 let format = optional_str(format, format_len, "format")?;
4915 let mut options = powerio::ParseOptions::default();
4916 if let Some(format) = format {
4917 options = options
4918 .format(format)
4919 .map_err(|failure| error_from_core(&failure))?;
4920 }
4921 apply_parse_selections(&mut options, selections)?;
4922 powerio::parse_with_options(source.clone(), &options)
4923 .map(module_handle)
4924 .map_err(|failure| error_from_core(&failure))
4925 })
4926 }
4927}
4928
4929unsafe fn apply_parse_selections(
4930 options: &mut powerio::ParseOptions,
4931 selections: *const PioParseOptions,
4932) -> Result<(), *mut PioError> {
4933 unsafe {
4934 if let Some(selections) = selections.as_ref() {
4935 options.acquisition_root = optional_str(
4936 selections.acquisition_root.data,
4937 selections.acquisition_root.len,
4938 "acquisition_root",
4939 )?
4940 .map(PathBuf::from);
4941 if let Some(sincal) = selections.sincal_multiconductor.as_ref() {
4942 let mut selection = powerio_tnd::formats::sincal::SincalReadOptions::default();
4943 selection.variant = sincal.has_variant.then_some(sincal.variant);
4944 selection.snapshot_hours =
4945 sincal.has_snapshot_hours.then_some(sincal.snapshot_hours);
4946 selection.acquired_tables = optional_str(
4947 sincal.acquired_tables.data,
4948 sincal.acquired_tables.len,
4949 "acquired_tables",
4950 )?
4951 .map(str::to_owned);
4952 selection.assume_inactive_source_controls = sincal.assume_inactive_source_controls;
4953 options.sincal_multiconductor = Some(selection);
4954 }
4955 if let Some(sincal) = selections.sincal_balanced.as_ref() {
4956 let mut selection =
4957 powerio_tnd::formats::sincal::SincalBalancedReadOptions::default();
4958 selection.variant = sincal.has_variant.then_some(sincal.variant);
4959 selection.snapshot_hours =
4960 sincal.has_snapshot_hours.then_some(sincal.snapshot_hours);
4961 selection.acquired_tables = optional_str(
4962 sincal.acquired_tables.data,
4963 sincal.acquired_tables.len,
4964 "acquired_tables",
4965 )?
4966 .map(str::to_owned);
4967 options.sincal_balanced = Some(selection);
4968 }
4969 }
4970 }
4971 Ok(())
4972}
4973
4974#[unsafe(no_mangle)]
4983pub unsafe extern "C" fn pio_module_deserialize(
4984 source: *const PioSource,
4985 error: *mut *mut PioError,
4986) -> *mut PioModule {
4987 unsafe {
4988 entry(error, std::ptr::null_mut(), || {
4989 let source = PioSource::get(source).ok_or_else(|| {
4990 boundary_error(&codes::BIND_CAPI_NULL_HANDLE, "PioSource must not be NULL")
4991 })?;
4992 powerio::deserialize(source.clone())
4993 .map(module_handle)
4994 .map_err(|failure| error_from_core(&failure))
4995 })
4996 }
4997}
4998
4999unsafe fn transform_module<T>(
5000 module: *const PioModule,
5001 error: *mut *mut PioError,
5002 transform: impl FnOnce(
5003 &powerio::PioModule<PioValue>,
5004 ) -> Result<powerio::PioModule<T>, powerio_core::Error>,
5005 wrap: impl FnOnce(T) -> PioValue,
5006) -> *mut PioModule {
5007 unsafe {
5008 entry(error, std::ptr::null_mut(), || {
5009 let module = PioModule::get(module).ok_or_else(|| {
5010 boundary_error(&codes::BIND_CAPI_NULL_HANDLE, "PioModule must not be NULL")
5011 })?;
5012 transform(&module.module)
5013 .map(|derived| module_handle(derived.map_value(wrap)))
5014 .map_err(|failure| error_from_core(&failure))
5015 })
5016 }
5017}
5018
5019#[unsafe(no_mangle)]
5024pub unsafe extern "C" fn pio_module_to_dc_pf_instance(
5025 module: *const PioModule,
5026 error: *mut *mut PioError,
5027) -> *mut PioModule {
5028 unsafe {
5029 transform_module(
5030 module,
5031 error,
5032 powerio::transform::to_dc_pf_instance,
5033 PioValue::DcPfInstance,
5034 )
5035 }
5036}
5037
5038#[unsafe(no_mangle)]
5043pub unsafe extern "C" fn pio_module_to_ac_pf_instance(
5044 module: *const PioModule,
5045 error: *mut *mut PioError,
5046) -> *mut PioModule {
5047 unsafe {
5048 transform_module(
5049 module,
5050 error,
5051 powerio::transform::to_ac_pf_instance,
5052 PioValue::AcPfInstance,
5053 )
5054 }
5055}
5056
5057#[unsafe(no_mangle)]
5062pub unsafe extern "C" fn pio_module_to_dc_opf_instance(
5063 module: *const PioModule,
5064 error: *mut *mut PioError,
5065) -> *mut PioModule {
5066 unsafe {
5067 transform_module(
5068 module,
5069 error,
5070 powerio::transform::to_dc_opf_instance,
5071 PioValue::DcOpfInstance,
5072 )
5073 }
5074}
5075
5076#[unsafe(no_mangle)]
5081pub unsafe extern "C" fn pio_module_to_ac_opf_instance(
5082 module: *const PioModule,
5083 error: *mut *mut PioError,
5084) -> *mut PioModule {
5085 unsafe {
5086 transform_module(
5087 module,
5088 error,
5089 powerio::transform::to_ac_opf_instance,
5090 PioValue::AcOpfInstance,
5091 )
5092 }
5093}
5094
5095#[unsafe(no_mangle)]
5101pub unsafe extern "C" fn pio_module_to_mc_ac_pf_instance(
5102 module: *const PioModule,
5103 error: *mut *mut PioError,
5104) -> *mut PioModule {
5105 unsafe {
5106 transform_module(
5107 module,
5108 error,
5109 powerio::transform::to_mc_ac_pf_instance,
5110 PioValue::McAcPfInstance,
5111 )
5112 }
5113}
5114
5115#[unsafe(no_mangle)]
5121pub unsafe extern "C" fn pio_module_to_mc_ac_opf_instance(
5122 module: *const PioModule,
5123 error: *mut *mut PioError,
5124) -> *mut PioModule {
5125 unsafe {
5126 transform_module(
5127 module,
5128 error,
5129 powerio::transform::to_mc_ac_opf_instance,
5130 PioValue::McAcOpfInstance,
5131 )
5132 }
5133}
5134
5135#[unsafe(no_mangle)]
5139pub unsafe extern "C" fn pio_module_to_lindist3flow_opf_instance(
5140 module: *const PioModule,
5141 error: *mut *mut PioError,
5142) -> *mut PioModule {
5143 unsafe {
5144 transform_module(
5145 module,
5146 error,
5147 powerio::transform::to_lindist3flow_opf_instance,
5148 PioValue::LinDist3FlowOpfInstance,
5149 )
5150 }
5151}
5152
5153#[unsafe(no_mangle)]
5160pub unsafe extern "C" fn pio_module_apply_geo_layer(
5161 module: *const PioModule,
5162 layer: *const PioGeoLayer,
5163 out_report: *mut *mut PioGeoApplyReport,
5164 error: *mut *mut PioError,
5165) -> *mut PioModule {
5166 unsafe {
5167 if !out_report.is_null() {
5168 *out_report = std::ptr::null_mut();
5169 }
5170 entry(error, std::ptr::null_mut(), || {
5171 let module = PioModule::get(module).ok_or_else(|| {
5172 boundary_error(&codes::BIND_CAPI_NULL_HANDLE, "PioModule must not be NULL")
5173 })?;
5174 let layer = PioGeoLayer::get(layer).ok_or_else(|| {
5175 boundary_error(
5176 &codes::BIND_CAPI_NULL_HANDLE,
5177 "PioGeoLayer must not be NULL",
5178 )
5179 })?;
5180 let (mut derived, report) = powerio::apply_geo_layer(&module.module, &layer.layer)
5181 .map_err(|failure| error_from_core(&failure))?;
5182 for diagnostic in &layer.diagnostics {
5183 derived
5184 .add_diagnostic(diagnostic.clone())
5185 .map_err(|failure| error_from_core(&failure))?;
5186 }
5187 if !out_report.is_null() {
5188 *out_report = PioGeoApplyReport::new_raw(report);
5189 }
5190 Ok(module_handle(derived))
5191 })
5192 }
5193}
5194
5195#[unsafe(no_mangle)]
5199pub unsafe extern "C" fn pio_geo_apply_report_matched_buses(
5200 report: *const PioGeoApplyReport,
5201) -> usize {
5202 unsafe { PioGeoApplyReport::get(report) }.map_or(0, |report| report.matched_buses)
5203}
5204
5205#[unsafe(no_mangle)]
5209pub unsafe extern "C" fn pio_geo_apply_report_matched_branches(
5210 report: *const PioGeoApplyReport,
5211) -> usize {
5212 unsafe { PioGeoApplyReport::get(report) }.map_or(0, |report| report.matched_branches)
5213}
5214
5215#[unsafe(no_mangle)]
5219pub unsafe extern "C" fn pio_geo_apply_report_unmatched_features(
5220 report: *const PioGeoApplyReport,
5221) -> usize {
5222 unsafe { PioGeoApplyReport::get(report) }.map_or(0, |report| report.unmatched_features)
5223}
5224
5225#[unsafe(no_mangle)]
5229pub unsafe extern "C" fn pio_geo_apply_report_unlocated_buses(
5230 report: *const PioGeoApplyReport,
5231) -> usize {
5232 unsafe { PioGeoApplyReport::get(report) }.map_or(0, |report| report.unlocated_buses)
5233}
5234
5235#[unsafe(no_mangle)]
5239pub unsafe extern "C" fn pio_geo_apply_report_unlocated_branches(
5240 report: *const PioGeoApplyReport,
5241) -> usize {
5242 unsafe { PioGeoApplyReport::get(report) }.map_or(0, |report| report.unlocated_branches)
5243}
5244
5245#[unsafe(no_mangle)]
5249pub unsafe extern "C" fn pio_geo_apply_report_note_count(
5250 report: *const PioGeoApplyReport,
5251) -> usize {
5252 unsafe { PioGeoApplyReport::get(report) }.map_or(0, |report| report.notes.len())
5253}
5254
5255#[unsafe(no_mangle)]
5259pub unsafe extern "C" fn pio_geo_apply_report_note_at(
5260 report: *const PioGeoApplyReport,
5261 index: usize,
5262 error: *mut *mut PioError,
5263) -> PioStringView {
5264 unsafe {
5265 entry(error, PioStringView::EMPTY, || {
5266 let report = PioGeoApplyReport::get(report).ok_or_else(|| {
5267 boundary_error(
5268 &codes::BIND_CAPI_NULL_HANDLE,
5269 "PioGeoApplyReport must not be NULL",
5270 )
5271 })?;
5272 let note = report.notes.get(index).ok_or_else(|| {
5273 boundary_error(
5274 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
5275 format!("geo apply note index {index} is out of range"),
5276 )
5277 })?;
5278 Ok(PioStringView::new(note))
5279 })
5280 }
5281}
5282
5283#[unsafe(no_mangle)]
5288pub unsafe extern "C" fn pio_geo_apply_report_retain(
5289 report: *const PioGeoApplyReport,
5290) -> *mut PioGeoApplyReport {
5291 unsafe { PioGeoApplyReport::retain_raw(report) }
5292}
5293
5294#[unsafe(no_mangle)]
5299pub unsafe extern "C" fn pio_geo_apply_report_release(report: *mut PioGeoApplyReport) {
5300 unsafe { PioGeoApplyReport::release_raw(report) };
5301}
5302
5303#[unsafe(no_mangle)]
5308pub unsafe extern "C" fn pio_module_value(module: *const PioModule) -> *mut PioValueHandle {
5309 unsafe { PioModule::arc(module) }.map_or(std::ptr::null_mut(), |owner| {
5310 value_handle(ValueInner::root(owner))
5311 })
5312}
5313
5314#[unsafe(no_mangle)]
5319pub unsafe extern "C" fn pio_module_diagnostics(module: *const PioModule) -> *mut PioDiagnostics {
5320 unsafe { PioModule::arc(module) }.map_or(std::ptr::null_mut(), |module| {
5321 PioDiagnostics::new_raw(DiagnosticsInner {
5322 owner: DiagnosticsOwner::Module(module),
5323 })
5324 })
5325}
5326
5327fn source_relation_name(relation: powerio_core::SourceRelation) -> &'static str {
5328 match relation {
5329 powerio_core::SourceRelation::Exact => "exact",
5330 powerio_core::SourceRelation::Defaulted => "defaulted",
5331 powerio_core::SourceRelation::Inferred => "inferred",
5332 powerio_core::SourceRelation::ConvertedUnits => "converted_units",
5333 powerio_core::SourceRelation::Aggregated => "aggregated",
5334 powerio_core::SourceRelation::Split => "split",
5335 powerio_core::SourceRelation::Synthetic => "synthetic",
5336 powerio_core::SourceRelation::Transformed => "transformed",
5337 powerio_core::SourceRelation::RetainedExtra => "retained_extra",
5338 _ => "unknown",
5339 }
5340}
5341
5342fn history_kind_name(kind: HistoryKind) -> &'static str {
5343 match kind {
5344 HistoryKind::Parse => "parse",
5345 HistoryKind::Transform => "transform",
5346 HistoryKind::Edit => "edit",
5347 HistoryKind::Repair => "repair",
5348 HistoryKind::Solve => "solve",
5349 _ => "unknown",
5350 }
5351}
5352
5353fn json_value_kind(value: &serde_json::Value) -> &'static str {
5354 match value {
5355 serde_json::Value::Null => "null",
5356 serde_json::Value::Bool(_) => "boolean",
5357 serde_json::Value::Number(_) => "number",
5358 serde_json::Value::String(_) => "string",
5359 serde_json::Value::Array(_) => "array",
5360 serde_json::Value::Object(_) => "object",
5361 }
5362}
5363
5364#[unsafe(no_mangle)]
5369pub unsafe extern "C" fn pio_module_producer(
5370 module: *const PioModule,
5371 output: *mut PioModuleProducerView,
5372 error: *mut *mut PioError,
5373) -> bool {
5374 unsafe {
5375 entry(error, false, || {
5376 let module = PioModule::get(module).ok_or_else(|| {
5377 boundary_error(&codes::BIND_CAPI_NULL_HANDLE, "PioModule must not be NULL")
5378 })?;
5379 let producer = module.module.producer();
5380 *require_output(output, "output")? = PioModuleProducerView {
5381 name: PioStringView::new(producer.name()),
5382 version: PioStringView::new(producer.version()),
5383 };
5384 Ok(true)
5385 })
5386 }
5387}
5388
5389#[unsafe(no_mangle)]
5393pub unsafe extern "C" fn pio_module_source_count(module: *const PioModule) -> usize {
5394 unsafe { PioModule::get(module) }.map_or(0, |module| module.module.sources().len())
5395}
5396
5397#[unsafe(no_mangle)]
5402pub unsafe extern "C" fn pio_module_source_at(
5403 module: *const PioModule,
5404 index: usize,
5405 output: *mut PioModuleSourceView,
5406 error: *mut *mut PioError,
5407) -> bool {
5408 unsafe {
5409 entry(error, false, || {
5410 let module = PioModule::get(module).ok_or_else(|| {
5411 boundary_error(&codes::BIND_CAPI_NULL_HANDLE, "PioModule must not be NULL")
5412 })?;
5413 let source = module.module.sources().get(index).ok_or_else(|| {
5414 boundary_error(
5415 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
5416 format!("module source index {index} is out of range"),
5417 )
5418 })?;
5419 let (format, has_format) = source
5420 .format()
5421 .map_or((PioStringView::EMPTY, false), |format| {
5422 (PioStringView::new(format.as_str()), true)
5423 });
5424 let digest = source.digest();
5425 *require_output(output, "output")? = PioModuleSourceView {
5426 id: PioStringView::new(source.id().as_str()),
5427 name: PioStringView::new(source.name()),
5428 byte_length: source.byte_length(),
5429 format,
5430 has_format,
5431 digest_algorithm: digest.map_or(PioStringView::EMPTY, |digest| {
5432 PioStringView::new(digest.algorithm().as_str())
5433 }),
5434 digest: digest.map_or(PioStringView::EMPTY, |digest| {
5435 PioStringView::new(digest.value())
5436 }),
5437 has_digest: digest.is_some(),
5438 };
5439 Ok(true)
5440 })
5441 }
5442}
5443
5444#[unsafe(no_mangle)]
5448pub unsafe extern "C" fn pio_module_source_map_count(module: *const PioModule) -> usize {
5449 unsafe { PioModule::get(module) }.map_or(0, |module| module.module.source_map().len())
5450}
5451
5452#[unsafe(no_mangle)]
5457pub unsafe extern "C" fn pio_module_source_map_at(
5458 module: *const PioModule,
5459 index: usize,
5460 output: *mut PioModuleSourceMapEntryView,
5461 error: *mut *mut PioError,
5462) -> bool {
5463 unsafe {
5464 entry(error, false, || {
5465 let module = PioModule::get(module).ok_or_else(|| {
5466 boundary_error(&codes::BIND_CAPI_NULL_HANDLE, "PioModule must not be NULL")
5467 })?;
5468 let source_map = module.module.source_map().get(index).ok_or_else(|| {
5469 boundary_error(
5470 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
5471 format!("module source map index {index} is out of range"),
5472 )
5473 })?;
5474 *require_output(output, "output")? = PioModuleSourceMapEntryView {
5475 target: PioStringView::new(source_map.target()),
5476 relation: PioStringView::new(source_relation_name(source_map.relation())),
5477 span_count: source_map.spans().len(),
5478 };
5479 Ok(true)
5480 })
5481 }
5482}
5483
5484#[unsafe(no_mangle)]
5489pub unsafe extern "C" fn pio_module_source_map_span_at(
5490 module: *const PioModule,
5491 entry_index: usize,
5492 span_index: usize,
5493 output: *mut PioSourceSpanView,
5494 error: *mut *mut PioError,
5495) -> bool {
5496 unsafe {
5497 entry(error, false, || {
5498 let module = PioModule::get(module).ok_or_else(|| {
5499 boundary_error(&codes::BIND_CAPI_NULL_HANDLE, "PioModule must not be NULL")
5500 })?;
5501 let source_map = module.module.source_map().get(entry_index).ok_or_else(|| {
5502 boundary_error(
5503 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
5504 format!("module source map index {entry_index} is out of range"),
5505 )
5506 })?;
5507 let span = source_map.spans().get(span_index).ok_or_else(|| {
5508 boundary_error(
5509 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
5510 format!(
5511 "source map span index {span_index} is out of range for entry {entry_index}"
5512 ),
5513 )
5514 })?;
5515 *require_output(output, "output")? = PioSourceSpanView {
5516 source: PioStringView::new(span.source().as_str()),
5517 byte_start: span.byte_start(),
5518 byte_end: span.byte_end(),
5519 };
5520 Ok(true)
5521 })
5522 }
5523}
5524
5525#[unsafe(no_mangle)]
5529pub unsafe extern "C" fn pio_module_history_count(module: *const PioModule) -> usize {
5530 unsafe { PioModule::get(module) }.map_or(0, |module| module.module.history().len())
5531}
5532
5533#[unsafe(no_mangle)]
5538pub unsafe extern "C" fn pio_module_history_at(
5539 module: *const PioModule,
5540 index: usize,
5541 output: *mut PioModuleHistoryEntryView,
5542 error: *mut *mut PioError,
5543) -> bool {
5544 unsafe {
5545 entry(error, false, || {
5546 let module = PioModule::get(module).ok_or_else(|| {
5547 boundary_error(&codes::BIND_CAPI_NULL_HANDLE, "PioModule must not be NULL")
5548 })?;
5549 let history = module.module.history().get(index).ok_or_else(|| {
5550 boundary_error(
5551 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
5552 format!("module history index {index} is out of range"),
5553 )
5554 })?;
5555 let (input_type, has_input_type) = optional_string_view(history.input_type());
5556 let (output_type, has_output_type) = optional_string_view(history.output_type());
5557 *require_output(output, "output")? = PioModuleHistoryEntryView {
5558 id: PioStringView::new(history.id().as_str()),
5559 kind: PioStringView::new(history_kind_name(history.kind())),
5560 name: PioStringView::new(history.name()),
5561 input_type,
5562 has_input_type,
5563 output_type,
5564 has_output_type,
5565 parameter_count: history.parameters().len(),
5566 assumption_count: history.assumptions().len(),
5567 loss_count: history.losses().len(),
5568 };
5569 Ok(true)
5570 })
5571 }
5572}
5573
5574#[unsafe(no_mangle)]
5579pub unsafe extern "C" fn pio_module_history_parameter_at(
5580 module: *const PioModule,
5581 history_index: usize,
5582 parameter_index: usize,
5583 output: *mut PioModuleHistoryParameterView,
5584 error: *mut *mut PioError,
5585) -> bool {
5586 unsafe {
5587 entry(error, false, || {
5588 let module = PioModule::get(module).ok_or_else(|| {
5589 boundary_error(&codes::BIND_CAPI_NULL_HANDLE, "PioModule must not be NULL")
5590 })?;
5591 let history = module.module.history().get(history_index).ok_or_else(|| {
5592 boundary_error(
5593 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
5594 format!("module history index {history_index} is out of range"),
5595 )
5596 })?;
5597 let (name, value) = history
5598 .parameters()
5599 .iter()
5600 .nth(parameter_index)
5601 .ok_or_else(|| {
5602 boundary_error(
5603 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
5604 format!(
5605 "history parameter index {parameter_index} is out of range for entry {history_index}"
5606 ),
5607 )
5608 })?;
5609 *require_output(output, "output")? = PioModuleHistoryParameterView {
5610 name: PioStringView::new(name),
5611 value_kind: PioStringView::new(json_value_kind(value)),
5612 };
5613 Ok(true)
5614 })
5615 }
5616}
5617
5618#[unsafe(no_mangle)]
5623pub unsafe extern "C" fn pio_module_history_parameter_value_at(
5624 module: *const PioModule,
5625 history_index: usize,
5626 parameter_index: usize,
5627 error: *mut *mut PioError,
5628) -> *mut PioJsonValue {
5629 unsafe {
5630 entry(error, std::ptr::null_mut(), || {
5631 let owner = PioModule::arc(module).ok_or_else(|| {
5632 boundary_error(&codes::BIND_CAPI_NULL_HANDLE, "PioModule must not be NULL")
5633 })?;
5634 let history = owner.module.history().get(history_index).ok_or_else(|| {
5635 boundary_error(
5636 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
5637 format!("module history index {history_index} is out of range"),
5638 )
5639 })?;
5640 if history.parameters().values().nth(parameter_index).is_none() {
5641 return Err(boundary_error(
5642 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
5643 format!(
5644 "history parameter index {parameter_index} is out of range for entry {history_index}"
5645 ),
5646 ));
5647 }
5648 Ok(PioJsonValue::new_raw(JsonValueInner {
5649 owner,
5650 root: ModuleJsonRoot::HistoryParameter {
5651 history_index,
5652 parameter_index,
5653 },
5654 steps: Vec::new(),
5655 }))
5656 })
5657 }
5658}
5659
5660#[unsafe(no_mangle)]
5665pub unsafe extern "C" fn pio_module_history_assumption_at(
5666 module: *const PioModule,
5667 history_index: usize,
5668 assumption_index: usize,
5669 error: *mut *mut PioError,
5670) -> PioStringView {
5671 unsafe {
5672 entry(error, PioStringView::EMPTY, || {
5673 let module = PioModule::get(module).ok_or_else(|| {
5674 boundary_error(&codes::BIND_CAPI_NULL_HANDLE, "PioModule must not be NULL")
5675 })?;
5676 let history = module.module.history().get(history_index).ok_or_else(|| {
5677 boundary_error(
5678 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
5679 format!("module history index {history_index} is out of range"),
5680 )
5681 })?;
5682 history
5683 .assumptions()
5684 .get(assumption_index)
5685 .map(|value| PioStringView::new(value))
5686 .ok_or_else(|| {
5687 boundary_error(
5688 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
5689 format!(
5690 "history assumption index {assumption_index} is out of range for entry {history_index}"
5691 ),
5692 )
5693 })
5694 })
5695 }
5696}
5697
5698#[unsafe(no_mangle)]
5703pub unsafe extern "C" fn pio_module_history_loss_at(
5704 module: *const PioModule,
5705 history_index: usize,
5706 loss_index: usize,
5707 error: *mut *mut PioError,
5708) -> PioStringView {
5709 unsafe {
5710 entry(error, PioStringView::EMPTY, || {
5711 let module = PioModule::get(module).ok_or_else(|| {
5712 boundary_error(&codes::BIND_CAPI_NULL_HANDLE, "PioModule must not be NULL")
5713 })?;
5714 let history = module.module.history().get(history_index).ok_or_else(|| {
5715 boundary_error(
5716 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
5717 format!("module history index {history_index} is out of range"),
5718 )
5719 })?;
5720 history
5721 .losses()
5722 .get(loss_index)
5723 .map(|value| PioStringView::new(value))
5724 .ok_or_else(|| {
5725 boundary_error(
5726 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
5727 format!(
5728 "history loss index {loss_index} is out of range for entry {history_index}"
5729 ),
5730 )
5731 })
5732 })
5733 }
5734}
5735
5736#[unsafe(no_mangle)]
5740pub unsafe extern "C" fn pio_module_extension_count(module: *const PioModule) -> usize {
5741 unsafe { PioModule::get(module) }.map_or(0, |module| module.module.extensions().len())
5742}
5743
5744#[unsafe(no_mangle)]
5749pub unsafe extern "C" fn pio_module_extension_at(
5750 module: *const PioModule,
5751 index: usize,
5752 output: *mut PioModuleExtensionView,
5753 error: *mut *mut PioError,
5754) -> bool {
5755 unsafe {
5756 entry(error, false, || {
5757 let module = PioModule::get(module).ok_or_else(|| {
5758 boundary_error(&codes::BIND_CAPI_NULL_HANDLE, "PioModule must not be NULL")
5759 })?;
5760 let (namespace, value) =
5761 module
5762 .module
5763 .extensions()
5764 .iter()
5765 .nth(index)
5766 .ok_or_else(|| {
5767 boundary_error(
5768 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
5769 format!("module extension index {index} is out of range"),
5770 )
5771 })?;
5772 *require_output(output, "output")? = PioModuleExtensionView {
5773 namespace: PioStringView::new(namespace),
5774 value_kind: PioStringView::new(json_value_kind(value)),
5775 };
5776 Ok(true)
5777 })
5778 }
5779}
5780
5781#[unsafe(no_mangle)]
5786pub unsafe extern "C" fn pio_module_extension_value_at(
5787 module: *const PioModule,
5788 index: usize,
5789 error: *mut *mut PioError,
5790) -> *mut PioJsonValue {
5791 unsafe {
5792 entry(error, std::ptr::null_mut(), || {
5793 let owner = PioModule::arc(module).ok_or_else(|| {
5794 boundary_error(&codes::BIND_CAPI_NULL_HANDLE, "PioModule must not be NULL")
5795 })?;
5796 if owner.module.extensions().values().nth(index).is_none() {
5797 return Err(boundary_error(
5798 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
5799 format!("module extension index {index} is out of range"),
5800 ));
5801 }
5802 Ok(PioJsonValue::new_raw(JsonValueInner {
5803 owner,
5804 root: ModuleJsonRoot::Extension(index),
5805 steps: Vec::new(),
5806 }))
5807 })
5808 }
5809}
5810
5811fn json_value_view(value: &serde_json::Value) -> PioJsonValueView {
5812 let mut view = PioJsonValueView {
5813 kind: PioStringView::new(json_value_kind(value)),
5814 boolean_value: false,
5815 number_kind: PioStringView::EMPTY,
5816 signed_integer_value: 0,
5817 unsigned_integer_value: 0,
5818 floating_point_value: 0.0,
5819 string_value: PioStringView::EMPTY,
5820 element_count: 0,
5821 };
5822 match value {
5823 serde_json::Value::Bool(value) => view.boolean_value = *value,
5824 serde_json::Value::Number(value) if value.is_i64() => {
5825 view.number_kind = PioStringView::new("signed_integer");
5826 view.signed_integer_value = value.as_i64().unwrap_or_default();
5827 }
5828 serde_json::Value::Number(value) if value.is_u64() => {
5829 view.number_kind = PioStringView::new("unsigned_integer");
5830 view.unsigned_integer_value = value.as_u64().unwrap_or_default();
5831 }
5832 serde_json::Value::Number(value) => {
5833 view.number_kind = PioStringView::new("floating_point");
5834 view.floating_point_value = value.as_f64().unwrap_or(f64::NAN);
5835 }
5836 serde_json::Value::String(value) => view.string_value = PioStringView::new(value),
5837 serde_json::Value::Array(values) => view.element_count = values.len(),
5838 serde_json::Value::Object(values) => view.element_count = values.len(),
5839 serde_json::Value::Null => {}
5840 }
5841 view
5842}
5843
5844#[unsafe(no_mangle)]
5849pub unsafe extern "C" fn pio_json_value_get(
5850 value: *const PioJsonValue,
5851 output: *mut PioJsonValueView,
5852 error: *mut *mut PioError,
5853) -> bool {
5854 unsafe {
5855 entry(error, false, || {
5856 let value = PioJsonValue::get(value).ok_or_else(|| {
5857 boundary_error(
5858 &codes::BIND_CAPI_NULL_HANDLE,
5859 "PioJsonValue must not be NULL",
5860 )
5861 })?;
5862 let value = value.value().ok_or_else(|| {
5863 boundary_error(
5864 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
5865 "the structured value path is out of range",
5866 )
5867 })?;
5868 *require_output(output, "output")? = json_value_view(value);
5869 Ok(true)
5870 })
5871 }
5872}
5873
5874#[unsafe(no_mangle)]
5879pub unsafe extern "C" fn pio_json_value_array_at(
5880 value: *const PioJsonValue,
5881 index: usize,
5882 error: *mut *mut PioError,
5883) -> *mut PioJsonValue {
5884 unsafe {
5885 entry(error, std::ptr::null_mut(), || {
5886 let value = PioJsonValue::get(value).ok_or_else(|| {
5887 boundary_error(
5888 &codes::BIND_CAPI_NULL_HANDLE,
5889 "PioJsonValue must not be NULL",
5890 )
5891 })?;
5892 let values = value
5893 .value()
5894 .and_then(serde_json::Value::as_array)
5895 .ok_or_else(|| {
5896 boundary_error(
5897 &codes::REQUEST_CAPI_TYPE_MISMATCH,
5898 "the structured value is not an array",
5899 )
5900 })?;
5901 if values.get(index).is_none() {
5902 return Err(boundary_error(
5903 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
5904 format!("structured array index {index} is out of range"),
5905 ));
5906 }
5907 Ok(PioJsonValue::new_raw(
5908 value.child(JsonValueStep::Array(index)),
5909 ))
5910 })
5911 }
5912}
5913
5914#[unsafe(no_mangle)]
5919pub unsafe extern "C" fn pio_json_value_object_entry_at(
5920 value: *const PioJsonValue,
5921 index: usize,
5922 output: *mut PioJsonObjectEntryView,
5923 error: *mut *mut PioError,
5924) -> bool {
5925 unsafe {
5926 entry(error, false, || {
5927 let value = PioJsonValue::get(value).ok_or_else(|| {
5928 boundary_error(
5929 &codes::BIND_CAPI_NULL_HANDLE,
5930 "PioJsonValue must not be NULL",
5931 )
5932 })?;
5933 let values = value
5934 .value()
5935 .and_then(serde_json::Value::as_object)
5936 .ok_or_else(|| {
5937 boundary_error(
5938 &codes::REQUEST_CAPI_TYPE_MISMATCH,
5939 "the structured value is not an object",
5940 )
5941 })?;
5942 let (key, value) = values.iter().nth(index).ok_or_else(|| {
5943 boundary_error(
5944 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
5945 format!("structured object index {index} is out of range"),
5946 )
5947 })?;
5948 *require_output(output, "output")? = PioJsonObjectEntryView {
5949 key: PioStringView::new(key),
5950 value_kind: PioStringView::new(json_value_kind(value)),
5951 };
5952 Ok(true)
5953 })
5954 }
5955}
5956
5957#[unsafe(no_mangle)]
5962pub unsafe extern "C" fn pio_json_value_object_value_at(
5963 value: *const PioJsonValue,
5964 index: usize,
5965 error: *mut *mut PioError,
5966) -> *mut PioJsonValue {
5967 unsafe {
5968 entry(error, std::ptr::null_mut(), || {
5969 let value = PioJsonValue::get(value).ok_or_else(|| {
5970 boundary_error(
5971 &codes::BIND_CAPI_NULL_HANDLE,
5972 "PioJsonValue must not be NULL",
5973 )
5974 })?;
5975 let values = value
5976 .value()
5977 .and_then(serde_json::Value::as_object)
5978 .ok_or_else(|| {
5979 boundary_error(
5980 &codes::REQUEST_CAPI_TYPE_MISMATCH,
5981 "the structured value is not an object",
5982 )
5983 })?;
5984 if values.values().nth(index).is_none() {
5985 return Err(boundary_error(
5986 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
5987 format!("structured object index {index} is out of range"),
5988 ));
5989 }
5990 Ok(PioJsonValue::new_raw(
5991 value.child(JsonValueStep::Object(index)),
5992 ))
5993 })
5994 }
5995}
5996
5997#[unsafe(no_mangle)]
6002pub unsafe extern "C" fn pio_json_value_retain(value: *const PioJsonValue) -> *mut PioJsonValue {
6003 unsafe { PioJsonValue::retain_raw(value) }
6004}
6005
6006#[unsafe(no_mangle)]
6011pub unsafe extern "C" fn pio_json_value_release(value: *mut PioJsonValue) {
6012 unsafe { PioJsonValue::release_raw(value) };
6013}
6014
6015#[unsafe(no_mangle)]
6020pub unsafe extern "C" fn pio_module_retain(module: *const PioModule) -> *mut PioModule {
6021 unsafe { PioModule::retain_raw(module) }
6022}
6023
6024#[unsafe(no_mangle)]
6029pub unsafe extern "C" fn pio_module_release(module: *mut PioModule) {
6030 unsafe { PioModule::release_raw(module) };
6031}
6032
6033#[unsafe(no_mangle)]
6038pub unsafe extern "C" fn pio_value_type_name(value: *const PioValueHandle) -> PioStringView {
6039 unsafe { PioValueHandle::get(value) }
6040 .and_then(ValueInner::value)
6041 .map_or(PioStringView::EMPTY, |value| {
6042 PioStringView::new(value.type_name())
6043 })
6044}
6045
6046#[unsafe(no_mangle)]
6051pub unsafe extern "C" fn pio_value_is_type(
6052 value: *const PioValueHandle,
6053 type_name: *const c_char,
6054 type_name_len: usize,
6055) -> bool {
6056 let Some(value) = unsafe { PioValueHandle::get(value) }.and_then(ValueInner::value) else {
6057 return false;
6058 };
6059 let Ok(type_name) = (unsafe { input_str(type_name, type_name_len, "type_name") }) else {
6060 return false;
6061 };
6062 value.type_name() == type_name
6063}
6064
6065#[unsafe(no_mangle)]
6070pub unsafe extern "C" fn pio_value_balanced_network(
6071 value: *const PioValueHandle,
6072 error: *mut *mut PioError,
6073) -> *mut PioBalancedNetwork {
6074 unsafe {
6075 entry(error, std::ptr::null_mut(), || {
6076 let value = require_value(value)?;
6077 if !matches!(value.value(), Some(PioValue::BalancedNetwork(_))) {
6078 return Err(boundary_error(
6079 &codes::REQUEST_CAPI_TYPE_MISMATCH,
6080 "the value is not powerio.BalancedNetwork",
6081 ));
6082 }
6083 Ok(PioBalancedNetwork::new_raw(BalancedNetworkInner {
6084 value: ValueInner {
6085 owner: Arc::clone(&value.owner),
6086 steps: value.steps.clone(),
6087 },
6088 projection: BalancedNetworkProjection::Direct,
6089 }))
6090 })
6091 }
6092}
6093
6094#[unsafe(no_mangle)]
6101pub unsafe extern "C" fn pio_value_geo_layer(
6102 value: *const PioValueHandle,
6103 error: *mut *mut PioError,
6104) -> *mut PioGeoLayer {
6105 unsafe {
6106 entry(error, std::ptr::null_mut(), || {
6107 let value = require_value(value)?;
6108 let Some(PioValue::GeoLayer(layer)) = value.value() else {
6109 return Err(boundary_error(
6110 &codes::REQUEST_CAPI_TYPE_MISMATCH,
6111 "the value is not powerio.GeoLayer",
6112 ));
6113 };
6114 Ok(PioGeoLayer::new_raw(GeoLayerInner {
6115 layer: layer.clone(),
6116 diagnostics: Vec::new(),
6117 }))
6118 })
6119 }
6120}
6121
6122#[unsafe(no_mangle)]
6129pub unsafe extern "C" fn pio_value_contingency_set(
6130 value: *const PioValueHandle,
6131 error: *mut *mut PioError,
6132) -> *mut PioContingencySet {
6133 unsafe {
6134 entry(error, std::ptr::null_mut(), || {
6135 let value = require_value(value)?;
6136 if !matches!(value.value(), Some(PioValue::ContingencySet(_))) {
6137 return Err(boundary_error(
6138 &codes::REQUEST_CAPI_TYPE_MISMATCH,
6139 "the value is not powerio.ContingencySet",
6140 ));
6141 }
6142 Ok(PioContingencySet::new_raw(ContingencySetInner {
6143 source: ContingencySource::Value(ValueInner {
6144 owner: Arc::clone(&value.owner),
6145 steps: value.steps.clone(),
6146 }),
6147 diagnostics: Vec::new(),
6148 }))
6149 })
6150 }
6151}
6152
6153#[unsafe(no_mangle)]
6160pub unsafe extern "C" fn pio_value_subsystem_set(
6161 value: *const PioValueHandle,
6162 error: *mut *mut PioError,
6163) -> *mut PioSubsystemSet {
6164 unsafe {
6165 entry(error, std::ptr::null_mut(), || {
6166 let value = require_value(value)?;
6167 if !matches!(value.value(), Some(PioValue::SubsystemSet(_))) {
6168 return Err(boundary_error(
6169 &codes::REQUEST_CAPI_TYPE_MISMATCH,
6170 "the value is not powerio.SubsystemSet",
6171 ));
6172 }
6173 Ok(PioSubsystemSet::new_raw(SubsystemSetInner {
6174 source: ContingencySource::Value(ValueInner {
6175 owner: Arc::clone(&value.owner),
6176 steps: value.steps.clone(),
6177 }),
6178 }))
6179 })
6180 }
6181}
6182
6183#[unsafe(no_mangle)]
6190pub unsafe extern "C" fn pio_value_monitored_set(
6191 value: *const PioValueHandle,
6192 error: *mut *mut PioError,
6193) -> *mut PioMonitoredSet {
6194 unsafe {
6195 entry(error, std::ptr::null_mut(), || {
6196 let value = require_value(value)?;
6197 if !matches!(value.value(), Some(PioValue::MonitoredSet(_))) {
6198 return Err(boundary_error(
6199 &codes::REQUEST_CAPI_TYPE_MISMATCH,
6200 "the value is not powerio.MonitoredSet",
6201 ));
6202 }
6203 Ok(PioMonitoredSet::new_raw(MonitoredSetInner {
6204 source: ContingencySource::Value(ValueInner {
6205 owner: Arc::clone(&value.owner),
6206 steps: value.steps.clone(),
6207 }),
6208 }))
6209 })
6210 }
6211}
6212
6213#[unsafe(no_mangle)]
6218pub unsafe extern "C" fn pio_value_multiconductor_network(
6219 value: *const PioValueHandle,
6220 error: *mut *mut PioError,
6221) -> *mut PioMulticonductorNetwork {
6222 unsafe {
6223 entry(error, std::ptr::null_mut(), || {
6224 let value = require_value(value)?;
6225 if !matches!(value.value(), Some(PioValue::MulticonductorNetwork(_))) {
6226 return Err(boundary_error(
6227 &codes::REQUEST_CAPI_TYPE_MISMATCH,
6228 "the value is not powerio.MulticonductorNetwork",
6229 ));
6230 }
6231 Ok(PioMulticonductorNetwork::new_raw(
6232 MulticonductorNetworkInner {
6233 value: ValueInner {
6234 owner: Arc::clone(&value.owner),
6235 steps: value.steps.clone(),
6236 },
6237 projection: MulticonductorNetworkProjection::Direct,
6238 },
6239 ))
6240 })
6241 }
6242}
6243
6244#[unsafe(no_mangle)]
6249pub unsafe extern "C" fn pio_value_time_series(
6250 value: *const PioValueHandle,
6251 error: *mut *mut PioError,
6252) -> *mut PioTimeSeriesHandle {
6253 unsafe {
6254 entry(error, std::ptr::null_mut(), || {
6255 let value = require_value(value)?;
6256 if !matches!(value.value(), Some(PioValue::TimeSeries(_))) {
6257 return Err(boundary_error(
6258 &codes::REQUEST_CAPI_TYPE_MISMATCH,
6259 "the value is not powerio.TimeSeries<T>",
6260 ));
6261 }
6262 Ok(PioTimeSeriesHandle::new_raw(ValueInner {
6263 owner: Arc::clone(&value.owner),
6264 steps: value.steps.clone(),
6265 }))
6266 })
6267 }
6268}
6269
6270#[unsafe(no_mangle)]
6275pub unsafe extern "C" fn pio_value_scenario_set(
6276 value: *const PioValueHandle,
6277 error: *mut *mut PioError,
6278) -> *mut PioScenarioSetHandle {
6279 unsafe {
6280 entry(error, std::ptr::null_mut(), || {
6281 let value = require_value(value)?;
6282 if !matches!(value.value(), Some(PioValue::ScenarioSet(_))) {
6283 return Err(boundary_error(
6284 &codes::REQUEST_CAPI_TYPE_MISMATCH,
6285 "the value is not powerio.ScenarioSet<T>",
6286 ));
6287 }
6288 Ok(PioScenarioSetHandle::new_raw(ValueInner {
6289 owner: Arc::clone(&value.owner),
6290 steps: value.steps.clone(),
6291 }))
6292 })
6293 }
6294}
6295
6296#[derive(Clone, Copy)]
6297enum ExpectedValue {
6298 BalancedOperatingPoint,
6299 MulticonductorOperatingPoint,
6300 DcPfInstance,
6301 AcPfInstance,
6302 DcOpfInstance,
6303 AcOpfInstance,
6304 AcOtsInstance,
6305 McAcPfInstance,
6306 McAcOpfInstance,
6307 LinDist3FlowOpfInstance,
6308 AcScucInstance,
6309 DcPfSolution,
6310 AcPfSolution,
6311 DcOpfSolution,
6312 AcOpfSolution,
6313 AcOtsSolution,
6314 SocwrOpfSolution,
6315 McAcPfSolution,
6316 McAcOpfSolution,
6317 LinDist3FlowOpfSolution,
6318 AcScucSolution,
6319}
6320
6321impl ExpectedValue {
6322 fn matches(self, value: &PioValue) -> bool {
6323 matches!(
6324 (self, value),
6325 (
6326 Self::BalancedOperatingPoint,
6327 PioValue::BalancedOperatingPoint(_)
6328 ) | (
6329 Self::MulticonductorOperatingPoint,
6330 PioValue::MulticonductorOperatingPoint(_)
6331 ) | (Self::DcPfInstance, PioValue::DcPfInstance(_))
6332 | (Self::AcPfInstance, PioValue::AcPfInstance(_))
6333 | (Self::DcOpfInstance, PioValue::DcOpfInstance(_))
6334 | (Self::AcOpfInstance, PioValue::AcOpfInstance(_))
6335 | (Self::AcOtsInstance, PioValue::AcOtsInstance(_))
6336 | (Self::McAcPfInstance, PioValue::McAcPfInstance(_))
6337 | (Self::McAcOpfInstance, PioValue::McAcOpfInstance(_))
6338 | (
6339 Self::LinDist3FlowOpfInstance,
6340 PioValue::LinDist3FlowOpfInstance(_)
6341 )
6342 | (Self::AcScucInstance, PioValue::AcScucInstance(_))
6343 | (Self::DcPfSolution, PioValue::DcPfSolution(_))
6344 | (Self::AcPfSolution, PioValue::AcPfSolution(_))
6345 | (Self::DcOpfSolution, PioValue::DcOpfSolution(_))
6346 | (Self::AcOpfSolution, PioValue::AcOpfSolution(_))
6347 | (Self::AcOtsSolution, PioValue::AcOtsSolution(_))
6348 | (Self::SocwrOpfSolution, PioValue::SocwrOpfSolution(_))
6349 | (Self::McAcPfSolution, PioValue::McAcPfSolution(_))
6350 | (Self::McAcOpfSolution, PioValue::McAcOpfSolution(_))
6351 | (
6352 Self::LinDist3FlowOpfSolution,
6353 PioValue::LinDist3FlowOpfSolution(_)
6354 )
6355 | (Self::AcScucSolution, PioValue::AcScucSolution(_))
6356 )
6357 }
6358
6359 fn type_name(self) -> &'static str {
6360 match self {
6361 Self::BalancedOperatingPoint => "powerio.OperatingPoint<powerio.BalancedNetwork>",
6362 Self::MulticonductorOperatingPoint => {
6363 "powerio.OperatingPoint<powerio.MulticonductorNetwork>"
6364 }
6365 Self::DcPfInstance => "powerio.DcPfInstance",
6366 Self::AcPfInstance => "powerio.AcPfInstance",
6367 Self::DcOpfInstance => "powerio.DcOpfInstance",
6368 Self::AcOpfInstance => "powerio.AcOpfInstance",
6369 Self::AcOtsInstance => "powerio.AcOtsInstance",
6370 Self::McAcPfInstance => "powerio.McAcPfInstance",
6371 Self::McAcOpfInstance => "powerio.McAcOpfInstance",
6372 Self::LinDist3FlowOpfInstance => "powerio.LinDist3FlowOpfInstance",
6373 Self::AcScucInstance => "powerio.AcScucInstance",
6374 Self::DcPfSolution => "powerio.DcPfSolution",
6375 Self::AcPfSolution => "powerio.AcPfSolution",
6376 Self::DcOpfSolution => "powerio.DcOpfSolution",
6377 Self::AcOpfSolution => "powerio.AcOpfSolution",
6378 Self::AcOtsSolution => "powerio.AcOtsSolution",
6379 Self::SocwrOpfSolution => "powerio.SocwrOpfSolution",
6380 Self::McAcPfSolution => "powerio.McAcPfSolution",
6381 Self::McAcOpfSolution => "powerio.McAcOpfSolution",
6382 Self::LinDist3FlowOpfSolution => "powerio.LinDist3FlowOpfSolution",
6383 Self::AcScucSolution => "powerio.AcScucSolution",
6384 }
6385 }
6386}
6387
6388unsafe fn checked_typed_value(
6389 value: *const PioValueHandle,
6390 expected: ExpectedValue,
6391) -> Result<ValueInner, *mut PioError> {
6392 let value = unsafe { require_value(value) }?;
6393 if !value.value().is_some_and(|value| expected.matches(value)) {
6394 return Err(boundary_error(
6395 &codes::REQUEST_CAPI_TYPE_MISMATCH,
6396 format!("the value is not {}", expected.type_name()),
6397 ));
6398 }
6399 Ok(ValueInner {
6400 owner: Arc::clone(&value.owner),
6401 steps: value.steps.clone(),
6402 })
6403}
6404
6405unsafe fn operating_point_accessor(
6406 value: *const PioValueHandle,
6407 expected: ExpectedValue,
6408 error: *mut *mut PioError,
6409) -> *mut PioOperatingPoint {
6410 unsafe {
6411 entry(error, std::ptr::null_mut(), || {
6412 let value = checked_typed_value(value, expected)?;
6413 let projection = match expected {
6414 ExpectedValue::BalancedOperatingPoint => OperatingPointProjection::DirectBalanced,
6415 ExpectedValue::MulticonductorOperatingPoint => {
6416 OperatingPointProjection::DirectMulticonductor
6417 }
6418 _ => {
6419 return Err(boundary_error(
6420 &codes::REQUEST_CAPI_TYPE_MISMATCH,
6421 "the requested value is not an operating point",
6422 ));
6423 }
6424 };
6425 Ok(PioOperatingPoint::new_raw(OperatingPointInner {
6426 value,
6427 projection,
6428 }))
6429 })
6430 }
6431}
6432
6433unsafe fn instance_accessor(
6434 value: *const PioValueHandle,
6435 expected: ExpectedValue,
6436 error: *mut *mut PioError,
6437) -> *mut PioCalculationInstance {
6438 unsafe {
6439 entry(error, std::ptr::null_mut(), || {
6440 checked_typed_value(value, expected).map(|value| {
6441 PioCalculationInstance::new_raw(CalculationInstanceInner {
6442 value,
6443 projection: CalculationInstanceProjection::Direct,
6444 })
6445 })
6446 })
6447 }
6448}
6449
6450unsafe fn solution_accessor(
6451 value: *const PioValueHandle,
6452 expected: ExpectedValue,
6453 error: *mut *mut PioError,
6454) -> *mut PioCalculationSolution {
6455 unsafe {
6456 entry(error, std::ptr::null_mut(), || {
6457 checked_typed_value(value, expected).map(PioCalculationSolution::new_raw)
6458 })
6459 }
6460}
6461
6462#[unsafe(no_mangle)]
6466pub unsafe extern "C" fn pio_value_balanced_operating_point(
6467 value: *const PioValueHandle,
6468 error: *mut *mut PioError,
6469) -> *mut PioOperatingPoint {
6470 unsafe { operating_point_accessor(value, ExpectedValue::BalancedOperatingPoint, error) }
6471}
6472
6473#[unsafe(no_mangle)]
6477pub unsafe extern "C" fn pio_value_multiconductor_operating_point(
6478 value: *const PioValueHandle,
6479 error: *mut *mut PioError,
6480) -> *mut PioOperatingPoint {
6481 unsafe { operating_point_accessor(value, ExpectedValue::MulticonductorOperatingPoint, error) }
6482}
6483
6484#[unsafe(no_mangle)]
6488pub unsafe extern "C" fn pio_value_dc_pf_instance(
6489 value: *const PioValueHandle,
6490 error: *mut *mut PioError,
6491) -> *mut PioCalculationInstance {
6492 unsafe { instance_accessor(value, ExpectedValue::DcPfInstance, error) }
6493}
6494
6495#[unsafe(no_mangle)]
6499pub unsafe extern "C" fn pio_value_ac_pf_instance(
6500 value: *const PioValueHandle,
6501 error: *mut *mut PioError,
6502) -> *mut PioCalculationInstance {
6503 unsafe { instance_accessor(value, ExpectedValue::AcPfInstance, error) }
6504}
6505
6506#[unsafe(no_mangle)]
6510pub unsafe extern "C" fn pio_value_dc_opf_instance(
6511 value: *const PioValueHandle,
6512 error: *mut *mut PioError,
6513) -> *mut PioCalculationInstance {
6514 unsafe { instance_accessor(value, ExpectedValue::DcOpfInstance, error) }
6515}
6516
6517#[unsafe(no_mangle)]
6521pub unsafe extern "C" fn pio_value_ac_opf_instance(
6522 value: *const PioValueHandle,
6523 error: *mut *mut PioError,
6524) -> *mut PioCalculationInstance {
6525 unsafe { instance_accessor(value, ExpectedValue::AcOpfInstance, error) }
6526}
6527
6528#[unsafe(no_mangle)]
6532pub unsafe extern "C" fn pio_value_mc_ac_pf_instance(
6533 value: *const PioValueHandle,
6534 error: *mut *mut PioError,
6535) -> *mut PioCalculationInstance {
6536 unsafe { instance_accessor(value, ExpectedValue::McAcPfInstance, error) }
6537}
6538
6539#[unsafe(no_mangle)]
6543pub unsafe extern "C" fn pio_value_mc_ac_opf_instance(
6544 value: *const PioValueHandle,
6545 error: *mut *mut PioError,
6546) -> *mut PioCalculationInstance {
6547 unsafe { instance_accessor(value, ExpectedValue::McAcOpfInstance, error) }
6548}
6549
6550#[unsafe(no_mangle)]
6554pub unsafe extern "C" fn pio_value_lindist3flow_opf_instance(
6555 value: *const PioValueHandle,
6556 error: *mut *mut PioError,
6557) -> *mut PioCalculationInstance {
6558 unsafe { instance_accessor(value, ExpectedValue::LinDist3FlowOpfInstance, error) }
6559}
6560
6561#[unsafe(no_mangle)]
6565pub unsafe extern "C" fn pio_value_ac_scuc_instance(
6566 value: *const PioValueHandle,
6567 error: *mut *mut PioError,
6568) -> *mut PioCalculationInstance {
6569 unsafe { instance_accessor(value, ExpectedValue::AcScucInstance, error) }
6570}
6571
6572#[unsafe(no_mangle)]
6576pub unsafe extern "C" fn pio_value_dc_pf_solution(
6577 value: *const PioValueHandle,
6578 error: *mut *mut PioError,
6579) -> *mut PioCalculationSolution {
6580 unsafe { solution_accessor(value, ExpectedValue::DcPfSolution, error) }
6581}
6582
6583#[unsafe(no_mangle)]
6587pub unsafe extern "C" fn pio_value_ac_pf_solution(
6588 value: *const PioValueHandle,
6589 error: *mut *mut PioError,
6590) -> *mut PioCalculationSolution {
6591 unsafe { solution_accessor(value, ExpectedValue::AcPfSolution, error) }
6592}
6593
6594#[unsafe(no_mangle)]
6598pub unsafe extern "C" fn pio_value_dc_opf_solution(
6599 value: *const PioValueHandle,
6600 error: *mut *mut PioError,
6601) -> *mut PioCalculationSolution {
6602 unsafe { solution_accessor(value, ExpectedValue::DcOpfSolution, error) }
6603}
6604
6605#[unsafe(no_mangle)]
6609pub unsafe extern "C" fn pio_value_ac_opf_solution(
6610 value: *const PioValueHandle,
6611 error: *mut *mut PioError,
6612) -> *mut PioCalculationSolution {
6613 unsafe { solution_accessor(value, ExpectedValue::AcOpfSolution, error) }
6614}
6615
6616#[unsafe(no_mangle)]
6620pub unsafe extern "C" fn pio_value_socwr_opf_solution(
6621 value: *const PioValueHandle,
6622 error: *mut *mut PioError,
6623) -> *mut PioCalculationSolution {
6624 unsafe { solution_accessor(value, ExpectedValue::SocwrOpfSolution, error) }
6625}
6626
6627#[unsafe(no_mangle)]
6631pub unsafe extern "C" fn pio_value_mc_ac_pf_solution(
6632 value: *const PioValueHandle,
6633 error: *mut *mut PioError,
6634) -> *mut PioCalculationSolution {
6635 unsafe { solution_accessor(value, ExpectedValue::McAcPfSolution, error) }
6636}
6637
6638#[unsafe(no_mangle)]
6642pub unsafe extern "C" fn pio_value_mc_ac_opf_solution(
6643 value: *const PioValueHandle,
6644 error: *mut *mut PioError,
6645) -> *mut PioCalculationSolution {
6646 unsafe { solution_accessor(value, ExpectedValue::McAcOpfSolution, error) }
6647}
6648
6649#[unsafe(no_mangle)]
6653pub unsafe extern "C" fn pio_value_lindist3flow_opf_solution(
6654 value: *const PioValueHandle,
6655 error: *mut *mut PioError,
6656) -> *mut PioCalculationSolution {
6657 unsafe { solution_accessor(value, ExpectedValue::LinDist3FlowOpfSolution, error) }
6658}
6659
6660#[unsafe(no_mangle)]
6664pub unsafe extern "C" fn pio_value_ac_scuc_solution(
6665 value: *const PioValueHandle,
6666 error: *mut *mut PioError,
6667) -> *mut PioCalculationSolution {
6668 unsafe { solution_accessor(value, ExpectedValue::AcScucSolution, error) }
6669}
6670
6671#[unsafe(no_mangle)]
6675pub unsafe extern "C" fn pio_operating_point_type_name(
6676 point: *const PioOperatingPoint,
6677) -> PioStringView {
6678 unsafe { PioOperatingPoint::get(point) }
6679 .and_then(OperatingPointInner::type_name)
6680 .map_or(PioStringView::EMPTY, PioStringView::new)
6681}
6682
6683#[unsafe(no_mangle)]
6687pub unsafe extern "C" fn pio_calculation_instance_type_name(
6688 instance: *const PioCalculationInstance,
6689) -> PioStringView {
6690 unsafe { PioCalculationInstance::get(instance) }
6691 .and_then(CalculationInstanceInner::type_name)
6692 .map_or(PioStringView::EMPTY, PioStringView::new)
6693}
6694
6695#[unsafe(no_mangle)]
6699pub unsafe extern "C" fn pio_calculation_solution_type_name(
6700 solution: *const PioCalculationSolution,
6701) -> PioStringView {
6702 unsafe { PioCalculationSolution::get(solution) }
6703 .and_then(ValueInner::value)
6704 .map_or(PioStringView::EMPTY, |value| {
6705 PioStringView::new(value.type_name())
6706 })
6707}
6708
6709#[unsafe(no_mangle)]
6715pub unsafe extern "C" fn pio_calculation_solution_instance(
6716 solution: *const PioCalculationSolution,
6717 error: *mut *mut PioError,
6718) -> *mut PioCalculationInstance {
6719 unsafe {
6720 entry(error, std::ptr::null_mut(), || {
6721 let solution = PioCalculationSolution::get(solution).ok_or_else(|| {
6722 boundary_error(
6723 &codes::BIND_CAPI_NULL_HANDLE,
6724 "PioCalculationSolution must not be NULL",
6725 )
6726 })?;
6727 let projection = match solution.value() {
6728 Some(PioValue::DcPfSolution(_)) => CalculationInstanceProjection::DcPfSolution,
6729 Some(PioValue::AcPfSolution(_)) => CalculationInstanceProjection::AcPfSolution,
6730 Some(PioValue::DcOpfSolution(_)) => CalculationInstanceProjection::DcOpfSolution,
6731 Some(PioValue::AcOpfSolution(_)) => CalculationInstanceProjection::AcOpfSolution,
6732 Some(PioValue::AcOtsSolution(_)) => CalculationInstanceProjection::AcOtsSolution,
6733 Some(PioValue::SocwrOpfSolution(_)) => {
6734 CalculationInstanceProjection::SocwrOpfSolution
6735 }
6736 Some(PioValue::McAcPfSolution(_)) => CalculationInstanceProjection::McAcPfSolution,
6737 Some(PioValue::McAcOpfSolution(_)) => {
6738 CalculationInstanceProjection::McAcOpfSolution
6739 }
6740 Some(PioValue::LinDist3FlowOpfSolution(_)) => {
6741 CalculationInstanceProjection::LinDist3FlowOpfSolution
6742 }
6743 Some(PioValue::AcScucSolution(_)) => CalculationInstanceProjection::AcScucSolution,
6744 _ => {
6745 return Err(boundary_error(
6746 &codes::REQUEST_CAPI_TYPE_MISMATCH,
6747 "the handle does not refer to a calculation solution",
6748 ));
6749 }
6750 };
6751 Ok(PioCalculationInstance::new_raw(CalculationInstanceInner {
6752 value: ValueInner {
6753 owner: Arc::clone(&solution.owner),
6754 steps: solution.steps.clone(),
6755 },
6756 projection,
6757 }))
6758 })
6759 }
6760}
6761
6762fn make_balanced_network_view(
6763 value: &ValueInner,
6764 projection: BalancedNetworkProjection,
6765) -> *mut PioBalancedNetwork {
6766 PioBalancedNetwork::new_raw(BalancedNetworkInner {
6767 value: ValueInner {
6768 owner: Arc::clone(&value.owner),
6769 steps: value.steps.clone(),
6770 },
6771 projection,
6772 })
6773}
6774
6775fn make_multiconductor_network_view(
6776 value: &ValueInner,
6777 projection: MulticonductorNetworkProjection,
6778) -> *mut PioMulticonductorNetwork {
6779 PioMulticonductorNetwork::new_raw(MulticonductorNetworkInner {
6780 value: ValueInner {
6781 owner: Arc::clone(&value.owner),
6782 steps: value.steps.clone(),
6783 },
6784 projection,
6785 })
6786}
6787
6788#[unsafe(no_mangle)]
6792pub unsafe extern "C" fn pio_operating_point_balanced_network(
6793 point: *const PioOperatingPoint,
6794 error: *mut *mut PioError,
6795) -> *mut PioBalancedNetwork {
6796 unsafe {
6797 entry(error, std::ptr::null_mut(), || {
6798 let point = PioOperatingPoint::get(point).ok_or_else(|| {
6799 boundary_error(
6800 &codes::BIND_CAPI_NULL_HANDLE,
6801 "PioOperatingPoint must not be NULL",
6802 )
6803 })?;
6804 let projection = point.balanced_network_projection().ok_or_else(|| {
6805 boundary_error(
6806 &codes::REQUEST_CAPI_TYPE_MISMATCH,
6807 "the operating point does not use powerio.BalancedNetwork",
6808 )
6809 })?;
6810 Ok(make_balanced_network_view(&point.value, projection))
6811 })
6812 }
6813}
6814
6815#[unsafe(no_mangle)]
6819pub unsafe extern "C" fn pio_operating_point_multiconductor_network(
6820 point: *const PioOperatingPoint,
6821 error: *mut *mut PioError,
6822) -> *mut PioMulticonductorNetwork {
6823 unsafe {
6824 entry(error, std::ptr::null_mut(), || {
6825 let point = PioOperatingPoint::get(point).ok_or_else(|| {
6826 boundary_error(
6827 &codes::BIND_CAPI_NULL_HANDLE,
6828 "PioOperatingPoint must not be NULL",
6829 )
6830 })?;
6831 let projection = point.multiconductor_network_projection().ok_or_else(|| {
6832 boundary_error(
6833 &codes::REQUEST_CAPI_TYPE_MISMATCH,
6834 "the operating point does not use powerio.MulticonductorNetwork",
6835 )
6836 })?;
6837 Ok(make_multiconductor_network_view(&point.value, projection))
6838 })
6839 }
6840}
6841
6842#[unsafe(no_mangle)]
6846pub unsafe extern "C" fn pio_calculation_instance_balanced_network(
6847 instance: *const PioCalculationInstance,
6848 error: *mut *mut PioError,
6849) -> *mut PioBalancedNetwork {
6850 unsafe {
6851 entry(error, std::ptr::null_mut(), || {
6852 let instance = PioCalculationInstance::get(instance).ok_or_else(|| {
6853 boundary_error(
6854 &codes::BIND_CAPI_NULL_HANDLE,
6855 "PioCalculationInstance must not be NULL",
6856 )
6857 })?;
6858 let projection = match instance.projection {
6859 CalculationInstanceProjection::Direct => match instance.instance() {
6860 Some(CalculationInstanceRef::DcPf(_)) => {
6861 BalancedNetworkProjection::DcPfInstance
6862 }
6863 Some(CalculationInstanceRef::AcPf(_)) => {
6864 BalancedNetworkProjection::AcPfInstance
6865 }
6866 Some(CalculationInstanceRef::DcOpf(_)) => {
6867 BalancedNetworkProjection::DcOpfInstance
6868 }
6869 Some(CalculationInstanceRef::AcOpf(_)) => {
6870 BalancedNetworkProjection::AcOpfInstance
6871 }
6872 Some(CalculationInstanceRef::AcOts(_)) => {
6873 BalancedNetworkProjection::AcOtsInstance
6874 }
6875 Some(CalculationInstanceRef::AcScuc(_)) => {
6876 BalancedNetworkProjection::AcScucInstance
6877 }
6878 _ => {
6879 return Err(boundary_error(
6880 &codes::REQUEST_CAPI_TYPE_MISMATCH,
6881 "the calculation instance does not use powerio.BalancedNetwork",
6882 ));
6883 }
6884 },
6885 CalculationInstanceProjection::DcPfSolution => {
6886 BalancedNetworkProjection::DcPfSolution
6887 }
6888 CalculationInstanceProjection::AcPfSolution => {
6889 BalancedNetworkProjection::AcPfSolution
6890 }
6891 CalculationInstanceProjection::DcOpfSolution => {
6892 BalancedNetworkProjection::DcOpfSolution
6893 }
6894 CalculationInstanceProjection::AcOpfSolution => {
6895 BalancedNetworkProjection::AcOpfSolution
6896 }
6897 CalculationInstanceProjection::AcOtsSolution => {
6898 BalancedNetworkProjection::AcOtsSolution
6899 }
6900 CalculationInstanceProjection::SocwrOpfSolution => {
6901 BalancedNetworkProjection::SocwrOpfSolution
6902 }
6903 CalculationInstanceProjection::AcScucSolution => {
6904 BalancedNetworkProjection::AcScucSolution
6905 }
6906 _ => {
6907 return Err(boundary_error(
6908 &codes::REQUEST_CAPI_TYPE_MISMATCH,
6909 "the calculation instance does not use powerio.BalancedNetwork",
6910 ));
6911 }
6912 };
6913 Ok(make_balanced_network_view(&instance.value, projection))
6914 })
6915 }
6916}
6917
6918#[unsafe(no_mangle)]
6922pub unsafe extern "C" fn pio_calculation_instance_multiconductor_network(
6923 instance: *const PioCalculationInstance,
6924 error: *mut *mut PioError,
6925) -> *mut PioMulticonductorNetwork {
6926 unsafe {
6927 entry(error, std::ptr::null_mut(), || {
6928 let instance = PioCalculationInstance::get(instance).ok_or_else(|| {
6929 boundary_error(
6930 &codes::BIND_CAPI_NULL_HANDLE,
6931 "PioCalculationInstance must not be NULL",
6932 )
6933 })?;
6934 let projection = match instance.projection {
6935 CalculationInstanceProjection::Direct => match instance.instance() {
6936 Some(CalculationInstanceRef::McAcPf(_)) => {
6937 MulticonductorNetworkProjection::McAcPfInstance
6938 }
6939 Some(CalculationInstanceRef::McAcOpf(_)) => {
6940 MulticonductorNetworkProjection::McAcOpfInstance
6941 }
6942 Some(CalculationInstanceRef::LinDist3FlowOpf(_)) => {
6943 MulticonductorNetworkProjection::LinDist3FlowOpfInstance
6944 }
6945 _ => {
6946 return Err(boundary_error(
6947 &codes::REQUEST_CAPI_TYPE_MISMATCH,
6948 "the calculation instance does not use powerio.MulticonductorNetwork",
6949 ));
6950 }
6951 },
6952 CalculationInstanceProjection::McAcPfSolution => {
6953 MulticonductorNetworkProjection::McAcPfSolution
6954 }
6955 CalculationInstanceProjection::McAcOpfSolution => {
6956 MulticonductorNetworkProjection::McAcOpfSolution
6957 }
6958 CalculationInstanceProjection::LinDist3FlowOpfSolution => {
6959 MulticonductorNetworkProjection::LinDist3FlowOpfSolution
6960 }
6961 _ => {
6962 return Err(boundary_error(
6963 &codes::REQUEST_CAPI_TYPE_MISMATCH,
6964 "the calculation instance does not use powerio.MulticonductorNetwork",
6965 ));
6966 }
6967 };
6968 Ok(make_multiconductor_network_view(
6969 &instance.value,
6970 projection,
6971 ))
6972 })
6973 }
6974}
6975
6976fn branch_susceptance_formula_name(formula: BranchSusceptanceFormula) -> &'static str {
6977 formula.formula_name()
6978}
6979
6980unsafe fn require_calculation_instance<'a>(
6981 instance: *const PioCalculationInstance,
6982) -> Result<&'a CalculationInstanceInner, *mut PioError> {
6983 unsafe { PioCalculationInstance::get(instance) }.ok_or_else(|| {
6984 boundary_error(
6985 &codes::BIND_CAPI_NULL_HANDLE,
6986 "PioCalculationInstance must not be NULL",
6987 )
6988 })
6989}
6990
6991fn opf_preparation_units(name: &str) -> Result<Units, *mut PioError> {
6992 match name {
6993 "per_unit" => Ok(Units::PerUnit),
6994 "native" => Ok(Units::Native),
6995 _ => Err(boundary_error(
6996 &codes::BIND_CAPI_INVALID_OPTIONS,
6997 format!("unknown OPF preparation units '{name}'; expected 'per_unit' or 'native'"),
6998 )),
6999 }
7000}
7001
7002fn opf_preparation_units_name(units: Units) -> Option<&'static str> {
7003 match units {
7004 Units::PerUnit => Some("per_unit"),
7005 Units::Native => Some("native"),
7006 _ => None,
7007 }
7008}
7009
7010fn prepared_objective_name(objective: PreparedObjective) -> Option<&'static str> {
7011 match objective {
7012 PreparedObjective::Feasibility => Some("feasibility"),
7013 PreparedObjective::NetworkGeneratorCost => Some("network_generator_cost"),
7014 _ => None,
7015 }
7016}
7017
7018fn opf_analysis_branch_source(
7019 source: AnalysisBranchSource,
7020 preparation: &str,
7021) -> Result<(&'static str, usize, Option<usize>), *mut PioError> {
7022 match source {
7023 AnalysisBranchSource::Branch { row } => Ok(("branch", row, None)),
7024 AnalysisBranchSource::ThreeWindingTransformerWinding {
7025 transformer_row,
7026 winding,
7027 } => Ok((
7028 "three_winding_transformer_winding",
7029 transformer_row,
7030 Some(winding),
7031 )),
7032 _ => Err(boundary_error(
7033 &codes::REQUEST_CAPI_TYPE_MISMATCH,
7034 format!(
7035 "the {preparation} OPF preparation has an analysis branch source unsupported by the C ABI"
7036 ),
7037 )),
7038 }
7039}
7040
7041#[unsafe(no_mangle)]
7046pub unsafe extern "C" fn pio_build_dc_opf_preparation(
7047 instance: *const PioCalculationInstance,
7048 units: *const c_char,
7049 units_len: usize,
7050 skip_zero_impedance: bool,
7051 synthesize_unrated_limits: bool,
7052 correct_angle_difference_bounds: bool,
7053 error: *mut *mut PioError,
7054) -> *mut PioDcOpfPreparation {
7055 unsafe {
7056 entry(error, std::ptr::null_mut(), || {
7057 let instance = require_calculation_instance(instance)?
7058 .dc_opf()
7059 .ok_or_else(|| {
7060 boundary_error(
7061 &codes::REQUEST_CAPI_TYPE_MISMATCH,
7062 "DC OPF preparation requires powerio.DcOpfInstance",
7063 )
7064 })?;
7065 let units = opf_preparation_units(required_str(units, units_len, "units")?)?;
7066 let options = DcOpfAssemblyOptions::default()
7072 .with_units(units)
7073 .with_skip_zero_impedance(skip_zero_impedance)
7074 .with_synthesize_unrated_limits(synthesize_unrated_limits)
7075 .with_correct_angle_difference_bounds(correct_angle_difference_bounds)
7076 .with_hvdc_treatment(powerio_tx::HvdcTreatment::Ignore);
7077 build_dc_opf_preparation(instance, &options)
7078 .map(PioDcOpfPreparation::new_raw)
7079 .map_err(|failure| error_from_matrix(&failure))
7080 })
7081 }
7082}
7083
7084#[unsafe(no_mangle)]
7089pub unsafe extern "C" fn pio_dc_opf_preparation_summary(
7090 preparation: *const PioDcOpfPreparation,
7091 output: *mut PioDcOpfPreparationView,
7092 error: *mut *mut PioError,
7093) -> bool {
7094 unsafe {
7095 entry(error, false, || {
7096 let preparation = PioDcOpfPreparation::get(preparation).ok_or_else(|| {
7097 boundary_error(
7098 &codes::BIND_CAPI_NULL_HANDLE,
7099 "PioDcOpfPreparation must not be NULL",
7100 )
7101 })?;
7102 let units = opf_preparation_units_name(preparation.units).ok_or_else(|| {
7103 boundary_error(
7104 &codes::REQUEST_CAPI_TYPE_MISMATCH,
7105 "the DC OPF preparation uses units unsupported by the C ABI",
7106 )
7107 })?;
7108 let objective = prepared_objective_name(preparation.objective).ok_or_else(|| {
7109 boundary_error(
7110 &codes::REQUEST_CAPI_TYPE_MISMATCH,
7111 "the DC OPF preparation uses an objective unsupported by the C ABI",
7112 )
7113 })?;
7114 *require_output(output, "output")? = PioDcOpfPreparationView {
7115 name: PioStringView::new(&preparation.name),
7116 bus_count: preparation.n_buses,
7117 generator_count: preparation.n_generators(),
7118 branch_count: preparation.n_branches(),
7119 source_generator_count: preparation.n_source_generators,
7120 source_branch_count: preparation.n_source_branches,
7121 base_mva: preparation.base_mva,
7122 units: PioStringView::new(units),
7123 branch_susceptance_formula: PioStringView::new(branch_susceptance_formula_name(
7124 preparation.formula,
7125 )),
7126 objective: PioStringView::new(objective),
7127 skip_zero_impedance: preparation.skip_zero_impedance,
7128 synthesize_unrated_limits: preparation.synthesize_unrated_limits,
7129 correct_angle_difference_bounds: preparation.correct_angle_difference_bounds,
7130 reference_bus_count: preparation.reference_buses.len(),
7131 skipped_zero_impedance_count: preparation.branches.skipped_zero_impedance.len(),
7132 };
7133 Ok(true)
7134 })
7135 }
7136}
7137
7138#[unsafe(no_mangle)]
7143pub unsafe extern "C" fn pio_dc_opf_preparation_reference_buses(
7144 preparation: *const PioDcOpfPreparation,
7145) -> PioSizeView {
7146 unsafe { PioDcOpfPreparation::get(preparation) }.map_or(PioSizeView::EMPTY, |value| {
7147 PioSizeView::new(value.reference_buses.as_ref())
7148 })
7149}
7150
7151#[unsafe(no_mangle)]
7156pub unsafe extern "C" fn pio_dc_opf_preparation_skipped_zero_impedance(
7157 preparation: *const PioDcOpfPreparation,
7158) -> PioSizeView {
7159 unsafe { PioDcOpfPreparation::get(preparation) }.map_or(PioSizeView::EMPTY, |value| {
7160 PioSizeView::new(&value.branches.skipped_zero_impedance)
7161 })
7162}
7163
7164#[unsafe(no_mangle)]
7169pub unsafe extern "C" fn pio_dc_opf_preparation_bus_at(
7170 preparation: *const PioDcOpfPreparation,
7171 index: usize,
7172 output: *mut PioDcOpfBusView,
7173 error: *mut *mut PioError,
7174) -> bool {
7175 unsafe {
7176 entry(error, false, || {
7177 let value = PioDcOpfPreparation::get(preparation).ok_or_else(|| {
7178 boundary_error(
7179 &codes::BIND_CAPI_NULL_HANDLE,
7180 "PioDcOpfPreparation must not be NULL",
7181 )
7182 })?;
7183 if index >= value.n_buses {
7184 return Err(boundary_error(
7185 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
7186 format!("DC OPF preparation bus index {index} is out of range"),
7187 ));
7188 }
7189 let source_row = value.bus_source_rows[index];
7190 *require_output(output, "output")? = PioDcOpfBusView {
7191 bus_id: value.bus_ids[index].0,
7192 analysis_row: value.bus_analysis_rows[index],
7193 source_row: source_row.unwrap_or(0),
7194 has_source_row: source_row.is_some(),
7195 active_power_demand: value.p_d[index],
7196 shunt_conductance: value.g_s[index],
7197 phase_shift_injection: value.p_shift[index],
7198 };
7199 Ok(true)
7200 })
7201 }
7202}
7203
7204#[unsafe(no_mangle)]
7209pub unsafe extern "C" fn pio_dc_opf_preparation_generator_at(
7210 preparation: *const PioDcOpfPreparation,
7211 index: usize,
7212 output: *mut PioDcOpfGeneratorView,
7213 error: *mut *mut PioError,
7214) -> bool {
7215 unsafe {
7216 entry(error, false, || {
7217 let value = PioDcOpfPreparation::get(preparation).ok_or_else(|| {
7218 boundary_error(
7219 &codes::BIND_CAPI_NULL_HANDLE,
7220 "PioDcOpfPreparation must not be NULL",
7221 )
7222 })?;
7223 if index >= value.n_generators() {
7224 return Err(boundary_error(
7225 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
7226 format!("DC OPF preparation generator index {index} is out of range"),
7227 ));
7228 }
7229 let source_row = value.generators.source_rows[index];
7230 let piecewise = value.generators.piecewise_linear[index].as_ref();
7231 *require_output(output, "output")? = PioDcOpfGeneratorView {
7232 component_id: PioStringView::new(&value.generators.identities[index]),
7233 bus_index: value.generators.bus_of_gen[index],
7234 analysis_row: value.generators.analysis_rows[index],
7235 source_row: source_row.unwrap_or(0),
7236 has_source_row: source_row.is_some(),
7237 quadratic_cost: value.generators.q[index],
7238 linear_cost: value.generators.c[index],
7239 constant_cost: value.generators.c0[index],
7240 has_piecewise_linear_cost: piecewise.is_some(),
7241 piecewise_linear_power: piecewise
7242 .map_or(PioF64View::EMPTY, |cost| PioF64View::new(&cost.power)),
7243 piecewise_linear_value: piecewise
7244 .map_or(PioF64View::EMPTY, |cost| PioF64View::new(&cost.value)),
7245 active_power_max: value.generators.pmax[index],
7246 active_power_min: value.generators.pmin[index],
7247 capability_active: value.generators.capability_active[index],
7248 };
7249 Ok(true)
7250 })
7251 }
7252}
7253
7254#[unsafe(no_mangle)]
7259pub unsafe extern "C" fn pio_dc_opf_preparation_branch_at(
7260 preparation: *const PioDcOpfPreparation,
7261 index: usize,
7262 output: *mut PioDcOpfBranchView,
7263 error: *mut *mut PioError,
7264) -> bool {
7265 unsafe {
7266 entry(error, false, || {
7267 let value = PioDcOpfPreparation::get(preparation).ok_or_else(|| {
7268 boundary_error(
7269 &codes::BIND_CAPI_NULL_HANDLE,
7270 "PioDcOpfPreparation must not be NULL",
7271 )
7272 })?;
7273 if index >= value.n_branches() {
7274 return Err(boundary_error(
7275 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
7276 format!("DC OPF preparation branch index {index} is out of range"),
7277 ));
7278 }
7279 let (source_kind, source_row, winding) =
7280 opf_analysis_branch_source(value.branches.analysis_sources[index], "DC")?;
7281 *require_output(output, "output")? = PioDcOpfBranchView {
7282 component_id: PioStringView::new(&value.branches.identities[index]),
7283 from_bus_index: value.branches.from_bus[index],
7284 to_bus_index: value.branches.to_bus[index],
7285 susceptance_magnitude: value.branches.susceptance_magnitude[index],
7286 phase_shift_radians: value.branches.shift[index],
7287 active_power_max: value.branches.f_max[index],
7288 angle_difference_min_radians: value.branches.angle_min[index],
7289 angle_difference_max_radians: value.branches.angle_max[index],
7290 analysis_row: value.branches.analysis_rows[index],
7291 source_kind: PioStringView::new(source_kind),
7292 source_row,
7293 winding: winding.unwrap_or(0),
7294 has_winding: winding.is_some(),
7295 thermal_limit_active: value.branches.thermal_limit_active[index],
7296 angle_bound_active: value.branches.angle_bound_active[index],
7297 };
7298 Ok(true)
7299 })
7300 }
7301}
7302
7303#[unsafe(no_mangle)]
7308pub unsafe extern "C" fn pio_build_ac_opf_preparation(
7309 instance: *const PioCalculationInstance,
7310 units: *const c_char,
7311 units_len: usize,
7312 skip_zero_impedance: bool,
7313 synthesize_unrated_limits: bool,
7314 correct_angle_difference_bounds: bool,
7315 error: *mut *mut PioError,
7316) -> *mut PioAcOpfPreparation {
7317 unsafe {
7318 entry(error, std::ptr::null_mut(), || {
7319 let instance = require_calculation_instance(instance)?
7320 .ac_opf()
7321 .ok_or_else(|| {
7322 boundary_error(
7323 &codes::REQUEST_CAPI_TYPE_MISMATCH,
7324 "AC OPF preparation requires powerio.AcOpfInstance",
7325 )
7326 })?;
7327 let units = opf_preparation_units(required_str(units, units_len, "units")?)?;
7328 let options = AcOpfAssemblyOptions::default()
7329 .with_units(units)
7330 .with_skip_zero_impedance(skip_zero_impedance)
7331 .with_synthesize_unrated_limits(synthesize_unrated_limits)
7332 .with_correct_angle_difference_bounds(correct_angle_difference_bounds);
7333 build_ac_opf_preparation(instance, &options)
7334 .map(PioAcOpfPreparation::new_raw)
7335 .map_err(|failure| error_from_matrix(&failure))
7336 })
7337 }
7338}
7339
7340#[unsafe(no_mangle)]
7345pub unsafe extern "C" fn pio_ac_opf_preparation_summary(
7346 preparation: *const PioAcOpfPreparation,
7347 output: *mut PioAcOpfPreparationView,
7348 error: *mut *mut PioError,
7349) -> bool {
7350 unsafe {
7351 entry(error, false, || {
7352 let preparation = PioAcOpfPreparation::get(preparation).ok_or_else(|| {
7353 boundary_error(
7354 &codes::BIND_CAPI_NULL_HANDLE,
7355 "PioAcOpfPreparation must not be NULL",
7356 )
7357 })?;
7358 let units = opf_preparation_units_name(preparation.units).ok_or_else(|| {
7359 boundary_error(
7360 &codes::REQUEST_CAPI_TYPE_MISMATCH,
7361 "the AC OPF preparation uses units unsupported by the C ABI",
7362 )
7363 })?;
7364 let objective = prepared_objective_name(preparation.objective).ok_or_else(|| {
7365 boundary_error(
7366 &codes::REQUEST_CAPI_TYPE_MISMATCH,
7367 "the AC OPF preparation uses an objective unsupported by the C ABI",
7368 )
7369 })?;
7370 *require_output(output, "output")? = PioAcOpfPreparationView {
7371 name: PioStringView::new(&preparation.name),
7372 bus_count: preparation.n_buses,
7373 generator_count: preparation.n_generators(),
7374 storage_count: preparation.n_storage(),
7375 branch_count: preparation.n_branches(),
7376 source_generator_count: preparation.n_source_generators,
7377 source_branch_count: preparation.n_source_branches,
7378 base_mva: preparation.base_mva,
7379 units: PioStringView::new(units),
7380 objective: PioStringView::new(objective),
7381 skip_zero_impedance: preparation.skip_zero_impedance,
7382 synthesize_unrated_limits: preparation.synthesize_unrated_limits,
7383 correct_angle_difference_bounds: preparation.correct_angle_difference_bounds,
7384 reference_bus_count: preparation.reference_buses.len(),
7385 skipped_zero_impedance_count: preparation.branches.skipped_zero_impedance.len(),
7386 };
7387 Ok(true)
7388 })
7389 }
7390}
7391
7392#[unsafe(no_mangle)]
7397pub unsafe extern "C" fn pio_ac_opf_preparation_reference_buses(
7398 preparation: *const PioAcOpfPreparation,
7399) -> PioSizeView {
7400 unsafe { PioAcOpfPreparation::get(preparation) }.map_or(PioSizeView::EMPTY, |value| {
7401 PioSizeView::new(value.reference_buses.as_ref())
7402 })
7403}
7404
7405#[unsafe(no_mangle)]
7410pub unsafe extern "C" fn pio_ac_opf_preparation_skipped_zero_impedance(
7411 preparation: *const PioAcOpfPreparation,
7412) -> PioSizeView {
7413 unsafe { PioAcOpfPreparation::get(preparation) }.map_or(PioSizeView::EMPTY, |value| {
7414 PioSizeView::new(&value.branches.skipped_zero_impedance)
7415 })
7416}
7417
7418#[unsafe(no_mangle)]
7423pub unsafe extern "C" fn pio_ac_opf_preparation_bus_at(
7424 preparation: *const PioAcOpfPreparation,
7425 index: usize,
7426 output: *mut PioAcOpfBusView,
7427 error: *mut *mut PioError,
7428) -> bool {
7429 unsafe {
7430 entry(error, false, || {
7431 let value = PioAcOpfPreparation::get(preparation).ok_or_else(|| {
7432 boundary_error(
7433 &codes::BIND_CAPI_NULL_HANDLE,
7434 "PioAcOpfPreparation must not be NULL",
7435 )
7436 })?;
7437 if index >= value.n_buses {
7438 return Err(boundary_error(
7439 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
7440 format!("AC OPF preparation bus index {index} is out of range"),
7441 ));
7442 }
7443 let source_row = value.bus_source_rows[index];
7444 *require_output(output, "output")? = PioAcOpfBusView {
7445 bus_id: value.bus_ids[index].0,
7446 analysis_row: value.bus_analysis_rows[index],
7447 source_row: source_row.unwrap_or(0),
7448 has_source_row: source_row.is_some(),
7449 active_power_demand: value.buses.p_d[index],
7450 reactive_power_demand: value.buses.q_d[index],
7451 shunt_conductance: value.buses.g_s[index],
7452 shunt_susceptance: value.buses.b_s[index],
7453 voltage_magnitude_min_pu: value.buses.vm_min[index],
7454 voltage_magnitude_max_pu: value.buses.vm_max[index],
7455 initial_voltage_magnitude_pu: value.buses.initial_vm[index],
7456 initial_voltage_angle_radians: value.buses.initial_va[index],
7457 voltage_bound_active: value.buses.voltage_bound_active[index],
7458 };
7459 Ok(true)
7460 })
7461 }
7462}
7463
7464#[unsafe(no_mangle)]
7469pub unsafe extern "C" fn pio_ac_opf_preparation_generator_at(
7470 preparation: *const PioAcOpfPreparation,
7471 index: usize,
7472 output: *mut PioAcOpfGeneratorView,
7473 error: *mut *mut PioError,
7474) -> bool {
7475 unsafe {
7476 entry(error, false, || {
7477 let value = PioAcOpfPreparation::get(preparation).ok_or_else(|| {
7478 boundary_error(
7479 &codes::BIND_CAPI_NULL_HANDLE,
7480 "PioAcOpfPreparation must not be NULL",
7481 )
7482 })?;
7483 if index >= value.n_generators() {
7484 return Err(boundary_error(
7485 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
7486 format!("AC OPF preparation generator index {index} is out of range"),
7487 ));
7488 }
7489 let source_row = value.generators.source_rows[index];
7490 let piecewise = value.generators.piecewise_linear[index].as_ref();
7491 *require_output(output, "output")? = PioAcOpfGeneratorView {
7492 component_id: PioStringView::new(&value.generators.identities[index]),
7493 bus_index: value.generators.bus_of_gen[index],
7494 analysis_row: value.generators.analysis_rows[index],
7495 source_row: source_row.unwrap_or(0),
7496 has_source_row: source_row.is_some(),
7497 quadratic_cost: value.generators.q[index],
7498 linear_cost: value.generators.c[index],
7499 constant_cost: value.generators.c0[index],
7500 has_piecewise_linear_cost: piecewise.is_some(),
7501 piecewise_linear_power: piecewise
7502 .map_or(PioF64View::EMPTY, |cost| PioF64View::new(&cost.power)),
7503 piecewise_linear_value: piecewise
7504 .map_or(PioF64View::EMPTY, |cost| PioF64View::new(&cost.value)),
7505 active_power_max: value.generators.pmax[index],
7506 active_power_min: value.generators.pmin[index],
7507 reactive_power_max: value.generators.qmax[index],
7508 reactive_power_min: value.generators.qmin[index],
7509 initial_active_power: value.generators.pg[index],
7510 initial_reactive_power: value.generators.qg[index],
7511 voltage_magnitude_setpoint_pu: value.generators.vg[index],
7512 capability_active: value.generators.capability_active[index],
7513 };
7514 Ok(true)
7515 })
7516 }
7517}
7518
7519#[unsafe(no_mangle)]
7524pub unsafe extern "C" fn pio_ac_opf_preparation_storage_at(
7525 preparation: *const PioAcOpfPreparation,
7526 index: usize,
7527 output: *mut PioAcOpfStorageView,
7528 error: *mut *mut PioError,
7529) -> bool {
7530 unsafe {
7531 entry(error, false, || {
7532 let value = PioAcOpfPreparation::get(preparation).ok_or_else(|| {
7533 boundary_error(
7534 &codes::BIND_CAPI_NULL_HANDLE,
7535 "PioAcOpfPreparation must not be NULL",
7536 )
7537 })?;
7538 if index >= value.n_storage() {
7539 return Err(boundary_error(
7540 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
7541 format!("AC OPF preparation storage index {index} is out of range"),
7542 ));
7543 }
7544 let storage = &value.storage;
7545 *require_output(output, "output")? = PioAcOpfStorageView {
7546 component_id: PioStringView::new(&storage.identities[index]),
7547 bus_index: storage.bus_of_storage[index],
7548 source_row: storage.source_rows[index],
7549 initial_active_power: storage.p[index],
7550 initial_reactive_power: storage.q[index],
7551 energy: storage.energy[index],
7552 energy_rating: storage.energy_rating[index],
7553 charge_rating: storage.charge_rating[index],
7554 discharge_rating: storage.discharge_rating[index],
7555 charge_efficiency: storage.charge_efficiency[index],
7556 discharge_efficiency: storage.discharge_efficiency[index],
7557 apparent_power_max: storage.s_max[index],
7558 reactive_power_min: storage.qmin[index],
7559 reactive_power_max: storage.qmax[index],
7560 resistance_pu: storage.r[index],
7561 reactance_pu: storage.x[index],
7562 active_power_loss: storage.p_loss[index],
7563 reactive_power_loss: storage.q_loss[index],
7564 in_service: storage.in_service[index],
7565 };
7566 Ok(true)
7567 })
7568 }
7569}
7570
7571#[unsafe(no_mangle)]
7576pub unsafe extern "C" fn pio_ac_opf_preparation_branch_at(
7577 preparation: *const PioAcOpfPreparation,
7578 index: usize,
7579 output: *mut PioAcOpfBranchView,
7580 error: *mut *mut PioError,
7581) -> bool {
7582 unsafe {
7583 entry(error, false, || {
7584 let value = PioAcOpfPreparation::get(preparation).ok_or_else(|| {
7585 boundary_error(
7586 &codes::BIND_CAPI_NULL_HANDLE,
7587 "PioAcOpfPreparation must not be NULL",
7588 )
7589 })?;
7590 if index >= value.n_branches() {
7591 return Err(boundary_error(
7592 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
7593 format!("AC OPF preparation branch index {index} is out of range"),
7594 ));
7595 }
7596 let (source_kind, source_row, winding) =
7597 opf_analysis_branch_source(value.branches.analysis_sources[index], "AC")?;
7598 *require_output(output, "output")? = PioAcOpfBranchView {
7599 component_id: PioStringView::new(&value.branches.identities[index]),
7600 from_bus_index: value.branches.from_bus[index],
7601 to_bus_index: value.branches.to_bus[index],
7602 series_conductance: value.branches.g[index],
7603 series_susceptance: value.branches.b[index],
7604 from_conductance: value.branches.g_fr[index],
7605 from_susceptance: value.branches.b_fr[index],
7606 to_conductance: value.branches.g_to[index],
7607 to_susceptance: value.branches.b_to[index],
7608 tap_ratio: value.branches.tap[index],
7609 phase_shift_radians: value.branches.shift[index],
7610 apparent_power_max: value.branches.s_max[index],
7611 angle_difference_min_radians: value.branches.angle_min[index],
7612 angle_difference_max_radians: value.branches.angle_max[index],
7613 analysis_row: value.branches.analysis_rows[index],
7614 source_kind: PioStringView::new(source_kind),
7615 source_row,
7616 winding: winding.unwrap_or(0),
7617 has_winding: winding.is_some(),
7618 thermal_limit_active: value.branches.thermal_limit_active[index],
7619 angle_bound_active: value.branches.angle_bound_active[index],
7620 };
7621 Ok(true)
7622 })
7623 }
7624}
7625
7626#[unsafe(no_mangle)]
7630pub unsafe extern "C" fn pio_dc_pf_instance_bus_specification_count(
7631 instance: *const PioCalculationInstance,
7632) -> usize {
7633 unsafe { PioCalculationInstance::get(instance) }
7634 .and_then(CalculationInstanceInner::dc_pf)
7635 .map_or(0, |instance| instance.specifications().len())
7636}
7637
7638#[unsafe(no_mangle)]
7643pub unsafe extern "C" fn pio_dc_pf_instance_bus_specification_at(
7644 instance: *const PioCalculationInstance,
7645 index: usize,
7646 output: *mut PioDcBusSpecificationView,
7647 error: *mut *mut PioError,
7648) -> bool {
7649 unsafe {
7650 entry(error, false, || {
7651 let instance = require_calculation_instance(instance)?
7652 .dc_pf()
7653 .ok_or_else(|| {
7654 boundary_error(
7655 &codes::REQUEST_CAPI_TYPE_MISMATCH,
7656 "the calculation instance is not powerio.DcPfInstance",
7657 )
7658 })?;
7659 let specification = instance.specifications().get(index).ok_or_else(|| {
7660 boundary_error(
7661 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
7662 format!("DC bus specification index {index} is out of range"),
7663 )
7664 })?;
7665 let bus_id = instance
7666 .network()
7667 .buses()
7668 .get(index)
7669 .ok_or_else(|| {
7670 boundary_error(
7671 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
7672 format!("bus specification index {index} has no bus"),
7673 )
7674 })?
7675 .id
7676 .0;
7677 let (kind, net_active_power_mw, voltage_angle_degrees) = match *specification {
7678 powerio_prob::DcBusSpecification::NetActivePower { p_mw } => {
7679 ("net_active_power", p_mw, 0.0)
7680 }
7681 powerio_prob::DcBusSpecification::Reference { va_degrees } => {
7682 ("reference", 0.0, va_degrees)
7683 }
7684 powerio_prob::DcBusSpecification::Isolated => ("isolated", 0.0, 0.0),
7685 _ => ("unknown", 0.0, 0.0),
7686 };
7687 *require_output(output, "output")? = PioDcBusSpecificationView {
7688 bus_id,
7689 kind: PioStringView::new(kind),
7690 net_active_power_mw,
7691 voltage_angle_degrees,
7692 };
7693 Ok(true)
7694 })
7695 }
7696}
7697
7698#[unsafe(no_mangle)]
7702pub unsafe extern "C" fn pio_dc_pf_instance_branch_susceptance_formula(
7703 instance: *const PioCalculationInstance,
7704) -> PioStringView {
7705 unsafe { PioCalculationInstance::get(instance) }
7706 .and_then(CalculationInstanceInner::dc_pf)
7707 .map_or(PioStringView::EMPTY, |instance| {
7708 PioStringView::new(branch_susceptance_formula_name(
7709 instance.branch_susceptance_formula(),
7710 ))
7711 })
7712}
7713
7714#[unsafe(no_mangle)]
7718pub unsafe extern "C" fn pio_ac_pf_instance_bus_specification_count(
7719 instance: *const PioCalculationInstance,
7720) -> usize {
7721 unsafe { PioCalculationInstance::get(instance) }
7722 .and_then(CalculationInstanceInner::ac_pf)
7723 .map_or(0, |instance| instance.specifications().len())
7724}
7725
7726#[unsafe(no_mangle)]
7731pub unsafe extern "C" fn pio_ac_pf_instance_bus_specification_at(
7732 instance: *const PioCalculationInstance,
7733 index: usize,
7734 output: *mut PioAcBusSpecificationView,
7735 error: *mut *mut PioError,
7736) -> bool {
7737 unsafe {
7738 entry(error, false, || {
7739 let instance = require_calculation_instance(instance)?
7740 .ac_pf()
7741 .ok_or_else(|| {
7742 boundary_error(
7743 &codes::REQUEST_CAPI_TYPE_MISMATCH,
7744 "the calculation instance is not powerio.AcPfInstance",
7745 )
7746 })?;
7747 let specification = instance.specifications().get(index).ok_or_else(|| {
7748 boundary_error(
7749 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
7750 format!("AC bus specification index {index} is out of range"),
7751 )
7752 })?;
7753 let bus_id = instance
7754 .network()
7755 .buses()
7756 .get(index)
7757 .ok_or_else(|| {
7758 boundary_error(
7759 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
7760 format!("bus specification index {index} has no bus"),
7761 )
7762 })?
7763 .id
7764 .0;
7765 let (kind, p, q, vm, va) = match *specification {
7766 powerio_prob::AcBusSpecification::Pq { p, q } => ("pq", p, q, 0.0, 0.0),
7767 powerio_prob::AcBusSpecification::Pv { p, vm } => ("pv", p, 0.0, vm, 0.0),
7768 powerio_prob::AcBusSpecification::Reference { vm, va } => {
7769 ("reference", 0.0, 0.0, vm, va)
7770 }
7771 powerio_prob::AcBusSpecification::Isolated => ("isolated", 0.0, 0.0, 0.0, 0.0),
7772 _ => ("unknown", 0.0, 0.0, 0.0, 0.0),
7773 };
7774 *require_output(output, "output")? = PioAcBusSpecificationView {
7775 bus_id,
7776 kind: PioStringView::new(kind),
7777 net_active_power_mw: p,
7778 net_reactive_power_mvar: q,
7779 voltage_magnitude_pu: vm,
7780 voltage_angle_degrees: va,
7781 };
7782 Ok(true)
7783 })
7784 }
7785}
7786
7787#[unsafe(no_mangle)]
7791pub unsafe extern "C" fn pio_dc_opf_instance_branch_susceptance_formula(
7792 instance: *const PioCalculationInstance,
7793) -> PioStringView {
7794 unsafe { PioCalculationInstance::get(instance) }
7795 .and_then(CalculationInstanceInner::dc_opf)
7796 .map_or(PioStringView::EMPTY, |instance| {
7797 PioStringView::new(branch_susceptance_formula_name(
7798 instance.branch_susceptance_formula(),
7799 ))
7800 })
7801}
7802
7803#[repr(C)]
7805#[derive(Clone, Copy)]
7806pub struct PioLinDist3FlowNodeView {
7807 pub bus: PioStringView,
7808 pub terminal: PioStringView,
7809 pub reference_magnitude: f64,
7810 pub reference_angle: f64,
7811 pub is_root: bool,
7812}
7813
7814#[repr(C)]
7817#[derive(Clone, Copy)]
7818pub struct PioLinDist3FlowConductorView {
7819 pub line: PioStringView,
7820 pub source_line_row: usize,
7821 pub conductor_position: usize,
7822 pub parent_bus: PioStringView,
7823 pub parent_terminal: PioStringView,
7824 pub child_bus: PioStringView,
7825 pub child_terminal: PioStringView,
7826 pub reversed: bool,
7827}
7828
7829impl CalculationInstanceInner {
7830 fn lindist3flow(&self) -> Option<&powerio_prob::LinDist3FlowOpfInstance> {
7831 match self.instance()? {
7832 CalculationInstanceRef::LinDist3FlowOpf(instance) => Some(instance),
7833 _ => None,
7834 }
7835 }
7836}
7837
7838#[unsafe(no_mangle)]
7842pub unsafe extern "C" fn pio_lindist3flow_opf_instance_node_count(
7843 instance: *const PioCalculationInstance,
7844) -> usize {
7845 unsafe { PioCalculationInstance::get(instance) }
7846 .and_then(CalculationInstanceInner::lindist3flow)
7847 .map_or(0, |instance| instance.topology().nodes.len())
7848}
7849
7850#[unsafe(no_mangle)]
7854pub unsafe extern "C" fn pio_lindist3flow_opf_instance_conductor_count(
7855 instance: *const PioCalculationInstance,
7856) -> usize {
7857 unsafe { PioCalculationInstance::get(instance) }
7858 .and_then(CalculationInstanceInner::lindist3flow)
7859 .map_or(0, |instance| instance.topology().conductors.len())
7860}
7861
7862#[unsafe(no_mangle)]
7867pub unsafe extern "C" fn pio_lindist3flow_opf_instance_node_at(
7868 instance: *const PioCalculationInstance,
7869 index: usize,
7870 output: *mut PioLinDist3FlowNodeView,
7871 error: *mut *mut PioError,
7872) -> bool {
7873 unsafe {
7874 entry(error, false, || {
7875 let instance = require_calculation_instance(instance)?
7876 .lindist3flow()
7877 .ok_or_else(|| {
7878 boundary_error(
7879 &codes::REQUEST_CAPI_TYPE_MISMATCH,
7880 "expected a LinDist3Flow OPF instance",
7881 )
7882 })?;
7883 let voltage = instance.reference().voltages.get(index).ok_or_else(|| {
7884 boundary_error(
7885 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
7886 format!("node index {index} is out of range"),
7887 )
7888 })?;
7889 *require_output(output, "output")? = PioLinDist3FlowNodeView {
7890 bus: PioStringView::new(&voltage.node.bus),
7891 terminal: PioStringView::new(&voltage.node.terminal),
7892 reference_magnitude: voltage.magnitude,
7893 reference_angle: voltage.angle,
7894 is_root: instance.topology().roots.contains(&voltage.node),
7895 };
7896 Ok(true)
7897 })
7898 }
7899}
7900
7901#[unsafe(no_mangle)]
7906pub unsafe extern "C" fn pio_lindist3flow_opf_instance_conductor_at(
7907 instance: *const PioCalculationInstance,
7908 index: usize,
7909 output: *mut PioLinDist3FlowConductorView,
7910 error: *mut *mut PioError,
7911) -> bool {
7912 unsafe {
7913 entry(error, false, || {
7914 let instance = require_calculation_instance(instance)?
7915 .lindist3flow()
7916 .ok_or_else(|| {
7917 boundary_error(
7918 &codes::REQUEST_CAPI_TYPE_MISMATCH,
7919 "expected a LinDist3Flow OPF instance",
7920 )
7921 })?;
7922 let conductor = instance.topology().conductors.get(index).ok_or_else(|| {
7923 boundary_error(
7924 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
7925 format!("conductor index {index} is out of range"),
7926 )
7927 })?;
7928 *require_output(output, "output")? = PioLinDist3FlowConductorView {
7929 line: PioStringView::new(&conductor.line),
7930 source_line_row: conductor.source_line_row,
7931 conductor_position: conductor.conductor_position,
7932 parent_bus: PioStringView::new(&conductor.parent.bus),
7933 parent_terminal: PioStringView::new(&conductor.parent.terminal),
7934 child_bus: PioStringView::new(&conductor.child.bus),
7935 child_terminal: PioStringView::new(&conductor.child.terminal),
7936 reversed: conductor.reversed,
7937 };
7938 Ok(true)
7939 })
7940 }
7941}
7942
7943fn objective(instance: &CalculationInstanceInner) -> Option<&powerio_prob::Objective> {
7944 match instance.instance()? {
7945 CalculationInstanceRef::DcOpf(instance) => Some(instance.objective()),
7946 CalculationInstanceRef::AcOpf(instance) => Some(instance.objective()),
7947 CalculationInstanceRef::AcOts(instance) => Some(instance.objective()),
7948 CalculationInstanceRef::McAcOpf(instance) => Some(instance.objective()),
7949 CalculationInstanceRef::LinDist3FlowOpf(instance) => {
7950 Some(instance.base_instance().objective())
7951 }
7952 _ => None,
7953 }
7954}
7955
7956fn objective_term_name(term: &powerio_prob::ObjectiveTerm) -> &'static str {
7957 match term {
7958 powerio_prob::ObjectiveTerm::NetworkGeneratorCost => "network_generator_cost",
7959 powerio_prob::ObjectiveTerm::ActivePowerDispatchCost => "active_power_dispatch_cost",
7960 powerio_prob::ObjectiveTerm::BranchSwitchingCost => "branch_switching_cost",
7961 _ => "unknown",
7962 }
7963}
7964
7965#[unsafe(no_mangle)]
7969pub unsafe extern "C" fn pio_calculation_instance_objective_term_count(
7970 instance: *const PioCalculationInstance,
7971) -> usize {
7972 unsafe { PioCalculationInstance::get(instance) }
7973 .and_then(objective)
7974 .map_or(0, |objective| objective.terms().len())
7975}
7976
7977#[unsafe(no_mangle)]
7982pub unsafe extern "C" fn pio_calculation_instance_objective_term_at(
7983 instance: *const PioCalculationInstance,
7984 index: usize,
7985 output: *mut PioObjectiveTermView,
7986 error: *mut *mut PioError,
7987) -> bool {
7988 unsafe {
7989 entry(error, false, || {
7990 let value = require_calculation_instance(instance)?;
7991 let objective = objective(value).ok_or_else(|| {
7992 boundary_error(
7993 &codes::REQUEST_CAPI_TYPE_MISMATCH,
7994 "the calculation instance has no optimization objective",
7995 )
7996 })?;
7997 let term = objective.terms().get(index).ok_or_else(|| {
7998 boundary_error(
7999 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
8000 format!("objective term index {index} is out of range"),
8001 )
8002 })?;
8003 *require_output(output, "output")? = PioObjectiveTermView {
8004 kind: PioStringView::new(objective_term_name(term)),
8005 };
8006 Ok(true)
8007 })
8008 }
8009}
8010
8011fn active_constraint(
8012 instance: &CalculationInstanceInner,
8013 index: usize,
8014) -> Option<(&'static str, &powerio_prob::ConstraintSelection)> {
8015 match instance.instance()? {
8016 CalculationInstanceRef::DcOpf(instance) => {
8017 balanced_active_constraint(instance.constraints(), index)
8018 }
8019 CalculationInstanceRef::AcOpf(instance) => {
8020 balanced_active_constraint(instance.constraints(), index)
8021 }
8022 CalculationInstanceRef::AcOts(instance) => {
8023 balanced_active_constraint(instance.constraints(), index)
8024 }
8025 CalculationInstanceRef::McAcOpf(instance) => match index {
8026 0 => Some((
8027 "terminal_voltage_bounds",
8028 &instance.constraints().terminal_voltage_bounds,
8029 )),
8030 1 => Some(("conductor_limits", &instance.constraints().conductor_limits)),
8031 2 => Some((
8032 "generator_capability",
8033 &instance.constraints().generator_capability,
8034 )),
8035 _ => None,
8036 },
8037 CalculationInstanceRef::LinDist3FlowOpf(instance) => match index {
8038 0 => Some((
8039 "terminal_voltage_bounds",
8040 &instance
8041 .base_instance()
8042 .constraints()
8043 .terminal_voltage_bounds,
8044 )),
8045 1 => Some((
8046 "conductor_limits",
8047 &instance.base_instance().constraints().conductor_limits,
8048 )),
8049 2 => Some((
8050 "generator_capability",
8051 &instance.base_instance().constraints().generator_capability,
8052 )),
8053 _ => None,
8054 },
8055 _ => None,
8056 }
8057}
8058
8059fn balanced_active_constraint(
8061 constraints: &powerio_prob::ActiveConstraints,
8062 index: usize,
8063) -> Option<(&'static str, &powerio_prob::ConstraintSelection)> {
8064 match index {
8065 0 => Some(("generator_capability", &constraints.generator_capability)),
8066 1 => Some(("voltage_bounds", &constraints.voltage_bounds)),
8067 2 => Some(("thermal_limits", &constraints.thermal_limits)),
8068 3 => Some(("angle_bounds", &constraints.angle_bounds)),
8069 _ => None,
8070 }
8071}
8072
8073fn constraint_selection_parts(
8074 selection: &powerio_prob::ConstraintSelection,
8075) -> (&'static str, &[String]) {
8076 match selection {
8077 powerio_prob::ConstraintSelection::All => ("all", &[]),
8078 powerio_prob::ConstraintSelection::None => ("none", &[]),
8079 powerio_prob::ConstraintSelection::Only(identities) => ("only", identities),
8080 _ => ("unknown", &[]),
8081 }
8082}
8083
8084#[unsafe(no_mangle)]
8088pub unsafe extern "C" fn pio_calculation_instance_active_constraint_count(
8089 instance: *const PioCalculationInstance,
8090) -> usize {
8091 match unsafe { PioCalculationInstance::get(instance) }
8092 .and_then(CalculationInstanceInner::instance)
8093 {
8094 Some(
8095 CalculationInstanceRef::DcOpf(_)
8096 | CalculationInstanceRef::AcOpf(_)
8097 | CalculationInstanceRef::AcOts(_),
8098 ) => 4,
8099 Some(CalculationInstanceRef::McAcOpf(_)) => 3,
8100 Some(CalculationInstanceRef::LinDist3FlowOpf(_)) => 3,
8101 _ => 0,
8102 }
8103}
8104
8105#[unsafe(no_mangle)]
8110pub unsafe extern "C" fn pio_calculation_instance_active_constraint_at(
8111 instance: *const PioCalculationInstance,
8112 index: usize,
8113 output: *mut PioActiveConstraintView,
8114 error: *mut *mut PioError,
8115) -> bool {
8116 unsafe {
8117 entry(error, false, || {
8118 let instance = require_calculation_instance(instance)?;
8119 let (family, selection) = active_constraint(instance, index).ok_or_else(|| {
8120 boundary_error(
8121 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
8122 format!("active constraint index {index} is out of range"),
8123 )
8124 })?;
8125 let (selection, identities) = constraint_selection_parts(selection);
8126 *require_output(output, "output")? = PioActiveConstraintView {
8127 family: PioStringView::new(family),
8128 selection: PioStringView::new(selection),
8129 identity_count: identities.len(),
8130 };
8131 Ok(true)
8132 })
8133 }
8134}
8135
8136#[unsafe(no_mangle)]
8141pub unsafe extern "C" fn pio_calculation_instance_active_constraint_identity_at(
8142 instance: *const PioCalculationInstance,
8143 constraint_index: usize,
8144 identity_index: usize,
8145 error: *mut *mut PioError,
8146) -> PioStringView {
8147 unsafe {
8148 entry(error, PioStringView::EMPTY, || {
8149 let instance = require_calculation_instance(instance)?;
8150 let (_, selection) =
8151 active_constraint(instance, constraint_index).ok_or_else(|| {
8152 boundary_error(
8153 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
8154 format!("active constraint index {constraint_index} is out of range"),
8155 )
8156 })?;
8157 let (_, identities) = constraint_selection_parts(selection);
8158 let identity = identities.get(identity_index).ok_or_else(|| {
8159 boundary_error(
8160 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
8161 format!("constraint identity index {identity_index} is out of range"),
8162 )
8163 })?;
8164 Ok(PioStringView::new(identity))
8165 })
8166 }
8167}
8168
8169#[unsafe(no_mangle)]
8173pub unsafe extern "C" fn pio_calculation_instance_has_initial_point(
8174 instance: *const PioCalculationInstance,
8175) -> bool {
8176 unsafe { PioCalculationInstance::get(instance) }
8177 .is_some_and(CalculationInstanceInner::has_initial_point)
8178}
8179
8180#[unsafe(no_mangle)]
8186pub unsafe extern "C" fn pio_calculation_instance_initial_point(
8187 instance: *const PioCalculationInstance,
8188 error: *mut *mut PioError,
8189) -> *mut PioOperatingPoint {
8190 unsafe {
8191 entry(error, std::ptr::null_mut(), || {
8192 let instance = PioCalculationInstance::get(instance).ok_or_else(|| {
8193 boundary_error(
8194 &codes::BIND_CAPI_NULL_HANDLE,
8195 "PioCalculationInstance must not be NULL",
8196 )
8197 })?;
8198 let has_initial_point = instance.has_initial_point();
8199 let projection = if has_initial_point {
8200 Some(match (instance.projection, instance.instance()) {
8201 (
8202 CalculationInstanceProjection::Direct,
8203 Some(CalculationInstanceRef::DcPf(_)),
8204 ) => OperatingPointProjection::DcPfInitial,
8205 (
8206 CalculationInstanceProjection::Direct,
8207 Some(CalculationInstanceRef::AcPf(_)),
8208 ) => OperatingPointProjection::AcPfInitial,
8209 (
8210 CalculationInstanceProjection::Direct,
8211 Some(CalculationInstanceRef::DcOpf(_)),
8212 ) => OperatingPointProjection::DcOpfInitial,
8213 (
8214 CalculationInstanceProjection::Direct,
8215 Some(CalculationInstanceRef::AcOpf(_)),
8216 ) => OperatingPointProjection::AcOpfInitial,
8217 (
8218 CalculationInstanceProjection::Direct,
8219 Some(CalculationInstanceRef::AcOts(_)),
8220 ) => OperatingPointProjection::AcOtsInitial,
8221 (
8222 CalculationInstanceProjection::Direct,
8223 Some(CalculationInstanceRef::McAcPf(_)),
8224 ) => OperatingPointProjection::McAcPfInitial,
8225 (
8226 CalculationInstanceProjection::Direct,
8227 Some(CalculationInstanceRef::McAcOpf(_)),
8228 ) => OperatingPointProjection::McAcOpfInitial,
8229 (
8230 CalculationInstanceProjection::Direct,
8231 Some(CalculationInstanceRef::LinDist3FlowOpf(_)),
8232 ) => OperatingPointProjection::LinDist3FlowOpfInitial,
8233 (CalculationInstanceProjection::DcPfSolution, _) => {
8234 OperatingPointProjection::DcPfSolutionInitial
8235 }
8236 (CalculationInstanceProjection::AcPfSolution, _) => {
8237 OperatingPointProjection::AcPfSolutionInitial
8238 }
8239 (CalculationInstanceProjection::DcOpfSolution, _) => {
8240 OperatingPointProjection::DcOpfSolutionInitial
8241 }
8242 (CalculationInstanceProjection::AcOpfSolution, _) => {
8243 OperatingPointProjection::AcOpfSolutionInitial
8244 }
8245 (CalculationInstanceProjection::AcOtsSolution, _) => {
8246 OperatingPointProjection::AcOtsSolutionInitial
8247 }
8248 (CalculationInstanceProjection::SocwrOpfSolution, _) => {
8249 OperatingPointProjection::SocwrOpfSolutionInitial
8250 }
8251 (CalculationInstanceProjection::McAcPfSolution, _) => {
8252 OperatingPointProjection::McAcPfSolutionInitial
8253 }
8254 (CalculationInstanceProjection::McAcOpfSolution, _) => {
8255 OperatingPointProjection::McAcOpfSolutionInitial
8256 }
8257 (CalculationInstanceProjection::LinDist3FlowOpfSolution, _) => {
8258 OperatingPointProjection::LinDist3FlowOpfSolutionInitial
8259 }
8260 _ => {
8261 return Err(boundary_error(
8262 &codes::REQUEST_CAPI_TYPE_MISMATCH,
8263 "the handle does not refer to a calculation instance with an operating point",
8264 ));
8265 }
8266 })
8267 } else {
8268 None
8269 };
8270 Ok(projection.map_or(std::ptr::null_mut(), |projection| {
8271 PioOperatingPoint::new_raw(OperatingPointInner {
8272 value: ValueInner {
8273 owner: Arc::clone(&instance.value.owner),
8274 steps: instance.value.steps.clone(),
8275 },
8276 projection,
8277 })
8278 }))
8279 })
8280 }
8281}
8282
8283fn require_legacy_load_voltage_model(
8284 model: &powerio_dist::DistLoadVoltageModel,
8285) -> Result<(), *mut PioError> {
8286 if matches!(
8287 model,
8288 powerio_dist::DistLoadVoltageModel::BoundedZip { .. }
8289 | powerio_dist::DistLoadVoltageModel::BoundedExponential { .. }
8290 | powerio_dist::DistLoadVoltageModel::BoundedConstantPower { .. }
8291 ) {
8292 return Err(boundary_error(
8293 &codes::REQUEST_CAPI_TYPE_MISMATCH,
8294 "legacy load view cannot describe voltage-band transitions, current limits or dropout",
8295 ));
8296 }
8297 Ok(())
8298}
8299
8300fn dist_load_voltage_model_name(model: &powerio_dist::DistLoadVoltageModel) -> &'static str {
8301 match model {
8302 powerio_dist::DistLoadVoltageModel::ConstantPower { .. } => "constant_power",
8303 powerio_dist::DistLoadVoltageModel::ConstantCurrent { .. } => "constant_current",
8304 powerio_dist::DistLoadVoltageModel::ConstantImpedance { .. } => "constant_impedance",
8305 powerio_dist::DistLoadVoltageModel::Zip { .. } => "zip",
8306 powerio_dist::DistLoadVoltageModel::Exponential { .. } => "exponential",
8307 powerio_dist::DistLoadVoltageModel::BoundedZip { .. } => "bounded_zip",
8308 powerio_dist::DistLoadVoltageModel::BoundedExponential { .. } => "bounded_exponential",
8309 powerio_dist::DistLoadVoltageModel::BoundedConstantPower { .. } => "bounded_constant_power",
8310 _ => "unknown",
8311 }
8312}
8313
8314#[unsafe(no_mangle)]
8318pub unsafe extern "C" fn pio_mc_ac_pf_instance_load_count(
8319 instance: *const PioCalculationInstance,
8320) -> usize {
8321 unsafe { PioCalculationInstance::get(instance) }
8322 .and_then(CalculationInstanceInner::mc_ac_pf)
8323 .map_or(0, |instance| instance.loads().len())
8324}
8325
8326#[unsafe(no_mangle)]
8330pub unsafe extern "C" fn pio_mc_ac_pf_instance_load_at(
8331 instance: *const PioCalculationInstance,
8332 index: usize,
8333 output: *mut PioPrescribedTerminalPowerView,
8334 error: *mut *mut PioError,
8335) -> bool {
8336 unsafe {
8337 entry(error, false, || {
8338 let instance = require_calculation_instance(instance)?
8339 .mc_ac_pf()
8340 .ok_or_else(|| {
8341 boundary_error(
8342 &codes::REQUEST_CAPI_TYPE_MISMATCH,
8343 "the calculation instance is not powerio.McAcPfInstance",
8344 )
8345 })?;
8346 let load = instance.loads().get(index).ok_or_else(|| {
8347 boundary_error(
8348 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
8349 format!("prescribed load index {index} is out of range"),
8350 )
8351 })?;
8352 require_legacy_load_voltage_model(&load.voltage_model)?;
8353 *require_output(output, "output")? = PioPrescribedTerminalPowerView {
8354 load: PioStringView::new(&load.load),
8355 terminal_count: load.terminals.len(),
8356 voltage_model: PioStringView::new(dist_load_voltage_model_name(
8357 &load.voltage_model,
8358 )),
8359 };
8360 Ok(true)
8361 })
8362 }
8363}
8364
8365#[unsafe(no_mangle)]
8370pub unsafe extern "C" fn pio_mc_ac_pf_instance_load_details_at(
8371 instance: *const PioCalculationInstance,
8372 index: usize,
8373 output: *mut PioPrescribedLoadDetailsView,
8374 error: *mut *mut PioError,
8375) -> bool {
8376 unsafe {
8377 entry(error, false, || {
8378 let instance = require_calculation_instance(instance)?
8379 .mc_ac_pf()
8380 .ok_or_else(|| {
8381 boundary_error(
8382 &codes::REQUEST_CAPI_TYPE_MISMATCH,
8383 "the calculation instance is not powerio.McAcPfInstance",
8384 )
8385 })?;
8386 let load = instance.loads().get(index).ok_or_else(|| {
8387 boundary_error(
8388 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
8389 format!("prescribed load index {index} is out of range"),
8390 )
8391 })?;
8392 *require_output(output, "output")? = PioPrescribedLoadDetailsView {
8393 load: PioStringView::new(&load.load),
8394 terminal_count: load.terminals.len(),
8395 active_power_w: PioF64View::new(&load.p_w),
8396 reactive_power_var: PioF64View::new(&load.q_var),
8397 voltage_model: dist_load_voltage_model_view(&load.voltage_model),
8398 };
8399 Ok(true)
8400 })
8401 }
8402}
8403
8404#[unsafe(no_mangle)]
8409pub unsafe extern "C" fn pio_mc_ac_pf_instance_load_terminal_name_at(
8410 instance: *const PioCalculationInstance,
8411 load_index: usize,
8412 terminal_index: usize,
8413 output: *mut PioStringView,
8414 error: *mut *mut PioError,
8415) -> bool {
8416 unsafe {
8417 entry(error, false, || {
8418 let instance = require_calculation_instance(instance)?
8419 .mc_ac_pf()
8420 .ok_or_else(|| {
8421 boundary_error(
8422 &codes::REQUEST_CAPI_TYPE_MISMATCH,
8423 "the calculation instance is not powerio.McAcPfInstance",
8424 )
8425 })?;
8426 let load = instance.loads().get(load_index).ok_or_else(|| {
8427 boundary_error(
8428 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
8429 format!("prescribed load index {load_index} is out of range"),
8430 )
8431 })?;
8432 *require_output(output, "output")? =
8433 string_slice_at(&load.terminals, terminal_index, "prescribed load terminal")?;
8434 Ok(true)
8435 })
8436 }
8437}
8438
8439fn model_value(values: &[f64], index: usize) -> (f64, bool) {
8440 values
8441 .get(index)
8442 .copied()
8443 .map_or((0.0, false), |value| (value, true))
8444}
8445
8446#[unsafe(no_mangle)]
8450pub unsafe extern "C" fn pio_mc_ac_pf_instance_load_terminal_at(
8451 instance: *const PioCalculationInstance,
8452 load_index: usize,
8453 terminal_index: usize,
8454 output: *mut PioTerminalPowerView,
8455 error: *mut *mut PioError,
8456) -> bool {
8457 unsafe {
8458 entry(error, false, || {
8459 let instance = require_calculation_instance(instance)?
8460 .mc_ac_pf()
8461 .ok_or_else(|| {
8462 boundary_error(
8463 &codes::REQUEST_CAPI_TYPE_MISMATCH,
8464 "the calculation instance is not powerio.McAcPfInstance",
8465 )
8466 })?;
8467 let load = instance.loads().get(load_index).ok_or_else(|| {
8468 boundary_error(
8469 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
8470 format!("prescribed load index {load_index} is out of range"),
8471 )
8472 })?;
8473 require_legacy_load_voltage_model(&load.voltage_model)?;
8474 let terminal = load.terminals.get(terminal_index).ok_or_else(|| {
8475 boundary_error(
8476 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
8477 format!("load terminal index {terminal_index} is out of range"),
8478 )
8479 })?;
8480 let p = *load.p_w.get(terminal_index).ok_or_else(|| {
8481 boundary_error(
8482 &codes::REQUEST_CAPI_TYPE_MISMATCH,
8483 "the prescribed load active power does not align with its terminals",
8484 )
8485 })?;
8486 let q = *load.q_var.get(terminal_index).ok_or_else(|| {
8487 boundary_error(
8488 &codes::REQUEST_CAPI_TYPE_MISMATCH,
8489 "the prescribed load reactive power does not align with its terminals",
8490 )
8491 })?;
8492 let mut model_values = (0.0, false, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0);
8493 match &load.voltage_model {
8494 powerio_dist::DistLoadVoltageModel::ConstantPower { v_nom } => {
8495 let (v, has_v) = model_value(v_nom, terminal_index);
8496 model_values.0 = v;
8497 model_values.1 = has_v;
8498 }
8499 powerio_dist::DistLoadVoltageModel::ConstantCurrent { v_nom } => {
8500 let (v, has_v) = model_value(v_nom, terminal_index);
8501 model_values = (v, has_v, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0);
8502 }
8503 powerio_dist::DistLoadVoltageModel::ConstantImpedance { v_nom } => {
8504 let (v, has_v) = model_value(v_nom, terminal_index);
8505 model_values = (v, has_v, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0);
8506 }
8507 powerio_dist::DistLoadVoltageModel::Zip {
8508 v_nom,
8509 alpha_z,
8510 alpha_i,
8511 alpha_p,
8512 beta_z,
8513 beta_i,
8514 beta_p,
8515 } => {
8516 let (v, has_v) = model_value(v_nom, terminal_index);
8517 model_values = (
8518 v,
8519 has_v,
8520 alpha_z.get(terminal_index).copied().unwrap_or(0.0),
8521 alpha_i.get(terminal_index).copied().unwrap_or(0.0),
8522 alpha_p.get(terminal_index).copied().unwrap_or(0.0),
8523 beta_z.get(terminal_index).copied().unwrap_or(0.0),
8524 beta_i.get(terminal_index).copied().unwrap_or(0.0),
8525 beta_p.get(terminal_index).copied().unwrap_or(0.0),
8526 0.0,
8527 0.0,
8528 );
8529 }
8530 powerio_dist::DistLoadVoltageModel::Exponential {
8531 v_nom,
8532 gamma_p,
8533 gamma_q,
8534 } => {
8535 let (v, has_v) = model_value(v_nom, terminal_index);
8536 model_values = (
8537 v,
8538 has_v,
8539 0.0,
8540 0.0,
8541 0.0,
8542 0.0,
8543 0.0,
8544 0.0,
8545 gamma_p.get(terminal_index).copied().unwrap_or(0.0),
8546 gamma_q.get(terminal_index).copied().unwrap_or(0.0),
8547 );
8548 }
8549 _ => {}
8550 }
8551 *require_output(output, "output")? = PioTerminalPowerView {
8552 terminal: PioStringView::new(terminal),
8553 active_power_w: p,
8554 reactive_power_var: q,
8555 nominal_voltage_v: model_values.0,
8556 has_nominal_voltage: model_values.1,
8557 active_impedance_fraction: model_values.2,
8558 active_current_fraction: model_values.3,
8559 active_power_fraction: model_values.4,
8560 reactive_impedance_fraction: model_values.5,
8561 reactive_current_fraction: model_values.6,
8562 reactive_power_fraction: model_values.7,
8563 active_power_exponent: model_values.8,
8564 reactive_power_exponent: model_values.9,
8565 };
8566 Ok(true)
8567 })
8568 }
8569}
8570
8571#[unsafe(no_mangle)]
8575pub unsafe extern "C" fn pio_mc_ac_pf_instance_source_count(
8576 instance: *const PioCalculationInstance,
8577) -> usize {
8578 unsafe { PioCalculationInstance::get(instance) }
8579 .and_then(CalculationInstanceInner::mc_ac_pf)
8580 .map_or(0, |instance| instance.sources().len())
8581}
8582
8583#[unsafe(no_mangle)]
8589pub unsafe extern "C" fn pio_mc_ac_pf_instance_source_at(
8590 instance: *const PioCalculationInstance,
8591 index: usize,
8592 output: *mut PioPrescribedSourceVoltageView,
8593 error: *mut *mut PioError,
8594) -> bool {
8595 unsafe {
8596 entry(error, false, || {
8597 let instance = require_calculation_instance(instance)?
8598 .mc_ac_pf()
8599 .ok_or_else(|| {
8600 boundary_error(
8601 &codes::REQUEST_CAPI_TYPE_MISMATCH,
8602 "the calculation instance is not powerio.McAcPfInstance",
8603 )
8604 })?;
8605 let source = instance.sources().get(index).ok_or_else(|| {
8606 boundary_error(
8607 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
8608 format!("prescribed source index {index} is out of range"),
8609 )
8610 })?;
8611 if instance
8612 .source_boundary(index)
8613 .and_then(|source| source.reference_terminal)
8614 .is_some()
8615 {
8616 return Err(boundary_error(
8617 &codes::REQUEST_CAPI_TYPE_MISMATCH,
8618 "legacy prescribed source view cannot describe a reference-terminal source",
8619 ));
8620 }
8621 *require_output(output, "output")? = PioPrescribedSourceVoltageView {
8622 source: PioStringView::new(&source.source),
8623 terminal_count: source.terminals.len(),
8624 };
8625 Ok(true)
8626 })
8627 }
8628}
8629
8630#[unsafe(no_mangle)]
8636pub unsafe extern "C" fn pio_mc_ac_pf_instance_source_terminal_at(
8637 instance: *const PioCalculationInstance,
8638 source_index: usize,
8639 terminal_index: usize,
8640 output: *mut PioTerminalVoltageView,
8641 error: *mut *mut PioError,
8642) -> bool {
8643 unsafe {
8644 entry(error, false, || {
8645 let instance = require_calculation_instance(instance)?
8646 .mc_ac_pf()
8647 .ok_or_else(|| {
8648 boundary_error(
8649 &codes::REQUEST_CAPI_TYPE_MISMATCH,
8650 "the calculation instance is not powerio.McAcPfInstance",
8651 )
8652 })?;
8653 let source = instance.sources().get(source_index).ok_or_else(|| {
8654 boundary_error(
8655 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
8656 format!("prescribed source index {source_index} is out of range"),
8657 )
8658 })?;
8659 if instance
8660 .source_boundary(source_index)
8661 .and_then(|source| source.reference_terminal)
8662 .is_some()
8663 {
8664 return Err(boundary_error(
8665 &codes::REQUEST_CAPI_TYPE_MISMATCH,
8666 "legacy prescribed voltage view cannot describe a reference-terminal source",
8667 ));
8668 }
8669 let terminal = source.terminals.get(terminal_index).ok_or_else(|| {
8670 boundary_error(
8671 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
8672 format!("source terminal index {terminal_index} is out of range"),
8673 )
8674 })?;
8675 let magnitude = source.v_magnitude.get(terminal_index).ok_or_else(|| {
8676 boundary_error(
8677 &codes::REQUEST_CAPI_TYPE_MISMATCH,
8678 "the prescribed source magnitudes do not align with its terminals",
8679 )
8680 })?;
8681 let angle = source.v_angle.get(terminal_index).ok_or_else(|| {
8682 boundary_error(
8683 &codes::REQUEST_CAPI_TYPE_MISMATCH,
8684 "the prescribed source angles do not align with its terminals",
8685 )
8686 })?;
8687 *require_output(output, "output")? = PioTerminalVoltageView {
8688 terminal: PioStringView::new(terminal),
8689 magnitude_v: *magnitude,
8690 angle_radians: *angle,
8691 };
8692 Ok(true)
8693 })
8694 }
8695}
8696
8697#[unsafe(no_mangle)]
8701pub unsafe extern "C" fn pio_mc_ac_pf_instance_isolated_terminal_count(
8702 instance: *const PioCalculationInstance,
8703) -> usize {
8704 unsafe { PioCalculationInstance::get(instance) }
8705 .and_then(CalculationInstanceInner::mc_ac_pf)
8706 .map_or(0, |instance| instance.isolated_terminals().len())
8707}
8708
8709#[unsafe(no_mangle)]
8713pub unsafe extern "C" fn pio_mc_ac_pf_instance_isolated_terminal_at(
8714 instance: *const PioCalculationInstance,
8715 index: usize,
8716 output: *mut PioIsolatedTerminalView,
8717 error: *mut *mut PioError,
8718) -> bool {
8719 unsafe {
8720 entry(error, false, || {
8721 let instance = require_calculation_instance(instance)?
8722 .mc_ac_pf()
8723 .ok_or_else(|| {
8724 boundary_error(
8725 &codes::REQUEST_CAPI_TYPE_MISMATCH,
8726 "the calculation instance is not powerio.McAcPfInstance",
8727 )
8728 })?;
8729 let (bus, terminal) = instance.isolated_terminals().get(index).ok_or_else(|| {
8730 boundary_error(
8731 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
8732 format!("isolated terminal index {index} is out of range"),
8733 )
8734 })?;
8735 *require_output(output, "output")? = PioIsolatedTerminalView {
8736 bus: PioStringView::new(bus),
8737 terminal: PioStringView::new(terminal),
8738 };
8739 Ok(true)
8740 })
8741 }
8742}
8743
8744#[unsafe(no_mangle)]
8748pub unsafe extern "C" fn pio_mc_ac_pf_instance_active_control_count(
8749 instance: *const PioCalculationInstance,
8750) -> usize {
8751 unsafe { PioCalculationInstance::get(instance) }
8752 .and_then(CalculationInstanceInner::mc_ac_pf)
8753 .map_or(0, |instance| instance.control_modes().len())
8754}
8755
8756#[unsafe(no_mangle)]
8760pub unsafe extern "C" fn pio_mc_ac_pf_instance_active_control_at(
8761 instance: *const PioCalculationInstance,
8762 index: usize,
8763 output: *mut PioActiveControlView,
8764 error: *mut *mut PioError,
8765) -> bool {
8766 unsafe {
8767 entry(error, false, || {
8768 let instance = require_calculation_instance(instance)?
8769 .mc_ac_pf()
8770 .ok_or_else(|| {
8771 boundary_error(
8772 &codes::REQUEST_CAPI_TYPE_MISMATCH,
8773 "the calculation instance is not powerio.McAcPfInstance",
8774 )
8775 })?;
8776 let control = instance.control_modes().get(index).ok_or_else(|| {
8777 boundary_error(
8778 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
8779 format!("active control index {index} is out of range"),
8780 )
8781 })?;
8782 let (kind, component_id) = match control {
8783 powerio_prob::ActiveControlMode::RegulatorTap { transformer } => {
8784 ("regulator_tap", transformer.as_str())
8785 }
8786 powerio_prob::ActiveControlMode::CapacitorSteps { capacitor } => {
8787 ("capacitor_steps", capacitor.as_str())
8788 }
8789 _ => ("unknown", ""),
8790 };
8791 *require_output(output, "output")? = PioActiveControlView {
8792 kind: PioStringView::new(kind),
8793 component_id: PioStringView::new(component_id),
8794 };
8795 Ok(true)
8796 })
8797 }
8798}
8799
8800fn scuc_inputs(instance: &CalculationInstanceInner) -> Option<&powerio_prob::ScucInputs> {
8801 instance.ac_scuc().map(powerio_prob::AcScucInstance::inputs)
8802}
8803
8804fn scuc_inputs_or_error(
8805 instance: &CalculationInstanceInner,
8806) -> Result<&powerio_prob::ScucInputs, *mut PioError> {
8807 scuc_inputs(instance).ok_or_else(|| {
8808 boundary_error(
8809 &codes::REQUEST_CAPI_TYPE_MISMATCH,
8810 "the calculation instance is not powerio.AcScucInstance",
8811 )
8812 })
8813}
8814
8815fn component_id_view(id: &ComponentId) -> PioComponentIdView {
8816 PioComponentIdView {
8817 component_type: PioStringView::new(id.component_type()),
8818 local_id: PioStringView::new(id.local_id()),
8819 }
8820}
8821
8822fn empty_component_id_view() -> PioComponentIdView {
8823 PioComponentIdView {
8824 component_type: PioStringView::EMPTY,
8825 local_id: PioStringView::EMPTY,
8826 }
8827}
8828
8829fn optional_component_id_view(value: Option<&ComponentId>) -> (PioComponentIdView, bool) {
8830 value.map_or((empty_component_id_view(), false), |value| {
8831 (component_id_view(value), true)
8832 })
8833}
8834
8835fn terminal_reference_view(
8836 value: Option<&powerio_tx::TerminalReference>,
8837) -> (PioTerminalReferenceView, bool) {
8838 value.map_or(
8839 (
8840 PioTerminalReferenceView {
8841 equipment: empty_component_id_view(),
8842 terminal: 0,
8843 },
8844 false,
8845 ),
8846 |value| {
8847 (
8848 PioTerminalReferenceView {
8849 equipment: component_id_view(&value.equipment),
8850 terminal: value.terminal,
8851 },
8852 true,
8853 )
8854 },
8855 )
8856}
8857
8858fn transformer_control_mode_name(mode: powerio_tx::TransformerControlMode) -> &'static str {
8859 match mode {
8860 powerio_tx::TransformerControlMode::Fixed => "fixed",
8861 powerio_tx::TransformerControlMode::Voltage => "voltage",
8862 powerio_tx::TransformerControlMode::ReactiveFlow => "reactive_flow",
8863 powerio_tx::TransformerControlMode::ActiveFlow => "active_flow",
8864 powerio_tx::TransformerControlMode::DcLineQuantity => "dc_line_quantity",
8865 powerio_tx::TransformerControlMode::AsymmetricActiveFlow => "asymmetric_active_flow",
8866 _ => "unknown",
8867 }
8868}
8869
8870fn transformer_control_view(
8871 value: Option<&powerio_tx::TransformerControl>,
8872) -> (PioTransformerControlView, bool) {
8873 let empty_terminal = terminal_reference_view(None).0;
8874 value.map_or(
8875 (
8876 PioTransformerControlView {
8877 mode: PioStringView::EMPTY,
8878 enabled: false,
8879 controlled_bus_id: 0,
8880 has_controlled_bus: false,
8881 controlled_bus_on_winding_side: false,
8882 regulating_terminal: empty_terminal,
8883 has_regulating_terminal: false,
8884 tap_min: 0.0,
8885 tap_max: 0.0,
8886 band_min: 0.0,
8887 band_max: 0.0,
8888 tap_position_count: 0,
8889 mva_base: 0.0,
8890 winding_connection_angle: 0.0,
8891 has_winding_connection_angle: false,
8892 },
8893 false,
8894 ),
8895 |control| {
8896 let (regulating_terminal, has_regulating_terminal) =
8897 terminal_reference_view(control.regulating_terminal.as_ref());
8898 (
8899 PioTransformerControlView {
8900 mode: PioStringView::new(transformer_control_mode_name(control.mode)),
8901 enabled: control.enabled,
8902 controlled_bus_id: control.controlled_bus.map_or(0, |bus| bus.0),
8903 has_controlled_bus: control.controlled_bus.is_some(),
8904 controlled_bus_on_winding_side: control.controlled_bus_on_winding_side,
8905 regulating_terminal,
8906 has_regulating_terminal,
8907 tap_min: control.tap_min,
8908 tap_max: control.tap_max,
8909 band_min: control.band_min,
8910 band_max: control.band_max,
8911 tap_position_count: control.ntp,
8912 mva_base: control.mva_base,
8913 winding_connection_angle: control.winding_connection_angle.unwrap_or(0.0),
8914 has_winding_connection_angle: control.winding_connection_angle.is_some(),
8915 },
8916 true,
8917 )
8918 },
8919 )
8920}
8921
8922fn scuc_device_kind_name(kind: powerio_prob::ScucDeviceKind) -> &'static str {
8923 match kind {
8924 powerio_prob::ScucDeviceKind::Producer => "producer",
8925 powerio_prob::ScucDeviceKind::Consumer => "consumer",
8926 _ => "unknown",
8927 }
8928}
8929
8930fn scuc_reactive_capability_view(
8931 capability: &powerio_prob::ScucReactiveCapability,
8932) -> PioScucReactiveCapabilityView {
8933 match capability {
8934 powerio_prob::ScucReactiveCapability::None => PioScucReactiveCapabilityView {
8935 kind: PioStringView::new("none"),
8936 reactive_power_at_zero_active_power_pu: 0.0,
8937 reactive_power_at_zero_active_power_min_pu: 0.0,
8938 reactive_power_at_zero_active_power_max_pu: 0.0,
8939 slope: 0.0,
8940 slope_min: 0.0,
8941 slope_max: 0.0,
8942 },
8943 powerio_prob::ScucReactiveCapability::Linear {
8944 reactive_power_at_zero_active_power,
8945 slope,
8946 } => PioScucReactiveCapabilityView {
8947 kind: PioStringView::new("linear"),
8948 reactive_power_at_zero_active_power_pu: *reactive_power_at_zero_active_power,
8949 reactive_power_at_zero_active_power_min_pu: 0.0,
8950 reactive_power_at_zero_active_power_max_pu: 0.0,
8951 slope: *slope,
8952 slope_min: 0.0,
8953 slope_max: 0.0,
8954 },
8955 powerio_prob::ScucReactiveCapability::Bounded {
8956 reactive_power_at_zero_active_power_min,
8957 reactive_power_at_zero_active_power_max,
8958 slope_min,
8959 slope_max,
8960 } => PioScucReactiveCapabilityView {
8961 kind: PioStringView::new("bounded"),
8962 reactive_power_at_zero_active_power_pu: 0.0,
8963 reactive_power_at_zero_active_power_min_pu: *reactive_power_at_zero_active_power_min,
8964 reactive_power_at_zero_active_power_max_pu: *reactive_power_at_zero_active_power_max,
8965 slope: 0.0,
8966 slope_min: *slope_min,
8967 slope_max: *slope_max,
8968 },
8969 _ => PioScucReactiveCapabilityView {
8970 kind: PioStringView::new("unknown"),
8971 reactive_power_at_zero_active_power_pu: 0.0,
8972 reactive_power_at_zero_active_power_min_pu: 0.0,
8973 reactive_power_at_zero_active_power_max_pu: 0.0,
8974 slope: 0.0,
8975 slope_min: 0.0,
8976 slope_max: 0.0,
8977 },
8978 }
8979}
8980
8981fn scuc_reserve_costs_view(costs: &powerio_prob::ScucReserveCosts) -> PioScucReserveCostsView {
8982 PioScucReserveCostsView {
8983 regulation_up: costs.regulation_up,
8984 regulation_down: costs.regulation_down,
8985 synchronized: costs.synchronized,
8986 nonsynchronized: costs.nonsynchronized,
8987 ramping_up_online: costs.ramping_up_online,
8988 ramping_down_online: costs.ramping_down_online,
8989 ramping_up_offline: costs.ramping_up_offline,
8990 ramping_down_offline: costs.ramping_down_offline,
8991 reactive_up: costs.reactive_up,
8992 reactive_down: costs.reactive_down,
8993 }
8994}
8995
8996fn scuc_device_view(device: &powerio_prob::ScucDevice) -> PioScucDeviceView {
8997 PioScucDeviceView {
8998 id: component_id_view(&device.id),
8999 kind: PioStringView::new(scuc_device_kind_name(device.kind)),
9000 initial_on_status: device.initial_on_status,
9001 on_cost: device.on_cost,
9002 startup_cost: device.startup_cost,
9003 shutdown_cost: device.shutdown_cost,
9004 minimum_up_time_hours: device.minimum_up_time,
9005 minimum_down_time_hours: device.minimum_down_time,
9006 ramp_limits: PioScucRampLimitsView {
9007 up_pu_per_hour: device.ramp_limits.up,
9008 down_pu_per_hour: device.ramp_limits.down,
9009 startup_pu_per_hour: device.ramp_limits.startup,
9010 shutdown_pu_per_hour: device.ramp_limits.shutdown,
9011 },
9012 reserve_limits: PioScucReserveLimitsView {
9013 regulation_up_pu: device.reserve_limits.regulation_up,
9014 regulation_down_pu: device.reserve_limits.regulation_down,
9015 synchronized_pu: device.reserve_limits.synchronized,
9016 nonsynchronized_pu: device.reserve_limits.nonsynchronized,
9017 ramping_up_online_pu: device.reserve_limits.ramping_up_online,
9018 ramping_down_online_pu: device.reserve_limits.ramping_down_online,
9019 ramping_up_offline_pu: device.reserve_limits.ramping_up_offline,
9020 ramping_down_offline_pu: device.reserve_limits.ramping_down_offline,
9021 },
9022 initial_commitment: PioScucInitialCommitmentView {
9023 accumulated_up_time_hours: device.initial_commitment.accumulated_up_time,
9024 accumulated_down_time_hours: device.initial_commitment.accumulated_down_time,
9025 },
9026 reactive_capability: scuc_reactive_capability_view(&device.reactive_capability),
9027 period_count: device.periods.len(),
9028 startup_cost_adjustment_count: device.startup_cost_adjustments.len(),
9029 startup_limit_count: device.startup_limits.len(),
9030 energy_upper_bound_count: device.energy_upper_bounds.len(),
9031 energy_lower_bound_count: device.energy_lower_bounds.len(),
9032 }
9033}
9034
9035fn scuc_device_or_error(
9036 inputs: &powerio_prob::ScucInputs,
9037 device_index: usize,
9038) -> Result<&powerio_prob::ScucDevice, *mut PioError> {
9039 inputs.devices.get(device_index).ok_or_else(|| {
9040 boundary_error(
9041 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
9042 format!("SCUC device index {device_index} is out of range"),
9043 )
9044 })
9045}
9046
9047#[unsafe(no_mangle)]
9052pub unsafe extern "C" fn pio_ac_scuc_instance_dimensions(
9053 instance: *const PioCalculationInstance,
9054 output: *mut PioScucDimensionsView,
9055 error: *mut *mut PioError,
9056) -> bool {
9057 unsafe {
9058 entry(error, false, || {
9059 let inputs = scuc_inputs_or_error(require_calculation_instance(instance)?)?;
9060 *require_output(output, "output")? = PioScucDimensionsView {
9061 period_count: inputs.interval_durations.len(),
9062 device_count: inputs.devices.len(),
9063 producer_count: inputs.producers().count(),
9064 consumer_count: inputs.consumers().count(),
9065 shunt_count: inputs.shunts.len(),
9066 branch_switching_cost_count: inputs.branch_switching_costs.len(),
9067 transformer_control_count: inputs.transformer_controls.len(),
9068 active_reserve_zone_count: inputs.active_reserve_zones.len(),
9069 reactive_reserve_zone_count: inputs.reactive_reserve_zones.len(),
9070 contingency_count: inputs.contingencies.len(),
9071 };
9072 Ok(true)
9073 })
9074 }
9075}
9076
9077#[unsafe(no_mangle)]
9082pub unsafe extern "C" fn pio_ac_scuc_instance_interval_durations(
9083 instance: *const PioCalculationInstance,
9084) -> PioF64View {
9085 unsafe { PioCalculationInstance::get(instance) }
9086 .and_then(scuc_inputs)
9087 .map_or(PioF64View::EMPTY, |inputs| {
9088 PioF64View::new(&inputs.interval_durations)
9089 })
9090}
9091
9092#[unsafe(no_mangle)]
9097pub unsafe extern "C" fn pio_ac_scuc_instance_violation_costs(
9098 instance: *const PioCalculationInstance,
9099 output: *mut PioScucViolationCostView,
9100 error: *mut *mut PioError,
9101) -> bool {
9102 unsafe {
9103 entry(error, false, || {
9104 let inputs = scuc_inputs_or_error(require_calculation_instance(instance)?)?;
9105 let costs = inputs.violation_costs;
9106 *require_output(output, "output")? = PioScucViolationCostView {
9107 active_power_balance: costs.active_power_balance,
9108 reactive_power_balance: costs.reactive_power_balance,
9109 branch_thermal_limit: costs.branch_thermal_limit,
9110 energy_requirement: costs.energy_requirement,
9111 };
9112 Ok(true)
9113 })
9114 }
9115}
9116
9117#[unsafe(no_mangle)]
9121pub unsafe extern "C" fn pio_ac_scuc_instance_device_count(
9122 instance: *const PioCalculationInstance,
9123) -> usize {
9124 unsafe { PioCalculationInstance::get(instance) }
9125 .and_then(scuc_inputs)
9126 .map_or(0, |inputs| inputs.devices.len())
9127}
9128
9129#[unsafe(no_mangle)]
9133pub unsafe extern "C" fn pio_ac_scuc_instance_device_at(
9134 instance: *const PioCalculationInstance,
9135 index: usize,
9136 output: *mut PioScucDeviceView,
9137 error: *mut *mut PioError,
9138) -> bool {
9139 unsafe {
9140 entry(error, false, || {
9141 let inputs = scuc_inputs_or_error(require_calculation_instance(instance)?)?;
9142 let device = scuc_device_or_error(inputs, index)?;
9143 *require_output(output, "output")? = scuc_device_view(device);
9144 Ok(true)
9145 })
9146 }
9147}
9148
9149#[unsafe(no_mangle)]
9154pub unsafe extern "C" fn pio_ac_scuc_instance_device_get(
9155 instance: *const PioCalculationInstance,
9156 uid: *const c_char,
9157 uid_len: usize,
9158 output: *mut PioScucDeviceView,
9159 error: *mut *mut PioError,
9160) -> bool {
9161 unsafe {
9162 entry(error, false, || {
9163 let uid = required_str(uid, uid_len, "device_uid")?;
9164 let inputs = scuc_inputs_or_error(require_calculation_instance(instance)?)?;
9165 let device = inputs.device(uid).ok_or_else(|| {
9166 boundary_error(
9167 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
9168 format!("SCUC device UID '{uid}' does not exist"),
9169 )
9170 })?;
9171 *require_output(output, "output")? = scuc_device_view(device);
9172 Ok(true)
9173 })
9174 }
9175}
9176
9177#[unsafe(no_mangle)]
9181pub unsafe extern "C" fn pio_ac_scuc_instance_device_startup_cost_adjustment_count(
9182 instance: *const PioCalculationInstance,
9183 device_index: usize,
9184) -> usize {
9185 unsafe { PioCalculationInstance::get(instance) }
9186 .and_then(scuc_inputs)
9187 .and_then(|inputs| inputs.devices.get(device_index))
9188 .map_or(0, |device| device.startup_cost_adjustments.len())
9189}
9190
9191#[unsafe(no_mangle)]
9195pub unsafe extern "C" fn pio_ac_scuc_instance_device_startup_cost_adjustment_at(
9196 instance: *const PioCalculationInstance,
9197 device_index: usize,
9198 adjustment_index: usize,
9199 output: *mut PioScucStartupCostAdjustmentView,
9200 error: *mut *mut PioError,
9201) -> bool {
9202 unsafe {
9203 entry(error, false, || {
9204 let inputs = scuc_inputs_or_error(require_calculation_instance(instance)?)?;
9205 let device = scuc_device_or_error(inputs, device_index)?;
9206 let adjustment = device
9207 .startup_cost_adjustments
9208 .get(adjustment_index)
9209 .ok_or_else(|| {
9210 boundary_error(
9211 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
9212 format!(
9213 "SCUC device {device_index} startup cost adjustment index {adjustment_index} is out of range"
9214 ),
9215 )
9216 })?;
9217 *require_output(output, "output")? = PioScucStartupCostAdjustmentView {
9218 cost: adjustment.cost,
9219 maximum_down_time_hours: adjustment.maximum_down_time,
9220 };
9221 Ok(true)
9222 })
9223 }
9224}
9225
9226#[unsafe(no_mangle)]
9230pub unsafe extern "C" fn pio_ac_scuc_instance_device_startup_limit_count(
9231 instance: *const PioCalculationInstance,
9232 device_index: usize,
9233) -> usize {
9234 unsafe { PioCalculationInstance::get(instance) }
9235 .and_then(scuc_inputs)
9236 .and_then(|inputs| inputs.devices.get(device_index))
9237 .map_or(0, |device| device.startup_limits.len())
9238}
9239
9240#[unsafe(no_mangle)]
9244pub unsafe extern "C" fn pio_ac_scuc_instance_device_startup_limit_at(
9245 instance: *const PioCalculationInstance,
9246 device_index: usize,
9247 limit_index: usize,
9248 output: *mut PioScucStartupLimitView,
9249 error: *mut *mut PioError,
9250) -> bool {
9251 unsafe {
9252 entry(error, false, || {
9253 let inputs = scuc_inputs_or_error(require_calculation_instance(instance)?)?;
9254 let device = scuc_device_or_error(inputs, device_index)?;
9255 let limit = device.startup_limits.get(limit_index).ok_or_else(|| {
9256 boundary_error(
9257 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
9258 format!(
9259 "SCUC device {device_index} startup limit index {limit_index} is out of range"
9260 ),
9261 )
9262 })?;
9263 *require_output(output, "output")? = PioScucStartupLimitView {
9264 start_time_hours: limit.start_time,
9265 end_time_hours: limit.end_time,
9266 maximum_startups: limit.maximum_startups,
9267 };
9268 Ok(true)
9269 })
9270 }
9271}
9272
9273unsafe fn scuc_energy_requirement_count(
9274 instance: *const PioCalculationInstance,
9275 device_index: usize,
9276 upper: bool,
9277) -> usize {
9278 unsafe { PioCalculationInstance::get(instance) }
9279 .and_then(scuc_inputs)
9280 .and_then(|inputs| inputs.devices.get(device_index))
9281 .map_or(0, |device| {
9282 if upper {
9283 device.energy_upper_bounds.len()
9284 } else {
9285 device.energy_lower_bounds.len()
9286 }
9287 })
9288}
9289
9290unsafe fn scuc_energy_requirement_at(
9291 instance: *const PioCalculationInstance,
9292 device_index: usize,
9293 requirement_index: usize,
9294 upper: bool,
9295 output: *mut PioScucEnergyRequirementView,
9296 error: *mut *mut PioError,
9297) -> bool {
9298 unsafe {
9299 entry(error, false, || {
9300 let inputs = scuc_inputs_or_error(require_calculation_instance(instance)?)?;
9301 let device = scuc_device_or_error(inputs, device_index)?;
9302 let requirements = if upper {
9303 &device.energy_upper_bounds
9304 } else {
9305 &device.energy_lower_bounds
9306 };
9307 let requirement = requirements.get(requirement_index).ok_or_else(|| {
9308 boundary_error(
9309 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
9310 format!(
9311 "SCUC device {device_index} {} energy requirement index {requirement_index} is out of range",
9312 if upper { "upper" } else { "lower" }
9313 ),
9314 )
9315 })?;
9316 *require_output(output, "output")? = PioScucEnergyRequirementView {
9317 start_time_hours: requirement.start_time,
9318 end_time_hours: requirement.end_time,
9319 energy_pu: requirement.energy,
9320 };
9321 Ok(true)
9322 })
9323 }
9324}
9325
9326#[unsafe(no_mangle)]
9330pub unsafe extern "C" fn pio_ac_scuc_instance_device_energy_upper_bound_count(
9331 instance: *const PioCalculationInstance,
9332 device_index: usize,
9333) -> usize {
9334 unsafe { scuc_energy_requirement_count(instance, device_index, true) }
9335}
9336
9337#[unsafe(no_mangle)]
9341pub unsafe extern "C" fn pio_ac_scuc_instance_device_energy_upper_bound_at(
9342 instance: *const PioCalculationInstance,
9343 device_index: usize,
9344 requirement_index: usize,
9345 output: *mut PioScucEnergyRequirementView,
9346 error: *mut *mut PioError,
9347) -> bool {
9348 unsafe {
9349 scuc_energy_requirement_at(
9350 instance,
9351 device_index,
9352 requirement_index,
9353 true,
9354 output,
9355 error,
9356 )
9357 }
9358}
9359
9360#[unsafe(no_mangle)]
9364pub unsafe extern "C" fn pio_ac_scuc_instance_device_energy_lower_bound_count(
9365 instance: *const PioCalculationInstance,
9366 device_index: usize,
9367) -> usize {
9368 unsafe { scuc_energy_requirement_count(instance, device_index, false) }
9369}
9370
9371#[unsafe(no_mangle)]
9375pub unsafe extern "C" fn pio_ac_scuc_instance_device_energy_lower_bound_at(
9376 instance: *const PioCalculationInstance,
9377 device_index: usize,
9378 requirement_index: usize,
9379 output: *mut PioScucEnergyRequirementView,
9380 error: *mut *mut PioError,
9381) -> bool {
9382 unsafe {
9383 scuc_energy_requirement_at(
9384 instance,
9385 device_index,
9386 requirement_index,
9387 false,
9388 output,
9389 error,
9390 )
9391 }
9392}
9393
9394#[unsafe(no_mangle)]
9398pub unsafe extern "C" fn pio_ac_scuc_instance_device_period_at(
9399 instance: *const PioCalculationInstance,
9400 device_index: usize,
9401 period_index: usize,
9402 output: *mut PioScucDevicePeriodView,
9403 error: *mut *mut PioError,
9404) -> bool {
9405 unsafe {
9406 entry(error, false, || {
9407 let inputs = scuc_inputs_or_error(require_calculation_instance(instance)?)?;
9408 let device = scuc_device_or_error(inputs, device_index)?;
9409 let period = device.periods.get(period_index).ok_or_else(|| {
9410 boundary_error(
9411 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
9412 format!(
9413 "SCUC device {device_index} period index {period_index} is out of range"
9414 ),
9415 )
9416 })?;
9417 *require_output(output, "output")? = PioScucDevicePeriodView {
9418 on_status_min: period.on_status_min,
9419 on_status_max: period.on_status_max,
9420 active_power_min_pu: period.active_power_min,
9421 active_power_max_pu: period.active_power_max,
9422 reactive_power_min_pu: period.reactive_power_min,
9423 reactive_power_max_pu: period.reactive_power_max,
9424 energy_cost_block_count: period.energy_cost_blocks.len(),
9425 reserve_costs: scuc_reserve_costs_view(&period.reserve_costs),
9426 };
9427 Ok(true)
9428 })
9429 }
9430}
9431
9432#[unsafe(no_mangle)]
9436pub unsafe extern "C" fn pio_ac_scuc_instance_device_energy_cost_block_count(
9437 instance: *const PioCalculationInstance,
9438 device_index: usize,
9439 period_index: usize,
9440) -> usize {
9441 unsafe { PioCalculationInstance::get(instance) }
9442 .and_then(scuc_inputs)
9443 .and_then(|inputs| inputs.devices.get(device_index))
9444 .and_then(|device| device.periods.get(period_index))
9445 .map_or(0, |period| period.energy_cost_blocks.len())
9446}
9447
9448#[unsafe(no_mangle)]
9452pub unsafe extern "C" fn pio_ac_scuc_instance_device_energy_cost_block_at(
9453 instance: *const PioCalculationInstance,
9454 device_index: usize,
9455 period_index: usize,
9456 block_index: usize,
9457 output: *mut PioScucEnergyCostBlockView,
9458 error: *mut *mut PioError,
9459) -> bool {
9460 unsafe {
9461 entry(error, false, || {
9462 let inputs = scuc_inputs_or_error(require_calculation_instance(instance)?)?;
9463 let device = scuc_device_or_error(inputs, device_index)?;
9464 let period = device.periods.get(period_index).ok_or_else(|| {
9465 boundary_error(
9466 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
9467 format!(
9468 "SCUC device {device_index} period index {period_index} is out of range"
9469 ),
9470 )
9471 })?;
9472 let block = period.energy_cost_blocks.get(block_index).ok_or_else(|| {
9473 boundary_error(
9474 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
9475 format!(
9476 "SCUC device {device_index} period {period_index} energy cost block index {block_index} is out of range"
9477 ),
9478 )
9479 })?;
9480 *require_output(output, "output")? = PioScucEnergyCostBlockView {
9481 marginal_cost: block.marginal_cost,
9482 block_size_pu: block.block_size,
9483 };
9484 Ok(true)
9485 })
9486 }
9487}
9488
9489#[unsafe(no_mangle)]
9493pub unsafe extern "C" fn pio_ac_scuc_instance_shunt_count(
9494 instance: *const PioCalculationInstance,
9495) -> usize {
9496 unsafe { PioCalculationInstance::get(instance) }
9497 .and_then(scuc_inputs)
9498 .map_or(0, |inputs| inputs.shunts.len())
9499}
9500
9501fn scuc_shunt_view(shunt: &powerio_prob::ScucShunt) -> PioScucShuntView {
9502 PioScucShuntView {
9503 id: component_id_view(&shunt.id),
9504 conductance_per_step_pu: shunt.conductance_per_step,
9505 susceptance_per_step_pu: shunt.susceptance_per_step,
9506 step_min: shunt.step_min,
9507 step_max: shunt.step_max,
9508 initial_step: shunt.initial_step,
9509 }
9510}
9511
9512#[unsafe(no_mangle)]
9516pub unsafe extern "C" fn pio_ac_scuc_instance_shunt_at(
9517 instance: *const PioCalculationInstance,
9518 index: usize,
9519 output: *mut PioScucShuntView,
9520 error: *mut *mut PioError,
9521) -> bool {
9522 unsafe {
9523 entry(error, false, || {
9524 let inputs = scuc_inputs_or_error(require_calculation_instance(instance)?)?;
9525 let shunt = inputs.shunts.get(index).ok_or_else(|| {
9526 boundary_error(
9527 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
9528 format!("SCUC shunt index {index} is out of range"),
9529 )
9530 })?;
9531 *require_output(output, "output")? = scuc_shunt_view(shunt);
9532 Ok(true)
9533 })
9534 }
9535}
9536
9537#[unsafe(no_mangle)]
9542pub unsafe extern "C" fn pio_ac_scuc_instance_shunt_get(
9543 instance: *const PioCalculationInstance,
9544 uid: *const c_char,
9545 uid_len: usize,
9546 output: *mut PioScucShuntView,
9547 error: *mut *mut PioError,
9548) -> bool {
9549 unsafe {
9550 entry(error, false, || {
9551 let uid = required_str(uid, uid_len, "shunt_uid")?;
9552 let inputs = scuc_inputs_or_error(require_calculation_instance(instance)?)?;
9553 let shunt = inputs.shunt(uid).ok_or_else(|| {
9554 boundary_error(
9555 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
9556 format!("SCUC shunt UID '{uid}' does not exist"),
9557 )
9558 })?;
9559 *require_output(output, "output")? = scuc_shunt_view(shunt);
9560 Ok(true)
9561 })
9562 }
9563}
9564
9565#[unsafe(no_mangle)]
9569pub unsafe extern "C" fn pio_ac_scuc_instance_branch_switching_cost_count(
9570 instance: *const PioCalculationInstance,
9571) -> usize {
9572 unsafe { PioCalculationInstance::get(instance) }
9573 .and_then(scuc_inputs)
9574 .map_or(0, |inputs| inputs.branch_switching_costs.len())
9575}
9576
9577#[unsafe(no_mangle)]
9581pub unsafe extern "C" fn pio_ac_scuc_instance_branch_switching_cost_at(
9582 instance: *const PioCalculationInstance,
9583 index: usize,
9584 output: *mut PioScucBranchSwitchingCostView,
9585 error: *mut *mut PioError,
9586) -> bool {
9587 unsafe {
9588 entry(error, false, || {
9589 let inputs = scuc_inputs_or_error(require_calculation_instance(instance)?)?;
9590 let cost = inputs.branch_switching_costs.get(index).ok_or_else(|| {
9591 boundary_error(
9592 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
9593 format!("SCUC branch switching cost index {index} is out of range"),
9594 )
9595 })?;
9596 *require_output(output, "output")? = PioScucBranchSwitchingCostView {
9597 id: component_id_view(&cost.id),
9598 connection_cost: cost.connection_cost,
9599 disconnection_cost: cost.disconnection_cost,
9600 };
9601 Ok(true)
9602 })
9603 }
9604}
9605
9606#[unsafe(no_mangle)]
9610pub unsafe extern "C" fn pio_ac_scuc_instance_transformer_control_count(
9611 instance: *const PioCalculationInstance,
9612) -> usize {
9613 unsafe { PioCalculationInstance::get(instance) }
9614 .and_then(scuc_inputs)
9615 .map_or(0, |inputs| inputs.transformer_controls.len())
9616}
9617
9618#[unsafe(no_mangle)]
9622pub unsafe extern "C" fn pio_ac_scuc_instance_transformer_control_at(
9623 instance: *const PioCalculationInstance,
9624 index: usize,
9625 output: *mut PioScucTransformerControlView,
9626 error: *mut *mut PioError,
9627) -> bool {
9628 unsafe {
9629 entry(error, false, || {
9630 let inputs = scuc_inputs_or_error(require_calculation_instance(instance)?)?;
9631 let control = inputs.transformer_controls.get(index).ok_or_else(|| {
9632 boundary_error(
9633 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
9634 format!("SCUC transformer control index {index} is out of range"),
9635 )
9636 })?;
9637 *require_output(output, "output")? = PioScucTransformerControlView {
9638 id: component_id_view(&control.id),
9639 tap_ratio_min: control.tap_ratio_min,
9640 tap_ratio_max: control.tap_ratio_max,
9641 phase_shift_min_radians: control.phase_shift_min,
9642 phase_shift_max_radians: control.phase_shift_max,
9643 };
9644 Ok(true)
9645 })
9646 }
9647}
9648
9649#[unsafe(no_mangle)]
9653pub unsafe extern "C" fn pio_ac_scuc_instance_active_reserve_zone_count(
9654 instance: *const PioCalculationInstance,
9655) -> usize {
9656 unsafe { PioCalculationInstance::get(instance) }
9657 .and_then(scuc_inputs)
9658 .map_or(0, |inputs| inputs.active_reserve_zones.len())
9659}
9660
9661#[unsafe(no_mangle)]
9665pub unsafe extern "C" fn pio_ac_scuc_instance_active_reserve_zone_at(
9666 instance: *const PioCalculationInstance,
9667 index: usize,
9668 output: *mut PioScucActiveReserveZoneView,
9669 error: *mut *mut PioError,
9670) -> bool {
9671 unsafe {
9672 entry(error, false, || {
9673 let inputs = scuc_inputs_or_error(require_calculation_instance(instance)?)?;
9674 let zone = inputs.active_reserve_zones.get(index).ok_or_else(|| {
9675 boundary_error(
9676 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
9677 format!("SCUC active reserve zone index {index} is out of range"),
9678 )
9679 })?;
9680 *require_output(output, "output")? = PioScucActiveReserveZoneView {
9681 id: component_id_view(&zone.id),
9682 regulation_up_requirement_fraction: zone.regulation_up_requirement_fraction,
9683 regulation_down_requirement_fraction: zone.regulation_down_requirement_fraction,
9684 synchronized_requirement_fraction: zone.synchronized_requirement_fraction,
9685 nonsynchronized_requirement_fraction: zone.nonsynchronized_requirement_fraction,
9686 regulation_up_violation_cost: zone.regulation_up_violation_cost,
9687 regulation_down_violation_cost: zone.regulation_down_violation_cost,
9688 synchronized_violation_cost: zone.synchronized_violation_cost,
9689 nonsynchronized_violation_cost: zone.nonsynchronized_violation_cost,
9690 ramping_up_violation_cost: zone.ramping_up_violation_cost,
9691 ramping_down_violation_cost: zone.ramping_down_violation_cost,
9692 period_count: zone.ramping_up_requirement.len(),
9693 bus_count: zone.buses.len(),
9694 };
9695 Ok(true)
9696 })
9697 }
9698}
9699
9700#[unsafe(no_mangle)]
9704pub unsafe extern "C" fn pio_ac_scuc_instance_active_reserve_zone_period_at(
9705 instance: *const PioCalculationInstance,
9706 zone_index: usize,
9707 period_index: usize,
9708 output: *mut PioScucActiveReservePeriodView,
9709 error: *mut *mut PioError,
9710) -> bool {
9711 unsafe {
9712 entry(error, false, || {
9713 let inputs = scuc_inputs_or_error(require_calculation_instance(instance)?)?;
9714 let zone = inputs.active_reserve_zones.get(zone_index).ok_or_else(|| {
9715 boundary_error(
9716 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
9717 format!("SCUC active reserve zone index {zone_index} is out of range"),
9718 )
9719 })?;
9720 let up = zone
9721 .ramping_up_requirement
9722 .get(period_index)
9723 .copied()
9724 .ok_or_else(|| {
9725 boundary_error(
9726 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
9727 format!("SCUC reserve period index {period_index} is out of range"),
9728 )
9729 })?;
9730 let down = zone
9731 .ramping_down_requirement
9732 .get(period_index)
9733 .copied()
9734 .ok_or_else(|| {
9735 boundary_error(
9736 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
9737 format!("SCUC reserve period index {period_index} is out of range"),
9738 )
9739 })?;
9740 *require_output(output, "output")? = PioScucActiveReservePeriodView {
9741 ramping_up_requirement_pu: up,
9742 ramping_down_requirement_pu: down,
9743 };
9744 Ok(true)
9745 })
9746 }
9747}
9748
9749#[unsafe(no_mangle)]
9753pub unsafe extern "C" fn pio_ac_scuc_instance_active_reserve_zone_bus_at(
9754 instance: *const PioCalculationInstance,
9755 zone_index: usize,
9756 bus_index: usize,
9757 output: *mut PioComponentIdView,
9758 error: *mut *mut PioError,
9759) -> bool {
9760 unsafe {
9761 entry(error, false, || {
9762 let inputs = scuc_inputs_or_error(require_calculation_instance(instance)?)?;
9763 let zone = inputs.active_reserve_zones.get(zone_index).ok_or_else(|| {
9764 boundary_error(
9765 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
9766 format!("SCUC active reserve zone index {zone_index} is out of range"),
9767 )
9768 })?;
9769 let bus = zone.buses.get(bus_index).ok_or_else(|| {
9770 boundary_error(
9771 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
9772 format!("SCUC reserve zone bus index {bus_index} is out of range"),
9773 )
9774 })?;
9775 *require_output(output, "output")? = component_id_view(bus);
9776 Ok(true)
9777 })
9778 }
9779}
9780
9781#[unsafe(no_mangle)]
9785pub unsafe extern "C" fn pio_ac_scuc_instance_reactive_reserve_zone_count(
9786 instance: *const PioCalculationInstance,
9787) -> usize {
9788 unsafe { PioCalculationInstance::get(instance) }
9789 .and_then(scuc_inputs)
9790 .map_or(0, |inputs| inputs.reactive_reserve_zones.len())
9791}
9792
9793#[unsafe(no_mangle)]
9797pub unsafe extern "C" fn pio_ac_scuc_instance_reactive_reserve_zone_at(
9798 instance: *const PioCalculationInstance,
9799 index: usize,
9800 output: *mut PioScucReactiveReserveZoneView,
9801 error: *mut *mut PioError,
9802) -> bool {
9803 unsafe {
9804 entry(error, false, || {
9805 let inputs = scuc_inputs_or_error(require_calculation_instance(instance)?)?;
9806 let zone = inputs.reactive_reserve_zones.get(index).ok_or_else(|| {
9807 boundary_error(
9808 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
9809 format!("SCUC reactive reserve zone index {index} is out of range"),
9810 )
9811 })?;
9812 *require_output(output, "output")? = PioScucReactiveReserveZoneView {
9813 id: component_id_view(&zone.id),
9814 reactive_up_violation_cost: zone.reactive_up_violation_cost,
9815 reactive_down_violation_cost: zone.reactive_down_violation_cost,
9816 period_count: zone.reactive_up_requirement.len(),
9817 bus_count: zone.buses.len(),
9818 };
9819 Ok(true)
9820 })
9821 }
9822}
9823
9824#[unsafe(no_mangle)]
9828pub unsafe extern "C" fn pio_ac_scuc_instance_reactive_reserve_zone_period_at(
9829 instance: *const PioCalculationInstance,
9830 zone_index: usize,
9831 period_index: usize,
9832 output: *mut PioScucReactiveReservePeriodView,
9833 error: *mut *mut PioError,
9834) -> bool {
9835 unsafe {
9836 entry(error, false, || {
9837 let inputs = scuc_inputs_or_error(require_calculation_instance(instance)?)?;
9838 let zone = inputs
9839 .reactive_reserve_zones
9840 .get(zone_index)
9841 .ok_or_else(|| {
9842 boundary_error(
9843 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
9844 format!("SCUC reactive reserve zone index {zone_index} is out of range"),
9845 )
9846 })?;
9847 let up = zone
9848 .reactive_up_requirement
9849 .get(period_index)
9850 .copied()
9851 .ok_or_else(|| {
9852 boundary_error(
9853 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
9854 format!("SCUC reserve period index {period_index} is out of range"),
9855 )
9856 })?;
9857 let down = zone
9858 .reactive_down_requirement
9859 .get(period_index)
9860 .copied()
9861 .ok_or_else(|| {
9862 boundary_error(
9863 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
9864 format!("SCUC reserve period index {period_index} is out of range"),
9865 )
9866 })?;
9867 *require_output(output, "output")? = PioScucReactiveReservePeriodView {
9868 reactive_up_requirement_pu: up,
9869 reactive_down_requirement_pu: down,
9870 };
9871 Ok(true)
9872 })
9873 }
9874}
9875
9876#[unsafe(no_mangle)]
9880pub unsafe extern "C" fn pio_ac_scuc_instance_reactive_reserve_zone_bus_at(
9881 instance: *const PioCalculationInstance,
9882 zone_index: usize,
9883 bus_index: usize,
9884 output: *mut PioComponentIdView,
9885 error: *mut *mut PioError,
9886) -> bool {
9887 unsafe {
9888 entry(error, false, || {
9889 let inputs = scuc_inputs_or_error(require_calculation_instance(instance)?)?;
9890 let zone = inputs
9891 .reactive_reserve_zones
9892 .get(zone_index)
9893 .ok_or_else(|| {
9894 boundary_error(
9895 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
9896 format!("SCUC reactive reserve zone index {zone_index} is out of range"),
9897 )
9898 })?;
9899 let bus = zone.buses.get(bus_index).ok_or_else(|| {
9900 boundary_error(
9901 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
9902 format!("SCUC reserve zone bus index {bus_index} is out of range"),
9903 )
9904 })?;
9905 *require_output(output, "output")? = component_id_view(bus);
9906 Ok(true)
9907 })
9908 }
9909}
9910
9911#[unsafe(no_mangle)]
9916pub unsafe extern "C" fn pio_ac_scuc_instance_contingency_count(
9917 instance: *const PioCalculationInstance,
9918) -> usize {
9919 unsafe { PioCalculationInstance::get(instance) }
9920 .and_then(scuc_inputs)
9921 .map_or(0, |inputs| inputs.contingencies.len())
9922}
9923
9924fn scuc_contingency_view(contingency: &powerio_prob::ScucContingency) -> PioScucContingencyView {
9925 PioScucContingencyView {
9926 id: component_id_view(&contingency.id),
9927 component_count: contingency.components.len(),
9928 }
9929}
9930
9931#[unsafe(no_mangle)]
9936pub unsafe extern "C" fn pio_ac_scuc_instance_contingency_at(
9937 instance: *const PioCalculationInstance,
9938 contingency_index: usize,
9939 output: *mut PioScucContingencyView,
9940 error: *mut *mut PioError,
9941) -> bool {
9942 unsafe {
9943 entry(error, false, || {
9944 let inputs = scuc_inputs_or_error(require_calculation_instance(instance)?)?;
9945 let contingency = inputs.contingencies.get(contingency_index).ok_or_else(|| {
9946 boundary_error(
9947 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
9948 format!("SCUC contingency index {contingency_index} is out of range"),
9949 )
9950 })?;
9951 *require_output(output, "output")? = scuc_contingency_view(contingency);
9952 Ok(true)
9953 })
9954 }
9955}
9956
9957#[unsafe(no_mangle)]
9962pub unsafe extern "C" fn pio_ac_scuc_instance_contingency_get(
9963 instance: *const PioCalculationInstance,
9964 uid: *const c_char,
9965 uid_len: usize,
9966 output: *mut PioScucContingencyView,
9967 error: *mut *mut PioError,
9968) -> bool {
9969 unsafe {
9970 entry(error, false, || {
9971 let uid = required_str(uid, uid_len, "contingency_uid")?;
9972 let inputs = scuc_inputs_or_error(require_calculation_instance(instance)?)?;
9973 let contingency = inputs.contingency(uid).ok_or_else(|| {
9974 boundary_error(
9975 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
9976 format!("SCUC contingency UID '{uid}' does not exist"),
9977 )
9978 })?;
9979 *require_output(output, "output")? = scuc_contingency_view(contingency);
9980 Ok(true)
9981 })
9982 }
9983}
9984
9985#[unsafe(no_mangle)]
9990pub unsafe extern "C" fn pio_ac_scuc_instance_contingency_component_at(
9991 instance: *const PioCalculationInstance,
9992 contingency_index: usize,
9993 component_index: usize,
9994 output: *mut PioScucContingencyComponentView,
9995 error: *mut *mut PioError,
9996) -> bool {
9997 unsafe {
9998 entry(error, false, || {
9999 let inputs = scuc_inputs_or_error(require_calculation_instance(instance)?)?;
10000 let contingency = inputs.contingencies.get(contingency_index).ok_or_else(|| {
10001 boundary_error(
10002 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
10003 format!("SCUC contingency index {contingency_index} is out of range"),
10004 )
10005 })?;
10006 let component = contingency.components.get(component_index).ok_or_else(|| {
10007 boundary_error(
10008 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
10009 format!(
10010 "SCUC contingency {contingency_index} component index {component_index} is out of range"
10011 ),
10012 )
10013 })?;
10014 *require_output(output, "output")? = PioScucContingencyComponentView {
10015 id: component_id_view(component),
10016 };
10017 Ok(true)
10018 })
10019 }
10020}
10021
10022#[unsafe(no_mangle)]
10026pub unsafe extern "C" fn pio_calculation_solution_balanced_network(
10027 solution: *const PioCalculationSolution,
10028 error: *mut *mut PioError,
10029) -> *mut PioBalancedNetwork {
10030 unsafe {
10031 entry(error, std::ptr::null_mut(), || {
10032 let solution = PioCalculationSolution::get(solution).ok_or_else(|| {
10033 boundary_error(
10034 &codes::BIND_CAPI_NULL_HANDLE,
10035 "PioCalculationSolution must not be NULL",
10036 )
10037 })?;
10038 let projection = match solution.value() {
10039 Some(PioValue::DcPfSolution(_)) => BalancedNetworkProjection::DcPfSolution,
10040 Some(PioValue::AcPfSolution(_)) => BalancedNetworkProjection::AcPfSolution,
10041 Some(PioValue::DcOpfSolution(_)) => BalancedNetworkProjection::DcOpfSolution,
10042 Some(PioValue::AcOpfSolution(_)) => BalancedNetworkProjection::AcOpfSolution,
10043 Some(PioValue::AcOtsSolution(_)) => BalancedNetworkProjection::AcOtsSolution,
10044 Some(PioValue::SocwrOpfSolution(_)) => BalancedNetworkProjection::SocwrOpfSolution,
10045 Some(PioValue::AcScucSolution(_)) => BalancedNetworkProjection::AcScucSolution,
10046 _ => {
10047 return Err(boundary_error(
10048 &codes::REQUEST_CAPI_TYPE_MISMATCH,
10049 "the calculation solution does not use powerio.BalancedNetwork",
10050 ));
10051 }
10052 };
10053 Ok(make_balanced_network_view(solution, projection))
10054 })
10055 }
10056}
10057
10058#[unsafe(no_mangle)]
10062pub unsafe extern "C" fn pio_calculation_solution_multiconductor_network(
10063 solution: *const PioCalculationSolution,
10064 error: *mut *mut PioError,
10065) -> *mut PioMulticonductorNetwork {
10066 unsafe {
10067 entry(error, std::ptr::null_mut(), || {
10068 let solution = PioCalculationSolution::get(solution).ok_or_else(|| {
10069 boundary_error(
10070 &codes::BIND_CAPI_NULL_HANDLE,
10071 "PioCalculationSolution must not be NULL",
10072 )
10073 })?;
10074 let projection = match solution.value() {
10075 Some(PioValue::McAcPfSolution(_)) => {
10076 MulticonductorNetworkProjection::McAcPfSolution
10077 }
10078 Some(PioValue::McAcOpfSolution(_)) => {
10079 MulticonductorNetworkProjection::McAcOpfSolution
10080 }
10081 Some(PioValue::LinDist3FlowOpfSolution(_)) => {
10082 MulticonductorNetworkProjection::LinDist3FlowOpfSolution
10083 }
10084 _ => {
10085 return Err(boundary_error(
10086 &codes::REQUEST_CAPI_TYPE_MISMATCH,
10087 "the calculation solution does not use powerio.MulticonductorNetwork",
10088 ));
10089 }
10090 };
10091 Ok(make_multiconductor_network_view(solution, projection))
10092 })
10093 }
10094}
10095
10096#[unsafe(no_mangle)]
10104pub unsafe extern "C" fn pio_operating_point_get_value(
10105 point: *const PioOperatingPoint,
10106 quantity: *const c_char,
10107 quantity_len: usize,
10108 identity: *const c_char,
10109 identity_len: usize,
10110 out_value: *mut f64,
10111 error: *mut *mut PioError,
10112) -> bool {
10113 unsafe {
10114 entry(error, false, || {
10115 if out_value.is_null() {
10116 return Err(boundary_error(
10117 &codes::BIND_CAPI_NULL_ARGUMENT,
10118 "out_value must not be NULL",
10119 ));
10120 }
10121 let quantity = required_str(quantity, quantity_len, "quantity")?;
10122 let identity = required_str(identity, identity_len, "identity")?;
10123 let point = PioOperatingPoint::get(point).ok_or_else(|| {
10124 boundary_error(
10125 &codes::BIND_CAPI_NULL_HANDLE,
10126 "PioOperatingPoint must not be NULL",
10127 )
10128 })?;
10129 let value = if let Some(point) = point.balanced() {
10130 use powerio_prob::{
10131 BalancedOperatingPointFlag as F, BalancedOperatingPointQuantity as Q,
10132 };
10133 match quantity {
10134 "bus_voltage_magnitude" => point.values(Q::BusVoltageMagnitude),
10135 "bus_voltage_angle" => point.values(Q::BusVoltageAngle),
10136 "bus_active_injection" => point.values(Q::BusActiveInjection),
10137 "bus_reactive_injection" => point.values(Q::BusReactiveInjection),
10138 "generator_active_power" => point.values(Q::GeneratorActivePower),
10139 "generator_reactive_power" => point.values(Q::GeneratorReactivePower),
10140 "generator_voltage_setpoint" => point.values(Q::GeneratorVoltageSetpoint),
10141 "load_active_power" => point.values(Q::LoadActivePower),
10142 "load_reactive_power" => point.values(Q::LoadReactivePower),
10143 "branch_tap_ratio" => point.values(Q::BranchTapRatio),
10144 "branch_phase_shift" => point.values(Q::BranchPhaseShift),
10145 "generator_in_service" => {
10146 let found = point
10147 .flags(F::GeneratorInService)
10148 .and_then(|mut values| values.find(|(key, _)| *key == identity))
10149 .map(|(_, value)| if value { 1.0 } else { 0.0 });
10150 if let Some(found) = found {
10151 *out_value = found;
10152 return Ok(true);
10153 }
10154 return Ok(false);
10155 }
10156 "branch_in_service" => {
10157 let found = point
10158 .flags(F::BranchInService)
10159 .and_then(|mut values| values.find(|(key, _)| *key == identity))
10160 .map(|(_, value)| if value { 1.0 } else { 0.0 });
10161 if let Some(found) = found {
10162 *out_value = found;
10163 return Ok(true);
10164 }
10165 return Ok(false);
10166 }
10167 "switch_closed" => {
10168 let found = point
10169 .flags(F::SwitchClosed)
10170 .and_then(|mut values| values.find(|(key, _)| *key == identity))
10171 .map(|(_, value)| if value { 1.0 } else { 0.0 });
10172 if let Some(found) = found {
10173 *out_value = found;
10174 return Ok(true);
10175 }
10176 return Ok(false);
10177 }
10178 _ => {
10179 return Err(boundary_error(
10180 &codes::REQUEST_CAPI_QUANTITY_UNKNOWN,
10181 format!("unknown balanced operating point quantity '{quantity}'"),
10182 ));
10183 }
10184 }
10185 .and_then(|mut values| values.find(|(key, _)| *key == identity))
10186 .map(|(_, value)| value)
10187 } else if let Some(point) = point.multiconductor() {
10188 use powerio_prob::{
10189 MulticonductorOperatingPointFlag as F,
10190 MulticonductorOperatingPointQuantity as Q,
10191 };
10192 match quantity {
10193 "terminal_voltage_magnitude" => point.values(Q::TerminalVoltageMagnitude),
10194 "terminal_voltage_angle" => point.values(Q::TerminalVoltageAngle),
10195 "load_active_power" => point.values(Q::LoadActivePower),
10196 "load_reactive_power" => point.values(Q::LoadReactivePower),
10197 "generator_active_power" => point.values(Q::GeneratorActivePower),
10198 "generator_reactive_power" => point.values(Q::GeneratorReactivePower),
10199 "transformer_tap" => point.values(Q::TransformerTap),
10200 "capacitor_steps" => point.values(Q::CapacitorSteps),
10201 "switch_closed" => {
10202 let found = point
10203 .flags(F::SwitchClosed)
10204 .and_then(|mut values| values.find(|(key, _)| *key == identity))
10205 .map(|(_, value)| if value { 1.0 } else { 0.0 });
10206 if let Some(found) = found {
10207 *out_value = found;
10208 return Ok(true);
10209 }
10210 return Ok(false);
10211 }
10212 _ => {
10213 return Err(boundary_error(
10214 &codes::REQUEST_CAPI_QUANTITY_UNKNOWN,
10215 format!("unknown multiconductor operating point quantity '{quantity}'"),
10216 ));
10217 }
10218 }
10219 .and_then(|mut values| values.find(|(key, _)| *key == identity))
10220 .map(|(_, value)| value)
10221 } else {
10222 return Err(boundary_error(
10223 &codes::REQUEST_CAPI_TYPE_MISMATCH,
10224 "the handle does not refer to an operating point",
10225 ));
10226 };
10227 if let Some(value) = value {
10228 *out_value = value;
10229 Ok(true)
10230 } else {
10231 Ok(false)
10232 }
10233 })
10234 }
10235}
10236
10237#[unsafe(no_mangle)]
10242pub unsafe extern "C" fn pio_operating_point_retain(
10243 point: *const PioOperatingPoint,
10244) -> *mut PioOperatingPoint {
10245 unsafe { PioOperatingPoint::retain_raw(point) }
10246}
10247
10248#[unsafe(no_mangle)]
10253pub unsafe extern "C" fn pio_operating_point_release(point: *mut PioOperatingPoint) {
10254 unsafe { PioOperatingPoint::release_raw(point) };
10255}
10256
10257#[unsafe(no_mangle)]
10262pub unsafe extern "C" fn pio_calculation_instance_retain(
10263 instance: *const PioCalculationInstance,
10264) -> *mut PioCalculationInstance {
10265 unsafe { PioCalculationInstance::retain_raw(instance) }
10266}
10267
10268#[unsafe(no_mangle)]
10273pub unsafe extern "C" fn pio_calculation_instance_release(instance: *mut PioCalculationInstance) {
10274 unsafe { PioCalculationInstance::release_raw(instance) };
10275}
10276
10277#[unsafe(no_mangle)]
10282pub unsafe extern "C" fn pio_dc_opf_preparation_retain(
10283 preparation: *const PioDcOpfPreparation,
10284) -> *mut PioDcOpfPreparation {
10285 unsafe { PioDcOpfPreparation::retain_raw(preparation) }
10286}
10287
10288#[unsafe(no_mangle)]
10293pub unsafe extern "C" fn pio_dc_opf_preparation_release(preparation: *mut PioDcOpfPreparation) {
10294 unsafe { PioDcOpfPreparation::release_raw(preparation) };
10295}
10296
10297#[unsafe(no_mangle)]
10302pub unsafe extern "C" fn pio_ac_opf_preparation_retain(
10303 preparation: *const PioAcOpfPreparation,
10304) -> *mut PioAcOpfPreparation {
10305 unsafe { PioAcOpfPreparation::retain_raw(preparation) }
10306}
10307
10308#[unsafe(no_mangle)]
10313pub unsafe extern "C" fn pio_ac_opf_preparation_release(preparation: *mut PioAcOpfPreparation) {
10314 unsafe { PioAcOpfPreparation::release_raw(preparation) };
10315}
10316
10317#[unsafe(no_mangle)]
10322pub unsafe extern "C" fn pio_calculation_solution_retain(
10323 solution: *const PioCalculationSolution,
10324) -> *mut PioCalculationSolution {
10325 unsafe { PioCalculationSolution::retain_raw(solution) }
10326}
10327
10328#[unsafe(no_mangle)]
10333pub unsafe extern "C" fn pio_calculation_solution_release(solution: *mut PioCalculationSolution) {
10334 unsafe { PioCalculationSolution::release_raw(solution) };
10335}
10336
10337#[unsafe(no_mangle)]
10342pub unsafe extern "C" fn pio_value_retain(value: *const PioValueHandle) -> *mut PioValueHandle {
10343 unsafe { PioValueHandle::retain_raw(value) }
10344}
10345
10346#[unsafe(no_mangle)]
10351pub unsafe extern "C" fn pio_value_release(value: *mut PioValueHandle) {
10352 unsafe { PioValueHandle::release_raw(value) };
10353}
10354
10355#[repr(C)]
10360#[derive(Clone, Copy)]
10361pub struct PioTimePointView {
10362 pub label: PioStringView,
10363 pub duration_seconds: f64,
10364 pub has_duration: bool,
10365}
10366
10367fn time_series(value: &ValueInner) -> Option<&PioTimeSeries> {
10368 match value.value()? {
10369 PioValue::TimeSeries(series) => Some(series),
10370 _ => None,
10371 }
10372}
10373
10374fn scenario_set(value: &ValueInner) -> Option<&PioScenarioSet> {
10375 match value.value()? {
10376 PioValue::ScenarioSet(scenarios) => Some(scenarios),
10377 _ => None,
10378 }
10379}
10380
10381#[unsafe(no_mangle)]
10385pub unsafe extern "C" fn pio_time_series_len(series: *const PioTimeSeriesHandle) -> usize {
10386 unsafe { PioTimeSeriesHandle::get(series) }
10387 .and_then(time_series)
10388 .map_or(0, PioTimeSeries::len)
10389}
10390
10391#[unsafe(no_mangle)]
10397pub unsafe extern "C" fn pio_time_series_time_point(
10398 series: *const PioTimeSeriesHandle,
10399 index: usize,
10400 out: *mut PioTimePointView,
10401 error: *mut *mut PioError,
10402) -> bool {
10403 unsafe {
10404 entry(error, false, || {
10405 if out.is_null() {
10406 return Err(boundary_error(
10407 &codes::BIND_CAPI_NULL_ARGUMENT,
10408 "out must not be NULL",
10409 ));
10410 }
10411 let values = PioTimeSeriesHandle::get(series)
10412 .and_then(time_series)
10413 .ok_or_else(|| {
10414 boundary_error(
10415 &codes::BIND_CAPI_NULL_HANDLE,
10416 "a live time-series handle is required",
10417 )
10418 })?;
10419 let point = values.time_points().get(index).ok_or_else(|| {
10420 boundary_error(
10421 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
10422 format!("time series index {index} is out of range"),
10423 )
10424 })?;
10425 out.write(PioTimePointView {
10426 label: PioStringView::new(point.label()),
10427 duration_seconds: point
10428 .duration()
10429 .map_or(0.0, |duration| duration.as_secs_f64()),
10430 has_duration: point.duration().is_some(),
10431 });
10432 Ok(true)
10433 })
10434 }
10435}
10436
10437#[unsafe(no_mangle)]
10441pub unsafe extern "C" fn pio_time_series_element_type(
10442 series: *const PioTimeSeriesHandle,
10443) -> PioStringView {
10444 unsafe { PioTimeSeriesHandle::get(series) }
10445 .and_then(time_series)
10446 .map_or(PioStringView::EMPTY, |series| {
10447 PioStringView::new(series.element_type())
10448 })
10449}
10450
10451#[unsafe(no_mangle)]
10456pub unsafe extern "C" fn pio_time_series_get(
10457 series: *const PioTimeSeriesHandle,
10458 index: usize,
10459 error: *mut *mut PioError,
10460) -> *mut PioValueHandle {
10461 unsafe {
10462 entry(error, std::ptr::null_mut(), || {
10463 let series = PioTimeSeriesHandle::get(series).ok_or_else(|| {
10464 boundary_error(
10465 &codes::BIND_CAPI_NULL_HANDLE,
10466 "PioTimeSeriesHandle must not be NULL",
10467 )
10468 })?;
10469 let values = time_series(series).ok_or_else(|| {
10470 boundary_error(
10471 &codes::REQUEST_CAPI_TYPE_MISMATCH,
10472 "the handle does not refer to a time series",
10473 )
10474 })?;
10475 if values.get(index).is_none() {
10476 return Err(boundary_error(
10477 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
10478 format!("time series index {index} is out of range"),
10479 ));
10480 }
10481 Ok(value_handle(series.child(ValueStep::TimeSeries(index))))
10482 })
10483 }
10484}
10485
10486#[unsafe(no_mangle)]
10491pub unsafe extern "C" fn pio_time_series_retain(
10492 series: *const PioTimeSeriesHandle,
10493) -> *mut PioTimeSeriesHandle {
10494 unsafe { PioTimeSeriesHandle::retain_raw(series) }
10495}
10496
10497#[unsafe(no_mangle)]
10502pub unsafe extern "C" fn pio_time_series_release(series: *mut PioTimeSeriesHandle) {
10503 unsafe { PioTimeSeriesHandle::release_raw(series) };
10504}
10505
10506#[unsafe(no_mangle)]
10510pub unsafe extern "C" fn pio_scenario_set_len(set: *const PioScenarioSetHandle) -> usize {
10511 unsafe { PioScenarioSetHandle::get(set) }
10512 .and_then(scenario_set)
10513 .map_or(0, PioScenarioSet::len)
10514}
10515
10516#[unsafe(no_mangle)]
10520pub unsafe extern "C" fn pio_scenario_set_element_type(
10521 set: *const PioScenarioSetHandle,
10522) -> PioStringView {
10523 unsafe { PioScenarioSetHandle::get(set) }
10524 .and_then(scenario_set)
10525 .map_or(PioStringView::EMPTY, |set| {
10526 PioStringView::new(set.element_type())
10527 })
10528}
10529
10530#[unsafe(no_mangle)]
10534pub unsafe extern "C" fn pio_scenario_set_id_at(
10535 set: *const PioScenarioSetHandle,
10536 index: usize,
10537) -> PioStringView {
10538 unsafe { PioScenarioSetHandle::get(set) }
10539 .and_then(scenario_set)
10540 .and_then(|set| set.iter().nth(index))
10541 .map_or(PioStringView::EMPTY, |scenario| {
10542 PioStringView::new(scenario.id().as_str())
10543 })
10544}
10545
10546#[unsafe(no_mangle)]
10551pub unsafe extern "C" fn pio_scenario_set_get_at(
10552 set: *const PioScenarioSetHandle,
10553 index: usize,
10554 error: *mut *mut PioError,
10555) -> *mut PioValueHandle {
10556 unsafe {
10557 entry(error, std::ptr::null_mut(), || {
10558 let set = PioScenarioSetHandle::get(set).ok_or_else(|| {
10559 boundary_error(
10560 &codes::BIND_CAPI_NULL_HANDLE,
10561 "PioScenarioSetHandle must not be NULL",
10562 )
10563 })?;
10564 let values = scenario_set(set).ok_or_else(|| {
10565 boundary_error(
10566 &codes::REQUEST_CAPI_TYPE_MISMATCH,
10567 "the handle does not refer to a scenario set",
10568 )
10569 })?;
10570 if values.get_at(index).is_none() {
10571 return Err(boundary_error(
10572 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
10573 format!("scenario position {index} is out of range"),
10574 ));
10575 }
10576 Ok(value_handle(set.child(ValueStep::Scenario(index))))
10577 })
10578 }
10579}
10580
10581#[unsafe(no_mangle)]
10586pub unsafe extern "C" fn pio_scenario_set_get(
10587 set: *const PioScenarioSetHandle,
10588 id: *const c_char,
10589 id_len: usize,
10590 error: *mut *mut PioError,
10591) -> *mut PioValueHandle {
10592 unsafe {
10593 entry(error, std::ptr::null_mut(), || {
10594 let id = required_str(id, id_len, "scenario_id")?;
10595 let set = PioScenarioSetHandle::get(set).ok_or_else(|| {
10596 boundary_error(
10597 &codes::BIND_CAPI_NULL_HANDLE,
10598 "PioScenarioSetHandle must not be NULL",
10599 )
10600 })?;
10601 let values = scenario_set(set).ok_or_else(|| {
10602 boundary_error(
10603 &codes::REQUEST_CAPI_TYPE_MISMATCH,
10604 "the handle does not refer to a scenario set",
10605 )
10606 })?;
10607 let Some(position) = values
10608 .iter()
10609 .position(|scenario| scenario.id().as_str() == id)
10610 else {
10611 return Err(boundary_error(
10612 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
10613 format!("scenario ID '{id}' does not exist"),
10614 ));
10615 };
10616 Ok(value_handle(set.child(ValueStep::Scenario(position))))
10617 })
10618 }
10619}
10620
10621#[unsafe(no_mangle)]
10626pub unsafe extern "C" fn pio_scenario_set_retain(
10627 set: *const PioScenarioSetHandle,
10628) -> *mut PioScenarioSetHandle {
10629 unsafe { PioScenarioSetHandle::retain_raw(set) }
10630}
10631
10632#[unsafe(no_mangle)]
10637pub unsafe extern "C" fn pio_scenario_set_release(set: *mut PioScenarioSetHandle) {
10638 unsafe { PioScenarioSetHandle::release_raw(set) };
10639}
10640
10641#[unsafe(no_mangle)]
10647pub unsafe extern "C" fn pio_balanced_network_name(
10648 network: *const PioBalancedNetwork,
10649) -> PioStringView {
10650 unsafe { PioBalancedNetwork::get(network) }
10651 .and_then(BalancedNetworkInner::network)
10652 .map_or(PioStringView::EMPTY, |network| {
10653 PioStringView::new(network.name())
10654 })
10655}
10656
10657#[unsafe(no_mangle)]
10661pub unsafe extern "C" fn pio_balanced_network_base_mva(network: *const PioBalancedNetwork) -> f64 {
10662 unsafe { PioBalancedNetwork::get(network) }
10663 .and_then(BalancedNetworkInner::network)
10664 .map_or(f64::NAN, BalancedNetwork::base_mva)
10665}
10666
10667#[unsafe(no_mangle)]
10671pub unsafe extern "C" fn pio_balanced_network_base_frequency_hz(
10672 network: *const PioBalancedNetwork,
10673) -> f64 {
10674 unsafe { PioBalancedNetwork::get(network) }
10675 .and_then(BalancedNetworkInner::network)
10676 .map_or(f64::NAN, BalancedNetwork::base_frequency)
10677}
10678
10679#[unsafe(no_mangle)]
10684pub unsafe extern "C" fn pio_balanced_network_geo(
10685 network: *const PioBalancedNetwork,
10686 output: *mut PioBalancedGeoView,
10687 error: *mut *mut PioError,
10688) -> bool {
10689 unsafe {
10690 entry(error, false, || {
10691 let network = require_balanced_network(network)?;
10692 *require_output(output, "output")? = balanced_geo_view(network.geo().as_ref());
10693 Ok(true)
10694 })
10695 }
10696}
10697
10698#[unsafe(no_mangle)]
10702pub unsafe extern "C" fn pio_balanced_network_has_detailed_connectivity(
10703 network: *const PioBalancedNetwork,
10704) -> bool {
10705 unsafe { PioBalancedNetwork::get(network) }
10706 .and_then(BalancedNetworkInner::network)
10707 .is_some_and(|network| network.detailed_connectivity().is_some())
10708}
10709
10710#[unsafe(no_mangle)]
10715pub unsafe extern "C" fn pio_balanced_network_detailed_connectivity(
10716 network: *const PioBalancedNetwork,
10717) -> *mut PioDetailedConnectivity {
10718 let Some(owner) = (unsafe { PioBalancedNetwork::arc(network) }) else {
10719 return std::ptr::null_mut();
10720 };
10721 if owner
10722 .network()
10723 .is_none_or(|network| network.detailed_connectivity().is_none())
10724 {
10725 return std::ptr::null_mut();
10726 }
10727 PioDetailedConnectivity::new_raw(DetailedConnectivityInner { owner })
10728}
10729
10730#[unsafe(no_mangle)]
10735pub unsafe extern "C" fn pio_detailed_connectivity_counts(
10736 details: *const PioDetailedConnectivity,
10737 output: *mut PioDetailedConnectivityCountsView,
10738 error: *mut *mut PioError,
10739) -> bool {
10740 unsafe {
10741 entry(error, false, || {
10742 let details = require_detailed_connectivity(details)?;
10743 *require_output(output, "output")? = PioDetailedConnectivityCountsView {
10744 omitted_fields: details.omitted_fields.len(),
10745 component_metadata: details.component_metadata.len(),
10746 subnetworks: details.subnetworks.len(),
10747 substations: details.substations.len(),
10748 voltage_levels: details.voltage_levels.len(),
10749 bus_breaker_buses: details.bus_breaker_buses.len(),
10750 calculated_buses: details.calculated_buses.len(),
10751 connectivity_nodes: details.connectivity_nodes.len(),
10752 busbar_sections: details.busbar_sections.len(),
10753 junctions: details.junctions.len(),
10754 terminals: details.terminals.len(),
10755 switches: details.switches.len(),
10756 internal_connections: details.internal_connections.len(),
10757 operational_limit_groups: details.operational_limit_groups.len(),
10758 tap_changers: details.tap_changers.len(),
10759 equipment_reactive_limits: details.equipment_reactive_limits.len(),
10760 boundary_lines: details.boundary_lines.len(),
10761 tie_lines: details.tie_lines.len(),
10762 dc_converter_units: details.dc_converter_units.len(),
10763 dc_topological_nodes: details.dc_topological_nodes.len(),
10764 dc_nodes: details.dc_nodes.len(),
10765 dc_grounds: details.dc_grounds.len(),
10766 dc_busbars: details.dc_busbars.len(),
10767 dc_lines: details.dc_lines.len(),
10768 dc_series_devices: details.dc_series_devices.len(),
10769 dc_switches: details.dc_switches.len(),
10770 voltage_source_converters: details.voltage_source_converters.len(),
10771 line_commutated_converters: details.line_commutated_converters.len(),
10772 };
10773 Ok(true)
10774 })
10775 }
10776}
10777
10778fn omitted_field_name(value: powerio_tx::OmittedFieldName) -> &'static str {
10779 match value {
10780 powerio_tx::OmittedFieldName::ActivePower => "active_power",
10781 powerio_tx::OmittedFieldName::ReactivePower => "reactive_power",
10782 powerio_tx::OmittedFieldName::VoltageSetpoint => "voltage_setpoint",
10783 powerio_tx::OmittedFieldName::RatedApparentPower => "rated_apparent_power",
10784 powerio_tx::OmittedFieldName::ShuntConductancePerSection => "shunt_conductance_per_section",
10785 _ => "unknown",
10786 }
10787}
10788
10789fn topology_kind_name(kind: powerio_tx::TopologyKind) -> &'static str {
10790 match kind {
10791 powerio_tx::TopologyKind::BusBreaker => "bus_breaker",
10792 powerio_tx::TopologyKind::NodeBreaker => "node_breaker",
10793 _ => "unknown",
10794 }
10795}
10796
10797fn topology_switch_kind_name(kind: powerio_tx::SwitchKind) -> &'static str {
10798 match kind {
10799 powerio_tx::SwitchKind::Breaker => "breaker",
10800 powerio_tx::SwitchKind::Disconnector => "disconnector",
10801 powerio_tx::SwitchKind::LoadBreakSwitch => "load_break_switch",
10802 _ => "unknown",
10803 }
10804}
10805
10806fn curve_style_name(style: powerio_tx::CurveStyle) -> &'static str {
10807 match style {
10808 powerio_tx::CurveStyle::ConstantYValue => "constant_y_value",
10809 powerio_tx::CurveStyle::StraightLineYValues => "straight_line_y_values",
10810 _ => "unknown",
10811 }
10812}
10813
10814fn empty_reactive_limits_view() -> PioReactiveLimitsView {
10815 PioReactiveLimitsView {
10816 kind: PioStringView::EMPTY,
10817 minimum_reactive_power_mvar: 0.0,
10818 maximum_reactive_power_mvar: 0.0,
10819 has_minimum_and_maximum: false,
10820 curve_style: PioStringView::EMPTY,
10821 has_curve_style: false,
10822 property_count: 0,
10823 point_count: 0,
10824 }
10825}
10826
10827fn reactive_limits_view(
10828 value: Option<&powerio_tx::ReactiveLimits>,
10829) -> (PioReactiveLimitsView, bool) {
10830 match value {
10831 Some(powerio_tx::ReactiveLimits::MinMax(limits)) => (
10832 PioReactiveLimitsView {
10833 kind: PioStringView::new("min_max"),
10834 minimum_reactive_power_mvar: limits.minimum_reactive_power_mvar,
10835 maximum_reactive_power_mvar: limits.maximum_reactive_power_mvar,
10836 has_minimum_and_maximum: true,
10837 curve_style: PioStringView::EMPTY,
10838 has_curve_style: false,
10839 property_count: limits.properties.len(),
10840 point_count: 0,
10841 },
10842 true,
10843 ),
10844 Some(powerio_tx::ReactiveLimits::CapabilityCurve(curve)) => (
10845 PioReactiveLimitsView {
10846 kind: PioStringView::new("capability_curve"),
10847 minimum_reactive_power_mvar: 0.0,
10848 maximum_reactive_power_mvar: 0.0,
10849 has_minimum_and_maximum: false,
10850 curve_style: PioStringView::new(curve_style_name(curve.curve_style)),
10851 has_curve_style: true,
10852 property_count: curve.properties.len(),
10853 point_count: curve.points.len(),
10854 },
10855 true,
10856 ),
10857 Some(_) => (empty_reactive_limits_view(), true),
10858 None => (empty_reactive_limits_view(), false),
10859 }
10860}
10861
10862fn reactive_limit_properties(
10863 limits: &powerio_tx::ReactiveLimits,
10864) -> Result<&std::collections::BTreeMap<String, String>, *mut PioError> {
10865 Ok(match limits {
10866 powerio_tx::ReactiveLimits::MinMax(limits) => &limits.properties,
10867 powerio_tx::ReactiveLimits::CapabilityCurve(curve) => &curve.properties,
10868 _ => {
10869 return Err(boundary_error(
10870 &codes::REQUEST_CAPI_TYPE_MISMATCH,
10871 "unsupported reactive limit form",
10872 ));
10873 }
10874 })
10875}
10876
10877fn reactive_capability_curve(
10878 limits: &powerio_tx::ReactiveLimits,
10879) -> Option<&powerio_tx::ReactiveCapabilityCurve> {
10880 match limits {
10881 powerio_tx::ReactiveLimits::CapabilityCurve(curve) => Some(curve),
10882 _ => None,
10883 }
10884}
10885
10886fn string_property_view(
10887 properties: &std::collections::BTreeMap<String, String>,
10888 index: usize,
10889) -> Result<PioStringPropertyView, *mut PioError> {
10890 let (name, value) = properties.iter().nth(index).ok_or_else(|| {
10891 boundary_error(
10892 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
10893 format!("property index {index} is out of range"),
10894 )
10895 })?;
10896 Ok(PioStringPropertyView {
10897 name: PioStringView::new(name),
10898 value: PioStringView::new(value),
10899 })
10900}
10901
10902fn reactive_capability_point_view(
10903 curve: &powerio_tx::ReactiveCapabilityCurve,
10904 index: usize,
10905) -> Result<PioReactiveCapabilityCurvePointView, *mut PioError> {
10906 let point = curve.points.get(index).ok_or_else(|| {
10907 boundary_error(
10908 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
10909 format!("reactive capability point index {index} is out of range"),
10910 )
10911 })?;
10912 Ok(PioReactiveCapabilityCurvePointView {
10913 active_power_mw: point.active_power_mw,
10914 minimum_reactive_power_mvar: point.minimum_reactive_power_mvar,
10915 maximum_reactive_power_mvar: point.maximum_reactive_power_mvar,
10916 property_count: point.properties.len(),
10917 })
10918}
10919
10920fn empty_boundary_line_generation_view() -> PioBoundaryLineGenerationView {
10921 PioBoundaryLineGenerationView {
10922 voltage_regulation_on: false,
10923 minimum_active_power_mw: 0.0,
10924 has_minimum_active_power: false,
10925 maximum_active_power_mw: 0.0,
10926 has_maximum_active_power: false,
10927 target_active_power_mw: 0.0,
10928 has_target_active_power: false,
10929 target_reactive_power_mvar: 0.0,
10930 has_target_reactive_power: false,
10931 target_voltage_kv: 0.0,
10932 has_target_voltage: false,
10933 reactive_limits: empty_reactive_limits_view(),
10934 has_reactive_limits: false,
10935 }
10936}
10937
10938fn boundary_line_generation_view(
10939 value: Option<&powerio_tx::BoundaryLineGeneration>,
10940) -> (PioBoundaryLineGenerationView, bool) {
10941 let Some(value) = value else {
10942 return (empty_boundary_line_generation_view(), false);
10943 };
10944 let (reactive_limits, has_reactive_limits) =
10945 reactive_limits_view(value.reactive_limits.as_ref());
10946 (
10947 PioBoundaryLineGenerationView {
10948 voltage_regulation_on: value.voltage_regulation_on,
10949 minimum_active_power_mw: value.minimum_active_power_mw.unwrap_or(0.0),
10950 has_minimum_active_power: value.minimum_active_power_mw.is_some(),
10951 maximum_active_power_mw: value.maximum_active_power_mw.unwrap_or(0.0),
10952 has_maximum_active_power: value.maximum_active_power_mw.is_some(),
10953 target_active_power_mw: value.target_active_power_mw.unwrap_or(0.0),
10954 has_target_active_power: value.target_active_power_mw.is_some(),
10955 target_reactive_power_mvar: value.target_reactive_power_mvar.unwrap_or(0.0),
10956 has_target_reactive_power: value.target_reactive_power_mvar.is_some(),
10957 target_voltage_kv: value.target_voltage_kv.unwrap_or(0.0),
10958 has_target_voltage: value.target_voltage_kv.is_some(),
10959 reactive_limits,
10960 has_reactive_limits,
10961 },
10962 true,
10963 )
10964}
10965
10966fn topology_endpoint_view(
10967 endpoint: &powerio_tx::TopologyEndpoint,
10968) -> (PioStringView, PioComponentIdView) {
10969 match endpoint {
10970 powerio_tx::TopologyEndpoint::Bus(component) => {
10971 (PioStringView::new("bus"), component_id_view(component))
10972 }
10973 powerio_tx::TopologyEndpoint::Node(component) => {
10974 (PioStringView::new("node"), component_id_view(component))
10975 }
10976 _ => (PioStringView::new("unknown"), empty_component_id_view()),
10977 }
10978}
10979
10980fn tap_changer_kind_name(kind: powerio_tx::TapChangerKind) -> &'static str {
10981 match kind {
10982 powerio_tx::TapChangerKind::Ratio => "ratio",
10983 powerio_tx::TapChangerKind::Phase => "phase",
10984 _ => "unknown",
10985 }
10986}
10987
10988fn tap_changer_regulation_mode_name(mode: powerio_tx::TapChangerRegulationMode) -> &'static str {
10989 match mode {
10990 powerio_tx::TapChangerRegulationMode::Voltage => "voltage",
10991 powerio_tx::TapChangerRegulationMode::ReactivePower => "reactive_power",
10992 powerio_tx::TapChangerRegulationMode::ActivePower => "active_power",
10993 powerio_tx::TapChangerRegulationMode::Current => "current",
10994 _ => "unknown",
10995 }
10996}
10997
10998fn dc_polarity_name(value: powerio_tx::DcPolarity) -> &'static str {
10999 match value {
11000 powerio_tx::DcPolarity::Positive => "positive",
11001 powerio_tx::DcPolarity::Middle => "middle",
11002 powerio_tx::DcPolarity::Negative => "negative",
11003 _ => "unknown",
11004 }
11005}
11006
11007fn dc_switch_kind_name(value: powerio_tx::DcSwitchKind) -> &'static str {
11008 match value {
11009 powerio_tx::DcSwitchKind::Switch => "switch",
11010 powerio_tx::DcSwitchKind::Breaker => "breaker",
11011 powerio_tx::DcSwitchKind::Disconnector => "disconnector",
11012 _ => "unknown",
11013 }
11014}
11015
11016fn dc_converter_operation_mode_name(value: powerio_tx::DcConverterOperatingMode) -> &'static str {
11017 match value {
11018 powerio_tx::DcConverterOperatingMode::Bipolar => "bipolar",
11019 powerio_tx::DcConverterOperatingMode::MonopolarGroundReturn => "monopolar_ground_return",
11020 powerio_tx::DcConverterOperatingMode::MonopolarMetallicReturn => {
11021 "monopolar_metallic_return"
11022 }
11023 _ => "unknown",
11024 }
11025}
11026
11027fn ac_dc_converter_control_mode_name(value: powerio_tx::AcDcConverterControlMode) -> &'static str {
11028 match value {
11029 powerio_tx::AcDcConverterControlMode::ActivePowerAtPcc => "active_power_at_pcc",
11030 powerio_tx::AcDcConverterControlMode::DcVoltage => "dc_voltage",
11031 powerio_tx::AcDcConverterControlMode::DcCurrent => "dc_current",
11032 powerio_tx::AcDcConverterControlMode::ActivePowerAtPccAndDcVoltageDroopCurve => {
11033 "active_power_at_pcc_and_dc_voltage_droop_curve"
11034 }
11035 powerio_tx::AcDcConverterControlMode::ActivePowerAtPccAndDcVoltageDroop => {
11036 "active_power_at_pcc_and_dc_voltage_droop"
11037 }
11038 powerio_tx::AcDcConverterControlMode::ActivePowerAtPccAndDcVoltageDroopWithCompensation => {
11039 "active_power_at_pcc_and_dc_voltage_droop_with_compensation"
11040 }
11041 powerio_tx::AcDcConverterControlMode::ActivePowerAtPccAndDcVoltageDroopPilot => {
11042 "active_power_at_pcc_and_dc_voltage_droop_pilot"
11043 }
11044 _ => "unknown",
11045 }
11046}
11047
11048fn line_commutated_converter_reactive_model_name(
11049 value: powerio_tx::LineCommutatedConverterReactiveModel,
11050) -> &'static str {
11051 match value {
11052 powerio_tx::LineCommutatedConverterReactiveModel::FixedPowerFactor => "fixed_power_factor",
11053 powerio_tx::LineCommutatedConverterReactiveModel::CalculatedPowerFactor => {
11054 "calculated_power_factor"
11055 }
11056 _ => "unknown",
11057 }
11058}
11059
11060fn line_commutated_converter_operating_mode_name(
11061 value: powerio_tx::LineCommutatedConverterOperatingMode,
11062) -> &'static str {
11063 match value {
11064 powerio_tx::LineCommutatedConverterOperatingMode::Rectifier => "rectifier",
11065 powerio_tx::LineCommutatedConverterOperatingMode::Inverter => "inverter",
11066 _ => "unknown",
11067 }
11068}
11069
11070fn empty_dc_terminal_view() -> PioDcTerminalView {
11071 PioDcTerminalView {
11072 component: empty_component_id_view(),
11073 has_component: false,
11074 sequence_number: 0,
11075 has_sequence_number: false,
11076 dc_node: empty_component_id_view(),
11077 has_dc_node: false,
11078 dc_topological_node: empty_component_id_view(),
11079 has_dc_topological_node: false,
11080 polarity: PioStringView::EMPTY,
11081 has_polarity: false,
11082 connected: false,
11083 has_connected: false,
11084 active_power_mw: 0.0,
11085 has_active_power: false,
11086 current_a: 0.0,
11087 has_current: false,
11088 }
11089}
11090
11091fn dc_terminal_view(value: &powerio_tx::DcTerminal) -> PioDcTerminalView {
11092 let (component, has_component) = optional_component_id_view(value.component.as_ref());
11093 let (dc_node, has_dc_node) = optional_component_id_view(value.dc_node.as_ref());
11094 let (dc_topological_node, has_dc_topological_node) =
11095 optional_component_id_view(value.dc_topological_node.as_ref());
11096 let (polarity, has_polarity) = value
11097 .polarity
11098 .map_or((PioStringView::EMPTY, false), |polarity| {
11099 (PioStringView::new(dc_polarity_name(polarity)), true)
11100 });
11101 PioDcTerminalView {
11102 component,
11103 has_component,
11104 sequence_number: value.sequence_number.unwrap_or(0),
11105 has_sequence_number: value.sequence_number.is_some(),
11106 dc_node,
11107 has_dc_node,
11108 dc_topological_node,
11109 has_dc_topological_node,
11110 polarity,
11111 has_polarity,
11112 connected: value.connected.unwrap_or(false),
11113 has_connected: value.connected.is_some(),
11114 active_power_mw: value.active_power_mw.unwrap_or(0.0),
11115 has_active_power: value.active_power_mw.is_some(),
11116 current_a: value.current_a.unwrap_or(0.0),
11117 has_current: value.current_a.is_some(),
11118 }
11119}
11120
11121#[allow(clippy::too_many_arguments)]
11122fn dc_equipment_view(
11123 component: &ComponentId,
11124 equipment_container: Option<&ComponentId>,
11125 kind: &'static str,
11126 terminal1: &powerio_tx::DcTerminal,
11127 terminal2: Option<&powerio_tx::DcTerminal>,
11128 rated_dc_voltage_kv: Option<f64>,
11129 resistance_ohm: Option<f64>,
11130 inductance_h: Option<f64>,
11131 capacitance_f: Option<f64>,
11132 length_km: Option<f64>,
11133 switch_kind: Option<powerio_tx::DcSwitchKind>,
11134 open: Option<bool>,
11135) -> PioDcEquipmentView {
11136 let (equipment_container, has_equipment_container) =
11137 optional_component_id_view(equipment_container);
11138 let (switch_kind, has_switch_kind) = switch_kind
11139 .map_or((PioStringView::EMPTY, false), |kind| {
11140 (PioStringView::new(dc_switch_kind_name(kind)), true)
11141 });
11142 PioDcEquipmentView {
11143 component: component_id_view(component),
11144 equipment_container,
11145 has_equipment_container,
11146 kind: PioStringView::new(kind),
11147 terminal_count: usize::from(terminal2.is_some()) + 1,
11148 terminal1: dc_terminal_view(terminal1),
11149 terminal2: terminal2.map_or_else(empty_dc_terminal_view, dc_terminal_view),
11150 rated_dc_voltage_kv: rated_dc_voltage_kv.unwrap_or(0.0),
11151 has_rated_dc_voltage: rated_dc_voltage_kv.is_some(),
11152 resistance_ohm: resistance_ohm.unwrap_or(0.0),
11153 has_resistance: resistance_ohm.is_some(),
11154 inductance_h: inductance_h.unwrap_or(0.0),
11155 has_inductance: inductance_h.is_some(),
11156 capacitance_f: capacitance_f.unwrap_or(0.0),
11157 has_capacitance: capacitance_f.is_some(),
11158 length_km: length_km.unwrap_or(0.0),
11159 has_length: length_km.is_some(),
11160 switch_kind,
11161 has_switch_kind,
11162 open: open.unwrap_or(false),
11163 has_open: open.is_some(),
11164 }
11165}
11166
11167#[unsafe(no_mangle)]
11172pub unsafe extern "C" fn pio_detailed_connectivity_omitted_field_at(
11173 details: *const PioDetailedConnectivity,
11174 index: usize,
11175 output: *mut PioOmittedFieldView,
11176 error: *mut *mut PioError,
11177) -> bool {
11178 unsafe {
11179 entry(error, false, || {
11180 let details = require_detailed_connectivity(details)?;
11181 let field = details.omitted_fields.get(index).ok_or_else(|| {
11182 boundary_error(
11183 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
11184 format!("omitted field index {index} is out of range"),
11185 )
11186 })?;
11187 *require_output(output, "output")? = PioOmittedFieldView {
11188 component: component_id_view(&field.component),
11189 field: PioStringView::new(omitted_field_name(field.field)),
11190 };
11191 Ok(true)
11192 })
11193 }
11194}
11195
11196#[unsafe(no_mangle)]
11201pub unsafe extern "C" fn pio_detailed_connectivity_component_metadata_at(
11202 details: *const PioDetailedConnectivity,
11203 index: usize,
11204 output: *mut PioComponentMetadataView,
11205 error: *mut *mut PioError,
11206) -> bool {
11207 unsafe {
11208 entry(error, false, || {
11209 let details = require_detailed_connectivity(details)?;
11210 let metadata = details.component_metadata.get(index).ok_or_else(|| {
11211 boundary_error(
11212 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
11213 format!("component metadata index {index} is out of range"),
11214 )
11215 })?;
11216 let (name, has_name) = optional_string_view(metadata.name.as_deref());
11217 let (equipment_container, has_equipment_container) =
11218 optional_component_id_view(metadata.equipment_container.as_ref());
11219 *require_output(output, "output")? = PioComponentMetadataView {
11220 component: component_id_view(&metadata.component),
11221 name,
11222 has_name,
11223 equipment_container,
11224 has_equipment_container,
11225 fictitious: metadata.fictitious,
11226 alias_count: metadata.aliases.len(),
11227 external_identifier_count: metadata.external_identifiers.len(),
11228 property_count: metadata.properties.len(),
11229 };
11230 Ok(true)
11231 })
11232 }
11233}
11234
11235#[unsafe(no_mangle)]
11240pub unsafe extern "C" fn pio_detailed_connectivity_component_alias_at(
11241 details: *const PioDetailedConnectivity,
11242 metadata_index: usize,
11243 alias_index: usize,
11244 output: *mut PioComponentAliasView,
11245 error: *mut *mut PioError,
11246) -> bool {
11247 unsafe {
11248 entry(error, false, || {
11249 let details = require_detailed_connectivity(details)?;
11250 let metadata = details
11251 .component_metadata
11252 .get(metadata_index)
11253 .ok_or_else(|| {
11254 boundary_error(
11255 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
11256 format!("component metadata index {metadata_index} is out of range"),
11257 )
11258 })?;
11259 let alias = metadata.aliases.get(alias_index).ok_or_else(|| {
11260 boundary_error(
11261 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
11262 format!("component alias index {alias_index} is out of range"),
11263 )
11264 })?;
11265 let (alias_type, has_alias_type) = optional_string_view(alias.alias_type.as_deref());
11266 *require_output(output, "output")? = PioComponentAliasView {
11267 value: PioStringView::new(&alias.value),
11268 alias_type,
11269 has_alias_type,
11270 };
11271 Ok(true)
11272 })
11273 }
11274}
11275
11276#[unsafe(no_mangle)]
11281pub unsafe extern "C" fn pio_detailed_connectivity_external_identifier_at(
11282 details: *const PioDetailedConnectivity,
11283 metadata_index: usize,
11284 identifier_index: usize,
11285 output: *mut PioExternalIdentifierView,
11286 error: *mut *mut PioError,
11287) -> bool {
11288 unsafe {
11289 entry(error, false, || {
11290 let details = require_detailed_connectivity(details)?;
11291 let metadata = details
11292 .component_metadata
11293 .get(metadata_index)
11294 .ok_or_else(|| {
11295 boundary_error(
11296 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
11297 format!("component metadata index {metadata_index} is out of range"),
11298 )
11299 })?;
11300 let identifier = metadata
11301 .external_identifiers
11302 .get(identifier_index)
11303 .ok_or_else(|| {
11304 boundary_error(
11305 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
11306 format!("external identifier index {identifier_index} is out of range"),
11307 )
11308 })?;
11309 let (authority, has_authority) = optional_string_view(identifier.authority.as_deref());
11310 *require_output(output, "output")? = PioExternalIdentifierView {
11311 value: PioStringView::new(&identifier.value),
11312 authority,
11313 has_authority,
11314 };
11315 Ok(true)
11316 })
11317 }
11318}
11319
11320#[unsafe(no_mangle)]
11325pub unsafe extern "C" fn pio_detailed_connectivity_component_property_at(
11326 details: *const PioDetailedConnectivity,
11327 metadata_index: usize,
11328 property_index: usize,
11329 output: *mut PioStringPropertyView,
11330 error: *mut *mut PioError,
11331) -> bool {
11332 unsafe {
11333 entry(error, false, || {
11334 let details = require_detailed_connectivity(details)?;
11335 let metadata = details
11336 .component_metadata
11337 .get(metadata_index)
11338 .ok_or_else(|| {
11339 boundary_error(
11340 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
11341 format!("component metadata index {metadata_index} is out of range"),
11342 )
11343 })?;
11344 let (name, value) =
11345 metadata
11346 .properties
11347 .iter()
11348 .nth(property_index)
11349 .ok_or_else(|| {
11350 boundary_error(
11351 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
11352 format!("component property index {property_index} is out of range"),
11353 )
11354 })?;
11355 *require_output(output, "output")? = PioStringPropertyView {
11356 name: PioStringView::new(name),
11357 value: PioStringView::new(value),
11358 };
11359 Ok(true)
11360 })
11361 }
11362}
11363
11364fn case_metadata_view(metadata: &powerio_tx::CaseMetadata) -> PioCaseMetadataView {
11365 let (case_date, has_case_date) = optional_string_view(metadata.case_date.as_deref());
11366 let (source_model_format, has_source_model_format) =
11367 optional_string_view(metadata.source_model_format.as_deref());
11368 let (minimum_validation_level, has_minimum_validation_level) =
11369 optional_string_view(metadata.minimum_validation_level.as_deref());
11370 PioCaseMetadataView {
11371 case_date,
11372 has_case_date,
11373 forecast_distance: metadata.forecast_distance.unwrap_or(0),
11374 has_forecast_distance: metadata.forecast_distance.is_some(),
11375 source_model_format,
11376 has_source_model_format,
11377 minimum_validation_level,
11378 has_minimum_validation_level,
11379 }
11380}
11381
11382#[unsafe(no_mangle)]
11387pub unsafe extern "C" fn pio_detailed_connectivity_subnetwork_at(
11388 details: *const PioDetailedConnectivity,
11389 index: usize,
11390 output: *mut PioSubnetworkView,
11391 error: *mut *mut PioError,
11392) -> bool {
11393 unsafe {
11394 entry(error, false, || {
11395 let details = require_detailed_connectivity(details)?;
11396 let subnetwork = details.subnetworks.get(index).ok_or_else(|| {
11397 boundary_error(
11398 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
11399 format!("subnetwork index {index} is out of range"),
11400 )
11401 })?;
11402 *require_output(output, "output")? = PioSubnetworkView {
11403 component: component_id_view(&subnetwork.component),
11404 parent: component_id_view(&subnetwork.parent),
11405 case_metadata: case_metadata_view(&subnetwork.case_metadata),
11406 component_count: subnetwork.components.len(),
11407 };
11408 Ok(true)
11409 })
11410 }
11411}
11412
11413#[unsafe(no_mangle)]
11418pub unsafe extern "C" fn pio_detailed_connectivity_subnetwork_component_at(
11419 details: *const PioDetailedConnectivity,
11420 subnetwork_index: usize,
11421 component_index: usize,
11422 output: *mut PioComponentIdView,
11423 error: *mut *mut PioError,
11424) -> bool {
11425 unsafe {
11426 entry(error, false, || {
11427 let details = require_detailed_connectivity(details)?;
11428 let subnetwork = details.subnetworks.get(subnetwork_index).ok_or_else(|| {
11429 boundary_error(
11430 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
11431 format!("subnetwork index {subnetwork_index} is out of range"),
11432 )
11433 })?;
11434 let component = subnetwork.components.get(component_index).ok_or_else(|| {
11435 boundary_error(
11436 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
11437 format!("subnetwork component index {component_index} is out of range"),
11438 )
11439 })?;
11440 *require_output(output, "output")? = component_id_view(component);
11441 Ok(true)
11442 })
11443 }
11444}
11445
11446#[unsafe(no_mangle)]
11451pub unsafe extern "C" fn pio_detailed_connectivity_substation_at(
11452 details: *const PioDetailedConnectivity,
11453 index: usize,
11454 output: *mut PioSubstationView,
11455 error: *mut *mut PioError,
11456) -> bool {
11457 unsafe {
11458 entry(error, false, || {
11459 let details = require_detailed_connectivity(details)?;
11460 let substation = details.substations.get(index).ok_or_else(|| {
11461 boundary_error(
11462 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
11463 format!("substation index {index} is out of range"),
11464 )
11465 })?;
11466 let (country, has_country) = optional_string_view(substation.country.as_deref());
11467 let (operator_name, has_operator_name) =
11468 optional_string_view(substation.operator.as_deref());
11469 *require_output(output, "output")? = PioSubstationView {
11470 component: component_id_view(&substation.component),
11471 country,
11472 has_country,
11473 operator_name,
11474 has_operator_name,
11475 geographical_tag_count: substation.geographical_tags.len(),
11476 };
11477 Ok(true)
11478 })
11479 }
11480}
11481
11482#[unsafe(no_mangle)]
11487pub unsafe extern "C" fn pio_detailed_connectivity_substation_geographical_tag_at(
11488 details: *const PioDetailedConnectivity,
11489 substation_index: usize,
11490 tag_index: usize,
11491 output: *mut PioStringView,
11492 error: *mut *mut PioError,
11493) -> bool {
11494 unsafe {
11495 entry(error, false, || {
11496 let details = require_detailed_connectivity(details)?;
11497 let substation = details.substations.get(substation_index).ok_or_else(|| {
11498 boundary_error(
11499 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
11500 format!("substation index {substation_index} is out of range"),
11501 )
11502 })?;
11503 let tag = substation.geographical_tags.get(tag_index).ok_or_else(|| {
11504 boundary_error(
11505 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
11506 format!("geographical tag index {tag_index} is out of range"),
11507 )
11508 })?;
11509 *require_output(output, "output")? = PioStringView::new(tag);
11510 Ok(true)
11511 })
11512 }
11513}
11514
11515#[unsafe(no_mangle)]
11520pub unsafe extern "C" fn pio_detailed_connectivity_voltage_level_at(
11521 details: *const PioDetailedConnectivity,
11522 index: usize,
11523 output: *mut PioVoltageLevelView,
11524 error: *mut *mut PioError,
11525) -> bool {
11526 unsafe {
11527 entry(error, false, || {
11528 let details = require_detailed_connectivity(details)?;
11529 let level = details.voltage_levels.get(index).ok_or_else(|| {
11530 boundary_error(
11531 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
11532 format!("voltage level index {index} is out of range"),
11533 )
11534 })?;
11535 let (substation, has_substation) =
11536 optional_component_id_view(level.substation.as_ref());
11537 *require_output(output, "output")? = PioVoltageLevelView {
11538 component: component_id_view(&level.component),
11539 substation,
11540 has_substation,
11541 nominal_voltage_kv: level.nominal_kv,
11542 low_voltage_limit_kv: level.low_voltage_limit_kv.unwrap_or(0.0),
11543 has_low_voltage_limit: level.low_voltage_limit_kv.is_some(),
11544 high_voltage_limit_kv: level.high_voltage_limit_kv.unwrap_or(0.0),
11545 has_high_voltage_limit: level.high_voltage_limit_kv.is_some(),
11546 topology_kind: PioStringView::new(topology_kind_name(level.topology_kind)),
11547 bus_count: level.buses.len(),
11548 };
11549 Ok(true)
11550 })
11551 }
11552}
11553
11554#[unsafe(no_mangle)]
11559pub unsafe extern "C" fn pio_detailed_connectivity_voltage_level_bus_at(
11560 details: *const PioDetailedConnectivity,
11561 voltage_level_index: usize,
11562 bus_index: usize,
11563 output: *mut usize,
11564 error: *mut *mut PioError,
11565) -> bool {
11566 unsafe {
11567 entry(error, false, || {
11568 let details = require_detailed_connectivity(details)?;
11569 let level = details
11570 .voltage_levels
11571 .get(voltage_level_index)
11572 .ok_or_else(|| {
11573 boundary_error(
11574 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
11575 format!("voltage level index {voltage_level_index} is out of range"),
11576 )
11577 })?;
11578 let bus = level.buses.get(bus_index).ok_or_else(|| {
11579 boundary_error(
11580 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
11581 format!("voltage level bus index {bus_index} is out of range"),
11582 )
11583 })?;
11584 *require_output(output, "output")? = bus.0;
11585 Ok(true)
11586 })
11587 }
11588}
11589
11590#[unsafe(no_mangle)]
11595pub unsafe extern "C" fn pio_detailed_connectivity_bus_breaker_bus_at(
11596 details: *const PioDetailedConnectivity,
11597 index: usize,
11598 output: *mut PioBusBreakerBusView,
11599 error: *mut *mut PioError,
11600) -> bool {
11601 unsafe {
11602 entry(error, false, || {
11603 let details = require_detailed_connectivity(details)?;
11604 let bus = details.bus_breaker_buses.get(index).ok_or_else(|| {
11605 boundary_error(
11606 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
11607 format!("bus breaker bus index {index} is out of range"),
11608 )
11609 })?;
11610 *require_output(output, "output")? = PioBusBreakerBusView {
11611 component: component_id_view(&bus.component),
11612 voltage_level: component_id_view(&bus.voltage_level),
11613 calculated_bus_id: bus.calculated_bus.map_or(0, |value| value.0),
11614 has_calculated_bus: bus.calculated_bus.is_some(),
11615 voltage_kv: bus.voltage_kv.unwrap_or(0.0),
11616 has_voltage: bus.voltage_kv.is_some(),
11617 angle_degrees: bus.angle_degrees.unwrap_or(0.0),
11618 has_angle: bus.angle_degrees.is_some(),
11619 };
11620 Ok(true)
11621 })
11622 }
11623}
11624
11625#[unsafe(no_mangle)]
11630pub unsafe extern "C" fn pio_detailed_connectivity_calculated_bus_at(
11631 details: *const PioDetailedConnectivity,
11632 index: usize,
11633 output: *mut PioCalculatedBusView,
11634 error: *mut *mut PioError,
11635) -> bool {
11636 unsafe {
11637 entry(error, false, || {
11638 let details = require_detailed_connectivity(details)?;
11639 let bus = details.calculated_buses.get(index).ok_or_else(|| {
11640 boundary_error(
11641 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
11642 format!("calculated bus index {index} is out of range"),
11643 )
11644 })?;
11645 *require_output(output, "output")? = PioCalculatedBusView {
11646 voltage_level: component_id_view(&bus.voltage_level),
11647 calculated_bus_id: bus.calculated_bus.0,
11648 node_count: bus.nodes.len(),
11649 voltage_kv: bus.voltage_kv.unwrap_or(0.0),
11650 has_voltage: bus.voltage_kv.is_some(),
11651 angle_degrees: bus.angle_degrees.unwrap_or(0.0),
11652 has_angle: bus.angle_degrees.is_some(),
11653 };
11654 Ok(true)
11655 })
11656 }
11657}
11658
11659#[unsafe(no_mangle)]
11664pub unsafe extern "C" fn pio_detailed_connectivity_calculated_bus_node_at(
11665 details: *const PioDetailedConnectivity,
11666 calculated_bus_index: usize,
11667 node_index: usize,
11668 output: *mut PioComponentIdView,
11669 error: *mut *mut PioError,
11670) -> bool {
11671 unsafe {
11672 entry(error, false, || {
11673 let details = require_detailed_connectivity(details)?;
11674 let bus = details
11675 .calculated_buses
11676 .get(calculated_bus_index)
11677 .ok_or_else(|| {
11678 boundary_error(
11679 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
11680 format!("calculated bus index {calculated_bus_index} is out of range"),
11681 )
11682 })?;
11683 let node = bus.nodes.get(node_index).ok_or_else(|| {
11684 boundary_error(
11685 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
11686 format!("calculated bus node index {node_index} is out of range"),
11687 )
11688 })?;
11689 *require_output(output, "output")? = component_id_view(node);
11690 Ok(true)
11691 })
11692 }
11693}
11694
11695#[unsafe(no_mangle)]
11700pub unsafe extern "C" fn pio_detailed_connectivity_node_at(
11701 details: *const PioDetailedConnectivity,
11702 index: usize,
11703 output: *mut PioConnectivityNodeView,
11704 error: *mut *mut PioError,
11705) -> bool {
11706 unsafe {
11707 entry(error, false, || {
11708 let details = require_detailed_connectivity(details)?;
11709 let node = details.connectivity_nodes.get(index).ok_or_else(|| {
11710 boundary_error(
11711 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
11712 format!("connectivity node index {index} is out of range"),
11713 )
11714 })?;
11715 *require_output(output, "output")? = PioConnectivityNodeView {
11716 component: component_id_view(&node.component),
11717 voltage_level: component_id_view(&node.voltage_level),
11718 node_number: node.node_number.unwrap_or(0),
11719 has_node_number: node.node_number.is_some(),
11720 calculated_bus_id: node.calculated_bus.map_or(0, |bus| bus.0),
11721 has_calculated_bus: node.calculated_bus.is_some(),
11722 };
11723 Ok(true)
11724 })
11725 }
11726}
11727
11728#[unsafe(no_mangle)]
11733pub unsafe extern "C" fn pio_detailed_connectivity_busbar_section_at(
11734 details: *const PioDetailedConnectivity,
11735 index: usize,
11736 output: *mut PioBusbarSectionView,
11737 error: *mut *mut PioError,
11738) -> bool {
11739 unsafe {
11740 entry(error, false, || {
11741 let details = require_detailed_connectivity(details)?;
11742 let section = details.busbar_sections.get(index).ok_or_else(|| {
11743 boundary_error(
11744 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
11745 format!("busbar section index {index} is out of range"),
11746 )
11747 })?;
11748 *require_output(output, "output")? = PioBusbarSectionView {
11749 component: component_id_view(§ion.component),
11750 voltage_level: component_id_view(§ion.voltage_level),
11751 node: component_id_view(§ion.node),
11752 };
11753 Ok(true)
11754 })
11755 }
11756}
11757
11758#[unsafe(no_mangle)]
11763pub unsafe extern "C" fn pio_detailed_connectivity_junction_at(
11764 details: *const PioDetailedConnectivity,
11765 index: usize,
11766 output: *mut PioJunctionView,
11767 error: *mut *mut PioError,
11768) -> bool {
11769 unsafe {
11770 entry(error, false, || {
11771 let details = require_detailed_connectivity(details)?;
11772 let junction = details.junctions.get(index).ok_or_else(|| {
11773 boundary_error(
11774 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
11775 format!("junction index {index} is out of range"),
11776 )
11777 })?;
11778 *require_output(output, "output")? = PioJunctionView {
11779 component: component_id_view(&junction.component),
11780 };
11781 Ok(true)
11782 })
11783 }
11784}
11785
11786#[unsafe(no_mangle)]
11791pub unsafe extern "C" fn pio_detailed_connectivity_terminal_at(
11792 details: *const PioDetailedConnectivity,
11793 index: usize,
11794 output: *mut PioDetailedTerminalView,
11795 error: *mut *mut PioError,
11796) -> bool {
11797 unsafe {
11798 entry(error, false, || {
11799 let details = require_detailed_connectivity(details)?;
11800 let terminal = details.terminals.get(index).ok_or_else(|| {
11801 boundary_error(
11802 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
11803 format!("terminal index {index} is out of range"),
11804 )
11805 })?;
11806 let (bus, has_bus) = optional_component_id_view(terminal.bus.as_ref());
11807 let (connectable_bus, has_connectable_bus) =
11808 optional_component_id_view(terminal.connectable_bus.as_ref());
11809 let (node, has_node) = optional_component_id_view(terminal.node.as_ref());
11810 let (component, has_component) =
11811 optional_component_id_view(terminal.component.as_ref());
11812 *require_output(output, "output")? = PioDetailedTerminalView {
11813 component,
11814 has_component,
11815 equipment: component_id_view(&terminal.equipment),
11816 terminal: terminal.terminal,
11817 voltage_level: component_id_view(&terminal.voltage_level),
11818 bus,
11819 has_bus,
11820 connectable_bus,
11821 has_connectable_bus,
11822 node,
11823 has_node,
11824 connected: terminal.connected,
11825 active_power_mw: terminal.active_power_mw.unwrap_or(0.0),
11826 has_active_power: terminal.active_power_mw.is_some(),
11827 reactive_power_mvar: terminal.reactive_power_mvar.unwrap_or(0.0),
11828 has_reactive_power: terminal.reactive_power_mvar.is_some(),
11829 };
11830 Ok(true)
11831 })
11832 }
11833}
11834
11835#[unsafe(no_mangle)]
11840pub unsafe extern "C" fn pio_detailed_connectivity_switch_at(
11841 details: *const PioDetailedConnectivity,
11842 index: usize,
11843 output: *mut PioTopologySwitchView,
11844 error: *mut *mut PioError,
11845) -> bool {
11846 unsafe {
11847 entry(error, false, || {
11848 let details = require_detailed_connectivity(details)?;
11849 let switch = details.switches.get(index).ok_or_else(|| {
11850 boundary_error(
11851 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
11852 format!("topology switch index {index} is out of range"),
11853 )
11854 })?;
11855 let (endpoint1_kind, endpoint1) = topology_endpoint_view(&switch.endpoint1);
11856 let (endpoint2_kind, endpoint2) = topology_endpoint_view(&switch.endpoint2);
11857 *require_output(output, "output")? = PioTopologySwitchView {
11858 component: component_id_view(&switch.component),
11859 voltage_level: component_id_view(&switch.voltage_level),
11860 kind: PioStringView::new(topology_switch_kind_name(switch.kind)),
11861 endpoint1_kind,
11862 endpoint1,
11863 endpoint2_kind,
11864 endpoint2,
11865 open: switch.open,
11866 retained: switch.retained,
11867 };
11868 Ok(true)
11869 })
11870 }
11871}
11872
11873#[unsafe(no_mangle)]
11878pub unsafe extern "C" fn pio_detailed_connectivity_internal_connection_at(
11879 details: *const PioDetailedConnectivity,
11880 index: usize,
11881 output: *mut PioInternalConnectionView,
11882 error: *mut *mut PioError,
11883) -> bool {
11884 unsafe {
11885 entry(error, false, || {
11886 let details = require_detailed_connectivity(details)?;
11887 let connection = details.internal_connections.get(index).ok_or_else(|| {
11888 boundary_error(
11889 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
11890 format!("internal connection index {index} is out of range"),
11891 )
11892 })?;
11893 *require_output(output, "output")? = PioInternalConnectionView {
11894 voltage_level: component_id_view(&connection.voltage_level),
11895 node1: component_id_view(&connection.node1),
11896 node2: component_id_view(&connection.node2),
11897 };
11898 Ok(true)
11899 })
11900 }
11901}
11902
11903#[unsafe(no_mangle)]
11908pub unsafe extern "C" fn pio_detailed_connectivity_operational_limit_group_at(
11909 details: *const PioDetailedConnectivity,
11910 index: usize,
11911 output: *mut PioOperationalLimitGroupView,
11912 error: *mut *mut PioError,
11913) -> bool {
11914 unsafe {
11915 entry(error, false, || {
11916 let details = require_detailed_connectivity(details)?;
11917 let group = details.operational_limit_groups.get(index).ok_or_else(|| {
11918 boundary_error(
11919 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
11920 format!("operational limit group index {index} is out of range"),
11921 )
11922 })?;
11923 let current = group.current_limits.as_ref();
11924 let active = group.active_power_limits.as_ref();
11925 let apparent = group.apparent_power_limits.as_ref();
11926 let (current_name, has_current_name) = optional_string_view(
11927 current.and_then(|limits| limits.permanent_limit_name.as_deref()),
11928 );
11929 let (active_name, has_active_name) = optional_string_view(
11930 active.and_then(|limits| limits.permanent_limit_name.as_deref()),
11931 );
11932 let (apparent_name, has_apparent_name) = optional_string_view(
11933 apparent.and_then(|limits| limits.permanent_limit_name.as_deref()),
11934 );
11935 *require_output(output, "output")? = PioOperationalLimitGroupView {
11936 equipment: component_id_view(&group.equipment),
11937 terminal: group.terminal,
11938 id: PioStringView::new(&group.id),
11939 selected: group.selected,
11940 property_count: group.properties.len(),
11941 has_current_limits: current.is_some(),
11942 current_permanent_limit_a: current
11943 .and_then(|limits| limits.permanent_limit)
11944 .unwrap_or(0.0),
11945 current_permanent_limit_name: current_name,
11946 has_current_permanent_limit: current
11947 .is_some_and(|limits| limits.permanent_limit.is_some()),
11948 has_current_permanent_limit_name: has_current_name,
11949 current_temporary_limit_count: current
11950 .map_or(0, |limits| limits.temporary_limits.len()),
11951 has_active_power_limits: active.is_some(),
11952 active_power_permanent_limit_mw: active
11953 .and_then(|limits| limits.permanent_limit)
11954 .unwrap_or(0.0),
11955 active_power_permanent_limit_name: active_name,
11956 has_active_power_permanent_limit: active
11957 .is_some_and(|limits| limits.permanent_limit.is_some()),
11958 has_active_power_permanent_limit_name: has_active_name,
11959 active_power_temporary_limit_count: active
11960 .map_or(0, |limits| limits.temporary_limits.len()),
11961 has_apparent_power_limits: apparent.is_some(),
11962 apparent_power_permanent_limit_mva: apparent
11963 .and_then(|limits| limits.permanent_limit)
11964 .unwrap_or(0.0),
11965 apparent_power_permanent_limit_name: apparent_name,
11966 has_apparent_power_permanent_limit: apparent
11967 .is_some_and(|limits| limits.permanent_limit.is_some()),
11968 has_apparent_power_permanent_limit_name: has_apparent_name,
11969 apparent_power_temporary_limit_count: apparent
11970 .map_or(0, |limits| limits.temporary_limits.len()),
11971 };
11972 Ok(true)
11973 })
11974 }
11975}
11976
11977#[unsafe(no_mangle)]
11982pub unsafe extern "C" fn pio_detailed_connectivity_operational_limit_group_property_at(
11983 details: *const PioDetailedConnectivity,
11984 group_index: usize,
11985 property_index: usize,
11986 output: *mut PioStringPropertyView,
11987 error: *mut *mut PioError,
11988) -> bool {
11989 unsafe {
11990 entry(error, false, || {
11991 let details = require_detailed_connectivity(details)?;
11992 let group = details
11993 .operational_limit_groups
11994 .get(group_index)
11995 .ok_or_else(|| {
11996 boundary_error(
11997 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
11998 format!("operational limit group index {group_index} is out of range"),
11999 )
12000 })?;
12001 *require_output(output, "output")? =
12002 string_property_view(&group.properties, property_index)?;
12003 Ok(true)
12004 })
12005 }
12006}
12007
12008#[unsafe(no_mangle)]
12013pub unsafe extern "C" fn pio_detailed_connectivity_temporary_limit_at(
12014 details: *const PioDetailedConnectivity,
12015 group_index: usize,
12016 quantity: *const c_char,
12017 quantity_len: usize,
12018 limit_index: usize,
12019 output: *mut PioTemporaryLimitView,
12020 error: *mut *mut PioError,
12021) -> bool {
12022 unsafe {
12023 entry(error, false, || {
12024 let details = require_detailed_connectivity(details)?;
12025 let group = details
12026 .operational_limit_groups
12027 .get(group_index)
12028 .ok_or_else(|| {
12029 boundary_error(
12030 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
12031 format!("operational limit group index {group_index} is out of range"),
12032 )
12033 })?;
12034 let quantity = required_str(quantity, quantity_len, "quantity")?;
12035 let limits = match quantity {
12036 "current" => group.current_limits.as_ref(),
12037 "active_power" => group.active_power_limits.as_ref(),
12038 "apparent_power" => group.apparent_power_limits.as_ref(),
12039 _ => {
12040 return Err(boundary_error(
12041 &codes::REQUEST_CAPI_QUANTITY_UNKNOWN,
12042 "quantity must be current, active_power, or apparent_power",
12043 ));
12044 }
12045 }
12046 .ok_or_else(|| {
12047 boundary_error(
12048 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
12049 format!("operational limit group {group_index} has no {quantity} limits"),
12050 )
12051 })?;
12052 let limit = limits.temporary_limits.get(limit_index).ok_or_else(|| {
12053 boundary_error(
12054 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
12055 format!("temporary limit index {limit_index} is out of range"),
12056 )
12057 })?;
12058 *require_output(output, "output")? = PioTemporaryLimitView {
12059 name: PioStringView::new(&limit.name),
12060 value: limit.value,
12061 acceptable_duration_seconds: limit.acceptable_duration_seconds,
12062 fictitious: limit.fictitious,
12063 };
12064 Ok(true)
12065 })
12066 }
12067}
12068
12069#[unsafe(no_mangle)]
12074pub unsafe extern "C" fn pio_detailed_connectivity_boundary_line_at(
12075 details: *const PioDetailedConnectivity,
12076 index: usize,
12077 output: *mut PioBoundaryLineView,
12078 error: *mut *mut PioError,
12079) -> bool {
12080 unsafe {
12081 entry(error, false, || {
12082 let details = require_detailed_connectivity(details)?;
12083 let line = details.boundary_lines.get(index).ok_or_else(|| {
12084 boundary_error(
12085 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
12086 format!("boundary line index {index} is out of range"),
12087 )
12088 })?;
12089 let (pairing_key, has_pairing_key) = optional_string_view(line.pairing_key.as_deref());
12090 let (generation, has_generation) =
12091 boundary_line_generation_view(line.generation.as_ref());
12092 let (calculation_load, has_calculation_load) =
12093 optional_component_id_view(line.calculation_load.as_ref());
12094 let (calculation_generator, has_calculation_generator) =
12095 optional_component_id_view(line.calculation_generator.as_ref());
12096 *require_output(output, "output")? = PioBoundaryLineView {
12097 component: component_id_view(&line.component),
12098 voltage_level: component_id_view(&line.voltage_level),
12099 active_power_setpoint_mw: line.active_power_setpoint_mw,
12100 reactive_power_setpoint_mvar: line.reactive_power_setpoint_mvar,
12101 resistance_ohm: line.resistance_ohm,
12102 reactance_ohm: line.reactance_ohm,
12103 conductance_siemens: line.conductance_siemens,
12104 susceptance_siemens: line.susceptance_siemens,
12105 pairing_key,
12106 has_pairing_key,
12107 generation,
12108 has_generation,
12109 calculation_load,
12110 has_calculation_load,
12111 calculation_generator,
12112 has_calculation_generator,
12113 };
12114 Ok(true)
12115 })
12116 }
12117}
12118
12119#[unsafe(no_mangle)]
12124pub unsafe extern "C" fn pio_detailed_connectivity_boundary_line_reactive_limit_property_at(
12125 details: *const PioDetailedConnectivity,
12126 boundary_line_index: usize,
12127 property_index: usize,
12128 output: *mut PioStringPropertyView,
12129 error: *mut *mut PioError,
12130) -> bool {
12131 unsafe {
12132 entry(error, false, || {
12133 let details = require_detailed_connectivity(details)?;
12134 let line = details
12135 .boundary_lines
12136 .get(boundary_line_index)
12137 .ok_or_else(|| {
12138 boundary_error(
12139 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
12140 format!("boundary line index {boundary_line_index} is out of range"),
12141 )
12142 })?;
12143 let limits = line
12144 .generation
12145 .as_ref()
12146 .and_then(|generation| generation.reactive_limits.as_ref())
12147 .ok_or_else(|| {
12148 boundary_error(
12149 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
12150 format!(
12151 "boundary line {boundary_line_index} has no generation reactive limits"
12152 ),
12153 )
12154 })?;
12155 let properties = match limits {
12156 powerio_tx::ReactiveLimits::MinMax(limits) => &limits.properties,
12157 powerio_tx::ReactiveLimits::CapabilityCurve(curve) => &curve.properties,
12158 _ => {
12159 return Err(boundary_error(
12160 &codes::REQUEST_CAPI_TYPE_MISMATCH,
12161 "unsupported reactive limit record",
12162 ));
12163 }
12164 };
12165 let (name, value) = properties.iter().nth(property_index).ok_or_else(|| {
12166 boundary_error(
12167 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
12168 format!("reactive limit property index {property_index} is out of range"),
12169 )
12170 })?;
12171 *require_output(output, "output")? = PioStringPropertyView {
12172 name: PioStringView::new(name),
12173 value: PioStringView::new(value),
12174 };
12175 Ok(true)
12176 })
12177 }
12178}
12179
12180#[unsafe(no_mangle)]
12185pub unsafe extern "C" fn pio_detailed_connectivity_boundary_line_reactive_capability_point_at(
12186 details: *const PioDetailedConnectivity,
12187 boundary_line_index: usize,
12188 point_index: usize,
12189 output: *mut PioReactiveCapabilityCurvePointView,
12190 error: *mut *mut PioError,
12191) -> bool {
12192 unsafe {
12193 entry(error, false, || {
12194 let details = require_detailed_connectivity(details)?;
12195 let line = details
12196 .boundary_lines
12197 .get(boundary_line_index)
12198 .ok_or_else(|| {
12199 boundary_error(
12200 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
12201 format!("boundary line index {boundary_line_index} is out of range"),
12202 )
12203 })?;
12204 let curve = line
12205 .generation
12206 .as_ref()
12207 .and_then(|generation| generation.reactive_limits.as_ref())
12208 .and_then(|limits| match limits {
12209 powerio_tx::ReactiveLimits::CapabilityCurve(curve) => Some(curve),
12210 _ => None,
12211 })
12212 .ok_or_else(|| {
12213 boundary_error(
12214 &codes::REQUEST_CAPI_TYPE_MISMATCH,
12215 format!(
12216 "boundary line {boundary_line_index} has no generation reactive capability curve"
12217 ),
12218 )
12219 })?;
12220 let point = curve.points.get(point_index).ok_or_else(|| {
12221 boundary_error(
12222 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
12223 format!("reactive capability point index {point_index} is out of range"),
12224 )
12225 })?;
12226 *require_output(output, "output")? = PioReactiveCapabilityCurvePointView {
12227 active_power_mw: point.active_power_mw,
12228 minimum_reactive_power_mvar: point.minimum_reactive_power_mvar,
12229 maximum_reactive_power_mvar: point.maximum_reactive_power_mvar,
12230 property_count: point.properties.len(),
12231 };
12232 Ok(true)
12233 })
12234 }
12235}
12236
12237#[unsafe(no_mangle)]
12242pub unsafe extern "C" fn pio_detailed_connectivity_boundary_line_reactive_capability_point_property_at(
12243 details: *const PioDetailedConnectivity,
12244 boundary_line_index: usize,
12245 point_index: usize,
12246 property_index: usize,
12247 output: *mut PioStringPropertyView,
12248 error: *mut *mut PioError,
12249) -> bool {
12250 unsafe {
12251 entry(error, false, || {
12252 let details = require_detailed_connectivity(details)?;
12253 let line = details
12254 .boundary_lines
12255 .get(boundary_line_index)
12256 .ok_or_else(|| {
12257 boundary_error(
12258 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
12259 format!("boundary line index {boundary_line_index} is out of range"),
12260 )
12261 })?;
12262 let curve = line
12263 .generation
12264 .as_ref()
12265 .and_then(|generation| generation.reactive_limits.as_ref())
12266 .and_then(|limits| match limits {
12267 powerio_tx::ReactiveLimits::CapabilityCurve(curve) => Some(curve),
12268 _ => None,
12269 })
12270 .ok_or_else(|| {
12271 boundary_error(
12272 &codes::REQUEST_CAPI_TYPE_MISMATCH,
12273 format!(
12274 "boundary line {boundary_line_index} has no generation reactive capability curve"
12275 ),
12276 )
12277 })?;
12278 let point = curve.points.get(point_index).ok_or_else(|| {
12279 boundary_error(
12280 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
12281 format!("reactive capability point index {point_index} is out of range"),
12282 )
12283 })?;
12284 let (name, value) = point.properties.iter().nth(property_index).ok_or_else(|| {
12285 boundary_error(
12286 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
12287 format!(
12288 "reactive capability point property index {property_index} is out of range"
12289 ),
12290 )
12291 })?;
12292 *require_output(output, "output")? = PioStringPropertyView {
12293 name: PioStringView::new(name),
12294 value: PioStringView::new(value),
12295 };
12296 Ok(true)
12297 })
12298 }
12299}
12300
12301#[unsafe(no_mangle)]
12306pub unsafe extern "C" fn pio_detailed_connectivity_tie_line_at(
12307 details: *const PioDetailedConnectivity,
12308 index: usize,
12309 output: *mut PioTieLineView,
12310 error: *mut *mut PioError,
12311) -> bool {
12312 unsafe {
12313 entry(error, false, || {
12314 let details = require_detailed_connectivity(details)?;
12315 let tie = details.tie_lines.get(index).ok_or_else(|| {
12316 boundary_error(
12317 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
12318 format!("tie line index {index} is out of range"),
12319 )
12320 })?;
12321 let (calculation_branch, has_calculation_branch) =
12322 optional_component_id_view(tie.calculation_branch.as_ref());
12323 *require_output(output, "output")? = PioTieLineView {
12324 component: component_id_view(&tie.component),
12325 boundary_line1: component_id_view(&tie.boundary_line1),
12326 boundary_line2: component_id_view(&tie.boundary_line2),
12327 calculation_branch,
12328 has_calculation_branch,
12329 };
12330 Ok(true)
12331 })
12332 }
12333}
12334
12335#[unsafe(no_mangle)]
12340pub unsafe extern "C" fn pio_detailed_connectivity_tap_changer_at(
12341 details: *const PioDetailedConnectivity,
12342 index: usize,
12343 output: *mut PioTapChangerView,
12344 error: *mut *mut PioError,
12345) -> bool {
12346 unsafe {
12347 entry(error, false, || {
12348 let details = require_detailed_connectivity(details)?;
12349 let changer = details.tap_changers.get(index).ok_or_else(|| {
12350 boundary_error(
12351 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
12352 format!("tap changer index {index} is out of range"),
12353 )
12354 })?;
12355 let (regulation_mode, has_regulation_mode) =
12356 changer
12357 .regulation_mode
12358 .map_or((PioStringView::EMPTY, false), |mode| {
12359 (
12360 PioStringView::new(tap_changer_regulation_mode_name(mode)),
12361 true,
12362 )
12363 });
12364 let (regulation_terminal, has_regulation_terminal) =
12365 terminal_reference_view(changer.regulation_terminal.as_ref());
12366 let (component, has_component) = optional_component_id_view(changer.component.as_ref());
12367 *require_output(output, "output")? = PioTapChangerView {
12368 component,
12369 has_component,
12370 transformer: component_id_view(&changer.transformer),
12371 winding: changer.winding,
12372 kind: PioStringView::new(tap_changer_kind_name(changer.kind)),
12373 tap_position: changer.tap_position.unwrap_or(0),
12374 has_tap_position: changer.tap_position.is_some(),
12375 solved_tap_position: changer.solved_tap_position.unwrap_or(0),
12376 has_solved_tap_position: changer.solved_tap_position.is_some(),
12377 low_tap_position: changer.low_tap_position,
12378 neutral_tap_position: changer.neutral_tap_position.unwrap_or(0),
12379 has_neutral_tap_position: changer.neutral_tap_position.is_some(),
12380 normal_tap_position: changer.normal_tap_position.unwrap_or(0),
12381 has_normal_tap_position: changer.normal_tap_position.is_some(),
12382 voltage_step_increment_percent: changer
12383 .voltage_step_increment_percent
12384 .unwrap_or(0.0),
12385 has_voltage_step_increment_percent: changer
12386 .voltage_step_increment_percent
12387 .is_some(),
12388 load_tap_changing_capabilities: changer.load_tap_changing_capabilities,
12389 regulating: changer.regulating,
12390 regulation_mode,
12391 has_regulation_mode,
12392 regulation_value: changer.regulation_value.unwrap_or(0.0),
12393 has_regulation_value: changer.regulation_value.is_some(),
12394 target_deadband: changer.target_deadband.unwrap_or(0.0),
12395 has_target_deadband: changer.target_deadband.is_some(),
12396 regulation_terminal,
12397 has_regulation_terminal,
12398 step_count: changer.steps.len(),
12399 };
12400 Ok(true)
12401 })
12402 }
12403}
12404
12405#[unsafe(no_mangle)]
12410pub unsafe extern "C" fn pio_detailed_connectivity_tap_changer_step_at(
12411 details: *const PioDetailedConnectivity,
12412 tap_changer_index: usize,
12413 step_index: usize,
12414 output: *mut PioTapChangerStepView,
12415 error: *mut *mut PioError,
12416) -> bool {
12417 unsafe {
12418 entry(error, false, || {
12419 let details = require_detailed_connectivity(details)?;
12420 let changer = details.tap_changers.get(tap_changer_index).ok_or_else(|| {
12421 boundary_error(
12422 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
12423 format!("tap changer index {tap_changer_index} is out of range"),
12424 )
12425 })?;
12426 let step = changer.steps.get(step_index).ok_or_else(|| {
12427 boundary_error(
12428 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
12429 format!("tap changer step index {step_index} is out of range"),
12430 )
12431 })?;
12432 *require_output(output, "output")? = PioTapChangerStepView {
12433 position: step.position,
12434 ratio_pu: step.rho,
12435 phase_shift_degrees: step.alpha_degrees,
12436 resistance_deviation_percent: step.resistance_deviation_percent,
12437 reactance_deviation_percent: step.reactance_deviation_percent,
12438 conductance_deviation_percent: step.conductance_deviation_percent,
12439 susceptance_deviation_percent: step.susceptance_deviation_percent,
12440 };
12441 Ok(true)
12442 })
12443 }
12444}
12445
12446#[unsafe(no_mangle)]
12451pub unsafe extern "C" fn pio_detailed_connectivity_equipment_reactive_limits_at(
12452 details: *const PioDetailedConnectivity,
12453 index: usize,
12454 output: *mut PioEquipmentReactiveLimitsView,
12455 error: *mut *mut PioError,
12456) -> bool {
12457 unsafe {
12458 entry(error, false, || {
12459 let details = require_detailed_connectivity(details)?;
12460 let record = details
12461 .equipment_reactive_limits
12462 .get(index)
12463 .ok_or_else(|| {
12464 boundary_error(
12465 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
12466 format!("equipment reactive limits index {index} is out of range"),
12467 )
12468 })?;
12469 *require_output(output, "output")? = PioEquipmentReactiveLimitsView {
12470 equipment: component_id_view(&record.equipment),
12471 limits: reactive_limits_view(Some(&record.limits)).0,
12472 };
12473 Ok(true)
12474 })
12475 }
12476}
12477
12478#[unsafe(no_mangle)]
12483pub unsafe extern "C" fn pio_detailed_connectivity_equipment_reactive_limit_property_at(
12484 details: *const PioDetailedConnectivity,
12485 equipment_index: usize,
12486 property_index: usize,
12487 output: *mut PioStringPropertyView,
12488 error: *mut *mut PioError,
12489) -> bool {
12490 unsafe {
12491 entry(error, false, || {
12492 let details = require_detailed_connectivity(details)?;
12493 let record = details
12494 .equipment_reactive_limits
12495 .get(equipment_index)
12496 .ok_or_else(|| {
12497 boundary_error(
12498 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
12499 format!(
12500 "equipment reactive limits index {equipment_index} is out of range"
12501 ),
12502 )
12503 })?;
12504 *require_output(output, "output")? =
12505 string_property_view(reactive_limit_properties(&record.limits)?, property_index)?;
12506 Ok(true)
12507 })
12508 }
12509}
12510
12511#[unsafe(no_mangle)]
12516pub unsafe extern "C" fn pio_detailed_connectivity_equipment_reactive_capability_point_at(
12517 details: *const PioDetailedConnectivity,
12518 equipment_index: usize,
12519 point_index: usize,
12520 output: *mut PioReactiveCapabilityCurvePointView,
12521 error: *mut *mut PioError,
12522) -> bool {
12523 unsafe {
12524 entry(error, false, || {
12525 let details = require_detailed_connectivity(details)?;
12526 let record = details
12527 .equipment_reactive_limits
12528 .get(equipment_index)
12529 .ok_or_else(|| {
12530 boundary_error(
12531 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
12532 format!(
12533 "equipment reactive limits index {equipment_index} is out of range"
12534 ),
12535 )
12536 })?;
12537 let curve = reactive_capability_curve(&record.limits).ok_or_else(|| {
12538 boundary_error(
12539 &codes::REQUEST_CAPI_TYPE_MISMATCH,
12540 format!(
12541 "equipment reactive limits {equipment_index} is not a capability curve"
12542 ),
12543 )
12544 })?;
12545 *require_output(output, "output")? =
12546 reactive_capability_point_view(curve, point_index)?;
12547 Ok(true)
12548 })
12549 }
12550}
12551
12552#[unsafe(no_mangle)]
12557pub unsafe extern "C" fn pio_detailed_connectivity_equipment_reactive_capability_point_property_at(
12558 details: *const PioDetailedConnectivity,
12559 equipment_index: usize,
12560 point_index: usize,
12561 property_index: usize,
12562 output: *mut PioStringPropertyView,
12563 error: *mut *mut PioError,
12564) -> bool {
12565 unsafe {
12566 entry(error, false, || {
12567 let details = require_detailed_connectivity(details)?;
12568 let record = details
12569 .equipment_reactive_limits
12570 .get(equipment_index)
12571 .ok_or_else(|| {
12572 boundary_error(
12573 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
12574 format!(
12575 "equipment reactive limits index {equipment_index} is out of range"
12576 ),
12577 )
12578 })?;
12579 let curve = reactive_capability_curve(&record.limits).ok_or_else(|| {
12580 boundary_error(
12581 &codes::REQUEST_CAPI_TYPE_MISMATCH,
12582 format!(
12583 "equipment reactive limits {equipment_index} is not a capability curve"
12584 ),
12585 )
12586 })?;
12587 let point = curve.points.get(point_index).ok_or_else(|| {
12588 boundary_error(
12589 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
12590 format!("reactive capability point index {point_index} is out of range"),
12591 )
12592 })?;
12593 *require_output(output, "output")? =
12594 string_property_view(&point.properties, property_index)?;
12595 Ok(true)
12596 })
12597 }
12598}
12599
12600#[unsafe(no_mangle)]
12605pub unsafe extern "C" fn pio_detailed_connectivity_dc_converter_unit_at(
12606 details: *const PioDetailedConnectivity,
12607 index: usize,
12608 output: *mut PioDcConverterUnitView,
12609 error: *mut *mut PioError,
12610) -> bool {
12611 unsafe {
12612 entry(error, false, || {
12613 let details = require_detailed_connectivity(details)?;
12614 let unit = details.dc_converter_units.get(index).ok_or_else(|| {
12615 boundary_error(
12616 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
12617 format!("DC converter unit index {index} is out of range"),
12618 )
12619 })?;
12620 let (substation, has_substation) = optional_component_id_view(unit.substation.as_ref());
12621 *require_output(output, "output")? = PioDcConverterUnitView {
12622 component: component_id_view(&unit.component),
12623 substation,
12624 has_substation,
12625 operation_mode: PioStringView::new(dc_converter_operation_mode_name(
12626 unit.operation_mode,
12627 )),
12628 };
12629 Ok(true)
12630 })
12631 }
12632}
12633
12634#[unsafe(no_mangle)]
12639pub unsafe extern "C" fn pio_detailed_connectivity_dc_topological_node_at(
12640 details: *const PioDetailedConnectivity,
12641 index: usize,
12642 output: *mut PioDcNodeView,
12643 error: *mut *mut PioError,
12644) -> bool {
12645 unsafe {
12646 entry(error, false, || {
12647 let details = require_detailed_connectivity(details)?;
12648 let node = details.dc_topological_nodes.get(index).ok_or_else(|| {
12649 boundary_error(
12650 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
12651 format!("DC topological node index {index} is out of range"),
12652 )
12653 })?;
12654 let (dc_converter_unit, has_dc_converter_unit) =
12655 optional_component_id_view(node.dc_converter_unit.as_ref());
12656 *require_output(output, "output")? = PioDcNodeView {
12657 component: component_id_view(&node.component),
12658 kind: PioStringView::new("topological_node"),
12659 nominal_voltage_kv: 0.0,
12660 has_nominal_voltage: false,
12661 voltage_kv: 0.0,
12662 has_voltage: false,
12663 dc_converter_unit,
12664 has_dc_converter_unit,
12665 dc_topological_node: empty_component_id_view(),
12666 has_dc_topological_node: false,
12667 };
12668 Ok(true)
12669 })
12670 }
12671}
12672
12673#[unsafe(no_mangle)]
12678pub unsafe extern "C" fn pio_detailed_connectivity_dc_node_at(
12679 details: *const PioDetailedConnectivity,
12680 index: usize,
12681 output: *mut PioDcNodeView,
12682 error: *mut *mut PioError,
12683) -> bool {
12684 unsafe {
12685 entry(error, false, || {
12686 let details = require_detailed_connectivity(details)?;
12687 let node = details.dc_nodes.get(index).ok_or_else(|| {
12688 boundary_error(
12689 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
12690 format!("DC node index {index} is out of range"),
12691 )
12692 })?;
12693 let (dc_converter_unit, has_dc_converter_unit) =
12694 optional_component_id_view(node.dc_converter_unit.as_ref());
12695 let (dc_topological_node, has_dc_topological_node) =
12696 optional_component_id_view(node.dc_topological_node.as_ref());
12697 *require_output(output, "output")? = PioDcNodeView {
12698 component: component_id_view(&node.component),
12699 kind: PioStringView::new("node"),
12700 nominal_voltage_kv: node.nominal_voltage_kv.unwrap_or(0.0),
12701 has_nominal_voltage: node.nominal_voltage_kv.is_some(),
12702 voltage_kv: node.voltage_kv.unwrap_or(0.0),
12703 has_voltage: node.voltage_kv.is_some(),
12704 dc_converter_unit,
12705 has_dc_converter_unit,
12706 dc_topological_node,
12707 has_dc_topological_node,
12708 };
12709 Ok(true)
12710 })
12711 }
12712}
12713
12714#[unsafe(no_mangle)]
12719pub unsafe extern "C" fn pio_detailed_connectivity_dc_ground_at(
12720 details: *const PioDetailedConnectivity,
12721 index: usize,
12722 output: *mut PioDcEquipmentView,
12723 error: *mut *mut PioError,
12724) -> bool {
12725 unsafe {
12726 entry(error, false, || {
12727 let details = require_detailed_connectivity(details)?;
12728 let record = details.dc_grounds.get(index).ok_or_else(|| {
12729 boundary_error(
12730 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
12731 format!("DC ground index {index} is out of range"),
12732 )
12733 })?;
12734 *require_output(output, "output")? = dc_equipment_view(
12735 &record.component,
12736 record.equipment_container.as_ref(),
12737 "ground",
12738 &record.dc_terminal,
12739 None,
12740 record.rated_dc_voltage_kv,
12741 record.resistance_ohm,
12742 record.inductance_h,
12743 None,
12744 None,
12745 None,
12746 None,
12747 );
12748 Ok(true)
12749 })
12750 }
12751}
12752
12753#[unsafe(no_mangle)]
12758pub unsafe extern "C" fn pio_detailed_connectivity_dc_busbar_at(
12759 details: *const PioDetailedConnectivity,
12760 index: usize,
12761 output: *mut PioDcEquipmentView,
12762 error: *mut *mut PioError,
12763) -> bool {
12764 unsafe {
12765 entry(error, false, || {
12766 let details = require_detailed_connectivity(details)?;
12767 let record = details.dc_busbars.get(index).ok_or_else(|| {
12768 boundary_error(
12769 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
12770 format!("DC busbar index {index} is out of range"),
12771 )
12772 })?;
12773 *require_output(output, "output")? = dc_equipment_view(
12774 &record.component,
12775 record.equipment_container.as_ref(),
12776 "busbar",
12777 &record.dc_terminal,
12778 None,
12779 record.rated_dc_voltage_kv,
12780 None,
12781 None,
12782 None,
12783 None,
12784 None,
12785 None,
12786 );
12787 Ok(true)
12788 })
12789 }
12790}
12791
12792#[unsafe(no_mangle)]
12797pub unsafe extern "C" fn pio_detailed_connectivity_dc_line_at(
12798 details: *const PioDetailedConnectivity,
12799 index: usize,
12800 output: *mut PioDcEquipmentView,
12801 error: *mut *mut PioError,
12802) -> bool {
12803 unsafe {
12804 entry(error, false, || {
12805 let details = require_detailed_connectivity(details)?;
12806 let record = details.dc_lines.get(index).ok_or_else(|| {
12807 boundary_error(
12808 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
12809 format!("DC line index {index} is out of range"),
12810 )
12811 })?;
12812 *require_output(output, "output")? = dc_equipment_view(
12813 &record.component,
12814 record.equipment_container.as_ref(),
12815 "line",
12816 &record.dc_terminal1,
12817 Some(&record.dc_terminal2),
12818 record.rated_dc_voltage_kv,
12819 record.resistance_ohm,
12820 record.inductance_h,
12821 record.capacitance_f,
12822 record.length_km,
12823 None,
12824 None,
12825 );
12826 Ok(true)
12827 })
12828 }
12829}
12830
12831#[unsafe(no_mangle)]
12836pub unsafe extern "C" fn pio_detailed_connectivity_dc_series_device_at(
12837 details: *const PioDetailedConnectivity,
12838 index: usize,
12839 output: *mut PioDcEquipmentView,
12840 error: *mut *mut PioError,
12841) -> bool {
12842 unsafe {
12843 entry(error, false, || {
12844 let details = require_detailed_connectivity(details)?;
12845 let record = details.dc_series_devices.get(index).ok_or_else(|| {
12846 boundary_error(
12847 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
12848 format!("DC series device index {index} is out of range"),
12849 )
12850 })?;
12851 *require_output(output, "output")? = dc_equipment_view(
12852 &record.component,
12853 record.equipment_container.as_ref(),
12854 "series_device",
12855 &record.dc_terminal1,
12856 Some(&record.dc_terminal2),
12857 record.rated_dc_voltage_kv,
12858 record.resistance_ohm,
12859 record.inductance_h,
12860 None,
12861 None,
12862 None,
12863 None,
12864 );
12865 Ok(true)
12866 })
12867 }
12868}
12869
12870#[unsafe(no_mangle)]
12875pub unsafe extern "C" fn pio_detailed_connectivity_dc_switch_at(
12876 details: *const PioDetailedConnectivity,
12877 index: usize,
12878 output: *mut PioDcEquipmentView,
12879 error: *mut *mut PioError,
12880) -> bool {
12881 unsafe {
12882 entry(error, false, || {
12883 let details = require_detailed_connectivity(details)?;
12884 let record = details.dc_switches.get(index).ok_or_else(|| {
12885 boundary_error(
12886 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
12887 format!("DC switch index {index} is out of range"),
12888 )
12889 })?;
12890 *require_output(output, "output")? = dc_equipment_view(
12891 &record.component,
12892 record.equipment_container.as_ref(),
12893 "switch",
12894 &record.dc_terminal1,
12895 Some(&record.dc_terminal2),
12896 record.rated_dc_voltage_kv,
12897 record.resistance_ohm,
12898 None,
12899 None,
12900 None,
12901 Some(record.kind),
12902 record.open,
12903 );
12904 Ok(true)
12905 })
12906 }
12907}
12908
12909#[unsafe(no_mangle)]
12914pub unsafe extern "C" fn pio_detailed_connectivity_voltage_source_converter_at(
12915 details: *const PioDetailedConnectivity,
12916 index: usize,
12917 output: *mut PioAcDcConverterView,
12918 error: *mut *mut PioError,
12919) -> bool {
12920 unsafe {
12921 entry(error, false, || {
12922 let details = require_detailed_connectivity(details)?;
12923 let converter = details
12924 .voltage_source_converters
12925 .get(index)
12926 .ok_or_else(|| {
12927 boundary_error(
12928 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
12929 format!("voltage source converter index {index} is out of range"),
12930 )
12931 })?;
12932 let (dc_converter_unit, has_dc_converter_unit) =
12933 optional_component_id_view(converter.dc_converter_unit.as_ref());
12934 let (control_mode, has_control_mode) =
12935 converter
12936 .control_mode
12937 .map_or((PioStringView::EMPTY, false), |mode| {
12938 (
12939 PioStringView::new(ac_dc_converter_control_mode_name(mode)),
12940 true,
12941 )
12942 });
12943 let (pcc_terminal, has_pcc_terminal) =
12944 terminal_reference_view(converter.pcc_terminal.as_ref());
12945 let (reactive_limits, has_reactive_limits) =
12946 reactive_limits_view(converter.reactive_limits.as_ref());
12947 *require_output(output, "output")? = PioAcDcConverterView {
12948 component: component_id_view(&converter.component),
12949 kind: PioStringView::new("voltage_source"),
12950 dc_converter_unit,
12951 has_dc_converter_unit,
12952 dc_terminal1: dc_terminal_view(&converter.dc_terminal1),
12953 dc_terminal2: dc_terminal_view(&converter.dc_terminal2),
12954 base_apparent_power_mva: converter.base_apparent_power_mva.unwrap_or(0.0),
12955 has_base_apparent_power: converter.base_apparent_power_mva.is_some(),
12956 minimum_active_power_mw: converter.minimum_active_power_mw.unwrap_or(0.0),
12957 has_minimum_active_power: converter.minimum_active_power_mw.is_some(),
12958 maximum_active_power_mw: converter.maximum_active_power_mw.unwrap_or(0.0),
12959 has_maximum_active_power: converter.maximum_active_power_mw.is_some(),
12960 minimum_dc_voltage_kv: converter.minimum_dc_voltage_kv.unwrap_or(0.0),
12961 has_minimum_dc_voltage: converter.minimum_dc_voltage_kv.is_some(),
12962 maximum_dc_voltage_kv: converter.maximum_dc_voltage_kv.unwrap_or(0.0),
12963 has_maximum_dc_voltage: converter.maximum_dc_voltage_kv.is_some(),
12964 rated_dc_voltage_kv: converter.rated_dc_voltage_kv.unwrap_or(0.0),
12965 has_rated_dc_voltage: converter.rated_dc_voltage_kv.is_some(),
12966 valve_u0_kv: converter.valve_u0_kv.unwrap_or(0.0),
12967 has_valve_u0: converter.valve_u0_kv.is_some(),
12968 number_of_valves: converter.number_of_valves.unwrap_or(0),
12969 has_number_of_valves: converter.number_of_valves.is_some(),
12970 idle_loss_mw: converter.idle_loss_mw.unwrap_or(0.0),
12971 has_idle_loss: converter.idle_loss_mw.is_some(),
12972 switching_loss_mw_per_ampere: converter.switching_loss_mw_per_ampere.unwrap_or(0.0),
12973 has_switching_loss: converter.switching_loss_mw_per_ampere.is_some(),
12974 resistive_loss_ohm: converter.resistive_loss_ohm.unwrap_or(0.0),
12975 has_resistive_loss: converter.resistive_loss_ohm.is_some(),
12976 control_mode,
12977 has_control_mode,
12978 active_power_at_pcc_mw: converter.active_power_at_pcc_mw.unwrap_or(0.0),
12979 has_active_power_at_pcc: converter.active_power_at_pcc_mw.is_some(),
12980 reactive_power_at_pcc_mvar: converter.reactive_power_at_pcc_mvar.unwrap_or(0.0),
12981 has_reactive_power_at_pcc: converter.reactive_power_at_pcc_mvar.is_some(),
12982 target_active_power_mw: converter.target_active_power_mw.unwrap_or(0.0),
12983 has_target_active_power: converter.target_active_power_mw.is_some(),
12984 target_dc_voltage_kv: converter.target_dc_voltage_kv.unwrap_or(0.0),
12985 has_target_dc_voltage: converter.target_dc_voltage_kv.is_some(),
12986 pcc_terminal,
12987 has_pcc_terminal,
12988 droop_curve_segment_count: converter
12989 .droop_curve
12990 .as_ref()
12991 .map_or(0, |curve| curve.segments.len()),
12992 has_droop_curve: converter.droop_curve.is_some(),
12993 droop: converter.droop.unwrap_or(0.0),
12994 has_droop: converter.droop.is_some(),
12995 droop_compensation: converter.droop_compensation.unwrap_or(0.0),
12996 has_droop_compensation: converter.droop_compensation.is_some(),
12997 q_share: converter.q_share.unwrap_or(0.0),
12998 has_q_share: converter.q_share.is_some(),
12999 maximum_modulation_index: converter.maximum_modulation_index.unwrap_or(0.0),
13000 has_maximum_modulation_index: converter.maximum_modulation_index.is_some(),
13001 maximum_valve_current_a: converter.maximum_valve_current_a.unwrap_or(0.0),
13002 has_maximum_valve_current: converter.maximum_valve_current_a.is_some(),
13003 dc_current_a: converter.dc_current_a.unwrap_or(0.0),
13004 has_dc_current: converter.dc_current_a.is_some(),
13005 ac_voltage_kv: converter.ac_voltage_kv.unwrap_or(0.0),
13006 has_ac_voltage: converter.ac_voltage_kv.is_some(),
13007 dc_voltage_kv: converter.dc_voltage_kv.unwrap_or(0.0),
13008 has_dc_voltage: converter.dc_voltage_kv.is_some(),
13009 voltage_regulator_on: converter.voltage_regulator_on.unwrap_or(false),
13010 has_voltage_regulator_on: converter.voltage_regulator_on.is_some(),
13011 voltage_setpoint_kv: converter.voltage_setpoint_kv.unwrap_or(0.0),
13012 has_voltage_setpoint: converter.voltage_setpoint_kv.is_some(),
13013 reactive_power_setpoint_mvar: converter.reactive_power_setpoint_mvar.unwrap_or(0.0),
13014 has_reactive_power_setpoint: converter.reactive_power_setpoint_mvar.is_some(),
13015 reactive_limits,
13016 has_reactive_limits,
13017 pole_loss_active_power_mw: converter.pole_loss_active_power_mw.unwrap_or(0.0),
13018 has_pole_loss_active_power: converter.pole_loss_active_power_mw.is_some(),
13019 reactive_model: PioStringView::EMPTY,
13020 has_reactive_model: false,
13021 power_factor: 0.0,
13022 has_power_factor: false,
13023 operating_mode: PioStringView::EMPTY,
13024 has_operating_mode: false,
13025 rated_dc_current_a: 0.0,
13026 has_rated_dc_current: false,
13027 minimum_alpha_degrees: 0.0,
13028 has_minimum_alpha: false,
13029 maximum_alpha_degrees: 0.0,
13030 has_maximum_alpha: false,
13031 minimum_gamma_degrees: 0.0,
13032 has_minimum_gamma: false,
13033 maximum_gamma_degrees: 0.0,
13034 has_maximum_gamma: false,
13035 target_alpha_degrees: 0.0,
13036 has_target_alpha: false,
13037 target_gamma_degrees: 0.0,
13038 has_target_gamma: false,
13039 target_dc_current_a: 0.0,
13040 has_target_dc_current: false,
13041 alpha_degrees: 0.0,
13042 has_alpha: false,
13043 gamma_degrees: 0.0,
13044 has_gamma: false,
13045 delta_degrees: converter.delta_degrees.unwrap_or(0.0),
13046 has_delta: converter.delta_degrees.is_some(),
13047 uf_kv: converter.uf_kv.unwrap_or(0.0),
13048 has_uf: converter.uf_kv.is_some(),
13049 uv_kv: converter.uv_kv.unwrap_or(0.0),
13050 has_uv: converter.uv_kv.is_some(),
13051 };
13052 Ok(true)
13053 })
13054 }
13055}
13056
13057#[unsafe(no_mangle)]
13062pub unsafe extern "C" fn pio_detailed_connectivity_line_commutated_converter_at(
13063 details: *const PioDetailedConnectivity,
13064 index: usize,
13065 output: *mut PioAcDcConverterView,
13066 error: *mut *mut PioError,
13067) -> bool {
13068 unsafe {
13069 entry(error, false, || {
13070 let details = require_detailed_connectivity(details)?;
13071 let converter = details
13072 .line_commutated_converters
13073 .get(index)
13074 .ok_or_else(|| {
13075 boundary_error(
13076 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
13077 format!("line commutated converter index {index} is out of range"),
13078 )
13079 })?;
13080 let (dc_converter_unit, has_dc_converter_unit) =
13081 optional_component_id_view(converter.dc_converter_unit.as_ref());
13082 let (control_mode, has_control_mode) =
13083 converter
13084 .control_mode
13085 .map_or((PioStringView::EMPTY, false), |mode| {
13086 (
13087 PioStringView::new(ac_dc_converter_control_mode_name(mode)),
13088 true,
13089 )
13090 });
13091 let (reactive_model, has_reactive_model) =
13092 converter
13093 .reactive_model
13094 .map_or((PioStringView::EMPTY, false), |model| {
13095 (
13096 PioStringView::new(line_commutated_converter_reactive_model_name(
13097 model,
13098 )),
13099 true,
13100 )
13101 });
13102 let (operating_mode, has_operating_mode) =
13103 converter
13104 .operating_mode
13105 .map_or((PioStringView::EMPTY, false), |mode| {
13106 (
13107 PioStringView::new(line_commutated_converter_operating_mode_name(mode)),
13108 true,
13109 )
13110 });
13111 let (pcc_terminal, has_pcc_terminal) =
13112 terminal_reference_view(converter.pcc_terminal.as_ref());
13113 *require_output(output, "output")? = PioAcDcConverterView {
13114 component: component_id_view(&converter.component),
13115 kind: PioStringView::new("line_commutated"),
13116 dc_converter_unit,
13117 has_dc_converter_unit,
13118 dc_terminal1: dc_terminal_view(&converter.dc_terminal1),
13119 dc_terminal2: dc_terminal_view(&converter.dc_terminal2),
13120 base_apparent_power_mva: converter.base_apparent_power_mva.unwrap_or(0.0),
13121 has_base_apparent_power: converter.base_apparent_power_mva.is_some(),
13122 minimum_active_power_mw: converter.minimum_active_power_mw.unwrap_or(0.0),
13123 has_minimum_active_power: converter.minimum_active_power_mw.is_some(),
13124 maximum_active_power_mw: converter.maximum_active_power_mw.unwrap_or(0.0),
13125 has_maximum_active_power: converter.maximum_active_power_mw.is_some(),
13126 minimum_dc_voltage_kv: converter.minimum_dc_voltage_kv.unwrap_or(0.0),
13127 has_minimum_dc_voltage: converter.minimum_dc_voltage_kv.is_some(),
13128 maximum_dc_voltage_kv: converter.maximum_dc_voltage_kv.unwrap_or(0.0),
13129 has_maximum_dc_voltage: converter.maximum_dc_voltage_kv.is_some(),
13130 rated_dc_voltage_kv: converter.rated_dc_voltage_kv.unwrap_or(0.0),
13131 has_rated_dc_voltage: converter.rated_dc_voltage_kv.is_some(),
13132 valve_u0_kv: converter.valve_u0_kv.unwrap_or(0.0),
13133 has_valve_u0: converter.valve_u0_kv.is_some(),
13134 number_of_valves: converter.number_of_valves.unwrap_or(0),
13135 has_number_of_valves: converter.number_of_valves.is_some(),
13136 idle_loss_mw: converter.idle_loss_mw.unwrap_or(0.0),
13137 has_idle_loss: converter.idle_loss_mw.is_some(),
13138 switching_loss_mw_per_ampere: converter.switching_loss_mw_per_ampere.unwrap_or(0.0),
13139 has_switching_loss: converter.switching_loss_mw_per_ampere.is_some(),
13140 resistive_loss_ohm: converter.resistive_loss_ohm.unwrap_or(0.0),
13141 has_resistive_loss: converter.resistive_loss_ohm.is_some(),
13142 control_mode,
13143 has_control_mode,
13144 active_power_at_pcc_mw: converter.active_power_at_pcc_mw.unwrap_or(0.0),
13145 has_active_power_at_pcc: converter.active_power_at_pcc_mw.is_some(),
13146 reactive_power_at_pcc_mvar: converter.reactive_power_at_pcc_mvar.unwrap_or(0.0),
13147 has_reactive_power_at_pcc: converter.reactive_power_at_pcc_mvar.is_some(),
13148 target_active_power_mw: converter.target_active_power_mw.unwrap_or(0.0),
13149 has_target_active_power: converter.target_active_power_mw.is_some(),
13150 target_dc_voltage_kv: converter.target_dc_voltage_kv.unwrap_or(0.0),
13151 has_target_dc_voltage: converter.target_dc_voltage_kv.is_some(),
13152 pcc_terminal,
13153 has_pcc_terminal,
13154 droop_curve_segment_count: converter
13155 .droop_curve
13156 .as_ref()
13157 .map_or(0, |curve| curve.segments.len()),
13158 has_droop_curve: converter.droop_curve.is_some(),
13159 droop: 0.0,
13160 has_droop: false,
13161 droop_compensation: 0.0,
13162 has_droop_compensation: false,
13163 q_share: 0.0,
13164 has_q_share: false,
13165 maximum_modulation_index: 0.0,
13166 has_maximum_modulation_index: false,
13167 maximum_valve_current_a: 0.0,
13168 has_maximum_valve_current: false,
13169 dc_current_a: converter.dc_current_a.unwrap_or(0.0),
13170 has_dc_current: converter.dc_current_a.is_some(),
13171 ac_voltage_kv: converter.ac_voltage_kv.unwrap_or(0.0),
13172 has_ac_voltage: converter.ac_voltage_kv.is_some(),
13173 dc_voltage_kv: converter.dc_voltage_kv.unwrap_or(0.0),
13174 has_dc_voltage: converter.dc_voltage_kv.is_some(),
13175 voltage_regulator_on: false,
13176 has_voltage_regulator_on: false,
13177 voltage_setpoint_kv: 0.0,
13178 has_voltage_setpoint: false,
13179 reactive_power_setpoint_mvar: 0.0,
13180 has_reactive_power_setpoint: false,
13181 reactive_limits: empty_reactive_limits_view(),
13182 has_reactive_limits: false,
13183 pole_loss_active_power_mw: converter.pole_loss_active_power_mw.unwrap_or(0.0),
13184 has_pole_loss_active_power: converter.pole_loss_active_power_mw.is_some(),
13185 reactive_model,
13186 has_reactive_model,
13187 power_factor: converter.power_factor.unwrap_or(0.0),
13188 has_power_factor: converter.power_factor.is_some(),
13189 operating_mode,
13190 has_operating_mode,
13191 rated_dc_current_a: converter.rated_dc_current_a.unwrap_or(0.0),
13192 has_rated_dc_current: converter.rated_dc_current_a.is_some(),
13193 minimum_alpha_degrees: converter.minimum_alpha_degrees.unwrap_or(0.0),
13194 has_minimum_alpha: converter.minimum_alpha_degrees.is_some(),
13195 maximum_alpha_degrees: converter.maximum_alpha_degrees.unwrap_or(0.0),
13196 has_maximum_alpha: converter.maximum_alpha_degrees.is_some(),
13197 minimum_gamma_degrees: converter.minimum_gamma_degrees.unwrap_or(0.0),
13198 has_minimum_gamma: converter.minimum_gamma_degrees.is_some(),
13199 maximum_gamma_degrees: converter.maximum_gamma_degrees.unwrap_or(0.0),
13200 has_maximum_gamma: converter.maximum_gamma_degrees.is_some(),
13201 target_alpha_degrees: converter.target_alpha_degrees.unwrap_or(0.0),
13202 has_target_alpha: converter.target_alpha_degrees.is_some(),
13203 target_gamma_degrees: converter.target_gamma_degrees.unwrap_or(0.0),
13204 has_target_gamma: converter.target_gamma_degrees.is_some(),
13205 target_dc_current_a: converter.target_dc_current_a.unwrap_or(0.0),
13206 has_target_dc_current: converter.target_dc_current_a.is_some(),
13207 alpha_degrees: converter.alpha_degrees.unwrap_or(0.0),
13208 has_alpha: converter.alpha_degrees.is_some(),
13209 gamma_degrees: converter.gamma_degrees.unwrap_or(0.0),
13210 has_gamma: converter.gamma_degrees.is_some(),
13211 delta_degrees: 0.0,
13212 has_delta: false,
13213 uf_kv: 0.0,
13214 has_uf: false,
13215 uv_kv: 0.0,
13216 has_uv: false,
13217 };
13218 Ok(true)
13219 })
13220 }
13221}
13222
13223fn droop_curve_segment_view(segment: &powerio_tx::DroopCurveSegment) -> PioDroopCurveSegmentView {
13224 PioDroopCurveSegmentView {
13225 minimum_voltage_kv: segment.minimum_voltage_kv,
13226 maximum_voltage_kv: segment.maximum_voltage_kv,
13227 k: segment.k,
13228 }
13229}
13230
13231#[unsafe(no_mangle)]
13236pub unsafe extern "C" fn pio_detailed_connectivity_voltage_source_converter_droop_curve_segment_at(
13237 details: *const PioDetailedConnectivity,
13238 converter_index: usize,
13239 segment_index: usize,
13240 output: *mut PioDroopCurveSegmentView,
13241 error: *mut *mut PioError,
13242) -> bool {
13243 unsafe {
13244 entry(error, false, || {
13245 let details = require_detailed_connectivity(details)?;
13246 let converter = details
13247 .voltage_source_converters
13248 .get(converter_index)
13249 .ok_or_else(|| {
13250 boundary_error(
13251 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
13252 format!("voltage source converter index {converter_index} is out of range"),
13253 )
13254 })?;
13255 let curve = converter.droop_curve.as_ref().ok_or_else(|| {
13256 boundary_error(
13257 &codes::REQUEST_CAPI_TYPE_MISMATCH,
13258 format!("voltage source converter {converter_index} has no droop curve"),
13259 )
13260 })?;
13261 let segment = curve.segments.get(segment_index).ok_or_else(|| {
13262 boundary_error(
13263 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
13264 format!("droop curve segment index {segment_index} is out of range"),
13265 )
13266 })?;
13267 *require_output(output, "output")? = droop_curve_segment_view(segment);
13268 Ok(true)
13269 })
13270 }
13271}
13272
13273#[unsafe(no_mangle)]
13278pub unsafe extern "C" fn pio_detailed_connectivity_line_commutated_converter_droop_curve_segment_at(
13279 details: *const PioDetailedConnectivity,
13280 converter_index: usize,
13281 segment_index: usize,
13282 output: *mut PioDroopCurveSegmentView,
13283 error: *mut *mut PioError,
13284) -> bool {
13285 unsafe {
13286 entry(error, false, || {
13287 let details = require_detailed_connectivity(details)?;
13288 let converter = details
13289 .line_commutated_converters
13290 .get(converter_index)
13291 .ok_or_else(|| {
13292 boundary_error(
13293 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
13294 format!(
13295 "line commutated converter index {converter_index} is out of range"
13296 ),
13297 )
13298 })?;
13299 let curve = converter.droop_curve.as_ref().ok_or_else(|| {
13300 boundary_error(
13301 &codes::REQUEST_CAPI_TYPE_MISMATCH,
13302 format!("line commutated converter {converter_index} has no droop curve"),
13303 )
13304 })?;
13305 let segment = curve.segments.get(segment_index).ok_or_else(|| {
13306 boundary_error(
13307 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
13308 format!("droop curve segment index {segment_index} is out of range"),
13309 )
13310 })?;
13311 *require_output(output, "output")? = droop_curve_segment_view(segment);
13312 Ok(true)
13313 })
13314 }
13315}
13316
13317#[unsafe(no_mangle)]
13322pub unsafe extern "C" fn pio_detailed_connectivity_voltage_source_converter_reactive_limit_property_at(
13323 details: *const PioDetailedConnectivity,
13324 converter_index: usize,
13325 property_index: usize,
13326 output: *mut PioStringPropertyView,
13327 error: *mut *mut PioError,
13328) -> bool {
13329 unsafe {
13330 entry(error, false, || {
13331 let details = require_detailed_connectivity(details)?;
13332 let converter = details
13333 .voltage_source_converters
13334 .get(converter_index)
13335 .ok_or_else(|| {
13336 boundary_error(
13337 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
13338 format!("voltage source converter index {converter_index} is out of range"),
13339 )
13340 })?;
13341 let limits = converter.reactive_limits.as_ref().ok_or_else(|| {
13342 boundary_error(
13343 &codes::REQUEST_CAPI_TYPE_MISMATCH,
13344 format!("voltage source converter {converter_index} has no reactive limits"),
13345 )
13346 })?;
13347 *require_output(output, "output")? =
13348 string_property_view(reactive_limit_properties(limits)?, property_index)?;
13349 Ok(true)
13350 })
13351 }
13352}
13353
13354#[unsafe(no_mangle)]
13359pub unsafe extern "C" fn pio_detailed_connectivity_voltage_source_converter_reactive_capability_point_at(
13360 details: *const PioDetailedConnectivity,
13361 converter_index: usize,
13362 point_index: usize,
13363 output: *mut PioReactiveCapabilityCurvePointView,
13364 error: *mut *mut PioError,
13365) -> bool {
13366 unsafe {
13367 entry(error, false, || {
13368 let details = require_detailed_connectivity(details)?;
13369 let converter = details
13370 .voltage_source_converters
13371 .get(converter_index)
13372 .ok_or_else(|| {
13373 boundary_error(
13374 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
13375 format!("voltage source converter index {converter_index} is out of range"),
13376 )
13377 })?;
13378 let curve = converter
13379 .reactive_limits
13380 .as_ref()
13381 .and_then(reactive_capability_curve)
13382 .ok_or_else(|| {
13383 boundary_error(
13384 &codes::REQUEST_CAPI_TYPE_MISMATCH,
13385 format!(
13386 "voltage source converter {converter_index} has no reactive capability curve"
13387 ),
13388 )
13389 })?;
13390 *require_output(output, "output")? =
13391 reactive_capability_point_view(curve, point_index)?;
13392 Ok(true)
13393 })
13394 }
13395}
13396
13397#[unsafe(no_mangle)]
13402pub unsafe extern "C" fn pio_detailed_connectivity_voltage_source_converter_reactive_capability_point_property_at(
13403 details: *const PioDetailedConnectivity,
13404 converter_index: usize,
13405 point_index: usize,
13406 property_index: usize,
13407 output: *mut PioStringPropertyView,
13408 error: *mut *mut PioError,
13409) -> bool {
13410 unsafe {
13411 entry(error, false, || {
13412 let details = require_detailed_connectivity(details)?;
13413 let converter = details
13414 .voltage_source_converters
13415 .get(converter_index)
13416 .ok_or_else(|| {
13417 boundary_error(
13418 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
13419 format!("voltage source converter index {converter_index} is out of range"),
13420 )
13421 })?;
13422 let curve = converter
13423 .reactive_limits
13424 .as_ref()
13425 .and_then(reactive_capability_curve)
13426 .ok_or_else(|| {
13427 boundary_error(
13428 &codes::REQUEST_CAPI_TYPE_MISMATCH,
13429 format!(
13430 "voltage source converter {converter_index} has no reactive capability curve"
13431 ),
13432 )
13433 })?;
13434 let point = curve.points.get(point_index).ok_or_else(|| {
13435 boundary_error(
13436 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
13437 format!("reactive capability point index {point_index} is out of range"),
13438 )
13439 })?;
13440 *require_output(output, "output")? =
13441 string_property_view(&point.properties, property_index)?;
13442 Ok(true)
13443 })
13444 }
13445}
13446
13447#[unsafe(no_mangle)]
13452pub unsafe extern "C" fn pio_detailed_connectivity_retain(
13453 details: *const PioDetailedConnectivity,
13454) -> *mut PioDetailedConnectivity {
13455 unsafe { PioDetailedConnectivity::retain_raw(details) }
13456}
13457
13458#[unsafe(no_mangle)]
13463pub unsafe extern "C" fn pio_detailed_connectivity_release(details: *mut PioDetailedConnectivity) {
13464 unsafe { PioDetailedConnectivity::release_raw(details) };
13465}
13466
13467#[unsafe(no_mangle)]
13471pub unsafe extern "C" fn pio_balanced_network_bus_count(
13472 network: *const PioBalancedNetwork,
13473) -> usize {
13474 unsafe { PioBalancedNetwork::get(network) }
13475 .and_then(BalancedNetworkInner::network)
13476 .map_or(0, |network| network.buses().len())
13477}
13478
13479#[unsafe(no_mangle)]
13483pub unsafe extern "C" fn pio_balanced_network_branch_count(
13484 network: *const PioBalancedNetwork,
13485) -> usize {
13486 unsafe { PioBalancedNetwork::get(network) }
13487 .and_then(BalancedNetworkInner::network)
13488 .map_or(0, |network| network.branches().len())
13489}
13490
13491#[unsafe(no_mangle)]
13495pub unsafe extern "C" fn pio_balanced_network_load_count(
13496 network: *const PioBalancedNetwork,
13497) -> usize {
13498 unsafe { PioBalancedNetwork::get(network) }
13499 .and_then(BalancedNetworkInner::network)
13500 .map_or(0, |network| network.loads().len())
13501}
13502
13503#[unsafe(no_mangle)]
13507pub unsafe extern "C" fn pio_balanced_network_shunt_count(
13508 network: *const PioBalancedNetwork,
13509) -> usize {
13510 unsafe { PioBalancedNetwork::get(network) }
13511 .and_then(BalancedNetworkInner::network)
13512 .map_or(0, |network| network.shunts().len())
13513}
13514
13515#[unsafe(no_mangle)]
13519pub unsafe extern "C" fn pio_balanced_network_static_var_compensator_count(
13520 network: *const PioBalancedNetwork,
13521) -> usize {
13522 unsafe { PioBalancedNetwork::get(network) }
13523 .and_then(BalancedNetworkInner::network)
13524 .map_or(0, |network| network.static_var_compensators().len())
13525}
13526
13527#[unsafe(no_mangle)]
13531pub unsafe extern "C" fn pio_balanced_network_generator_count(
13532 network: *const PioBalancedNetwork,
13533) -> usize {
13534 unsafe { PioBalancedNetwork::get(network) }
13535 .and_then(BalancedNetworkInner::network)
13536 .map_or(0, |network| network.generators().len())
13537}
13538
13539#[unsafe(no_mangle)]
13543pub unsafe extern "C" fn pio_balanced_network_storage_count(
13544 network: *const PioBalancedNetwork,
13545) -> usize {
13546 unsafe { PioBalancedNetwork::get(network) }
13547 .and_then(BalancedNetworkInner::network)
13548 .map_or(0, |network| network.storage().len())
13549}
13550
13551#[unsafe(no_mangle)]
13555pub unsafe extern "C" fn pio_balanced_network_switch_count(
13556 network: *const PioBalancedNetwork,
13557) -> usize {
13558 unsafe { PioBalancedNetwork::get(network) }
13559 .and_then(BalancedNetworkInner::network)
13560 .map_or(0, |network| network.switches().len())
13561}
13562
13563#[unsafe(no_mangle)]
13567pub unsafe extern "C" fn pio_balanced_network_hvdc_count(
13568 network: *const PioBalancedNetwork,
13569) -> usize {
13570 unsafe { PioBalancedNetwork::get(network) }
13571 .and_then(BalancedNetworkInner::network)
13572 .map_or(0, |network| network.hvdc().len())
13573}
13574
13575#[unsafe(no_mangle)]
13579pub unsafe extern "C" fn pio_balanced_network_three_winding_transformer_count(
13580 network: *const PioBalancedNetwork,
13581) -> usize {
13582 unsafe { PioBalancedNetwork::get(network) }
13583 .and_then(BalancedNetworkInner::network)
13584 .map_or(0, |network| network.transformers_3w().len())
13585}
13586
13587#[unsafe(no_mangle)]
13591pub unsafe extern "C" fn pio_balanced_network_area_count(
13592 network: *const PioBalancedNetwork,
13593) -> usize {
13594 unsafe { PioBalancedNetwork::get(network) }
13595 .and_then(BalancedNetworkInner::network)
13596 .map_or(0, |network| network.areas().len())
13597}
13598
13599unsafe fn require_balanced_network<'a>(
13600 network: *const PioBalancedNetwork,
13601) -> Result<&'a BalancedNetwork, *mut PioError> {
13602 unsafe { PioBalancedNetwork::get(network) }
13603 .and_then(BalancedNetworkInner::network)
13604 .ok_or_else(|| {
13605 boundary_error(
13606 &codes::BIND_CAPI_NULL_HANDLE,
13607 "PioBalancedNetwork must not be NULL",
13608 )
13609 })
13610}
13611
13612unsafe fn require_output<'a, T>(
13613 output: *mut T,
13614 argument: &str,
13615) -> Result<&'a mut T, *mut PioError> {
13616 unsafe { output.as_mut() }.ok_or_else(|| {
13617 boundary_error(
13618 &codes::BIND_CAPI_NULL_ARGUMENT,
13619 format!("{argument} must not be NULL"),
13620 )
13621 })
13622}
13623
13624unsafe fn require_detailed_connectivity<'a>(
13625 details: *const PioDetailedConnectivity,
13626) -> Result<&'a powerio_tx::DetailedConnectivity, *mut PioError> {
13627 unsafe { PioDetailedConnectivity::get(details) }
13628 .and_then(DetailedConnectivityInner::details)
13629 .ok_or_else(|| {
13630 boundary_error(
13631 &codes::BIND_CAPI_NULL_HANDLE,
13632 "PioDetailedConnectivity must not be NULL",
13633 )
13634 })
13635}
13636
13637fn optional_string_view(value: Option<&str>) -> (PioStringView, bool) {
13638 value.map_or((PioStringView::EMPTY, false), |value| {
13639 (PioStringView::new(value), true)
13640 })
13641}
13642
13643fn balanced_coords_kind_name(kind: powerio_tx::CoordsKind) -> &'static str {
13644 match kind {
13645 powerio_tx::CoordsKind::Source => "source",
13646 powerio_tx::CoordsKind::Synthetic => "synthetic",
13647 powerio_tx::CoordsKind::Manual => "manual",
13648 powerio_tx::CoordsKind::Derived => "derived",
13649 _ => "unknown",
13650 }
13651}
13652
13653fn balanced_location_view(location: &powerio_tx::Location) -> PioBalancedLocationView {
13654 let (kind, has_kind) = location.kind.map_or((PioStringView::EMPTY, false), |kind| {
13655 (PioStringView::new(balanced_coords_kind_name(kind)), true)
13656 });
13657 PioBalancedLocationView {
13658 x: location.x,
13659 y: location.y,
13660 kind,
13661 has_kind,
13662 }
13663}
13664
13665fn empty_balanced_location_view() -> PioBalancedLocationView {
13666 PioBalancedLocationView {
13667 x: 0.0,
13668 y: 0.0,
13669 kind: PioStringView::EMPTY,
13670 has_kind: false,
13671 }
13672}
13673
13674fn balanced_geo_view(geo: Option<&powerio_tx::GeoMeta>) -> PioBalancedGeoView {
13675 let Some(geo) = geo else {
13676 return PioBalancedGeoView {
13677 has_geo: false,
13678 space: PioStringView::EMPTY,
13679 crs: PioStringView::EMPTY,
13680 has_crs: false,
13681 kind: PioStringView::EMPTY,
13682 has_kind: false,
13683 has_canvas: false,
13684 canvas_width: 0.0,
13685 has_canvas_width: false,
13686 canvas_height: 0.0,
13687 has_canvas_height: false,
13688 canvas_units: PioStringView::EMPTY,
13689 has_canvas_units: false,
13690 };
13691 };
13692 let (space, crs, has_crs, canvas) = match &geo.space {
13693 powerio_tx::CoordinateSpace::Geographic { crs } => (
13694 "geographic",
13695 crs.as_deref()
13696 .map_or(PioStringView::EMPTY, PioStringView::new),
13697 crs.is_some(),
13698 None,
13699 ),
13700 powerio_tx::CoordinateSpace::Projected { crs } => (
13701 "projected",
13702 crs.as_deref()
13703 .map_or(PioStringView::EMPTY, PioStringView::new),
13704 crs.is_some(),
13705 None,
13706 ),
13707 powerio_tx::CoordinateSpace::Diagram { canvas } => {
13708 ("diagram", PioStringView::EMPTY, false, canvas.as_ref())
13709 }
13710 powerio_tx::CoordinateSpace::Unknown => ("unknown", PioStringView::EMPTY, false, None),
13711 _ => ("unknown", PioStringView::EMPTY, false, None),
13712 };
13713 let (kind, has_kind) = geo.kind.map_or((PioStringView::EMPTY, false), |kind| {
13714 (PioStringView::new(balanced_coords_kind_name(kind)), true)
13715 });
13716 PioBalancedGeoView {
13717 has_geo: true,
13718 space: PioStringView::new(space),
13719 crs,
13720 has_crs,
13721 kind,
13722 has_kind,
13723 has_canvas: canvas.is_some(),
13724 canvas_width: canvas.and_then(|canvas| canvas.width).unwrap_or(0.0),
13725 has_canvas_width: canvas.is_some_and(|canvas| canvas.width.is_some()),
13726 canvas_height: canvas.and_then(|canvas| canvas.height).unwrap_or(0.0),
13727 has_canvas_height: canvas.is_some_and(|canvas| canvas.height.is_some()),
13728 canvas_units: canvas
13729 .and_then(|canvas| canvas.units.as_deref())
13730 .map_or(PioStringView::EMPTY, PioStringView::new),
13731 has_canvas_units: canvas.is_some_and(|canvas| canvas.units.is_some()),
13732 }
13733}
13734
13735fn load_voltage_model_view(load: &powerio_tx::Load) -> PioBalancedLoadVoltageModelView {
13736 let mut view = PioBalancedLoadVoltageModelView {
13737 kind: PioStringView::new("constant_power"),
13738 p_constant_power_mw: load.p,
13739 q_constant_power_mvar: load.q,
13740 p_constant_current_mw: 0.0,
13741 q_constant_current_mvar: 0.0,
13742 p_constant_impedance_mw: 0.0,
13743 q_constant_impedance_mvar: 0.0,
13744 exponential_p_mw: 0.0,
13745 exponential_q_mvar: 0.0,
13746 gamma_p: 0.0,
13747 gamma_q: 0.0,
13748 nominal_voltage_pu: 0.0,
13749 has_nominal_voltage: false,
13750 load_type: 0,
13751 has_load_type: false,
13752 scaling: 0.0,
13753 has_scaling: false,
13754 };
13755 match &load.voltage_model {
13756 None | Some(powerio_tx::LoadVoltageModel::ConstantPower) => {}
13757 Some(powerio_tx::LoadVoltageModel::Zip {
13758 p_constant_power,
13759 q_constant_power,
13760 p_constant_current,
13761 q_constant_current,
13762 p_constant_impedance,
13763 q_constant_impedance,
13764 v_nom,
13765 load_type,
13766 scaling,
13767 }) => {
13768 view.kind = PioStringView::new("zip");
13769 view.p_constant_power_mw = *p_constant_power;
13770 view.q_constant_power_mvar = *q_constant_power;
13771 view.p_constant_current_mw = *p_constant_current;
13772 view.q_constant_current_mvar = *q_constant_current;
13773 view.p_constant_impedance_mw = *p_constant_impedance;
13774 view.q_constant_impedance_mvar = *q_constant_impedance;
13775 if let Some(value) = v_nom {
13776 view.nominal_voltage_pu = *value;
13777 view.has_nominal_voltage = true;
13778 }
13779 if let Some(value) = load_type {
13780 view.load_type = *value;
13781 view.has_load_type = true;
13782 }
13783 if let Some(value) = scaling {
13784 view.scaling = *value;
13785 view.has_scaling = true;
13786 }
13787 }
13788 Some(powerio_tx::LoadVoltageModel::Exponential {
13789 p,
13790 q,
13791 v_nom,
13792 gamma_p,
13793 gamma_q,
13794 }) => {
13795 view.kind = PioStringView::new("exponential");
13796 view.p_constant_power_mw = 0.0;
13797 view.q_constant_power_mvar = 0.0;
13798 view.exponential_p_mw = *p;
13799 view.exponential_q_mvar = *q;
13800 view.gamma_p = *gamma_p;
13801 view.gamma_q = *gamma_q;
13802 if let Some(value) = v_nom {
13803 view.nominal_voltage_pu = *value;
13804 view.has_nominal_voltage = true;
13805 }
13806 }
13807 Some(_) => view.kind = PioStringView::new("unknown"),
13808 }
13809 view
13810}
13811
13812fn switched_shunt_mode_name(mode: powerio_tx::SwitchedShuntMode) -> &'static str {
13813 match mode {
13814 powerio_tx::SwitchedShuntMode::Locked => "locked",
13815 powerio_tx::SwitchedShuntMode::Continuous => "continuous",
13816 powerio_tx::SwitchedShuntMode::Discrete => "discrete",
13817 _ => "unknown",
13818 }
13819}
13820
13821use powerio_tx::network::GEN_EXTRA_KEYS as GENERATOR_CAPABILITY_NAMES;
13822
13823fn static_var_compensator_regulation_mode_name(
13824 mode: powerio_tx::StaticVarCompensatorRegulationMode,
13825) -> &'static str {
13826 match mode {
13827 powerio_tx::StaticVarCompensatorRegulationMode::Voltage => "voltage",
13828 powerio_tx::StaticVarCompensatorRegulationMode::ReactivePower => "reactive_power",
13829 _ => "unknown",
13830 }
13831}
13832
13833fn hvdc_converter_kind_name(kind: powerio_tx::HvdcConverterKind) -> &'static str {
13834 match kind {
13835 powerio_tx::HvdcConverterKind::Vsc => "vsc",
13836 powerio_tx::HvdcConverterKind::Lcc => "lcc",
13837 _ => "unknown",
13838 }
13839}
13840
13841fn hvdc_converters_mode_name(mode: powerio_tx::HvdcConvertersMode) -> &'static str {
13842 match mode {
13843 powerio_tx::HvdcConvertersMode::Side1RectifierSide2Inverter => {
13844 "side1_rectifier_side2_inverter"
13845 }
13846 powerio_tx::HvdcConvertersMode::Side1InverterSide2Rectifier => {
13847 "side1_inverter_side2_rectifier"
13848 }
13849 _ => "unknown",
13850 }
13851}
13852
13853fn hvdc_converter_view(
13854 converter: Option<&powerio_tx::HvdcConverter>,
13855) -> (PioBalancedHvdcConverterView, bool) {
13856 let empty_terminal = terminal_reference_view(None).0;
13857 converter.map_or(
13858 (
13859 PioBalancedHvdcConverterView {
13860 component: empty_component_id_view(),
13861 kind: PioStringView::EMPTY,
13862 loss_factor_percent: 0.0,
13863 voltage_regulator_on: false,
13864 has_voltage_regulator_on: false,
13865 voltage_setpoint_kv: 0.0,
13866 has_voltage_setpoint: false,
13867 reactive_power_setpoint_mvar: 0.0,
13868 has_reactive_power_setpoint: false,
13869 power_factor: 0.0,
13870 has_power_factor: false,
13871 regulating_terminal: empty_terminal,
13872 has_regulating_terminal: false,
13873 },
13874 false,
13875 ),
13876 |converter| {
13877 let (regulating_terminal, has_regulating_terminal) =
13878 terminal_reference_view(converter.regulating_terminal.as_ref());
13879 (
13880 PioBalancedHvdcConverterView {
13881 component: component_id_view(&converter.component),
13882 kind: PioStringView::new(hvdc_converter_kind_name(converter.kind)),
13883 loss_factor_percent: converter.loss_factor_percent,
13884 voltage_regulator_on: converter.voltage_regulator_on.unwrap_or(false),
13885 has_voltage_regulator_on: converter.voltage_regulator_on.is_some(),
13886 voltage_setpoint_kv: converter.voltage_setpoint_kv.unwrap_or(0.0),
13887 has_voltage_setpoint: converter.voltage_setpoint_kv.is_some(),
13888 reactive_power_setpoint_mvar: converter
13889 .reactive_power_setpoint_mvar
13890 .unwrap_or(0.0),
13891 has_reactive_power_setpoint: converter.reactive_power_setpoint_mvar.is_some(),
13892 power_factor: converter.power_factor.unwrap_or(0.0),
13893 has_power_factor: converter.power_factor.is_some(),
13894 regulating_terminal,
13895 has_regulating_terminal,
13896 },
13897 true,
13898 )
13899 },
13900 )
13901}
13902
13903#[unsafe(no_mangle)]
13908pub unsafe extern "C" fn pio_balanced_network_bus_at(
13909 network: *const PioBalancedNetwork,
13910 index: usize,
13911 output: *mut PioBalancedBusView,
13912 error: *mut *mut PioError,
13913) -> bool {
13914 unsafe {
13915 entry(error, false, || {
13916 let network = require_balanced_network(network)?;
13917 let bus = network.buses().get(index).ok_or_else(|| {
13918 boundary_error(
13919 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
13920 format!("bus index {index} is out of range"),
13921 )
13922 })?;
13923 let output = require_output(output, "output")?;
13924 let (component_id, has_component_id) = optional_string_view(bus.uid.as_deref());
13925 let (name, has_name) = optional_string_view(bus.name.as_deref());
13926 let (location, has_location) = bus
13927 .location
13928 .as_ref()
13929 .map_or((empty_balanced_location_view(), false), |location| {
13930 (balanced_location_view(location), true)
13931 });
13932 *output = PioBalancedBusView {
13933 component_id,
13934 has_component_id,
13935 id: bus.id.0,
13936 bus_type: PioStringView::new(bus.kind.as_str()),
13937 vm_pu: bus.vm,
13938 va_degrees: bus.va,
13939 base_kv: bus.base_kv,
13940 vmax_pu: bus.vmax,
13941 vmin_pu: bus.vmin,
13942 has_emergency_voltage_limits: bus.evhi.is_some() || bus.evlo.is_some(),
13943 emergency_vmax_pu: bus.evhi.unwrap_or(bus.vmax),
13944 emergency_vmin_pu: bus.evlo.unwrap_or(bus.vmin),
13945 area: bus.area,
13946 zone: bus.zone,
13947 name,
13948 has_name,
13949 location,
13950 has_location,
13951 };
13952 Ok(true)
13953 })
13954 }
13955}
13956
13957#[unsafe(no_mangle)]
13962pub unsafe extern "C" fn pio_balanced_network_load_at(
13963 network: *const PioBalancedNetwork,
13964 index: usize,
13965 output: *mut PioBalancedLoadView,
13966 error: *mut *mut PioError,
13967) -> bool {
13968 unsafe {
13969 entry(error, false, || {
13970 let network = require_balanced_network(network)?;
13971 let load = network.loads().get(index).ok_or_else(|| {
13972 boundary_error(
13973 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
13974 format!("load index {index} is out of range"),
13975 )
13976 })?;
13977 let output = require_output(output, "output")?;
13978 let (component_id, has_component_id) = optional_string_view(load.uid.as_deref());
13979 *output = PioBalancedLoadView {
13980 component_id,
13981 has_component_id,
13982 bus_id: load.bus.0,
13983 p_mw: load.p,
13984 q_mvar: load.q,
13985 in_service: load.in_service,
13986 voltage_model: load_voltage_model_view(load),
13987 };
13988 Ok(true)
13989 })
13990 }
13991}
13992
13993#[unsafe(no_mangle)]
13998pub unsafe extern "C" fn pio_balanced_network_shunt_at(
13999 network: *const PioBalancedNetwork,
14000 index: usize,
14001 output: *mut PioBalancedShuntView,
14002 error: *mut *mut PioError,
14003) -> bool {
14004 unsafe {
14005 entry(error, false, || {
14006 let network = require_balanced_network(network)?;
14007 let shunt = network.shunts().get(index).ok_or_else(|| {
14008 boundary_error(
14009 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
14010 format!("shunt index {index} is out of range"),
14011 )
14012 })?;
14013 let output = require_output(output, "output")?;
14014 let (component_id, has_component_id) = optional_string_view(shunt.uid.as_deref());
14015 let control = shunt.control.as_ref();
14016 *output = PioBalancedShuntView {
14017 component_id,
14018 has_component_id,
14019 bus_id: shunt.bus.0,
14020 conductance_mw: shunt.g,
14021 susceptance_mvar: shunt.b,
14022 in_service: shunt.in_service,
14023 section_count: shunt.section_count.unwrap_or(0),
14024 has_section_count: shunt.section_count.is_some(),
14025 has_control: control.is_some(),
14026 control_mode: control.map_or(PioStringView::EMPTY, |control| {
14027 PioStringView::new(switched_shunt_mode_name(control.mode))
14028 }),
14029 control_vmax_pu: control.map_or(0.0, |control| control.vhigh),
14030 control_vmin_pu: control.map_or(0.0, |control| control.vlow),
14031 control_bus_id: control
14032 .and_then(|control| control.control_bus)
14033 .map_or(0, |bus| bus.0),
14034 has_control_bus: control.is_some_and(|control| control.control_bus.is_some()),
14035 control_reactive_range_percent: control.map_or(0.0, |control| control.rmpct),
14036 control_block_count: control.map_or(0, |control| control.blocks.len()),
14037 };
14038 Ok(true)
14039 })
14040 }
14041}
14042
14043#[unsafe(no_mangle)]
14048pub unsafe extern "C" fn pio_balanced_network_shunt_block_at(
14049 network: *const PioBalancedNetwork,
14050 shunt_index: usize,
14051 block_index: usize,
14052 output: *mut PioShuntBlockView,
14053 error: *mut *mut PioError,
14054) -> bool {
14055 unsafe {
14056 entry(error, false, || {
14057 let network = require_balanced_network(network)?;
14058 let shunt = network.shunts().get(shunt_index).ok_or_else(|| {
14059 boundary_error(
14060 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
14061 format!("shunt index {shunt_index} is out of range"),
14062 )
14063 })?;
14064 let block = shunt
14065 .control
14066 .as_ref()
14067 .and_then(|control| control.blocks.get(block_index))
14068 .ok_or_else(|| {
14069 boundary_error(
14070 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
14071 format!(
14072 "shunt block index {block_index} is out of range for shunt {shunt_index}"
14073 ),
14074 )
14075 })?;
14076 *require_output(output, "output")? = PioShuntBlockView {
14077 steps: block.steps,
14078 conductance_mw: block.g,
14079 susceptance_mvar: block.b,
14080 };
14081 Ok(true)
14082 })
14083 }
14084}
14085
14086#[unsafe(no_mangle)]
14091pub unsafe extern "C" fn pio_balanced_network_static_var_compensator_at(
14092 network: *const PioBalancedNetwork,
14093 index: usize,
14094 output: *mut PioBalancedStaticVarCompensatorView,
14095 error: *mut *mut PioError,
14096) -> bool {
14097 unsafe {
14098 entry(error, false, || {
14099 let network = require_balanced_network(network)?;
14100 let svc = network
14101 .static_var_compensators()
14102 .get(index)
14103 .ok_or_else(|| {
14104 boundary_error(
14105 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
14106 format!("static VAR compensator index {index} is out of range"),
14107 )
14108 })?;
14109 let (component_id, has_component_id) = optional_string_view(svc.uid.as_deref());
14110 let (regulating_terminal, has_regulating_terminal) =
14111 terminal_reference_view(svc.regulating_terminal.as_ref());
14112 *require_output(output, "output")? = PioBalancedStaticVarCompensatorView {
14113 component_id,
14114 has_component_id,
14115 bus_id: svc.bus.0,
14116 minimum_susceptance_siemens: svc.b_min_siemens,
14117 maximum_susceptance_siemens: svc.b_max_siemens,
14118 voltage_setpoint_kv: svc.voltage_setpoint_kv,
14119 reactive_power_setpoint_mvar: svc.reactive_power_setpoint_mvar,
14120 regulation_mode: PioStringView::new(static_var_compensator_regulation_mode_name(
14121 svc.regulation_mode,
14122 )),
14123 regulating: svc.regulating,
14124 regulating_terminal,
14125 has_regulating_terminal,
14126 active_power_mw: svc.p,
14127 reactive_power_mvar: svc.q,
14128 in_service: svc.in_service,
14129 };
14130 Ok(true)
14131 })
14132 }
14133}
14134
14135#[unsafe(no_mangle)]
14140pub unsafe extern "C" fn pio_balanced_network_branch_at(
14141 network: *const PioBalancedNetwork,
14142 index: usize,
14143 output: *mut PioBalancedBranchView,
14144 error: *mut *mut PioError,
14145) -> bool {
14146 unsafe {
14147 entry(error, false, || {
14148 let network = require_balanced_network(network)?;
14149 let branch = network.branches().get(index).ok_or_else(|| {
14150 boundary_error(
14151 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
14152 format!("branch index {index} is out of range"),
14153 )
14154 })?;
14155 let output = require_output(output, "output")?;
14156 let (component_id, has_component_id) = optional_string_view(branch.uid.as_deref());
14157 let (name, has_name) = optional_string_view(branch.name.as_deref());
14158 let charging = branch.calc_terminal_charging();
14159 let current = branch.current_ratings;
14160 let (control, has_control) = transformer_control_view(branch.control.as_ref());
14161 *output = PioBalancedBranchView {
14162 component_id,
14163 has_component_id,
14164 name,
14165 has_name,
14166 from_bus_id: branch.from.0,
14167 to_bus_id: branch.to.0,
14168 resistance_pu: branch.r,
14169 reactance_pu: branch.x,
14170 total_charging_susceptance_pu: branch.b,
14171 terminal_charging_is_explicit: branch.charging.is_some(),
14172 from_conductance_pu: charging.g_fr,
14173 from_susceptance_pu: charging.b_fr,
14174 to_conductance_pu: charging.g_to,
14175 to_susceptance_pu: charging.b_to,
14176 rate_a_mva: branch.rate_a,
14177 rate_b_mva: branch.rate_b,
14178 rate_c_mva: branch.rate_c,
14179 additional_rating_count: branch.rating_sets.len(),
14180 has_current_ratings: current.is_some(),
14181 current_rating_a: current.map_or(0.0, |rating| rating.c_rating_a),
14182 current_rating_b: current.map_or(0.0, |rating| rating.c_rating_b),
14183 current_rating_c: current.map_or(0.0, |rating| rating.c_rating_c),
14184 tap_ratio: branch.tap,
14185 effective_tap_ratio: branch.calc_effective_tap(),
14186 phase_shift_degrees: branch.shift,
14187 in_service: branch.in_service,
14188 angle_min_degrees: branch.angmin,
14189 angle_max_degrees: branch.angmax,
14190 control,
14191 has_control,
14192 route_point_count: branch.route.as_ref().map_or(0, Vec::len),
14193 has_route: branch.route.is_some(),
14194 };
14195 Ok(true)
14196 })
14197 }
14198}
14199
14200#[unsafe(no_mangle)]
14205pub unsafe extern "C" fn pio_balanced_network_branch_route_point_at(
14206 network: *const PioBalancedNetwork,
14207 branch_index: usize,
14208 point_index: usize,
14209 output: *mut PioBalancedLocationView,
14210 error: *mut *mut PioError,
14211) -> bool {
14212 unsafe {
14213 entry(error, false, || {
14214 let network = require_balanced_network(network)?;
14215 let branch = network.branches().get(branch_index).ok_or_else(|| {
14216 boundary_error(
14217 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
14218 format!("branch index {branch_index} is out of range"),
14219 )
14220 })?;
14221 let route = branch.route.as_ref().ok_or_else(|| {
14222 boundary_error(
14223 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
14224 format!("balanced branch {branch_index} has no route"),
14225 )
14226 })?;
14227 let point = route.get(point_index).ok_or_else(|| {
14228 boundary_error(
14229 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
14230 format!("branch route point index {point_index} is out of range"),
14231 )
14232 })?;
14233 *require_output(output, "output")? = balanced_location_view(point);
14234 Ok(true)
14235 })
14236 }
14237}
14238
14239#[unsafe(no_mangle)]
14244pub unsafe extern "C" fn pio_balanced_network_branch_rating_at(
14245 network: *const PioBalancedNetwork,
14246 branch_index: usize,
14247 rating_index: usize,
14248 output: *mut PioBranchRatingView,
14249 error: *mut *mut PioError,
14250) -> bool {
14251 unsafe {
14252 entry(error, false, || {
14253 let network = require_balanced_network(network)?;
14254 let branch = network.branches().get(branch_index).ok_or_else(|| {
14255 boundary_error(
14256 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
14257 format!("branch index {branch_index} is out of range"),
14258 )
14259 })?;
14260 let rating = branch.rating_sets.get(rating_index).ok_or_else(|| {
14261 boundary_error(
14262 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
14263 format!(
14264 "rating index {rating_index} is out of range for branch {branch_index}"
14265 ),
14266 )
14267 })?;
14268 *require_output(output, "output")? = PioBranchRatingView {
14269 name: PioStringView::new(&rating.name),
14270 rate_mva: rating.rate_mva,
14271 };
14272 Ok(true)
14273 })
14274 }
14275}
14276
14277fn active_power_control_view(
14278 value: Option<&powerio_tx::ActivePowerControl>,
14279) -> (PioActivePowerControlView, bool) {
14280 let Some(value) = value else {
14281 return (
14282 PioActivePowerControlView {
14283 participate: false,
14284 droop_percent: 0.0,
14285 has_droop_percent: false,
14286 participation_factor: 0.0,
14287 has_participation_factor: false,
14288 minimum_target_active_power_mw: 0.0,
14289 has_minimum_target_active_power: false,
14290 maximum_target_active_power_mw: 0.0,
14291 has_maximum_target_active_power: false,
14292 },
14293 false,
14294 );
14295 };
14296 (
14297 PioActivePowerControlView {
14298 participate: value.participate,
14299 droop_percent: value.droop_percent.unwrap_or(0.0),
14300 has_droop_percent: value.droop_percent.is_some(),
14301 participation_factor: value.participation_factor.unwrap_or(0.0),
14302 has_participation_factor: value.participation_factor.is_some(),
14303 minimum_target_active_power_mw: value.minimum_target_active_power_mw.unwrap_or(0.0),
14304 has_minimum_target_active_power: value.minimum_target_active_power_mw.is_some(),
14305 maximum_target_active_power_mw: value.maximum_target_active_power_mw.unwrap_or(0.0),
14306 has_maximum_target_active_power: value.maximum_target_active_power_mw.is_some(),
14307 },
14308 true,
14309 )
14310}
14311
14312fn generator_energy_source_name(value: powerio_tx::GeneratorEnergySource) -> &'static str {
14313 match value {
14314 powerio_tx::GeneratorEnergySource::Hydro => "hydro",
14315 powerio_tx::GeneratorEnergySource::Nuclear => "nuclear",
14316 powerio_tx::GeneratorEnergySource::Wind => "wind",
14317 powerio_tx::GeneratorEnergySource::Thermal => "thermal",
14318 powerio_tx::GeneratorEnergySource::Solar => "solar",
14319 powerio_tx::GeneratorEnergySource::Other => "other",
14320 _ => "unknown",
14321 }
14322}
14323
14324#[unsafe(no_mangle)]
14329pub unsafe extern "C" fn pio_balanced_network_generator_at(
14330 network: *const PioBalancedNetwork,
14331 index: usize,
14332 output: *mut PioBalancedGeneratorView,
14333 error: *mut *mut PioError,
14334) -> bool {
14335 unsafe {
14336 entry(error, false, || {
14337 let network = require_balanced_network(network)?;
14338 let generator = network.generators().get(index).ok_or_else(|| {
14339 boundary_error(
14340 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
14341 format!("generator index {index} is out of range"),
14342 )
14343 })?;
14344 let output = require_output(output, "output")?;
14345 let (component_id, has_component_id) = optional_string_view(generator.uid.as_deref());
14346 let cost = generator.cost.as_ref();
14347 let (active_power_control, has_active_power_control) =
14348 active_power_control_view(generator.active_power_control.as_ref());
14349 let (regulating_terminal, has_regulating_terminal) =
14350 terminal_reference_view(generator.regulating_terminal.as_ref());
14351 *output = PioBalancedGeneratorView {
14352 component_id,
14353 has_component_id,
14354 bus_id: generator.bus.0,
14355 energy_source: PioStringView::new(generator_energy_source_name(
14356 generator.energy_source,
14357 )),
14358 active_power_mw: generator.pg,
14359 reactive_power_mvar: generator.qg,
14360 active_power_max_mw: generator.pmax,
14361 active_power_min_mw: generator.pmin,
14362 reactive_power_max_mvar: generator.qmax,
14363 reactive_power_min_mvar: generator.qmin,
14364 voltage_setpoint_pu: generator.vg,
14365 machine_base_mva: generator.mbase,
14366 in_service: generator.in_service,
14367 has_cost: cost.is_some(),
14368 cost: cost.map_or(
14369 PioGeneratorCostView {
14370 model: 0,
14371 startup: 0.0,
14372 shutdown: 0.0,
14373 ncost: 0,
14374 coefficients: PioF64View::EMPTY,
14375 },
14376 |cost| PioGeneratorCostView {
14377 model: cost.model,
14378 startup: cost.startup,
14379 shutdown: cost.shutdown,
14380 ncost: cost.ncost,
14381 coefficients: PioF64View::new(&cost.coeffs),
14382 },
14383 ),
14384 regulated_bus_id: generator.regulated_bus.map_or(0, |bus| bus.0),
14385 has_regulated_bus: generator.regulated_bus.is_some(),
14386 capability_count: GENERATOR_CAPABILITY_NAMES.len(),
14387 active_power_control,
14388 has_active_power_control,
14389 voltage_regulation_on: generator.voltage_regulation_on,
14390 regulating_terminal,
14391 has_regulating_terminal,
14392 };
14393 Ok(true)
14394 })
14395 }
14396}
14397
14398#[unsafe(no_mangle)]
14403pub unsafe extern "C" fn pio_balanced_network_generator_capability_at(
14404 network: *const PioBalancedNetwork,
14405 generator_index: usize,
14406 capability_index: usize,
14407 output: *mut PioGeneratorCapabilityView,
14408 error: *mut *mut PioError,
14409) -> bool {
14410 unsafe {
14411 entry(error, false, || {
14412 let network = require_balanced_network(network)?;
14413 let generator = network.generators().get(generator_index).ok_or_else(|| {
14414 boundary_error(
14415 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
14416 format!("generator index {generator_index} is out of range"),
14417 )
14418 })?;
14419 let name = GENERATOR_CAPABILITY_NAMES
14420 .get(capability_index)
14421 .ok_or_else(|| {
14422 boundary_error(
14423 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
14424 format!("generator capability index {capability_index} is out of range"),
14425 )
14426 })?;
14427 let value = *generator.caps.get(capability_index).ok_or_else(|| {
14428 boundary_error(
14429 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
14430 "generator capability index is out of range",
14431 )
14432 })?;
14433 *require_output(output, "output")? = PioGeneratorCapabilityView {
14434 name: PioStringView::new(name),
14435 value: value.unwrap_or(0.0),
14436 has_value: value.is_some(),
14437 };
14438 Ok(true)
14439 })
14440 }
14441}
14442
14443#[unsafe(no_mangle)]
14448pub unsafe extern "C" fn pio_balanced_network_storage_at(
14449 network: *const PioBalancedNetwork,
14450 index: usize,
14451 output: *mut PioBalancedStorageView,
14452 error: *mut *mut PioError,
14453) -> bool {
14454 unsafe {
14455 entry(error, false, || {
14456 let network = require_balanced_network(network)?;
14457 let storage = network.storage().get(index).ok_or_else(|| {
14458 boundary_error(
14459 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
14460 format!("storage index {index} is out of range"),
14461 )
14462 })?;
14463 let output = require_output(output, "output")?;
14464 let (component_id, has_component_id) = optional_string_view(storage.uid.as_deref());
14465 let (active_power_control, has_active_power_control) =
14466 active_power_control_view(storage.active_power_control.as_ref());
14467 *output = PioBalancedStorageView {
14468 component_id,
14469 has_component_id,
14470 bus_id: storage.bus.0,
14471 active_power_mw: storage.ps,
14472 reactive_power_mvar: storage.qs,
14473 energy_mwh: storage.energy,
14474 energy_rating_mwh: storage.energy_rating,
14475 charge_rating_mw: storage.charge_rating,
14476 discharge_rating_mw: storage.discharge_rating,
14477 charge_efficiency: storage.charge_efficiency,
14478 discharge_efficiency: storage.discharge_efficiency,
14479 thermal_rating_mva: storage.thermal_rating,
14480 current_rating: storage.current_rating.unwrap_or(0.0),
14481 has_current_rating: storage.current_rating.is_some(),
14482 reactive_power_min_mvar: storage.qmin,
14483 reactive_power_max_mvar: storage.qmax,
14484 resistance_pu: storage.r,
14485 reactance_pu: storage.x,
14486 active_power_loss_mw: storage.p_loss,
14487 reactive_power_loss_mvar: storage.q_loss,
14488 in_service: storage.in_service,
14489 active_power_control,
14490 has_active_power_control,
14491 };
14492 Ok(true)
14493 })
14494 }
14495}
14496
14497#[unsafe(no_mangle)]
14502pub unsafe extern "C" fn pio_balanced_network_switch_at(
14503 network: *const PioBalancedNetwork,
14504 index: usize,
14505 output: *mut PioBalancedSwitchView,
14506 error: *mut *mut PioError,
14507) -> bool {
14508 unsafe {
14509 entry(error, false, || {
14510 let network = require_balanced_network(network)?;
14511 let switch = network.switches().get(index).ok_or_else(|| {
14512 boundary_error(
14513 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
14514 format!("switch index {index} is out of range"),
14515 )
14516 })?;
14517 let (component_id, has_component_id) = optional_string_view(switch.uid.as_deref());
14518 *require_output(output, "output")? = PioBalancedSwitchView {
14519 component_id,
14520 has_component_id,
14521 from_bus_id: switch.from.0,
14522 to_bus_id: switch.to.0,
14523 closed: switch.closed,
14524 thermal_rating_mva: switch.thermal_rating.unwrap_or(0.0),
14525 has_thermal_rating: switch.thermal_rating.is_some(),
14526 current_rating_a: switch.current_rating.unwrap_or(0.0),
14527 has_current_rating: switch.current_rating.is_some(),
14528 from_active_power_mw: switch.pf.unwrap_or(0.0),
14529 has_from_active_power: switch.pf.is_some(),
14530 from_reactive_power_mvar: switch.qf.unwrap_or(0.0),
14531 has_from_reactive_power: switch.qf.is_some(),
14532 to_active_power_mw: switch.pt.unwrap_or(0.0),
14533 has_to_active_power: switch.pt.is_some(),
14534 to_reactive_power_mvar: switch.qt.unwrap_or(0.0),
14535 has_to_reactive_power: switch.qt.is_some(),
14536 };
14537 Ok(true)
14538 })
14539 }
14540}
14541
14542#[unsafe(no_mangle)]
14547pub unsafe extern "C" fn pio_balanced_network_hvdc_at(
14548 network: *const PioBalancedNetwork,
14549 index: usize,
14550 output: *mut PioBalancedHvdcView,
14551 error: *mut *mut PioError,
14552) -> bool {
14553 unsafe {
14554 entry(error, false, || {
14555 let network = require_balanced_network(network)?;
14556 let hvdc = network.hvdc().get(index).ok_or_else(|| {
14557 boundary_error(
14558 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
14559 format!("HVDC index {index} is out of range"),
14560 )
14561 })?;
14562 let (component_id, has_component_id) = optional_string_view(hvdc.uid.as_deref());
14563 let (converter1, has_converter1) = hvdc_converter_view(hvdc.converter1.as_ref());
14564 let (converter2, has_converter2) = hvdc_converter_view(hvdc.converter2.as_ref());
14565 let (converters_mode, has_converters_mode) = hvdc
14566 .converters_mode
14567 .map_or((PioStringView::EMPTY, false), |mode| {
14568 (PioStringView::new(hvdc_converters_mode_name(mode)), true)
14569 });
14570 let cost = hvdc.cost.as_ref();
14571 *require_output(output, "output")? = PioBalancedHvdcView {
14572 component_id,
14573 has_component_id,
14574 from_bus_id: hvdc.from.0,
14575 to_bus_id: hvdc.to.0,
14576 in_service: hvdc.in_service,
14577 from_active_power_mw: hvdc.pf,
14578 to_active_power_mw: hvdc.pt,
14579 from_reactive_power_mvar: hvdc.qf,
14580 to_reactive_power_mvar: hvdc.qt,
14581 from_voltage_pu: hvdc.vf,
14582 to_voltage_pu: hvdc.vt,
14583 minimum_active_power_mw: hvdc.pmin,
14584 maximum_active_power_mw: hvdc.pmax,
14585 minimum_from_reactive_power_mvar: hvdc.qminf,
14586 maximum_from_reactive_power_mvar: hvdc.qmaxf,
14587 minimum_to_reactive_power_mvar: hvdc.qmint,
14588 maximum_to_reactive_power_mvar: hvdc.qmaxt,
14589 constant_loss_mw: hvdc.loss0,
14590 proportional_loss: hvdc.loss1,
14591 resistance_ohm: hvdc.resistance_ohm.unwrap_or(0.0),
14592 has_resistance: hvdc.resistance_ohm.is_some(),
14593 nominal_voltage_kv: hvdc.nominal_voltage_kv.unwrap_or(0.0),
14594 has_nominal_voltage: hvdc.nominal_voltage_kv.is_some(),
14595 converters_mode,
14596 has_converters_mode,
14597 converter1,
14598 has_converter1,
14599 converter2,
14600 has_converter2,
14601 cost: cost.map_or(
14602 PioGeneratorCostView {
14603 model: 0,
14604 startup: 0.0,
14605 shutdown: 0.0,
14606 ncost: 0,
14607 coefficients: PioF64View::EMPTY,
14608 },
14609 |cost| PioGeneratorCostView {
14610 model: cost.model,
14611 startup: cost.startup,
14612 shutdown: cost.shutdown,
14613 ncost: cost.ncost,
14614 coefficients: PioF64View::new(&cost.coeffs),
14615 },
14616 ),
14617 has_cost: cost.is_some(),
14618 };
14619 Ok(true)
14620 })
14621 }
14622}
14623
14624#[unsafe(no_mangle)]
14629pub unsafe extern "C" fn pio_balanced_network_three_winding_transformer_at(
14630 network: *const PioBalancedNetwork,
14631 index: usize,
14632 output: *mut PioBalancedThreeWindingTransformerView,
14633 error: *mut *mut PioError,
14634) -> bool {
14635 unsafe {
14636 entry(error, false, || {
14637 let network = require_balanced_network(network)?;
14638 let transformer = network.transformers_3w().get(index).ok_or_else(|| {
14639 boundary_error(
14640 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
14641 format!("three winding transformer index {index} is out of range"),
14642 )
14643 })?;
14644 let (component_id, has_component_id) = optional_string_view(transformer.uid.as_deref());
14645 let (name, has_name) = optional_string_view(transformer.name.as_deref());
14646 *require_output(output, "output")? = PioBalancedThreeWindingTransformerView {
14647 component_id,
14648 has_component_id,
14649 name,
14650 has_name,
14651 winding_count: transformer.windings.len(),
14652 impedance_count: transformer.z.len(),
14653 star_voltage_magnitude_pu: transformer.star_vm,
14654 star_voltage_angle_degrees: transformer.star_va,
14655 magnetizing_conductance_pu: transformer.mag_g,
14656 magnetizing_susceptance_pu: transformer.mag_b,
14657 in_service: transformer.in_service,
14658 magnetizing_connection: PioStringView::new(magnetizing_connection_name(
14659 transformer.magnetizing_connection,
14660 )),
14661 };
14662 Ok(true)
14663 })
14664 }
14665}
14666
14667fn magnetizing_connection_name(connection: powerio::MagnetizingConnection) -> &'static str {
14669 match connection {
14670 powerio::MagnetizingConnection::Winding1Terminal => "winding1_terminal",
14671 _ => "star_point",
14672 }
14673}
14674
14675#[unsafe(no_mangle)]
14680pub unsafe extern "C" fn pio_balanced_network_three_winding_transformer_winding_at(
14681 network: *const PioBalancedNetwork,
14682 transformer_index: usize,
14683 winding_index: usize,
14684 output: *mut PioThreeWindingTransformerWindingView,
14685 error: *mut *mut PioError,
14686) -> bool {
14687 unsafe {
14688 entry(error, false, || {
14689 let network = require_balanced_network(network)?;
14690 let transformer = network
14691 .transformers_3w()
14692 .get(transformer_index)
14693 .ok_or_else(|| {
14694 boundary_error(
14695 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
14696 format!(
14697 "three winding transformer index {transformer_index} is out of range"
14698 ),
14699 )
14700 })?;
14701 let winding = transformer.windings.get(winding_index).ok_or_else(|| {
14702 boundary_error(
14703 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
14704 format!("winding index {winding_index} is out of range"),
14705 )
14706 })?;
14707 let (control, has_control) = transformer_control_view(winding.control.as_ref());
14708 *require_output(output, "output")? = PioThreeWindingTransformerWindingView {
14709 bus_id: winding.bus.0,
14710 tap_ratio: winding.tap,
14711 phase_shift_degrees: winding.shift,
14712 nominal_voltage_kv: winding.nominal_kv,
14713 rating_a_mva: winding.rate_a,
14714 rating_b_mva: winding.rate_b,
14715 rating_c_mva: winding.rate_c,
14716 control,
14717 has_control,
14718 };
14719 Ok(true)
14720 })
14721 }
14722}
14723
14724#[unsafe(no_mangle)]
14729pub unsafe extern "C" fn pio_balanced_network_three_winding_transformer_impedance_at(
14730 network: *const PioBalancedNetwork,
14731 transformer_index: usize,
14732 impedance_index: usize,
14733 output: *mut PioThreeWindingTransformerImpedanceView,
14734 error: *mut *mut PioError,
14735) -> bool {
14736 unsafe {
14737 entry(error, false, || {
14738 let network = require_balanced_network(network)?;
14739 let transformer = network
14740 .transformers_3w()
14741 .get(transformer_index)
14742 .ok_or_else(|| {
14743 boundary_error(
14744 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
14745 format!(
14746 "three winding transformer index {transformer_index} is out of range"
14747 ),
14748 )
14749 })?;
14750 let impedance = transformer.z.get(impedance_index).ok_or_else(|| {
14751 boundary_error(
14752 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
14753 format!("impedance index {impedance_index} is out of range"),
14754 )
14755 })?;
14756 *require_output(output, "output")? = PioThreeWindingTransformerImpedanceView {
14757 resistance_pu: impedance.r,
14758 reactance_pu: impedance.x,
14759 base_mva: impedance.base_mva,
14760 };
14761 Ok(true)
14762 })
14763 }
14764}
14765
14766#[unsafe(no_mangle)]
14771pub unsafe extern "C" fn pio_balanced_network_area_at(
14772 network: *const PioBalancedNetwork,
14773 index: usize,
14774 output: *mut PioBalancedAreaView,
14775 error: *mut *mut PioError,
14776) -> bool {
14777 unsafe {
14778 entry(error, false, || {
14779 let network = require_balanced_network(network)?;
14780 let area = network.areas().get(index).ok_or_else(|| {
14781 boundary_error(
14782 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
14783 format!("area index {index} is out of range"),
14784 )
14785 })?;
14786 let (name, has_name) = optional_string_view(area.name.as_deref());
14787 let (component_id, has_component_id) = optional_string_view(area.uid.as_deref());
14788 let (area_type, has_area_type) = optional_string_view(area.area_type.as_deref());
14789 *require_output(output, "output")? = PioBalancedAreaView {
14790 number: area.number,
14791 slack_bus_id: area.slack_bus.map_or(0, |bus| bus.0),
14792 has_slack_bus: area.slack_bus.is_some(),
14793 net_interchange_mw: area.net_interchange,
14794 tolerance_mw: area.tolerance,
14795 name,
14796 has_name,
14797 component_id,
14798 has_component_id,
14799 area_type,
14800 has_area_type,
14801 };
14802 Ok(true)
14803 })
14804 }
14805}
14806
14807#[unsafe(no_mangle)]
14812pub unsafe extern "C" fn pio_balanced_network_retain(
14813 network: *const PioBalancedNetwork,
14814) -> *mut PioBalancedNetwork {
14815 unsafe { PioBalancedNetwork::retain_raw(network) }
14816}
14817
14818#[unsafe(no_mangle)]
14823pub unsafe extern "C" fn pio_balanced_network_release(network: *mut PioBalancedNetwork) {
14824 unsafe { PioBalancedNetwork::release_raw(network) };
14825}
14826
14827unsafe fn require_multiconductor_network<'a>(
14828 network: *const PioMulticonductorNetwork,
14829) -> Result<&'a powerio_dist::MulticonductorNetwork, *mut PioError> {
14830 unsafe { PioMulticonductorNetwork::get(network) }
14831 .and_then(MulticonductorNetworkInner::network)
14832 .ok_or_else(|| {
14833 boundary_error(
14834 &codes::BIND_CAPI_NULL_HANDLE,
14835 "PioMulticonductorNetwork must not be NULL",
14836 )
14837 })
14838}
14839
14840fn optional_f64_view(value: Option<&[f64]>) -> (PioF64View, bool) {
14841 value.map_or((PioF64View::EMPTY, false), |value| {
14842 (PioF64View::new(value), true)
14843 })
14844}
14845
14846fn dist_coords_kind_name(kind: powerio_dist::DistCoordsKind) -> &'static str {
14847 match kind {
14848 powerio_dist::DistCoordsKind::Source => "source",
14849 powerio_dist::DistCoordsKind::Synthetic => "synthetic",
14850 powerio_dist::DistCoordsKind::Manual => "manual",
14851 powerio_dist::DistCoordsKind::Derived => "derived",
14852 _ => "unknown",
14853 }
14854}
14855
14856fn multiconductor_location_view(
14857 location: &powerio_dist::DistLocation,
14858) -> PioMulticonductorLocationView {
14859 let (kind, has_kind) = location.kind.map_or((PioStringView::EMPTY, false), |kind| {
14860 (PioStringView::new(dist_coords_kind_name(kind)), true)
14861 });
14862 PioMulticonductorLocationView {
14863 x: location.x,
14864 y: location.y,
14865 kind,
14866 has_kind,
14867 }
14868}
14869
14870fn empty_multiconductor_location_view() -> PioMulticonductorLocationView {
14871 PioMulticonductorLocationView {
14872 x: 0.0,
14873 y: 0.0,
14874 kind: PioStringView::EMPTY,
14875 has_kind: false,
14876 }
14877}
14878
14879fn multiconductor_geo_view(geo: Option<&powerio_dist::DistGeoMeta>) -> PioMulticonductorGeoView {
14880 let Some(geo) = geo else {
14881 return PioMulticonductorGeoView {
14882 has_geo: false,
14883 space: PioStringView::EMPTY,
14884 crs: PioStringView::EMPTY,
14885 has_crs: false,
14886 kind: PioStringView::EMPTY,
14887 has_kind: false,
14888 has_canvas: false,
14889 canvas_width: 0.0,
14890 has_canvas_width: false,
14891 canvas_height: 0.0,
14892 has_canvas_height: false,
14893 canvas_units: PioStringView::EMPTY,
14894 has_canvas_units: false,
14895 };
14896 };
14897 let (space, crs, has_crs, canvas) = match &geo.space {
14898 powerio_dist::CoordinateSpace::Geographic { crs } => (
14899 "geographic",
14900 crs.as_deref()
14901 .map_or(PioStringView::EMPTY, PioStringView::new),
14902 crs.is_some(),
14903 None,
14904 ),
14905 powerio_dist::CoordinateSpace::Projected { crs } => (
14906 "projected",
14907 crs.as_deref()
14908 .map_or(PioStringView::EMPTY, PioStringView::new),
14909 crs.is_some(),
14910 None,
14911 ),
14912 powerio_dist::CoordinateSpace::Diagram { canvas } => {
14913 ("diagram", PioStringView::EMPTY, false, canvas.as_ref())
14914 }
14915 powerio_dist::CoordinateSpace::Unknown => ("unknown", PioStringView::EMPTY, false, None),
14916 _ => ("unknown", PioStringView::EMPTY, false, None),
14917 };
14918 let (kind, has_kind) = geo.kind.map_or((PioStringView::EMPTY, false), |kind| {
14919 (PioStringView::new(dist_coords_kind_name(kind)), true)
14920 });
14921 PioMulticonductorGeoView {
14922 has_geo: true,
14923 space: PioStringView::new(space),
14924 crs,
14925 has_crs,
14926 kind,
14927 has_kind,
14928 has_canvas: canvas.is_some(),
14929 canvas_width: canvas.and_then(|canvas| canvas.width).unwrap_or(0.0),
14930 has_canvas_width: canvas.is_some_and(|canvas| canvas.width.is_some()),
14931 canvas_height: canvas.and_then(|canvas| canvas.height).unwrap_or(0.0),
14932 has_canvas_height: canvas.is_some_and(|canvas| canvas.height.is_some()),
14933 canvas_units: canvas
14934 .and_then(|canvas| canvas.units.as_deref())
14935 .map_or(PioStringView::EMPTY, PioStringView::new),
14936 has_canvas_units: canvas.is_some_and(|canvas| canvas.units.is_some()),
14937 }
14938}
14939
14940fn multiconductor_configuration_name(configuration: powerio_dist::Configuration) -> &'static str {
14941 match configuration {
14942 powerio_dist::Configuration::Wye => "wye",
14943 powerio_dist::Configuration::Delta => "delta",
14944 powerio_dist::Configuration::SinglePhase => "single_phase",
14945 _ => "unknown",
14946 }
14947}
14948
14949fn multiconductor_winding_connection_name(
14950 connection: powerio_dist::DistWindingConn,
14951) -> &'static str {
14952 match connection {
14953 powerio_dist::DistWindingConn::Wye => "wye",
14954 powerio_dist::DistWindingConn::Delta => "delta",
14955 _ => "unknown",
14956 }
14957}
14958
14959fn inverter_topology_name(topology: powerio_dist::IbrTopology) -> &'static str {
14960 match topology {
14961 powerio_dist::IbrTopology::SinglePhase => "SINGLE_PHASE",
14962 powerio_dist::IbrTopology::ThreeLeg => "THREE_LEG",
14963 powerio_dist::IbrTopology::FourLeg => "FOUR_LEG",
14964 _ => "UNKNOWN",
14965 }
14966}
14967
14968fn inverter_prime_mover_name(prime_mover: powerio_dist::IbrPrimeMover) -> &'static str {
14969 match prime_mover {
14970 powerio_dist::IbrPrimeMover::Pv => "PV",
14971 powerio_dist::IbrPrimeMover::Battery => "BATTERY",
14972 powerio_dist::IbrPrimeMover::Generic => "GENERIC",
14973 powerio_dist::IbrPrimeMover::Statcom => "STATCOM",
14974 powerio_dist::IbrPrimeMover::Dstatcom => "DSTATCOM",
14975 _ => "UNKNOWN",
14976 }
14977}
14978
14979fn inverter_voltage_aggregation_name(
14980 aggregation: powerio_dist::IbrVoltageAggregation,
14981) -> &'static str {
14982 match aggregation {
14983 powerio_dist::IbrVoltageAggregation::PerPhase => "PER_PHASE",
14984 powerio_dist::IbrVoltageAggregation::Average => "AVERAGE",
14985 _ => "UNKNOWN",
14986 }
14987}
14988
14989fn control_voltage_reference_name(
14990 reference: powerio_dist::ControlVoltageReference,
14991) -> &'static str {
14992 match reference {
14993 powerio_dist::ControlVoltageReference::PnPerPhase => "PN_PER_PHASE",
14994 powerio_dist::ControlVoltageReference::PpPerPhase => "PP_PER_PHASE",
14995 powerio_dist::ControlVoltageReference::PpAveraged => "PP_AVERAGED",
14996 powerio_dist::ControlVoltageReference::PgAveraged => "PG_AVERAGED",
14997 powerio_dist::ControlVoltageReference::PnAveraged => "PN_AVERAGED",
14998 powerio_dist::ControlVoltageReference::PgPerPhase => "PG_PER_PHASE",
14999 _ => "UNKNOWN",
15000 }
15001}
15002
15003fn reactive_power_unit_name(unit: powerio_dist::ReactivePowerUnit) -> &'static str {
15004 match unit {
15005 powerio_dist::ReactivePowerUnit::VaFraction => "VA_FRACTION",
15006 powerio_dist::ReactivePowerUnit::Var => "VAR",
15007 _ => "UNKNOWN",
15008 }
15009}
15010
15011fn active_power_unit_name(unit: powerio_dist::ActivePowerUnit) -> &'static str {
15012 match unit {
15013 powerio_dist::ActivePowerUnit::VaFraction => "VA_FRACTION",
15014 powerio_dist::ActivePowerUnit::W => "W",
15015 _ => "UNKNOWN",
15016 }
15017}
15018
15019fn reactive_power_reference_name(reference: powerio_dist::ReactivePowerReference) -> &'static str {
15020 match reference {
15021 powerio_dist::ReactivePowerReference::VarMax => "VAR_MAX",
15022 powerio_dist::ReactivePowerReference::VarAvailable => "VAR_AVAILABLE",
15023 _ => "UNKNOWN",
15024 }
15025}
15026
15027fn active_power_reference_name(reference: powerio_dist::ActivePowerReference) -> &'static str {
15028 match reference {
15029 powerio_dist::ActivePowerReference::PAvailable => "P_AVAILABLE",
15030 powerio_dist::ActivePowerReference::PMax => "P_MAX",
15031 powerio_dist::ActivePowerReference::SMax => "S_MAX",
15032 _ => "UNKNOWN",
15033 }
15034}
15035
15036fn string_slice_at(
15037 values: &[String],
15038 index: usize,
15039 description: &str,
15040) -> Result<PioStringView, *mut PioError> {
15041 values
15042 .get(index)
15043 .map(|value| PioStringView::new(value))
15044 .ok_or_else(|| {
15045 boundary_error(
15046 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
15047 format!("{description} index {index} is out of range"),
15048 )
15049 })
15050}
15051
15052fn conductor_matrix_row(
15053 matrix: &powerio_dist::ConductorMatrix,
15054 row_index: usize,
15055 description: &str,
15056) -> Result<PioF64View, *mut PioError> {
15057 matrix
15058 .get(row_index)
15059 .map(|row| PioF64View::new(row))
15060 .ok_or_else(|| {
15061 boundary_error(
15062 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
15063 format!("{description} row index {row_index} is out of range"),
15064 )
15065 })
15066}
15067
15068fn multiconductor_bus_view(bus: &powerio_dist::DistBus) -> PioMulticonductorBusView {
15069 let (vpn_min, has_vpn_min) = optional_f64_view(bus.vpn_min.as_deref());
15070 let (vpn_max, has_vpn_max) = optional_f64_view(bus.vpn_max.as_deref());
15071 let (vpp_min, has_vpp_min) = optional_f64_view(bus.vpp_min.as_deref());
15072 let (vpp_max, has_vpp_max) = optional_f64_view(bus.vpp_max.as_deref());
15073 let (location, has_location) = bus
15074 .location
15075 .as_ref()
15076 .map_or((empty_multiconductor_location_view(), false), |location| {
15077 (multiconductor_location_view(location), true)
15078 });
15079 PioMulticonductorBusView {
15080 id: PioStringView::new(&bus.id),
15081 terminal_count: bus.terminals.len(),
15082 grounded_terminal_count: bus.grounded.len(),
15083 voltage_min_v: bus.v_min.unwrap_or(0.0),
15084 has_voltage_min: bus.v_min.is_some(),
15085 voltage_max_v: bus.v_max.unwrap_or(0.0),
15086 has_voltage_max: bus.v_max.is_some(),
15087 phase_to_ground_voltage_min_v: optional_f64_view(bus.v_min_phase.as_deref()).0,
15088 has_phase_to_ground_voltage_min: bus.v_min_phase.is_some(),
15089 phase_to_ground_voltage_max_v: optional_f64_view(bus.v_max_phase.as_deref()).0,
15090 has_phase_to_ground_voltage_max: bus.v_max_phase.is_some(),
15091 phase_to_neutral_voltage_min_v: vpn_min,
15092 has_phase_to_neutral_voltage_min: has_vpn_min,
15093 phase_to_neutral_voltage_max_v: vpn_max,
15094 has_phase_to_neutral_voltage_max: has_vpn_max,
15095 phase_to_phase_voltage_min_v: vpp_min,
15096 has_phase_to_phase_voltage_min: has_vpp_min,
15097 phase_to_phase_voltage_max_v: vpp_max,
15098 has_phase_to_phase_voltage_max: has_vpp_max,
15099 positive_sequence_voltage_min_v: bus.vpos_min.unwrap_or(0.0),
15100 has_positive_sequence_voltage_min: bus.vpos_min.is_some(),
15101 positive_sequence_voltage_max_v: bus.vpos_max.unwrap_or(0.0),
15102 has_positive_sequence_voltage_max: bus.vpos_max.is_some(),
15103 negative_sequence_voltage_max_v: bus.vneg_max.unwrap_or(0.0),
15104 has_negative_sequence_voltage_max: bus.vneg_max.is_some(),
15105 zero_sequence_voltage_max_v: bus.vzero_max.unwrap_or(0.0),
15106 has_zero_sequence_voltage_max: bus.vzero_max.is_some(),
15107 neutral_to_ground_voltage_max_v: bus.vn_max.unwrap_or(0.0),
15108 has_neutral_to_ground_voltage_max: bus.vn_max.is_some(),
15109 location,
15110 has_location,
15111 }
15112}
15113
15114fn multiconductor_line_code_view(
15115 line_code: &powerio_dist::DistLineCode,
15116) -> PioMulticonductorLineCodeView {
15117 let (current_limit, has_current_limit) = optional_f64_view(line_code.i_max.as_deref());
15118 let (apparent_power_limit, has_apparent_power_limit) =
15119 optional_f64_view(line_code.s_max.as_deref());
15120 let (source, has_source) = optional_string_view(line_code.source.as_deref());
15121 PioMulticonductorLineCodeView {
15122 name: PioStringView::new(&line_code.name),
15123 conductor_count: line_code.n_conductors,
15124 resistance_matrix_row_count: line_code.r_series.len(),
15125 reactance_matrix_row_count: line_code.x_series.len(),
15126 conductance_from_matrix_row_count: line_code.g_from.len(),
15127 susceptance_from_matrix_row_count: line_code.b_from.len(),
15128 conductance_to_matrix_row_count: line_code.g_to.len(),
15129 susceptance_to_matrix_row_count: line_code.b_to.len(),
15130 current_limit_a: current_limit,
15131 has_current_limit,
15132 apparent_power_limit_va: apparent_power_limit,
15133 has_apparent_power_limit,
15134 source,
15135 has_source,
15136 }
15137}
15138
15139fn multiconductor_line_view(line: &powerio_dist::DistLine) -> PioMulticonductorLineView {
15140 let (current_limit, has_current_limit) = optional_f64_view(line.i_max.as_deref());
15141 let (apparent_power_limit, has_apparent_power_limit) = optional_f64_view(line.s_max.as_deref());
15142 PioMulticonductorLineView {
15143 name: PioStringView::new(&line.name),
15144 bus_from: PioStringView::new(&line.bus_from),
15145 bus_to: PioStringView::new(&line.bus_to),
15146 terminal_map_from_count: line.terminal_map_from.len(),
15147 terminal_map_to_count: line.terminal_map_to.len(),
15148 line_code: PioStringView::new(&line.linecode),
15149 length_m: line.length,
15150 route_point_count: line.route.as_ref().map_or(0, Vec::len),
15151 has_route: line.route.is_some(),
15152 current_limit_a: current_limit,
15153 has_current_limit,
15154 apparent_power_limit_va: apparent_power_limit,
15155 has_apparent_power_limit,
15156 }
15157}
15158
15159fn multiconductor_switch_view(switch: &powerio_dist::DistSwitch) -> PioMulticonductorSwitchView {
15160 let (current_limit, has_current_limit) = optional_f64_view(switch.i_max.as_deref());
15161 PioMulticonductorSwitchView {
15162 name: PioStringView::new(&switch.name),
15163 bus_from: PioStringView::new(&switch.bus_from),
15164 bus_to: PioStringView::new(&switch.bus_to),
15165 terminal_map_from_count: switch.terminal_map_from.len(),
15166 terminal_map_to_count: switch.terminal_map_to.len(),
15167 open: switch.open,
15168 current_limit_a: current_limit,
15169 has_current_limit,
15170 }
15171}
15172
15173fn dist_load_voltage_model_view(
15174 model: &powerio_dist::DistLoadVoltageModel,
15175) -> PioDistLoadVoltageModelView {
15176 use powerio_dist::DistLoadVoltageModel as M;
15177 let empty = PioF64View::EMPTY;
15178 let mut view = PioDistLoadVoltageModelView {
15179 model: PioStringView::new(dist_load_voltage_model_name(model)),
15180 nominal_voltage_v: PioF64View::new(model.v_nom()),
15181 active_power_constant_impedance: empty,
15182 active_power_constant_current: empty,
15183 active_power_constant_power: empty,
15184 reactive_power_constant_impedance: empty,
15185 reactive_power_constant_current: empty,
15186 reactive_power_constant_power: empty,
15187 active_power_exponent: empty,
15188 reactive_power_exponent: empty,
15189 voltage_low_pu: 0.0,
15190 has_voltage_low: false,
15191 voltage_min_pu: 0.0,
15192 has_voltage_min: false,
15193 voltage_max_pu: 0.0,
15194 has_voltage_max: false,
15195 cutoff_pu: 0.0,
15196 has_cutoff: false,
15197 current_limit_pu: 0.0,
15198 has_current_limit: false,
15199 };
15200 match model {
15201 M::Zip {
15202 alpha_z,
15203 alpha_i,
15204 alpha_p,
15205 beta_z,
15206 beta_i,
15207 beta_p,
15208 ..
15209 }
15210 | M::BoundedZip {
15211 alpha_z,
15212 alpha_i,
15213 alpha_p,
15214 beta_z,
15215 beta_i,
15216 beta_p,
15217 ..
15218 } => {
15219 view.active_power_constant_impedance = PioF64View::new(alpha_z);
15220 view.active_power_constant_current = PioF64View::new(alpha_i);
15221 view.active_power_constant_power = PioF64View::new(alpha_p);
15222 view.reactive_power_constant_impedance = PioF64View::new(beta_z);
15223 view.reactive_power_constant_current = PioF64View::new(beta_i);
15224 view.reactive_power_constant_power = PioF64View::new(beta_p);
15225 }
15226 M::Exponential {
15227 gamma_p, gamma_q, ..
15228 }
15229 | M::BoundedExponential {
15230 gamma_p, gamma_q, ..
15231 } => {
15232 view.active_power_exponent = PioF64View::new(gamma_p);
15233 view.reactive_power_exponent = PioF64View::new(gamma_q);
15234 }
15235 _ => {}
15236 }
15237 match model {
15238 M::BoundedZip {
15239 v_low_pu,
15240 v_min_pu,
15241 v_max_pu,
15242 cutoff_pu,
15243 ..
15244 } => {
15245 view.voltage_low_pu = *v_low_pu;
15246 view.has_voltage_low = true;
15247 view.voltage_min_pu = *v_min_pu;
15248 view.has_voltage_min = true;
15249 view.voltage_max_pu = *v_max_pu;
15250 view.has_voltage_max = true;
15251 view.cutoff_pu = *cutoff_pu;
15252 view.has_cutoff = true;
15253 }
15254 M::BoundedExponential {
15255 v_low_pu,
15256 v_min_pu,
15257 v_max_pu,
15258 ..
15259 } => {
15260 view.voltage_low_pu = *v_low_pu;
15261 view.has_voltage_low = true;
15262 view.voltage_min_pu = *v_min_pu;
15263 view.has_voltage_min = true;
15264 view.voltage_max_pu = *v_max_pu;
15265 view.has_voltage_max = true;
15266 }
15267 M::BoundedConstantPower {
15268 v_min_pu,
15269 v_max_pu,
15270 current_limit_pu,
15271 ..
15272 } => {
15273 view.voltage_min_pu = *v_min_pu;
15274 view.has_voltage_min = true;
15275 view.voltage_max_pu = *v_max_pu;
15276 view.has_voltage_max = true;
15277 if let Some(limit) = current_limit_pu {
15278 view.current_limit_pu = *limit;
15279 view.has_current_limit = true;
15280 }
15281 }
15282 _ => {}
15283 }
15284 view
15285}
15286
15287fn multiconductor_load_view(load: &powerio_dist::DistLoad) -> PioMulticonductorLoadView {
15288 let model = dist_load_voltage_model_view(&load.voltage_model);
15289 PioMulticonductorLoadView {
15290 name: PioStringView::new(&load.name),
15291 bus: PioStringView::new(&load.bus),
15292 terminal_map_count: load.terminal_map.len(),
15293 configuration: PioStringView::new(multiconductor_configuration_name(load.configuration)),
15294 active_power_nominal_w: PioF64View::new(&load.p_nom),
15295 reactive_power_nominal_var: PioF64View::new(&load.q_nom),
15296 voltage_model: model.model,
15297 nominal_voltage_v: model.nominal_voltage_v,
15298 active_power_constant_impedance: model.active_power_constant_impedance,
15299 active_power_constant_current: model.active_power_constant_current,
15300 active_power_constant_power: model.active_power_constant_power,
15301 reactive_power_constant_impedance: model.reactive_power_constant_impedance,
15302 reactive_power_constant_current: model.reactive_power_constant_current,
15303 reactive_power_constant_power: model.reactive_power_constant_power,
15304 active_power_exponent: model.active_power_exponent,
15305 reactive_power_exponent: model.reactive_power_exponent,
15306 }
15307}
15308
15309fn multiconductor_generator_view(
15310 generator: &powerio_dist::DistGenerator,
15311) -> PioMulticonductorGeneratorView {
15312 let (p_min, has_p_min) = optional_f64_view(generator.p_min.as_deref());
15313 let (p_max, has_p_max) = optional_f64_view(generator.p_max.as_deref());
15314 let (q_min, has_q_min) = optional_f64_view(generator.q_min.as_deref());
15315 let (q_max, has_q_max) = optional_f64_view(generator.q_max.as_deref());
15316 let (cost, has_cost) = optional_f64_view(generator.cost.as_deref());
15317 let (s_max, has_s_max) = optional_f64_view(generator.s_max.as_deref());
15318 let (i_max, has_i_max) = optional_f64_view(generator.i_max.as_deref());
15319 PioMulticonductorGeneratorView {
15320 name: PioStringView::new(&generator.name),
15321 bus: PioStringView::new(&generator.bus),
15322 terminal_map_count: generator.terminal_map.len(),
15323 configuration: PioStringView::new(multiconductor_configuration_name(
15324 generator.configuration,
15325 )),
15326 active_power_nominal_w: PioF64View::new(&generator.p_nom),
15327 reactive_power_nominal_var: PioF64View::new(&generator.q_nom),
15328 active_power_min_w: p_min,
15329 has_active_power_min: has_p_min,
15330 active_power_max_w: p_max,
15331 has_active_power_max: has_p_max,
15332 reactive_power_min_var: q_min,
15333 has_reactive_power_min: has_q_min,
15334 reactive_power_max_var: q_max,
15335 has_reactive_power_max: has_q_max,
15336 active_power_dispatch_cost_per_kwh: cost,
15337 has_active_power_dispatch_cost: has_cost,
15338 apparent_power_limit_va: s_max,
15339 has_apparent_power_limit: has_s_max,
15340 current_limit_a: i_max,
15341 has_current_limit: has_i_max,
15342 }
15343}
15344
15345fn inverter_based_resource_view(ibr: &powerio_dist::DistIbr) -> PioInverterBasedResourceView {
15346 let (i_max, has_i_max) = optional_f64_view(ibr.i_max.as_deref());
15347 let (p_min, has_p_min) = optional_f64_view(ibr.p_min.as_deref());
15348 let (p_max, has_p_max) = optional_f64_view(ibr.p_max.as_deref());
15349 let (q_min, has_q_min) = optional_f64_view(ibr.q_min.as_deref());
15350 let (q_max, has_q_max) = optional_f64_view(ibr.q_max.as_deref());
15351 let (control_profile, has_control_profile) =
15352 optional_string_view(ibr.control_profile.as_deref());
15353 let (voltage_aggregation, has_voltage_aggregation) =
15354 ibr.voltage_aggregation
15355 .map_or((PioStringView::EMPTY, false), |aggregation| {
15356 (
15357 PioStringView::new(inverter_voltage_aggregation_name(aggregation)),
15358 true,
15359 )
15360 });
15361 PioInverterBasedResourceView {
15362 name: PioStringView::new(&ibr.name),
15363 bus: PioStringView::new(&ibr.bus),
15364 terminal_map_count: ibr.terminal_map.len(),
15365 topology: PioStringView::new(inverter_topology_name(ibr.topology)),
15366 prime_mover: PioStringView::new(inverter_prime_mover_name(ibr.prime_mover)),
15367 apparent_power_limit_va: PioF64View::new(&ibr.s_max),
15368 current_limit_a: i_max,
15369 has_current_limit: has_i_max,
15370 active_power_available_w: ibr.p_avail.unwrap_or(0.0),
15371 has_active_power_available: ibr.p_avail.is_some(),
15372 active_power_min_w: p_min,
15373 has_active_power_min: has_p_min,
15374 active_power_max_w: p_max,
15375 has_active_power_max: has_p_max,
15376 reactive_power_min_var: q_min,
15377 has_reactive_power_min: has_q_min,
15378 reactive_power_max_var: q_max,
15379 has_reactive_power_max: has_q_max,
15380 control_profile,
15381 has_control_profile,
15382 voltage_aggregation,
15383 has_voltage_aggregation,
15384 }
15385}
15386
15387fn control_profile_view(profile: &powerio_dist::DistControlProfile) -> PioControlProfileView {
15388 let power_factor = profile.power_factor.as_ref();
15389 let volt_var = profile.volt_var.as_ref();
15390 let volt_watt = profile.volt_watt.as_ref();
15391 let (vv_voltage_reference, has_vv_voltage_reference) = volt_var
15392 .and_then(|control| control.voltage_reference)
15393 .map_or((PioStringView::EMPTY, false), |reference| {
15394 (
15395 PioStringView::new(control_voltage_reference_name(reference)),
15396 true,
15397 )
15398 });
15399 let (vv_q_unit, has_vv_q_unit) = volt_var
15400 .and_then(|control| control.q_unit)
15401 .map_or((PioStringView::EMPTY, false), |unit| {
15402 (PioStringView::new(reactive_power_unit_name(unit)), true)
15403 });
15404 let (vv_q_ref, has_vv_q_ref) = volt_var.and_then(|control| control.q_ref).map_or(
15405 (PioStringView::EMPTY, false),
15406 |reference| {
15407 (
15408 PioStringView::new(reactive_power_reference_name(reference)),
15409 true,
15410 )
15411 },
15412 );
15413 let (vw_voltage_reference, has_vw_voltage_reference) = volt_watt
15414 .and_then(|control| control.voltage_reference)
15415 .map_or((PioStringView::EMPTY, false), |reference| {
15416 (
15417 PioStringView::new(control_voltage_reference_name(reference)),
15418 true,
15419 )
15420 });
15421 let (vw_p_unit, has_vw_p_unit) = volt_watt
15422 .and_then(|control| control.p_unit)
15423 .map_or((PioStringView::EMPTY, false), |unit| {
15424 (PioStringView::new(active_power_unit_name(unit)), true)
15425 });
15426 let (vw_p_ref, has_vw_p_ref) = volt_watt.and_then(|control| control.p_ref).map_or(
15427 (PioStringView::EMPTY, false),
15428 |reference| {
15429 (
15430 PioStringView::new(active_power_reference_name(reference)),
15431 true,
15432 )
15433 },
15434 );
15435 PioControlProfileView {
15436 name: PioStringView::new(&profile.name),
15437 has_power_factor: power_factor.is_some(),
15438 power_factor: power_factor.map_or(0.0, |control| control.pf),
15439 has_volt_var: volt_var.is_some(),
15440 volt_var_voltage_reference: vv_voltage_reference,
15441 has_volt_var_voltage_reference: has_vv_voltage_reference,
15442 volt_var_breakpoints: volt_var.map_or(PioF64View::EMPTY, |control| {
15443 PioF64View::new(&control.breakpoints)
15444 }),
15445 volt_var_reactive_power_limits: volt_var.map_or(PioF64View::EMPTY, |control| {
15446 PioF64View::new(&control.q_limits)
15447 }),
15448 volt_var_reactive_power_unit: vv_q_unit,
15449 has_volt_var_reactive_power_unit: has_vv_q_unit,
15450 volt_var_reactive_power_reference: vv_q_ref,
15451 has_volt_var_reactive_power_reference: has_vv_q_ref,
15452 volt_var_active_power_min_for_reactive_power_w: volt_var
15453 .and_then(|control| control.p_min_for_q)
15454 .unwrap_or(0.0),
15455 has_volt_var_active_power_min_for_reactive_power: volt_var
15456 .is_some_and(|control| control.p_min_for_q.is_some()),
15457 volt_var_active_power_min_for_max_reactive_power_w: volt_var
15458 .and_then(|control| control.p_min_for_q_max)
15459 .unwrap_or(0.0),
15460 has_volt_var_active_power_min_for_max_reactive_power: volt_var
15461 .is_some_and(|control| control.p_min_for_q_max.is_some()),
15462 has_volt_watt: volt_watt.is_some(),
15463 volt_watt_voltage_reference: vw_voltage_reference,
15464 has_volt_watt_voltage_reference: has_vw_voltage_reference,
15465 volt_watt_breakpoints: volt_watt.map_or(PioF64View::EMPTY, |control| {
15466 PioF64View::new(&control.breakpoints)
15467 }),
15468 volt_watt_active_power_limits: volt_watt.map_or(PioF64View::EMPTY, |control| {
15469 PioF64View::new(&control.p_limits)
15470 }),
15471 volt_watt_active_power_unit: vw_p_unit,
15472 has_volt_watt_active_power_unit: has_vw_p_unit,
15473 volt_watt_active_power_reference: vw_p_ref,
15474 has_volt_watt_active_power_reference: has_vw_p_ref,
15475 }
15476}
15477
15478#[unsafe(no_mangle)]
15482pub unsafe extern "C" fn pio_multiconductor_network_name(
15483 network: *const PioMulticonductorNetwork,
15484) -> PioStringView {
15485 unsafe { PioMulticonductorNetwork::get(network) }
15486 .and_then(MulticonductorNetworkInner::network)
15487 .and_then(|network| network.name().as_deref())
15488 .map_or(PioStringView::EMPTY, PioStringView::new)
15489}
15490
15491#[unsafe(no_mangle)]
15495pub unsafe extern "C" fn pio_multiconductor_network_has_name(
15496 network: *const PioMulticonductorNetwork,
15497) -> bool {
15498 unsafe { PioMulticonductorNetwork::get(network) }
15499 .and_then(MulticonductorNetworkInner::network)
15500 .is_some_and(|network| network.name().is_some())
15501}
15502
15503#[unsafe(no_mangle)]
15507pub unsafe extern "C" fn pio_multiconductor_network_source_format(
15508 network: *const PioMulticonductorNetwork,
15509) -> PioStringView {
15510 unsafe { PioMulticonductorNetwork::get(network) }
15511 .and_then(MulticonductorNetworkInner::network)
15512 .and_then(|network| *network.source_format())
15513 .map_or(PioStringView::EMPTY, |format| {
15514 PioStringView::new(format.name())
15515 })
15516}
15517
15518#[unsafe(no_mangle)]
15522pub unsafe extern "C" fn pio_multiconductor_network_has_source_format(
15523 network: *const PioMulticonductorNetwork,
15524) -> bool {
15525 unsafe { PioMulticonductorNetwork::get(network) }
15526 .and_then(MulticonductorNetworkInner::network)
15527 .is_some_and(|network| network.source_format().is_some())
15528}
15529
15530#[unsafe(no_mangle)]
15535pub unsafe extern "C" fn pio_multiconductor_network_geo(
15536 network: *const PioMulticonductorNetwork,
15537 output: *mut PioMulticonductorGeoView,
15538 error: *mut *mut PioError,
15539) -> bool {
15540 unsafe {
15541 entry(error, false, || {
15542 let network = require_multiconductor_network(network)?;
15543 *require_output(output, "output")? = multiconductor_geo_view(network.geo().as_ref());
15544 Ok(true)
15545 })
15546 }
15547}
15548
15549#[unsafe(no_mangle)]
15555pub unsafe extern "C" fn pio_multiconductor_network_counts(
15556 network: *const PioMulticonductorNetwork,
15557 output: *mut PioMulticonductorNetworkCountsView,
15558 error: *mut *mut PioError,
15559) -> bool {
15560 unsafe {
15561 entry(error, false, || {
15562 let network = require_multiconductor_network(network)?;
15563 *require_output(output, "output")? = PioMulticonductorNetworkCountsView {
15564 buses: network.buses().len(),
15565 line_codes: network.line_codes().len(),
15566 lines: network.lines().len(),
15567 switches: network.switches().len(),
15568 transformers: network.transformers().len(),
15569 loads: network.loads().len(),
15570 generators: network.generators().len(),
15571 inverter_based_resources: network.ibrs().len(),
15572 control_profiles: network.control_profiles().len(),
15573 shunts: network.shunts().len(),
15574 capacitors: network.capacitors().len(),
15575 voltage_sources: network.sources().len(),
15576 untyped_objects: network.untyped_objects().len(),
15577 commands: network.commands().len(),
15578 options: network.options().len(),
15579 };
15580 Ok(true)
15581 })
15582 }
15583}
15584
15585#[unsafe(no_mangle)]
15589pub unsafe extern "C" fn pio_multiconductor_network_base_frequency_hz(
15590 network: *const PioMulticonductorNetwork,
15591) -> f64 {
15592 unsafe { PioMulticonductorNetwork::get(network) }
15593 .and_then(MulticonductorNetworkInner::network)
15594 .map_or(f64::NAN, |network| network.base_frequency())
15595}
15596
15597#[unsafe(no_mangle)]
15601pub unsafe extern "C" fn pio_multiconductor_network_bus_count(
15602 network: *const PioMulticonductorNetwork,
15603) -> usize {
15604 unsafe { PioMulticonductorNetwork::get(network) }
15605 .and_then(MulticonductorNetworkInner::network)
15606 .map_or(0, |network| network.buses().len())
15607}
15608
15609#[unsafe(no_mangle)]
15613pub unsafe extern "C" fn pio_multiconductor_network_line_count(
15614 network: *const PioMulticonductorNetwork,
15615) -> usize {
15616 unsafe { PioMulticonductorNetwork::get(network) }
15617 .and_then(MulticonductorNetworkInner::network)
15618 .map_or(0, |network| network.lines().len())
15619}
15620
15621#[unsafe(no_mangle)]
15625pub unsafe extern "C" fn pio_multiconductor_network_load_count(
15626 network: *const PioMulticonductorNetwork,
15627) -> usize {
15628 unsafe { PioMulticonductorNetwork::get(network) }
15629 .and_then(MulticonductorNetworkInner::network)
15630 .map_or(0, |network| network.loads().len())
15631}
15632
15633#[unsafe(no_mangle)]
15637pub unsafe extern "C" fn pio_multiconductor_network_generator_count(
15638 network: *const PioMulticonductorNetwork,
15639) -> usize {
15640 unsafe { PioMulticonductorNetwork::get(network) }
15641 .and_then(MulticonductorNetworkInner::network)
15642 .map_or(0, |network| network.generators().len())
15643}
15644
15645#[unsafe(no_mangle)]
15651pub unsafe extern "C" fn pio_multiconductor_network_bus_at(
15652 network: *const PioMulticonductorNetwork,
15653 index: usize,
15654 output: *mut PioMulticonductorBusView,
15655 error: *mut *mut PioError,
15656) -> bool {
15657 unsafe {
15658 entry(error, false, || {
15659 let network = require_multiconductor_network(network)?;
15660 let bus = network.buses().get(index).ok_or_else(|| {
15661 boundary_error(
15662 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
15663 format!("multiconductor bus index {index} is out of range"),
15664 )
15665 })?;
15666 *require_output(output, "output")? = multiconductor_bus_view(bus);
15667 Ok(true)
15668 })
15669 }
15670}
15671
15672#[unsafe(no_mangle)]
15676pub unsafe extern "C" fn pio_multiconductor_network_bus_terminal_at(
15677 network: *const PioMulticonductorNetwork,
15678 bus_index: usize,
15679 terminal_index: usize,
15680 output: *mut PioStringView,
15681 error: *mut *mut PioError,
15682) -> bool {
15683 unsafe {
15684 entry(error, false, || {
15685 let network = require_multiconductor_network(network)?;
15686 let bus = network.buses().get(bus_index).ok_or_else(|| {
15687 boundary_error(
15688 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
15689 format!("multiconductor bus index {bus_index} is out of range"),
15690 )
15691 })?;
15692 *require_output(output, "output")? =
15693 string_slice_at(&bus.terminals, terminal_index, "bus terminal")?;
15694 Ok(true)
15695 })
15696 }
15697}
15698
15699#[unsafe(no_mangle)]
15703pub unsafe extern "C" fn pio_multiconductor_network_bus_grounded_terminal_at(
15704 network: *const PioMulticonductorNetwork,
15705 bus_index: usize,
15706 terminal_index: usize,
15707 output: *mut PioStringView,
15708 error: *mut *mut PioError,
15709) -> bool {
15710 unsafe {
15711 entry(error, false, || {
15712 let network = require_multiconductor_network(network)?;
15713 let bus = network.buses().get(bus_index).ok_or_else(|| {
15714 boundary_error(
15715 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
15716 format!("multiconductor bus index {bus_index} is out of range"),
15717 )
15718 })?;
15719 *require_output(output, "output")? =
15720 string_slice_at(&bus.grounded, terminal_index, "grounded bus terminal")?;
15721 Ok(true)
15722 })
15723 }
15724}
15725
15726#[unsafe(no_mangle)]
15730pub unsafe extern "C" fn pio_multiconductor_network_line_code_at(
15731 network: *const PioMulticonductorNetwork,
15732 index: usize,
15733 output: *mut PioMulticonductorLineCodeView,
15734 error: *mut *mut PioError,
15735) -> bool {
15736 unsafe {
15737 entry(error, false, || {
15738 let network = require_multiconductor_network(network)?;
15739 let line_code = network.line_codes().get(index).ok_or_else(|| {
15740 boundary_error(
15741 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
15742 format!("multiconductor line code index {index} is out of range"),
15743 )
15744 })?;
15745 *require_output(output, "output")? = multiconductor_line_code_view(line_code);
15746 Ok(true)
15747 })
15748 }
15749}
15750
15751fn multiconductor_line_code_matrix<'a>(
15752 network: &'a powerio_dist::MulticonductorNetwork,
15753 line_code_index: usize,
15754 matrix: &str,
15755) -> Result<&'a powerio_dist::ConductorMatrix, *mut PioError> {
15756 let line_code = network.line_codes().get(line_code_index).ok_or_else(|| {
15757 boundary_error(
15758 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
15759 format!("multiconductor line code index {line_code_index} is out of range"),
15760 )
15761 })?;
15762 Ok(match matrix {
15763 "resistance" => &line_code.r_series,
15764 "reactance" => &line_code.x_series,
15765 "conductance_from" => &line_code.g_from,
15766 "susceptance_from" => &line_code.b_from,
15767 "conductance_to" => &line_code.g_to,
15768 "susceptance_to" => &line_code.b_to,
15769 _ => {
15770 return Err(boundary_error(
15771 &codes::REQUEST_CAPI_TYPE_MISMATCH,
15772 "unsupported line code matrix",
15773 ));
15774 }
15775 })
15776}
15777
15778unsafe fn write_multiconductor_line_code_matrix_row(
15779 network: *const PioMulticonductorNetwork,
15780 line_code_index: usize,
15781 row_index: usize,
15782 matrix: &str,
15783 output: *mut PioF64View,
15784 error: *mut *mut PioError,
15785) -> bool {
15786 unsafe {
15787 entry(error, false, || {
15788 let network = require_multiconductor_network(network)?;
15789 let values = multiconductor_line_code_matrix(network, line_code_index, matrix)?;
15790 *require_output(output, "output")? =
15791 conductor_matrix_row(values, row_index, &format!("line code {matrix} matrix"))?;
15792 Ok(true)
15793 })
15794 }
15795}
15796
15797#[unsafe(no_mangle)]
15801pub unsafe extern "C" fn pio_multiconductor_network_line_code_resistance_matrix_row_at(
15802 network: *const PioMulticonductorNetwork,
15803 line_code_index: usize,
15804 row_index: usize,
15805 output: *mut PioF64View,
15806 error: *mut *mut PioError,
15807) -> bool {
15808 unsafe {
15809 write_multiconductor_line_code_matrix_row(
15810 network,
15811 line_code_index,
15812 row_index,
15813 "resistance",
15814 output,
15815 error,
15816 )
15817 }
15818}
15819
15820#[unsafe(no_mangle)]
15824pub unsafe extern "C" fn pio_multiconductor_network_line_code_reactance_matrix_row_at(
15825 network: *const PioMulticonductorNetwork,
15826 line_code_index: usize,
15827 row_index: usize,
15828 output: *mut PioF64View,
15829 error: *mut *mut PioError,
15830) -> bool {
15831 unsafe {
15832 write_multiconductor_line_code_matrix_row(
15833 network,
15834 line_code_index,
15835 row_index,
15836 "reactance",
15837 output,
15838 error,
15839 )
15840 }
15841}
15842
15843#[unsafe(no_mangle)]
15847pub unsafe extern "C" fn pio_multiconductor_network_line_code_conductance_from_matrix_row_at(
15848 network: *const PioMulticonductorNetwork,
15849 line_code_index: usize,
15850 row_index: usize,
15851 output: *mut PioF64View,
15852 error: *mut *mut PioError,
15853) -> bool {
15854 unsafe {
15855 write_multiconductor_line_code_matrix_row(
15856 network,
15857 line_code_index,
15858 row_index,
15859 "conductance_from",
15860 output,
15861 error,
15862 )
15863 }
15864}
15865
15866#[unsafe(no_mangle)]
15870pub unsafe extern "C" fn pio_multiconductor_network_line_code_susceptance_from_matrix_row_at(
15871 network: *const PioMulticonductorNetwork,
15872 line_code_index: usize,
15873 row_index: usize,
15874 output: *mut PioF64View,
15875 error: *mut *mut PioError,
15876) -> bool {
15877 unsafe {
15878 write_multiconductor_line_code_matrix_row(
15879 network,
15880 line_code_index,
15881 row_index,
15882 "susceptance_from",
15883 output,
15884 error,
15885 )
15886 }
15887}
15888
15889#[unsafe(no_mangle)]
15893pub unsafe extern "C" fn pio_multiconductor_network_line_code_conductance_to_matrix_row_at(
15894 network: *const PioMulticonductorNetwork,
15895 line_code_index: usize,
15896 row_index: usize,
15897 output: *mut PioF64View,
15898 error: *mut *mut PioError,
15899) -> bool {
15900 unsafe {
15901 write_multiconductor_line_code_matrix_row(
15902 network,
15903 line_code_index,
15904 row_index,
15905 "conductance_to",
15906 output,
15907 error,
15908 )
15909 }
15910}
15911
15912#[unsafe(no_mangle)]
15916pub unsafe extern "C" fn pio_multiconductor_network_line_code_susceptance_to_matrix_row_at(
15917 network: *const PioMulticonductorNetwork,
15918 line_code_index: usize,
15919 row_index: usize,
15920 output: *mut PioF64View,
15921 error: *mut *mut PioError,
15922) -> bool {
15923 unsafe {
15924 write_multiconductor_line_code_matrix_row(
15925 network,
15926 line_code_index,
15927 row_index,
15928 "susceptance_to",
15929 output,
15930 error,
15931 )
15932 }
15933}
15934
15935#[unsafe(no_mangle)]
15939pub unsafe extern "C" fn pio_multiconductor_network_line_at(
15940 network: *const PioMulticonductorNetwork,
15941 index: usize,
15942 output: *mut PioMulticonductorLineView,
15943 error: *mut *mut PioError,
15944) -> bool {
15945 unsafe {
15946 entry(error, false, || {
15947 let network = require_multiconductor_network(network)?;
15948 let line = network.lines().get(index).ok_or_else(|| {
15949 boundary_error(
15950 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
15951 format!("multiconductor line index {index} is out of range"),
15952 )
15953 })?;
15954 *require_output(output, "output")? = multiconductor_line_view(line);
15955 Ok(true)
15956 })
15957 }
15958}
15959
15960unsafe fn write_multiconductor_line_terminal(
15961 network: *const PioMulticonductorNetwork,
15962 line_index: usize,
15963 terminal_index: usize,
15964 from: bool,
15965 output: *mut PioStringView,
15966 error: *mut *mut PioError,
15967) -> bool {
15968 unsafe {
15969 entry(error, false, || {
15970 let network = require_multiconductor_network(network)?;
15971 let line = network.lines().get(line_index).ok_or_else(|| {
15972 boundary_error(
15973 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
15974 format!("multiconductor line index {line_index} is out of range"),
15975 )
15976 })?;
15977 let (terminals, description) = if from {
15978 (&line.terminal_map_from, "line from terminal")
15979 } else {
15980 (&line.terminal_map_to, "line to terminal")
15981 };
15982 *require_output(output, "output")? =
15983 string_slice_at(terminals, terminal_index, description)?;
15984 Ok(true)
15985 })
15986 }
15987}
15988
15989#[unsafe(no_mangle)]
15993pub unsafe extern "C" fn pio_multiconductor_network_line_terminal_from_at(
15994 network: *const PioMulticonductorNetwork,
15995 line_index: usize,
15996 terminal_index: usize,
15997 output: *mut PioStringView,
15998 error: *mut *mut PioError,
15999) -> bool {
16000 unsafe {
16001 write_multiconductor_line_terminal(network, line_index, terminal_index, true, output, error)
16002 }
16003}
16004
16005#[unsafe(no_mangle)]
16009pub unsafe extern "C" fn pio_multiconductor_network_line_terminal_to_at(
16010 network: *const PioMulticonductorNetwork,
16011 line_index: usize,
16012 terminal_index: usize,
16013 output: *mut PioStringView,
16014 error: *mut *mut PioError,
16015) -> bool {
16016 unsafe {
16017 write_multiconductor_line_terminal(
16018 network,
16019 line_index,
16020 terminal_index,
16021 false,
16022 output,
16023 error,
16024 )
16025 }
16026}
16027
16028#[unsafe(no_mangle)]
16032pub unsafe extern "C" fn pio_multiconductor_network_line_route_point_at(
16033 network: *const PioMulticonductorNetwork,
16034 line_index: usize,
16035 point_index: usize,
16036 output: *mut PioMulticonductorLocationView,
16037 error: *mut *mut PioError,
16038) -> bool {
16039 unsafe {
16040 entry(error, false, || {
16041 let network = require_multiconductor_network(network)?;
16042 let line = network.lines().get(line_index).ok_or_else(|| {
16043 boundary_error(
16044 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
16045 format!("multiconductor line index {line_index} is out of range"),
16046 )
16047 })?;
16048 let route = line.route.as_ref().ok_or_else(|| {
16049 boundary_error(
16050 &codes::REQUEST_CAPI_TYPE_MISMATCH,
16051 format!("multiconductor line {line_index} has no route"),
16052 )
16053 })?;
16054 let point = route.get(point_index).ok_or_else(|| {
16055 boundary_error(
16056 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
16057 format!("line route point index {point_index} is out of range"),
16058 )
16059 })?;
16060 *require_output(output, "output")? = multiconductor_location_view(point);
16061 Ok(true)
16062 })
16063 }
16064}
16065
16066#[unsafe(no_mangle)]
16070pub unsafe extern "C" fn pio_multiconductor_network_switch_at(
16071 network: *const PioMulticonductorNetwork,
16072 index: usize,
16073 output: *mut PioMulticonductorSwitchView,
16074 error: *mut *mut PioError,
16075) -> bool {
16076 unsafe {
16077 entry(error, false, || {
16078 let network = require_multiconductor_network(network)?;
16079 let switch = network.switches().get(index).ok_or_else(|| {
16080 boundary_error(
16081 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
16082 format!("multiconductor switch index {index} is out of range"),
16083 )
16084 })?;
16085 *require_output(output, "output")? = multiconductor_switch_view(switch);
16086 Ok(true)
16087 })
16088 }
16089}
16090
16091unsafe fn write_multiconductor_switch_terminal(
16092 network: *const PioMulticonductorNetwork,
16093 switch_index: usize,
16094 terminal_index: usize,
16095 from: bool,
16096 output: *mut PioStringView,
16097 error: *mut *mut PioError,
16098) -> bool {
16099 unsafe {
16100 entry(error, false, || {
16101 let network = require_multiconductor_network(network)?;
16102 let switch = network.switches().get(switch_index).ok_or_else(|| {
16103 boundary_error(
16104 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
16105 format!("multiconductor switch index {switch_index} is out of range"),
16106 )
16107 })?;
16108 let (terminals, description) = if from {
16109 (&switch.terminal_map_from, "switch from terminal")
16110 } else {
16111 (&switch.terminal_map_to, "switch to terminal")
16112 };
16113 *require_output(output, "output")? =
16114 string_slice_at(terminals, terminal_index, description)?;
16115 Ok(true)
16116 })
16117 }
16118}
16119
16120#[unsafe(no_mangle)]
16124pub unsafe extern "C" fn pio_multiconductor_network_switch_terminal_from_at(
16125 network: *const PioMulticonductorNetwork,
16126 switch_index: usize,
16127 terminal_index: usize,
16128 output: *mut PioStringView,
16129 error: *mut *mut PioError,
16130) -> bool {
16131 unsafe {
16132 write_multiconductor_switch_terminal(
16133 network,
16134 switch_index,
16135 terminal_index,
16136 true,
16137 output,
16138 error,
16139 )
16140 }
16141}
16142
16143#[unsafe(no_mangle)]
16147pub unsafe extern "C" fn pio_multiconductor_network_switch_terminal_to_at(
16148 network: *const PioMulticonductorNetwork,
16149 switch_index: usize,
16150 terminal_index: usize,
16151 output: *mut PioStringView,
16152 error: *mut *mut PioError,
16153) -> bool {
16154 unsafe {
16155 write_multiconductor_switch_terminal(
16156 network,
16157 switch_index,
16158 terminal_index,
16159 false,
16160 output,
16161 error,
16162 )
16163 }
16164}
16165
16166#[unsafe(no_mangle)]
16170pub unsafe extern "C" fn pio_multiconductor_network_transformer_at(
16171 network: *const PioMulticonductorNetwork,
16172 index: usize,
16173 output: *mut PioMulticonductorTransformerView,
16174 error: *mut *mut PioError,
16175) -> bool {
16176 unsafe {
16177 entry(error, false, || {
16178 let network = require_multiconductor_network(network)?;
16179 let transformer = network.transformers().get(index).ok_or_else(|| {
16180 boundary_error(
16181 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
16182 format!("multiconductor transformer index {index} is out of range"),
16183 )
16184 })?;
16185 *require_output(output, "output")? = PioMulticonductorTransformerView {
16186 name: PioStringView::new(&transformer.name),
16187 winding_count: transformer.windings.len(),
16188 short_circuit_reactance_percent: PioF64View::new(&transformer.xsc_pct),
16189 phase_count: transformer.phases,
16190 };
16191 Ok(true)
16192 })
16193 }
16194}
16195
16196#[unsafe(no_mangle)]
16200pub unsafe extern "C" fn pio_multiconductor_network_transformer_winding_at(
16201 network: *const PioMulticonductorNetwork,
16202 transformer_index: usize,
16203 winding_index: usize,
16204 output: *mut PioMulticonductorTransformerWindingView,
16205 error: *mut *mut PioError,
16206) -> bool {
16207 unsafe {
16208 entry(error, false, || {
16209 let network = require_multiconductor_network(network)?;
16210 let transformer = network
16211 .transformers()
16212 .get(transformer_index)
16213 .ok_or_else(|| {
16214 boundary_error(
16215 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
16216 format!(
16217 "multiconductor transformer index {transformer_index} is out of range"
16218 ),
16219 )
16220 })?;
16221 let winding = transformer.windings.get(winding_index).ok_or_else(|| {
16222 boundary_error(
16223 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
16224 format!("transformer winding index {winding_index} is out of range"),
16225 )
16226 })?;
16227 *require_output(output, "output")? = PioMulticonductorTransformerWindingView {
16228 bus: PioStringView::new(&winding.bus),
16229 terminal_map_count: winding.terminal_map.len(),
16230 connection: PioStringView::new(multiconductor_winding_connection_name(
16231 winding.conn,
16232 )),
16233 rated_voltage_v: winding.v_ref,
16234 apparent_power_rating_va: winding.s_rating,
16235 resistance_percent: winding.r_pct,
16236 tap: winding.tap,
16237 neutral_resistance_ohm: winding.r_neutral.unwrap_or(0.0),
16238 has_neutral_resistance: winding.r_neutral.is_some(),
16239 neutral_reactance_ohm: winding.x_neutral.unwrap_or(0.0),
16240 has_neutral_reactance: winding.x_neutral.is_some(),
16241 };
16242 Ok(true)
16243 })
16244 }
16245}
16246
16247#[unsafe(no_mangle)]
16251pub unsafe extern "C" fn pio_multiconductor_network_transformer_winding_terminal_at(
16252 network: *const PioMulticonductorNetwork,
16253 transformer_index: usize,
16254 winding_index: usize,
16255 terminal_index: usize,
16256 output: *mut PioStringView,
16257 error: *mut *mut PioError,
16258) -> bool {
16259 unsafe {
16260 entry(error, false, || {
16261 let network = require_multiconductor_network(network)?;
16262 let transformer = network
16263 .transformers()
16264 .get(transformer_index)
16265 .ok_or_else(|| {
16266 boundary_error(
16267 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
16268 format!(
16269 "multiconductor transformer index {transformer_index} is out of range"
16270 ),
16271 )
16272 })?;
16273 let winding = transformer.windings.get(winding_index).ok_or_else(|| {
16274 boundary_error(
16275 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
16276 format!("transformer winding index {winding_index} is out of range"),
16277 )
16278 })?;
16279 *require_output(output, "output")? = string_slice_at(
16280 &winding.terminal_map,
16281 terminal_index,
16282 "transformer winding terminal",
16283 )?;
16284 Ok(true)
16285 })
16286 }
16287}
16288
16289#[derive(Clone, Copy)]
16290enum MulticonductorTerminalTable {
16291 Load,
16292 Generator,
16293 InverterBasedResource,
16294 Shunt,
16295 Capacitor,
16296 VoltageSource,
16297}
16298
16299unsafe fn write_multiconductor_terminal(
16300 network: *const PioMulticonductorNetwork,
16301 table: MulticonductorTerminalTable,
16302 element_index: usize,
16303 terminal_index: usize,
16304 output: *mut PioStringView,
16305 error: *mut *mut PioError,
16306) -> bool {
16307 unsafe {
16308 entry(error, false, || {
16309 let network = require_multiconductor_network(network)?;
16310 let (terminals, description): (&[String], &str) = match table {
16311 MulticonductorTerminalTable::Load => (
16312 &network
16313 .loads()
16314 .get(element_index)
16315 .ok_or_else(|| {
16316 boundary_error(
16317 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
16318 format!(
16319 "multiconductor load index {element_index} is out of range"
16320 ),
16321 )
16322 })?
16323 .terminal_map,
16324 "load terminal",
16325 ),
16326 MulticonductorTerminalTable::Generator => (
16327 &network
16328 .generators()
16329 .get(element_index)
16330 .ok_or_else(|| {
16331 boundary_error(
16332 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
16333 format!(
16334 "multiconductor generator index {element_index} is out of range"
16335 ),
16336 )
16337 })?
16338 .terminal_map,
16339 "generator terminal",
16340 ),
16341 MulticonductorTerminalTable::InverterBasedResource => (
16342 &network
16343 .ibrs()
16344 .get(element_index)
16345 .ok_or_else(|| {
16346 boundary_error(
16347 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
16348 format!(
16349 "inverter based resource index {element_index} is out of range"
16350 ),
16351 )
16352 })?
16353 .terminal_map,
16354 "inverter based resource terminal",
16355 ),
16356 MulticonductorTerminalTable::Shunt => (
16357 &network
16358 .shunts()
16359 .get(element_index)
16360 .ok_or_else(|| {
16361 boundary_error(
16362 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
16363 format!(
16364 "multiconductor shunt index {element_index} is out of range"
16365 ),
16366 )
16367 })?
16368 .terminal_map,
16369 "shunt terminal",
16370 ),
16371 MulticonductorTerminalTable::Capacitor => (
16372 &network
16373 .capacitors()
16374 .get(element_index)
16375 .ok_or_else(|| {
16376 boundary_error(
16377 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
16378 format!(
16379 "multiconductor capacitor index {element_index} is out of range"
16380 ),
16381 )
16382 })?
16383 .terminal_map,
16384 "capacitor terminal",
16385 ),
16386 MulticonductorTerminalTable::VoltageSource => (
16387 &network
16388 .sources()
16389 .get(element_index)
16390 .ok_or_else(|| {
16391 boundary_error(
16392 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
16393 format!("voltage source index {element_index} is out of range"),
16394 )
16395 })?
16396 .terminal_map,
16397 "voltage source terminal",
16398 ),
16399 };
16400 *require_output(output, "output")? =
16401 string_slice_at(terminals, terminal_index, description)?;
16402 Ok(true)
16403 })
16404 }
16405}
16406
16407#[unsafe(no_mangle)]
16411pub unsafe extern "C" fn pio_multiconductor_network_load_at(
16412 network: *const PioMulticonductorNetwork,
16413 index: usize,
16414 output: *mut PioMulticonductorLoadView,
16415 error: *mut *mut PioError,
16416) -> bool {
16417 unsafe {
16418 entry(error, false, || {
16419 let network = require_multiconductor_network(network)?;
16420 let load = network.loads().get(index).ok_or_else(|| {
16421 boundary_error(
16422 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
16423 format!("multiconductor load index {index} is out of range"),
16424 )
16425 })?;
16426 require_legacy_load_voltage_model(&load.voltage_model)?;
16427 *require_output(output, "output")? = multiconductor_load_view(load);
16428 Ok(true)
16429 })
16430 }
16431}
16432
16433#[unsafe(no_mangle)]
16438pub unsafe extern "C" fn pio_multiconductor_network_load_details_at(
16439 network: *const PioMulticonductorNetwork,
16440 index: usize,
16441 output: *mut PioMulticonductorLoadDetailsView,
16442 error: *mut *mut PioError,
16443) -> bool {
16444 unsafe {
16445 entry(error, false, || {
16446 let load = require_multiconductor_network(network)?
16447 .loads()
16448 .get(index)
16449 .ok_or_else(|| {
16450 boundary_error(
16451 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
16452 format!("multiconductor load index {index} is out of range"),
16453 )
16454 })?;
16455 *require_output(output, "output")? = PioMulticonductorLoadDetailsView {
16456 name: PioStringView::new(&load.name),
16457 bus: PioStringView::new(&load.bus),
16458 terminal_map_count: load.terminal_map.len(),
16459 configuration: PioStringView::new(multiconductor_configuration_name(
16460 load.configuration,
16461 )),
16462 active_power_nominal_w: PioF64View::new(&load.p_nom),
16463 reactive_power_nominal_var: PioF64View::new(&load.q_nom),
16464 voltage_model: dist_load_voltage_model_view(&load.voltage_model),
16465 };
16466 Ok(true)
16467 })
16468 }
16469}
16470
16471#[unsafe(no_mangle)]
16475pub unsafe extern "C" fn pio_multiconductor_network_load_terminal_at(
16476 network: *const PioMulticonductorNetwork,
16477 load_index: usize,
16478 terminal_index: usize,
16479 output: *mut PioStringView,
16480 error: *mut *mut PioError,
16481) -> bool {
16482 unsafe {
16483 write_multiconductor_terminal(
16484 network,
16485 MulticonductorTerminalTable::Load,
16486 load_index,
16487 terminal_index,
16488 output,
16489 error,
16490 )
16491 }
16492}
16493
16494#[unsafe(no_mangle)]
16498pub unsafe extern "C" fn pio_multiconductor_network_generator_at(
16499 network: *const PioMulticonductorNetwork,
16500 index: usize,
16501 output: *mut PioMulticonductorGeneratorView,
16502 error: *mut *mut PioError,
16503) -> bool {
16504 unsafe {
16505 entry(error, false, || {
16506 let network = require_multiconductor_network(network)?;
16507 let generator = network.generators().get(index).ok_or_else(|| {
16508 boundary_error(
16509 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
16510 format!("multiconductor generator index {index} is out of range"),
16511 )
16512 })?;
16513 *require_output(output, "output")? = multiconductor_generator_view(generator);
16514 Ok(true)
16515 })
16516 }
16517}
16518
16519#[unsafe(no_mangle)]
16523pub unsafe extern "C" fn pio_multiconductor_network_generator_terminal_at(
16524 network: *const PioMulticonductorNetwork,
16525 generator_index: usize,
16526 terminal_index: usize,
16527 output: *mut PioStringView,
16528 error: *mut *mut PioError,
16529) -> bool {
16530 unsafe {
16531 write_multiconductor_terminal(
16532 network,
16533 MulticonductorTerminalTable::Generator,
16534 generator_index,
16535 terminal_index,
16536 output,
16537 error,
16538 )
16539 }
16540}
16541
16542#[unsafe(no_mangle)]
16546pub unsafe extern "C" fn pio_multiconductor_network_inverter_based_resource_at(
16547 network: *const PioMulticonductorNetwork,
16548 index: usize,
16549 output: *mut PioInverterBasedResourceView,
16550 error: *mut *mut PioError,
16551) -> bool {
16552 unsafe {
16553 entry(error, false, || {
16554 let network = require_multiconductor_network(network)?;
16555 let resource = network.ibrs().get(index).ok_or_else(|| {
16556 boundary_error(
16557 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
16558 format!("inverter based resource index {index} is out of range"),
16559 )
16560 })?;
16561 *require_output(output, "output")? = inverter_based_resource_view(resource);
16562 Ok(true)
16563 })
16564 }
16565}
16566
16567#[unsafe(no_mangle)]
16571pub unsafe extern "C" fn pio_multiconductor_network_inverter_based_resource_terminal_at(
16572 network: *const PioMulticonductorNetwork,
16573 resource_index: usize,
16574 terminal_index: usize,
16575 output: *mut PioStringView,
16576 error: *mut *mut PioError,
16577) -> bool {
16578 unsafe {
16579 write_multiconductor_terminal(
16580 network,
16581 MulticonductorTerminalTable::InverterBasedResource,
16582 resource_index,
16583 terminal_index,
16584 output,
16585 error,
16586 )
16587 }
16588}
16589
16590#[unsafe(no_mangle)]
16594pub unsafe extern "C" fn pio_multiconductor_network_control_profile_at(
16595 network: *const PioMulticonductorNetwork,
16596 index: usize,
16597 output: *mut PioControlProfileView,
16598 error: *mut *mut PioError,
16599) -> bool {
16600 unsafe {
16601 entry(error, false, || {
16602 let network = require_multiconductor_network(network)?;
16603 let profile = network.control_profiles().get(index).ok_or_else(|| {
16604 boundary_error(
16605 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
16606 format!("control profile index {index} is out of range"),
16607 )
16608 })?;
16609 *require_output(output, "output")? = control_profile_view(profile);
16610 Ok(true)
16611 })
16612 }
16613}
16614
16615#[unsafe(no_mangle)]
16619pub unsafe extern "C" fn pio_multiconductor_network_shunt_at(
16620 network: *const PioMulticonductorNetwork,
16621 index: usize,
16622 output: *mut PioMulticonductorShuntView,
16623 error: *mut *mut PioError,
16624) -> bool {
16625 unsafe {
16626 entry(error, false, || {
16627 let network = require_multiconductor_network(network)?;
16628 let shunt = network.shunts().get(index).ok_or_else(|| {
16629 boundary_error(
16630 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
16631 format!("multiconductor shunt index {index} is out of range"),
16632 )
16633 })?;
16634 *require_output(output, "output")? = PioMulticonductorShuntView {
16635 name: PioStringView::new(&shunt.name),
16636 bus: PioStringView::new(&shunt.bus),
16637 terminal_map_count: shunt.terminal_map.len(),
16638 conductance_matrix_row_count: shunt.g.len(),
16639 susceptance_matrix_row_count: shunt.b.len(),
16640 };
16641 Ok(true)
16642 })
16643 }
16644}
16645
16646#[unsafe(no_mangle)]
16650pub unsafe extern "C" fn pio_multiconductor_network_shunt_terminal_at(
16651 network: *const PioMulticonductorNetwork,
16652 shunt_index: usize,
16653 terminal_index: usize,
16654 output: *mut PioStringView,
16655 error: *mut *mut PioError,
16656) -> bool {
16657 unsafe {
16658 write_multiconductor_terminal(
16659 network,
16660 MulticonductorTerminalTable::Shunt,
16661 shunt_index,
16662 terminal_index,
16663 output,
16664 error,
16665 )
16666 }
16667}
16668
16669unsafe fn write_multiconductor_shunt_matrix_row(
16670 network: *const PioMulticonductorNetwork,
16671 shunt_index: usize,
16672 row_index: usize,
16673 conductance: bool,
16674 output: *mut PioF64View,
16675 error: *mut *mut PioError,
16676) -> bool {
16677 unsafe {
16678 entry(error, false, || {
16679 let network = require_multiconductor_network(network)?;
16680 let shunt = network.shunts().get(shunt_index).ok_or_else(|| {
16681 boundary_error(
16682 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
16683 format!("multiconductor shunt index {shunt_index} is out of range"),
16684 )
16685 })?;
16686 let (matrix, description) = if conductance {
16687 (&shunt.g, "shunt conductance matrix")
16688 } else {
16689 (&shunt.b, "shunt susceptance matrix")
16690 };
16691 *require_output(output, "output")? =
16692 conductor_matrix_row(matrix, row_index, description)?;
16693 Ok(true)
16694 })
16695 }
16696}
16697
16698#[unsafe(no_mangle)]
16702pub unsafe extern "C" fn pio_multiconductor_network_shunt_conductance_matrix_row_at(
16703 network: *const PioMulticonductorNetwork,
16704 shunt_index: usize,
16705 row_index: usize,
16706 output: *mut PioF64View,
16707 error: *mut *mut PioError,
16708) -> bool {
16709 unsafe {
16710 write_multiconductor_shunt_matrix_row(network, shunt_index, row_index, true, output, error)
16711 }
16712}
16713
16714#[unsafe(no_mangle)]
16718pub unsafe extern "C" fn pio_multiconductor_network_shunt_susceptance_matrix_row_at(
16719 network: *const PioMulticonductorNetwork,
16720 shunt_index: usize,
16721 row_index: usize,
16722 output: *mut PioF64View,
16723 error: *mut *mut PioError,
16724) -> bool {
16725 unsafe {
16726 write_multiconductor_shunt_matrix_row(network, shunt_index, row_index, false, output, error)
16727 }
16728}
16729
16730#[unsafe(no_mangle)]
16734pub unsafe extern "C" fn pio_multiconductor_network_capacitor_at(
16735 network: *const PioMulticonductorNetwork,
16736 index: usize,
16737 output: *mut PioMulticonductorCapacitorView,
16738 error: *mut *mut PioError,
16739) -> bool {
16740 unsafe {
16741 entry(error, false, || {
16742 let network = require_multiconductor_network(network)?;
16743 let capacitor = network.capacitors().get(index).ok_or_else(|| {
16744 boundary_error(
16745 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
16746 format!("multiconductor capacitor index {index} is out of range"),
16747 )
16748 })?;
16749 *require_output(output, "output")? = PioMulticonductorCapacitorView {
16750 name: PioStringView::new(&capacitor.name),
16751 bus: PioStringView::new(&capacitor.bus),
16752 terminal_map_count: capacitor.terminal_map.len(),
16753 configuration: PioStringView::new(multiconductor_configuration_name(
16754 capacitor.configuration,
16755 )),
16756 rated_reactive_power_var: capacitor.q_rated,
16757 nominal_voltage_v: capacitor.v_nom,
16758 };
16759 Ok(true)
16760 })
16761 }
16762}
16763
16764#[unsafe(no_mangle)]
16768pub unsafe extern "C" fn pio_multiconductor_network_capacitor_terminal_at(
16769 network: *const PioMulticonductorNetwork,
16770 capacitor_index: usize,
16771 terminal_index: usize,
16772 output: *mut PioStringView,
16773 error: *mut *mut PioError,
16774) -> bool {
16775 unsafe {
16776 write_multiconductor_terminal(
16777 network,
16778 MulticonductorTerminalTable::Capacitor,
16779 capacitor_index,
16780 terminal_index,
16781 output,
16782 error,
16783 )
16784 }
16785}
16786
16787#[unsafe(no_mangle)]
16791pub unsafe extern "C" fn pio_multiconductor_network_voltage_source_at(
16792 network: *const PioMulticonductorNetwork,
16793 index: usize,
16794 output: *mut PioVoltageSourceView,
16795 error: *mut *mut PioError,
16796) -> bool {
16797 unsafe {
16798 entry(error, false, || {
16799 let network = require_multiconductor_network(network)?;
16800 let source = network.sources().get(index).ok_or_else(|| {
16801 boundary_error(
16802 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
16803 format!("voltage source index {index} is out of range"),
16804 )
16805 })?;
16806 if source.reference_terminal.is_some() {
16807 return Err(boundary_error(
16808 &codes::REQUEST_CAPI_TYPE_MISMATCH,
16809 "PioVoltageSourceView cannot describe a reference-terminal source",
16810 ));
16811 }
16812 *require_output(output, "output")? = voltage_source_view(source);
16813 Ok(true)
16814 })
16815 }
16816}
16817
16818#[unsafe(no_mangle)]
16822pub unsafe extern "C" fn pio_multiconductor_network_voltage_source_terminal_at(
16823 network: *const PioMulticonductorNetwork,
16824 source_index: usize,
16825 terminal_index: usize,
16826 output: *mut PioStringView,
16827 error: *mut *mut PioError,
16828) -> bool {
16829 unsafe {
16830 write_multiconductor_terminal(
16831 network,
16832 MulticonductorTerminalTable::VoltageSource,
16833 source_index,
16834 terminal_index,
16835 output,
16836 error,
16837 )
16838 }
16839}
16840
16841#[unsafe(no_mangle)]
16845pub unsafe extern "C" fn pio_multiconductor_network_untyped_object_at(
16846 network: *const PioMulticonductorNetwork,
16847 index: usize,
16848 output: *mut PioMulticonductorUntypedObjectView,
16849 error: *mut *mut PioError,
16850) -> bool {
16851 unsafe {
16852 entry(error, false, || {
16853 let network = require_multiconductor_network(network)?;
16854 let object = network.untyped_objects().get(index).ok_or_else(|| {
16855 boundary_error(
16856 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
16857 format!("untyped object index {index} is out of range"),
16858 )
16859 })?;
16860 *require_output(output, "output")? = PioMulticonductorUntypedObjectView {
16861 class_name: PioStringView::new(&object.class),
16862 name: PioStringView::new(&object.name),
16863 property_count: object.props.len(),
16864 };
16865 Ok(true)
16866 })
16867 }
16868}
16869
16870#[unsafe(no_mangle)]
16874pub unsafe extern "C" fn pio_multiconductor_network_untyped_object_property_at(
16875 network: *const PioMulticonductorNetwork,
16876 object_index: usize,
16877 property_index: usize,
16878 output: *mut PioMulticonductorUntypedPropertyView,
16879 error: *mut *mut PioError,
16880) -> bool {
16881 unsafe {
16882 entry(error, false, || {
16883 let network = require_multiconductor_network(network)?;
16884 let object = network.untyped_objects().get(object_index).ok_or_else(|| {
16885 boundary_error(
16886 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
16887 format!("untyped object index {object_index} is out of range"),
16888 )
16889 })?;
16890 let (name, value) = object.props.get(property_index).ok_or_else(|| {
16891 boundary_error(
16892 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
16893 format!("untyped object property index {property_index} is out of range"),
16894 )
16895 })?;
16896 let (name, has_name) = optional_string_view(name.as_deref());
16897 *require_output(output, "output")? = PioMulticonductorUntypedPropertyView {
16898 name,
16899 has_name,
16900 value: PioStringView::new(value),
16901 };
16902 Ok(true)
16903 })
16904 }
16905}
16906
16907#[unsafe(no_mangle)]
16911pub unsafe extern "C" fn pio_multiconductor_network_command_at(
16912 network: *const PioMulticonductorNetwork,
16913 index: usize,
16914 output: *mut PioMulticonductorCommandView,
16915 error: *mut *mut PioError,
16916) -> bool {
16917 unsafe {
16918 entry(error, false, || {
16919 let network = require_multiconductor_network(network)?;
16920 let (verb, args) = network.commands().get(index).ok_or_else(|| {
16921 boundary_error(
16922 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
16923 format!("source command index {index} is out of range"),
16924 )
16925 })?;
16926 *require_output(output, "output")? = PioMulticonductorCommandView {
16927 verb: PioStringView::new(verb),
16928 args: PioStringView::new(args),
16929 };
16930 Ok(true)
16931 })
16932 }
16933}
16934
16935#[unsafe(no_mangle)]
16939pub unsafe extern "C" fn pio_multiconductor_network_option_at(
16940 network: *const PioMulticonductorNetwork,
16941 index: usize,
16942 output: *mut PioStringPropertyView,
16943 error: *mut *mut PioError,
16944) -> bool {
16945 unsafe {
16946 entry(error, false, || {
16947 let network = require_multiconductor_network(network)?;
16948 let (name, value) = network.options().get(index).ok_or_else(|| {
16949 boundary_error(
16950 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
16951 format!("source option index {index} is out of range"),
16952 )
16953 })?;
16954 *require_output(output, "output")? = PioStringPropertyView {
16955 name: PioStringView::new(name),
16956 value: PioStringView::new(value),
16957 };
16958 Ok(true)
16959 })
16960 }
16961}
16962
16963#[unsafe(no_mangle)]
16968pub unsafe extern "C" fn pio_multiconductor_network_retain(
16969 network: *const PioMulticonductorNetwork,
16970) -> *mut PioMulticonductorNetwork {
16971 unsafe { PioMulticonductorNetwork::retain_raw(network) }
16972}
16973
16974#[unsafe(no_mangle)]
16979pub unsafe extern "C" fn pio_multiconductor_network_release(
16980 network: *mut PioMulticonductorNetwork,
16981) {
16982 unsafe { PioMulticonductorNetwork::release_raw(network) };
16983}
16984
16985opaque_handle!(
16988 PioComponentId,
16990 ComponentId
16991);
16992opaque_handle!(
16993 PioActivePower,
16995 ActivePower
16996);
16997opaque_handle!(
16998 PioReactivePower,
17000 ReactivePower
17001);
17002opaque_handle!(
17003 PioApparentPower,
17005 ApparentPower
17006);
17007opaque_handle!(
17008 PioOperatingPointUpdate,
17010 OperatingPointUpdate
17011);
17012opaque_handle!(
17013 PioNetworkUpdate,
17015 NetworkUpdate
17016);
17017opaque_handle!(
17018 PioCalculationUpdate,
17020 CalculationUpdate
17021);
17022
17023struct UpdateReportInner {
17024 changes: Vec<UpdateChange>,
17025 connectivity_changed: bool,
17026}
17027
17028struct UpdateChangeInner {
17029 owner: Arc<UpdateReportInner>,
17030 index: usize,
17031}
17032
17033impl UpdateChangeInner {
17034 fn change(&self) -> Option<&UpdateChange> {
17035 self.owner.changes.get(self.index)
17036 }
17037}
17038
17039opaque_handle!(
17040 PioUpdateReport,
17042 UpdateReportInner
17043);
17044opaque_handle!(
17045 PioUpdateChange,
17047 UpdateChangeInner
17048);
17049
17050unsafe fn require_handle<'a, T>(
17051 handle: *const HandleBox<T>,
17052 name: &str,
17053) -> Result<&'a T, *mut PioError> {
17054 unsafe { handle_get(handle) }.ok_or_else(|| {
17055 boundary_error(
17056 &codes::BIND_CAPI_NULL_HANDLE,
17057 format!("{name} must not be NULL"),
17058 )
17059 })
17060}
17061
17062unsafe fn optional_owned_string(
17063 value: *const c_char,
17064 value_len: usize,
17065 name: &str,
17066) -> Result<Option<String>, *mut PioError> {
17067 unsafe { optional_str(value, value_len, name) }.map(|value| value.map(str::to_owned))
17068}
17069
17070#[unsafe(no_mangle)]
17075pub unsafe extern "C" fn pio_component_id_new(
17076 component_type: *const c_char,
17077 component_type_len: usize,
17078 local_id: *const c_char,
17079 local_id_len: usize,
17080 error: *mut *mut PioError,
17081) -> *mut PioComponentId {
17082 unsafe {
17083 entry(error, std::ptr::null_mut(), || {
17084 let component_type =
17085 required_str(component_type, component_type_len, "component_type")?;
17086 let local_id = required_str(local_id, local_id_len, "local_id")?;
17087 ComponentId::new(component_type, local_id)
17088 .map(PioComponentId::new_raw)
17089 .map_err(|failure| error_from_core(&failure))
17090 })
17091 }
17092}
17093
17094#[unsafe(no_mangle)]
17098pub unsafe extern "C" fn pio_component_id_type(component: *const PioComponentId) -> PioStringView {
17099 unsafe { PioComponentId::get(component) }.map_or(PioStringView::EMPTY, |component| {
17100 PioStringView::new(component.component_type())
17101 })
17102}
17103
17104#[unsafe(no_mangle)]
17108pub unsafe extern "C" fn pio_component_id_local_id(
17109 component: *const PioComponentId,
17110) -> PioStringView {
17111 unsafe { PioComponentId::get(component) }.map_or(PioStringView::EMPTY, |component| {
17112 PioStringView::new(component.local_id())
17113 })
17114}
17115
17116#[unsafe(no_mangle)]
17121pub unsafe extern "C" fn pio_component_id_retain(
17122 component: *const PioComponentId,
17123) -> *mut PioComponentId {
17124 unsafe { PioComponentId::retain_raw(component) }
17125}
17126
17127#[unsafe(no_mangle)]
17132pub unsafe extern "C" fn pio_component_id_release(component: *mut PioComponentId) {
17133 unsafe { PioComponentId::release_raw(component) };
17134}
17135
17136#[unsafe(no_mangle)]
17137pub extern "C" fn pio_active_power_from_watts(value: f64) -> *mut PioActivePower {
17138 PioActivePower::new_raw(ActivePower::from_watts(value))
17139}
17140
17141#[unsafe(no_mangle)]
17142pub extern "C" fn pio_active_power_from_megawatts(value: f64) -> *mut PioActivePower {
17143 PioActivePower::new_raw(ActivePower::from_megawatts(value))
17144}
17145
17146#[unsafe(no_mangle)]
17150pub unsafe extern "C" fn pio_active_power_value(power: *const PioActivePower) -> f64 {
17151 unsafe { PioActivePower::get(power) }.map_or(f64::NAN, |power| power.value())
17152}
17153
17154#[unsafe(no_mangle)]
17158pub unsafe extern "C" fn pio_active_power_unit(power: *const PioActivePower) -> PioStringView {
17159 unsafe { PioActivePower::get(power) }.map_or(PioStringView::EMPTY, |power| {
17160 PioStringView::new(match power.unit() {
17161 ActivePowerUnit::Watts => "watts",
17162 ActivePowerUnit::Megawatts => "megawatts",
17163 _ => "unknown",
17164 })
17165 })
17166}
17167
17168#[unsafe(no_mangle)]
17173pub unsafe extern "C" fn pio_active_power_retain(
17174 power: *const PioActivePower,
17175) -> *mut PioActivePower {
17176 unsafe { PioActivePower::retain_raw(power) }
17177}
17178
17179#[unsafe(no_mangle)]
17184pub unsafe extern "C" fn pio_active_power_release(power: *mut PioActivePower) {
17185 unsafe { PioActivePower::release_raw(power) };
17186}
17187
17188#[unsafe(no_mangle)]
17189pub extern "C" fn pio_reactive_power_from_vars(value: f64) -> *mut PioReactivePower {
17190 PioReactivePower::new_raw(ReactivePower::from_vars(value))
17191}
17192
17193#[unsafe(no_mangle)]
17194pub extern "C" fn pio_reactive_power_from_megavars(value: f64) -> *mut PioReactivePower {
17195 PioReactivePower::new_raw(ReactivePower::from_megavars(value))
17196}
17197
17198#[unsafe(no_mangle)]
17202pub unsafe extern "C" fn pio_reactive_power_value(power: *const PioReactivePower) -> f64 {
17203 unsafe { PioReactivePower::get(power) }.map_or(f64::NAN, |power| power.value())
17204}
17205
17206#[unsafe(no_mangle)]
17210pub unsafe extern "C" fn pio_reactive_power_unit(power: *const PioReactivePower) -> PioStringView {
17211 unsafe { PioReactivePower::get(power) }.map_or(PioStringView::EMPTY, |power| {
17212 PioStringView::new(match power.unit() {
17213 ReactivePowerUnit::Vars => "vars",
17214 ReactivePowerUnit::Megavars => "megavars",
17215 _ => "unknown",
17216 })
17217 })
17218}
17219
17220#[unsafe(no_mangle)]
17225pub unsafe extern "C" fn pio_reactive_power_retain(
17226 power: *const PioReactivePower,
17227) -> *mut PioReactivePower {
17228 unsafe { PioReactivePower::retain_raw(power) }
17229}
17230
17231#[unsafe(no_mangle)]
17236pub unsafe extern "C" fn pio_reactive_power_release(power: *mut PioReactivePower) {
17237 unsafe { PioReactivePower::release_raw(power) };
17238}
17239
17240#[unsafe(no_mangle)]
17241pub extern "C" fn pio_apparent_power_from_volt_amperes(value: f64) -> *mut PioApparentPower {
17242 PioApparentPower::new_raw(ApparentPower::from_volt_amperes(value))
17243}
17244
17245#[unsafe(no_mangle)]
17246pub extern "C" fn pio_apparent_power_from_megavolt_amperes(value: f64) -> *mut PioApparentPower {
17247 PioApparentPower::new_raw(ApparentPower::from_megavolt_amperes(value))
17248}
17249
17250#[unsafe(no_mangle)]
17254pub unsafe extern "C" fn pio_apparent_power_value(power: *const PioApparentPower) -> f64 {
17255 unsafe { PioApparentPower::get(power) }.map_or(f64::NAN, |power| power.value())
17256}
17257
17258#[unsafe(no_mangle)]
17262pub unsafe extern "C" fn pio_apparent_power_unit(power: *const PioApparentPower) -> PioStringView {
17263 unsafe { PioApparentPower::get(power) }.map_or(PioStringView::EMPTY, |power| {
17264 PioStringView::new(match power.unit() {
17265 ApparentPowerUnit::VoltAmperes => "volt_amperes",
17266 ApparentPowerUnit::MegavoltAmperes => "megavolt_amperes",
17267 _ => "unknown",
17268 })
17269 })
17270}
17271
17272#[unsafe(no_mangle)]
17277pub unsafe extern "C" fn pio_apparent_power_retain(
17278 power: *const PioApparentPower,
17279) -> *mut PioApparentPower {
17280 unsafe { PioApparentPower::retain_raw(power) }
17281}
17282
17283#[unsafe(no_mangle)]
17288pub unsafe extern "C" fn pio_apparent_power_release(power: *mut PioApparentPower) {
17289 unsafe { PioApparentPower::release_raw(power) };
17290}
17291
17292unsafe fn component_clone(component: *const PioComponentId) -> Result<ComponentId, *mut PioError> {
17293 unsafe { require_handle(component.cast(), "PioComponentId") }.cloned()
17294}
17295
17296unsafe fn active_power_copy(power: *const PioActivePower) -> Result<ActivePower, *mut PioError> {
17297 unsafe { require_handle(power.cast(), "PioActivePower") }.copied()
17298}
17299
17300unsafe fn reactive_power_copy(
17301 power: *const PioReactivePower,
17302) -> Result<ReactivePower, *mut PioError> {
17303 unsafe { require_handle(power.cast(), "PioReactivePower") }.copied()
17304}
17305
17306unsafe fn apparent_power_copy(
17307 power: *const PioApparentPower,
17308) -> Result<ApparentPower, *mut PioError> {
17309 unsafe { require_handle(power.cast(), "PioApparentPower") }.copied()
17310}
17311
17312#[unsafe(no_mangle)]
17316pub unsafe extern "C" fn pio_operating_point_update_set_load_active_power(
17317 load: *const PioComponentId,
17318 terminal: *const c_char,
17319 terminal_len: usize,
17320 power: *const PioActivePower,
17321 error: *mut *mut PioError,
17322) -> *mut PioOperatingPointUpdate {
17323 unsafe {
17324 entry(error, std::ptr::null_mut(), || {
17325 Ok(PioOperatingPointUpdate::new_raw(
17326 OperatingPointUpdate::LoadActivePower {
17327 load: component_clone(load)?,
17328 terminal: optional_owned_string(terminal, terminal_len, "terminal")?,
17329 p: active_power_copy(power)?,
17330 },
17331 ))
17332 })
17333 }
17334}
17335
17336#[unsafe(no_mangle)]
17340pub unsafe extern "C" fn pio_operating_point_update_set_load_reactive_power(
17341 load: *const PioComponentId,
17342 terminal: *const c_char,
17343 terminal_len: usize,
17344 power: *const PioReactivePower,
17345 error: *mut *mut PioError,
17346) -> *mut PioOperatingPointUpdate {
17347 unsafe {
17348 entry(error, std::ptr::null_mut(), || {
17349 Ok(PioOperatingPointUpdate::new_raw(
17350 OperatingPointUpdate::LoadReactivePower {
17351 load: component_clone(load)?,
17352 terminal: optional_owned_string(terminal, terminal_len, "terminal")?,
17353 q: reactive_power_copy(power)?,
17354 },
17355 ))
17356 })
17357 }
17358}
17359
17360#[unsafe(no_mangle)]
17364pub unsafe extern "C" fn pio_operating_point_update_set_generator_active_power(
17365 generator: *const PioComponentId,
17366 terminal: *const c_char,
17367 terminal_len: usize,
17368 power: *const PioActivePower,
17369 error: *mut *mut PioError,
17370) -> *mut PioOperatingPointUpdate {
17371 unsafe {
17372 entry(error, std::ptr::null_mut(), || {
17373 Ok(PioOperatingPointUpdate::new_raw(
17374 OperatingPointUpdate::GeneratorActivePower {
17375 generator: component_clone(generator)?,
17376 terminal: optional_owned_string(terminal, terminal_len, "terminal")?,
17377 p: active_power_copy(power)?,
17378 },
17379 ))
17380 })
17381 }
17382}
17383
17384#[unsafe(no_mangle)]
17388pub unsafe extern "C" fn pio_operating_point_update_set_generator_reactive_power(
17389 generator: *const PioComponentId,
17390 terminal: *const c_char,
17391 terminal_len: usize,
17392 power: *const PioReactivePower,
17393 error: *mut *mut PioError,
17394) -> *mut PioOperatingPointUpdate {
17395 unsafe {
17396 entry(error, std::ptr::null_mut(), || {
17397 Ok(PioOperatingPointUpdate::new_raw(
17398 OperatingPointUpdate::GeneratorReactivePower {
17399 generator: component_clone(generator)?,
17400 terminal: optional_owned_string(terminal, terminal_len, "terminal")?,
17401 q: reactive_power_copy(power)?,
17402 },
17403 ))
17404 })
17405 }
17406}
17407
17408#[unsafe(no_mangle)]
17412pub unsafe extern "C" fn pio_operating_point_update_set_generator_voltage_magnitude(
17413 generator: *const PioComponentId,
17414 voltage_magnitude_per_unit: f64,
17415 error: *mut *mut PioError,
17416) -> *mut PioOperatingPointUpdate {
17417 unsafe {
17418 entry(error, std::ptr::null_mut(), || {
17419 Ok(PioOperatingPointUpdate::new_raw(
17420 OperatingPointUpdate::GeneratorVoltageMagnitude {
17421 generator: component_clone(generator)?,
17422 vm_pu: voltage_magnitude_per_unit,
17423 },
17424 ))
17425 })
17426 }
17427}
17428
17429#[unsafe(no_mangle)]
17433pub unsafe extern "C" fn pio_operating_point_update_set_generator_in_service(
17434 generator: *const PioComponentId,
17435 in_service: bool,
17436 error: *mut *mut PioError,
17437) -> *mut PioOperatingPointUpdate {
17438 unsafe {
17439 entry(error, std::ptr::null_mut(), || {
17440 Ok(PioOperatingPointUpdate::new_raw(
17441 OperatingPointUpdate::GeneratorInService {
17442 generator: component_clone(generator)?,
17443 in_service,
17444 },
17445 ))
17446 })
17447 }
17448}
17449
17450#[unsafe(no_mangle)]
17454pub unsafe extern "C" fn pio_operating_point_update_set_branch_in_service(
17455 branch: *const PioComponentId,
17456 in_service: bool,
17457 error: *mut *mut PioError,
17458) -> *mut PioOperatingPointUpdate {
17459 unsafe {
17460 entry(error, std::ptr::null_mut(), || {
17461 Ok(PioOperatingPointUpdate::new_raw(
17462 OperatingPointUpdate::BranchInService {
17463 branch: component_clone(branch)?,
17464 in_service,
17465 },
17466 ))
17467 })
17468 }
17469}
17470
17471#[unsafe(no_mangle)]
17475pub unsafe extern "C" fn pio_operating_point_update_set_transformer_tap_ratio(
17476 transformer: *const PioComponentId,
17477 tap_ratio: f64,
17478 error: *mut *mut PioError,
17479) -> *mut PioOperatingPointUpdate {
17480 unsafe {
17481 entry(error, std::ptr::null_mut(), || {
17482 Ok(PioOperatingPointUpdate::new_raw(
17483 OperatingPointUpdate::TransformerTapRatio {
17484 transformer: component_clone(transformer)?,
17485 tap_ratio,
17486 },
17487 ))
17488 })
17489 }
17490}
17491
17492#[unsafe(no_mangle)]
17496pub unsafe extern "C" fn pio_operating_point_update_set_transformer_phase_shift_degrees(
17497 transformer: *const PioComponentId,
17498 phase_shift_degrees: f64,
17499 error: *mut *mut PioError,
17500) -> *mut PioOperatingPointUpdate {
17501 unsafe {
17502 entry(error, std::ptr::null_mut(), || {
17503 Ok(PioOperatingPointUpdate::new_raw(
17504 OperatingPointUpdate::TransformerPhaseShift {
17505 transformer: component_clone(transformer)?,
17506 shift_degrees: phase_shift_degrees,
17507 },
17508 ))
17509 })
17510 }
17511}
17512
17513#[unsafe(no_mangle)]
17517pub unsafe extern "C" fn pio_operating_point_update_set_switch_closed(
17518 switch_id: *const PioComponentId,
17519 closed: bool,
17520 error: *mut *mut PioError,
17521) -> *mut PioOperatingPointUpdate {
17522 unsafe {
17523 entry(error, std::ptr::null_mut(), || {
17524 Ok(PioOperatingPointUpdate::new_raw(
17525 OperatingPointUpdate::SwitchClosed {
17526 switch: component_clone(switch_id)?,
17527 closed,
17528 },
17529 ))
17530 })
17531 }
17532}
17533
17534#[unsafe(no_mangle)]
17538pub unsafe extern "C" fn pio_network_update_set_branch_thermal_rating(
17539 branch: *const PioComponentId,
17540 terminal: *const c_char,
17541 terminal_len: usize,
17542 rating: *const PioApparentPower,
17543 error: *mut *mut PioError,
17544) -> *mut PioNetworkUpdate {
17545 unsafe {
17546 entry(error, std::ptr::null_mut(), || {
17547 Ok(PioNetworkUpdate::new_raw(
17548 NetworkUpdate::BranchThermalRating {
17549 branch: component_clone(branch)?,
17550 terminal: optional_owned_string(terminal, terminal_len, "terminal")?,
17551 rating: apparent_power_copy(rating)?,
17552 },
17553 ))
17554 })
17555 }
17556}
17557
17558#[unsafe(no_mangle)]
17562pub unsafe extern "C" fn pio_calculation_update_from_operating_point(
17563 update: *const PioOperatingPointUpdate,
17564 error: *mut *mut PioError,
17565) -> *mut PioCalculationUpdate {
17566 unsafe {
17567 entry(error, std::ptr::null_mut(), || {
17568 let update = PioOperatingPointUpdate::get(update)
17569 .ok_or_else(|| {
17570 boundary_error(
17571 &codes::BIND_CAPI_NULL_HANDLE,
17572 "PioOperatingPointUpdate must not be NULL",
17573 )
17574 })?
17575 .clone();
17576 Ok(PioCalculationUpdate::new_raw(
17577 CalculationUpdate::OperatingPoint(update),
17578 ))
17579 })
17580 }
17581}
17582
17583#[unsafe(no_mangle)]
17587pub unsafe extern "C" fn pio_calculation_update_from_network(
17588 update: *const PioNetworkUpdate,
17589 error: *mut *mut PioError,
17590) -> *mut PioCalculationUpdate {
17591 unsafe {
17592 entry(error, std::ptr::null_mut(), || {
17593 let update = PioNetworkUpdate::get(update)
17594 .ok_or_else(|| {
17595 boundary_error(
17596 &codes::BIND_CAPI_NULL_HANDLE,
17597 "PioNetworkUpdate must not be NULL",
17598 )
17599 })?
17600 .clone();
17601 Ok(PioCalculationUpdate::new_raw(CalculationUpdate::Network(
17602 update,
17603 )))
17604 })
17605 }
17606}
17607
17608#[unsafe(no_mangle)]
17613pub unsafe extern "C" fn pio_operating_point_update_retain(
17614 update: *const PioOperatingPointUpdate,
17615) -> *mut PioOperatingPointUpdate {
17616 unsafe { PioOperatingPointUpdate::retain_raw(update) }
17617}
17618
17619#[unsafe(no_mangle)]
17624pub unsafe extern "C" fn pio_operating_point_update_release(update: *mut PioOperatingPointUpdate) {
17625 unsafe { PioOperatingPointUpdate::release_raw(update) };
17626}
17627
17628#[unsafe(no_mangle)]
17633pub unsafe extern "C" fn pio_network_update_retain(
17634 update: *const PioNetworkUpdate,
17635) -> *mut PioNetworkUpdate {
17636 unsafe { PioNetworkUpdate::retain_raw(update) }
17637}
17638
17639#[unsafe(no_mangle)]
17644pub unsafe extern "C" fn pio_network_update_release(update: *mut PioNetworkUpdate) {
17645 unsafe { PioNetworkUpdate::release_raw(update) };
17646}
17647
17648#[unsafe(no_mangle)]
17653pub unsafe extern "C" fn pio_calculation_update_retain(
17654 update: *const PioCalculationUpdate,
17655) -> *mut PioCalculationUpdate {
17656 unsafe { PioCalculationUpdate::retain_raw(update) }
17657}
17658
17659#[unsafe(no_mangle)]
17664pub unsafe extern "C" fn pio_calculation_update_release(update: *mut PioCalculationUpdate) {
17665 unsafe { PioCalculationUpdate::release_raw(update) };
17666}
17667
17668fn append_update_report(output: &mut UpdateReportInner, report: powerio_prob::UpdateReport) {
17669 output.connectivity_changed |= report.connectivity_changed();
17670 output.changes.extend_from_slice(report.changes());
17671}
17672
17673fn apply_bus_load_to_typed_module<T>(
17674 module: &mut powerio::PioModule<PioValue>,
17675 bus: powerio_tx::BusId,
17676 total: ActivePower,
17677 allocation: LoadAllocation,
17678 narrow: impl FnOnce(PioValue) -> Result<T, PioValue>,
17679 wrap: impl FnOnce(T) -> PioValue,
17680) -> Result<UpdateReportInner, powerio_core::Error>
17681where
17682 T: powerio_prob::BalancedCalculationInstance,
17683{
17684 let mut typed = module.clone().__try_map_value(narrow).map_err(|value| {
17685 powerio_core::Error::new(
17686 &codes::REQUEST_CAPI_TYPE_MISMATCH,
17687 format!(
17688 "{} does not accept aggregate bus active demand",
17689 value.value().type_name()
17690 ),
17691 )
17692 })?;
17693 let report = apply_bus_load_active_power(&mut typed, bus, total, allocation)?;
17694 *module = typed.map_value(wrap);
17695 let mut output = UpdateReportInner {
17696 changes: Vec::new(),
17697 connectivity_changed: false,
17698 };
17699 append_update_report(&mut output, report);
17700 Ok(output)
17701}
17702
17703#[allow(clippy::result_large_err)]
17706fn apply_dynamic_bus_load_active_power(
17707 module: &mut powerio::PioModule<PioValue>,
17708 bus: powerio_tx::BusId,
17709 total: ActivePower,
17710 allocation: LoadAllocation,
17711) -> Result<UpdateReportInner, powerio_core::Error> {
17712 match &module.value() {
17713 PioValue::DcPfInstance(_) => apply_bus_load_to_typed_module(
17714 module,
17715 bus,
17716 total,
17717 allocation,
17718 |value| match value {
17719 PioValue::DcPfInstance(instance) => Ok(instance),
17720 other => Err(other),
17721 },
17722 PioValue::DcPfInstance,
17723 ),
17724 PioValue::AcPfInstance(_) => apply_bus_load_to_typed_module(
17725 module,
17726 bus,
17727 total,
17728 allocation,
17729 |value| match value {
17730 PioValue::AcPfInstance(instance) => Ok(instance),
17731 other => Err(other),
17732 },
17733 PioValue::AcPfInstance,
17734 ),
17735 PioValue::DcOpfInstance(_) => apply_bus_load_to_typed_module(
17736 module,
17737 bus,
17738 total,
17739 allocation,
17740 |value| match value {
17741 PioValue::DcOpfInstance(instance) => Ok(instance),
17742 other => Err(other),
17743 },
17744 PioValue::DcOpfInstance,
17745 ),
17746 PioValue::AcOpfInstance(_) => apply_bus_load_to_typed_module(
17747 module,
17748 bus,
17749 total,
17750 allocation,
17751 |value| match value {
17752 PioValue::AcOpfInstance(instance) => Ok(instance),
17753 other => Err(other),
17754 },
17755 PioValue::AcOpfInstance,
17756 ),
17757 value => Err(powerio_core::Error::new(
17758 &codes::REQUEST_CAPI_TYPE_MISMATCH,
17759 format!(
17760 "{} does not accept aggregate bus active demand",
17761 value.type_name()
17762 ),
17763 )),
17764 }
17765}
17766
17767fn parse_load_allocation(value: &str) -> Result<LoadAllocation, *mut PioError> {
17768 match value {
17769 "equal" => Ok(LoadAllocation::Equal),
17770 "proportional_to_current_active_power" => {
17771 Ok(LoadAllocation::ProportionalToCurrentActivePower)
17772 }
17773 other => Err(boundary_error(
17774 &codes::REQUEST_CAPI_ALLOCATION_UNKNOWN,
17775 format!("unknown load allocation rule '{other}'"),
17776 )),
17777 }
17778}
17779
17780fn separated_updates(
17781 updates: &[CalculationUpdate],
17782) -> Result<(Vec<OperatingPointUpdate>, Vec<NetworkUpdate>), powerio_core::Error> {
17783 let mut operating = Vec::new();
17784 let mut network = Vec::new();
17785 for update in updates {
17786 match update {
17787 CalculationUpdate::OperatingPoint(update) => operating.push(update.clone()),
17788 CalculationUpdate::Network(update) => network.push(update.clone()),
17789 _ => {
17790 return Err(powerio_core::Error::new(
17791 &codes::REQUEST_CAPI_TYPE_MISMATCH,
17792 "unsupported calculation update",
17793 ));
17794 }
17795 }
17796 }
17797 Ok((operating, network))
17798}
17799
17800fn reject_network_updates(
17801 updates: &[CalculationUpdate],
17802) -> Result<Vec<OperatingPointUpdate>, powerio_core::Error> {
17803 updates
17804 .iter()
17805 .map(|update| match update {
17806 CalculationUpdate::OperatingPoint(update) => Ok(update.clone()),
17807 CalculationUpdate::Network(_) => Err(powerio_core::Error::new(
17808 &codes::REQUEST_CAPI_TYPE_MISMATCH,
17809 "a network update cannot be applied to an operating point",
17810 )),
17811 _ => Err(powerio_core::Error::new(
17812 &codes::REQUEST_CAPI_TYPE_MISMATCH,
17813 "unsupported calculation update",
17814 )),
17815 })
17816 .collect()
17817}
17818
17819fn apply_dynamic_updates(
17820 value: &mut PioValue,
17821 updates: &[CalculationUpdate],
17822) -> Result<UpdateReportInner, powerio_core::Error> {
17823 let mut output = UpdateReportInner {
17824 changes: Vec::new(),
17825 connectivity_changed: false,
17826 };
17827 match value {
17828 PioValue::BalancedNetwork(network) => {
17829 let (operating, physical) = separated_updates(updates)?;
17830 append_update_report(&mut output, apply_updates(network, &operating)?);
17831 append_update_report(&mut output, apply_updates(network, &physical)?);
17832 }
17833 PioValue::MulticonductorNetwork(network) => {
17834 let (operating, physical) = separated_updates(updates)?;
17835 append_update_report(&mut output, apply_updates(network, &operating)?);
17836 append_update_report(&mut output, apply_updates(network, &physical)?);
17837 }
17838 PioValue::BalancedOperatingPoint(point) => {
17839 let operating = reject_network_updates(updates)?;
17840 append_update_report(&mut output, apply_updates(point, &operating)?);
17841 }
17842 PioValue::MulticonductorOperatingPoint(point) => {
17843 let operating = reject_network_updates(updates)?;
17844 append_update_report(&mut output, apply_updates(point, &operating)?);
17845 }
17846 PioValue::DcPfInstance(instance) => {
17847 append_update_report(&mut output, apply_updates(instance, updates)?);
17848 }
17849 PioValue::AcPfInstance(instance) => {
17850 append_update_report(&mut output, apply_updates(instance, updates)?);
17851 }
17852 PioValue::DcOpfInstance(instance) => {
17853 append_update_report(&mut output, apply_updates(instance, updates)?);
17854 }
17855 PioValue::AcOpfInstance(instance) => {
17856 append_update_report(&mut output, apply_updates(instance, updates)?);
17857 }
17858 PioValue::McAcPfInstance(instance) => {
17859 append_update_report(&mut output, apply_updates(instance, updates)?);
17860 }
17861 PioValue::McAcOpfInstance(instance) => {
17862 append_update_report(&mut output, apply_updates(instance, updates)?);
17863 }
17864 _ => {
17865 return Err(powerio_core::Error::new(
17866 &codes::REQUEST_CAPI_TYPE_MISMATCH,
17867 format!("{} does not accept calculation updates", value.type_name()),
17868 ));
17869 }
17870 }
17871 Ok(output)
17872}
17873
17874fn update_history_id(
17875 module: &powerio::PioModule<PioValue>,
17876) -> Result<HistoryId, powerio_core::Error> {
17877 let mut suffix = 1usize;
17878 loop {
17879 let value = if suffix == 1 {
17880 "apply-updates".to_owned()
17881 } else {
17882 format!("apply-updates-{suffix}")
17883 };
17884 if module
17885 .history()
17886 .iter()
17887 .all(|entry| entry.id().as_str() != value)
17888 {
17889 return HistoryId::new(value);
17890 }
17891 suffix += 1;
17892 }
17893}
17894
17895fn apply_module_updates(
17896 module: &mut powerio::PioModule<PioValue>,
17897 updates: &[CalculationUpdate],
17898) -> Result<UpdateReportInner, powerio_core::Error> {
17899 let history_id = update_history_id(module)?;
17900 let mut edit = module.stage_edit();
17901 let report = apply_dynamic_updates(edit.value_mut(), updates)?;
17902 if report.changes.is_empty() {
17903 return Ok(report);
17904 }
17905
17906 let mut parameters = std::collections::BTreeMap::new();
17907 parameters.insert(
17908 "updates".to_owned(),
17909 serde_json::to_value(updates).map_err(|failure| {
17910 powerio_core::Error::new(
17911 &codes::EMIT_CAPI_SERIALIZE_FAILED,
17912 format!("cannot record applied updates: {failure}"),
17913 )
17914 })?,
17915 );
17916 parameters.insert(
17917 "changes".to_owned(),
17918 serde_json::to_value(&report.changes).map_err(|failure| {
17919 powerio_core::Error::new(
17920 &codes::EMIT_CAPI_SERIALIZE_FAILED,
17921 format!("cannot record update changes: {failure}"),
17922 )
17923 })?,
17924 );
17925 parameters.insert(
17926 "connectivity_changed".to_owned(),
17927 serde_json::Value::Bool(report.connectivity_changed),
17928 );
17929 let history = HistoryEntry::new(history_id, HistoryKind::Edit, "apply_updates")?
17930 .with_parameters(parameters)?;
17931 edit.commit(Producer::new("powerio-capi", powerio::VERSION)?, history)?;
17932 Ok(report)
17933}
17934
17935unsafe fn module_make_mut<'a>(
17936 module: *mut PioModule,
17937) -> Result<&'a mut ModuleInner, *mut PioError> {
17938 let handle = unsafe { module.cast::<HandleBox<ModuleInner>>().as_mut() }.ok_or_else(|| {
17939 boundary_error(&codes::BIND_CAPI_NULL_HANDLE, "PioModule must not be NULL")
17940 })?;
17941 Ok(Arc::make_mut(&mut handle.inner))
17942}
17943
17944#[unsafe(no_mangle)]
17957pub unsafe extern "C" fn pio_apply_updates(
17958 module: *mut PioModule,
17959 updates: *const *const PioCalculationUpdate,
17960 updates_len: usize,
17961 error: *mut *mut PioError,
17962) -> *mut PioUpdateReport {
17963 unsafe {
17964 entry(error, std::ptr::null_mut(), || {
17965 if updates.is_null() && updates_len != 0 {
17966 return Err(boundary_error(
17967 &codes::BIND_CAPI_NULL_ARGUMENT,
17968 "updates is NULL with a nonzero length",
17969 ));
17970 }
17971 let handles = if updates_len == 0 {
17972 &[]
17973 } else {
17974 std::slice::from_raw_parts(updates, updates_len)
17975 };
17976 let mut values = Vec::with_capacity(handles.len());
17977 for (index, handle) in handles.iter().copied().enumerate() {
17978 let update = PioCalculationUpdate::get(handle).ok_or_else(|| {
17979 boundary_error(
17980 &codes::BIND_CAPI_NULL_HANDLE,
17981 format!("updates[{index}] must not be NULL"),
17982 )
17983 })?;
17984 values.push(update.clone());
17985 }
17986 let module = module_make_mut(module)?;
17987 apply_module_updates(&mut module.module, &values)
17988 .map(PioUpdateReport::new_raw)
17989 .map_err(|failure| error_from_core(&failure))
17990 })
17991 }
17992}
17993
17994#[unsafe(no_mangle)]
18003pub unsafe extern "C" fn pio_apply_bus_load_active_power(
18004 module: *mut PioModule,
18005 bus_id: usize,
18006 power: *const PioActivePower,
18007 allocation: *const c_char,
18008 allocation_len: usize,
18009 error: *mut *mut PioError,
18010) -> *mut PioUpdateReport {
18011 unsafe {
18012 entry(error, std::ptr::null_mut(), || {
18013 let total = active_power_copy(power)?;
18014 let allocation = required_str(allocation, allocation_len, "allocation")?;
18015 let allocation = parse_load_allocation(allocation)?;
18016 let module = module_make_mut(module)?;
18017 apply_dynamic_bus_load_active_power(
18018 &mut module.module,
18019 powerio_tx::BusId::new(bus_id),
18020 total,
18021 allocation,
18022 )
18023 .map(PioUpdateReport::new_raw)
18024 .map_err(|failure| error_from_core(&failure))
18025 })
18026 }
18027}
18028
18029#[unsafe(no_mangle)]
18033pub unsafe extern "C" fn pio_update_report_len(report: *const PioUpdateReport) -> usize {
18034 unsafe { PioUpdateReport::get(report) }.map_or(0, |report| report.changes.len())
18035}
18036
18037#[unsafe(no_mangle)]
18041pub unsafe extern "C" fn pio_update_report_connectivity_changed(
18042 report: *const PioUpdateReport,
18043) -> bool {
18044 unsafe { PioUpdateReport::get(report) }.is_some_and(|report| report.connectivity_changed)
18045}
18046
18047#[unsafe(no_mangle)]
18051pub unsafe extern "C" fn pio_update_report_change(
18052 report: *const PioUpdateReport,
18053 index: usize,
18054 error: *mut *mut PioError,
18055) -> *mut PioUpdateChange {
18056 unsafe {
18057 entry(error, std::ptr::null_mut(), || {
18058 let owner = PioUpdateReport::arc(report).ok_or_else(|| {
18059 boundary_error(
18060 &codes::BIND_CAPI_NULL_HANDLE,
18061 "PioUpdateReport must not be NULL",
18062 )
18063 })?;
18064 if index >= owner.changes.len() {
18065 return Err(boundary_error(
18066 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
18067 format!("update change index {index} is out of range"),
18068 ));
18069 }
18070 Ok(PioUpdateChange::new_raw(UpdateChangeInner { owner, index }))
18071 })
18072 }
18073}
18074
18075#[unsafe(no_mangle)]
18079pub unsafe extern "C" fn pio_update_change_component_id(
18080 change: *const PioUpdateChange,
18081) -> *mut PioComponentId {
18082 unsafe { PioUpdateChange::get(change) }
18083 .and_then(UpdateChangeInner::change)
18084 .map_or(std::ptr::null_mut(), |change| {
18085 PioComponentId::new_raw(change.component_id().clone())
18086 })
18087}
18088
18089fn updated_field_name(field: UpdatedField) -> &'static str {
18090 match field {
18091 UpdatedField::LoadActivePower => "load_active_power",
18092 UpdatedField::LoadReactivePower => "load_reactive_power",
18093 UpdatedField::GeneratorActivePower => "generator_active_power",
18094 UpdatedField::GeneratorReactivePower => "generator_reactive_power",
18095 UpdatedField::GeneratorVoltageMagnitude => "generator_voltage_magnitude",
18096 UpdatedField::GeneratorInService => "generator_in_service",
18097 UpdatedField::BranchThermalRating => "branch_thermal_rating",
18098 UpdatedField::BranchInService => "branch_in_service",
18099 UpdatedField::TransformerTapRatio => "transformer_tap_ratio",
18100 UpdatedField::TransformerPhaseShift => "transformer_phase_shift",
18101 UpdatedField::SwitchClosed => "switch_closed",
18102 _ => "unknown",
18103 }
18104}
18105
18106#[unsafe(no_mangle)]
18110pub unsafe extern "C" fn pio_update_change_field(change: *const PioUpdateChange) -> PioStringView {
18111 unsafe { PioUpdateChange::get(change) }
18112 .and_then(UpdateChangeInner::change)
18113 .map_or(PioStringView::EMPTY, |change| {
18114 PioStringView::new(updated_field_name(change.field()))
18115 })
18116}
18117
18118#[unsafe(no_mangle)]
18122pub unsafe extern "C" fn pio_update_change_terminal(
18123 change: *const PioUpdateChange,
18124) -> PioStringView {
18125 unsafe { PioUpdateChange::get(change) }
18126 .and_then(UpdateChangeInner::change)
18127 .and_then(UpdateChange::terminal)
18128 .map_or(PioStringView::EMPTY, PioStringView::new)
18129}
18130
18131#[unsafe(no_mangle)]
18136pub unsafe extern "C" fn pio_update_report_retain(
18137 report: *const PioUpdateReport,
18138) -> *mut PioUpdateReport {
18139 unsafe { PioUpdateReport::retain_raw(report) }
18140}
18141
18142#[unsafe(no_mangle)]
18147pub unsafe extern "C" fn pio_update_report_release(report: *mut PioUpdateReport) {
18148 unsafe { PioUpdateReport::release_raw(report) };
18149}
18150
18151#[unsafe(no_mangle)]
18156pub unsafe extern "C" fn pio_update_change_retain(
18157 change: *const PioUpdateChange,
18158) -> *mut PioUpdateChange {
18159 unsafe { PioUpdateChange::retain_raw(change) }
18160}
18161
18162#[unsafe(no_mangle)]
18167pub unsafe extern "C" fn pio_update_change_release(change: *mut PioUpdateChange) {
18168 unsafe { PioUpdateChange::release_raw(change) };
18169}
18170
18171struct ArtifactRecord {
18174 name: String,
18175 bytes: Option<Vec<u8>>,
18176}
18177
18178struct EmitResultInner {
18179 layout: &'static str,
18180 fidelity: &'static str,
18181 artifacts: Vec<ArtifactRecord>,
18182 diagnostics: Arc<DiagnosticsInner>,
18183}
18184
18185struct ArtifactInner {
18186 owner: Arc<EmitResultInner>,
18187 index: usize,
18188}
18189
18190impl ArtifactInner {
18191 fn artifact(&self) -> Option<&ArtifactRecord> {
18192 self.owner.artifacts.get(self.index)
18193 }
18194}
18195
18196opaque_handle!(
18197 PioEmitResult,
18199 EmitResultInner
18200);
18201opaque_handle!(
18202 PioArtifact,
18204 ArtifactInner
18205);
18206
18207fn emit_result_handle(result: EmitResult) -> Result<*mut PioEmitResult, *mut PioError> {
18208 let layout = match result.layout() {
18209 powerio::OutputLayout::File => "file",
18210 powerio::OutputLayout::Directory => "directory",
18211 };
18212 let fidelity = match result.fidelity() {
18213 powerio::Fidelity::ExactSameFormat => "exact_same_format",
18214 powerio::Fidelity::Canonical => "canonical",
18215 };
18216 let diagnostics = Arc::new(DiagnosticsInner {
18217 owner: DiagnosticsOwner::Owned(result.diagnostics().to_vec()),
18218 });
18219 let artifacts = match result.into_output() {
18220 EmittedOutput::Memory { artifacts } => artifacts
18221 .into_iter()
18222 .map(|artifact| {
18223 let name = artifact.name().as_str().to_owned();
18224 ArtifactRecord {
18225 name,
18226 bytes: Some(artifact.into_bytes()),
18227 }
18228 })
18229 .collect(),
18230 EmittedOutput::Path { artifacts, .. } => artifacts
18231 .into_iter()
18232 .map(|path| ArtifactRecord {
18233 name: path.to_string_lossy().into_owned(),
18234 bytes: None,
18235 })
18236 .collect(),
18237 _ => {
18238 return Err(boundary_error(
18239 &codes::REQUEST_CAPI_TYPE_MISMATCH,
18240 "unsupported emitted output",
18241 ));
18242 }
18243 };
18244 Ok(PioEmitResult::new_raw(EmitResultInner {
18245 layout,
18246 fidelity,
18247 artifacts,
18248 diagnostics,
18249 }))
18250}
18251
18252unsafe fn run_output_operation(
18253 module: *const PioModule,
18254 destination: *const PioDestination,
18255 error: *mut *mut PioError,
18256 operation: impl FnOnce(
18257 &powerio::PioModule<PioValue>,
18258 Destination,
18259 ) -> Result<EmitResult, *mut PioError>,
18260) -> *mut PioEmitResult {
18261 unsafe {
18262 entry(error, std::ptr::null_mut(), || {
18263 let module = PioModule::get(module).ok_or_else(|| {
18264 boundary_error(&codes::BIND_CAPI_NULL_HANDLE, "PioModule must not be NULL")
18265 })?;
18266 let destination = PioDestination::get(destination).ok_or_else(|| {
18267 boundary_error(
18268 &codes::BIND_CAPI_NULL_HANDLE,
18269 "PioDestination must not be NULL",
18270 )
18271 })?;
18272 let destination = destination
18273 .build()
18274 .map_err(|failure| error_from_core(&failure))?;
18275 operation(&module.module, destination).and_then(emit_result_handle)
18276 })
18277 }
18278}
18279
18280#[unsafe(no_mangle)]
18285pub unsafe extern "C" fn pio_emit(
18286 module: *const PioModule,
18287 format: *const c_char,
18288 format_len: usize,
18289 destination: *const PioDestination,
18290 error: *mut *mut PioError,
18291) -> *mut PioEmitResult {
18292 unsafe {
18293 run_output_operation(module, destination, error, |module, destination| {
18294 let format = required_str(format, format_len, "format")?;
18295 powerio::emit(module, format, destination).map_err(|failure| error_from_core(&failure))
18296 })
18297 }
18298}
18299
18300#[unsafe(no_mangle)]
18305pub unsafe extern "C" fn pio_module_serialize(
18306 module: *const PioModule,
18307 destination: *const PioDestination,
18308 error: *mut *mut PioError,
18309) -> *mut PioEmitResult {
18310 unsafe {
18311 run_output_operation(module, destination, error, |module, destination| {
18312 powerio::serialize(module, destination).map_err(|failure| error_from_core(&failure))
18313 })
18314 }
18315}
18316
18317#[unsafe(no_mangle)]
18321pub unsafe extern "C" fn pio_emit_result_layout(result: *const PioEmitResult) -> PioStringView {
18322 unsafe { PioEmitResult::get(result) }.map_or(PioStringView::EMPTY, |result| {
18323 PioStringView::new(result.layout)
18324 })
18325}
18326
18327#[unsafe(no_mangle)]
18331pub unsafe extern "C" fn pio_emit_result_fidelity(result: *const PioEmitResult) -> PioStringView {
18332 unsafe { PioEmitResult::get(result) }.map_or(PioStringView::EMPTY, |result| {
18333 PioStringView::new(result.fidelity)
18334 })
18335}
18336
18337#[unsafe(no_mangle)]
18341pub unsafe extern "C" fn pio_emit_result_artifact_count(result: *const PioEmitResult) -> usize {
18342 unsafe { PioEmitResult::get(result) }.map_or(0, |result| result.artifacts.len())
18343}
18344
18345#[unsafe(no_mangle)]
18349pub unsafe extern "C" fn pio_emit_result_artifact(
18350 result: *const PioEmitResult,
18351 index: usize,
18352 error: *mut *mut PioError,
18353) -> *mut PioArtifact {
18354 unsafe {
18355 entry(error, std::ptr::null_mut(), || {
18356 let owner = PioEmitResult::arc(result).ok_or_else(|| {
18357 boundary_error(
18358 &codes::BIND_CAPI_NULL_HANDLE,
18359 "PioEmitResult must not be NULL",
18360 )
18361 })?;
18362 if index >= owner.artifacts.len() {
18363 return Err(boundary_error(
18364 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
18365 format!("artifact index {index} is out of range"),
18366 ));
18367 }
18368 Ok(PioArtifact::new_raw(ArtifactInner { owner, index }))
18369 })
18370 }
18371}
18372
18373#[unsafe(no_mangle)]
18377pub unsafe extern "C" fn pio_emit_result_diagnostics(
18378 result: *const PioEmitResult,
18379) -> *mut PioDiagnostics {
18380 unsafe { PioEmitResult::get(result) }.map_or(std::ptr::null_mut(), |result| {
18381 PioDiagnostics::from_arc(Arc::clone(&result.diagnostics))
18382 })
18383}
18384
18385#[unsafe(no_mangle)]
18390pub unsafe extern "C" fn pio_emit_result_retain(
18391 result: *const PioEmitResult,
18392) -> *mut PioEmitResult {
18393 unsafe { PioEmitResult::retain_raw(result) }
18394}
18395
18396#[unsafe(no_mangle)]
18401pub unsafe extern "C" fn pio_emit_result_release(result: *mut PioEmitResult) {
18402 unsafe { PioEmitResult::release_raw(result) };
18403}
18404
18405#[unsafe(no_mangle)]
18409pub unsafe extern "C" fn pio_artifact_name(artifact: *const PioArtifact) -> PioStringView {
18410 unsafe { PioArtifact::get(artifact) }
18411 .and_then(ArtifactInner::artifact)
18412 .map_or(PioStringView::EMPTY, |artifact| {
18413 PioStringView::new(&artifact.name)
18414 })
18415}
18416
18417#[unsafe(no_mangle)]
18423pub unsafe extern "C" fn pio_artifact_bytes(artifact: *const PioArtifact) -> PioByteView {
18424 unsafe { PioArtifact::get(artifact) }
18425 .and_then(ArtifactInner::artifact)
18426 .and_then(|artifact| artifact.bytes.as_deref())
18427 .map_or(PioByteView::EMPTY, PioByteView::new)
18428}
18429
18430#[unsafe(no_mangle)]
18435pub unsafe extern "C" fn pio_artifact_retain(artifact: *const PioArtifact) -> *mut PioArtifact {
18436 unsafe { PioArtifact::retain_raw(artifact) }
18437}
18438
18439#[unsafe(no_mangle)]
18444pub unsafe extern "C" fn pio_artifact_release(artifact: *mut PioArtifact) {
18445 unsafe { PioArtifact::release_raw(artifact) };
18446}
18447
18448struct SparseMatrixInner {
18451 rows: usize,
18452 columns: usize,
18453 row_offsets: Vec<usize>,
18454 column_indices: Vec<usize>,
18455 values: Vec<f64>,
18456}
18457
18458impl From<SparseMatrix> for SparseMatrixInner {
18459 fn from(matrix: SparseMatrix) -> Self {
18460 let matrix = matrix.to_csr();
18461 Self {
18462 rows: matrix.rows(),
18463 columns: matrix.cols(),
18464 row_offsets: matrix.indptr().raw_storage().to_vec(),
18465 column_indices: matrix.indices().to_vec(),
18466 values: matrix.data().to_vec(),
18467 }
18468 }
18469}
18470
18471struct VectorInner {
18472 values: Vec<f64>,
18473}
18474
18475opaque_handle!(
18476 PioSparseMatrix,
18478 SparseMatrixInner
18479);
18480opaque_handle!(
18481 PioVector,
18483 VectorInner
18484);
18485
18486fn termination_name(termination: &powerio_prob::Termination) -> &'static str {
18487 use powerio_prob::Termination;
18488 match termination {
18489 Termination::Converged => "converged",
18490 Termination::IterationLimit => "iteration_limit",
18491 Termination::Infeasible => "infeasible",
18492 Termination::Unbounded => "unbounded",
18493 Termination::Failed => "failed",
18494 Termination::NotReported => "not_reported",
18495 _ => "not_reported",
18496 }
18497}
18498
18499#[unsafe(no_mangle)]
18503pub unsafe extern "C" fn pio_calculation_solution_termination(
18504 solution: *const PioCalculationSolution,
18505) -> PioStringView {
18506 let Some(solution) =
18507 (unsafe { PioCalculationSolution::get(solution) }).and_then(ValueInner::value)
18508 else {
18509 return PioStringView::EMPTY;
18510 };
18511 let termination = match solution {
18512 PioValue::DcPfSolution(solution) => solution.termination(),
18513 PioValue::AcPfSolution(solution) => solution.termination(),
18514 PioValue::DcOpfSolution(solution) => solution.termination(),
18515 PioValue::AcOpfSolution(solution) => solution.termination(),
18516 PioValue::AcOtsSolution(solution) => solution.termination(),
18517 PioValue::SocwrOpfSolution(solution) => solution.termination(),
18518 PioValue::McAcPfSolution(solution) => solution.termination(),
18519 PioValue::McAcOpfSolution(solution) => solution.termination(),
18520 PioValue::LinDist3FlowOpfSolution(solution) => solution.termination(),
18521 PioValue::AcScucSolution(solution) => solution.termination(),
18522 _ => return PioStringView::EMPTY,
18523 };
18524 PioStringView::new(termination_name(termination))
18525}
18526
18527#[unsafe(no_mangle)]
18533pub unsafe extern "C" fn pio_calculation_solution_get_objective(
18534 solution: *const PioCalculationSolution,
18535 out_objective: *mut f64,
18536) -> bool {
18537 if out_objective.is_null() {
18538 return false;
18539 }
18540 unsafe {
18543 entry(std::ptr::null_mut(), false, || {
18544 let Some(solution) = PioCalculationSolution::get(solution).and_then(ValueInner::value)
18545 else {
18546 return Ok(false);
18547 };
18548 let objective = match solution {
18549 PioValue::DcOpfSolution(solution) => Some(solution.objective()),
18550 PioValue::AcOpfSolution(solution) => Some(solution.objective()),
18551 PioValue::AcOtsSolution(solution) => Some(solution.objective()),
18552 PioValue::McAcOpfSolution(solution) => Some(solution.objective()),
18553 PioValue::LinDist3FlowOpfSolution(solution) => Some(solution.objective()),
18554 PioValue::AcScucSolution(solution) => solution.objective(),
18555 _ => None,
18556 };
18557 Ok(match objective {
18558 Some(objective) => {
18559 *out_objective = objective;
18560 true
18561 }
18562 None => false,
18563 })
18564 })
18565 }
18566}
18567
18568#[unsafe(no_mangle)]
18572pub unsafe extern "C" fn pio_socwr_opf_solution_get_objective_lower_bound(
18573 solution: *const PioCalculationSolution,
18574 out_lower_bound: *mut f64,
18575) -> bool {
18576 if out_lower_bound.is_null() {
18577 return false;
18578 }
18579 unsafe {
18581 entry(std::ptr::null_mut(), false, || {
18582 let Some(PioValue::SocwrOpfSolution(solution)) =
18583 PioCalculationSolution::get(solution).and_then(ValueInner::value)
18584 else {
18585 return Ok(false);
18586 };
18587 *out_lower_bound = solution.objective_lower_bound();
18588 Ok(true)
18589 })
18590 }
18591}
18592
18593fn balanced_branch_identities(network: &BalancedNetwork) -> impl Iterator<Item = &str> {
18594 network
18595 .branches()
18596 .iter()
18597 .map(|branch| branch.uid.as_deref().expect("facade assigns component IDs"))
18598}
18599
18600fn balanced_generator_identities(network: &BalancedNetwork) -> impl Iterator<Item = &str> {
18601 network.generators().iter().map(|generator| {
18602 generator
18603 .uid
18604 .as_deref()
18605 .expect("facade assigns component IDs")
18606 })
18607}
18608
18609fn ac_opf_solution_values(
18612 solution: &powerio_prob::AcOpfSolution,
18613 quantity: &str,
18614) -> Option<Vec<f64>> {
18615 let values = match quantity {
18616 "bus_voltage_magnitude" => solution.bus_voltage_magnitudes(),
18617 "bus_voltage_angle" => solution.bus_voltage_angles(),
18618 "bus_active_injection" => solution.bus_active_injections(),
18619 "bus_reactive_injection" => solution.bus_reactive_injections(),
18620 "branch_from_active_flow" => solution.branch_from_active_flows(),
18621 "branch_from_reactive_flow" => solution.branch_from_reactive_flows(),
18622 "branch_to_active_flow" => solution.branch_to_active_flows(),
18623 "branch_to_reactive_flow" => solution.branch_to_reactive_flows(),
18624 "generator_active_power" => solution.generator_active_powers(),
18625 "generator_reactive_power" => solution.generator_reactive_powers(),
18626 "bus_active_power_marginal" => solution.bus_active_power_marginals()?,
18627 "bus_reactive_power_marginal" => solution.bus_reactive_power_marginals()?,
18628 "branch_from_limit_multiplier" => solution.branch_from_limit_multipliers()?,
18629 "branch_to_limit_multiplier" => solution.branch_to_limit_multipliers()?,
18630 _ => return None,
18631 };
18632 Some(values.to_vec())
18633}
18634
18635fn collect_solution_values(solution: &PioValue, quantity: &str) -> Result<Vec<f64>, *mut PioError> {
18636 let unknown = || {
18637 boundary_error(
18638 &codes::REQUEST_CAPI_QUANTITY_UNKNOWN,
18639 format!(
18640 "{} does not define solution quantity '{quantity}'",
18641 solution.type_name()
18642 ),
18643 )
18644 };
18645 let values = match solution {
18646 PioValue::DcPfSolution(solution) => match quantity {
18647 "bus_voltage_angle" => solution.bus_voltage_angles().to_vec(),
18648 "bus_active_injection" => solution.bus_active_injections().to_vec(),
18649 "branch_from_active_flow" => solution.branch_from_active_flows().to_vec(),
18650 "branch_to_active_flow" => solution.branch_to_active_flows().to_vec(),
18651 "generator_active_power" => solution
18652 .generator_dispatch()
18653 .map(|dispatch| dispatch.p_mw.clone())
18654 .ok_or_else(unknown)?,
18655 "generator_reactive_power" => solution
18656 .generator_dispatch()
18657 .map(|dispatch| dispatch.q_mvar.clone())
18658 .ok_or_else(unknown)?,
18659 _ => return Err(unknown()),
18660 },
18661 PioValue::AcPfSolution(solution) => match quantity {
18662 "bus_voltage_magnitude" => solution
18663 .network()
18664 .buses()
18665 .iter()
18666 .map(|bus| {
18667 solution
18668 .bus_voltage_magnitude(bus.id)
18669 .expect("complete solution")
18670 })
18671 .collect(),
18672 "bus_voltage_angle" => solution
18673 .network()
18674 .buses()
18675 .iter()
18676 .map(|bus| {
18677 solution
18678 .bus_voltage_angle(bus.id)
18679 .expect("complete solution")
18680 })
18681 .collect(),
18682 "bus_active_injection" => solution
18683 .network()
18684 .buses()
18685 .iter()
18686 .map(|bus| {
18687 solution
18688 .bus_active_injection(bus.id)
18689 .expect("complete solution")
18690 })
18691 .collect(),
18692 "bus_reactive_injection" => solution
18693 .network()
18694 .buses()
18695 .iter()
18696 .map(|bus| {
18697 solution
18698 .bus_reactive_injection(bus.id)
18699 .expect("complete solution")
18700 })
18701 .collect(),
18702 "branch_from_active_flow" => balanced_branch_identities(solution.network())
18703 .map(|id| {
18704 solution
18705 .branch_from_active_flow(id)
18706 .expect("complete solution")
18707 })
18708 .collect(),
18709 "branch_from_reactive_flow" => balanced_branch_identities(solution.network())
18710 .map(|id| {
18711 solution
18712 .branch_from_reactive_flow(id)
18713 .expect("complete solution")
18714 })
18715 .collect(),
18716 "branch_to_active_flow" => balanced_branch_identities(solution.network())
18717 .map(|id| {
18718 solution
18719 .branch_to_active_flow(id)
18720 .expect("complete solution")
18721 })
18722 .collect(),
18723 "branch_to_reactive_flow" => balanced_branch_identities(solution.network())
18724 .map(|id| {
18725 solution
18726 .branch_to_reactive_flow(id)
18727 .expect("complete solution")
18728 })
18729 .collect(),
18730 "generator_active_power" => solution
18731 .generator_dispatch()
18732 .map(|dispatch| dispatch.p_mw.clone())
18733 .ok_or_else(unknown)?,
18734 "generator_reactive_power" => solution
18735 .generator_dispatch()
18736 .map(|dispatch| dispatch.q_mvar.clone())
18737 .ok_or_else(unknown)?,
18738 _ => return Err(unknown()),
18739 },
18740 PioValue::DcOpfSolution(solution) => match quantity {
18741 "bus_voltage_angle" => solution
18742 .network()
18743 .buses()
18744 .iter()
18745 .map(|bus| {
18746 solution
18747 .bus_voltage_angle(bus.id)
18748 .expect("complete solution")
18749 })
18750 .collect(),
18751 "bus_active_injection" => solution
18752 .network()
18753 .buses()
18754 .iter()
18755 .map(|bus| {
18756 solution
18757 .bus_active_injection(bus.id)
18758 .expect("complete solution")
18759 })
18760 .collect(),
18761 "branch_from_active_flow" => balanced_branch_identities(solution.network())
18762 .map(|id| {
18763 solution
18764 .branch_from_active_flow(id)
18765 .expect("complete solution")
18766 })
18767 .collect(),
18768 "branch_to_active_flow" => balanced_branch_identities(solution.network())
18769 .map(|id| {
18770 solution
18771 .branch_to_active_flow(id)
18772 .expect("complete solution")
18773 })
18774 .collect(),
18775 "generator_active_power" => balanced_generator_identities(solution.network())
18776 .map(|id| {
18777 solution
18778 .generator_active_power(id)
18779 .expect("complete solution")
18780 })
18781 .collect(),
18782 "bus_active_power_marginal" => solution
18783 .bus_active_power_marginals()
18784 .map(<[f64]>::to_vec)
18785 .ok_or_else(unknown)?,
18786 "branch_from_limit_multiplier" => solution
18787 .branch_from_limit_multipliers()
18788 .map(<[f64]>::to_vec)
18789 .ok_or_else(unknown)?,
18790 "branch_to_limit_multiplier" => solution
18791 .branch_to_limit_multipliers()
18792 .map(<[f64]>::to_vec)
18793 .ok_or_else(unknown)?,
18794 _ => return Err(unknown()),
18795 },
18796 PioValue::AcOpfSolution(solution) => {
18797 ac_opf_solution_values(solution, quantity).ok_or_else(unknown)?
18798 }
18799 PioValue::AcOtsSolution(solution) => {
18802 ac_opf_solution_values(solution.ac_solution(), quantity).ok_or_else(unknown)?
18803 }
18804 PioValue::SocwrOpfSolution(solution) => {
18805 let values = solution.values();
18806 match quantity {
18807 "bus_voltage_magnitude_squared" => values.bus_voltage_magnitude_squared.clone(),
18808 "branch_voltage_product_real" => values.branch_voltage_product_real.clone(),
18809 "branch_voltage_product_imaginary" => {
18810 values.branch_voltage_product_imaginary.clone()
18811 }
18812 "generator_active_power" => values.generator_active_power.clone(),
18813 "generator_reactive_power" => values.generator_reactive_power.clone(),
18814 "branch_from_active_flow" => values.branch_from_active_flow.clone(),
18815 "branch_from_reactive_flow" => values.branch_from_reactive_flow.clone(),
18816 "branch_to_active_flow" => values.branch_to_active_flow.clone(),
18817 "branch_to_reactive_flow" => values.branch_to_reactive_flow.clone(),
18818 _ => return Err(unknown()),
18819 }
18820 }
18821 PioValue::McAcPfSolution(solution) => match quantity {
18822 "terminal_voltage_magnitude" => solution
18823 .network()
18824 .buses()
18825 .iter()
18826 .flat_map(|bus| {
18827 bus.terminals.iter().map(move |terminal| {
18828 solution
18829 .terminal_voltage_magnitude(&bus.id, terminal)
18830 .expect("complete solution")
18831 })
18832 })
18833 .collect(),
18834 "terminal_voltage_angle" => solution
18835 .network()
18836 .buses()
18837 .iter()
18838 .flat_map(|bus| {
18839 bus.terminals.iter().map(move |terminal| {
18840 solution
18841 .terminal_voltage_angle(&bus.id, terminal)
18842 .expect("complete solution")
18843 })
18844 })
18845 .collect(),
18846 "source_active_injection" => solution.source_active_injections().to_vec(),
18847 _ => return Err(unknown()),
18848 },
18849 PioValue::LinDist3FlowOpfSolution(solution) => match quantity {
18850 "terminal_voltage_magnitude_squared" => {
18851 solution.values().terminal_voltage_magnitude_squared.clone()
18852 }
18853 "line_active_power" => solution.values().line_active_power.clone(),
18854 "line_reactive_power" => solution.values().line_reactive_power.clone(),
18855 "generator_active_power" => solution.values().generator_active_power.clone(),
18856 "generator_reactive_power" => solution.values().generator_reactive_power.clone(),
18857 "source_active_power" => solution.values().source_active_power.clone(),
18858 "source_reactive_power" => solution.values().source_reactive_power.clone(),
18859 _ => return Err(unknown()),
18860 },
18861 PioValue::McAcOpfSolution(solution) => match quantity {
18862 "terminal_voltage_magnitude" => solution
18863 .network()
18864 .buses()
18865 .iter()
18866 .flat_map(|bus| {
18867 bus.terminals.iter().map(move |terminal| {
18868 solution
18869 .terminal_voltage_magnitude(&bus.id, terminal)
18870 .expect("complete solution")
18871 })
18872 })
18873 .collect(),
18874 "terminal_voltage_angle" => solution
18875 .network()
18876 .buses()
18877 .iter()
18878 .flat_map(|bus| {
18879 bus.terminals.iter().map(move |terminal| {
18880 solution
18881 .terminal_voltage_angle(&bus.id, terminal)
18882 .expect("complete solution")
18883 })
18884 })
18885 .collect(),
18886 "source_active_injection" => solution.source_active_injections().to_vec(),
18887 "generator_active_power" => solution.generator_active_powers().to_vec(),
18888 "generator_coil_active_power" => solution
18889 .generator_coil_active_powers()
18890 .map(<[f64]>::to_vec)
18891 .ok_or_else(unknown)?,
18892 _ => return Err(unknown()),
18893 },
18894 _ => {
18895 return Err(boundary_error(
18896 &codes::REQUEST_CAPI_TYPE_MISMATCH,
18897 "the handle does not refer to a supported calculation solution",
18898 ));
18899 }
18900 };
18901 Ok(values)
18902}
18903
18904#[unsafe(no_mangle)]
18909pub unsafe extern "C" fn pio_calculation_solution_get_values(
18910 solution: *const PioCalculationSolution,
18911 quantity: *const c_char,
18912 quantity_len: usize,
18913 error: *mut *mut PioError,
18914) -> *mut PioVector {
18915 unsafe {
18916 entry(error, std::ptr::null_mut(), || {
18917 let quantity = required_str(quantity, quantity_len, "quantity")?;
18918 let solution = PioCalculationSolution::get(solution)
18919 .and_then(ValueInner::value)
18920 .ok_or_else(|| {
18921 boundary_error(
18922 &codes::BIND_CAPI_NULL_HANDLE,
18923 "PioCalculationSolution must not be NULL",
18924 )
18925 })?;
18926 collect_solution_values(solution, quantity)
18927 .map(|values| PioVector::new_raw(VectorInner { values }))
18928 })
18929 }
18930}
18931
18932#[unsafe(no_mangle)]
18936pub unsafe extern "C" fn pio_ac_scuc_solution_time_count(
18937 solution: *const PioCalculationSolution,
18938) -> usize {
18939 let Some(PioValue::AcScucSolution(solution)) =
18940 (unsafe { PioCalculationSolution::get(solution) }).and_then(ValueInner::value)
18941 else {
18942 return 0;
18943 };
18944 solution.instance().inputs().interval_durations.len()
18945}
18946
18947#[unsafe(no_mangle)]
18952pub unsafe extern "C" fn pio_ac_scuc_solution_get_values_at(
18953 solution: *const PioCalculationSolution,
18954 quantity: *const c_char,
18955 quantity_len: usize,
18956 time_index: usize,
18957 error: *mut *mut PioError,
18958) -> *mut PioVector {
18959 unsafe {
18960 entry(error, std::ptr::null_mut(), || {
18961 let quantity = required_str(quantity, quantity_len, "quantity")?;
18962 let Some(PioValue::AcScucSolution(solution)) =
18963 PioCalculationSolution::get(solution).and_then(ValueInner::value)
18964 else {
18965 return Err(boundary_error(
18966 &codes::REQUEST_CAPI_TYPE_MISMATCH,
18967 "the handle does not refer to powerio.AcScucSolution",
18968 ));
18969 };
18970 let network = solution.network_outputs();
18971 let device = solution.device_outputs();
18972 macro_rules! row {
18973 ($rows:expr, $convert:expr) => {{
18974 $rows
18975 .get(time_index)
18976 .ok_or_else(|| {
18977 boundary_error(
18978 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
18979 format!("AC SCUC time index {time_index} is out of range"),
18980 )
18981 })?
18982 .iter()
18983 .copied()
18984 .map($convert)
18985 .collect::<Vec<f64>>()
18986 }};
18987 }
18988 let values = match quantity {
18989 "bus_voltage_magnitude" => row!(&network.bus_vm, |value| value),
18990 "bus_voltage_angle" => row!(&network.bus_va, |value| value),
18991 "shunt_step" => row!(&network.shunt_step, |value| value as f64),
18992 "ac_line_on_status" => row!(&network.ac_line_on_status, f64::from),
18993 "transformer_tap_ratio" => row!(&network.transformer_tm, |value| value),
18994 "transformer_phase_shift" => row!(&network.transformer_ta, |value| value),
18995 "transformer_on_status" => row!(&network.transformer_on_status, f64::from),
18996 "dc_line_from_active_power" => row!(&network.dc_line_pdc_fr, |value| value),
18997 "dc_line_from_reactive_power" => row!(&network.dc_line_qdc_fr, |value| value),
18998 "dc_line_to_reactive_power" => row!(&network.dc_line_qdc_to, |value| value),
18999 "device_on_status" => row!(&device.on_status, f64::from),
19000 "device_startup_status" => row!(&device.startup_status, f64::from),
19001 "device_shutdown_status" => row!(&device.shutdown_status, f64::from),
19002 "device_active_power" => row!(&device.p_on, |value| value),
19003 "device_reactive_power" => row!(&device.q, |value| value),
19004 "regulation_reserve_up" => row!(&device.p_reg_res_up, |value| value),
19005 "regulation_reserve_down" => row!(&device.p_reg_res_down, |value| value),
19006 "synchronized_reserve" => row!(&device.p_syn_res, |value| value),
19007 "nonsynchronized_reserve" => row!(&device.p_nsyn_res, |value| value),
19008 "ramping_reserve_up_online" => row!(&device.p_ramp_res_up_online, |value| value),
19009 "ramping_reserve_up_offline" => {
19010 row!(&device.p_ramp_res_up_offline, |value| value)
19011 }
19012 "ramping_reserve_down_online" => {
19013 row!(&device.p_ramp_res_down_online, |value| value)
19014 }
19015 "ramping_reserve_down_offline" => {
19016 row!(&device.p_ramp_res_down_offline, |value| value)
19017 }
19018 "reactive_reserve_up" => row!(&device.q_res_up, |value| value),
19019 "reactive_reserve_down" => row!(&device.q_res_down, |value| value),
19020 _ => {
19021 return Err(boundary_error(
19022 &codes::REQUEST_CAPI_QUANTITY_UNKNOWN,
19023 format!("unknown AC SCUC solution quantity '{quantity}'"),
19024 ));
19025 }
19026 };
19027 Ok(PioVector::new_raw(VectorInner { values }))
19028 })
19029 }
19030}
19031
19032fn formula(name: Option<&str>) -> Result<BranchSusceptanceFormula, *mut PioError> {
19033 let name = name.unwrap_or("series_susceptance");
19034 BranchSusceptanceFormula::from_formula_name(name).ok_or_else(|| {
19035 boundary_error(
19036 &codes::REQUEST_CAPI_UNKNOWN_FORMULA,
19037 format!("unknown branch susceptance formula '{name}'"),
19038 )
19039 })
19040}
19041
19042unsafe fn dc_operators(
19043 network: *const PioBalancedNetwork,
19044 formula_name: *const c_char,
19045 formula_name_len: usize,
19046) -> Result<DcOperators, *mut PioError> {
19047 let network = unsafe { PioBalancedNetwork::get(network) }
19048 .and_then(BalancedNetworkInner::network)
19049 .ok_or_else(|| {
19050 boundary_error(
19051 &codes::BIND_CAPI_NULL_HANDLE,
19052 "PioBalancedNetwork must not be NULL",
19053 )
19054 })?;
19055 let formula_name = unsafe { optional_str(formula_name, formula_name_len, "formula") }?;
19056 let formula = formula(formula_name)?;
19057 let instance = DcPfInstance::from_network(network.clone())
19058 .map_err(|failure| error_from_core(&failure))?
19059 .with_branch_susceptance_formula(formula);
19060 DcOperators::build(&instance).map_err(|failure| error_from_core(&failure))
19061}
19062
19063struct DcOperatorsInner {
19066 operators: DcOperators,
19067 bus_ids: Vec<usize>,
19068}
19069
19070opaque_handle!(
19071 PioDcOperators,
19075 DcOperatorsInner
19076);
19077
19078#[unsafe(no_mangle)]
19091pub unsafe extern "C" fn pio_calc_dc_operators(
19092 network: *const PioBalancedNetwork,
19093 formula: *const c_char,
19094 formula_len: usize,
19095 skip_zero_impedance: bool,
19096 error: *mut *mut PioError,
19097) -> *mut PioDcOperators {
19098 unsafe {
19099 entry(error, std::ptr::null_mut(), || {
19100 let network = PioBalancedNetwork::get(network)
19101 .and_then(BalancedNetworkInner::network)
19102 .ok_or_else(|| {
19103 boundary_error(
19104 &codes::BIND_CAPI_NULL_HANDLE,
19105 "PioBalancedNetwork must not be NULL",
19106 )
19107 })?;
19108 let formula_name = optional_str(formula, formula_len, "formula")?;
19109 let formula = self::formula(formula_name)?;
19110 let instance = DcPfInstance::from_network(network.clone())
19111 .map_err(|failure| error_from_core(&failure))?
19112 .with_branch_susceptance_formula(formula);
19113 let options = DcOperatorOptions::new().with_skip_zero_impedance(skip_zero_impedance);
19114 let operators = DcOperators::build_with(&instance, &options)
19115 .map_err(|failure| error_from_core(&failure))?;
19116 let bus_ids = operators.bus_ids().iter().map(|bus| bus.0).collect();
19117 Ok(PioDcOperators::new_raw(DcOperatorsInner {
19118 operators,
19119 bus_ids,
19120 }))
19121 })
19122 }
19123}
19124
19125#[unsafe(no_mangle)]
19130pub unsafe extern "C" fn pio_dc_operators_n_buses(operators: *const PioDcOperators) -> usize {
19131 unsafe { PioDcOperators::get(operators) }.map_or(0, |inner| inner.bus_ids.len())
19132}
19133
19134#[unsafe(no_mangle)]
19139pub unsafe extern "C" fn pio_dc_operators_n_branches(operators: *const PioDcOperators) -> usize {
19140 unsafe { PioDcOperators::get(operators) }
19141 .map_or(0, |inner| inner.operators.branch_identities().len())
19142}
19143
19144#[unsafe(no_mangle)]
19149pub unsafe extern "C" fn pio_dc_operators_bus_ids(operators: *const PioDcOperators) -> PioSizeView {
19150 unsafe { PioDcOperators::get(operators) }
19151 .map_or(PioSizeView::EMPTY, |inner| PioSizeView::new(&inner.bus_ids))
19152}
19153
19154#[unsafe(no_mangle)]
19161pub unsafe extern "C" fn pio_dc_operators_branch_rows(
19162 operators: *const PioDcOperators,
19163) -> PioSizeView {
19164 unsafe { PioDcOperators::get(operators) }.map_or(PioSizeView::EMPTY, |inner| {
19165 PioSizeView::new(inner.operators.branch_rows())
19166 })
19167}
19168
19169#[unsafe(no_mangle)]
19175pub unsafe extern "C" fn pio_dc_operators_skipped_branch_rows(
19176 operators: *const PioDcOperators,
19177) -> PioSizeView {
19178 unsafe { PioDcOperators::get(operators) }.map_or(PioSizeView::EMPTY, |inner| {
19179 PioSizeView::new(inner.operators.skipped_branch_rows())
19180 })
19181}
19182
19183#[unsafe(no_mangle)]
19190pub unsafe extern "C" fn pio_dc_operators_branch_identity(
19191 operators: *const PioDcOperators,
19192 index: usize,
19193) -> PioStringView {
19194 unsafe { PioDcOperators::get(operators) }
19195 .and_then(|inner| inner.operators.branch_identities().get(index))
19196 .map_or(PioStringView::EMPTY, |identity| {
19197 PioStringView::new(identity)
19198 })
19199}
19200
19201unsafe fn dc_operators_matrix(
19202 operators: *const PioDcOperators,
19203 error: *mut *mut PioError,
19204 calculation: impl FnOnce(&DcOperators) -> SparseMatrix,
19205) -> *mut PioSparseMatrix {
19206 unsafe {
19207 entry(error, std::ptr::null_mut(), || {
19208 let inner = PioDcOperators::get(operators).ok_or_else(|| {
19209 boundary_error(
19210 &codes::BIND_CAPI_NULL_HANDLE,
19211 "PioDcOperators must not be NULL",
19212 )
19213 })?;
19214 Ok(PioSparseMatrix::new_raw(SparseMatrixInner::from(
19215 calculation(&inner.operators),
19216 )))
19217 })
19218 }
19219}
19220
19221unsafe fn dc_operators_vector(
19222 operators: *const PioDcOperators,
19223 error: *mut *mut PioError,
19224 calculation: impl FnOnce(&DcOperators) -> Vec<f64>,
19225) -> *mut PioVector {
19226 unsafe {
19227 entry(error, std::ptr::null_mut(), || {
19228 let inner = PioDcOperators::get(operators).ok_or_else(|| {
19229 boundary_error(
19230 &codes::BIND_CAPI_NULL_HANDLE,
19231 "PioDcOperators must not be NULL",
19232 )
19233 })?;
19234 Ok(PioVector::new_raw(VectorInner {
19235 values: calculation(&inner.operators),
19236 }))
19237 })
19238 }
19239}
19240
19241unsafe fn dc_operators_vector_from_angles(
19242 operators: *const PioDcOperators,
19243 voltage_angles: *const f64,
19244 voltage_angles_len: usize,
19245 error: *mut *mut PioError,
19246 calculation: impl FnOnce(&DcOperators, &[f64]) -> Result<Vec<f64>, powerio_core::Error>,
19247) -> *mut PioVector {
19248 unsafe {
19249 entry(error, std::ptr::null_mut(), || {
19250 if voltage_angles.is_null() && voltage_angles_len != 0 {
19251 return Err(boundary_error(
19252 &codes::BIND_CAPI_NULL_ARGUMENT,
19253 "voltage_angles is NULL with a nonzero length",
19254 ));
19255 }
19256 let angles = if voltage_angles_len == 0 {
19257 &[]
19258 } else {
19259 std::slice::from_raw_parts(voltage_angles, voltage_angles_len)
19260 };
19261 let inner = PioDcOperators::get(operators).ok_or_else(|| {
19262 boundary_error(
19263 &codes::BIND_CAPI_NULL_HANDLE,
19264 "PioDcOperators must not be NULL",
19265 )
19266 })?;
19267 calculation(&inner.operators, angles)
19268 .map(|values| PioVector::new_raw(VectorInner { values }))
19269 .map_err(|failure| error_from_core(&failure))
19270 })
19271 }
19272}
19273
19274#[unsafe(no_mangle)]
19279pub unsafe extern "C" fn pio_dc_operators_incidence_matrix(
19280 operators: *const PioDcOperators,
19281 error: *mut *mut PioError,
19282) -> *mut PioSparseMatrix {
19283 unsafe { dc_operators_matrix(operators, error, DcOperators::calc_incidence_matrix) }
19284}
19285
19286#[unsafe(no_mangle)]
19291pub unsafe extern "C" fn pio_dc_operators_bus_susceptance_matrix(
19292 operators: *const PioDcOperators,
19293 error: *mut *mut PioError,
19294) -> *mut PioSparseMatrix {
19295 unsafe { dc_operators_matrix(operators, error, DcOperators::calc_bus_susceptance_matrix) }
19296}
19297
19298#[unsafe(no_mangle)]
19303pub unsafe extern "C" fn pio_dc_operators_branch_flow_matrix(
19304 operators: *const PioDcOperators,
19305 error: *mut *mut PioError,
19306) -> *mut PioSparseMatrix {
19307 unsafe { dc_operators_matrix(operators, error, DcOperators::calc_branch_flow_matrix) }
19308}
19309
19310#[unsafe(no_mangle)]
19315pub unsafe extern "C" fn pio_dc_operators_branch_susceptances(
19316 operators: *const PioDcOperators,
19317 error: *mut *mut PioError,
19318) -> *mut PioVector {
19319 unsafe {
19320 dc_operators_vector(operators, error, |operators| {
19321 operators.calc_branch_susceptances().to_vec()
19322 })
19323 }
19324}
19325
19326#[unsafe(no_mangle)]
19331pub unsafe extern "C" fn pio_dc_operators_branch_phase_shift_injection(
19332 operators: *const PioDcOperators,
19333 error: *mut *mut PioError,
19334) -> *mut PioVector {
19335 unsafe {
19336 dc_operators_vector(
19337 operators,
19338 error,
19339 DcOperators::calc_branch_phase_shift_injection,
19340 )
19341 }
19342}
19343
19344#[unsafe(no_mangle)]
19349pub unsafe extern "C" fn pio_dc_operators_bus_phase_shift_injection(
19350 operators: *const PioDcOperators,
19351 error: *mut *mut PioError,
19352) -> *mut PioVector {
19353 unsafe {
19354 dc_operators_vector(
19355 operators,
19356 error,
19357 DcOperators::calc_bus_phase_shift_injection,
19358 )
19359 }
19360}
19361
19362#[unsafe(no_mangle)]
19367pub unsafe extern "C" fn pio_dc_operators_branch_flow_dc(
19368 operators: *const PioDcOperators,
19369 voltage_angles: *const f64,
19370 voltage_angles_len: usize,
19371 error: *mut *mut PioError,
19372) -> *mut PioVector {
19373 unsafe {
19374 dc_operators_vector_from_angles(
19375 operators,
19376 voltage_angles,
19377 voltage_angles_len,
19378 error,
19379 DcOperators::calc_branch_flow_dc,
19380 )
19381 }
19382}
19383
19384#[unsafe(no_mangle)]
19389pub unsafe extern "C" fn pio_dc_operators_bus_injection_dc(
19390 operators: *const PioDcOperators,
19391 voltage_angles: *const f64,
19392 voltage_angles_len: usize,
19393 error: *mut *mut PioError,
19394) -> *mut PioVector {
19395 unsafe {
19396 dc_operators_vector_from_angles(
19397 operators,
19398 voltage_angles,
19399 voltage_angles_len,
19400 error,
19401 DcOperators::calc_bus_injection_dc,
19402 )
19403 }
19404}
19405
19406#[unsafe(no_mangle)]
19411pub unsafe extern "C" fn pio_dc_operators_retain(
19412 operators: *const PioDcOperators,
19413) -> *mut PioDcOperators {
19414 unsafe { PioDcOperators::retain_raw(operators) }
19415}
19416
19417#[unsafe(no_mangle)]
19422pub unsafe extern "C" fn pio_dc_operators_release(operators: *mut PioDcOperators) {
19423 unsafe { PioDcOperators::release_raw(operators) };
19424}
19425
19426#[repr(C)]
19436#[derive(Clone, Copy)]
19437pub struct PioIslandView {
19438 pub bus_indices: PioSizeView,
19439 pub bus_ids: PioSizeView,
19440 pub reference_bus_indices: PioSizeView,
19441 pub reference_bus_ids: PioSizeView,
19442 pub generator_rows: PioSizeView,
19443 pub hvdc_rows: PioSizeView,
19444 pub supplied: bool,
19445}
19446
19447struct IslandRows {
19448 bus_indices: Vec<usize>,
19449 bus_ids: Vec<usize>,
19450 reference_bus_indices: Vec<usize>,
19451 reference_bus_ids: Vec<usize>,
19452 generator_rows: Vec<usize>,
19453 hvdc_rows: Vec<usize>,
19454 supplied: bool,
19455}
19456
19457struct IslandsInner {
19458 islands: Vec<IslandRows>,
19459 isolated_bus_indices: Vec<usize>,
19460 isolated_bus_ids: Vec<usize>,
19461}
19462
19463opaque_handle!(
19464 PioIslands,
19467 IslandsInner
19468);
19469
19470#[unsafe(no_mangle)]
19482pub unsafe extern "C" fn pio_balanced_network_islands(
19483 network: *const PioBalancedNetwork,
19484 error: *mut *mut PioError,
19485) -> *mut PioIslands {
19486 unsafe {
19487 entry(error, std::ptr::null_mut(), || {
19488 let network = require_balanced_network(network)?;
19489 let position: std::collections::HashMap<powerio_tx::BusId, usize> = network
19490 .buses()
19491 .iter()
19492 .enumerate()
19493 .map(|(index, bus)| (bus.id, index))
19494 .collect();
19495 let indices = |ids: &[powerio_tx::BusId]| -> Vec<usize> {
19496 ids.iter()
19497 .filter_map(|id| position.get(id).copied())
19498 .collect()
19499 };
19500 let raw =
19501 |ids: &[powerio_tx::BusId]| -> Vec<usize> { ids.iter().map(|id| id.0).collect() };
19502 let partition = network.calc_islands();
19503 let islands = partition
19504 .islands
19505 .iter()
19506 .map(|island| IslandRows {
19507 bus_indices: indices(&island.buses),
19508 bus_ids: raw(&island.buses),
19509 reference_bus_indices: indices(&island.references),
19510 reference_bus_ids: raw(&island.references),
19511 generator_rows: island.generators.clone(),
19512 hvdc_rows: island.hvdc.clone(),
19513 supplied: island.is_supplied(),
19514 })
19515 .collect();
19516 Ok(PioIslands::new_raw(IslandsInner {
19517 islands,
19518 isolated_bus_indices: indices(&partition.isolated),
19519 isolated_bus_ids: raw(&partition.isolated),
19520 }))
19521 })
19522 }
19523}
19524
19525#[unsafe(no_mangle)]
19530pub unsafe extern "C" fn pio_islands_count(islands: *const PioIslands) -> usize {
19531 unsafe { PioIslands::get(islands) }.map_or(0, |inner| inner.islands.len())
19532}
19533
19534#[unsafe(no_mangle)]
19540pub unsafe extern "C" fn pio_islands_at(
19541 islands: *const PioIslands,
19542 index: usize,
19543 output: *mut PioIslandView,
19544 error: *mut *mut PioError,
19545) -> bool {
19546 unsafe {
19547 entry(error, false, || {
19548 let inner = PioIslands::get(islands).ok_or_else(|| {
19549 boundary_error(&codes::BIND_CAPI_NULL_HANDLE, "PioIslands must not be NULL")
19550 })?;
19551 let island = inner.islands.get(index).ok_or_else(|| {
19552 boundary_error(
19553 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
19554 format!("island index {index} is out of range"),
19555 )
19556 })?;
19557 *require_output(output, "output")? = PioIslandView {
19558 bus_indices: PioSizeView::new(&island.bus_indices),
19559 bus_ids: PioSizeView::new(&island.bus_ids),
19560 reference_bus_indices: PioSizeView::new(&island.reference_bus_indices),
19561 reference_bus_ids: PioSizeView::new(&island.reference_bus_ids),
19562 generator_rows: PioSizeView::new(&island.generator_rows),
19563 hvdc_rows: PioSizeView::new(&island.hvdc_rows),
19564 supplied: island.supplied,
19565 };
19566 Ok(true)
19567 })
19568 }
19569}
19570
19571#[unsafe(no_mangle)]
19577pub unsafe extern "C" fn pio_islands_isolated_bus_indices(
19578 islands: *const PioIslands,
19579) -> PioSizeView {
19580 unsafe { PioIslands::get(islands) }.map_or(PioSizeView::EMPTY, |inner| {
19581 PioSizeView::new(&inner.isolated_bus_indices)
19582 })
19583}
19584
19585#[unsafe(no_mangle)]
19591pub unsafe extern "C" fn pio_islands_isolated_bus_ids(islands: *const PioIslands) -> PioSizeView {
19592 unsafe { PioIslands::get(islands) }.map_or(PioSizeView::EMPTY, |inner| {
19593 PioSizeView::new(&inner.isolated_bus_ids)
19594 })
19595}
19596
19597#[unsafe(no_mangle)]
19602pub unsafe extern "C" fn pio_islands_retain(islands: *const PioIslands) -> *mut PioIslands {
19603 unsafe { PioIslands::retain_raw(islands) }
19604}
19605
19606#[unsafe(no_mangle)]
19611pub unsafe extern "C" fn pio_islands_release(islands: *mut PioIslands) {
19612 unsafe { PioIslands::release_raw(islands) };
19613}
19614
19615struct SensitivitiesInner {
19618 bus_ids: Vec<usize>,
19619 branch_rows: Vec<usize>,
19620 branch_identities: Vec<String>,
19621 reference_bus_indices: Vec<usize>,
19622 ptdf: Vec<f64>,
19623 lodf: Vec<f64>,
19624 solver_path: &'static str,
19625 reduced_dimension: usize,
19626}
19627
19628opaque_handle!(
19629 PioSensitivities,
19632 SensitivitiesInner
19633);
19634
19635fn sensitivity_solver(name: Option<&str>) -> Result<SensitivitySolver, *mut PioError> {
19636 match name.unwrap_or("auto") {
19637 "auto" => Ok(SensitivitySolver::Auto),
19638 "dense" => Ok(SensitivitySolver::Dense),
19639 "sparse" => Ok(SensitivitySolver::Sparse),
19640 other => Err(boundary_error(
19641 &codes::BIND_CAPI_INVALID_ARGUMENT,
19642 format!("unknown sensitivity solver '{other}'; expected auto, dense, or sparse"),
19643 )),
19644 }
19645}
19646
19647fn dense_row_major(matrix: &SparseMatrix) -> Result<Vec<f64>, *mut PioError> {
19649 let (rows, columns) = matrix.shape();
19650 let len = rows.checked_mul(columns).ok_or_else(|| {
19651 boundary_error(
19652 &codes::BIND_CAPI_INVALID_ARGUMENT,
19653 format!("a dense {rows} by {columns} matrix does not fit in memory"),
19654 )
19655 })?;
19656 let mut dense = vec![0.0; len];
19657 for (&value, (row, column)) in matrix {
19658 dense[row * columns + column] = value;
19659 }
19660 Ok(dense)
19661}
19662
19663#[unsafe(no_mangle)]
19683pub unsafe extern "C" fn pio_calc_sensitivities(
19684 network: *const PioBalancedNetwork,
19685 formula: *const c_char,
19686 formula_len: usize,
19687 solver: *const c_char,
19688 solver_len: usize,
19689 error: *mut *mut PioError,
19690) -> *mut PioSensitivities {
19691 unsafe {
19692 entry(error, std::ptr::null_mut(), || {
19693 let network = require_balanced_network(network)?;
19694 let formula = self::formula(optional_str(formula, formula_len, "formula")?)?;
19695 let solver = sensitivity_solver(optional_str(solver, solver_len, "solver")?)?;
19696 let options = SensitivityOptions {
19697 formula,
19698 solver,
19699 ..SensitivityOptions::default()
19700 };
19701 let view = IndexedNetwork::new(network);
19702 let matrices = calc_ptdf_lodf_with_options(&view, &options)
19703 .map_err(|failure| error_from_matrix(&failure))?;
19704 let bus_ids = (0..view.n()).map(|index| view.bus_id(index).0).collect();
19705 let (branch_rows, branch_identities): (Vec<usize>, Vec<String>) = view
19706 .in_service_branches()
19707 .filter(|(_, branch)| branch.from != branch.to)
19708 .map(|(row, branch)| {
19709 let identity = branch
19710 .uid
19711 .clone()
19712 .unwrap_or_else(|| format!("branches:{row}"));
19713 (row, identity)
19714 })
19715 .unzip();
19716 if branch_rows.len() != matrices.ptdf.rows() || view.n() != matrices.ptdf.cols() {
19717 return Err(boundary_error(
19718 &codes::BIND_CAPI_UNCODED_FAILURE,
19719 "the PTDF shape does not match the network's DC axes",
19720 ));
19721 }
19722 Ok(PioSensitivities::new_raw(SensitivitiesInner {
19723 bus_ids,
19724 branch_rows,
19725 branch_identities,
19726 reference_bus_indices: view.reference_bus_indices(),
19727 ptdf: dense_row_major(&matrices.ptdf)?,
19728 lodf: dense_row_major(&matrices.lodf)?,
19729 solver_path: matrices.metadata.solver_path.as_str(),
19730 reduced_dimension: matrices.metadata.reduced_dimension,
19731 }))
19732 })
19733 }
19734}
19735
19736#[unsafe(no_mangle)]
19741pub unsafe extern "C" fn pio_sensitivities_n_buses(
19742 sensitivities: *const PioSensitivities,
19743) -> usize {
19744 unsafe { PioSensitivities::get(sensitivities) }.map_or(0, |inner| inner.bus_ids.len())
19745}
19746
19747#[unsafe(no_mangle)]
19752pub unsafe extern "C" fn pio_sensitivities_n_branches(
19753 sensitivities: *const PioSensitivities,
19754) -> usize {
19755 unsafe { PioSensitivities::get(sensitivities) }.map_or(0, |inner| inner.branch_rows.len())
19756}
19757
19758#[unsafe(no_mangle)]
19763pub unsafe extern "C" fn pio_sensitivities_bus_ids(
19764 sensitivities: *const PioSensitivities,
19765) -> PioSizeView {
19766 unsafe { PioSensitivities::get(sensitivities) }
19767 .map_or(PioSizeView::EMPTY, |inner| PioSizeView::new(&inner.bus_ids))
19768}
19769
19770#[unsafe(no_mangle)]
19776pub unsafe extern "C" fn pio_sensitivities_branch_rows(
19777 sensitivities: *const PioSensitivities,
19778) -> PioSizeView {
19779 unsafe { PioSensitivities::get(sensitivities) }.map_or(PioSizeView::EMPTY, |inner| {
19780 PioSizeView::new(&inner.branch_rows)
19781 })
19782}
19783
19784#[unsafe(no_mangle)]
19791pub unsafe extern "C" fn pio_sensitivities_branch_identity(
19792 sensitivities: *const PioSensitivities,
19793 index: usize,
19794) -> PioStringView {
19795 unsafe { PioSensitivities::get(sensitivities) }
19796 .and_then(|inner| inner.branch_identities.get(index))
19797 .map_or(PioStringView::EMPTY, |identity| {
19798 PioStringView::new(identity)
19799 })
19800}
19801
19802#[unsafe(no_mangle)]
19808pub unsafe extern "C" fn pio_sensitivities_reference_bus_indices(
19809 sensitivities: *const PioSensitivities,
19810) -> PioSizeView {
19811 unsafe { PioSensitivities::get(sensitivities) }.map_or(PioSizeView::EMPTY, |inner| {
19812 PioSizeView::new(&inner.reference_bus_indices)
19813 })
19814}
19815
19816#[unsafe(no_mangle)]
19823pub unsafe extern "C" fn pio_sensitivities_ptdf(
19824 sensitivities: *const PioSensitivities,
19825) -> PioF64View {
19826 unsafe { PioSensitivities::get(sensitivities) }
19827 .map_or(PioF64View::EMPTY, |inner| PioF64View::new(&inner.ptdf))
19828}
19829
19830#[unsafe(no_mangle)]
19838pub unsafe extern "C" fn pio_sensitivities_lodf(
19839 sensitivities: *const PioSensitivities,
19840) -> PioF64View {
19841 unsafe { PioSensitivities::get(sensitivities) }
19842 .map_or(PioF64View::EMPTY, |inner| PioF64View::new(&inner.lodf))
19843}
19844
19845#[unsafe(no_mangle)]
19851pub unsafe extern "C" fn pio_sensitivities_solver_path(
19852 sensitivities: *const PioSensitivities,
19853) -> PioStringView {
19854 unsafe { PioSensitivities::get(sensitivities) }.map_or(PioStringView::EMPTY, |inner| {
19855 PioStringView::new(inner.solver_path)
19856 })
19857}
19858
19859#[unsafe(no_mangle)]
19865pub unsafe extern "C" fn pio_sensitivities_reduced_dimension(
19866 sensitivities: *const PioSensitivities,
19867) -> usize {
19868 unsafe { PioSensitivities::get(sensitivities) }.map_or(0, |inner| inner.reduced_dimension)
19869}
19870
19871#[unsafe(no_mangle)]
19876pub unsafe extern "C" fn pio_sensitivities_retain(
19877 sensitivities: *const PioSensitivities,
19878) -> *mut PioSensitivities {
19879 unsafe { PioSensitivities::retain_raw(sensitivities) }
19880}
19881
19882#[unsafe(no_mangle)]
19887pub unsafe extern "C" fn pio_sensitivities_release(sensitivities: *mut PioSensitivities) {
19888 unsafe { PioSensitivities::release_raw(sensitivities) };
19889}
19890
19891unsafe fn dc_matrix(
19892 network: *const PioBalancedNetwork,
19893 formula: *const c_char,
19894 formula_len: usize,
19895 error: *mut *mut PioError,
19896 calculation: impl FnOnce(&DcOperators) -> SparseMatrix,
19897) -> *mut PioSparseMatrix {
19898 unsafe {
19899 entry(error, std::ptr::null_mut(), || {
19900 let operators = dc_operators(network, formula, formula_len)?;
19901 Ok(PioSparseMatrix::new_raw(SparseMatrixInner::from(
19902 calculation(&operators),
19903 )))
19904 })
19905 }
19906}
19907
19908unsafe fn dc_vector(
19909 network: *const PioBalancedNetwork,
19910 formula: *const c_char,
19911 formula_len: usize,
19912 error: *mut *mut PioError,
19913 calculation: impl FnOnce(&DcOperators) -> Vec<f64>,
19914) -> *mut PioVector {
19915 unsafe {
19916 entry(error, std::ptr::null_mut(), || {
19917 let operators = dc_operators(network, formula, formula_len)?;
19918 Ok(PioVector::new_raw(VectorInner {
19919 values: calculation(&operators),
19920 }))
19921 })
19922 }
19923}
19924
19925#[unsafe(no_mangle)]
19935pub unsafe extern "C" fn pio_calc_incidence_matrix(
19936 network: *const PioBalancedNetwork,
19937 formula: *const c_char,
19938 formula_len: usize,
19939 error: *mut *mut PioError,
19940) -> *mut PioSparseMatrix {
19941 unsafe {
19942 dc_matrix(network, formula, formula_len, error, |operators| {
19943 operators.calc_incidence_matrix()
19944 })
19945 }
19946}
19947
19948#[unsafe(no_mangle)]
19952pub unsafe extern "C" fn pio_calc_bus_susceptance_matrix(
19953 network: *const PioBalancedNetwork,
19954 formula: *const c_char,
19955 formula_len: usize,
19956 error: *mut *mut PioError,
19957) -> *mut PioSparseMatrix {
19958 unsafe {
19959 dc_matrix(network, formula, formula_len, error, |operators| {
19960 operators.calc_bus_susceptance_matrix()
19961 })
19962 }
19963}
19964
19965#[unsafe(no_mangle)]
19969pub unsafe extern "C" fn pio_calc_branch_flow_matrix(
19970 network: *const PioBalancedNetwork,
19971 formula: *const c_char,
19972 formula_len: usize,
19973 error: *mut *mut PioError,
19974) -> *mut PioSparseMatrix {
19975 unsafe {
19976 dc_matrix(network, formula, formula_len, error, |operators| {
19977 operators.calc_branch_flow_matrix()
19978 })
19979 }
19980}
19981
19982#[unsafe(no_mangle)]
19986pub unsafe extern "C" fn pio_calc_branch_susceptances(
19987 network: *const PioBalancedNetwork,
19988 formula: *const c_char,
19989 formula_len: usize,
19990 error: *mut *mut PioError,
19991) -> *mut PioVector {
19992 unsafe {
19993 dc_vector(network, formula, formula_len, error, |operators| {
19994 operators.calc_branch_susceptances().to_vec()
19995 })
19996 }
19997}
19998
19999#[unsafe(no_mangle)]
20003pub unsafe extern "C" fn pio_calc_branch_phase_shift_injection(
20004 network: *const PioBalancedNetwork,
20005 formula: *const c_char,
20006 formula_len: usize,
20007 error: *mut *mut PioError,
20008) -> *mut PioVector {
20009 unsafe {
20010 dc_vector(network, formula, formula_len, error, |operators| {
20011 operators.calc_branch_phase_shift_injection()
20012 })
20013 }
20014}
20015
20016#[unsafe(no_mangle)]
20020pub unsafe extern "C" fn pio_calc_bus_phase_shift_injection(
20021 network: *const PioBalancedNetwork,
20022 formula: *const c_char,
20023 formula_len: usize,
20024 error: *mut *mut PioError,
20025) -> *mut PioVector {
20026 unsafe {
20027 dc_vector(network, formula, formula_len, error, |operators| {
20028 operators.calc_bus_phase_shift_injection()
20029 })
20030 }
20031}
20032
20033unsafe fn dc_vector_from_angles(
20034 network: *const PioBalancedNetwork,
20035 formula_name: *const c_char,
20036 formula_name_len: usize,
20037 voltage_angles: *const f64,
20038 voltage_angles_len: usize,
20039 error: *mut *mut PioError,
20040 calculation: impl FnOnce(&DcOperators, &[f64]) -> Result<Vec<f64>, powerio_core::Error>,
20041) -> *mut PioVector {
20042 unsafe {
20043 entry(error, std::ptr::null_mut(), || {
20044 if voltage_angles.is_null() && voltage_angles_len != 0 {
20045 return Err(boundary_error(
20046 &codes::BIND_CAPI_NULL_ARGUMENT,
20047 "voltage_angles is NULL with a nonzero length",
20048 ));
20049 }
20050 let angles = if voltage_angles_len == 0 {
20051 &[]
20052 } else {
20053 std::slice::from_raw_parts(voltage_angles, voltage_angles_len)
20054 };
20055 let operators = dc_operators(network, formula_name, formula_name_len)?;
20056 calculation(&operators, angles)
20057 .map(|values| PioVector::new_raw(VectorInner { values }))
20058 .map_err(|failure| error_from_core(&failure))
20059 })
20060 }
20061}
20062
20063#[unsafe(no_mangle)]
20067pub unsafe extern "C" fn pio_calc_branch_flow_dc(
20068 network: *const PioBalancedNetwork,
20069 formula: *const c_char,
20070 formula_len: usize,
20071 voltage_angles: *const f64,
20072 voltage_angles_len: usize,
20073 error: *mut *mut PioError,
20074) -> *mut PioVector {
20075 unsafe {
20076 dc_vector_from_angles(
20077 network,
20078 formula,
20079 formula_len,
20080 voltage_angles,
20081 voltage_angles_len,
20082 error,
20083 DcOperators::calc_branch_flow_dc,
20084 )
20085 }
20086}
20087
20088#[unsafe(no_mangle)]
20092pub unsafe extern "C" fn pio_calc_bus_injection_dc(
20093 network: *const PioBalancedNetwork,
20094 formula: *const c_char,
20095 formula_len: usize,
20096 voltage_angles: *const f64,
20097 voltage_angles_len: usize,
20098 error: *mut *mut PioError,
20099) -> *mut PioVector {
20100 unsafe {
20101 dc_vector_from_angles(
20102 network,
20103 formula,
20104 formula_len,
20105 voltage_angles,
20106 voltage_angles_len,
20107 error,
20108 DcOperators::calc_bus_injection_dc,
20109 )
20110 }
20111}
20112
20113#[unsafe(no_mangle)]
20117pub unsafe extern "C" fn pio_sparse_matrix_rows(matrix: *const PioSparseMatrix) -> usize {
20118 unsafe { PioSparseMatrix::get(matrix) }.map_or(0, |matrix| matrix.rows)
20119}
20120
20121#[unsafe(no_mangle)]
20125pub unsafe extern "C" fn pio_sparse_matrix_columns(matrix: *const PioSparseMatrix) -> usize {
20126 unsafe { PioSparseMatrix::get(matrix) }.map_or(0, |matrix| matrix.columns)
20127}
20128
20129#[unsafe(no_mangle)]
20133pub unsafe extern "C" fn pio_sparse_matrix_row_offsets(
20134 matrix: *const PioSparseMatrix,
20135) -> PioSizeView {
20136 unsafe { PioSparseMatrix::get(matrix) }.map_or(PioSizeView::EMPTY, |matrix| {
20137 PioSizeView::new(&matrix.row_offsets)
20138 })
20139}
20140
20141#[unsafe(no_mangle)]
20145pub unsafe extern "C" fn pio_sparse_matrix_column_indices(
20146 matrix: *const PioSparseMatrix,
20147) -> PioSizeView {
20148 unsafe { PioSparseMatrix::get(matrix) }.map_or(PioSizeView::EMPTY, |matrix| {
20149 PioSizeView::new(&matrix.column_indices)
20150 })
20151}
20152
20153#[unsafe(no_mangle)]
20157pub unsafe extern "C" fn pio_sparse_matrix_values(matrix: *const PioSparseMatrix) -> PioF64View {
20158 unsafe { PioSparseMatrix::get(matrix) }
20159 .map_or(PioF64View::EMPTY, |matrix| PioF64View::new(&matrix.values))
20160}
20161
20162#[unsafe(no_mangle)]
20167pub unsafe extern "C" fn pio_sparse_matrix_retain(
20168 matrix: *const PioSparseMatrix,
20169) -> *mut PioSparseMatrix {
20170 unsafe { PioSparseMatrix::retain_raw(matrix) }
20171}
20172
20173#[unsafe(no_mangle)]
20178pub unsafe extern "C" fn pio_sparse_matrix_release(matrix: *mut PioSparseMatrix) {
20179 unsafe { PioSparseMatrix::release_raw(matrix) };
20180}
20181
20182#[unsafe(no_mangle)]
20186pub unsafe extern "C" fn pio_vector_values(vector: *const PioVector) -> PioF64View {
20187 unsafe { PioVector::get(vector) }
20188 .map_or(PioF64View::EMPTY, |vector| PioF64View::new(&vector.values))
20189}
20190
20191#[unsafe(no_mangle)]
20196pub unsafe extern "C" fn pio_vector_retain(vector: *const PioVector) -> *mut PioVector {
20197 unsafe { PioVector::retain_raw(vector) }
20198}
20199
20200#[unsafe(no_mangle)]
20205pub unsafe extern "C" fn pio_vector_release(vector: *mut PioVector) {
20206 unsafe { PioVector::release_raw(vector) };
20207}
20208
20209struct StringInner {
20212 text: String,
20213}
20214
20215opaque_handle!(
20216 PioString,
20218 StringInner
20219);
20220
20221#[unsafe(no_mangle)]
20226pub unsafe extern "C" fn pio_schema_report(error: *mut *mut PioError) -> *mut PioString {
20227 unsafe {
20228 entry(error, std::ptr::null_mut(), || {
20229 serde_json::to_string(&serde_json::json!({
20230 "powerio_version": powerio::VERSION,
20231 "powerio_ir": {
20232 "schema": powerio::IR_SCHEMA_NAME,
20233 "version": powerio::IR_VERSION
20234 },
20235 "bmopf_schema": powerio_dist::BMOPF_SCHEMA_ID,
20236 "features": {
20240 "matrix": true,
20241 "gridfm": cfg!(feature = "gridfm"),
20242 "dist": true,
20243 "prob": true
20244 },
20245 "foreign_schemas": {
20246 "bmopf": powerio_dist::BMOPF_SCHEMA_ID
20247 },
20248 "error_categories": powerio_core::ErrorCategory::TOKENS,
20249 "diagnostic_namespaces": powerio_core::DiagnosticStage::NAMESPACES,
20250 "json_classes": powerio::JSON_CLASSES
20251 }))
20252 .map(|text| PioString::new_raw(StringInner { text }))
20253 .map_err(|failure| {
20254 boundary_error(
20255 &codes::EMIT_CAPI_SERIALIZE_FAILED,
20256 format!("cannot serialize the schema report: {failure}"),
20257 )
20258 })
20259 })
20260 }
20261}
20262
20263#[unsafe(no_mangle)]
20267pub unsafe extern "C" fn pio_string_view(string: *const PioString) -> PioStringView {
20268 unsafe { PioString::get(string) }.map_or(PioStringView::EMPTY, |string| {
20269 PioStringView::new(&string.text)
20270 })
20271}
20272
20273#[unsafe(no_mangle)]
20278pub unsafe extern "C" fn pio_string_retain(string: *const PioString) -> *mut PioString {
20279 unsafe { PioString::retain_raw(string) }
20280}
20281
20282#[unsafe(no_mangle)]
20287pub unsafe extern "C" fn pio_string_release(string: *mut PioString) {
20288 unsafe { PioString::release_raw(string) };
20289}
20290
20291#[unsafe(no_mangle)]
20298pub unsafe extern "C" fn pio_multiconductor_network_voltage_source_boundary_at(
20299 network: *const PioMulticonductorNetwork,
20300 index: usize,
20301 output: *mut PioVoltageSourceBoundaryView,
20302 error: *mut *mut PioError,
20303) -> bool {
20304 unsafe {
20305 entry(error, false, || {
20306 let source = require_multiconductor_network(network)?
20307 .sources()
20308 .get(index)
20309 .ok_or_else(|| {
20310 boundary_error(
20311 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
20312 format!("voltage source index {index} is out of range"),
20313 )
20314 })?;
20315 *require_output(output, "output")? = voltage_source_boundary_view(source);
20316 Ok(true)
20317 })
20318 }
20319}
20320
20321#[unsafe(no_mangle)]
20329pub unsafe extern "C" fn pio_mc_ac_pf_instance_source_boundary_at(
20330 instance: *const PioCalculationInstance,
20331 index: usize,
20332 output: *mut PioVoltageSourceBoundaryView,
20333 error: *mut *mut PioError,
20334) -> bool {
20335 unsafe {
20336 entry(error, false, || {
20337 let instance = require_calculation_instance(instance)?
20338 .mc_ac_pf()
20339 .ok_or_else(|| {
20340 boundary_error(
20341 &codes::REQUEST_CAPI_TYPE_MISMATCH,
20342 "the calculation instance is not powerio.McAcPfInstance",
20343 )
20344 })?;
20345 let source = instance.network().sources().get(index).ok_or_else(|| {
20346 boundary_error(
20347 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
20348 format!("prescribed source index {index} is out of range"),
20349 )
20350 })?;
20351 *require_output(output, "output")? = voltage_source_boundary_view(source);
20352 Ok(true)
20353 })
20354 }
20355}
20356
20357unsafe fn input_slice<'a, T>(
20362 data: *const T,
20363 len: usize,
20364 argument: &str,
20365) -> Result<&'a [T], *mut PioError> {
20366 if len == 0 {
20367 return Ok(&[]);
20368 }
20369 if data.is_null() {
20370 return Err(boundary_error(
20371 &codes::BIND_CAPI_NULL_ARGUMENT,
20372 format!("{argument} is NULL with a nonzero length"),
20373 ));
20374 }
20375 Ok(unsafe { std::slice::from_raw_parts(data, len) })
20376}
20377
20378fn invalid_ots_option(message: String) -> *mut PioError {
20379 boundary_error(&codes::BIND_CAPI_INVALID_OPTIONS, message)
20380}
20381
20382unsafe fn ac_ots_options(
20386 options: *const PioAcOtsOptions,
20387) -> Result<powerio_prob::AcOtsOptions, *mut PioError> {
20388 let mut parsed = powerio_prob::AcOtsOptions::default();
20389 let Some(raw) = (unsafe { options.as_ref() }) else {
20390 return Ok(parsed);
20391 };
20392 let switchable = unsafe {
20393 required_str(
20394 raw.switchable.data,
20395 raw.switchable.len,
20396 "options.switchable",
20397 )
20398 }?;
20399 let identities =
20400 unsafe { input_slice(raw.identities, raw.identities_len, "options.identities") }?;
20401 parsed.switchable = match switchable {
20402 "only" => powerio_prob::BranchSelection::Only(
20403 identities
20404 .iter()
20405 .enumerate()
20406 .map(|(index, identity)| {
20407 unsafe {
20408 required_str(
20409 identity.data,
20410 identity.len,
20411 &format!("options.identities[{index}]"),
20412 )
20413 }
20414 .map(str::to_owned)
20415 })
20416 .collect::<Result<_, _>>()?,
20417 ),
20418 "all" | "none" if !identities.is_empty() => {
20419 return Err(invalid_ots_option(format!(
20420 "options.identities names branches, but the selection is '{switchable}'; \
20421 identities require 'only'"
20422 )));
20423 }
20424 "all" => powerio_prob::BranchSelection::All,
20425 "none" => powerio_prob::BranchSelection::None,
20426 other => {
20427 return Err(invalid_ots_option(format!(
20428 "unknown branch selection '{other}'; expected 'all', 'none', or 'only'"
20429 )));
20430 }
20431 };
20432 let costs = unsafe {
20433 input_slice(
20434 raw.switching_costs,
20435 raw.switching_costs_len,
20436 "options.switching_costs",
20437 )
20438 }?;
20439 parsed.switching_costs = costs
20440 .iter()
20441 .enumerate()
20442 .map(|(index, cost)| {
20443 let id = unsafe {
20444 required_str(
20445 cost.id.data,
20446 cost.id.len,
20447 &format!("options.switching_costs[{index}].id"),
20448 )
20449 }?;
20450 Ok(powerio_prob::BranchSwitchingCost::new(
20451 id,
20452 cost.open_cost,
20453 cost.close_cost,
20454 ))
20455 })
20456 .collect::<Result<_, *mut PioError>>()?;
20457 parsed.islanding = match unsafe {
20458 required_str(raw.islanding.data, raw.islanding.len, "options.islanding")
20459 }? {
20460 "forbidden" => powerio_prob::IslandingPolicy::Forbidden,
20461 "allowed" => powerio_prob::IslandingPolicy::Allowed,
20462 other => {
20463 return Err(invalid_ots_option(format!(
20464 "unknown islanding policy '{other}'; expected 'forbidden' or 'allowed'"
20465 )));
20466 }
20467 };
20468 parsed.max_open = raw.has_max_open.then_some(raw.max_open);
20469 parsed.max_switched = raw.has_max_switched.then_some(raw.max_switched);
20470 parsed.current_limits = match unsafe {
20471 required_str(
20472 raw.current_limits.data,
20473 raw.current_limits.len,
20474 "options.current_limits",
20475 )
20476 }? {
20477 "skip" => powerio_prob::CurrentLimitPolicy::Skip,
20478 "stated" => powerio_prob::CurrentLimitPolicy::Stated,
20479 "derive_from_rate_a" => powerio_prob::CurrentLimitPolicy::DeriveFromRateA,
20480 other => {
20481 return Err(invalid_ots_option(format!(
20482 "unknown current limit policy '{other}'; expected 'skip', 'stated', or \
20483 'derive_from_rate_a'"
20484 )));
20485 }
20486 };
20487 let limits = unsafe {
20488 input_slice(
20489 raw.stated_current_limits,
20490 raw.stated_current_limits_len,
20491 "options.stated_current_limits",
20492 )
20493 }?;
20494 parsed.stated_current_limits = limits
20495 .iter()
20496 .enumerate()
20497 .map(|(index, limit)| {
20498 let id = unsafe {
20499 required_str(
20500 limit.id.data,
20501 limit.id.len,
20502 &format!("options.stated_current_limits[{index}].id"),
20503 )
20504 }?;
20505 Ok(powerio_prob::BranchCurrentLimit::new(
20506 id,
20507 limit.has_from_pu.then_some(limit.from_pu),
20508 limit.has_to_pu.then_some(limit.to_pu),
20509 ))
20510 })
20511 .collect::<Result<_, *mut PioError>>()?;
20512 Ok(parsed)
20513}
20514
20515unsafe fn branch_statuses(data: *const u8, len: usize) -> Result<Vec<bool>, *mut PioError> {
20517 unsafe { input_slice(data, len, "branch_closed") }?
20518 .iter()
20519 .enumerate()
20520 .map(|(index, &status)| match status {
20521 0 => Ok(false),
20522 1 => Ok(true),
20523 other => Err(boundary_error(
20524 &codes::BIND_CAPI_INVALID_ARGUMENT,
20525 format!("branch_closed[{index}] is {other}; a status is 0 (open) or 1 (closed)"),
20526 )),
20527 })
20528 .collect()
20529}
20530
20531unsafe fn require_ac_ots_instance<'a>(
20532 instance: *const PioCalculationInstance,
20533) -> Result<
20534 (
20535 &'a CalculationInstanceInner,
20536 &'a powerio_prob::AcOtsInstance,
20537 ),
20538 *mut PioError,
20539> {
20540 let handle = unsafe { require_calculation_instance(instance) }?;
20541 let instance = handle.ac_ots().ok_or_else(|| {
20542 boundary_error(
20543 &codes::REQUEST_CAPI_TYPE_MISMATCH,
20544 "the calculation instance is not powerio.AcOtsInstance",
20545 )
20546 })?;
20547 Ok((handle, instance))
20548}
20549
20550unsafe fn require_ac_ots_solution<'a>(
20551 solution: *const PioCalculationSolution,
20552) -> Result<(&'a ValueInner, &'a powerio_prob::AcOtsSolution), *mut PioError> {
20553 let handle = unsafe { PioCalculationSolution::get(solution) }.ok_or_else(|| {
20554 boundary_error(
20555 &codes::BIND_CAPI_NULL_HANDLE,
20556 "PioCalculationSolution must not be NULL",
20557 )
20558 })?;
20559 match handle.value() {
20560 Some(PioValue::AcOtsSolution(solution)) => Ok((handle, solution)),
20561 _ => Err(boundary_error(
20562 &codes::REQUEST_CAPI_TYPE_MISMATCH,
20563 "the calculation solution is not powerio.AcOtsSolution",
20564 )),
20565 }
20566}
20567
20568fn optional_f64(value: Option<f64>) -> (f64, bool) {
20570 (value.unwrap_or(0.0), value.is_some())
20571}
20572
20573fn ac_ots_branch_view(branch: &powerio_prob::AcOtsBranch) -> PioAcOtsBranchView {
20574 let (open_cost, close_cost) = branch
20575 .switching_cost
20576 .map_or((0.0, 0.0), |cost| (cost.open, cost.close));
20577 let (stated_from_pu, has_stated_from_pu) = optional_f64(branch.stated_current.from_pu);
20578 let (stated_to_pu, has_stated_to_pu) = optional_f64(branch.stated_current.to_pu);
20579 let (current_from_pu, has_current_from_pu) = optional_f64(branch.current.from_pu);
20580 let (current_to_pu, has_current_to_pu) = optional_f64(branch.current.to_pu);
20581 PioAcOtsBranchView {
20582 id: PioStringView::new(&branch.id),
20583 initial_closed: branch.initial_closed,
20584 switchable: branch.switchable,
20585 has_switching_cost: branch.switching_cost.is_some(),
20586 open_cost,
20587 close_cost,
20588 stated_from_pu,
20589 stated_to_pu,
20590 has_stated_from_pu,
20591 has_stated_to_pu,
20592 current_from_pu,
20593 current_to_pu,
20594 has_current_from_pu,
20595 has_current_to_pu,
20596 }
20597}
20598
20599#[unsafe(no_mangle)]
20604pub unsafe extern "C" fn pio_value_ac_ots_instance(
20605 value: *const PioValueHandle,
20606 error: *mut *mut PioError,
20607) -> *mut PioCalculationInstance {
20608 unsafe { instance_accessor(value, ExpectedValue::AcOtsInstance, error) }
20609}
20610
20611#[unsafe(no_mangle)]
20616pub unsafe extern "C" fn pio_value_ac_ots_solution(
20617 value: *const PioValueHandle,
20618 error: *mut *mut PioError,
20619) -> *mut PioCalculationSolution {
20620 unsafe { solution_accessor(value, ExpectedValue::AcOtsSolution, error) }
20621}
20622
20623#[unsafe(no_mangle)]
20631pub unsafe extern "C" fn pio_module_to_ac_ots_instance(
20632 module: *const PioModule,
20633 error: *mut *mut PioError,
20634) -> *mut PioModule {
20635 unsafe {
20636 transform_module(
20637 module,
20638 error,
20639 powerio::transform::to_ac_ots_instance,
20640 PioValue::AcOtsInstance,
20641 )
20642 }
20643}
20644
20645#[unsafe(no_mangle)]
20656pub unsafe extern "C" fn pio_module_to_ac_ots_instance_with_options(
20657 module: *const PioModule,
20658 options: *const PioAcOtsOptions,
20659 error: *mut *mut PioError,
20660) -> *mut PioModule {
20661 if options.is_null() {
20662 return unsafe { pio_module_to_ac_ots_instance(module, error) };
20665 }
20666 unsafe {
20667 entry(error, std::ptr::null_mut(), || {
20668 let module = PioModule::get(module).ok_or_else(|| {
20669 boundary_error(&codes::BIND_CAPI_NULL_HANDLE, "PioModule must not be NULL")
20670 })?;
20671 let options = ac_ots_options(options)?;
20672 powerio::transform::to_ac_ots_instance_with_options(&module.module, options)
20673 .map(|derived| module_handle(derived.map_value(PioValue::AcOtsInstance)))
20674 .map_err(|failure| error_from_core(&failure))
20675 })
20676 }
20677}
20678
20679#[unsafe(no_mangle)]
20686pub unsafe extern "C" fn pio_ac_ots_instance_create(
20687 base: *const PioCalculationInstance,
20688 options: *const PioAcOtsOptions,
20689 error: *mut *mut PioError,
20690) -> *mut PioModule {
20691 unsafe {
20692 entry(error, std::ptr::null_mut(), || {
20693 let handle = require_calculation_instance(base)?;
20694 let base = handle.ac_opf().ok_or_else(|| {
20695 boundary_error(
20696 &codes::REQUEST_CAPI_TYPE_MISMATCH,
20697 "the base calculation instance is not powerio.AcOpfInstance",
20698 )
20699 })?;
20700 let options = ac_ots_options(options)?;
20701 powerio::transform::ac_ots_instance_from_base(&handle.value.owner.module, base, options)
20702 .map(|derived| module_handle(derived.map_value(PioValue::AcOtsInstance)))
20703 .map_err(|failure| error_from_core(&failure))
20704 })
20705 }
20706}
20707
20708#[unsafe(no_mangle)]
20714pub unsafe extern "C" fn pio_ac_ots_instance_options(
20715 instance: *const PioCalculationInstance,
20716 output: *mut PioAcOtsOptionsView,
20717 error: *mut *mut PioError,
20718) -> bool {
20719 unsafe {
20720 entry(error, false, || {
20721 let (_, instance) = require_ac_ots_instance(instance)?;
20722 let options = instance.options();
20723 *require_output(output, "output")? = PioAcOtsOptionsView {
20724 switchable: PioStringView::new(options.switchable.kind_name()),
20725 islanding: PioStringView::new(options.islanding.name()),
20726 current_limits: PioStringView::new(options.current_limits.name()),
20727 branch_count: instance.branches().len(),
20728 max_open: options.max_open.unwrap_or(0),
20729 has_max_open: options.max_open.is_some(),
20730 max_switched: options.max_switched.unwrap_or(0),
20731 has_max_switched: options.max_switched.is_some(),
20732 };
20733 Ok(true)
20734 })
20735 }
20736}
20737
20738#[unsafe(no_mangle)]
20744pub unsafe extern "C" fn pio_ac_ots_instance_branch_at(
20745 instance_handle: *const PioCalculationInstance,
20746 index: usize,
20747 output: *mut PioAcOtsBranchView,
20748 error: *mut *mut PioError,
20749) -> bool {
20750 unsafe {
20751 entry(error, false, || {
20752 let (_, instance) = require_ac_ots_instance(instance_handle)?;
20753 let branch = instance.branches().get(index).ok_or_else(|| {
20754 boundary_error(
20755 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
20756 format!("branch index {index} is out of range"),
20757 )
20758 })?;
20759 *require_output(output, "output")? = ac_ots_branch_view(branch);
20760 Ok(true)
20761 })
20762 }
20763}
20764
20765#[unsafe(no_mangle)]
20773pub unsafe extern "C" fn pio_ac_ots_instance_validate_topology(
20774 instance: *const PioCalculationInstance,
20775 branch_closed: *const u8,
20776 branch_count: usize,
20777 switching_cost: *mut f64,
20778 error: *mut *mut PioError,
20779) -> bool {
20780 unsafe {
20781 entry(error, false, || {
20782 let (_, instance) = require_ac_ots_instance(instance)?;
20783 let closed = branch_statuses(branch_closed, branch_count)?;
20784 let output = require_output(switching_cost, "switching_cost")?;
20785 *output = instance
20786 .validate_topology(&closed)
20787 .map_err(|failure| error_from_core(&failure))?;
20788 Ok(true)
20789 })
20790 }
20791}
20792
20793#[unsafe(no_mangle)]
20800pub unsafe extern "C" fn pio_ac_ots_instance_fix_topology(
20801 instance: *const PioCalculationInstance,
20802 branch_closed: *const u8,
20803 branch_count: usize,
20804 error: *mut *mut PioError,
20805) -> *mut PioModule {
20806 unsafe {
20807 entry(error, std::ptr::null_mut(), || {
20808 let (handle, instance) = require_ac_ots_instance(instance)?;
20809 let closed = branch_statuses(branch_closed, branch_count)?;
20810 powerio::transform::fix_ac_ots_topology(&handle.value.owner.module, instance, &closed)
20811 .map(|derived| module_handle(derived.map_value(PioValue::AcOpfInstance)))
20812 .map_err(|failure| error_from_core(&failure))
20813 })
20814 }
20815}
20816
20817#[unsafe(no_mangle)]
20826pub unsafe extern "C" fn pio_ac_ots_solution_create(
20827 instance: *const PioCalculationInstance,
20828 branch_closed: *const u8,
20829 branch_count: usize,
20830 ac_solution: *const PioCalculationSolution,
20831 error: *mut *mut PioError,
20832) -> *mut PioModule {
20833 unsafe {
20834 entry(error, std::ptr::null_mut(), || {
20835 let (handle, instance) = require_ac_ots_instance(instance)?;
20836 let closed = branch_statuses(branch_closed, branch_count)?;
20837 let ac_solution = match PioCalculationSolution::get(ac_solution)
20838 .ok_or_else(|| {
20839 boundary_error(
20840 &codes::BIND_CAPI_NULL_HANDLE,
20841 "PioCalculationSolution must not be NULL",
20842 )
20843 })?
20844 .value()
20845 {
20846 Some(PioValue::AcOpfSolution(solution)) => solution.clone(),
20847 _ => {
20848 return Err(boundary_error(
20849 &codes::REQUEST_CAPI_TYPE_MISMATCH,
20850 "the AC solution is not powerio.AcOpfSolution",
20851 ));
20852 }
20853 };
20854 powerio::transform::ac_ots_solution(
20855 &handle.value.owner.module,
20856 instance,
20857 closed,
20858 ac_solution,
20859 )
20860 .map(|derived| module_handle(derived.map_value(PioValue::AcOtsSolution)))
20861 .map_err(|failure| error_from_core(&failure))
20862 })
20863 }
20864}
20865
20866#[unsafe(no_mangle)]
20871pub unsafe extern "C" fn pio_ac_ots_solution_summary(
20872 solution: *const PioCalculationSolution,
20873 output: *mut PioAcOtsSolutionView,
20874 error: *mut *mut PioError,
20875) -> bool {
20876 unsafe {
20877 entry(error, false, || {
20878 let (_, solution) = require_ac_ots_solution(solution)?;
20879 *require_output(output, "output")? = PioAcOtsSolutionView {
20880 branch_count: solution.branch_closed().len(),
20881 branches_open: solution.branches_open(),
20882 branches_switched: solution.branches_switched(),
20883 switching_cost: solution.switching_cost(),
20884 objective: solution.objective(),
20885 };
20886 Ok(true)
20887 })
20888 }
20889}
20890
20891#[unsafe(no_mangle)]
20896pub unsafe extern "C" fn pio_ac_ots_solution_branch_closed_at(
20897 solution: *const PioCalculationSolution,
20898 index: usize,
20899 output: *mut bool,
20900 error: *mut *mut PioError,
20901) -> bool {
20902 unsafe {
20903 entry(error, false, || {
20904 let (_, solution) = require_ac_ots_solution(solution)?;
20905 let closed = *solution.branch_closed().get(index).ok_or_else(|| {
20906 boundary_error(
20907 &codes::BIND_CAPI_INDEX_OUT_OF_RANGE,
20908 format!("branch index {index} is out of range"),
20909 )
20910 })?;
20911 *require_output(output, "output")? = closed;
20912 Ok(true)
20913 })
20914 }
20915}
20916
20917#[unsafe(no_mangle)]
20924pub unsafe extern "C" fn pio_ac_ots_solution_materialize(
20925 solution: *const PioCalculationSolution,
20926 error: *mut *mut PioError,
20927) -> *mut PioModule {
20928 unsafe {
20929 entry(error, std::ptr::null_mut(), || {
20930 let (handle, solution) = require_ac_ots_solution(solution)?;
20931 powerio::transform::materialize_ac_ots_solution(&handle.owner.module, solution)
20932 .map(|derived| module_handle(derived.map_value(PioValue::from)))
20933 .map_err(|failure| error_from_core(&failure))
20934 })
20935 }
20936}
20937
20938#[cfg(test)]
20939mod tests {
20940 #[test]
20941 fn dc_formula_names_include_the_additive_variants() {
20942 for name in [
20943 "series_susceptance",
20944 "tap_adjusted_reactance",
20945 "reactance_only",
20946 "tap_adjusted_series_susceptance",
20947 "series_susceptance_no_phase_shift",
20948 ] {
20949 let parsed = super::formula(Some(name)).expect("stable formula");
20950 assert_eq!(super::branch_susceptance_formula_name(parsed), name);
20951 }
20952 }
20953
20954 use super::*;
20955
20956 #[test]
20957 fn powermodels_construction_preserves_stated_frequency() {
20958 unsafe {
20959 let name = b"frequency.json";
20960 let format = b"powermodels-json";
20961 let text = br#"{"baseMVA":100,"base_frequency":50,"bus":{"1":{"bus_i":1,"bus_type":3,"base_kv":220}}}"#;
20962 let mut error = std::ptr::null_mut();
20963 let source = pio_source_from_memory(
20964 name.as_ptr().cast(),
20965 name.len(),
20966 text.as_ptr(),
20967 text.len(),
20968 &mut error,
20969 );
20970 assert!(!source.is_null(), "{}", error_text(error));
20971 let module = pio_parse(source, format.as_ptr().cast(), format.len(), &mut error);
20972 pio_source_release(source);
20973 assert!(!module.is_null(), "{}", error_text(error));
20974 let value = pio_module_value(module);
20975 let network = pio_value_balanced_network(value, &mut error);
20976 assert!(!network.is_null(), "{}", error_text(error));
20977 assert_eq!(pio_balanced_network_base_frequency_hz(network), 50.0);
20978 pio_balanced_network_release(network);
20979 pio_value_release(value);
20980 pio_module_release(module);
20981 }
20982 }
20983
20984 unsafe fn view_text(view: PioStringView) -> String {
20985 if view.data.is_null() {
20986 return String::new();
20987 }
20988 String::from_utf8_lossy(unsafe {
20989 std::slice::from_raw_parts(view.data.cast::<u8>(), view.len)
20990 })
20991 .into_owned()
20992 }
20993
20994 unsafe fn parse_case9() -> *mut PioModule {
20995 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../tests/data/case9.m");
20996 let path = path.to_string_lossy();
20997 let mut error = std::ptr::null_mut();
20998 let source = unsafe { pio_source_open(path.as_ptr().cast(), path.len(), &mut error) };
20999 assert!(!source.is_null(), "{}", unsafe { error_text(error) });
21000 let module = unsafe { pio_parse(source, std::ptr::null(), 0, &mut error) };
21001 unsafe { pio_source_release(source) };
21002 assert!(!module.is_null(), "{}", unsafe { error_text(error) });
21003 module
21004 }
21005
21006 fn parse_xiidm_text(text: &str) -> *mut PioModule {
21007 unsafe {
21008 let name = b"case.xiidm";
21009 let format = b"xiidm";
21010 let mut error = std::ptr::null_mut();
21011 let source = pio_source_from_memory(
21012 name.as_ptr().cast(),
21013 name.len(),
21014 text.as_ptr(),
21015 text.len(),
21016 &mut error,
21017 );
21018 assert!(!source.is_null(), "{}", error_text(error));
21019 let module = pio_parse(source, format.as_ptr().cast(), format.len(), &mut error);
21020 pio_source_release(source);
21021 assert!(!module.is_null(), "{}", error_text(error));
21022 module
21023 }
21024 }
21025
21026 unsafe fn parse_bmopf() -> *mut PioModule {
21027 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
21028 .join("../tests/data/dist/bmopf/example_ieee13.json");
21029 let path = path.to_string_lossy();
21030 let mut error = std::ptr::null_mut();
21031 let source = unsafe { pio_source_open(path.as_ptr().cast(), path.len(), &mut error) };
21032 assert!(!source.is_null(), "{}", unsafe { error_text(error) });
21033 let module = unsafe { pio_parse(source, std::ptr::null(), 0, &mut error) };
21034 unsafe { pio_source_release(source) };
21035 assert!(!module.is_null(), "{}", unsafe { error_text(error) });
21036 module
21037 }
21038
21039 unsafe fn error_text(error: *const PioError) -> String {
21040 let view = unsafe { pio_error_message(error) };
21041 if view.data.is_null() {
21042 return "missing PioError".to_owned();
21043 }
21044 String::from_utf8_lossy(unsafe {
21045 std::slice::from_raw_parts(view.data.cast::<u8>(), view.len)
21046 })
21047 .into_owned()
21048 }
21049
21050 unsafe fn case9_network() -> BalancedNetwork {
21051 let module = unsafe { parse_case9() };
21052 let network = match &unsafe { PioModule::get(module) }.unwrap().module.value() {
21053 PioValue::BalancedNetwork(network) => network.clone(),
21054 value => panic!("expected balanced network, got {}", value.type_name()),
21055 };
21056 unsafe { pio_module_release(module) };
21057 network
21058 }
21059
21060 fn module_with_complete_records() -> *mut PioModule {
21061 use std::collections::BTreeMap;
21062
21063 let mut module = powerio::PioModule::new(PioValue::BalancedNetwork(BalancedNetwork::new(
21064 "metadata", 100.0,
21065 )))
21066 .with_producer(Producer::new("record-test", "1.2.3").unwrap());
21067 let source_id = powerio_core::SourceId::new("source-1").unwrap();
21068 let source =
21069 powerio_core::SourceDescriptor::new(source_id.clone(), "record-test.xiidm", 128)
21070 .unwrap()
21071 .with_format(powerio_core::FormatId::new("xiidm").unwrap())
21072 .with_digest(
21073 powerio_core::Digest::sha256(
21074 "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
21075 )
21076 .unwrap(),
21077 );
21078 module.add_source_descriptor(source).unwrap();
21079 module
21080 .add_source_map_entry(
21081 powerio_core::SourceMapEntry::new(
21082 "/value/buses/0",
21083 powerio_core::SourceRelation::Exact,
21084 vec![powerio_core::SourceSpan::new(source_id, 4, 12).unwrap()],
21085 )
21086 .unwrap(),
21087 )
21088 .unwrap();
21089 let parameters = BTreeMap::from([(
21090 "settings".to_owned(),
21091 serde_json::json!({
21092 "items": [null, true, "named", 18446744073709551615u64, 1.25]
21093 }),
21094 )]);
21095 let history = HistoryEntry::new(
21096 HistoryId::new("history-1").unwrap(),
21097 HistoryKind::Transform,
21098 "normalize",
21099 )
21100 .unwrap()
21101 .with_input_type("powerio.BalancedNetwork")
21102 .unwrap()
21103 .with_output_type("powerio.BalancedNetwork")
21104 .unwrap()
21105 .with_parameters(parameters)
21106 .unwrap()
21107 .with_assumption("base power is known")
21108 .unwrap()
21109 .with_loss("source token spelling")
21110 .unwrap();
21111 module.add_history_entry(history).unwrap();
21112 module
21113 .insert_extension("org.example.record", serde_json::json!({"enabled": true}))
21114 .unwrap();
21115 module_handle(module)
21116 }
21117
21118 fn multiconductor_network() -> powerio_dist::MulticonductorNetwork {
21119 let mut network = powerio_dist::MulticonductorNetwork::named("capi-solution-instance");
21120 network.buses_mut().push(powerio_dist::DistBus::new(
21121 "source",
21122 vec!["1".into(), "2".into(), "3".into()],
21123 ));
21124 network.sources_mut().push(powerio_dist::VoltageSource::new(
21125 "source",
21126 "source",
21127 vec!["1".into(), "2".into(), "3".into()],
21128 vec![240.0, 240.0, 240.0],
21129 vec![0.0, -2.094, 2.094],
21130 ));
21131 network
21132 }
21133
21134 fn complete_multiconductor_network() -> powerio_dist::MulticonductorNetwork {
21135 let mut network = powerio_dist::MulticonductorNetwork::named("");
21136 *network.source_format_mut() = Some(powerio_dist::DistSourceFormat::Dss);
21137 *network.geo_mut() = Some(powerio_dist::DistGeoMeta {
21138 space: powerio_dist::CoordinateSpace::Diagram {
21139 canvas: Some(powerio_dist::DistCanvas {
21140 width: Some(640.0),
21141 height: None,
21142 units: Some(String::new()),
21143 }),
21144 },
21145 kind: Some(powerio_dist::DistCoordsKind::Manual),
21146 });
21147
21148 let mut bus = powerio_dist::DistBus::new("bus", vec!["1".into(), "2".into()]);
21149 bus.grounded.push("2".into());
21150 bus.v_min = Some(0.0);
21151 bus.vpn_min = Some(Vec::new());
21152 bus.vpp_max = Some(vec![240.0, 240.0]);
21153 bus.location = Some(powerio_dist::DistLocation {
21154 x: 10.0,
21155 y: 20.0,
21156 kind: None,
21157 });
21158 network.buses_mut().push(bus);
21159
21160 let mut line_code = powerio_dist::DistLineCode::new(
21161 "code",
21162 vec![vec![1.0, 2.0], vec![3.0]],
21163 vec![vec![4.0]],
21164 );
21165 line_code.g_from = vec![vec![5.0]];
21166 line_code.b_from = vec![vec![6.0]];
21167 line_code.g_to = vec![vec![7.0]];
21168 line_code.b_to = vec![vec![8.0]];
21169 line_code.i_max = Some(Vec::new());
21170 line_code.s_max = Some(vec![900.0]);
21171 line_code.source = Some(String::new());
21172 network.line_codes_mut().push(line_code);
21173
21174 let mut line = powerio_dist::DistLine::new(
21175 "line",
21176 "bus",
21177 "bus",
21178 vec!["1".into()],
21179 vec!["2".into()],
21180 "code",
21181 12.0,
21182 );
21183 line.route = Some(Vec::new());
21184 line.i_max = Some(vec![10.0]);
21185 network.lines_mut().push(line);
21186
21187 let mut switch = powerio_dist::DistSwitch::new(
21188 "switch",
21189 "bus",
21190 "bus",
21191 vec!["1".into()],
21192 vec!["2".into()],
21193 true,
21194 );
21195 switch.i_max = Some(Vec::new());
21196 network.switches_mut().push(switch);
21197
21198 let mut winding = powerio_dist::DistWinding::new(
21199 "bus",
21200 vec!["1".into(), "2".into()],
21201 powerio_dist::DistWindingConn::Wye,
21202 240.0,
21203 1_000.0,
21204 );
21205 winding.r_pct = 0.5;
21206 winding.r_neutral = Some(0.0);
21207 network
21208 .transformers_mut()
21209 .push(powerio_dist::DistTransformer::new(
21210 "transformer",
21211 vec![winding],
21212 vec![2.5],
21213 1,
21214 ));
21215
21216 let mut load = powerio_dist::DistLoad::new(
21217 "load",
21218 "bus",
21219 vec!["1".into()],
21220 powerio_dist::Configuration::Wye,
21221 vec![100.0],
21222 vec![20.0],
21223 );
21224 load.voltage_model = powerio_dist::DistLoadVoltageModel::Zip {
21225 v_nom: vec![240.0],
21226 alpha_z: vec![0.1],
21227 alpha_i: vec![0.2],
21228 alpha_p: vec![0.7],
21229 beta_z: vec![0.2],
21230 beta_i: vec![0.3],
21231 beta_p: vec![0.5],
21232 };
21233 network.loads_mut().push(load);
21234
21235 let mut generator = powerio_dist::DistGenerator::new(
21236 "generator",
21237 "bus",
21238 vec!["1".into()],
21239 powerio_dist::Configuration::SinglePhase,
21240 vec![50.0],
21241 vec![5.0],
21242 );
21243 generator.p_min = Some(Vec::new());
21244 generator.cost = Some(vec![0.25]);
21245 network.generators_mut().push(generator);
21246
21247 let mut resource = powerio_dist::DistIbr::new(
21248 "ibr",
21249 "bus",
21250 vec!["1".into()],
21251 powerio_dist::IbrTopology::SinglePhase,
21252 powerio_dist::IbrPrimeMover::Pv,
21253 vec![100.0],
21254 );
21255 resource.i_max = Some(Vec::new());
21256 resource.p_avail = Some(75.0);
21257 resource.control_profile = Some(String::new());
21258 resource.voltage_aggregation = Some(powerio_dist::IbrVoltageAggregation::PerPhase);
21259 network.ibrs_mut().push(resource);
21260
21261 let profile: powerio_dist::DistControlProfile = serde_json::from_value(serde_json::json!({
21262 "name": "profile",
21263 "power_factor": { "pf": 0.97 },
21264 "volt_var": {
21265 "voltage_reference": "PN_PER_PHASE",
21266 "breakpoints": [0.95, 1.05],
21267 "q_limits": [-0.4, 0.4],
21268 "q_unit": "VA_FRACTION",
21269 "q_ref": "VAR_MAX",
21270 "p_min_for_q": 10.0,
21271 "p_min_for_q_max": null
21272 },
21273 "volt_watt": {
21274 "voltage_reference": null,
21275 "breakpoints": [1.0],
21276 "p_limits": [0.8],
21277 "p_unit": "W",
21278 "p_ref": "P_AVAILABLE"
21279 },
21280 "extras": {}
21281 }))
21282 .unwrap();
21283 network.control_profiles_mut().push(profile);
21284
21285 network.shunts_mut().push(powerio_dist::DistShunt::new(
21286 "shunt",
21287 "bus",
21288 vec!["2".into()],
21289 vec![vec![0.01, 0.02], vec![0.03]],
21290 vec![vec![0.04]],
21291 ));
21292 network
21293 .capacitors_mut()
21294 .push(powerio_dist::DistCapacitor::new(
21295 "capacitor",
21296 "bus",
21297 vec!["1".into()],
21298 powerio_dist::Configuration::SinglePhase,
21299 100.0,
21300 240.0,
21301 ));
21302 network.sources_mut().push(powerio_dist::VoltageSource::new(
21303 "source",
21304 "bus",
21305 vec!["1".into()],
21306 vec![240.0],
21307 vec![0.0],
21308 ));
21309 network.sources_mut()[0].energy_cost_rate = Some(vec![0.125]);
21310 network
21311 .untyped_objects_mut()
21312 .push(powerio_dist::UntypedObject::new(
21313 "curve",
21314 "raw",
21315 vec![
21316 (None, "first".into()),
21317 (Some(String::new()), "second".into()),
21318 ],
21319 ));
21320 network
21321 .commands_mut()
21322 .push(("solve".into(), "mode=daily".into()));
21323 network
21324 .options_mut()
21325 .push(("frequency".into(), "60".into()));
21326 network
21327 }
21328
21329 fn goc3_instance(source: Source) -> powerio_prob::AcScucInstance {
21330 let module = powerio::parse_with_options(
21331 source,
21332 &powerio::ParseOptions::default()
21333 .format("goc3-json")
21334 .unwrap(),
21335 )
21336 .unwrap();
21337 let PioValue::AcScucInstance(instance) = module.into_value() else {
21338 panic!("GO Challenge 3 problem did not produce powerio.AcScucInstance");
21339 };
21340 instance
21341 }
21342
21343 #[test]
21344 fn header_version_is_the_crate_version() {
21345 let numbers = [
21346 env!("CARGO_PKG_VERSION_MAJOR"),
21347 env!("CARGO_PKG_VERSION_MINOR"),
21348 env!("CARGO_PKG_VERSION_PATCH"),
21349 ]
21350 .map(|number| number.parse::<u32>().unwrap());
21351 assert_eq!(
21352 [PIO_VERSION_MAJOR, PIO_VERSION_MINOR, PIO_VERSION_PATCH],
21353 numbers,
21354 "update PIO_VERSION_* with the workspace version and regenerate powerio.h"
21355 );
21356 let version = pio_version_numbers();
21357 assert_eq!([version.major, version.minor, version.patch], numbers);
21358 let text = unsafe { view_text(pio_version()) };
21361 assert_eq!(text, powerio::VERSION);
21362 assert_eq!(
21363 text.split_once('-').map_or(text.as_str(), |(core, _)| core),
21364 format!("{}.{}.{}", version.major, version.minor, version.patch)
21365 );
21366 }
21367
21368 #[test]
21369 fn reports_schema_versions() {
21370 unsafe {
21371 let mut error = std::ptr::null_mut();
21372 let report = pio_schema_report(&mut error);
21373 assert!(!report.is_null(), "{}", error_text(error));
21374 let parsed: serde_json::Value =
21375 serde_json::from_str(&view_text(pio_string_view(report))).unwrap();
21376 assert!(parsed.get("abi").is_none());
21377 assert_eq!(parsed["powerio_version"], powerio::VERSION);
21378 assert_eq!(parsed["powerio_ir"]["schema"], powerio::IR_SCHEMA_NAME);
21379 assert_eq!(parsed["powerio_ir"]["version"], powerio::IR_VERSION);
21380 assert_eq!(
21381 parsed["bmopf_schema"],
21382 serde_json::json!(powerio_dist::BMOPF_SCHEMA_ID)
21383 );
21384 assert_eq!(parsed["foreign_schemas"]["bmopf"], parsed["bmopf_schema"]);
21385 assert_eq!(
21386 parsed["error_categories"],
21387 serde_json::json!(powerio_core::ErrorCategory::TOKENS)
21388 );
21389 assert_eq!(
21390 parsed["diagnostic_namespaces"],
21391 serde_json::json!(powerio_core::DiagnosticStage::NAMESPACES)
21392 );
21393 assert_eq!(
21394 parsed["json_classes"],
21395 serde_json::json!(powerio::JSON_CLASSES)
21396 );
21397 for feature in ["matrix", "gridfm", "dist", "prob"] {
21398 assert!(parsed["features"][feature].is_boolean());
21399 }
21400 pio_string_release(report);
21401 }
21402 }
21403
21404 #[test]
21405 fn structured_diagnostic_fields_keep_their_owner_alive() {
21406 unsafe {
21407 let source = powerio_core::SourceId::new("input").unwrap();
21408 let span = powerio_core::SourceSpan::new(source, 2, 7).unwrap();
21409 let mut details = serde_json::Map::new();
21410 details.insert("count".to_owned(), serde_json::json!(3));
21411 details.insert("nested".to_owned(), serde_json::json!({ "ok": true }));
21412 let diagnostic = Diagnostic::new(
21413 powerio_core::DiagnosticCode::new("PARTNER.TEST.STRUCTURED").unwrap(),
21414 powerio_core::DiagnosticSeverity::Warning,
21415 "structured finding",
21416 )
21417 .with_id(powerio_core::DiagnosticId::new("d1").unwrap())
21418 .with_target("/value/data")
21419 .unwrap()
21420 .with_span(span)
21421 .unwrap()
21422 .with_related(powerio_core::DiagnosticId::new("d0").unwrap())
21423 .unwrap()
21424 .with_details(details)
21425 .unwrap()
21426 .with_suggested_action("fix it");
21427 let diagnostics = PioDiagnostics::new_raw(DiagnosticsInner {
21428 owner: DiagnosticsOwner::Owned(vec![diagnostic]),
21429 });
21430 let retained = pio_diagnostics_retain(diagnostics);
21431 pio_diagnostics_release(diagnostics);
21432
21433 assert_eq!(pio_diagnostics_len(retained), 1);
21434 assert_eq!(
21435 view_text(pio_diagnostic_code(retained, 0)),
21436 "PARTNER.TEST.STRUCTURED"
21437 );
21438 assert_eq!(view_text(pio_diagnostic_severity(retained, 0)), "warning");
21439 assert_eq!(
21440 view_text(pio_diagnostic_message(retained, 0)),
21441 "structured finding"
21442 );
21443 assert!(pio_diagnostic_has_id(retained, 0));
21444 assert_eq!(view_text(pio_diagnostic_id(retained, 0)), "d1");
21445 assert!(pio_diagnostic_has_target(retained, 0));
21446 assert_eq!(view_text(pio_diagnostic_target(retained, 0)), "/value/data");
21447 assert!(pio_diagnostic_has_suggested_action(retained, 0));
21448 assert_eq!(
21449 view_text(pio_diagnostic_suggested_action(retained, 0)),
21450 "fix it"
21451 );
21452
21453 assert_eq!(pio_diagnostic_n_spans(retained, 0), 1);
21454 let mut output = PioDiagnosticSpanView {
21455 source: PioStringView::EMPTY,
21456 byte_start: 0,
21457 byte_end: 0,
21458 };
21459 let mut error = std::ptr::null_mut();
21460 assert!(pio_diagnostic_span(retained, 0, 0, &mut output, &mut error));
21461 assert!(error.is_null());
21462 assert_eq!(view_text(output.source), "input");
21463 assert_eq!(output.byte_start, 2);
21464 assert_eq!(output.byte_end, 7);
21465
21466 assert_eq!(pio_diagnostic_n_related(retained, 0), 1);
21467 assert_eq!(view_text(pio_diagnostic_related(retained, 0, 0)), "d0");
21468
21469 let details_text = pio_diagnostic_details_json(retained, 0, &mut error);
21470 assert!(!details_text.is_null(), "{}", error_text(error));
21471 let details: serde_json::Value =
21472 serde_json::from_str(&view_text(pio_string_view(details_text))).unwrap();
21473 assert_eq!(details["count"], 3);
21474 assert_eq!(details["nested"]["ok"], true);
21475 pio_string_release(details_text);
21476
21477 pio_diagnostics_release(retained);
21478 }
21479 }
21480
21481 #[test]
21482 fn module_records_are_typed_and_structured_values_keep_the_owner_alive() {
21483 unsafe {
21484 let module = module_with_complete_records();
21485 let mut error = std::ptr::null_mut();
21486
21487 let mut producer = std::mem::MaybeUninit::<PioModuleProducerView>::uninit();
21488 assert!(pio_module_producer(
21489 module,
21490 producer.as_mut_ptr(),
21491 &mut error
21492 ));
21493 let producer = producer.assume_init();
21494 assert_eq!(view_text(producer.name), "record-test");
21495 assert_eq!(view_text(producer.version), "1.2.3");
21496
21497 assert_eq!(pio_module_source_count(module), 1);
21498 let mut source = std::mem::MaybeUninit::<PioModuleSourceView>::uninit();
21499 assert!(pio_module_source_at(
21500 module,
21501 0,
21502 source.as_mut_ptr(),
21503 &mut error
21504 ));
21505 let source = source.assume_init();
21506 assert_eq!(view_text(source.id), "source-1");
21507 assert_eq!(view_text(source.name), "record-test.xiidm");
21508 assert_eq!(source.byte_length, 128);
21509 assert!(source.has_format);
21510 assert_eq!(view_text(source.format), "xiidm");
21511 assert!(source.has_digest);
21512 assert_eq!(view_text(source.digest_algorithm), "sha256");
21513 assert_eq!(source.digest.len, 64);
21514
21515 assert_eq!(pio_module_source_map_count(module), 1);
21516 let mut mapping = std::mem::MaybeUninit::<PioModuleSourceMapEntryView>::uninit();
21517 assert!(pio_module_source_map_at(
21518 module,
21519 0,
21520 mapping.as_mut_ptr(),
21521 &mut error
21522 ));
21523 let mapping = mapping.assume_init();
21524 assert_eq!(view_text(mapping.target), "/value/buses/0");
21525 assert_eq!(view_text(mapping.relation), "exact");
21526 assert_eq!(mapping.span_count, 1);
21527 let mut span = std::mem::MaybeUninit::<PioSourceSpanView>::uninit();
21528 assert!(pio_module_source_map_span_at(
21529 module,
21530 0,
21531 0,
21532 span.as_mut_ptr(),
21533 &mut error
21534 ));
21535 let span = span.assume_init();
21536 assert_eq!(view_text(span.source), "source-1");
21537 assert_eq!((span.byte_start, span.byte_end), (4, 12));
21538
21539 assert_eq!(pio_module_history_count(module), 1);
21540 let mut history = std::mem::MaybeUninit::<PioModuleHistoryEntryView>::uninit();
21541 assert!(pio_module_history_at(
21542 module,
21543 0,
21544 history.as_mut_ptr(),
21545 &mut error
21546 ));
21547 let history = history.assume_init();
21548 assert_eq!(view_text(history.id), "history-1");
21549 assert_eq!(view_text(history.kind), "transform");
21550 assert_eq!(view_text(history.name), "normalize");
21551 assert!(history.has_input_type);
21552 assert_eq!(view_text(history.input_type), "powerio.BalancedNetwork");
21553 assert!(history.has_output_type);
21554 assert_eq!(view_text(history.output_type), "powerio.BalancedNetwork");
21555 assert_eq!(history.parameter_count, 1);
21556 assert_eq!(history.assumption_count, 1);
21557 assert_eq!(history.loss_count, 1);
21558 assert_eq!(
21559 view_text(pio_module_history_assumption_at(module, 0, 0, &mut error)),
21560 "base power is known"
21561 );
21562 assert_eq!(
21563 view_text(pio_module_history_loss_at(module, 0, 0, &mut error)),
21564 "source token spelling"
21565 );
21566 let mut parameter = std::mem::MaybeUninit::<PioModuleHistoryParameterView>::uninit();
21567 assert!(pio_module_history_parameter_at(
21568 module,
21569 0,
21570 0,
21571 parameter.as_mut_ptr(),
21572 &mut error
21573 ));
21574 let parameter = parameter.assume_init();
21575 assert_eq!(view_text(parameter.name), "settings");
21576 assert_eq!(view_text(parameter.value_kind), "object");
21577
21578 assert_eq!(pio_module_extension_count(module), 1);
21579 let mut extension = std::mem::MaybeUninit::<PioModuleExtensionView>::uninit();
21580 assert!(pio_module_extension_at(
21581 module,
21582 0,
21583 extension.as_mut_ptr(),
21584 &mut error
21585 ));
21586 let extension = extension.assume_init();
21587 assert_eq!(view_text(extension.namespace), "org.example.record");
21588 assert_eq!(view_text(extension.value_kind), "object");
21589
21590 let parameter_value = pio_module_history_parameter_value_at(module, 0, 0, &mut error);
21591 assert!(!parameter_value.is_null(), "{}", error_text(error));
21592 let items = pio_json_value_object_value_at(parameter_value, 0, &mut error);
21593 assert!(!items.is_null(), "{}", error_text(error));
21594 let unsigned = pio_json_value_array_at(items, 3, &mut error);
21595 assert!(!unsigned.is_null(), "{}", error_text(error));
21596 let retained_unsigned = pio_json_value_retain(unsigned);
21597 let extension_value = pio_module_extension_value_at(module, 0, &mut error);
21598 assert!(!extension_value.is_null(), "{}", error_text(error));
21599
21600 let mut ignored = std::mem::MaybeUninit::<PioModuleSourceView>::uninit();
21601 assert!(!pio_module_source_at(
21602 module,
21603 1,
21604 ignored.as_mut_ptr(),
21605 &mut error
21606 ));
21607 assert!(!error.is_null());
21608 pio_error_release(error);
21609 error = std::ptr::null_mut();
21610
21611 pio_module_release(module);
21612 pio_json_value_release(parameter_value);
21613 pio_json_value_release(items);
21614 pio_json_value_release(unsigned);
21615
21616 let mut number = std::mem::MaybeUninit::<PioJsonValueView>::uninit();
21617 assert!(pio_json_value_get(
21618 retained_unsigned,
21619 number.as_mut_ptr(),
21620 &mut error
21621 ));
21622 let number = number.assume_init();
21623 assert_eq!(view_text(number.kind), "number");
21624 assert_eq!(view_text(number.number_kind), "unsigned_integer");
21625 assert_eq!(number.unsigned_integer_value, u64::MAX);
21626
21627 let enabled = pio_json_value_object_value_at(extension_value, 0, &mut error);
21628 assert!(!enabled.is_null(), "{}", error_text(error));
21629 let mut boolean = std::mem::MaybeUninit::<PioJsonValueView>::uninit();
21630 assert!(pio_json_value_get(
21631 enabled,
21632 boolean.as_mut_ptr(),
21633 &mut error
21634 ));
21635 let boolean = boolean.assume_init();
21636 assert_eq!(view_text(boolean.kind), "boolean");
21637 assert!(boolean.boolean_value);
21638
21639 let mut null_output = std::mem::MaybeUninit::<PioModuleProducerView>::uninit();
21640 assert!(!pio_module_producer(
21641 std::ptr::null(),
21642 null_output.as_mut_ptr(),
21643 &mut error
21644 ));
21645 assert!(!error.is_null());
21646 pio_error_release(error);
21647 pio_json_value_release(enabled);
21648 pio_json_value_release(extension_value);
21649 pio_json_value_release(retained_unsigned);
21650 }
21651 }
21652
21653 #[test]
21654 fn structural_access_keeps_the_module_owner_alive() {
21655 unsafe {
21656 let module = parse_case9();
21657 let diagnostics = pio_module_diagnostics(module);
21658 let value = pio_module_value(module);
21659 assert!(pio_value_is_type(
21660 value,
21661 c"powerio.BalancedNetwork".as_ptr(),
21662 "powerio.BalancedNetwork".len(),
21663 ));
21664 let mut error = std::ptr::null_mut();
21665 let network = pio_value_balanced_network(value, &mut error);
21666 assert!(!network.is_null(), "{}", error_text(error));
21667
21668 pio_module_release(module);
21669 pio_value_release(value);
21670 assert_eq!(pio_balanced_network_bus_count(network), 9);
21671 assert_eq!(pio_balanced_network_branch_count(network), 9);
21672 assert_eq!(pio_diagnostics_len(diagnostics), 0);
21673
21674 pio_balanced_network_release(network);
21675 pio_diagnostics_release(diagnostics);
21676 }
21677 }
21678
21679 #[test]
21680 fn abi_seven_bus_views_preserve_phase_bounds_after_owner_release() {
21681 unsafe {
21682 let mut network = complete_multiconductor_network();
21683 network.buses_mut()[0].v_min = None;
21684 network.buses_mut()[0].v_min_phase = Some(vec![210.0, 215.0]);
21685 let module = module_handle(powerio::PioModule::new(PioValue::from(network)));
21686 let value = pio_module_value(module);
21687 let mut error = std::ptr::null_mut();
21688 let network = pio_value_multiconductor_network(value, &mut error);
21689 assert!(!network.is_null());
21690 let mut bus = std::mem::MaybeUninit::<PioMulticonductorBusView>::uninit();
21691 pio_module_release(module);
21692 pio_value_release(value);
21693 assert!(pio_multiconductor_network_bus_at(
21694 network,
21695 0,
21696 bus.as_mut_ptr(),
21697 &mut error
21698 ));
21699 let bus = bus.assume_init();
21700 assert!(bus.has_phase_to_ground_voltage_min);
21701 assert!(!bus.has_voltage_min);
21702 assert_eq!(
21703 std::slice::from_raw_parts(
21704 bus.phase_to_ground_voltage_min_v.data,
21705 bus.phase_to_ground_voltage_min_v.len
21706 ),
21707 &[210.0, 215.0]
21708 );
21709 pio_multiconductor_network_release(network);
21710 }
21711 }
21712
21713 #[test]
21714 fn distribution_cim_parses_by_its_token() {
21715 unsafe {
21716 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
21717 .join("../tests/data/dist/cim/micro_feeder.xml");
21718 let path = path.to_string_lossy();
21719 let format = b"cim-dist";
21720 let mut error = std::ptr::null_mut();
21721 let source = pio_source_open(path.as_ptr().cast(), path.len(), &mut error);
21722 assert!(!source.is_null(), "{}", error_text(error));
21723 let module = pio_parse(source, format.as_ptr().cast(), format.len(), &mut error);
21724 pio_source_release(source);
21725 assert!(!module.is_null(), "{}", error_text(error));
21726 let value = pio_module_value(module);
21727 let network = pio_value_multiconductor_network(value, &mut error);
21728 assert!(!network.is_null(), "{}", error_text(error));
21729 assert!(pio_multiconductor_network_has_source_format(network));
21730 assert_eq!(
21731 view_text(pio_multiconductor_network_source_format(network)),
21732 "cim-dist"
21733 );
21734 pio_multiconductor_network_release(network);
21735 pio_value_release(value);
21736 pio_module_release(module);
21737 }
21738 }
21739
21740 #[test]
21741 fn distribution_cim_reads_the_transformer_tank_form() {
21742 unsafe {
21743 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
21744 .join("../tests/data/dist/cim/tank_feeder.xml");
21745 let path = path.to_string_lossy();
21746 let format = b"cim-dist";
21747 let mut error = std::ptr::null_mut();
21748 let source = pio_source_open(path.as_ptr().cast(), path.len(), &mut error);
21749 assert!(!source.is_null(), "{}", error_text(error));
21750 let module = pio_parse(source, format.as_ptr().cast(), format.len(), &mut error);
21751 pio_source_release(source);
21752 assert!(!module.is_null(), "{}", error_text(error));
21753 let value = pio_module_value(module);
21754 let network = pio_value_multiconductor_network(value, &mut error);
21755 assert!(!network.is_null(), "{}", error_text(error));
21756 let mut counts = std::mem::MaybeUninit::<PioMulticonductorNetworkCountsView>::uninit();
21757 assert!(pio_multiconductor_network_counts(
21758 network,
21759 counts.as_mut_ptr(),
21760 &mut error,
21761 ));
21762 assert_eq!(counts.assume_init().transformers, 9);
21764 pio_multiconductor_network_release(network);
21765 pio_value_release(value);
21766 pio_module_release(module);
21767 }
21768 }
21769
21770 #[test]
21771 #[allow(clippy::too_many_lines)]
21772 fn multiconductor_typed_views_preserve_ownership_and_optional_values() {
21773 unsafe {
21774 let module = module_handle(powerio::PioModule::new(PioValue::from(
21775 complete_multiconductor_network(),
21776 )));
21777 let value = pio_module_value(module);
21778 let mut error = std::ptr::null_mut();
21779 let network = pio_value_multiconductor_network(value, &mut error);
21780 assert!(!network.is_null(), "{}", error_text(error));
21781 let retained = pio_multiconductor_network_retain(network);
21782 pio_module_release(module);
21783 pio_value_release(value);
21784 pio_multiconductor_network_release(network);
21785
21786 assert!(pio_multiconductor_network_has_name(retained));
21787 assert_eq!(pio_multiconductor_network_name(retained).len, 0);
21788 assert!(pio_multiconductor_network_has_source_format(retained));
21789 assert_eq!(
21790 view_text(pio_multiconductor_network_source_format(retained)),
21791 "dss"
21792 );
21793
21794 let mut geo = std::mem::MaybeUninit::<PioMulticonductorGeoView>::uninit();
21795 assert!(pio_multiconductor_network_geo(
21796 retained,
21797 geo.as_mut_ptr(),
21798 &mut error,
21799 ));
21800 let geo = geo.assume_init();
21801 assert!(geo.has_geo);
21802 assert_eq!(view_text(geo.space), "diagram");
21803 assert!(geo.has_canvas);
21804 assert!(geo.has_canvas_width);
21805 assert!(!geo.has_canvas_height);
21806 assert!(geo.has_canvas_units);
21807 assert_eq!(geo.canvas_units.len, 0);
21808
21809 let mut counts = std::mem::MaybeUninit::<PioMulticonductorNetworkCountsView>::uninit();
21810 assert!(pio_multiconductor_network_counts(
21811 retained,
21812 counts.as_mut_ptr(),
21813 &mut error,
21814 ));
21815 let counts = counts.assume_init();
21816 for count in [
21817 counts.buses,
21818 counts.line_codes,
21819 counts.lines,
21820 counts.switches,
21821 counts.transformers,
21822 counts.loads,
21823 counts.generators,
21824 counts.inverter_based_resources,
21825 counts.control_profiles,
21826 counts.shunts,
21827 counts.capacitors,
21828 counts.voltage_sources,
21829 counts.untyped_objects,
21830 counts.commands,
21831 counts.options,
21832 ] {
21833 assert_eq!(count, 1);
21834 }
21835
21836 let mut bus = std::mem::MaybeUninit::<PioMulticonductorBusView>::uninit();
21837 assert!(pio_multiconductor_network_bus_at(
21838 retained,
21839 0,
21840 bus.as_mut_ptr(),
21841 &mut error,
21842 ));
21843 let bus = bus.assume_init();
21844 assert_eq!(view_text(bus.id), "bus");
21845 assert!(bus.has_phase_to_neutral_voltage_min);
21846 assert_eq!(bus.phase_to_neutral_voltage_min_v.len, 0);
21847 assert!(bus.has_location);
21848 assert!(!bus.location.has_kind);
21849 let mut text = std::mem::MaybeUninit::<PioStringView>::uninit();
21850 assert!(pio_multiconductor_network_bus_terminal_at(
21851 retained,
21852 0,
21853 1,
21854 text.as_mut_ptr(),
21855 &mut error,
21856 ));
21857 assert_eq!(view_text(text.assume_init()), "2");
21858
21859 let mut line_code = std::mem::MaybeUninit::<PioMulticonductorLineCodeView>::uninit();
21860 assert!(pio_multiconductor_network_line_code_at(
21861 retained,
21862 0,
21863 line_code.as_mut_ptr(),
21864 &mut error,
21865 ));
21866 let line_code = line_code.assume_init();
21867 assert_eq!(line_code.resistance_matrix_row_count, 2);
21868 assert!(line_code.has_current_limit);
21869 assert_eq!(line_code.current_limit_a.len, 0);
21870 assert!(line_code.has_source);
21871 assert_eq!(line_code.source.len, 0);
21872 let mut matrix_row = std::mem::MaybeUninit::<PioF64View>::uninit();
21873 assert!(
21874 pio_multiconductor_network_line_code_resistance_matrix_row_at(
21875 retained,
21876 0,
21877 1,
21878 matrix_row.as_mut_ptr(),
21879 &mut error,
21880 )
21881 );
21882 let matrix_row = matrix_row.assume_init();
21883 assert_eq!(matrix_row.len, 1);
21884 assert_eq!(*matrix_row.data, 3.0);
21885
21886 let mut line = std::mem::MaybeUninit::<PioMulticonductorLineView>::uninit();
21887 assert!(pio_multiconductor_network_line_at(
21888 retained,
21889 0,
21890 line.as_mut_ptr(),
21891 &mut error,
21892 ));
21893 let line = line.assume_init();
21894 assert!(line.has_route);
21895 assert_eq!(line.route_point_count, 0);
21896
21897 let mut switch = std::mem::MaybeUninit::<PioMulticonductorSwitchView>::uninit();
21898 assert!(pio_multiconductor_network_switch_at(
21899 retained,
21900 0,
21901 switch.as_mut_ptr(),
21902 &mut error,
21903 ));
21904 let switch = switch.assume_init();
21905 assert!(switch.open);
21906 assert!(switch.has_current_limit);
21907 assert_eq!(switch.current_limit_a.len, 0);
21908
21909 let mut transformer =
21910 std::mem::MaybeUninit::<PioMulticonductorTransformerView>::uninit();
21911 assert!(pio_multiconductor_network_transformer_at(
21912 retained,
21913 0,
21914 transformer.as_mut_ptr(),
21915 &mut error,
21916 ));
21917 assert_eq!(transformer.assume_init().winding_count, 1);
21918 let mut winding =
21919 std::mem::MaybeUninit::<PioMulticonductorTransformerWindingView>::uninit();
21920 assert!(pio_multiconductor_network_transformer_winding_at(
21921 retained,
21922 0,
21923 0,
21924 winding.as_mut_ptr(),
21925 &mut error,
21926 ));
21927 let winding = winding.assume_init();
21928 assert!(winding.has_neutral_resistance);
21929 assert!(!winding.has_neutral_reactance);
21930
21931 let mut load = std::mem::MaybeUninit::<PioMulticonductorLoadView>::uninit();
21932 assert!(pio_multiconductor_network_load_at(
21933 retained,
21934 0,
21935 load.as_mut_ptr(),
21936 &mut error,
21937 ));
21938 let load = load.assume_init();
21939 assert_eq!(view_text(load.voltage_model), "zip");
21940 assert_eq!(*load.active_power_constant_power.data, 0.7);
21941
21942 let mut generator = std::mem::MaybeUninit::<PioMulticonductorGeneratorView>::uninit();
21943 assert!(pio_multiconductor_network_generator_at(
21944 retained,
21945 0,
21946 generator.as_mut_ptr(),
21947 &mut error,
21948 ));
21949 let generator = generator.assume_init();
21950 assert!(generator.has_active_power_min);
21951 assert_eq!(generator.active_power_min_w.len, 0);
21952 assert!(generator.has_active_power_dispatch_cost);
21953
21954 let mut resource = std::mem::MaybeUninit::<PioInverterBasedResourceView>::uninit();
21955 assert!(pio_multiconductor_network_inverter_based_resource_at(
21956 retained,
21957 0,
21958 resource.as_mut_ptr(),
21959 &mut error,
21960 ));
21961 let resource = resource.assume_init();
21962 assert_eq!(view_text(resource.topology), "SINGLE_PHASE");
21963 assert!(resource.has_control_profile);
21964 assert_eq!(resource.control_profile.len, 0);
21965
21966 let mut profile = std::mem::MaybeUninit::<PioControlProfileView>::uninit();
21967 assert!(pio_multiconductor_network_control_profile_at(
21968 retained,
21969 0,
21970 profile.as_mut_ptr(),
21971 &mut error,
21972 ));
21973 let profile = profile.assume_init();
21974 assert!(profile.has_power_factor);
21975 assert!(profile.has_volt_var);
21976 assert!(profile.has_volt_watt);
21977 assert_eq!(
21978 view_text(profile.volt_var_voltage_reference),
21979 "PN_PER_PHASE"
21980 );
21981
21982 let mut shunt = std::mem::MaybeUninit::<PioMulticonductorShuntView>::uninit();
21983 assert!(pio_multiconductor_network_shunt_at(
21984 retained,
21985 0,
21986 shunt.as_mut_ptr(),
21987 &mut error,
21988 ));
21989 assert_eq!(shunt.assume_init().conductance_matrix_row_count, 2);
21990 let mut shunt_matrix_row = std::mem::MaybeUninit::<PioF64View>::uninit();
21991 assert!(pio_multiconductor_network_shunt_conductance_matrix_row_at(
21992 retained,
21993 0,
21994 1,
21995 shunt_matrix_row.as_mut_ptr(),
21996 &mut error,
21997 ));
21998 assert_eq!(shunt_matrix_row.assume_init().len, 1);
21999
22000 let mut capacitor = std::mem::MaybeUninit::<PioMulticonductorCapacitorView>::uninit();
22001 assert!(pio_multiconductor_network_capacitor_at(
22002 retained,
22003 0,
22004 capacitor.as_mut_ptr(),
22005 &mut error,
22006 ));
22007 assert_eq!(capacitor.assume_init().rated_reactive_power_var, 100.0);
22008
22009 let mut source = std::mem::MaybeUninit::<PioVoltageSourceView>::uninit();
22010 assert!(pio_multiconductor_network_voltage_source_at(
22011 retained,
22012 0,
22013 source.as_mut_ptr(),
22014 &mut error,
22015 ));
22016 let source = source.assume_init();
22017 assert_eq!(*source.voltage_magnitude_v.data, 240.0);
22018 assert!(source.has_energy_cost_rate);
22019 assert_eq!(source.energy_cost_rate_per_kwh.len, 1);
22020 assert_eq!(*source.energy_cost_rate_per_kwh.data, 0.125);
22021
22022 let mut object = std::mem::MaybeUninit::<PioMulticonductorUntypedObjectView>::uninit();
22023 assert!(pio_multiconductor_network_untyped_object_at(
22024 retained,
22025 0,
22026 object.as_mut_ptr(),
22027 &mut error,
22028 ));
22029 assert_eq!(object.assume_init().property_count, 2);
22030 let mut property =
22031 std::mem::MaybeUninit::<PioMulticonductorUntypedPropertyView>::uninit();
22032 assert!(pio_multiconductor_network_untyped_object_property_at(
22033 retained,
22034 0,
22035 0,
22036 property.as_mut_ptr(),
22037 &mut error,
22038 ));
22039 assert!(!property.assume_init().has_name);
22040 assert!(pio_multiconductor_network_untyped_object_property_at(
22041 retained,
22042 0,
22043 1,
22044 property.as_mut_ptr(),
22045 &mut error,
22046 ));
22047 let property = property.assume_init();
22048 assert!(property.has_name);
22049 assert_eq!(property.name.len, 0);
22050
22051 let mut command = std::mem::MaybeUninit::<PioMulticonductorCommandView>::uninit();
22052 assert!(pio_multiconductor_network_command_at(
22053 retained,
22054 0,
22055 command.as_mut_ptr(),
22056 &mut error,
22057 ));
22058 assert_eq!(view_text(command.assume_init().verb), "solve");
22059 let mut option = std::mem::MaybeUninit::<PioStringPropertyView>::uninit();
22060 assert!(pio_multiconductor_network_option_at(
22061 retained,
22062 0,
22063 option.as_mut_ptr(),
22064 &mut error,
22065 ));
22066 assert_eq!(view_text(option.assume_init().name), "frequency");
22067
22068 assert!(
22069 std::mem::offset_of!(PioMulticonductorLineView, has_route)
22070 > std::mem::offset_of!(PioMulticonductorLineView, route_point_count)
22071 );
22072 assert!(
22073 std::mem::offset_of!(PioMulticonductorBusView, has_location)
22074 > std::mem::offset_of!(PioMulticonductorBusView, location)
22075 );
22076
22077 let mut null_error = std::ptr::null_mut();
22078 let mut null_output = std::mem::MaybeUninit::<PioMulticonductorBusView>::uninit();
22079 assert!(!pio_multiconductor_network_bus_at(
22080 std::ptr::null(),
22081 0,
22082 null_output.as_mut_ptr(),
22083 &mut null_error,
22084 ));
22085 assert!(!null_error.is_null());
22086 assert_eq!(
22087 view_text(pio_error_code(null_error)),
22088 codes::BIND_CAPI_NULL_HANDLE.code
22089 );
22090 pio_error_release(null_error);
22091 pio_multiconductor_network_release(retained);
22092 }
22093 }
22094
22095 #[test]
22096 fn legacy_load_views_refuse_unrepresented_voltage_bands() {
22097 for model in [0, 1, 3, 4, 8] {
22098 check_legacy_load_voltage_refusal(model);
22099 }
22100 }
22101
22102 fn check_legacy_load_voltage_refusal(model: u8) {
22103 let device = if model == 0 {
22104 "New Storage.l phases=1 bus1=b.1.0 kv=.24 kwrated=100 kva=100 limitcurrent=yes"
22105 .to_owned()
22106 } else {
22107 let zip = if model == 8 {
22108 " zipv=[0 .5 .5 0 .3 .7 .2]"
22109 } else {
22110 ""
22111 };
22112 format!("New Load.l phases=1 bus1=b.1.0 kv=.24 kw=1 kvar=.5 model={model}{zip}")
22113 };
22114 let source = powerio_core::Source::from_memory(
22115 "load.dss",
22116 format!("New Circuit.c phases=1 bus1=b.1 basekv=.24\n{device}\n").into_bytes(),
22117 )
22118 .unwrap();
22119 let parsed = powerio_dist::parse(source).unwrap();
22120 let pf = powerio_prob::McAcPfInstance::from_network(parsed.value().clone()).unwrap();
22121 unsafe {
22122 let module = module_handle(powerio::PioModule::new(PioValue::from(pf)));
22123 let value = pio_module_value(module);
22124 let mut error = std::ptr::null_mut();
22125 let instance = pio_value_mc_ac_pf_instance(value, &mut error);
22126 assert!(!instance.is_null());
22127 let network = pio_calculation_instance_multiconductor_network(instance, &mut error);
22128 assert!(!network.is_null());
22129 let mut load = std::mem::MaybeUninit::<PioMulticonductorLoadView>::uninit();
22130 assert!(!pio_multiconductor_network_load_at(
22131 network,
22132 0,
22133 load.as_mut_ptr(),
22134 &mut error
22135 ));
22136 assert!(error_text(error).contains("voltage-band"));
22137 pio_error_release(error);
22138 error = std::ptr::null_mut();
22139 let mut prescribed = std::mem::MaybeUninit::<PioPrescribedTerminalPowerView>::uninit();
22140 assert!(!pio_mc_ac_pf_instance_load_at(
22141 instance,
22142 0,
22143 prescribed.as_mut_ptr(),
22144 &mut error
22145 ));
22146 assert!(error_text(error).contains("voltage-band"));
22147 pio_error_release(error);
22148 error = std::ptr::null_mut();
22149 let mut terminal = std::mem::MaybeUninit::<PioTerminalPowerView>::uninit();
22150 assert!(!pio_mc_ac_pf_instance_load_terminal_at(
22151 instance,
22152 0,
22153 0,
22154 terminal.as_mut_ptr(),
22155 &mut error
22156 ));
22157 assert!(error_text(error).contains("voltage-band"));
22158 pio_error_release(error);
22159 error = std::ptr::null_mut();
22160 pio_value_release(value);
22163 pio_module_release(module);
22164 let mut details = std::mem::MaybeUninit::<PioMulticonductorLoadDetailsView>::uninit();
22165 assert!(pio_multiconductor_network_load_details_at(
22166 network,
22167 0,
22168 details.as_mut_ptr(),
22169 &mut error
22170 ));
22171 let details = details.assume_init();
22172 let expected = match model {
22173 3 | 4 => "bounded_exponential",
22174 0 => "bounded_constant_power",
22175 _ => "bounded_zip",
22176 };
22177 assert_eq!(view_text(details.voltage_model.model), expected);
22178 assert_eq!(details.active_power_nominal_w.len, 1);
22179 assert_eq!(details.reactive_power_nominal_var.len, 1);
22180 assert_eq!(details.voltage_model.nominal_voltage_v.len, 1);
22181 assert!(details.voltage_model.has_voltage_min);
22182 assert!(details.voltage_model.has_voltage_max);
22183 assert_eq!(details.voltage_model.has_cutoff, expected == "bounded_zip");
22184 assert_eq!(details.voltage_model.has_current_limit, model == 0);
22185 let original = &require_multiconductor_network(network).unwrap().loads()[0];
22186 assert_eq!(details.active_power_nominal_w.data, original.p_nom.as_ptr());
22187 assert_eq!(
22188 details.voltage_model.nominal_voltage_v.data,
22189 original.voltage_model.v_nom().as_ptr()
22190 );
22191 let mut powers = std::mem::MaybeUninit::<PioPrescribedLoadDetailsView>::uninit();
22192 assert!(pio_mc_ac_pf_instance_load_details_at(
22193 instance,
22194 0,
22195 powers.as_mut_ptr(),
22196 &mut error
22197 ));
22198 let powers = powers.assume_init();
22199 let pf = require_calculation_instance(instance)
22200 .unwrap()
22201 .mc_ac_pf()
22202 .unwrap();
22203 assert_eq!(powers.terminal_count, pf.loads()[0].terminals.len());
22204 assert_eq!(view_text(powers.voltage_model.model), expected);
22205 assert_eq!(powers.active_power_w.len, pf.loads()[0].p_w.len());
22206 assert_eq!(powers.reactive_power_var.len, pf.loads()[0].q_var.len());
22207 assert_eq!(powers.active_power_w.data, pf.loads()[0].p_w.as_ptr());
22208 assert_eq!(powers.reactive_power_var.data, pf.loads()[0].q_var.as_ptr());
22209 let mut terminal_name = std::mem::MaybeUninit::<PioStringView>::uninit();
22210 assert!(pio_mc_ac_pf_instance_load_terminal_name_at(
22211 instance,
22212 0,
22213 0,
22214 terminal_name.as_mut_ptr(),
22215 &mut error
22216 ));
22217 let pf = require_calculation_instance(instance)
22218 .unwrap()
22219 .mc_ac_pf()
22220 .unwrap();
22221 assert_eq!(
22222 view_text(terminal_name.assume_init()),
22223 pf.loads()[0].terminals[0]
22224 );
22225 assert!(!pio_multiconductor_network_load_details_at(
22226 network,
22227 1,
22228 std::ptr::null_mut(),
22229 &mut error
22230 ));
22231 assert!(error_text(error).contains("out of range"));
22232 pio_error_release(error);
22233 pio_multiconductor_network_release(network);
22234 pio_calculation_instance_release(instance);
22235 }
22236 }
22237
22238 #[test]
22239 fn legacy_source_view_refuses_reference_terminal_physics() {
22240 unsafe {
22241 let mut net = complete_multiconductor_network();
22242 net.sources_mut()[0].reference_terminal = Some("n".into());
22243 let module = module_handle(powerio::PioModule::new(PioValue::from(net)));
22244 let value = pio_module_value(module);
22245 let mut error = std::ptr::null_mut();
22246 let network = pio_value_multiconductor_network(value, &mut error);
22247 assert!(!network.is_null());
22248 let mut output = std::mem::MaybeUninit::<PioVoltageSourceView>::uninit();
22249 assert!(!pio_multiconductor_network_voltage_source_at(
22250 network,
22251 0,
22252 output.as_mut_ptr(),
22253 &mut error
22254 ));
22255 assert!(error_text(error).contains("reference-terminal"));
22256 pio_error_release(error);
22257 pio_multiconductor_network_release(network);
22258 pio_value_release(value);
22259 pio_module_release(module);
22260 }
22261 }
22262
22263 #[test]
22264 fn source_boundary_views_retain_references_and_owner_rooted_arrays() {
22265 unsafe {
22266 let mut net = powerio_dist::MulticonductorNetwork::new();
22267 net.buses_mut().push(powerio_dist::DistBus::new(
22268 "b",
22269 vec!["1".into(), "n".into()],
22270 ));
22271 net.sources_mut().push(
22272 powerio_dist::VoltageSource::new(
22273 "s",
22274 "b",
22275 vec!["1".into()],
22276 vec![230.0],
22277 vec![0.0],
22278 )
22279 .with_reference_terminal("n"),
22280 );
22281 let instance = powerio_prob::McAcPfInstance::from_network(net).unwrap();
22282 let module = module_handle(powerio::PioModule::new(PioValue::from(instance)));
22283 let value = pio_module_value(module);
22284 let mut error = std::ptr::null_mut();
22285 let instance = pio_value_mc_ac_pf_instance(value, &mut error);
22286 assert!(!instance.is_null());
22287 pio_module_release(module);
22288 pio_value_release(value);
22289
22290 let mut output = std::mem::MaybeUninit::<PioVoltageSourceBoundaryView>::uninit();
22291 assert!(pio_mc_ac_pf_instance_source_boundary_at(
22292 instance,
22293 0,
22294 output.as_mut_ptr(),
22295 &mut error
22296 ));
22297 let boundary = output.assume_init();
22298 assert!(boundary.has_reference_terminal);
22299 assert_eq!(view_text(boundary.reference_terminal), "n");
22300 assert_eq!(view_text(boundary.source.bus), "b");
22301 assert_eq!(
22302 std::slice::from_raw_parts(boundary.source.voltage_magnitude_v.data, 1),
22303 [230.0]
22304 );
22305 let mut old = std::mem::MaybeUninit::<PioPrescribedSourceVoltageView>::uninit();
22306 assert!(!pio_mc_ac_pf_instance_source_at(
22307 instance,
22308 0,
22309 old.as_mut_ptr(),
22310 &mut error
22311 ));
22312 assert!(error_text(error).contains("reference-terminal"));
22313 pio_error_release(error);
22314 error = std::ptr::null_mut();
22315 let mut terminal = std::mem::MaybeUninit::<PioTerminalVoltageView>::uninit();
22316 assert!(!pio_mc_ac_pf_instance_source_terminal_at(
22317 instance,
22318 0,
22319 0,
22320 terminal.as_mut_ptr(),
22321 &mut error
22322 ));
22323 assert!(error_text(error).contains("reference-terminal"));
22324 pio_error_release(error);
22325 error = std::ptr::null_mut();
22326
22327 let network = pio_calculation_instance_multiconductor_network(instance, &mut error);
22328 assert!(!network.is_null());
22329 assert!(pio_multiconductor_network_voltage_source_boundary_at(
22330 network,
22331 0,
22332 output.as_mut_ptr(),
22333 &mut error
22334 ));
22335 let network_boundary = output.assume_init();
22336 assert_eq!(
22337 network_boundary.source.voltage_magnitude_v.data,
22338 boundary.source.voltage_magnitude_v.data
22339 );
22340 pio_calculation_instance_release(instance);
22341 assert_eq!(view_text(network_boundary.reference_terminal), "n");
22342 assert_eq!(view_text(network_boundary.source.name), "s");
22343 assert!(!pio_multiconductor_network_voltage_source_boundary_at(
22344 network,
22345 1,
22346 output.as_mut_ptr(),
22347 &mut error
22348 ));
22349 assert!(error_text(error).contains("out of range"));
22350 pio_error_release(error);
22351 pio_multiconductor_network_release(network);
22352 }
22353 }
22354
22355 #[test]
22356 fn balanced_geography_is_typed_and_preserves_optional_routes() {
22357 unsafe {
22358 let mut network = case9_network();
22359 *network.geo_mut() = Some(powerio_tx::GeoMeta {
22360 space: powerio_tx::CoordinateSpace::Diagram {
22361 canvas: Some(powerio_tx::Canvas {
22362 width: Some(800.0),
22363 height: None,
22364 units: Some(String::new()),
22365 }),
22366 },
22367 kind: Some(powerio_tx::CoordsKind::Manual),
22368 });
22369 network.buses_mut()[0].location = Some(powerio_tx::Location {
22370 x: 12.0,
22371 y: 34.0,
22372 kind: None,
22373 });
22374 network.branches_mut()[0].route = Some(Vec::new());
22375 network.branches_mut()[1].route = Some(vec![powerio_tx::Location {
22376 x: 56.0,
22377 y: 78.0,
22378 kind: Some(powerio_tx::CoordsKind::Derived),
22379 }]);
22380
22381 let module = module_handle(powerio::PioModule::new(PioValue::BalancedNetwork(network)));
22382 let value = pio_module_value(module);
22383 let mut error = std::ptr::null_mut();
22384 let balanced = pio_value_balanced_network(value, &mut error);
22385 assert!(!balanced.is_null(), "{}", error_text(error));
22386 let retained = pio_balanced_network_retain(balanced);
22387 pio_balanced_network_release(balanced);
22388 pio_value_release(value);
22389 pio_module_release(module);
22390
22391 let mut geo = std::mem::MaybeUninit::<PioBalancedGeoView>::uninit();
22392 assert!(pio_balanced_network_geo(
22393 retained,
22394 geo.as_mut_ptr(),
22395 &mut error
22396 ));
22397 let geo = geo.assume_init();
22398 assert!(geo.has_geo);
22399 assert_eq!(view_text(geo.space), "diagram");
22400 assert!(geo.has_kind);
22401 assert_eq!(view_text(geo.kind), "manual");
22402 assert!(geo.has_canvas);
22403 assert!(geo.has_canvas_width);
22404 assert_eq!(geo.canvas_width, 800.0);
22405 assert!(!geo.has_canvas_height);
22406 assert!(geo.has_canvas_units);
22407 assert_eq!(geo.canvas_units.len, 0);
22408
22409 let mut bus = std::mem::MaybeUninit::<PioBalancedBusView>::uninit();
22410 assert!(pio_balanced_network_bus_at(
22411 retained,
22412 0,
22413 bus.as_mut_ptr(),
22414 &mut error
22415 ));
22416 let bus = bus.assume_init();
22417 assert!(bus.has_location);
22418 assert_eq!((bus.location.x, bus.location.y), (12.0, 34.0));
22419 assert!(!bus.location.has_kind);
22420
22421 let mut branch = std::mem::MaybeUninit::<PioBalancedBranchView>::uninit();
22422 assert!(pio_balanced_network_branch_at(
22423 retained,
22424 0,
22425 branch.as_mut_ptr(),
22426 &mut error
22427 ));
22428 let branch = branch.assume_init();
22429 assert!(branch.has_route);
22430 assert_eq!(branch.route_point_count, 0);
22431
22432 let mut routed_branch = std::mem::MaybeUninit::<PioBalancedBranchView>::uninit();
22433 assert!(pio_balanced_network_branch_at(
22434 retained,
22435 1,
22436 routed_branch.as_mut_ptr(),
22437 &mut error
22438 ));
22439 let routed_branch = routed_branch.assume_init();
22440 assert!(routed_branch.has_route);
22441 assert_eq!(routed_branch.route_point_count, 1);
22442 let mut point = std::mem::MaybeUninit::<PioBalancedLocationView>::uninit();
22443 assert!(pio_balanced_network_branch_route_point_at(
22444 retained,
22445 1,
22446 0,
22447 point.as_mut_ptr(),
22448 &mut error
22449 ));
22450 let point = point.assume_init();
22451 assert_eq!((point.x, point.y), (56.0, 78.0));
22452 assert!(point.has_kind);
22453 assert_eq!(view_text(point.kind), "derived");
22454
22455 assert!(
22456 std::mem::offset_of!(PioBalancedBusView, has_location)
22457 > std::mem::offset_of!(PioBalancedBusView, location)
22458 );
22459 assert!(
22460 std::mem::offset_of!(PioBalancedBranchView, has_route)
22461 > std::mem::offset_of!(PioBalancedBranchView, route_point_count)
22462 );
22463
22464 let mut null_geo = std::mem::MaybeUninit::<PioBalancedGeoView>::uninit();
22465 assert!(!pio_balanced_network_geo(
22466 std::ptr::null(),
22467 null_geo.as_mut_ptr(),
22468 &mut error
22469 ));
22470 assert!(!error.is_null());
22471 pio_error_release(error);
22472 pio_balanced_network_release(retained);
22473 }
22474 }
22475
22476 #[test]
22477 fn lindist3flow_views_and_quantities_keep_their_owner_alive() {
22478 unsafe {
22479 let text = include_bytes!("../../tests/data/dist/micro/lindist3flow-solution.pio.json");
22480 let module = module_handle(
22481 powerio::deserialize(
22482 powerio_core::Source::from_memory("solution.pio.json", text.to_vec()).unwrap(),
22483 )
22484 .unwrap(),
22485 );
22486 let value = pio_module_value(module);
22487 let mut error = std::ptr::null_mut();
22488 assert!(pio_value_mc_ac_opf_solution(value, &mut error).is_null());
22489 assert!(!error.is_null());
22490 pio_error_release(error);
22491 error = std::ptr::null_mut();
22492 let solution = pio_value_lindist3flow_opf_solution(value, &mut error);
22493 assert!(!solution.is_null(), "{}", error_text(error));
22494 let instance = pio_calculation_solution_instance(solution, &mut error);
22495 assert!(!instance.is_null(), "{}", error_text(error));
22496 assert_eq!(
22497 view_text(pio_calculation_instance_type_name(instance)),
22498 "powerio.LinDist3FlowOpfInstance"
22499 );
22500 let network = pio_calculation_instance_multiconductor_network(instance, &mut error);
22501 assert!(!network.is_null(), "{}", error_text(error));
22502 pio_module_release(module);
22503 pio_value_release(value);
22504 assert_eq!(
22505 view_text(pio_calculation_solution_termination(solution)),
22506 "converged"
22507 );
22508 let mut objective = 0.0;
22509 assert!(pio_calculation_solution_get_objective(
22510 solution,
22511 &mut objective
22512 ));
22513 assert_eq!(objective, 1.0);
22514 let quantity = "line_active_power";
22515 let values = pio_calculation_solution_get_values(
22516 solution,
22517 quantity.as_ptr().cast(),
22518 quantity.len(),
22519 &mut error,
22520 );
22521 assert!(!values.is_null(), "{}", error_text(error));
22522 pio_calculation_solution_release(solution);
22523 let values_view = pio_vector_values(values);
22524 assert_eq!(values_view.len, 1);
22525 assert_eq!(values_view.data.as_ref(), Some(&1000.0));
22526 assert_eq!(pio_lindist3flow_opf_instance_node_count(instance), 2);
22527 assert_eq!(pio_lindist3flow_opf_instance_conductor_count(instance), 1);
22528 let mut node = std::mem::MaybeUninit::<PioLinDist3FlowNodeView>::uninit();
22529 assert!(pio_lindist3flow_opf_instance_node_at(
22530 instance,
22531 0,
22532 node.as_mut_ptr(),
22533 &mut error
22534 ));
22535 assert_eq!(node.assume_init().reference_magnitude, 230.0);
22536 let mut conductor = std::mem::MaybeUninit::<PioLinDist3FlowConductorView>::uninit();
22537 assert!(pio_lindist3flow_opf_instance_conductor_at(
22538 instance,
22539 0,
22540 conductor.as_mut_ptr(),
22541 &mut error
22542 ));
22543 let conductor = conductor.assume_init();
22544 assert!(conductor.reversed);
22545 assert_eq!(view_text(conductor.parent_bus), "source");
22546 assert_eq!(view_text(conductor.child_bus), "load");
22547 assert!(!pio_lindist3flow_opf_instance_node_at(
22548 instance,
22549 2,
22550 node.as_mut_ptr(),
22551 &mut error
22552 ));
22553 assert!(!error.is_null());
22554 pio_error_release(error);
22555 pio_vector_release(values);
22556 pio_calculation_instance_release(instance);
22557 assert_eq!(pio_multiconductor_network_bus_count(network), 2);
22558 pio_multiconductor_network_release(network);
22559 }
22560 }
22561
22562 fn check_stored_solution_rejected(document: &serde_json::Value) {
22563 let bytes = serde_json::to_vec(document).unwrap();
22564 unsafe {
22565 let mut error = std::ptr::null_mut();
22566 let source = pio_source_from_memory(
22567 c"input.pio.json".as_ptr(),
22568 14,
22569 bytes.as_ptr(),
22570 bytes.len(),
22571 &mut error,
22572 );
22573 assert!(!source.is_null());
22574 let decoded = pio_module_deserialize(source, &mut error);
22575 assert!(decoded.is_null());
22576 assert!(!error.is_null());
22577 assert_ne!(view_text(pio_error_code(error)), "BIND.CAPI.PANIC");
22578 pio_error_release(error);
22579 pio_source_release(source);
22580 }
22581 }
22582
22583 fn check_stored_solution_columns(module: &powerio::PioModule<PioValue>) {
22584 let result = powerio::serialize(module, Destination::memory("solution").unwrap()).unwrap();
22585 let EmittedOutput::Memory { artifacts } = result.into_output() else {
22586 panic!("memory output required")
22587 };
22588 let document: serde_json::Value = serde_json::from_slice(artifacts[0].bytes()).unwrap();
22589 for key in [
22590 "bus_voltage_magnitude",
22591 "bus_voltage_angle",
22592 "bus_active_injection",
22593 "branch_from_active_flow",
22594 "terminal_voltage_magnitude",
22595 "terminal_voltage_angle",
22596 ] {
22597 let Some(values) = document["value"]["data"][key].as_array() else {
22598 continue;
22599 };
22600 if values.is_empty() {
22601 continue;
22602 }
22603 assert_eq!(
22604 collect_solution_values(module.value(), key).unwrap().len(),
22605 values.len()
22606 );
22607 let mut malformed = document.clone();
22608 malformed["value"]["data"][key]
22609 .as_array_mut()
22610 .unwrap()
22611 .pop();
22612 check_stored_solution_rejected(&malformed);
22613 }
22614 let mut duplicate = document;
22615 let buses = duplicate["value"]["data"]["instance"]["network"]["buses"]
22616 .as_array_mut()
22617 .unwrap();
22618 if buses.len() > 1 {
22619 buses[1]["id"] = buses[0]["id"].clone();
22620 } else {
22621 let terminals = buses[0]["terminals"].as_array_mut().unwrap();
22622 assert!(terminals.len() >= 2);
22623 terminals[1] = terminals[0].clone();
22624 }
22625 check_stored_solution_rejected(&duplicate);
22626 }
22627
22628 #[test]
22629 fn mc_ac_opf_coil_dispatch_is_a_quantity_only_when_recorded() {
22630 let mut network = multiconductor_network();
22632 network
22633 .generators_mut()
22634 .push(powerio_dist::DistGenerator::new(
22635 "g",
22636 "source",
22637 vec!["1".into(), "2".into(), "3".into()],
22638 powerio_dist::Configuration::Delta,
22639 Vec::new(),
22640 Vec::new(),
22641 ));
22642 let solution = powerio_prob::McAcOpfSolution::new(
22643 Arc::new(powerio_prob::McAcOpfInstance::from_network(network).unwrap()),
22644 powerio_prob::Termination::Converged,
22645 vec![240.0; 3],
22646 vec![0.0; 3],
22647 vec![0.0; 3],
22648 vec![0.0; 3],
22649 0.0,
22650 )
22651 .unwrap();
22652 let quantity = "generator_coil_active_power";
22653 let absent = PioValue::McAcOpfSolution(solution.clone());
22654 assert!(collect_solution_values(&absent, quantity).is_err());
22655 let recorded = PioValue::McAcOpfSolution(
22656 solution
22657 .with_generator_coil_active_powers(vec![1.0, 2.0, 3.0])
22658 .unwrap(),
22659 );
22660 assert_eq!(
22661 collect_solution_values(&recorded, quantity).unwrap(),
22662 vec![1.0, 2.0, 3.0]
22663 );
22664 }
22665
22666 #[test]
22667 #[allow(clippy::too_many_lines)]
22668 fn every_solution_exposes_its_owner_rooted_instance() {
22669 unsafe {
22670 let network = case9_network();
22671 let buses = network.buses().len();
22672 let branches = network.branches().len();
22673 let generators = network.generators().len();
22674 let three_winding = network.transformers_3w().len();
22675
22676 let dc_pf_instance =
22677 Arc::new(powerio_prob::DcPfInstance::from_network(network.clone()).unwrap());
22678 let dc_pf = powerio_prob::DcPfSolution::new(
22679 dc_pf_instance,
22680 powerio_prob::Termination::Converged,
22681 vec![0.0; buses],
22682 vec![0.0; buses],
22683 vec![0.0; branches],
22684 vec![0.0; branches],
22685 vec![Default::default(); three_winding],
22686 )
22687 .unwrap();
22688
22689 let ac_pf_instance =
22690 Arc::new(powerio_prob::AcPfInstance::from_network(network.clone()).unwrap());
22691 let ac_pf = powerio_prob::AcPfSolution::new(
22692 ac_pf_instance,
22693 powerio_prob::Termination::Converged,
22694 vec![1.0; buses],
22695 vec![0.0; buses],
22696 vec![0.0; buses],
22697 vec![0.0; buses],
22698 vec![0.0; branches],
22699 vec![0.0; branches],
22700 vec![0.0; branches],
22701 vec![0.0; branches],
22702 vec![Default::default(); three_winding],
22703 )
22704 .unwrap();
22705
22706 let dc_opf_instance =
22707 Arc::new(powerio_prob::DcOpfInstance::from_network(network.clone()).unwrap());
22708 let dc_opf = powerio_prob::DcOpfSolution::new(
22709 dc_opf_instance,
22710 powerio_prob::Termination::Converged,
22711 vec![0.0; buses],
22712 vec![0.0; buses],
22713 vec![0.0; branches],
22714 vec![0.0; branches],
22715 vec![0.0; generators],
22716 0.0,
22717 vec![Default::default(); three_winding],
22718 )
22719 .unwrap();
22720
22721 let ac_opf_instance =
22722 Arc::new(powerio_prob::AcOpfInstance::from_network(network.clone()).unwrap());
22723 let ac_opf = powerio_prob::AcOpfSolution::new(
22724 Arc::clone(&ac_opf_instance),
22725 powerio_prob::Termination::Converged,
22726 vec![1.0; buses],
22727 vec![0.0; buses],
22728 vec![0.0; buses],
22729 vec![0.0; buses],
22730 vec![0.0; branches],
22731 vec![0.0; branches],
22732 vec![0.0; branches],
22733 vec![0.0; branches],
22734 vec![0.0; generators],
22735 vec![0.0; generators],
22736 0.0,
22737 vec![Default::default(); three_winding],
22738 )
22739 .unwrap();
22740
22741 let mut socwr_values = powerio_prob::solution::SocwrOpfValues::default();
22742 socwr_values.bus_voltage_magnitude_squared = vec![1.0; buses];
22743 socwr_values.branch_voltage_product_real = vec![0.0; branches];
22744 socwr_values.branch_voltage_product_imaginary = vec![0.0; branches];
22745 socwr_values.generator_active_power = vec![0.0; generators];
22746 socwr_values.generator_reactive_power = vec![0.0; generators];
22747 socwr_values.branch_from_active_flow = vec![0.0; branches];
22748 socwr_values.branch_from_reactive_flow = vec![0.0; branches];
22749 socwr_values.branch_to_active_flow = vec![0.0; branches];
22750 socwr_values.branch_to_reactive_flow = vec![0.0; branches];
22751 socwr_values.three_winding_transformer_terminal_powers =
22752 vec![Default::default(); three_winding];
22753 let socwr = powerio_prob::solution::SocwrOpfSolution::new(
22754 ac_opf_instance,
22755 powerio_prob::Termination::Converged,
22756 socwr_values,
22757 0.0,
22758 )
22759 .unwrap();
22760
22761 let multiconductor = multiconductor_network();
22762 let terminals: usize = multiconductor
22763 .buses()
22764 .iter()
22765 .map(|bus| bus.terminals.len())
22766 .sum();
22767 let source_terminals: usize = multiconductor
22768 .sources()
22769 .iter()
22770 .map(|source| source.terminal_map.len())
22771 .sum();
22772 let generator_terminals: usize = multiconductor
22773 .generators()
22774 .iter()
22775 .map(|generator| generator.terminal_map.len())
22776 .sum();
22777 let mc_pf_instance = Arc::new(
22778 powerio_prob::McAcPfInstance::from_network(multiconductor.clone()).unwrap(),
22779 );
22780 let mc_pf = powerio_prob::McAcPfSolution::new(
22781 mc_pf_instance,
22782 powerio_prob::Termination::Converged,
22783 vec![1.0; terminals],
22784 vec![0.0; terminals],
22785 vec![0.0; source_terminals],
22786 )
22787 .unwrap();
22788 let mc_opf_instance =
22789 Arc::new(powerio_prob::McAcOpfInstance::from_network(multiconductor).unwrap());
22790 let mc_opf = powerio_prob::McAcOpfSolution::new(
22791 mc_opf_instance,
22792 powerio_prob::Termination::Converged,
22793 vec![1.0; terminals],
22794 vec![0.0; terminals],
22795 vec![0.0; source_terminals],
22796 vec![0.0; generator_terminals],
22797 0.0,
22798 )
22799 .unwrap();
22800
22801 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
22802 .join("../tests/data/goc3/goc3_small.json");
22803 let scuc_instance = goc3_instance(Source::open(path).unwrap());
22804 let scuc = powerio_prob::AcScucSolution::new(
22805 Arc::new(scuc_instance),
22806 powerio_prob::Termination::Converged,
22807 powerio_prob::ScucNetworkOutputs::default(),
22808 powerio_prob::ScucDeviceOutputs::default(),
22809 None,
22810 )
22811 .unwrap();
22812
22813 let ac_ots_instance =
22814 Arc::new(powerio_prob::AcOtsInstance::from_network(network.clone()).unwrap());
22815 let initial = ac_ots_instance.initial_closed();
22816 let (fixed, _) = ac_ots_instance.fix_topology(&initial).unwrap();
22817 let ac_ots = powerio_prob::AcOtsSolution::new(
22818 ac_ots_instance,
22819 initial,
22820 synthetic_ac_opf_solution(fixed, 0.0),
22821 )
22822 .unwrap();
22823
22824 type SolutionAccessor = unsafe extern "C" fn(
22825 *const PioValueHandle,
22826 *mut *mut PioError,
22827 )
22828 -> *mut PioCalculationSolution;
22829 let solutions: [(PioValue, &str, bool, SolutionAccessor); 9] = [
22830 (
22831 PioValue::DcPfSolution(dc_pf),
22832 "powerio.DcPfInstance",
22833 false,
22834 pio_value_dc_pf_solution,
22835 ),
22836 (
22837 PioValue::AcPfSolution(ac_pf),
22838 "powerio.AcPfInstance",
22839 false,
22840 pio_value_ac_pf_solution,
22841 ),
22842 (
22843 PioValue::DcOpfSolution(dc_opf),
22844 "powerio.DcOpfInstance",
22845 false,
22846 pio_value_dc_opf_solution,
22847 ),
22848 (
22849 PioValue::AcOpfSolution(ac_opf),
22850 "powerio.AcOpfInstance",
22851 false,
22852 pio_value_ac_opf_solution,
22853 ),
22854 (
22855 PioValue::SocwrOpfSolution(socwr),
22856 "powerio.AcOpfInstance",
22857 false,
22858 pio_value_socwr_opf_solution,
22859 ),
22860 (
22861 PioValue::AcOtsSolution(ac_ots),
22862 "powerio.AcOtsInstance",
22863 false,
22864 pio_value_ac_ots_solution,
22865 ),
22866 (
22867 PioValue::McAcPfSolution(mc_pf),
22868 "powerio.McAcPfInstance",
22869 true,
22870 pio_value_mc_ac_pf_solution,
22871 ),
22872 (
22873 PioValue::McAcOpfSolution(mc_opf),
22874 "powerio.McAcOpfInstance",
22875 true,
22876 pio_value_mc_ac_opf_solution,
22877 ),
22878 (
22879 PioValue::AcScucSolution(scuc),
22880 "powerio.AcScucInstance",
22881 false,
22882 pio_value_ac_scuc_solution,
22883 ),
22884 ];
22885
22886 for (value, expected_instance_type, is_multiconductor, accessor) in solutions {
22887 let stored = powerio::PioModule::new(value);
22888 if matches!(
22889 stored.value(),
22890 PioValue::AcPfSolution(_)
22891 | PioValue::DcOpfSolution(_)
22892 | PioValue::McAcPfSolution(_)
22893 | PioValue::McAcOpfSolution(_)
22894 ) {
22895 check_stored_solution_columns(&stored);
22896 }
22897 let module = module_handle(stored);
22898 let value = pio_module_value(module);
22899 let mut error = std::ptr::null_mut();
22900 let solution = accessor(value, &mut error);
22901 assert!(!solution.is_null(), "{}", error_text(error));
22902 let instance = pio_calculation_solution_instance(solution, &mut error);
22903 assert!(!instance.is_null(), "{}", error_text(error));
22904
22905 pio_calculation_solution_release(solution);
22906 pio_value_release(value);
22907 pio_module_release(module);
22908
22909 assert_eq!(
22910 view_text(pio_calculation_instance_type_name(instance)),
22911 expected_instance_type
22912 );
22913 if is_multiconductor {
22914 let network =
22915 pio_calculation_instance_multiconductor_network(instance, &mut error);
22916 assert!(!network.is_null(), "{}", error_text(error));
22917 assert!(pio_multiconductor_network_bus_count(network) > 0);
22918 pio_multiconductor_network_release(network);
22919 } else {
22920 let network = pio_calculation_instance_balanced_network(instance, &mut error);
22921 assert!(!network.is_null(), "{}", error_text(error));
22922 assert!(pio_balanced_network_bus_count(network) > 0);
22923 pio_balanced_network_release(network);
22924 }
22925 pio_calculation_instance_release(instance);
22926 }
22927 }
22928 }
22929
22930 #[test]
22931 fn balanced_rows_are_checked_borrowed_views() {
22932 unsafe {
22933 let module = parse_case9();
22934 let value = pio_module_value(module);
22935 let mut error = std::ptr::null_mut();
22936 let network = pio_value_balanced_network(value, &mut error);
22937 assert!(!network.is_null(), "{}", error_text(error));
22938
22939 pio_module_release(module);
22940 pio_value_release(value);
22941
22942 assert_eq!(pio_balanced_network_base_mva(network), 100.0);
22943 assert_eq!(pio_balanced_network_base_frequency_hz(network), 60.0);
22944 assert_eq!(pio_balanced_network_bus_count(network), 9);
22945 assert_eq!(pio_balanced_network_load_count(network), 3);
22946 assert_eq!(pio_balanced_network_shunt_count(network), 0);
22947 assert_eq!(pio_balanced_network_branch_count(network), 9);
22948 assert_eq!(pio_balanced_network_generator_count(network), 3);
22949 assert_eq!(pio_balanced_network_storage_count(network), 0);
22950
22951 let mut bus = std::mem::MaybeUninit::<PioBalancedBusView>::uninit();
22952 assert!(pio_balanced_network_bus_at(
22953 network,
22954 0,
22955 bus.as_mut_ptr(),
22956 &mut error,
22957 ));
22958 let bus = bus.assume_init();
22959 assert_eq!(bus.id, 1);
22960 assert_eq!(view_text(bus.bus_type), "REF");
22961 assert_eq!(bus.base_kv, 345.0);
22962 assert!(bus.has_component_id);
22963 assert_eq!(view_text(bus.component_id), "1");
22964
22965 let mut load = std::mem::MaybeUninit::<PioBalancedLoadView>::uninit();
22966 assert!(pio_balanced_network_load_at(
22967 network,
22968 0,
22969 load.as_mut_ptr(),
22970 &mut error,
22971 ));
22972 let load = load.assume_init();
22973 assert_eq!(load.bus_id, 5);
22974 assert_eq!(load.p_mw, 90.0);
22975 assert_eq!(load.q_mvar, 30.0);
22976 assert_eq!(view_text(load.voltage_model.kind), "constant_power");
22977
22978 let mut branch = std::mem::MaybeUninit::<PioBalancedBranchView>::uninit();
22979 assert!(pio_balanced_network_branch_at(
22980 network,
22981 0,
22982 branch.as_mut_ptr(),
22983 &mut error,
22984 ));
22985 let branch = branch.assume_init();
22986 assert_eq!(branch.from_bus_id, 1);
22987 assert_eq!(branch.to_bus_id, 4);
22988 assert_eq!(branch.reactance_pu, 0.0576);
22989 assert_eq!(branch.rate_a_mva, 250.0);
22990 assert_eq!(branch.tap_ratio, 0.0);
22991 assert_eq!(branch.effective_tap_ratio, 1.0);
22992 assert!(!branch.terminal_charging_is_explicit);
22993 assert_eq!(branch.additional_rating_count, 0);
22994
22995 let mut generator = std::mem::MaybeUninit::<PioBalancedGeneratorView>::uninit();
22996 assert!(pio_balanced_network_generator_at(
22997 network,
22998 0,
22999 generator.as_mut_ptr(),
23000 &mut error,
23001 ));
23002 let generator = generator.assume_init();
23003 assert_eq!(generator.bus_id, 1);
23004 assert_eq!(view_text(generator.energy_source), "other");
23005 assert_eq!(generator.active_power_mw, 72.3);
23006 assert!(generator.has_cost);
23007 assert!(generator.voltage_regulation_on);
23008 assert!(!generator.has_regulating_terminal);
23009 assert!(!generator.has_active_power_control);
23010 assert!(!generator.active_power_control.has_droop_percent);
23011 assert_eq!(generator.cost.model, 2);
23012 assert_eq!(generator.cost.ncost, 3);
23013 assert_eq!(generator.cost.coefficients.len, 3);
23014 let coefficients = std::slice::from_raw_parts(
23015 generator.cost.coefficients.data,
23016 generator.cost.coefficients.len,
23017 );
23018 assert_eq!(coefficients, &[0.11, 5.0, 150.0]);
23019
23020 let mut capability = std::mem::MaybeUninit::<PioGeneratorCapabilityView>::uninit();
23021 assert!(pio_balanced_network_generator_capability_at(
23022 network,
23023 0,
23024 0,
23025 capability.as_mut_ptr(),
23026 &mut error,
23027 ));
23028 let capability = capability.assume_init();
23029 assert_eq!(view_text(capability.name), "pc1");
23030 assert!(capability.has_value);
23031 assert_eq!(capability.value, 0.0);
23032
23033 let mut missing = std::mem::MaybeUninit::<PioBalancedBusView>::uninit();
23034 assert!(!pio_balanced_network_bus_at(
23035 network,
23036 9,
23037 missing.as_mut_ptr(),
23038 &mut error,
23039 ));
23040 assert_eq!(
23041 view_text(pio_error_code(error)),
23042 "BIND.CAPI.INDEX_OUT_OF_RANGE"
23043 );
23044 pio_error_release(error);
23045
23046 pio_balanced_network_release(network);
23047 }
23048 }
23049
23050 #[test]
23051 fn balanced_optional_row_fields_are_explicit() {
23052 unsafe {
23053 let mut network = BalancedNetwork::new("optional-fields", 100.0);
23054 network.buses_mut().push(powerio_tx::Bus::new(
23055 powerio_tx::BusId(1),
23056 powerio_tx::BusType::Ref,
23057 115.0,
23058 ));
23059 network.buses_mut().push(powerio_tx::Bus::new(
23060 powerio_tx::BusId(2),
23061 powerio_tx::BusType::Pq,
23062 115.0,
23063 ));
23064
23065 let mut load = powerio_tx::Load::new(powerio_tx::BusId(2), 6.0, 3.0);
23066 load.voltage_model = Some(powerio_tx::LoadVoltageModel::Zip {
23067 p_constant_power: 3.0,
23068 q_constant_power: 1.5,
23069 p_constant_current: 2.0,
23070 q_constant_current: 1.0,
23071 p_constant_impedance: 1.0,
23072 q_constant_impedance: 0.5,
23073 v_nom: Some(1.0),
23074 load_type: Some(7),
23075 scaling: Some(0.9),
23076 });
23077 network.loads_mut().push(load);
23078
23079 let mut shunt = powerio_tx::Shunt::new(powerio_tx::BusId(2), 0.0, 2.0);
23080 let mut control = powerio_tx::SwitchedShuntControl::new(
23081 powerio_tx::SwitchedShuntMode::Discrete,
23082 1.05,
23083 0.95,
23084 vec![powerio_tx::ShuntBlock::with_admittance(4, 0.25, 0.5)],
23085 );
23086 control.control_bus = Some(powerio_tx::BusId(1));
23087 shunt.control = Some(control);
23088 network.shunts_mut().push(shunt);
23089
23090 let mut branch =
23091 powerio_tx::Branch::new(powerio_tx::BusId(1), powerio_tx::BusId(2), 0.01, 0.1);
23092 branch.name = Some("controlled transformer".to_owned());
23093 branch.charging = Some(powerio_tx::BranchCharging::new(0.01, 0.02, 0.03, 0.04));
23094 branch
23095 .rating_sets
23096 .push(powerio_tx::BranchRatingSet::new("LTE", 175.0));
23097 branch.current_ratings = Some(powerio_tx::BranchCurrentRatings::new(1.0, 2.0, 3.0));
23098 branch.tap = 1.05;
23099 branch.shift = 4.0;
23100 branch.angmin = -30.0;
23101 branch.angmax = 30.0;
23102 let mut transformer_control = powerio_tx::TransformerControl::new(
23103 powerio_tx::TransformerControlMode::DcLineQuantity,
23104 );
23105 transformer_control.enabled = false;
23106 transformer_control.controlled_bus = Some(powerio_tx::BusId(2));
23107 transformer_control.controlled_bus_on_winding_side = true;
23108 transformer_control.regulating_terminal = Some(
23109 serde_json::from_value(serde_json::json!({
23110 "equipment": {
23111 "component_type": "transformer",
23112 "local_id": "controlled-transformer"
23113 },
23114 "terminal": 2
23115 }))
23116 .unwrap(),
23117 );
23118 transformer_control.ntp = 17;
23119 transformer_control.winding_connection_angle = Some(12.5);
23120 branch.control = Some(transformer_control);
23121 network.branches_mut().push(branch);
23122
23123 let mut generator = powerio_tx::Generator::new(powerio_tx::BusId(1));
23124 generator.energy_source = powerio_tx::GeneratorEnergySource::Nuclear;
23125 generator.cost = Some(powerio_tx::GenCost::new(2, 10.0, 20.0, vec![1.0, 2.0]));
23126 generator.caps[8] = Some(25.0);
23127 generator.voltage_regulation_on = false;
23128 generator.regulating_terminal = Some(
23129 serde_json::from_value(serde_json::json!({
23130 "equipment": {
23131 "component_type": "load",
23132 "local_id": "regulated-load"
23133 },
23134 "terminal": 1
23135 }))
23136 .unwrap(),
23137 );
23138 generator.regulated_bus = Some(powerio_tx::BusId(2));
23139 let mut generator_control = powerio_tx::ActivePowerControl::new(true);
23140 generator_control.droop_percent = Some(4.0);
23141 generator_control.participation_factor = Some(0.6);
23142 generator_control.minimum_target_active_power_mw = Some(10.0);
23143 generator_control.maximum_target_active_power_mw = Some(100.0);
23144 generator.active_power_control = Some(generator_control);
23145 network.generators_mut().push(generator);
23146
23147 let mut storage = powerio_tx::Storage::new(powerio_tx::BusId(2));
23148 storage.energy = 2.0;
23149 storage.energy_rating = 10.0;
23150 storage.current_rating = Some(100.0);
23151 let mut storage_control = powerio_tx::ActivePowerControl::new(false);
23152 storage_control.participation_factor = Some(0.4);
23153 storage.active_power_control = Some(storage_control);
23154 network.storage_mut().push(storage);
23155
23156 let module = module_handle(powerio::PioModule::new(PioValue::from(network)));
23157 let value = pio_module_value(module);
23158 let mut error = std::ptr::null_mut();
23159 let network = pio_value_balanced_network(value, &mut error);
23160
23161 let mut load = std::mem::MaybeUninit::<PioBalancedLoadView>::uninit();
23162 assert!(pio_balanced_network_load_at(
23163 network,
23164 0,
23165 load.as_mut_ptr(),
23166 &mut error
23167 ));
23168 let load = load.assume_init();
23169 assert_eq!(view_text(load.voltage_model.kind), "zip");
23170 assert_eq!(load.voltage_model.p_constant_current_mw, 2.0);
23171 assert!(load.voltage_model.has_nominal_voltage);
23172 assert!(load.voltage_model.has_load_type);
23173 assert!(load.voltage_model.has_scaling);
23174
23175 let mut shunt = std::mem::MaybeUninit::<PioBalancedShuntView>::uninit();
23176 assert!(pio_balanced_network_shunt_at(
23177 network,
23178 0,
23179 shunt.as_mut_ptr(),
23180 &mut error
23181 ));
23182 let shunt = shunt.assume_init();
23183 assert!(!shunt.has_section_count);
23184 assert_eq!(shunt.section_count, 0);
23185 assert!(shunt.has_control);
23186 assert_eq!(view_text(shunt.control_mode), "discrete");
23187 assert_eq!(shunt.control_block_count, 1);
23188 assert!(shunt.has_control_bus);
23189 let mut block = std::mem::MaybeUninit::<PioShuntBlockView>::uninit();
23190 assert!(pio_balanced_network_shunt_block_at(
23191 network,
23192 0,
23193 0,
23194 block.as_mut_ptr(),
23195 &mut error,
23196 ));
23197 let block = block.assume_init();
23198 assert_eq!(block.steps, 4);
23199 assert_eq!(block.conductance_mw, 0.25);
23200 assert_eq!(block.susceptance_mvar, 0.5);
23201
23202 let mut branch = std::mem::MaybeUninit::<PioBalancedBranchView>::uninit();
23203 assert!(pio_balanced_network_branch_at(
23204 network,
23205 0,
23206 branch.as_mut_ptr(),
23207 &mut error,
23208 ));
23209 let branch = branch.assume_init();
23210 assert!(branch.has_name);
23211 assert_eq!(view_text(branch.name), "controlled transformer");
23212 assert!(branch.has_control);
23213 assert_eq!(view_text(branch.control.mode), "dc_line_quantity");
23214 assert!(!branch.control.enabled);
23215 assert!(branch.control.has_controlled_bus);
23216 assert_eq!(branch.control.controlled_bus_id, 2);
23217 assert!(branch.control.controlled_bus_on_winding_side);
23218 assert!(branch.control.has_regulating_terminal);
23219 assert_eq!(branch.control.regulating_terminal.terminal, 2);
23220 assert_eq!(branch.control.tap_position_count, 17);
23221 assert!(branch.control.has_winding_connection_angle);
23222 assert_eq!(branch.control.winding_connection_angle, 12.5);
23223 assert!(branch.terminal_charging_is_explicit);
23224 assert_eq!(branch.from_conductance_pu, 0.01);
23225 assert_eq!(branch.to_susceptance_pu, 0.04);
23226 assert!(branch.has_current_ratings);
23227 assert_eq!(branch.current_rating_c, 3.0);
23228 assert_eq!(branch.additional_rating_count, 1);
23229 let mut rating = std::mem::MaybeUninit::<PioBranchRatingView>::uninit();
23230 assert!(pio_balanced_network_branch_rating_at(
23231 network,
23232 0,
23233 0,
23234 rating.as_mut_ptr(),
23235 &mut error,
23236 ));
23237 let rating = rating.assume_init();
23238 assert_eq!(view_text(rating.name), "LTE");
23239 assert_eq!(rating.rate_mva, 175.0);
23240
23241 let mut generator = std::mem::MaybeUninit::<PioBalancedGeneratorView>::uninit();
23242 assert!(pio_balanced_network_generator_at(
23243 network,
23244 0,
23245 generator.as_mut_ptr(),
23246 &mut error,
23247 ));
23248 let generator = generator.assume_init();
23249 assert!(generator.has_regulated_bus);
23250 assert_eq!(generator.regulated_bus_id, 2);
23251 assert!(!generator.voltage_regulation_on);
23252 assert!(generator.has_regulating_terminal);
23253 assert_eq!(view_text(generator.energy_source), "nuclear");
23254 assert_eq!(
23255 view_text(generator.regulating_terminal.equipment.component_type),
23256 "load"
23257 );
23258 assert_eq!(
23259 view_text(generator.regulating_terminal.equipment.local_id),
23260 "regulated-load"
23261 );
23262 assert_eq!(generator.regulating_terminal.terminal, 1);
23263 assert!(generator.has_active_power_control);
23264 assert!(generator.active_power_control.participate);
23265 assert!(generator.active_power_control.has_droop_percent);
23266 assert_eq!(generator.active_power_control.droop_percent, 4.0);
23267 assert!(generator.active_power_control.has_participation_factor);
23268 assert_eq!(generator.active_power_control.participation_factor, 0.6);
23269 assert!(
23270 generator
23271 .active_power_control
23272 .has_minimum_target_active_power
23273 );
23274 assert_eq!(
23275 generator
23276 .active_power_control
23277 .minimum_target_active_power_mw,
23278 10.0
23279 );
23280 assert!(
23281 generator
23282 .active_power_control
23283 .has_maximum_target_active_power
23284 );
23285 assert_eq!(
23286 generator
23287 .active_power_control
23288 .maximum_target_active_power_mw,
23289 100.0
23290 );
23291 let mut capability = std::mem::MaybeUninit::<PioGeneratorCapabilityView>::uninit();
23292 assert!(pio_balanced_network_generator_capability_at(
23293 network,
23294 0,
23295 8,
23296 capability.as_mut_ptr(),
23297 &mut error,
23298 ));
23299 let capability = capability.assume_init();
23300 assert_eq!(view_text(capability.name), "ramp_30");
23301 assert!(capability.has_value);
23302 assert_eq!(capability.value, 25.0);
23303
23304 let mut storage = std::mem::MaybeUninit::<PioBalancedStorageView>::uninit();
23305 assert!(pio_balanced_network_storage_at(
23306 network,
23307 0,
23308 storage.as_mut_ptr(),
23309 &mut error,
23310 ));
23311 let storage = storage.assume_init();
23312 assert_eq!(storage.energy_mwh, 2.0);
23313 assert_eq!(storage.energy_rating_mwh, 10.0);
23314 assert!(storage.has_current_rating);
23315 assert_eq!(storage.current_rating, 100.0);
23316 assert!(storage.has_active_power_control);
23317 assert!(!storage.active_power_control.participate);
23318 assert!(!storage.active_power_control.has_droop_percent);
23319 assert!(storage.active_power_control.has_participation_factor);
23320 assert_eq!(storage.active_power_control.participation_factor, 0.4);
23321
23322 pio_balanced_network_release(network);
23323 pio_value_release(value);
23324 pio_module_release(module);
23325 }
23326 }
23327
23328 #[test]
23329 fn powsybl_balanced_tables_are_borrowed_without_serialization() {
23330 unsafe {
23331 let mut network = BalancedNetwork::new("powsybl-tables", 100.0);
23332 for (id, kind, kv) in [
23333 (1, powerio_tx::BusType::Ref, 400.0),
23334 (2, powerio_tx::BusType::Pq, 225.0),
23335 (3, powerio_tx::BusType::Pq, 63.0),
23336 ] {
23337 network
23338 .buses_mut()
23339 .push(powerio_tx::Bus::new(powerio_tx::BusId(id), kind, kv));
23340 }
23341
23342 let mut shunt = powerio_tx::Shunt::new(powerio_tx::BusId(2), 0.0, 12.0);
23343 shunt.uid = Some("SH".to_owned());
23344 shunt.section_count = Some(2);
23345 network.shunts_mut().push(shunt);
23346
23347 let mut svc = powerio_tx::StaticVarCompensator::new(powerio_tx::BusId(2), -0.02, 0.03);
23348 svc.uid = Some("SVC".to_owned());
23349 svc.regulating = true;
23350 svc.regulation_mode = powerio_tx::StaticVarCompensatorRegulationMode::ReactivePower;
23351 svc.reactive_power_setpoint_mvar = 12.0;
23352 svc.regulating_terminal = Some(
23353 serde_json::from_value(serde_json::json!({
23354 "equipment": {
23355 "component_type": "static_var_compensator",
23356 "local_id": "SVC"
23357 },
23358 "terminal": 1
23359 }))
23360 .unwrap(),
23361 );
23362 network.static_var_compensators_mut().push(svc);
23363
23364 let mut switch =
23365 powerio_tx::Switch::new(powerio_tx::BusId(1), powerio_tx::BusId(2), true);
23366 switch.uid = Some("SW".to_owned());
23367 switch.thermal_rating = Some(500.0);
23368 switch.pf = Some(75.0);
23369 network.switches_mut().push(switch);
23370
23371 let mut hvdc = powerio_tx::Hvdc::new(powerio_tx::BusId(1), powerio_tx::BusId(2));
23372 hvdc.uid = Some("HVDC".to_owned());
23373 hvdc.resistance_ohm = Some(1.5);
23374 hvdc.nominal_voltage_kv = Some(320.0);
23375 hvdc.converters_mode =
23376 Some(powerio_tx::HvdcConvertersMode::Side1RectifierSide2Inverter);
23377 hvdc.converter1 = Some(
23378 serde_json::from_value(serde_json::json!({
23379 "component": {
23380 "component_type": "hvdc_converter",
23381 "local_id": "C1"
23382 },
23383 "kind": "vsc",
23384 "loss_factor_percent": 1.0,
23385 "voltage_regulator_on": true,
23386 "voltage_setpoint_kv": 400.0
23387 }))
23388 .unwrap(),
23389 );
23390 network.hvdc_mut().push(hvdc);
23391
23392 let mut windings = [
23393 powerio_tx::Winding::new(powerio_tx::BusId(1)),
23394 powerio_tx::Winding::new(powerio_tx::BusId(2)),
23395 powerio_tx::Winding::new(powerio_tx::BusId(3)),
23396 ];
23397 let mut winding_control =
23398 powerio_tx::TransformerControl::new(powerio_tx::TransformerControlMode::ActiveFlow);
23399 winding_control.controlled_bus = Some(powerio_tx::BusId(3));
23400 winding_control.regulating_terminal = Some(
23401 serde_json::from_value(serde_json::json!({
23402 "equipment": {
23403 "component_type": "transformer",
23404 "local_id": "T3"
23405 },
23406 "terminal": 3
23407 }))
23408 .unwrap(),
23409 );
23410 winding_control.ntp = 21;
23411 windings[2].control = Some(winding_control);
23412 let mut transformer = powerio_tx::Transformer3W::new(
23413 windings,
23414 [
23415 powerio_tx::Impedance::new(0.01, 0.1, 100.0),
23416 powerio_tx::Impedance::new(0.02, 0.2, 100.0),
23417 powerio_tx::Impedance::new(0.03, 0.3, 100.0),
23418 ],
23419 );
23420 transformer.uid = Some("T3".to_owned());
23421 transformer.name = Some("three winding".to_owned());
23422 network.transformers_3w_mut().push(transformer);
23423
23424 let mut area = powerio_tx::Area::new(7);
23425 area.uid = Some("A7".to_owned());
23426 area.name = Some("control area".to_owned());
23427 area.area_type = Some("control_area".to_owned());
23428 area.slack_bus = Some(powerio_tx::BusId(1));
23429 area.net_interchange = 12.5;
23430 network.areas_mut().push(area);
23431
23432 let module = module_handle(powerio::PioModule::new(PioValue::from(network)));
23433 let value = pio_module_value(module);
23434 let mut error = std::ptr::null_mut();
23435 let network = pio_value_balanced_network(value, &mut error);
23436 pio_value_release(value);
23437 pio_module_release(module);
23438
23439 assert_eq!(
23440 pio_balanced_network_static_var_compensator_count(network),
23441 1
23442 );
23443 assert_eq!(pio_balanced_network_shunt_count(network), 1);
23444 assert_eq!(pio_balanced_network_switch_count(network), 1);
23445 assert_eq!(pio_balanced_network_hvdc_count(network), 1);
23446 assert_eq!(
23447 pio_balanced_network_three_winding_transformer_count(network),
23448 1
23449 );
23450 assert_eq!(pio_balanced_network_area_count(network), 1);
23451
23452 let mut svc = std::mem::MaybeUninit::<PioBalancedStaticVarCompensatorView>::uninit();
23453 assert!(pio_balanced_network_static_var_compensator_at(
23454 network,
23455 0,
23456 svc.as_mut_ptr(),
23457 &mut error,
23458 ));
23459 let svc = svc.assume_init();
23460 assert_eq!(view_text(svc.component_id), "SVC");
23461 assert_eq!(view_text(svc.regulation_mode), "reactive_power");
23462 assert!(svc.has_regulating_terminal);
23463
23464 let mut shunt = std::mem::MaybeUninit::<PioBalancedShuntView>::uninit();
23465 assert!(pio_balanced_network_shunt_at(
23466 network,
23467 0,
23468 shunt.as_mut_ptr(),
23469 &mut error,
23470 ));
23471 let shunt = shunt.assume_init();
23472 assert!(shunt.has_section_count);
23473 assert_eq!(shunt.section_count, 2);
23474
23475 let mut switch = std::mem::MaybeUninit::<PioBalancedSwitchView>::uninit();
23476 assert!(pio_balanced_network_switch_at(
23477 network,
23478 0,
23479 switch.as_mut_ptr(),
23480 &mut error,
23481 ));
23482 let switch = switch.assume_init();
23483 assert!(switch.closed);
23484 assert_eq!(switch.thermal_rating_mva, 500.0);
23485 assert!(switch.has_from_active_power);
23486
23487 let mut hvdc = std::mem::MaybeUninit::<PioBalancedHvdcView>::uninit();
23488 assert!(pio_balanced_network_hvdc_at(
23489 network,
23490 0,
23491 hvdc.as_mut_ptr(),
23492 &mut error,
23493 ));
23494 let hvdc = hvdc.assume_init();
23495 assert!(hvdc.has_converter1);
23496 assert_eq!(view_text(hvdc.converter1.kind), "vsc");
23497 assert_eq!(hvdc.nominal_voltage_kv, 320.0);
23498
23499 let mut transformer =
23500 std::mem::MaybeUninit::<PioBalancedThreeWindingTransformerView>::uninit();
23501 assert!(pio_balanced_network_three_winding_transformer_at(
23502 network,
23503 0,
23504 transformer.as_mut_ptr(),
23505 &mut error,
23506 ));
23507 assert_eq!(transformer.assume_init().winding_count, 3);
23508 let mut winding =
23509 std::mem::MaybeUninit::<PioThreeWindingTransformerWindingView>::uninit();
23510 assert!(pio_balanced_network_three_winding_transformer_winding_at(
23511 network,
23512 0,
23513 2,
23514 winding.as_mut_ptr(),
23515 &mut error,
23516 ));
23517 let winding = winding.assume_init();
23518 assert_eq!(winding.bus_id, 3);
23519 assert!(winding.has_control);
23520 assert_eq!(view_text(winding.control.mode), "active_flow");
23521 assert!(winding.control.enabled);
23522 assert_eq!(winding.control.controlled_bus_id, 3);
23523 assert!(winding.control.has_regulating_terminal);
23524 assert_eq!(winding.control.regulating_terminal.terminal, 3);
23525 assert_eq!(winding.control.tap_position_count, 21);
23526
23527 let mut area = std::mem::MaybeUninit::<PioBalancedAreaView>::uninit();
23528 assert!(pio_balanced_network_area_at(
23529 network,
23530 0,
23531 area.as_mut_ptr(),
23532 &mut error,
23533 ));
23534 let area = area.assume_init();
23535 assert_eq!(view_text(area.component_id), "A7");
23536 assert_eq!(area.slack_bus_id, 1);
23537
23538 pio_balanced_network_release(network);
23539 }
23540 }
23541
23542 #[test]
23543 fn detailed_connectivity_tables_are_owner_rooted_views() {
23544 const HIERARCHY: &str = r#"<?xml version="1.0" encoding="UTF-8"?>
23545<iidm:network xmlns:iidm="http://www.powsybl.org/schema/iidm/1_17" id="details" caseDate="2026-01-01T00:00:00Z" forecastDistance="0" sourceFormat="test" minimumValidationLevel="STEADY_STATE_HYPOTHESIS">
23546 <iidm:substation id="S" country="US" tso="MISO" geographicalTags="east">
23547 <iidm:voltageLevel id="VL1" nominalV="132" topologyKind="BUS_BREAKER"><iidm:busBreakerTopology><iidm:bus id="B1"/></iidm:busBreakerTopology></iidm:voltageLevel>
23548 <iidm:voltageLevel id="VL2" nominalV="33" topologyKind="BUS_BREAKER"><iidm:busBreakerTopology><iidm:bus id="B2"/></iidm:busBreakerTopology></iidm:voltageLevel>
23549 <iidm:voltageLevel id="VL3" nominalV="11" topologyKind="BUS_BREAKER"><iidm:busBreakerTopology><iidm:bus id="B3"/></iidm:busBreakerTopology></iidm:voltageLevel>
23550 <iidm:threeWindingsTransformer id="T3" ratedU0="132" ratedU1="132" ratedU2="33" ratedU3="11" r1="17.424" x1="34.848" r2="1.7424" x2="3.4848" r3="0.8712" x3="1.7424" bus1="B1" connectableBus1="B1" voltageLevelId1="VL1" bus2="B2" connectableBus2="B2" voltageLevelId2="VL2" bus3="B3" connectableBus3="B3" voltageLevelId3="VL3" selectedOperationalLimitsGroupIds1="normal">
23551 <iidm:ratioTapChanger2 tapPosition="0" lowTapPosition="0" loadTapChangingCapabilities="false"><iidm:step rho="1.05"/></iidm:ratioTapChanger2>
23552 <iidm:operationalLimitsGroup1 id="normal"><iidm:apparentPowerLimits permanentLimit="90"><iidm:temporaryLimit name="emergency" acceptableDuration="600" value="100"/></iidm:apparentPowerLimits></iidm:operationalLimitsGroup1>
23553 </iidm:threeWindingsTransformer>
23554 </iidm:substation>
23555</iidm:network>"#;
23556
23557 unsafe {
23558 let module = parse_xiidm_text(HIERARCHY);
23559 let mut identified_network = match &PioModule::get(module).unwrap().module.value() {
23560 PioValue::BalancedNetwork(network) => network.clone(),
23561 value => panic!("expected balanced network, got {}", value.type_name()),
23562 };
23563 let identified_details = Arc::make_mut(
23564 identified_network
23565 .detailed_connectivity_mut()
23566 .as_mut()
23567 .unwrap(),
23568 );
23569 identified_details.terminals[0].component =
23570 Some(ComponentId::new("terminal", "terminal-T3-1").unwrap());
23571 identified_details.tap_changers[0].component =
23572 Some(ComponentId::new("tap_changer", "tap-T3-2").unwrap());
23573 let value = pio_module_value(module);
23574 let mut error = std::ptr::null_mut();
23575 let network = pio_value_balanced_network(value, &mut error);
23576 assert!(pio_balanced_network_has_detailed_connectivity(network));
23577 let details = pio_balanced_network_detailed_connectivity(network);
23578 assert!(!details.is_null());
23579 pio_value_release(value);
23580 pio_module_release(module);
23581 pio_balanced_network_release(network);
23582
23583 let mut counts = std::mem::MaybeUninit::<PioDetailedConnectivityCountsView>::uninit();
23584 assert!(pio_detailed_connectivity_counts(
23585 details,
23586 counts.as_mut_ptr(),
23587 &mut error,
23588 ));
23589 let counts = counts.assume_init();
23590 assert_eq!(counts.substations, 1);
23591 assert_eq!(counts.voltage_levels, 3);
23592 assert_eq!(counts.terminals, 3);
23593 assert_eq!(counts.operational_limit_groups, 1);
23594 assert_eq!(counts.tap_changers, 1);
23595
23596 let mut substation = std::mem::MaybeUninit::<PioSubstationView>::uninit();
23597 assert!(pio_detailed_connectivity_substation_at(
23598 details,
23599 0,
23600 substation.as_mut_ptr(),
23601 &mut error,
23602 ));
23603 let substation = substation.assume_init();
23604 assert_eq!(view_text(substation.component.local_id), "S");
23605 assert_eq!(substation.geographical_tag_count, 1);
23606
23607 let mut level = std::mem::MaybeUninit::<PioVoltageLevelView>::uninit();
23608 assert!(pio_detailed_connectivity_voltage_level_at(
23609 details,
23610 0,
23611 level.as_mut_ptr(),
23612 &mut error,
23613 ));
23614 let level = level.assume_init();
23615 assert_eq!(view_text(level.topology_kind), "bus_breaker");
23616 assert_eq!(level.nominal_voltage_kv, 132.0);
23617
23618 let mut terminal = std::mem::MaybeUninit::<PioDetailedTerminalView>::uninit();
23619 assert!(pio_detailed_connectivity_terminal_at(
23620 details,
23621 0,
23622 terminal.as_mut_ptr(),
23623 &mut error,
23624 ));
23625 let terminal = terminal.assume_init();
23626 assert!(terminal.connected);
23627 assert!(!terminal.has_component);
23628
23629 let mut limit = std::mem::MaybeUninit::<PioOperationalLimitGroupView>::uninit();
23630 assert!(pio_detailed_connectivity_operational_limit_group_at(
23631 details,
23632 0,
23633 limit.as_mut_ptr(),
23634 &mut error,
23635 ));
23636 let limit = limit.assume_init();
23637 assert!(limit.has_apparent_power_limits);
23638 assert_eq!(limit.apparent_power_permanent_limit_mva, 90.0);
23639 assert_eq!(limit.apparent_power_temporary_limit_count, 1);
23640
23641 let mut changer = std::mem::MaybeUninit::<PioTapChangerView>::uninit();
23642 assert!(pio_detailed_connectivity_tap_changer_at(
23643 details,
23644 0,
23645 changer.as_mut_ptr(),
23646 &mut error,
23647 ));
23648 let changer = changer.assume_init();
23649 assert!(!changer.has_component);
23650 assert_eq!(view_text(changer.kind), "ratio");
23651 assert!(changer.has_tap_position);
23652 assert_eq!(changer.tap_position, 0);
23653 assert_eq!(changer.step_count, 1);
23654
23655 pio_detailed_connectivity_release(details);
23656
23657 let module = module_handle(powerio::PioModule::new(PioValue::BalancedNetwork(
23658 identified_network,
23659 )));
23660 let value = pio_module_value(module);
23661 let network = pio_value_balanced_network(value, &mut error);
23662 let details = pio_balanced_network_detailed_connectivity(network);
23663 pio_value_release(value);
23664 pio_module_release(module);
23665 pio_balanced_network_release(network);
23666
23667 let mut terminal = std::mem::MaybeUninit::<PioDetailedTerminalView>::uninit();
23668 assert!(pio_detailed_connectivity_terminal_at(
23669 details,
23670 0,
23671 terminal.as_mut_ptr(),
23672 &mut error,
23673 ));
23674 let terminal = terminal.assume_init();
23675 assert!(terminal.has_component);
23676 assert_eq!(view_text(terminal.component.component_type), "terminal");
23677 assert_eq!(view_text(terminal.component.local_id), "terminal-T3-1");
23678
23679 let mut changer = std::mem::MaybeUninit::<PioTapChangerView>::uninit();
23680 assert!(pio_detailed_connectivity_tap_changer_at(
23681 details,
23682 0,
23683 changer.as_mut_ptr(),
23684 &mut error,
23685 ));
23686 let changer = changer.assume_init();
23687 assert!(changer.has_component);
23688 assert_eq!(view_text(changer.component.component_type), "tap_changer");
23689 assert_eq!(view_text(changer.component.local_id), "tap-T3-2");
23690 pio_detailed_connectivity_release(details);
23691
23692 let without_assigned_tap = HIERARCHY.replace(r#" tapPosition="0""#, "");
23693 let module = parse_xiidm_text(&without_assigned_tap);
23694 let value = pio_module_value(module);
23695 let network = pio_value_balanced_network(value, &mut error);
23696 let details = pio_balanced_network_detailed_connectivity(network);
23697 let mut changer = std::mem::MaybeUninit::<PioTapChangerView>::uninit();
23698 assert!(pio_detailed_connectivity_tap_changer_at(
23699 details,
23700 0,
23701 changer.as_mut_ptr(),
23702 &mut error,
23703 ));
23704 let changer = changer.assume_init();
23705 assert!(!changer.has_tap_position);
23706 assert_eq!(changer.tap_position, 0);
23707 pio_detailed_connectivity_release(details);
23708 pio_balanced_network_release(network);
23709 pio_value_release(value);
23710 pio_module_release(module);
23711 }
23712 }
23713
23714 #[test]
23715 fn subnetworks_boundary_lines_and_tie_lines_are_owner_rooted_views() {
23716 const XIIDM: &str = r#"<?xml version="1.0" encoding="UTF-8"?>
23717<iidm:network xmlns:iidm="http://www.powsybl.org/schema/iidm/1_17" id="Merged" caseDate="2026-01-01T00:00:00Z" forecastDistance="0" sourceFormat="root" minimumValidationLevel="STEADY_STATE_HYPOTHESIS">
23718 <iidm:network id="A" caseDate="2026-01-01T01:00:00Z" forecastDistance="1" sourceFormat="part-a" minimumValidationLevel="STEADY_STATE_HYPOTHESIS">
23719 <iidm:substation id="SA"><iidm:voltageLevel id="VA" nominalV="100" topologyKind="BUS_BREAKER"><iidm:busBreakerTopology><iidm:bus id="BA"/></iidm:busBreakerTopology><iidm:boundaryLine id="DLA" p0="5" q0="6" r="1" x="2" generationVoltageRegulationOn="true" generationMinP="0" generationMaxP="20" generationTargetP="10" generationTargetV="100" bus="BA" connectableBus="BA"><iidm:reactiveCapabilityCurve><iidm:property name="owner" value="RTE"/><iidm:point p="0" minQ="-10" maxQ="10"/><iidm:point p="10" minQ="0" maxQ="20"/></iidm:reactiveCapabilityCurve></iidm:boundaryLine></iidm:voltageLevel></iidm:substation>
23720 </iidm:network>
23721 <iidm:network id="B" caseDate="2026-01-01T02:00:00Z" forecastDistance="2" sourceFormat="part-b" minimumValidationLevel="STEADY_STATE_HYPOTHESIS">
23722 <iidm:substation id="SB"><iidm:voltageLevel id="VB" nominalV="100" topologyKind="BUS_BREAKER"><iidm:busBreakerTopology><iidm:bus id="BB"/></iidm:busBreakerTopology><iidm:boundaryLine id="DLB" p0="-5" q0="-6" r="3" x="4" bus="BB" connectableBus="BB"/></iidm:voltageLevel></iidm:substation>
23723 </iidm:network>
23724 <iidm:tieLine id="TL" boundaryLineId1="DLA" boundaryLineId2="DLB"/>
23725</iidm:network>"#;
23726
23727 unsafe {
23728 let module = parse_xiidm_text(XIIDM);
23729 let value = pio_module_value(module);
23730 let mut error = std::ptr::null_mut();
23731 let network = pio_value_balanced_network(value, &mut error);
23732 let details = pio_balanced_network_detailed_connectivity(network);
23733 pio_value_release(value);
23734 pio_module_release(module);
23735 pio_balanced_network_release(network);
23736
23737 let mut counts = std::mem::MaybeUninit::<PioDetailedConnectivityCountsView>::uninit();
23738 assert!(pio_detailed_connectivity_counts(
23739 details,
23740 counts.as_mut_ptr(),
23741 &mut error,
23742 ));
23743 let counts = counts.assume_init();
23744 assert_eq!(counts.subnetworks, 2);
23745 assert_eq!(counts.boundary_lines, 2);
23746 assert_eq!(counts.tie_lines, 1);
23747
23748 let mut subnetwork = std::mem::MaybeUninit::<PioSubnetworkView>::uninit();
23749 assert!(pio_detailed_connectivity_subnetwork_at(
23750 details,
23751 0,
23752 subnetwork.as_mut_ptr(),
23753 &mut error,
23754 ));
23755 let subnetwork = subnetwork.assume_init();
23756 assert_eq!(view_text(subnetwork.component.local_id), "A");
23757 assert_eq!(view_text(subnetwork.parent.local_id), "Merged");
23758 assert!(subnetwork.case_metadata.has_forecast_distance);
23759 assert_eq!(subnetwork.case_metadata.forecast_distance, 1);
23760 assert_eq!(
23761 view_text(subnetwork.case_metadata.source_model_format),
23762 "part-a"
23763 );
23764 assert!(subnetwork.component_count >= 4);
23765
23766 let mut member = std::mem::MaybeUninit::<PioComponentIdView>::uninit();
23767 assert!(pio_detailed_connectivity_subnetwork_component_at(
23768 details,
23769 0,
23770 0,
23771 member.as_mut_ptr(),
23772 &mut error,
23773 ));
23774 assert_ne!(view_text(member.assume_init().local_id), "");
23775
23776 let mut boundary = std::mem::MaybeUninit::<PioBoundaryLineView>::uninit();
23777 assert!(pio_detailed_connectivity_boundary_line_at(
23778 details,
23779 0,
23780 boundary.as_mut_ptr(),
23781 &mut error,
23782 ));
23783 let boundary = boundary.assume_init();
23784 assert_eq!(view_text(boundary.component.local_id), "DLA");
23785 assert_eq!(boundary.active_power_setpoint_mw, 5.0);
23786 assert!(boundary.has_generation);
23787 assert!(boundary.generation.voltage_regulation_on);
23788 assert_eq!(boundary.generation.target_active_power_mw, 10.0);
23789 assert!(boundary.generation.has_reactive_limits);
23790 assert_eq!(
23791 view_text(boundary.generation.reactive_limits.kind),
23792 "capability_curve"
23793 );
23794 assert_eq!(boundary.generation.reactive_limits.point_count, 2);
23795
23796 let mut property = std::mem::MaybeUninit::<PioStringPropertyView>::uninit();
23797 assert!(
23798 pio_detailed_connectivity_boundary_line_reactive_limit_property_at(
23799 details,
23800 0,
23801 0,
23802 property.as_mut_ptr(),
23803 &mut error,
23804 )
23805 );
23806 let property = property.assume_init();
23807 assert_eq!(view_text(property.name), "owner");
23808 assert_eq!(view_text(property.value), "RTE");
23809
23810 let mut point = std::mem::MaybeUninit::<PioReactiveCapabilityCurvePointView>::uninit();
23811 assert!(
23812 pio_detailed_connectivity_boundary_line_reactive_capability_point_at(
23813 details,
23814 0,
23815 1,
23816 point.as_mut_ptr(),
23817 &mut error,
23818 )
23819 );
23820 let point = point.assume_init();
23821 assert_eq!(point.active_power_mw, 10.0);
23822 assert_eq!(point.maximum_reactive_power_mvar, 20.0);
23823
23824 let mut tie = std::mem::MaybeUninit::<PioTieLineView>::uninit();
23825 assert!(pio_detailed_connectivity_tie_line_at(
23826 details,
23827 0,
23828 tie.as_mut_ptr(),
23829 &mut error,
23830 ));
23831 let tie = tie.assume_init();
23832 assert_eq!(view_text(tie.component.local_id), "TL");
23833 assert_eq!(view_text(tie.boundary_line1.local_id), "DLA");
23834 assert_eq!(view_text(tie.boundary_line2.local_id), "DLB");
23835 assert!(tie.has_calculation_branch);
23836
23837 pio_detailed_connectivity_release(details);
23838 }
23839 }
23840
23841 #[test]
23842 fn connectivity_node_numbers_are_optional_borrowed_fields() {
23843 const XIIDM: &str = r#"<?xml version="1.0" encoding="UTF-8"?>
23844<iidm:network xmlns:iidm="http://www.powsybl.org/schema/iidm/1_17" id="nodes" caseDate="2025-01-01T00:00:00Z" forecastDistance="0" sourceFormat="test" minimumValidationLevel="STEADY_STATE_HYPOTHESIS">
23845 <iidm:substation id="S">
23846 <iidm:voltageLevel id="VL" nominalV="110" topologyKind="NODE_BREAKER">
23847 <iidm:nodeBreakerTopology>
23848 <iidm:bus v="110" angle="0" nodes="0,1,2"/>
23849 <iidm:busbarSection id="BBS" node="2"/>
23850 <iidm:switch id="BR" kind="BREAKER" open="false" node1="1" node2="2"/>
23851 <iidm:internalConnection node1="0" node2="1"/>
23852 </iidm:nodeBreakerTopology>
23853 <iidm:generator id="G" energySource="OTHER" minP="0" maxP="10" voltageRegulatorOn="true" targetP="5" node="0"><iidm:minMaxReactiveLimits minQ="-2" maxQ="2"/></iidm:generator>
23854 </iidm:voltageLevel>
23855 </iidm:substation>
23856</iidm:network>"#;
23857
23858 unsafe {
23859 let module = parse_xiidm_text(XIIDM);
23860 let value = pio_module_value(module);
23861 let mut error = std::ptr::null_mut();
23862 let network = pio_value_balanced_network(value, &mut error);
23863 let details = pio_balanced_network_detailed_connectivity(network);
23864
23865 let mut numbers = Vec::new();
23866 for index in 0..3 {
23867 let mut node = std::mem::MaybeUninit::<PioConnectivityNodeView>::uninit();
23868 assert!(pio_detailed_connectivity_node_at(
23869 details,
23870 index,
23871 node.as_mut_ptr(),
23872 &mut error,
23873 ));
23874 let node = node.assume_init();
23875 assert!(node.has_node_number);
23876 assert!(node.has_calculated_bus);
23877 numbers.push(node.node_number);
23878 }
23879 numbers.sort_unstable();
23880 assert_eq!(numbers, [0, 1, 2]);
23881
23882 pio_detailed_connectivity_release(details);
23883 pio_balanced_network_release(network);
23884 pio_value_release(value);
23885 pio_module_release(module);
23886 }
23887 }
23888
23889 #[test]
23890 fn omitted_fields_and_equipment_reactive_limits_are_typed_views() {
23891 const XIIDM: &str = r#"<?xml version="1.0" encoding="UTF-8"?>
23892<iidm:network xmlns:iidm="http://www.powsybl.org/schema/iidm/equipment/1_12" id="equipment" caseDate="2021-01-03T00:00:00Z" forecastDistance="0" sourceFormat="test" minimumValidationLevel="EQUIPMENT">
23893 <iidm:substation id="S"><iidm:voltageLevel id="VL" nominalV="225" topologyKind="NODE_BREAKER">
23894 <iidm:nodeBreakerTopology><iidm:busbarSection id="BBS" node="0"/></iidm:nodeBreakerTopology>
23895 <iidm:generator id="G" energySource="SOLAR" minP="0" maxP="100" voltageRegulatorOn="true" node="0">
23896 <iidm:reactiveCapabilityCurve><iidm:property name="curve" value="retained"/><iidm:point p="0" minQ="-20" maxQ="20"><iidm:property name="point" value="first"/></iidm:point><iidm:point p="100" minQ="-10" maxQ="10"/></iidm:reactiveCapabilityCurve>
23897 </iidm:generator>
23898 </iidm:voltageLevel></iidm:substation>
23899</iidm:network>"#;
23900
23901 unsafe {
23902 let module = parse_xiidm_text(XIIDM);
23903 let value = pio_module_value(module);
23904 let mut error = std::ptr::null_mut();
23905 let network = pio_value_balanced_network(value, &mut error);
23906 let details = pio_balanced_network_detailed_connectivity(network);
23907
23908 let mut counts = std::mem::MaybeUninit::<PioDetailedConnectivityCountsView>::uninit();
23909 assert!(pio_detailed_connectivity_counts(
23910 details,
23911 counts.as_mut_ptr(),
23912 &mut error,
23913 ));
23914 let counts = counts.assume_init();
23915 assert_eq!(counts.omitted_fields, 4);
23916 assert_eq!(counts.equipment_reactive_limits, 1);
23917
23918 let mut omitted = std::mem::MaybeUninit::<PioOmittedFieldView>::uninit();
23919 assert!(pio_detailed_connectivity_omitted_field_at(
23920 details,
23921 2,
23922 omitted.as_mut_ptr(),
23923 &mut error,
23924 ));
23925 let omitted = omitted.assume_init();
23926 assert_eq!(view_text(omitted.component.local_id), "G");
23927 assert_eq!(view_text(omitted.field), "voltage_setpoint");
23928
23929 let mut limits = std::mem::MaybeUninit::<PioEquipmentReactiveLimitsView>::uninit();
23930 assert!(pio_detailed_connectivity_equipment_reactive_limits_at(
23931 details,
23932 0,
23933 limits.as_mut_ptr(),
23934 &mut error,
23935 ));
23936 let limits = limits.assume_init();
23937 assert_eq!(view_text(limits.equipment.local_id), "G");
23938 assert_eq!(view_text(limits.limits.kind), "capability_curve");
23939 assert_eq!(limits.limits.property_count, 1);
23940 assert_eq!(limits.limits.point_count, 2);
23941
23942 let mut point = std::mem::MaybeUninit::<PioReactiveCapabilityCurvePointView>::uninit();
23943 assert!(
23944 pio_detailed_connectivity_equipment_reactive_capability_point_at(
23945 details,
23946 0,
23947 0,
23948 point.as_mut_ptr(),
23949 &mut error,
23950 )
23951 );
23952 let point = point.assume_init();
23953 assert_eq!(point.minimum_reactive_power_mvar, -20.0);
23954 assert_eq!(point.property_count, 1);
23955
23956 let mut property = std::mem::MaybeUninit::<PioStringPropertyView>::uninit();
23957 assert!(
23958 pio_detailed_connectivity_equipment_reactive_capability_point_property_at(
23959 details,
23960 0,
23961 0,
23962 0,
23963 property.as_mut_ptr(),
23964 &mut error,
23965 )
23966 );
23967 let property = property.assume_init();
23968 assert_eq!(view_text(property.name), "point");
23969 assert_eq!(view_text(property.value), "first");
23970
23971 let mut generator = std::mem::MaybeUninit::<PioBalancedGeneratorView>::uninit();
23972 assert!(pio_balanced_network_generator_at(
23973 network,
23974 0,
23975 generator.as_mut_ptr(),
23976 &mut error,
23977 ));
23978 assert_eq!(view_text(generator.assume_init().energy_source), "solar");
23979
23980 pio_detailed_connectivity_release(details);
23981 pio_balanced_network_release(network);
23982 pio_value_release(value);
23983 pio_module_release(module);
23984 }
23985 }
23986
23987 #[test]
23988 fn detailed_dc_and_converter_records_are_typed_views() {
23989 const DC: &str = r#"<?xml version="1.0" encoding="UTF-8"?>
23990<iidm:network xmlns:iidm="http://www.powsybl.org/schema/iidm/1_17" id="dc" caseDate="2026-01-01T00:00:00Z" forecastDistance="0" sourceFormat="test" minimumValidationLevel="STEADY_STATE_HYPOTHESIS">
23991 <iidm:dcNode id="N1" nominalV="500" v="498"/><iidm:dcNode id="N2" nominalV="500"/>
23992 <iidm:dcSwitch id="S" dcNode1="N1" dcNode2="N2" kind="DISCONNECTOR" open="true" r="0.9"/>
23993 <iidm:dcGround id="G" dcNode="N1" r="0.1" connected="false"/>
23994 <iidm:dcLine id="L" dcNode1="N1" dcNode2="N2" r="4" connected1="true" connected2="true" dcP1="100" dcI1="200" dcP2="-98" dcI2="-195"/>
23995 <iidm:substation id="SUB"><iidm:voltageLevel id="VL" nominalV="400" topologyKind="BUS_BREAKER">
23996 <iidm:busBreakerTopology><iidm:bus id="B1"/><iidm:bus id="B2"/></iidm:busBreakerTopology>
23997 <iidm:voltageSourceConverter id="VSC" dcNode1="N1" dcConnected1="true" dcNode2="N2" dcConnected2="false" idleLoss="2" switchingLoss="0.2" resistiveLoss="0.000002" controlMode="P_PCC_DROOP" targetP="301" targetVdc="502" bus1="B1" connectableBus1="B1" bus2="B2" connectableBus2="B2" voltageRegulatorOn="true" voltageSetpoint="397"><iidm:pccTerminal id="VSC" number="ONE"/><iidm:droopCurve><iidm:segment minV="-100" maxV="100" k="-5"/></iidm:droopCurve><iidm:reactiveCapabilityCurve><iidm:property name="curve" value="retained"/><iidm:point p="-200" minQ="-190" maxQ="192"><iidm:property name="point" value="one"/></iidm:point><iidm:point p="200" minQ="-189" maxQ="191"/></iidm:reactiveCapabilityCurve></iidm:voltageSourceConverter>
23998 </iidm:voltageLevel></iidm:substation>
23999</iidm:network>"#;
24000
24001 unsafe {
24002 let module = parse_xiidm_text(DC);
24003 let value = pio_module_value(module);
24004 let mut error = std::ptr::null_mut();
24005 let network = pio_value_balanced_network(value, &mut error);
24006 let details = pio_balanced_network_detailed_connectivity(network);
24007
24008 let mut counts = std::mem::MaybeUninit::<PioDetailedConnectivityCountsView>::uninit();
24009 assert!(pio_detailed_connectivity_counts(
24010 details,
24011 counts.as_mut_ptr(),
24012 &mut error,
24013 ));
24014 let counts = counts.assume_init();
24015 assert_eq!(counts.dc_nodes, 2);
24016 assert_eq!(counts.dc_grounds, 1);
24017 assert_eq!(counts.dc_lines, 1);
24018 assert_eq!(counts.dc_switches, 1);
24019 assert_eq!(counts.voltage_source_converters, 1);
24020
24021 let mut line = std::mem::MaybeUninit::<PioDcEquipmentView>::uninit();
24022 assert!(pio_detailed_connectivity_dc_line_at(
24023 details,
24024 0,
24025 line.as_mut_ptr(),
24026 &mut error,
24027 ));
24028 let line = line.assume_init();
24029 assert_eq!(view_text(line.kind), "line");
24030 assert_eq!(line.terminal_count, 2);
24031 assert_eq!(line.resistance_ohm, 4.0);
24032 assert_eq!(line.terminal1.current_a, 200.0);
24033
24034 let mut converter = std::mem::MaybeUninit::<PioAcDcConverterView>::uninit();
24035 assert!(pio_detailed_connectivity_voltage_source_converter_at(
24036 details,
24037 0,
24038 converter.as_mut_ptr(),
24039 &mut error,
24040 ));
24041 let converter = converter.assume_init();
24042 assert_eq!(view_text(converter.kind), "voltage_source");
24043 assert_eq!(
24044 view_text(converter.control_mode),
24045 "active_power_at_pcc_and_dc_voltage_droop_curve"
24046 );
24047 assert!(converter.voltage_regulator_on);
24048 assert_eq!(converter.idle_loss_mw, 2.0);
24049 assert!(converter.has_switching_loss);
24050 assert_eq!(converter.switching_loss_mw_per_ampere, 0.2);
24051 assert!(converter.has_resistive_loss);
24052 assert!(converter.has_pcc_terminal);
24053 assert_eq!(converter.pcc_terminal.terminal, 1);
24054 assert!(converter.has_reactive_limits);
24055 assert_eq!(
24056 view_text(converter.reactive_limits.kind),
24057 "capability_curve"
24058 );
24059 assert_eq!(converter.droop_curve_segment_count, 1);
24060 assert!(converter.has_droop_curve);
24061
24062 let mut segment = std::mem::MaybeUninit::<PioDroopCurveSegmentView>::uninit();
24063 assert!(
24064 pio_detailed_connectivity_voltage_source_converter_droop_curve_segment_at(
24065 details,
24066 0,
24067 0,
24068 segment.as_mut_ptr(),
24069 &mut error,
24070 )
24071 );
24072 let segment = segment.assume_init();
24073 assert_eq!(segment.minimum_voltage_kv, -100.0);
24074 assert_eq!(segment.maximum_voltage_kv, 100.0);
24075 assert_eq!(segment.k, -5.0);
24076
24077 let mut point = std::mem::MaybeUninit::<PioReactiveCapabilityCurvePointView>::uninit();
24078 assert!(
24079 pio_detailed_connectivity_voltage_source_converter_reactive_capability_point_at(
24080 details,
24081 0,
24082 0,
24083 point.as_mut_ptr(),
24084 &mut error,
24085 )
24086 );
24087 let point = point.assume_init();
24088 assert_eq!(point.active_power_mw, -200.0);
24089 assert_eq!(point.property_count, 1);
24090
24091 let base_network = match &PioModule::get(module).unwrap().module.value() {
24092 PioValue::BalancedNetwork(network) => network.clone(),
24093 value => panic!("expected balanced network, got {}", value.type_name()),
24094 };
24095
24096 pio_detailed_connectivity_release(details);
24097 pio_balanced_network_release(network);
24098 pio_value_release(value);
24099 pio_module_release(module);
24100
24101 let mut empty_curve_network = base_network.clone();
24102 std::sync::Arc::make_mut(
24103 empty_curve_network
24104 .detailed_connectivity_mut()
24105 .as_mut()
24106 .unwrap(),
24107 )
24108 .voltage_source_converters[0]
24109 .droop_curve = Some(serde_json::from_str(r#"{"segments":[]}"#).unwrap());
24110 let mut absent_curve_network = base_network;
24111 std::sync::Arc::make_mut(
24112 absent_curve_network
24113 .detailed_connectivity_mut()
24114 .as_mut()
24115 .unwrap(),
24116 )
24117 .voltage_source_converters[0]
24118 .droop_curve = None;
24119
24120 for (network, has_droop_curve) in
24121 [(empty_curve_network, true), (absent_curve_network, false)]
24122 {
24123 let module = module_handle(powerio::PioModule::new(PioValue::from(network)));
24124 let value = pio_module_value(module);
24125 let network = pio_value_balanced_network(value, &mut error);
24126 let details = pio_balanced_network_detailed_connectivity(network);
24127 let mut converter = std::mem::MaybeUninit::<PioAcDcConverterView>::uninit();
24128 assert!(pio_detailed_connectivity_voltage_source_converter_at(
24129 details,
24130 0,
24131 converter.as_mut_ptr(),
24132 &mut error,
24133 ));
24134 let converter = converter.assume_init();
24135 assert_eq!(converter.droop_curve_segment_count, 0);
24136 assert_eq!(converter.has_droop_curve, has_droop_curve);
24137 pio_detailed_connectivity_release(details);
24138 pio_balanced_network_release(network);
24139 pio_value_release(value);
24140 pio_module_release(module);
24141 }
24142 }
24143 }
24144
24145 #[test]
24146 fn balanced_calculation_instances_expose_typed_inputs() {
24147 unsafe {
24148 let network = case9_network();
24149 let dc_pf = powerio_prob::DcPfInstance::from_network(network.clone()).unwrap();
24150 let dc_pf_module =
24151 module_handle(powerio::PioModule::new(PioValue::DcPfInstance(dc_pf)));
24152 let dc_pf_value = pio_module_value(dc_pf_module);
24153 let mut error = std::ptr::null_mut();
24154 let dc_pf = pio_value_dc_pf_instance(dc_pf_value, &mut error);
24155 assert!(!dc_pf.is_null(), "{}", error_text(error));
24156 assert_eq!(pio_dc_pf_instance_bus_specification_count(dc_pf), 9);
24157 assert_eq!(
24158 view_text(pio_dc_pf_instance_branch_susceptance_formula(dc_pf)),
24159 "series_susceptance"
24160 );
24161 assert!(!pio_calculation_instance_has_initial_point(dc_pf));
24162 assert!(pio_calculation_instance_initial_point(dc_pf, &mut error).is_null());
24163 assert!(error.is_null());
24164
24165 let mut reference = std::mem::MaybeUninit::<PioDcBusSpecificationView>::uninit();
24166 assert!(pio_dc_pf_instance_bus_specification_at(
24167 dc_pf,
24168 0,
24169 reference.as_mut_ptr(),
24170 &mut error,
24171 ));
24172 let reference = reference.assume_init();
24173 assert_eq!(reference.bus_id, 1);
24174 assert_eq!(view_text(reference.kind), "reference");
24175 assert_eq!(reference.voltage_angle_degrees, 0.0);
24176
24177 let mut load_bus = std::mem::MaybeUninit::<PioDcBusSpecificationView>::uninit();
24178 assert!(pio_dc_pf_instance_bus_specification_at(
24179 dc_pf,
24180 4,
24181 load_bus.as_mut_ptr(),
24182 &mut error,
24183 ));
24184 let load_bus = load_bus.assume_init();
24185 assert_eq!(load_bus.bus_id, 5);
24186 assert_eq!(view_text(load_bus.kind), "net_active_power");
24187 assert_eq!(load_bus.net_active_power_mw, -90.0);
24188
24189 pio_calculation_instance_release(dc_pf);
24190 pio_value_release(dc_pf_value);
24191 pio_module_release(dc_pf_module);
24192
24193 let initial = powerio_prob::BalancedOperatingPointBuilder::for_point(network.clone())
24194 .bus_voltage_magnitudes(vec![1.01; network.buses().len()])
24195 .build_point()
24196 .unwrap();
24197 let dc_pf = powerio_prob::DcPfInstance::from_network(network.clone())
24198 .unwrap()
24199 .with_initial_point(initial);
24200 let dc_pf_module =
24201 module_handle(powerio::PioModule::new(PioValue::DcPfInstance(dc_pf)));
24202 let dc_pf_value = pio_module_value(dc_pf_module);
24203 let dc_pf = pio_value_dc_pf_instance(dc_pf_value, &mut error);
24204 let initial = pio_calculation_instance_initial_point(dc_pf, &mut error);
24205 assert!(!initial.is_null(), "{}", error_text(error));
24206 assert_eq!(
24207 view_text(pio_operating_point_type_name(initial)),
24208 "powerio.OperatingPoint<powerio.BalancedNetwork>"
24209 );
24210 pio_calculation_instance_release(dc_pf);
24211 pio_value_release(dc_pf_value);
24212 pio_module_release(dc_pf_module);
24213 let mut initial_vm = 0.0;
24214 assert!(pio_operating_point_get_value(
24215 initial,
24216 c"bus_voltage_magnitude".as_ptr(),
24217 "bus_voltage_magnitude".len(),
24218 c"1".as_ptr(),
24219 1,
24220 &mut initial_vm,
24221 &mut error,
24222 ));
24223 assert_eq!(initial_vm, 1.01);
24224 let initial_network = pio_operating_point_balanced_network(initial, &mut error);
24225 assert_eq!(pio_balanced_network_bus_count(initial_network), 9);
24226 pio_balanced_network_release(initial_network);
24227 pio_operating_point_release(initial);
24228
24229 let ac_pf = powerio_prob::AcPfInstance::from_network(network.clone()).unwrap();
24230 let ac_pf_module =
24231 module_handle(powerio::PioModule::new(PioValue::AcPfInstance(ac_pf)));
24232 let ac_pf_value = pio_module_value(ac_pf_module);
24233 let ac_pf = pio_value_ac_pf_instance(ac_pf_value, &mut error);
24234 let mut pv = std::mem::MaybeUninit::<PioAcBusSpecificationView>::uninit();
24235 assert!(pio_ac_pf_instance_bus_specification_at(
24236 ac_pf,
24237 1,
24238 pv.as_mut_ptr(),
24239 &mut error,
24240 ));
24241 let pv = pv.assume_init();
24242 assert_eq!(pv.bus_id, 2);
24243 assert_eq!(view_text(pv.kind), "pv");
24244 assert_eq!(pv.net_active_power_mw, 163.0);
24245 assert_eq!(pv.voltage_magnitude_pu, 1.025);
24246 pio_calculation_instance_release(ac_pf);
24247 pio_value_release(ac_pf_value);
24248 pio_module_release(ac_pf_module);
24249
24250 let dc_opf = powerio_prob::DcOpfInstance::from_network(network).unwrap();
24251 let dc_opf_module =
24252 module_handle(powerio::PioModule::new(PioValue::DcOpfInstance(dc_opf)));
24253 let dc_opf_value = pio_module_value(dc_opf_module);
24254 let dc_opf = pio_value_dc_opf_instance(dc_opf_value, &mut error);
24255 assert_eq!(pio_calculation_instance_objective_term_count(dc_opf), 1);
24256 let mut term = std::mem::MaybeUninit::<PioObjectiveTermView>::uninit();
24257 assert!(pio_calculation_instance_objective_term_at(
24258 dc_opf,
24259 0,
24260 term.as_mut_ptr(),
24261 &mut error,
24262 ));
24263 assert_eq!(view_text(term.assume_init().kind), "network_generator_cost");
24264 assert_eq!(pio_calculation_instance_active_constraint_count(dc_opf), 4);
24265 let mut constraint = std::mem::MaybeUninit::<PioActiveConstraintView>::uninit();
24266 assert!(pio_calculation_instance_active_constraint_at(
24267 dc_opf,
24268 2,
24269 constraint.as_mut_ptr(),
24270 &mut error,
24271 ));
24272 let constraint = constraint.assume_init();
24273 assert_eq!(view_text(constraint.family), "thermal_limits");
24274 assert_eq!(view_text(constraint.selection), "all");
24275 assert_eq!(constraint.identity_count, 0);
24276
24277 pio_calculation_instance_release(dc_opf);
24278 pio_value_release(dc_opf_value);
24279 pio_module_release(dc_opf_module);
24280 }
24281 }
24282
24283 #[test]
24284 fn dc_opf_preparation_rows_keep_their_owner_alive() {
24285 unsafe {
24286 let source_module = parse_case9();
24287 let mut error = std::ptr::null_mut();
24288 let instance_module = pio_module_to_dc_opf_instance(source_module, &mut error);
24289 assert!(!instance_module.is_null(), "{}", error_text(error));
24290 let value = pio_module_value(instance_module);
24291 let instance = pio_value_dc_opf_instance(value, &mut error);
24292 assert!(!instance.is_null(), "{}", error_text(error));
24293 let units = "per_unit";
24294 let preparation = pio_build_dc_opf_preparation(
24295 instance,
24296 units.as_ptr().cast(),
24297 units.len(),
24298 false,
24299 false,
24300 true,
24301 &mut error,
24302 );
24303 assert!(!preparation.is_null(), "{}", error_text(error));
24304
24305 pio_calculation_instance_release(instance);
24306 pio_value_release(value);
24307 pio_module_release(instance_module);
24308 pio_module_release(source_module);
24309
24310 let mut summary = std::mem::MaybeUninit::<PioDcOpfPreparationView>::uninit();
24311 assert!(pio_dc_opf_preparation_summary(
24312 preparation,
24313 summary.as_mut_ptr(),
24314 &mut error,
24315 ));
24316 let summary = summary.assume_init();
24317 assert_eq!(summary.bus_count, 9);
24318 assert_eq!(summary.generator_count, 3);
24319 assert_eq!(summary.branch_count, 9);
24320 assert_eq!(summary.base_mva, 100.0);
24321 assert_eq!(view_text(summary.units), "per_unit");
24322 assert!(summary.correct_angle_difference_bounds);
24323 assert_eq!(
24324 view_text(summary.branch_susceptance_formula),
24325 "series_susceptance"
24326 );
24327 assert_eq!(view_text(summary.objective), "network_generator_cost");
24328
24329 let reference = pio_dc_opf_preparation_reference_buses(preparation);
24330 assert_eq!(
24331 std::slice::from_raw_parts(reference.data, reference.len),
24332 &[0]
24333 );
24334
24335 let mut bus = std::mem::MaybeUninit::<PioDcOpfBusView>::uninit();
24336 assert!(pio_dc_opf_preparation_bus_at(
24337 preparation,
24338 4,
24339 bus.as_mut_ptr(),
24340 &mut error,
24341 ));
24342 let bus = bus.assume_init();
24343 assert_eq!(bus.bus_id, 5);
24344 assert_eq!(bus.active_power_demand, 0.9);
24345 assert_eq!(bus.shunt_conductance, 0.0);
24346 assert_eq!(bus.phase_shift_injection, 0.0);
24347
24348 let mut generator = std::mem::MaybeUninit::<PioDcOpfGeneratorView>::uninit();
24349 assert!(pio_dc_opf_preparation_generator_at(
24350 preparation,
24351 0,
24352 generator.as_mut_ptr(),
24353 &mut error,
24354 ));
24355 let generator = generator.assume_init();
24356 assert_eq!(generator.bus_index, 0);
24357 assert_eq!(generator.quadratic_cost, 2200.0);
24358 assert!(!generator.has_piecewise_linear_cost);
24359
24360 let mut branch = std::mem::MaybeUninit::<PioDcOpfBranchView>::uninit();
24361 assert!(pio_dc_opf_preparation_branch_at(
24362 preparation,
24363 0,
24364 branch.as_mut_ptr(),
24365 &mut error,
24366 ));
24367 let branch = branch.assume_init();
24368 assert_eq!(branch.from_bus_index, 0);
24369 assert_eq!(branch.to_bus_index, 3);
24370 assert!(branch.susceptance_magnitude > 0.0);
24371 assert_eq!(view_text(branch.source_kind), "branch");
24372 assert_eq!(branch.source_row, 0);
24373 assert!(!branch.has_winding);
24374
24375 let mut missing = std::mem::MaybeUninit::<PioDcOpfBusView>::uninit();
24376 assert!(!pio_dc_opf_preparation_bus_at(
24377 preparation,
24378 summary.bus_count,
24379 missing.as_mut_ptr(),
24380 &mut error,
24381 ));
24382 assert_eq!(
24383 view_text(pio_error_code(error)),
24384 "BIND.CAPI.INDEX_OUT_OF_RANGE"
24385 );
24386 pio_error_release(error);
24387 pio_dc_opf_preparation_release(preparation);
24388 }
24389 }
24390
24391 #[test]
24392 fn ac_opf_preparation_rows_keep_their_owner_alive() {
24393 unsafe {
24394 let source_module = parse_case9();
24395 let mut error = std::ptr::null_mut();
24396 let instance_module = pio_module_to_ac_opf_instance(source_module, &mut error);
24397 assert!(!instance_module.is_null(), "{}", error_text(error));
24398 let value = pio_module_value(instance_module);
24399 let instance = pio_value_ac_opf_instance(value, &mut error);
24400 assert!(!instance.is_null(), "{}", error_text(error));
24401 let units = "per_unit";
24402 let preparation = pio_build_ac_opf_preparation(
24403 instance,
24404 units.as_ptr().cast(),
24405 units.len(),
24406 false,
24407 false,
24408 true,
24409 &mut error,
24410 );
24411 assert!(!preparation.is_null(), "{}", error_text(error));
24412
24413 pio_calculation_instance_release(instance);
24414 pio_value_release(value);
24415 pio_module_release(instance_module);
24416 pio_module_release(source_module);
24417
24418 let mut summary = std::mem::MaybeUninit::<PioAcOpfPreparationView>::uninit();
24419 assert!(pio_ac_opf_preparation_summary(
24420 preparation,
24421 summary.as_mut_ptr(),
24422 &mut error,
24423 ));
24424 let summary = summary.assume_init();
24425 assert_eq!(summary.bus_count, 9);
24426 assert_eq!(summary.generator_count, 3);
24427 assert_eq!(summary.branch_count, 9);
24428 assert_eq!(summary.base_mva, 100.0);
24429 assert_eq!(view_text(summary.units), "per_unit");
24430 assert!(summary.correct_angle_difference_bounds);
24431 assert_eq!(view_text(summary.objective), "network_generator_cost");
24432
24433 let reference = pio_ac_opf_preparation_reference_buses(preparation);
24434 assert_eq!(
24435 std::slice::from_raw_parts(reference.data, reference.len),
24436 &[0]
24437 );
24438
24439 let mut bus = std::mem::MaybeUninit::<PioAcOpfBusView>::uninit();
24440 assert!(pio_ac_opf_preparation_bus_at(
24441 preparation,
24442 4,
24443 bus.as_mut_ptr(),
24444 &mut error,
24445 ));
24446 let bus = bus.assume_init();
24447 assert_eq!(bus.bus_id, 5);
24448 assert_eq!(bus.active_power_demand, 0.9);
24449 assert_eq!(bus.reactive_power_demand, 0.3);
24450 assert_eq!(bus.initial_voltage_angle_radians, 0.0);
24451
24452 let mut generator = std::mem::MaybeUninit::<PioAcOpfGeneratorView>::uninit();
24453 assert!(pio_ac_opf_preparation_generator_at(
24454 preparation,
24455 0,
24456 generator.as_mut_ptr(),
24457 &mut error,
24458 ));
24459 let generator = generator.assume_init();
24460 assert_eq!(generator.bus_index, 0);
24461 assert_eq!(generator.initial_active_power, 0.723);
24462 assert_eq!(generator.quadratic_cost, 2200.0);
24463 assert!(!generator.has_piecewise_linear_cost);
24464
24465 let mut branch = std::mem::MaybeUninit::<PioAcOpfBranchView>::uninit();
24466 assert!(pio_ac_opf_preparation_branch_at(
24467 preparation,
24468 0,
24469 branch.as_mut_ptr(),
24470 &mut error,
24471 ));
24472 let branch = branch.assume_init();
24473 assert_eq!(branch.from_bus_index, 0);
24474 assert_eq!(branch.to_bus_index, 3);
24475 assert_eq!(view_text(branch.source_kind), "branch");
24476 assert_eq!(branch.source_row, 0);
24477 assert!(!branch.has_winding);
24478
24479 let mut missing = std::mem::MaybeUninit::<PioAcOpfBusView>::uninit();
24480 assert!(!pio_ac_opf_preparation_bus_at(
24481 preparation,
24482 summary.bus_count,
24483 missing.as_mut_ptr(),
24484 &mut error,
24485 ));
24486 assert_eq!(
24487 view_text(pio_error_code(error)),
24488 "BIND.CAPI.INDEX_OUT_OF_RANGE"
24489 );
24490 pio_error_release(error);
24491 pio_ac_opf_preparation_release(preparation);
24492 }
24493 }
24494
24495 #[test]
24496 fn ac_opf_storage_view_preserves_fields_and_units() {
24497 unsafe {
24498 let mut network = case9_network();
24499 let mut storage = powerio_tx::Storage::new(powerio_tx::BusId(5));
24500 storage.uid = Some("battery".into());
24501 storage.ps = 12.0;
24502 storage.qs = -3.0;
24503 storage.energy = 80.0;
24504 storage.energy_rating = 120.0;
24505 storage.charge_rating = 25.0;
24506 storage.discharge_rating = 30.0;
24507 storage.charge_efficiency = 0.91;
24508 storage.discharge_efficiency = 0.88;
24509 storage.thermal_rating = 35.0;
24510 storage.qmin = -14.0;
24511 storage.qmax = 16.0;
24512 storage.r = 0.001;
24513 storage.x = 0.002;
24514 storage.p_loss = 0.4;
24515 storage.q_loss = 0.5;
24516 network.storage_mut().push(storage);
24517 let instance = powerio_prob::AcOpfInstance::from_network(network).unwrap();
24518 let close = |actual: f64, expected: f64| assert!((actual - expected).abs() < 1e-12);
24519
24520 for (units, power_scale) in [(Units::PerUnit, 0.01), (Units::Native, 1.0)] {
24521 let prepared = build_ac_opf_preparation(
24522 &instance,
24523 &AcOpfAssemblyOptions::default().with_units(units),
24524 )
24525 .unwrap();
24526 let preparation = PioAcOpfPreparation::new_raw(prepared);
24527 let mut error = std::ptr::null_mut();
24528 let mut summary = std::mem::MaybeUninit::<PioAcOpfPreparationView>::uninit();
24529 assert!(pio_ac_opf_preparation_summary(
24530 preparation,
24531 summary.as_mut_ptr(),
24532 &mut error,
24533 ));
24534 assert_eq!(summary.assume_init().storage_count, 1);
24535
24536 let mut row = std::mem::MaybeUninit::<PioAcOpfStorageView>::uninit();
24537 assert!(pio_ac_opf_preparation_storage_at(
24538 preparation,
24539 0,
24540 row.as_mut_ptr(),
24541 &mut error,
24542 ));
24543 let row = row.assume_init();
24544 assert_eq!(view_text(row.component_id), "battery");
24545 assert_eq!(row.bus_index, 4);
24546 assert_eq!(row.source_row, 0);
24547 close(row.initial_active_power, 12.0 * power_scale);
24548 close(row.initial_reactive_power, -3.0 * power_scale);
24549 close(row.energy, 80.0 * power_scale);
24550 close(row.energy_rating, 120.0 * power_scale);
24551 close(row.charge_rating, 25.0 * power_scale);
24552 close(row.discharge_rating, 30.0 * power_scale);
24553 assert_eq!(row.charge_efficiency, 0.91);
24554 assert_eq!(row.discharge_efficiency, 0.88);
24555 close(row.apparent_power_max, 35.0 * power_scale);
24556 close(row.reactive_power_min, -14.0 * power_scale);
24557 close(row.reactive_power_max, 16.0 * power_scale);
24558 assert_eq!(row.resistance_pu, 0.001);
24559 assert_eq!(row.reactance_pu, 0.002);
24560 close(row.active_power_loss, 0.4 * power_scale);
24561 close(row.reactive_power_loss, 0.5 * power_scale);
24562 assert!(row.in_service);
24563
24564 pio_ac_opf_preparation_release(preparation);
24565 }
24566 }
24567 }
24568
24569 #[test]
24570 fn module_transforms_build_typed_calculation_modules() {
24571 unsafe {
24572 type Transform =
24573 unsafe extern "C" fn(*const PioModule, *mut *mut PioError) -> *mut PioModule;
24574 let source = parse_case9();
24575 let operations: [(Transform, &str, &str); 4] = [
24576 (
24577 pio_module_to_dc_pf_instance,
24578 "powerio.DcPfInstance",
24579 "to_dc_pf_instance",
24580 ),
24581 (
24582 pio_module_to_ac_pf_instance,
24583 "powerio.AcPfInstance",
24584 "to_ac_pf_instance",
24585 ),
24586 (
24587 pio_module_to_dc_opf_instance,
24588 "powerio.DcOpfInstance",
24589 "to_dc_opf_instance",
24590 ),
24591 (
24592 pio_module_to_ac_opf_instance,
24593 "powerio.AcOpfInstance",
24594 "to_ac_opf_instance",
24595 ),
24596 ];
24597 for (operation, expected_type, expected_history) in operations {
24598 let mut error = std::ptr::null_mut();
24599 let derived = operation(source, &mut error);
24600 assert!(!derived.is_null(), "{}", error_text(error));
24601 let value = pio_module_value(derived);
24602 assert!(pio_value_is_type(
24603 value,
24604 expected_type.as_ptr().cast(),
24605 expected_type.len(),
24606 ));
24607 let derived_module = &PioModule::get(derived).unwrap().module;
24608 assert_eq!(
24609 derived_module.history().last().unwrap().name(),
24610 expected_history
24611 );
24612 assert!(derived_module.source().is_none());
24613 pio_value_release(value);
24614 pio_module_release(derived);
24615 }
24616
24617 let mut error = std::ptr::null_mut();
24618 let instance = pio_module_to_dc_pf_instance(source, &mut error);
24619 let invalid = pio_module_to_ac_pf_instance(instance, &mut error);
24620 assert!(invalid.is_null());
24621 assert_eq!(
24622 view_text(pio_error_code(error)),
24623 "REQUEST.MODULE.WRONG_MODEL_KIND"
24624 );
24625 pio_error_release(error);
24626 pio_module_release(instance);
24627 pio_module_release(source);
24628 }
24629 }
24630
24631 #[test]
24632 fn multiconductor_module_transforms_build_typed_calculation_modules() {
24633 unsafe {
24634 let source = parse_bmopf();
24635 let value = pio_module_value(source);
24636 let network_type = "powerio.MulticonductorNetwork";
24637 assert!(pio_value_is_type(
24638 value,
24639 network_type.as_ptr().cast(),
24640 network_type.len(),
24641 ));
24642 pio_value_release(value);
24643
24644 type Transform =
24645 unsafe extern "C" fn(*const PioModule, *mut *mut PioError) -> *mut PioModule;
24646 let operations: [(Transform, &str, &str); 2] = [
24647 (
24648 pio_module_to_mc_ac_pf_instance,
24649 "powerio.McAcPfInstance",
24650 "to_mc_ac_pf_instance",
24651 ),
24652 (
24653 pio_module_to_mc_ac_opf_instance,
24654 "powerio.McAcOpfInstance",
24655 "to_mc_ac_opf_instance",
24656 ),
24657 ];
24658 for (operation, expected_type, expected_history) in operations {
24659 let mut error = std::ptr::null_mut();
24660 let derived = operation(source, &mut error);
24661 assert!(!derived.is_null(), "{}", error_text(error));
24662 let value = pio_module_value(derived);
24663 assert!(pio_value_is_type(
24664 value,
24665 expected_type.as_ptr().cast(),
24666 expected_type.len(),
24667 ));
24668 let derived_module = &PioModule::get(derived).unwrap().module;
24669 assert_eq!(
24670 derived_module.history().last().unwrap().name(),
24671 expected_history
24672 );
24673 assert!(derived_module.source().is_none());
24674 pio_value_release(value);
24675 pio_module_release(derived);
24676 }
24677 pio_module_release(source);
24678 }
24679 }
24680
24681 #[test]
24682 fn geo_layer_derives_a_new_network_module() {
24683 unsafe {
24684 let source_module = parse_case9();
24685 let geojson = br#"{
24686 "type": "FeatureCollection",
24687 "features": [{
24688 "type": "Feature",
24689 "geometry": {
24690 "type": "Point",
24691 "coordinates": [-83.743, 42.281]
24692 },
24693 "properties": {"bus": "1"}
24694 }]
24695 }"#;
24696 let mut error = std::ptr::null_mut();
24697 let source = pio_source_from_memory(
24698 c"case9.geojson".as_ptr(),
24699 "case9.geojson".len(),
24700 geojson.as_ptr(),
24701 geojson.len(),
24702 &mut error,
24703 );
24704 assert!(!source.is_null(), "{}", error_text(error));
24705 let layer = pio_geo_layer_parse(source, &mut error);
24706 pio_source_release(source);
24707 assert!(!layer.is_null(), "{}", error_text(error));
24708
24709 let diagnostics = pio_geo_layer_diagnostics(layer);
24710 assert_eq!(pio_diagnostics_len(diagnostics), 0);
24711 pio_diagnostics_release(diagnostics);
24712
24713 let mut report = std::ptr::null_mut();
24714 let derived = pio_module_apply_geo_layer(source_module, layer, &mut report, &mut error);
24715 assert!(!derived.is_null(), "{}", error_text(error));
24716 assert!(!report.is_null());
24717 assert_eq!(pio_geo_apply_report_matched_buses(report), 1);
24718 assert_eq!(pio_geo_apply_report_matched_branches(report), 0);
24719 assert_eq!(pio_geo_apply_report_unmatched_features(report), 0);
24720 assert_eq!(pio_geo_apply_report_unlocated_buses(report), 8);
24721 assert_eq!(pio_geo_apply_report_unlocated_branches(report), 9);
24722
24723 let note_count = pio_geo_apply_report_note_count(report);
24724 let note = pio_geo_apply_report_note_at(report, note_count, &mut error);
24725 assert_eq!(note.len, 0);
24726 assert_eq!(
24727 view_text(pio_error_code(error)),
24728 "BIND.CAPI.INDEX_OUT_OF_RANGE"
24729 );
24730 pio_error_release(error);
24731 error = std::ptr::null_mut();
24732
24733 let derived_module = &PioModule::get(derived).unwrap().module;
24734 assert!(derived_module.source().is_none());
24735 assert_eq!(
24736 derived_module.history().last().unwrap().name(),
24737 "apply_geo_layer"
24738 );
24739 let PioValue::BalancedNetwork(derived_network) = &derived_module.value() else {
24740 panic!("geo application changed the value type")
24741 };
24742 let derived_location = derived_network
24743 .buses()
24744 .iter()
24745 .find(|bus| bus.id == powerio_tx::BusId(1))
24746 .and_then(|bus| bus.location)
24747 .unwrap();
24748 assert_eq!((derived_location.x, derived_location.y), (-83.743, 42.281));
24749
24750 let original_module = &PioModule::get(source_module).unwrap().module;
24751 let PioValue::BalancedNetwork(original_network) = &original_module.value() else {
24752 unreachable!()
24753 };
24754 assert!(
24755 original_network
24756 .buses()
24757 .iter()
24758 .find(|bus| bus.id == powerio_tx::BusId(1))
24759 .unwrap()
24760 .location
24761 .is_none()
24762 );
24763
24764 let calculation = pio_module_to_dc_pf_instance(source_module, &mut error);
24765 assert!(!calculation.is_null(), "{}", error_text(error));
24766 let rejected =
24767 pio_module_apply_geo_layer(calculation, layer, std::ptr::null_mut(), &mut error);
24768 assert!(rejected.is_null());
24769 assert_eq!(
24770 view_text(pio_error_code(error)),
24771 "REQUEST.MODULE.WRONG_MODEL_KIND"
24772 );
24773 pio_error_release(error);
24774
24775 pio_module_release(calculation);
24776 pio_geo_apply_report_release(report);
24777 pio_geo_layer_release(layer);
24778 pio_module_release(derived);
24779 pio_module_release(source_module);
24780 }
24781 }
24782
24783 #[test]
24784 fn a_geo_layer_writes_the_canonical_document_it_parses_back() {
24785 unsafe {
24786 let document = br#"{
24787 "type": "FeatureCollection",
24788 "features": [{
24789 "type": "Feature",
24790 "geometry": {
24791 "type": "Point",
24792 "coordinates": [-83.743, 42.281]
24793 },
24794 "properties": {"bus": "1"}
24795 }]
24796 }"#;
24797 let mut error = std::ptr::null_mut();
24798 let source = pio_source_from_memory(
24799 c"case9.geojson".as_ptr(),
24800 "case9.geojson".len(),
24801 document.as_ptr(),
24802 document.len(),
24803 &mut error,
24804 );
24805 assert!(!source.is_null(), "{}", error_text(error));
24806 let layer = pio_geo_layer_parse(source, &mut error);
24807 pio_source_release(source);
24808 assert!(!layer.is_null(), "{}", error_text(error));
24809
24810 let written = pio_geo_layer_to_geojson(layer, &mut error);
24811 assert!(!written.is_null(), "{}", error_text(error));
24812 let written_text = view_text(pio_string_view(written));
24813 pio_string_release(written);
24814 assert!(written_text.contains("FeatureCollection"), "{written_text}");
24815 assert!(written_text.contains("powerio_geo"), "{written_text}");
24816
24817 let echo_source = pio_source_from_memory(
24820 c"case9.geo.json".as_ptr(),
24821 "case9.geo.json".len(),
24822 written_text.as_ptr(),
24823 written_text.len(),
24824 &mut error,
24825 );
24826 assert!(!echo_source.is_null(), "{}", error_text(error));
24827 let echo = pio_geo_layer_parse(echo_source, &mut error);
24828 pio_source_release(echo_source);
24829 assert!(!echo.is_null(), "{}", error_text(error));
24830 let again = pio_geo_layer_to_geojson(echo, &mut error);
24831 assert!(!again.is_null(), "{}", error_text(error));
24832 assert_eq!(view_text(pio_string_view(again)), written_text);
24833 pio_string_release(again);
24834 pio_geo_layer_release(echo);
24835
24836 let missing = pio_geo_layer_to_geojson(std::ptr::null(), &mut error);
24837 assert!(missing.is_null());
24838 assert_eq!(view_text(pio_error_code(error)), "BIND.CAPI.NULL_HANDLE");
24839 pio_error_release(error);
24840
24841 pio_geo_layer_release(layer);
24842 }
24843 }
24844
24845 unsafe fn contingency_fixture(name: &str) -> std::path::PathBuf {
24846 std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
24847 .join("../tests/data/psse/contingency")
24848 .join(name)
24849 }
24850
24851 unsafe fn parse_contingency_fixture(name: &str) -> *mut PioModule {
24852 let path = unsafe { contingency_fixture(name) };
24853 let path = path.to_string_lossy();
24854 let mut error = std::ptr::null_mut();
24855 let source = unsafe { pio_source_open(path.as_ptr().cast(), path.len(), &mut error) };
24856 assert!(!source.is_null(), "{}", unsafe { error_text(error) });
24857 let module = unsafe { pio_parse(source, std::ptr::null(), 0, &mut error) };
24858 unsafe { pio_source_release(source) };
24859 assert!(!module.is_null(), "{name}: {}", unsafe {
24860 error_text(error)
24861 });
24862 module
24863 }
24864
24865 unsafe fn reread_contingency_text(name: &str, format: &str, text: &str) -> *mut PioModule {
24868 let mut error = std::ptr::null_mut();
24869 let source = unsafe {
24870 pio_source_from_memory(
24871 name.as_ptr().cast(),
24872 name.len(),
24873 text.as_ptr(),
24874 text.len(),
24875 &mut error,
24876 )
24877 };
24878 assert!(!source.is_null(), "{}", unsafe { error_text(error) });
24879 let module = unsafe { pio_parse(source, format.as_ptr().cast(), format.len(), &mut error) };
24880 unsafe { pio_source_release(source) };
24881 assert!(!module.is_null(), "{name}: {}", unsafe {
24882 error_text(error)
24883 });
24884 module
24885 }
24886
24887 unsafe fn contingency_network(name: &str) -> (*mut PioModule, *mut PioBalancedNetwork) {
24890 let module = unsafe { parse_contingency_fixture(name) };
24891 let mut error = std::ptr::null_mut();
24892 let value = unsafe { pio_module_value(module) };
24893 let network = unsafe { pio_value_balanced_network(value, &mut error) };
24894 assert!(!network.is_null(), "{}", unsafe { error_text(error) });
24895 unsafe { pio_value_release(value) };
24896 (module, network)
24897 }
24898
24899 #[test]
24900 fn a_contingency_set_binds_every_case_to_the_network_it_names() {
24901 unsafe {
24902 let path = contingency_fixture("resolve_cases.con");
24903 let path_text = path.to_string_lossy();
24904 let mut error = std::ptr::null_mut();
24905 let source = pio_source_open(path_text.as_ptr().cast(), path_text.len(), &mut error);
24906 assert!(!source.is_null(), "{}", error_text(error));
24907 let set = pio_contingency_set_parse(source, &mut error);
24908 pio_source_release(source);
24909 assert!(!set.is_null(), "{}", error_text(error));
24910
24911 assert_eq!(pio_contingency_set_case_count(set), 20);
24912 assert_eq!(
24913 view_text(pio_contingency_set_case_name(set, 0, &mut error)),
24914 "BR_1_2_C1"
24915 );
24916 let past_end = pio_contingency_set_case_name(set, 20, &mut error);
24917 assert_eq!(past_end.len, 0);
24918 assert_eq!(
24919 view_text(pio_error_code(error)),
24920 "BIND.CAPI.INDEX_OUT_OF_RANGE"
24921 );
24922 pio_error_release(error);
24923 error = std::ptr::null_mut();
24924
24925 let notes = pio_contingency_set_diagnostics(set);
24928 assert!(pio_diagnostics_len(notes) > 0);
24929 pio_diagnostics_release(notes);
24930
24931 let (module, network) = contingency_network("resolve_v33.raw");
24932 let resolution = pio_contingency_set_resolve(set, network, &mut error);
24933 assert!(!resolution.is_null(), "{}", error_text(error));
24934
24935 assert_eq!(pio_contingency_resolution_case_count(resolution), 20);
24936 assert_eq!(pio_contingency_resolution_resolved_count(resolution), 17);
24937 assert_eq!(pio_contingency_resolution_unresolved_count(resolution), 3);
24938 assert_eq!(
24939 pio_contingency_resolution_unrecognized_statement_count(resolution),
24940 1
24941 );
24942
24943 assert!(pio_contingency_resolution_case_is_resolved(resolution, 0));
24945 assert_eq!(
24946 view_text(pio_contingency_resolution_case_name(
24947 resolution, 0, &mut error
24948 )),
24949 "BR_1_2_C1"
24950 );
24951 assert_eq!(
24952 pio_contingency_resolution_case_component_count(resolution, 0),
24953 1
24954 );
24955 let mut component = std::mem::MaybeUninit::<PioContingencyComponentView>::uninit();
24956 assert!(pio_contingency_resolution_case_component(
24957 resolution,
24958 0,
24959 0,
24960 component.as_mut_ptr(),
24961 &mut error,
24962 ));
24963 let component = component.assume_init();
24964 assert_eq!(view_text(component.id.component_type), "branch");
24965 assert!(component.in_service);
24966 assert_eq!(
24967 pio_contingency_resolution_case_unresolved_count(resolution, 0),
24968 0
24969 );
24970
24971 let unresolved: Vec<(String, String, String)> = (0
24974 ..pio_contingency_resolution_case_count(resolution))
24975 .filter(|index| !pio_contingency_resolution_case_is_resolved(resolution, *index))
24976 .map(|index| {
24977 assert_eq!(
24978 pio_contingency_resolution_case_unresolved_count(resolution, index),
24979 1
24980 );
24981 (
24982 view_text(pio_contingency_resolution_case_name(
24983 resolution, index, &mut error,
24984 )),
24985 view_text(pio_contingency_resolution_case_unresolved_reason(
24986 resolution, index, 0, &mut error,
24987 )),
24988 view_text(pio_contingency_resolution_case_unresolved_action(
24989 resolution, index, 0, &mut error,
24990 )),
24991 )
24992 })
24993 .collect();
24994 assert_eq!(
24995 unresolved,
24996 vec![
24997 (
24998 "BR_MISSING".to_owned(),
24999 "no_such_branch".to_owned(),
25000 "OPEN LINE FROM BUS 3 TO BUS 4 CIRCUIT 1".to_owned(),
25001 ),
25002 (
25003 "MACHINE_MISSING".to_owned(),
25004 "no_such_machine".to_owned(),
25005 "REMOVE MACHINE 9 FROM BUS 1".to_owned(),
25006 ),
25007 (
25008 "UNRECOGNIZED".to_owned(),
25009 "unrecognized".to_owned(),
25010 "PARALLEL BRANCH FROM BUS 1 TO BUS 2".to_owned(),
25011 ),
25012 ]
25013 );
25014 let past_end =
25015 pio_contingency_resolution_case_unresolved_action(resolution, 0, 0, &mut error);
25016 assert_eq!(past_end.len, 0);
25017 assert_eq!(
25018 view_text(pio_error_code(error)),
25019 "BIND.CAPI.INDEX_OUT_OF_RANGE"
25020 );
25021 pio_error_release(error);
25022 error = std::ptr::null_mut();
25023
25024 let written = pio_contingency_set_to_con(set, &mut error);
25027 assert!(!written.is_null(), "{}", error_text(error));
25028 let written_text = view_text(pio_string_view(written));
25029 pio_string_release(written);
25030 assert!(
25031 written_text.contains(
25032 "CONTINGENCY 'BR_MISSING'\nOPEN LINE FROM BUS 3 TO BUS 4 CIRCUIT 1\nEND\n"
25033 ),
25034 "{written_text}"
25035 );
25036 let echo = pio_source_from_memory(
25037 c"written.con".as_ptr(),
25038 "written.con".len(),
25039 written_text.as_ptr(),
25040 written_text.len(),
25041 &mut error,
25042 );
25043 assert!(!echo.is_null(), "{}", error_text(error));
25044 let again = pio_contingency_set_parse(echo, &mut error);
25045 pio_source_release(echo);
25046 assert!(!again.is_null(), "{}", error_text(error));
25047 assert_eq!(pio_contingency_set_case_count(again), 20);
25048 assert_eq!(
25049 view_text(pio_contingency_set_case_name(again, 19, &mut error)),
25050 "UNRECOGNIZED"
25051 );
25052 pio_contingency_set_release(again);
25053
25054 let retained = pio_contingency_resolution_retain(resolution);
25056 pio_contingency_resolution_release(retained);
25057 assert_eq!(pio_contingency_resolution_case_count(resolution), 20);
25058 let retained_set = pio_contingency_set_retain(set);
25059 pio_contingency_set_release(retained_set);
25060 assert_eq!(pio_contingency_set_case_count(set), 20);
25061
25062 pio_contingency_resolution_release(resolution);
25063 pio_balanced_network_release(network);
25064 pio_module_release(module);
25065 pio_contingency_set_release(set);
25066 }
25067 }
25068
25069 #[test]
25075 fn a_bound_component_states_its_table_and_an_optional_identity() {
25076 unsafe {
25077 let mut error = std::ptr::null_mut();
25078 let module = parse_contingency_fixture("resolve_v33.raw");
25079 let destination = pio_destination_memory(
25080 c"network.pio.json".as_ptr(),
25081 "network.pio.json".len(),
25082 &mut error,
25083 );
25084 assert!(!destination.is_null(), "{}", error_text(error));
25085 let result = pio_module_serialize(module, destination, &mut error);
25086 assert!(!result.is_null(), "{}", error_text(error));
25087 let artifact = pio_emit_result_artifact(result, 0, &mut error);
25088 assert!(!artifact.is_null(), "{}", error_text(error));
25089 let bytes = pio_artifact_bytes(artifact);
25090 let mut document: serde_json::Value =
25091 serde_json::from_slice(std::slice::from_raw_parts(bytes.data, bytes.len)).unwrap();
25092 let loads = document["value"]["data"]["loads"].as_array_mut().unwrap();
25093 assert_eq!(loads.len(), 2);
25094 for load in loads {
25095 load["uid"] = serde_json::Value::String(String::new());
25096 }
25097 let rewritten = serde_json::to_vec(&document).unwrap();
25098 pio_artifact_release(artifact);
25099 pio_emit_result_release(result);
25100 pio_destination_release(destination);
25101 pio_module_release(module);
25102
25103 let source = pio_source_from_memory(
25104 c"network.pio.json".as_ptr(),
25105 "network.pio.json".len(),
25106 rewritten.as_ptr(),
25107 rewritten.len(),
25108 &mut error,
25109 );
25110 assert!(!source.is_null(), "{}", error_text(error));
25111 let decoded = pio_module_deserialize(source, &mut error);
25112 pio_source_release(source);
25113 assert!(!decoded.is_null(), "{}", error_text(error));
25114 let value = pio_module_value(decoded);
25115 let network = pio_value_balanced_network(value, &mut error);
25116 assert!(!network.is_null(), "{}", error_text(error));
25117 pio_value_release(value);
25118
25119 let path = contingency_fixture("resolve_cases.con");
25120 let path_text = path.to_string_lossy();
25121 let cases = pio_source_open(path_text.as_ptr().cast(), path_text.len(), &mut error);
25122 assert!(!cases.is_null(), "{}", error_text(error));
25123 let set = pio_contingency_set_parse(cases, &mut error);
25124 pio_source_release(cases);
25125 assert!(!set.is_null(), "{}", error_text(error));
25126 let resolution = pio_contingency_set_resolve(set, network, &mut error);
25127 assert!(!resolution.is_null(), "{}", error_text(error));
25128
25129 let case_of = |name: &str| {
25130 let mut case_error = std::ptr::null_mut();
25131 (0..pio_contingency_resolution_case_count(resolution))
25132 .find(|index| {
25133 view_text(pio_contingency_resolution_case_name(
25134 resolution,
25135 *index,
25136 &mut case_error,
25137 )) == name
25138 })
25139 .unwrap_or_else(|| panic!("the fixture states a case named {name}"))
25140 };
25141 let read = |case_index: usize, component_index: usize| {
25142 let mut component = std::mem::MaybeUninit::<PioContingencyComponentView>::uninit();
25143 let mut read_error = std::ptr::null_mut();
25144 assert!(
25145 pio_contingency_resolution_case_component(
25146 resolution,
25147 case_index,
25148 component_index,
25149 component.as_mut_ptr(),
25150 &mut read_error,
25151 ),
25152 "{}",
25153 error_text(read_error)
25154 );
25155 component.assume_init()
25156 };
25157
25158 let loads_at_bus = case_of("LOADS_AT_BUS");
25161 assert_eq!(
25162 pio_contingency_resolution_case_component_count(resolution, loads_at_bus),
25163 2
25164 );
25165 for row in 0..2 {
25166 let component = read(loads_at_bus, row);
25167 assert_eq!(view_text(component.id.component_type), "load");
25168 assert_eq!(component.id.local_id.len, 0);
25169 assert_eq!(component.row, row);
25170 assert!(component.in_service);
25171 }
25172
25173 let branch = read(case_of("BR_1_2_C1"), 0);
25176 assert_eq!(view_text(branch.id.component_type), "branch");
25177 assert_eq!(view_text(branch.id.local_id), "1-2");
25178
25179 pio_contingency_resolution_release(resolution);
25180 pio_contingency_set_release(set);
25181 pio_balanced_network_release(network);
25182 pio_module_release(decoded);
25183 }
25184 }
25185
25186 #[test]
25187 fn an_automatic_specification_expands_against_a_subsystem_set() {
25188 unsafe {
25189 let mut error = std::ptr::null_mut();
25190 let cases_module = parse_contingency_fixture("expand.con");
25191 let cases_value = pio_module_value(cases_module);
25192 assert!(pio_value_is_type(
25193 cases_value,
25194 c"powerio.ContingencySet".as_ptr().cast(),
25195 "powerio.ContingencySet".len(),
25196 ));
25197 let set = pio_value_contingency_set(cases_value, &mut error);
25198 assert!(!set.is_null(), "{}", error_text(error));
25199 let notes = pio_contingency_set_diagnostics(set);
25201 assert_eq!(pio_diagnostics_len(notes), 0);
25202 pio_diagnostics_release(notes);
25203
25204 let wrong = pio_value_subsystem_set(cases_value, &mut error);
25206 assert!(wrong.is_null());
25207 assert_eq!(
25208 view_text(pio_error_code(error)),
25209 "REQUEST.CAPI.TYPE_MISMATCH"
25210 );
25211 pio_error_release(error);
25212 error = std::ptr::null_mut();
25213 pio_value_release(cases_value);
25214
25215 pio_module_release(cases_module);
25218 assert_eq!(pio_contingency_set_case_count(set), 1);
25219 let written = pio_contingency_set_to_con(set, &mut error);
25220 assert!(!written.is_null(), "{}", error_text(error));
25221 let written_text = view_text(pio_string_view(written));
25222 assert!(
25223 written_text.contains("CONTINGENCY 'EXPLICIT'"),
25224 "{written_text}"
25225 );
25226 assert!(
25227 written_text.contains("SINGLE BRANCH IN SUBSYSTEM 'NOSUCH'"),
25228 "{written_text}"
25229 );
25230 pio_string_release(written);
25231
25232 let sub_module = parse_contingency_fixture("selectors.sub");
25233 let sub_value = pio_module_value(sub_module);
25234 let subsystems = pio_value_subsystem_set(sub_value, &mut error);
25235 assert!(!subsystems.is_null(), "{}", error_text(error));
25236 pio_value_release(sub_value);
25237 assert_eq!(pio_subsystem_set_count(subsystems), 10);
25238 assert_eq!(
25239 view_text(pio_subsystem_set_name(subsystems, 0, &mut error)),
25240 "A1"
25241 );
25242 let written = pio_subsystem_set_to_sub(subsystems, &mut error);
25243 assert!(!written.is_null(), "{}", error_text(error));
25244 let written_text = view_text(pio_string_view(written));
25245 pio_string_release(written);
25246 let echo = reread_contingency_text("written.sub", "psse-sub", &written_text);
25247 let echo_value = pio_module_value(echo);
25248 let again = pio_value_subsystem_set(echo_value, &mut error);
25249 assert!(!again.is_null(), "{}", error_text(error));
25250 pio_value_release(echo_value);
25251 assert_eq!(pio_subsystem_set_count(again), 10);
25252 assert_eq!(
25253 view_text(pio_subsystem_set_name(again, 7, &mut error)),
25254 "BAREJOIN"
25255 );
25256 pio_subsystem_set_release(again);
25257 pio_module_release(echo);
25258
25259 let (network_module, network) = contingency_network("select_v33.raw");
25260 let mut expansion_notes = std::ptr::null_mut();
25261 let expanded = pio_contingency_set_expand(
25262 set,
25263 network,
25264 subsystems,
25265 &mut expansion_notes,
25266 &mut error,
25267 );
25268 assert!(!expanded.is_null(), "{}", error_text(error));
25269 assert_eq!(pio_contingency_set_case_count(expanded), 8);
25270 let written = pio_contingency_set_to_con(expanded, &mut error);
25272 assert!(!written.is_null(), "{}", error_text(error));
25273 assert!(
25274 view_text(pio_string_view(written)).contains("CONTINGENCY 'T_101_102_103_1'"),
25275 "the expanded text states every generated case"
25276 );
25277 pio_string_release(written);
25278 assert_eq!(
25279 view_text(pio_contingency_set_case_name(expanded, 0, &mut error)),
25280 "EXPLICIT"
25281 );
25282 assert_eq!(
25283 view_text(pio_contingency_set_case_name(expanded, 3, &mut error)),
25284 "T_101_102_103_1"
25285 );
25286 assert_eq!(pio_diagnostics_len(expansion_notes), 1);
25289 pio_diagnostics_release(expansion_notes);
25290
25291 let monitored_module = parse_contingency_fixture("generated.mon");
25292 let monitored_value = pio_module_value(monitored_module);
25293 let monitored = pio_value_monitored_set(monitored_value, &mut error);
25294 assert!(!monitored.is_null(), "{}", error_text(error));
25295 pio_value_release(monitored_value);
25296 assert_eq!(pio_monitored_set_statement_count(monitored), 12);
25297 let written = pio_monitored_set_to_mon(monitored, &mut error);
25298 assert!(!written.is_null(), "{}", error_text(error));
25299 let written_text = view_text(pio_string_view(written));
25300 pio_string_release(written);
25301 let echo = reread_contingency_text("written.mon", "psse-mon", &written_text);
25302 let echo_value = pio_module_value(echo);
25303 let again = pio_value_monitored_set(echo_value, &mut error);
25304 assert!(!again.is_null(), "{}", error_text(error));
25305 pio_value_release(echo_value);
25306 assert_eq!(pio_monitored_set_statement_count(again), 12);
25307 pio_monitored_set_release(again);
25308 pio_module_release(echo);
25309
25310 pio_monitored_set_release(monitored);
25311 pio_module_release(monitored_module);
25312 pio_contingency_set_release(expanded);
25313 pio_balanced_network_release(network);
25314 pio_module_release(network_module);
25315 pio_subsystem_set_release(subsystems);
25316 pio_module_release(sub_module);
25317 pio_contingency_set_release(set);
25318 }
25319 }
25320
25321 #[test]
25322 fn a_named_subsystem_selects_the_buses_of_one_network() {
25323 unsafe {
25324 let mut error = std::ptr::null_mut();
25325 let (network_module, network) = contingency_network("select_v33.raw");
25326 let sub_module = parse_contingency_fixture("selectors.sub");
25327 let sub_value = pio_module_value(sub_module);
25328 let subsystems = pio_value_subsystem_set(sub_value, &mut error);
25329 assert!(!subsystems.is_null(), "{}", error_text(error));
25330 pio_value_release(sub_value);
25331 pio_module_release(sub_module);
25334
25335 for (name, expected) in [
25336 ("A1", &[101.0, 102.0, 103.0][..]),
25337 ("AREARANGE", &[101.0, 102.0, 103.0, 201.0, 202.0][..]),
25338 ("KV", &[101.0, 102.0, 103.0, 201.0][..]),
25339 (" a1 ", &[101.0, 102.0, 103.0][..]),
25342 ] {
25343 let selected = pio_balanced_network_select_subsystem_buses(
25344 network,
25345 subsystems,
25346 name.as_ptr().cast(),
25347 name.len(),
25348 &mut error,
25349 );
25350 assert!(!selected.is_null(), "{name}: {}", error_text(error));
25351 let values = pio_vector_values(selected);
25352 assert_eq!(
25353 std::slice::from_raw_parts(values.data, values.len),
25354 expected,
25355 "{name}"
25356 );
25357 pio_vector_release(selected);
25358 }
25359
25360 let unknown = pio_balanced_network_select_subsystem_buses(
25361 network,
25362 subsystems,
25363 c"NOSUCH".as_ptr(),
25364 "NOSUCH".len(),
25365 &mut error,
25366 );
25367 assert!(unknown.is_null());
25368 assert_eq!(
25369 view_text(pio_error_code(error)),
25370 "BIND.CAPI.INDEX_OUT_OF_RANGE"
25371 );
25372 pio_error_release(error);
25373 error = std::ptr::null_mut();
25374
25375 let no_network = pio_balanced_network_select_subsystem_buses(
25376 std::ptr::null(),
25377 subsystems,
25378 c"A1".as_ptr(),
25379 "A1".len(),
25380 &mut error,
25381 );
25382 assert!(no_network.is_null());
25383 assert_eq!(view_text(pio_error_code(error)), "BIND.CAPI.NULL_HANDLE");
25384 pio_error_release(error);
25385 error = std::ptr::null_mut();
25386
25387 let no_subsystems = pio_balanced_network_select_subsystem_buses(
25388 network,
25389 std::ptr::null(),
25390 c"A1".as_ptr(),
25391 "A1".len(),
25392 &mut error,
25393 );
25394 assert!(no_subsystems.is_null());
25395 assert_eq!(view_text(pio_error_code(error)), "BIND.CAPI.NULL_HANDLE");
25396 pio_error_release(error);
25397 error = std::ptr::null_mut();
25398
25399 let no_name = pio_balanced_network_select_subsystem_buses(
25400 network,
25401 subsystems,
25402 std::ptr::null(),
25403 0,
25404 &mut error,
25405 );
25406 assert!(no_name.is_null());
25407 assert_eq!(view_text(pio_error_code(error)), "BIND.CAPI.NULL_ARGUMENT");
25408 pio_error_release(error);
25409
25410 pio_subsystem_set_release(subsystems);
25411 pio_balanced_network_release(network);
25412 pio_module_release(network_module);
25413 }
25414 }
25415
25416 #[test]
25417 fn sincal_multiconductor_uses_existing_owner_rooted_handles_and_echo() {
25418 let mut connection = rusqlite::Connection::open_in_memory().unwrap();
25419 connection
25420 .execute_batch(include_str!(
25421 "../../tests/data/sincal/synthetic-multiconductor.sql"
25422 ))
25423 .unwrap();
25424 let native = connection.serialize("main").unwrap().to_vec();
25425 unsafe {
25426 let mut error = std::ptr::null_mut();
25427 let source = pio_source_from_memory(
25428 c"case.db".as_ptr(),
25429 7,
25430 native.as_ptr(),
25431 native.len(),
25432 &mut error,
25433 );
25434 assert!(!source.is_null(), "{}", error_text(error));
25435 let format = b"sincal-multiconductor";
25436 let module = pio_parse(source, format.as_ptr().cast(), format.len(), &mut error);
25437 pio_source_release(source);
25438 assert!(!module.is_null(), "{}", error_text(error));
25439 let value = pio_module_value(module);
25440 let network = pio_value_multiconductor_network(value, &mut error);
25441 assert!(!network.is_null(), "{}", error_text(error));
25442 let destination = pio_destination_memory(c"copy.db".as_ptr(), 7, &mut error);
25443 let emitted = pio_emit(module, c"sincal".as_ptr(), 6, destination, &mut error);
25444 pio_destination_release(destination);
25445 assert!(!emitted.is_null(), "{}", error_text(error));
25446 assert_eq!(pio_emit_result_artifact_count(emitted), 1);
25447 let artifact = pio_emit_result_artifact(emitted, 0, &mut error);
25448 let bytes = pio_artifact_bytes(artifact);
25449 assert_eq!(std::slice::from_raw_parts(bytes.data, bytes.len), native);
25450 pio_artifact_release(artifact);
25451 pio_emit_result_release(emitted);
25452 pio_value_release(value);
25453 pio_module_release(module);
25454 assert_eq!(pio_multiconductor_network_load_count(network), 1);
25455 assert_eq!(pio_multiconductor_network_line_count(network), 1);
25456 pio_multiconductor_network_release(network);
25457 assert!(error.is_null());
25458 }
25459 }
25460
25461 #[test]
25462 fn sincal_balanced_uses_existing_typed_handles_and_binary_echo() {
25463 const NATIVE: &[u8] = include_bytes!("../../tests/data/sincal/1-LV-rural1--0-sw.sinx");
25464 unsafe {
25465 let mut error = std::ptr::null_mut();
25466 let source = pio_source_from_memory(
25467 c"case.sinx".as_ptr(),
25468 9,
25469 NATIVE.as_ptr(),
25470 NATIVE.len(),
25471 &mut error,
25472 );
25473 assert!(!source.is_null(), "{}", error_text(error));
25474 let refused = pio_parse(source, std::ptr::null(), 0, &mut error);
25475 assert!(refused.is_null());
25476 assert_eq!(
25477 view_text(pio_error_code(error)),
25478 "REQUEST.SINCAL.PROFILE_REQUIRED"
25479 );
25480 pio_error_release(error);
25481 error = std::ptr::null_mut();
25482 let format = b"sincal-balanced";
25483 let module = pio_parse(source, format.as_ptr().cast(), format.len(), &mut error);
25484 pio_source_release(source);
25485 assert!(!module.is_null(), "{}", error_text(error));
25486 let value = pio_module_value(module);
25487 let network = pio_value_balanced_network(value, &mut error);
25488 assert!(!network.is_null(), "{}", error_text(error));
25489 let destination = pio_destination_memory(c"copy.sinx".as_ptr(), 9, &mut error);
25490 let emitted = pio_emit(module, c"sincal".as_ptr(), 6, destination, &mut error);
25491 pio_destination_release(destination);
25492 assert!(!emitted.is_null(), "{}", error_text(error));
25493 assert_eq!(pio_emit_result_artifact_count(emitted), 1);
25494 let artifact = pio_emit_result_artifact(emitted, 0, &mut error);
25495 let bytes = pio_artifact_bytes(artifact);
25496 assert_eq!(std::slice::from_raw_parts(bytes.data, bytes.len), NATIVE);
25497 pio_artifact_release(artifact);
25498 pio_emit_result_release(emitted);
25499 pio_value_release(value);
25500 pio_module_release(module);
25501 assert_eq!(pio_balanced_network_bus_count(network), 15);
25504 assert_eq!(pio_balanced_network_branch_count(network), 14);
25505 pio_balanced_network_release(network);
25506 assert!(error.is_null());
25507 }
25508 }
25509
25510 #[test]
25511 fn each_contingency_file_emits_the_bytes_it_was_read_from() {
25512 unsafe {
25513 for (name, format) in [
25514 ("resolve_cases.con", "psse-con"),
25515 ("selectors.sub", "psse-sub"),
25516 ("generated.mon", "psse-mon"),
25517 ] {
25518 let module = parse_contingency_fixture(name);
25519 let mut error = std::ptr::null_mut();
25520 let destination = pio_destination_memory(c"out".as_ptr(), 3, &mut error);
25521 assert!(!destination.is_null(), "{}", error_text(error));
25522 let result = pio_emit(
25523 module,
25524 format.as_ptr().cast(),
25525 format.len(),
25526 destination,
25527 &mut error,
25528 );
25529 pio_destination_release(destination);
25530 assert!(!result.is_null(), "{name}: {}", error_text(error));
25531 assert_eq!(pio_emit_result_artifact_count(result), 1);
25532 let artifact = pio_emit_result_artifact(result, 0, &mut error);
25533 assert!(!artifact.is_null(), "{name}: {}", error_text(error));
25534 let bytes = pio_artifact_bytes(artifact);
25535 let emitted = std::slice::from_raw_parts(bytes.data, bytes.len).to_vec();
25536 assert_eq!(
25537 emitted,
25538 std::fs::read(contingency_fixture(name)).unwrap(),
25539 "{name}"
25540 );
25541 pio_artifact_release(artifact);
25542 pio_emit_result_release(result);
25543 pio_module_release(module);
25544 }
25545 }
25546 }
25547
25548 #[test]
25549 fn aggregate_bus_active_demand_uses_explicit_proportional_allocation() {
25550 unsafe {
25551 let mut network = case9_network();
25552 let mut second = network
25553 .loads()
25554 .iter()
25555 .find(|load| load.bus == powerio_tx::BusId::new(5))
25556 .unwrap()
25557 .clone();
25558 second.p = 30.0;
25559 second.q = 10.0;
25560 second.uid = Some("extra-load-at-bus-5".to_owned());
25561 network.loads_mut().push(second);
25562 let source = module_handle(powerio::PioModule::new(PioValue::BalancedNetwork(network)));
25563 let mut error = std::ptr::null_mut();
25564 let module = pio_module_to_dc_pf_instance(source, &mut error);
25565 assert!(!module.is_null(), "{}", error_text(error));
25566 pio_module_release(source);
25567
25568 let value_before = pio_module_value(module);
25569 let instance_before = pio_value_dc_pf_instance(value_before, &mut error);
25570 let network_before =
25571 pio_calculation_instance_balanced_network(instance_before, &mut error);
25572
25573 let power = pio_active_power_from_watts(240_000_000.0);
25574 let bad_rule = "first_load";
25575 let bad_report = pio_apply_bus_load_active_power(
25576 module,
25577 5,
25578 power,
25579 bad_rule.as_ptr().cast(),
25580 bad_rule.len(),
25581 &mut error,
25582 );
25583 assert!(bad_report.is_null());
25584 assert_eq!(
25585 view_text(pio_error_code(error)),
25586 "REQUEST.CAPI.ALLOCATION_UNKNOWN"
25587 );
25588 pio_error_release(error);
25589 error = std::ptr::null_mut();
25590
25591 let rule = "proportional_to_current_active_power";
25592 let report = pio_apply_bus_load_active_power(
25593 module,
25594 5,
25595 power,
25596 rule.as_ptr().cast(),
25597 rule.len(),
25598 &mut error,
25599 );
25600 assert!(!report.is_null(), "{}", error_text(error));
25601 assert_eq!(pio_update_report_len(report), 2);
25602 assert!(!pio_update_report_connectivity_changed(report));
25603
25604 let value_after = pio_module_value(module);
25605 let instance_after = pio_value_dc_pf_instance(value_after, &mut error);
25606 let network_after =
25607 pio_calculation_instance_balanced_network(instance_after, &mut error);
25608 let mut first_before = std::mem::MaybeUninit::<PioBalancedLoadView>::uninit();
25609 let mut second_before = std::mem::MaybeUninit::<PioBalancedLoadView>::uninit();
25610 let mut first_after = std::mem::MaybeUninit::<PioBalancedLoadView>::uninit();
25611 let mut second_after = std::mem::MaybeUninit::<PioBalancedLoadView>::uninit();
25612 assert!(pio_balanced_network_load_at(
25613 network_before,
25614 0,
25615 first_before.as_mut_ptr(),
25616 &mut error,
25617 ));
25618 assert!(pio_balanced_network_load_at(
25619 network_before,
25620 3,
25621 second_before.as_mut_ptr(),
25622 &mut error,
25623 ));
25624 assert!(pio_balanced_network_load_at(
25625 network_after,
25626 0,
25627 first_after.as_mut_ptr(),
25628 &mut error,
25629 ));
25630 assert!(pio_balanced_network_load_at(
25631 network_after,
25632 3,
25633 second_after.as_mut_ptr(),
25634 &mut error,
25635 ));
25636 assert_eq!(first_before.assume_init().p_mw, 90.0);
25637 assert_eq!(second_before.assume_init().p_mw, 30.0);
25638 assert_eq!(first_after.assume_init().p_mw, 180.0);
25639 assert_eq!(second_after.assume_init().p_mw, 60.0);
25640 assert_eq!(
25641 PioModule::get(module)
25642 .unwrap()
25643 .module
25644 .history()
25645 .last()
25646 .unwrap()
25647 .name(),
25648 "apply_updates"
25649 );
25650
25651 pio_balanced_network_release(network_before);
25652 pio_calculation_instance_release(instance_before);
25653 pio_value_release(value_before);
25654 pio_balanced_network_release(network_after);
25655 pio_calculation_instance_release(instance_after);
25656 pio_value_release(value_after);
25657 pio_update_report_release(report);
25658 pio_active_power_release(power);
25659 pio_module_release(module);
25660 }
25661 }
25662
25663 #[test]
25664 fn scuc_instance_exposes_typed_scheduling_inputs() {
25665 unsafe {
25666 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
25667 .join("../tests/data/goc3/goc3_small.json");
25668 let source = std::fs::read_to_string(path).unwrap().replacen(
25669 "\"startup_states\": []",
25670 "\"startup_states\": [[2.0, 3.0]]",
25671 1,
25672 );
25673 let parsed =
25674 goc3_instance(Source::from_memory("goc3_small.json", source.into_bytes()).unwrap());
25675 let module = module_handle(powerio::PioModule::new(PioValue::AcScucInstance(parsed)));
25676 let value = pio_module_value(module);
25677 let mut error = std::ptr::null_mut();
25678 let instance = pio_value_ac_scuc_instance(value, &mut error);
25679 assert!(!instance.is_null(), "{}", error_text(error));
25680 pio_value_release(value);
25681 pio_module_release(module);
25682
25683 let mut dimensions = std::mem::MaybeUninit::<PioScucDimensionsView>::uninit();
25684 assert!(pio_ac_scuc_instance_dimensions(
25685 instance,
25686 dimensions.as_mut_ptr(),
25687 &mut error,
25688 ));
25689 let dimensions = dimensions.assume_init();
25690 assert_eq!(dimensions.period_count, 2);
25691 assert_eq!(dimensions.device_count, 2);
25692 assert_eq!(dimensions.producer_count, 1);
25693 assert_eq!(dimensions.consumer_count, 1);
25694 assert_eq!(dimensions.shunt_count, 1);
25695 assert_eq!(dimensions.branch_switching_cost_count, 3);
25696 assert_eq!(dimensions.transformer_control_count, 1);
25697 assert_eq!(dimensions.active_reserve_zone_count, 1);
25698 assert_eq!(dimensions.reactive_reserve_zone_count, 1);
25699 assert_eq!(dimensions.contingency_count, 3);
25700
25701 let durations = pio_ac_scuc_instance_interval_durations(instance);
25702 assert_eq!(
25703 std::slice::from_raw_parts(durations.data, durations.len),
25704 &[1.0, 1.0]
25705 );
25706
25707 let mut violation = std::mem::MaybeUninit::<PioScucViolationCostView>::uninit();
25708 assert!(pio_ac_scuc_instance_violation_costs(
25709 instance,
25710 violation.as_mut_ptr(),
25711 &mut error,
25712 ));
25713 let violation = violation.assume_init();
25714 assert_eq!(violation.active_power_balance, 1.0);
25715 assert_eq!(violation.reactive_power_balance, 1.0);
25716 assert_eq!(violation.branch_thermal_limit, 1.0);
25717 assert_eq!(violation.energy_requirement, 1.0);
25718
25719 let mut producer = std::mem::MaybeUninit::<PioScucDeviceView>::uninit();
25720 assert!(pio_ac_scuc_instance_device_at(
25721 instance,
25722 0,
25723 producer.as_mut_ptr(),
25724 &mut error,
25725 ));
25726 let producer = producer.assume_init();
25727 assert_eq!(view_text(producer.id.component_type), "generator");
25728 assert_eq!(view_text(producer.id.local_id), "sd_00");
25729 assert_eq!(view_text(producer.kind), "producer");
25730 assert!(producer.initial_on_status);
25731 assert_eq!(producer.minimum_up_time_hours, 1.0);
25732 assert_eq!(producer.minimum_down_time_hours, 1.0);
25733 assert_eq!(producer.initial_commitment.accumulated_up_time_hours, 4.0);
25734 assert_eq!(producer.initial_commitment.accumulated_down_time_hours, 0.0);
25735 assert_eq!(producer.startup_cost_adjustment_count, 1);
25736 assert_eq!(producer.startup_limit_count, 1);
25737 assert_eq!(producer.energy_upper_bound_count, 1);
25738 assert_eq!(producer.energy_lower_bound_count, 1);
25739 assert_eq!(producer.period_count, 2);
25740
25741 let uid = "sd_00";
25742 let mut found_device = std::mem::MaybeUninit::<PioScucDeviceView>::uninit();
25743 assert!(pio_ac_scuc_instance_device_get(
25744 instance,
25745 uid.as_ptr().cast(),
25746 uid.len(),
25747 found_device.as_mut_ptr(),
25748 &mut error,
25749 ));
25750 assert_eq!(view_text(found_device.assume_init().id.local_id), "sd_00");
25751
25752 let mut adjustment =
25753 std::mem::MaybeUninit::<PioScucStartupCostAdjustmentView>::uninit();
25754 assert!(pio_ac_scuc_instance_device_startup_cost_adjustment_at(
25755 instance,
25756 0,
25757 0,
25758 adjustment.as_mut_ptr(),
25759 &mut error,
25760 ));
25761 assert_eq!(adjustment.assume_init().maximum_down_time_hours, 3.0);
25762
25763 let mut limit = std::mem::MaybeUninit::<PioScucStartupLimitView>::uninit();
25764 assert!(pio_ac_scuc_instance_device_startup_limit_at(
25765 instance,
25766 0,
25767 0,
25768 limit.as_mut_ptr(),
25769 &mut error,
25770 ));
25771 assert_eq!(limit.assume_init().maximum_startups, 1);
25772
25773 let mut energy = std::mem::MaybeUninit::<PioScucEnergyRequirementView>::uninit();
25774 assert!(pio_ac_scuc_instance_device_energy_upper_bound_at(
25775 instance,
25776 0,
25777 0,
25778 energy.as_mut_ptr(),
25779 &mut error,
25780 ));
25781 assert_eq!(energy.assume_init().energy_pu, 9.0);
25782 assert!(pio_ac_scuc_instance_device_energy_lower_bound_at(
25783 instance,
25784 0,
25785 0,
25786 energy.as_mut_ptr(),
25787 &mut error,
25788 ));
25789 assert_eq!(energy.assume_init().energy_pu, 1.0);
25790
25791 let mut period = std::mem::MaybeUninit::<PioScucDevicePeriodView>::uninit();
25792 assert!(pio_ac_scuc_instance_device_period_at(
25793 instance,
25794 0,
25795 0,
25796 period.as_mut_ptr(),
25797 &mut error,
25798 ));
25799 let period = period.assume_init();
25800 assert!(period.on_status_min);
25801 assert!(period.on_status_max);
25802 assert_eq!(period.active_power_min_pu, 2.0);
25803 assert_eq!(period.active_power_max_pu, 5.0);
25804 assert_eq!(period.energy_cost_block_count, 1);
25805
25806 let mut cost_block = std::mem::MaybeUninit::<PioScucEnergyCostBlockView>::uninit();
25807 assert!(pio_ac_scuc_instance_device_energy_cost_block_at(
25808 instance,
25809 0,
25810 0,
25811 0,
25812 cost_block.as_mut_ptr(),
25813 &mut error,
25814 ));
25815 let cost_block = cost_block.assume_init();
25816 assert_eq!(cost_block.marginal_cost, 10.0);
25817 assert_eq!(cost_block.block_size_pu, 5.0);
25818
25819 let mut shunt = std::mem::MaybeUninit::<PioScucShuntView>::uninit();
25820 assert!(pio_ac_scuc_instance_shunt_at(
25821 instance,
25822 0,
25823 shunt.as_mut_ptr(),
25824 &mut error,
25825 ));
25826 let shunt = shunt.assume_init();
25827 assert_eq!(view_text(shunt.id.local_id), "sh_00");
25828 assert_eq!(shunt.conductance_per_step_pu, 0.0);
25829 assert_eq!(shunt.susceptance_per_step_pu, 3.0);
25830 assert_eq!(
25831 (shunt.step_min, shunt.initial_step, shunt.step_max),
25832 (0, 1, 4)
25833 );
25834 let shunt_uid = "sh_00";
25835 let mut found_shunt = std::mem::MaybeUninit::<PioScucShuntView>::uninit();
25836 assert!(pio_ac_scuc_instance_shunt_get(
25837 instance,
25838 shunt_uid.as_ptr().cast(),
25839 shunt_uid.len(),
25840 found_shunt.as_mut_ptr(),
25841 &mut error,
25842 ));
25843 assert_eq!(view_text(found_shunt.assume_init().id.local_id), "sh_00");
25844
25845 let mut switching = std::mem::MaybeUninit::<PioScucBranchSwitchingCostView>::uninit();
25846 assert!(pio_ac_scuc_instance_branch_switching_cost_at(
25847 instance,
25848 0,
25849 switching.as_mut_ptr(),
25850 &mut error,
25851 ));
25852 let switching = switching.assume_init();
25853 assert_eq!(view_text(switching.id.component_type), "branch");
25854 assert_eq!(view_text(switching.id.local_id), "acl_00");
25855
25856 let mut control = std::mem::MaybeUninit::<PioScucTransformerControlView>::uninit();
25857 assert!(pio_ac_scuc_instance_transformer_control_at(
25858 instance,
25859 0,
25860 control.as_mut_ptr(),
25861 &mut error,
25862 ));
25863 let control = control.assume_init();
25864 assert_eq!(view_text(control.id.component_type), "transformer");
25865 assert_eq!(view_text(control.id.local_id), "xf_00");
25866 assert_eq!((control.tap_ratio_min, control.tap_ratio_max), (1.0, 1.0));
25867
25868 let mut active_zone = std::mem::MaybeUninit::<PioScucActiveReserveZoneView>::uninit();
25869 assert!(pio_ac_scuc_instance_active_reserve_zone_at(
25870 instance,
25871 0,
25872 active_zone.as_mut_ptr(),
25873 &mut error,
25874 ));
25875 assert_eq!(active_zone.assume_init().bus_count, 2);
25876 let mut active_period =
25877 std::mem::MaybeUninit::<PioScucActiveReservePeriodView>::uninit();
25878 assert!(pio_ac_scuc_instance_active_reserve_zone_period_at(
25879 instance,
25880 0,
25881 0,
25882 active_period.as_mut_ptr(),
25883 &mut error,
25884 ));
25885 assert_eq!(active_period.assume_init().ramping_up_requirement_pu, 0.0);
25886 let mut reserve_bus = std::mem::MaybeUninit::<PioComponentIdView>::uninit();
25887 assert!(pio_ac_scuc_instance_active_reserve_zone_bus_at(
25888 instance,
25889 0,
25890 0,
25891 reserve_bus.as_mut_ptr(),
25892 &mut error,
25893 ));
25894 assert_eq!(view_text(reserve_bus.assume_init().local_id), "bus_00");
25895
25896 let mut reactive_zone =
25897 std::mem::MaybeUninit::<PioScucReactiveReserveZoneView>::uninit();
25898 assert!(pio_ac_scuc_instance_reactive_reserve_zone_at(
25899 instance,
25900 0,
25901 reactive_zone.as_mut_ptr(),
25902 &mut error,
25903 ));
25904 assert_eq!(reactive_zone.assume_init().bus_count, 2);
25905 let mut reactive_period =
25906 std::mem::MaybeUninit::<PioScucReactiveReservePeriodView>::uninit();
25907 assert!(pio_ac_scuc_instance_reactive_reserve_zone_period_at(
25908 instance,
25909 0,
25910 0,
25911 reactive_period.as_mut_ptr(),
25912 &mut error,
25913 ));
25914 assert_eq!(
25915 reactive_period.assume_init().reactive_up_requirement_pu,
25916 0.0
25917 );
25918 assert!(pio_ac_scuc_instance_reactive_reserve_zone_bus_at(
25919 instance,
25920 0,
25921 1,
25922 reserve_bus.as_mut_ptr(),
25923 &mut error,
25924 ));
25925 assert_eq!(view_text(reserve_bus.assume_init().local_id), "bus_01");
25926
25927 let mut contingency = std::mem::MaybeUninit::<PioScucContingencyView>::uninit();
25928 assert!(pio_ac_scuc_instance_contingency_at(
25929 instance,
25930 0,
25931 contingency.as_mut_ptr(),
25932 &mut error,
25933 ));
25934 let first_contingency = contingency.assume_init();
25935 assert_eq!(
25936 view_text(first_contingency.id.component_type),
25937 "contingency"
25938 );
25939 assert_eq!(view_text(first_contingency.id.local_id), "ctg_00");
25940 let contingency_uid = "ctg_02";
25941 assert!(pio_ac_scuc_instance_contingency_get(
25942 instance,
25943 contingency_uid.as_ptr().cast(),
25944 contingency_uid.len(),
25945 contingency.as_mut_ptr(),
25946 &mut error,
25947 ));
25948 assert_eq!(view_text(contingency.assume_init().id.local_id), "ctg_02");
25949 let mut component = std::mem::MaybeUninit::<PioScucContingencyComponentView>::uninit();
25950 assert!(pio_ac_scuc_instance_contingency_component_at(
25951 instance,
25952 0,
25953 0,
25954 component.as_mut_ptr(),
25955 &mut error,
25956 ));
25957 let component = component.assume_init();
25958 assert_eq!(view_text(component.id.component_type), "branch");
25959 assert_eq!(view_text(component.id.local_id), "acl_00");
25960
25961 pio_calculation_instance_release(instance);
25962 }
25963 }
25964
25965 #[test]
25966 fn one_parse_reads_a_goc3_problem_and_solution_directory() {
25967 unsafe {
25968 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../tests/data/goc3");
25969 let path = path.to_string_lossy();
25970 let mut error = std::ptr::null_mut();
25971 let source = pio_source_open(path.as_ptr().cast(), path.len(), &mut error);
25972 assert!(!source.is_null(), "{}", error_text(error));
25973 let module = pio_parse(source, std::ptr::null(), 0, &mut error);
25974 pio_source_release(source);
25975 assert!(!module.is_null(), "{}", error_text(error));
25976
25977 let inner = PioModule::get(module).unwrap();
25978 assert_eq!(inner.module.value().type_name(), "powerio.AcScucSolution");
25979 assert_eq!(inner.module.sources().len(), 2);
25980
25981 let value = pio_module_value(module);
25982 let solution = pio_value_ac_scuc_solution(value, &mut error);
25983 pio_value_release(value);
25984 assert!(!solution.is_null(), "{}", error_text(error));
25985 assert_eq!(pio_ac_scuc_solution_time_count(solution), 2);
25986 let quantity = "bus_voltage_magnitude";
25987 let row = pio_ac_scuc_solution_get_values_at(
25988 solution,
25989 quantity.as_ptr().cast(),
25990 quantity.len(),
25991 0,
25992 &mut error,
25993 );
25994 assert!(!row.is_null(), "{}", error_text(error));
25995 let values = pio_vector_values(row);
25996 assert_eq!(
25997 std::slice::from_raw_parts(values.data, values.len),
25998 &[1.0, 0.99]
25999 );
26000 pio_vector_release(row);
26001
26002 for quantity in [
26003 "bus_voltage_magnitude",
26004 "bus_voltage_angle",
26005 "shunt_step",
26006 "ac_line_on_status",
26007 "transformer_tap_ratio",
26008 "transformer_phase_shift",
26009 "transformer_on_status",
26010 "dc_line_from_active_power",
26011 "dc_line_from_reactive_power",
26012 "dc_line_to_reactive_power",
26013 "device_on_status",
26014 "device_startup_status",
26015 "device_shutdown_status",
26016 "device_active_power",
26017 "device_reactive_power",
26018 "regulation_reserve_up",
26019 "regulation_reserve_down",
26020 "synchronized_reserve",
26021 "nonsynchronized_reserve",
26022 "ramping_reserve_up_online",
26023 "ramping_reserve_up_offline",
26024 "ramping_reserve_down_online",
26025 "ramping_reserve_down_offline",
26026 "reactive_reserve_up",
26027 "reactive_reserve_down",
26028 ] {
26029 let vector = pio_ac_scuc_solution_get_values_at(
26030 solution,
26031 quantity.as_ptr().cast(),
26032 quantity.len(),
26033 0,
26034 &mut error,
26035 );
26036 assert!(!vector.is_null(), "{quantity}: {}", error_text(error));
26037 pio_vector_release(vector);
26038 }
26039
26040 pio_calculation_solution_release(solution);
26041 pio_module_release(module);
26042 }
26043 }
26044
26045 #[test]
26046 fn temporal_metadata_outlives_its_parent_and_checks_bounds() {
26047 unsafe {
26048 let text = br#"{"system":{"baseMVA":100,"time_keys":["morning","evening"],"time_period_length_minutes":15},"elements":{"bus":{"7":{"matpower_bustype":"ref"}},"load":{"1":{"bus":"7","p_load":{"data_type":"time_series","values":[10,20]}}}}}"#;
26049 let parsed =
26050 powerio::parse(Source::from_memory("case.egret.json", text.to_vec()).unwrap())
26051 .unwrap();
26052 let module = module_handle(parsed);
26053 let value = pio_module_value(module);
26054 let mut error = std::ptr::null_mut();
26055 let series = pio_value_time_series(value, &mut error);
26056 assert!(!series.is_null(), "{}", error_text(error));
26057 pio_value_release(value);
26058 pio_module_release(module);
26059 let mut view = std::mem::MaybeUninit::<PioTimePointView>::uninit();
26060 assert!(pio_time_series_time_point(
26061 series,
26062 1,
26063 view.as_mut_ptr(),
26064 &mut error
26065 ));
26066 let view = view.assume_init();
26067 assert_eq!(view_text(view.label), "evening");
26068 assert!(view.has_duration);
26069 assert_eq!(view.duration_seconds, 900.0);
26070 let mut out = std::mem::MaybeUninit::<PioTimePointView>::uninit();
26071 assert!(!pio_time_series_time_point(
26072 series,
26073 2,
26074 out.as_mut_ptr(),
26075 &mut error
26076 ));
26077 assert!(!error.is_null());
26078 pio_error_release(error);
26079 assert!(!pio_time_series_time_point(
26080 series,
26081 0,
26082 std::ptr::null_mut(),
26083 &mut error
26084 ));
26085 assert!(!error.is_null());
26086 pio_error_release(error);
26087 pio_time_series_release(series);
26088 }
26089 }
26090
26091 #[test]
26092 fn one_parse_and_one_emit_cover_powsybl_formats() {
26093 unsafe {
26094 let module = parse_case9();
26095 let directory = tempfile::tempdir().unwrap();
26096
26097 for (format, output_name) in [
26098 ("xiidm", "case9.xiidm"),
26099 ("cgmes", "case9-cgmes"),
26100 ("psse-rawx", "case9.rawx"),
26101 ("ucte", "case9.uct"),
26102 ] {
26103 let output = directory.path().join(output_name);
26104 let output_text = output.to_string_lossy();
26105 let mut error = std::ptr::null_mut();
26106 let destination = pio_destination_path(
26107 output_text.as_ptr().cast(),
26108 output_text.len(),
26109 &mut error,
26110 );
26111 assert!(!destination.is_null(), "{}", error_text(error));
26112 let result = pio_emit(
26113 module,
26114 format.as_ptr().cast(),
26115 format.len(),
26116 destination,
26117 &mut error,
26118 );
26119 pio_destination_release(destination);
26120 assert!(!result.is_null(), "{format}: {}", error_text(error));
26121 pio_emit_result_release(result);
26122
26123 let source =
26124 pio_source_open(output_text.as_ptr().cast(), output_text.len(), &mut error);
26125 assert!(!source.is_null(), "{format}: {}", error_text(error));
26126 let reparsed = pio_parse(source, std::ptr::null(), 0, &mut error);
26127 pio_source_release(source);
26128 assert!(!reparsed.is_null(), "{format}: {}", error_text(error));
26129 assert_eq!(
26130 PioModule::get(reparsed).unwrap().module.value().type_name(),
26131 "powerio.BalancedNetwork"
26132 );
26133 pio_module_release(reparsed);
26134 }
26135
26136 pio_module_release(module);
26137 }
26138 }
26139
26140 #[test]
26141 fn scuc_solution_exposes_every_device_status_and_offline_reserve() {
26142 unsafe {
26143 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
26144 .join("../tests/data/goc3/goc3_small.json");
26145 let parsed = goc3_instance(Source::open(path).unwrap());
26146 let mut outputs = powerio_prob::ScucDeviceOutputs::default();
26147 outputs.startup_status = vec![vec![false, true], vec![true, false]];
26148 outputs.shutdown_status = vec![vec![true, false], vec![false, true]];
26149 outputs.p_ramp_res_up_offline = vec![vec![1.25, 1.75], vec![1.5, 2.0]];
26150 outputs.p_ramp_res_down_offline = vec![vec![2.25, 2.75], vec![2.5, 3.0]];
26151 let solution = powerio_prob::AcScucSolution::new(
26152 Arc::new(parsed),
26153 powerio_prob::Termination::Converged,
26154 powerio_prob::ScucNetworkOutputs::default(),
26155 outputs,
26156 None,
26157 )
26158 .unwrap();
26159 let module = module_handle(powerio::PioModule::new(PioValue::AcScucSolution(solution)));
26160 let value = pio_module_value(module);
26161 let mut error = std::ptr::null_mut();
26162 let solution = pio_value_ac_scuc_solution(value, &mut error);
26163 assert!(!solution.is_null(), "{}", error_text(error));
26164 pio_value_release(value);
26165 pio_module_release(module);
26166
26167 for (quantity, expected) in [
26168 ("device_startup_status", [0.0, 1.0]),
26169 ("device_shutdown_status", [1.0, 0.0]),
26170 ("ramping_reserve_up_offline", [1.25, 1.75]),
26171 ("ramping_reserve_down_offline", [2.25, 2.75]),
26172 ] {
26173 let vector = pio_ac_scuc_solution_get_values_at(
26174 solution,
26175 quantity.as_ptr().cast(),
26176 quantity.len(),
26177 0,
26178 &mut error,
26179 );
26180 assert!(!vector.is_null(), "{}", error_text(error));
26181 let view = pio_vector_values(vector);
26182 assert_eq!(view.len, 2);
26183 assert_eq!(std::slice::from_raw_parts(view.data, view.len), &expected);
26184 pio_vector_release(vector);
26185 }
26186
26187 pio_calculation_solution_release(solution);
26188 }
26189 }
26190
26191 #[test]
26192 fn update_detaches_from_retained_value_views() {
26193 unsafe {
26194 let module = parse_case9();
26195 let value = pio_module_value(module);
26196 let mut error = std::ptr::null_mut();
26197 let old_network = pio_value_balanced_network(value, &mut error);
26198 pio_value_release(value);
26199 assert!(!old_network.is_null(), "{}", error_text(error));
26200
26201 let old = PioBalancedNetwork::get(old_network)
26202 .and_then(BalancedNetworkInner::network)
26203 .unwrap();
26204 let load = &old.loads()[0];
26205 let old_active_power = load.p;
26206 let local_id = load.uid.as_deref().unwrap().to_owned();
26207
26208 let component = pio_component_id_new(
26209 c"load".as_ptr(),
26210 4,
26211 local_id.as_ptr().cast(),
26212 local_id.len(),
26213 &mut error,
26214 );
26215 let replacement = pio_active_power_from_megawatts(old_active_power + 1.0);
26216 let operating = pio_operating_point_update_set_load_active_power(
26217 component,
26218 std::ptr::null(),
26219 0,
26220 replacement,
26221 &mut error,
26222 );
26223 let update = pio_calculation_update_from_operating_point(operating, &mut error);
26224 let updates = [update.cast_const()];
26225 let report = pio_apply_updates(module, updates.as_ptr(), updates.len(), &mut error);
26226 assert!(!report.is_null(), "{}", error_text(error));
26227 assert_eq!(pio_update_report_len(report), 1);
26228 assert!(!pio_update_report_connectivity_changed(report));
26229
26230 let new_value = pio_module_value(module);
26231 let new_network = pio_value_balanced_network(new_value, &mut error);
26232 let new = PioBalancedNetwork::get(new_network)
26233 .and_then(BalancedNetworkInner::network)
26234 .unwrap();
26235 assert_eq!(new.loads()[0].p, old_active_power + 1.0);
26236 assert_eq!(
26237 PioBalancedNetwork::get(old_network)
26238 .and_then(BalancedNetworkInner::network)
26239 .unwrap()
26240 .loads()[0]
26241 .p,
26242 old_active_power,
26243 );
26244
26245 pio_balanced_network_release(new_network);
26246 pio_value_release(new_value);
26247 pio_update_report_release(report);
26248 pio_calculation_update_release(update);
26249 pio_operating_point_update_release(operating);
26250 pio_active_power_release(replacement);
26251 pio_component_id_release(component);
26252 pio_balanced_network_release(old_network);
26253 pio_module_release(module);
26254 }
26255 }
26256
26257 #[test]
26258 fn dc_calculations_return_named_generic_handles() {
26259 unsafe {
26260 let module = parse_case9();
26261 let value = pio_module_value(module);
26262 let mut error = std::ptr::null_mut();
26263 let network = pio_value_balanced_network(value, &mut error);
26264 let incidence = pio_calc_incidence_matrix(network, std::ptr::null(), 0, &mut error);
26265 assert!(!incidence.is_null(), "{}", error_text(error));
26266 assert_eq!(pio_sparse_matrix_rows(incidence), 9);
26267 assert_eq!(pio_sparse_matrix_columns(incidence), 9);
26268 assert_eq!(pio_sparse_matrix_values(incidence).len, 18);
26269
26270 let branch = pio_calc_branch_susceptances(
26271 network,
26272 c"reactance_only".as_ptr(),
26273 "reactance_only".len(),
26274 &mut error,
26275 );
26276 assert!(!branch.is_null(), "{}", error_text(error));
26277 assert_eq!(pio_vector_values(branch).len, 9);
26278
26279 pio_vector_release(branch);
26280 pio_sparse_matrix_release(incidence);
26281 pio_balanced_network_release(network);
26282 pio_value_release(value);
26283 pio_module_release(module);
26284 }
26285 }
26286
26287 const ISLANDED_CASE: &str = "\
26291function mpc = case6_islands
26292mpc.version = '2';
26293mpc.baseMVA = 100;
26294mpc.bus = [
26295 1 3 0 0 0 0 1 1 0 230 1 1.1 0.9;
26296 2 1 40 0 0 0 1 1 0 230 1 1.1 0.9;
26297 3 1 30 0 0 0 1 1 0 230 1 1.1 0.9;
26298 4 3 0 0 0 0 1 1 0 230 1 1.1 0.9;
26299 5 1 20 0 0 0 1 1 0 230 1 1.1 0.9;
26300 6 4 0 0 0 0 1 1 0 230 1 1.1 0.9;
26301];
26302mpc.gen = [
26303 1 70 0 100 -100 1 100 1 200 0;
26304 4 20 0 100 -100 1 100 1 200 0;
26305];
26306mpc.branch = [
26307 1 2 0.01 0.10 0 100 100 100 0 0 1 -60 60;
26308 2 3 0.01 0.20 0 100 100 100 0 0 1 -60 60;
26309 1 3 0.01 0.25 0 100 100 100 0 0 1 -60 60;
26310 4 5 0.01 0.10 0 100 100 100 0 0 1 -60 60;
26311 3 4 0.01 0.10 0 100 100 100 0 0 0 -60 60;
26312 5 6 0.01 0.10 0 100 100 100 0 0 0 -60 60;
26313];
26314mpc.gencost = [
26315 2 0 0 3 0.01 10 0;
26316 2 0 0 3 0.01 10 0;
26317];
26318";
26319
26320 unsafe fn parse_matpower_text(text: &str) -> *mut PioModule {
26321 unsafe {
26322 let name = b"case.m";
26323 let format = b"matpower";
26324 let mut error = std::ptr::null_mut();
26325 let source = pio_source_from_memory(
26326 name.as_ptr().cast(),
26327 name.len(),
26328 text.as_ptr(),
26329 text.len(),
26330 &mut error,
26331 );
26332 assert!(!source.is_null(), "{}", error_text(error));
26333 let module = pio_parse(source, format.as_ptr().cast(), format.len(), &mut error);
26334 pio_source_release(source);
26335 assert!(!module.is_null(), "{}", error_text(error));
26336 module
26337 }
26338 }
26339
26340 unsafe fn parse_case14() -> *mut PioModule {
26341 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../tests/data/case14.m");
26342 let path = path.to_string_lossy();
26343 let mut error = std::ptr::null_mut();
26344 let source = unsafe { pio_source_open(path.as_ptr().cast(), path.len(), &mut error) };
26345 assert!(!source.is_null(), "{}", unsafe { error_text(error) });
26346 let module = unsafe { pio_parse(source, std::ptr::null(), 0, &mut error) };
26347 unsafe { pio_source_release(source) };
26348 assert!(!module.is_null(), "{}", unsafe { error_text(error) });
26349 module
26350 }
26351
26352 unsafe fn balanced_network_of(module: *const PioModule) -> *mut PioBalancedNetwork {
26353 unsafe {
26354 let mut error = std::ptr::null_mut();
26355 let value = pio_module_value(module);
26356 let network = pio_value_balanced_network(value, &mut error);
26357 pio_value_release(value);
26358 assert!(!network.is_null(), "{}", error_text(error));
26359 network
26360 }
26361 }
26362
26363 unsafe fn sizes(view: PioSizeView) -> Vec<usize> {
26364 if view.data.is_null() {
26365 return Vec::new();
26366 }
26367 unsafe { std::slice::from_raw_parts(view.data, view.len) }.to_vec()
26368 }
26369
26370 unsafe fn doubles(view: PioF64View) -> Vec<f64> {
26371 if view.data.is_null() {
26372 return Vec::new();
26373 }
26374 unsafe { std::slice::from_raw_parts(view.data, view.len) }.to_vec()
26375 }
26376
26377 fn dense_of(matrix: &SparseMatrix) -> Vec<f64> {
26379 let (rows, columns) = matrix.shape();
26380 let mut dense = vec![0.0; rows * columns];
26381 for (&value, (row, column)) in matrix {
26382 dense[row * columns + column] = value;
26383 }
26384 dense
26385 }
26386
26387 unsafe fn check_sensitivities_match_rust(
26390 network: *const PioBalancedNetwork,
26391 formula: &str,
26392 solver: SensitivitySolver,
26393 solver_name: &str,
26394 ) -> *mut PioSensitivities {
26395 unsafe {
26396 let mut error = std::ptr::null_mut();
26397 let handle = pio_calc_sensitivities(
26398 network,
26399 formula.as_ptr().cast(),
26400 formula.len(),
26401 solver_name.as_ptr().cast(),
26402 solver_name.len(),
26403 &mut error,
26404 );
26405 assert!(!handle.is_null(), "{}", error_text(error));
26406 let net = require_balanced_network(network).unwrap_or_else(|_| unreachable!());
26407 let options = SensitivityOptions {
26408 formula: BranchSusceptanceFormula::from_formula_name(formula)
26409 .expect("a known formula"),
26410 solver,
26411 ..SensitivityOptions::default()
26412 };
26413 let view = IndexedNetwork::new(net);
26414 let expected =
26415 calc_ptdf_lodf_with_options(&view, &options).expect("the Rust build succeeds");
26416 assert_eq!(pio_sensitivities_n_branches(handle), expected.ptdf.rows());
26417 assert_eq!(pio_sensitivities_n_buses(handle), expected.ptdf.cols());
26418 assert_eq!(
26419 doubles(pio_sensitivities_ptdf(handle)),
26420 dense_of(&expected.ptdf)
26421 );
26422 assert_eq!(
26423 doubles(pio_sensitivities_lodf(handle)),
26424 dense_of(&expected.lodf)
26425 );
26426 assert_eq!(
26427 view_text(pio_sensitivities_solver_path(handle)),
26428 expected.metadata.solver_path.as_str()
26429 );
26430 assert_eq!(
26431 pio_sensitivities_reduced_dimension(handle),
26432 expected.metadata.reduced_dimension
26433 );
26434 assert_eq!(
26435 sizes(pio_sensitivities_reference_bus_indices(handle)),
26436 view.reference_bus_indices()
26437 );
26438 handle
26439 }
26440 }
26441
26442 #[test]
26443 fn sensitivities_on_case14_match_the_rust_routine() {
26444 unsafe {
26445 let module = parse_case14();
26446 let mut error = std::ptr::null_mut();
26447 let network = balanced_network_of(module);
26448 assert!(!network.is_null(), "{}", error_text(error));
26449
26450 for (solver, name) in [
26451 (SensitivitySolver::Auto, "auto"),
26452 (SensitivitySolver::Dense, "dense"),
26453 (SensitivitySolver::Sparse, "sparse"),
26454 ] {
26455 for formula in [
26456 "series_susceptance",
26457 "tap_adjusted_reactance",
26458 "reactance_only",
26459 ] {
26460 let handle = check_sensitivities_match_rust(network, formula, solver, name);
26461 pio_sensitivities_release(handle);
26462 }
26463 }
26464
26465 let formula = b"tap_adjusted_reactance";
26469 let handle = pio_calc_sensitivities(
26470 network,
26471 formula.as_ptr().cast(),
26472 formula.len(),
26473 std::ptr::null(),
26474 0,
26475 &mut error,
26476 );
26477 assert!(!handle.is_null(), "{}", error_text(error));
26478 let ptdf = doubles(pio_sensitivities_ptdf(handle));
26479 for (branch, bus, matpower) in [
26480 (0, 1, -0.838_018_649_617_430_2),
26481 (6, 3, 0.502_572_102_534_224_5),
26482 (7, 6, -0.633_831_600_927_454_8),
26483 (19, 13, -0.399_182_226_185_603_56),
26484 ] {
26485 let value = ptdf[branch * 14 + bus];
26486 assert!((value - matpower).abs() < 1e-12, "{value} vs {matpower}");
26487 }
26488 pio_sensitivities_release(handle);
26489
26490 let handle = pio_calc_sensitivities(
26492 network,
26493 std::ptr::null(),
26494 0,
26495 std::ptr::null(),
26496 0,
26497 &mut error,
26498 );
26499 assert!(!handle.is_null(), "{}", error_text(error));
26500 let (m, n) = (20, 14);
26501 assert_eq!(pio_sensitivities_n_branches(handle), m);
26502 assert_eq!(pio_sensitivities_n_buses(handle), n);
26503 assert_eq!(
26504 sizes(pio_sensitivities_bus_ids(handle)),
26505 (1..=14).collect::<Vec<_>>()
26506 );
26507 assert_eq!(
26508 sizes(pio_sensitivities_branch_rows(handle)),
26509 (0..20).collect::<Vec<_>>()
26510 );
26511 let operators = pio_calc_dc_operators(network, std::ptr::null(), 0, false, &mut error);
26513 assert!(!operators.is_null(), "{}", error_text(error));
26514 assert_eq!(
26515 sizes(pio_sensitivities_bus_ids(handle)),
26516 sizes(pio_dc_operators_bus_ids(operators))
26517 );
26518 assert_eq!(
26519 sizes(pio_sensitivities_branch_rows(handle)),
26520 sizes(pio_dc_operators_branch_rows(operators))
26521 );
26522 for row in 0..m {
26523 assert_eq!(
26524 view_text(pio_sensitivities_branch_identity(handle, row)),
26525 view_text(pio_dc_operators_branch_identity(operators, row))
26526 );
26527 }
26528 pio_dc_operators_release(operators);
26529 let past_end = pio_sensitivities_branch_identity(handle, m);
26530 assert!(past_end.data.is_null());
26531 assert_eq!(sizes(pio_sensitivities_reference_bus_indices(handle)), [0]);
26533 let ptdf = doubles(pio_sensitivities_ptdf(handle));
26534 assert_eq!(ptdf.len(), m * n);
26535 assert!((0..m).all(|row| ptdf[row * n] == 0.0));
26536 let leaving_bus_1 = ptdf[2] + ptdf[n + 2];
26539 assert!((leaving_bus_1 + 1.0).abs() < 1e-12, "{leaving_bus_1}");
26540 let lodf = doubles(pio_sensitivities_lodf(handle));
26541 assert_eq!(lodf.len(), m * m);
26542 assert!((0..m).all(|k| lodf[k * m + k] == -1.0));
26543 assert_eq!(
26544 view_text(pio_sensitivities_solver_path(handle)),
26545 "dense_cholesky"
26546 );
26547 assert_eq!(pio_sensitivities_reduced_dimension(handle), 13);
26548
26549 let retained = pio_sensitivities_retain(handle);
26550 pio_sensitivities_release(handle);
26551 assert_eq!(pio_sensitivities_n_buses(retained), n);
26552 pio_sensitivities_release(retained);
26553
26554 let solver = b"cholesky";
26556 let refused = pio_calc_sensitivities(
26557 network,
26558 std::ptr::null(),
26559 0,
26560 solver.as_ptr().cast(),
26561 solver.len(),
26562 &mut error,
26563 );
26564 assert!(refused.is_null());
26565 assert_eq!(
26566 view_text(pio_error_code(error)),
26567 "BIND.CAPI.INVALID_ARGUMENT"
26568 );
26569 pio_error_release(error);
26570 let formula = b"admittance";
26571 let refused = pio_calc_sensitivities(
26572 network,
26573 formula.as_ptr().cast(),
26574 formula.len(),
26575 std::ptr::null(),
26576 0,
26577 &mut error,
26578 );
26579 assert!(refused.is_null());
26580 assert_eq!(
26581 view_text(pio_error_code(error)),
26582 "REQUEST.CAPI.UNKNOWN_FORMULA"
26583 );
26584 pio_error_release(error);
26585
26586 assert_eq!(pio_sensitivities_n_buses(std::ptr::null()), 0);
26588 assert_eq!(pio_sensitivities_n_branches(std::ptr::null()), 0);
26589 assert!(pio_sensitivities_ptdf(std::ptr::null()).data.is_null());
26590 assert!(pio_sensitivities_lodf(std::ptr::null()).data.is_null());
26591
26592 let islands = pio_balanced_network_islands(network, &mut error);
26594 assert!(!islands.is_null(), "{}", error_text(error));
26595 assert_eq!(pio_islands_count(islands), 1);
26596 let mut island = std::mem::zeroed::<PioIslandView>();
26597 assert!(pio_islands_at(islands, 0, &mut island, &mut error));
26598 assert_eq!(sizes(island.bus_ids), (1..=14).collect::<Vec<_>>());
26599 assert_eq!(sizes(island.bus_indices), (0..14).collect::<Vec<_>>());
26600 assert_eq!(sizes(island.reference_bus_ids), [1]);
26601 assert!(island.supplied);
26602 assert_eq!(sizes(pio_islands_isolated_bus_ids(islands)), [0_usize; 0]);
26603 pio_islands_release(islands);
26604
26605 pio_balanced_network_release(network);
26606 pio_module_release(module);
26607 }
26608 }
26609
26610 #[test]
26611 fn islands_follow_calc_islands_and_sensitivities_ground_every_reference() {
26612 unsafe {
26613 let module = parse_matpower_text(ISLANDED_CASE);
26614 let mut error = std::ptr::null_mut();
26615 let network = balanced_network_of(module);
26616 assert!(!network.is_null(), "{}", error_text(error));
26617
26618 let islands = pio_balanced_network_islands(network, &mut error);
26619 assert!(!islands.is_null(), "{}", error_text(error));
26620 let net = require_balanced_network(network).unwrap_or_else(|_| unreachable!());
26621 let partition = net.calc_islands();
26622 assert_eq!(pio_islands_count(islands), partition.islands.len());
26623 assert_eq!(pio_islands_count(islands), 2);
26624 let mut view = std::mem::zeroed::<PioIslandView>();
26625 for (index, expected) in partition.islands.iter().enumerate() {
26626 assert!(pio_islands_at(islands, index, &mut view, &mut error));
26627 let ids: Vec<usize> = expected.buses.iter().map(|bus| bus.0).collect();
26628 let references: Vec<usize> = expected.references.iter().map(|bus| bus.0).collect();
26629 assert_eq!(sizes(view.bus_ids), ids);
26630 assert_eq!(sizes(view.reference_bus_ids), references);
26631 assert_eq!(sizes(view.generator_rows), expected.generators);
26632 assert_eq!(sizes(view.hvdc_rows), expected.hvdc);
26633 assert_eq!(view.supplied, expected.is_supplied());
26634 }
26635 assert!(pio_islands_at(islands, 0, &mut view, &mut error));
26636 assert_eq!(sizes(view.bus_ids), [1, 2, 3]);
26637 assert_eq!(sizes(view.bus_indices), [0, 1, 2]);
26638 assert_eq!(sizes(view.reference_bus_indices), [0]);
26639 assert_eq!(sizes(view.generator_rows), [0]);
26640 assert!(pio_islands_at(islands, 1, &mut view, &mut error));
26641 assert_eq!(sizes(view.bus_ids), [4, 5]);
26642 assert_eq!(sizes(view.bus_indices), [3, 4]);
26643 assert_eq!(sizes(view.reference_bus_ids), [4]);
26644 assert_eq!(sizes(view.reference_bus_indices), [3]);
26645 assert_eq!(sizes(pio_islands_isolated_bus_ids(islands)), [6]);
26646 assert_eq!(sizes(pio_islands_isolated_bus_indices(islands)), [5]);
26647
26648 assert!(!pio_islands_at(islands, 2, &mut view, &mut error));
26649 assert_eq!(
26650 view_text(pio_error_code(error)),
26651 "BIND.CAPI.INDEX_OUT_OF_RANGE"
26652 );
26653 pio_error_release(error);
26654 assert_eq!(pio_islands_count(std::ptr::null()), 0);
26655 assert!(
26656 pio_islands_isolated_bus_ids(std::ptr::null())
26657 .data
26658 .is_null()
26659 );
26660 let retained = pio_islands_retain(islands);
26661 pio_islands_release(islands);
26662 assert_eq!(pio_islands_count(retained), 2);
26663 pio_islands_release(retained);
26664
26665 let refused = pio_calc_sensitivities(
26669 network,
26670 std::ptr::null(),
26671 0,
26672 std::ptr::null(),
26673 0,
26674 &mut error,
26675 );
26676 assert!(refused.is_null());
26677 assert_eq!(
26678 view_text(pio_error_code(error)),
26679 "BUILD.INDEX.UNGROUNDED_COMPONENT"
26680 );
26681 pio_error_release(error);
26682 pio_balanced_network_release(network);
26683 pio_module_release(module);
26684
26685 let two_islands = ISLANDED_CASE
26688 .replace(" 6 4 0 0 0 0 1 1 0 230 1 1.1 0.9;\n", "")
26689 .replace(" 5 6 0.01 0.10 0 100 100 100 0 0 0 -60 60;\n", "");
26690 let module = parse_matpower_text(&two_islands);
26691 let network = balanced_network_of(module);
26692 assert!(!network.is_null(), "{}", error_text(error));
26693 for (solver, name) in [
26694 (SensitivitySolver::Dense, "dense"),
26695 (SensitivitySolver::Sparse, "sparse"),
26696 ] {
26697 let handle =
26698 check_sensitivities_match_rust(network, "series_susceptance", solver, name);
26699 assert_eq!(
26700 sizes(pio_sensitivities_reference_bus_indices(handle)),
26701 [0, 3]
26702 );
26703 assert_eq!(sizes(pio_sensitivities_branch_rows(handle)), [0, 1, 2, 3]);
26705 let ptdf = doubles(pio_sensitivities_ptdf(handle));
26706 let n = 5;
26707 for row in 0..4 {
26710 assert_eq!(ptdf[row * n], 0.0);
26711 assert_eq!(ptdf[row * n + 3], 0.0);
26712 }
26713 for row in 0..3 {
26714 assert_eq!(ptdf[row * n + 4], 0.0);
26715 }
26716 for column in 1..3 {
26717 assert_eq!(ptdf[3 * n + column], 0.0);
26718 }
26719 assert!((ptdf[3 * n + 4] + 1.0).abs() < 1e-12);
26721 pio_sensitivities_release(handle);
26722 }
26723 pio_balanced_network_release(network);
26724 pio_module_release(module);
26725 }
26726 }
26727
26728 const ZERO_IMPEDANCE_CASE: &str = "\
26730function mpc = case3_zero_impedance
26731mpc.version = '2';
26732mpc.baseMVA = 100;
26733mpc.bus = [
26734 1 3 0 0 0 0 1 1 0 230 1 1.1 0.9;
26735 2 1 50 0 0 0 1 1 0 230 1 1.1 0.9;
26736 3 1 50 0 0 0 1 1 0 230 1 1.1 0.9;
26737];
26738mpc.gen = [
26739 1 100 0 100 -100 1 100 1 200 0;
26740];
26741mpc.branch = [
26742 1 2 0 0 0.02 100 100 100 0 0 1 -60 60;
26743 2 3 0 0.1 0 100 100 100 0 0 1 -60 60;
26744];
26745mpc.gencost = [
26746 2 0 0 3 0.01 10 0;
26747];
26748";
26749
26750 #[test]
26751 fn dc_operators_handle_names_its_axes_and_skips_a_zero_impedance_branch() {
26752 unsafe {
26753 let name = b"zero.m";
26754 let format = b"matpower";
26755 let mut error = std::ptr::null_mut();
26756 let source = pio_source_from_memory(
26757 name.as_ptr().cast(),
26758 name.len(),
26759 ZERO_IMPEDANCE_CASE.as_ptr(),
26760 ZERO_IMPEDANCE_CASE.len(),
26761 &mut error,
26762 );
26763 assert!(!source.is_null(), "{}", error_text(error));
26764 let module = pio_parse(source, format.as_ptr().cast(), format.len(), &mut error);
26765 pio_source_release(source);
26766 assert!(!module.is_null(), "{}", error_text(error));
26767 let value = pio_module_value(module);
26768 let network = pio_value_balanced_network(value, &mut error);
26769 assert!(!network.is_null(), "{}", error_text(error));
26770
26771 let refused = pio_calc_dc_operators(network, std::ptr::null(), 0, false, &mut error);
26773 assert!(refused.is_null());
26774 assert_eq!(
26775 view_text(pio_error_code(error)),
26776 "BUILD.OPERATOR.ZERO_IMPEDANCE"
26777 );
26778 pio_error_release(error);
26779 error = std::ptr::null_mut();
26780
26781 let operators = pio_calc_dc_operators(network, std::ptr::null(), 0, true, &mut error);
26782 assert!(!operators.is_null(), "{}", error_text(error));
26783 assert_eq!(pio_dc_operators_n_buses(operators), 3);
26784 assert_eq!(pio_dc_operators_n_branches(operators), 1);
26785
26786 let bus_ids = pio_dc_operators_bus_ids(operators);
26787 assert_eq!(
26788 std::slice::from_raw_parts(bus_ids.data, bus_ids.len),
26789 &[1, 2, 3]
26790 );
26791 let branch_rows = pio_dc_operators_branch_rows(operators);
26793 assert_eq!(
26794 std::slice::from_raw_parts(branch_rows.data, branch_rows.len),
26795 &[1]
26796 );
26797 let skipped = pio_dc_operators_skipped_branch_rows(operators);
26798 assert_eq!(std::slice::from_raw_parts(skipped.data, skipped.len), &[0]);
26799 assert_ne!(
26800 view_text(pio_dc_operators_branch_identity(operators, 0)),
26801 ""
26802 );
26803 let past_end = pio_dc_operators_branch_identity(operators, 1);
26804 assert!(past_end.data.is_null());
26805 assert_eq!(past_end.len, 0);
26806
26807 let incidence = pio_dc_operators_incidence_matrix(operators, &mut error);
26808 assert!(!incidence.is_null(), "{}", error_text(error));
26809 assert_eq!(pio_sparse_matrix_rows(incidence), 1);
26810 assert_eq!(pio_sparse_matrix_columns(incidence), 3);
26811
26812 let bus_susceptance = pio_dc_operators_bus_susceptance_matrix(operators, &mut error);
26813 assert!(!bus_susceptance.is_null(), "{}", error_text(error));
26814 assert_eq!(pio_sparse_matrix_rows(bus_susceptance), 3);
26815 assert_eq!(pio_sparse_matrix_columns(bus_susceptance), 3);
26816
26817 let branch_flow = pio_dc_operators_branch_flow_matrix(operators, &mut error);
26818 assert!(!branch_flow.is_null(), "{}", error_text(error));
26819 assert_eq!(pio_sparse_matrix_rows(branch_flow), 1);
26820 assert_eq!(pio_sparse_matrix_columns(branch_flow), 3);
26821
26822 let susceptances = pio_dc_operators_branch_susceptances(operators, &mut error);
26823 assert!(!susceptances.is_null(), "{}", error_text(error));
26824 assert_eq!(pio_vector_values(susceptances).len, 1);
26825
26826 let branch_shift = pio_dc_operators_branch_phase_shift_injection(operators, &mut error);
26827 assert!(!branch_shift.is_null(), "{}", error_text(error));
26828 assert_eq!(pio_vector_values(branch_shift).len, 1);
26829
26830 let bus_shift = pio_dc_operators_bus_phase_shift_injection(operators, &mut error);
26831 assert!(!bus_shift.is_null(), "{}", error_text(error));
26832 assert_eq!(pio_vector_values(bus_shift).len, 3);
26833
26834 let angles = [0.0_f64, 0.0, 0.1];
26835 let flows = pio_dc_operators_branch_flow_dc(
26836 operators,
26837 angles.as_ptr(),
26838 angles.len(),
26839 &mut error,
26840 );
26841 assert!(!flows.is_null(), "{}", error_text(error));
26842 assert_eq!(pio_vector_values(flows).len, 1);
26843
26844 let injections = pio_dc_operators_bus_injection_dc(
26845 operators,
26846 angles.as_ptr(),
26847 angles.len(),
26848 &mut error,
26849 );
26850 assert!(!injections.is_null(), "{}", error_text(error));
26851 assert_eq!(pio_vector_values(injections).len, 3);
26852
26853 let retained = pio_dc_operators_retain(operators);
26855 assert!(!retained.is_null());
26856 pio_dc_operators_release(retained);
26857 assert_eq!(pio_dc_operators_n_branches(operators), 1);
26858
26859 assert_eq!(pio_dc_operators_n_buses(std::ptr::null()), 0);
26861 assert_eq!(pio_dc_operators_n_branches(std::ptr::null()), 0);
26862 let empty = pio_dc_operators_bus_ids(std::ptr::null());
26863 assert!(empty.data.is_null());
26864 assert_eq!(empty.len, 0);
26865
26866 pio_vector_release(injections);
26867 pio_vector_release(flows);
26868 pio_vector_release(bus_shift);
26869 pio_vector_release(branch_shift);
26870 pio_vector_release(susceptances);
26871 pio_sparse_matrix_release(branch_flow);
26872 pio_sparse_matrix_release(bus_susceptance);
26873 pio_sparse_matrix_release(incidence);
26874 pio_dc_operators_release(operators);
26875 pio_balanced_network_release(network);
26876 pio_value_release(value);
26877 pio_module_release(module);
26878 }
26879 }
26880
26881 #[test]
26882 fn powerio_ir_uses_serialize_and_deserialize() {
26883 unsafe {
26884 let module = parse_case9();
26885 let mut error = std::ptr::null_mut();
26886 let destination = pio_destination_memory(
26887 c"case.pio.json".as_ptr(),
26888 "case.pio.json".len(),
26889 &mut error,
26890 );
26891 let result = pio_module_serialize(module, destination, &mut error);
26892 assert!(!result.is_null(), "{}", error_text(error));
26893 let artifact = pio_emit_result_artifact(result, 0, &mut error);
26894 let bytes = pio_artifact_bytes(artifact);
26895 let source = pio_source_from_memory(
26896 c"case.pio.json".as_ptr(),
26897 "case.pio.json".len(),
26898 bytes.data,
26899 bytes.len,
26900 &mut error,
26901 );
26902 let decoded = pio_module_deserialize(source, &mut error);
26903 assert!(!decoded.is_null(), "{}", error_text(error));
26904
26905 pio_module_release(decoded);
26906 pio_source_release(source);
26907 pio_artifact_release(artifact);
26908 pio_emit_result_release(result);
26909 pio_destination_release(destination);
26910 pio_module_release(module);
26911 }
26912 }
26913
26914 fn synthetic_ac_opf_solution(
26917 instance: powerio_prob::AcOpfInstance,
26918 objective: f64,
26919 ) -> powerio_prob::AcOpfSolution {
26920 let network = instance.network().clone();
26921 let (buses, branches, generators) = (
26922 network.buses().len(),
26923 network.branches().len(),
26924 network.generators().len(),
26925 );
26926 powerio_prob::AcOpfSolution::new(
26927 Arc::new(instance),
26928 powerio_prob::Termination::NotReported,
26929 vec![1.01; buses],
26930 vec![0.0; buses],
26931 vec![0.0; buses],
26932 vec![0.0; buses],
26933 vec![0.0; branches],
26934 vec![0.0; branches],
26935 vec![0.0; branches],
26936 vec![0.0; branches],
26937 vec![12.0; generators],
26938 vec![3.0; generators],
26939 objective,
26940 vec![Default::default(); network.transformers_3w().len()],
26941 )
26942 .unwrap()
26943 }
26944
26945 unsafe fn error_code_text(error: *mut PioError) -> String {
26946 let code = unsafe { view_text(pio_error_code(error)) };
26947 unsafe { pio_error_release(error) };
26948 code
26949 }
26950
26951 unsafe fn ac_ots_switchable_set(module: *const PioModule) -> (Vec<bool>, usize) {
26954 unsafe {
26955 let mut error = std::ptr::null_mut();
26956 let value = pio_module_value(module);
26957 let instance = pio_value_ac_ots_instance(value, &mut error);
26958 assert!(!instance.is_null(), "{}", error_text(error));
26959 let mut options_view: PioAcOtsOptionsView = std::mem::zeroed();
26960 assert!(pio_ac_ots_instance_options(
26961 instance,
26962 &raw mut options_view,
26963 &mut error
26964 ));
26965 let mut switchable = Vec::new();
26966 for index in 0..options_view.branch_count {
26967 let mut branch: PioAcOtsBranchView = std::mem::zeroed();
26968 assert!(pio_ac_ots_instance_branch_at(
26969 instance,
26970 index,
26971 &raw mut branch,
26972 &mut error
26973 ));
26974 switchable.push(branch.switchable);
26975 }
26976 let terms = pio_calculation_instance_objective_term_count(instance);
26977 pio_calculation_instance_release(instance);
26978 pio_value_release(value);
26979 (switchable, terms)
26980 }
26981 }
26982
26983 #[test]
26984 fn null_options_give_the_same_instance_as_the_no_options_entry_point() {
26985 unsafe {
26986 let mut network = case9_network();
26989 network.branches_mut()[1].in_service = false;
26990 let network_module = module_handle(powerio::PioModule::new(PioValue::from(network)));
26991 let mut error = std::ptr::null_mut();
26992
26993 let plain = pio_module_to_ac_ots_instance(network_module, &mut error);
26994 assert!(!plain.is_null(), "{}", error_text(error));
26995 let with_null = pio_module_to_ac_ots_instance_with_options(
26996 network_module,
26997 std::ptr::null(),
26998 &mut error,
26999 );
27000 assert!(!with_null.is_null(), "{}", error_text(error));
27001 let (plain_set, plain_terms) = ac_ots_switchable_set(plain);
27002 let (null_set, null_terms) = ac_ots_switchable_set(with_null);
27003 let initially_closed: Vec<bool> = (0..9).map(|row| row != 1).collect();
27004 assert_eq!(plain_set, initially_closed);
27005 assert_eq!(null_set, plain_set);
27006 assert_eq!(null_terms, plain_terms);
27007
27008 let again =
27010 pio_module_to_ac_ots_instance_with_options(with_null, std::ptr::null(), &mut error);
27011 assert!(!again.is_null(), "{}", error_text(error));
27012 assert_eq!(ac_ots_switchable_set(again), (plain_set, plain_terms));
27013 }
27014 }
27015
27016 #[test]
27017 #[allow(clippy::too_many_lines)] fn ac_ots_entry_points_follow_the_julia_binding_flow() {
27019 unsafe {
27020 let mut network = case9_network();
27022 network.branches_mut()[1].in_service = false;
27023 let network_module = module_handle(powerio::PioModule::new(PioValue::from(network)));
27024 let mut error = std::ptr::null_mut();
27025
27026 let defaults = pio_module_to_ac_ots_instance(network_module, &mut error);
27027 assert!(!defaults.is_null(), "{}", error_text(error));
27028 let value = pio_module_value(defaults);
27029 let instance = pio_value_ac_ots_instance(value, &mut error);
27030 assert!(!instance.is_null(), "{}", error_text(error));
27031 let mut options_view: PioAcOtsOptionsView = std::mem::zeroed();
27032 assert!(pio_ac_ots_instance_options(
27033 instance,
27034 &raw mut options_view,
27035 &mut error
27036 ));
27037 assert_eq!(view_text(options_view.switchable), "only");
27038 assert_eq!(view_text(options_view.islanding), "forbidden");
27039 assert_eq!(view_text(options_view.current_limits), "skip");
27040 assert_eq!(options_view.branch_count, 9);
27041 assert!(!options_view.has_max_open);
27042 let mut branch: PioAcOtsBranchView = std::mem::zeroed();
27043 assert!(!pio_ac_ots_instance_branch_at(
27044 instance,
27045 9,
27046 &raw mut branch,
27047 &mut error
27048 ));
27049 assert_eq!(error_code_text(error), "BIND.CAPI.INDEX_OUT_OF_RANGE");
27050 let mut ids = Vec::new();
27051 for index in 0..9 {
27052 assert!(pio_ac_ots_instance_branch_at(
27053 instance,
27054 index,
27055 &raw mut branch,
27056 &mut error
27057 ));
27058 assert_eq!(branch.initial_closed, index != 1);
27059 assert_eq!(branch.switchable, index != 1);
27060 ids.push(view_text(branch.id));
27061 }
27062 pio_calculation_instance_release(instance);
27063 pio_value_release(value);
27064
27065 let costs = [
27067 PioBranchSwitchingCost {
27068 id: PioStringView::new(&ids[1]),
27069 open_cost: 4.0,
27070 close_cost: 7.0,
27071 },
27072 PioBranchSwitchingCost {
27073 id: PioStringView::new(&ids[2]),
27074 open_cost: 2.0,
27075 close_cost: 5.0,
27076 },
27077 ];
27078 let limits = [PioBranchCurrentLimit {
27079 id: PioStringView::new(&ids[1]),
27080 from_pu: 1.25,
27081 to_pu: 0.0,
27082 has_from_pu: true,
27083 has_to_pu: false,
27084 }];
27085 let mut options = PioAcOtsOptions {
27086 switchable: PioStringView::new("all"),
27087 identities: std::ptr::null(),
27088 identities_len: 0,
27089 switching_costs: costs.as_ptr(),
27090 switching_costs_len: costs.len(),
27091 islanding: PioStringView::new("forbidden"),
27092 max_open: 1,
27093 has_max_open: true,
27094 max_switched: 2,
27095 has_max_switched: true,
27096 current_limits: PioStringView::new("stated"),
27097 stated_current_limits: limits.as_ptr(),
27098 stated_current_limits_len: limits.len(),
27099 };
27100 let module = pio_module_to_ac_ots_instance_with_options(
27101 defaults,
27102 &raw const options,
27103 &mut error,
27104 );
27105 assert!(!module.is_null(), "{}", error_text(error));
27106 let value = pio_module_value(module);
27107 let instance = pio_value_ac_ots_instance(value, &mut error);
27108 assert!(!instance.is_null(), "{}", error_text(error));
27109 assert_eq!(
27110 view_text(pio_calculation_instance_type_name(instance)),
27111 "powerio.AcOtsInstance"
27112 );
27113 assert!(pio_ac_ots_instance_branch_at(
27114 instance,
27115 1,
27116 &raw mut branch,
27117 &mut error
27118 ));
27119 assert!(branch.switchable && branch.has_switching_cost);
27120 assert_eq!(branch.close_cost, 7.0);
27121 assert!(branch.has_current_from_pu && !branch.has_current_to_pu);
27122 assert_eq!(branch.current_from_pu, 1.25);
27123 assert_eq!(pio_calculation_instance_objective_term_count(instance), 2);
27124 let mut term: PioObjectiveTermView = std::mem::zeroed();
27125 assert!(pio_calculation_instance_objective_term_at(
27126 instance,
27127 1,
27128 &raw mut term,
27129 &mut error
27130 ));
27131 assert_eq!(view_text(term.kind), "branch_switching_cost");
27132 assert_eq!(
27133 pio_calculation_instance_active_constraint_count(instance),
27134 4
27135 );
27136 let network = pio_calculation_instance_balanced_network(instance, &mut error);
27137 assert!(!network.is_null(), "{}", error_text(error));
27138 pio_balanced_network_release(network);
27139
27140 options.islanding = PioStringView::new("sometimes");
27142 assert!(
27143 pio_module_to_ac_ots_instance_with_options(
27144 defaults,
27145 &raw const options,
27146 &mut error
27147 )
27148 .is_null()
27149 );
27150 assert_eq!(error_code_text(error), "BIND.CAPI.INVALID_OPTIONS");
27151 options.islanding = PioStringView::new("forbidden");
27152 let identities = [PioStringView::new(&ids[0])];
27153 options.identities = identities.as_ptr();
27154 options.identities_len = identities.len();
27155 assert!(
27156 pio_module_to_ac_ots_instance_with_options(
27157 defaults,
27158 &raw const options,
27159 &mut error
27160 )
27161 .is_null()
27162 );
27163 assert_eq!(error_code_text(error), "BIND.CAPI.INVALID_OPTIONS");
27164 let duplicate = [PioStringView::new(&ids[0]), PioStringView::new(&ids[0])];
27165 options.switchable = PioStringView::new("only");
27166 options.identities = duplicate.as_ptr();
27167 options.identities_len = duplicate.len();
27168 assert!(
27169 pio_module_to_ac_ots_instance_with_options(
27170 defaults,
27171 &raw const options,
27172 &mut error
27173 )
27174 .is_null()
27175 );
27176 assert_eq!(
27177 error_code_text(error),
27178 "BUILD.INSTANCE.SWITCHING_OPTIONS_INVALID"
27179 );
27180
27181 let mut closed = [1u8; 9];
27183 closed[2] = 0;
27184 let mut cost = 0.0;
27185 assert!(
27186 pio_ac_ots_instance_validate_topology(
27187 instance,
27188 closed.as_ptr(),
27189 closed.len(),
27190 &raw mut cost,
27191 &mut error
27192 ),
27193 "{}",
27194 error_text(error)
27195 );
27196 assert_eq!(cost, 9.0);
27197 assert!(!pio_ac_ots_instance_validate_topology(
27198 instance,
27199 closed.as_ptr(),
27200 1,
27201 &raw mut cost,
27202 &mut error
27203 ));
27204 assert_eq!(error_code_text(error), "BUILD.INSTANCE.TOPOLOGY_INVALID");
27205 let mut bad = closed;
27206 bad[0] = 2;
27207 assert!(!pio_ac_ots_instance_validate_topology(
27208 instance,
27209 bad.as_ptr(),
27210 bad.len(),
27211 &raw mut cost,
27212 &mut error
27213 ));
27214 assert_eq!(error_code_text(error), "BIND.CAPI.INVALID_ARGUMENT");
27215
27216 let fixed = pio_ac_ots_instance_fix_topology(
27218 instance,
27219 closed.as_ptr(),
27220 closed.len(),
27221 &mut error,
27222 );
27223 assert!(!fixed.is_null(), "{}", error_text(error));
27224 let fixed_module = &PioModule::get(fixed).unwrap().module;
27225 assert!(
27226 !fixed_module.diagnostics().is_empty(),
27227 "fixing the topology reports what the AC OPF leaves out"
27228 );
27229 let PioValue::AcOpfInstance(fixed_instance) = fixed_module.value() else {
27230 panic!("fix_topology returns an AC OPF instance")
27231 };
27232 let statuses: Vec<u8> = fixed_instance
27233 .network()
27234 .branches()
27235 .iter()
27236 .map(|branch| u8::from(branch.in_service))
27237 .collect();
27238 assert_eq!(statuses, closed);
27239 let ac_module = module_handle(powerio::PioModule::new(PioValue::AcOpfSolution(
27240 synthetic_ac_opf_solution(fixed_instance.clone(), 40.0),
27241 )));
27242 let ac_value = pio_module_value(ac_module);
27243 let ac_solution = pio_value_ac_opf_solution(ac_value, &mut error);
27244 assert!(!ac_solution.is_null(), "{}", error_text(error));
27245
27246 let all_closed = [1u8; 9];
27247 assert!(
27248 pio_ac_ots_solution_create(
27249 instance,
27250 all_closed.as_ptr(),
27251 all_closed.len(),
27252 ac_solution,
27253 &mut error
27254 )
27255 .is_null()
27256 );
27257 assert_eq!(error_code_text(error), "BUILD.SOLUTION.TOPOLOGY_MISMATCH");
27258 let solution_module = pio_ac_ots_solution_create(
27259 instance,
27260 closed.as_ptr(),
27261 closed.len(),
27262 ac_solution,
27263 &mut error,
27264 );
27265 assert!(!solution_module.is_null(), "{}", error_text(error));
27266 let solution_value = pio_module_value(solution_module);
27267 let solution = pio_value_ac_ots_solution(solution_value, &mut error);
27268 assert!(!solution.is_null(), "{}", error_text(error));
27269 let mut summary: PioAcOtsSolutionView = std::mem::zeroed();
27270 assert!(pio_ac_ots_solution_summary(
27271 solution,
27272 &raw mut summary,
27273 &mut error
27274 ));
27275 assert_eq!(summary.branch_count, 9);
27276 assert_eq!(summary.branches_open, 1);
27277 assert_eq!(summary.branches_switched, 2);
27278 assert_eq!(summary.switching_cost, 9.0);
27279 assert_eq!(summary.objective, 49.0);
27280 let mut objective = 0.0;
27281 assert!(pio_calculation_solution_get_objective(
27282 solution,
27283 &raw mut objective
27284 ));
27285 assert_eq!(objective, 49.0);
27286 assert_eq!(
27287 view_text(pio_calculation_solution_termination(solution)),
27288 "not_reported"
27289 );
27290 let mut status = true;
27291 assert!(pio_ac_ots_solution_branch_closed_at(
27292 solution,
27293 2,
27294 &raw mut status,
27295 &mut error
27296 ));
27297 assert!(!status);
27298 assert!(!pio_ac_ots_solution_branch_closed_at(
27299 solution,
27300 9,
27301 &raw mut status,
27302 &mut error
27303 ));
27304 assert_eq!(error_code_text(error), "BIND.CAPI.INDEX_OUT_OF_RANGE");
27305 let quantity = "bus_voltage_magnitude";
27306 let magnitudes = pio_calculation_solution_get_values(
27307 solution,
27308 quantity.as_ptr().cast(),
27309 quantity.len(),
27310 &mut error,
27311 );
27312 assert!(!magnitudes.is_null(), "{}", error_text(error));
27313 let view = pio_vector_values(magnitudes);
27314 assert_eq!(
27315 std::slice::from_raw_parts(view.data, view.len),
27316 &[1.01; 9][..]
27317 );
27318 pio_vector_release(magnitudes);
27319
27320 let solution_network = pio_calculation_solution_balanced_network(solution, &mut error);
27323 assert!(!solution_network.is_null(), "{}", error_text(error));
27324 pio_balanced_network_release(solution_network);
27325 let materialized = pio_ac_ots_solution_materialize(solution, &mut error);
27326 assert!(!materialized.is_null(), "{}", error_text(error));
27327 let PioValue::BalancedNetwork(materialized_network) =
27328 PioModule::get(materialized).unwrap().module.value()
27329 else {
27330 panic!("materialize returns a balanced network")
27331 };
27332 let statuses: Vec<u8> = materialized_network
27333 .branches()
27334 .iter()
27335 .map(|branch| u8::from(branch.in_service))
27336 .collect();
27337 assert_eq!(statuses, closed);
27338 pio_module_release(materialized);
27339
27340 let child = pio_calculation_solution_instance(solution, &mut error);
27342 assert!(!child.is_null(), "{}", error_text(error));
27343 pio_calculation_solution_release(solution);
27344 pio_value_release(solution_value);
27345 pio_module_release(solution_module);
27346 pio_calculation_solution_release(ac_solution);
27347 pio_value_release(ac_value);
27348 pio_module_release(ac_module);
27349 pio_module_release(fixed);
27350 pio_calculation_instance_release(instance);
27351 pio_value_release(value);
27352 pio_module_release(module);
27353 pio_module_release(defaults);
27354 pio_module_release(network_module);
27355 assert_eq!(
27356 view_text(pio_calculation_instance_type_name(child)),
27357 "powerio.AcOtsInstance"
27358 );
27359 assert!(pio_ac_ots_instance_options(
27360 child,
27361 &raw mut options_view,
27362 &mut error
27363 ));
27364 assert_eq!(options_view.max_switched, 2);
27365 assert!(pio_ac_ots_instance_branch_at(
27366 child,
27367 1,
27368 &raw mut branch,
27369 &mut error
27370 ));
27371 assert_eq!(view_text(branch.id), ids[1]);
27372 pio_calculation_instance_release(child);
27373 }
27374 }
27375
27376 #[test]
27377 fn an_ac_ots_instance_is_created_from_an_ac_opf_base() {
27378 unsafe {
27379 let module = parse_case9();
27380 let mut error = std::ptr::null_mut();
27381 let opf = pio_module_to_ac_opf_instance(module, &mut error);
27382 assert!(!opf.is_null(), "{}", error_text(error));
27383 let value = pio_module_value(opf);
27384 let base = pio_value_ac_opf_instance(value, &mut error);
27385 assert!(!base.is_null(), "{}", error_text(error));
27386 let created = pio_ac_ots_instance_create(base, std::ptr::null(), &mut error);
27387 assert!(!created.is_null(), "{}", error_text(error));
27388 let created_value = pio_module_value(created);
27389 let instance = pio_value_ac_ots_instance(created_value, &mut error);
27390 assert!(!instance.is_null(), "{}", error_text(error));
27391 let mut options: PioAcOtsOptionsView = std::mem::zeroed();
27392 assert!(pio_ac_ots_instance_options(
27393 instance,
27394 &raw mut options,
27395 &mut error
27396 ));
27397 assert_eq!(view_text(options.switchable), "all");
27398 assert_eq!(
27400 pio_calculation_instance_objective_term_count(instance),
27401 pio_calculation_instance_objective_term_count(base)
27402 );
27403 assert!(pio_ac_ots_instance_create(instance, std::ptr::null(), &mut error).is_null());
27405 assert_eq!(error_code_text(error), "REQUEST.CAPI.TYPE_MISMATCH");
27406 pio_calculation_instance_release(instance);
27407 pio_value_release(created_value);
27408 pio_module_release(created);
27409 pio_calculation_instance_release(base);
27410 pio_value_release(value);
27411 pio_module_release(opf);
27412 pio_module_release(module);
27413 }
27414 }
27415}