Change Gain with a Partial Emitter Bypass

Gain is the ratio of output signal amplitude to input signal amplitude. A capacitor can change the gain of a transistor stage while its direct-current resistor network stays in place. Build one stage, measure its two gains, and check the actual operating point before, after and on restoration. The measured control matters: leakage, unsettled charging or a wiring error can move the bias even when the resistor values have not changed.

Use the exact onsemi BC547BBU bipolar junction transistor (BJT). A BJT uses a small base current to control a larger collector current. Its NPN name describes n-type, p-type and n-type semiconductor regions; these names describe material properties, not three charged terminals. Here it operates as a common-emitter amplifier: the base receives the input, the collector supplies an inverted output and the emitter returns through resistors to the common reference. An upward base signal normally causes a downward collector signal.

Direct current (DC) describes the steady bias; alternating current (AC) describes the changing signal around it. This experiment compares base-to-collector gain at 1 kilohertz (kHz), or 1000 cycles per second. It does not measure a generator-to-output DC gain: the input coupling capacitor blocks steady generator voltage. The article provides a design, a blank capture worksheet and host-tested analysis; no physical measurements or firmware build are claimed.

Before connecting any input or output cables, connect the RIGOL DHO804’s rear Ground Terminal to earth ground using the supplied ground cable, as required by the DHO800 User Guide. Its Type-C power input does not ground the instrument through the power cord. Use the supplied power adapter and keep the AFG1022’s and SPD3303X’s protective earth connected. The G0 signal-return connections described below do not replace this separate chassis earth lead.

BC547BBU common-emitter circuit with pins 1 collector, 2 base and 3 emitter; a removable 4.7 microfarad capacitor bypasses only the lower 820 ohm emitter resistor.
The jumper adds CE across RE2 while RE1 stays in the emitter path. Repeated B, C and G0 labels identify the same connected nets. Both probe returns and the generator shell join G0. Lower traces are calculated examples, not bench measurements. The drawing omits the DHO804 power adapter and separate chassis earth lead; connect them as described before adding any input or output cables. Editable Scalable Vector Graphics (SVG) · Full-size Portable Network Graphics (PNG)

What changes, and what must be checked

Negative feedback opposes a signal change. More emitter current produces more voltage across the emitter resistance, reducing the change in base-to-emitter voltage that caused it. This local feedback makes gain smaller and less dependent on transistor properties. With the bypass branch open, the signal sees both emitter resistors. Closing the branch gives AC another path through CE around the lower resistor. The upper resistor still supplies feedback.

The operating point is the set of steady voltages and currents before the signal is applied. Keeping the two resistors connected preserves the intended DC network. It does not prove identical measured bias. If the collector's DC voltage stays approximately unchanged, its output-voltage room also stays approximately unchanged. A larger gain then reduces input-referred headroom: the input amplitude available before the output approaches its limits. Our small input may remain clean in both states; clipping or a harmonic contrast is not a required result.

Parts, pins and connections

The current manufacturer table lists BC547BBU as Active, in the three-lead TO-92 package, case 135AN, bulk bag. That lifecycle entry is not a stock promise. The current BC550/D Rev6 drawing assigns pin 1 collector, pin 2 base, pin 3 emitter. Check the actual package drawing and numbered leads before inserting it. The unsuffixed BC547B is discontinued in that revision; its status is not transferred to BC547BBU. Group-B current gain, beta, is specified as 200–450 at collector current 2 milliamperes (mA) and collector-to-emitter voltage 5 V. One milliampere is one-thousandth of an ampere. Those test-point limits do not guarantee beta at our approximately 0.53 mA illustrative point.

An ohm (Ω) measures resistance; one kilohm (kΩ) is 1000 Ω. A farad measures capacitance: a microfarad (µF) is one-millionth of a farad and a nanofarad (nF) one-billionth. A millivolt (mV) is one-thousandth of a volt.

PartSelection and connection
Q1onsemi BC547BBU: pin 1 to C, pin 2 to B, pin 3 to E.
R1, R2Vishay MRS25 ±1%: 47 kΩ from 5 V to B; 15 kΩ from B to G0.
RCMRS25 4.7 kΩ ±1% from 5 V to C.
RE1, RE2MRS25 180 Ω from E to J; 820 Ω from J to G0. Neither is removed.
CEWIMA MKS2 4.7 µF, 63 V, ±10%, prefix MKS2C044701O00; connect its branch from J to G0 only for the bypassed state.
RS, CINMRS25 1 kΩ from generator center to CIN; WIMA MKS2 1 µF, 63 V, ±10%, prefix MKS2C041001F00, from RS to B.
CSWIMA MKS2 100 nF, 63 V, ±10%, prefix MKS2C031001A00, directly from 5 V to G0 near Q1.

The WIMA parts are nonpolar metallized polyester film capacitors: either electrical lead may face either node. The current March 2026 MKS2 table supplies these values and 5 mm lead spacing; select K for ±10% tolerance and the desired bulk/lead completion from that table. Their capacitance is finite and their insulation is not an ideal open circuit. Do not substitute an old 10 µF/50 V family description for this current selection. MRS25's stated 0.6 W rating applies under its documented temperature conditions; nominal powers here are below 10 mW, where a milliwatt is one-thousandth of a watt.

Use SIGLENT SPD3303X channel 1 (CH1) for measured 5.00 V, with a 20 mA current limit, tracking off and its other channels off. This is one common-reference circuit. Supply minus, generator shell and both scope returns join G0. Never connect a scope return to E, J or C. Use Tektronix AFG1022 channel 1 at 1 kHz sine, zero offset, meaning no commanded DC addition, and High Z display, meaning a high-impedance load assumption for the displayed amplitude. This menu choice does not remove the physical source impedance. Its typical 50 Ω source resistance and the stage's changing input loading make the displayed generator amplitude a starting setting. Measure B after CIN for the actual input.

Use a RIGOL DHO804 with two PVP2350 probes in 10× mode. Each probe attenuates the tip voltage by ten before the scope input; set the matching channel attenuation to 10× so exported volts refer to the tip. Compensate each probe by adjusting its response to the scope calibration square wave until its top is flat. Scope channel 1 touches B; scope channel 2 (CH2) touches C. The probes present 10 megohms (MΩ), where a megohm is one million ohms, with ±1% resistance tolerance, and 10 picofarads (pF) ±5 pF in this mode; one picofarad is one-trillionth of a farad. The nominal collector resistive loading is about 4.7 kΩ/10 MΩ, or 0.047%. Keep the probes installed in all states. The Bayonet Neill–Concelman (BNC) connector has a signal center and a common outer shell.

A calculation to compare with your own fixture

Replace the 47 kΩ/15 kΩ divider by its equivalent source for a conditional estimate. VTH is that equivalent source voltage and RTH its resistance; IB, IC and IE are base, collector and emitter currents:

