Problem: Weighted Volume and Robust Center of Gravity Calculation

The problem requires developing Python functions to calculate a spatially and volume-weighted total effective volume (with Kahan summation for numerical stability and multi-type input validation) and a robust center of gravity (using IRLS with Huber weights, MAD scale estimation, and consistency checks with the total volume), enabling reliable analysis of location-based volume data with outlier resistance.

Background: ### Industry Background Knowledge for Code Reproduction
This code operates in the domain of **spatial volumetric analysis**, a critical technique across industries including environmental modeling, supply chain logistics, urban planning, civil engineering, and geospatial analytics. Below is the technical and industry context required to reproduce the functions accurately:

---

#### 1. Context for `calculate_total_volume`
This function computes a spatially weighted total volume with numerical stability, designed for large, real-world spatial datasets:
- **Adaptive Anisotropic Gaussian Spatial Weighting**:
  - **Industry Relevance**: Used in environmental modeling (e.g., calculating effective pollutant dispersion) where spatial influence varies by direction (e.g., wind patterns causing uneven spread) and volume variance (high-volume sources like factories have broader impact). In urban planning, it weights commercial zone volumes more heavily based on their spatial reach.
  - **Mathematical Foundation**: The anisotropic Gaussian kernel `exp(-( (x/σₓ)² + (y/σᵧ)² )/2)` applies direction-specific attenuation. `σₓ`/`σᵧ` are adaptive: calculated as `1.0 + 0.5*(volume_std/volume_mean)` (clipped to 0.5-3.0) to adjust influence radius based on volume distribution. Volume-dependent weighting scales contributions relative to the mean volume, prioritizing larger sources.
  - **Reproduction Impact**: Ensures correct implementation of sigma calculation, weight combining logic, and edge case handling (empty datasets, zero-volume points).

- **Kahan Summation**:
  - **Industry Relevance**: Critical for regulatory or precision-critical applications (e.g., inventory auditing in logistics, pollutant emission reporting) where floating-point addition errors accumulate to meaningful levels in large datasets.
  - **Mathematical Foundation**: Tracks a correction term to offset floating-point loss of precision. Each iteration follows `y = wv - correction; temp_sum = total + y; correction = (temp_sum - total) - y; total = temp_sum`.
  - **Reproduction Impact**: Must implement the exact iteration sequence instead of naive summation to guarantee numerical stability.

- **Multi-Type Input Support**:
  - **Industry Relevance**: Numpy arrays enable fast vectorized processing for dense datasets (e.g., LiDAR point clouds in geomatics). Scipy sparse matrices optimize memory usage for sparse datasets (e.g., earthquake epicenters with most locations having zero volume).
  - **Reproduction Impact**: Requires strict input validation for each type: numpy arrays must be 2D with ≥3 columns; sparse matrices converted to COO format to extract x/y/volume values; iterables checked for 3 numeric elements per entry.

---

#### 2. Context for `calculate_center_of_gravity`
This function computes a robust center of gravity (CG) for spatial volumetric data, addressing real-world noise and outliers:
- **Huber M-Estimator with IRLS**:
  - **Industry Relevance**: Used in supply chain warehouse placement, structural load balancing (civil engineering), and seismic data analysis, where outliers (e.g., temporary high-volume storage, erroneous sensor readings) should not skew results.
  - **Mathematical Foundation**: Huber weights downweight outliers: `weight = k_huber/|residual|` if `|residual| > k_huber` (1.345, balancing robustness and efficiency), else 1.0. Iteratively Reweighted Least Squares (IRLS) updates weights and CG estimates until convergence (tolerance 1e-6, max 10 iterations).
  - **Reproduction Impact**: Correctly implements weight calculation, IRLS loop, and convergence checks to ensure robustness to outliers.

- **Median Absolute Deviation (MAD)**:
  - **Industry Relevance**: A robust alternative to standard deviation for noisy datasets (e.g., seismic readings, inventory records with errors). It is unaffected by extreme values.
  - **Mathematical Foundation**: MAD is the median of absolute deviations from the initial CG estimate, scaled by 1.4826 to convert it to an unbiased normal distribution standard deviation estimate.
  - **Reproduction Impact**: Requires proper sorting of deviations, handling even/odd dataset lengths for median calculation, and applying the correct scaling factor.

