reda-spice 0.1.0

Spice simulate and parse library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
mod api;
mod plot;
mod callback;

use std::sync::atomic::{AtomicI32, Ordering};
use std::sync::LazyLock;
use std::collections::HashMap;
use std::env;
use std::path::{Path, PathBuf};
use std::ffi::{CStr, CString, c_char, c_double, c_int, c_void};
use api::{NgSpiceAPI, VecData, VecInfoAll, VecValuesAll};
use libloading::Library;
use num_complex::Complex64;
use plot::Plot;
use regex::Regex;
use callback::{DefaultNgSpiceSharedCallback, NgSpiceSharedCallback};
use crate::probe::{AcAnalysis, DcVoltageAnalysis, OpAnalysis, ToAnalysis, TranAnalysis};
use crate::simulate::Simulate;
use crate::Value;

use super::error::*;

#[cfg(unix)]
use libc::setlocale;
#[cfg(unix)]
use libc::LC_NUMERIC;

static NGSPICE_ID: LazyLock<AtomicI32> = LazyLock::new(|| AtomicI32::new(0));
fn next_count() -> i32 {
    NGSPICE_ID.fetch_add(1, Ordering::SeqCst)
}

pub struct NgSpiceShared {
    ngspice_id: i32,
    pub api: NgSpiceAPI,
    callback: Box<dyn NgSpiceSharedCallback>,
    library_path: PathBuf,

    stdout: Vec<String>,
    stderr: Vec<String>,
    error_in_stdout: bool,
    error_in_stderr: bool,
    spinit_not_found: bool,
    is_running: bool,

    ngspice_version: Option<u32>,
    has_xspice: bool,
    has_cider: bool,
    extensions: Vec<String>,
}


impl NgSpiceShared {
    pub fn default() -> NgSpiceResult<Self> {
        Self::new_with_callback(None, DefaultNgSpiceSharedCallback)
    }

    pub fn new(library_path: PathBuf) -> NgSpiceResult<Self> {
        Self::new_with_callback(Some(library_path), DefaultNgSpiceSharedCallback)
    }

    pub fn new_with_callback(
        library_path: Option<PathBuf>, 
        callback: impl NgSpiceSharedCallback + 'static
    ) -> NgSpiceResult<Self> {
        let ngspice_id = next_count();
    
        let library_path = match library_path {
            Some(p) => p,
            None => Self::setup_platform()?,
        };
        
        let lib = Self::load_library(&library_path)?;
        let api = NgSpiceAPI::new(lib);

        Ok(NgSpiceShared {
            library_path,
            callback: Box::new(callback),
            api,
            stdout: vec![],
            stderr: vec![],
            error_in_stdout: false,
            error_in_stderr: false,
            spinit_not_found: false,
            is_running: false,
            ngspice_id,
            ngspice_version: None,
            has_xspice: false,
            has_cider: false,
            extensions: Vec::new(),
        })
    }

    fn setup_platform() -> NgSpiceResult<PathBuf> {
        if let Ok(path) = env::var("NGSPICE_LIBRARY_PATH") {
            return Ok(PathBuf::from(path))
        }

        #[cfg(target_os = "linux")] {
            return Ok(PathBuf::from("libngspice.so"));
        }

        #[allow(unreachable_code)]
        Err(NgSpiceError::Platform)
    }

    fn load_library<P: AsRef<Path>>(library_path: P) -> NgSpiceResult<Library> {
        let library_path = library_path.as_ref();
        #[cfg(target_os = "linux")] {
            unsafe {
                let c_locale = CString::new("C").unwrap();
                setlocale(LC_NUMERIC, c_locale.as_ptr());
            }
        }

        log::debug!("Loading ngspice library: {:?}", library_path);
        let lib = unsafe { Library::new(library_path)? };

        Ok(lib)
    } 
}

impl NgSpiceShared {
    pub fn init(&mut self) -> NgSpiceResult<()> {
        self.api.init(
            Some(Self::send_char_callback), 
            Some(Self::send_stat_callback), 
            Some(Self::exit_callback),
            Some(Self::send_data_callback), 
            Some(Self::send_init_data_callback), 
            Some(Self::background_thread_running_callback), 
            self as *const Self as *mut c_void
        );

        self.api.init_sync(
            Some(Self::get_vsrc_data_callback), 
            Some(Self::get_isrc_data_callback), 
            None,
            &self.ngspice_id as *const i32 as *mut i32, 
            self as *const Self as *mut c_void
        );

        self.get_infomation()
    }