VTH = 5 × 15 / (47 + 15) = 1.20968 V
RTH = 47 kΩ || 15 kΩ = 11.371 kΩ
IB = (VTH − VBE) / [RTH + (β + 1)(RE1 + RE2)]
IC = β IB;  IE = (β + 1) IB

The parallel symbol || denotes two impedances connected across the same two nodes. VB, VE and VC are the base, emitter and collector voltages relative to G0; VCE = VC − VE. Illustrative assumptions β = 200 and base-to-emitter voltage VBE = 0.65 V give IC = 0.527 mA, VE = 0.530 V, VB = 1.180 V, VC = 2.523 V and VCE = 1.993 V. They are calculated values, not transistor guarantees. Measure the real bias before proceeding.

For a small signal, use thermal voltage VT = 25.85 mV as a room-temperature assumption; VT is a temperature-dependent voltage scale in the transistor model. The small-signal base-to-emitter resistance is rπ = βVT/IC. The letter j denotes the imaginary unit used to represent phase. At angular frequency ω = 2πf:

ZE(open) = RE1 + RE2
ZE(bypassed) = RE1 + [RE2 || 1/(jωCE)]
Av ≈ −β(RC || 10 MΩ) / [rπ + (β + 1)ZE]

At 1 kHz, CE's reactance, the frequency-dependent opposition of a capacitor to AC, has magnitude about 33.9 Ω, so it is not a perfect short. The model gives ZE ≈ 181.4 − j33.8 Ω, unbypassed gain magnitude 4.457 and bypassed magnitude 20.091. Phase describes where one sine lies within a cycle relative to another; 360° is a full cycle. The latter gain has phase about −171.6° rather than exactly −180°. With an actual 20 mV-peak base sine, the two calculated collector peaks are approximately 89 mV and 402 mV. RC dissipates about 1.31 mW; RE1 about 0.051 mW and RE2 about 0.230 mW. Early effect, the dependence of collector current on collector-to-emitter voltage, along with device variation, capacitance tolerance, temperature and unwanted stray resistances/capacitances limit this model. The analyzer does not demand these gains or a particular phase shift.

Resolve the small input on the scope

Warm the scope for at least 30 minutes, self-calibrate according to its guide and compensate both probes. Use DC coupling, Normal acquisition, both 20 megahertz (MHz, million cycles per second) bandwidth limits, both channel Invert functions OFF and no averaging. Center the actual signals using vertical offset, which moves the measurement window around a DC level. Keep the final offsets, scales and probe positions fixed for all three states and their blanks.

With 10× probe settings, use displayed 10 mV/div on CH1, equivalent to 1 mV/div at its BNC input, and displayed 200 mV/div on CH2, equivalent to 20 mV/div at BNC. The current DHO800 specification permits ±1 V of BNC offset in both underlying ranges: approximately 0.118 V and 0.252 V of BNC offset can center the two nominal DC levels. Observe the trace direction and center it; do not rely on an assumed menu sign. The 20 mV-peak base sine occupies about four divisions peak-to-peak. Verify that neither channel reports overload and save the actual setup. A wide range showing the full 1.2 V base level would not establish a precise small-signal amplitude.

Save a simultaneous two-channel Memory CSV record near 20 ms long with 10,000 points, about 20 periods. CSV means comma-separated values, a text table. Retain the untouched native file, its setup screenshot and a normalized copy in seconds and probe-tip volts. The normalized header is exactly time_s,base_v,collector_v. Remove only documented metadata and rename headers; do not multiply, subtract offsets, interpolate, average or smooth the numeric rows. The software checks that native and normalized numeric triples are identical. Other export formats require a documented adapter and review rather than a guessed unit conversion.

Capture open, bypassed and open again

  1. With both source and generator outputs off, inspect the exact numbered transistor leads, resistors and common returns. Begin with the CE branch open. Set 5 V and the 20 mA limit. Unexpected current-limit operation, heating, unstable bias, instrument overload or clipped/unstable readings means stop, turn both outputs off and inspect the wiring.
  2. Enable the supply and wait at least 10 seconds. Set the generator to enabled DC 0 V. Use a Fluke 87V MAX digital multimeter (DMM), an instrument that reads voltage numerically, on its normal 6.000 V range. Its VΩ socket accepts voltage/resistance readings; COM is the common-return socket. Record VCC, VB, VE and VC in that order as the state's before controls, then detach its leads before capture.
  3. Capture one source-zero blank with both scope channels and all settings unchanged. Use Auto/free-running acquisition because a blank may not trigger. It records this fixture's observed background; it does not certify all later noise or source artifacts.
  4. Select the 1 kHz sine and adjust its amplitude until the measured base peak is near 20 mV. Save three separate active records, numbered 1–3. Keep fitted base peaks between 18 and 22 mV and within 5% of the initial state's median. This fitted-amplitude screen matches experiment points; it does not certify 5% absolute accuracy.
  5. Return the generator to enabled DC 0 V and repeat the four DMM readings in the same order as after. Switch both outputs off. Wait at least one second and verify CE's residual voltage before handling it. Its nominal discharge time constant through 820 Ω is only 3.85 ms, but time alone is not a voltage measurement.
  6. Install only CE's branch jumper and repeat as bypassed. Then turn both outputs off, remove that jumper and repeat as open_restore. Both emitter resistors stay connected throughout. The complete set contains six DC rows and twelve two-channel traces.

The DMM's normal 6.000 V range has 1 mV counts and a stated error of ±(0.05% of reading + 1 count). At approximately 1.18 V that is about ±1.59 mV; at 2.52 V about ±2.26 mV. Its nominal 10 MΩ input also loads the node while reading: divider-only estimates are about 1.4 mV at B and 1.2 mV at C. The handheld is removed for waveform capture; repeat the same control protocol in all states. These small loading estimates support the chosen agreement screens rather than establish unloaded precision.

What the analyzer can resolve

The analyzer fits a constant plus sine and cosine at 1000 Hz to each channel using ordinary least squares (OLS), choosing coefficients that minimize squared sample differences. The fitted sine/cosine pair supplies peak amplitude and phase; dividing the collector pair by the actual base pair supplies gain. A residual is the difference between a sample and that fitted waveform. Keep the reported residual and observed blank alongside the gain.

An interval is a lower and upper endpoint under stated assumptions, not a probability. At CH1's underlying 1 mV/div range the manufacturer's gain figure is typical, not guaranteed. This lesson therefore chooses an engineering allowance of 4% of its full displayed span: 4% × 8 × 10 mV = 3.2 mV. CH2 uses 1% × 8 × 200 mV = 16 mV. The software propagates these sample-error allowances through the actual OLS coefficient sensitivities, adds probe gain, observed blank fundamental plus maximum residual, and active maximum residual. Repetitions do not divide these fixed errors by the square root of sample count. In particular, the small unbypassed output keeps its broader relative error at the fixed collector range.

