qsim_io/
network.rs

1//! Network serialization
2
3use qsim_elements::{Branch, Bus, Generator, Load};
4use serde::{Deserialize, Serialize};
5
6/// Network definition for JSON serialization
7#[derive(Debug, Clone, Serialize, Deserialize)]
8pub struct NetworkData {
9    /// Network name
10    #[serde(default)]
11    pub name: String,
12    /// Base MVA for per-unit conversion
13    #[serde(default = "default_base_mva")]
14    pub base_mva: f64,
15    /// Buses
16    pub buses: Vec<Bus>,
17    /// Branches
18    pub branches: Vec<Branch>,
19    /// Generators
20    #[serde(default)]
21    pub generators: Vec<Generator>,
22    /// Loads
23    #[serde(default)]
24    pub loads: Vec<Load>,
25}
26
27fn default_base_mva() -> f64 {
28    100.0
29}
30
31impl NetworkData {
32    /// Create an empty network
33    pub fn new(name: impl Into<String>) -> Self {
34        Self {
35            name: name.into(),
36            base_mva: 100.0,
37            buses: Vec::new(),
38            branches: Vec::new(),
39            generators: Vec::new(),
40            loads: Vec::new(),
41        }
42    }
43
44    /// Load network from JSON string
45    pub fn from_json(json: &str) -> Result<Self, serde_json::Error> {
46        serde_json::from_str(json)
47    }
48
49    /// Save network to JSON string
50    pub fn to_json(&self) -> Result<String, serde_json::Error> {
51        serde_json::to_string_pretty(self)
52    }
53
54    /// Load network from file
55    pub fn from_file(path: impl AsRef<std::path::Path>) -> Result<Self, std::io::Error> {
56        let json = std::fs::read_to_string(path)?;
57        serde_json::from_str(&json).map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))
58    }
59
60    /// Save network to file
61    pub fn to_file(&self, path: impl AsRef<std::path::Path>) -> Result<(), std::io::Error> {
62        let json = serde_json::to_string_pretty(self)
63            .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
64        std::fs::write(path, json)
65    }
66}
67
68impl Default for NetworkData {
69    fn default() -> Self {
70        Self::new("Unnamed Network")
71    }
72}