1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
//! Spectre plugin for Substrate.
#![warn(missing_docs)]

use std::collections::{HashMap, HashSet};
use std::fmt::{Display, Formatter};
use std::io::Write;
#[cfg(any(unix, target_os = "redox"))]
use std::os::unix::prelude::PermissionsExt;
use std::path::{Path, PathBuf};
use std::sync::Arc;

use crate::analysis::ac::{Ac, Sweep};
use crate::analysis::montecarlo;
use crate::analysis::montecarlo::MonteCarlo;

use analysis::ac;
use analysis::tran;
use analysis::tran::Tran;
use arcstr::ArcStr;
use cache::error::TryInnerError;
use cache::CacheableWithState;
use error::*;
use itertools::Itertools;
use lazy_static::lazy_static;
use num::complex::Complex64;
use psfparser::analysis::ac::AcData;
use psfparser::analysis::transient::TransientData;
use regex::Regex;
use rust_decimal::Decimal;
use scir::schema::{FromSchema, NoSchema, NoSchemaError};
use scir::{
    Library, NamedSliceOne, NetlistLibConversion, ParamValue, SignalInfo, Slice, SliceOnePath,
};
use serde::{Deserialize, Serialize};
use spice::netlist::{
    HasSpiceLikeNetlist, Include, NetlistKind, NetlistOptions, NetlisterInstance, RenameGround,
};
use spice::{BlackboxContents, BlackboxElement, Spice};
use substrate::block::Block;
use substrate::context::Installation;
use substrate::execute::Executor;
use substrate::io::schematic::HardwareType;
use substrate::io::schematic::NodePath;
use substrate::schematic::conv::ConvertedNodePath;
use substrate::schematic::netlist::ConvertibleNetlister;
use substrate::schematic::primitives::{Capacitor, RawInstance, Resistor};
use substrate::schematic::schema::Schema;
use substrate::schematic::{CellBuilder, PrimitiveBinding, Schematic};
use substrate::simulation::options::ic::InitialCondition;
use substrate::simulation::options::{ic, SimOption, Temperature};
use substrate::simulation::{SimulationContext, Simulator, SupportedBy};
use substrate::type_dispatch::impl_dispatch;
use templates::{write_run_script, RunScriptContext};

pub mod analysis;
pub mod blocks;
pub mod dspf;
pub mod error;
pub(crate) mod templates;

/// Spectre primitives.
#[derive(Debug, Clone)]
pub enum Primitive {
    /// A raw instance with an associated cell.
    RawInstance {
        /// The associated cell.
        cell: ArcStr,
        /// The ordered ports of the instance.
        ports: Vec<ArcStr>,
        /// Parameters associated with the instance.
        params: HashMap<ArcStr, ParamValue>,
    },
    /// A raw instance with an associated cell represented in SPF format.
    ///
    /// Parameters are not supported.
    SpfInstance {
        /// The name of the associated cell.
        cell: ArcStr,
        /// The path to the SPF netlist.
        netlist: PathBuf,
        /// The ordered ports of the instance.
        ports: Vec<ArcStr>,
    },
    /// An instance with blackboxed contents.
    BlackboxInstance {
        /// The contents of the cell.
        contents: BlackboxContents,
    },
    /// A SPICE primitive.
    ///
    /// Integrated using `simulator lang=spice`.
    Spice(spice::Primitive),
}

/// Spectre error presets.
#[derive(
    Copy, Clone, Debug, Default, Eq, PartialEq, Hash, Ord, PartialOrd, Serialize, Deserialize,
)]
pub enum ErrPreset {
    /// Liberal.
    Liberal,
    /// Moderate.
    #[default]
    Moderate,
    /// Conservative.
    Conservative,
}

impl Display for ErrPreset {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match *self {
            Self::Liberal => write!(f, "liberal"),
            Self::Moderate => write!(f, "moderate"),
            Self::Conservative => write!(f, "conservative"),
        }
    }
}

/// A signal referenced by a save/ic Spectre statement.
#[derive(Debug, Clone, Eq, PartialEq, Hash, Ord, PartialOrd)]
pub enum SimSignal {
    /// A raw string to follow "save/ic".
    Raw(ArcStr),
    /// A SCIR signal path representing a node whose voltage should be referenced.
    ScirVoltage(SliceOnePath),
    /// A SCIR signal path representing a terminal whose current should be referenced.
    ScirCurrent(SliceOnePath),

    /// An instance path followed by a raw tail path.
    InstanceTail(InstanceTail),
}

/// An instance path followed by a raw tail path.
#[derive(Debug, Clone, Eq, PartialEq, Hash, Ord, PartialOrd)]
pub struct InstanceTail {
    /// The path to the instance.
    pub instance: scir::InstancePath,
    /// The raw tail string.
    pub tail: ArcStr,
}

impl<T: Into<ArcStr>> From<T> for SimSignal {
    fn from(value: T) -> Self {
        Self::Raw(value.into())
    }
}

impl From<InstanceTail> for SimSignal {
    fn from(value: InstanceTail) -> Self {
        Self::InstanceTail(value)
    }
}

impl SimSignal {
    /// Creates a new [`SimSignal`].
    pub fn new(path: impl Into<ArcStr>) -> Self {
        Self::from(path)
    }

    pub(crate) fn to_string(&self, lib: &Library<Spectre>, conv: &NetlistLibConversion) -> ArcStr {
        match self {
            SimSignal::Raw(raw) => raw.clone(),
            SimSignal::ScirCurrent(scir) => {
                ArcStr::from(Spectre::node_current_path(lib, conv, scir))
            }
            SimSignal::ScirVoltage(scir) => {
                ArcStr::from(Spectre::node_voltage_path(lib, conv, scir))
            }
            SimSignal::InstanceTail(itail) => {
                let ipath = Spectre::instance_path(lib, conv, &itail.instance);
                arcstr::format!("{}.{}", ipath, itail.tail)
            }
        }
    }
}

/// Spectre simulator global configuration.
#[derive(Debug, Clone, Default)]
pub struct Spectre {}

/// Spectre per-simulation options.
///
/// A single simulation contains zero or more analyses.
#[derive(Debug, Clone, Default)]
pub struct Options {
    includes: HashSet<Include>,
    saves: HashMap<SimSignal, u64>,
    ics: HashMap<SimSignal, Decimal>,
    next_save_key: u64,
    /// The simulation temperature.
    temp: Option<Decimal>,
    save: Option<SaveOption>,
    /// Override the default Spectre flags.
    override_flags: Option<String>,
}

/// The allowed values of the `save` option.
#[derive(Copy, Clone, Debug, Default)]
pub enum SaveOption {
    /// All signals.
    All,
    /// All signals up to `nestlvl` deep in the subcircuit hierarchy.
    Lvl,
    /// All public signals.
    ///
    /// Excludes certain currents and internal nodes.
    AllPub,
    /// All public signals up to `nestlvl` deep in the subcircuit hierarchy.
    ///
    /// Excludes certain currents and internal nodes.
    LvlPub,
    /// Save only selected signals.
    ///
    /// This is the default behavior of Spectre.
    #[default]
    Selected,
    /// Save no signals.
    None,
}

impl SaveOption {
    /// The Spectre string corresponding to this [`SaveOption`].
    fn as_str(&self) -> &'static str {
        match *self {
            SaveOption::All => "all",
            SaveOption::Lvl => "lvl",
            SaveOption::AllPub => "allpub",
            SaveOption::LvlPub => "lvlpub",
            SaveOption::Selected => "selected",
            SaveOption::None => "none",
        }
    }
}

impl Display for SaveOption {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

impl Options {
    /// Include the given file.
    pub fn include(&mut self, path: impl Into<PathBuf>) {
        self.includes.insert(Include::new(path));
    }
    /// Include the given section of a file.
    pub fn include_section(&mut self, path: impl Into<PathBuf>, section: impl Into<ArcStr>) {
        self.includes.insert(Include::new(path).section(section));
    }

    fn save_inner(&mut self, save: impl Into<SimSignal>) -> u64 {
        let save = save.into();

        if let Some(key) = self.saves.get(&save) {
            *key
        } else {
            let save_key = self.next_save_key;
            self.next_save_key += 1;
            self.saves.insert(save, save_key);
            save_key
        }
    }

    fn set_ic_inner(&mut self, key: impl Into<SimSignal>, value: Decimal) {
        self.ics.insert(key.into(), value);
    }

    /// Marks a transient voltage to be saved in all transient analyses.
    pub fn save_tran_voltage(&mut self, save: impl Into<SimSignal>) -> tran::VoltageSavedKey {
        tran::VoltageSavedKey(self.save_inner(save))
    }

    /// Marks a transient current to be saved in all transient analyses.
    pub fn save_tran_current(&mut self, save: impl Into<SimSignal>) -> tran::CurrentSavedKey {
        tran::CurrentSavedKey(vec![self.save_inner(save)])
    }

    /// Marks an AC voltage to be saved in all AC analyses.
    pub fn save_ac_voltage(&mut self, save: impl Into<SimSignal>) -> ac::VoltageSavedKey {
        ac::VoltageSavedKey(self.save_inner(save))
    }

    /// Marks an AC current to be saved in all AC analyses.
    pub fn save_ac_current(&mut self, save: impl Into<SimSignal>) -> ac::CurrentSavedKey {
        ac::CurrentSavedKey(vec![self.save_inner(save)])
    }

    /// Set the simulation temperature.
    pub fn set_temp(&mut self, temp: Decimal) {
        self.temp = Some(temp);
    }

    /// Set the `save` option.
    pub fn save(&mut self, save: SaveOption) {
        self.save = Some(save);
    }

    /// Sets the flags used to invoke Spectre.
    ///
    /// Overrides the default set of flags.
    pub fn set_flags(&mut self, flags: impl Into<String>) {
        self.override_flags = Some(flags.into());
    }
}

impl SimOption<Spectre> for Temperature {
    fn set_option(
        self,
        opts: &mut <Spectre as Simulator>::Options,
        _ctx: &SimulationContext<Spectre>,
    ) {
        opts.set_temp(*self)
    }
}

#[impl_dispatch({&str; &String; ArcStr; String; SimSignal})]
impl<K> SimOption<Spectre> for InitialCondition<K, ic::Voltage> {
    fn set_option(
        self,
        opts: &mut <Spectre as Simulator>::Options,
        _ctx: &SimulationContext<Spectre>,
    ) {
        opts.set_ic_inner(self.path, *self.value);
    }
}

impl SimOption<Spectre> for InitialCondition<&SliceOnePath, ic::Voltage> {
    fn set_option(
        self,
        opts: &mut <Spectre as Simulator>::Options,
        _ctx: &SimulationContext<Spectre>,
    ) {
        opts.set_ic_inner(SimSignal::ScirVoltage(self.path.clone()), *self.value);
    }
}

impl SimOption<Spectre> for InitialCondition<&ConvertedNodePath, ic::Voltage> {
    fn set_option(
        self,
        opts: &mut <Spectre as Simulator>::Options,
        _ctx: &SimulationContext<Spectre>,
    ) {
        opts.set_ic_inner(
            SimSignal::ScirVoltage(match self.path {
                ConvertedNodePath::Cell(path) => path.clone(),
                ConvertedNodePath::Primitive {
                    instances, port, ..
                } => SliceOnePath::new(instances.clone(), NamedSliceOne::new(port.clone())),
            }),
            *self.value,
        );
    }
}

impl SimOption<Spectre> for InitialCondition<&NodePath, ic::Voltage> {
    fn set_option(
        self,
        opts: &mut <Spectre as Simulator>::Options,
        ctx: &SimulationContext<Spectre>,
    ) {
        InitialCondition {
            path: ctx.lib.convert_node_path(self.path).unwrap(),
            value: self.value,
        }
        .set_option(opts, ctx)
    }
}

#[impl_dispatch({SliceOnePath; ConvertedNodePath; NodePath})]
impl<T> SimOption<Spectre> for InitialCondition<T, ic::Voltage> {
    fn set_option(
        self,
        opts: &mut <Spectre as Simulator>::Options,
        ctx: &SimulationContext<Spectre>,
    ) {
        InitialCondition {
            path: &self.path,
            value: self.value,
        }
        .set_option(opts, ctx)
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, Hash, PartialEq, Eq)]
struct CachedSim {
    simulation_netlist: Vec<u8>,
}

struct CachedSimState {
    input: Vec<Input>,
    netlist: PathBuf,
    output_path: PathBuf,
    log: PathBuf,
    run_script: PathBuf,
    work_dir: PathBuf,
    executor: Arc<dyn Executor>,
    /// Override the default Spectre flags.
    override_flags: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
enum CachedData {
    Tran(HashMap<String, Vec<f64>>),
    Ac {
        freq: Vec<f64>,
        signals: HashMap<String, Vec<Complex64>>,
    },
    // The outer vec has length `numruns`.
    // The inner vec length equals the length of the inner analysis.
    MonteCarlo(Vec<Vec<CachedData>>),
}

impl CachedData {
    fn into_output(
        self,
        ctx: &SimulationContext<Spectre>,
        conv: &NetlistLibConversion,
        saves: &HashMap<SimSignal, u64>,
    ) -> Output {
        match self {
            CachedData::Tran(mut raw_values) => tran::Output {
                time: Arc::new(raw_values.remove("time").unwrap()),
                raw_values: raw_values
                    .into_iter()
                    .map(|(k, v)| (ArcStr::from(k), Arc::new(v)))
                    .collect(),
                saved_values: saves
                    .iter()
                    .map(|(k, v)| (*v, k.to_string(&ctx.lib.scir, conv)))
                    .collect(),
            }
            .into(),
            CachedData::Ac { freq, signals } => ac::Output {
                freq: Arc::new(freq),
                raw_values: signals
                    .into_iter()
                    .map(|(k, v)| (ArcStr::from(k), Arc::new(v)))
                    .collect(),
                saved_values: saves
                    .iter()
                    .map(|(k, v)| (*v, k.to_string(&ctx.lib.scir, conv)))
                    .collect(),
            }
            .into(),
            CachedData::MonteCarlo(data) => Output::MonteCarlo(montecarlo::Output(
                data.into_iter()
                    .map(|data| {
                        data.into_iter()
                            .map(|d| d.into_output(ctx, conv, saves))
                            .collect()
                    })
                    .collect(),
            )),
        }
    }
}

impl CacheableWithState<CachedSimState> for CachedSim {
    type Output = Vec<CachedData>;
    type Error = Arc<Error>;

    fn generate_with_state(
        &self,
        state: CachedSimState,
    ) -> std::result::Result<Self::Output, Self::Error> {
        let inner = || -> Result<Self::Output> {
            let CachedSimState {
                input,
                netlist,
                output_path,
                log,
                run_script,
                work_dir,
                executor,
                override_flags,
            } = state;
            write_run_script(
                RunScriptContext {
                    netlist: &netlist,
                    raw_output_path: &output_path,
                    log_path: &log,
                    bashrc: None,
                    format: "psfbin",
                    flags: override_flags.as_deref().unwrap_or("++aps +mt"),
                },
                &run_script,
            )?;

            let mut perms = std::fs::metadata(&run_script)?.permissions();
            #[cfg(any(unix, target_os = "redox"))]
            perms.set_mode(0o744);
            std::fs::set_permissions(&run_script, perms)?;

            let mut command = std::process::Command::new("/bin/bash");
            command.arg(&run_script).current_dir(&work_dir);
            executor
                .execute(command, Default::default())
                .map_err(|_| Error::SpectreError)?;

            let mut raw_outputs = Vec::with_capacity(input.len());

            for (i, input) in input.iter().enumerate() {
                raw_outputs.push(parse_analysis(
                    &output_path,
                    &subanalysis_name("analysis", i),
                    input,
                )?);
            }
            Ok(raw_outputs)
        };
        inner().map_err(Arc::new)
    }
}

impl ConvertibleNetlister<Spectre> for Spectre {
    type Error = std::io::Error;
    type Options<'a> = NetlistOptions<'a>;

    fn write_scir_netlist<W: Write>(
        &self,
        lib: &Library<Spectre>,
        out: &mut W,
        opts: Self::Options<'_>,
    ) -> std::result::Result<NetlistLibConversion, Self::Error> {
        NetlisterInstance::new(self, lib, out, opts).export()
    }
}

impl Spectre {
    fn simulate(
        &self,
        ctx: &SimulationContext<Self>,
        options: Options,
        input: Vec<Input>,
    ) -> Result<Vec<Output>> {
        std::fs::create_dir_all(&ctx.work_dir)?;
        let netlist = ctx.work_dir.join("netlist.scs");
        let mut f = std::fs::File::create(&netlist)?;
        let mut w = Vec::new();

        let mut includes = options.includes.into_iter().collect::<Vec<_>>();
        let mut saves = options.saves.keys().cloned().collect::<Vec<_>>();
        let mut ics = options
            .ics
            .iter()
            .map(|(k, v)| (k.clone(), *v))
            .collect::<Vec<_>>();
        // Sorting the include list makes repeated netlist invocations
        // produce the same output. If we were to iterate over the HashSet directly,
        // the order of includes may change even if the contents of the set did not change.
        includes.sort();
        saves.sort();
        ics.sort();

        let conv = self.write_scir_netlist(
            &ctx.lib.scir,
            &mut w,
            NetlistOptions::new(
                NetlistKind::Testbench(RenameGround::Yes("0".into())),
                &includes,
            ),
        )?;

        writeln!(w)?;
        if let Some(temp) = options.temp {
            writeln!(w, "settemp1 options temp={}", temp)?;
        }
        for save in saves {
            writeln!(w, "save {}", save.to_string(&ctx.lib.scir, &conv))?;
        }
        if let Some(save) = options.save {
            writeln!(w, "setsave1 options save={}", save)?;
        }
        for (k, v) in ics {
            writeln!(w, "ic {}={}", k.to_string(&ctx.lib.scir, &conv), v)?;
        }

        writeln!(w)?;
        for (i, an) in input.iter().enumerate() {
            an.netlist(&mut w, &subanalysis_name("analysis", i))?;
            writeln!(w)?;
        }
        f.write_all(&w)?;

        let output_path = ctx.work_dir.join("psf");
        let log = ctx.work_dir.join("spectre.log");
        let run_script = ctx.work_dir.join("simulate.sh");
        let work_dir = ctx.work_dir.clone();
        let executor = ctx.ctx.executor.clone();

        let raw_outputs = ctx
            .ctx
            .cache
            .get_with_state(
                "spectre.simulation.outputs",
                CachedSim {
                    simulation_netlist: w,
                },
                CachedSimState {
                    input,
                    netlist,
                    output_path,
                    log,
                    run_script,
                    work_dir,
                    executor,
                    override_flags: options.override_flags.clone(),
                },
            )
            .try_inner()
            .map_err(|e| match e {
                TryInnerError::CacheError(e) => Error::Caching(e),
                TryInnerError::GeneratorError(e) => Error::Generator(e.clone()),
            })?
            .clone();

        let conv = Arc::new(conv);
        let outputs = raw_outputs
            .into_iter()
            .map(|raw_values| raw_values.into_output(ctx, &conv, &options.saves))
            .collect();

        Ok(outputs)
    }

    /// Escapes the given identifier to be Spectre-compatible.
    pub fn escape_identifier(node_name: &str) -> String {
        // The name "0" is reserved, as it represents global ground.
        // To prevent nodes from being accidentally connected to global ground,
        // we rename 0 to x0, x0 to xx0, xx0 to xxx0, etc.
        lazy_static! {
            static ref RE: Regex = Regex::new("^(x*)0$").unwrap();
        }
        if let Some(caps) = RE.captures(node_name) {
            let xs = caps.get(1).unwrap();
            return format!("x{}0", xs.as_str());
        }

        let mut escaped_name = String::new();
        for c in node_name.chars() {
            if c.is_alphanumeric() || c == '_' {
                escaped_name.push(c);
            } else {
                escaped_name.push('\\');
                escaped_name.push(c);
            }
        }
        escaped_name
    }

    /// Converts a [`scir::InstancePath`] to a Spectre path string corresponding to
    /// the associated instance.
    pub fn instance_path(
        lib: &Library<Spectre>,
        conv: &NetlistLibConversion,
        path: &scir::InstancePath,
    ) -> String {
        lib.convert_instance_path_with_conv(conv, path.clone())
            .join(".")
    }

    /// Converts a [`SliceOnePath`] to a Spectre path string corresponding to the associated
    /// node voltage.
    pub fn node_voltage_path(
        lib: &Library<Spectre>,
        conv: &NetlistLibConversion,
        path: &SliceOnePath,
    ) -> String {
        lib.convert_slice_one_path_with_conv(conv, path.clone(), |name, index| {
            let name = Spectre::escape_identifier(name);
            if let Some(index) = index {
                arcstr::format!("{}\\[{}\\]", name, index)
            } else {
                name.into()
            }
        })
        .join(".")
    }

    /// Converts a [`SliceOnePath`] to a Spectre path string corresponding to the associated
    /// terminal current.
    pub fn node_current_path(
        lib: &Library<Spectre>,
        conv: &NetlistLibConversion,
        path: &SliceOnePath,
    ) -> String {
        let mut named_path =
            lib.convert_slice_one_path_with_conv(conv, path.clone(), |name, index| {
                let name = Spectre::escape_identifier(name);
                if let Some(index) = index {
                    arcstr::format!("{}\\[{}\\]", name, index)
                } else {
                    name.into()
                }
            });
        let signal = named_path.pop().unwrap();
        let mut str_path = named_path.join(".");
        str_path.push(':');
        str_path.push_str(&signal);
        str_path
    }
}

impl scir::schema::Schema for Spectre {
    type Primitive = Primitive;
}

impl FromSchema<NoSchema> for Spectre {
    type Error = NoSchemaError;

    fn convert_primitive(
        _primitive: <NoSchema as Schema>::Primitive,
    ) -> std::result::Result<<Self as Schema>::Primitive, Self::Error> {
        Err(NoSchemaError)
    }

    fn convert_instance(
        _instance: &mut scir::Instance,
        _primitive: &<NoSchema as Schema>::Primitive,
    ) -> std::result::Result<(), Self::Error> {
        Err(NoSchemaError)
    }
}

/// An error converting to/from the [`Spectre`] schema.
#[derive(Debug, Clone, Copy)]
pub enum SpectreConvError {
    /// A primitive that is not supported by the target schema was encountered.
    UnsupportedPrimitive,
    /// A primitive is missing a required parameter.
    MissingParameter,
    /// A primitive has an extra parameter.
    ExtraParameter,
    /// A primitive has an invalid value for a certain parameter.
    InvalidParameter,
    /// A primitive has an invalid port.
    InvalidPort,
}

impl FromSchema<Spice> for Spectre {
    type Error = SpectreConvError;

    fn convert_primitive(
        primitive: <Spice as Schema>::Primitive,
    ) -> std::result::Result<<Self as Schema>::Primitive, Self::Error> {
        Ok(Primitive::Spice(primitive))
    }

    fn convert_instance(
        _instance: &mut scir::Instance,
        _primitive: &<Spice as Schema>::Primitive,
    ) -> std::result::Result<(), Self::Error> {
        Ok(())
    }
}

impl Schematic<Spectre> for Resistor {
    fn schematic(
        &self,
        io: &<<Self as Block>::Io as HardwareType>::Bundle,
        cell: &mut CellBuilder<Spectre>,
    ) -> substrate::error::Result<Self::NestedData> {
        let mut prim = PrimitiveBinding::new(Primitive::RawInstance {
            cell: arcstr::literal!("resistor"),
            ports: vec![arcstr::literal!("1"), arcstr::literal!("2")],
            params: HashMap::from_iter([(
                arcstr::literal!("r"),
                ParamValue::Numeric(self.value()),
            )]),
        });
        prim.connect("1", io.p);
        prim.connect("2", io.n);
        cell.set_primitive(prim);
        Ok(())
    }
}

impl Schematic<Spectre> for Capacitor {
    fn schematic(
        &self,
        io: &<<Self as Block>::Io as HardwareType>::Bundle,
        cell: &mut CellBuilder<Spectre>,
    ) -> substrate::error::Result<Self::NestedData> {
        let mut prim = PrimitiveBinding::new(Primitive::RawInstance {
            cell: arcstr::literal!("capacitor"),
            ports: vec![arcstr::literal!("1"), arcstr::literal!("2")],
            params: HashMap::from_iter([(
                arcstr::literal!("c"),
                ParamValue::Numeric(self.value()),
            )]),
        });
        prim.connect("1", io.p);
        prim.connect("2", io.n);
        cell.set_primitive(prim);
        Ok(())
    }
}

impl Schematic<Spectre> for RawInstance {
    fn schematic(
        &self,
        io: &<<Self as Block>::Io as HardwareType>::Bundle,
        cell: &mut CellBuilder<Spectre>,
    ) -> substrate::error::Result<Self::NestedData> {
        let mut prim = PrimitiveBinding::new(Primitive::RawInstance {
            cell: self.cell.clone(),
            ports: self.ports.clone(),
            params: self.params.clone(),
        });
        for (i, port) in self.ports.iter().enumerate() {
            prim.connect(port, io[i]);
        }
        cell.set_primitive(prim);
        Ok(())
    }
}

impl Installation for Spectre {}

impl Simulator for Spectre {
    type Schema = Spectre;
    type Input = Input;
    type Options = Options;
    type Output = Output;
    type Error = Error;

    fn simulate_inputs(
        &self,
        config: &substrate::simulation::SimulationContext<Self>,
        options: Self::Options,
        input: Vec<Self::Input>,
    ) -> Result<Vec<Self::Output>> {
        self.simulate(config, options, input)
    }
}

/// Inputs directly supported by Spectre.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum Input {
    /// Transient simulation input.
    Tran(Tran),
    /// AC simulation input.
    Ac(Ac),
    /// A Monte Carlo input.
    MonteCarlo(MonteCarlo<Vec<Input>>),
}

impl From<Tran> for Input {
    fn from(value: Tran) -> Self {
        Self::Tran(value)
    }
}

impl From<Ac> for Input {
    fn from(value: Ac) -> Self {
        Self::Ac(value)
    }
}

impl<A: SupportedBy<Spectre>> From<MonteCarlo<A>> for Input {
    fn from(value: MonteCarlo<A>) -> Self {
        Self::MonteCarlo(value.into())
    }
}

/// Outputs directly produced by Spectre.
#[derive(Debug, Clone)]
pub enum Output {
    /// Transient simulation output.
    Tran(tran::Output),
    /// AC simulation output.
    Ac(ac::Output),
    /// Monte Carlo simulation output.
    MonteCarlo(montecarlo::Output<Vec<Output>>),
}

impl From<tran::Output> for Output {
    fn from(value: tran::Output) -> Self {
        Self::Tran(value)
    }
}

impl From<ac::Output> for Output {
    fn from(value: ac::Output) -> Self {
        Self::Ac(value)
    }
}

impl TryFrom<Output> for tran::Output {
    type Error = Error;
    fn try_from(value: Output) -> Result<Self> {
        match value {
            Output::Tran(t) => Ok(t),
            _ => Err(Error::SpectreError),
        }
    }
}

impl TryFrom<Output> for ac::Output {
    type Error = Error;
    fn try_from(value: Output) -> Result<Self> {
        match value {
            Output::Ac(ac) => Ok(ac),
            _ => Err(Error::SpectreError),
        }
    }
}

impl From<montecarlo::Output<Vec<Output>>> for Output {
    fn from(value: montecarlo::Output<Vec<Output>>) -> Self {
        Self::MonteCarlo(value)
    }
}

impl TryFrom<Output> for montecarlo::Output<Vec<Output>> {
    type Error = Error;
    fn try_from(value: Output) -> Result<Self> {
        match value {
            Output::MonteCarlo(mc) => Ok(mc),
            _ => Err(Error::SpectreError),
        }
    }
}

impl Input {
    fn netlist<W: Write>(&self, out: &mut W, name: &str) -> Result<()> {
        write!(out, "{name} ")?;
        match self {
            Self::Tran(t) => t.netlist(out),
            Input::Ac(ac) => ac.netlist(out),
            Self::MonteCarlo(mc) => mc.netlist(out, name),
        }
    }
}

impl Tran {
    fn netlist<W: Write>(&self, out: &mut W) -> Result<()> {
        write!(out, "tran stop={}", self.stop)?;
        if let Some(ref start) = self.start {
            write!(out, " start={start}")?;
        }
        if let Some(errpreset) = self.errpreset {
            write!(out, " errpreset={errpreset}")?;
        }
        if let Some(noisefmax) = self.noise_fmax {
            write!(out, " noisefmax={noisefmax}")?;
        }
        if let Some(noisefmin) = self.noise_fmin {
            write!(out, " noisefmin={noisefmin}")?;
        }
        Ok(())
    }
}

impl Ac {
    fn netlist<W: Write>(&self, out: &mut W) -> Result<()> {
        write!(out, "ac start={} stop={}", self.start, self.stop)?;
        match self.sweep {
            Sweep::Linear(pts) => write!(out, " lin={pts}")?,
            Sweep::Logarithmic(pts) => write!(out, " log={pts}")?,
            Sweep::Decade(pts) => write!(out, " dec={pts}")?,
        };
        if let Some(errpreset) = self.errpreset {
            write!(out, " errpreset={errpreset}")?;
        }
        Ok(())
    }
}

fn subanalysis_name(prefix: &str, idx: usize) -> String {
    format!("{prefix}_{idx}")
}

fn parse_analysis(output_dir: &Path, name: &str, analysis: &Input) -> Result<CachedData> {
    Ok(if let Input::MonteCarlo(analysis) = analysis {
        let mut data = Vec::new();
        for iter in 1..analysis.numruns + 1 {
            let mut mc_data = Vec::new();
            for i in 0..analysis.analysis.len() {
                // FIXME: loops should be swapped
                let new_name = subanalysis_name(&format!("{}-{:0>3}_{}", name, iter, name), i);
                mc_data.push(parse_analysis(
                    output_dir,
                    &new_name,
                    &analysis.analysis[i],
                )?)
            }
            data.push(mc_data);
        }
        CachedData::MonteCarlo(data)
    } else {
        let file_name = match analysis {
            Input::Tran(_) => {
                format!("{name}.tran.tran")
            }
            Input::Ac(_) => format!("{name}.ac"),
            Input::MonteCarlo(_) => unreachable!(),
        };
        let psf_path = output_dir.join(file_name);
        let psf = std::fs::read(psf_path)?;
        let ast = psfparser::binary::parse(&psf).map_err(|_| Error::Parse)?;

        match analysis {
            Input::Tran(_) => {
                let values = TransientData::from_binary(ast).signals;
                CachedData::Tran(values)
            }
            Input::Ac(_) => {
                let values = AcData::from_binary(ast);
                CachedData::Ac {
                    freq: values.freq,
                    signals: values.signals,
                }
            }
            Input::MonteCarlo(_) => {
                unreachable!()
            }
        }
    })
}

impl MonteCarlo<Vec<Input>> {
    fn netlist<W: Write>(&self, out: &mut W, name: &str) -> Result<()> {
        write!(
            out,
            "montecarlo variations={} numruns={} savefamilyplots=yes",
            self.variations, self.numruns
        )?;
        if let Some(seed) = self.seed {
            write!(out, " seed={seed}")?;
        }
        if let Some(firstrun) = self.firstrun {
            write!(out, " firstrun={firstrun}")?;
        }
        write!(out, " {{")?;

        for (i, an) in self.analysis.iter().enumerate() {
            let name = subanalysis_name(name, i);
            write!(out, "\n\t")?;
            an.netlist(out, &name)?;
        }
        write!(out, "\n}}")?;

        Ok(())
    }
}

impl HasSpiceLikeNetlist for Spectre {
    fn write_prelude<W: Write>(&self, out: &mut W, lib: &Library<Spectre>) -> std::io::Result<()> {
        writeln!(out, "// Substrate Spectre library\n")?;
        writeln!(out, "simulator lang=spectre\n")?;
        writeln!(out, "// This is a generated file.")?;
        writeln!(
            out,
            "// Be careful when editing manually: this file may be overwritten.\n"
        )?;
        writeln!(out, "global 0\n")?;

        // find all unique spf netlists and include them
        let spfs = lib
            .primitives()
            .filter_map(|p| {
                if let Primitive::SpfInstance { netlist, .. } = p.1 {
                    Some(netlist.clone())
                } else {
                    None
                }
            })
            .collect::<HashSet<_>>();
        // sort paths before including them to ensure stable output
        for spf_path in spfs.iter().sorted() {
            writeln!(out, "dspf_include {:?}", spf_path)?;
        }

        Ok(())
    }

    fn write_include<W: Write>(&self, out: &mut W, include: &Include) -> std::io::Result<()> {
        if let Some(section) = &include.section {
            write!(out, "include {:?} section={}", include.path, section)?;
        } else {
            write!(out, "include {:?}", include.path)?;
        }
        Ok(())
    }

    fn write_start_subckt<W: Write>(
        &self,
        out: &mut W,
        name: &ArcStr,
        ports: &[&SignalInfo],
    ) -> std::io::Result<()> {
        write!(out, "subckt {} (", name)?;
        for sig in ports {
            if let Some(width) = sig.width {
                for i in 0..width {
                    write!(out, " {}\\[{}\\]", Spectre::escape_identifier(&sig.name), i)?;
                }
            } else {
                write!(out, " {}", Spectre::escape_identifier(&sig.name))?;
            }
        }
        write!(out, " )")?;
        Ok(())
    }

    fn write_end_subckt<W: Write>(&self, out: &mut W, name: &ArcStr) -> std::io::Result<()> {
        write!(out, "ends {}", name)
    }

    fn write_instance<W: Write>(
        &self,
        out: &mut W,
        name: &ArcStr,
        connections: Vec<ArcStr>,
        child: &ArcStr,
    ) -> std::io::Result<ArcStr> {
        let name = ArcStr::from(Spectre::escape_identifier(&format!("x{}", name)));
        write!(out, "{} (", name)?;

        for connection in connections {
            write!(out, " {}", connection)?;
        }

        write!(out, " ) {}", child)?;

        Ok(name)
    }

    fn write_primitive_inst<W: Write>(
        &self,
        out: &mut W,
        name: &ArcStr,
        mut connections: HashMap<ArcStr, Vec<ArcStr>>,
        primitive: &<Self as Schema>::Primitive,
    ) -> std::io::Result<ArcStr> {
        Ok(match primitive {
            Primitive::RawInstance {
                cell,
                ports,
                params,
            } => {
                let connections = ports
                    .iter()
                    .flat_map(|port| connections.remove(port).unwrap_or_else(|| panic!("raw instance `{name}` must connect to all ports; missing connection to port `{port}`")))
                    .collect();
                let name = self.write_instance(out, name, connections, cell)?;
                for (key, value) in params.iter().sorted_by_key(|(key, _)| *key) {
                    write!(out, " {key}={value}")?;
                }
                name
            }
            Primitive::BlackboxInstance { contents } => {
                // TODO: See if there is a way to translate the name based on the
                // contents, or make documentation explaining that blackbox instances
                // cannot be addressed by path.
                for elem in &contents.elems {
                    match elem {
                        BlackboxElement::InstanceName => write!(out, "{}", name)?,
                        BlackboxElement::RawString(s) => write!(out, "{}", s)?,
                        BlackboxElement::Port(p) => {
                            for part in connections.get(p).unwrap() {
                                write!(out, "{}", part)?
                            }
                        }
                    }
                }
                name.clone()
            }
            Primitive::Spice(p) => {
                writeln!(out, "simulator lang=spice")?;
                let name = Spice.write_primitive_inst(out, name, connections, p)?;
                writeln!(out, "simulator lang=spectre")?;
                name
            }
            Primitive::SpfInstance { cell, ports, .. } => {
                let connections = ports
                    .iter()
                    .flat_map(|port| connections.remove(port).unwrap())
                    .collect();
                self.write_instance(out, name, connections, cell)?
            }
        })
    }

    fn write_slice<W: Write>(
        &self,
        out: &mut W,
        slice: Slice,
        info: &SignalInfo,
    ) -> std::io::Result<()> {
        let name = Spectre::escape_identifier(&info.name);
        if let Some(range) = slice.range() {
            for i in range.indices() {
                write!(out, "{}\\[{}\\]", &name, i)?;
            }
        } else {
            write!(out, "{}", &name)?;
        }
        Ok(())
    }
}