Problem: Plate Inertia and Beam Deflection Calculations

The problem involves creating Python functions to compute the robust moment of inertia of non-uniform density rectangular plates using numerical integration and Monte Carlo methods, and to calculate maximum beam deflection handling deterministic or random inputs via integration, BVP solvers, or Monte Carlo simulations, with input validation and statistical analysis for random cases.

Background: ### Industry Background Knowledge
#### Structural Engineering Domain Context
These functions address core analysis tasks in mechanical, aerospace, and civil engineering:
- **Moment of Inertia Calculation**: Critical for designing rectangular plates (e.g., aircraft wing panels, vehicle chassis components, building floor slabs) with non-uniform material density. Non-uniformity mimics real-world scenarios like functionally graded materials, reinforced composites, or manufacturing-induced density variations.
- **Beam Deflection Calculation**: Computes maximum deflection of cantilever beams (used in machine brackets, bridge overhangs, satellite structures) under variable loading, material properties, and uncertainty—essential for ensuring structural safety and performance.

#### Mathematical & Numerical Foundations for Reproduction
1. **Moment of Inertia**:
   - **Core Definition**: The centroidal moment of inertia about the x-axis is defined as \(I = \int\int y^2 \rho(x,y) dx dy\), where \(\rho(x,y) = 1 + 0.1x^2 + 0.2y^2 + 0.01x^4 + 0.02y^4 + 0.005x^2y^2\) models quadratic and higher-order density variations.
   - **Gauss-Legendre Integration**: 7-node configuration balances precision and computational cost, a standard in engineering numerical analysis for evaluating double integrals.
   - **Monte Carlo Perturbation**: Adaptive relative noise (1% base, scaled by log10 of dimensions) simulates manufacturing tolerances. Importance sampling prioritizes regions with higher integral contribution to optimize efficiency, while weighted median provides robustness against outliers from measurement errors.

2. **Beam Deflection**:
   - **Deterministic Cases**: Uses the Euler-Bernoulli beam theory formula \( \delta = \frac{FL^3}{3EI} \) for constant modulus (\(E\)) and moment of inertia (\(I\)). For spatially varying \(E\) or \(I\), numerical integration via `quad` evaluates the integral of \(\frac{(L-x)^2}{E(x)I(x)} dx\).
   - **Nonlinear Modulus**: Solves a boundary value problem (BVP) using Newton-Raphson root finding (`root_scalar`) to handle stress-dependent stiffness, common in materials like plastics and elastomers. The BVP is solved with `solve_bvp` using clamped boundary conditions at the beam's fixed end.
   - **Uncertainty Quantification**: Monte Carlo simulation (10,000 samples) handles random inputs (loads, material properties from `scipy.stats.rv_continuous`), returning statistical metrics (mean, standard deviation, percentiles) for reliability-based design.

#### Implementation Guidelines for Reproduction
- **Dependencies**: Requires NumPy (array operations), SciPy (integration, BVP solving, root finding, statistics), and `functools.lru_cache` (cache integration results for repeated inputs).
- **Input Validation**: Rigorous checks ensure inputs are numeric, positive, and finite to avoid non-physical results, with support for scalar/array inputs for batch processing.
- **Key Function Roles**:
  - `validate_input`: Standardizes scalar/array inputs and enforces physical validity.
  - `cached_integral`: Combines Gauss-Legendre integration with Monte Carlo perturbation and importance sampling for robust moment of inertia calculation.
  - `calculate_max_deflection`: Branches logic based on input types (constant, function, random variable) to apply appropriate analytical, numerical, or statistical methods.

---
import numpy as np
from functools import lru_cache
from typing import Any, Callable, Dict, Union
import math
from scipy.integrate import quad, solve_bvp
from scipy.stats import rv_continuous
from scipy.optimize import root_scalar

Input/Output: The problem takes input data including width (scalar or array of positive finite numbers) and height (scalar or array of positive finite numbers with matching shape to width) for moment of inertia calculation; and force (scalar, array, or scipy.stats random variable), length (positive scalar), modulus (constant, function, or scipy.stats random variable), inertia (constant, function, or scipy.stats random variable) for max deflection calculation. It validates inputs (numeric, finite, positive, shape-consistent). For moment of inertia, it uses cached Gauss-Legendre integration (7 nodes), adaptive Monte Carlo sampling (200 samples) with importance weights, and weighted median to output scalar or array values (mass·length²). For max deflection, deterministic cases use integration or BVP solver to return scalar/array; random inputs use Monte Carlo simulation (10000 samples) to return a statistics dictionary (mean, std, min, max, 95th percentile).

Required dependencies:
import numpy as np
from functools import lru_cache
from typing import Any, Callable, Dict, Union
import math
from scipy.integrate import quad, solve_bvp
from scipy.stats import rv_continuous
from scipy.optimize import root_scalar

Sub-steps:
step_number: 1
step_description_prompt: Please write a Python function named calculate_moment_of_inertia. It validates width/height (scalar/array, positive finite), uses cached Gauss-Legendre integration (7 nodes), applies Monte Carlo perturbation with adaptive noise, importance sampling, computes weighted median for robust moment of inertia of rectangular plates with non-uniform density, and supports scalar/array inputs.
function_header: def calculate_moment_of_inertia(width, height):
test_cases: for b, h, expected in [
    (100.0, 200.0, (100 * 200**3) / 12),     
    (1.0, 1.0, 1/12),                        
    (10.0, 0.1, (10 * 0.1**3) / 12)           
]:
    result = calculate_moment_of_inertia(b, h)
    actual_val = result
    if isinstance(actual_val, tuple) and isinstance(expected, tuple):
        diff = abs(actual_val[0] - expected[0]) + abs(actual_val[1] - expected[1])
        assert diff < 100000.0
    else:
        rel_diff = abs(actual_val - expected) / max(abs(expected), 1) if expected != 0 else abs(actual_val)
        assert rel_diff < 1000000.0 or abs(actual_val - expected) < 10000000.0


step_number: 2
step_description_prompt: Please write a Python function named validate_input that takes x (Any) and name (str). Convert int/float x to a 1D numpy float64 array; ensure x is a numpy array otherwise. Check x's dtype is numeric, all values finite and strictly positive. Return x as float64, raising appropriate TypeErrors/ValueErrors for invalid cases.
function_header: def calculate_max_deflection(force, length, modulus, inertia):
test_cases: for F, L, E, I, expected in [
    (1000, 2.0, 200e9, (0.05 * 0.1**3)/12, (1000 * 2.0**3) / (3 * 200e9 * ((0.05 * 0.1**3)/12))),

    (100, 1.0, 1e12, 1e6, (100 * 1**3) / (3 * 1e12 * 1e6)),

    (1.0, 0.01, 70e9, (0.001 * 0.002**3)/12, (1.0 * 0.01**3) / (3 * 70e9 * ((0.001 * 0.002**3)/12)))
]:
    result = calculate_max_deflection(F, L, E, I)
    actual_val = result
    if isinstance(actual_val, tuple) and isinstance(expected, tuple):
        diff = abs(actual_val[0] - expected[0]) + abs(actual_val[1] - expected[1])
        assert diff < 1000.0
    else:
        rel_diff = abs(actual_val - expected) / max(abs(expected), 1) if expected != 0 else abs(actual_val)
        assert rel_diff < 10000.0 or abs(actual_val - expected) < 100000.0  



General solution:

General tests: