A Smaller Diode Step Does Not Automatically Give a Better Slope
A silicon diode is a two-terminal component that conducts more readily in one direction. Hold it near 0.50 milliamperes (mA), then compare two pairs of nearby current settings. A milliampere is one-thousandth of an ampere, the unit of electric current. The wider pair is 0.40 and 0.60 mA; the narrower pair is 0.49 and 0.51 mA. Return to the center between endpoint readings.
For each pair, divide the measured voltage change by the measured current change. This gives a finite chord, the average slope between two points on a voltage–current curve. A nonlinear curve has a changing slope. A narrower bracket covers less of it, but it also produces a smaller voltage difference. Two perfectly ordinary meter errors can then hide that difference. The experiment asks what your recorded intervals resolve; neither bracket is required to pass or fail.
The observations are settled direct current (DC), meaning steady voltage and current at each setting. Impedance describes opposition to an alternating signal; this is a DC experiment. An infinitesimal derivative is the limiting slope at one point. Our finite chord is not that derivative and does not establish an exactly fixed junction temperature: the junction is the diode’s internal semiconductor boundary. The article provides a design and software tested on a computer. No physical measurements or firmware build are claimed.
Use the two independent meter returns
Use one Vishay 1N4148-TAP diode. Its black band identifies the cathode; the other lead is the anode. The current manufacturer document lists the axial DO-35, also called DO-204AH, package and this exact ordering code. Its 1 V forward-voltage maximum is specified at 10 mA. It does not guarantee a voltage, slope or bracket classification at the smaller currents here.
An ohm (Ω) is the unit of resistance; a kilohm (kΩ) is 1000 Ω and a megohm (MΩ) one million Ω. A volt (V) measures voltage. Use Vishay MRS25 MRS25000C3901FCT00, 3.90 kΩ ±1%, as R1. The control load is MRS25000C1001FCT00, 1.00 kΩ ±1%. A ±1% tolerance describes the permitted resistance deviation from nominal under the stated reference conditions. A watt is the unit of power, energy transferred per second. These parts have a 0.6 watt rating at 70°C under their datasheet conditions; the fixture runs them at only a few milliwatts, where a milliwatt (mW) is one-thousandth of a watt.
Use RIGOL DP832A channel 1 (CH1), with other outputs off. With output disabled, start at zero, set a 10 mA current limit and 5.0 V overvoltage protection (OVP). Stay at or below a 5.0 V programmed voltage. These settings are backups. The source setting, current limit and front-panel current display do not replace the two measured voltage drops.
Use two separate battery-operated Fluke 87V MAX digital multimeters (DMMs), instruments that display numerical voltage readings. Keep both in normal 6.000 V DC mode, using their voltage inputs. The VΩ socket accepts voltage/resistance measurements; COM is that meter's common-return socket. Here the two COM sockets connect to different circuit nodes and must remain electrically independent.
- Connect source positive, S+, through R1 to node A. Connect the diode anode to A and its banded cathode to source negative, N.
- Meter M1 measures R1: red VΩ lead at S+, black COM lead at A. Call its reading VR.
- Meter M2 measures the load: red VΩ lead at A, black COM lead at N. Call its reading VF. CSV means comma-separated values, a plain-text worksheet. It keeps this column name for the resistor control too, where it means the control-load voltage.
Keep the same meter on each pair of sense points throughout. A common grounded oscilloscope return cannot replace these two floating battery-meter connections: joining A to N would bypass the diode. Use voltage sockets throughout; do not connect a current input across the source.

Infer the load current, including nominal meter loading
M1 draws a small current across R1 that also enters node A. M2 draws current from A to N without passing through the diode. With RM1 and RM2 representing the two input resistances, the load-current estimate is:
I = V_R × (1/R1 + 1/R_M1) − V_F/R_M2
Use the nominal 10 MΩ input model for both meters. For example, constructed readings VR = 1.950 V and VF = 0.600 V give approximately 500.135 microamperes (µA), where a microampere is one-millionth of an ampere. Simply dividing 1.950 V by 3900 Ω gives 500 µA; the difference is the nominal loading correction.
The manual describes input resistance as nominal. It does not certify a minimum resistance or an exact correction. The analyzer therefore adds a chosen ±0.5 µA loading-model allowance at each point. It also uses R1 = 3900 ±42.9 Ω and the control = 1000 ±11 Ω: a 1.1% interval incorporating the 1% part tolerance and a chosen 0.1% fixture/thermal allowance. Those extra allowances are engineering assumptions, not manufacturer-certified bounds on every meter input or mounting condition. The intervals are conditional on them being appropriate to the actual setup.
The first supplied analyzer keeps these fixed reviewed assumptions. A separately measured resistor value needs a documented measurement and temperature uncertainty before changing that model. Do not reduce an allowance merely to obtain a preferred result.
Keep the normal-range error floor
On the normal 6.000 V DC range, each display count is 1 millivolt (mV), or one-thousandth of a volt. The stated voltage error is ±(0.05% of reading + 1 count). At 0.600 V, this is ±1.30 mV. The detailed accuracy applies within two years after calibration, at 18–28 degrees Celsius (°C) and the manual's applicable humidity and electromagnetic conditions, including 0–95% relative humidity (RH). RH describes the air's moisture relative to saturation. Electromagnetic compatibility (EMC) conditions concern interference around the instrument; the software does not verify them.
High-resolution extra digits do not divide this absolute count contribution. The manual multiplies count terms when using that mode. The separate 600 mV range has a different accuracy specification and may overrange a silicon diode's forward voltage. Keep the normal 6 V range for this comparison.
For an observed voltage v, form the interval v ± e(v), with e(v) = 0.0005 × |v| + 0.001 V. An interval has lower and upper endpoints under the stated assumptions; it is not a probability or a confidence percentage. Evaluate the current formula at every combination of the two voltage endpoints and R1 endpoints, then widen by the chosen ±0.5 µA loading allowance. Keep errors at different observations independent for this conservative calculation. A common physical resistor can create correlations, but this analyzer does not assume cancellation.
Acquire the exact 36 rows
Keep the same diode mounting, sense points, lead placement and airflow. Do not deliberately heat the fixture. At each setting wait at least 30 seconds, then compare a second voltage pair five seconds later. If either reading changes by more than its single-reading error allowance, wait and repeat. Enter the final settled pair and retain the two-pair check in bench notes. The 30-second wait and manual five-second check are acquisition requirements, not software proof of settling.
Adjust source voltage using the corrected measured current. The analyzer's nominal-current matching screen is ±0.5% of each target. This matches experiment points; it does not establish 0.5% absolute current accuracy. Retain every current interval. If the source stays in current limit, polarity is unexpected, a meter overloads or readings remain unstable, stop, disable the output and inspect the wiring. Do not invent numeric values to complete a stopped sheet.
| Diode step, in order | C0 | WL | C1 | WH | C2 | NL | C3 | NH | C4 |
|---|---|---|---|---|---|---|---|---|---|
| Target µA | 500 | 400 | 500 | 600 | 500 | 490 | 500 | 510 | 500 |
Repeat this entire nine-step sequence as cycles 1, 2 and 3, making 27 diode observations. C0–C4 are separate center returns, not duplicated row names. Pair WL with WH and NL with NH within the same cycle. Do not pair across cycles or average the observations before constructing their bounds.
After all diode cycles, disable output and replace D1 with the 1.00 kΩ control at the same A/N sense points. Acquire L = 400 µA, C = 500 µA and H = 600 µA in that order, then repeat as control cycles 2 and 3. These nine control observations complete the 36-row sheet. Never connect diode and control in parallel.
The upper voltage bounds must add to no more than 5.05 V. With R1 at its 3857.1 Ω lower model bound, a shorted load would draw at most about 1.31 mA and R1 would dissipate 6.62 mW at that actual source bound. A passive diode's bound V²/(4R) is about 1.66 mW. These are steady-state fixture calculations, not certification of fast transients or arbitrary source faults. Handle the load only with output off.
Compare signed differences before dividing
The high and low observations supply voltage and current intervals. Subtract their endpoints conservatively:
ΔV = [V_high,low − V_low,high, V_high,high − V_low,low] ΔI = [I_high,low − I_low,high, I_high,high − I_low,low]
Here Δ means a difference, not a new meter range. If the lower ΔI endpoint is not positive, the quotient is withheld. Otherwise calculate every ΔV/ΔI endpoint combination and retain the smallest and largest. Keep a negative lower bound. Taking an absolute value, clipping it to zero or replacing actual currents with target labels would conceal the unresolved comparison.
| Constructed, quantized example | Wide bracket | Narrow bracket |
|---|---|---|
| Recorded endpoint VF | 0.594 / 0.605 V | 0.599 / 0.601 V |
| ΔV interval | 8.4005 to 13.5995 mV | −0.6000 to 4.6000 mV |
| ΔI interval | 186.834 to 212.858 µA | 7.001 to 33.019 µA |
| Finite-chord interval | 39.47 to 72.79 Ω | −85.70 to 657.04 Ω |
The supplied constructed example resolves a positive wide chord while the narrow voltage difference includes zero. The negative lower bound does not establish negative diode differential resistance. It says that the stated errors can account for an apparent reversal. A real diode need not reproduce these voltages, slopes or classifications.
The narrower bracket does not automatically provide a better derivative estimate: its smaller voltage difference can be overwhelmed by fixed endpoint errors. The wider chord averages a larger nonlinear interval. Both limitations matter. The center's V/I ratio, about 1.2 kΩ in the example, is contextual; it is a different quantity and is not the lesson's acceptance target. No nVT/I or ideality-factor model is used to require a result.
Read controls and resolution separately
The report retains all raw readings, current intervals and failure reasons. Every point must fit the declared meter range, have positive lower voltage/current bounds, meet the source-voltage bound and satisfy nominal current matching. All 15 diode-center current intervals must share an overlap. The analyzer also reports each cycle's five-center overlap. Overlap supports consistency; it does not prove identical actual currents.
For center voltage drift, use the full range of all 15 center VF readings plus the two extreme readings' voltage-error allowances. This must fit a chosen 5 mV screen. The global check prevents slow changes between otherwise quiet cycles from being hidden. Apply the same current-overlap and voltage-range checks separately to the three control C rows. Do not mix their voltages with diode voltages.
Every control V/I interval and each control L/H chord interval must overlap the chosen [989, 1011] Ω control interval. This tests consistency of the measurement/model chain at low power. Control-interval overlap is not certification of every instrument, part or contact. A failure withholds interpretation rather than adjusting the error model to make the data pass.
Center returns detect some drift, but cannot establish equal endpoint junction temperatures, eliminate equilibrium self-heating, or rule out brief disturbances. Settled thermal differences, ambient changes, contacts and finite-width curvature remain limitations of the operational DC chord. The software does not turn these observations into an isothermal or infinitesimal resistance.
Each chord reports arithmetic_positive, interpretation_supported and positive_slope_resolved, with the conditional model beside the interpretation. Failed controls can leave arithmetic intervals visible while withholding a supported positive-slope claim. The overall pattern is unsupported, neither, wide_only, narrow_only or both. In the summary, a width is supported only if all three cycles resolve its positive chord. Per-cycle results remain visible. Summary bounds use the hull, the full span enclosing the three intervals; repetition never divides fixed errors by the square root of sample count.
Run the complete analyzer
Download the standalone experiment ZIP. Extract it into a new directory. It contains the complete Python 3 standard-library analyzer, generator, meaningful tests, blank physical CSV, labelled constructed CSV, readable instructions and original SVG/PNG. The exact header is device,cycle,step,target_ua,series_v,forward_v. The blank file has fixed keys and empty measured cells.
python3 -m unittest -v test_diode_brackets.py python3 diode_brackets.py constructed-example.csv --kind constructed python3 diode_brackets.py physical-blank.csv --kind observed python3 make_constructed.py new-constructed-directory
The physical-blank command must fail until observations are entered. The generator refuses a populated destination. It makes explicitly constructed, 1 mV-quantized values using an illustrative curve; they are not manufacturer tolerances or bench readings. Keep them separate from the physical sheet. The --kind declaration is mandatory, but cannot prove physical acquisition.
The command-line interface (CLI), the text command used in a terminal, writes JavaScript Object Notation (JSON), a structured report. Exit 0 means a valid report, which can remain unsupported or unresolved. Check controls_passed, the conditional assumptions and each chord's flags. Wrong-polarity or out-of-range finite observations produce a valid unsupported report; the out-of-range reading’s voltage interval, derived current and dependent quotient intervals are null because the declared meter model is inapplicable. Valid companion-voltage or voltage-difference diagnostics may remain.
UTF-8 (Unicode Transformation Format, 8-bit) is the plain-text byte format used here. Standard error (stderr) is the terminal’s error-output stream. Exit 2 means malformed or incomplete input, with stderr text and no JSON: duplicated/reordered headers, invalid UTF-8 text encoding, malformed quoting, blank/nonfinite numeric cells, wrong acquisition keys/order/targets, missing/extra rows or fields, or more than 65536 bytes. The parser checks the physical header before dictionaries can collapse duplicate columns. Entered OL is not a numeric voltage. Do not repair order, fill empty readings with zero or hide failed controls. The program contains no instrument/network control or firmware.
Complete diode_brackets.py
#!/usr/bin/env python3
"""Finite settled-DC diode chords, using a fixed conditional engineering model.
Python 3 standard library; no instrument or network control.
Exit 0: a valid report, possibly unsupported or unresolved.
Exit 2: malformed/incomplete input, stderr only and no JSON.
"""
import argparse
import csv
import io
import itertools
import json
import math
import sys
from pathlib import Path
FIELDS=('device','cycle','step','target_ua','series_v','forward_v')
DIODE_SEQUENCE=(('C0',500),('WL',400),('C1',500),('WH',600),('C2',500),('NL',490),('C3',500),('NH',510),('C4',500))
CONTROL_SEQUENCE=(('L',400),('C',500),('H',600))
SERIES_R=3900.0
SERIES_ERROR=42.9
CONTROL_R=1000.0
CONTROL_ERROR=11.0
METER_INPUT=10000000.0 #Nominal, not a guaranteed minimum resistance.
LOADING_ALLOWANCE=.5e-6 #Chosen engineering allowance, not a maker specification.
EPS_V=1e-12 #Numerical comparison allowance, one picovolt.
EPS_A=1e-15 #Numerical comparison allowance, one femtoampere.
EPS_R=1e-9
CONDITION_SCOPE=('Conditional on the declared meter conditions and chosen R/loading '
'engineering assumptions; not certified thermal/input-conductance coverage.')
def number(value):
if isinstance(value,bool):
raise ValueError('boolean is not a measured number')
try:
x=float(value)
except (TypeError,ValueError,OverflowError):
raise ValueError('blank or nonnumeric cell')
if not math.isfinite(x):
raise ValueError('nonfinite numeric cell')
return x
def expected_rows():
return tuple((device,cycle,step,target)
for device,sequence in [('diode',DIODE_SEQUENCE),('control',CONTROL_SEQUENCE)]
for cycle in (1,2,3) for step,target in sequence)
def normalize_rows(rows):
if not isinstance(rows,(list,tuple)) or len(rows)!=36:
raise ValueError('exactly 36 acquisition rows required')
normalized=[]
for ordinal,(row,expected) in enumerate(zip(rows,expected_rows()),1):
if not isinstance(row,dict) or set(row)!=set(FIELDS):
raise ValueError('row %d has the wrong fields'%ordinal)
device,cycle,step,target=expected
if (row['device'],str(row['cycle']),row['step'])!=(device,str(cycle),step):
raise ValueError('row %d has a wrong/duplicate/out-of-order acquisition key'%ordinal)
if number(row['target_ua'])!=target:
raise ValueError('row %d has the wrong target label'%ordinal)
normalized.append({'device':device,'cycle':cycle,'step':step,'target_ua':target,
'series_v':number(row['series_v']),'forward_v':number(row['forward_v'])})
return normalized
def read_rows(path):
try:
with Path(path).open('rb') as f:
data=f.read(65537)
if len(data)>65536:
raise ValueError('worksheet exceeds 65536 bytes')
parser=csv.reader(io.StringIO(data.decode('utf-8'),newline=''),strict=True)
header=next(parser,None)
#Check the physical header before a dictionary can collapse duplicates.
if header!=list(FIELDS) or len(header)!=len(set(header)):
raise ValueError('need the exact unique ordered CSV header')
rows=[]
for cells in parser:
if len(cells)!=len(FIELDS):
raise ValueError('wrong field count or blank physical record')
rows.append(dict(zip(FIELDS,cells)))
if len(rows)>36:
raise ValueError('worksheet has more than 36 rows')
return normalize_rows(rows)
except (OSError,UnicodeError,csv.Error) as exc:
raise ValueError('cannot read strict UTF-8 CSV: '+str(exc))
def meter_interval(v):
v=number(v)
if abs(v)>6.0+EPS_V:
return None
error=.0005*abs(v)+.001
return [v-error,v+error]
def point_interval(vr,vf):
vr=number(vr);vf=number(vf)
sr=meter_interval(vr);fr=meter_interval(vf)
result={'series_v':vr,'forward_v':vf,'series_interval_v':sr,'forward_interval_v':fr,
'nominal_current_a':None,'current_interval_a':None}
if sr is None or fr is None:
result['fixture_screens']={'meter_range':False,'positive_voltage_bounds':False,
'positive_current_bound':False,'source_voltage_bound':False}
else:
currents=[a*(1/r+1/METER_INPUT)-b/METER_INPUT
for a,r,b in itertools.product(sr,[SERIES_R-SERIES_ERROR,SERIES_R+SERIES_ERROR],fr)]
current=[min(currents)-LOADING_ALLOWANCE,max(currents)+LOADING_ALLOWANCE]
result.update(nominal_current_a=vr*(1/SERIES_R+1/METER_INPUT)-vf/METER_INPUT,
current_interval_a=current)
result['fixture_screens']={'meter_range':True,'positive_voltage_bounds':min(sr[0],fr[0])>EPS_V,
'positive_current_bound':current[0]>EPS_A,
'source_voltage_bound':sr[1]+fr[1]<=5.05+EPS_V}
result['fixture_screens_passed']=all(result['fixture_screens'].values())
result['failed_fixture_screens']=[k for k,v in result['fixture_screens'].items() if not v]
return result
def quotient_interval(numerator,denominator):
if numerator is None or denominator is None or denominator[0]<=EPS_A:
return None
corners=[a/b for a,b in itertools.product(numerator,denominator)]
return [min(corners),max(corners)]
def chord_interval(low,high):
dv=di=None
if low.get('forward_interval_v') is not None and high.get('forward_interval_v') is not None:
dv=[high['forward_interval_v'][0]-low['forward_interval_v'][1],
high['forward_interval_v'][1]-low['forward_interval_v'][0]]
if low.get('current_interval_a') is not None and high.get('current_interval_a') is not None:
di=[high['current_interval_a'][0]-low['current_interval_a'][1],
high['current_interval_a'][1]-low['current_interval_a'][0]]
bounds=quotient_interval(dv,di)
positive=bounds is not None and dv[0]>EPS_V and di[0]>EPS_A
reason=('point interval unavailable' if dv is None or di is None else
'positive current difference unresolved' if di[0]<=EPS_A else
'positive voltage difference unresolved' if dv[0]<=EPS_V else 'positive arithmetic chord')
return {'delta_v_interval':dv,'delta_i_interval_a':di,'interval_ohm':bounds,
'arithmetic_positive':bool(positive),'arithmetic_reason':reason}
def center_checks(points):
available=all(p['current_interval_a'] is not None and p['forward_interval_v'] is not None for p in points)
if not available:
return {'current_overlap':False,'intersection_lower_a':None,'intersection_upper_a':None,
'voltage_range_plus_errors_v':None,'voltage_stable':False}
lower=max(p['current_interval_a'][0] for p in points)
upper=min(p['current_interval_a'][1] for p in points)
low=min(points,key=lambda p:p['forward_v']);high=max(points,key=lambda p:p['forward_v'])
metric=(high['forward_v']-low['forward_v']+
high['forward_interval_v'][1]-high['forward_v']+
low['forward_v']-low['forward_interval_v'][0])
return {'current_overlap':lower<=upper+EPS_A,'intersection_lower_a':lower,'intersection_upper_a':upper,
'voltage_range_plus_errors_v':metric,'voltage_stable':metric<=.005+EPS_V}
def overlaps_control(interval):
return interval is not None and max(interval[0],CONTROL_R-CONTROL_ERROR)<=min(interval[1],CONTROL_R+CONTROL_ERROR)+EPS_R
def assess_controls(points):
lookup={(p['device'],p['cycle'],p['step']):p for p in points}
diode_centers=[p for p in points if p['device']=='diode' and p['step'].startswith('C')]
control_centers=[p for p in points if p['device']=='control' and p['step']=='C']
dc=center_checks(diode_centers);cc=center_checks(control_centers)
local=[dict(cycle=cycle,**center_checks([p for p in diode_centers if p['cycle']==cycle])) for cycle in (1,2,3)]
control_points=[];control_chords=[]
for p in points:
if p['device']=='control':
ratio=quotient_interval(p['forward_interval_v'],p['current_interval_a'])
control_points.append({'cycle':p['cycle'],'step':p['step'],'V_over_I_interval_ohm':ratio,
'overlaps_control':overlaps_control(ratio)})
for cycle in (1,2,3):
c=chord_interval(lookup[('control',cycle,'L')],lookup[('control',cycle,'H')])
control_chords.append(dict(cycle=cycle,overlaps_control=overlaps_control(c['interval_ohm']),**c))
screens={'point_fixture_screens':all(p['fixture_screens_passed'] for p in points),
'nominal_target_matching':all(p['nominal_target_matched'] for p in points),
'diode_center_current_overlap':dc['current_overlap'],'diode_center_voltage_stable':dc['voltage_stable'],
'control_center_current_overlap':cc['current_overlap'],'control_center_voltage_stable':cc['voltage_stable'],
'control_ratios_consistent':all(p['overlaps_control'] for p in control_points),
'control_chords_consistent':all(c['overlaps_control'] for c in control_chords)}
return {'screens':screens,'passed':all(screens.values()),'failed_screens':[k for k,v in screens.items() if not v],
'diode_global_centers':dc,'diode_per_cycle_centers':local,'control_centers':cc,
'control_points':control_points,'control_chords':control_chords}
def pattern(wide,narrow,supported):
if not supported:return 'unsupported'
if wide and narrow:return 'both'
if wide:return 'wide_only'
if narrow:return 'narrow_only'
return 'neither'
def hull(intervals):
if any(x is None for x in intervals):return None
return [min(x[0] for x in intervals),max(x[1] for x in intervals)]
def analyze_rows(rows,kind):
if kind not in ('observed','constructed'):
raise ValueError('kind must be observed or constructed')
rows=normalize_rows(rows);points=[]
for row in rows:
p=point_interval(row['series_v'],row['forward_v']);p.update(row)
target=row['target_ua']*1e-6;nominal=p['nominal_current_a']
p['nominal_target_matched']=nominal is not None and abs(nominal-target)<=.005*target+EPS_A
points.append(p)
controls=assess_controls(points);supported=controls['passed']
lookup={(p['device'],p['cycle'],p['step']):p for p in points};cycles=[]
for cycle in (1,2,3):
c={'cycle':cycle}
for width,lo,hi in [('wide','WL','WH'),('narrow','NL','NH')]:
chord=chord_interval(lookup[('diode',cycle,lo)],lookup[('diode',cycle,hi)])
chord.update(interpretation_supported=supported,conditional_model=CONDITION_SCOPE,
positive_slope_resolved=supported and chord['arithmetic_positive'])
c[width]=chord
c['resolution_pattern']=pattern(c['wide']['positive_slope_resolved'],c['narrow']['positive_slope_resolved'],supported)
cycles.append(c)
summary={}
for width in ('wide','narrow'):
summary[width]={'hull_ohm':hull([c[width]['interval_ohm'] for c in cycles]),
'all_three_positive_slopes_resolved':all(c[width]['positive_slope_resolved'] for c in cycles)}
origin=[quotient_interval(p['forward_interval_v'],p['current_interval_a']) for p in points
if p['device']=='diode' and p['step'].startswith('C')]
model={'qualification':CONDITION_SCOPE,'series_R_ohm':SERIES_R,'series_R_error_ohm':SERIES_ERROR,
'control_R_ohm':CONTROL_R,'control_R_error_ohm':CONTROL_ERROR,'nominal_meter_input_ohm':METER_INPUT,
'chosen_loading_allowance_a':LOADING_ALLOWANCE,'loading_and_extra_R_allowance_not_manufacturer_guarantees':True,
'meter_error_v':'0.0005*abs(reading)+0.001','meter_conditions':'87V MAX normal 6 V; within 2 years after calibration; 18–28°C; 0–95% RH; applicable manual EMC conditions',
'manual_acquisition_conditions_verified_by_software':False,'fixed_errors_divided_by_sqrt_n':False,
'numerical_comparison_allowance_v':EPS_V,'numerical_comparison_allowance_a':EPS_A}
return {'schema':'trickycircuit-diode-brackets-1','valid_report':True,'measurement_kind_declared':kind,
'physical_acquisition_verified':False,'interpretation_supported':supported,'conditional_model':model,
'controls_passed':supported,'controls':controls,'points':points,'cycles':cycles,'summary':summary,
'resolution_pattern':pattern(summary['wide']['all_three_positive_slopes_resolved'],summary['narrow']['all_three_positive_slopes_resolved'],supported),
'summary_pattern_scope':'Each width is positive only if all three cycles support it. No expected pattern is required.',
'center_V_over_I_context_hull_ohm':hull(origin),
'claim_limits':['Finite settled-DC chords only; no AC impedance or isothermal derivative.',
'Center overlap and return screens do not prove identical currents or junction temperatures.',
'A signed interval spanning zero does not establish negative differential resistance.',
'Control overlap is consistency, not certification of every part, contact or instrument.']}
def main(argv=None):
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument('worksheet');parser.add_argument('--kind',required=True,choices=['observed','constructed'])
args=parser.parse_args(argv)
try:
report=analyze_rows(read_rows(args.worksheet),args.kind)
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
"""Generate labelled constructed values, never physical observations. No overwrite."""
import csv
import math
import sys
from pathlib import Path
import diode_brackets as db
def make(destination):
destination=Path(destination)
if destination.exists() and (not destination.is_dir() or any(destination.iterdir())):
raise ValueError('destination must be absent or empty; existing data is not overwritten')
destination.mkdir(parents=True,exist_ok=True)
with (destination/'constructed-example.csv').open('w',newline='') as f:
writer=csv.writer(f);writer.writerow(db.FIELDS)
for device,cycle,step,target in db.expected_rows():
current=target*1e-6
#An illustrative logarithmic curve, not a manufacturer specification.
vf=.600+.02585*math.log(current/.0005) if device=='diode' else current*1000
vf=round(vf,3)
vr=(current+vf/db.METER_INPUT)/(1/db.SERIES_R+1/db.METER_INPUT)
writer.writerow([device,cycle,step,target,format(vr,'.3f'),format(vf,'.3f')])
(destination/'CONSTRUCTED-NOT-MEASURED.txt').write_text(
'Every value is constructed and quantized to 1 mV. No physical observations.\n'
'The logarithmic curve is illustrative, not an acceptance target.\n'
'Run with --kind constructed. Do not copy these values into physical-blank.csv.\n')
if __name__=='__main__':
if len(sys.argv)!=2:
raise SystemExit('usage: python3 make_constructed.py NEW_OR_EMPTY_DIRECTORY')
try:make(sys.argv[1])
except (ValueError,OSError) as exc:
print('input error: '+str(exc),file=sys.stderr);sys.exit(2)
Complete host tests
"""Independent requirement examples. Every numeric fixture is constructed."""
import csv, hashlib, json, math, subprocess, sys, tempfile, unittest
from pathlib import Path
import diode_brackets as db
HEADER=['device','cycle','step','target_ua','series_v','forward_v']
def fixture(style='wide_only'):
"""Build rows from the approved acquisition table, not the parser's function."""
result=[]
seq=[('C0',500),('WL',400),('C1',500),('WH',600),('C2',500),('NL',490),('C3',500),('NH',510),('C4',500)]
for cycle in (1,2,3):
for step,target in seq:
if step.startswith('C'):vf=.600
elif step in ('WL','WH'):
width=.010 if style in ('wide_only','both') else .001
vf=.600+(-width if step=='WL' else width)
else:
width=.005 if style in ('narrow_only','both') else .001
vf=.600+(-width if step=='NL' else width)
current=target*1e-6
vr=(current+vf/1e7)/(1/3900+1/1e7)
result.append(dict(zip(HEADER,['diode',str(cycle),step,str(target),vr,vf])))
for cycle in (1,2,3):
for step,target in [('L',400),('C',500),('H',600)]:
current=target*1e-6;vf=current*1000
vr=(current+vf/1e7)/(1/3900+1/1e7)
result.append(dict(zip(HEADER,['control',str(cycle),step,str(target),vr,vf])))
return result
def write_sheet(path,rows):
with Path(path).open('w',newline='') as f:
w=csv.DictWriter(f,fieldnames=HEADER);w.writeheader();w.writerows(rows)
class ParserTests(unittest.TestCase):
def parse(self,text):
with tempfile.TemporaryDirectory() as d:
p=Path(d)/'x.csv';p.write_bytes(text if isinstance(text,bytes) else text.encode())
return db.read_rows(p)
def test_exact_contract(self):
self.assertEqual(len(db.expected_rows()),36)
self.assertEqual([x[2] for x in db.expected_rows()[:9]],['C0','WL','C1','WH','C2','NL','C3','NH','C4'])
with tempfile.TemporaryDirectory() as d:
p=Path(d)/'x.csv';write_sheet(p,fixture());self.assertEqual(len(db.read_rows(p)),36)
def test_duplicate_header_hidden_nan(self):
with self.assertRaises(ValueError):self.parse('device,cycle,step,target_ua,series_v,series_v,forward_v\ndiode,1,C0,500,nan,1.95,.6\n')
def test_utf8_quotes_and_schema(self):
for text in [b'\xff','device,cycle,step,target_ua,series_v,forward_v\ndiode,1,C0,500,"1.95,.6\n',','.join(reversed(HEADER))+'\n']:
with self.subTest(text=text):
with self.assertRaises(ValueError):self.parse(text)
def test_byte_limit(self):
with self.assertRaises(ValueError):self.parse(b' '*65537)
def test_order_duplicate_row_and_wrong_target(self):
for mode in ['order','duplicate','target','extra','missing','blank','nan']:
with tempfile.TemporaryDirectory() as d:
rows=fixture();p=Path(d)/'x.csv'
if mode=='order':rows[0],rows[1]=rows[1],rows[0]
if mode=='duplicate':rows[1]=dict(rows[0])
if mode=='target':rows[1]['target_ua']='401'
if mode=='extra':rows.append(dict(rows[-1]))
if mode=='missing':rows.pop()
if mode=='blank':rows[0]['series_v']=''
if mode=='nan':rows[0]['forward_v']='nan'
write_sheet(p,rows)
with self.subTest(mode=mode):
with self.assertRaises(ValueError):db.read_rows(p)
class IntervalTests(unittest.TestCase):
def test_meter_count_floor_not_sample_mean(self):
self.assertEqual(db.meter_interval(.600),[.5987,.6013])
def test_loaded_current_and_corners(self):
p=db.point_interval(1.9494737052549505,.6)
self.assertAlmostEqual(p['nominal_current_a'],.0005,places=14)
self.assertAlmostEqual(p['current_interval_a'][0],.0004935601489242878,places=14)
self.assertAlmostEqual(p['current_interval_a'][1],.0005065719739465359,places=14)
def test_signed_chord_is_not_clipped(self):
lo={'forward_interval_v':[.598,.602],'current_interval_a':[.00048,.00049],'forward_v':.600,'nominal_current_a':.000485}
hi={'forward_interval_v':[.599,.603],'current_interval_a':[.00051,.00052],'forward_v':.601,'nominal_current_a':.000515}
r=db.chord_interval(lo,hi)
self.assertLess(r['interval_ohm'][0],0)
self.assertFalse(r['arithmetic_positive'])
def test_nonpositive_denominator_withheld(self):
lo={'forward_interval_v':[.59,.60],'current_interval_a':[.0004,.0006],'forward_v':.595,'nominal_current_a':.0005}
hi={'forward_interval_v':[.60,.61],'current_interval_a':[.0005,.0007],'forward_v':.605,'nominal_current_a':.0006}
self.assertIsNone(db.chord_interval(lo,hi)['interval_ohm'])
def test_wider_endpoint_bounds_do_not_improve_chord(self):
lo={'forward_interval_v':[.590,.592],'current_interval_a':[.00039,.00041],'forward_v':.591,'nominal_current_a':.0004}
hi={'forward_interval_v':[.608,.610],'current_interval_a':[.00059,.00061],'forward_v':.609,'nominal_current_a':.0006}
a=db.chord_interval(lo,hi)['interval_ohm']
lo['forward_interval_v']=[.589,.593];lo['current_interval_a']=[.00038,.00042]
hi['forward_interval_v']=[.607,.611];hi['current_interval_a']=[.00058,.00062]
b=db.chord_interval(lo,hi)['interval_ohm']
self.assertLessEqual(b[0],a[0]);self.assertGreaterEqual(b[1],a[1])
def test_extreme_finite_reading_skips_range_arithmetic(self):
rows=fixture();rows[0]['series_v']=1e308
report=db.analyze_rows(rows,'constructed')
self.assertFalse(report['controls_passed']);self.assertEqual(report['resolution_pattern'],'unsupported')
self.assertIsNone(report['points'][0]['current_interval_a'])
json.dumps(report,allow_nan=False)
def test_model_visible_beside_interpretation(self):
r=db.analyze_rows(fixture(),'constructed')
self.assertIn('engineering',r['conditional_model']['qualification'])
for cycle in r['cycles']:
for width in ['wide','narrow']:
self.assertIn('conditional_model',cycle[width]);self.assertIn('interpretation_supported',cycle[width])
class ControlTests(unittest.TestCase):
def test_all_five_resolution_states(self):
for pattern in ['wide_only','narrow_only','both','neither']:
r=db.analyze_rows(fixture(pattern),'constructed')
self.assertTrue(r['controls_passed'],r['controls']);self.assertEqual(r['resolution_pattern'],pattern)
rows=fixture();rows[0]['forward_v']=-.6
self.assertEqual(db.analyze_rows(rows,'constructed')['resolution_pattern'],'unsupported')
def test_no_averaging_of_fixed_error(self):
r=db.analyze_rows(fixture(),'constructed')
first=r['cycles'][0]['wide']['interval_ohm']
self.assertEqual(r['summary']['wide']['hull_ohm'],first)
def test_slow_global_center_drift(self):
rows=fixture()
for row in rows:
if row['device']=='diode' and row['cycle']=='3' and row['step'].startswith('C'):
row['forward_v']+=.004
row['series_v']=(.0005+row['forward_v']/1e7)/(1/3900+1/1e7)
r=db.analyze_rows(rows,'constructed')
self.assertTrue(all(x['voltage_stable'] for x in r['controls']['diode_per_cycle_centers']))
self.assertFalse(r['controls']['screens']['diode_center_voltage_stable']);self.assertFalse(r['interpretation_supported'])
def test_disjoint_center_currents_are_reported(self):
rows=fixture();row=rows[0];row['series_v']=(.00055+row['forward_v']/1e7)/(1/3900+1/1e7)
r=db.analyze_rows(rows,'constructed')
self.assertFalse(r['controls']['screens']['diode_center_current_overlap'])
def test_separate_control_center_drift(self):
rows=fixture();row=next(r for r in rows if r['device']=='control' and r['cycle']=='3' and r['step']=='C')
row['forward_v']+=.004;row['series_v']=(.0005+row['forward_v']/1e7)/(1/3900+1/1e7)
r=db.analyze_rows(rows,'constructed')
self.assertTrue(r['controls']['screens']['diode_center_voltage_stable'])
self.assertFalse(r['controls']['screens']['control_center_voltage_stable'])
def test_target_mismatch_does_not_become_parser_error(self):
rows=fixture();rows[1]['series_v']+=.100
r=db.analyze_rows(rows,'constructed');self.assertFalse(r['controls_passed'])
self.assertFalse(r['controls']['screens']['nominal_target_matching'])
def test_bad_resistor_control(self):
rows=fixture()
for row in rows:
if row['device']=='control':
current=float(row['target_ua'])*1e-6;row['forward_v']=current*1400
row['series_v']=(current+row['forward_v']/1e7)/(1/3900+1/1e7)
r=db.analyze_rows(rows,'constructed');self.assertFalse(r['controls']['screens']['control_ratios_consistent'])
self.assertFalse(r['interpretation_supported']);self.assertTrue(r['cycles'][0]['wide']['arithmetic_positive'])
self.assertFalse(r['cycles'][0]['wide']['positive_slope_resolved'])
def test_wrong_polarity_and_voltage_bound(self):
for field,value in [('forward_v',-.6),('series_v',4.8),('forward_v',6.1)]:
rows=fixture();rows[0][field]=value;r=db.analyze_rows(rows,'constructed')
self.assertFalse(r['controls_passed']);self.assertEqual(r['resolution_pattern'],'unsupported')
class CLITests(unittest.TestCase):
def call(self,p,*args):
return subprocess.run([sys.executable,str(Path(db.__file__)),str(p),*args],capture_output=True,text=True)
def test_valid_and_unresolved_are_exit_zero(self):
with tempfile.TemporaryDirectory() as d:
p=Path(d)/'x.csv'
for style in ['wide_only','neither']:
write_sheet(p,fixture(style));q=self.call(p,'--kind','constructed')
self.assertEqual(q.returncode,0,q.stderr);self.assertEqual(json.loads(q.stdout)['resolution_pattern'],style)
rows=fixture();rows[0]['forward_v']=-.6;write_sheet(p,rows);q=self.call(p,'--kind','observed')
self.assertEqual(q.returncode,0,q.stderr);self.assertFalse(json.loads(q.stdout)['controls_passed'])
def test_actual_duplicate_header_and_blank_are_no_json(self):
with tempfile.TemporaryDirectory() as d:
p=Path(d)/'x.csv';write_sheet(p,fixture());text=p.read_text()
text=text.replace('series_v,','series_v,series_v,',1).replace('diode,1,C0,500,','diode,1,C0,500,nan,',1)
p.write_text(text);q=self.call(p,'--kind','constructed');self.assertEqual(q.returncode,2);self.assertEqual(q.stdout,'')
rows=fixture();rows[0]['series_v']='';write_sheet(p,rows);q=self.call(p,'--kind','observed')
self.assertEqual(q.returncode,2);self.assertEqual(q.stdout,'')
def test_kind_is_mandatory(self):
with tempfile.TemporaryDirectory() as d:
p=Path(d)/'x.csv';write_sheet(p,fixture())
for args in [(),('--kind','fake')]:
q=self.call(p,*args);self.assertEqual(q.returncode,2);self.assertEqual(q.stdout,'')
class GeneratorTests(unittest.TestCase):
def test_generator_quantizes_and_refuses_overwrite(self):
import make_constructed
with tempfile.TemporaryDirectory() as d:
root=Path(d)/'constructed';make_constructed.make(root)
p=root/'constructed-example.csv';data=p.read_bytes();rows=db.read_rows(p)
self.assertEqual(db.analyze_rows(rows,'constructed')['resolution_pattern'],'wide_only')
raw=list(csv.DictReader(p.read_text().splitlines()))
self.assertTrue(all(len(r['series_v'].split('.')[-1])==3 for r in raw))
with self.assertRaises(ValueError):make_constructed.make(root)
self.assertEqual(p.read_bytes(),data)
if __name__=='__main__':unittest.main()
Challenge
Two readings are 0.599 V and 0.601 V. Each has about ±1.3 mV error. Can a positive 2 mV difference establish a positive finite chord just because the displayed values increase?
Answer
No. Their conservative difference interval is approximately −0.6 to 4.6 mV. It includes zero. Even if actual current ordering is positive, the voltage change is unresolved under these bounds. A positive displayed difference is not sufficient. Repeating the same readings does not divide the manufacturer's fixed errors by sqrt(N).
Sources and related reading
- Vishay 1N4148, document 81857 Rev.1.6: exact ordering, package/polarity and stated test conditions. Typical curves are not slope guarantees.
- Vishay MRS25: resistor values, tolerance and ratings under stated conditions.
- Fluke 87V MAX user manual: normal-range resolution, accuracy period/conditions and nominal input loading.
- RIGOL DP800 specifications: the exact DP832A source variant and programming/protection limits.
- Analog Devices diode chapter: the distinction between a local small-signal model and a nonlinear curve.
- For a separate experiment that matches actual current while changing temperature, read Measure a 1N4148’s Forward Voltage at Two Temperatures.