    pub fn exec_command(&mut self, command: &str) -> NgSpiceResult<String> {
        log::debug!("Execute command: {}", command);
        self.clear_output();

        let result = self.api.command(command).unwrap();
        if result != 0 {
            return Err(NgSpiceError::command(
                command.into(),
                format!("ngSpice_Command return '{}'", result)
            ));
        }

        if self.error_in_stdout || self.error_in_stderr {
            return Err(NgSpiceError::command(
                command.into(),
                "Error in stdout/stderr".into()
            ));
        } 

        Ok(self.stdout())
    }

    pub fn set(&mut self, key: &str) -> NgSpiceResult<()> {
        self.exec_command(&format!("set {}", key))?;
        Ok(())
    }

    pub fn reset(&mut self) -> NgSpiceResult<()> {
        self.exec_command("reset")?;
        Ok(())
    }

    pub fn status(&mut self) -> NgSpiceResult<String> {
        self.exec_command("status")
    }

    pub fn step(&mut self, step: Option<usize>) -> NgSpiceResult<()> {
        match step {
            Some(step) => self.exec_command(&format!("step {}", step))?,
            None => self.exec_command("step")?
        };
        Ok(())
    }

    pub fn listing(&mut self) -> NgSpiceResult<String> {
        self.exec_command("listing")
    }

    pub fn load_circuit(&mut self, circuit: &str) -> NgSpiceResult<()> {
        let circuit_lines: Vec<_> = circuit
            .lines()
            .collect();

        self.clear_output();
        let result = self.api.circ(&circuit_lines).unwrap();
        if result != 0 {
            return Err(NgSpiceError::circuit(circuit.into(), format!("ngSpice_Circ returned {}", result)));
        }

        if self.error_in_stdout || self.error_in_stderr {
            return Err(NgSpiceError::circuit(
                circuit.into(),
                "Error in stdout/stderr".into()
            ));
        } 

        Ok(())
    }

    /// Run the simulation
    pub fn run(&mut self, background: bool) -> NgSpiceResult<()> {
        let command = if background { "bg_run" } else { "run" };
        self.exec_command(command)?;

        if background {
            self.is_running = true;
        } else {
            log::debug!("Simulation is done");
        }
        
        Ok(())
    }

    pub fn halt(&mut self) -> NgSpiceResult<()> {
        self.exec_command("bg_halt")?;
        Ok(())
    }

    pub fn resume(&mut self, background: bool) -> NgSpiceResult<()> {
        let command = if background { "bg_resume" } else { "resume" };
        self.exec_command(command)?;
        Ok(())
    }

    pub fn get_vec(&self, name: &str) -> NgSpiceResult<Vec<f64>> {
        match self.api.get_vec_real_data(name).unwrap() {
            Some(data) => Ok(data),
            None => Err(NgSpiceError::ResultNotFound(name.into())),
        }
    }

    pub fn get_plot(&self, plot_name: &str) -> NgSpiceResult<Plot> {
        let vec_names = self.api.all_vecs(plot_name)?;
        let mut vectors = HashMap::new();

        for name in vec_names {
            let full_name = format!("{}.{}", plot_name, name);
            match self.api.get_vec_data(&full_name) {
                Ok(Some(data)) => {
                    match data {
                        VecData::Real(values) => {
                            let values = values.into_iter().map(|v| Value::real(v)).collect();
                            vectors.insert(name.clone(), values);
                        }
                        VecData::Complex(values) => {
                            let values = values.into_iter().map(|(re, im)| Value::complex(re, im)).collect();
                            vectors.insert(name.clone(), values);
                        }
                    }
                }
                _ => {
                    eprintln!("Warning: failed to load vector {}", full_name);
                }
            }
        }

        Ok(Plot {
            name: plot_name.to_string(),
            vectors,
        })
    }

    pub fn destroy(&mut self, plot_name: &str) -> NgSpiceResult<()> {
        self.exec_command(&format!("destroy {}", plot_name))?;
        Ok(())
    }

    pub fn destroy_all(&mut self) -> NgSpiceResult<()> {
        self.exec_command("destroy all")?;
        Ok(())
    }

