A capacitor can stay unchanged while its measured capacitance changes with the test leads. Use a DE-5000 to compare a matched open/short calibration, a deliberately changed lead route and a restored setup. Then use a separate constructed complex model to learn why subtracting one capacitance number is not a general fixture correction.
An LCR meter measures inductance (L), capacitance (C) and resistance (R). Capacitance describes charge stored per volt. This experiment uses parallel capacitance, Cp: the capacitance in an equivalent model whose loss and capacitance connect across the same two terminals at one frequency. Its secondary display is dissipation factor, D, a dimensionless ratio of loss current to the capacitor’s charging current in that parallel model. The device under test (DUT) is one detached capacitor. Open/short compensation is the meter’s procedure for reducing effects of the test fixture using an open connection and a short connection; its CAL key calls this calibration. It does not turn an ordinary capacitor into a calibration standard.
There are two records here. The physical worksheet contains only manually transcribed DE-5000 displays and actual CAL outcomes. The computer model contains invented, explicitly declared complex impedances—numbers that retain both opposition to an alternating signal and the phase relationship between voltage and current, meaning their relative positions within a cycle. No instrument measurements were made for this article, and the software neither communicates with the meter nor verifies that a user performed CAL.
A measurement plane identifies the two contacts at which a result is intended to describe the DUT. Here it is the TL-21 clip jaws touching the capacitor leads. The lead portions from those jaws to the capacitor body remain part of the measured object. Moving the contact positions changes that object; moving the cable can change the fixture’s unwanted resistance, inductance and capacitance, called parasitics.
Use battery operation only. There is no external direct-current (DC) source, alternating-current (AC) source, AC adapter or infrared-to-Universal-Serial-Bus (IR-USB) connection. The optional guard lead is unused and unattached. The low-side contact is a measurement terminal, not a protective-earth connection. A picofarad (pF) is 10−12 farad, a nanofarad (nF) is 10−9 farad, and a kilohertz (kHz) is 1,000 cycles per second. The illustrations’ H and L mean the high-side and low-side measurement contacts.