The additional 1% probe attenuation budget is also a chosen engineering assumption. The PVP2350 guide specifies ±1% input resistance, but does not certify a ±1% attenuation-ratio accuracy; resistance tolerance does not establish that gain limit. These chosen errors and observed backgrounds are engineering screens, not certified bounds on every future sample. They do not supply a confidence percentage or a calibrated distortion/noise specification. If the resulting base lower endpoint is zero, gain is unresolved. The program reports each gain interval and a bypass/open ratio interval. A resolved increase requires the bypassed lower gain endpoint to exceed both open-state upper endpoints and every control to pass. No expected factor is forced.

The chosen DC range screens are VCC 4.95–5.05 V, VB 0.8–1.6 V, VE 0.2–0.9 V, VC 1.5–3.5 V and VCE at least 0.8 V, including DMM error. Across all six readings, differences from the initial control plus both meter errors must fit within 20 mV for VCC, 10 mV for VB/VE and 30 mV for VC. Waveform-fitted DC must separately agree with the matching manual-control mean within chosen 60 mV at B and 120 mV at C, including the manual-reading error. These consistency thresholds acknowledge offset limitations; they are not certified offset bounds or precise AC-gain error terms. A zero-mean AC-coupled or wrong-unit export must not pass plausible DC controls.

Other quality screens require observed blank and maximum active residual each no greater than 5% of the active fundamental, no manually reported overload, and at least 0.4 V collector-swing room above emitter DC and below supply using the conservative output amplitude. Restoration needs overlapping gain intervals, a median gain within 10% of the initial median and the DC checks. Correct wiring alone does not guarantee a blank or residual below 5%; a real setup may exceed either screen and remain unresolved. All active traces must also show a broad inverted phase, with absolute phase at least 135°, while both scope channel Invert functions remain OFF. This chosen phase screen rejects a noninverting/wrong-channel result without forcing exactly −180° or the conditional −171.6° prediction. These are validity screens, not total harmonic distortion certification. A failed screen leaves the result unresolved even if nominal gains look persuasive.

Blank worksheet, complete code and an honest example

Download the standalone analysis ZIP. Extract it into a new directory. It contains the complete Python 3 standard-library analyzer and tests, a constructed-example generator, a blank physical worksheet directory and its README. No extra Python packages, target board or firmware are needed.

python3 -m unittest -v test_emitter_bypass.py
python3 make_constructed.py constructed-example
python3 emitter_bypass.py constructed-example
python3 emitter_bypass.py physical-blank

The generated example is explicitly constructed; its native files are labelled surrogates, not RIGOL exports. The last command must fail until real controls, records and hashes exist. The generator refuses a populated destination. Keep your real captures in a separate directory.

The administrative headers are exactly state,edge,vcc_v,vb_v,ve_v,vc_v and state,kind,repeat,file,native_sha256,normalized_sha256,overload. The README lists every required row, supported native header and provenance step. SHA-256, Secure Hash Algorithm with a 256-bit digest, is a summary of file bytes used to detect mismatches. A native file is named <normalized stem>.native.csv. Unique capture names, unique state/kind/repeat keys, both digests and equality of every native/normalized numeric row are checked; these checks do not prove independent physical acquisition or the truth of an operator's notes.

Strict parsing rejects duplicated/reordered headers, malformed quoting, invalid text, extra/missing rows, empty/nonfinite numeric cells, traversal/symlink paths and digest mismatches. Each administrative file is limited to 64 KiB, each waveform/native file to 2 MiB, and each waveform to 1000–20,000 rows, 10–30 periods and at least 50 samples per period with nearly uniform increasing times. A kibibyte (KiB) is 1024 bytes; a mebibyte (MiB) is 1024 KiB. Exit 2 means invalid or unsupported input with no JSON report. Exit 0 means a valid report, which may remain unresolved: check controls_passed and gain_increase_resolved. JSON is JavaScript Object Notation, the structured text used for the report.

Complete emitter_bypass.py
#!/usr/bin/env python3
"""BC547BBU partial-emitter-bypass worksheet analyzer. Python3 standard library.

No instrument control. All error allowances below are explicit engineering
screens, not probabilities or calibration certificates. Exit0 is a valid report,
possibly unresolved. Exit2 is invalid/unsupported input, with no JSON report.
"""
import cmath
import csv
import hashlib
import io
import json
import math
import re
import sys
from pathlib import Path

STATES=('open_before','bypassed','open_restore')
CONTROL_FIELDS=('state','edge','vcc_v','vb_v','ve_v','vc_v')
CAPTURE_FIELDS=('state','kind','repeat','file','native_sha256','normalized_sha256','overload')
WAVE_FIELDS=('time_s','base_v','collector_v')
FREQUENCY=1000.0
BASE_FS_ALLOWANCE=.04*(8*.010)  #4% of80mV displayed span; CH1 engineering choice.
COLLECTOR_FS_ALLOWANCE=.01*(8*.200)  #1% of1.6V span; actual20mV/div BNC.
PROBE_RELATIVE_ALLOWANCE=.01/.99  #Convert ±1% gain factor to conservative reading error.


def number(value):
    try:
        x=float(value)
    except (TypeError,ValueError,OverflowError):
        raise ValueError('numeric cell is blank or not a number')
    if not math.isfinite(x):
        raise ValueError('nonfinite numeric cell')
    return x


def read_csv(path,fields,byte_cap,row_cap):
    """Check the physical header before DictReader can collapse duplicates."""
    try:
        with Path(path).open('rb') as f:
            data=f.read(byte_cap+1)
        if len(data)>byte_cap:
            raise ValueError('CSV exceeds byte limit')
        text=data.decode('utf-8')
        parser=csv.reader(io.StringIO(text,newline=''),strict=True)
        header=next(parser,None)
        if header!=list(fields) or len(header)!=len(set(header)):
            raise ValueError('CSV must have the exact unique ordered header')
        rows=[]
        for cells in parser:
            if len(cells)!=len(fields):
                raise ValueError('wrong CSV field count or empty record')
            rows.append(dict(zip(fields,cells)))
            if len(rows)>row_cap:
                raise ValueError('CSV exceeds row limit')
        return rows,data
    except (OSError,UnicodeError,csv.Error) as exc:
        raise ValueError('CSV cannot be read strictly: '+str(exc))


def local_file(root,name):
    if not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9_.-]{0,90}\.csv',name):
        raise ValueError('capture file must be a plain CSV basename')
    p=root/name
    if p.is_symlink() or not p.is_file() or p.resolve().parent!=root.resolve():
        raise ValueError('capture is absent, a symlink, or outside fixture')
    return p



def verify_native_pair(data,normalized_samples):
    """Only metadata/header removal: compare every numeric row, with no rescaling.

    Supports the explicit3-column headers documented in README. Other native
    formats need an independently documented adapter, not a silent guess.
    """
    headers={('time_s','base_v','collector_v'),('x','ch1','ch2'),('time','ch1','ch2'),
             ('time(s)','ch1(v)','ch2(v)')}
    units={('second','volt','volt'),('s','v','v')}
    try:
        parser=csv.reader(io.StringIO(data.decode('utf-8'),newline=''),strict=True)
        found=False;started=False;rows=[];prefix=0
        for cells in parser:
            tokens=tuple(v.strip().lower() for v in cells)
            if not found:
                if tokens in headers:found=True
                else:
                    prefix+=1
                    if prefix>100:raise ValueError('too much native metadata')
                continue
            if not started and tokens in units:continue
            if len(cells)!=3:raise ValueError('native numeric row field count')
            row=tuple(number(v) for v in cells);started=True;rows.append(row)
            if len(rows)>20000:raise ValueError('native row limit')
        if not found or rows!=normalized_samples:
            raise ValueError('native/normalized numeric rows differ')
    except (UnicodeError,csv.Error) as exc:
        raise ValueError('unsupported native CSV: '+str(exc))


def inverse3(matrix):
    a=[list(row)+[float(i==j) for j in range(3)] for i,row in enumerate(matrix)]
    for k in range(3):
        pivot=max(range(k,3),key=lambda i:abs(a[i][k]))
        if abs(a[pivot][k])<1e-10:
            raise ValueError('singular sine fit')
        a[k],a[pivot]=a[pivot],a[k]
        factor=a[k][k];a[k]=[v/factor for v in a[k]]
        for i in range(3):
            if i!=k:
                factor=a[i][k];a[i]=[v-factor*w for v,w in zip(a[i],a[k])]
    return [row[3:] for row in a]


def fit_capture(samples):
    """Fit constant+sine+cosine at1kHz; return deterministic fit sensitivity.

    If each input sample has additive perturbation |e_i|<=epsilon, the fitted
    sine/cosine vector changes by at most epsilon*sum(hypot(w_s_i,w_c_i)).
    Hence its amplitude changes by no more than that quantity (triangle rule).
    This bound does not become a probability or establish the chosen epsilon.
    """
    if not 1000<=len(samples)<=20000:
        raise ValueError('waveform needs1000..20000 rows')
    if any(len(row)!=3 or any(not math.isfinite(v) for v in row) for row in samples):
        raise ValueError('waveform values must be finite triples')
    t0=samples[0][0];times=[r[0]-t0 for r in samples]
    dt=[b-a for a,b in zip(times,times[1:])]
    duration=times[-1]
    if not .010<=duration<=.030 or min(dt)<=0:
        raise ValueError('need10..30 periods and increasing time')
    step=sum(dt)/len(dt)
    if max(abs(x-step) for x in dt)>max(1e-12,step*.001) or max(dt)>.000020*(1+1e-9):
        raise ValueError('unsupported nonuniform or sparse sampling')
    basis=[(1.0,math.sin(2*math.pi*FREQUENCY*t),math.cos(2*math.pi*FREQUENCY*t)) for t in times]
    gram=[[sum(row[i]*row[j] for row in basis) for j in range(3)] for i in range(3)]
    inv=inverse3(gram)
    #An actual10..30-cycle record must be well conditioned for all3 coefficients.
    norm=max(sum(abs(v) for v in row) for row in gram)
    condition=norm*max(sum(abs(v) for v in row) for row in inv)
    if condition>5:
        raise ValueError('sine fit is poorly conditioned')
    weights=[[sum(inv[k][j]*row[j] for j in range(3)) for row in basis] for k in range(3)]
    sensitivity=sum(math.hypot(s,c) for s,c in zip(weights[1],weights[2]))
    result={'rows':len(samples),'duration_s':duration,'condition':condition,'sensitivity':sensitivity}
    phasors=[]
    for col,name in [(1,'base'),(2,'collector')]:
        values=[r[col] for r in samples]
        coeff=[sum(w*v for w,v in zip(ws,values)) for ws in weights]
        residual=[v-sum(c*x for c,x in zip(coeff,row)) for v,row in zip(values,basis)]
        phasor=complex(coeff[1],coeff[2]);phasors.append(phasor)
        result[name]={'dc_v':coeff[0],'sine_v':coeff[1],'cosine_v':coeff[2],
                      'amplitude_v':abs(phasor),'residual_rms_v':math.sqrt(sum(v*v for v in residual)/len(residual)),
                      'max_residual_v':max(abs(v) for v in residual),
                      'sample_min_v':min(values),'sample_max_v':max(values)}
    gain=phasors[1]/phasors[0] if abs(phasors[0])>1e-12 else None
    result['gain_magnitude']=abs(gain) if gain is not None else None
    result['phase_degrees']=math.degrees(cmath.phase(gain)) if gain is not None else None
    return result


def amplitude_interval(amplitude,sensitivity,fs_allowance,blank_allowance,residual_allowance):
    error=(sensitivity*fs_allowance+PROBE_RELATIVE_ALLOWANCE*amplitude+
           blank_allowance+residual_allowance)
    return [max(0.0,amplitude-error),amplitude+error]


def ratio_interval(numerator,denominator):
    if denominator[0]<=0:
        return None
    return [numerator[0]/denominator[1],numerator[1]/denominator[0]]


def meter_error(v):
    return .0005*abs(v)+.001


def nominal_model():
    beta=200.0;vbe=.65;vt=.02585;rth=47000*15000/(47000+15000)
    vth=5*15000/(47000+15000);ib=(vth-vbe)/(rth+(beta+1)*1000)
    ic=beta*ib;ie=(beta+1)*ib;rpi=beta*vt/ic
    rc=1/(1/4700+1/10000000)
    ze=180+1/(1/820+complex(0,2*math.pi*FREQUENCY*4.7e-6))
    opened=-beta*rc/(rpi+(beta+1)*1000)
    bypass=-beta*rc/(rpi+(beta+1)*ze)
    return {'calculated_not_measured':True,'beta_not_guaranteed_at_fixture_current':True,
            'ic_a':ic,'ve_v':ie*1000,'vc_v':5-ic*4700,'vce_v':5-ic*4700-ie*1000,
            'unbypassed_gain_magnitude':abs(opened),'bypassed_gain_magnitude':abs(bypass),
            'bypassed_phase_degrees':math.degrees(cmath.phase(bypass)),
            'emitter_impedance_ohm':[ze.real,ze.imag]}


def analyze(root):
    root=Path(root)
    if root.is_symlink() or not root.is_dir():
        raise ValueError('fixture must be a local directory, not a symlink')
    #The fixed administrative CSVs are subject to the same no-symlink rule.
    control_path=local_file(root,'controls.csv');manifest_path=local_file(root,'captures.csv')
    controls,_=read_csv(control_path,CONTROL_FIELDS,65536,6)
    if len(controls)!=6:
        raise ValueError('exactly6 manual DC rows required')
    dc={}
    for row in controls:
        key=(row['state'],row['edge'])
        if key[0] not in STATES or key[1] not in ('before','after') or key in dc:
            raise ValueError('duplicate or unknown manual DC state/edge')
        vals={f:number(row[f]) for f in CONTROL_FIELDS[2:]}
        if any(not -0.1<=v<=6 for v in vals.values()):
            raise ValueError('DC reading outside supported0..6V fixture')
        dc[key]=vals
    expected={(s,e) for s in STATES for e in ('before','after')}
    if set(dc)!=expected:
        raise ValueError('missing manual DC control')
    ranges={'vcc_v':(4.95,5.05),'vb_v':(.8,1.6),'ve_v':(.2,.9),'vc_v':(1.5,3.5)}
    tolerances={'vcc_v':.020,'vb_v':.010,'ve_v':.010,'vc_v':.030}
    dc_range=all(lo<=vals[f]-meter_error(vals[f]) and vals[f]+meter_error(vals[f])<=hi
                 for vals in dc.values() for f,(lo,hi) in ranges.items())
    vce_ok=all(v['vc_v']-v['ve_v']-meter_error(v['vc_v'])-meter_error(v['ve_v'])>=.8 for v in dc.values())
    baseline=dc[('open_before','before')]
    dc_agreement=all(abs(v[f]-baseline[f])+meter_error(v[f])+meter_error(baseline[f])<=tol
                     for v in dc.values() for f,tol in tolerances.items())
    rows,_=read_csv(manifest_path,CAPTURE_FIELDS,65536,12)
    if len(rows)!=12:
        raise ValueError('exactly12 capture records required')
    captures={};used=set()
    for row in rows:
        if row['state'] not in STATES or row['kind'] not in ('blank','active') or row['repeat'] not in ('0','1','2','3'):
            raise ValueError('unknown capture state/kind/repeat')
        key=(row['state'],row['kind'],int(row['repeat']))
        if key in captures or (key[1]=='blank')!=(key[2]==0):
            raise ValueError('duplicate or inconsistent capture key')
        if row['overload'] not in ('false','true'):
            raise ValueError('overload must be the literal false or true')
        for h in ('native_sha256','normalized_sha256'):
            if not re.fullmatch(r'[0-9a-f]{64}',row[h]):
                raise ValueError('missing/invalid capture SHA256')
        p=local_file(root,row['file'])
        native=local_file(root,p.stem+'.native.csv')
        if p.name in used or native.name in used:
            raise ValueError('capture file reused')
        used.update((p.name,native.name))
        wave,data=read_csv(p,WAVE_FIELDS,2**21,20000)
        if hashlib.sha256(data).hexdigest()!=row['normalized_sha256']:
            raise ValueError('normalized waveform SHA256 mismatch')
        #Native bytes are retained, not interpreted or silently normalized here.
        with native.open('rb') as f:native_bytes=f.read(2**21+1)
        if len(native_bytes)>2**21 or hashlib.sha256(native_bytes).hexdigest()!=row['native_sha256']:
            raise ValueError('native waveform size/SHA256 mismatch')
        samples=[tuple(number(r[f]) for f in WAVE_FIELDS) for r in wave]
        verify_native_pair(native_bytes,samples)
        if any(not -.25<=b<=6 or not -.25<=c<=6 for t,b,c in samples):
            raise ValueError('waveform outside supported probe-tip voltage range')
        fit=fit_capture(samples)
        fit.update(file=p.name,native_file=native.name,overload=row['overload']=='true',
                   normalized_sha256=row['normalized_sha256'],native_sha256=row['native_sha256'])
        captures[key]=fit
    expected={(s,'blank',0) for s in STATES}|{(s,'active',n) for s in STATES for n in (1,2,3)}
    if set(captures)!=expected:
        raise ValueError('missing capture key')
    reports={};all_quality=True;all_headroom=True;dc_consistency=True;overload=any(f['overload'] for f in captures.values())
    for state in STATES:
        blank=captures[(state,'blank',0)];active=[]
        for kind,n in [('blank',0),('active',1),('active',2),('active',3)]:
            f=captures[(state,kind,n)]
            for channel,field,threshold in [('base','vb_v',.060),('collector','vc_v',.120)]:
                control_values=[dc[(state,e)][field] for e in ('before','after')]
                center=sum(control_values)/2
                control_error=max(meter_error(v) for v in control_values)
                dc_consistency=dc_consistency and abs(f[channel]['dc_v']-center)+control_error<=threshold
        for n in (1,2,3):
            fit=captures[(state,'active',n)]
            intervals={}
            quality=True
            for name,fs in [('base',BASE_FS_ALLOWANCE),('collector',COLLECTOR_FS_ALLOWANCE)]:
                q=fit[name];bg=blank[name]
                background=bg['amplitude_v']+bg['max_residual_v']
                intervals[name]=amplitude_interval(q['amplitude_v'],fit['sensitivity'],fs,background,q['max_residual_v'])
                quality=quality and q['amplitude_v']>0 and background<=.05*q['amplitude_v'] and q['max_residual_v']<=.05*q['amplitude_v']
            gain_bounds=ratio_interval(intervals['collector'],intervals['base'])
            #DC room comparison is an engineering screen, not a saturation model.
            low_rail=max(v['ve_v']+meter_error(v['ve_v']) for k,v in dc.items() if k[0]==state)
            high_rail=min(v['vcc_v']-meter_error(v['vcc_v']) for k,v in dc.items() if k[0]==state)
            center_low=min(v['vc_v']-meter_error(v['vc_v']) for k,v in dc.items() if k[0]==state)
            center_high=max(v['vc_v']+meter_error(v['vc_v']) for k,v in dc.items() if k[0]==state)
            headroom=center_low-intervals['collector'][1]>=low_rail+.4 and center_high+intervals['collector'][1]<=high_rail-.4
            fit.update(amplitude_intervals_v=intervals,gain_interval=gain_bounds,
                       quality_screen_passed=quality,headroom_screen_passed=headroom)
            active.append(fit);all_quality=all_quality and quality;all_headroom=all_headroom and headroom
        amplitudes=sorted(f['base']['amplitude_v'] for f in active)
        gains=[f['gain_magnitude'] for f in active]
        intervals=[f['gain_interval'] for f in active]
        bound=[min(x[0] for x in intervals),max(x[1] for x in intervals)] if all(x is not None for x in intervals) else None
        reports[state]={'blank':blank,'active':active,'median_base_peak_v':amplitudes[1],
                        'median_gain':sorted(gains)[1] if all(x is not None for x in gains) else None,
                        'gain_interval':bound}
    initial=reports['open_before'];restore=reports['open_restore'];bypassed=reports['bypassed']
    nominal_base=initial['median_base_peak_v']
    matching=nominal_base>0 and all(.018<=f['base']['amplitude_v']<=.022 and abs(f['base']['amplitude_v']/nominal_base-1)<=.05
                                  for s in STATES for f in reports[s]['active'])
    a=initial['gain_interval'];b=restore['gain_interval'];c=bypassed['gain_interval']
    restore_ok=(a is not None and b is not None and max(a[0],b[0])<=min(a[1],b[1]) and
                initial['median_gain']>0 and abs(restore['median_gain']/initial['median_gain']-1)<=.10)
    phase_ok=all(f['phase_degrees'] is not None and abs(f['phase_degrees'])>=135-1e-9 for s in STATES for f in reports[s]['active'])
    controls_passed=all((phase_ok,dc_range,vce_ok,dc_agreement,matching,restore_ok,all_quality,all_headroom,dc_consistency,not overload))
    resolved=bool(controls_passed and all(x is not None for x in (a,b,c)) and c[0]>max(a[1],b[1]))
    return {'schema':'trickycircuit-emitter-bypass-1','valid_report':True,'physical_measurements_claimed':False,
            'frequency_hz':FREQUENCY,'gain_increase_resolved':resolved,'controls_passed':controls_passed,
            'screens':{'expected_inversion':phase_ok,'manual_dc_ranges':dc_range,'vce_room':vce_ok,'manual_dc_agreement':dc_agreement,
                       'fitted_base_matching':matching,'open_restore':restore_ok,'blank_and_residual':all_quality,
                       'collector_headroom':all_headroom,'waveform_dc_consistency':dc_consistency,'no_manual_overload':not overload},
            'engineering_assumptions':{'confidence_level':None,'ch1_fs_fraction_chosen_not_guaranteed':.04,
                'ch2_fs_fraction':.01,'base_fs_allowance_v':BASE_FS_ALLOWANCE,'collector_fs_allowance_v':COLLECTOR_FS_ALLOWANCE,
                'probe_gain_fraction':.01,'blank_and_residual_not_certified_error_bounds':True,
                'fixed_systematic_errors_not_divided_by_sqrt_n':True,'fit_matching_not_absolute_accuracy':True,'chosen_inversion_minimum_absolute_phase_degrees':135,'scope_channel_invert_must_be_off':True,'dc_consistency_thresholds_v':{'base':.060,'collector':.120},
                'dc_consistency_thresholds_chosen_not_certified':True},
            'manual_dc_controls':controls,'states':reports,
            'bypass_to_initial_gain_ratio_interval':ratio_interval(c,a) if a is not None and c is not None else None,
            'conditional_model':nominal_model()}


def main(argv=None):
    args=sys.argv[1:] if argv is None else argv
    if len(args)!=1:
        print('usage: python3 emitter_bypass.py FIXTURE_DIRECTORY',file=sys.stderr);return 2
    try:
        report=analyze(args[0]);output=json.dumps(report,indent=2,allow_nan=False)
    except (ValueError,OSError,OverflowError) as exc:
        print('input error: '+str(exc),file=sys.stderr);return 2
    print(output);return 0


if __name__=='__main__':sys.exit(main())
Complete constructed-example generator
#!/usr/bin/env python3
"""Create explicitly CONSTRUCTED fixtures, never measured bench records.

The .native.csv files in this example are labelled surrogates, not RIGOL exports.
Refuses any existing directory: it cannot overwrite an acquired fixture.
"""
import csv,hashlib,math,sys
from pathlib import Path
import emitter_bypass as eb

def write_csv(p,fields,rows):
    with p.open('w',newline='') as f:
        w=csv.writer(f);w.writerow(fields);w.writerows(rows)

def make(root):
    root=Path(root)
    if root.exists() and any(root.iterdir()):raise ValueError('destination must be absent or empty')
    root.mkdir(parents=True,exist_ok=True)
    model=eb.nominal_model();vc=model['vc_v'];ve=model['ve_v'];vb=ve+.65
    controls=[];manifest=[]
    for s in eb.STATES:
        for e in ('before','after'):controls.append([s,e,5.0,vb,ve,vc])
        for n in range(4):
            kind='blank' if n==0 else 'active';name='%s_%s_%s.csv'%(s,kind,n)
            amp=0 if n==0 else .02*(1+.002*(n-2))
            gain=model['bypassed_gain_magnitude'] if s=='bypassed' else model['unbypassed_gain_magnitude']
            phase=math.radians(model['bypassed_phase_degrees']) if s=='bypassed' else math.pi
            rows=[]
            for i in range(10000):
                t=i/500000.0;a=2*math.pi*1000*t+.2*n
                noise=2e-5*math.sin(i*1.726)
                rows.append([format(t,'.12g'),format(vb+amp*math.sin(a)+noise,'.12g'),format(vc+amp*gain*math.sin(a+phase)+noise*2,'.12g')])
            p=root/name;write_csv(p,eb.WAVE_FIELDS,rows);data=p.read_bytes()
            native=p.with_name(p.stem+'.native.csv')
            native.write_bytes(b'CONSTRUCTED SURROGATE - NOT AN INSTRUMENT EXPORT\n'+data)
            manifest.append([s,kind,n,name,hashlib.sha256(native.read_bytes()).hexdigest(),hashlib.sha256(data).hexdigest(),'false'])
    write_csv(root/'controls.csv',eb.CONTROL_FIELDS,controls)
    write_csv(root/'captures.csv',eb.CAPTURE_FIELDS,manifest)
    (root/'CONSTRUCTED-NOT-MEASURED.txt').write_text('All traces and DC values are constructed examples. Native files are explicitly labelled surrogates, not RIGOL captures. No physical measurements.\n')

if __name__=='__main__':
    if len(sys.argv)!=2:raise SystemExit('usage: python3 make_constructed.py EMPTY_OR_NEW_DIRECTORY')
    make(Path(sys.argv[1]))
Complete host tests
"""Meaningful stdlib tests; all waveforms below are constructed, never bench data."""
import csv, hashlib, json, math, subprocess, sys, tempfile, unittest
from pathlib import Path
import emitter_bypass as eb

class BoundaryTests(unittest.TestCase):
    def test_unique_header_before_dict_collapse(self):
        with tempfile.TemporaryDirectory() as d:
            p=Path(d)/'x.csv';p.write_text('time_s,base_v,base_v,collector_v\n0,nan,1,2\n')
            with self.assertRaises(ValueError):eb.read_csv(p,eb.WAVE_FIELDS,2**21,20000)
    def test_strict_quotes(self):
        with tempfile.TemporaryDirectory() as d:
            p=Path(d)/'x.csv';p.write_text('time_s,base_v,collector_v\n0,"1,2\n')
            with self.assertRaises(ValueError):eb.read_csv(p,eb.WAVE_FIELDS,2**21,20000)
    def test_limit_and_invalid_utf8(self):
        with tempfile.TemporaryDirectory() as d:
            p=Path(d)/'x.csv'
            for raw in [b' '*65537,b'\xff']:
                p.write_bytes(raw)
                with self.assertRaises(ValueError):eb.read_csv(p,eb.CONTROL_FIELDS,65536,6)
    def test_numeric_nan_and_blank(self):
        for v in ['nan','inf','','1e500']:
            with self.assertRaises(ValueError):eb.number(v)
    def test_safe_path(self):
        with tempfile.TemporaryDirectory() as d:
            for name in ['../x.csv','/tmp/x.csv','https://x','sub/x.csv']:
                with self.assertRaises(ValueError):eb.local_file(Path(d),name)
            (Path(d)/'s.csv').symlink_to('/etc/hosts')
            with self.assertRaises(ValueError):eb.local_file(Path(d),'s.csv')

class MathTests(unittest.TestCase):
    def samples(self,gain=-4.5,phase=0.0,noise=0.0):
        return [(i/500000.0,1.18+.02*math.sin(2*math.pi*1000*i/500000.0+.3),2.5+.02*gain*math.sin(2*math.pi*1000*i/500000.0+.3+phase)+noise*((i%3)-1)) for i in range(10000)]
    def test_known_gain_dc_and_inversion(self):
        r=eb.fit_capture(self.samples())
        self.assertAlmostEqual(r['base']['amplitude_v'],.02,places=12)
        self.assertAlmostEqual(r['collector']['dc_v'],2.5,places=12)
        self.assertAlmostEqual(r['gain_magnitude'],4.5,places=10)
        self.assertAlmostEqual(abs(r['phase_degrees']),180,places=8)
    def test_complex_phase(self):
        r=eb.fit_capture(self.samples(-20,.14))
        self.assertAlmostEqual(r['gain_magnitude'],20,places=10)
        self.assertAlmostEqual(r['phase_degrees'],-180+math.degrees(.14),places=8)
    def test_coefficient_error_contains_bounded_perturbation(self):
        s=self.samples();r=eb.fit_capture(s);eps=.0008
        altered=[(t,b+eps*math.sin(i*1.73),c) for i,(t,b,c) in enumerate(s)]
        q=eb.fit_capture(altered)
        self.assertLessEqual(abs(q['base']['amplitude_v']-r['base']['amplitude_v']),eps*r['sensitivity']+1e-12)
    def test_interval_widens(self):
        a=eb.amplitude_interval(.02,2,.0001,.0002,.0001)
        b=eb.amplitude_interval(.02,2,.001,.0002,.0001)
        self.assertLessEqual(b[0],a[0]);self.assertGreaterEqual(b[1],a[1])
    def test_denominator_unresolved(self):
        self.assertIsNone(eb.ratio_interval([.1,.2],[0,.1]))
    def test_nonuniform_and_bad_timing(self):
        s=self.samples()
        for bad in [s[:999],[(0,b,c) for t,b,c in s],[(t*10,b,c) for t,b,c in s]]:
            with self.assertRaises(ValueError):eb.fit_capture(bad)
    def test_exactly_fifty_samples_per_period(self):
        s=[(i*.000020,1.18+.02*math.sin(2*math.pi*1000*i*.000020),2.5-.09*math.sin(2*math.pi*1000*i*.000020)) for i in range(1000)]
        r=eb.fit_capture(s);self.assertAlmostEqual(r['gain_magnitude'],4.5,places=8)
        bad=[(t*1.001,b,c) for t,b,c in s]
        with self.assertRaises(ValueError):eb.fit_capture(bad)
    def test_nonfinite_programmatic_samples(self):
        s=self.samples();s[4]=(s[4][0],float('nan'),2.5)
        with self.assertRaises(ValueError):eb.fit_capture(s)
    def test_conditional_model(self):
        r=eb.nominal_model()
        self.assertAlmostEqual(r['unbypassed_gain_magnitude'],4.456921168975944,places=6)
        self.assertAlmostEqual(r['bypassed_gain_magnitude'],20.090756578836075,places=5)

class CLITests(unittest.TestCase):
    def build(self,root):
        import make_constructed
        make_constructed.make(root)
    def call(self,root):
        return subprocess.run([sys.executable,str(Path(eb.__file__)),str(root)],capture_output=True,text=True)
    def test_constructed_complete_and_truthful(self):
        with tempfile.TemporaryDirectory() as d:
            self.build(Path(d));p=self.call(Path(d));self.assertEqual(p.returncode,0,p.stderr)
            r=json.loads(p.stdout);self.assertTrue(r['gain_increase_resolved']);self.assertTrue(r['controls_passed']);self.assertFalse(r['physical_measurements_claimed'])
    def test_unresolved_is_valid_report(self):
        with tempfile.TemporaryDirectory() as d:
            self.build(Path(d));p=Path(d)/'controls.csv';rows=list(csv.reader(p.read_text().splitlines()));rows[3][5]='2.65'
            with p.open('w',newline='') as f:csv.writer(f).writerows(rows)
            q=self.call(Path(d));self.assertEqual(q.returncode,0,q.stderr);self.assertFalse(json.loads(q.stdout)['controls_passed'])
    def test_duplicate_hidden_nan_actual_cli(self):
        with tempfile.TemporaryDirectory() as d:
            self.build(Path(d));p=Path(d)/'controls.csv';s=p.read_text();s=s.replace('vcc_v,','vcc_v,vcc_v,',1).replace('before,5.0,','before,nan,5.0,',1);p.write_text(s)
            q=self.call(Path(d));self.assertEqual(q.returncode,2);self.assertEqual(q.stdout,'')
    def test_zero_mean_base_export_cannot_pass_manual_dc(self):
        with tempfile.TemporaryDirectory() as d:
            self.build(Path(d));root=Path(d)
            manifest=list(csv.DictReader((root/'captures.csv').read_text().splitlines()))
            for row in manifest:
                p=root/row['file'];lines=list(csv.reader(p.read_text().splitlines()))
                for cells in lines[1:]:cells[1]=str(float(cells[1])-1.1797106402369562)
                with p.open('w',newline='') as f:csv.writer(f).writerows(lines)
                row['normalized_sha256']=hashlib.sha256(p.read_bytes()).hexdigest()
                native=p.with_name(p.stem+'.native.csv');native.write_bytes(b'CONSTRUCTED AC-COUPLED SURROGATE - NOT MEASURED\n'+p.read_bytes())
                row['native_sha256']=hashlib.sha256(native.read_bytes()).hexdigest()
            with (root/'captures.csv').open('w',newline='') as f:
                w=csv.DictWriter(f,fieldnames=eb.CAPTURE_FIELDS);w.writeheader();w.writerows(manifest)
            q=self.call(root);self.assertEqual(q.returncode,0,q.stderr)
            self.assertFalse(json.loads(q.stdout)['screens']['waveform_dc_consistency'])
            self.assertFalse(json.loads(q.stdout)['gain_increase_resolved'])
    def test_valid_hashes_but_wrong_native_pair(self):
        with tempfile.TemporaryDirectory() as d:
            self.build(Path(d));root=Path(d)
            rows=list(csv.DictReader((root/'captures.csv').read_text().splitlines()))
            native=root/'open_before_active_1.native.csv';native.write_bytes((root/'bypassed_active_1.native.csv').read_bytes())
            for row in rows:
                if row['file']=='open_before_active_1.csv':row['native_sha256']=hashlib.sha256(native.read_bytes()).hexdigest()
            with (root/'captures.csv').open('w',newline='') as f:
                w=csv.DictWriter(f,fieldnames=eb.CAPTURE_FIELDS);w.writeheader();w.writerows(rows)
            q=self.call(root);self.assertEqual(q.returncode,2);self.assertEqual(q.stdout,'')
    def test_reused_capture_basename(self):
        with tempfile.TemporaryDirectory() as d:
            self.build(Path(d));root=Path(d)
            rows=list(csv.DictReader((root/'captures.csv').read_text().splitlines()))
            rows[2].update({k:rows[1][k] for k in ('file','native_sha256','normalized_sha256')})
            with (root/'captures.csv').open('w',newline='') as f:
                w=csv.DictWriter(f,fieldnames=eb.CAPTURE_FIELDS);w.writeheader();w.writerows(rows)
            q=self.call(root);self.assertEqual(q.returncode,2);self.assertEqual(q.stdout,'')
    def test_noninverting_capture_cannot_resolve_expected_stage(self):
        with tempfile.TemporaryDirectory() as d:
            self.build(Path(d));root=Path(d)
            manifest=list(csv.DictReader((root/'captures.csv').read_text().splitlines()))
            model=eb.nominal_model();vb=model['ve_v']+.65;vc=model['vc_v']
            for row in manifest:
                if row['kind']!='active':continue
                p=root/row['file'];lines=list(csv.reader(p.read_text().splitlines()))
                gain=model['bypassed_gain_magnitude'] if row['state']=='bypassed' else model['unbypassed_gain_magnitude']
                for cells in lines[1:]:cells[2]=str(vc+gain*(float(cells[1])-vb))
                with p.open('w',newline='') as f:csv.writer(f).writerows(lines)
                row['normalized_sha256']=hashlib.sha256(p.read_bytes()).hexdigest()
                native=p.with_name(p.stem+'.native.csv');native.write_bytes(b'CONSTRUCTED WRONG-PHASE SURROGATE\n'+p.read_bytes());row['native_sha256']=hashlib.sha256(native.read_bytes()).hexdigest()
            with (root/'captures.csv').open('w',newline='') as f:
                w=csv.DictWriter(f,fieldnames=eb.CAPTURE_FIELDS);w.writeheader();w.writerows(manifest)
            q=self.call(root);self.assertEqual(q.returncode,0,q.stderr)
            self.assertFalse(json.loads(q.stdout)['gain_increase_resolved'])
    def test_exact_negative135_phase_actual_cli(self):
        with tempfile.TemporaryDirectory() as d:
            self.build(Path(d));root=Path(d)
            manifest=list(csv.DictReader((root/'captures.csv').read_text().splitlines()))
            model=eb.nominal_model();vb=model['ve_v']+.65;vc=model['vc_v']
            for row in manifest:
                if row['kind']!='active':continue
                p=root/row['file'];lines=list(csv.reader(p.read_text().splitlines()))
                n=int(row['repeat']);amp=.02*(1+.002*(n-2))
                gain=model['bypassed_gain_magnitude'] if row['state']=='bypassed' else model['unbypassed_gain_magnitude']
                for cells in lines[1:]:
                    a=2*math.pi*1000*float(cells[0])+.2*n
                    cells[1]=str(vb+amp*math.sin(a));cells[2]=str(vc+amp*gain*math.sin(a-math.radians(135)))
                with p.open('w',newline='') as f:csv.writer(f).writerows(lines)
                row['normalized_sha256']=hashlib.sha256(p.read_bytes()).hexdigest()
                native=p.with_name(p.stem+'.native.csv');native.write_bytes(b'CONSTRUCTED EXACT NEGATIVE135 SURROGATE\n'+p.read_bytes());row['native_sha256']=hashlib.sha256(native.read_bytes()).hexdigest()
            with (root/'captures.csv').open('w',newline='') as f:
                w=csv.DictWriter(f,fieldnames=eb.CAPTURE_FIELDS);w.writeheader();w.writerows(manifest)
            q=self.call(root);self.assertEqual(q.returncode,0,q.stderr)
            self.assertTrue(json.loads(q.stdout)['screens']['expected_inversion'])
    def test_hash_mismatch(self):
        with tempfile.TemporaryDirectory() as d:
            self.build(Path(d));p=Path(d)/'open_before_active_1.csv';p.write_text(p.read_text()+'\n')
            q=self.call(Path(d));self.assertEqual(q.returncode,2);self.assertEqual(q.stdout,'')
    def test_blank_controls_actual_cli(self):
        with tempfile.TemporaryDirectory() as d:
            self.build(Path(d));p=Path(d)/'controls.csv';rows=list(csv.reader(p.read_text().splitlines()));rows[1][2]=''
            with p.open('w',newline='') as f:csv.writer(f).writerows(rows)
            q=self.call(Path(d));self.assertEqual(q.returncode,2);self.assertEqual(q.stdout,'')

if __name__=='__main__':unittest.main()

Challenge

Why does bypassing only RE2 increase 1 kHz gain without intentionally changing the DC resistor network, and why is unchanged DC still a measurement?

Answer

CE supplies a lower-impedance AC path around RE2 while RE1 retains local feedback. At DC the intended emitter path still contains both resistors, but real capacitor leakage, settling, device heating or a wiring mistake can alter bias. The before/after/restored measurements test that control. A changed generator setting also cannot replace the actual base measurement because input loading changes when feedback changes.

Sources and related reading