    pub fn get_infomation(&mut self) -> NgSpiceResult<()> {
        self.ngspice_version = None;
        self.has_xspice = false;
        self.has_cider = false;
        self.extensions.clear();

        let output = self.exec_command("version -f")?;
        let version_regex = Regex::new(r"\*\* ngspice-(\d+)").unwrap();

        for line in output.lines() {
            if let Some(caps) = version_regex.captures(line) {
                if let Some(matched) = caps.get(1) {
                    self.ngspice_version = matched.as_str().parse::<u32>().ok();
                }
            }

            if line.contains("** XSPICE") {
                self.has_xspice = true;
                self.extensions.push("XSPICE".to_string());
            }

            if line.contains("CIDER") {
                self.has_cider = true;
                self.extensions.push("CIDER".to_string());
            }
        }

        log::debug!(
            "Ngspice version {:?} with extensions: {}",
            self.ngspice_version,
            self.extensions.join(", ")
        );

        Ok(())
    }

    fn clear_output(&mut self) {
        self.stdout.clear();
        self.stderr.clear();
        self.error_in_stdout = false;
        self.error_in_stderr = false;
    }
}

/// Property
impl NgSpiceShared {
    pub fn stdout(&self) -> String {
        self.stdout.join(" ")
    }

    pub fn stderr(&self) -> String {
        self.stderr.join(" ")
    }

    pub fn is_running(&self) -> bool {
        self.is_running
    }

    pub fn library_path(&self) -> &Path {
        self.library_path.as_path()
    }

    pub fn ngspice_version(&self) -> u32 {
        self.ngspice_version.unwrap()
    }

    pub fn has_xspice(&self) -> bool {
        self.has_xspice
    }

    pub fn has_cider(&self) -> bool {
        self.has_cider
    }

    pub fn set_callback(&mut self, callback: impl NgSpiceSharedCallback + 'static) {
        self.callback = Box::new(callback)
    }
}

impl NgSpiceShared {
    unsafe extern "C" fn send_char_callback(message_c: *mut c_char, id: c_int, user_data: *mut c_void) -> c_int {
        let shared: &mut Self = unsafe { &mut *(user_data as *mut Self) };
        let message = unsafe { match CStr::from_ptr(message_c).to_str() {
            Ok(s) => s.to_string(),
            Err(_) => return 1,
        }};

        log::debug!("[ngSpice raw] {message}");

        let (prefix, content) = if let Some(pos) = message.find(' ') {
            message.split_at(pos)
        } else {
            ("", &message[..])
        };

        let content = content.trim_start();

        if prefix == "stderr" {
            shared.stderr.push(content.to_string());
            if content.starts_with("Warning:") {
                eprintln!("[ngSpice warning] {content}");
            } else {
                shared.error_in_stderr = true;
                if content == "Note: can't find init file." {
                    shared.spinit_not_found = true;
                    eprintln!("[ngSpice warning] spinit was not found");
                } else {
                    eprintln!("[ngSpice error] {content}");
                }
            }
        } else {
            shared.stdout.push(content.to_string());
            if content.to_lowercase().contains("error") {
                shared.error_in_stdout = true;
                eprintln!("[ngSpice error? stdout] {content}");
            } else {
                println!("[ngSpice] {content}");
            }
        }

        shared.callback.send_char(&message, id)
    }

    unsafe extern "C" fn send_stat_callback(message_c: *mut c_char, id: c_int, user_data: *mut c_void) -> c_int {
        let shared: &mut Self = unsafe { &mut *(user_data as *mut Self) };
        let message = unsafe { match CStr::from_ptr(message_c).to_str() {
            Ok(s) => s.to_string(),
            Err(_) => return 1,
        }};

        shared.callback.send_stat(&message, id)
    }

    unsafe extern "C" fn exit_callback(exit_status: c_int, immediate_unloding: bool, quit_exit: bool, ngspice_id: c_int, _user_data: *mut c_void) -> c_int {
        log::debug!(
            "ngspice_id-{} exit status={} immediate_unloding={} quit_exit={}",
            ngspice_id,
            exit_status,
            immediate_unloding,
            quit_exit
        );
        exit_status
    }

    unsafe extern "C" fn send_data_callback(data: *mut VecValuesAll, number_of_vectors: c_int, ngspice_id: c_int, user_data: *mut c_void) -> c_int {
        let handler = unsafe { &mut *(user_data as *mut Self) };
        let data_ref = unsafe { &*data };
        let vecsa_array = unsafe { 
            std::slice::from_raw_parts(data_ref.vecsa, number_of_vectors as usize)
        };

        let mut actual_vector_values = HashMap::new();
        for &vec_ptr in vecsa_array {
            if vec_ptr.is_null() {
                continue;
            }
    
            let vec = unsafe { &*vec_ptr };
    
            let name = if vec.name.is_null() {
                "<null>".to_string()
            } else {
                unsafe { CStr::from_ptr(vec.name).to_string_lossy().into_owned() }
            };
    
            let value = Complex64::new(vec.creal, vec.cimag);
            actual_vector_values.insert(name, value);
        }
        
        handler.callback.send_data(actual_vector_values, number_of_vectors, ngspice_id)
    }

    unsafe extern "C" fn send_init_data_callback(data: *mut VecInfoAll, ngspice_id: c_int, user_data: *mut c_void) -> c_int {
        let handler = unsafe { &mut *(user_data as *mut Self) };
        if data.is_null() {
            return 0;
        }
        let data_ref = unsafe { &*data };
        handler.callback.send_init_data(data_ref, ngspice_id)
    }

    unsafe extern "C" fn background_thread_running_callback(is_running: bool, ngspice_id: c_int, user_data: *mut c_void) -> c_int {
        let handler = unsafe { &mut *(user_data as *mut Self) };
        log::debug!("ngspice_id-{} background_thread_running {}", ngspice_id, is_running);
        handler.is_running = is_running;
        0
    }

    unsafe extern "C" fn get_vsrc_data_callback(voltage: *mut c_double, time: c_double, node: *mut c_char, ngspice_id: c_int, user_data: *mut c_void) -> c_int {
        let handler = unsafe { &mut *(user_data as *mut Self) };
        let node = unsafe { match CStr::from_ptr(node).to_str() {
            Ok(s) => s.to_string(),
            Err(_) => return 1,
        }};
        let voltage = unsafe { &mut *voltage };

        handler.callback.get_vsrc_data(voltage, time, node, ngspice_id)
    }

    unsafe extern "C" fn get_isrc_data_callback(current: *mut c_double, time: c_double, node: *mut c_char, ngspice_id: c_int, user_data: *mut c_void) -> c_int {
        let handler = unsafe { &mut *(user_data as *mut Self) };
        let node = unsafe { match CStr::from_ptr(node).to_str() {
            Ok(s) => s.to_string(),
            Err(_) => return 1,
        }};
        let current = unsafe { &mut *current }; 

        handler.callback.get_isrc_data(current, time, node, ngspice_id)
    }
}

impl NgSpiceShared {
    pub fn simulate(&mut self, circuit: &str) -> NgSpiceResult<Plot> {
        self.init()?;
        // self.destroy_all()?;
        self.load_circuit(circuit)?;
        self.run(false)?;
        let plot_name = self.api.cur_plot().unwrap();
        let plot = self.get_plot(&plot_name)?;
        Ok(plot)
    }
}

impl Simulate for NgSpiceShared {
    type Err = NgSpiceError;

    fn run_dc(&mut self, netlist: &str) -> Result<DcVoltageAnalysis, Self::Err> {
        let plot = self.simulate(netlist)?;
        plot.to_dc_voltage_analysis()
    }

    fn run_op(&mut self, netlist: &str) -> Result<OpAnalysis, Self::Err> {
        let plot = self.simulate(netlist)?;
        plot.to_op_analysis()
    }

    fn run_tran(&mut self, netlist: &str) -> Result<TranAnalysis, Self::Err> {
        let plot = self.simulate(netlist)?;
        plot.to_tran_analysis()    
    }
    
    fn run_ac(&mut self, netlist: &str) -> Result<AcAnalysis, Self::Err> {
        let plot = self.simulate(netlist)?;
        plot.to_ac_analysis()
    }
}

#[allow(unused)]
#[cfg(test)]
mod tests {
    use reda_unit::{num, u};
    use crate::simulate::ngspice::shared;

    use super::*;
    use std::ffi::CString;
    use std::os::raw::{c_char, c_int};
    use callback::DefaultNgSpiceSharedCallback;
    use libloading::Symbol;

    #[test]
    fn test_load_lib() {
        let mut ng = NgSpiceShared::default().expect("Failed to create NgSpiceShared");
        ng.init().expect("Failed to init ngspice");
        ng.exec_command("version");

    }

    #[test]
    fn test_use_shared() {
        let mut ng = NgSpiceShared::default().expect("Failed to create NgSpiceShared");
        ng.init().expect("Failed to init ngspice");
    
        let netlist = r#"
* RC low-pass filter
V1 in 0 DC 1
R1 in out 1k
C1 out 0 1u
.IC V(out)=0
.tran 1u 1m
.end
    "#;
    
        ng.load_circuit(netlist).expect("Failed to load circuit");
        ng.run(false).expect("Failed to run simulation");
    
        let time = ng.api.get_vec_real_data("time")
            .expect("Vec access failed")
            .expect("Missing time vector");
    
        let vout = ng.api.get_vec_real_data("v(out)")
            .expect("Vec access failed")
            .expect("Missing v(out) vector");

        println!("v(out): {:?}", &vout);
        println!("{}", time.len());
        println!("{}", vout.len());
    }

    #[test]
    fn test_tran_analysis() {
        let mut ng = NgSpiceShared::default().expect("Failed to create NgSpiceShared");
        ng.init().expect("Failed to init ngspice");
    
        let netlist = r#"
* RC low-pass filter
V1 in 0 DC 1
R1 in out 1k
C1 out 0 1u
.IC V(out)=0
.tran 1u 1m
.end
    "#;
    
        ng.load_circuit(netlist).expect("Failed to load circuit");
        ng.run(false).expect("Failed to run simulation");

        let plot_name = ng.api.cur_plot().expect("No current plot");
        let plot = ng.get_plot(&plot_name).expect("plot");
        let analysis = plot.to_tran_analysis().expect("ana");

        println!("{}", analysis.time.len());

        println!("node:");
        for (name, values) in analysis.nodes.iter() {
            println!("{}", name);
        }
        
        println!("branches:");
        for (name, values) in analysis.branches.iter() {
            println!("{}", name);
        }
        
        println!("internal_parameters:");
        for (name, values) in analysis.internal_parameters.iter() {
            println!("{}", name);
        }

        println!("{}", analysis.get_voltage_at("out", u!(200 us)).unwrap());
    }

    #[test]
    fn test_dc_analysis() {
        let mut ng = NgSpiceShared::default()
            .expect("Failed to create NgSpiceShared");
        ng.init().expect("Failed to init ngspice");
    
        let netlist = r#"
    * Simple DC Sweep
    V1 in 0 DC 0
    R1 in out 2k
    R2 out 0 1k
    .dc V1 0 5 0.1
    .end
        "#;
    
        ng.load_circuit(netlist).expect("Failed to load circuit");
        ng.run(false).expect("Failed to run simulation");
    
        let plot_name = ng.api.cur_plot().expect("No current plot");
        let plot = ng.get_plot(&plot_name).expect("Failed to get plot");
    
        let analysis = plot.to_dc_voltage_analysis().expect("Failed to convert to DC analysis");
    
        println!("Sweep points: {}", analysis.sweep.len());
    
        println!("Nodes:");
        for (name, _) in analysis.nodes.iter() {
            println!("  {}", name);
        }
    
        println!("Branches:");
        for (name, _) in analysis.branches.iter() {
            println!("  {}", name);
        }
    
        println!("Internal parameters:");
        for (name, _) in analysis.internal_parameters.iter() {
            println!("  {}", name);
        }
    
        // 测试一个节点电压(如 "out")在扫到 V1 = 2.0V 时的值
        let vout = analysis.get_voltage_at("out", u!(2.0 V));
        match vout {
            Some(val) => println!("Voltage at out when V1=2.0V: {} V", val.to_f64()),
            None => println!("No matching voltage value found for V1=2.0V"),
        }
    }
    
    #[test]
    fn test_operating_point_analysis() {
        let mut ng = 
            NgSpiceShared::default()
            .expect("Failed to create NgSpiceShared");
        ng.init().expect("Failed to init ngspice");
    
        let netlist = r#"
    * Operating Point Test
    V1 in 0 DC 5
    R1 in out 1k
    R2 out 0 2k
    .op
    .end
        "#;
    
        ng.load_circuit(netlist).expect("Failed to load circuit");
        ng.run(false).expect("Failed to run simulation");
    
        let plot_name = ng.api.cur_plot().expect("No current plot");
        let plot = ng.get_plot(&plot_name).expect("Failed to get plot");
    
        let analysis = plot
            .to_op_analysis()
            .expect("Failed to convert to operating point analysis");
    
        println!("Nodes:");
        for (name, values) in &analysis.nodes {
            println!("  {}: {:?}", name, values);
        }
    
        println!("Branches:");
        for (name, values) in &analysis.branches {
            println!("  {}: {:?}", name, values);
        }
    
        println!("Internal parameters:");
        for (name, values) in &analysis.internal_parameters {
            println!("  {}: {:?}", name, values);
        }
    
        // 检查输出节点的电压值
        let vout = analysis.nodes.get("out").unwrap();
        println!("{}", vout);
    }
    
}