Notes and internals

Optional numeric output adapter

tclsimrawreaderRbc.c contains the conditional RBC headers, stub initialization, literal names with a collision-free encoding fallback, collision checks and publication. RawOutputOptions records handle defaults; read commands copy it before parsing overrides. RawNumericColumn buffers hold decoded doubles, interleaved for complex samples.

The list readers retain their result representation. The vector reader reuses binary layout metadata and ASCII token decoding, but writes numeric buffers instead of per-sample Tcl objects. Real buffers transfer to RBC with TCL_DYNAMIC; complex buffers are packed into the public Rbc_Complex representation. Creation uses RBC’s Tcl command with -literal true -variable {} so names such as v(1) cannot be parsed as size specifications and ordinary real names cannot create mapped arrays. No Tcl script is assembled from raw names; creation uses Tcl_EvalObjv. Safe literal names retain their spelling; unsupported names, namespace separators, and the reserved _raw_ prefix are encoded as _raw_ plus hexadecimal UTF-8 bytes. This keeps literal and encoded names disjoint and confines creation to the per-call namespace when supplied, then the handle namespace, or the read caller’s namespace otherwise. The explicit namespace is created and captured at open time; the handle retains its name, not ownership of the namespace.

All selected data is decoded before publication. Known collisions and type mismatches are preflighted. Newly created commands are removed if publication fails; existing vectors are never deleted. Client notifications can execute reentrant application code, so callback-induced failures are not fully atomic. Active raw handles are preserved during calls and freed through Tcl_EventuallyFree to tolerate callbacks that close the handle. Per-interpreter package initialization always precedes the data read.

Raw file format support

This reader supports two raw-file dialects:

::tclsimrawreader::openraw file.raw
::tclsimrawreader::openraw -dialect generic file.raw
::tclsimrawreader::openraw -dialect ltspice file.raw

The generic dialect is used for SPICE3-style raw files, including ngspice and Xyce. The ltspice dialect enables LTspice-specific binary layout detection and stepped-plot splitting.

Supported raw-file structure

A raw file is treated as a sequence of one or more plots. Each plot has a text header, a variable table, and a data block.

Title: ...
Date: ...
Plotname: ...
Flags: real|complex [double] [stepped] ...
No. Variables: N
No. Points: M
Variables:
        0       <name0>     <type0>
        1       <name1>     <type1>
        ...
Binary:
<binary data>

or:

Title: ...
Date: ...
Plotname: ...
Flags: real|complex [stepped] ...
No. Variables: N
No. Points: M
Variables:
        0       <name0>     <type0>
        1       <name1>     <type1>
        ...
Values:
        0       <value0>
                <value1>
                ...
        1       <value0>
                <value1>
                ...

The reader supports both Binary: and ASCII Values: blocks. Xyce documents its raw-file format as closely following SPICE3 conventions, with Title, Date, Plotname, Flags, No. Variables, No. Points, Variables, and either Values or Binary sections.

Generic SPICE3-style dialect

The generic dialect is intended for ngspice, Xyce and SPICE-OPUS raw files.

ASCII Values: data

ASCII raw files store one point as an integer point index followed by the variable values for that point. Complex values are represented as real and imaginary components. Xyce documents this as an integer index preceding each set of point values, with complex values written as <real component>, <imaginary component>.

The reader scans ASCII data once at open time to build pointOffsets. Vector values are still read lazily later by seeking to the requested point offset.

Binary data

For generic binary raw files, the layout is point-major:

point 0: var0 var1 var2 ... varN
point 1: var0 var1 var2 ... varN
point 2: var0 var1 var2 ... varN
...

For real data, every variable is read as a 64-bit double. For complex data, every variable is read as two 64-bit doubles: real part followed by imaginary part. Xyce documents binary real values as sizeof(double) blocks and complex values as real and imaginary components of size 2*sizeof(double).

ngspice supports both ASCII and binary raw output through its filetype setting; the documented values are ascii and binary, with binary being the default.

Multiple plots

Generic multi-plot files are represented as concatenated complete plots:

<header for plot 0>
<data for plot 0>
<header for plot 1>
<data for plot 1>
<header for plot 2>
<data for plot 2>

Xyce documents raw output from -r as a concatenation of plots, and -a with -r as producing an ASCII raw file.

The reader exposes each complete plot as a separate indexed plot:

$handle plots
$handle names -plot 0
$handle names -plot 1
$handle vector -plot 0 time

LTspice dialect

LTspice raw files use a similar header and data-section structure, but binary real-data storage is different from the generic SPICE3-style layout. LTspice’s raw format is not officially specified; an Analog Devices forum answer notes that the format is not officially disclosed, although it has been practically stable for many years.

Use:

set r [::tclsimrawreader::openraw -dialect ltspice file.raw]

LTspice text/header encoding

The reader supports UTF-8/ASCII-style text headers and UTF-16LE headers. LTspice raw headers may be UTF-16LE; the LTspice forum answer explicitly notes that the raw-file header is in 16-bit Unicode.

LTspice ASCII Values: data

For LTspice ASCII raw files, values are parsed as text. The LTspice mixed float/double binary layout does not apply to ASCII files.

The reader supports:

  • LTspice ASCII single plot

  • LTspice ASCII stepped (multi-plot) file

For stepped ASCII files, the reader scans the whole physical Values: block, records point offsets and axis values, then exposes each detected step as a separate pseudo-plot.

LTspice binary data

LTspice binary data is also point-major in normal non-FastAccess files:

point 0: axis0 trace1 trace2 ... traceN
point 1: axis1 trace1 trace2 ... traceN
...

For transient analysis, LTspice stores the time variable as a 64-bit double and the dependent traces as 32-bit floats by default. If double precision is forced with .options numdgt > 6, the dependent traces are stored as doubles as well.

The reader detects LTspice real-data storage from the physical data-block size:

mixed layout:
    variable 0: double
    variables 1..N: float

all-double layout:
    variables 0..N: double

For AC analysis, LTspice binary data is treated as complex data, with each value stored as a pair of doubles: real part and imaginary part. Public LTspice raw-format notes describe AC binary data as complex values made from two 8-byte components.

FastAccess

LTspice FastAccess changes the storage order from point-major to variable-major:

normal:
    point0 var0 var1 var2 ...
    point1 var0 var1 var2 ...

FastAccess:
    var0 point0 point1 point2 ...
    var1 point0 point1 point2 ...

FastAccess is marked in the Flags: line. The current implementation rejects LTspice FastAccess files instead of silently reading them incorrectly. Public documentation describes FastAccess as storing each variable contiguously rather than storing complete points contiguously.

LTspice stepped plot separation

LTspice stepped raw files are normalized into indexed plots by this reader. The .log file is not read. Step parameter names and values are not reconstructed. The goal is only to expose each step as a normal plot so the existing API stays consistent.

After opening a stepped LTspice file:

set r [::tclsimrawreader::openraw -dialect ltspice stepped.raw]

$r plots
$r vector -plot 0 time
$r vector -plot 1 time
$r vectors -plot 2 -all

each step is available as a separate plot index.

Transient stepped data

For transient data, LTspice steps are detected from the axis variable, normally time.

A new plot is started when the axis stops increasing:

if current_time <= previous_time:
    start new step

This works because each transient step starts its own time sequence again.

Example:

physical LTspice data block:

step 0:
    time = 0
    time = 1e-6
    time = 2e-6

step 1:
    time = 0        <-- reset detected here
    time = 1e-6
    time = 2e-6

step 2:
    time = 0        <-- reset detected here
    time = 1e-6
    time = 2e-6

The reader exposes this as:

plot 0: step 0 points
plot 1: step 1 points
plot 2: step 2 points

The same rule is used for binary and ASCII LTspice transient files.

Non-transient stepped data

For non-transient stepped data, such as DC sweeps, AC sweeps, or parameter sweeps, the preferred split method is fixed-size segmentation using the declared No. Points value when it cleanly divides the physical data block.

if total_physical_points % declared_points == 0:
    points_per_step = declared_points
    number_of_steps = total_physical_points / declared_points

Example:

No. Points: 101
physical points: 303

plot 0: points   0..100
plot 1: points 101..201
plot 2: points 202..302

If fixed-size splitting is not applicable, the reader may fall back to axis-reset detection. In this case, the axis direction must be detected first.

For an increasing sweep, a new step starts when the axis value stops increasing:

if current_axis <= previous_axis:
    start new step

For a decreasing sweep, a new step starts when the axis value stops decreasing:

if current_axis >= previous_axis:
    start new step

For AC data, the real component of the first variable is used as the scalar axis value.

The fixed-size split is preferred for non-transient LTspice stepped data because it does not depend on sweep direction or axis monotonicity assumptions.

Exposed API behavior

The public API does not expose whether a plot came from a physical plot header or from an LTspice stepped pseudo-plot.

Limitations

The current implementation does not read LTspice .log files. Therefore, LTspice step parameter names and values are not available.

LTspice FastAccess files are not supported.

The LTspice dialect is based on observed and publicly described LTspice raw-file behavior rather than an official file-format specification.

tclsimrawreader implementation overview

Core data model

The reader normalizes all supported raw files into an array of RawPlot objects owned by one RawFile.

RawFile
    chan
    dialect
    encKind
    enc
    plots[0]
    plots[1]
    ...

Each RawPlot contains:

RawPlot
    header          parsed RawHeader
    dataKind        DATA_BINARY or DATA_VALUES
    dataOffset      offset of the first data byte / first Values point
    nextOffset      offset immediately after this plot's data block
    dataBytes       size of this plot's data block
    pointOffsets    ASCII only: offset of each point

For binary plots, random access is computed from:

pointOffset = plot->dataOffset + pointIndex * plot->header.pointStrideBytes

For ASCII plots, random access uses:

pointOffset = plot->pointOffsets[pointIndex]

This means binary plots need only dataOffset, numPoints, and pointStrideBytes, while ASCII plots need a point-offset index built at open time.

Open path

The top-level command is:

::tclsimrawreader::openraw ?-dialect generic|ltspice? fileName

The main open path is:

RawOpenCmd
    RawReadOptions
    Tcl_FSOpenFileChannel
    Tcl_SetChannelOption -translation binary
    DetectEncoding

    loop:
        ReadHeader
        Tcl_Tell -> dataOffset

        if DATA_BINARY:
            binary open path

        if DATA_VALUES:
            ASCII open path

    Tcl_CreateObjCommand2 -> HandleCmd -> Tcl Dispatch -> NativeCall -> RawFileObjCmd

ReadHeader() parses only the text header and stops after consuming either the Binary: or Values: marker. It leaves the channel positioned at the beginning of the data block.

Layout resolution is done after ReadHeader() because LTspice binary layout may require knowing the physical data-block size.

Header parsing path

Header parsing is shared by all dialects and data kinds.

ReadHeader
    ReadDecodedHeaderLine
        ReadRawHeaderLine
        DecodeHeaderLine
        StripTrailingCR

    ParseFlags
        AppendFlag

    ParseSizeField

    ReadVariablesSection
        ParseVariableLine
            RawIsVariableTypeToken

The header parser fills:

title
date
plotname
flags / flagsMask
numVariables
numPoints
variables[]

It does not read vector values.

Generic binary open path

The generic dialect is used for SPICE3-style raw files, including ngspice and Xyce-style files.

The generic binary open path is:

RawOpenCmd
    ReadHeader
    dataOffset = Tcl_Tell

    RawHeaderResolveVariableLayout(..., RAW_DIALECT_GENERIC, 0)
        ResolveDefaultStorage
        RawSetVariableLayout for each variable

    ComputeBinaryByteCount
        dataBytes = numPoints * pointStrideBytes

    nextOffset = dataOffset + dataBytes
    Tcl_Seek(chan, nextOffset, SEEK_SET)

    RawFileAppendPlotMove

For generic binary files, the data block border is calculated entirely from the header:

dataOffset  = offset immediately after Binary:
dataBytes   = No. Points * pointStrideBytes
nextOffset  = dataOffset + dataBytes

The generic binary layout is point-major:

point 0: var0 var1 var2 ...
point 1: var0 var1 var2 ...
point 2: var0 var1 var2 ...

For real data, all variables use the same resolved real storage. For complex data, each variable stores a real and imaginary component.

Generic ASCII open path

The generic ASCII open path is:

RawOpenCmd
    ReadHeader
    dataOffset = Tcl_Tell

    RawHeaderResolveVariableLayout(..., RAW_DIALECT_GENERIC, 0)

    RawPlotScanAsciiValues
        scan declared No. Points
        record pointOffsets[]

    RawFileAppendPlotMove

For generic ASCII files, the block border is found by scanning the declared number of points from the Values: block.

dataOffset      = offset after Values:
pointOffsets[i] = offset of point i
nextOffset      = channel position after the last scanned point
dataBytes       = nextOffset - dataOffset

The ASCII scan does not fully decode all vectors. It only records point offsets. Actual vector values are decoded lazily later.

This keeps open-time work small while allowing random access by point range.

LTspice binary open path

The LTspice dialect is selected with:

::tclsimrawreader::openraw -dialect ltspice file.raw

The LTspice binary path is:

RawOpenCmd
    ReadHeader
    dataOffset = Tcl_Tell

    RawLtspicePrepareBinaryPlot
        RawGetChannelSize
        physicalDataBytes = fileSize - dataOffset
        RawLtspiceDetectAllDouble
        RawHeaderResolveVariableLayout(..., RAW_DIALECT_LTSPICE, allDouble)
        physicalPoints = physicalDataBytes / pointStrideBytes
        update header.numPoints to physicalPoints
        update dataBytes and nextOffset

    RawLtspiceAppendSplitBinaryPlots
        if not stepped:
            RawFileAppendPlotMove

        if stepped:
            split into pseudo-plots

LTspice binary block borders are calculated from the physical file size:

dataOffset          = offset immediately after Binary:
physicalDataBytes   = fileSize - dataOffset
nextOffset          = fileSize

This is needed because LTspice stepped data is stored as one physical data block, not as multiple complete raw-file plots.

LTspice binary storage detection

LTspice real binary data may use two layouts.

Normal mixed layout:

variable 0: double
variable 1: float
variable 2: float
...

All-double layout:

variable 0: double
variable 1: double
variable 2: double
...

The storage mode is inferred by RawLtspiceDetectAllDouble().

RawLtspiceDetectAllDouble
    RawLtspiceCandidateStrides

    mixedStride  = 8 + (numVariables - 1) * 4
    doubleStride = numVariables * 8

    compare physicalDataBytes with:
        numPoints * mixedStride
        numPoints * doubleStride

    for stepped files:
        also allow physicalDataBytes to be an integer multiple
        of the declared per-step byte count

Complex LTspice binary data is treated as double-based complex storage:

real component: double
imag component: double

LTspice FastAccess files are rejected because their storage order is variable-major instead of point-major.

LTspice ASCII open path

LTspice ASCII files use text values, so the LTspice binary mixed float/double layout is irrelevant.

For non-stepped LTspice ASCII files, the path is the same as generic ASCII:

RawOpenCmd
    ReadHeader
    RawHeaderResolveVariableLayout(..., RAW_DIALECT_GENERIC, 0)
    RawPlotScanAsciiValues
    RawFileAppendPlotMove

For stepped LTspice ASCII files, the path is:

RawOpenCmd
    ReadHeader
    RawHeaderResolveVariableLayout(..., RAW_DIALECT_GENERIC, 0)

    RawLtspiceAppendSplitAsciiPlots
        RawLtspiceScanAllAsciiValues
            RawAsciiFindNextContentLine
            RawAsciiReadAxisAtCurrentPoint
            RawAppendAsciiScannedPoint

        split into pseudo-plots

RawLtspiceScanAllAsciiValues() scans the whole physical Values: block until EOF or the beginning of the next raw header.

The ASCII block border is determined as:

dataOffset = offset after Values:
nextOffset = EOF or offset of next "Title:" header
dataBytes  = nextOffset - dataOffset

During this scan, the reader records:

pointOffsets[i] = file offset of point i
axisValues[i]   = decoded scalar value of variable 0 at point i

The full vector data is still not stored. Only offsets and axis values are collected.

LTspice stepped plot splitting

LTspice stepped data is normalized into several indexed RawPlot objects.

The .log file is not read. Step parameter names and values are not reconstructed. The reader only separates the physical raw data into step-sized plots.

After splitting:

physical LTspice data block
    step 0 data
    step 1 data
    step 2 data

becomes:

RawFile
    plots[0] -> step 0
    plots[1] -> step 1
    plots[2] -> step 2

The public API sees these as ordinary plots:

$handle vector -plot 0 time
$handle vector -plot 1 time
$handle vectors -plot 2 -all

LTspice transient step splitting

Transient data is detected by RawLtspiceIsTransientPlot().

A plot is treated as transient if either:

plotname contains "Transient"

or:

first variable name is "time"

Transient steps are detected by axis reset.

For binary data:

RawLtspiceFindAxisResetSteps(..., transientMode = 1)
    read binary points in chunks
    RawDecodeBinaryAxisValue
    if currentAxis <= previousAxis:
        start new step

For ASCII data:

RawLtspiceBuildAxisResetStepsFromValues(..., transientMode = 1)
    if axisValues[i] <= axisValues[i - 1]:
        start new step

The rule is intentionally simple for transient data because time should increase within one transient run and reset at the beginning of the next step.

LTspice non-transient step splitting

For non-transient stepped data, fixed-size splitting is preferred.

RawLtspiceAppendSplitBinaryPlots
RawLtspiceAppendSplitAsciiPlots

    if not transient
       and declaredPoints > 0
       and totalPhysicalPoints > declaredPoints
       and totalPhysicalPoints % declaredPoints == 0:

        RawLtspiceBuildFixedSteps

This uses the original No. Points header value as the per-step point count.

Example:

declared No. Points: 101
physical points:    303

step 0: points   0..100
step 1: points 101..201
step 2: points 202..302

If fixed-size splitting is not possible, the reader falls back to direction-aware axis reset detection.

RawAxisStartsNewStep

For increasing sweeps:

current <= previous  -> new step

For decreasing sweeps:

current >= previous  -> new step

The direction is detected from the first unequal pair of axis values in the current step.

This avoids incorrectly handling sweeps such as:

step 0:  10,  5,  0, -5, -10
step 1:  10,  5,  0, -5, -10

where the axis reset is an increase, not a decrease.

Binary pseudo-plot construction

Binary LTspice step plots are created by RawLtspiceAppendSegmentPlots().

For each detected step:

stepPlot.header      = clone of base header
stepPlot.numPoints   = step point count
stepPlot.dataKind    = DATA_BINARY
stepPlot.dataOffset  = baseDataOffset + startPoint * pointStrideBytes
stepPlot.dataBytes   = pointCount * pointStrideBytes
stepPlot.nextOffset  = dataOffset + dataBytes

No binary data is copied. Each pseudo-plot references a byte range inside the original physical data block.

ASCII pseudo-plot construction

ASCII LTspice step plots are created by RawLtspiceAppendAsciiSegmentPlots().

For each detected step:

stepPlot.header            = clone of base header
stepPlot.numPoints         = step point count
stepPlot.dataKind          = DATA_VALUES
stepPlot.pointOffsets[]    = copied subset of base pointOffsets[]
stepPlot.dataOffset        = first point offset in this step
stepPlot.nextOffset        = next step's first point offset, or basePlot->nextOffset
stepPlot.dataBytes         = nextOffset - dataOffset

Only the point-offset array is copied. Textual value data remains in the original file.

Vector extraction path

Vector extraction is lazy. Opening the file builds plot metadata and point indexes, but does not decode every vector.

Single vector

RawFileObjCmd
    vector subcommand
        RawSelectPlotFromArgs
        RawPlotFindVariable
        Range bounds checks in RawFileObjCmdImpl
        RawPlotVectorToObj
            RawPlotReadVectorsToObj

Multiple vectors

RawFileObjCmd
    vectors subcommand
        RawSelectPlotFromArgs
        RawPlotResolveVariableList
            or RawPlotResolveAllVariables
        Range bounds checks in RawFileObjCmdImpl
        RawPlotReadVectorsToObj

Backend dispatch

RawPlotReadVectorsToObj
    if DATA_BINARY:
        RawPlotBinaryReadVectorsToObj

    if DATA_VALUES:
        RawPlotAsciiReadVectorsToObj

Binary vector reading

Binary vector reading uses point-major offsets.

RawPlotBinaryReadVectorsToObj
    validate range and selected variables
    allocate one Tcl list per selected variable
    seek to first requested point
    read chunks of complete points

    for each point:
        for each selected variable:
            pointer = point + variable.offsetBytes
            RawAppendBinaryValue

    RawBuildVectorResult

The binary reader reads complete point records even when only a few variables are requested, because the file is stored point-major.

ASCII vector reading

ASCII vector reading uses pointOffsets.

RawPlotAsciiReadVectorsToObj
    validate range and selected variables
    allocate one Tcl list per selected variable
    build sparse all-variable output array

    seek to plot->pointOffsets[firstPoint]

    for each requested point:
        RawAsciiReadOnePoint

    RawBuildVectorResult

RawAsciiReadOnePoint() consumes the whole ASCII point, but appends only selected variables.

For selected-vector reading, unselected entries in the sparse output array are NULL.

allVecObjs[varIndex] == NULL
    -> value is parsed/skipped but not appended

allVecObjs[varIndex] != NULL
    -> value is appended to that variable's list

This keeps ASCII parsing correct for multi-line points and complex values while avoiding unnecessary output objects.

Result construction

All vector backends produce one list object per selected variable.

RawBuildVectorResult() converts those internal lists to the requested result shape.

Single-vector result:

RAW_VECTOR_RESULT_LIST
    -> return vecObjs[0]

Dictionary result:

RAW_VECTOR_RESULT_DICT
    -> return dict:
           variableName -> valueList

The public commands use this as follows:

vector
    RAW_VECTOR_RESULT_LIST

vectors
vectors -all
allvectors
    RAW_VECTOR_RESULT_DICT

Ownership summary

RawFile owns:

channel
encoding handle
plot array
all plot headers
all ASCII point-offset arrays

Each RawPlot owns:

RawHeader
pointOffsets, for ASCII plots

Pseudo-plots own their cloned headers and, for ASCII pseudo-plots, their own point-offset arrays.

Pseudo-plots do not copy raw value data. They reference the same open channel using different offsets and point ranges.

Summary

The implementation follows this principle:

Open time:
    parse headers
    resolve layout
    find data-block borders
    build plot list
    build ASCII point indexes
    split LTspice stepped data into pseudo-plots

Read time:
    seek to requested points
    decode only requested vectors
    build Tcl list or dictionary result

Generic SPICE3-style files use explicit headers and declared point counts to find plot borders.

LTspice binary files use physical data size to infer storage layout and point count.

LTspice stepped files are normalized into ordinary indexed plots, so the rest of the reader can use the same vector-reading path for all formats.

Tcl and C interface boundary

Public argument parsing, interactive help and command documentation live in the package’s Tcl source. Wrappers pass normalized dictionaries to private native commands. The native engine keeps semantic checks, data buffers, event handling and RBC publication; numeric samples are not copied through Tcl merely to parse options.

Each returned handle remains a native command and owns its original deletion callback. It dispatches to the real RAWFILE Tcl procedures, which call the native engine in the original caller’s frame. Renaming or deleting the handle therefore retains the existing ownership rules, and relative namespaces still resolve against the caller. No second TclOO object or hidden lifetime-owning handle is introduced.

Wrappers call the fixed native argparse directly with -helplevel 1. Help prints and returns from the current wrapper without running its native operation. The argparse help-return fix is required; no local compatibility helper is used.


Copyright (c) George Yashin