#4863 TRIZ Pipeline for Mechanical Systems Breakdown

#4863 TRIZ Pipeline for Mechanical Systems Breakdown

#4863 Describe how TRIZ Functional Analysis, then TRIZ Ideal Final Result, then TRIZ 76 Standard Solutions, then TRIZ Contradiction matrix can be applied to a system, subsystem, component, and/or or part of a mechanical system (e.g. bicycle)

Applying TRIZ sequentially from Functional Analysis to the Ideal Final Result (IFR), 76 Standard Solutions, and the Contradiction Matrix creates a systematic pipeline for decomposing mechanical failure modes and synthesizing non-compromise solutions.

Using a bicycle transmission as the subject, the hierarchy decomposes as follows:

  • System: Bicycle

  • Subsystem: Drivetrain / Transmission

  • Component: Roller chain and sprocket interface

  • Part: Chain link pin and roller bushing


1. TRIZ Functional Analysis

Functional Analysis maps interactions into discrete Subject --> Action --> Object triplets, categorizing functions as useful (sufficient, excessive, insufficient) or harmful.

[Rider Leg] --(useful: produces)--> [Torque]
     |
[Crankset] --(useful: tensions)--> [Drive Chain]
     |
[Drive Chain] --(useful: rotates)--> [Rear Sprocket]
     |
     +--(harmful: abrades)---------> [Sprocket Teeth]
     +--(harmful: attracts)--------> [Road Grit / Contaminants]
     +--(insufficient: retains)---> [Lubricant Film under load]

At the part level (chain roller pin vs. bushing):

  • Primary Useful Function (PUF): The roller pin transfers shear load to the bushing/roller.

  • Harmful Action 1: Friction between pin and bushing generates heat and wear (F_friction to material degradation).

  • Harmful Action 2: External abrasive particles enter the clearance gap, accelerating mechanical erosion.

  • Insufficient Function: Factory wet lubricant fails to stay adhered under centrifugal force and wet environmental exposure.

2. TRIZ Ideal Final Result (IFR)

The Ideal Final Result establishes the boundary condition where the system delivers its full utility without introducing mass, energy loss, complexity, or maintenance:

I = {sum Useful Functions} / {sum Harmful Functions + sum Costs} to infty
  • System-level IFR: The bicycle moves forward upon pedaling without requiring an exposed transmission.

  • Component-level IFR: The chain transfers torque from crank to wheel without wearing out, accumulating dirt, or requiring external lubrication.

  • Part-level IFR: The roller pin lubricates and cleans itself using available system resources (internal friction, ambient air, or pedal motion), or the pin/bushing boundary eliminates mechanical contact entirely while transferring normal force.

3. TRIZ 76 Standard Solutions (Su-Field Analysis)

Su-Field (Substance-Field) modeling abstracts the pin-roller wear problem into two interacting substances (S_1, S_2) acted on by a mechanical field (F_mech).

  • Substance 1 (S_1): Chain roller/bushing

  • Substance 2 (S_2): Pin

  • Field (F_mech): Mechanical contact/load transfer

  • Harmful Field (F_harm): Friction wear and abrasive grit scouring

       F_mech (Load)
        /          \
      S_1 <=======> S_2
      (Bushing)    (Pin)
        \          /
       F_harm (Wear/Grit)

The 76 Standard Solutions are organized into 5 classes. Applying the relevant classes to this interaction:

ClassSolution StrategyPart/Component Application
Class 1 (Decomposition & Synthesis)1.2.2: Introduce an internal substance (S_3) derived from existing materials to absorb the harmful field.Impregnate the sintered metal bushing with solid PTFE or graphite (S_3), so wear debris itself acts as a continuous self-replenishing dry lubricant.
Class 2 (Su-Field Evolution)2.2.2: Replace an unstructured field with a structured field (e.g., magnetic field F_mag).Replace pin-roller contact with magnetic gear teeth (contactless magnetic transmission), decoupling physical friction entirely.
Class 3 (Transitions to Supersystem)3.1.1: Transition to a monoblock or continuous flexible member.Eliminate discrete pins and bushings by switching from an articulated roller chain to a continuous carbon-reinforced toothed belt drive.
Class 5 (Resource Exploitation)5.2.2: Use phase transitions or thermal expansion of ambient resources.Apply diamond-like carbon (DLC) coatings that utilize moisture in ambient air to generate self-healing passivation layers.

4. TRIZ Contradiction Matrix

When physical modification of the mechanical chain creates an engineering trade-off, the problem is formulated as a Technical Contradiction (TC) using the 39 Engineering Parameters:

Framing the Contradiction

  • Improving Parameter: We want to improve the transmission's service life and resistance to elongation/wear under high pedal load to Parameter 14: Strength (or Parameter 27: Reliability).

  • Worsening Parameter: Increasing pin diameter, adding sealed O-rings, or thickening links increases rotational inertia and pedaling resistance to Parameter 1: Weight of moving object (or Parameter 19: Use of energy by moving object).

Querying the Matrix

Crossing Improving: #14 (Strength) with Worsening: #1 (Weight of moving object) yields four primary Inventive Principles:

  • Principle 40 (Composite Materials): Replace homogenous steel pins and rollers with a carbon-fiber/ceramic composite matrix, delivering higher shear yield strength at 40% lower mass.

  • Principle 8 (Anti-weight): Compensate for heavier sealed links by integrating hollow roller pins and slotted inner/outer link plates (standard practice in high-end chains like SRAM Eagle HollowPin / Shimano HG).

  • Principle 1 (Segmentation): Segment the continuous roller sleeve into independent micro-bearings or needle rollers to distribute contact stresses, preventing localized stress concentrations.

  • Principle 35 (Parameter Changes / Transformation of Properties): Treat the steel pin with surface nitriding or Physical Vapor Deposition (PVD) titanium carbo-nitride (TiCN), modifying only the outer 2–3 micrometers to high ceramic hardness while leaving the interior core ductile and lightweight.

Synthesis: From Part to System Execution

Following this progression resolves the engineering path without compromise:

  1. Functional Analysis isolates the root inefficiency to the microscopic gap between the roller pin and bushing under external particulate ingress.

  2. IFR forces the objective away from "add a heavier chain case" toward "the chain requires zero lubrication maintenance."

  3. 76 Standard Solutions (Class 1 & 3) yield two divergent commercial paths: solid-lubricant sintered bushings (part level) or a carbon belt drive (subsystem level).

  4. Contradiction Matrix (Principles 8, 35, 40) refines the surviving roller chain architecture into hollow-core, PVD-coated components that withstand peak torque without mass penalties.


Would SCAMPER be beneficial in this pipeline, or redundant?

In an analytical engineering pipeline already using TRIZ Functional Analysis, IFR, the 76 Standard Solutions, and the Contradiction Matrix, SCAMPER is structurally redundant and methodologically mismatched, offering value only in narrow post-synthesis packaging or part-consolidation tasks.

While SCAMPER serves well as a rapid brainstorming checklist for product concepting, injecting it into an active TRIZ pipeline introduces lateral noise into an otherwise mathematically and physically directed problem-solving sequence.

1. Functional Equivalence: SCAMPER is a Diluted Subset of TRIZ

Every operator in SCAMPER represents an informal, linguistic rephrasing of specific TRIZ Inventive Principles and Su-Field classes, but lacks physical mechanisms or technical parameters:

SCAMPER PromptEquivalent TRIZ Inventive PrinciplesTRIZ Standard Solutions / ToolsDifference in Depth
Substitute

Principle 28 (Mechanics Substitution)


Principle 40 (Composite Materials)


Principle 35 (Parameter Changes)

Class 1.2.1 (Introduce foreign field/substance)


Class 2.2.2 (Shift from mechanical to field)

SCAMPER asks "What material can we swap?" TRIZ specifies substituting fields (mechanical to acoustic/magnetic) or phase states.
Combine

Principle 5 (Merging)


Principle 6 (Multifunctionality)

Class 3.1.1 (Bi- and poly-systems)


Class 3.1.2 (Chained mono-systems)

TRIZ defines homogeneous vs. heterogeneous coupling, shifted operating modes, and symbiotic function sharing.
Adapt

Principle 15 (Dynamicity)


Principle 37 (Thermal Expansion)

Class 2.2.1 (Increase controllability)SCAMPER asks "Can we adapt this from elsewhere?" TRIZ instructs turning rigid linkages into flexible, segmented, or fluidic states.
Modify / Magnify / Minify

Principle 1 (Segmentation)


Principle 14 (Spheroidality)


Principle 17 (Another Dimension)

Class 2.1.1 (Transition to micro-levels)TRIZ directs transitions from macro to micro-structures, nested concentric parts, or changing 2D profiles to 3D helixes.
Put to Another Use

Principle 25 (Self-Service)


Principle 22 ("Blessing in Disguise")

Class 5.1 (Exploit internal substance/field resources)SCAMPER asks "What else can this do?" TRIZ forces the system to exploit waste heat, friction, or environmental contaminants to perform work.
Eliminate

Principle 2 (Taking Out / Extraction)


Principle 34 (Discarding / Recovering)

TRIZ Trimming (Pruning Rules A, B, C)


Ideal Final Result ($Costs \to 0$)

SCAMPER prompts removal; TRIZ Trimming enforces strict conditions: the carrier is removed only if the object disappears, performs the action itself, or another element absorbs the function.
Reverse / Rearrange

Principle 13 (The Other Way Round)


Principle 10 (Prior Action)


Principle 11 (Beforehand Cushioning)

Class 1.1.8 (Counter-field application)TRIZ specifies exact temporal, kinematic, or positional inversions (e.g., make the moving part stationary and the casing move).

2. Methodological Mismatch: Associative Brainstorming vs. Contradiction Resolution

The primary conflict between SCAMPER and TRIZ lies in how they navigate engineering trade-offs:

[SCAMPER Approach]
Problem ──> Broad Lateral Prompts ──> 50 Ideas ──> Filtering / Compromise / Trade-off
                                                   (e.g., "Substitute pin for titanium" -> lighter, but 10x cost)

[TRIZ Approach]
Problem ──> Functional Analysis ──> Root Contradiction ──> Directed Invariant Patterns ──> Non-Compromise Solution
                                                           (e.g., Improving Strength WITHOUT adding Mass)
  • SCAMPER generates compromises: Asking "Can we magnify the pin?" might improve fatigue strength, but directly degrades rotational inertia and weight. SCAMPER does not flag the worsening parameter.

  • TRIZ prohibits compromises: The Contradiction Matrix and Physical Contradiction separation rules (in space, time, condition, or relation) exist specifically to stop engineers from optimizing one parameter at the expense of another.

3. Where SCAMPER Adds Actual Value

SCAMPER is not useless; it is simply misplaced when treated as a peer to Su-Field or Contradiction Analysis. It provides utility in two specific phases:

  1. Pre-TRIZ Divergence (Ideation Seeding):

    If an engineering team or automated agent struggles to formulate the initial problem statement, SCAMPER can be run for 5–10 minutes to generate divergent concepts that highlight where the system is breaking down.

  2. Post-TRIZ Physical Packaging & Part Consolidation:

    Once TRIZ resolves the core physics (e.g., deciding to transition to a hollow-pin DLC-coated bushing), running Combine and Rearrange aids Design for Manufacture and Assembly (DFMA)—merging the outer link plate and retention clips into a single stamped stamped profile to reduce BOM count.

Verification Checklist: Incorporate or Prune?

  • Drop SCAMPER if: Your objective is deterministic engineering root-cause resolution, automating engineering pipelines (e.g., LLM/agentic workflows), or eliminating technical trade-offs. TRIZ Functional Analysis and Trimming already strictly supersedes SCAMPER.

  • Retain SCAMPER if: The pipeline involves collaborative human workshops where non-technical stakeholders (marketing, industrial design) must participate in feature brainstorming before handing the architecture off to engineering.


Is the pipeline as-is good, or are there other TRIZ methods that could be applied?

The current sequence—Functional Analysis --> Ideal Final Result (IFR) --> 76 Standard Solutions --> Contradiction Matrix—is functionally sound, but it contains three distinct structural gaps:

  1. Missing Root-Cause Decomposition: Moving straight from Functional Analysis to IFR risks tackling symptoms rather than the initiating physical mechanisms.

  2. Missing Systemic/Temporal Context: It focuses strictly on the present component, missing evolutionary trends and supersystem interactions.

  3. Missing Physical Contradiction Handling: The Contradiction Matrix resolves Technical Contradictions (trade-offs between two different parameters), but fails when an engineering parameter must be both high and low simultaneously.

Integrating five specific TRIZ tools closes these gaps into an end-to-end analytical pipeline:

Critical TRIZ Additions to the Pipeline

[System & Function Scoping]
  │  ├── 1. Functional Analysis (Current)
  │  └── 2. 9-Windows / System Operator (NEW: Supersystem/Temporal context)
  ▼
[Root Cause & Resource Identification]
  │  ├── 3. Cause-Effect Chain Analysis / CECA (NEW: Isolates root physical conflicts)
  │  └── 4. Substance-Field & System Resource Audit (NEW: Exploit free internal fields/matter)
  ▼
[Target Setting]
  │  └── 5. Ideal Final Result / IFR (Current)
  ▼
[Resolution Engines: Parallel Tracks based on Conflict Type]
  │  ├── Path A: Su-Field Inefficiencies ──> 76 Standard Solutions (Current)
  │  ├── Path B: Technical Contradictions ──> 39 Parameters & 40 Principles (Current)
  │  ├── Path C: Physical Contradictions  ──> 4 Separation Principles (NEW: Space, Time, Condition, System)
  │  └── Path D: Functional Pruning       ──> TRIZ Trimming / Component Elimination (NEW)
  ▼
[Verification & Evolution]
  └── 6. Trends of Engineering System Evolution / TESE (NEW: S-curve maturity verification)

Detailed Method Integrations

1. Cause-Effect Chain Analysis (CECA / RCA+)

  • Placement: Immediately following Functional Analysis, before IFR.

  • Why it's needed: In the bicycle drivetrain example, "wear on the chain pin" is a late-stage effect. CECA drills downward:

    Chain breaks/slips <-- Pitch elongation <-- Bushing bore wear} <-- Abrasive 3-body wear <-- Capillary attraction of road slurry <-- Low-viscosity liquid carrier

  • Impact: Discovers that preventing liquid surface tension/capillarity eliminates the grit ingress entirely, bypassing the need to redesign the steel alloy.

2. The 9-Windows System Operator (System, Supersystem, Subsystem x Past, Present, Future)

  • Placement: Upfront during Problem Framing.

  • Why it's needed: Prevents "component-level myopia."

    • Supersystem Present: Bicycle frame geometry, road surface debris, weather environment.

    • Supersystem Future: Enclosed bottom-bracket gearboxes (e.g., Pinion), electric hub-drive integration (eliminating high-tension chains).

    • Subsystem Past: Solid link rods --> Bushing chains --> Bushingless roller chains.

  • Impact: Prevents spending engineering budget optimizing a chain pin if the supersystem is actively shifting to direct hub motors or enclosed belt drivetrains.

3. Separation Principles for Physical Contradictions

  • Placement: Parallel to the Contradiction Matrix.

  • Why it's needed: Technical contradictions cross two parameters (e.g., Strength vs. Weight). A Physical Contradiction occurs when one single parameter must exhibit opposing physical states:

    • The clearance gap between pin and bushing must be large (to allow lubricant entry and reduce manufacturing tolerance costs) AND small/zero (to block grit entry and prevent play/shock loads).

  • Resolution Mechanics:

    • Separation in Space: Porous internal sintered metal provides open space for lubricant storage internally, while external seals provide zero clearance to outside grit.

    • Separation in Time: Clearance is large during assembly/immersion lubrication; clearance shrinks to zero under operational tension.

    • Separation by Condition / Phase: Lubricant is low-viscosity liquid during application (penetrates micro-gaps), then cross-links or solidifies into a dry wax film under evaporation.

4. TRIZ Trimming (Pruning)

  • Placement: Directly after IFR.

  • Why it's needed: The highest ideality is reached not by making a part better, but by removing the part while preserving its function.

    • Rule A: Can the pin's function (transferring shear between plates) be performed by the outer plate itself? (Yields integral stamped/extruded swaged pins).

    • Rule B: Can the object of the function (the bushing) be eliminated? (Yields modern bushingless chains, where the inner plates are formed into extended half-sleeves).

