""" 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()