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