Analog circuit modeling
Run an analog circuit from its netlist, sample by sample: resistors, pots, capacitors, diodes, transistors, JFETs, OTAs and op-amps solved together.
The circuit solver runs an analog circuit sample by sample. You describe the circuit as a netlist, one part per line as on a schematic, and the solver computes every node voltage at once, so the parts affect each other as they do in hardware. A module can model a drum voice, a filter or a pedal from its schematic, part by part, instead of approximating it with hand-written DSP.
It supports resistors, capacitors, inductors, pots, variable resistors, switches, diodes, bipolar transistors, JFETs, op-amps (ideal, or a model with gain-bandwidth, slew rate and supply rails), operational transconductance amplifiers (OTAs), voltage and current sources, audio inputs and output probes. The Learn guide to circuit modeling explains the idea for musicians, and the circuit modeling overview introduces it.
When to use the circuit solver
Use the solver when the behaviour you want comes from parts interacting: a drive control that changes the tone as well as the gain, clipping that depends on how hard you play, a transistor stage that sits at its bias point, or a filter whose response depends on several pots at once. Those behaviours follow from solving the parts together. You don't add them separately.
Use the other toolkit leaves when a known curve or a standard filter already gives you the sound:
| You want | Use |
|---|---|
| A waveshaping curve, voiced overdrive or an oversampled waveshaper | Modulation and distortion |
| A tone filter, EQ or resonant filter from coefficients | Filters and EQ |
| The sound of a pedal or amp learned from recordings, without a schematic | Room acoustics and neural models |
| The behaviour of a specific circuit, from its schematic | The circuit solver |
A circuit model does more work per sample than a single curve or filter: each sample is a few small matrix-vector products and, when the circuit has diodes or transistors, a short iterative solve. Moving a pot rebuilds the model, which costs far more than a sample. The solver needs the schematic and part values; it can't learn a box you can only listen to.
Quick start
This netlist is a diode clipper with a drive pot: the input feeds a 100 kΩ log pot, a 2.2 kΩ resistor and a 10 nF capacitor, and two antiparallel silicon diodes clip the voltage across the capacitor.
* Diode clipper with a drive pot Vin in 0 INPUT=in ; audio input, volts P1 0 x in 100k NAME=drive VALUE=0.5 TAPER=log R1 x mid 2.2k C1 mid 0 10n D1 mid 0 IS=2.52n N=1.752 D2 0 mid IS=2.52n N=1.752 .output out mid 0
Parse it once, allocate the solver for it, prepare it at the host rate, then call it once per sample:
import { circuitParameterIndex, parseCircuitNetlist } from "maruaudio/dsp/circuit/netlist"
import {
circuitTick,
initCircuit,
prepareCircuit,
setCircuitParameter,
updateCircuit,
} from "maruaudio/dsp/circuit/dk-solver"
const netlist = parseCircuitNetlist(`
Vin in 0 INPUT=in
P1 0 x in 100k NAME=drive VALUE=0.5 TAPER=log
R1 x mid 2.2k
C1 mid 0 10n
D1 mid 0 IS=2.52n N=1.752
D2 0 mid IS=2.52n N=1.752
.output out mid
`)
const DRIVE = circuitParameterIndex(netlist, "drive")
// createState: allocate once for this topology
const circuit = initCircuit(netlist)
// prepare: build the model at the host rate and settle at DC
prepareCircuit(circuit, 48000)
// control path: move the pot, rebuild once
setCircuitParameter(circuit, DRIVE, 0.8)
updateCircuit(circuit)
// process: one call per sample, volts in, volts out
for (let frame = 0; frame < frameCount; frame++) {
output[frame] = circuitTick(circuit, 0.5 * input[frame])
}
Inputs and outputs are in volts, so the scale between full-scale audio and
circuit volts sets how hard the circuit is driven. With the drive at 0.8, this
clipper is clean at a few hundred millivolts and clips at a volt or two; at
0.5 it stays clean even at 2 V. The 0.5 * input above sends a full-scale
signal in at 0.5 V, so raise that scale to drive it harder. Choose the input
scale for the circuit's real signal level, and trim the output back to your
module's level.
In a Processor module, the calls map onto the lifecycle like this:
| Processor stage | Circuit call |
|---|---|
createState() | parseCircuitNetlist and initCircuit: everything that allocates |
prepare(state, spec) | prepareCircuit(circuit, sampleRate); return false when it returns false |
setParameter(state, path, value) | setCircuitParameter(circuit, index, position) with a 0 to 1 position |
process(state, block) | updateCircuit once, then circuitTick (or circuitStep) per frame |
reset(state) | resetCircuit(circuit) |
Parsing uses strings, regular expressions, arrays and exceptions, which belong
outside the realtime path. The solver itself never reads names: it reads the
numeric tables of a CircuitTopology, which a CircuitNetlist extends. A
compiled Processor that must not carry the parser can author those tables as
literals; Go to Definition on CircuitTopology shows their layout.
Netlist reference
The netlist is SPICE-like: one element or directive per line.
- Names and keywords are case-insensitive.
- A node, input or parameter name is any run of letters, digits,
_,.,+or-.0andgndare ground. - A line starting with
*is a comment, and;starts a comment anywhere on a line. .endis optional; nothing after it is read.- There is no title line, and there are no subcircuits,
.modelcards,.paramexpressions or continuation lines.
Values
A value is a number with an optional SPICE scale suffix:
| Suffix | Scale | Suffix | Scale |
|---|---|---|---|
f | 1e-15 | m | 1e-3 (milli) |
p | 1e-12 | k | 1e3 |
n | 1e-9 | meg | 1e6 |
u, µ or μ | 1e-6 | g | 1e9 |
t | 1e12 |
As in SPICE, m is milli: write 1meg for a megohm. A bare upper-case
M, or the Greek capital Μ, is refused as ambiguous, and so is trailing
unit text: 10nF, 4k7 and
1kOhm are errors, so write 10n and 4.7k. Exponents such as 2.52e-9
are accepted.
Elements
The first letter of an element's name selects its type: R1, Rload and
Rc are all resistors. Element names must be unique.
| Line | Element | Parameters (defaults) |
|---|---|---|
R<name> a b <ohms> | Resistor | |
R<name> a b <ohms> NAME=<param> [VALUE=0.5] [MIN=0] [TAPER=lin] | Variable resistor: MIN + taper(p)·ohms | Parameter p from 0 to 1; VALUE is its default |
P<name> a w b <ohms> NAME=<param> [VALUE=0.5] [TAPER=lin] | Potentiometer: a to w is taper(p)·ohms, w to b the rest | w is the wiper; a is the end the wiper leaves as p rises |
S<name> a b NAME=<param> [VALUE=0] [RON=1m] [ROFF=1g] | Switch, closed when the parameter is 0.5 or more | RON and ROFF in ohms |
C<name> a b <farads> | Capacitor | |
L<name> a b <henries> | Inductor | |
V<name> a b [DC] <volts> | DC voltage source, v(a) − v(b) | SPICE's DC keyword is optional |
V<name> a b INPUT=<input> [DC=0] | Input voltage source: the input's sample value plus DC | |
I<name> a b [DC] <amps> | DC current source, flowing from a through the source to b | |
I<name> a b INPUT=<input> [DC=0] | Input current source | |
D<name> anode cathode [IS=1e-14] [N=1] [CJ=0] [RS=0] | Shockley diode, i = IS·(exp(v/(N·VT)) − 1) + GMIN·v | IS saturation current in amps, N emission coefficient, CJ constant junction capacitance in farads, RS series resistance in ohms |
Q<name> c b e NPN|PNP [IS=1e-14] [BF=100] [BR=1] [CJE=0] [CJC=0] [RB=0] [RE=0] [RC=0] | Bipolar transistor, Ebers-Moll transport model, GMIN across each junction | BF and BR forward and reverse current gain, CJE and CJC constant base-emitter and base-collector capacitances, RB, RE and RC series resistances |
J<name> d g s NJF|PJF [VTO=-2] [BETA=1e-4] [LAMBDA=0] [IS=1e-14] [CGS=0] [CGD=0] [RD=0] [RS=0] | JFET, N- or P-channel: the Shichman-Hodges square law, gate junctions as diodes | VTO pinch-off voltage (negative for either polarity), BETA in A/V², LAMBDA channel-length modulation per volt, CGS and CGD constant gate capacitances, RD and RS series resistances |
U<name> plus minus out OPAMP [GAIN=inf] | Op-amp, output referenced to ground | inf is an ideal op-amp; a number is the open-loop gain |
U<name> plus minus out OPAMP GBW=<hertz> [GAIN=100k] [SR=<V/s>] [VPOS=<volts> VNEG=<volts> [KNEE=0.1]] | Op-amp model with a gain-bandwidth, optional slew rate and supply rails (see Op-amp model) | GBW in hertz; GAIN the finite open-loop DC gain; SR in volts per second (13 V/µs is 13meg); rails VNEG … VPOS with a soft KNEE in volts |
U<name> plus minus out OTA IABC=<amps> [N=1] | OTA with a fixed bias current: IABC·tanh((v+ − v−)/(2·N·VT)) into out | N widens the linear range |
U<name> plus minus out abc OTA [IS=1e-14] [N=1] | OTA biased through its pin abc, a junction to ground: drive it through a resistor from a control voltage | IS of the bias pin's junction |
VT is the thermal voltage at 300 K, 25.852 mV. GMIN is a 1e-12 S
leakage across every junction, as in SPICE: it keeps a point reached only
through diodes or transistors, such as the middle of a diode string,
determined while they are all off.
For a volume or drive control, wire a to ground and b to the signal:
P1 0 w in 100k NAME=level puts taper(p) of the input on the wiper.
TAPER=lin is linear. TAPER=log is an audio taper, (81^p − 1)/80, which
puts 10 % of the resistance at mid travel. Every resistance a parameter sets
is floored at 1 mΩ, so a pot at its end stop still solves.
Directives, inputs and parameters
| Line | Does |
|---|---|
.output <name> a [b] | Declares output probe <name> = v(a) − v(b); b defaults to ground |
.end | Ends the netlist |
Inputs are declared by INPUT= on a source and parameters by NAME= on a
pot, variable resistor or switch. Input, output and parameter indices follow
their first appearance in the netlist, counting from 0. Several elements may
share one parameter name, as the two halves of a dual-gang pot do, and they
then move together. Elements that share a name must declare the same default.
Errors
parseCircuitNetlist throws an Error whose message names the line and the
problem: an unknown element letter or keyword, a missing node, a bad value, a
duplicate element name, a parameter declared with two different defaults, or a
circuit beyond the size limits. For example, R1 a b 4k7 fails with a message that
starts circuit netlist line 1: invalid value "4k7" for a resistance.
A circuit can parse and still be impossible to solve, such as a node that no
element connects to ground or a loop of voltage sources.
prepareCircuit reports that by returning false. It also returns false
for hand-written numeric tables that break the size limits or point at a
node, input or parameter that does not exist.
API reference
import {
circuitInputIndex,
circuitNodeIndex,
circuitOutputIndex,
circuitParameterIndex,
parseCircuitNetlist,
parseCircuitValue,
type CircuitNetlist,
} from "maruaudio/dsp/circuit/netlist"
import {
circuitOutput,
circuitStep,
circuitTick,
initCircuit,
prepareCircuit,
resetCircuit,
setCircuitInput,
setCircuitParameter,
updateCircuit,
type CircuitOptions,
type CircuitState,
type CircuitTopology,
} from "maruaudio/dsp/circuit/dk-solver"
maruaudio/dsp/circuit re-exports both. The netlist leaf is authoring and
preparation code; the solver leaf runs in preparation and in the audio callback.
Netlist functions
| Function | Does |
|---|---|
parseCircuitNetlist(text) | Returns a CircuitNetlist; throws on a syntax or size error |
parseCircuitValue(token) | One value with its SPICE suffix, or null |
circuitInputIndex(netlist, name) | Index of a named input, or −1 |
circuitOutputIndex(netlist, name) | Index of a named output probe, or −1 |
circuitParameterIndex(netlist, name) | Index of a named parameter, or −1 |
circuitNodeIndex(netlist, name) | Index of a node, −1 for ground, −2 if unknown |
Look the indices up once, when you create the state, and keep the numbers.
Solver functions
| Function | When | Does |
|---|---|---|
initCircuit(topology, options?) | Create; allocates | Allocates every matrix and work vector for this topology |
prepareCircuit(state, sampleRate) | Prepare | Builds the model at this rate and settles it at the DC operating point. Returns false for an invalid rate or an unsolvable circuit and leaves the state silent |
setCircuitParameter(state, index, value) | Control | Stores a parameter position, clamped to 0 to 1, and marks the model for rebuild. A non-finite value is ignored |
updateCircuit(state) | Control, once per block | Rebuilds the model if a parameter changed and returns whether it did. If the new values make the circuit unsolvable, the previous model stays in use |
setCircuitInput(state, index, value) | Process | Sets input index for the next step |
circuitStep(state) | Process | Advances one sample with the inputs already set |
circuitTick(state, input) | Process | Sets input 0, advances one sample and returns output 0 |
circuitOutput(state, index) | Process | Output probe index from the latest step |
resetCircuit(state) | Reset | Returns to the DC operating point at the current parameters, with inputs at zero |
options.maxIterations (1 to 32, default 16) bounds the solver's iterations
per sample, and options.tolerance (volts, default 1e-9) sets when a sample
counts as solved.
Inputs and output probes
circuitTick is the shortcut for one input and one output. For several of
either, set each input, step once, then read each probe:
setCircuitInput(circuit, LEFT_IN, left[frame]) setCircuitInput(circuit, RIGHT_IN, right[frame]) circuitStep(circuit) outLeft[frame] = circuitOutput(circuit, LEFT_OUT) outRight[frame] = circuitOutput(circuit, RIGHT_OUT)
An input source adds the input's sample value to its DC offset. A voltage
input is in volts, a current input in amps. A non-finite input is read as 0.
An output probe is the voltage between its two nodes after the latest step,
and is always finite.
State and telemetry
The state carries its sizes: nodeCount, unknownCount, stateCount,
junctionCount, portCount, inputCount and outputCount. It also records
how the solver is doing, which is useful in tests and during development:
| Field | Meaning |
|---|---|
iterations | Iterations used by the latest step |
maxIterationsSeen | The most any step has used since prepareCircuit |
fallbacks | Steps that did not converge within maxIterations |
rebuilds | How many times the model has been rebuilt |
dcFloating | 1 when the circuit has no unique DC operating point, such as the junction of two capacitors in series; it then starts from zero state |
A step that does not converge keeps its last estimate. One that would produce a non-finite value keeps the previous sample's device solution instead.
Devices and models
| Device | Model |
|---|---|
| Resistor, variable resistor, pot, switch | Linear conductances |
| Capacitor, inductor | Trapezoidal companion model, one state each |
| Voltage, current and input sources | Standard source stamps; fixed sources are folded into constants and cost nothing per sample |
| Op-amp | Ideal (GAIN=inf) or a finite open-loop gain. Linear: no supply rails, slew limit or bandwidth limit |
Op-amp model (GBW=) | One dominant pole, an optional slew rate and supply rails with a soft knee; see below |
| JFET | Shichman-Hodges square law with channel-length modulation, symmetric in drain and source; gate junctions as Shockley diodes with GMIN; optional constant gate capacitances and series resistances |
| OTA | The tanh law of a bipolar differential pair into an ideal current output, with a fixed bias current or a junction bias pin |
| Diode | Shockley equation, with a linear continuation of the exponential above 40·N·VT so currents stay finite, and GMIN in parallel; optional constant junction capacitance and series resistance |
| NPN or PNP transistor | Ebers-Moll transport model with GMIN across each junction; optional constant junction capacitances and series resistances; no Early effect and no voltage-dependent or diffusion charge |
A device's capacitance or series resistance becomes an ordinary capacitor or
resistor in the netlist, placed right after the device: D1 a k CJ=4p RS=10
is the diode on an internal anode node d1:a, a 10 Ω resistor d1:rs from
a to it and a 4 pF capacitor d1:cj across the junction. A transistor's
internal nodes are q1:b, q1:e and q1:c. Netlist lines cannot connect
to internal nodes, but .output can probe them.
The ideal op-amp is solved exactly, inside the linear part of the system, so it never fails to converge. An ideal op-amp whose feedback path can open, such as a peak detector or a comparator, has no bounded answer: use the op-amp model for it, and for any stage whose bandwidth, slewing or clipping you want to hear.
Op-amp model
Adding GBW= turns an op-amp into a model of a real one:
- Gain-bandwidth. The open-loop gain is
GAINat DC and falls 6 dB per octave through unity atGBW, so a stage with a noise gain of 100 andGBW=1megrolls off around 10 kHz. - Slew rate. With
SR=the output can change no faster thanSRvolts per second; a large, fast signal turns into a triangle. - Rails. With
VPOS=andVNEG=the output stops at the rails: it follows the circuit untilKNEEvolts before a rail and bends over to it, and recovers at once when the signal comes back.
The model's internal pole is integrated with a second-order backward difference (BDF2, SPICE's Gear method) rather than the trapezoidal rule the rest of the circuit uses. An op-amp's closed-loop pole is usually far above the sample rate, where the trapezoidal rule would make every transient ring at Nyquist; BDF2 settles it in a few samples. The price is that a closed-loop corner in the top octaves comes out lower than the analog one: a 10 kHz corner measures 7.1 kHz at 48 kHz (8.85 kHz with the trapezoidal rule) and 9.6 kHz at 192 kHz, so oversample a stage whose top-octave response matters. The model has no output resistance or current limit, input offset or noise, and its rails are fixed voltages rather than supply nodes.
JFET
J<name> d g s NJF is the standard square-law model: below pinch-off
(vgs ≤ VTO) the channel is off; above it, the current rises with the
square of vgs − VTO in saturation and is a voltage-controlled resistance
of about 1/(2·BETA·(vgs − VTO)) at small drain-source voltages, the classic
use in phasers and drum voices. IDSS = BETA·VTO². Drain and source are
interchangeable. A P-channel PJF mirrors every voltage and current.
OTA
An OTA's output current is I·tanh((v+ − v−)/(2·N·VT)): a transconductance
I/(2·N·VT) for small inputs, proportional to the bias current, and at
most I. Give it a fixed IABC=, or a bias node: the pin is a junction to
ground, as in the chips, so a control voltage through a resistor sets the
bias current, about (Vc − 0.6 V)/R. A control at audio rate modulates the
gain or a filter's cutoff with no rebuild. An OTA follower into a capacitor
is a one-pole low-pass at gm/(2πC); its capacitor is held at DC only by
the OTA, so the circuit starts with every capacitor uncharged unless you
add the OTA's output resistance, a few megohms across the capacitor.
The solver is an independent implementation of the nodal DK method, from D. T. Yeh, J. S. Abel and J. O. Smith, "Automated Physical Modeling of Nonlinear Audio Circuits for Real-Time Audio Effects, Part I" (IEEE Transactions on Audio, Speech, and Language Processing, 2010), and M. Holters and U. Zölzer, "A generalized method for the derivation of non-linear state-space models from circuit schematics" (EUSIPCO, 2015). Once per parameter change, it reduces the circuit's equations to a discrete state-space system. Each sample then solves only for the voltages the nonlinear devices sense (the diode, transistor and JFET junctions, an OTA's or op-amp model's input, the op-amp model's internal node), starting from the previous sample's answer. Junctions that share the same pair of nodes, such as two antiparallel diodes, are solved as one voltage.
Limits
- Size. At most 64 unknowns (nodes, plus one for each voltage source and op-amp), 32 capacitors and inductors, 16 device junctions (a diode has one, a transistor two), 8 inputs, 8 outputs, 16 parameters and 256 elements. The parser refuses a larger circuit. A JFET counts two junctions, an OTA one (two with a bias pin), and an op-amp model adds a node, two capacitor states and up to two junctions. The realtime loops run to these bounds, so they also bound the worst-case cost.
- Devices. Only the devices in the table above. There are no vacuum tubes or MOSFETs. Junction capacitances are constant (no voltage-dependent depletion or diffusion charge), and there is no temperature dependence, noise or breakdown.
- Iterations. Each sample is bounded at
maxIterations. A circuit that needs more, because it is very stiff or driven far past its rails, reportsfallbacksrather than running longer. Results agree with an exact solve to the tolerance, not to the last bit. - Oscillators. A circuit starts at its DC operating point and nothing
perturbs it. An oscillator such as an astable multivibrator sits at its
unstable balance point until an input disturbs it, and its switching edges
are not solved: in the sample where it switches, the previous state stops
being a solution and Newton cannot reach the switched state from it. It
reports
fallbacksat each edge and the frequency depends on the sample rate. Junction capacitance does not help at audio rates; it would only slow the edge enough at steps of picoseconds. - Shared junctions. Only junctions on the same pair of nodes are merged. Junctions that depend on each other in another way, such as three diodes around a loop, are still solved but may need more iterations.
Realtime behaviour
initCircuit and parseCircuitNetlist are the only calls that allocate.
prepareCircuit, setCircuitParameter, updateCircuit, the step functions
and resetCircuit allocate nothing, take no locks, do no I/O and run bounded
loops. Every matrix is a flat Float64Array sized when you create the state.
Pots, variable resistors and switches are part of the circuit's linear system, so moving one means rebuilding the model. A rebuild is bounded, but it costs far more than a sample. Treat parameters as control-rate values:
- Call
setCircuitParameterwhenever a value arrives. It only stores the value, and moving several pots in one block still costs one rebuild. - Call
updateCircuitonce per block, before the sample loop. If you forget, the next step rebuilds for you, so a change is never lost, but that puts the rebuild inside your sample loop. - Don't modulate a pot at audio rate. For a sweep, update once per block.
A rebuild leaves the circuit's state untouched: the capacitors and inductors
keep their present charge and current, and the circuit continues with the new
component value, as the real circuit would. A moving pot does not click
because of the solver. prepareCircuit and resetCircuit settle
the circuit at its DC operating point, so a biased transistor stage starts at
its quiescent voltages instead of charging up from 0 V when the module loads.
Aliasing and oversampling
The trapezoidal method is the bilinear transform. A linear circuit's response matches the analog one with its frequency axis warped towards Nyquist: at 48 kHz an RC low-pass with a 1.59 kHz corner is about 3.03 dB down at that corner rather than 3.01 dB, and the difference grows towards the top octave. Diodes and transistors also create harmonics above Nyquist, which fold back as aliasing.
Both errors shrink when the circuit runs faster. maruaudio/dsp/circuit/oversampled
runs the solver at 2, 4 or 8 times the host rate: it interpolates each input
up to that rate through linear-phase half-band filters, steps the circuit
there, and filters and decimates each output back. You call it like the plain
solver, at the host rate:
import {
initOversampledCircuit,
oversampledCircuitTick,
prepareOversampledCircuit,
resetOversampledCircuit,
setOversampledCircuitParameter,
updateOversampledCircuit,
type OversampledCircuitState,
} from "maruaudio/dsp/circuit/oversampled"
// createState
const runner = initOversampledCircuit(netlist)
// prepare: the circuit runs at four times the host rate
prepareOversampledCircuit(runner, spec.sampleRate, 4)
const latency = runner.latencySamples // report this to the host
// control, once per block
setOversampledCircuitParameter(runner, DRIVE, drive)
updateOversampledCircuit(runner)
// process
output[frame] = oversampledCircuitTick(runner, input[frame])
| Function | Does |
|---|---|
initOversampledCircuit(topology, options?) | Allocates the solver and every filter buffer, for factors up to 8 |
prepareOversampledCircuit(state, sampleRate, factor) | Prepares the solver at factor × sampleRate and the filters for this host rate, and settles at the DC operating point. factor is 1, 2, 4 or 8; anything else, an invalid rate or an unsolvable circuit returns false. Call it again to change the factor |
oversampledCircuitLatencySamples(sampleRate, factor) | The latency in whole host samples, before preparing |
setOversampledCircuitParameter, updateOversampledCircuit | The solver's parameter calls, unchanged |
setOversampledCircuitInput, oversampledCircuitStep, oversampledCircuitOutput, oversampledCircuitTick | The solver's per-sample calls, at the host rate, for one or several inputs and outputs |
resetOversampledCircuit(state) | Back to the DC operating point with the filters at rest |
The solver itself is runner.circuit, so its telemetry is there. At factor 1
the runner is the plain solver, sample for sample, with no latency.
The output is delayed by latencySamples, a whole number of host samples that
depends on the rate and the factor. Report it to the host so it can align the
track, and delay a dry signal by the same amount before mixing it back in:
| Host rate | ×2 | ×4 | ×8 |
|---|---|---|---|
| 44.1 kHz | 77 | 84 | 87 |
| 48 kHz | 43 | 49 | 51 |
| 96 kHz | 13 | 17 | 19 |
| 192 kHz | 9 | 13 | 15 |
The filters are flat to 20 kHz within about 0.0001 dB and reject everything that would fold below 20 kHz by at least 100 dB. Between 20 kHz and the host's Nyquist they roll off, so that band is slightly attenuated and a hard-driven circuit can still leave folded components there. What the factor buys, for a diode clipper at 48 kHz in the tests:
| Measurement | ×1 | ×2 | ×4 | ×8 |
|---|---|---|---|---|
| RC low-pass with a 15.9 kHz corner, error at 20 kHz against the analog response | −7.3 dB | −0.90 dB | −0.20 dB | −0.05 dB |
| Clipper driven with 10 V at 5 kHz, largest aliased component below 20 kHz | −22 dB | −32 dB | −61 dB | −79 dB |
| Same at 9 kHz | −16 dB | −22 dB | −42 dB | −67 dB |
| Clipper at 2 V, 1 kHz, error below 20 kHz against a 512× reference | 1.6 mV | 0.38 mV | 0.096 mV | 0.024 mV |
The cost is about the solver's cost times the factor; the filters add little. A hard clipper needs ×4 or ×8 before its folded tones fall well below its harmonics, while ×2 already removes most of a filter's treble warping. A circuit that is linear, or that only shapes low frequencies, gains little: use the plain solver there. Choose the lowest factor whose result you cannot tell from the next one up.
How it is verified
The solver's tests render every circuit through the real solver and compare it with references computed independently in the test:
- an RC low-pass, a series RLC resonator and a unity-gain Sallen-Key low-pass against their bilinear-transform transfer functions (impulse, frequency and, for the RC, step response);
- exact DC of a voltage divider, a pot swept through linear and log tapers, a variable resistor, a switch and a current source;
- inverting, non-inverting and follower op-amp gains, ideal and with a finite open-loop gain;
- the op-amp model's closed-loop corner against its transfer function, its slew rate, knee and rails, a peak detector and a comparator against per-sample solves of the model, and a diode-feedback clipper converging to the ideal op-amp's as the gain-bandwidth grows;
- a JFET's output and transfer characteristics in every region against the closed form, a common-source stage's bias and gain against hand analysis, its channel as a voltage-controlled resistor and switch, and drain-source symmetry;
- an OTA's tanh curve and bias-proportional transconductance, and an OTA-C
low-pass's cutoff against
gm/(2πC), also with its bias modulated at audio rate; - a diode clipper against an independent scalar solve of its circuit equation at the same rate, and against a heavily oversampled continuous-time reference, where doubling the rate must cut the error at least threefold;
- the clipper's odd symmetry, and its DC operating point against the Shockley equation;
- a common-emitter transistor stage's DC operating point and small-signal gain against a hand-solved Ebers-Moll model;
- ±20 V into the clipper, a transistor stage and circuits with each new device, which must stay finite with bounded iterations and no fallbacks;
- a pot move costing one rebuild per update, keeping the capacitor state and changing the sound, and a reset that renders like a freshly prepared circuit;
- no allocation in prepare, parameter updates, steps and reset;
- the parser's values, names and indices, and a refusal for each class of mistake;
- unsolvable circuits refused by
prepareCircuit, and a DC-floating circuit flagged and started from zero state. - the oversampled runner's filters, measured from their impulse responses at six host rates; its latency against the impulse centre and the cross-correlation of noise in and out; an RC low-pass against the analog response, a hard-driven clipper's aliasing on a long windowed spectrum and the clipper against the 512× reference, for each factor; identity with the plain solver at factor 1; and reset, parameter, hot-input and allocation checks like the solver's.
These tests show that the solver solves the circuit you give it. Whether a model sounds like a particular piece of hardware is a separate question: measure your model against that hardware and listen to it.
Recipes
Each recipe is a complete netlist with one input called in and one output
probe called out, so circuitTick drives it directly.
RC low-pass
The simplest filter: a resistor in series and a capacitor to ground. Its
corner is 1/(2πRC), about 1.59 kHz for these values, and above the corner
it falls at 6 dB per octave.
* RC low-pass: corner 1/(2*pi*R*C), about 1.59 kHz Vin in 0 INPUT=in R1 in out 10k C1 out 0 10n .output out out
At 48 kHz it passes 100 Hz almost unchanged, is about 3 dB down at the corner,
and about 10.7 dB down at 5 kHz. To turn it into a tone control, make R1 a
variable resistor: R1 in out 100k NAME=tone MIN=1k moves the corner from
about 15.9 kHz at 0 down to about 158 Hz at 1.
Inverting op-amp stage with a gain control
An ideal op-amp holds its inverting input at the non-inverting input's
voltage, so the gain is −R2/R1. Here R2 is a variable resistor from
10 kΩ to 110 kΩ, so the gain control runs from −1 to −11.
* Inverting amplifier: gain -(R2/R1), R2 from 10k to 110k Vin in 0 INPUT=in R1 in minus 10k R2 minus out 100k NAME=gain VALUE=0.5 MIN=10k U1 0 minus out OPAMP .output out out
At the default position of 0.5, 0.1 V in gives −0.6 V out. Add GAIN=1e5 to
the op-amp line for a finite open-loop gain, which lowers the closed-loop gain
very slightly. For a stage that runs out of headroom, use the op-amp model:
U1 0 minus out OPAMP GBW=1meg SR=13meg VPOS=13.5 VNEG=-13.5 clips at
±13.5 V and slews at 13 V/µs.
Common-emitter transistor stage
A single NPN transistor, biased by a divider from a 9 V supply, with coupling capacitors on the input and output and the emitter resistor bypassed for gain. The solver settles the bias at prepare time, and the stage inverts and amplifies.
* Common-emitter stage, divider bias from 9 V, emitter bypassed for gain V1 vcc 0 9 Vin src 0 INPUT=in Cin src b 1u R1 vcc b 100k R2 b 0 22k RC vcc c 4.7k RE e 0 1k CE e 0 100u Cout c out 1u RL out 0 100k Q1 c b e NPN IS=1e-14 BF=200 .output out out .output vc c
The collector sits at about 4.8 V with no signal, and a 1 mV input at 1 kHz
comes out roughly 150 times larger and inverted. The stage is not
symmetrical, so it distorts unevenly: by 10 mV in, the negative half of the
output already swings further than the positive half, and at 100 mV the
transistor clips hard, swinging about +2.5 V and −5.9 V. Read the second probe with
circuitOutput(circuit, circuitOutputIndex(netlist, "vc")) to watch the
collector voltage itself.
Next steps
Return to DSP fundamentals for I/O, lifecycle, units and the other building blocks a circuit model can sit beside in a module.