Skip to content

IO API

Unified I/O layer: parsing waveform outputs into xarray.Dataset objects.

Low-level Parsers

Trace dataclass

Um traço: nome, unidade (quando existir) e vetor de valores (np.ndarray).

Source code in spicelab/io/raw_reader.py
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
@dataclass(frozen=True)
class Trace:
    """Um traço: nome, unidade (quando existir) e vetor de valores (np.ndarray)."""

    name: str
    unit: str | None
    values: NDArray[Any]
    _complex: NDArray[Any] | None = None  # apenas AC: vetor complex

    def magnitude(self) -> NDArray[Any]:
        if self._complex is not None:
            return cast(NDArray[Any], np.abs(self._complex))
        return cast(NDArray[Any], np.abs(self.values))

    def real(self) -> NDArray[Any]:
        if self._complex is not None:
            return self._complex.real
        return self.values

    def imag(self) -> NDArray[Any]:
        if self._complex is not None:
            return self._complex.imag
        return np.zeros_like(self.values, dtype=float)

    def phase_deg(self) -> NDArray[Any]:
        if self._complex is not None:
            return np.angle(self._complex, deg=True)
        return np.zeros_like(self.values, dtype=float)

TraceSet

Conjunto de traços indexado por nome. O primeiro traço é o eixo X (time/freq).

Acesso

ts["V(out)"] -> Trace ts.x -> Trace (primeira coluna) ts.names -> lista de nomes ts.to_dataframe() -> pandas.DataFrame (se pandas instalado)

Source code in spicelab/io/raw_reader.py
 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
class TraceSet:
    """
    Conjunto de traços indexado por nome. O primeiro traço é o eixo X (time/freq).

    Acesso:
        ts["V(out)"] -> Trace
        ts.x -> Trace (primeira coluna)
        ts.names -> lista de nomes
        ts.to_dataframe() -> pandas.DataFrame (se pandas instalado)
    """

    def __init__(
        self,
        traces: list[Trace],
        *,
        meta: dict[str, Any] | None = None,
    ) -> None:
        if not traces:
            raise ValueError("TraceSet requires at least one trace")
        self._traces = traces
        self._by_name: dict[str, Trace] = {t.name: t for t in traces}
        self.meta: dict[str, Any] = meta or {}

        # valida tamanhos
        n = len(self._traces[0].values)
        for t in self._traces[1:]:
            if len(t.values) != n:
                raise ValueError("All traces must have same length")

    @property
    def x(self) -> Trace:
        return self._traces[0]

    @property
    def names(self) -> list[str]:
        return [t.name for t in self._traces]

    def __getitem__(self, key: str) -> Trace:
        try:
            return self._by_name[key]
        except KeyError as e:
            raise KeyError(f"Trace '{key}' not found. Available: {self.names}") from e

    def to_dataframe(self) -> Any:
        # Evita depender de stubs do pandas: import dinâmico via importlib, tipado como Any
        try:
            pd: Any = importlib.import_module("pandas")
        except Exception as exc:  # pragma: no cover
            raise RuntimeError("pandas is required for to_dataframe()") from exc
        data = {t.name: t.values for t in self._traces}
        return pd.DataFrame(data)

    @classmethod
    def from_dataset(cls, dataset: Any) -> TraceSet:
        """Build a TraceSet from an xarray.Dataset-like object."""

        try:
            import numpy as _np
        except Exception as exc:  # pragma: no cover - numpy optional
            raise RuntimeError("numpy is required to convert dataset into TraceSet") from exc

        if not hasattr(dataset, "data_vars"):
            raise TypeError("Expected an xarray.Dataset-like object with 'data_vars'")

        coords = getattr(dataset, "coords", {})
        coord_names = ("time", "freq", "frequency", "index")
        coord_obj = None
        coord_key = None
        for name in coord_names:
            if name in coords:
                coord_obj = coords[name]
                coord_key = name
                break
        if coord_obj is not None:
            x_values = _np.asarray(getattr(coord_obj, "values", coord_obj), dtype=float)
            x_name = str(getattr(coord_obj, "name", None) or coord_key or "index")
        else:
            data_vars = list(getattr(dataset, "data_vars", {}))
            if not data_vars:
                raise ValueError("Dataset has no data variables to build TraceSet")
            first = _np.asarray(dataset[data_vars[0]].values)
            length = first.shape[0] if first.ndim > 0 else 1
            x_values = _np.arange(length, dtype=float)
            x_name = "index"

        x_values = _np.asarray(x_values, dtype=float).reshape(-1)
        axis_len = x_values.shape[0]
        traces: list[Trace] = [Trace(x_name, None, x_values)]

        for name, data in getattr(dataset, "data_vars", {}).items():
            arr = _np.asarray(data.values)
            if arr.ndim == 0:
                arr = _np.full((axis_len,), float(arr))
            elif arr.shape[0] != axis_len:
                try:
                    arr = arr.reshape(axis_len, -1)
                    arr = arr[:, 0]
                except Exception as exc:  # pragma: no cover - defensive reshape
                    raise ValueError(
                        f"Unable to align data variable '{name}' with independent axis"
                    ) from exc
            else:
                arr = arr.reshape(axis_len)
            arr = _np.real_if_close(arr)
            traces.append(Trace(str(name), None, _np.asarray(arr)))

        meta = dict(getattr(dataset, "attrs", {}))
        return cls(traces, meta=meta)

from_dataset(dataset) classmethod

Build a TraceSet from an xarray.Dataset-like object.

Source code in spicelab/io/raw_reader.py
 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
@classmethod
def from_dataset(cls, dataset: Any) -> TraceSet:
    """Build a TraceSet from an xarray.Dataset-like object."""

    try:
        import numpy as _np
    except Exception as exc:  # pragma: no cover - numpy optional
        raise RuntimeError("numpy is required to convert dataset into TraceSet") from exc

    if not hasattr(dataset, "data_vars"):
        raise TypeError("Expected an xarray.Dataset-like object with 'data_vars'")

    coords = getattr(dataset, "coords", {})
    coord_names = ("time", "freq", "frequency", "index")
    coord_obj = None
    coord_key = None
    for name in coord_names:
        if name in coords:
            coord_obj = coords[name]
            coord_key = name
            break
    if coord_obj is not None:
        x_values = _np.asarray(getattr(coord_obj, "values", coord_obj), dtype=float)
        x_name = str(getattr(coord_obj, "name", None) or coord_key or "index")
    else:
        data_vars = list(getattr(dataset, "data_vars", {}))
        if not data_vars:
            raise ValueError("Dataset has no data variables to build TraceSet")
        first = _np.asarray(dataset[data_vars[0]].values)
        length = first.shape[0] if first.ndim > 0 else 1
        x_values = _np.arange(length, dtype=float)
        x_name = "index"

    x_values = _np.asarray(x_values, dtype=float).reshape(-1)
    axis_len = x_values.shape[0]
    traces: list[Trace] = [Trace(x_name, None, x_values)]

    for name, data in getattr(dataset, "data_vars", {}).items():
        arr = _np.asarray(data.values)
        if arr.ndim == 0:
            arr = _np.full((axis_len,), float(arr))
        elif arr.shape[0] != axis_len:
            try:
                arr = arr.reshape(axis_len, -1)
                arr = arr[:, 0]
            except Exception as exc:  # pragma: no cover - defensive reshape
                raise ValueError(
                    f"Unable to align data variable '{name}' with independent axis"
                ) from exc
        else:
            arr = arr.reshape(axis_len)
        arr = _np.real_if_close(arr)
        traces.append(Trace(str(name), None, _np.asarray(arr)))

    meta = dict(getattr(dataset, "attrs", {}))
    return cls(traces, meta=meta)

parse_ngspice_ascii_raw(path)

Parser robusto para NGSpice ASCII RAW.

Retorna TraceSet onde a primeira coluna é o eixo X (tipicamente 'time' ou 'frequency').

Source code in spicelab/io/raw_reader.py
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
def parse_ngspice_ascii_raw(path: str) -> TraceSet:
    """
    Parser robusto para NGSpice ASCII RAW.

    Retorna TraceSet onde a primeira coluna é o eixo X (tipicamente 'time' ou 'frequency').
    """
    with open(path, encoding="utf-8", errors="ignore") as f:
        lines = f.read().splitlines()

    meta, i0 = _parse_header(lines)
    nvars = int(meta["nvars"])
    npoints = int(meta["npoints"])
    vars_meta, i1 = _parse_variables(lines, i0, nvars)
    data, complex_cols = _parse_values(lines, i1, nvars, npoints)

    traces: list[Trace] = []
    for j, (name, unit) in enumerate(vars_meta):
        traces.append(
            Trace(
                name=name,
                unit=unit,
                values=data[:, j].copy(),
                _complex=complex_cols[j],
            )
        )
    return TraceSet(traces, meta=meta)

parse_ngspice_ascii_raw_multi(path)

Lê um arquivo ASCII com múltiplos plots (p.ex. .step nativo) e retorna uma lista de TraceSet (um por bloco).

Source code in spicelab/io/raw_reader.py
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
def parse_ngspice_ascii_raw_multi(path: str) -> list[TraceSet]:
    """
    Lê um arquivo ASCII com múltiplos plots (p.ex. .step nativo) e retorna
    uma lista de TraceSet (um por bloco).
    """
    with open(path, encoding="utf-8", errors="ignore") as f:
        lines = f.read().splitlines()

    i = 0
    out: list[TraceSet] = []
    while i < len(lines):
        # procurar início de um bloco (Title:/Plotname:/Variables:)
        # Reutiliza as funções privadas para cada bloco
        # pular linhas vazias
        while i < len(lines) and not lines[i].strip():
            i += 1
        if i >= len(lines):
            break
        # precisa ver se há um cabeçalho válido
        try:
            meta, i0 = _parse_header(lines[i:])
            nvars = int(meta["nvars"])
            npoints = int(meta["npoints"])
            vars_meta, i1 = _parse_variables(lines[i:], i0, nvars)
            data, complex_cols = _parse_values(lines[i:], i1, nvars, npoints)
        except Exception:
            # se não conseguiu, avança uma linha e tenta de novo
            i += 1
            continue

        traces: list[Trace] = []
        for j, (name, unit) in enumerate(vars_meta):
            traces.append(
                Trace(name=name, unit=unit, values=data[:, j].copy(), _complex=complex_cols[j])
            )
        out.append(TraceSet(traces, meta=meta))
        # avançar: i += i1 + npoints ... mas já usamos slices; então mova i para frente
        # tenta achar próximo 'Title:' após o bloco atual
        # heurística simples: move i até encontrar próxima 'Title:' ou EOF
        k = i + i1 + npoints + 4  # + margem
        i = max(i + 1, k)
    return out

parse_ngspice_raw(path)

Dispatcher para RAW ASCII ou binário.

Suporta formato binário de linha simples (LTspice/NGSpice) para casos reais e complexos.

Source code in spicelab/io/raw_reader.py
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
def parse_ngspice_raw(path: str) -> TraceSet:
    """Dispatcher para RAW ASCII ou binário.

    Suporta formato binário de linha simples (LTspice/NGSpice) para casos reais e complexos.
    """
    with open(path, "rb") as f:
        blob = f.read()
    # Heurísticas:
    # 1. ASCII header: contém 'Binary:' sem null interleaving.
    # 2. UTF-16 (wide) header: contém padrão intercalado
    #    B\x00i\x00n\x00a... ou grande densidade de nulls.
    head_scan = blob[:8192]
    wide_pattern = b"B\x00i\x00n\x00a\x00r\x00y\x00:\x00"
    is_ascii_binary = b"Binary:" in head_scan or b"binary" in head_scan.lower()
    is_wide_binary = wide_pattern in head_scan

    if is_ascii_binary:
        meta, data_bytes = _parse_binary_header_and_data(blob)
        return _parse_binary_payload(meta, data_bytes)
    if is_wide_binary:
        # Localizar fim da linha 'Binary:' (padrão newline UTF-16 '\n\x00')
        marker_pos = head_scan.find(wide_pattern)
        newline_pat = b"\n\x00"
        nl_pos = head_scan.find(newline_pat, marker_pos)
        if nl_pos == -1:
            raise ValueError("UTF-16 binary RAW: newline after Binary: not found")
        header_bytes = blob[: nl_pos + 2]
        # Remover nulls para obter texto ascii simplificado
        ascii_header = header_bytes[::2].decode("utf-8", errors="ignore")
        # Reaproveitar parser ascii-binary: reconstruir bytes artificiais com ascii header e newline
        rebuilt = ascii_header.encode("utf-8") + blob[nl_pos + 2 :]
        meta, data_bytes = _parse_binary_header_and_data(rebuilt)
        return _parse_binary_payload(meta, data_bytes)
    # caso contrário tratar como ASCII
    return parse_ngspice_ascii_raw(path)

Unified Readers Facade

High-level façade returning an xarray.Dataset enriched with metadata.

Parameters:

Name Type Description Default
path str | Path

waveform file (.raw/.prn/.csv)

required
engine str | None

optional explicit engine name (ngspice|ltspice|xyce)

None
log str | Path | None

optional ngspice log path to extract version/warnings/errors

None
netlist_hash str | None

deterministic hash of circuit/netlist (for provenance)

None
analysis_args dict[str, object] | None

dict of analysis parameters used in run

None
allow_binary bool

if False and RAW detected as binary, raise with guidance

False
complex_components bool | tuple[str, ...] | list[str] | None

True or iterable specifying which complex parts to expand (e.g. True → ("real","imag"), or ("real","imag","phase"))

None
Source code in spicelab/io/readers.py
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
def load_dataset(
    path: str | Path,
    *,
    engine: str | None = None,
    log: str | Path | None = None,
    netlist_hash: str | None = None,
    analysis_args: dict[str, object] | None = None,
    allow_binary: bool = False,
    complex_components: bool | tuple[str, ...] | list[str] | None = None,
) -> Any:
    """High-level façade returning an xarray.Dataset enriched with metadata.

    Parameters:
        path: waveform file (.raw/.prn/.csv)
        engine: optional explicit engine name (ngspice|ltspice|xyce)
        log: optional ngspice log path to extract version/warnings/errors
        netlist_hash: deterministic hash of circuit/netlist (for provenance)
        analysis_args: dict of analysis parameters used in run
        allow_binary: if False and RAW detected as binary, raise with guidance
        complex_components: True or iterable specifying which complex parts to expand
            (e.g. True → ("real","imag"), or ("real","imag","phase"))
    """

    p = Path(path)
    include_complex: tuple[str, ...] | None = None
    if complex_components:
        if complex_components is True:
            include_complex = ("real", "imag")
        elif isinstance(complex_components, list | tuple):
            include_complex = tuple(str(c).lower() for c in complex_components)
        else:  # unexpected truthy
            include_complex = ("real", "imag")

    ds = read_waveform(
        p,
        engine_hint=engine,
        allow_binary=allow_binary,
        include_complex=include_complex,
    )
    if engine:
        ds.attrs["engine"] = engine
    # Enrich with log summary if ngspice
    if log is not None and (
        engine == "ngspice" or (engine is None and ds.attrs.get("engine") == "ngspice")
    ):
        summary = read_ngspice_log(log)
        if summary.version:
            ds.attrs.setdefault("engine_version", summary.version)
        if summary.warnings:
            ds.attrs.setdefault("log_warnings", summary.warnings)
        if summary.errors:
            ds.attrs.setdefault("log_errors", summary.errors)
    if netlist_hash:
        ds.attrs.setdefault("netlist_hash", netlist_hash)
    if analysis_args:
        ds.attrs.setdefault("analysis_args", analysis_args)
    # Infer version for other engines if not set
    eng = ds.attrs.get("engine")
    if eng and "engine_version" not in ds.attrs:
        ver = _infer_engine_version(eng, p)
        if ver:
            ds.attrs["engine_version"] = ver
    # Additional derived metadata
    if "engine" in ds.attrs and "analysis" in ds.attrs:
        ds.attrs.setdefault("provenance", json.dumps({"loaded_at": datetime.utcnow().isoformat()}))
    # Count points
    try:
        ds.attrs.setdefault("n_points", int(ds.dims.get("index", 0)))
    except Exception:
        pass
    ds = normalize_dataset(ds)
    return ds
Source code in spicelab/io/readers.py
445
446
447
448
449
450
451
452
453
def read_waveform(
    path: str | Path,
    engine_hint: str | None = None,
    allow_binary: bool = True,
    include_complex: tuple[str, ...] | None = None,
) -> Any:  # alias
    return read(
        path, engine_hint=engine_hint, allow_binary=allow_binary, include_complex=include_complex
    )
Source code in spicelab/io/readers.py
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
def read_ngspice_raw(path: str | Path, *, include_complex: tuple[str, ...] | None = None) -> Any:
    ts = parse_ngspice_raw(str(path))
    # parse single plot only; multi handled by read_ngspice_raw_multi
    # meta inference only available on ascii for now
    analysis = None
    try:
        # parse header manually for plotname
        with open(path, encoding="utf-8", errors="ignore") as f:
            for ln in f:
                if ln.lower().startswith("plotname:"):
                    analysis = _infer_analysis_from_plot(ln.split(":", 1)[1].strip())
                    break
    except Exception:
        pass
    # Fallback: if still unknown, attempt to use TraceSet meta (works for binary path)
    if analysis is None:
        meta = getattr(ts, "meta", None)
        if isinstance(meta, dict):  # defensive
            analysis = _infer_analysis_from_plot(meta.get("plotname"))
    return _to_xarray_from_traceset(
        ts,
        engine="ngspice",
        analysis=analysis,
        raw_path=str(path),
        meta=getattr(ts, "meta", None),
        include_complex=include_complex,
    )
Source code in spicelab/io/readers.py
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
def read_ngspice_raw_multi(
    path: str | Path, *, include_complex: tuple[str, ...] | None = None
) -> Any:
    tsets = parse_ngspice_ascii_raw_multi(str(path))
    if not tsets:
        raise ValueError("No plots found in RAW file")
    datasets: list[Any] = []
    for idx, ts in enumerate(tsets):
        ds = _to_xarray_from_traceset(
            ts,
            engine="ngspice",
            analysis=None,
            raw_path=str(path),
            stepped=True,
            step_index=idx,
            total_steps=len(tsets),
            meta=getattr(ts, "meta", None),
            include_complex=include_complex,
        )
        datasets.append(ds)
    if len(datasets) == 1:
        return datasets[0]
    merged = _merge_steps(datasets, coord_name="step")
    merged.attrs.update(datasets[0].attrs)
    return merged
Source code in spicelab/io/readers.py
388
389
def read_xyce_prn(path: str | Path) -> Any:
    return read_xyce_table(path)
Source code in spicelab/io/readers.py
251
252
253
254
255
256
257
258
259
260
261
262
263
264
def read_ltspice_raw(path: str | Path, *, include_complex: tuple[str, ...] | None = None) -> Any:
    # Reuse ngspice RAW parser (ASCII ou binário compatível simples)
    ds = read_ngspice_raw(path, include_complex=include_complex)
    # Adjust engine attr if heuristic suggests LTspice (presence of 'ltspice' in meta title)
    try:
        title = ds.attrs.get("title") or ds.attrs.get("plot_title")
        command = ds.attrs.get("command")
        if (title and "ltspice" in str(title).lower()) or (
            command and "ltspice" in str(command).lower()
        ):
            ds.attrs["engine"] = "ltspice"
    except Exception:  # pragma: no cover
        pass
    return ds

Normalization & Helpers

Apply post-load normalization (idempotent).

  • Ensures signal names are canonical V(...)/I(...)
  • Re-derives time/freq coordinate if missing and an alias column exists
Source code in spicelab/io/readers.py
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
def normalize_dataset(ds: Any) -> Any:
    """Apply post-load normalization (idempotent).

    - Ensures signal names are canonical V(...)/I(...)
    - Re-derives time/freq coordinate if missing and an alias column exists
    """
    # If time coord absent, search for possible alias in data_vars
    if "time" not in ds.coords:
        for alias in _TIME_ALIASES:
            if alias in ds.data_vars:
                ds = ds.assign_coords({"time": ("index", ds[alias].values)})
                break
    if "freq" not in ds.coords:
        for alias in _FREQ_ALIASES:
            if alias in ds.data_vars:
                ds = ds.assign_coords({"freq": ("index", ds[alias].values)})
                break
    return ds

Return a pandas.DataFrame with coords as columns (time/freq/step first).

Source code in spicelab/io/readers.py
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
def to_pandas(ds: Any) -> Any:
    """Return a `pandas.DataFrame` with coords as columns (time/freq/step first)."""
    try:
        pd = importlib.import_module("pandas")
    except Exception as exc:  # pragma: no cover
        raise RuntimeError("pandas is required for to_pandas(); pip install pandas") from exc
    data: dict[str, Any] = {}
    order: list[str] = []
    for special in ("time", "freq", "step"):
        if special in ds.coords:
            order.append(special)
    for c in ds.coords:
        if c not in order and c != "index":
            order.append(c)
    for c in order:
        data[c] = ds[c].values
    for name in sorted(ds.data_vars):
        data[name] = ds[name].values
    return pd.DataFrame(data)

Return a polars.DataFrame with coordinates lifted to columns.

Columns order heuristic
  1. time or freq if present
  2. step (if present)
  3. remaining coords
  4. data variables (sorted)
Source code in spicelab/io/readers.py
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
def to_polars(ds: Any) -> Any:
    """Return a `polars.DataFrame` with coordinates lifted to columns.

    Columns order heuristic:
      1. time or freq if present
      2. step (if present)
      3. remaining coords
      4. data variables (sorted)
    """
    try:
        pl = importlib.import_module("polars")
    except Exception as exc:  # pragma: no cover
        raise RuntimeError("polars is required for to_polars(); pip install polars") from exc
    cols: dict[str, Iterable[Any]] = {}
    # Collect coordinate-like columns
    coord_order: list[str] = []
    for special in ("time", "freq", "step"):
        if special in ds.coords:
            coord_order.append(special)
    # Include other 1D coords (excluding index)
    for c in ds.coords:
        if c not in coord_order and c != "index":
            coord_order.append(c)
    # Add coordinate values
    for c in coord_order:
        cols[c] = ds[c].values.tolist()
    # Data variables
    for name in sorted(ds.data_vars):
        cols[name] = ds[name].values.tolist()
    return pl.DataFrame(cols)

Return a melted (long form) polars DataFrame: coord columns + name/value.

Source code in spicelab/io/readers.py
592
593
594
595
596
597
598
599
def dataset_to_long_polars(ds: Any) -> Any:
    """Return a melted (long form) polars DataFrame: coord columns + name/value."""
    wide = to_polars(ds)
    coord_cols = [c for c in ("time", "freq", "step") if c in wide.columns]
    id_vars = coord_cols
    value_vars = [c for c in wide.columns if c not in id_vars]
    long = wide.unpivot(on=value_vars, index=id_vars, variable_name="signal", value_name="value")
    return long