5. Trends of Engineering System Evolution (TESE)

  • Placement: Solution evaluation gate at the end of the pipeline.

  • Why it's needed: Ensures the synthesized design moves with physical evolution laws rather than against them:

    • Trend of Increasing Dynamicity: Rigid chain link --> Multi-jointed link --> Flexible toothed belt --> Contactless magnetic field.

    • Trend of Transition to Micro-level: Solid pin --> Sintered porous metal --> PVD nanostructured coating --> Molecular boundary layer.

Comparison: As-Is vs. Augmented Pipeline

Metric / DimensionAs-Is PipelineAugmented TRIZ Pipeline
Diagnostic PrecisionFunctional links mapped, but root physical causes are lumped together.CECA isolates fundamental physical root causes prior to ideation.
Trade-Off ResolutionHandles Technical Contradictions via 39 Parameters.Handles both Technical Contradictions and Physical Contradictions (Separation Principles).
BOM / Part ReductionIdentifies parameter changes, but rarely eliminates entire components.Trimming methodically strips parts, reducing assembly and manufacturing costs.
Systemic HorizonConfined to the defined assembly boundary.9-Windows accounts for frame/environmental supersystems and historical trajectory.


Structure this augmented TRIZ pipeline into a deterministic execution workflow with input/output artifacts for each stage.

1.System Scoping & Temporal Context (9-Windows):Phase gate: supersystem integration and temporal trajectory established.

Frames the target system across hierarchical scales (Supersystem, System, Subsystem) and temporal states (Past, Present, Future) to prevent local optimization of obsolete architectures.

  • Input Artifact: SystemBoundarySpecification (BOM, boundary definitions, operational envelope, failure records).

  • Execution Method: Populate the 3x3 System Operator matrix; cross-reference current subsystem life cycles against emerging supersystem requirements (e.g., shifts to direct-drive motors or enclosed gearboxes).

  • Output Artifact: SystemHorizonReport (Active system scope, explicit exclusions, and evolutionary velocity assessment).

2.Functional & Substance-Field Interaction Modeling:Phase gate: complete functional graph with all harmful/insufficient links categorized.

Deconstructs assemblies into discrete Subject-Action-Object triplets and establishes baseline Substance-Field (Su-Field) models.

  • Input Artifact: SystemHorizonReport + Assembly CAD/Schematics.

  • Execution Method: Enumerate primary useful functions (PUFs), auxiliary useful functions, excessive functions, insufficient functions, and harmful interactions (F_harm).

  • Output Artifact: FunctionalInteractionGraph (Directed graph of components linked by standard TRIZ functional and field relationships).

3.Cause-Effect Chain Analysis (CECA / RCA+):Phase gate: target problem converted from top symptom to physical root contradiction.

Drills down from surface degradation or performance limits through causal links to the underlying governing physics.

  • Input Artifact: Identified harmful functions from FunctionalInteractionGraph.

  • Execution Method: Construct converging/diverging cause-effect chains until reaching primary physical phenomena (e.g., surface tension, shear stresses, thermal gradient limits).

  • Output Artifact: RootConflictManifest (Ranked list of target failure mechanisms mapped to key physical parameters).

4.System Resource Audit & IFR Target Formulation:Phase gate: ideality equation and zero-cost resource inventory established.

Audits all internal, external, field, spatial, temporal, and waste resources while calculating the Ideal Final Result boundary.

  • Input Artifact: FunctionalInteractionGraph + Environmental Operating Specs.

  • Execution Method: Catalog matter/field resources (S_internal, S_external, F_mech, F_thermal, waste matter, clearances); compute I = {sum UF} / {sum HF + sum Cost}; define conditions where the function executes autonomously.

  • Output Artifact: ResourceInventory & IdealFinalResultSpec (Operational boundary condition: "The component performs [PUF] using only [Available Resources] without introducing [Harmful Fields]").

5.Trimming & Functional Pruning:Phase gate: candidate components methodically excised before adding new elements.

Evaluates components against systematic pruning rules to maximize ideality by part reduction.

  • Input Artifact: FunctionalInteractionGraph + IdealFinalResultSpec.

  • Execution Method: Apply Trimming Rules A (Object of function removed), B (Object performs action itself), and C (Another existing element absorbs function) across all candidate nodes.

  • Output Artifact: TrimmedSystemArchitecture (Pruned graph with eliminated parts and redistributed functional duties).

6.Conflict Resolution Engine (Parallel Tracks):Phase gate: non-compromise concept generation across three specialized resolution tracks.

Routes remaining system bottlenecks to targeted physical and technical resolution engines.

  • Input Artifact: TrimmedSystemArchitecture + RootConflictManifest + ResourceInventory.

  • Execution Method:

    • Track 1 (Su-Field Impairments): Apply the 76 Standard Solutions (Classes 1–5).

    • Track 2 (Technical Contradictions): Map improving vs. worsening parameters to the Contradiction Matrix (40 Principles).

    • Track 3 (Physical Contradictions): Apply 4 Separation Principles (Space, Time, Condition, System Scale).

  • Output Artifact: CandidateConceptMatrix (Set of candidate solution architectures with exact physical mechanisms specified).

7.Evolutionary Verification & S-Curve Alignment (TESE):Phase gate: candidate solutions verified against invariant laws of technical evolution.

Filters candidate solutions against the 8 Trends of Engineering System Evolution (TESE) to reject obsolete or regressive architectures.

  • Input Artifact: CandidateConceptMatrix + SystemHorizonReport.

  • Execution Method: Score candidate concepts against evolutionary directions (Increasing Dynamicity, Transition to Micro-level, Increasing Controllability, Harmonization of Rhythms).

  • Output Artifact: ValidatedEngineeringArchitecture (Down-selected, defensible solution package with evolutionary maturity scoring).

Artifact Data Schema & Flow Matrix

StageInput ArtifactOutput ArtifactPrimary Gate Criteria
1. 9-WindowsSystemBoundarySpecificationSystemHorizonReportActive component not superseded by supersystem migration.
2. Functional AnalysisSystemHorizonReportFunctionalInteractionGraphEvery component mapped with >= 1 PUF and explicit harmful/insufficient tags.
3. CECA / RCA+FunctionalInteractionGraph (Harmful links)RootConflictManifestRoot physical cause reached (no remaining unverified intermediate effects).
4. Resource & IFRFunctionalInteractionGraph + Env SpecsResourceInventory & IdealFinalResultSpec>= 5 unused matter/field/spatial resources identified; explicit IFR defined.
5. TrimmingFunctionalInteractionGraph + IdealFinalResultSpecTrimmedSystemArchitectureTrimming Rules A, B, and C evaluated for all non-core components.
6. Resolution EnginesTrimmedSystemArchitecture + RootConflictManifestCandidateConceptMatrixZero compromises permitted; trade-offs mapped to Matrix or Separation.
7. TESE VerificationCandidateConceptMatrix + SystemHorizonReportValidatedEngineeringArchitectureConcept advances >= 1 TESE axis without regressing on system dynamicity.

Immediate Execution Steps

  1. Serialize Input Schema: Define the baseline SystemBoundarySpecification with exact component breakdown, mass, and operating limits.

  2. Execute Stage 1 & 2 Parser: Ingest the boundary spec to output the SystemHorizonReport and initialize node-edge relationships for the FunctionalInteractionGraph.

  3. Run CECA Branching: Trace identified wear, friction, or thermal failure nodes to physical parameter limits to seed the RootConflictManifest.


Write the complete Pydantic models for each artifact: SystemHorizonReport, FunctionalInteractionGraph, RootConflictManifest, ResourceInventory, IdealFinalResultSpec, CandidateConceptMatrix, and ValidatedEngineeringArchitecture.

The complete Pydantic (v2) data models below define strict validation rules, enum taxonomies, and cross-stage relational links for all seven pipeline stage artifacts.

"""
TRIZ Automated Engineering Pipeline Data Models (Pydantic v2).
Defines schemas and gate invariants for:
  1. SystemHorizonReport (9-Windows System Operator)
  2. FunctionalInteractionGraph (Subject-Action-Object & Su-Field)
  3. RootConflictManifest (CECA / RCA+ physical decomposition)
  4. ResourceInventory & IdealFinalResultSpec (Resource audit & IFR)
  5. CandidateConceptMatrix (Trimming, 76 Standards, Contradiction Matrix, Separations)
  6. ValidatedEngineeringArchitecture (TESE evaluation & final verification)
"""

