"""Direct-entry interfaces to the same parts-count and system engines used for files.""" from datetime import date import math from pathlib import Path def _rows(payload): rows = payload.get("rows") if not isinstance(rows, list) or not rows: raise ValueError("Enter at least one population or contribution.") if not all(isinstance(row,dict) for row in rows): raise ValueError("Each contribution must contain named fields.") return rows def _text(value, label, required=True): value = "" if value is None else str(value).strip() if required and not value: raise ValueError(f"Enter {label}.") if value.startswith("="): raise ValueError(f"Enter plain text for {label}.") return value def _number(value, label): try: number = float(value) except (ValueError, TypeError, OverflowError): raise ValueError(f"Enter a number for {label}.") from None if not math.isfinite(number): raise ValueError(f"Enter a finite number for {label}.") return number def run_parts(payload, template_path, output_dir): """Populate the public workbook and evaluate it through the original parts-count engine.""" from openpyxl import load_workbook import PCMTBF project = payload.get("project", {}) required = ["Project_ID", "Project_Name", "Prepared_By", "Calculation_Date", "Assembly_Part_Number", "BOM_Revision", "Equipment_Boundary"] rows = _rows(payload) setup = {key: _text(project.get(key), key.replace("_", " ")) for key in required} setup.update(Strict_Mode="TRUE", Output_File_Name="Parts_Count_Results.xlsx") out = Path(output_dir) out.mkdir(parents=True, exist_ok=True) book = load_workbook(template_path) bom = book["BOM_Input"] project_sheet = book["Project_Setup"] for row in project_sheet.iter_rows(min_row=4): if row[0].value in setup: row[1].value = setup[row[0].value] controlled = {} for ref in book["Rate_Database"].iter_rows(min_row=7,values_only=True): if ref[9] == "VERIFIED": controlled[(ref[0],ref[4])] = (str(ref[1]),ref[2]) headers = {cell.value:cell.column for cell in bom[5] if cell.value} for index, row in enumerate(rows, start=1): key = _text(row.get("Rate_Key"), f"a rate category on row {index}") env = _text(row.get("Environment"), f"an environment on row {index}") if (key,env) not in controlled: raise ValueError(f"Row {index} has no verified generic rate for that category and environment.") section, family = controlled[(key,env)] values = {"Include":"YES","Assembly_PN":setup["Assembly_Part_Number"], "Handbook_Section":section,"Part_Group":family,"Environment":env,"Rate_Key":key, "Prediction_Method":"PARTS_COUNT","Parts_Count_Rate_Source":"RATE_DATABASE"} for field in ["Item_ID","Ref_Des_or_Group","Description","Quality_Class","Quality_Evidence"]: values[field] = _text(row.get(field), f"{field.replace('_',' ')} on row {index}") values["Quality_Scheme"] = _text(row.get("Quality_Scheme"), "quality scheme", False) or "AUTO" for field in ["Quantity", "Years_In_Production", "Custom_Screening_Points"]: if field == "Quantity" or row.get(field) not in (None,""): values[field] = _number(row.get(field), f"{field.replace('_',' ')} on row {index}") for name, value in values.items(): bom.cell(5+index,headers[name],value) input_path = out / "Entered_BOM.xlsx" book.save(input_path) book.close() result = PCMTBF.run(input_path,out) result["outputs"].append(str(input_path)) return result def run_system(payload, output_dir): """Normalize directly entered contributions and generate the same PDF report and audit ledger.""" import MTBF_AGGREGATOR as agg if not all(payload.get(key) is True for key in ["series_confirmed","boundary_confirmed","nonoverlap_confirmed"]): raise ValueError("Confirm the constant-rate series model, complete boundary and non-overlap.") records = [] for i,row in enumerate(_rows(payload),1): def get(field): return _text(row.get(field), f"{field} on row {i}") form, kind = str(row.get("form","")), str(row.get("kind","1")) if form not in agg.INPUT_FORMS or kind not in agg.RECORD_KINDS: raise ValueError(f"Row {i} needs a recognized input form and contribution type.") quantity = _number(row.get("quantity"), f"quantity on row {i}") if not quantity.is_integer() or quantity < 1: raise ValueError(f"Row {i} needs a positive whole quantity.") value = _number(row.get("value"), f"value on row {i}") per_unit, rate, units = agg.normalize_input(form, value, int(quantity)) if not math.isfinite(rate): raise ValueError(f"Row {i} produces a non-finite rate.") source = get("source") method = str(row.get("method","5")) if method not in agg.SOURCE_METHODS: raise ValueError(f"Row {i} needs a recognized source method.") record = agg.Contribution( sequence=i,subassembly_pn=get("parent"),item_id=get("item"), description=get("description"),record_kind=agg.RECORD_KINDS[kind], quantity=int(quantity),source_method=agg.SOURCE_METHODS[method], source_reference=source,traceability_reference=_text(row.get("evidence"),"evidence",False), input_form=agg.INPUT_FORMS[form],input_value=value,input_units=units, per_unit_lambda_1e6h=per_unit,contribution_lambda_1e6h=rate,include=True, exclusion_reason="",note="",is_aggregate_total=agg.RECORD_KINDS[kind] in agg.AGGREGATE_KINDS, zero_rate_flag=rate==0, ) conflict = agg.overlap_conflict(records,record) if conflict: raise ValueError(f"Row {i}: {conflict}") records.append(record) if agg.find_duplicate_ids(records): raise ValueError("Each included population within a parent needs a unique identifier.") metrics = agg.aggregate_system(records) hours = _number(payload.get("hours_per_year",8760),"operating hours per year") horizon = _number(payload.get("horizon_years",40),"report horizon in years") if not 0 < hours <= 8760 or horizon <= 0 or not math.isfinite(hours * horizon): raise ValueError("Use positive annual operating hours up to 8,760 and a positive finite report horizon.") metadata = {key:_text(payload.get(key),key,False) or "Unspecified" for key in ["system_pn","system_rev","analyst","project","organization","report_id","reviewer","system_reference"]} metadata.update(system_name=_text(payload.get("system_name"),"a system name"), report_date=date.today().isoformat(),analysis_status="For review") out = Path(output_dir) out.mkdir(parents=True,exist_ok=True) ledger = agg.write_ledger_csv(records,out/"System_Ledger.csv") report = agg.create_report_pdf(metadata,records,metrics,hours,horizon,out/"System_Report.pdf",ledger.name) return {"summary":metrics,"outputs":[str(ledger),str(report)]}