Persist dataset to disk in selected format (netcdf|zarr|parquet).

Source code in spicelab/io/readers.py
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
def save_dataset(ds: Any, path: str | Path, *, format: str = "netcdf") -> Path:
    """Persist dataset to disk in selected format (netcdf|zarr|parquet)."""
    xr = _require_xarray()
    p = Path(path)
    fmt = format.lower()
    if fmt == "netcdf":
        xr.decode_cf(ds).to_netcdf(p)
    elif fmt == "zarr":  # pragma: no cover - optional
        ds.to_zarr(p, mode="w")
    elif fmt == "parquet":
        # Use long-form for parquet friendliness
        long_df = dataset_to_long_polars(ds)
        long_df.write_parquet(p)
    else:  # pragma: no cover
        raise ValueError("Unsupported format; choose netcdf|zarr|parquet")
    return p
Source code in spicelab/io/readers.py
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
def load_saved_dataset(path: str | Path) -> Any:
    p = Path(path)
    xr = _require_xarray()
    ext = p.suffix.lower()
    if ext in {".nc", ".netcdf"}:
        return xr.load_dataset(p)
    if ext == ".zarr":  # pragma: no cover
        return xr.open_zarr(p)
    if ext == ".parquet":
        pl = importlib.import_module("polars")
        df = pl.read_parquet(p)
        # reconstruct minimal dataset (wide pivot)
        if {"signal", "value"}.issubset(set(df.columns)):
            # pivot back
            coord_cols = [c for c in ("time", "freq", "step") if c in df.columns]
            wide = df.pivot(values="value", columns="signal", index=coord_cols)
            ds = _require_xarray().Dataset.from_dataframe(wide.to_pandas())
            return ds
        raise ValueError("Parquet file missing required columns 'signal' and 'value'")
    raise ValueError("Unsupported file extension for load_saved_dataset")

Return a classification of signals in an xarray Dataset.

Categories
  • voltage: names starting with 'V('
  • current: names starting with 'I(' (including device/subckt currents)
  • other: remaining data variables

The returned dict maps category -> sorted list of variable names.

Example

from spicelab.io import load_dataset, list_signals # doctest: +SKIP ds = load_dataset("example.raw", allow_binary=True) # doctest: +SKIP list_signals(ds) # doctest: +SKIP {'voltage': ['V(out)'], 'current': ['I(R1)'], 'other': []}

Source code in spicelab/io/readers.py
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
def list_signals(ds: Any) -> dict[str, list[str]]:
    """Return a classification of signals in an xarray Dataset.

    Categories:
      - voltage: names starting with 'V('
      - current: names starting with 'I(' (including device/subckt currents)
      - other: remaining data variables

    The returned dict maps category -> sorted list of variable names.

    Example
    -------
    >>> from spicelab.io import load_dataset, list_signals  # doctest: +SKIP
    >>> ds = load_dataset("example.raw", allow_binary=True)  # doctest: +SKIP
    >>> list_signals(ds)  # doctest: +SKIP
    {'voltage': ['V(out)'], 'current': ['I(R1)'], 'other': []}
    """
    volt: list[str] = []
    curr: list[str] = []
    other: list[str] = []
    for name in ds.data_vars:
        if name.startswith("V("):
            volt.append(name)
        elif name.startswith("I("):
            curr.append(name)
        else:
            other.append(name)
    return {
        "voltage": sorted(volt),
        "current": sorted(curr),
        "other": sorted(other),
    }

Binary RAW parsing, UTF‑16 header detection, complex AC component expansion (complex_components), device current normalization extensions (@R1[i] -> I(R1), @M1[id] -> Id(M1)), classification helpers & persistence utilities are integrated; upcoming work will focus on refined engine version heuristics, noise/distortion ingestion, and coordinate indexing improvements.