from __future__ import annotations
from enum import Enum
from typing import List, Optional, Dict, Literal
from pydantic import BaseModel, Field, field_validator, model_validator


# ============================================================================
# SHARED PRIMITIVES & ENUMS
# ============================================================================

class TemporalScale(str, Enum):
    PAST = "past"
    PRESENT = "present"
    FUTURE = "future"


class SystemHierarchy(str, Enum):
    SUPERSYSTEM = "supersystem"
    SYSTEM = "system"
    SUBSYSTEM = "subsystem"


class FunctionType(str, Enum):
    USEFUL_PRIMARY = "useful_primary"
    USEFUL_AUXILIARY = "useful_auxiliary"
    USEFUL_INSUFFICIENT = "useful_insufficient"
    USEFUL_EXCESSIVE = "useful_excessive"
    HARMFUL = "harmful"


class FieldType(str, Enum):
    MECHANICAL = "mechanical"
    THERMAL = "thermal"
    CHEMICAL = "chemical"
    ELECTROMAGNETIC = "electromagnetic"
    ACOUSTIC = "acoustic"
    BIOLOGICAL = "biological"


class ResourceState(str, Enum):
    INTERNAL = "internal"
    EXTERNAL_ENVIRONMENT = "external_environment"
    WASTE_PRODUCT = "waste_product"
    FIELD = "field"
    SPACE_TIME = "space_time"


class ConflictTrack(str, Enum):
    TRIMMING = "trimming"
    SU_FIELD_76_STANDARDS = "su_field_76_standards"
    TECHNICAL_CONTRADICTION = "technical_contradiction"
    PHYSICAL_CONTRADICTION = "physical_contradiction"


class SeparationType(str, Enum):
    SPACE = "space"
    TIME = "time"
    CONDITION = "condition"
    SYSTEM_SCALE = "system_scale"


class TrimmingRule(str, Enum):
    RULE_A = "rule_a_carrier_eliminated_with_object"
    RULE_B = "rule_b_object_performs_action_itself"
    RULE_C = "rule_c_other_component_absorbs_function"


# ============================================================================
# STAGE 1: SYSTEM HORIZON REPORT (9-WINDOWS SYSTEM OPERATOR)
# ============================================================================

class WindowCell(BaseModel):
    hierarchy: SystemHierarchy
    temporal: TemporalScale
    description: str = Field(..., description="State of the system at this coordinate")
    key_drivers_or_constraints: List[str] = Field(default_factory=list)


class SystemHorizonReport(BaseModel):
    artifact_id: str = Field(..., pattern=r"^SHR-[A-Z0-9_-]+$")
    system_name: str
    target_subsystem: str
    operator_matrix: List[WindowCell] = Field(..., min_length=9, max_length=9)
    supersystem_threats_or_disruptions: List[str] = Field(
        ..., min_length=1, description="External migrations that could render component obsolete"
    )
    is_obsolescence_risk_mitigated: bool = Field(
        ..., description="Gate check: true if active target remains viable against future supersystem shifts"
    )

    @field_validator("operator_matrix")
    @classmethod
    def validate_complete_3x3(cls, v: List[WindowCell]) -> List[WindowCell]:
        combos = {(cell.hierarchy, cell.temporal) for cell in v}
        expected = {(h, t) for h in SystemHierarchy for t in TemporalScale}
        if combos != expected:
            raise ValueError(f"9-Windows matrix incomplete. Missing coordinates: {expected - combos}")
        return v


# ============================================================================
# STAGE 2: FUNCTIONAL INTERACTION GRAPH (FUNCTIONAL & SU-FIELD)
# ============================================================================

class FunctionalNode(BaseModel):
    node_id: str = Field(..., pattern=r"^NODE-[A-Z0-9_-]+$")
    label: str
    hierarchy_level: SystemHierarchy
    material_spec: Optional[str] = None
    is_carrier: bool = Field(False, description="Whether node serves primarily as a function carrier")


class FunctionalEdge(BaseModel):
    edge_id: str = Field(..., pattern=r"^EDGE-[A-Z0-9_-]+$")
    source_node_id: str
    target_node_id: str
    action_verb: str = Field(..., min_length=2)
    function_type: FunctionType
    field_medium: FieldType
    magnitude_or_parameter: Optional[str] = Field(None, description="e.g., '1200 N shear stress'")


class FunctionalInteractionGraph(BaseModel):
    artifact_id: str = Field(..., pattern=r"^FIG-[A-Z0-9_-]+$")
    system_horizon_ref: str
    nodes: List[FunctionalNode] = Field(..., min_length=2)
    edges: List[FunctionalEdge] = Field(..., min_length=1)

    @model_validator(mode="after")
    def validate_graph_integrity(self) -> FunctionalInteractionGraph:
        node_ids = {n.node_id for n in self.nodes}
        for edge in self.edges:
            if edge.source_node_id not in node_ids:
                raise ValueError(f"Edge {edge.edge_id} source {edge.source_node_id} does not exist in nodes")
            if edge.target_node_id not in node_ids:
                raise ValueError(f"Edge {edge.edge_id} target {edge.target_node_id} does not exist in nodes")
        
        # Verify gate criteria: at least one primary useful function and at least one problem link
        has_primary = any(e.function_type == FunctionType.USEFUL_PRIMARY for e in self.edges)
        has_defect = any(
            e.function_type in (FunctionType.HARMFUL, FunctionType.USEFUL_INSUFFICIENT, FunctionType.USEFUL_EXCESSIVE)
            for e in self.edges
        )
        if not has_primary:
            raise ValueError("Functional graph must contain at least one USEFUL_PRIMARY edge")
        if not has_defect:
            raise ValueError("Functional graph must identify at least one HARMFUL, INSUFFICIENT, or EXCESSIVE edge")
        return self


# ============================================================================
# STAGE 3: ROOT CONFLICT MANIFEST (CAUSE-EFFECT CHAIN ANALYSIS / CECA)
# ============================================================================

class CausalStep(BaseModel):
    step_id: str
    observed_effect: str
    governing_physics: str = Field(..., description="Fundamental physical or chemical mechanism")
    is_root_cause: bool = False


class RootConflict(BaseModel):
    conflict_id: str = Field(..., pattern=r"^RC-[A-Z0-9_-]+$")
    source_edge_ref: str = Field(..., description="Edge ID from FunctionalInteractionGraph")
    causal_chain: List[CausalStep] = Field(..., min_length=2)
    primary_conflict_statement: str = Field(
        ..., description="Standardized problem framing: [Phenomenon] causes [Failure] under [Operating Condition]"
    )


class RootConflictManifest(BaseModel):
    artifact_id: str = Field(..., pattern=r"^RCM-[A-Z0-9_-]+$")
    graph_ref: str
    conflicts: List[RootConflict] = Field(..., min_length=1)

    @model_validator(mode="after")
    def validate_terminal_root_causes(self) -> RootConflictManifest:
        for conflict in self.conflicts:
            root_count = sum(1 for step in conflict.causal_chain if step.is_root_cause)
            if root_count != 1:
                raise ValueError(
                    f"Conflict {conflict.conflict_id} must have exactly one terminal step marked is_root_cause=True"
                )
        return self


# ============================================================================
# STAGE 4: RESOURCE INVENTORY & IDEAL FINAL RESULT (IFR) SPEC
# ============================================================================

class SystemResource(BaseModel):
    resource_id: str = Field(..., pattern=r"^RES-[A-Z0-9_-]+$")
    name: str
    state: ResourceState
    field_or_substance: str
    availability_cost: float = Field(0.0, description="Cost to exploit; 0.0 indicates existing free resource")
    limitations: Optional[str] = None


class ResourceInventory(BaseModel):
    artifact_id: str = Field(..., pattern=r"^RINV-[A-Z0-9_-]+$")
    system_name: str
    resources: List[SystemResource] = Field(..., min_length=5, description="Gate requirement: >= 5 resources audited")


class IdealFinalResultSpec(BaseModel):
    artifact_id: str = Field(..., pattern=r"^IFR-[A-Z0-9_-]+$")
    target_node_ref: str = Field(..., description="Component or link undergoing IFR transformation")
    target_puf: str = Field(..., description="The primary useful function to preserve")
    ideality_formula: str = Field(
        "I = sum(Useful Functions) / (sum(Harmful Functions) + sum(Costs)) -> Infinity",
        description="Invariant ideality metric"
    )
    operational_boundary_statement: str = Field(
        ...,
        description="Canonical IFR: 'The component performs [PUF] by itself using [Resources] without [Harmful Functions]'",
    )
    consumed_resources: List[str] = Field(..., min_length=1, description="List of Resource IDs deployed")


# ============================================================================
# STAGE 5: CANDIDATE CONCEPT MATRIX (TRIMMING + 3 RESOLUTION TRACKS)
# ============================================================================

class TrimmingAction(BaseModel):
    rule_applied: TrimmingRule
    carrier_node_id: str
    function_transferred_to: Optional[str] = Field(
        None, description="Required for Rule C (absorbing node) or Rule B (object node)"
    )
    feasibility_notes: str


class ResolutionMechanism(BaseModel):
    track: ConflictTrack
    applied_operator_number: int = Field(
        ..., description="Standard Solution # (1-76), Inventive Principle # (1-40), or Separation rule (1-4)"
    )
    operator_name: str
    separation_dimension: Optional[SeparationType] = None
    physical_realization: str = Field(..., description="Explicit mechanical, structural, or material implementation")


class CandidateConcept(BaseModel):
    concept_id: str = Field(..., pattern=r"^CC-[A-Z0-9_-]+$")
    conflict_ref: str = Field(..., description="Target RootConflict ID")
    trimming_actions: List[TrimmingAction] = Field(default_factory=list)
    resolution_mechanisms: List[ResolutionMechanism] = Field(..., min_length=1)
    eliminates_compromise: bool = Field(
        ..., description="Gate invariant: must not introduce a secondary degradation"
    )
    expected_bom_delta: int = Field(
        ..., description="Estimated net change in unique parts (negative values indicate pruning)"
    )


class CandidateConceptMatrix(BaseModel):
    artifact_id: str = Field(..., pattern=r"^CCM-[A-Z0-9_-]+$")
    root_manifest_ref: str
    ifr_spec_ref: str
    concepts: List[CandidateConcept] = Field(..., min_length=1)


# ============================================================================
# STAGE 6: VALIDATED ENGINEERING ARCHITECTURE (TESE VERIFICATION)
# ============================================================================

class EvolutionTrendScore(BaseModel):
    trend_name: Literal[
        "increasing_dynamicity",
        "transition_to_micro_level",
        "increasing_controllability",
        "harmonization_of_rhythms",
        "non_uniform_evolution_of_subsystems",
        "transition_to_supersystem",
        "decreasing_human_involvement",
        "increasing_ideality"
    ]
    current_state_score: int = Field(..., ge=1, le=5)
    concept_state_score: int = Field(..., ge=1, le=5)
    evolutionary_progression: str = Field(..., description="Physical justification for score progression")


class ValidatedEngineeringArchitecture(BaseModel):
    artifact_id: str = Field(..., pattern=r"^VEA-[A-Z0-9_-]+$")
    selected_concept_id: str
    architecture_title: str
    detailed_specification: str
    tese_alignment: List[EvolutionTrendScore] = Field(..., min_length=3)
    final_verification_checklist: Dict[str, bool] = Field(
        ...,
        description="Verification gate: e.g. {'no_secondary_contradictions': True, 'dynamicity_not_regressed': True}",
    )
    is_approved_for_cad_fmea: bool

    @model_validator(mode="after")
    def validate_evolutionary_advance(self) -> ValidatedEngineeringArchitecture:
        regressed = any(t.concept_state_score < t.current_state_score for t in self.tese_alignment)
        if regressed:
            raise ValueError("Candidate concept regresses on one or more TESE evolution trends")
        
        all_passed = all(self.final_verification_checklist.values())
        if self.is_approved_for_cad_fmea and not all_passed:
            raise ValueError("Cannot approve architecture if any gate verification item is False")
        return self

Artifact Lineage & Validation Gates

SystemHorizonReport (SHR)
  │ (Invariance: 9/9 3x3 cells populated, obsolescence risk cleared)
  ▼
FunctionalInteractionGraph (FIG)
  │ (Invariance: Node-edge referential integrity, >=1 PUF, >=1 defect edge)
  ▼
RootConflictManifest (RCM)
  │ (Invariance: Every defect chain reaches exactly 1 is_root_cause=True)
  ▼
ResourceInventory (RINV) & IdealFinalResultSpec (IFR)
  │ (Invariance: >=5 zero/low-cost resources cataloged, operational IFR defined)
  ▼
CandidateConceptMatrix (CCM)
  │ (Invariance: Tracks 1-3 mapped, zero compromises, eliminates_compromise=True)
  ▼
ValidatedEngineeringArchitecture (VEA)
  └ (Invariance: delta(TESE) >= 0 across all trends, 100% gate pass)


Provide a Python application using Google Gemini API, saving the results from each step and the final result in markdown files

Your Python files are ready:

  • Core Pipeline Application:

    PY icon
    triz_pipeline_app
    PY

  • CLI Execution Harness:

    PY icon
    run_pipeline_demo
    PY

Pipeline Architecture Overview

The application uses the official google-genai SDK (from google import genai) with structured JSON schema outputs (response_schema=BaseModel) via Gemini. Each stage enforces relational integrity, validates phase-gate criteria, and exports an isolated Markdown report as well as a consolidated master document.

Input Specification
   │
   ├── [Stage 1] 9-Windows System Operator ──────> 01_system_horizon_report.md
   │
   ├── [Stage 2] Functional & Su-Field Graph ────> 02_functional_interaction_graph.md
   │
   ├── [Stage 3] CECA Root Cause Decomposition ──> 03_root_conflict_manifest.md
   │
   ├── [Stage 4] Resource Audit & IFR Spec ──────> 04_resource_and_ifr_spec.md
   │
   ├── [Stage 5] Trimming & Conflict Engines ────> 05_candidate_concept_matrix.md
   │
   ├── [Stage 6] TESE Evolutionary Validation ───> 06_validated_engineering_architecture.md
   │
   └── [Stage 7] Master Compilation ─────────────> 00_TRIZ_MASTER_REPORT.md

Key Application Implementation (triz_pipeline_app.py)

Here is the core orchestrator implementation showing the Pydantic structured output integration with the Google GenAI SDK:

"""
Augmented TRIZ Engineering Pipeline Application
==============================================
Uses the Google GenAI SDK (google-genai) with Pydantic structured outputs
to execute a 7-stage TRIZ analysis on mechanical systems (e.g., bicycle chain wear).

Pipeline Stages:
  1. System Scoping & Temporal Trajectory (9-Windows System Operator) -> SHR
  2. Functional & Su-Field Interaction Modeling -> FIG
  3. Cause-Effect Chain Analysis (CECA / RCA+) -> RCM
  4. System Resource Audit & Ideal Final Result (IFR) Spec -> RINV & IFR
  5. Trimming & Conflict Resolution Engine (76 Standards, 40 Principles, Separations) -> CCM
  6. Evolutionary Verification & S-Curve Alignment (TESE) -> VEA
  7. Final Synthesis & Consolidated Markdown Report Export
"""

import os
import json
import logging
from typing import List, Optional, Dict, Literal
from enum import Enum
from pathlib import Path

from pydantic import BaseModel, Field, field_validator, model_validator
from google import genai
from google.genai import types

logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")


# ============================================================================
# 1. PYDANTIC DATA MODELS & INVARIANTS
# ============================================================================

class TemporalScale(str, Enum):
    PAST = "past"
    PRESENT = "present"
    FUTURE = "future"


class SystemHierarchy(str, Enum):
    SUPERSYSTEM = "supersystem"
    SYSTEM = "system"
    SUBSYSTEM = "subsystem"


class FunctionType(str, Enum):
    USEFUL_PRIMARY = "useful_primary"
    USEFUL_AUXILIARY = "useful_auxiliary"
    USEFUL_INSUFFICIENT = "useful_insufficient"
    USEFUL_EXCESSIVE = "useful_excessive"
    HARMFUL = "harmful"


class FieldType(str, Enum):
    MECHANICAL = "mechanical"
    THERMAL = "thermal"
    CHEMICAL = "chemical"
    ELECTROMAGNETIC = "electromagnetic"
    ACOUSTIC = "acoustic"
    BIOLOGICAL = "biological"


class ResourceState(str, Enum):
    INTERNAL = "internal"
    EXTERNAL_ENVIRONMENT = "external_environment"
    WASTE_PRODUCT = "waste_product"
    FIELD = "field"
    SPACE_TIME = "space_time"


class ConflictTrack(str, Enum):
    TRIMMING = "trimming"
    SU_FIELD_76_STANDARDS = "su_field_76_standards"
    TECHNICAL_CONTRADICTION = "technical_contradiction"
    PHYSICAL_CONTRADICTION = "physical_contradiction"


class SeparationType(str, Enum):
    SPACE = "space"
    TIME = "time"
    CONDITION = "condition"
    SYSTEM_SCALE = "system_scale"


class TrimmingRule(str, Enum):
    RULE_A = "rule_a_carrier_eliminated_with_object"
    RULE_B = "rule_b_object_performs_action_itself"
    RULE_C = "rule_c_other_component_absorbs_function"


# Stage 1: 9-Windows
class WindowCell(BaseModel):
    hierarchy: SystemHierarchy
    temporal: TemporalScale
    description: str
    key_drivers_or_constraints: List[str] = Field(default_factory=list)


class SystemHorizonReport(BaseModel):
    artifact_id: str = Field(..., pattern=r"^SHR-[A-Z0-9_-]+$")
    system_name: str
    target_subsystem: str
    operator_matrix: List[WindowCell] = Field(..., min_length=9, max_length=9)
    supersystem_threats_or_disruptions: List[str] = Field(..., min_length=1)
    is_obsolescence_risk_mitigated: bool


# Stage 2: Functional Graph
class FunctionalNode(BaseModel):
    node_id: str = Field(..., pattern=r"^NODE-[A-Z0-9_-]+$")
    label: str
    hierarchy_level: SystemHierarchy
    material_spec: Optional[str] = None
    is_carrier: bool = False


class FunctionalEdge(BaseModel):
    edge_id: str = Field(..., pattern=r"^EDGE-[A-Z0-9_-]+$")
    source_node_id: str
    target_node_id: str
    action_verb: str
    function_type: FunctionType
    field_medium: FieldType
    magnitude_or_parameter: Optional[str] = None


class FunctionalInteractionGraph(BaseModel):
    artifact_id: str = Field(..., pattern=r"^FIG-[A-Z0-9_-]+$")
    system_horizon_ref: str
    nodes: List[FunctionalNode] = Field(..., min_length=2)
    edges: List[FunctionalEdge] = Field(..., min_length=1)


# Stage 3: CECA Root Conflict Manifest
class CausalStep(BaseModel):
    step_id: str
    observed_effect: str
    governing_physics: str
    is_root_cause: bool = False


class RootConflict(BaseModel):
    conflict_id: str = Field(..., pattern=r"^RC-[A-Z0-9_-]+$")
    source_edge_ref: str
    causal_chain: List[CausalStep] = Field(..., min_length=2)
    primary_conflict_statement: str


class RootConflictManifest(BaseModel):
    artifact_id: str = Field(..., pattern=r"^RCM-[A-Z0-9_-]+$")
    graph_ref: str
    conflicts: List[RootConflict] = Field(..., min_length=1)


# Stage 4: Resource Inventory & IFR
class SystemResource(BaseModel):
    resource_id: str = Field(..., pattern=r"^RES-[A-Z0-9_-]+$")
    name: str
    state: ResourceState
    field_or_substance: str
    availability_cost: float = 0.0
    limitations: Optional[str] = None


class ResourceInventory(BaseModel):
    artifact_id: str = Field(..., pattern=r"^RINV-[A-Z0-9_-]+$")
    system_name: str
    resources: List[SystemResource] = Field(..., min_length=5)


class IdealFinalResultSpec(BaseModel):
    artifact_id: str = Field(..., pattern=r"^IFR-[A-Z0-9_-]+$")
    target_node_ref: str
    target_puf: str
    ideality_formula: str = "I = sum(Useful Functions) / (sum(Harmful Functions) + sum(Costs)) -> Infinity"
    operational_boundary_statement: str
    consumed_resources: List[str] = Field(..., min_length=1)


# Stage 5: Resolution Engines
class TrimmingAction(BaseModel):
    rule_applied: TrimmingRule
    carrier_node_id: str
    function_transferred_to: Optional[str] = None
    feasibility_notes: str


class ResolutionMechanism(BaseModel):
    track: ConflictTrack
    applied_operator_number: int
    operator_name: str
    separation_dimension: Optional[SeparationType] = None
    physical_realization: str


class CandidateConcept(BaseModel):
    concept_id: str = Field(..., pattern=r"^CC-[A-Z0-9_-]+$")
    conflict_ref: str
    trimming_actions: List[TrimmingAction] = Field(default_factory=list)
    resolution_mechanisms: List[ResolutionMechanism] = Field(..., min_length=1)
    eliminates_compromise: bool
    expected_bom_delta: int


class CandidateConceptMatrix(BaseModel):
    artifact_id: str = Field(..., pattern=r"^CCM-[A-Z0-9_-]+$")
    root_manifest_ref: str
    ifr_spec_ref: str
    concepts: List[CandidateConcept] = Field(..., min_length=1)


# Stage 6: Evolutionary Verification (TESE)
class EvolutionTrendScore(BaseModel):
    trend_name: Literal[
        "increasing_dynamicity",
        "transition_to_micro_level",
        "increasing_controllability",
        "harmonization_of_rhythms",
        "non_uniform_evolution_of_subsystems",
        "transition_to_supersystem",
        "decreasing_human_involvement",
        "increasing_ideality"
    ]
    current_state_score: int = Field(..., ge=1, le=5)
    concept_state_score: int = Field(..., ge=1, le=5)
    evolutionary_progression: str


class ValidatedEngineeringArchitecture(BaseModel):
    artifact_id: str = Field(..., pattern=r"^VEA-[A-Z0-9_-]+$")
    selected_concept_id: str
    architecture_title: str
    detailed_specification: str
    tese_alignment: List[EvolutionTrendScore] = Field(..., min_length=3)
    final_verification_checklist: Dict[str, bool]
    is_approved_for_cad_fmea: bool


# ============================================================================
# 2. MARKDOWN EXPORT FORMATTERS
# ============================================================================

def export_markdown_report(filename: Path, title: str, content: str):
    filename.parent.mkdir(parents=True, exist_ok=True)
    with open(filename, "w", encoding="utf-8") as f:
        f.write(f"# {title}\n\n{content}\n")
    logging.info(f"Saved Markdown artifact: {filename}")


def format_stage1_md(data: SystemHorizonReport) -> str:
    md = [f"**Artifact ID:** `{data.artifact_id}`",
          f"**Target System:** {data.system_name} | **Subsystem:** {data.target_subsystem}",
          f"**Obsolescence Risk Mitigated:** {'Yes' if data.is_obsolescence_risk_mitigated else 'No'}\n",
          "### 9-Windows System Operator Matrix\n",
          "| Hierarchy | Past | Present | Future |",
          "|---|---|---|---|"]
    
    def get_cell(h, t):
        for c in data.operator_matrix:
            if c.hierarchy == h and c.temporal == t:
                return f"{c.description} (Drivers: {', '.join(c.key_drivers_or_constraints)})"
        return "N/A"

    for h in [SystemHierarchy.SUPERSYSTEM, SystemHierarchy.SYSTEM, SystemHierarchy.SUBSYSTEM]:
        row = f"| **{h.value.capitalize()}** | {get_cell(h, TemporalScale.PAST)} | {get_cell(h, TemporalScale.PRESENT)} | {get_cell(h, TemporalScale.FUTURE)} |"
        md.append(row)

    md.append("\n### Supersystem Disruptions & Threats")
    for threat in data.supersystem_threats_or_disruptions:
        md.append(f"- {threat}")
    return "\n".join(md)