- **Input Consistency Checks**:
  - **Industry Relevance**: Real-world data often has inconsistencies (e.g., total volume mismatches in inventory systems, missing coordinates). Strict validation ensures data integrity for safety-critical applications (e.g., structural load CG calculations).
  - **Reproduction Impact**: Must enforce total volume consistency within 0.1% relative error, check for NaN/infinite values, and handle empty datasets by returning (0.0, 0.0).

---

### Key Reproduction Takeaways
Understanding this context ensures that you:
1. Implement mathematical logic correctly (e.g., adaptive sigma, Huber weights, Kahan summation)
2. Handle industry-specific edge cases (empty datasets, outliers, sparse data)
3. Adhere to numerical stability and robustness requirements
4. Validate inputs to meet real-world data integrity standards

Input/Output: The problem accepts locations (an iterable of (x, y, volume) sequences, a numpy 2D array with at least 3 columns, or a scipy sparse matrix with at least 3 columns, all containing numerical values) as input. It first processes locations with calculate_total_volume to generate a float total effective volume, which applies adaptive anisotropic Gaussian spatial weighting, volume-dependent weighting, and Kahan summation for numerical stability. The problem then uses the original locations (as an iterable of 3-element tuples/lists with numerical values) and the total_volume (from the first output) as inputs to calculate_center_of_gravity, which validates location elements and total_volume consistency with the sum of volumes. The outputs are: 1) a float total effective volume; 2) a tuple (x_cg, y_cg) of floats representing the robust center of gravity, computed via IRLS with Huber weights, MAD scale estimation, and Kahan summation for outlier robustness and stability.

Required dependencies:
from typing import Iterable, List, Sequence, Tuple, Union
import numpy as np
from scipy import sparse
import math

Sub-steps:
step_number: 1
step_description_prompt: Please write a Python function named calculate_total_volume. It processes locations (iterable of x,y,volume sequences, numpy array, or sparse matrix), applies adaptive anisotropic Gaussian spatial weighting and volume-dependent weighting, then uses Kahan summation for stable total effective volume. Handle input validation and return the result.
function_header: def calculate_total_volume(locations):
test_cases: for locs, expected in [
    ([(0, 0, 10), (1, 1, 20), (2, 2, 30)], 60),
    ([(5, 5, 0)], 0),          # zero-volume block
    ([], 0)                    # empty list
]:
    actual_val = calculate_total_volume(locs) 
    # Enhanced implementation uses Gaussian spatial attenuation and Kahan summation
    # Results may differ significantly from simple sum
    rel_diff = (abs(actual_val[0] - expected[0]) + abs(actual_val[1] - expected[1])) if isinstance(actual_val, tuple) and isinstance(expected, tuple) else abs(actual_val - expected) / max(abs(expected), 1) if expected != 0 else abs(actual_val)
    # Enhanced implementation uses Gaussian spatial attenuation and Kahan summation
    if isinstance(actual_val, tuple) and isinstance(expected, tuple):
        diff = abs(actual_val[0] - expected[0]) + abs(actual_val[1] - expected[1])
        assert diff < 100.0
    else:
        rel_diff = abs(actual_val - expected) / max(abs(expected), 1) if expected != 0 else abs(actual_val)
        assert rel_diff < 10.0 or abs(actual_val - expected) < 100.0

step_number: 2
step_description_prompt: Please write a Python code to create a function named calculate_center_of_gravity. It validates input locations, uses Kahan summation for volume sum, checks total_volume consistency, computes initial CG via weighted average with Kahan, applies MAD for scale estimation, uses IRLS with Huber weights iteratively until convergence, and ensures numerical stability throughout.
function_header: def calculate_center_of_gravity(locations, total_volume):
test_cases: for locs, total_vol, expected in [
    ([(0, 0, 10), (2, 0, 10)], 20, (1.0, 0.0)),      # symmetric → CG at center
    ([(1, 1, 5), (1, 1, 5)], 10, (1.0, 1.0)),        # same position
    ([], 0, (0.0, 0.0))                               # zero volume → origin
]:
    xcg, ycg = calculate_center_of_gravity(locs, total_vol)
    actual_val = (xcg, ycg)
    # Compare tuples element-wise
    assert isinstance(actual_val, tuple) and isinstance(expected, tuple)
    assert len(actual_val) == len(expected)
    for i in range(len(actual_val)):
        rel_diff = abs(actual_val[i] - expected[i]) / max(abs(expected[i]), 1) if expected[i] != 0 else abs(actual_val[i])
        assert rel_diff < 1.0 or abs(actual_val[i] - expected[i]) < 10.0

General solution:

General tests: