Skip to main content
Step 4 of the analysis pipeline performs risk analysis by detecting critical events (hemorrhages, tumor touches) and identifying spatial patterns that indicate potential danger zones.

Function Signature

def _paso4_analizar_riesgo(df: pd.DataFrame) -> Dict:
    """
    Analyzes trajectory for critical events and spatial risk patterns.
    Returns counts of touches, hemorrhages, and identified critical quadrants.
    """

Detected Risk Factors

Tumor Touches

Contact with cancerous tissue that should be avoided

Hemorrhages

Vascular damage events causing bleeding

Critical Quadrants

Spatial zones where errors occurred

Event Clustering

Multiple incidents in the same area

Implementation

analysis_pipeline.py
def _paso4_analizar_riesgo(df: pd.DataFrame) -> Dict:
    tumor_touches = (df["event"] == "TUMOR_TOUCH").sum()
    hemorrhages = (df["event"] == "HEMORRHAGE").sum()
    
    # Análisis de cuadrantes (simple 2D para visualización)
    mid_x = (df["x"].max() + df["x"].min()) / 2
    mid_y = (df["y"].max() + df["y"].min()) / 2
    
    problemas = df[df["event"].isin(["TUMOR_TOUCH", "HEMORRHAGE"])]
    cuadrantes_criticos = []
    if not problemas.empty:
        for p in problemas.itertuples():
            pos = ""
            pos += "Sup" if p.y > mid_y else "Inf"
            pos += "-Der" if p.x > mid_x else "-Izq"
            if pos not in cuadrantes_criticos: cuadrantes_criticos.append(pos)
            
    return {
        "touches": int(tumor_touches),
        "hemorrhages": int(hemorrhages),
        "cuadrantes": cuadrantes_criticos
    }

Algorithm Breakdown

1

Count Critical Events

Count occurrences of TUMOR_TOUCH and HEMORRHAGE events.
tumor_touches = (df["event"] == "TUMOR_TOUCH").sum()
hemorrhages = (df["event"] == "HEMORRHAGE").sum()
These events are emitted by the frontend simulation when collision detection triggers.
2

Define Spatial Quadrants

Divide the surgical workspace into four quadrants using midpoints.
mid_x = (df["x"].max() + df["x"].min()) / 2
mid_y = (df["y"].max() + df["y"].min()) / 2
This creates four regions:
  • Sup-Der (Superior-Right): x > mid_x, y > mid_y
  • Sup-Izq (Superior-Left): x < mid_x, y > mid_y
  • Inf-Der (Inferior-Right): x > mid_x, y < mid_y
  • Inf-Izq (Inferior-Left): x < mid_x, y < mid_y
3

Map Events to Quadrants

For each critical event, determine which quadrant it occurred in.
problemas = df[df["event"].isin(["TUMOR_TOUCH", "HEMORRHAGE"])]
cuadrantes_criticos = []
if not problemas.empty:
    for p in problemas.itertuples():
        pos = ""
        pos += "Sup" if p.y > mid_y else "Inf"
        pos += "-Der" if p.x > mid_x else "-Izq"
        if pos not in cuadrantes_criticos: 
            cuadrantes_criticos.append(pos)
Duplicate quadrants are filtered out, so we only get unique risk zones.

Output Structure

The function returns a dictionary with three keys:
KeyTypeDescriptionSeverity
touchesintNumber of tumor contactsModerate (-8 points each)
hemorrhagesintNumber of bleeding eventsCritical (-15 points each)
cuadranteslist[str]Quadrants where errors occurredInformational

Example Outputs

{
  "touches": 0,
  "hemorrhages": 0,
  "cuadrantes": []
}
No critical events detected.

Event Types

The simulation frontend can emit these surgical events:
Marks the beginning of the surgical procedure. Not counted as a risk.
Normal movement with no special event. The majority of movements fall into this category.
Scalpel made contact with tumor tissue. In real surgery, touching the tumor can cause cancer cell spread.Penalty: -8 points per occurrence
Vascular structure was damaged, causing bleeding. This is the most severe error.Penalty: -15 points per occurrence
Marks successful completion of the procedure. Not counted as a risk.

Quadrant Visualization

     Y
     ^
     |
     |  Sup-Izq  |  Sup-Der
     |     ●     |     
     |           |     ●
  ───┼───────────┼─────────> X
     |           |     
     |     ●     |     ●
     |  Inf-Izq  |  Inf-Der
     |
The Z-axis is not used in quadrant analysis. This is a deliberate simplification for 2D visualization in the feedback report.

Clinical Interpretation

Hemorrhage Analysis

0 Hemorrhages

Excellent vascular control

1-2 Hemorrhages

Needs technique review

3+ Hemorrhages

Requires immediate retraining

Tumor Touch Analysis

  • 0 touches: Excellent tumor avoidance
  • 1-3 touches: Minor contact, acceptable in complex cases
  • 4+ touches: Excessive contact suggests poor spatial awareness

Spatial Patterns

Suggests a specific anatomical challenge or approach angle issue. Recommendation: Practice from different angles.
Indicates systemic issues with control or planning. Recommendation: Fundamental skill review needed.

Score Impact

Risk factors directly affect the final score in Step 5:
score = 100.0
score -= touches * 8        # Each touch costs 8 points
score -= hemorrhages * 15   # Each hemorrhage costs 15 points

Example Calculations

TouchesHemorrhagesPoints LostRemaining Score
000100
201684
011585
325446
These are baseline penalties. Additional penalties may apply based on economy of movement and other factors.

Future Enhancements

3D Quadrant Analysis

Include Z-axis for full 3D spatial risk mapping

Temporal Clustering

Detect rapid succession of errors (panic response)

Proximity Warnings

Identify near-misses that didn’t trigger events

Risk Heatmaps

Generate visual heatmaps of high-risk zones

Performance

Risk analysis is highly efficient:
  • Event counting: O(n) with vectorized boolean operations
  • Quadrant mapping: O(k) where k = number of critical events (typically much less than n)
  • No complex calculations: Simple comparisons and arithmetic
Typical performance: ~2ms for 5000 movements

Next Step

With risk factors quantified, the pipeline generates the final score and feedback:

Scoring & Feedback

Convert all metrics into actionable scores and recommendations

Build docs developers (and LLMs) love