def format_stage2_md(data: FunctionalInteractionGraph) -> str:
    md = [f"**Artifact ID:** `{data.artifact_id}` (Ref: `{data.system_horizon_ref}`)\n",
          "### Functional Nodes\n",
          "| Node ID | Label | Hierarchy | Material Spec | Function Carrier |",
          "|---|---|---|---|---|"]
    for n in data.nodes:
        md.append(f"| `{n.node_id}` | {n.label} | {n.hierarchy_level.value} | {n.material_spec or 'N/A'} | {'Yes' if n.is_carrier else 'No'} |")

    md.append("\n### Functional & Substance-Field Interactions\n")
    md.append("| Edge ID | Source Node | Action Verb | Target Node | Type | Field Medium | Parameter / Load |")
    md.append("|---|---|---|---|---|---|---|")
    for e in data.edges:
        md.append(f"| `{e.edge_id}` | `{e.source_node_id}` | **{e.action_verb}** | `{e.target_node_id}` | `{e.function_type.value}` | {e.field_medium.value} | {e.magnitude_or_parameter or 'N/A'} |")
    return "\n".join(md)


def format_stage3_md(data: RootConflictManifest) -> str:
    md = [f"**Artifact ID:** `{data.artifact_id}` (Ref: `{data.graph_ref}`)\n",
          "### Root Physical Conflicts (CECA Decomposition)\n"]
    for c in data.conflicts:
        md.append(f"#### Conflict `{c.conflict_id}` (Triggered by Edge: `{c.source_edge_ref}`)")
        md.append(f"**Statement:** {c.primary_conflict_statement}\n")
        md.append("| Step | Observed Symptom / Effect | Governing Physics | Root Cause? |")
        md.append("|---|---|---|---|")
        for s in c.causal_chain:
            md.append(f"| `{s.step_id}` | {s.observed_effect} | {s.governing_physics} | {'**YES (ROOT)**' if s.is_root_cause else 'No'} |")
        md.append("")
    return "\n".join(md)


def format_stage4_md(rinv: ResourceInventory, ifr: IdealFinalResultSpec) -> str:
    md = [f"### System Resource Inventory (`{rinv.artifact_id}`)\n",
          "| Resource ID | Resource Name | State | Field / Substance | Cost | Limitations |",
          "|---|---|---|---|---|---|"]
    for r in rinv.resources:
        md.append(f"| `{r.resource_id}` | {r.name} | {r.state.value} | {r.field_or_substance} | ${r.availability_cost:.2f} | {r.limitations or 'None'} |")

    md.append(f"\n### Ideal Final Result (IFR) Specification (`{ifr.artifact_id}`)\n")
    md.append(f"* **Target Node:** `{ifr.target_node_ref}`")
    md.append(f"* **Primary Useful Function (PUF):** {ifr.target_puf}")
    md.append(f"* **Ideality Formula:** `{ifr.ideality_formula}`")
    md.append(f"* **Operational Boundary Statement:** > *"{ifr.operational_boundary_statement}"*")
    md.append(f"* **Exploited Resources:** {', '.join([f'`{rid}`' for rid in ifr.consumed_resources])}")
    return "\n".join(md)


def format_stage5_md(data: CandidateConceptMatrix) -> str:
    md = [f"**Artifact ID:** `{data.artifact_id}` (Conflict Ref: `{data.root_manifest_ref}` | IFR Ref: `{data.ifr_spec_ref}`)\n",
          "### Candidate Concept Architectures\n"]
    for c in data.concepts:
        md.append(f"#### Concept `{c.concept_id}` (Addresses: `{c.conflict_ref}`)")
        md.append(f"* **Eliminates Compromise:** {'Yes (Non-compromise)' if c.eliminates_compromise else 'No'}")
        md.append(f"* **Expected BOM Delta:** {c.expected_bom_delta} components")
        
        if c.trimming_actions:
            md.append("\n**Trimming Actions Applied:**")
            for t in c.trimming_actions:
                md.append(f"- Rule: `{t.rule_applied.value}` | Carrier: `{t.carrier_node_id}` | Absorbed by: `{t.function_transferred_to or 'Eliminated'}` ({t.feasibility_notes})")
        
        md.append("\n**Resolution Mechanisms:**")
        md.append("| Track | Operator # | Operator Name | Separation Dim | Physical Realization |")
        md.append("|---|---|---|---|---|")
        for m in c.resolution_mechanisms:
            sep = m.separation_dimension.value if m.separation_dimension else "N/A"
            md.append(f"| `{m.track.value}` | #{m.applied_operator_number} | {m.operator_name} | {sep} | {m.physical_realization} |")
        md.append("")
    return "\n".join(md)


def format_stage6_md(data: ValidatedEngineeringArchitecture) -> str:
    md = [f"**Artifact ID:** `{data.artifact_id}` (Selected Concept: `{data.selected_concept_id}`)",
          f"## Architecture: {data.architecture_title}\n",
          f"### Detailed Specification\n{data.detailed_specification}\n",
          "### Trends of Engineering System Evolution (TESE) Scoring\n",
          "| Evolution Trend | Baseline Score (1-5) | Concept Score (1-5) | Evolutionary Progression Justification |",
          "|---|---|---|---|"]
    for t in data.tese_alignment:
        md.append(f"| `{t.trend_name}` | {t.current_state_score} | **{t.concept_state_score}** | {t.evolutionary_progression} |")

    md.append("\n### Phase Gate Verification Checklist")
    for check, status in data.final_verification_checklist.items():
        md.append(f"- [{'x' if status else ' '}] **{check}**: {'PASSED' if status else 'FAILED'}")

    md.append(f"\n**CAD & FMEA Hand-off Approved:** {'APPROVED' if data.is_approved_for_cad_fmea else 'REJECTED'}")
    return "\n".join(md)


# ============================================================================
# 3. DETERMINISTIC PIPELINE ORCHESTRATOR CLASS
# ============================================================================