| Item | Exact choice and purpose |
|---|---|
| Meter and leads | DER EE / IET DE-5000 with its factory TL-21 four-wire alligator adapter, assembled as supplied, and a good 9 V battery. Each clip is the joining point for its pair of conductors. Do not infer a connector pinout from the functional drawing. |
| C1 | WIMA FKP2 polypropylene film/foil, 100 pF, 100 V DC, ±5%, 5 mm lead pitch; nonpolar, so either lead can face H. Use FKP2D001001D00JSSD: the current 03.26 catalogue’s 100 pF/100 V stem completed with J (±5%), S (bulk packing) and SD (nominal 6 mm leads, −2 mm tolerance). Its body is 4.5 × 6 × 7.2 mm. Verify that exact value/rating/tolerance and completion on the supplied part’s documentation. |
| Voltage check | Fluke 87V MAX digital multimeter (DMM), black lead in the common (COM) socket and red lead in V/Ω, selected to DC voltage. Use only to check this detached, previously unpowered capacitor before LCR connection; detach both DMM probes before using the DE-5000. |
| Reference marks | A nonconducting surface, two documented cable routes A/B, marked capacitor contact positions, and a clock/camera for actual setup notes. Do not add a breadboard, long extension wires or other parallel instruments. |
Choose the DE-5000’s Auto C function using LCR AUTO, then use SER/PAL to select Cp explicitly. Use FREQ to select 100 kHz and D/Q/ESR/Θ to select D (ESR on the button means equivalent series resistance; Θ is phase angle). Confirm those actual indicators; leave relative mode (REL%), HOLD and sorting off. Do not rely on the automatic series/parallel choice. At nominal 100 pF and 100 kHz, the ideal capacitive impedance magnitude is about 15.9 kilohms, and an automatic representation choice can differ from the Cp convention used here.
The selected range is 200.00 pF with 0.01 pF resolution. The current official DE-5000 manual specifies ±(2.0% of reading + 5 least-significant counts) at 100 kHz for this range after open/short calibration. At a 100.00 pF display, that term is 2.05 pF, not 0.01 pF. Resolution describes the display step, not accuracy. Use 18–28 °C and relative humidity below 70%, noncondensing: this respects the manual’s general humidity condition and its 23 ±5 °C accuracy condition. The selected simple capacitance specification applies with D ≤0.1; this lesson also withholds comparisons for negative or nonnumeric D. These screens do not establish a complete uncertainty budget for contacts, interference, temperature, repeatability or the D display.
The IET manual calls the test signal 0.5 volts root mean square (Vrms), typical. That is not a guaranteed maximum or a user-selected amplitude here. C1’s 100 V DC rating is a component working rating, not permission to connect an external voltage to the meter. Its ±5% tolerance describes manufacture, not traceable calibration. Do not call the displayed value “correct” merely because it is closer to 100 pF.
On battery power the manual describes automatic shutoff after about five minutes of inactivity. Keep records promptly and watch for shutdown. If the meter powers off, its state becomes unknown for this sequence: restore the settings and begin a new sequence with fresh documented CAL events. No persistence of compensation across power cycling is assumed.
Use the current official manual’s TL-21 example and CAL steps (printed pages 14–16). For OPEN, keep the adapter installed but remove the DUT and leave the measurement ends separated. “Open” refers to those ends, not to unplugging the adapter and calibrating a different fixture.
OPEn appears. Press CAL again to start the approximately 30-second countdown. Record the actual PASS or FAIL. A failure requires restarting; do not invent a successful reference.Srt, then press CAL again to start the short-calibration countdown. Record its actual PASS or FAIL; restart on failure.The real short has contact resistance and geometry; it is not an independently certified zero-ohm standard. The stock clips inevitably move between open, short and DUT states. Record that limitation and keep their route and contact region consistent rather than claiming perfect removal of every fixture effect. Do not add guard wiring midway through the sequence. If interference or unstable indications prevent repeatable observations, stop this comparison and investigate the setup.
OPEn, Srt and PASS are procedure/status indications, not complex impedance readings. An OL overload display is nonnumeric. The program never replaces it with a very large finite impedance, and it never invents a phase or raw complex open/short value from Cp and D.
A control is a deliberately retained or restored condition used to judge what a change might mean. Record all five stages in the blank manual worksheet. Its format is comma-separated values (CSV): one header followed by fields separated by commas. Actual display, environmental and CAL-result cells are blank because no measurements have been made. Route A/B and CAL-event labels are declarations you must substantiate with your own notes.
| Stage | Physical route / retained CAL | What to do |
|---|---|---|
| as_found_A | A / unknown | Before new CAL, record the actual Cp/D displays with the intended settings. The prior compensation state is unknown; do not label it raw or uncompensated. |
| matched_A | A / fresh A1 | Run OPEN and SHORT as above. Record their real outcomes, reconnect C1 and transcribe Cp/D. |
| stale_B | B / still A1 | Change only the cable route to a photographed B arrangement, keeping C1 and jaw contact positions as consistent as possible. Do not run CAL. Record Cp/D. If you cannot preserve contacts, document that additional change. |
| matched_B | B / fresh B1 | Run a fresh OPEN/SHORT sequence at B, reconnect C1 and record actual Cp/D and CAL outcomes. |
| restored_A | A / fresh A2 | Restore the documented A arrangement, run a new OPEN/SHORT sequence and record again. A2 is a new event; do not assume old coefficients were recalled. |
Complete the fields exactly: frequency 100000 in hertz; modes Cp and D; relative mode off; primary unit pF; source kind reported. Transcribe a plain display decimal, OL or ----, without silently changing signs or adding precision. Record temperature in degrees Celsius and relative humidity in percent. Retain A1 for the deliberately stale B record; use distinct fresh B1 and A2 events for the later calibrations. Event names can differ, but their relationships must remain the same.
Only a complete sequence meeting the selected conditions and successful new CAL outcomes produces three display differences: A after CAL minus A as found; B with stale CAL minus B after fresh CAL; and restored A minus matched A. These are changes in displayed values, not measured parasitic components or proof that accuracy improved. A repeatable nonzero difference is evidence to investigate; a difference too small to resolve is a valid outcome. The existing capacitance specification is not automatically an error bound on a difference of two observations.
The native command refuses wrong units, modes, ordering, frequency, malformed records or inconsistent CAL-event identities. It retains OL, a failed CAL or out-of-scope D/environment without producing the numerical comparison. Nothing in this log is externally compensated a second time. Manual declarations cannot verify the physical connections, calibration execution or instrument state.
Impedance, Z, describes opposition to an alternating signal, including both magnitude and phase. A complex number keeps the in-phase real part and the quarter-cycle imaginary part together; j is the square root of −1. The admittance, Y = 1/Z, is the reciprocal of impedance. Ohms (Ω) are impedance units; siemens (S) are admittance units. Angular frequency is ω = 2πf, with f in hertz. A henry (H) is the unit of inductance. The prefixes micro (µ) and nano (n) mean 10−6 and 10−9.
The manual illustrates a series resistance/inductance followed by a shunt conductance/capacitance. Conductance is the in-phase current per volt; shunt means connected across the two measurement sides. For this declared teaching network, define Zs = Rs + jωLs and Yp = Gp + jωCp, with Gp the unwanted parallel conductance. The model’s Cp symbol refers to fixture shunt capacitance here; the meter’s displayed Cp is an equivalent parallel capacitance. The distinction matters. We use the following topology, not a reconstruction of DE-5000 firmware:
Zm = Zs + 1 / (1/Zdut + Yp)
Zshort = Zs
Zopen = Zs + 1/Yp
Zdut = 1 / [1/(Zm − Zshort) − 1/(Zopen − Zshort)]
An ideal short at that model’s contact plane gives Zshort = Zs. An ideal open gives Zopen = Zs + 1/Yp. Subtract the series term first; then subtract the open’s admittance from the DUT measurement’s admittance. This produces the inverse above only when the three data sets describe the same plane, frequency and fixture state. The algebra does not justify applying it to native readings that the meter may already have compensated.
In the constructed worksheet, fixture A has Rs = 2 Ω, Ls = 2 µH, Gp = 10 nS and shunt capacitance 20 pF. The modeled DUT is a capacitor with 0.5 Ω series loss, swept from 100 pF to 100 nF at 100 kHz. Fixture B in the optional demo uses 3 Ω, 3 µH, 20 nS and 35 pF. These are chosen teaching values, not measured TL-21 parameters. Only the first nominal capacitance equals physical C1; all other sweep points are synthetic model variations.

The orange raw curve includes the fixture. The purple comparison subtracts the apparent open Cp from the apparent DUT Cp; it can be close at one end yet retain a growing series-fixture error elsewhere. The blue curve uses the complete inverse. Its near-zero error reflects algebraic recovery of the known model, not demonstrated meter accuracy. At the 100 nF end, naive Cp subtraction leaves roughly 5.6% relative error in this particular network.
Small differences followed by reciprocals can magnify uncertainty. A complex disk is the set of possible complex values within a stated radius of a center. Here the radii are declared model perturbations in ohms, not DE-5000 specifications. If a measured center has disk radius um and the short center has radius us, their difference a has radius ua = um + us. Likewise b, the open-minus-short difference, has radius ub = uo + us.
a = Zm − Zshort; ua = um + us
b = Zopen − Zshort; ub = uo + us
Require |a| > ua and |b| > ub.
y = 1/a − 1/b
uy = ua/[|a|(|a|−ua)] + ub/[|b|(|b|−ub)]
Require |y| > uy; otherwise withhold finite Zd.
Zd center = 1/y
Analytic input-disk radius = uy/[|y|(|y|−uy)]
The reciprocal bound follows from |1/(a+δ) − 1/a| = |δ|/(|a||a+δ|) and |a+δ| ≥ |a| − ua. Add the two reciprocal bounds for y. If the resulting disk reaches zero, arbitrarily large inverses remain possible, so the program withholds a finite result. Where it excludes zero, the same identity bounds the final reciprocal. This is a conservative analytic input-perturbation bound under exact arithmetic; shared short errors are bounded by triangle inequalities, not treated as independent random errors.
The provided model radii are um = 0.001 Ω, uo = 0.1 Ω and us = 0.001 Ω. They are invented assumptions. The code also has a separate floating-point cancellation screen at 64 machine-epsilon times the reciprocal magnitudes. Ordinary Python arithmetic is not a certified rounding enclosure, and this screen is not a proof of all roundoff error. The reported disk must not be promoted into a calibrated physical uncertainty claim.
Use Python 3.9 or later with only its standard library. Read the extraction and run instructions before running the commands from the extracted folder. No driver, USB protocol, meter export or instrument-control library is used.
python3 code/fixture_correction.py demo > generated-constructed.csv
python3 code/fixture_correction.py complex constructed-complex.csv
python3 code/fixture_correction.py complex constructed-near-open.csv
python3 code/fixture_correction.py complex constructed-stale-plane.csv
# Expected refusal above: stale measurement plane, exit 2.
# Fill actual readings and CAL outcomes in a COPY of the blank worksheet:
python3 code/fixture_correction.py native my-native-display.csv
python3 -m unittest discover -s tests -v
The first command emits only constructed raw complex data; --fixture B selects the other declared fixture. The complex command accepts only source kind constructed and compensation state raw, with three equal frequency and plane declarations. Change the appropriate blank native worksheet cells to your actual records before running its command; the delivered blank file is expected to be refused. Keep a copy of original observations and setup notes. Do not change a mode label just to make a file pass.
Valid reports exit with status 0, including a valid near-open row whose inverse is withheld. Refusals exit with status 2 and no partial report on standard output. Input is strict Unicode Transformation Format, 8-bit (UTF-8), CSV, at most 128 kibibytes (KiB; 1 KiB = 1,024 bytes), with exact headers, full-width records and at most 64 rows. The native path requires its exact five stages. Invalid numeric values, nonfinite values, malformed quoting, unknown source kinds, mismatched planes and double compensation are refused. A syntactically valid file still does not prove that its declarations are true.
#!/usr/bin/env python3
"""Manual DE-5000 display log and SEPARATE constructed complex-fixture model.
No instrument transport. Native Cp/D readings are never externally corrected.
Complex correction accepts only declared raw constructed inputs with matching
planes/frequencies. Its disks are analytic input-perturbation bounds under
exact arithmetic; ordinary floating-point evaluation is not a certified full
roundoff or physical measurement-uncertainty calculation.
"""
import argparse
import csv
from fractions import Fraction
import io
import json
import math
from pathlib import Path
import re
import sys
MAX_BYTES = 131072
COMPLEX_HEADER = ['freq_hz','open_freq_hz','short_freq_hz','dut_real_ohm','dut_imag_ohm',
'zm_real_ohm','zm_imag_ohm','zo_real_ohm','zo_imag_ohm','zs_real_ohm','zs_imag_ohm',
'u_m_ohm','u_o_ohm','u_s_ohm','compensation_state','dut_plane','open_plane','short_plane','source_kind']
NATIVE_HEADER = ['stage','route_id','cal_plane','cal_event','open_result','short_result',
'freq_hz','primary_mode','secondary_mode','relative_mode','primary_text','primary_unit',
'secondary_text','temperature_c','humidity_percent','source_kind']
STAGES = ['as_found_A','matched_A','stale_B','matched_B','restored_A']
def finite(value):
if isinstance(value,bool):
raise ValueError('Boolean is not a numeric observation')
try:
value = float(value)
except (TypeError,ValueError,OverflowError) as exc:
raise ValueError('Need a finite number') from exc
if not math.isfinite(value) or abs(value)>1e15:
raise ValueError('Nonfinite or unsupported number')
return value
def complex_value(value):
value = complex(value)
finite(value.real); finite(value.imag)
return value
def fixture(frequency, name='A'):
f = finite(frequency)
if not 100<=f<=100000 or name not in ('A','B'):
raise ValueError('Constructed fixture needs A/B and 100..100000 Hz')
r,l,g,c = (2.,2e-6,1e-8,20e-12) if name=='A' else (3.,3e-6,2e-8,35e-12)
w = 2*math.pi*f
return complex(r,w*l),complex(g,w*c)
def forward(zd,zs,yp):
zd,zs,yp = map(complex_value,(zd,zs,yp))
if zd==0:
return zs
denominator=1/zd+yp
if denominator==0:
raise ValueError('Forward parallel network is singular')
return complex_value(zs+1/denominator)
def parallel_c(z,frequency):
"""Nominal parallel capacitance from a constructed complex center only."""
z=complex_value(z);f=finite(frequency)
if z==0 or f<=0:
return None
b=(1/z).imag
return b/(2*math.pi*f) if b>0 else None
def correct(zm,zo,zs,um,uo,us,state='raw',planes=('A','A','A'),
frequencies=(100000,100000,100000),source_kind='constructed'):
if source_kind!='constructed' or state!='raw':
raise ValueError('Only RAW CONSTRUCTED complex data; never native compensated readings')
if len(planes)!=3 or len(set(planes))!=1 or not all(re.fullmatch(r'[A-Za-z0-9_-]{1,40}',p) for p in planes):
raise ValueError('DUT/open/short measurement planes must match')
if len(frequencies)!=3 or any(not 100<=finite(f)<=100000 for f in frequencies) or len(set(map(float,frequencies)))!=1:
raise ValueError('DUT/open/short frequencies must match within 100..100000 Hz')
zm,zo,zs=map(complex_value,(zm,zo,zs))
um,uo,us=map(finite,(um,uo,us))
if min(um,uo,us)<0:
raise ValueError('Complex input disk radii cannot be negative')
result={'status':None,'z_center_ohm':None,'analytic_input_disk_radius_ohm':None,
'physical_uncertainty_verified':False,'floating_roundoff_certified':False}
a,b=zm-zs,zo-zs
ua,ub=um+us,uo+us
if abs(a)<=ua:
result['status']='fixture_subtraction_unresolved';return result
if abs(b)<=ub:
result['status']='open_reference_unresolved';return result
ia,ib=1/a,1/b
y=ia-ib
uy=ua/(abs(a)*(abs(a)-ua))+ub/(abs(b)*(abs(b)-ub))
if abs(y)<=uy:
result['status']='inverse_denominator_unresolved';return result
# Separate finite-precision cancellation screen, not a full roundoff proof.
if abs(y)<=64*sys.float_info.epsilon*(abs(ia)+abs(ib)):
result['status']='floating_cancellation_unresolved';return result
z=1/y
radius=uy/(abs(y)*(abs(y)-uy))
if not all(math.isfinite(x) for x in (z.real,z.imag,radius)):
result['status']='nonfinite_inverse_withheld';return result
result.update(status='bounded_constructed_inverse',z_center_ohm=[z.real,z.imag],
analytic_input_disk_radius_ohm=radius)
return result
def demo_rows(name='A'):
f=100000;zs,yp=fixture(f,name);zo=zs+1/yp
values=[100,150,220,330,470,680,1000,1500,2200,3300,4700,6800,10000,15000,22000,33000,47000,68000,100000]
rows=[]
for pf in values:
zd=complex(.5,-1/(2*math.pi*f*pf*1e-12));zm=forward(zd,zs,yp)
row=dict(zip(COMPLEX_HEADER,[f,f,f,zd.real,zd.imag,zm.real,zm.imag,zo.real,zo.imag,zs.real,zs.imag,
.001,.1,.001,'raw','synthetic-'+name,'synthetic-'+name,'synthetic-'+name,'constructed']))
rows.append(row)
return rows
def analyze_complex(rows):
if not 1<=len(rows)<=64:
raise ValueError('Need 1..64 complete constructed complex rows')
results=[]
for row in rows:
if set(row)!=set(COMPLEX_HEADER):
raise ValueError('Exact complex worksheet fields required')
f,fo,fs=[finite(row[k]) for k in COMPLEX_HEADER[:3]]
def z(prefix):return complex(finite(row[prefix+'_real_ohm']),finite(row[prefix+'_imag_ohm']))
zd,zm,zo,zs=[z(k) for k in ['dut','zm','zo','zs']]
if zd==0:
raise ValueError('Constructed reference DUT cannot be zero')
r=correct(zm,zo,zs,*[finite(row[k]) for k in ['u_m_ohm','u_o_ohm','u_s_ohm']],
state=row['compensation_state'],planes=tuple(row[k] for k in ['dut_plane','open_plane','short_plane']),
frequencies=(f,fo,fs),source_kind=row['source_kind'])
center=complex(*r['z_center_ohm']) if r['z_center_ohm'] is not None else None
raw_cp,open_cp,true_cp=parallel_c(zm,f),parallel_c(zo,f),parallel_c(zd,f)
results.append({'frequency_hz':f,'known_constructed_DUT_ohm':[zd.real,zd.imag],
'raw_parallel_cp_f':raw_cp,'open_parallel_cp_f':open_cp,
'naive_open_cp_subtraction_f':raw_cp-open_cp if raw_cp is not None and open_cp is not None else None,
'known_constructed_parallel_cp_f':true_cp,'inverse':r,
'relative_z_center_error':abs(center-zd)/abs(zd) if center is not None else None})
return {'source_kind':'constructed_complex_model','manufacturer_firmware_reproduced':False,
'physical_measurements':False,'native_DE5000_readings_used':False,'rows':results,
'limits':'Input disks are declared model perturbations. Complex centers and analytic radii use floating arithmetic; no physical accuracy or certified full roundoff bound. Cp subtraction is a comparison method, not the complex inverse.'}
def display(text):
if text in ('OL','----'):
return None
if not isinstance(text,str) or not re.fullmatch(r'-?(?:0|[1-9][0-9]{0,5})(?:\.[0-9]{1,6})?',text):
raise ValueError('Transcribe a plain display decimal, OL or ---- exactly')
return finite(text)
def analyze_native(rows):
if len(rows)!=5 or any(set(r)!=set(NATIVE_HEADER) for r in rows):
raise ValueError('Need all five exact native display records')
observations=[]
expected_routes=['A','A','B','B','A'];expected_planes=['unknown','A','A','B','A']
events=[];cal_ok=True
for i,row in enumerate(rows):
if row['stage']!=STAGES[i] or row['route_id']!=expected_routes[i] or row['cal_plane']!=expected_planes[i]:
raise ValueError('Wrong stage order, route or documented calibration plane')
if row['source_kind']!='reported':
raise ValueError('Native path is MANUAL REPORTED display transcription only')
if (row['freq_hz'],row['primary_mode'],row['secondary_mode'],row['relative_mode'],row['primary_unit'])!=('100000','Cp','D','off','pF'):
raise ValueError('Native worksheet is only 100kHz Cp[pF]/D with REL off')
if not re.fullmatch(r'[A-Za-z0-9_-]{1,32}',row['cal_event']):
raise ValueError('Need a documented calibration-event label')
if row['open_result'] not in ('PASS','FAIL','not_run') or row['short_result'] not in ('PASS','FAIL','not_run'):
raise ValueError('Record actual OPEN/SHORT PASS/FAIL, or not_run')
if i in (0,2) and (row['open_result'],row['short_result'])!=('not_run','not_run'):
raise ValueError('As-found and deliberately stale stages do not run a new CAL')
if i in (1,3,4):cal_ok=cal_ok and row['open_result']=='PASS' and row['short_result']=='PASS'
cp,loss=display(row['primary_text']),display(row['secondary_text'])
if cp is not None and (Fraction(row['primary_text'])*100).denominator!=1:
raise ValueError('This 200-pF display range has 0.01-pF counts')
t,h=finite(row['temperature_c']),finite(row['humidity_percent'])
scope=cp is not None and 0<cp<200 and loss is not None and 0<=loss<=.1 and 18<=t<=28 and 0<=h<70
observations.append({'stage':row['stage'],'route_id':row['route_id'],'cal_plane':row['cal_plane'],
'cal_event':row['cal_event'],'primary_text':row['primary_text'],'secondary_text':row['secondary_text'],
'cp_pF':cp,'D':loss,'selected_scope_conditions':scope,'open_result':row['open_result'],'short_result':row['short_result']})
events.append(row['cal_event'])
if events[0]!='unknown' or events[2]!=events[1] or 'unknown' in [events[1],events[3],events[4]] or len({events[1],events[3],events[4]})!=3:
raise ValueError('Retain A CAL event while stale at B, then record distinct fresh B and restored-A CAL events')
usable=cal_ok and all(x['selected_scope_conditions'] for x in observations)
cp=[x['cp_pF'] for x in observations]
deltas={'A_after_minus_as_found':cp[1]-cp[0],'B_stale_minus_B_recal':cp[2]-cp[3],
'restored_A_minus_matched_A':cp[4]-cp[1]} if usable else None
return {'source_kind':'manual_reported_native_display_log','physical_acquisition_verified':False,
'native_CAL_execution_verified':False,'calibration_events_are_user_declarations':True,
'external_correction_applied':False,'sequence_usable_for_display_comparison':usable,
'display_deltas_pF':deltas,'observations':observations,
'limits':['Differences are displayed-value changes, not proof of improved accuracy or measured parasitics.',
'OL/---- stay nonnumeric. D and environment are scope screens, not a completed uncertainty budget.',
'No native open/short complex values, phase reconstruction, firmware algorithm or instrument protocol is inferred.']}
def read_sheet(path,header):
try:
with Path(path).open('rb') as stream:data=stream.read(MAX_BYTES+1)
if len(data)>MAX_BYTES:raise ValueError('Input exceeds 128 KiB')
parser=csv.reader(io.StringIO(data.decode('utf-8'),newline=''),strict=True)
if next(parser,None)!=header:raise ValueError('Header must exactly match the selected worksheet')
rows=[]
for cells in parser:
if len(cells)!=len(header):raise ValueError('Blank or wrong-width record')
rows.append(dict(zip(header,cells)))
if len(rows)>64:raise ValueError('More than 64 records')
return rows
except (OSError,UnicodeError,csv.Error) as exc:
raise ValueError('Cannot read strict UTF-8 worksheet') from exc
def main(argv=None):
parser=argparse.ArgumentParser(description=__doc__);sub=parser.add_subparsers(dest='command',required=True)
demo=sub.add_parser('demo',help='emit only constructed raw-complex model rows');demo.add_argument('--fixture',choices=['A','B'],default='A')
for name in ['complex','native']:sub.add_parser(name).add_argument('csv_path')
args=parser.parse_args(argv)
try:
if args.command=='demo':
s=io.StringIO(newline='');w=csv.DictWriter(s,fieldnames=COMPLEX_HEADER,lineterminator='\n');w.writeheader();w.writerows(demo_rows(args.fixture));output=s.getvalue()
elif args.command=='complex':output=json.dumps(analyze_complex(read_sheet(args.csv_path,COMPLEX_HEADER)),indent=2,allow_nan=False)+'\n'
else:output=json.dumps(analyze_native(read_sheet(args.csv_path,NATIVE_HEADER)),indent=2,allow_nan=False)+'\n'
except (ValueError,TypeError,OverflowError,ZeroDivisionError) as exc:
print('Refused: '+str(exc),file=sys.stderr);return 2
print(output,end='');return 0
if __name__=='__main__':raise SystemExit(main())
The supplied test suite has 22 host test methods. It exercises forward/inverse recovery across frequencies and capacitances, a counterexample to naive Cp subtraction, 125 independent input-perturbation combinations against the analytic disk bound, unresolved inverse cases, double-correction and plane/frequency refusals, native OL and failed-CAL handling, negative D and environment screens, exact display quantization, record identities and real command-line malformed-input behavior. The native numbers inside these tests are invented test fixtures, not measured readings. Host tests validate program behavior; they do not perform CAL, establish a physical error budget or test the meter.
"""Constructed host tests only; no DE-5000 or actual readings."""
from pathlib import Path
import importlib.util,sys,unittest,math,copy,csv,io,json,subprocess,tempfile
ROOT=Path(__file__).resolve().parents[1]
spec=importlib.util.spec_from_file_location('fixture_correction',ROOT/'code/fixture_correction.py');m=importlib.util.module_from_spec(spec);spec.loader.exec_module(m)
def native_fixture():
rows=[]
profiles=[('as_found_A','A','unknown','unknown','not_run','not_run','118.00'),
('matched_A','A','A','A1','PASS','PASS','100.00'),
('stale_B','B','A','A1','not_run','not_run','110.00'),
('matched_B','B','B','B1','PASS','PASS','100.10'),
('restored_A','A','A','A2','PASS','PASS','100.00')]
for stage,route,plane,event,op,sh,cp in profiles:
rows.append(dict(zip(m.NATIVE_HEADER,[stage,route,plane,event,op,sh,'100000','Cp','D','off',cp,'pF','0.001','23','45','reported'])))
return rows
def csv_bytes(header,rows):
s=io.StringIO(newline='');w=csv.DictWriter(s,fieldnames=header,lineterminator='\n');w.writeheader();w.writerows(rows);return s.getvalue().encode()
class ComplexModel(unittest.TestCase):
def test_forward_and_inverse_across_frequency_and_capacitance(self):
for f in [100,1000,10000,100000]:
for c in [1e-10,1e-9,1e-8,1e-7]:
zs,yp=m.fixture(f,'A');zd=complex(.5,-1/(2*math.pi*f*c));zm=m.forward(zd,zs,yp);zo=zs+1/yp
r=m.correct(zm,zo,zs,.001,.1,.001)
self.assertEqual(r['status'],'bounded_constructed_inverse')
self.assertLess(abs(complex(*r['z_center_ohm'])-zd),1e-6)
def test_naive_capacitance_subtraction_is_not_complex_inverse(self):
f=100000.;zs,yp=m.fixture(f,'A');zd=complex(.5,-1/(2*math.pi*f*1e-7));zm=m.forward(zd,zs,yp);zo=zs+1/yp
naive=m.parallel_c(zm,f)-m.parallel_c(zo,f)
self.assertGreater(abs(naive/m.parallel_c(zd,f)-1),.01)
def test_radius_encloses_independent_small_input_perturbations(self):
f=100000.;zs,yp=m.fixture(f,'A');zd=complex(.5,-100);zm=m.forward(zd,zs,yp);zo=zs+1/yp
r=m.correct(zm,zo,zs,.02,.1,.01);center=complex(*r['z_center_ohm']);radius=r['analytic_input_disk_radius_ohm']
for dm in [0,.02,-.02,.02j,-.02j]:
for do in [0,.1,-.1,.1j,-.1j]:
for ds in [0,.01,-.01,.01j,-.01j]:
a=zm+dm-zs-ds;b=zo+do-zs-ds;actual=1/(1/a-1/b)
self.assertLessEqual(abs(actual-center),radius*(1+1e-10))
def test_zero_or_uncertain_fixture_subtraction_withheld(self):
for zm in [complex(2,1),complex(2.0001,1)]:
r=m.correct(zm,100+1j,2+1j,.001,.1,.001)
self.assertIsNone(r['z_center_ohm'])
def test_near_open_inverse_refuses_a_finite_estimate(self):
zs,yp=m.fixture(100000,'A');zo=zs+1/yp;r=m.correct(zo,zo,zs,.001,.1,.001)
self.assertEqual(r['status'],'inverse_denominator_unresolved');self.assertIsNone(r['z_center_ohm'])
def test_double_correction_and_plane_or_frequency_mismatch_refused(self):
for kwargs in [{'state':'native_compensated'},{'planes':('B','A','A')},{'frequencies':(100000,10000,100000)},{'source_kind':'reported'}]:
with self.assertRaises(ValueError):m.correct(20-100j,1-10000j,1+1j,.001,.1,.001,**kwargs)
def test_invalid_complex_or_radius_refused(self):
for kw in [{'zm':complex(float('nan'),0)},{'um':-1},{'uo':float('inf')}]:
args=dict(zm=20-100j,zo=1-10000j,zs=1+1j,um=.001,uo=.1,us=.001);args.update(kw)
with self.assertRaises(ValueError):m.correct(**args)
def test_demo_all_rows_recover_known_constructed_device(self):
rows=m.demo_rows();self.assertEqual(len(rows),19);r=m.analyze_complex(rows)
self.assertTrue(all(x['inverse']['status']=='bounded_constructed_inverse' for x in r['rows']))
self.assertTrue(all(x['relative_z_center_error']<1e-10 for x in r['rows']))
def test_noncapacitive_complex_conversion_is_not_fake_capacitance(self):
self.assertIsNone(m.parallel_c(10+10j,1000))
class NativeRecords(unittest.TestCase):
def test_manual_sequence_changes_are_not_metrology_or_acquisition(self):
r=m.analyze_native(native_fixture());self.assertTrue(r['sequence_usable_for_display_comparison']);self.assertFalse(r['physical_acquisition_verified']);self.assertTrue(r['external_correction_applied'] is False)
self.assertEqual(r['display_deltas_pF']['A_after_minus_as_found'],-18)
def test_OL_stays_nonnumeric_and_withholds_comparison(self):
rows=native_fixture();rows[0]['primary_text']='OL';r=m.analyze_native(rows)
self.assertIsNone(r['observations'][0]['cp_pF']);self.assertFalse(r['sequence_usable_for_display_comparison']);self.assertIsNone(r['display_deltas_pF'])
def test_secondary_OL_is_not_zero_loss(self):
rows=native_fixture();rows[1]['secondary_text']='OL';r=m.analyze_native(rows)
self.assertIsNone(r['observations'][1]['D']);self.assertIsNone(r['display_deltas_pF'])
def test_failed_CAL_retained_but_comparison_withheld(self):
rows=native_fixture();rows[1]['open_result']='FAIL';r=m.analyze_native(rows)
self.assertFalse(r['sequence_usable_for_display_comparison']);self.assertIsNone(r['display_deltas_pF'])
def test_negative_D_or_wrong_conditions_withholds_without_relabel(self):
for field,value in [('secondary_text','-0.001'),('temperature_c','35'),('humidity_percent','80')]:
rows=native_fixture();rows[1][field]=value;r=m.analyze_native(rows);self.assertFalse(r['sequence_usable_for_display_comparison'])
def test_wrong_mode_frequency_relative_or_unit_refused(self):
for field,value in [('primary_mode','Cs'),('secondary_mode','phase'),('freq_hz','1000'),('relative_mode','on'),('primary_unit','nF')]:
rows=native_fixture();rows[1][field]=value
with self.assertRaises(ValueError):m.analyze_native(rows)
def test_stale_plane_and_new_recalibration_events_required(self):
for field,value in [('cal_plane','B'),('cal_event','unknown')]:
rows=native_fixture();rows[2][field]=value
with self.assertRaises(ValueError):m.analyze_native(rows)
rows=native_fixture();rows[4]['cal_event']='A1'
with self.assertRaises(ValueError):m.analyze_native(rows)
def test_display_quantum_and_nonfinite_refused(self):
for field,value in [('primary_text','100.001'),('primary_text','nan'),('secondary_text','inf')]:
rows=native_fixture();rows[1][field]=value
with self.assertRaises(ValueError):m.analyze_native(rows)
def test_complete_order_and_source_kind_required(self):
rows=native_fixture();rows.reverse()
with self.assertRaises(ValueError):m.analyze_native(rows)
rows=native_fixture();rows[0]['source_kind']='constructed'
with self.assertRaises(ValueError):m.analyze_native(rows)
class FileAndCLI(unittest.TestCase):
def run_cli(self,*args):return subprocess.run([sys.executable,str(ROOT/'code/fixture_correction.py'),*args],capture_output=True)
def test_actual_demo_and_complex_cli(self):
r=self.run_cli('demo');self.assertEqual(r.returncode,0,r.stderr)
with tempfile.TemporaryDirectory() as td:
p=Path(td)/'x.csv';p.write_bytes(r.stdout);out=self.run_cli('complex',str(p));self.assertEqual(out.returncode,0,out.stderr);self.assertEqual(len(json.loads(out.stdout)['rows']),19)
def test_actual_native_OL_cli_valid_but_no_finite_substitute(self):
rows=native_fixture();rows[0]['primary_text']='OL'
with tempfile.TemporaryDirectory() as td:
p=Path(td)/'x.csv';p.write_bytes(csv_bytes(m.NATIVE_HEADER,rows));r=self.run_cli('native',str(p));self.assertEqual(r.returncode,0,r.stderr);self.assertIsNone(json.loads(r.stdout)['display_deltas_pF'])
def test_actual_malformed_inputs_refused_cleanly(self):
bad=[b'"stage,route\n',b'\xff',b'x'*(m.MAX_BYTES+1),b'wrong,header\n',csv_bytes(m.NATIVE_HEADER,native_fixture())+b'\n']
with tempfile.TemporaryDirectory() as td:
p=Path(td)/'x.csv'
for data in bad:
p.write_bytes(data);r=self.run_cli('native',str(p));self.assertEqual(r.returncode,2);self.assertEqual(r.stdout,b'');self.assertNotIn(b'Traceback',r.stderr)
def test_actual_missing_file_refused_cleanly(self):
r=self.run_cli('complex',str(ROOT/'no-such-file.csv'));self.assertEqual(r.returncode,2);self.assertEqual(r.stdout,b'')
if __name__=='__main__':unittest.main()
Run constructed-near-open.csv. Its DUT is a finite 10−18 F model capacitor with 0.5 Ω series loss at 100 kHz, while the same 20 pF shunt dominates the fixture. It is not a proposed physical component or an OL transcription. Why should the code decline a finite inverse even though the input centers are finite? Then try constructed-stale-plane.csv, which deliberately combines a B-plane DUT model with A-plane calibration references.
For the nearly open finite DUT, the two reciprocal terms almost cancel. With the stated nonzero input disks, their difference disk contains zero. The result is inverse_denominator_unresolved with a null center and radius; printing a huge finite corrected value would conceal the unresolved denominator. The supplied bounds do not identify a finite inverse; this is an identifiability limit, not an overload reading. The stale-plane file instead fails an explicit precondition and exits 2: the A and B declarations differ. Relabeling it A does not repair the physical or model mismatch. Restore a common fixture and acquire or construct consistent references. Native matched readings remain on the separate manual log path and are never passed through this inverse.
Repeat the five-stage physical sequence without changing C1. Compare repeated displays, photographs and restoration results before deciding that lead routing produced a resolvable effect. If it does not, record that result rather than substituting the constructed graph. For the representation question, read why series and parallel capacitance can differ. For an intentionally added loss element, see the capacitor resistance experiment. This lesson instead concerns the reference plane and whether a correction is valid for its fixture.
Prepared experiment and constructed model. Physical measurements, native calibration execution, instrument transport and target execution have not been performed for this package.