Electronic Reliability Prediction and MTBF Analysis Toolkit
Three Python programs carry a reliability estimate from a bill of materials through MIL-HDBK-217F parts count, component stress analysis, and a traceable system MTBF.
Independent Research & Computational Methods
- Affiliation
- Mirion (Paragon Energy Solutions)
- Classification
- Computational reliability engineering
- Stage
- Developed analytical software
From a bill of materials to a defensible estimate
A resistor appears four times on a board. A supplier gives one failure rate for an entire module. Both values can belong in the same equipment prediction, but only the resistor rate should be multiplied by four. I built this Python, Jupyter, and Excel workflow so that a reviewer can follow those decisions from the original parts list to the reported mean time between failures (MTBF).
The three programs answer different engineering questions. The parts-count engine estimates a population from its classification, quality, and environment. The part-stress console uses circuit and thermal conditions where the design supports a more specific model. The system aggregator records what each contribution covers, normalizes its units, and calculates reliability over a declared operating exposure.
Open the working calculator · Read the governing formula inventory · Inspect the complete Python source
Parts count from a controlled table
For equipment in one environment, Notice 2 Appendix A gives
Each term represents a group of like parts. counts physical items, is the per-part generic rate for the selected part type and environment in failures per million operating hours, and is the applicable Appendix A quality factor. The generic rate already incorporates the environment selected in the table. Equipment portions operating in different environments are evaluated separately, then their non-overlapping contributions are added.
Eligible microcircuits have one further adjustment. The generic table assumes a device type with at least two years of production history. For production age in years, the learning multiplier is
The age belongs to the generic device type. An unknown age leaves a required input unresolved. Hybrid microcircuits require a separate §5.5 part-stress calculation because Appendix A supplies no generic hybrid rate. The workbook accepts a documented final per-item rate for that replacement.
record["lambda_per_item"] = lam_g * pi_q
if microcircuit:
record["lambda_per_item"] *= pi_l
record["lambda_line"] = quantity * record["lambda_per_item"]
Worked output · four composition resistors
The calculator’s parts-count example selects the RCR row for MIL-R-39008 composition resistors on Appendix A page A-7. The GB (ground benign) column gives 0.0022 failures per million operating hours per resistor. The illustrative class M selection gives a quality factor of 1. The program records the row, environment column, factor selections, and substituted equation in the results workbook.
| Results workbook entry | Calculated value |
|---|---|
| Included population | 4 resistors, one calculation line |
| Population failure rate | 4 × 0.0022 × 1 = 0.0088 failures per million operating hours |
| Reciprocal of the population rate | 113,636,364 operating hours, rounded |
| Strict-mode review | 0 errors, 1 warning for demonstration data |
The reciprocal applies to the four-resistor boundary. The workbook marks the calculation “VALID - REVIEW WARNINGS” and the release status “NOT RELEASE-READY.” Its summary identifies the exact input by SHA-256, so a reviewer can check which revision produced the result. Production release also requires independent verification of the transcribed Appendix A reference cells.
Inspect the example input workbook · Inspect the calculated results workbook
Part stress under documented operating conditions
For a resistor with known operating conditions, the Notice 2 §9.1 model uses the style-dependent base rate and five factors,
The style and applicable specification establish the base rate, temperature branch, and stress branch. For example, the RCR style uses , temperature column 1, and stress column 2. The base rate and factors come from §9.1. The 0.0022 generic rate used in the preceding Appendix A example belongs to a different calculation.
The power factor uses the actual dissipated power in watts. The stress ratio compares that dissipation with , the applicable rated power after any required derating at the modeled condition.
S = PD/PR
if S > 1:
raise ModelApplicabilityError(f"Resistor power stress S=PD/PR={S:.6g} exceeds 1.0.")
piP = PD**.39 if PD>0 else 0.0
piS = resistor_piS(scol,S)
Where a temperature column applies, is resistor case temperature in °C and is 0.20 eV for column 1 or 0.08 eV for column 2. RD and RTH use a fixed . Ambient component temperature can approximate case temperature for a low-dissipation, non-power resistor with negligible self-heating.
Two checks in the inventory isolate the branch selection. At 25 °C both temperature columns give unity. At half rated power the console returns for column 1 and for column 2. A calculation can use the correct stress ratio and still pick the wrong multiplier if the style is misclassified.
Reproducing the handbook capacitor example
Notice 2 §10.2 supplies an independent worked case for the §10.1 model. The CQ capacitor is 0.015 µF, rated at 400 VDC, and operates at 50 °C in the ground fixed environment. The applied voltage is 200 VDC with a 50 V RMS, 60 Hz sinusoid. The voltage factor depends on peak applied voltage, so the AC term is converted to peak before the ratio is formed.
| Calculation path | Factors and result |
|---|---|
| Published lookup | 0.00051 × 1.6 × 0.69 × 2.9 × 1 × 3 × 10 ≈ 0.049 failures per million operating hours |
| Continuous equations | Temperature 1.57164, capacitance 0.68525, voltage 2.82587. The per-part rate is approximately 0.04656 failures per million operating hours. |
The difference comes from rounding the handbook’s displayed lookup factors. The console’s acceptance check retains the continuous calculation so that changes to the RMS conversion, capacitance units, or voltage-stress branch can be detected.
cap_piT=arrhenius(50,.15)
cap_piC=.015**.09
cap_S=(200+math.sqrt(2)*50)/400
cap_piV=capacitor_piV(1,cap_S)
cap_lp=.00051*cap_piT*cap_piC*cap_piV*1.0*3.0*10.0
assert math.isclose(cap_piT,1.5716449017549696,rel_tol=1e-12)
assert math.isclose(cap_lp,.04656,rel_tol=.002) # source inventory gives approximately 0.04656
Replacing a population and adding assembly contributions
The console covers resistors (§9.1), capacitors (§10.1), transformers and coils (§§11.1–11.2), low-frequency diodes and silicon FETs (§§6.1 and 6.4), optoelectronics (§6.11), connectors (§15.1), and solid-state or time-delay relays (§13.2). It records the selected model, inputs, factors, and evidence. If a documented part-stress rate replaces the estimate for the same population, the revised accounting is
The final per-item stress rate already contains its applicable factors. A distinct assembly contribution can enter as a supplement. The console includes plated-through-hole assemblies (§16.1), the surface-mount assembly weakest-link model (§16.2), and individual connections outside §16 (§17.1). Each entry needs a physical boundary so that a board, its devices, and its connections are counted once.
System aggregation and operating exposure
In the separate system example from the workspace, one input is a per-component rate and the other is an already aggregated module rate. The ledger preserves the input form and quantity alongside the contribution actually included in the sum. Rates in this table are failures per million operating hours.
| Physical scope | Calculation | Rate |
|---|---|---|
| Four components | 4 × 0.25 per component | 1.00 |
| Separate module | 1.00 for the complete module | 1.00 |
| System | Sum of the two contributions | 2.00 |
For an independent, constant-rate series model, let be the summed numerical rate in failures per million operating hours. The hourly rate, predicted MTBF in operating hours, and survival probability after operating hours are
total = sum(r.contribution_lambda_1e6h for r in included)
if not math.isfinite(total) or total <= 0 or not math.isfinite(MILLION / total):
raise ValueError("Total included failure rate must be > 0 to report a finite MTBF.")
for r in records:
r.percent_of_total = 100.0 * r.contribution_lambda_1e6h / total if r.include else 0.0
return {
"lambda_total_1e6h": total,
"lambda_total_hour": total * 1e-6,
"mtbf_hours": MILLION / total,
}
Here , giving per hour and a predicted MTBF of 500,000 operating hours. At the example’s declared use of 8,760 hours per year, forty years corresponds to 350,400 operating hours. The model gives 49.619% probability of surviving that exposure and 50.381% probability of at least one failure.
View the one-page system calculation sheet
Inspect the calculated contribution ledger (CSV)
Each of the two rows accounts for 50% of the predicted rate. That share shows where to look when examining the drivers of a prediction. An engineering decision about system risk also depends on what each failure does. The additive model requires a complete non-overlapping boundary and a failure of any included series element to constitute system failure. Redundancy, shared causes, and changing operating states can require a different system model. Estimating observed field performance would require operating and failure records.
Where the prediction enters FMECA
A per-item rate can feed the quantitative criticality analysis in MIL-STD-1629A Task 102. For one failure mode, severity class, and mission phase, the inventory gives
With operating exposure in hours, convert the predicted per-item rate to failures per hour first. The analyst supplies , the fraction of the item failure rate assigned to the mode, and , the conditional probability of the specified effect given that mode. The sum for is restricted to one item, one severity classification, and one mission phase. The toolkit supplies the rate and its calculation basis. Determining the modes, effects, severity, and allocations remains a separate engineering analysis.
Complete Python source
These are the three complete Python engines used by the live workspace. The excerpts above are drawn directly from these files. The workspace accepts a controlled workbook or direct population entry for parts count, provides an interactive part-stress console, and accepts a ledger or direct contribution entry for the system calculation.
PCMTBF.py · parts count and workbook validation
"""MIL-HDBK-217F Notice 2 Appendix A Parts Count calculation by Kyle M. LeClair.
Web edition of PCMTBF. Reads a controlled workbook and writes a separate results
workbook with the author's calculation tables, reference checks and issue ledger.
"""
from __future__ import annotations
import hashlib
import math
import re
import shutil
import sys
import warnings
from dataclasses import dataclass
from datetime import date, datetime, timezone
from pathlib import Path
from typing import Any, Dict, Iterable, List, Mapping, Optional, Sequence, Tuple
import json
import numpy as np
import pandas as pd
from openpyxl import load_workbook
from openpyxl.chart import BarChart, Reference
from openpyxl.styles import Alignment, Border, Font, PatternFill, Side
from openpyxl.utils import get_column_letter
ENGINE_VERSION = "1.0.1"
NOTEBOOK_NAME = "PCMTBF.py"
RATE_UNITS = "failures / 10^6 operating hours"
def clean_header(value: Any) -> str:
"""Normalize a header cell while preserving the workbook's controlled spelling."""
if value is None or pd.isna(value):
return ""
return str(value).strip()
def read_controlled_table(book, sheet_name, required_columns):
raw = pd.read_excel(book, sheet_name=sheet_name, header=None, dtype=object)
required = set(required_columns)
for index, row in raw.head(100).iterrows():
headers = [clean_header(value) for value in row]
if required.issubset(headers):
frame = raw.iloc[index + 1:].reset_index(drop=True)
frame.columns = headers
return frame.dropna(how="all").copy(), int(index + 1)
raise ValueError(f"Could not locate the controlled header row on {sheet_name!r}.")
PROJECT_COLUMNS = ["Parameter", "Value", "Description / Required Basis"]
BOM_COLUMNS = [
"Include", "Item_ID", "Assembly_PN", "Ref_Des_or_Group", "Manufacturer_PN",
"Description", "Handbook_Section", "Part_Group", "Environment", "Quantity",
"Prediction_Method", "Parts_Count_Rate_Source", "Rate_Key", "Direct_lambda_g",
"Quality_Scheme", "Quality_Class", "pi_Q_Override", "Quality_Evidence",
"Years_In_Production", "Custom_Screening_Points", "Part_Stress_lambda",
"Source_Page", "Source_Row", "Source_Column", "Notes",
]
RATE_DATABASE_COLUMNS = [
"Rate_Key", "Section", "Generic_Part_Type", "Branch_or_Style", "Environment",
"lambda_g", "Source_Page", "Source_Row", "Source_Column", "Verification_Status",
"Verified_By", "Verification_Date", "Notes",
]
QUALITY_COLUMNS = [
"Quality_Table", "Section_or_Branch", "Quality_Class", "pi_Q", "Applicable",
"Source_Page", "Notes", "Alias_or_Routing",
]
ENVIRONMENT_COLUMNS = ["Environment", "Name", "Selection Basis", "Source"]
REQUIRED_SHEETS = {
"START_HERE", "Project_Setup", "BOM_Input", "Rate_Database", "Quality_Factors",
"Reference_Data", "Summary_Output", "Detail_Output", "Issues_Output",
}
def infer_quality_scheme(section: str, part_group: Any) -> str:
"""Route AUTO selections using the workbook's Appendix A structure."""
pg = str(part_group or "").strip().upper()
if section == "5" or section.startswith("5."):
return "MICROCIRCUIT"
if section == "6.13":
return "LASER_DIODE"
if section == "6.2":
return "DISCRETE_SCHOTTKY" if "SCHOTTKY" in pg else "DISCRETE_HIGH_FREQ_DIODE"
if section in {"6.6", "6.7", "6.8", "6.9"}:
return "DISCRETE_RF_TRANSISTOR"
if section == "6" or section.startswith("6."):
return "DISCRETE_NON_RF"
if section == "9" or section.startswith("9."):
return "RESISTOR"
if section == "10" or section.startswith("10."):
return "CAPACITOR"
if section in {
"11.1", "11.2", "12.1", "12.2", "12.3", "13.1", "13.2",
"14.1", "14.2", "15.1", "15.2", "16.1", "16.2", "17.1",
"18.1", "19.1", "20.1", "21.1", "22.1",
}:
return "A11"
return ""
def run(input_path, output_dir, *, allow_overwrite=False):
"""Return summary and output file paths. The source workbook is preserved."""
INPUT_WORKBOOK = Path(input_path)
if INPUT_WORKBOOK.suffix.lower() != ".xlsx" or not INPUT_WORKBOOK.is_file():
raise ValueError("Choose an existing .xlsx controlled input workbook.")
Path(output_dir).mkdir(parents=True, exist_ok=True)
# Confirm sheet names before reading individual tables.
book = pd.ExcelFile(INPUT_WORKBOOK, engine="openpyxl")
missing_sheets = REQUIRED_SHEETS - set(book.sheet_names)
if missing_sheets:
raise ValueError(f"The workbook is missing required sheets: {sorted(missing_sheets)}")
project_table, PROJECT_HEADER_ROW = read_controlled_table(book, "Project_Setup", PROJECT_COLUMNS)
bom_raw, BOM_HEADER_ROW = read_controlled_table(book, "BOM_Input", BOM_COLUMNS)
rate_db_raw, RATE_DATABASE_HEADER_ROW = read_controlled_table(book, "Rate_Database", RATE_DATABASE_COLUMNS)
quality_raw, QUALITY_HEADER_ROW = read_controlled_table(book, "Quality_Factors", QUALITY_COLUMNS)
environment_raw, ENVIRONMENT_HEADER_ROW = read_controlled_table(book, "Reference_Data", ENVIRONMENT_COLUMNS)
# Preserve the exact Excel row of every BOM and rate-database record.
bom_raw["_Excel_Row"] = bom_raw.index.astype(int) + BOM_HEADER_ROW + 1
rate_db_raw["_Excel_Row"] = rate_db_raw.index.astype(int) + RATE_DATABASE_HEADER_ROW + 1
book.close()
project = {
str(row["Parameter"]).strip(): row["Value"]
for _, row in project_table.iterrows()
if pd.notna(row.get("Parameter")) and str(row.get("Parameter")).strip()
}
file_sha256 = hashlib.sha256(INPUT_WORKBOOK.read_bytes()).hexdigest()
# Extract the actual environment-definition block, excluding later tables on Reference_Data.
environment_ref = environment_raw.copy()
environment_ref["Environment"] = environment_ref["Environment"].astype(str).str.strip().str.upper()
environment_ref = environment_ref[
environment_ref["Environment"].str.fullmatch(r"[A-Z]{2,3}", na=False)
& environment_ref["Name"].notna()
].copy()
environment_ref = environment_ref.drop_duplicates(subset=["Environment"], keep="first")
ENVIRONMENTS = set(environment_ref["Environment"].tolist())
EXPECTED_ENVIRONMENTS = {
"GB", "GF", "GM", "NS", "NU", "AIC", "AIF", "AUC", "AUF", "ARW",
"SF", "MF", "ML", "CL",
}
if ENVIRONMENTS != EXPECTED_ENVIRONMENTS:
raise ValueError(
"Reference_Data environment definitions do not match the fourteen handbook symbols. "
f"Missing: {sorted(EXPECTED_ENVIRONMENTS - ENVIRONMENTS)}; "
f"Unexpected: {sorted(ENVIRONMENTS - EXPECTED_ENVIRONMENTS)}"
)
METHOD_PARTS_COUNT = "PARTS_COUNT"
METHOD_PART_STRESS = "PART_STRESS_REPLACEMENT"
RATE_DATABASE = "RATE_DATABASE"
DIRECT_RATE = "DIRECT_LAMBDA_G"
VALID_METHODS = {METHOD_PARTS_COUNT, METHOD_PART_STRESS}
VALID_RATE_SOURCES = {RATE_DATABASE, DIRECT_RATE}
VALID_VERIFICATION_STATUSES = {"VERIFIED", "DRAFT", "N/A_UNSUPPORTED", "DO_NOT_USE"}
def norm(value: Any) -> str:
"""Uppercase, trim, collapse whitespace, and treat underscores as spaces."""
if value is None or pd.isna(value):
return ""
return " ".join(str(value).strip().upper().replace("_", " ").split())
def canonical(value: Any) -> str:
return norm(value).replace(" ", "_")
def text(value: Any) -> str:
if value is None or pd.isna(value):
return ""
return str(value).strip()
def numeric(value: Any) -> Optional[float]:
if isinstance(value, (bool, np.bool_)):
return None # Excel TRUE/FALSE is not a physical quantity or failure rate.
if value is None or pd.isna(value) or str(value).strip() == "":
return None
try:
number = float(value)
except (TypeError, ValueError):
return None
return number if math.isfinite(number) else None
def parse_bool(value: Any) -> Tuple[Optional[bool], Optional[str]]:
v = norm(value)
if v in {"TRUE", "YES", "1"}:
return True, None
if v in {"FALSE", "NO", "0"}:
return False, None
return None, "Use TRUE or FALSE."
def whole_quantity(value: Any) -> Tuple[Optional[int], Optional[str]]:
q = numeric(value)
if q is None:
return None, "Quantity is required and must be numeric."
if q < 0:
return None, "Quantity cannot be negative."
if not q.is_integer():
return None, "Quantity must be a whole number."
return int(q), None
def is_microcircuit(section: str) -> bool:
s = text(section)
return s == "5" or s.startswith("5.")
def is_hybrid_microcircuit(section: str, part_group: Any) -> bool:
return text(section) == "5.5" or (is_microcircuit(section) and "HYBRID" in norm(part_group))
def source_string(page: Any, row: Any, column: Any) -> str:
parts = [text(page), text(row), text(column)]
return " | ".join(p for p in parts if p)
@dataclass
class Issue:
severity: str
item_id: str
excel_row: Optional[int]
field: str
message: str
def as_dict(self) -> Dict[str, Any]:
return {
"Severity": self.severity,
"Item_ID": self.item_id,
"Excel_Row": self.excel_row,
"Field": self.field,
"Message": self.message,
}
def add_issue(
issues: List[Issue],
severity: str,
item_id: str,
field: str,
message: str,
excel_row: Optional[int] = None,
) -> None:
issues.append(Issue(severity.upper(), item_id, excel_row, field, message))
QUALITY_ALIASES = {
"CLASS S": "S",
"CLASS B": "B",
"CLASS B-1": "B-1",
"MIL SPEC": "MIL-SPEC",
"MILSPEC": "MIL-SPEC",
"NON MIL": "NON-MIL",
"NONMIL": "NON-MIL",
"ER": "ESTABLISHED",
"ESTABLISHED RELIABILITY": "ESTABLISHED",
}
# "OTHER", "COMMERCIAL", and "UNKNOWN" are not universal Appendix A quality classes.
# They must be interpreted only after the applicable quality scheme is known.
GENERIC_UNKNOWN_QUALITY = {
"OTHER",
"COMMERCIAL",
"UNKNOWN",
"COMMERCIAL OR UNKNOWN",
"OTHER COMMERCIAL OR UNKNOWN",
"OTHER/COMMERCIAL/UNKNOWN",
}
def resolve_quality_class_alias(
raw_value: Any,
scheme: str,
section: str,
part_group: Any,
description: Any,
supported_classes: Sequence[str],
) -> Tuple[str, str]:
"""Resolve human-friendly commercial/unknown quality text within the selected Appendix A scheme.
Returns (resolved_class, trace_note). The mapping is scheme-specific so the microcircuit
class OTHER is never incorrectly applied to discrete semiconductors, passives, or A-11 rows.
"""
raw = norm(raw_value)
mapped = QUALITY_ALIASES.get(raw, raw)
supported = {norm(v) for v in supported_classes if text(v)}
if mapped not in GENERIC_UNKNOWN_QUALITY:
return mapped, ""
# Microcircuits explicitly publish OTHER = commercial/unknown screening.
if scheme == "MICROCIRCUIT" and "OTHER" in supported:
return "OTHER", "Quality class commercial/unknown resolved to the Appendix A microcircuit OTHER category."
# Resistors/capacitors normalize the commercial/unknown category to LOWER (pi_Q=10).
if scheme in {"RESISTOR", "CAPACITOR"} and "LOWER" in supported:
return "LOWER", f"Quality class {raw!r} resolved to LOWER for the Appendix A {scheme.lower()} commercial/unknown category."
# Appendix A-11 uses NON-MIL for the non-military/commercial branch where quality applies.
if scheme == "A11" and "NON-MIL" in supported:
return "NON-MIL", f"Quality class {raw!r} resolved to NON-MIL for Appendix A-11 Section {section}."
# Discrete-semiconductor tables do not publish a universal OTHER class.
# If plastic construction is explicit, use PLASTIC where that branch exists;
# otherwise route commercial/unknown quality to LOWER and retain a trace note.
if scheme.startswith("DISCRETE_"):
construction_text = f"{norm(part_group)} {norm(description)}"
if "PLASTIC" in construction_text and "PLASTIC" in supported:
return "PLASTIC", f"Quality class {raw!r} resolved to PLASTIC because the part description/group identifies plastic construction."
if "LOWER" in supported:
return "LOWER", (
f"Quality class {raw!r} resolved to LOWER for {scheme}. "
"If the device is plastic-encapsulated and the selected scheme provides a PLASTIC category, select PLASTIC explicitly."
)
# Laser-diode quality is package/facet-specific; do not invent a generic fallback.
return mapped, ""
def prepare_quality_reference(frame: pd.DataFrame) -> pd.DataFrame:
ref = frame.copy()
ref["Quality_Table_N"] = ref["Quality_Table"].map(canonical)
ref["Section_N"] = ref["Section_or_Branch"].map(norm)
ref["Class_N"] = ref["Quality_Class"].map(norm).map(lambda x: QUALITY_ALIASES.get(x, x))
ref["Applicable_N"] = ref["Applicable"].map(norm)
ref["pi_Q_N"] = pd.to_numeric(ref["pi_Q"], errors="coerce")
return ref
def prepare_rate_reference(frame: pd.DataFrame) -> pd.DataFrame:
ref = frame.copy()
ref["Rate_Key_N"] = ref["Rate_Key"].map(text)
ref["Section_N"] = ref["Section"].map(text)
ref["Environment_N"] = ref["Environment"].map(norm)
ref["Verification_N"] = ref["Verification_Status"].map(canonical)
ref["lambda_g_N"] = pd.to_numeric(ref["lambda_g"], errors="coerce")
return ref
quality_ref = prepare_quality_reference(quality_raw)
rate_ref = prepare_rate_reference(rate_db_raw)
def microcircuit_learning_factor(years: Any) -> Tuple[Optional[float], str, Optional[str]]:
"""Return (pi_L, calculation note, error)."""
y = numeric(years)
if y is None:
return None, "", "Years_In_Production is required for a Section 5 Parts Count row."
if y < 0:
return None, "", "Years_In_Production cannot be negative."
if y <= 0.1:
return 2.0, f"Y={y:g} <= 0.1; Appendix A endpoint pi_L=2.0.", None
if y >= 2.0:
return 1.0, f"Y={y:g} >= 2.0; mature-production pi_L=1.0.", None
value = 0.01 * math.exp(5.35 - 0.35 * y)
return value, f"0.1 < Y={y:g} < 2.0; pi_L=0.01*exp(5.35-0.35Y)={value:.12g}.", None
def custom_quality_factor(points: Any) -> Tuple[Optional[float], str, Optional[str]]:
p = numeric(points)
if p is None or p <= 0:
return None, "", "CUSTOM microcircuit quality requires Custom_Screening_Points > 0."
value = 2.0 + 87.0 / p
note = (
f"Custom Appendix A-4 screening: pi_Q=2+87/{p:g}={value:.12g}. "
"The analyst remains responsible for group eligibility, independence restrictions, and required sequencing."
)
return value, note, None
def resolve_quality(
row: pd.Series,
section: str,
issues: List[Issue],
item_id: str,
excel_row: int,
) -> Tuple[Optional[float], bool, str, str, Optional[str]]:
"""Return pi_Q, applicable, resolved scheme, note, error."""
entered_scheme = canonical(row.get("Quality_Scheme"))
override = numeric(row.get("pi_Q_Override"))
if text(row.get("pi_Q_Override")) and override is None:
return None, True, entered_scheme, "", "pi_Q_Override is populated but is not a finite numeric value."
if override is not None:
if entered_scheme != "OVERRIDE":
return None, True, entered_scheme, "", (
"pi_Q_Override is populated; Quality_Scheme must be OVERRIDE in accordance with the configuration guide."
)
if override <= 0:
return None, True, entered_scheme, "", "pi_Q_Override must be greater than zero."
evidence = text(row.get("Quality_Evidence"))
if not evidence:
add_issue(issues, "WARNING", item_id, "Quality_Evidence", "A pi_Q override has no supporting evidence text.", excel_row)
return override, True, "OVERRIDE", "Explicit documented pi_Q override.", None
if entered_scheme == "OVERRIDE":
return None, True, "OVERRIDE", "", "Quality_Scheme=OVERRIDE requires pi_Q_Override."
construction = f"{text(row.get('Part_Group'))} {text(row.get('Description'))}"
inferred = infer_quality_scheme(section, construction)
# A-5 combines Schottky barrier and point-contact generic rates, but A-6
# gives them different quality routes. The combined database label alone
# cannot establish which device is installed.
if section == "6.2" and canonical(row.get("Parts_Count_Rate_Source")) == RATE_DATABASE:
selected = rate_ref[
rate_ref["Rate_Key_N"].eq(text(row.get("Rate_Key")))
& rate_ref["Environment_N"].eq(norm(row.get("Environment")))
& rate_ref["Verification_N"].eq("VERIFIED")
]
if len(selected) == 1:
branch = norm(selected.iloc[0].get("Branch_or_Style"))
combined_branch = "SCHOTTKY" in branch and "POINT CONTACT" in branch
named_schottky = "SCHOTTKY" in norm(construction)
named_point_contact = "POINT CONTACT" in norm(construction).replace("-", " ")
if combined_branch and entered_scheme in {"", "AUTO"} and named_schottky == named_point_contact:
return None, True, "", "", (
"The selected rate combines Schottky and point-contact diodes. Identify exactly one type "
"in Part_Group/Description, or explicitly select DISCRETE_SCHOTTKY or "
"DISCRETE_HIGH_FREQ_DIODE using device evidence."
)
if not combined_branch and (named_schottky or entered_scheme == "DISCRETE_SCHOTTKY"):
return None, True, entered_scheme, "", (
"A Schottky quality route conflicts with the selected non-Schottky generic-rate branch."
)
scheme = inferred if entered_scheme in {"", "AUTO"} else entered_scheme
if not scheme:
return None, True, scheme, "", (
"The notebook cannot infer an Appendix A quality table for this section. "
"Select a supported Quality_Scheme or use a documented OVERRIDE."
)
compatible_schemes = {inferred} if inferred else set()
if section == "6.2":
compatible_schemes = {"DISCRETE_SCHOTTKY", "DISCRETE_HIGH_FREQ_DIODE"}
if entered_scheme not in {"", "AUTO"} and compatible_schemes and scheme not in compatible_schemes:
return None, True, scheme, "", (
f"Quality_Scheme={scheme} is incompatible with Handbook_Section={section}. "
f"Use {sorted(compatible_schemes)} or a documented OVERRIDE."
)
quality_class_raw = norm(row.get("Quality_Class"))
candidates = quality_ref[quality_ref["Quality_Table_N"].eq(scheme)].copy()
if scheme == "A11":
candidates = candidates[candidates["Section_N"].eq(norm(section))]
if candidates.empty:
return None, True, scheme, "", f"No quality-reference rows exist for scheme {scheme} and section {section}."
# A-11 N/A rows establish non-applicability; unity is an internal arithmetic identity, not a selected factor.
if scheme == "A11":
non_app = candidates[candidates["Applicable_N"].eq("NO")]
if not non_app.empty:
note = text(non_app.iloc[0].get("Notes")) or "Appendix A-11 marks pi_Q N/A."
normalized_raw = QUALITY_ALIASES.get(quality_class_raw, quality_class_raw)
if normalized_raw and normalized_raw != "N/A":
add_issue(
issues, "WARNING", item_id, "Quality_Class",
f"Quality_Class {normalized_raw!r} is ignored because Appendix A-11 marks pi_Q N/A for Section {section}.",
excel_row,
)
return 1.0, False, scheme, note, None
supported = sorted(candidates["Quality_Class"].dropna().astype(str).unique().tolist())
quality_class, alias_note = resolve_quality_class_alias(
row.get("Quality_Class"),
scheme,
section,
row.get("Part_Group"),
row.get("Description"),
supported,
)
# Appendix A-11 footnote: the inductive-device ER factor is only for MIL-C-39010 coils.
if scheme == "A11" and quality_class == "ESTABLISHED" and section in {"11.1", "11.2"}:
evidence = f"{text(row.get('Quality_Evidence'))} {construction}"
if section != "11.2" or not re.search(r"\bMIL[ -]*C[ -]*39010\b", evidence, re.IGNORECASE):
return None, True, scheme, "", (
"Appendix A-11 limits inductive-device ESTABLISHED quality (pi_Q=0.25) to "
"MIL-C-39010 coils in Section 11.2; identify that procurement basis in Quality_Evidence."
)
if canonical(row.get("Parts_Count_Rate_Source")) == RATE_DATABASE:
selected = rate_ref[rate_ref["Rate_Key_N"].eq(text(row.get("Rate_Key")))]
if selected["Branch_or_Style"].map(norm).str.contains("VARIABLE", regex=False).any():
return None, True, scheme, "", "The selected variable MIL-C-15305 coil is not eligible for MIL-C-39010 ER quality."
# Discrete semiconductor tables have no universal handbook "unknown" quality class.
# Allow calculation to continue through LOWER, but force a reviewer-visible warning
# unless plastic construction was explicit and therefore routed to PLASTIC.
raw_quality_token = norm(row.get("Quality_Class"))
if (
scheme.startswith("DISCRETE_")
and raw_quality_token in GENERIC_UNKNOWN_QUALITY
and quality_class == "LOWER"
):
add_issue(
issues,
"WARNING",
item_id,
"Quality_Class",
(
f"Quality_Class {raw_quality_token!r} was routed to LOWER for {scheme}. "
"MIL-HDBK-217F does not publish a universal unknown-quality discrete-semiconductor class; "
"verify procurement/package evidence and select PLASTIC explicitly when applicable."
),
excel_row,
)
if scheme == "MICROCIRCUIT" and quality_class == "CUSTOM":
value, note, error = custom_quality_factor(row.get("Custom_Screening_Points"))
if alias_note and note:
note = f"{alias_note} {note}"
elif alias_note:
note = alias_note
return value, True, scheme, note, error
if not quality_class:
return None, True, scheme, "", f"Quality_Class is required for quality scheme {scheme}."
match = candidates[candidates["Class_N"].eq(quality_class)]
if len(match) == 0:
return None, True, scheme, "", (
f"Quality class {quality_class!r} is not supported by scheme {scheme}. Supported values: {supported}"
)
if len(match) > 1:
return None, True, scheme, "", f"Duplicate quality-reference rows exist for {scheme}/{section}/{quality_class}."
rec = match.iloc[0]
pi_q = numeric(rec.get("pi_Q_N"))
if pi_q is None or pi_q <= 0:
return None, True, scheme, "", f"Quality reference has no valid positive pi_Q for {scheme}/{quality_class}."
note = text(rec.get("Notes"))
if alias_note:
note = f"{alias_note} {note}".strip()
return pi_q, True, scheme, note, None
def lookup_generic_rate(
row: pd.Series,
section: str,
environment: str,
) -> Tuple[Optional[float], Dict[str, Any], str, Optional[str]]:
"""Resolve one exact VERIFIED Rate_Key + Environment cell."""
rate_key = text(row.get("Rate_Key"))
if not rate_key:
return None, {}, "", "RATE_DATABASE requires Rate_Key."
match = rate_ref[
rate_ref["Rate_Key_N"].eq(rate_key)
& rate_ref["Environment_N"].eq(environment)
& rate_ref["Verification_N"].eq("VERIFIED")
]
if len(match) == 0:
return None, {}, "", (
f"No VERIFIED Rate_Database cell exists for Rate_Key={rate_key!r}, Environment={environment!r}."
)
if len(match) > 1:
return None, {}, "", (
f"Duplicate VERIFIED Rate_Database cells exist for Rate_Key={rate_key!r}, Environment={environment!r}."
)
rec = match.iloc[0]
value = numeric(rec.get("lambda_g_N"))
if value is None:
return None, {}, "", "The VERIFIED Rate_Database cell has no numerical lambda_g."
if value < 0:
return None, {}, "", "Generic failure rate cannot be negative."
if text(rec.get("Section_N")) != section:
return None, {}, "", (
f"Rate_Database Section {text(rec.get('Section_N'))!r} does not match BOM Handbook_Section {section!r}."
)
source = {
"Source_Page": text(rec.get("Source_Page")),
"Source_Row": text(rec.get("Source_Row")),
"Source_Column": text(rec.get("Source_Column")),
"Rate_Verified_By": text(rec.get("Verified_By")),
"Rate_Verification_Date": rec.get("Verification_Date"),
"Rate_Database_Row": int(rec.get("_Excel_Row")) if numeric(rec.get("_Excel_Row")) is not None else None,
}
note = (
f"Rate database lookup: Rate_Key={rate_key}, Environment={environment}, "
f"lambda_g={value:.12g}; verified by {source['Rate_Verified_By'] or 'UNSPECIFIED'}."
)
return value, source, note, None
def run_engine_self_tests() -> pd.DataFrame:
"""Deterministic arithmetic checks independent of project data."""
checks: List[Tuple[str, bool, str]] = []
pi_l_01, _, _ = microcircuit_learning_factor(0.1)
checks.append(("Microcircuit learning endpoint Y=0.1", pi_l_01 == 2.0, f"Calculated {pi_l_01}"))
pi_l_2, _, _ = microcircuit_learning_factor(2.0)
checks.append(("Microcircuit learning endpoint Y=2.0", pi_l_2 == 1.0, f"Calculated {pi_l_2}"))
pi_q_80, _, _ = custom_quality_factor(80)
checks.append(("Custom screening points=80", abs((pi_q_80 or 0) - 3.0875) < 1e-12, f"Calculated {pi_q_80}"))
q, err = whole_quantity(25)
checks.append(("Whole-number quantity", q == 25 and err is None, f"Quantity={q}, error={err}"))
line = 10 * 0.0036 * 1.0 * 1.0
checks.append(("Known line arithmetic", abs(line - 0.036) < 1e-12, f"Calculated {line}"))
frame = pd.DataFrame(checks, columns=["Check", "Passed", "Detail"])
if not frame["Passed"].all():
failed = frame.loc[~frame["Passed"], "Check"].tolist()
raise AssertionError(f"Engine self-test failure: {failed}")
return frame
self_tests = run_engine_self_tests()
project_issues: List[Issue] = []
REQUIRED_PROJECT_PARAMETERS = [
"Project_ID", "Project_Name", "Prepared_By", "Calculation_Date",
"Assembly_Part_Number", "BOM_Revision", "Equipment_Boundary",
"Strict_Mode", "Output_File_Name",
]
for parameter in REQUIRED_PROJECT_PARAMETERS:
if not text(project.get(parameter)):
add_issue(project_issues, "ERROR", "PROJECT", parameter, f"Project_Setup parameter {parameter} is required.")
strict_mode, strict_error = parse_bool(project.get("Strict_Mode"))
if strict_error:
add_issue(project_issues, "ERROR", "PROJECT", "Strict_Mode", strict_error)
strict_mode = True
output_name = text(project.get("Output_File_Name")) or "PCMTBF_Results.xlsx"
output_path_value = Path(output_name)
if output_path_value.name != output_name or any(ch in output_name for ch in '/\\:\x00'):
add_issue(project_issues, "ERROR", "PROJECT", "Output_File_Name", "Enter a filename only, not a directory path.")
if output_path_value.suffix.lower() != ".xlsx":
add_issue(project_issues, "ERROR", "PROJECT", "Output_File_Name", "Output_File_Name must end in .xlsx.")
if output_path_value.name.lower() == INPUT_WORKBOOK.name.lower():
add_issue(project_issues, "ERROR", "PROJECT", "Output_File_Name", "The results filename must differ from the input workbook filename.")
reference_environment = norm(project.get("Default_Environment_Reference"))
if reference_environment and reference_environment not in ENVIRONMENTS:
add_issue(
project_issues, "ERROR", "PROJECT", "Default_Environment_Reference",
f"Use one recognized environment symbol: {sorted(ENVIRONMENTS)}."
)
comparison_rate = numeric(project.get("Detailed_Part_Stress_Total_lambda"))
comparison_source = text(project.get("Detailed_Part_Stress_Source"))
if text(project.get("Detailed_Part_Stress_Total_lambda")) and comparison_rate is None:
add_issue(
project_issues, "ERROR", "PROJECT", "Detailed_Part_Stress_Total_lambda",
"The populated comparison total must be a finite numeric value."
)
if comparison_rate is not None and comparison_rate <= 0:
add_issue(
project_issues, "ERROR", "PROJECT", "Detailed_Part_Stress_Total_lambda",
"The optional detailed Part Stress comparison rate must be greater than zero."
)
if comparison_rate is not None and not comparison_source:
add_issue(
project_issues, "WARNING", "PROJECT", "Detailed_Part_Stress_Source",
"A Part Stress comparison total was entered without a source calculation reference."
)
# Validate nonblank Rate_Database records.
rate_statuses = set(rate_ref["Verification_N"].dropna().astype(str).tolist())
for status in sorted(s for s in rate_statuses if s and s not in VALID_VERIFICATION_STATUSES):
add_issue(project_issues, "WARNING", "RATE_DATABASE", "Verification_Status", f"Unrecognized status {status!r} is ignored.")
verified = rate_ref[rate_ref["Verification_N"].eq("VERIFIED")].copy()
duplicate_verified = verified.duplicated(subset=["Rate_Key_N", "Environment_N"], keep=False)
for _, rec in verified[duplicate_verified].iterrows():
add_issue(
project_issues, "ERROR", "RATE_DATABASE", "Rate_Key + Environment",
f"Duplicate VERIFIED cell for {rec['Rate_Key_N']!r}/{rec['Environment_N']!r}.",
int(rec["_Excel_Row"]),
)
for _, rec in verified.iterrows():
excel_row = int(rec["_Excel_Row"])
key = text(rec.get("Rate_Key_N"))
env = norm(rec.get("Environment_N"))
lam = numeric(rec.get("lambda_g_N"))
label = key or f"row {excel_row}"
if not key:
add_issue(project_issues, "ERROR", "RATE_DATABASE", "Rate_Key", "A VERIFIED row requires Rate_Key.", excel_row)
if env not in ENVIRONMENTS:
add_issue(project_issues, "ERROR", "RATE_DATABASE", "Environment", f"Invalid environment {env!r} for {label}.", excel_row)
if lam is None or lam < 0:
add_issue(project_issues, "ERROR", "RATE_DATABASE", "lambda_g", f"VERIFIED row {label} requires a nonnegative numerical lambda_g.", excel_row)
for field in ["Source_Page", "Source_Row", "Source_Column", "Verified_By", "Verification_Date"]:
if not text(rec.get(field)):
add_issue(project_issues, "ERROR", "RATE_DATABASE", field, f"VERIFIED row {label} is missing {field}.", excel_row)
if text(rec.get("Source_Column")) and norm(rec.get("Source_Column")) != env:
add_issue(
project_issues, "WARNING", "RATE_DATABASE", "Source_Column",
f"Source_Column {text(rec.get('Source_Column'))!r} does not match Environment {env!r} for {label}.",
excel_row,
)
# Validate the quality table itself.
quality_key_cols = ["Quality_Table_N", "Section_N", "Class_N"]
quality_eligible = quality_ref[quality_ref["Applicable_N"].isin(["YES", "NO", "FORMULA"])]
quality_duplicate = quality_eligible.duplicated(
subset=quality_key_cols, keep=False
)
for _, rec in quality_eligible[quality_duplicate].iterrows():
add_issue(
project_issues, "ERROR", "QUALITY_FACTORS", "Reference key",
f"Duplicate quality row for {rec['Quality_Table_N']}/{rec['Section_N']}/{rec['Class_N']}."
)
for _, rec in quality_ref.iterrows():
applicable = norm(rec.get("Applicable_N"))
if applicable not in {"YES", "NO", "FORMULA"}:
add_issue(
project_issues, "ERROR", "QUALITY_FACTORS", "Applicable",
f"Quality row {rec['Quality_Table_N']}/{rec['Class_N']} requires Applicable=YES, NO, or FORMULA."
)
if applicable == "YES":
q = numeric(rec.get("pi_Q_N"))
if q is None or q <= 0:
add_issue(
project_issues, "ERROR", "QUALITY_FACTORS", "pi_Q",
f"Applicable quality row {rec['Quality_Table_N']}/{rec['Class_N']} requires positive pi_Q."
)
project_issue_df = pd.DataFrame([i.as_dict() for i in project_issues], columns=["Severity", "Item_ID", "Excel_Row", "Field", "Message"])
DETAIL_COLUMNS = ['Input_Row', 'Item_ID', 'Assembly_PN', 'Ref_Des_or_Group', 'Manufacturer_PN', 'Description', 'Section', 'Part_Group', 'Environment', 'Quantity', 'Method', 'Rate_Source', 'Rate_Key', 'lambda_g', 'pi_Q', 'pi_L', 'lambda_per_item', 'lambda_line', 'Contribution_Percent', 'Quality_Applicable', 'Resolved_Quality_Scheme', 'Quality_Note', 'Learning_Note', 'Rate_Note', 'Calculation_Equation', 'Calculation_Notes', 'Source_Page', 'Source_Row', 'Source_Column', 'Source_Traceability', 'Rate_Verified_By', 'Rate_Verification_Date', 'Rate_Database_Row', 'Status', 'Warnings', 'Notes']
def validate_include_values(bom: pd.DataFrame, issues: List[Issue]) -> None:
"""Flag populated rows whose Include value is not YES or NO."""
business_cols = [c for c in BOM_COLUMNS if c != "Include"]
populated = bom[business_cols].notna().any(axis=1)
values = bom["Include"].map(norm)
bad = bom[populated & ~values.isin({"YES", "NO"})]
for _, row in bad.iterrows():
add_issue(
issues, "ERROR", text(row.get("Item_ID")) or "UNIDENTIFIED",
"Include", "A populated BOM row must use Include=YES or Include=NO.", int(row["_Excel_Row"])
)
def calculate_appendix_a(
bom: pd.DataFrame,
) -> Tuple[pd.DataFrame, pd.DataFrame]:
records: List[Dict[str, Any]] = []
row_issues: List[Issue] = []
validate_include_values(bom, row_issues)
active = bom[bom["Include"].map(norm).eq("YES")].copy()
if active.empty:
add_issue(row_issues, "ERROR", "PROJECT", "BOM_Input", "No BOM populations are included; enter at least one valid Include=YES row.")
# Exact duplicate controls. Partial overlaps within text ranges still require manual review.
item_id_counts = active["Item_ID"].map(text).value_counts()
ref_group_counts = active["Ref_Des_or_Group"].map(text)
ref_group_counts = ref_group_counts[ref_group_counts.ne("")].value_counts()
for _, row in active.iterrows():
excel_row = int(row["_Excel_Row"])
item_id = text(row.get("Item_ID"))
item_label = item_id or f"EXCEL_ROW_{excel_row}"
description = text(row.get("Description"))
section = text(row.get("Handbook_Section"))
part_group = text(row.get("Part_Group"))
environment = norm(row.get("Environment"))
method = canonical(row.get("Prediction_Method"))
rate_source = canonical(row.get("Parts_Count_Rate_Source"))
errors: List[Tuple[str, str]] = []
warnings: List[str] = []
if not item_id:
errors.append(("Item_ID", "Item_ID is required."))
elif item_id_counts.get(item_id, 0) > 1:
errors.append(("Item_ID", "Duplicate included Item_ID violates one-population/one-line control."))
ref_group = text(row.get("Ref_Des_or_Group"))
if ref_group and ref_group_counts.get(ref_group, 0) > 1:
errors.append(("Ref_Des_or_Group", "Duplicate active reference-designator/group text indicates an overlapping population."))
if not ref_group:
warnings.append("Ref_Des_or_Group is blank; physical-population traceability is reduced.")
if not description:
warnings.append("Description is blank.")
if not section:
errors.append(("Handbook_Section", "Handbook_Section is required."))
if environment not in ENVIRONMENTS:
errors.append(("Environment", f"Use one exact environment symbol from {sorted(ENVIRONMENTS)}."))
quantity, quantity_error = whole_quantity(row.get("Quantity"))
if quantity_error:
errors.append(("Quantity", quantity_error))
quantity = 0
elif quantity == 0:
warnings.append("Quantity is zero; the line contributes zero.")
record: Dict[str, Any] = {
"Input_Row": excel_row,
"Item_ID": item_id,
"Assembly_PN": text(row.get("Assembly_PN")),
"Ref_Des_or_Group": ref_group,
"Manufacturer_PN": text(row.get("Manufacturer_PN")),
"Description": description,
"Section": section,
"Part_Group": part_group,
"Environment": environment,
"Quantity": quantity,
"Method": method,
"Rate_Source": rate_source,
"Rate_Key": text(row.get("Rate_Key")),
"lambda_g": np.nan,
"pi_Q": np.nan,
"pi_L": np.nan,
"lambda_per_item": np.nan,
"lambda_line": np.nan,
"Contribution_Percent": np.nan,
"Quality_Applicable": "",
"Resolved_Quality_Scheme": "",
"Quality_Note": "",
"Learning_Note": "",
"Rate_Note": "",
"Calculation_Equation": "",
"Calculation_Notes": "",
"Source_Page": text(row.get("Source_Page")),
"Source_Row": text(row.get("Source_Row")),
"Source_Column": text(row.get("Source_Column")),
"Source_Traceability": source_string(row.get("Source_Page"), row.get("Source_Row"), row.get("Source_Column")),
"Rate_Verified_By": "",
"Rate_Verification_Date": None,
"Rate_Database_Row": None,
"Status": "PENDING",
"Warnings": "",
"Notes": text(row.get("Notes")),
}
if method not in VALID_METHODS:
errors.append(("Prediction_Method", f"Use one of {sorted(VALID_METHODS)}."))
if not errors and method == METHOD_PART_STRESS:
if is_hybrid_microcircuit(section, part_group) is False and rate_source:
warnings.append("Parts_Count_Rate_Source is ignored for a Part Stress replacement.")
if text(row.get("Rate_Key")):
warnings.append("Rate_Key is ignored for a Part Stress replacement.")
if numeric(row.get("Direct_lambda_g")) is not None:
warnings.append("Direct_lambda_g is ignored for a Part Stress replacement.")
if numeric(row.get("pi_Q_Override")) is not None or text(row.get("Quality_Class")):
warnings.append("Appendix A quality fields are not reapplied to a final Part Stress rate.")
if numeric(row.get("Years_In_Production")) is not None:
warnings.append("Years_In_Production is ignored for a Part Stress replacement.")
lam_ps = numeric(row.get("Part_Stress_lambda"))
if lam_ps is None:
errors.append(("Part_Stress_lambda", "PART_STRESS_REPLACEMENT requires a numerical final per-item Part Stress rate."))
elif lam_ps < 0:
errors.append(("Part_Stress_lambda", "Part_Stress_lambda cannot be negative."))
else:
if lam_ps == 0:
warnings.append("Part_Stress_lambda is zero; verify that zero is the intended modeled contribution.")
if quantity and quantity > 1:
warnings.append("Part_Stress_lambda is treated as a per-item rate and multiplied by Quantity.")
if not record["Source_Page"] or not record["Source_Row"]:
warnings.append("Part Stress replacement should retain a governing section/calculation and final-rate reference.")
record["Rate_Source"] = METHOD_PART_STRESS
record["lambda_per_item"] = lam_ps
record["lambda_line"] = quantity * lam_ps
record["Quality_Applicable"] = "NO - final Part Stress rate"
record["Resolved_Quality_Scheme"] = "NOT REAPPLIED"
record["Quality_Note"] = "Quality and learning factors are already contained in the detailed final rate and are not reapplied."
record["Learning_Note"] = "Not applicable to the replacement-line arithmetic."
record["Rate_Note"] = f"Detailed per-item Part Stress rate={lam_ps:.12g}."
record["Calculation_Equation"] = "lambda_line = N * lambda_part_stress"
record["Calculation_Notes"] = (
f"N={quantity}; lambda_PS={lam_ps:.12g}; "
f"lambda_line={record['lambda_line']:.12g} {RATE_UNITS}."
)
elif not errors and method == METHOD_PARTS_COUNT:
if is_hybrid_microcircuit(section, part_group):
errors.append((
"Handbook_Section",
"Appendix A supplies no generic hybrid-microcircuit rate. Use PART_STRESS_REPLACEMENT with Section 5.5 traceability."
))
if rate_source not in VALID_RATE_SOURCES:
errors.append(("Parts_Count_Rate_Source", f"PARTS_COUNT requires one of {sorted(VALID_RATE_SOURCES)}."))
if numeric(row.get("Part_Stress_lambda")) is not None:
warnings.append("Part_Stress_lambda is ignored on a Parts Count row; remove it to avoid method ambiguity.")
lam_g: Optional[float] = None
source_from_db: Dict[str, Any] = {}
rate_note = ""
if not errors and rate_source == RATE_DATABASE:
if numeric(row.get("Direct_lambda_g")) is not None:
warnings.append("Direct_lambda_g is ignored because RATE_DATABASE is selected.")
lam_g, source_from_db, rate_note, rate_error = lookup_generic_rate(row, section, environment)
if rate_error:
errors.append(("Rate_Key", rate_error))
elif not errors and rate_source == DIRECT_RATE:
if text(row.get("Rate_Key")):
warnings.append("Rate_Key is ignored because DIRECT_LAMBDA_G is selected.")
lam_g = numeric(row.get("Direct_lambda_g"))
if lam_g is None:
errors.append(("Direct_lambda_g", "DIRECT_LAMBDA_G requires a numerical generic rate."))
elif lam_g < 0:
errors.append(("Direct_lambda_g", "Direct_lambda_g cannot be negative."))
else:
if lam_g == 0:
warnings.append("Direct_lambda_g is zero; confirm that the controlled source cell is truly zero and not blank/N/A.")
missing_trace = [
field for field in ["Source_Page", "Source_Row", "Source_Column"]
if not text(row.get(field))
]
if missing_trace:
warnings.append(f"Direct lambda_g is missing source traceability fields: {missing_trace}.")
rate_note = f"Direct controlled generic rate lambda_g={lam_g:.12g}."
pi_q: Optional[float] = None
q_applicable = True
resolved_scheme = ""
quality_note = ""
if not errors:
pi_q, q_applicable, resolved_scheme, quality_note, quality_error = resolve_quality(
row, section, row_issues, item_label, excel_row
)
if quality_error:
errors.append(("Quality_Class", quality_error))
elif q_applicable and not text(row.get("Quality_Evidence")):
warnings.append("No Quality_Evidence text was supplied for the selected pi_Q.")
pi_l: Optional[float] = 1.0
learning_note = "Non-microcircuit line; pi_L=1.0 and no learning multiplier is applied."
microcircuit = is_microcircuit(section)
if not errors and microcircuit:
pi_l, learning_note, learning_error = microcircuit_learning_factor(row.get("Years_In_Production"))
if learning_error:
errors.append(("Years_In_Production", learning_error))
elif not errors and numeric(row.get("Years_In_Production")) is not None:
warnings.append("Years_In_Production is ignored because this is not a Section 5 Parts Count row.")
if not errors:
assert lam_g is not None and pi_q is not None and pi_l is not None
record["lambda_g"] = lam_g
record["pi_Q"] = pi_q
record["pi_L"] = pi_l
record["lambda_per_item"] = lam_g * pi_q
if microcircuit:
record["lambda_per_item"] *= pi_l
record["lambda_line"] = quantity * record["lambda_per_item"]
record["Quality_Applicable"] = "YES" if q_applicable else "NO"
record["Resolved_Quality_Scheme"] = resolved_scheme
record["Quality_Note"] = quality_note
record["Learning_Note"] = learning_note
record["Rate_Note"] = rate_note
equation = "lambda_line = N * lambda_g"
if q_applicable:
equation += " * pi_Q"
if microcircuit:
equation += " * pi_L"
record["Calculation_Equation"] = equation
quality_trace = f"pi_Q={pi_q:.12g}; " if q_applicable else ""
learning_trace = f"pi_L={pi_l:.12g}; " if microcircuit else ""
record["Calculation_Notes"] = (
f"N={quantity}; lambda_g={lam_g:.12g}; {quality_trace}{learning_trace}"
f"lambda_per_item={record['lambda_per_item']:.12g}; "
f"lambda_line={record['lambda_line']:.12g} {RATE_UNITS}."
)
if source_from_db:
record.update(source_from_db)
record["Source_Traceability"] = source_string(
record.get("Source_Page"), record.get("Source_Row"), record.get("Source_Column")
)
if not errors and any(
not math.isfinite(float(record[field])) for field in ["lambda_per_item", "lambda_line"]
):
errors.append(("lambda_line", "Calculated failure rate is non-finite; check quantities, rates, and quality factors for overflow."))
if errors:
record["Status"] = "ERROR"
for field, message in errors:
add_issue(row_issues, "ERROR", item_label, field, message, excel_row)
else:
record["Status"] = "OK"
for warning in warnings:
add_issue(row_issues, "WARNING", item_label, "", warning, excel_row)
record["Warnings"] = " | ".join(warnings)
records.append(record)
detail = pd.DataFrame(records, columns=DETAIL_COLUMNS)
if detail.empty:
detail = detail.astype({field: "float64" for field in ["lambda_g", "pi_Q", "pi_L", "lambda_per_item", "lambda_line", "Contribution_Percent"]})
issues_df = pd.DataFrame([i.as_dict() for i in row_issues], columns=["Severity", "Item_ID", "Excel_Row", "Field", "Message"])
if not detail.empty:
valid_total = float(detail.loc[detail["Status"].eq("OK"), "lambda_line"].sum())
if math.isfinite(valid_total) and valid_total > 0:
detail["Contribution_Percent"] = np.where(
detail["Status"].eq("OK"), 100.0 * (detail["lambda_line"] / valid_total), np.nan
)
return detail, issues_df
detail, bom_issue_df = calculate_appendix_a(bom_raw)
# Demonstration content is intentionally visible but is not release-ready.
active_bom = bom_raw[bom_raw["Include"].map(norm).eq("YES")].copy()
demo_mask = pd.Series(False, index=active_bom.index)
for column in ["Description", "Notes", "Quality_Evidence", "Assembly_PN"]:
demo_mask |= active_bom[column].astype(str).str.contains("DEMO", case=False, na=False)
project_demo = any(
"DEMO" in norm(project.get(field))
for field in ["Project_ID", "Project_Name", "Assembly_Part_Number", "Equipment_Boundary", "Calculation_Notes"]
)
if demo_mask.any() or project_demo:
demo_issue = pd.DataFrame([{
"Severity": "WARNING",
"Item_ID": "PROJECT",
"Excel_Row": None,
"Field": "BOM_Input",
"Message": "Demonstration project identity, rows, or evidence remain. Replace project placeholders and replace or disable demonstration rows before release.",
}])
bom_issue_df = pd.concat([bom_issue_df, demo_issue], ignore_index=True)
issues = pd.concat([project_issue_df, bom_issue_df], ignore_index=True)
if not issues.empty:
severity_order = pd.Categorical(issues["Severity"], categories=["ERROR", "WARNING", "INFO"], ordered=True)
issues = issues.assign(_Severity_Order=severity_order).sort_values(
["_Severity_Order", "Excel_Row", "Item_ID"], na_position="last"
).drop(columns=["_Severity_Order"]).reset_index(drop=True)
error_count = int((issues["Severity"] == "ERROR").sum()) if not issues.empty else 0
warning_count = int((issues["Severity"] == "WARNING").sum()) if not issues.empty else 0
valid = detail[detail["Status"].eq("OK")].copy() if not detail.empty else detail.copy()
valid_row_subtotal = float(valid["lambda_line"].sum()) if not valid.empty else 0.0
aggregate_finite = math.isfinite(valid_row_subtotal)
if not aggregate_finite:
issues = pd.concat([issues, pd.DataFrame([{
"Severity": "ERROR", "Item_ID": "PROJECT", "Excel_Row": None,
"Field": "Reportable_Total_lambda", "Message": "The summed failure rate is non-finite; no reportable result or MTBF is available."
}])], ignore_index=True)
error_count += 1
if not aggregate_finite:
calculation_status = "INVALID - NON-FINITE AGGREGATE"
reportable_lambda = np.nan
reportable = False
elif error_count > 0 and strict_mode:
calculation_status = "INVALID - CORRECT ERRORS BEFORE RELEASE"
reportable_lambda = np.nan
reportable = False
elif error_count > 0 and not strict_mode:
calculation_status = "PARTIAL - ERRORS EXCLUDED; NOT RELEASE-READY"
reportable_lambda = valid_row_subtotal
reportable = True
elif warning_count > 0:
calculation_status = "VALID - REVIEW WARNINGS"
reportable_lambda = valid_row_subtotal
reportable = True
else:
calculation_status = "VALID - NO ERRORS"
reportable_lambda = valid_row_subtotal
reportable = True
if reportable and reportable_lambda > 0:
predicted_mtbf = 1_000_000.0 / reportable_lambda
elif reportable and reportable_lambda == 0:
predicted_mtbf = np.nan
zero_issue = pd.DataFrame([{
"Severity": "WARNING", "Item_ID": "PROJECT", "Excel_Row": None,
"Field": "Reportable_Total_lambda",
"Message": "The reportable aggregate is zero. A finite predicted MTBF is not reported; verify completeness and zero-rate bases.",
}])
issues = pd.concat([issues, zero_issue], ignore_index=True)
warning_count += 1
if error_count == 0:
calculation_status = "VALID - REVIEW WARNINGS"
else:
predicted_mtbf = np.nan
if reportable and reportable_lambda > 0 and not math.isfinite(predicted_mtbf):
issues = pd.concat([issues, pd.DataFrame([{
"Severity": "ERROR", "Item_ID": "PROJECT", "Excel_Row": None,
"Field": "Predicted_MTBF_hours", "Message": "MTBF reciprocal overflowed; no finite MTBF can be reported."
}])], ignore_index=True)
error_count += 1
predicted_mtbf = np.nan
calculation_status = "INVALID - NON-FINITE MTBF"
release_ready = (
error_count == 0
and not demo_mask.any()
and not project_demo
and not detail.empty
and reportable
and reportable_lambda > 0
and math.isfinite(predicted_mtbf)
)
release_status = "RELEASE-READY AFTER ENGINEERING REVIEW" if release_ready else "NOT RELEASE-READY"
summary = {
"Calculation_Status": calculation_status,
"Release_Status": release_status,
"Strict_Mode": bool(strict_mode),
"Project_ID": text(project.get("Project_ID")),
"Project_Name": text(project.get("Project_Name")),
"Prepared_By": text(project.get("Prepared_By")),
"Calculation_Date": project.get("Calculation_Date"),
"Assembly_Part_Number": text(project.get("Assembly_Part_Number")),
"BOM_Revision": text(project.get("BOM_Revision")),
"Equipment_Boundary": text(project.get("Equipment_Boundary")),
"Included_Populations": int(len(detail)),
"Valid_Populations": int(len(valid)),
"Total_Physical_Quantity": int(valid["Quantity"].sum()) if not valid.empty else 0,
"Valid_Line_Subtotal_lambda": valid_row_subtotal,
"Reportable_Total_lambda": reportable_lambda,
"Predicted_MTBF_hours": predicted_mtbf,
"Error_Count": error_count,
"Warning_Count": warning_count,
"Units": RATE_UNITS,
"Input_Workbook": INPUT_WORKBOOK.name,
"Input_Workbook_SHA256": file_sha256,
"Engine_Version": ENGINE_VERSION,
"Notebook": NOTEBOOK_NAME,
"Calculated_UTC": datetime.now(timezone.utc).isoformat(timespec="seconds"),
}
detail_display_columns = [
"Input_Row", "Item_ID", "Ref_Des_or_Group", "Description", "Section", "Part_Group",
"Environment", "Quantity", "Method", "Rate_Source", "Rate_Key", "lambda_g",
"Resolved_Quality_Scheme", "pi_Q", "Quality_Applicable", "pi_L",
"lambda_per_item", "lambda_line", "Contribution_Percent", "Status", "Warnings",
"Calculation_Equation", "Calculation_Notes", "Source_Traceability",
"Rate_Verified_By", "Rate_Verification_Date", "Rate_Database_Row",
]
def subtotal_table(detail_df: pd.DataFrame, by: str) -> pd.DataFrame:
valid_df = detail_df[detail_df["Status"].eq("OK")].copy()
if valid_df.empty:
return pd.DataFrame(columns=[by, "Quantity", "lambda_line", "Percent"])
out = (
valid_df.groupby(by, dropna=False, as_index=False)
.agg(Quantity=("Quantity", "sum"), lambda_line=("lambda_line", "sum"))
.sort_values("lambda_line", ascending=False)
.reset_index(drop=True)
)
total = float(out["lambda_line"].sum())
out["Percent"] = 100.0 * out["lambda_line"] / total if total > 0 else np.nan
return out
by_method = subtotal_table(detail, "Method")
by_section = subtotal_table(detail, "Section")
by_environment = subtotal_table(detail, "Environment")
part_stress_total = numeric(project.get("Detailed_Part_Stress_Total_lambda"))
comparison: Dict[str, Any] = {}
if part_stress_total is None:
print("No detailed Part Stress total was supplied. Comparison is skipped.")
elif part_stress_total <= 0:
print("The detailed Part Stress total must be greater than zero.")
elif error_count > 0:
print("Correct all calculation errors before using the Parts Count / Part Stress comparison.")
elif not reportable or not math.isfinite(float(reportable_lambda)) or reportable_lambda <= 0:
print("A positive reportable Appendix A result is required before comparison.")
else:
comparison = {
"Parts_Count_lambda": float(reportable_lambda),
"Part_Stress_lambda": float(part_stress_total),
"Lambda_Difference": float(reportable_lambda - part_stress_total),
"Parts_Count_to_Part_Stress_Ratio": float(reportable_lambda / part_stress_total),
"Percent_Difference_vs_Part_Stress": float(
(reportable_lambda - part_stress_total) / part_stress_total * 100.0
),
"Parts_Count_MTBF_hours": float(1_000_000.0 / reportable_lambda),
"Part_Stress_MTBF_hours": float(1_000_000.0 / part_stress_total),
"Part_Stress_Source": text(project.get("Detailed_Part_Stress_Source")),
"Boundary_Qualification": "Analyst shall confirm both totals represent the exact same physical boundary and operating basis.",
}
def replace_sheet(workbook, sheet_name: str):
"""Delete an existing output sheet and recreate it at the same tab position."""
if sheet_name in workbook.sheetnames:
index = workbook.sheetnames.index(sheet_name)
workbook.remove(workbook[sheet_name])
return workbook.create_sheet(sheet_name, index)
return workbook.create_sheet(sheet_name)
def excel_value(value: Any) -> Any:
"""Convert pandas/numpy values into openpyxl-safe scalar values."""
if value is None:
return None
if isinstance(value, (np.integer,)):
return int(value)
if isinstance(value, (np.floating,)):
value = float(value)
if isinstance(value, float) and (math.isnan(value) or math.isinf(value)):
return None
if isinstance(value, pd.Timestamp):
return value.to_pydatetime()
if pd.isna(value):
return None
return value
DARK = "404040"
DARKER = "1F1F1F"
WHITE = "FFFFFF"
LIGHT_GRAY = "E7E6E6"
PALE_RED = "F4CCCC"
PALE_YELLOW = "FFF2CC"
PALE_GREEN = "D9EAD3"
BORDER_COLOR = "A6A6A6"
THIN = Side(style="thin", color=BORDER_COLOR)
def style_title(cell) -> None:
cell.fill = PatternFill("solid", fgColor=DARKER)
cell.font = Font(color=WHITE, bold=True, size=15)
cell.alignment = Alignment(horizontal="left", vertical="center")
def style_header(cell) -> None:
cell.fill = PatternFill("solid", fgColor=DARK)
cell.font = Font(color=WHITE, bold=True)
cell.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
cell.border = Border(top=THIN, bottom=THIN, left=THIN, right=THIN)
def style_label(cell) -> None:
cell.fill = PatternFill("solid", fgColor=LIGHT_GRAY)
cell.font = Font(bold=True)
cell.alignment = Alignment(vertical="top", wrap_text=True)
cell.border = Border(top=THIN, bottom=THIN, left=THIN, right=THIN)
def set_reasonable_widths(ws, frame: pd.DataFrame, *, max_width: int = 58) -> None:
for col_index, col_name in enumerate(frame.columns, start=1):
values = [str(col_name)] + [
str(v) for v in frame[col_name].head(250).tolist() if excel_value(v) is not None
]
width = min(max(len(v) for v in values) + 2, max_width)
ws.column_dimensions[get_column_letter(col_index)].width = max(width, 10)
def write_frame(ws, frame: pd.DataFrame, *, header_row: int = 3, start_col: int = 1) -> None:
for offset, col_name in enumerate(frame.columns, start=start_col):
ws.cell(row=header_row, column=offset, value=str(col_name))
style_header(ws.cell(row=header_row, column=offset))
for row_offset, values in enumerate(frame.itertuples(index=False, name=None), start=header_row + 1):
for col_offset, value in enumerate(values, start=start_col):
cell = ws.cell(row=row_offset, column=col_offset, value=excel_value(value))
cell.alignment = Alignment(vertical="top", wrap_text=True)
cell.border = Border(bottom=THIN)
output_errors = [i.message for i in project_issues if i.severity == "ERROR" and i.field == "Output_File_Name"]
if output_errors:
raise ValueError("Unsafe results filename; export stopped before writing: " + " | ".join(output_errors))
OUTPUT_WORKBOOK = Path(output_dir) / output_name
if OUTPUT_WORKBOOK.resolve() == INPUT_WORKBOOK.resolve() or (
OUTPUT_WORKBOOK.exists() and OUTPUT_WORKBOOK.samefile(INPUT_WORKBOOK)
):
raise ValueError("The results file must not refer to the input workbook, including links to the same file.")
if OUTPUT_WORKBOOK.exists() and not allow_overwrite:
raise FileExistsError(
f"Results workbook already exists: {OUTPUT_WORKBOOK}. "
"Set allow_overwrite=True or change Project_Setup!Output_File_Name."
)
shutil.copy2(INPUT_WORKBOOK, OUTPUT_WORKBOOK)
owb = load_workbook(OUTPUT_WORKBOOK)
# ---------------- Summary_Output ----------------
ws = replace_sheet(owb, "Summary_Output")
ws.merge_cells("A1:K1")
ws["A1"] = "MIL-HDBK-217F Appendix A Parts Count - Calculation Summary"
style_title(ws["A1"])
ws.row_dimensions[1].height = 28
summary_rows = [
("Calculation Status", summary["Calculation_Status"], "Errors block a reportable total when Strict_Mode is TRUE."),
("Release Status", summary["Release_Status"], "Demonstration content or unresolved errors prevent release readiness."),
("Project ID", summary["Project_ID"], ""),
("Project Name", summary["Project_Name"], ""),
("Prepared By", summary["Prepared_By"], ""),
("Calculation Date", summary["Calculation_Date"], ""),
("Assembly Part Number", summary["Assembly_Part_Number"], ""),
("BOM Revision", summary["BOM_Revision"], ""),
("Equipment Boundary", summary["Equipment_Boundary"], "Must match any comparison calculation boundary."),
("Included Populations", summary["Included_Populations"], "Active non-overlapping BOM populations."),
("Valid Populations", summary["Valid_Populations"], "Rows that passed calculation validation."),
("Total Physical Quantity", summary["Total_Physical_Quantity"], "Sum of quantities on valid rows."),
("Valid-Row Subtotal lambda", summary["Valid_Line_Subtotal_lambda"], RATE_UNITS),
("Reportable Total lambda", summary["Reportable_Total_lambda"], RATE_UNITS),
("Predicted MTBF", summary["Predicted_MTBF_hours"], "hours; reciprocal of the unrounded reportable total"),
("Error Count", summary["Error_Count"], ""),
("Warning Count", summary["Warning_Count"], ""),
("Input Workbook", summary["Input_Workbook"], ""),
("Input Workbook SHA-256", summary["Input_Workbook_SHA256"], "Identifies the exact input file."),
("Notebook", summary["Notebook"], ""),
("Engine Version", summary["Engine_Version"], ""),
("Calculated UTC", summary["Calculated_UTC"], ""),
]
for col, value in enumerate(["Metric", "Value", "Units / Interpretation"], start=1):
ws.cell(row=3, column=col, value=value)
style_header(ws.cell(row=3, column=col))
for row_index, (metric, value, note) in enumerate(summary_rows, start=4):
ws.cell(row=row_index, column=1, value=metric)
ws.cell(row=row_index, column=2, value=excel_value(value))
ws.cell(row=row_index, column=3, value=note)
style_label(ws.cell(row=row_index, column=1))
for col in [2, 3]:
ws.cell(row=row_index, column=col).alignment = Alignment(vertical="top", wrap_text=True)
ws.cell(row=row_index, column=col).border = Border(bottom=THIN)
for row in range(4, 4 + len(summary_rows)):
metric = ws.cell(row=row, column=1).value
if metric in {"Valid-Row Subtotal lambda", "Reportable Total lambda"}:
ws.cell(row=row, column=2).number_format = "0.000000000000"
elif metric == "Predicted MTBF":
ws.cell(row=row, column=2).number_format = "#,##0.00"
elif metric == "Calculation Date":
ws.cell(row=row, column=2).number_format = "yyyy-mm-dd"
for row in [4, 5]:
value = str(ws.cell(row=row, column=2).value or "")
fill = PALE_RED if ("INVALID" in value or "NOT RELEASE" in value) else PALE_YELLOW if "WARNING" in value else PALE_GREEN
ws.cell(row=row, column=2).fill = PatternFill("solid", fgColor=fill)
ws.cell(row=row, column=2).font = Font(bold=True)
# Comparison block.
ws.merge_cells("E3:G3")
ws["E3"] = "Parts Count / Part Stress Comparison"
style_header(ws["E3"])
if comparison:
comparison_rows = [
("Parts Count lambda", comparison["Parts_Count_lambda"], RATE_UNITS),
("Part Stress lambda", comparison["Part_Stress_lambda"], RATE_UNITS),
("Lambda Difference", comparison["Lambda_Difference"], "PC - PS"),
("PC / PS Ratio", comparison["Parts_Count_to_Part_Stress_Ratio"], "dimensionless"),
("Percent Difference vs PS", comparison["Percent_Difference_vs_Part_Stress"], "%"),
("Parts Count MTBF", comparison["Parts_Count_MTBF_hours"], "hours"),
("Part Stress MTBF", comparison["Part_Stress_MTBF_hours"], "hours"),
("Part Stress Source", comparison["Part_Stress_Source"], ""),
("Boundary Qualification", comparison["Boundary_Qualification"], ""),
]
else:
comparison_rows = [("Status", "Not calculated", "Enter a positive detailed Part Stress total in Project_Setup.")]
for row_index, (metric, value, note) in enumerate(comparison_rows, start=4):
ws.cell(row=row_index, column=5, value=metric)
ws.cell(row=row_index, column=6, value=excel_value(value))
ws.cell(row=row_index, column=7, value=note)
style_label(ws.cell(row=row_index, column=5))
ws.cell(row=row_index, column=6).alignment = Alignment(vertical="top", wrap_text=True)
ws.cell(row=row_index, column=7).alignment = Alignment(vertical="top", wrap_text=True)
if isinstance(value, (int, float)) and not isinstance(value, bool):
ws.cell(row=row_index, column=6).number_format = "0.000000000000"
# Calculation notes block.
notes_start = 28
ws.merge_cells(start_row=notes_start, start_column=1, end_row=notes_start, end_column=7)
ws.cell(row=notes_start, column=1, value="Calculation and Release Notes")
style_header(ws.cell(row=notes_start, column=1))
method_notes = [
"Appendix A line: N * lambda_g with the applicable quality factor pi_Q. Only eligible microcircuit rows use the production learning factor pi_L.",
"Part Stress replacement line: lambda_line = N * final per-item Part Stress rate; Appendix A quality and learning factors are not reapplied.",
"Every active Item_ID must represent one non-overlapping population. Duplicate exact reference groups are treated as errors.",
"RATE_DATABASE requires one exact VERIFIED Rate_Key + Environment cell. Blank, N/A, unsupported, and unverified cells are unavailable, not zero.",
"DIRECT_LAMBDA_G requires source page, row, and environment-column traceability.",
"Predicted MTBF is calculated from the complete unrounded positive reportable total; it is a prediction metric, not a guaranteed field life.",
"Production release requires independent cell-for-cell verification of the complete Appendix A-2 through A-10 typed database.",
]
for offset, note in enumerate(method_notes, start=1):
ws.merge_cells(start_row=notes_start + offset, start_column=1, end_row=notes_start + offset, end_column=7)
ws.cell(row=notes_start + offset, column=1, value=f"{offset}. {note}")
ws.cell(row=notes_start + offset, column=1).alignment = Alignment(wrap_text=True, vertical="top")
# Largest contributors and chart.
ws.merge_cells("J3:K3")
ws["J3"] = "Largest Contributors"
style_header(ws["J3"])
for cell, value in [("J4", "Item_ID"), ("K4", "lambda_line")]:
ws[cell] = value
style_header(ws[cell])
top_chart = valid.sort_values("lambda_line", ascending=False).head(10)[["Item_ID", "lambda_line"]]
for row_index, values in enumerate(top_chart.itertuples(index=False, name=None), start=5):
ws.cell(row=row_index, column=10, value=excel_value(values[0]))
ws.cell(row=row_index, column=11, value=excel_value(values[1]))
ws.cell(row=row_index, column=11).number_format = "0.000000000000"
if not top_chart.empty:
chart = BarChart()
chart.type = "bar"
chart.title = "Largest Failure-Rate Contributions"
chart.x_axis.title = RATE_UNITS
chart.y_axis.title = "Item_ID"
chart.legend = None
data = Reference(ws, min_col=11, min_row=4, max_row=4 + len(top_chart))
cats = Reference(ws, min_col=10, min_row=5, max_row=4 + len(top_chart))
chart.add_data(data, titles_from_data=True)
chart.set_categories(cats)
chart.height = 8.5
chart.width = 17
ws.add_chart(chart, "J16")
# Subtotals.
start = 38
for title, frame in [
("Subtotal by Method", by_method),
("Subtotal by Section", by_section),
("Subtotal by Environment", by_environment),
]:
end_col = max(4, len(frame.columns))
ws.merge_cells(start_row=start, start_column=1, end_row=start, end_column=end_col)
ws.cell(row=start, column=1, value=title)
style_header(ws.cell(row=start, column=1))
start += 1
for col_index, col_name in enumerate(frame.columns, start=1):
ws.cell(row=start, column=col_index, value=col_name)
style_header(ws.cell(row=start, column=col_index))
start += 1
for values in frame.itertuples(index=False, name=None):
for col_index, value in enumerate(values, start=1):
ws.cell(row=start, column=col_index, value=excel_value(value))
if col_index >= 3 and isinstance(excel_value(value), (int, float)):
ws.cell(row=start, column=col_index).number_format = "0.000000000000"
start += 1
start += 2
ws.freeze_panes = "A4"
for col, width in {
"A": 31, "B": 31, "C": 67, "D": 3,
"E": 31, "F": 29, "G": 58, "H": 3,
"J": 27, "K": 19,
}.items():
ws.column_dimensions[col].width = width
# ---------------- Detail_Output ----------------
ws = replace_sheet(owb, "Detail_Output")
if detail.empty:
detail_to_write = pd.DataFrame(columns=detail_display_columns)
else:
detail_to_write = detail.copy()
ws.merge_cells(start_row=1, start_column=1, end_row=1, end_column=max(1, len(detail_to_write.columns)))
ws["A1"] = "Appendix A Line-by-Line Calculation Record"
style_title(ws["A1"])
ws.row_dimensions[1].height = 28
write_frame(ws, detail_to_write, header_row=3)
if not detail_to_write.empty:
status_col = detail_to_write.columns.get_loc("Status") + 1
for row_index in range(4, 4 + len(detail_to_write)):
if ws.cell(row=row_index, column=status_col).value == "ERROR":
for col_index in range(1, len(detail_to_write.columns) + 1):
ws.cell(row=row_index, column=col_index).fill = PatternFill("solid", fgColor=PALE_RED)
for name in ["lambda_g", "pi_Q", "pi_L", "lambda_per_item", "lambda_line", "Contribution_Percent"]:
if name in detail_to_write.columns:
col_index = detail_to_write.columns.get_loc(name) + 1
for row_index in range(4, 4 + len(detail_to_write)):
ws.cell(row=row_index, column=col_index).number_format = "0.000000000000"
ws.auto_filter.ref = f"A3:{get_column_letter(len(detail_to_write.columns))}{3 + len(detail_to_write)}"
ws.freeze_panes = "A4"
set_reasonable_widths(ws, detail_to_write)
# ---------------- Issues_Output ----------------
ws = replace_sheet(owb, "Issues_Output")
ws.merge_cells("A1:E1")
ws["A1"] = "Appendix A Validation Issues"
style_title(ws["A1"])
ws.row_dimensions[1].height = 28
issues_to_write = issues.copy()
if issues_to_write.empty:
issues_to_write = pd.DataFrame([{
"Severity": "INFO", "Item_ID": "", "Excel_Row": None,
"Field": "", "Message": "No validation errors or warnings were generated."
}])
write_frame(ws, issues_to_write, header_row=3)
for row_index in range(4, 4 + len(issues_to_write)):
severity = norm(ws.cell(row=row_index, column=1).value)
fill = PALE_RED if severity == "ERROR" else PALE_YELLOW if severity == "WARNING" else PALE_GREEN
for col_index in range(1, len(issues_to_write.columns) + 1):
ws.cell(row=row_index, column=col_index).fill = PatternFill("solid", fgColor=fill)
ws.auto_filter.ref = f"A3:{get_column_letter(len(issues_to_write.columns))}{3 + len(issues_to_write)}"
ws.freeze_panes = "A4"
ws.column_dimensions["A"].width = 14
ws.column_dimensions["B"].width = 24
ws.column_dimensions["C"].width = 13
ws.column_dimensions["D"].width = 28
ws.column_dimensions["E"].width = 105
owb.save(OUTPUT_WORKBOOK)
# Convert spreadsheet-specific missing values and date objects for web transport.
summary = json.loads(pd.Series(summary).to_json(date_format="iso", double_precision=15))
return {"summary": summary, "outputs": [str(OUTPUT_WORKBOOK)]}
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("workbook", type=Path)
parser.add_argument("output_dir", type=Path, nargs="?", default=Path("."))
args = parser.parse_args()
print(json.dumps(run(args.workbook, args.output_dir), indent=2))
PSSC.py · part stress and assembly contributions
"""
MIL-HDBK-217F Appendix A Part Stress Supplement / Replacement Calculator
Revision: 1.0 source-locked audit build
Purpose
-------
Console-driven calculator for selected non-microcircuit MIL-HDBK-217F Part Stress
or main-body assembly contributions used with an Appendix A Parts Count prediction.
Core accounting rule
--------------------
A Part Stress calculation for a physical part population is a REPLACEMENT for the
corresponding Appendix A Parts Count contribution, not an addition to that same
population. Section 16/17 assembly and connection models are handled separately as
supplemental main-body contributions and must not double-count the same joints.
Source basis
------------
MIL-HDBK-217F, 2 Dec 1991, as controlled by Notices 1 and 2, using the supplied
"MIL-HDBK-217F Master Governing Formula Inventory" as the revision-controlled
formula inventory. This implementation intentionally hard-stops unsupported or
ambiguous cases rather than inventing a factor.
Intentionally excluded
----------------------
Section 5 ICs / microcircuits and Section 5.5 hybrid microcircuits.
"""
import csv
import math
from pathlib import Path
K_B = 8.617e-5 # exact handbook constant used by the supplied source inventory
RESULTS = []
SOURCE_LOCK = (
"MIL-HDBK-217F (2 Dec 1991) + Notices 1/2; supplied Master Governing Formula Inventory"
)
# =============================================================================
# HMI / CONSOLE HELPERS
# =============================================================================
WIDTH = 96
class ModelApplicabilityError(RuntimeError):
"""Raised when the selected handbook model is not valid for the entered condition."""
class EngineeringDispositionRequired(RuntimeError):
"""Raised when the source requires engineering disposition instead of silent calculation."""
def _wrap(text, width=WIDTH-6):
words = str(text).split()
lines, line = [], ""
for word in words:
if not line:
line = word
elif len(line) + 1 + len(word) <= width:
line += " " + word
else:
lines.append(line)
line = word
if line:
lines.append(line)
return lines or [""]
def banner(title, subtitle=None, char="="):
print("\n" + char * WIDTH)
print(title.center(WIDTH))
if subtitle:
for line in _wrap(subtitle, WIDTH-4):
print(line.center(WIDTH))
print(char * WIDTH)
def panel(title, body, char="-"):
print("\n" + char * WIDTH)
print(f" {title}")
print(char * WIDTH)
if isinstance(body, (list, tuple)):
items = body
else:
items = [body]
for item in items:
for line in _wrap(item):
print(" " + line)
def step(n, title, text=None):
print("\n" + "-" * WIDTH)
print(f"STEP {n} — {title}")
print("-" * WIDTH)
if text:
for line in _wrap(text):
print(" " + line)
def stop_message(exc):
banner("CALCULATION STOPPED — NO VALID RELEASE VALUE GENERATED", char="!")
for line in _wrap(str(exc)):
print(" " + line)
print("!" * WIDTH)
def ask_text(prompt, *, required=True, default=None, help_text=None):
if help_text:
for line in _wrap(help_text):
print(" " + line)
while True:
suffix = f" [{default}]" if default is not None else ""
s = input(f"{prompt}{suffix}: ").strip()
if not s and default is not None:
return str(default)
if s:
return s
if not required:
return ""
print(" -> A value is required. This field may not be left blank.")
def ask_float(prompt, *, minimum=None, maximum=None, default=None, allow_blank=False, help_text=None):
if help_text:
for line in _wrap(help_text):
print(" " + line)
while True:
suffix = f" [{default}]" if default is not None else ""
raw = input(f"{prompt}{suffix}: ").strip()
if not raw and allow_blank:
return None
if not raw and default is not None:
value = float(default)
else:
try:
value = float(raw)
except ValueError:
print(" -> Enter a numeric value using ordinary decimal/scientific notation.")
continue
if not math.isfinite(value):
print(" -> Enter a finite number.")
continue
if minimum is not None and value < minimum:
print(f" -> Value must be >= {minimum}.")
continue
if maximum is not None and value > maximum:
print(f" -> Value must be <= {maximum}.")
continue
return value
def ask_int(prompt, *, minimum=None, maximum=None, default=None, help_text=None):
if help_text:
for line in _wrap(help_text):
print(" " + line)
while True:
suffix = f" [{default}]" if default is not None else ""
raw = input(f"{prompt}{suffix}: ").strip()
if not raw and default is not None:
value = int(default)
else:
try:
value = int(raw)
except ValueError:
print(" -> Enter a whole number.")
continue
if minimum is not None and value < minimum:
print(f" -> Value must be >= {minimum}.")
continue
if maximum is not None and value > maximum:
print(f" -> Value must be <= {maximum}.")
continue
return value
def ask_yes_no(prompt, *, default=None, help_text=None):
if help_text:
for line in _wrap(help_text):
print(" " + line)
if default is True:
suffix = " [Y/n]"
elif default is False:
suffix = " [y/N]"
else:
suffix = " [y/n]"
while True:
raw = input(prompt + suffix + ": ").strip().lower()
if not raw and default is not None:
return bool(default)
if raw in {"y", "yes"}:
return True
if raw in {"n", "no"}:
return False
print(" -> Enter y or n. No engineering selection is assumed when no default is shown.")
def ask_choice(prompt, options, *, default=None, help_text=None):
"""options: dict[str, str]. Engineering choices should normally use default=None."""
if help_text:
for line in _wrap(help_text):
print(" " + line)
print(f"\n{prompt}")
for key, desc in options.items():
print(f" [{key}] {desc}")
while True:
suffix = f" [{default}]" if default is not None else ""
raw = input(f"Selection{suffix}: ").strip().upper()
if not raw and default is not None:
raw = str(default).upper()
if raw in options:
return raw
print(" -> Select one of: " + ", ".join(options.keys()))
def ask_evidence(prompt, explanation=None):
return ask_text(
prompt,
required=True,
help_text=explanation or "Enter a datasheet, drawing, specification, PO/C of C, analysis, or calculation reference."
)
def require_attestation(prompt, explanation):
ok = ask_yes_no(prompt, default=None, help_text=explanation)
if not ok:
raise ModelApplicabilityError(
"Required applicability/evidence attestation was not confirmed. The handbook model is not released for this case."
)
# =============================================================================
# COMMON NUMERICAL HELPERS
# =============================================================================
def arrhenius(temp_c, ea_ev, reference_k=298.0):
"""Handbook form exp[-Ea/k * (1/(T+273)-1/Tref)]."""
return math.exp(-(ea_ev / K_B) * (1.0 / (temp_c + 273.0) - 1.0 / reference_k))
def exp_temp(temp_c, coefficient, reference_k=298.0):
"""Equivalent coefficient form used by Section 6 tables."""
return math.exp(-coefficient * (1.0 / (temp_c + 273.0) - 1.0 / reference_k))
def check_rating(value, rating, quantity_name, rating_name):
if value > rating:
raise ModelApplicabilityError(
f"{quantity_name}={value:g} exceeds {rating_name}={rating:g}. "
"The handbook model does not authorize operation beyond the actual component rating."
)
ENV_DESC = {
"GB":"Ground Benign", "GF":"Ground Fixed", "GM":"Ground Mobile",
"NS":"Naval Sheltered", "NU":"Naval Unsheltered",
"AIC":"Airborne Inhabited Cargo", "AIF":"Airborne Inhabited Fighter",
"AUC":"Airborne Uninhabited Cargo", "AUF":"Airborne Uninhabited Fighter",
"ARW":"Airborne Rotary Wing", "SF":"Space Flight",
"MF":"Missile Flight", "ML":"Missile Launch", "CL":"Cannon Launch",
}
RES_ENV = {
"GB":1.0, "GF":4.0, "GM":16.0, "NS":12.0, "NU":42.0,
"AIC":18.0, "AIF":23.0, "AUC":31.0, "AUF":43.0, "ARW":63.0,
"SF":0.50, "MF":37.0, "ML":87.0, "CL":1728.0,
}
CAP_ENV = {
"GB":1.0, "GF":10.0, "GM":20.0, "NS":7.0, "NU":15.0,
"AIC":12.0, "AIF":15.0, "AUC":25.0, "AUF":30.0, "ARW":40.0,
"SF":0.50, "MF":20.0, "ML":50.0, "CL":570.0,
}
IND_ENV = {
"GB":1.0, "GF":6.0, "GM":12.0, "NS":5.0, "NU":16.0,
"AIC":6.0, "AIF":8.0, "AUC":7.0, "AUF":9.0, "ARW":24.0,
"SF":0.50, "MF":13.0, "ML":34.0, "CL":610.0,
}
DISC_ENV = {
"GB":1.0, "GF":6.0, "GM":9.0, "NS":9.0, "NU":19.0,
"AIC":13.0, "AIF":29.0, "AUC":20.0, "AUF":43.0, "ARW":24.0,
"SF":0.50, "MF":14.0, "ML":32.0, "CL":320.0,
}
OPTO_ENV = {
"GB":1.0, "GF":2.0, "GM":8.0, "NS":5.0, "NU":12.0,
"AIC":4.0, "AIF":6.0, "AUC":6.0, "AUF":8.0, "ARW":17.0,
"SF":0.50, "MF":9.0, "ML":24.0, "CL":450.0,
}
CONN_ENV = {
"GB":1.0, "GF":1.0, "GM":8.0, "NS":5.0, "NU":13.0,
"AIC":3.0, "AIF":5.0, "AUC":8.0, "AUF":12.0, "ARW":19.0,
"SF":0.50, "MF":10.0, "ML":27.0, "CL":490.0,
}
SSR_ENV = {
"GB":1.0, "GF":3.0, "GM":12.0, "NS":6.0, "NU":17.0,
"AIC":12.0, "AIF":19.0, "AUC":21.0, "AUF":32.0, "ARW":23.0,
"SF":0.40, "MF":12.0, "ML":33.0, "CL":590.0,
}
PTH_ENV = {
"GB":1.0, "GF":2.0, "GM":7.0, "NS":5.0, "NU":13.0,
"AIC":5.0, "AIF":8.0, "AUC":16.0, "AUF":28.0, "ARW":19.0,
"SF":0.50, "MF":10.0, "ML":27.0, "CL":500.0,
}
CONNECTION_ENV = {
"GB":1.0, "GF":2.0, "GM":7.0, "NS":4.0, "NU":11.0,
"AIC":4.0, "AIF":6.0, "AUC":6.0, "AUF":8.0, "ARW":16.0,
"SF":0.50, "MF":9.0, "ML":24.0, "CL":420.0,
}
TABLE_6_1_TC = {
"GB":35.0, "GF":45.0, "GM":50.0, "NS":45.0, "NU":50.0,
"AIC":60.0, "AIF":60.0, "AUC":75.0, "AUF":75.0, "ARW":60.0,
"SF":35.0, "MF":50.0, "ML":60.0, "CL":45.0,
}
TABLE_6_2_THETA = {
"TO-1":70, "TO-3":10, "TO-5":70, "TO-8":70, "TO-9":70, "TO-12":70,
"TO-18":70, "TO-28":5, "TO-33":70, "TO-39":70, "TO-41":10, "TO-44":70,
"TO-46":70, "TO-52":70, "TO-53":5, "TO-57":5, "TO-59":5, "TO-60":5,
"TO-61":5, "TO-63":5, "TO-66":10, "TO-71":70, "TO-72":70, "TO-83":5,
"TO-89":22, "TO-92":70, "TO-94":5, "TO-99":70, "TO-126":5, "TO-127":5,
"TO-204":10, "TO-204AA":10, "TO-205AD":70, "TO-205AF":70, "TO-220":5,
"DO-4":5, "DO-5":5, "DO-7":10, "DO-8":5, "DO-9":5, "DO-13":10,
"DO-14":5, "DO-29":10, "DO-35":10, "DO-41":10, "DO-45":5,
"DO-204MB":70, "DO-205AB":5, "PA-42A/B":70, "PD-36C":70, "PD-50":70,
"PD-77":70, "PD-180":70, "PD-319":70, "PD-262":70, "PD-975":70,
"PD-280":70, "PD-216":70, "PT-2G":70, "PT-6B":70, "PH-13":70,
"PH-16":70, "PH-56":70, "PY-58":70, "PY-373":70,
}
def select_environment(table, title="Use environment"):
options = {
k: f"{ENV_DESC.get(k,k)} — piE = {v:g}"
for k, v in table.items()
}
key = ask_choice(
title,
options,
default=None,
help_text=(
"Select the actual intended-use environment. The handbook does not supply a universal unknown-"
"environment default, so this selection is intentionally mandatory."
),
)
return key, table[key]
def select_model_basis(family, direct_basis_text):
mode = ask_choice(
f"{family} model applicability basis",
{
"D": "DIRECT — actual part is supported by the handbook-listed style/specification/applicability",
"A": "ALTERNATE/SURROGATE — program-approved analogous handbook model will be used",
},
default=None,
help_text=(
direct_basis_text + " A commercial part that merely looks similar is not automatically a direct "
"handbook style. If using an engineering surrogate, the approval/basis must remain visible in the NOTE."
),
)
if mode == "D":
evidence = ask_evidence("Direct applicability/specification evidence reference")
return "DIRECT", evidence
evidence = ask_evidence(
"Approved alternate/surrogate basis reference",
"Enter the program-approved engineering rationale, deviation, calculation, or other controlled approval."
)
return "ALTERNATE_SURROGATE", evidence
def select_quality(table, descriptions, *, eligibility=None):
options = {k: f"{descriptions[k]} — piQ = {v:g}" for k, v in table.items()}
key = ask_choice(
"Quality / procurement classification",
options,
default=None,
help_text=(
"Select from procurement/specification/screening evidence. Do not select a more favorable class based on "
"manufacturer reputation, automotive qualification alone, or part-name similarity."
),
)
if eligibility is not None:
eligibility(key)
evidence = ask_evidence("Quality/procurement evidence reference")
return key, table[key], evidence
# =============================================================================
# APPENDIX A COMPARISON + RESULT RECORDING
# =============================================================================
def appendix_a_comparison(qty):
mode = ask_choice(
"Optional Appendix A comparison",
{
"R": "RATE DATABASE INPUT — I have raw Appendix A generic lambda_g and Appendix A piQ",
"L": "LINE RESULT INPUT — I already have the complete Appendix A line lambda",
"S": "SKIP — do not compare this Part Stress result with Appendix A now",
},
default=None,
help_text=(
"IMPORTANT: a Rate_Database value such as 0.0035 is normally lambda_g, not the complete line contribution. "
"For non-microcircuit Appendix A lines, this notebook computes line lambda = N * lambda_g * Appendix-A piQ. "
"The Appendix-A piQ is entered separately and must not be silently copied from the Part Stress model."
),
)
if mode == "S":
return None
if mode == "L":
line = ask_float(
"Existing complete Appendix A line lambda [failures/1e6 h]",
minimum=0,
help_text="Enter the already-aggregated line contribution after quantity and Appendix-A quality have been applied."
)
return {"mode":"LINE_INPUT", "appendix_line_lambda":line}
lg = ask_float(
"Appendix A generic rate lambda_g from Rate_Database [failures/1e6 h per part]",
minimum=0,
help_text="Paste the raw generic rate from the Appendix A rate table/database for the selected category and environment."
)
piq = ask_float(
"Appendix A quality factor piQ used by the existing Parts Count line",
minimum=0,
help_text="Enter the Appendix A part-class quality multiplier used by your workbook for this line."
)
line = qty * lg * piq
panel(
"APPENDIX A RECONSTRUCTION",
[
f"Quantity N = {qty}",
f"Generic rate lambda_g = {lg:.12g} failures/1e6 h per part",
f"Appendix A piQ = {piq:.12g}",
f"Existing Appendix A line lambda = N * lambda_g * piQ = {line:.12g} failures/1e6 h",
],
)
return {
"mode":"RATE_DATABASE",
"appendix_lambda_g":lg,
"appendix_piQ":piq,
"appendix_line_lambda":line,
}
def comparison_text(part_stress_line, comp):
if not comp:
return "No Appendix A numerical comparison was requested."
old = comp["appendix_line_lambda"]
if old == 0:
if part_stress_line == 0:
return "Appendix A and Part Stress line contributions are both zero."
return "Appendix A line is zero; a finite ratio is not defined."
ratio = part_stress_line / old
pct = (part_stress_line - old) / old * 100.0
if abs(pct) < 1e-10:
verdict = "numerically equal"
elif pct < 0:
verdict = f"Part Stress is {-pct:.3f}% LOWER than Appendix A"
else:
verdict = f"Part Stress is {pct:.3f}% HIGHER than Appendix A"
return (
f"Appendix A line lambda={old:.12g}; Part Stress line lambda={part_stress_line:.12g}; "
f"ratio PartStress/AppendixA={ratio:.8g}; {verdict}. Numerical favorability alone is NOT the method-selection rule."
)
def finalize_piece_part(part, section, source, formula, lambda_p, qty, factors, basis, warnings=None):
warnings = list(warnings or [])
line_lambda = lambda_p * qty
step(8, "APPENDIX A COMPARISON / METHOD DECISION")
comp = appendix_a_comparison(qty)
comp_text = comparison_text(line_lambda, comp)
panel("NUMERICAL COMPARISON", comp_text)
selected = ask_yes_no(
"Designate this Part Stress result as the selected REPLACEMENT for the same Appendix A physical population?",
default=False,
help_text=(
"Select YES only when the detailed Part Stress method is the approved/appropriate method for this population and the "
"corresponding Appendix A contribution will be excluded. Do NOT choose based only on whichever lambda is smaller."
),
)
selection_ref = ""
if selected:
require_attestation(
"Will the corresponding Appendix A contribution for this SAME physical population be removed/excluded?",
"This prevents double counting. The same physical part population may not be included by both Parts Count and Part Stress."
)
selection_ref = ask_evidence(
"Replacement selection / calculation approval reference",
"Enter the calculation note, analyst decision, review record, or program approval that identifies this as the selected method."
)
status = "SELECTED_PART_STRESS_REPLACEMENT"
else:
status = "EVALUATED_ONLY_NOT_SELECTED"
warning_text = " | ".join(warnings) if warnings else "None"
factor_text = "; ".join(f"{k}={v}" for k, v in factors.items())
note = (
f"NOTE — {part}: {status}. Source basis: {SOURCE_LOCK}; {source}. "
f"Governing equation: {formula}. Individual Part Stress lambda_p={lambda_p:.12g} failures/1e6 operating hours. "
f"Quantity N={qty}; Part Stress line lambda=N*lambda_p={line_lambda:.12g} failures/1e6 operating hours. "
f"Inputs/factors: {factor_text}. Model/applicability basis: {basis}. {comp_text} "
f"Appendix A mixed-method justification: detailed part-specific information is available and a main-body Part Stress result may "
f"replace the corresponding generic Parts Count population when the accounting remains complete and non-overlapping. "
f"Replacement selection reference: {selection_ref if selected else 'not selected'}. Warnings/dispositions: {warning_text}."
)
rec = {
"kind":"PIECE_PART_REPLACEMENT",
"status":status,
"part":part,
"section":section,
"source":source,
"formula":formula,
"lambda_p":lambda_p,
"quantity":qty,
"line_lambda":line_lambda,
"appendix_comparison":comp,
"factors":factors,
"basis":basis,
"selection_reference":selection_ref,
"warnings":warnings,
"note":note,
}
RESULTS.append(rec)
banner("CALCULATION RESULT")
print(f"PART / GROUP : {part}")
print(f"SECTION : {section}")
print(f"STATUS : {status}")
print(f"INDIVIDUAL lambda_p : {lambda_p:.12g} failures / 1e6 operating h")
print(f"QUANTITY N : {qty}")
print(f"PART STRESS LINE lambda: {line_lambda:.12g} failures / 1e6 operating h")
if line_lambda > 0:
print(f"RECIPROCAL LINE MTBF* : {1e6/line_lambda:.8g} h")
print("*MTBF shown only as reciprocal of this line contribution; it is not the equipment MTBF.")
panel("COPY/PASTE NOTE", note)
return rec
def finalize_supplement(part, section, source, formula, line_lambda, factors, basis, warnings=None):
warnings = list(warnings or [])
warning_text = " | ".join(warnings) if warnings else "None"
factor_text = "; ".join(f"{k}={v}" for k, v in factors.items())
note = (
f"NOTE — {part}: SUPPLEMENTAL_MAIN_BODY_CONTRIBUTION. Source basis: {SOURCE_LOCK}; {source}. "
f"Governing equation: {formula}. Calculated contribution={line_lambda:.12g} failures/1e6 operating hours. "
f"Inputs/factors: {factor_text}. Basis: {basis}. This result is not automatically a piece-part Appendix A replacement. "
f"It must be incorporated at the correct assembly/accounting boundary without double counting a connection or interconnection "
f"failure mechanism already represented elsewhere. Warnings/dispositions: {warning_text}."
)
rec = {
"kind":"SUPPLEMENTAL_MAIN_BODY",
"status":"SUPPLEMENTAL_MAIN_BODY_CONTRIBUTION",
"part":part,
"section":section,
"source":source,
"formula":formula,
"lambda_p":None,
"quantity":1,
"line_lambda":line_lambda,
"appendix_comparison":None,
"factors":factors,
"basis":basis,
"selection_reference":"",
"warnings":warnings,
"note":note,
}
RESULTS.append(rec)
banner("SUPPLEMENTAL CONTRIBUTION RESULT")
print(f"ASSEMBLY / GROUP : {part}")
print(f"SECTION : {section}")
print(f"CONTRIBUTION lambda : {line_lambda:.12g} failures / 1e6 operating h")
panel("COPY/PASTE NOTE", note)
return rec
# =============================================================================
# SECTION 9.1 — RESISTORS
# =============================================================================
RES_STYLES = {
"RC": (.0017,1,2,"Fixed composition, insulated","MIL-R-11",False),
"RCR": (.0017,1,2,"Fixed composition, established reliability","MIL-R-39008",True),
"RL": (.0037,2,1,"Fixed film, insulated","MIL-R-22684",False),
"RLR": (.0037,2,1,"Fixed film, established reliability","MIL-R-39017",True),
"RN_ER":(.0037,2,1,"Fixed film, established reliability","MIL-R-55182",True),
"RM": (.0037,2,1,"Fixed film chip, established reliability","MIL-R-55342",True),
"RN_HS":(.0037,2,1,"Fixed film, high stability","MIL-R-10509",False),
"RD": (.0037,0,1,"Fixed film, power type","MIL-R-11804",False),
"RZ": (.0019,1,0,"Fixed film resistor network","MIL-R-83401",False),
"RB": (.0024,2,1,"Fixed wirewound, accurate","MIL-R-93",False),
"RBR": (.0024,2,1,"Fixed wirewound, accurate, ER","MIL-R-39005",True),
"RW": (.0024,2,2,"Fixed wirewound, power type","MIL-R-26",False),
"RWR": (.0024,2,2,"Fixed wirewound, power type, ER","MIL-R-39007",True),
"RE": (.0024,2,2,"Fixed wirewound, chassis mounted","MIL-R-18546",False),
"RER": (.0024,2,2,"Fixed wirewound, chassis mounted, ER","MIL-R-39009",True),
"RTH": (.0019,0,0,"Thermistor, thermally sensitive","MIL-R-23648",False),
"RT": (.0024,2,1,"Variable wirewound, lead-screw activated","MIL-R-27208",False),
"RTR": (.0024,2,1,"Variable wirewound, lead-screw activated, ER","MIL-R-39015",True),
"RR": (.0024,2,1,"Variable wirewound, precision","MIL-R-12934",False),
"RA": (.0024,1,1,"Variable wirewound, low operating temperature","MIL-R-19",False),
"RK": (.0024,1,1,"Variable wirewound, semiprecision","MIL-R-39002",False),
"RP": (.0024,2,1,"Variable wirewound, power type","MIL-R-22",False),
"RJ": (.0037,2,1,"Variable nonwirewound","MIL-R-22097",False),
"RJR": (.0037,2,1,"Variable nonwirewound, ER","MIL-R-39035",True),
"RV": (.0037,2,1,"Variable composition","MIL-R-94",False),
"RQ": (.0037,1,1,"Variable nonwirewound, precision","MIL-R-39023",False),
"RVC": (.0037,1,1,"Variable nonwirewound","MIL-R-23285",False),
}
RES_Q = {"S":.03,"R":.10,"P":.30,"M":1.0,"NON_ER":3.0,"COMMERCIAL":10.0}
RES_Q_DESC = {
"S":"Established-reliability grade S",
"R":"Established-reliability grade R",
"P":"Established-reliability grade P",
"M":"Established-reliability grade M",
"NON_ER":"Supported non-established-reliability resistor category",
"COMMERCIAL":"Commercial or unknown screening level",
}
RES_POWER_STYLES = {"RD","RW","RWR","RE","RER","RP"}
def resistor_piS(column, stress):
if not 0 <= stress <= 1:
raise ModelApplicabilityError("Resistor stress ratio S=PD/PR must be within 0 to 1.")
if column == 0:
return 1.0
if column == 1:
return .71 * math.exp(1.1 * stress)
if column == 2:
return .54 * math.exp(2.04 * stress)
raise RuntimeError("Invalid resistor stress column in immutable source table.")
def calc_resistor():
banner("SECTION 9.1 — RESISTOR PART STRESS", "Notice 2 unified resistor model")
step(1,"IDENTIFY THE PHYSICAL POPULATION")
part = ask_text("Manufacturer part number / group identifier")
qty = ask_int("Quantity N represented by this calculation line", minimum=1)
step(2,"ROUTE TO THE HANDBOOK STYLE")
style = ask_choice(
"Select the Section 9.1 style used for base-rate/temperature/stress routing",
{k:f"{v[3]} | {v[4]} | lambda_b={v[0]}" for k,v in RES_STYLES.items()},
default=None,
help_text="No style is preselected. The style controls lambda_b and the temperature/stress equation branches."
)
lb,tcol,scol,desc,spec,is_er_style = RES_STYLES[style]
basis_mode,basis_ev = select_model_basis(
"Resistor",
"Direct Section 9.1 use requires the actual resistor style/applicable specification evidence to support the selected row."
)
step(3,"ESTABLISH TEMPERATURE")
if style in RES_POWER_STYLES:
tmode = "CASE"
else:
tmode = ask_choice(
"Temperature source",
{
"C":"Use known resistor case temperature",
"A":"Use ambient as case-temperature approximation for a low-dissipation, non-power-type resistor",
},
default=None,
)
T = ask_float("Resistor case temperature T [deg C]" if tmode=="CASE" or tmode=="C" else "Ambient component temperature used as case approximation [deg C]")
if tmode == "A":
require_attestation(
"Is this a low-dissipation, non-power-type resistor with negligible self-heating?",
"Notice 2 permits the ambient approximation only for low-dissipation non-power-type resistors."
)
t_rating = ask_float("Actual component maximum applicable temperature rating [deg C]")
check_rating(T,t_rating,"Modeled resistor temperature","component temperature rating")
piT = 1.0 if tcol==0 else arrhenius(T, .20 if tcol==1 else .08)
step(4,"ESTABLISH ACTUAL POWER AND POWER STRESS")
PD = ask_float("Actual worst-case resistor power dissipation PD [W]", minimum=0)
PR = ask_float("Applicable rated/DERATED power PR at the modeled condition [W]", minimum=1e-30)
S = PD/PR
if S > 1:
raise ModelApplicabilityError(f"Resistor power stress S=PD/PR={S:.6g} exceeds 1.0.")
piP = PD**.39 if PD>0 else 0.0
piS = resistor_piS(scol,S)
step(5,"QUALITY / PROCUREMENT")
def eligibility(q):
if q in {"S","R","P","M"}:
if not is_er_style or basis_mode != "DIRECT":
raise ModelApplicabilityError(
"An ER grade S/R/P/M may only be used here when the actual procured resistor is supported as the applicable ER style/specification."
)
qk,piQ,qev = select_quality(RES_Q,RES_Q_DESC,eligibility=eligibility)
step(6,"ENVIRONMENT")
ek,piE = select_environment(RES_ENV)
step(7,"CALCULATE")
lp = lb*piT*piP*piS*piQ*piE
warnings=[]
if PD < .001 or PD > 150:
warnings.append("PD lies outside the printed 0.001–150 W piP table span; equation used and engineering disposition should be retained")
if basis_mode != "DIRECT":
warnings.append("Alternate/surrogate resistor-style mapping — not represented as direct military-style qualification")
factors={"style":style,"lambda_b":lb,"T_C":T,"piT":piT,"PD_W":PD,"PR_W":PR,"S":S,"piP":piP,"piS":piS,"quality":qk,"piQ":piQ,"environment":ek,"piE":piE}
basis=f"{basis_mode}; selected style={style} ({desc}, {spec}); applicability evidence={basis_ev}; quality evidence={qev}"
return finalize_piece_part(part,"9.1","Notice 2 Section 9.1, handbook pages 9-1 through 9-3","lambda_p=lambda_b*piT*piP*piS*piQ*piE",lp,qty,factors,basis,warnings)
# =============================================================================
# SECTION 10.1 — CAPACITORS
# =============================================================================
# tuple: lambda_b, Tcol, Ccol, Vcol, SRroute, description, spec, ER-capable
CAP_STYLES = {
"CP":(.00037,1,1,1,"ONE","Fixed paper dielectric, DC, hermetic metal case","MIL-C-25",False),
"CA":(.00037,1,1,1,"ONE","RFI paper dielectric, AC/DC, hermetic metallic case","MIL-C-12889",False),
"CZ/CZR":(.00037,1,1,1,"ONE","Feed-through RFI, ER and non-ER","MIL-C-11693",True),
"CQ/CQR":(.00051,1,1,1,"ONE","Plastic/paper-plastic dielectric, ER and non-ER","MIL-C-19978",True),
"CH":(.00037,1,1,1,"ONE","Metallized paper/paper-plastic/plastic-film, DC","MIL-C-18312",False),
"CHR":(.00051,1,1,1,"ONE","Metallized paper/plastic-film","MIL-C-39022",True),
"CFR":(.00051,1,1,1,"ONE","Plastic or metallized-plastic dielectric, non-metal case","MIL-C-55514",False),
"CRH":(.00051,1,1,1,"ONE","Supermetallized plastic-film, hermetic metal, ER","MIL-C-83421",True),
"CM":(.00076,2,1,2,"ONE","Fixed mica dielectric","MIL-C-5",False),
"CMR":(.00076,2,1,2,"ONE","Fixed mica dielectric, ER","MIL-C-39001",True),
"CB":(.00076,2,1,2,"ONE","Fixed mica dielectric, button style","MIL-C-10950",False),
"CY":(.00076,2,1,2,"ONE","Fixed glass dielectric","MIL-C-11272",False),
"CYR":(.00076,2,1,2,"ONE","Fixed glass dielectric, ER","MIL-C-23269",True),
"CK":(.00099,2,1,3,"ONE","Fixed ceramic dielectric, general purpose","MIL-C-11015",False),
"CKR":(.00099,2,1,3,"ONE","Fixed ceramic dielectric, general purpose, ER","MIL-C-39014",True),
"CC/CCR":(.00099,2,1,3,"ONE","Fixed ceramic dielectric, temperature compensating, ER/non-ER","MIL-C-20",True),
"CDR":(.0020,2,1,3,"ONE","Fixed multilayer ceramic chip, ER","MIL-C-55681",True),
"CSR":(.00040,1,2,4,"TABLE","Fixed solid-electrolyte tantalum, ER","MIL-C-39003",True),
"CWR":(.00005,1,2,4,"TABLE","Fixed tantalum electrolytic chip, ER","MIL-C-55365",True),
"CL":(.00040,1,2,4,"ONE","Fixed nonsolid-electrolyte tantalum","MIL-C-3965",False),
"CLR":(.00040,1,2,4,"ONE","Fixed nonsolid-electrolyte tantalum, ER","MIL-C-39006",True),
"CRL":(.00040,1,2,4,"ONE","Fixed nonsolid-electrolyte tantalum-cathode construction","MIL-C-83500",False),
"CU/CUR":(.00012,2,2,1,"ONE","Fixed aluminum-oxide electrolytic, ER/non-ER","MIL-C-39018",True),
"CE":(.00012,2,2,1,"ONE","Fixed dry-electrolyte aluminum, polarized","MIL-C-62",False),
"CV":(.0079,1,1,5,"ONE","Variable ceramic dielectric trimmer","MIL-C-81",False),
"PC":(.0060,2,1,5,"ONE","Variable piston-type tubular trimmer","MIL-C-14409",False),
"CT":(.0000072,2,1,5,"ONE","Variable air-dielectric trimmer","MIL-C-92",False),
"CG":(.0060,1,1,5,"ONE","Fixed or variable vacuum dielectric","MIL-C-23183",False),
}
CAP_Q = {"D":.001,"C":.01,"S_OR_B":.03,"R":.1,"P":.3,"M":1.0,"L":1.5,"NON_ER":3.0,"COMMERCIAL":10.0}
CAP_Q_DESC = {
"D":"Established reliability grade D", "C":"Established reliability grade C",
"S_OR_B":"Established reliability grade S or B", "R":"Established reliability grade R",
"P":"Established reliability grade P", "M":"Established reliability grade M",
"L":"Established reliability grade L", "NON_ER":"Supported non-established-reliability capacitor category",
"COMMERCIAL":"Commercial or unknown screening level",
}
def capacitor_piV(col,S):
if not 0 <= S <= 1:
raise ModelApplicabilityError("Capacitor voltage stress S must be within 0 to 1.")
if col==1: return (S/.6)**5 + 1
if col==2: return (S/.6)**10 + 1
if col==3: return (S/.6)**3 + 1
if col==4: return (S/.6)**17 + 1
if col==5: return (S/.5)**3 + 1
raise RuntimeError("Invalid capacitor voltage-stress column.")
def capacitor_piSR(cr):
if cr < 0:
raise ModelApplicabilityError("Circuit resistance CR cannot be negative.")
if cr > .8: return .66
if cr > .6: return 1.0
if cr > .4: return 1.3
if cr > .2: return 2.0
if cr > .1: return 2.7
return 3.3
def ask_peak_ac():
mode = ask_choice(
"AC voltage component",
{
"0":"No AC component — peak AC = 0 V",
"P":"Peak AC voltage is already known",
"R":"Sinusoidal AC is known in RMS — convert peak = sqrt(2)*Vrms",
"W":"Nonsinusoidal waveform — enter the actual measured/calculated peak AC voltage",
},
default=None,
help_text="Notice 2 uses applied DC plus PEAK AC voltage. The sqrt(2) conversion is valid only for a sinusoid."
)
if mode=="0": return 0.0,"no AC component"
if mode=="R":
rms=ask_float("Sinusoidal AC RMS voltage [V]",minimum=0)
return math.sqrt(2)*rms,f"sinusoidal RMS-to-peak conversion from {rms:g} Vrms"
peak=ask_float("Peak AC voltage [V]",minimum=0)
return peak,"known peak AC" if mode=="P" else "actual nonsinusoidal peak AC"
def calc_capacitor():
banner("SECTION 10.1 — CAPACITOR PART STRESS","Notice 2 unified capacitor model")
step(1,"IDENTIFY THE PHYSICAL POPULATION")
part=ask_text("Manufacturer part number / group identifier")
qty=ask_int("Quantity N represented by this calculation line",minimum=1)
step(2,"ROUTE TO THE HANDBOOK STYLE")
style=ask_choice(
"Select the Section 10.1 style used for model routing",
{k:f"{v[5]} | {v[6]} | lambda_b={v[0]} | route T/C/V/SR={v[1]}/{v[2]}/{v[3]}/{v[4]}" for k,v in CAP_STYLES.items()},
default=None,
help_text="No capacitor style is assumed. Dielectric family alone is not sufficient where multiple styles have different routes."
)
lb,tcol,ccol,vcol,srroute,desc,spec,er_capable=CAP_STYLES[style]
basis_mode,basis_ev=select_model_basis(
"Capacitor",
"Direct Section 10.1 use requires the actual capacitor to be supported by a listed style/applicable specification."
)
step(3,"TEMPERATURE AND RATING")
T=ask_float("Capacitor ambient operating temperature T [deg C]")
T_rating=ask_float("Actual capacitor maximum applicable temperature rating [deg C]")
check_rating(T,T_rating,"Capacitor ambient temperature","component temperature rating")
piT=arrhenius(T,.15 if tcol==1 else .35)
step(4,"CAPACITANCE")
C_uF=ask_float("Capacitance C [microfarads, uF]",minimum=1e-30,help_text="Convert pF/nF before entry if needed: 1 pF=1e-6 uF; 1 nF=1e-3 uF.")
piC=C_uF**(.09 if ccol==1 else .23)
step(5,"VOLTAGE STRESS")
vdc=ask_float("Applied DC voltage [V]",minimum=0)
vacpk,ac_basis=ask_peak_ac()
vop=vdc+vacpk
vrated=ask_float("Actual rated capacitor voltage [V]",minimum=1e-30)
S=vop/vrated
if S>1:
raise ModelApplicabilityError(f"Capacitor voltage stress S=(Vdc+Vac_peak)/Vrated={S:.6g} exceeds 1.0.")
piV=capacitor_piV(vcol,S)
step(6,"SERIES-RESISTANCE FACTOR / QUALITY / ENVIRONMENT")
if srroute=="TABLE":
cr=ask_float("Circuit resistance CR [ohms/volt]",minimum=0,help_text="CR = effective resistance between capacitor and supply / applied capacitor voltage.")
piSR=capacitor_piSR(cr)
else:
cr=None; piSR=1.0
def eligibility(q):
if q in {"D","C","S_OR_B","R","P","M","L"}:
if not er_capable or basis_mode!="DIRECT":
raise ModelApplicabilityError("An established-reliability capacitor grade may only be used when actual procurement/specification evidence supports the applicable ER style.")
qk,piQ,qev=select_quality(CAP_Q,CAP_Q_DESC,eligibility=eligibility)
ek,piE=select_environment(CAP_ENV)
step(7,"CALCULATE")
lp=lb*piT*piC*piV*piSR*piQ*piE
warnings=[]
if not (1e-6 <= C_uF <= 1.2e5):
warnings.append("Capacitance lies outside the printed Section 10.1 piC table span; retain an outside-table engineering-disposition flag")
if style=="CWR":
warnings.append("CWR source anomaly retained: Notice 2 style table routes CWR to the piSR table although the printed piSR heading says CSR only")
if basis_mode!="DIRECT":
warnings.append("Alternate/surrogate capacitor-style mapping — not represented as direct military-style qualification")
factors={"style":style,"lambda_b":lb,"T_ambient_C":T,"piT":piT,"C_uF":C_uF,"piC":piC,"Vdc":vdc,"Vac_peak":vacpk,"AC_basis":ac_basis,"Voperating":vop,"Vrated":vrated,"S":S,"piV":piV,"CR_ohm_per_V":cr,"piSR":piSR,"quality":qk,"piQ":piQ,"environment":ek,"piE":piE}
basis=f"{basis_mode}; selected style={style} ({desc}, {spec}); applicability evidence={basis_ev}; quality evidence={qev}"
return finalize_piece_part(part,"10.1","Notice 2 Section 10.1, handbook pages 10-1 through 10-6","lambda_p=lambda_b*piT*piC*piV*piSR*piQ*piE",lp,qty,factors,basis,warnings)
# =============================================================================
# SECTION 11.3 THERMAL HELPER + 11.1 TRANSFORMERS + 11.2 COILS
# =============================================================================
COIL_Q={"S":.03,"R":.10,"P":.30,"M":1.0,"MIL_SPEC":1.0,"LOWER":3.0}
COIL_Q_DESC={
"S":"Established reliability grade S", "R":"Established reliability grade R",
"P":"Established reliability grade P", "M":"Established reliability grade M",
"MIL_SPEC":"MIL-SPEC category", "LOWER":"Lower/commercial/non-MIL category",
}
TRANS_Q={"MIL_SPEC":1.0,"LOWER":3.0}
TRANS_Q_DESC={"MIL_SPEC":"MIL-SPEC transformer category","LOWER":"Lower/commercial category"}
SLASH_RISE = {
"15C":"MIL-C-39010 /1C–3C, /5C, /7C, /9A, /10A, /13, /14 — deltaT=15 C",
"35C":"MIL-C-39010 /4C, /6C, /8A, /11, /12 — deltaT=35 C",
}
def inductive_hotspot(environment, *, allow_slash=True):
panel(
"SECTION 11.3 THERMAL HIERARCHY",
[
"The source priority is: specification/test temperature rise > applicable MIL-C-39010 slash-sheet rise > power-loss/radiating-area approximation > power-loss/weight approximation > input-power/weight approximation.",
"For Space Flight (SF), the source directs dedicated thermal analysis rather than the non-space approximations.",
"The final hot-spot temperature is THS = TA + 1.1*deltaT.",
]
)
TA=ask_float("Inductive-device ambient operating temperature TA [deg C]")
if environment=="SF":
method=ask_choice(
"Space-flight thermal basis",
{"D":"Dedicated thermal analysis — enter validated THS directly","T":"Specification/test temperature rise is available"},
default=None,
)
if method=="D":
ths=ask_float("Validated winding hot-spot temperature THS [deg C]")
ref=ask_evidence("Dedicated thermal-analysis reference")
return ths,{"thermal_method":"SF dedicated thermal analysis","TA_C":TA,"THS_C":ths,"source":ref}
dT=ask_float("Specification/test average temperature rise deltaT [deg C]",minimum=0)
ref=ask_evidence("Specification/test temperature-rise reference")
ths=TA+1.1*dT
return ths,{"thermal_method":"specification/test rise","TA_C":TA,"deltaT_C":dT,"THS_C":ths,"source":ref}
# Enforce preferred order by asking availability sequentially.
if ask_yes_no("Do you have a valid specification/test average temperature-rise value deltaT?",default=None):
dT=ask_float("Specification/test deltaT [deg C]",minimum=0)
ref=ask_evidence("Specification/test rise reference")
ths=TA+1.1*dT
return ths,{"thermal_method":"specification/test rise","TA_C":TA,"deltaT_C":dT,"THS_C":ths,"source":ref}
if allow_slash and ask_yes_no("Is this an applicable MIL-C-39010 device with a listed slash-sheet rise?",default=None):
grp=ask_choice("MIL-C-39010 slash-sheet rise group",SLASH_RISE,default=None)
dT=15.0 if grp=="15C" else 35.0
ref=ask_evidence("MIL-C-39010 slash-sheet / procurement reference")
ths=TA+1.1*dT
return ths,{"thermal_method":"MIL-C-39010 slash-sheet rise","slash_group":grp,"TA_C":TA,"deltaT_C":dT,"THS_C":ths,"source":ref}
if ask_yes_no("Are power loss WL and EXCLUDING-MOUNTING-SURFACE radiating area A available?",default=None):
WL=ask_float("Power loss WL [W]",minimum=0)
A=ask_float("Radiating surface area A [in^2], excluding mounting surface",minimum=1e-30)
if not (3 <= A <= 150):
raise ModelApplicabilityError("Section 11.3 power-loss/area approximation is published only for 3 <= A <= 150 in^2.")
dT=125*WL/A
ths=TA+1.1*dT
return ths,{"thermal_method":"125*WL/A","TA_C":TA,"WL_W":WL,"A_in2":A,"deltaT_C":dT,"THS_C":ths}
if ask_yes_no("Are power loss WL and device/transformer weight Wt available?",default=None):
WL=ask_float("Power loss WL [W]",minimum=0)
wt=ask_float("Weight Wt [lb]",minimum=1e-30)
dT=11.5*WL/(wt**.6766)
ths=TA+1.1*dT
return ths,{"thermal_method":"11.5*WL/Wt^0.6766","TA_C":TA,"WL_W":WL,"Wt_lb":wt,"deltaT_C":dT,"THS_C":ths}
if ask_yes_no("Are input power WI and device/transformer weight Wt available AND is the handbook 80% efficiency assumption applicable?",default=None):
require_attestation("Confirm the printed 80% efficiency assumption is applicable", "Section 11.3 Method 4 is not valid without this assumption unless an approved alternate basis is documented.")
WI=ask_float("Input power WI [W]",minimum=0)
wt=ask_float("Weight Wt [lb]",minimum=1e-30)
dT=2.1*WI/(wt**.6766)
ths=TA+1.1*dT
return ths,{"thermal_method":"2.1*WI/Wt^0.6766","TA_C":TA,"WI_W":WI,"Wt_lb":wt,"efficiency_assumption":"80%","deltaT_C":dT,"THS_C":ths}
raise ModelApplicabilityError(
"No supported Section 11.3 thermal method is available. Obtain specification/test rise or a dedicated thermal analysis; do not insert a nominal hot-spot temperature."
)
def calc_coil():
banner("SECTION 11.2 — COIL / INDUCTOR PART STRESS")
step(1,"IDENTIFY POPULATION")
part=ask_text("Manufacturer part number / group identifier")
qty=ask_int("Quantity N represented",minimum=1)
step(2,"MODEL APPLICABILITY")
kind=ask_choice("Inductor type",{"F":"Fixed inductor or choke — lambda_b=0.000030","V":"Variable inductor — lambda_b=0.000050"},default=None)
basis_mode,basis_ev=select_model_basis(
"Coil / inductor",
"Direct Section 11.2 applicability is for the published MIL-C-15305 RF coils, MIL-C-83446 RF chip coils, and MIL-C-39010 molded ER coils."
)
if basis_mode=="DIRECT":
family=ask_choice("Direct specification family",{"15305":"MIL-C-15305 fixed/variable RF coil","83446":"MIL-C-83446 fixed/variable RF chip coil","39010":"MIL-C-39010 molded RF established-reliability coil"},default=None)
else:
family="ALTERNATE"
lb=.000030 if kind=="F" else .000050
step(3,"ENVIRONMENT")
ek,piE=select_environment(IND_ENV)
step(4,"SECTION 11.3 HOT-SPOT TEMPERATURE")
ths,thermal=inductive_hotspot(ek,allow_slash=True)
rating=ask_float("Actual coil maximum applicable temperature rating [deg C]")
check_rating(ths,rating,"Calculated hot-spot temperature THS","coil temperature rating")
piT=arrhenius(ths,.11)
step(5,"QUALITY")
def eligibility(q):
if q in {"S","R","P","M"} and not (basis_mode=="DIRECT" and family=="39010"):
raise ModelApplicabilityError("Coil ER grade S/R/P/M requires applicable MIL-C-39010 ER grading evidence.")
if q=="MIL_SPEC" and basis_mode!="DIRECT":
raise ModelApplicabilityError("MIL-SPEC quality requires direct applicable military-specification procurement evidence.")
qk,piQ,qev=select_quality(COIL_Q,COIL_Q_DESC,eligibility=eligibility)
step(6,"CALCULATE")
lp=lb*piT*piQ*piE
warnings=[]
if basis_mode!="DIRECT": warnings.append("Alternate/surrogate Section 11.2 use; unlisted coil technology is not represented as direct handbook applicability")
factors={"type":"fixed/choke" if kind=="F" else "variable","lambda_b":lb,**thermal,"temperature_rating_C":rating,"piT":piT,"quality":qk,"piQ":piQ,"environment":ek,"piE":piE}
basis=f"{basis_mode}; family={family}; applicability evidence={basis_ev}; quality evidence={qev}"
return finalize_piece_part(part,"11.2","Notice 2 Section 11.2 page 11-3; Section 11.3 page 11-4","lambda_p=lambda_b*piT*piQ*piE",lp,qty,factors,basis,warnings)
TRANS_TYPES={
"FLYBACK":(.0054,"Flyback, less than 20 V"),
"AUDIO":(.014,"Audio, 15 Hz through 20 kHz"),
"LOW_PULSE":(.022,"Low-power pulse: peak <300 W AND average <5 W"),
"HIGH_PULSE":(.049,"High-power/pulse: peak >=300 W AND average >=5 W"),
"RF":(.13,"RF, 10 kHz through 10 MHz"),
}
def calc_transformer():
banner("SECTION 11.1 — TRANSFORMER PART STRESS")
step(1,"IDENTIFY POPULATION")
part=ask_text("Manufacturer part number / group identifier")
qty=ask_int("Quantity N represented",minimum=1)
step(2,"FUNCTION / MODEL ROUTING")
tt=ask_choice("Transformer category",{k:f"{v[1]} — lambda_b={v[0]}" for k,v in TRANS_TYPES.items()},default=None)
lb,desc=TRANS_TYPES[tt]
basis_mode,basis_ev=select_model_basis(
"Transformer",
"Direct Section 11.1 applicability uses the published transformer function/construction categories and, where applicable, MIL-T-27, MIL-T-21038, or MIL-T-55631 evidence."
)
if tt=="FLYBACK":
flyv=ask_float("Flyback voltage used to verify '<20 V' category [V]",minimum=0)
if flyv>=20: raise ModelApplicabilityError("The published flyback category is '<20 V'.")
elif tt=="AUDIO":
f=ask_float("Operating frequency used for category verification [Hz]",minimum=0)
if not (15<=f<=20000): raise ModelApplicabilityError("Audio category requires 15 Hz through 20 kHz.")
elif tt=="RF":
f=ask_float("Operating frequency used for category verification [Hz]",minimum=0)
if not (1e4<=f<=1e7): raise ModelApplicabilityError("RF category requires 10 kHz through 10 MHz.")
else:
ppk=ask_float("Peak pulse power [W]",minimum=0)
pav=ask_float("Average power [W]",minimum=0)
if tt=="LOW_PULSE" and not (ppk<300 and pav<5):
raise ModelApplicabilityError("Low-power pulse category requires BOTH peak <300 W and average <5 W.")
if tt=="HIGH_PULSE" and not (ppk>=300 and pav>=5):
raise ModelApplicabilityError("High-power pulse category requires BOTH peak >=300 W and average >=5 W; mixed thresholds are not assigned a published category.")
step(3,"ENVIRONMENT")
ek,piE=select_environment(IND_ENV)
step(4,"SECTION 11.3 HOT-SPOT")
ths,thermal=inductive_hotspot(ek,allow_slash=False)
ins_rating=ask_float("Transformer insulation / maximum operating-temperature rating [deg C]")
if ths>ins_rating:
pct=ask_float("Percent of operating time expected above the insulation rating [%]",minimum=0,maximum=100)
if pct>5:
raise ModelApplicabilityError("Section 11.1 assumes insulation rated temperature is not exceeded for more than 5% of the time.")
else:
pct=0.0
piT=arrhenius(ths,.11)
step(5,"QUALITY")
def eligibility(q):
if q=="MIL_SPEC" and basis_mode!="DIRECT":
raise ModelApplicabilityError("MIL-SPEC transformer quality requires direct applicable specification/procurement evidence.")
qk,piQ,qev=select_quality(TRANS_Q,TRANS_Q_DESC,eligibility=eligibility)
step(6,"CALCULATE")
lp=lb*piT*piQ*piE
warnings=[]
if basis_mode!="DIRECT": warnings.append("Alternate/surrogate Section 11.1 model use")
if ths>ins_rating: warnings.append(f"THS exceeds insulation rating during {pct:g}% of operating time; retained only because entered value is <=5%")
factors={"transformer_category":tt,"lambda_b":lb,**thermal,"insulation_rating_C":ins_rating,"pct_time_above_rating":pct,"piT":piT,"quality":qk,"piQ":piQ,"environment":ek,"piE":piE}
basis=f"{basis_mode}; function={desc}; applicability evidence={basis_ev}; quality evidence={qev}"
return finalize_piece_part(part,"11.1","Notice 2 Section 11.1 pages 11-1 through 11-2; Section 11.3 page 11-4","lambda_p=lambda_b*piT*piQ*piE",lp,qty,factors,basis,warnings)
# =============================================================================
# SECTION 6.14 THERMAL HELPER + SECTION 6.1 / 6.4 / 6.11
# =============================================================================
DISC_Q={"JANTXV":.70,"JANTX":1.0,"JAN":2.4,"LOWER":5.5,"PLASTIC":8.0}
DISC_Q_DESC={
"JANTXV":"MIL-S-19500 JANTXV", "JANTX":"MIL-S-19500 JANTX", "JAN":"MIL-S-19500 JAN",
"LOWER":"Lower quality category", "PLASTIC":"Published plastic-device quality category",
}
def select_discrete_quality():
package_is_plastic=ask_yes_no("Is the actual semiconductor package plastic/nonhermetic plastic?",default=None)
package_ev=ask_evidence("Package construction evidence reference")
def eligibility(q):
if q in {"JANTXV","JANTX","JAN"}:
require_attestation(
f"Does the ACTUAL procured part have documented {q} qualification/procurement evidence?",
"Do not credit JAN/JANTX/JANTXV from automotive qualification, temperature rating, or a related military sibling part."
)
if q=="PLASTIC" and not package_is_plastic:
raise ModelApplicabilityError("PLASTIC quality was selected but the package was not identified as plastic.")
if package_is_plastic and q=="LOWER":
raise ModelApplicabilityError("This selected Section 6 model publishes an explicit PLASTIC category; use PLASTIC for a known plastic package rather than silently treating it as LOWER.")
qk,piQ,qev=select_quality(DISC_Q,DISC_Q_DESC,eligibility=eligibility)
return qk,piQ,f"package evidence={package_ev}; quality evidence={qev}"
def semiconductor_thermal(environment):
panel(
"SECTION 6.14 THERMAL INPUT HIERARCHY",
[
"Case temperature TC: detailed worst-case equipment thermal analysis when available; otherwise use the actual environment's Table 6-1 default.",
"thetaJC: compare all applicable vendor, military-specification, Table 6-2, and valid derating-estimate candidates and use the GREATEST applicable value. If none can be determined, use the explicit 70 C/W fallback and flag it.",
"Power P: actual worst-case device dissipation, not rated power by default.",
"TJ,max: use the LOWER authoritative maximum when both military and vendor ratings are available.",
]
)
if ask_yes_no("Is a detailed worst-case equipment thermal analysis available for device case temperature TC?",default=None):
TC=ask_float("Worst-case case temperature TC [deg C]")
tc_source=ask_evidence("Case-temperature thermal-analysis reference")
tc_mode="DETAILED_ANALYSIS"
else:
TC=TABLE_6_1_TC[environment]
tc_source=f"MIL-HDBK-217F Table 6-1 default for {environment}"
tc_mode="TABLE_6_1_DEFAULT"
print(f" -> Using Table 6-1 TC default for {environment}: {TC:g} deg C")
candidates=[]
vendor=ask_float("Vendor thetaJC [deg C/W] (blank if unavailable)",minimum=0,allow_blank=True)
if vendor is not None: candidates.append((vendor,"vendor"))
mil=ask_float("Military specification thetaJC [deg C/W] (blank if unavailable)",minimum=0,allow_blank=True)
if mil is not None: candidates.append((mil,"MIL specification"))
if ask_yes_no("Does the actual package exactly match a package listed in handbook Table 6-2?",default=None):
pkg=ask_choice("Table 6-2 package",{k:f"{k} — thetaJC={v:g} C/W" for k,v in TABLE_6_2_THETA.items()},default=None)
candidates.append((float(TABLE_6_2_THETA[pkg]),f"Table 6-2 {pkg}"))
else:
pkg="NOT_USED"
slope=ask_float("Valid recommended power-derating slope DT [W/deg C] (blank if unavailable/not applicable)",minimum=1e-30,allow_blank=True)
if slope is not None:
candidates.append((1.0/slope,"1/DT derating estimate"))
fallback=False
if candidates:
theta,theta_source=max(candidates,key=lambda x:x[0])
else:
theta=70.0; theta_source="explicit Section 6.14 unresolved-theta fallback"; fallback=True
print(" -> No thetaJC source was available. Using explicit handbook fallback thetaJC=70 C/W.")
P=ask_float("Actual worst-case device power dissipation P [W]",minimum=0)
TJ=TC+theta*P
vendor_max=ask_float("Vendor maximum rated junction temperature TJ,max [deg C] (blank if unavailable)",allow_blank=True)
mil_max=ask_float("Military slash-sheet maximum TJ,max [deg C] (blank if unavailable)",allow_blank=True)
maxima=[x for x in (vendor_max,mil_max) if x is not None]
if not maxima:
raise ModelApplicabilityError("At least one authoritative maximum junction-temperature rating is required to perform the Section 6.14 overstress gate.")
tjmax=min(maxima)
if TJ>tjmax:
raise ModelApplicabilityError(f"Calculated TJ={TJ:.6g} C exceeds controlling TJ,max={tjmax:.6g} C. Section 6 model is not applicable; TJ may not be clipped.")
return TJ,{
"TC_C":TC,"TC_source":tc_source,"TC_mode":tc_mode,
"theta_candidates":candidates,"thetaJC_C_per_W":theta,"theta_source":theta_source,
"theta_70_fallback":fallback,"P_W":P,"TJ_C":TJ,"TJmax_C":tjmax,
"vendor_TJmax_C":vendor_max,"MIL_TJmax_C":mil_max,
}
DIODE_TYPES={
"GENERAL":(.0038,3091,False,"General-purpose analog diode"),
"SWITCHING":(.0010,3091,False,"Switching diode"),
"FAST_RECT":(.025,3091,False,"Fast-recovery power rectifier"),
"SCHOTTKY_POWER":(.0030,3091,False,"Power rectifier / Schottky power diode"),
"HV_STACK":(.0050,3091,False,"Power rectifier high-voltage stack — 0.0050 per junction"),
"TVS":(.0013,3091,True,"Transient suppressor / varistor"),
"CURRENT_REG":(.0034,1925,True,"Current regulator"),
"VOLT_REG_REF":(.0020,1925,True,"Voltage regulator/reference, avalanche or Zener"),
}
def diode_piS(S):
if not 0<=S<=1: raise ModelApplicabilityError("Diode reverse-voltage stress ratio must be within 0 to 1.")
return .054 if S<=.30 else S**2.43
def calc_diode():
banner("SECTION 6.1 — LOW-FREQUENCY DIODE PART STRESS")
step(1,"IDENTIFY POPULATION / SINGLE-DEVICE BOUNDARY")
part=ask_text("Manufacturer part number / group identifier")
qty=ask_int("Physical package quantity N represented",minimum=1)
dtype=ask_choice("Section 6.1 diode category",{k:f"{v[3]} — lambda_b={v[0]}" for k,v in DIODE_TYPES.items()},default=None)
lb,tcoef,unity_stress,desc=DIODE_TYPES[dtype]
if dtype=="HV_STACK":
nj=ask_int("Physical junction count in EACH high-voltage stack",minimum=1)
lb=lb*nj
else:
multi=ask_yes_no("Does one physical package contain multiple separately modeled semiconductor devices/dice/junction devices?",default=None)
if multi:
raise ModelApplicabilityError(
"Section 6 models generally apply to single devices. This notebook will not multiply a single-device diode rate across a multi-device package. Review Section 5.5 hybrid applicability or use an explicitly approved alternate reliability basis."
)
nj=1
step(2,"ENVIRONMENT")
ek,piE=select_environment(DISC_ENV)
step(3,"SECTION 6.14 JUNCTION TEMPERATURE")
TJ,thermal=semiconductor_thermal(ek)
if not (25<=TJ<=175):
raise ModelApplicabilityError("Section 6.1 published temperature-factor table span is 25–175 C; this notebook does not extrapolate outside that published domain.")
piT=exp_temp(TJ,tcoef)
step(4,"ELECTRICAL STRESS")
if unity_stress:
S=None; piS=1.0; stress_basis="published unity-stress category"
else:
va=ask_float("Applied reverse voltage [V]",minimum=0)
vr=ask_float("Rated reverse voltage [V]",minimum=1e-30)
S=va/vr
if S>1: raise ModelApplicabilityError(f"Reverse-voltage stress S={S:.6g} exceeds 1.0.")
piS=diode_piS(S); stress_basis=f"S={va:g}/{vr:g}"
step(5,"CONTACT CONSTRUCTION")
ck=ask_choice("Contact construction",{"M":"Metallurgically bonded — piC=1.0","N":"Non-metallurgically bonded / spring-loaded — piC=2.0"},default=None,help_text="The handbook supplies no unknown-construction numerical default.")
cev=ask_evidence("Contact-construction evidence reference")
piC=1.0 if ck=="M" else 2.0
step(6,"QUALITY")
qk,piQ,qev=select_discrete_quality()
step(7,"CALCULATE")
lp=lb*piT*piS*piC*piQ*piE
warnings=[]
if thermal["theta_70_fallback"]: warnings.append("Section 6.14 thetaJC=70 C/W handbook fallback used")
factors={"diode_category":dtype,"lambda_b":lb,"junction_count_per_stack":nj,**thermal,"piT":piT,"S":S,"piS":piS,"stress_basis":stress_basis,"contact":ck,"piC":piC,"quality":qk,"piQ":piQ,"environment":ek,"piE":piE}
basis=f"Physical classification={desc}; contact evidence={cev}; {qev}"
return finalize_piece_part(part,"6.1","Notice 2 Section 6.1 pages 6-2 through 6-3; Section 6.14 pages 6-23 through 6-24","lambda_p=lambda_b*piT*piS*piC*piQ*piE",lp,qty,factors,basis,warnings)
def calc_fet():
banner("SECTION 6.4 — LOW-FREQUENCY SILICON FET PART STRESS")
step(1,"IDENTIFY POPULATION / APPLICABILITY")
part=ask_text("Manufacturer part number / group identifier")
qty=ask_int("Physical package quantity N represented",minimum=1)
require_attestation("Is each represented package a single silicon FET device (not a multi-die hybrid/package)?","Section 6 models generally apply to single devices unless specifically noted.")
ft=ask_choice("FET type",{"M":"MOSFET — lambda_b=0.012","J":"JFET — lambda_b=0.0045"},default=None)
freq=ask_float("Maximum modeled operating frequency [MHz]",minimum=0)
if freq>400: raise ModelApplicabilityError("Section 6.4 applies to silicon FETs at <=400 MHz. Evaluate Section 6.9 applicability above 400 MHz.")
lb=.012 if ft=="M" else .0045
step(2,"ENVIRONMENT")
ek,piE=select_environment(DISC_ENV)
step(3,"SECTION 6.14 JUNCTION TEMPERATURE")
TJ,thermal=semiconductor_thermal(ek)
if not (25<=TJ<=175): raise ModelApplicabilityError("Section 6.4 published temperature-factor table span is 25–175 C; no extrapolation is performed.")
piT=exp_temp(TJ,1925)
step(4,"APPLICATION FACTOR")
app=ask_choice("Actual FET application",{"L":"Linear amplification, rated power Pr <2 W — piA=1.5","S":"Small-signal switching — piA=0.70","P":"Nonlinear power FET — piA depends on rated power"},default=None)
if app=="L":
pr=ask_float("Rated output power Pr [W]",minimum=0)
if pr>=2: raise ModelApplicabilityError("Linear branch requires rated power Pr <2 W.")
piA=1.5
elif app=="S":
pr=None; piA=.70
else:
pr=ask_float("Rated output power Pr [W]",minimum=2)
if pr<5: piA=2.0
elif pr<50: piA=4.0
elif pr<250: piA=8.0
else: piA=10.0
step(5,"QUALITY")
qk,piQ,qev=select_discrete_quality()
step(6,"CALCULATE")
lp=lb*piT*piA*piQ*piE
warnings=[]
if thermal["theta_70_fallback"]: warnings.append("Section 6.14 thetaJC=70 C/W handbook fallback used")
factors={"FET_type":"MOSFET" if ft=="M" else "JFET","lambda_b":lb,"frequency_MHz":freq,**thermal,"piT":piT,"application":app,"Pr_W":pr,"piA":piA,"quality":qk,"piQ":piQ,"environment":ek,"piE":piE}
basis=f"Silicon FET <=400 MHz; {qev}"
return finalize_piece_part(part,"6.4","Section 6.4 page 6-8; Section 6.14 pages 6-23 through 6-24","lambda_p=lambda_b*piT*piA*piQ*piE",lp,qty,factors,basis,warnings)
OPTO_TYPES={
"PT_DET":(.0055,"Photodetector — phototransistor"),
"PD_DET":(.0040,"Photodetector — photodiode"),
"ISO_PD_SINGLE":(.0025,"Opto-isolator, photodiode output, single device"),
"ISO_PT_SINGLE":(.013,"Opto-isolator, phototransistor output, single device"),
"ISO_DARL_SINGLE":(.013,"Opto-isolator, photodarlington output, single device"),
"ISO_LSR_SINGLE":(.0064,"Opto-isolator, light-sensitive-resistor output, single device"),
"ISO_PD_DUAL":(.0033,"Opto-isolator, photodiode output, dual device"),
"ISO_PT_DUAL":(.017,"Opto-isolator, phototransistor output, dual device"),
"ISO_DARL_DUAL":(.017,"Opto-isolator, photodarlington output, dual device"),
"ISO_LSR_DUAL":(.0086,"Opto-isolator, light-sensitive-resistor output, dual device"),
"IR_LED":(.0013,"Infrared light-emitting diode"),
"LED":(.00023,"Visible light-emitting diode"),
}
def calc_opto():
banner("SECTION 6.11 — OPTOELECTRONICS PART STRESS")
step(1,"IDENTIFY ARCHITECTURE")
part=ask_text("Manufacturer part number / group identifier")
qty=ask_int("Physical package quantity N represented",minimum=1)
ot=ask_choice("Section 6.11 published category",{k:f"{v[1]} — lambda_b={v[0]}" for k,v in OPTO_TYPES.items()},default=None)
lb,desc=OPTO_TYPES[ot]
mapmode=ask_choice("Architecture mapping basis",{"D":"DIRECT — actual architecture matches the selected published category","A":"ALTERNATE — approved analogous Section 6.11 category mapping"},default=None)
mapref=ask_evidence("Architecture / alternate-mapping evidence reference")
step(2,"ENVIRONMENT")
ek,piE=select_environment(OPTO_ENV)
step(3,"SECTION 6.14 JUNCTION TEMPERATURE")
TJ,thermal=semiconductor_thermal(ek)
if not (25<=TJ<=115): raise ModelApplicabilityError("Section 6.11 published temperature domain is 25–115 C; no extrapolation is performed.")
piT=exp_temp(TJ,2790)
step(4,"QUALITY")
qk,piQ,qev=select_discrete_quality()
step(5,"CALCULATE")
lp=lb*piT*piQ*piE
warnings=[]
if mapmode=="A": warnings.append("Approved alternate Section 6.11 architecture mapping used")
if thermal["theta_70_fallback"]: warnings.append("Section 6.14 thetaJC=70 C/W handbook fallback used")
factors={"opto_category":ot,"lambda_b":lb,**thermal,"piT":piT,"quality":qk,"piQ":piQ,"environment":ek,"piE":piE}
basis=f"{mapmode}; category={desc}; architecture evidence={mapref}; {qev}"
return finalize_piece_part(part,"6.11","Section 6.11 page 6-19; Section 6.14 pages 6-23 through 6-24","lambda_p=lambda_b*piT*piQ*piE",lp,qty,factors,basis,warnings)
# =============================================================================
# SECTION 15.1 — GENERAL CONNECTORS
# =============================================================================
CONN_TYPES={
"CIRCULAR":(.0010,"Circular/cylindrical"), "CARD_EDGE":(.040,"Card edge / PCB"),
"HEX":(.15,"Hexagonal"), "RACK_PANEL":(.021,"Rack and panel"),
"RECTANGULAR":(.046,"Rectangular"), "RF_COAX":(.00041,"RF coaxial"),
"TELEPHONE":(.0075,"Telephone"), "POWER":(.0070,"Power"), "TRIAX":(.0036,"Triaxial"),
}
GAUGE_K={32:3.256,30:2.856,28:2.286,24:1.345,22:.989,20:.640,18:.429,16:.274,12:.100}
CONN_Q={"MIL_SPEC":1.0,"LOWER":2.0}
CONN_Q_DESC={"MIL_SPEC":"MIL-SPEC quality","LOWER":"Lower/commercial quality"}
def connector_piK(cycles_per_1000h):
if cycles_per_1000h<0: raise ModelApplicabilityError("Mating cycle rate cannot be negative.")
if cycles_per_1000h<=.05: return 1.0
if cycles_per_1000h<=.5: return 1.5
if cycles_per_1000h<=5: return 2.0
if cycles_per_1000h<=50: return 3.0
return 4.0
def calc_connector():
banner("SECTION 15.1 — GENERAL CONNECTOR PART STRESS","Model basis is one physical mated pair")
step(1,"IDENTIFY MATED-PAIR POPULATION")
part=ask_text("Connector / mated-pair identifier")
qty=ask_int("Number of physical mated pairs represented",minimum=1)
ct=ask_choice("Connector family",{k:f"{v[1]} — lambda_b={v[0]}" for k,v in CONN_TYPES.items()},default=None)
lb,desc=CONN_TYPES[ct]
basis_mode,basis_ev=select_model_basis("Connector","Direct Section 15.1 use requires the actual connector construction/family to match a published connector family/specification basis.")
step(2,"OPERATING TEMPERATURE")
TA=ask_float("Connector ambient temperature [deg C]")
if ct=="RF_COAX":
rm=ask_choice("RF coaxial temperature-rise branch",{"N":"Normal RF coaxial — fixed deltaT=5 C","H":"High-power RF coaxial — fixed deltaT=50 C"},default=None)
dT=5.0 if rm=="N" else 50.0
rise_basis="published normal RF +5 C" if rm=="N" else "published high-power RF +50 C"
else:
tm=ask_choice("Contact temperature-rise method",{"G":"Published contact-gauge/current equation deltaT=kg*i^1.85","A":"Approved alternate validated deltaT (not a direct handbook contact-rise route)"},default=None)
if tm=="G":
g=ask_choice("Contact gauge",{str(k):f"Gauge {k}; kg={v:g}" for k,v in GAUGE_K.items()},default=None)
current=ask_float("Current per contact i [A]",minimum=0)
dT=GAUGE_K[int(g)]*(current**1.85)
rise_basis=f"published gauge/current equation; gauge={g}, current={current:g} A"
else:
dT=ask_float("Validated alternate contact temperature rise deltaT [deg C]",minimum=0)
rref=ask_evidence("Alternate contact-rise analysis / approval reference")
rise_basis=f"ALTERNATE thermal basis: {rref}"
TO=TA+dT
if not (20<=TO<=250): raise ModelApplicabilityError("Section 15.1 printed operating-temperature domain is 20–250 C.")
rating=ask_float("Actual connector maximum applicable temperature rating [deg C]")
check_rating(TO,rating,"Connector operating temperature TO","connector temperature rating")
piT=arrhenius(TO,.14)
step(3,"MATING / UNMATING")
cycles=ask_float("Mating/unmating cycles per 1000 operating hours",minimum=0,help_text="One cycle includes both connect and disconnect. Enter 0 only when that is the documented service profile.")
piK=connector_piK(cycles)
step(4,"QUALITY")
def eligibility(q):
if q=="MIL_SPEC" and basis_mode!="DIRECT": raise ModelApplicabilityError("MIL-SPEC connector quality requires direct applicable specification/procurement evidence.")
qk,piQ,qev=select_quality(CONN_Q,CONN_Q_DESC,eligibility=eligibility)
step(5,"ENVIRONMENT")
ek,piE=select_environment(CONN_ENV)
step(6,"CALCULATE")
lp=lb*piT*piK*piQ*piE
warnings=[]
if basis_mode!="DIRECT": warnings.append("Alternate/surrogate connector-family mapping")
if "ALTERNATE" in rise_basis: warnings.append("Alternate connector thermal-rise basis used")
factors={"family":ct,"lambda_b":lb,"TA_C":TA,"deltaT_C":dT,"TO_C":TO,"temperature_rating_C":rating,"piT":piT,"cycles_per_1000h":cycles,"piK":piK,"quality":qk,"piQ":piQ,"environment":ek,"piE":piE}
basis=f"{basis_mode}; family={desc}; applicability evidence={basis_ev}; rise basis={rise_basis}; quality evidence={qev}"
return finalize_piece_part(part,"15.1","Notice 2 Section 15.1 pages 15-1 through 15-2","lambda_p=lambda_b*piT*piK*piQ*piE",lp,qty,factors,basis,warnings)
# =============================================================================
# SECTION 13.2 — SOLID-STATE / TIME-DELAY RELAYS
# =============================================================================
SSR_Q={"MIL_SPEC":1.0,"COMMERCIAL":1.9}
SSR_Q_DESC={"MIL_SPEC":"MIL-SPEC default quality","COMMERCIAL":"Commercial default quality"}
def calc_ssr():
banner("SECTION 13.2 — SOLID-STATE / TIME-DELAY RELAY")
step(1,"IDENTIFY RELAY")
part=ask_text("Relay part number / group identifier")
qty=ask_int("Quantity N represented",minimum=1)
rt=ask_choice("Relay construction",{"S":"Solid state","T":"Solid-state time delay","H":"Hybrid"},default=None)
appmode,appref=select_model_basis("Section 13.2 relay","Notice 2 identifies MIL-R-28750 solid-state and MIL-R-83726 time-delay/hybrid/solid-state constructions; commercial analogous use should remain explicit.")
step(2,"SELECT MUTUALLY EXCLUSIVE METHOD")
internal=ask_yes_no("Is a COMPLETE, non-overlapping internal-component failure-rate sum available?",default=None,help_text="The handbook identifies the internal-component sum as the most accurate path when sufficient internal information exists. The default model is only for insufficient internal information.")
if internal:
lp=ask_float("Complete internal-sum relay lambda_p [failures/1e6 h]",minimum=0)
iref=ask_evidence("Internal component calculation/sum reference")
factors={"relay_type":rt,"path":"INTERNAL_SUM","entered_internal_lambda":lp}
basis=f"{appmode}; applicability evidence={appref}; complete internal sum reference={iref}; default relay model NOT added"
return finalize_piece_part(part,"13.2","Notice 2 Section 13.2 page 13-3","lambda_p,relay=sum(lambda_p,k)",lp,qty,factors,basis,[])
limitation=ask_text("Document why complete internal component information is insufficient",help_text="This explanation is required because the 0.029*piQ*piE route is expressly the default only when internal-component information is insufficient.")
step(3,"DEFAULT QUALITY AND ENVIRONMENT")
def eligibility(q):
if q=="MIL_SPEC" and appmode!="DIRECT": raise ModelApplicabilityError("MIL-SPEC default quality requires applicable MIL specification/procurement evidence.")
qk,piQ,qev=select_quality(SSR_Q,SSR_Q_DESC,eligibility=eligibility)
ek,piE=select_environment(SSR_ENV)
lb=.029
lp=lb*piQ*piE
factors={"relay_type":rt,"path":"DEFAULT_INSUFFICIENT_INTERNAL_INFO","lambda_b":lb,"quality":qk,"piQ":piQ,"environment":ek,"piE":piE}
basis=f"{appmode}; applicability evidence={appref}; internal information insufficient because: {limitation}; quality evidence={qev}"
return finalize_piece_part(part,"13.2","Notice 2 Section 13.2 page 13-3","lambda_p,default=0.029*piQ*piE",lp,qty,factors,basis,[])
# =============================================================================
# SECTION 16.1 — PTH INTERCONNECTION ASSEMBLY (SUPPLEMENTAL)
# =============================================================================
PTH_Q={"MIL_SPEC_OR_IPC3":1.0,"LOWER":2.0}
PTH_Q_DESC={"MIL_SPEC_OR_IPC3":"MIL-SPEC or comparable IPC Level 3","LOWER":"Lower assembly quality"}
def calc_pth():
banner("SECTION 16.1 — PTH INTERCONNECTION ASSEMBLY","Assembly-level contribution; NOT an intrinsic piece-part lambda")
step(1,"DEFINE ASSEMBLY BOUNDARY")
part=ask_text("Board / PTH assembly identifier")
tech=ask_choice("PTH assembly technology",{"PCB":"Printed wiring assembly / PCB with PTHs — lambda_b=0.000017","DW":"Discrete wiring with electroless-deposited PTHs, <=2 circuit levels — lambda_b=0.00011"},default=None)
n1=ask_int("N1: functional PTHs soldered by automated wave / infrared / vapor-phase methods",minimum=0)
n2=ask_int("N2: functional hand-soldered PTHs",minimum=0)
countref=ask_evidence("PTH count / solder-process evidence reference")
if tech=="PCB":
P=ask_int("Printed wiring board circuit planes P",minimum=2,maximum=18)
lb=.000017; piC=.65*(P**.63)
else:
P=None; lb=.00011; piC=1.0
step(2,"QUALITY")
def eligibility(q):
if q=="MIL_SPEC_OR_IPC3":
require_attestation("Is MIL-SPEC or comparable IPC Level 3 assembly quality documented?","Use piQ=1 only when this basis is actually supported.")
qk,piQ,qev=select_quality(PTH_Q,PTH_Q_DESC,eligibility=eligibility)
step(3,"ENVIRONMENT")
ek,piE=select_environment(PTH_ENV)
step(4,"DOUBLE-COUNTING GATE")
require_attestation("Will these same PTH joints be EXCLUDED from Section 17 connection counting?","Section 16.1 already represents the PTH assembly/soldering defect contribution; the same joints must not be entered again under Section 17.")
auto_term=n1*piC
hand_term=n2*(piC+13)
lp=lb*(auto_term+hand_term)*piQ*piE
factors={"technology":tech,"lambda_b":lb,"N1_auto":n1,"N2_hand":n2,"planes":P,"piC":piC,"automated_term":auto_term,"hand_term":hand_term,"quality":qk,"piQ":piQ,"environment":ek,"piE":piE}
basis=f"PTH count/process evidence={countref}; quality evidence={qev}; Section 17 overlap excluded"
return finalize_supplement(part,"16.1","Notice 2 Section 16.1 page 16-1","lambda_PTH=lambda_b*[N1*piC+N2*(piC+13)]*piQ*piE",lp,factors,basis,[])
# =============================================================================
# SECTION 16.2 — SMT INTERCONNECTION ASSEMBLY (SUPPLEMENTAL WEAKEST LINK)
# =============================================================================
SMT_PI_LC={"LEADLESS":1.0,"J_OR_S":150.0,"GULL_WING":5000.0}
SMT_PACKAGE_TCE={"PLASTIC":7.0,"CERAMIC":6.0}
SMT_CYCLE_DEFAULTS={
"AUTOMOTIVE":1.0,"CONSUMER":.08,"COMPUTER":.17,"TELECOM":.0042,
"COMMERCIAL_AIRCRAFT":.25,"INDUSTRIAL":.021,"MILITARY_GROUND":.03,
"MILITARY_AIRCRAFT_CARGO":.12,"MILITARY_AIRCRAFT_FIGHTER":.5,
}
SMT_DELTA_T_DEFAULTS={"GB":7.0,"GF":21.0,"GM":26.0,"NS":26.0,"NU":61.0,"AIC":31.0,"AIF":31.0,"AUC":57.0,"AUF":57.0,"ARW":31.0,"SF":7.0}
SMT_SUBSTRATE_TCE={
"FR4_LAMINATE":18,"FR4_MULTILAYER":20,"FR4_MULTILAYER_CU_INVAR":11,"CERAMIC_MULTILAYER":7,
"CU_INVAR":5,"CU_MOLY":5,"CARBON_FIBER_EPOXY":1,"KEVLAR_FIBER":3,"QUARTZ_FIBER":1,
"GLASS_FIBER":5,"EPOXY_GLASS":15,"POLYAMIDE_GLASS":13,"POLYAMIDE_KEVLAR":6,
"POLYAMIDE_QUARTZ":8,"EPOXY_KEVLAR":7,"ALUMINA":7,"EPOXY_ARAMID":7,
"POLYAMIDE_ARAMID":6,"EPOXY_QUARTZ":9,"FIBERGLASS_TEFLON":20,
"PORCELAINIZED_CU_INVAR":7,"FIBERGLASS_CERAMIC":7,
}
def smt_ecf(r):
# Preserve printed gaps exactly; do not smooth/interpolate.
intervals=[
(0.00,.10,.13),(.11,.20,.15),(.21,.30,.23),(.31,.40,.31),(.41,.50,.41),
(.51,.60,.51),(.61,.70,.61),(.71,.80,.68),(.81,.90,.76),
]
if r<0: raise ModelApplicabilityError("SMT life ratio r cannot be negative.")
for lo,hi,val in intervals:
if lo<=r<=hi: return val
if r>.90: return 1.0
raise EngineeringDispositionRequired(
f"SMT life ratio r={r:.12g} falls in an unassigned gap between the printed ECF intervals. The source says to flag the gap and not silently smooth/interpolate."
)
def smt_candidate_lambda(d_mil,h_mil,alpha_s,delta_t,alpha_cc,theta,power,pi_lc,cr,life_hours):
if min(d_mil,h_mil,cr,life_hours) <= 0:
raise ModelApplicabilityError("SMT d, h, CR, and life-hours inputs must all be positive.")
trise=theta*power
delta_eps=abs(alpha_s*delta_t - alpha_cc*(delta_t+trise))*1e-6
if delta_eps<=0:
raise ModelApplicabilityError("Calculated SMT strain range is zero; the published fatigue equation cannot be evaluated at zero strain.")
# IMPORTANT source-validation form: exponent applies to the combined normalized geometry*strain term.
# This is the form that reproduces the Notice 2 worked example (Nf≈18,893).
nf=3.5 * (((d_mil/(.65*h_mil))*delta_eps) ** (-2.26)) * pi_lc
alpha_smt=nf/cr
r=life_hours/alpha_smt
ecf=smt_ecf(r)
lam_per_hour=ecf/alpha_smt
lam_1e6=lam_per_hour*1e6
return {
"TRISE_C":trise,"delta_epsilon":delta_eps,"Nf":nf,"alpha_SMT_h":alpha_smt,
"life_ratio_r":r,"ECF":ecf,"lambda_per_hour":lam_per_hour,"lambda_1e6h":lam_1e6,
}
def calc_smt():
banner("SECTION 16.2 — SMT INTERCONNECTION ASSEMBLY","Board-level weakest-link thermal-fatigue contribution")
step(1,"DEFINE BOARD / COMMON SERVICE INPUTS")
board=ask_text("Board / SMT assembly identifier")
env=ask_choice("Actual use environment",{k:ENV_DESC[k] for k in ENV_DESC},default=None)
if ask_yes_no("Use the handbook default deltaT for this environment where published?",default=None):
if env not in SMT_DELTA_T_DEFAULTS:
raise ModelApplicabilityError(f"Section 16.2 default deltaT is N/A for environment {env}; provide a documented thermal profile instead.")
delta_t=SMT_DELTA_T_DEFAULTS[env]
dt_basis=f"handbook default deltaT for {env}"
else:
delta_t=ask_float("Documented assembly thermal-cycle deltaT [deg C]",minimum=0)
dt_basis=ask_evidence("Thermal-cycle deltaT source/reference")
crmode=ask_choice("Thermal cycle-rate CR basis",{"D":"Use a published equipment-type default","A":"Use documented actual cycle rate"},default=None)
if crmode=="D":
crk=ask_choice("Equipment-type default cycle rate",{k:f"{k}; CR={v:g} cycles/calendar h" for k,v in SMT_CYCLE_DEFAULTS.items()},default=None)
cr=SMT_CYCLE_DEFAULTS[crk]; cr_basis=f"published {crk} default"
else:
cr=ask_float("Actual thermal cycle rate CR [cycles/calendar h]",minimum=1e-30)
cr_basis=ask_evidence("Actual cycle-rate source/reference")
submode=ask_choice("Substrate TCE alphaS basis",{"D":"Use a published substrate default","A":"Use documented actual substrate TCE"},default=None)
if submode=="D":
sk=ask_choice("Substrate material",{k:f"{k}; alphaS={v:g} ppm/C" for k,v in SMT_SUBSTRATE_TCE.items()},default=None)
alpha_s=float(SMT_SUBSTRATE_TCE[sk]); sub_basis=f"published default {sk}"
else:
alpha_s=ask_float("Actual substrate TCE alphaS [ppm/deg C]",minimum=0)
sub_basis=ask_evidence("Substrate TCE source/reference")
life_hours=ask_float("Evaluation/service life LC [hours on the same time basis as alphaSMT]",minimum=1e-30)
step(2,"EVALUATE EVERY DISTINCT SMT PACKAGE CANDIDATE")
panel("WEAKEST-LINK RULE","Every SMT component/candidate must be represented. Candidate rates are NOT summed. The board contribution is the maximum candidate rate.")
candidates=[]
while True:
cid=ask_text("SMT candidate/group identifier")
lead=ask_choice("Lead configuration",{"LEADLESS":"Leadless — piLC=1; enter actual joint height h","J_OR_S":"J or S lead — piLC=150; h=8 mil","GULL_WING":"Gull wing — piLC=5000; h=8 mil"},default=None)
piLC=SMT_PI_LC[lead]
d=ask_float("Distance d from package center to furthest solder joint [mil]",minimum=1e-30)
if lead=="LEADLESS":
h=ask_float("Solder-joint height h [mil]",minimum=1e-30)
else:
h=8.0
print(" -> Using published h=8 mil for leaded configuration.")
pmode=ask_choice("Package TCE alphaCC basis",{"D":"Use handbook material default: plastic=7 or ceramic=6 ppm/C","A":"Use documented actual package TCE"},default=None)
if pmode=="D":
pk=ask_choice("Package material",{k:f"{k}; alphaCC={v:g} ppm/C" for k,v in SMT_PACKAGE_TCE.items()},default=None)
alpha_cc=SMT_PACKAGE_TCE[pk]; pkg_basis=f"published {pk} default"
else:
alpha_cc=ask_float("Actual package TCE alphaCC [ppm/deg C]",minimum=0)
pkg_basis=ask_evidence("Package TCE source/reference")
theta=ask_float("Package thetaJC [deg C/W] used for TRISE",minimum=0)
power=ask_float("Package power P [W] used for TRISE",minimum=0)
vals=smt_candidate_lambda(d,h,alpha_s,delta_t,alpha_cc,theta,power,piLC,cr,life_hours)
vals.update({"id":cid,"lead":lead,"piLC":piLC,"d_mil":d,"h_mil":h,"alphaS_ppm_C":alpha_s,"alphaCC_ppm_C":alpha_cc,"thetaJC_C_W":theta,"P_W":power,"package_TCE_basis":pkg_basis})
candidates.append(vals)
panel("CANDIDATE RESULT",[f"{cid}: Nf={vals['Nf']:.10g}",f"alphaSMT={vals['alpha_SMT_h']:.10g} h",f"r={vals['life_ratio_r']:.10g}; ECF={vals['ECF']}",f"candidate lambda={vals['lambda_1e6h']:.10g} failures/1e6 h"])
if not ask_yes_no("Add another distinct SMT candidate/group?",default=True):
break
step(3,"COMPLETENESS / WEAKEST-LINK GATE")
require_attestation("Are ALL SMT components on the defined board represented by the entered candidates/equivalent groups?","If a potentially governing SMT package is omitted, the max() result is not a valid board-level weakest-link result.")
weakest=max(candidates,key=lambda x:x["lambda_1e6h"])
line=weakest["lambda_1e6h"]
factors={"environment":env,"deltaT_C":delta_t,"deltaT_basis":dt_basis,"CR_cycles_per_h":cr,"CR_basis":cr_basis,"alphaS_ppm_C":alpha_s,"substrate_basis":sub_basis,"LC_h":life_hours,"candidate_count":len(candidates),"governing_candidate":weakest["id"],"governing_candidate_lambda":line}
basis=f"Complete SMT candidate set attested; candidate rates not summed; governing candidate={weakest['id']}"
warnings=["Section 16.2 represents thermal-fatigue wearout and expressly excludes solder/lead manufacturing defects; preserve separate defect accounting as applicable"]
return finalize_supplement(board,"16.2","Notice 2 Section 16.2 pages 16-2 through 16-4","lambda_SMT,board=max_j[ECF_j/alphaSMT_j]",line,factors,basis,warnings)
# =============================================================================
# SECTION 17.1 — INDIVIDUAL CONNECTIONS (SUPPLEMENTAL)
# =============================================================================
CONNECTION_TYPES={
"HAND_SOLDER":.0013,"HAND_SOLDER_WRAPPED":.000070,"CRIMP":.00026,"WELD":.000015,
"SOLDERLESS_WRAP":.0000068,"CLIP":.00012,"REFLOW":.000069,"SPRING_CONTACT":.17,"TERMINAL_BLOCK":.062,
}
def calc_connection():
banner("SECTION 17.1 — INDIVIDUAL CONNECTIONS","Only connections outside the Section 16 PTH/SMT boundary")
step(1,"EXCLUSION GATE")
part=ask_text("Connection group / identifier")
represented=ask_yes_no("Are these physical joints already represented by Section 16 PTH or SMT?",default=None)
if represented:
raise ModelApplicabilityError("Section 17 must not be used for joints already represented by Section 16.")
qty=ask_int("Number of equivalent physical connections",minimum=1)
require_attestation("Do all grouped connections have the same connection type and modeled environment?","Quantity multiplication is valid only for equivalent grouped connections.")
step(2,"CONNECTION TYPE / ENVIRONMENT")
ct=ask_choice("Connection type",{k:f"{k} — lambda_b={v:g}" for k,v in CONNECTION_TYPES.items()},default=None)
ek,piE=select_environment(CONNECTION_ENV)
lb=CONNECTION_TYPES[ct]
per=lb*piE
line=qty*per
factors={"connection_type":ct,"lambda_b":lb,"quantity":qty,"environment":ek,"piE":piE,"per_connection_lambda":per}
basis="Section 17.1 used only for equivalent eligible connections outside Section 16; no quality factor exists in the current equation"
return finalize_supplement(part,"17.1","Notice 2 Section 17.1 page 17-1","lambda_line=N*lambda_b*piE",line,factors,basis,[])
# =============================================================================
# SESSION / EXPORT / TESTS
# =============================================================================
CALCULATORS={
"1":("Resistor — Section 9.1",calc_resistor),
"2":("Capacitor — Section 10.1",calc_capacitor),
"3":("Coil / inductor — Section 11.2",calc_coil),
"4":("Transformer — Section 11.1",calc_transformer),
"5":("Low-frequency diode — Section 6.1",calc_diode),
"6":("Low-frequency silicon FET — Section 6.4",calc_fet),
"7":("Optoelectronic — Section 6.11",calc_opto),
"8":("General connector / mated pair — Section 15.1",calc_connector),
"9":("Solid-state / time-delay relay — Section 13.2",calc_ssr),
"10":("PTH interconnection assembly — Section 16.1 [supplemental]",calc_pth),
"11":("SMT interconnection assembly — Section 16.2 [supplemental weakest-link]",calc_smt),
"12":("Individual connection outside Section 16 — Section 17.1 [supplemental]",calc_connection),
"X":("Exit / show session summary",None),
}
def session_summary():
banner("SESSION SUMMARY")
selected=[r for r in RESULTS if r["status"]=="SELECTED_PART_STRESS_REPLACEMENT"]
evaluated=[r for r in RESULTS if r["status"]=="EVALUATED_ONLY_NOT_SELECTED"]
supplemental=[r for r in RESULTS if r["status"]=="SUPPLEMENTAL_MAIN_BODY_CONTRIBUTION"]
sel_total=sum(r["line_lambda"] for r in selected)
supp_total=sum(r["line_lambda"] for r in supplemental)
print(f"Selected Part Stress replacements : {len(selected)}")
print(f"Evaluated but NOT selected : {len(evaluated)}")
print(f"Supplemental main-body entries : {len(supplemental)}")
print(f"Selected replacement subtotal : {sel_total:.12g} failures/1e6 h")
print(f"Supplemental subtotal : {supp_total:.12g} failures/1e6 h")
print("\nIMPORTANT: these subtotals are not automatically the complete equipment lambda. They must be integrated")
print("with the remaining non-overlapping Appendix A / main-body contributions at the defined equipment boundary.")
return {"selected":selected,"evaluated":evaluated,"supplemental":supplemental}
def export_results_csv(path="PSSC_results.csv"):
path=Path(path)
fields=["kind","status","part","section","lambda_p","quantity","line_lambda","source","formula","basis","selection_reference","warnings","note"]
with path.open("w",newline="",encoding="utf-8-sig") as f:
w=csv.DictWriter(f,fieldnames=fields)
w.writeheader()
for r in RESULTS:
row={k:r.get(k,"") for k in fields}
row["warnings"]=" | ".join(r.get("warnings",[]))
w.writerow(row)
print(f"Exported {len(RESULTS)} result records to: {path.resolve()}")
return path
def run_console():
banner("MIL-HDBK-217F APPENDIX A — PART STRESS SUPPLEMENT / REPLACEMENT CALCULATOR","Source-locked console build | ICs / microcircuits intentionally excluded")
panel("ACCOUNTING RULES",[
"Piece-part Part Stress results are replacement CANDIDATES for the same Appendix A physical population. The program will never automatically choose the smaller lambda.",
"A selected Part Stress replacement requires confirmation that the corresponding Appendix A population will be excluded.",
"Sections 16.1, 16.2 and 17.1 are displayed separately as supplemental assembly/connection contributions because they are not ordinary intrinsic piece-part replacement rates.",
"Unsupported model domains, missing mandatory evidence, overstress, ambiguous multi-device semiconductor packages, and source-table gaps cause a hard stop instead of an invented value.",
])
while True:
key=ask_choice("MAIN MENU",{k:v[0] for k,v in CALCULATORS.items()},default=None)
if key=="X": break
try:
CALCULATORS[key][1]()
except (ModelApplicabilityError,EngineeringDispositionRequired,ValueError) as exc:
stop_message(exc)
except KeyboardInterrupt:
print("\nCalculation cancelled by user; no result record added.")
if not ask_yes_no("Return to the main menu for another calculation?",default=True):
break
summary=session_summary()
if RESULTS and ask_yes_no("Export all result records and NOTE text to CSV?",default=False):
name=ask_text("CSV output filename",default="PSSC_results.csv")
while Path(name).name != name or Path(name).suffix.lower() != ".csv" or any(c in name for c in "/\\:\x00"):
print("Enter a CSV filename without a directory path.")
name=ask_text("CSV output filename",default="PSSC_results.csv")
export_results_csv(name)
return summary
def run_self_tests(verbose=True):
"""Source-value / worked-example acceptance checks. Raises AssertionError on failure."""
# Section 9.1 normalization and stress checks
assert math.isclose(arrhenius(25,.20),1.0,rel_tol=0,abs_tol=1e-12)
assert math.isclose(arrhenius(25,.08),1.0,rel_tol=0,abs_tol=1e-12)
assert math.isclose(1.0**.39,1.0,rel_tol=0,abs_tol=1e-12)
assert math.isclose(resistor_piS(1,.5),.71*math.exp(.55),rel_tol=0,abs_tol=1e-12)
assert math.isclose(resistor_piS(2,.5),.54*math.exp(1.02),rel_tol=0,abs_tol=1e-12)
# Section 10.1 Notice 2 continuous-equation worked example check (~0.04656)
cap_piT=arrhenius(50,.15)
cap_piC=.015**.09
cap_S=(200+math.sqrt(2)*50)/400
cap_piV=capacitor_piV(1,cap_S)
cap_lp=.00051*cap_piT*cap_piC*cap_piV*1.0*3.0*10.0
assert math.isclose(cap_piT,1.5716449017549696,rel_tol=1e-12)
assert math.isclose(cap_lp,.04656,rel_tol=.002) # source inventory gives approximately 0.04656
# Section 11.2 fixed coil at 25 C, MIL-SPEC, GB
assert math.isclose(.000030*arrhenius(25,.11)*1*1,.000030,rel_tol=0,abs_tol=1e-15)
# Section 6 normalizations
assert math.isclose(exp_temp(25,3091),1.0,rel_tol=0,abs_tol=1e-12)
assert math.isclose(exp_temp(25,1925),1.0,rel_tol=0,abs_tol=1e-12)
assert math.isclose(exp_temp(25,2790),1.0,rel_tol=0,abs_tol=1e-12)
assert math.isclose(diode_piS(1.0),1.0,rel_tol=0,abs_tol=1e-12)
# Section 15.1 normalization
assert math.isclose(arrhenius(25,.14),1.0,rel_tol=0,abs_tol=1e-12)
assert connector_piK(.01)==1.0 and connector_piK(.1)==1.5 and connector_piK(1)==2.0 and connector_piK(10)==3.0 and connector_piK(51)==4.0
# Section 13.2 default MIL-SPEC GB
assert math.isclose(.029*1.0*1.0,.029,rel_tol=0,abs_tol=1e-15)
# Appendix A raw Rate_Database reconstruction example: 42 * .0035 * 10 = 1.47
assert math.isclose(42*.0035*10,1.47,rel_tol=0,abs_tol=1e-15)
# Section 16.2 Notice 2 worked example: Nf ~18,893; alpha~629,767 h; lambda~0.4/1e6 h
alpha=15; dt=21; acc=7; trise_theta=10; power=1; d=740; h=5; cr=.03
# choose life to give source example r≈.28; 176330 h is consistent with the unrounded model
vals=smt_candidate_lambda(d,h,alpha,dt,acc,trise_theta,power,1.0,cr,176330.1590018427)
assert math.isclose(vals["Nf"],18893,rel_tol=5e-5)
assert math.isclose(vals["alpha_SMT_h"],629767,rel_tol=5e-5)
assert math.isclose(vals["life_ratio_r"],.28,rel_tol=5e-5)
assert vals["ECF"]==.23
assert math.isclose(vals["lambda_1e6h"],.3652,rel_tol=.001)
if verbose:
banner("SELF-TESTS PASSED")
print("All source-normalization and worked-example acceptance checks passed.")
print("The notebook is ready for interactive use; model-domain/evidence gates remain mandatory.")
return True
if __name__ == "__main__":
run_self_tests()
run_console()
MTBF_AGGREGATOR.py · system ledger, exposure curve, and report
"""
Customer-Ready System MTBF Aggregator
=====================================
Interactive Jupyter-console workflow for combining previously calculated,
non-overlapping constant failure-rate contributions into a system-level
failure rate and reciprocal predicted MTBF.
The calculation does not replace the upstream MIL-HDBK-217F component or
subassembly calculations. It normalizes their reportable outputs to a common
failure-rate basis, performs controlled system aggregation, and creates a
single-page black-and-white engineering report plus a detailed CSV ledger.
"""
from __future__ import annotations
import csv
import math
import re
import tempfile
import textwrap
from dataclasses import dataclass
from datetime import date
from pathlib import Path
from typing import Dict, List, Optional, Tuple
try:
import matplotlib.pyplot as plt
from matplotlib.ticker import PercentFormatter
from reportlab.lib import colors
from reportlab.lib.pagesizes import letter
from reportlab.pdfbase.pdfmetrics import stringWidth
from reportlab.pdfgen import canvas
from reportlab.platypus import Paragraph, Table, TableStyle
from reportlab.lib.styles import ParagraphStyle
except Exception as exc:
raise ImportError(
"This notebook requires matplotlib and reportlab. Run the setup cell first, "
"or in Jupyter execute: %pip install matplotlib reportlab"
) from exc
MILLION = 1_000_000.0
DEFAULT_HORIZON_YEARS = 40.0
DEFAULT_OPERATING_HOURS_PER_YEAR = 8760.0
RATE_BASIS = "failures / 10^6 operating h"
SOURCE_METHODS = {
"1": "Appendix A Parts Count output",
"2": "MIL-HDBK-217F Part Stress output / replacement",
"3": "Approved direct or alternate constant failure rate",
"4": "Previously aggregated board / subassembly total",
"5": "Other validated constant-rate source",
}
RECORD_KINDS = {
"1": "Component or homogeneous component-group contribution",
"2": "Connector contribution",
"3": "Interconnection assembly contribution",
"4": "Discrete connection contribution",
"5": "Module contribution",
"6": "Board / subassembly aggregate total",
"7": "Assembly aggregate total",
"8": "Other validated contribution",
}
INPUT_FORMS = {
"1": "Per-unit lambda in failures / 10^6 operating h - quantity WILL be applied",
"2": "Reportable line / total lambda in failures / 10^6 operating h - quantity will NOT be applied again",
"3": "Per-unit MTBF in operating hours - converted to lambda and quantity WILL be applied",
"4": "Reportable aggregate MTBF in operating hours - converted to lambda; quantity will NOT be applied again",
"5": "Per-unit lambda in failures / operating h - converted to /10^6 h and quantity WILL be applied",
"6": "Reportable aggregate lambda in failures / operating h - converted to /10^6 h; quantity will NOT be applied again",
}
AGGREGATE_KINDS = {"Board / subassembly aggregate total", "Assembly aggregate total"}
@dataclass
class Contribution:
sequence: int
subassembly_pn: str
item_id: str
description: str
record_kind: str
quantity: int
source_method: str
source_reference: str
traceability_reference: str
input_form: str
input_value: float
input_units: str
per_unit_lambda_1e6h: Optional[float]
contribution_lambda_1e6h: float
include: bool
exclusion_reason: str
note: str
is_aggregate_total: bool
zero_rate_flag: bool
percent_of_total: float = 0.0
# =============================================================================
# Console / HMI helpers
# =============================================================================
def _wrap(text: str, width: int = 96) -> str:
out = []
for para in str(text).split("\n"):
if para.strip():
out.append("\n".join(textwrap.wrap(para, width=width, replace_whitespace=False)))
else:
out.append("")
return "\n".join(out)
def rule(char: str = "-", width: int = 96) -> None:
print(char * width)
def section(title: str, explanation: str = "") -> None:
print()
rule("=")
print(title)
rule("=")
if explanation:
print(_wrap(explanation))
def explain(what: str, why: str = "", example: str = "", caution: str = "") -> None:
print()
print(_wrap("WHAT TO ENTER: " + what))
if why:
print(_wrap("WHY IT IS NEEDED: " + why))
if example:
print(_wrap("EXAMPLE: " + example))
if caution:
print(_wrap("IMPORTANT: " + caution))
def ask_required(prompt: str) -> str:
while True:
v = input(prompt).strip()
if v:
return v
print(" A response is required.")
def ask_optional(prompt: str, default: str = "") -> str:
suffix = f" [{default}]" if default else ""
v = input(f"{prompt}{suffix}: ").strip()
return v if v else default
def ask_yes_no(prompt: str, default: Optional[bool] = None) -> bool:
suffix = " [Y/n]: " if default is True else " [y/N]: " if default is False else " [y/n]: "
while True:
v = input(prompt + suffix).strip().lower()
if not v and default is not None:
return default
if v in {"y", "yes"}:
return True
if v in {"n", "no"}:
return False
print(" Enter Y or N.")
def ask_float(prompt: str, *, min_value: Optional[float] = None,
allow_zero: bool = True, default: Optional[float] = None) -> float:
while True:
suffix = f" [{default:g}]" if default is not None else ""
raw = input(f"{prompt}{suffix}: ").strip()
if not raw and default is not None:
value = float(default)
else:
try:
value = float(raw)
except ValueError:
print(" Enter a numeric value.")
continue
if not math.isfinite(value):
print(" Value must be finite.")
continue
if min_value is not None and value < min_value:
print(f" Value must be >= {min_value}.")
continue
if not allow_zero and value == 0:
print(" Zero is not permitted for this field.")
continue
return value
def ask_int(prompt: str, *, min_value: int = 0, default: Optional[int] = None) -> int:
while True:
suffix = f" [{default}]" if default is not None else ""
raw = input(f"{prompt}{suffix}: ").strip()
if not raw and default is not None:
v = default
else:
try:
v = int(raw)
except ValueError:
print(" Enter a whole number.")
continue
if v < min_value:
print(f" Value must be >= {min_value}.")
continue
return v
def ask_choice(title: str, options: Dict[str, str]) -> Tuple[str, str]:
print()
print(title)
for key, label in options.items():
print(f" {key}. {label}")
while True:
v = input("Selection: ").strip()
if v in options:
return v, options[v]
print(" Enter one of the listed selection numbers.")
def sanitize_filename(text: str) -> str:
text = re.sub(r"[^A-Za-z0-9._-]+", "_", text.strip())
text = re.sub(r"_+", "_", text).strip("_.")
return text or "System"
def unique_path(path: Path) -> Path:
if not path.exists():
return path
for i in range(2, 10000):
p = path.with_name(f"{path.stem}_{i}{path.suffix}")
if not p.exists():
return p
raise RuntimeError("Could not create a unique output filename.")
# =============================================================================
# Calculation functions
# =============================================================================
def normalize_input(form_key: str, value: float, quantity: int) -> Tuple[Optional[float], float, str]:
if quantity < 1:
raise ValueError("Quantity must be at least 1 for an included physical contribution.")
if value < 0 or not math.isfinite(value):
raise ValueError("Failure-rate and MTBF inputs must be finite and nonnegative.")
if form_key == "1":
per_unit = value
return per_unit, per_unit * quantity, "failures/1e6 h"
if form_key == "2":
return None, value, "failures/1e6 h"
if form_key == "3":
if value <= 0:
raise ValueError("A finite MTBF must be > 0 hours.")
per_unit = MILLION / value
return per_unit, per_unit * quantity, "hours"
if form_key == "4":
if value <= 0:
raise ValueError("A finite aggregate MTBF must be > 0 hours.")
return None, MILLION / value, "hours"
if form_key == "5":
per_unit = value * MILLION
return per_unit, per_unit * quantity, "failures/hour"
if form_key == "6":
return None, value * MILLION, "failures/hour"
raise ValueError("Unknown input form.")
def aggregate_system(records: List[Contribution]) -> Dict[str, float]:
included = [r for r in records if r.include]
if not included:
raise ValueError("At least one included reliability contribution is required.")
total = sum(r.contribution_lambda_1e6h for r in included)
if not math.isfinite(total) or total <= 0 or not math.isfinite(MILLION / total):
raise ValueError("Total included failure rate must be > 0 to report a finite MTBF.")
for r in records:
r.percent_of_total = 100.0 * r.contribution_lambda_1e6h / total if r.include else 0.0
return {
"lambda_total_1e6h": total,
"lambda_total_hour": total * 1e-6,
"mtbf_hours": MILLION / total,
}
def reliability(lambda_hour: float, operating_hours: float) -> float:
return math.exp(-lambda_hour * operating_hours)
def failure_function(lambda_hour: float, operating_hours: float) -> float:
return 1.0 - reliability(lambda_hour, operating_hours)
def overlap_conflict(records: List[Contribution], candidate: Contribution) -> Optional[str]:
if not candidate.include:
return None
same = [r for r in records if r.include and r.subassembly_pn.strip().upper() == candidate.subassembly_pn.strip().upper()]
if not same:
return None
if candidate.is_aggregate_total:
return (
f"Subassembly '{candidate.subassembly_pn}' already contains included child contributions. "
"Adding its aggregate total would double count the same physical population."
)
if any(r.is_aggregate_total for r in same):
return (
f"Subassembly '{candidate.subassembly_pn}' already has an included aggregate total. "
"Adding a child contribution would double count part of that aggregate."
)
return None
def find_duplicate_ids(records: List[Contribution]) -> List[Tuple[str, str]]:
seen = set()
duplicates = []
for r in records:
if not r.include:
continue
key = (r.subassembly_pn.strip().upper(), r.item_id.strip().upper())
if key in seen and key not in duplicates:
duplicates.append(key)
seen.add(key)
return duplicates
# =============================================================================
# Audit ledger
# =============================================================================
def write_ledger_csv(records: List[Contribution], output_path: Path) -> Path:
output_path = unique_path(output_path)
fields = [
"Sequence", "Subassembly_PN", "Item_ID", "Description", "Record_Kind", "Quantity",
"Source_Method", "Numeric_Source_Reference", "Traceability_Evidence", "Input_Form",
"Input_Value", "Input_Units", "Per_Unit_Lambda_1E6h", "Contribution_Lambda_1E6h",
"Percent_of_System_Lambda", "Include", "Exclusion_Reason", "Is_Aggregate_Total",
"Zero_Rate_Flag", "Technical_Note"
]
with output_path.open("w", newline="", encoding="utf-8") as f:
w = csv.DictWriter(f, fieldnames=fields)
w.writeheader()
for r in records:
w.writerow({
"Sequence": r.sequence,
"Subassembly_PN": r.subassembly_pn,
"Item_ID": r.item_id,
"Description": r.description,
"Record_Kind": r.record_kind,
"Quantity": r.quantity,
"Source_Method": r.source_method,
"Numeric_Source_Reference": r.source_reference,
"Traceability_Evidence": r.traceability_reference,
"Input_Form": r.input_form,
"Input_Value": f"{r.input_value:.15g}",
"Input_Units": r.input_units,
"Per_Unit_Lambda_1E6h": "" if r.per_unit_lambda_1e6h is None else f"{r.per_unit_lambda_1e6h:.15g}",
"Contribution_Lambda_1E6h": f"{r.contribution_lambda_1e6h:.15g}",
"Percent_of_System_Lambda": f"{r.percent_of_total:.10g}",
"Include": "YES" if r.include else "NO",
"Exclusion_Reason": r.exclusion_reason,
"Is_Aggregate_Total": "YES" if r.is_aggregate_total else "NO",
"Zero_Rate_Flag": "YES" if r.zero_rate_flag else "NO",
"Technical_Note": r.note,
})
return output_path
# =============================================================================
# PDF rendering helpers - black / white / grayscale only
# =============================================================================
BLACK = colors.black
WHITE = colors.white
G90 = colors.HexColor("#E6E6E6")
G95 = colors.HexColor("#F2F2F2")
G80 = colors.HexColor("#CCCCCC")
G55 = colors.HexColor("#8C8C8C")
G35 = colors.HexColor("#595959")
def _safe(text: object) -> str:
return str(text).replace("&", "&").replace("<", "<").replace(">", ">")
def _p(text: object, size: float, leading: Optional[float] = None,
bold: bool = False, align: int = 1, color=BLACK) -> Paragraph:
if leading is None:
leading = size * 1.12
style = ParagraphStyle(
name="mtbf_cell",
fontName="Helvetica-Bold" if bold else "Helvetica",
fontSize=size,
leading=leading,
alignment=align,
textColor=color,
spaceBefore=0,
spaceAfter=0,
)
return Paragraph(_safe(text), style)
def _fit_center(c, text: object, cx: float, y: float, max_width: float,
font: str, size: float, min_size: float = 4.2, color=BLACK) -> None:
txt = str(text)
s = size
while s > min_size and stringWidth(txt, font, s) > max_width:
s -= 0.12
c.setFillColor(color)
c.setFont(font, s)
c.drawCentredString(cx, y, txt)
def _section_rule(c, title: str, x: float, y: float, w: float) -> None:
c.setStrokeColor(G55)
c.setLineWidth(0.4)
c.line(x, y, x + w, y)
_fit_center(c, title.upper(), x + w/2, y + 4.5, w - 8, "Helvetica-Bold", 6.2, 5.0, BLACK)
def _draw_metric_card(c, x: float, y: float, w: float, h: float,
label: str, value: str, unit: str) -> None:
c.setFillColor(G95)
c.setStrokeColor(G80)
c.setLineWidth(0.45)
c.roundRect(x, y, w, h, 3.2, fill=1, stroke=1)
_fit_center(c, label.upper(), x + w/2, y + h - 13, w - 10, "Helvetica-Bold", 5.5, 4.6, G35)
_fit_center(c, value, x + w/2, y + h/2 - 1.5, w - 12, "Helvetica-Bold", 13.0, 8.0, BLACK)
_fit_center(c, unit, x + w/2, y + 8.5, w - 10, "Helvetica", 5.0, 4.1, G35)
def _method_short(method: str) -> str:
m = method.lower()
if "parts count" in m:
return "Parts Count"
if "part stress" in m:
return "Part Stress"
if "direct" in m or "alternate" in m:
return "Direct / Alt."
if "aggregated" in m:
return "Aggregate"
return "Validated"
def _report_rows(records: List[Contribution], total: float) -> Tuple[List[Dict[str, object]], bool]:
included = [r for r in records if r.include]
# Show item-level records when practical. With a larger model, roll the PDF up
# by subassembly so every subassembly remains visible; the CSV preserves every item.
if len(included) <= 18:
return ([{
"subassembly": r.subassembly_pn,
"item": r.item_id,
"qty": str(r.quantity),
"basis": _method_short(r.source_method),
"lambda": r.contribution_lambda_1e6h,
"pct": r.percent_of_total,
"source": r.source_reference,
"trace": r.traceability_reference or "-",
} for r in included], False)
groups: Dict[str, List[Contribution]] = {}
order: List[str] = []
for r in included:
k = r.subassembly_pn.strip() or "UNSPECIFIED"
if k not in groups:
groups[k] = []
order.append(k)
groups[k].append(r)
rows = []
for k in order:
rr = groups[k]
lam = sum(x.contribution_lambda_1e6h for x in rr)
source_refs = []
trace_refs = []
methods = []
for x in rr:
sr = x.source_reference.strip()
tr = x.traceability_reference.strip()
ms = _method_short(x.source_method)
if sr and sr not in source_refs:
source_refs.append(sr)
if tr and tr not in trace_refs:
trace_refs.append(tr)
if ms not in methods:
methods.append(ms)
source = "; ".join(source_refs[:2]) + (f"; +{len(source_refs)-2}" if len(source_refs)>2 else "")
trace = "; ".join(trace_refs[:2]) + (f"; +{len(trace_refs)-2}" if len(trace_refs)>2 else "")
rows.append({
"subassembly": k,
"item": f"{len(rr)} records",
"qty": "-",
"basis": "/".join(methods)[:24],
"lambda": lam,
"pct": 100.0 * lam / total,
"source": source,
"trace": trace or "-",
})
return rows, True
def create_failure_plot(lambda_hour: float, hours_per_year: float, horizon_years: float,
mtbf_hours: float, output_png: Path) -> None:
years = [horizon_years * i / 600 for i in range(601)]
fvals = [failure_function(lambda_hour, y * hours_per_year) for y in years]
mtbf_years = mtbf_hours / hours_per_year
f_end = fvals[-1]
fig, ax = plt.subplots(figsize=(7.6, 2.45), dpi=240)
fig.patch.set_facecolor("white")
ax.set_facecolor("white")
ax.plot(years, fvals, color="black", linewidth=1.35)
ax.fill_between(years, fvals, 0, color="0.94", linewidth=0)
if 0 < mtbf_years <= horizon_years:
y_mtbf = failure_function(lambda_hour, mtbf_years * hours_per_year)
ax.axvline(mtbf_years, color="0.38", linestyle=(0, (3, 3)), linewidth=0.65)
ax.scatter([mtbf_years], [y_mtbf], color="black", s=10, zorder=4)
ax.annotate(
f"MTBF = {mtbf_years:.2f} calendar y",
xy=(mtbf_years, y_mtbf), xytext=(5, 7), textcoords="offset points",
fontsize=6.0, ha="left", va="bottom",
bbox=dict(boxstyle="round,pad=0.18", fc="white", ec="0.7", lw=0.4)
)
ax.scatter([horizon_years], [f_end], color="black", s=12, zorder=4)
ax.annotate(
f"F({horizon_years:g} y) = {100*f_end:.2f}%",
xy=(horizon_years, f_end), xytext=(-6, -14), textcoords="offset points",
fontsize=6.0, ha="right", va="top",
bbox=dict(boxstyle="round,pad=0.18", fc="white", ec="0.7", lw=0.4)
)
ax.set_xlim(0, horizon_years)
ax.set_ylim(0, 1.0)
ax.set_xlabel("Calendar time (years)", fontsize=6.8)
ax.set_ylabel("Cumulative failure probability, F(t)", fontsize=6.8)
ax.yaxis.set_major_formatter(PercentFormatter(xmax=1.0, decimals=0))
ax.tick_params(axis="both", labelsize=5.9, width=0.45, length=2.4, pad=2)
ax.grid(True, color="0.88", linewidth=0.35)
for spine in ax.spines.values():
spine.set_color("0.30")
spine.set_linewidth(0.55)
fig.tight_layout(pad=0.55)
fig.savefig(output_png, dpi=240, bbox_inches="tight", facecolor="white")
plt.close(fig)
def _contribution_profile(n: int, available_h: float) -> Tuple[float, float, float]:
# row height, font size, leading
for rh, fs, ld in [
(21.0, 6.1, 6.9), (18.0, 5.8, 6.5), (15.0, 5.35, 6.0),
(12.6, 4.95, 5.55), (10.7, 4.55, 5.05), (9.3, 4.15, 4.6)
]:
if 20 + n * rh <= available_h:
return rh, fs, ld
rh = max(8.3, (available_h - 20) / max(n, 1))
fs = max(3.8, min(4.1, rh * 0.43))
return rh, fs, max(fs + 0.35, rh * 0.48)
def create_report_pdf(metadata: Dict[str, str], records: List[Contribution], metrics: Dict[str, float],
hours_per_year: float, horizon_years: float, output_path: Path,
ledger_filename: str) -> Path:
output_path = unique_path(output_path)
W, H = letter
c = canvas.Canvas(str(output_path), pagesize=letter)
c.setTitle(f"System Reliability / MTBF Calculation - {metadata['system_pn']}")
c.setAuthor(metadata["analyst"])
c.setSubject("Constant-rate system reliability aggregation")
mx = 34.0
cw = W - 2*mx
total = metrics["lambda_total_1e6h"]
lam_h = metrics["lambda_total_hour"]
mtbf_h = metrics["mtbf_hours"]
mtbf_y = mtbf_h / hours_per_year
horizon_h = horizon_years * hours_per_year
f_end = failure_function(lam_h, horizon_h)
r_end = 1 - f_end
included = [r for r in records if r.include]
excluded = [r for r in records if not r.include]
# ------------------------------------------------------------------
# Quiet document identifier - centered and intentionally small.
# This is report body content, not a page header/footer.
# ------------------------------------------------------------------
y = H - 31
_fit_center(c, "SYSTEM RELIABILITY / MTBF CALCULATION", W/2, y, cw, "Helvetica-Bold", 9.0, 7.0, BLACK)
_fit_center(c, f"{metadata.get('report_id','')} | {metadata.get('report_date','')} | {metadata.get('analysis_status','Released for Review')}",
W/2, y-11, cw, "Helvetica", 5.4, 4.5, G35)
c.setStrokeColor(G55); c.setLineWidth(0.55); c.line(mx, y-18, W-mx, y-18)
y -= 29
# ------------------------------------------------------------------
# Identification matrix - all labels and values centered in their zones.
# ------------------------------------------------------------------
meta = [
[_p("SYSTEM / EQUIPMENT", 5.0, bold=True, color=G35),
_p("PART NUMBER / REVISION", 5.0, bold=True, color=G35),
_p("ANALYST / DATE", 5.0, bold=True, color=G35)],
[_p(metadata.get("system_name", ""), 7.1, bold=True),
_p(f"{metadata.get('system_pn','')} / {metadata.get('system_rev','')}", 7.1, bold=True),
_p(f"{metadata.get('analyst','')} / {metadata.get('report_date','')}", 7.1, bold=True)],
[_p("CUSTOMER / PROGRAM", 5.0, bold=True, color=G35),
_p("CONFIGURATION REFERENCE", 5.0, bold=True, color=G35),
_p("REVIEWER / ORGANIZATION", 5.0, bold=True, color=G35)],
[_p(metadata.get("project", "N/A"), 6.3),
_p(metadata.get("system_reference", "N/A"), 6.3),
_p(f"{metadata.get('reviewer','-') or '-'} / {metadata.get('organization','N/A')}", 6.3)],
]
mt = Table(meta, colWidths=[cw/3]*3, rowHeights=[13, 22, 13, 22])
mt.setStyle(TableStyle([
("ALIGN", (0,0), (-1,-1), "CENTER"),
("VALIGN", (0,0), (-1,-1), "MIDDLE"),
("BACKGROUND", (0,0), (-1,0), G95),
("BACKGROUND", (0,2), (-1,2), G95),
("BOX", (0,0), (-1,-1), 0.45, G80),
("INNERGRID", (0,0), (-1,-1), 0.3, G90),
("LEFTPADDING", (0,0), (-1,-1), 4),
("RIGHTPADDING", (0,0), (-1,-1), 4),
("TOPPADDING", (0,0), (-1,-1), 1),
("BOTTOMPADDING", (0,0), (-1,-1), 1),
]))
_, mh = mt.wrap(cw, 80)
mt.drawOn(c, mx, y-mh)
y -= mh + 12
# ------------------------------------------------------------------
# Four centered result cards.
# ------------------------------------------------------------------
card_gap = 7
card_w = (cw - 3*card_gap)/4
card_h = 59
x = mx
cards = [
("System failure rate", f"{total:.7g}", "failures / 10^6 operating h"),
("Predicted MTBF", f"{mtbf_h:,.0f} h", f"{mtbf_y:.3f} calendar y at declared use"),
(f"Failure probability at {horizon_years:g} y", f"{100*f_end:.3f}%", "F(t) = 1 - exp(-lambda t)"),
(f"Reliability at {horizon_years:g} y", f"{100*r_end:.3f}%", "R(t) = exp(-lambda t)"),
]
for label, val, unit in cards:
_draw_metric_card(c, x, y-card_h, card_w, card_h, label, val, unit)
x += card_w + card_gap
y -= card_h + 10
# ------------------------------------------------------------------
# Calculation basis zone - concise and customer-readable.
# ------------------------------------------------------------------
basis_h = 48
c.setFillColor(WHITE); c.setStrokeColor(G80); c.setLineWidth(0.45)
c.roundRect(mx, y-basis_h, cw, basis_h, 3, fill=1, stroke=1)
_fit_center(c, "CALCULATION BASIS", W/2, y-10, cw-12, "Helvetica-Bold", 5.4, 4.6, G35)
_fit_center(c, f"System failure rate = sum of normalized contribution rates = {total:.10g} failures / 10^6 operating h",
W/2, y-23, cw-18, "Helvetica-Bold", 6.8, 5.4, BLACK)
_fit_center(c, f"Predicted MTBF = 1,000,000 / {total:.10g} = {mtbf_h:,.3f} operating h",
W/2, y-34, cw-18, "Helvetica-Bold", 6.8, 5.4, BLACK)
controls = (
f"Constant-hazard aggregation | {len(included)} included contribution(s) | {len(excluded)} excluded record(s) | "
f"{hours_per_year:,.0f} operating h/year | non-overlap and boundary completeness confirmed"
)
_fit_center(c, controls, W/2, y-44, cw-16, "Helvetica", 4.85, 4.0, G35)
y -= basis_h + 12
# ------------------------------------------------------------------
# Contribution table - centered. Adaptive item-level / subassembly roll-up.
# ------------------------------------------------------------------
report_rows, rolled = _report_rows(records, total)
n = len(report_rows)
_section_rule(c, "Normalized reliability contributions", mx, y, cw)
y -= 10
note = (
"Subassembly-level roll-up shown because of record count; every subassembly remains visible. Full item-level detail is retained in the ledger."
if rolled else "All included calculation records are shown."
)
_fit_center(c, note, W/2, y, cw-12, "Helvetica", 4.6, 3.8, G35)
y -= 7
# Reserve graph and a compact evidence statement. As table grows, the graph contracts.
bottom_margin = 30
min_graph_h = 105
max_graph_h = 180
evidence_h = 0
available = y - bottom_margin - 11
preferred_graph = max_graph_h if n <= 10 else 128 if n <= 18 else 105
table_available = available - preferred_graph - 12
row_h, fs, ld = _contribution_profile(n, table_available)
table_h = 20 + n*row_h
graph_h = min(max_graph_h, max(min_graph_h, available - table_h - 12))
if graph_h <= min_graph_h + 0.1:
table_available = available - min_graph_h - 12
row_h, fs, ld = _contribution_profile(n, table_available)
table_h = 20 + n*row_h
graph_h = min_graph_h
if n <= 28:
headers = ["Subassembly PN", "Item ID", "Qty", "Basis", "lambda contribution", "% total", "Numeric source", "Evidence / traceability"]
widths = [70, 49, 25, 53, 70, 38, 104, 135]
data = [[_p(h, 5.0, 5.5, bold=True) for h in headers]]
for rr in report_rows:
data.append([
_p(rr["subassembly"], fs, ld),
_p(rr["item"], fs, ld),
_p(rr["qty"], fs, ld),
_p(rr["basis"], fs, ld),
_p(f"{rr['lambda']:.7g}", fs, ld),
_p(f"{rr['pct']:.2f}%", fs, ld),
_p(rr["source"] or "-", fs, ld),
_p(rr["trace"] or "-", fs, ld),
])
tbl = Table(data, colWidths=widths, rowHeights=[20] + [row_h]*n)
tbl.setStyle(TableStyle([
("ALIGN", (0,0), (-1,-1), "CENTER"),
("VALIGN", (0,0), (-1,-1), "MIDDLE"),
("BACKGROUND", (0,0), (-1,0), G90),
("BOX", (0,0), (-1,-1), 0.5, G55),
("INNERGRID", (0,0), (-1,-1), 0.25, G80),
("LEFTPADDING", (0,0), (-1,-1), 1.8),
("RIGHTPADDING", (0,0), (-1,-1), 1.8),
("TOPPADDING", (0,0), (-1,-1), 1),
("BOTTOMPADDING", (0,0), (-1,-1), 1),
]))
_, actual_h = tbl.wrap(cw, table_available)
tbl.drawOn(c, mx, y-actual_h)
y -= actual_h + 10
else:
# Very large system: two balanced, centered subassembly roll-up tables.
half = (n + 1)//2
left = report_rows[:half]
right = report_rows[half:]
block_w = (cw-8)/2
row_h = max(9.1, min(12.5, table_available / (half+1)))
fs = max(3.9, min(4.7, row_h*0.42))
def small_table(rows):
d = [[_p("Subassembly PN", 4.7, 5.1, True), _p("lambda / 10^6 h", 4.7, 5.1, True), _p("%", 4.7, 5.1, True), _p("Evidence / traceability", 4.7, 5.1, True)]]
for rr in rows:
d.append([_p(rr["subassembly"], fs, fs+0.4), _p(f"{rr['lambda']:.6g}", fs, fs+0.4), _p(f"{rr['pct']:.1f}%", fs, fs+0.4), _p(rr["trace"] or rr["source"] or "-", fs, fs+0.4)])
t = Table(d, colWidths=[68, 62, 30, block_w-160], rowHeights=[18]+[row_h]*len(rows))
t.setStyle(TableStyle([
("ALIGN", (0,0), (-1,-1), "CENTER"), ("VALIGN", (0,0), (-1,-1), "MIDDLE"),
("BACKGROUND", (0,0), (-1,0), G90), ("BOX", (0,0), (-1,-1), 0.5, G55),
("INNERGRID", (0,0), (-1,-1), 0.25, G80),
("LEFTPADDING", (0,0), (-1,-1), 1.4), ("RIGHTPADDING", (0,0), (-1,-1), 1.4),
]))
return t
t1 = small_table(left); t2 = small_table(right)
_, h1 = t1.wrap(block_w, table_available); _, h2 = t2.wrap(block_w, table_available)
htbl = max(h1,h2)
t1.drawOn(c, mx, y-h1); t2.drawOn(c, mx+block_w+8, y-h2)
y -= htbl + 10
# ------------------------------------------------------------------
# Failure function chart - centered within its own zone.
# ------------------------------------------------------------------
_section_rule(c, f"Failure function - {horizon_years:g}-year horizon", mx, y, cw)
y -= 7
with tempfile.TemporaryDirectory() as td:
png = Path(td)/"failure_function.png"
create_failure_plot(lam_h, hours_per_year, horizon_years, mtbf_h, png)
chart_bottom = max(bottom_margin, y - graph_h)
c.drawImage(str(png), mx+5, chart_bottom, width=cw-10, height=graph_h-4,
preserveAspectRatio=True, anchor="c", mask="auto")
y = chart_bottom - 4
c.showPage()
c.save()
return output_path
# =============================================================================
# Interactive workflow
# =============================================================================
def collect_metadata() -> Tuple[Dict[str, str], float, float]:
section(
"1 - SYSTEM / REPORT IDENTIFICATION",
"These fields identify the exact customer configuration represented by the calculation. "
"They appear in the report body. The generated PDF intentionally contains no page header or footer."
)
explain(
"The plain-language name of the complete system or equipment whose composite MTBF is being reported.",
"This establishes the physical aggregation boundary.",
"Laboratory data acquisition system"
)
system_name = ask_required("System / equipment name: ")
explain(
"The top-level system or equipment part number and revision.",
"These identify the exact configuration represented by the summed failure rate.",
"Use the identifier and revision for your assembly."
)
system_pn = ask_required("System / equipment part number: ")
system_rev = ask_optional("System revision", "N/A")
explain(
"The customer, program, or project name that should appear on the report.",
"This is optional but strongly recommended for customer-facing traceability.",
"Laboratory instrumentation upgrade"
)
project = ask_optional("Customer / program / project", "N/A")
organization = ask_optional("Analyst organization", "N/A")
explain(
"A controlled system-level document that defines the analyzed configuration or boundary.",
"This can be a system drawing, BOM, configuration index, SHA, specification, or other controlled reference.",
"Your controlled assembly drawing and revision"
)
system_reference = ask_optional("System / configuration reference", "N/A")
explain("Analyst name exactly as it should appear on the customer report.")
analyst = ask_required("Analyst name: ")
reviewer = ask_optional("Reviewer / independent checker", "")
report_id = ask_optional("Calculation / report ID", f"MTBF-{sanitize_filename(system_pn)}")
report_date = ask_optional("Report date (YYYY-MM-DD)", date.today().isoformat())
analysis_status = ask_optional("Analysis status", "Released for Review")
section(
"2 - OPERATING-TIME BASIS",
"MIL-HDBK-217F failure rates are normally expressed per operating hour. The MTBF remains in operating hours. "
"The annual operating-hours entry is used only to map operating time to the requested calendar-year failure-function plot."
)
explain(
"Answer YES only if the complete modeled system is operating continuously, 24 hours/day and 365 days/year.",
"If not continuous, enter the expected annual operating hours used for the calendar-time plot.",
"Continuous service = 8760 h/year; 8 h/day x 5 days/week is about 2080 h/year."
)
continuous = ask_yes_no("Continuous 24/7 operation?", default=None)
hours_per_year = DEFAULT_OPERATING_HOURS_PER_YEAR if continuous else ask_float(
"Expected operating hours per calendar year", min_value=0.000001, allow_zero=False
)
if continuous:
print(f" Operating basis set to {hours_per_year:,.0f} h/year.")
explain(
"The calendar horizon for the failure-function graph.",
"This does not change the calculated system failure rate or MTBF; it only sets the plotted time interval.",
"40 years"
)
horizon_years = ask_float("Failure-function horizon in calendar years", min_value=0.000001, allow_zero=False, default=40.0)
return ({
"system_name": system_name, "system_pn": system_pn, "system_rev": system_rev,
"project": project, "organization": organization, "system_reference": system_reference,
"analyst": analyst, "reviewer": reviewer, "report_id": report_id,
"report_date": report_date, "analysis_status": analysis_status,
}, hours_per_year, horizon_years)
def architecture_gate() -> None:
section(
"3 - SYSTEM MODEL VALIDITY CHECK",
"This tool performs constant-hazard, series-equivalent aggregation. It is appropriate when the included contribution rates can be added directly. "
"If redundancy, switching, or mission-state logic materially changes the probability of system failure, a separate system reliability model is required before using this reciprocal-MTBF calculation."
)
questions = [
"Is active redundancy credited such that one item can fail without causing the modeled system failure?",
"Is standby redundancy, failover, voting logic, or spare-channel switching credited in the reliability claim?",
"Are materially different hardware configurations switched in and out during normal operation?",
"Does the requested result span distinct mission phases or environments requiring time weighting?",
"Do major contributions have different duty cycles that are not already embedded in their upstream failure rates?",
]
any_yes = False
for q in questions:
explain(q, "Answer YES only when this behavior must be represented in the claimed system reliability.")
any_yes |= ask_yes_no("Applies to this calculation?", default=None)
if any_yes:
raise RuntimeError(
"Simple lambda summation is not sufficient for the declared architecture. "
"Use a system reliability / mission-state model first, then provide the resulting effective system rate."
)
print("\nModel validity check passed for constant-rate aggregation.")
def collect_one_contribution(sequence: int, existing: List[Contribution]) -> Contribution:
section(
f"4 - RELIABILITY CONTRIBUTION {sequence}",
"Enter one already-calculated contribution from the reliability spreadsheet, a Part Stress calculation, a module/vendor reliability report, or another approved source. "
"The tool does not recalculate the upstream component model. It normalizes the number you provide and includes it once in the system total."
)
explain(
"The subassembly part number that owns this contribution.",
"Use the board, module, harness, power supply, or lower-level assembly part number. This establishes hierarchy and supports double-count protection.",
"Your board or module identifier"
)
subassembly_pn = ask_required("Subassembly part number: ")
explain(
"A unique item or calculation-line identifier within that subassembly.",
"Use a stable identifier that lets a reviewer locate the exact upstream record.",
"A unique identifier for this population within its parent assembly"
)
item_id = ask_required("Item ID / calculation line ID: ")
explain(
"A concise human description of what the entered number represents.",
"This is narrative identification, not a formula or value.",
"Laboratory amplifier board - reportable total failure rate"
)
description = ask_optional("Contribution description", "Validated reliability contribution")
_, record_kind = ask_choice("Contribution category:", RECORD_KINDS)
is_aggregate = record_kind in AGGREGATE_KINDS
if is_aggregate:
print(_wrap(
"AGGREGATE TOTAL SELECTED: do not also enter child component, connector, PTH/SMT, or connection rates already contained within this same aggregate boundary."
))
explain(
"The number of identical physical instances represented in the system.",
"Quantity is multiplied only when you choose a PER-UNIT input form. If the spreadsheet already gives a reportable line/total lambda, quantity is retained only for traceability and is not applied again.",
"Two identical power modules -> quantity 2. One board-total lambda -> quantity 1."
)
quantity = ask_int("Physical quantity", min_value=1, default=1)
explain(
"The method or source that produced the upstream reliability number.",
"This is provenance information; it does not alter the system-level arithmetic."
)
_, source_method = ask_choice("Upstream prediction / source method:", SOURCE_METHODS)
explain(
"The exact location from which the NUMERIC lambda or MTBF was taken.",
"Reference the workbook output, calculation identifier, report page, or controlled result containing the value you are entering.",
"The reportable total in your calculation workbook or the final line of your Part Stress calculation"
)
source_reference = ask_required("Numeric source reference: ")
explain(
"The engineering evidence that supports traceability of this contribution - for example a SHA, datasheet, drawing, specification, calculation, or controlled report.",
"This field appears directly in the normalized-contribution table on the PDF. Enter document number/title and revision when available. Multiple references may be separated by semicolons.",
"A reference to your controlled assembly drawing or component datasheet and its revision",
"The numeric source and traceability evidence are different: the numeric source says where the lambda came from; this field says what technical evidence supports the item/configuration/model."
)
traceability_reference = ask_optional("Evidence / traceability reference", "")
print("\nVALUE FORM - SELECT THE FORM OF THE NUMBER YOU ALREADY HAVE")
print(_wrap(
"If the spreadsheet says 'Reportable Total lambda = 4.0 failures / 10^6 operating hours', choose option 2 and enter 4.0. "
"Do NOT enter the reciprocal MTBF when the reportable total lambda is available. Choose a per-unit option only when the entered value represents one physical item and system quantity still needs to be applied."
))
form_key, input_form = ask_choice("Value type:", INPUT_FORMS)
if form_key in {"1", "3", "5"}:
print(f"\nQuantity treatment: PER-UNIT input -> quantity {quantity} WILL be applied.")
else:
print("\nQuantity treatment: REPORTABLE LINE / AGGREGATE input -> quantity will NOT be applied again.")
if form_key in {"1", "2"}:
explain("Enter lambda exactly as reported in failures per 10^6 operating hours.", example="4.0")
elif form_key in {"3", "4"}:
explain("Enter MTBF in operating hours, not calendar years.", example="250000")
else:
explain("Enter lambda in failures per operating hour.", example="4.0e-6")
value = ask_float("Input value", min_value=0.0, allow_zero=True)
per_unit, contribution, units = normalize_input(form_key, value, quantity)
zero_flag = contribution == 0.0
if zero_flag:
print(" NOTE: A modeled zero contribution does not establish infinite physical life.")
explain(
"Whether this contribution is actually inside the defined system boundary and is not already represented by another aggregate total.",
"Only non-overlapping included contributions enter the system sum."
)
include = ask_yes_no("Include in system failure-rate sum?", default=True)
exclusion_reason = "" if include else ask_required("Reason for exclusion: ")
note = ask_optional("Technical applicability / assumption note", "")
candidate = Contribution(
sequence=sequence, subassembly_pn=subassembly_pn, item_id=item_id,
description=description, record_kind=record_kind, quantity=quantity,
source_method=source_method, source_reference=source_reference,
traceability_reference=traceability_reference, input_form=input_form,
input_value=value, input_units=units, per_unit_lambda_1e6h=per_unit,
contribution_lambda_1e6h=contribution, include=include,
exclusion_reason=exclusion_reason, note=note,
is_aggregate_total=is_aggregate, zero_rate_flag=zero_flag,
)
conflict = overlap_conflict(existing, candidate)
if conflict:
print("\nDOUBLE-COUNT CONTROL:")
print(_wrap(conflict))
raise RuntimeError("Contribution rejected because it creates a known aggregate/child overlap.")
print("\nNORMALIZED CONTRIBUTION")
print(f" Subassembly PN: {subassembly_pn}")
print(f" Item ID: {item_id}")
print(f" Quantity: {quantity}")
print(f" System lambda contribution:{contribution: .12g} failures / 10^6 operating h")
print(f" Numeric source: {source_reference}")
print(f" Evidence / traceability: {traceability_reference or '-'}")
print(f" Included: {'YES' if include else 'NO'}")
return candidate
def final_attestation(records: List[Contribution]) -> None:
section(
"5 - FINAL AGGREGATION CONTROL",
"Before calculation, confirm that the entered records define the intended physical boundary completely and without overlapping populations."
)
duplicates = find_duplicate_ids(records)
if duplicates:
print("\nDUPLICATE ITEM-ID WARNING")
for sub, item in duplicates:
print(f" {sub} / {item}")
if not ask_yes_no("These duplicate IDs are intentional and represent distinct non-overlapping contributions?", default=False):
raise RuntimeError("Calculation stopped for duplicate item-ID review.")
explain(
"Confirm that each included physical failure contribution is represented once and only once, and that no aggregate total is also represented by its child rates."
)
if not ask_yes_no("Non-overlap verified?", default=None):
raise RuntimeError("Calculation stopped: non-overlap was not confirmed.")
explain(
"Confirm that all required contributors within the declared system boundary have been entered or intentionally excluded with a documented reason."
)
if not ask_yes_no("Aggregation boundary complete?", default=None):
raise RuntimeError("Calculation stopped: boundary completeness was not confirmed.")
def run_console(output_directory: str = ".") -> Dict[str, str]:
print()
rule("=")
print("SYSTEM RELIABILITY / MTBF AGGREGATOR")
rule("=")
print(_wrap(
"Purpose: combine already-calculated reliability outputs into one controlled system failure rate and predicted MTBF. "
"Use the reportable total lambda from the upstream spreadsheet whenever it is available. The console explains each requested field before input. "
"The generated deliverables are a one-page black-and-white PDF and a complete CSV calculation ledger."
))
metadata, hours_per_year, horizon_years = collect_metadata()
architecture_gate()
records: List[Contribution] = []
seq = 1
while True:
records.append(collect_one_contribution(seq, records))
seq += 1
if not ask_yes_no("Add another reliability contribution?", default=True):
break
final_attestation(records)
metrics = aggregate_system(records)
section("6 - SYSTEM RESULT")
print(f"Included contributions: {sum(r.include for r in records)}")
print(f"System lambda: {metrics['lambda_total_1e6h']:.12g} failures / 10^6 operating h")
print(f"Predicted MTBF: {metrics['mtbf_hours']:,.3f} operating h")
print(f"MTBF calendar equivalent: {metrics['mtbf_hours']/hours_per_year:,.5f} years at {hours_per_year:,.0f} operating h/year")
f40 = failure_function(metrics['lambda_total_hour'], horizon_years*hours_per_year)
print(f"F({horizon_years:g} years): {100*f40:.6f}%")
print(f"R({horizon_years:g} years): {100*(1-f40):.6f}%")
outdir = Path(output_directory).expanduser().resolve()
outdir.mkdir(parents=True, exist_ok=True)
base = sanitize_filename(f"{metadata['system_pn']}_{metadata['system_rev']}_System_MTBF")
ledger = write_ledger_csv(records, outdir / f"{base}_Ledger.csv")
pdf = create_report_pdf(metadata, records, metrics, hours_per_year, horizon_years,
outdir / f"{base}.pdf", ledger.name)
print("\nFILES CREATED")
print(f" PDF report: {pdf}")
print(f" Calculation ledger:{ledger}")
return {"pdf": str(pdf), "ledger": str(ledger)}
# =============================================================================
# Self-tests
# =============================================================================
def run_self_tests() -> None:
p, c, u = normalize_input("1", 0.25, 4)
assert abs(p - 0.25) < 1e-15 and abs(c - 1.0) < 1e-15
p, c, u = normalize_input("2", 4.0, 278)
assert p is None and abs(c - 4.0) < 1e-15
p, c, u = normalize_input("3", 1_000_000.0, 2)
assert abs(c - 2.0) < 1e-12
p, c, u = normalize_input("4", 500_000.0, 9)
assert abs(c - 2.0) < 1e-12
assert abs(reliability(1e-6, 1_000_000) - math.exp(-1)) < 1e-12
assert abs(failure_function(1e-6, 1_000_000) + reliability(1e-6, 1_000_000) - 1.0) < 1e-12
print("Self-tests passed: normalization, quantity treatment, reciprocal conversion, and reliability identities.")
def read_ledger(path):
"""Read an aggregator export, verifying the input units and derived rates."""
required = {"Subassembly_PN", "Item_ID", "Description", "Record_Kind", "Quantity",
"Source_Method", "Numeric_Source_Reference", "Traceability_Evidence",
"Input_Form", "Input_Value", "Input_Units", "Contribution_Lambda_1E6h",
"Include", "Exclusion_Reason", "Technical_Note"}
forms = {label: key for key, label in INPUT_FORMS.items()}
records = []
with Path(path).open("r", encoding="utf-8-sig", newline="") as file:
rows = csv.DictReader(file)
headers = rows.fieldnames or []
missing = required.difference(headers)
if missing or len(headers) != len(set(headers)):
raise ValueError("Use the system ledger schema. Missing or duplicate headers: " + ", ".join(sorted(missing)))
for row in rows:
try:
if None in row or None in row.values():
raise ValueError("The number of values differs from the column count.")
row = {key: val.strip() for key, val in row.items()}
for field in ["Subassembly_PN", "Item_ID", "Numeric_Source_Reference"]:
if not row[field]:
raise ValueError(f"{field} is required.")
if row["Include"] not in ("YES", "NO"):
raise ValueError("Use YES or NO for Include.")
included = row["Include"] == "YES"
if not included and not row["Exclusion_Reason"]:
raise ValueError("An excluded contribution needs an exclusion reason.")
kind = row["Record_Kind"]
if kind not in RECORD_KINDS.values() or row["Source_Method"] not in SOURCE_METHODS.values():
raise ValueError("Unknown record kind or source method.")
form = row["Input_Form"]
if form not in forms:
raise ValueError("Unknown input form.")
quantity = int(row["Quantity"])
value = float(row["Input_Value"])
per_unit, rate, units = normalize_input(forms[form], value, quantity)
if units != row["Input_Units"]:
raise ValueError("Input units disagree with the specified input form.")
if not math.isfinite(rate) or not math.isclose(
float(row["Contribution_Lambda_1E6h"]), rate, rel_tol=1e-12, abs_tol=0
):
raise ValueError("Reported contribution disagrees with the recalculated rate.")
record = Contribution(
sequence=len(records) + 1, subassembly_pn=row["Subassembly_PN"], item_id=row["Item_ID"],
description=row["Description"], record_kind=kind, quantity=quantity,
source_method=row["Source_Method"], source_reference=row["Numeric_Source_Reference"],
traceability_reference=row["Traceability_Evidence"], input_form=form, input_value=value,
input_units=units, per_unit_lambda_1e6h=per_unit, contribution_lambda_1e6h=rate,
include=included, exclusion_reason=row["Exclusion_Reason"], note=row["Technical_Note"],
is_aggregate_total=kind in AGGREGATE_KINDS, zero_rate_flag=rate == 0,
)
conflict = overlap_conflict(records, record)
if conflict:
raise ValueError(conflict)
records.append(record)
except (ValueError, OverflowError) as exc:
raise ValueError(f"Ledger row {rows.line_num}: {exc}") from exc
if not any(record.include for record in records):
raise ValueError("The ledger needs at least one included record.")
return records
def import_ledger(input_path, output_dir):
"""Recalculate a saved ledger after the analyst reconfirms the model and boundary."""
records = read_ledger(input_path)
architecture_gate()
final_attestation(records)
metrics = aggregate_system(records)
outdir = Path(output_dir)
outdir.mkdir(parents=True, exist_ok=True)
output = write_ledger_csv(records, outdir / "Recalculated_System_Ledger.csv")
print(f"Included rate: {metrics['lambda_total_1e6h']:.12g} failures per million operating hours")
print(f"Predicted MTBF: {metrics['mtbf_hours']:,.3f} operating hours")
return {"summary": metrics, "outputs": [str(output)]}
if __name__ == "__main__":
run_self_tests()
run_console()
The direct-entry adapter passes form inputs to these same engines. To reproduce the two public examples, open the reliability workspace, select the parts-count or system direct-entry form, and load its worked example.
Technical areas
MIL-HDBK-217F methodology, Python and Jupyter, Failure-rate modeling, Input validation, Model traceability.