class TRIZPipelineRunner:
    """Executes the augmented TRIZ pipeline using Google Gemini structured generation."""

    def __init__(self, client: genai.Client, model: str = "gemini-2.5-flash", output_dir: str = "triz_output"):
        self.client = client
        self.model = model
        self.output_dir = Path(output_dir)
        self.output_dir.mkdir(parents=True, exist_ok=True)

    def _generate_structured(self, system_instruction: str, prompt: str, schema):
        response = self.client.models.generate_content(
            model=self.model,
            contents=prompt,
            config=types.GenerateContentConfig(
                system_instruction=system_instruction,
                response_mime_type="application/json",
                response_schema=schema,
                temperature=0.1,
            ),
        )
        return schema.model_validate_json(response.text)

    def run_stage_1(self, target_spec: str) -> SystemHorizonReport:
        logging.info("Executing Stage 1: 9-Windows System Operator...")
        sys_inst = (
            "You are an expert TRIZ Master. Construct a rigorous 9-Windows System Operator matrix "
            "(Past, Present, Future x Supersystem, System, Subsystem) for the given system. "
            "Ensure the active target is evaluated against future supersystem shifts to verify obsolescence risk."
        )
        prompt = f"Analyze the following mechanical system specification and produce the SystemHorizonReport:\n\n{target_spec}"
        report = self._generate_structured(sys_inst, prompt, SystemHorizonReport)
        export_markdown_report(self.output_dir / "01_system_horizon_report.md", "Stage 1: System Horizon Report (9-Windows)", format_stage1_md(report))
        return report

    def run_stage_2(self, horizon_report: SystemHorizonReport) -> FunctionalInteractionGraph:
        logging.info("Executing Stage 2: Functional Interaction Graph...")
        sys_inst = (
            "You are a TRIZ Functional Modeling engine. Deconstruct the subsystem into Subject-Action-Object triplets. "
            "Identify primary useful functions (PUFs), auxiliary functions, and explicit HARMFUL or INSUFFICIENT interactions."
        )
        prompt = (
            f"Based on the system horizon report `{horizon_report.artifact_id}` for {horizon_report.system_name} -> {horizon_report.target_subsystem},\n"
            f"create the FunctionalInteractionGraph. Ensure referential integrity between nodes and edges.\n"
            f"Context: {horizon_report.model_dump_json()}"
        )
        graph = self._generate_structured(sys_inst, prompt, FunctionalInteractionGraph)
        export_markdown_report(self.output_dir / "02_functional_interaction_graph.md", "Stage 2: Functional Interaction Graph", format_stage2_md(graph))
        return graph

    def run_stage_3(self, graph: FunctionalInteractionGraph) -> RootConflictManifest:
        logging.info("Executing Stage 3: Cause-Effect Chain Analysis (CECA)...")
        sys_inst = (
            "You are a TRIZ Root Cause Analysis engine. For each HARMFUL or INSUFFICIENT edge, perform Cause-Effect Chain Analysis (CECA). "
            "Drill down from surface degradation through governing physics to exactly ONE underlying physical root cause per chain."
        )
        prompt = f"Decompose all harmful/insufficient edges in graph `{graph.artifact_id}` into root physical conflicts:\n{graph.model_dump_json()}"
        manifest = self._generate_structured(sys_inst, prompt, RootConflictManifest)
        export_markdown_report(self.output_dir / "03_root_conflict_manifest.md", "Stage 3: Root Conflict Manifest (CECA)", format_stage3_md(manifest))
        return manifest

    def run_stage_4(self, graph: FunctionalInteractionGraph, manifest: RootConflictManifest) -> tuple[ResourceInventory, IdealFinalResultSpec]:
        logging.info("Executing Stage 4: Resource Audit & IFR Formulation...")
        sys_inst_rinv = (
            "You are a TRIZ Resource Auditor. Catalog at least 5 zero-cost or readily available matter, field, spatial, and waste resources."
        )
        prompt_rinv = f"Catalog system and environmental resources for {graph.artifact_id} experiencing conflicts in {manifest.artifact_id}:\n{graph.model_dump_json()}"
        rinv = self._generate_structured(sys_inst_rinv, prompt_rinv, ResourceInventory)

        sys_inst_ifr = (
            "Formulate the operational Ideal Final Result (IFR) specification for the critical component undergoing conflict resolution. "
            "Express the operational boundary statement such that the part performs its primary useful function autonomously."
        )
        prompt_ifr = f"Using resources {rinv.model_dump_json()} and conflicts {manifest.model_dump_json()}, define the IdealFinalResultSpec."
        ifr = self._generate_structured(sys_inst_ifr, prompt_ifr, IdealFinalResultSpec)

        export_markdown_report(self.output_dir / "04_resource_and_ifr_spec.md", "Stage 4: Resource Inventory & IFR Spec", format_stage4_md(rinv, ifr))
        return rinv, ifr

    def run_stage_5(self, manifest: RootConflictManifest, rinv: ResourceInventory, ifr: IdealFinalResultSpec) -> CandidateConceptMatrix:
        logging.info("Executing Stage 5: Conflict Resolution Engine...")
        sys_inst = (
            "You are a TRIZ inventive synthesis engine. Apply TRIZ Trimming, Su-Field 76 Standard Solutions, "
            "Contradiction Matrix (40 Principles), and 4 Separation Principles (Space, Time, Condition, Scale) "
            "to synthesize non-compromise candidate concepts."
        )
        prompt = (
            f"Generate candidate solutions resolving RootConflictManifest `{manifest.artifact_id}` under IFR `{ifr.artifact_id}` "
            f"using available resources `{rinv.artifact_id}`:\n"
            f"Conflicts: {manifest.model_dump_json()}\n"
            f"IFR: {ifr.model_dump_json()}\n"
            f"Resources: {rinv.model_dump_json()}"
        )
        ccm = self._generate_structured(sys_inst, prompt, CandidateConceptMatrix)
        export_markdown_report(self.output_dir / "05_candidate_concept_matrix.md", "Stage 5: Candidate Concept Matrix", format_stage5_md(ccm))
        return ccm

    def run_stage_6(self, ccm: CandidateConceptMatrix, horizon: SystemHorizonReport) -> ValidatedEngineeringArchitecture:
        logging.info("Executing Stage 6: Evolutionary Verification (TESE)...")
        sys_inst = (
            "You are a Chief Systems Engineer & TRIZ Master. Select the best concept from CandidateConceptMatrix. "
            "Evaluate it against the 8 Trends of Engineering System Evolution (TESE). Verify no evolutionary regression."
        )
        prompt = (
            f"Select the winning concept from `{ccm.artifact_id}` and perform TESE validation in context of `{horizon.artifact_id}`:\n"
            f"Candidate Concepts: {ccm.model_dump_json()}\n"
            f"Horizon Context: {horizon.model_dump_json()}"
        )
        vea = self._generate_structured(sys_inst, prompt, ValidatedEngineeringArchitecture)
        export_markdown_report(self.output_dir / "06_validated_engineering_architecture.md", "Stage 6: Validated Engineering Architecture", format_stage6_md(vea))
        return vea

    def compile_master_report(self, shr, fig, rcm, rinv, ifr, ccm, vea) -> Path:
        logging.info("Compiling Master TRIZ Engineering Report...")
        master_path = self.output_dir / "00_TRIZ_MASTER_REPORT.md"
        content = "\n\n---\n\n".join([
            format_stage1_md(shr),
            format_stage2_md(fig),
            format_stage3_md(rcm),
            format_stage4_md(rinv, ifr),
            format_stage5_md(ccm),
            format_stage6_md(vea),
        ])
        export_markdown_report(master_path, f"TRIZ Comprehensive Systems Engineering Report: {shr.system_name}", content)
        return master_path

#=========================================================

"""
CLI Entrypoint for Augmented TRIZ Engineering Pipeline.
"""
import os
import sys
from google import genai
from triz_pipeline_app import TRIZPipelineRunner

SAMPLE_BICYCLE_DRIVETRAIN_SPEC = """
Target System: Modern Road/Gravel Bicycle
Target Subsystem: Chain Drivetrain & Roller Link Interface
Current Components:
- Outer and inner link plates (Hardened carbon steel)
- Bearing pins (Case-hardened steel, OD 3.6mm)
- Rollers (Heat-treated steel bushing/roller interface)
- Lubricant: Liquid wet synthetic hydrocarbon lubricant
Operating Environment & Physics:
- Peak rider sprint tension: up to 1,800 N across the chain span.
- Ambient exposure: road grit (silica/quartz micro-particles 5-50 microns), rain, mud.
Current Primary Failure Mode:
- Road slurry enters clearance between pin and roller via capillary action.
- Abrasive slurry causes rapid 3-body wear, thinning the pin and boring out the roller.
- Pitch elongation occurs ("chain stretch"), accelerating sprocket wear and causing skipping under high pedal load.
Contradiction / Trade-off:
- Increasing pin diameter or adding contact elastomer seals increases weight, link friction, and rotational resistance.
"""

def main():
    api_key = "GEMINI_API_KEY"
    #if not api_key:
    #    print("[!] GEMINI_API_KEY not found in environment.")
    #    print("    Please set export GEMINI_API_KEY='your-api-key' to execute with live Google Gemini models.")
    #    print("    Running pipeline dry-run inspection on models...")
    #    sys.exit(0)

    client = genai.Client(api_key=api_key)
    runner = TRIZPipelineRunner(client=client, model="gemini-2.5-flash", output_dir="triz_output_bicycle")

    print("\n==================================================================")
    print("STARTING DETERMINISTIC TRIZ SYSTEMS ENGINEERING PIPELINE")
    print("==================================================================")
    
    shr = runner.run_stage_1(SAMPLE_BICYCLE_DRIVETRAIN_SPEC)
    fig = runner.run_stage_2(shr)
    rcm = runner.run_stage_3(fig)
    rinv, ifr = runner.run_stage_4(fig, rcm)
    ccm = runner.run_stage_5(rcm, rinv, ifr)
    vea = runner.run_stage_6(ccm, shr)
    master_file = runner.compile_master_report(shr, fig, rcm, rinv, ifr, ccm, vea)

    print(f"\nPipeline execution complete! Master report written to: {master_file}")

if __name__ == "__main__":
    main()

Execution Instructions

  1. Install dependencies:

    pip install google-genai pydantic
    
  2. Set your API key:

    export GEMINI_API_KEY="your-gemini-api-key"
    
  3. Execute the pipeline:

    python run_pipeline_demo.py
    

All stage outputs will be saved sequentially into triz_output_bicycle/, culminating in 00_TRIZ_MASTER_REPORT.md.


From <https://gemini.google.com/app/d4ecc87a313f13c7>  Google Gemini (3.8 Flash)

Comments

Popular posts from this blog

#4297 ISS Astronaut Unable to Speak

#4188 Hybrid/GraphRAG

#761 New Ways to Access Online Content, particularly Virtual Reality Content