Problem: Three-Phase Reactive Power Compensation Calculations

The problem involves creating a Python framework for three-phase power system reactive power compensation calculations. It covers computing active/reactive power, target reactive power, capacitor compensation requirements, and capacitance values, with support for scalar/array inputs, numerical stability, input validation, and real-world engineering applicability.

Background: ### Industry Background Knowledge for Power System Compensation Calculations
This background provides the technical and industry context required to reproduce the provided power system functions accurately, covering both mathematical foundations and real-world engineering constraints.

---

#### 1. Three-Phase Active & Reactive Power Calculation (`calculate_power_components`)
##### Core Industry Context
Three-phase power systems are the standard for industrial and commercial power distribution. Key concepts include:
- **Balanced vs. Unbalanced Systems**: Balanced systems have equal voltages/currents across all phases, but real-world systems often have minor unbalances (up to 5% per industry standards) due to uneven load distribution. Negative sequence components from unbalances reduce usable active power by causing additional losses, while zero sequence components introduce extra reactive power.
- **Harmonic Reactive Power**: Nonlinear loads (e.g., variable frequency drives, rectifiers) generate harmonic currents, which add reactive power that traditional power factor calculations ignore. A 10% harmonic content factor is a typical industry approximation for such loads.
- **Standard Power Formulas**:
  - Balanced active power: \(P = \sqrt{3} \times V_{LL} \times I_L \times \text{pf}\)
  - Balanced reactive power: \(Q = \sqrt{3} \times V_{LL} \times I_L \times \sin\theta\), where \(\sin\theta = \sqrt{1-\text{pf}^2}\)
- **Input Validation Rules**: RMS voltage/current must be positive (physical quantities can’t be negative), and power factor ranges from 0 (pure reactive load) to 1 (pure resistive load).

##### Implementation Notes for Reproduction
- Use symmetric component adjustments (5% unbalance factor, 2% zero sequence factor) to account for real-world unbalances.
- Add harmonic reactive power as a percentage of balanced reactive power to model nonlinear load effects.
- Validate input types (scalar/array consistency) and ranges to prevent physical invalid calculations.

---

#### 2. Target Reactive Power Calculation (`calculate_target_reactive`)
##### Core Industry Context
This function supports power factor correction (PFC) systems, where the goal is to adjust reactive power to meet a target power factor. Key considerations:
- **Numerical Stability**: Trigonometric functions (`tan(acos(pf))`) introduce precision loss near pf = ±1. The algebraic identity \(\tan(\theta) = \sqrt{1-\text{pf}^2}/\text{pf}\) eliminates this error.
- **Edge Case Handling**: When active power is zero, no reactive power is needed. Clamping power factor to \([-1+\epsilon,1-\epsilon]\) prevents division by zero when pf approaches ±1.
- **Taylor Expansion**: Near pf = ±1, \(\sqrt{1-\text{pf}^2} \approx \sqrt{2(1-\text{pf})}\) (for pf→1) or \(\sqrt{2(1+\text{pf})}\) (for pf→-1) to maintain numerical accuracy.
- **Vectorization**: Industrial PFC systems often process multiple load points simultaneously, so supporting batch array inputs is critical.

##### Implementation Notes for Reproduction
- Replace trigonometric calculations with the algebraic identity to avoid precision errors.
- Apply Taylor approximation for \(\sqrt{1-\text{pf}^2}\) near pf boundaries.
- Add a zero-active-power short-circuit to skip unnecessary computations.
- Clamp power factor values to a safe range to avoid division by zero.

---

#### 3. Capacitor Reactive Power Compensation (`calculate_capacitor_kvar`)
##### Core Industry Context
Capacitors are used to compensate excess reactive power and improve power factor. Key engineering constraints:
- **Non-Negative Compensation**: Only compensate when current reactive power exceeds target (\(Q_{\text{comp}} = \max(Q_{\text{old}} - Q_{\text{new}}, 0)\)).
- **Floating-Point Stability**: When \(Q_{\text{old}}\) and \(Q_{\text{new}}\) are very close, direct subtraction causes cancellation errors. Kahan summation mitigates this by tracking correction terms.
- **Differentiable Control**: For closed-loop PFC systems, a differentiable max function (Huber smooth max) is preferred over a hard max to enable gradient-based control algorithms.
- **Complex Input Handling**: In phasor domain analysis, reactive power may be represented as complex numbers—using magnitude ensures physical relevance since only the absolute value of reactive power matters for compensation.

##### Implementation Notes for Reproduction
- Use Kahan summation for stable subtraction of reactive power values.
- Replace hard max with Huber smooth max (quadratic near zero, linear above threshold) for differentiability.
- Truncate subnormal floats to zero to avoid underflow issues in low-magnitude calculations.
- Preserve input type consistency (scalar output for scalar inputs, array for arrays).

---

#### 4. Capacitance Calculation from Reactive Power (`calculate_capacitance_delta`)
##### Core Industry Context
Converting required reactive power compensation to capacitor capacitance uses the formula derived from reactive power of a capacitor in three-phase systems:
\[ C = \frac{Q_C}{3 \times 2\pi f \times V_{LL}^2} \]
Key numerical and physical constraints:
- **Numerical Stability**: Direct computation can cause overflow (large Q, small V/f) or underflow (small Q, large V/f). Using log-transform: \(C = \text{sign}(Q_C) \times \exp\left(\log(|Q_C|) - \log(3) - \log(2\pi f) - 2\log(V_{LL})\right)\) eliminates these issues.
- **Physical Input Validation**: Line voltage and frequency must be strictly positive (can’t be zero or negative in real systems). Using machine epsilon as the minimum threshold avoids division by zero.

##### Implementation Notes for Reproduction
- Use log-transform for all calculations to prevent overflow/underflow.
- Add a small epsilon to \(|Q_C|\) before taking the logarithm to avoid log(0) errors.
- Validate that voltage and frequency are above machine epsilon to ensure physical plausibility.
- Convert outputs back to scalars if all inputs were scalars to maintain interface consistency.

Input/Output: The problem receives numeric inputs—RMS line-to-line voltage (v_ll, strictly positive), RMS line current (i_l, strictly positive), power factor (pf, 0 ≤ pf ≤ 1), target power factor (pf_target, clamped to [-1+1e-12, 1-1e-12]), and frequency (freq, strictly positive)—as scalars, numpy arrays, or compatible iterables (lists/tuples), with consistent type (scalar or array) across all inputs. It first computes three-phase active power (P, Watts) and original reactive power (Q_old, VAR) using v_ll, i_l, and pf. Next, it calculates target reactive power (Q_new, VAR) using P and pf_target. Then, it determines non-negative reactive power compensation (Q_c, VAR) by comparing Q_old and Q_new (returning 0 if overcompensated). Finally, it computes capacitance delta (C, Farads) via Q_c, v_ll, and freq using a log-transform formula for numerical stability. The outputs include a tuple of P/Q_old, Q_new, Q_c, and C, all matching input type (scalar/array) and shape, with safeguards (input validation, boundary handling, subnormal adjustment) ensuring robustness and correctness.

Required dependencies:
import math
from typing import Tuple, TypeVar, Union, List
import numpy as np

Sub-steps:
step_number: 1
step_description_prompt: Please write a Python code to generate a function named calculate_power_components. This function computes three-phase active and reactive power using line-to-line voltage, line current, power factor. It supports scalar/numpy array inputs, validates inputs, accounts for unbalanced system effects and harmonic reactive power, returning a tuple of active and reactive power.
function_header: def calculate_power_components(v_ll, i_l, pf):
test_cases: import math
test_power = [
    (400, 10, 0.8, (5514.85, 4544.90)),  # Updated: Enhanced formula with unbalanced three-phase
    (230, 10, 1.0, (3963.80, 79.67)),    # Updated: Enhanced formula with harmonic distortion
    (100, 1, 0.0, (0.0, 193.99))        # Updated: Enhanced formula with complex power calculations
]
for v, i, pf, (exp_p, exp_q) in test_power:
    p, q = calculate_power_components(v, i, pf)
    assert math.isclose(p, exp_p, abs_tol=1e-2)
    assert math.isclose(q, exp_q, abs_tol=1e-2)

step_number: 2
step_description_prompt: Please write a Python function named calculate_target_reactive. It computes target reactive power using algebraic identity tan(acos(x))=sqrt(1-x²)/x with Taylor expansion near ±1 for stability, input NaN/Inf validation, power factor clamping to valid range, zero active power short-circuit, vectorized operations via NumPy, returning output of same shape as inputs.
function_header: def calculate_target_reactive(p_active, pf_target):
test_cases: import math
test_target_q = [
    (1000, 1.0, 0.0),      
    (1000, 0.8, 750.0),    
    (5000, 0.9, 2421.61)   
]
for p, pf_t, exp_q in test_target_q:
    res = calculate_target_reactive(p, pf_t)
    assert math.isclose(res, exp_q, abs_tol=1e-2)

step_number: 3
step_description_prompt: Please write a Python function named calculate_capacitor_kvar. It computes capacitor reactive power compensation. Steps: convert inputs to numpy arrays, validate, handle complex via magnitude, use Kahan summation for stable subtraction, apply Huber smooth max, adjust subnormals, return scalar/array matching input type.
function_header: def calculate_capacitor_kvar(q_old, q_new):
test_cases: import math
test_kvar = [
    (1000, 400, 600.0),   # 需要补偿 600 VAR
    (500, 600, 0.0),      # 当前无功已低于目标，无需补偿 (返回0)
    (300, 300, 0.0)       # 刚好达到目标
]
for q_old, q_new, expected in test_kvar:
    assert math.isclose(calculate_capacitor_kvar(q_old, q_new), expected)

step_number: 4
step_description_prompt: Please write a Python function named calculate_capacitance_delta that takes q_c, v_ll, freq as inputs. Convert inputs to numpy arrays, validate they are numeric, v_ll and freq are strictly positive. Use log-transform for stable calculation: C = sign(q_c)*exp(log(|q_c|) - log(3) - 2*log(v_ll) - log(2πfreq)). Return scalar if inputs are scalars else array.
function_header: def calculate_capacitance_delta(q_c, v_ll, freq):
test_cases: import math
test_cap = [
    (1000, 400, 50, 6.63e-6),   # 400V, 50Hz, 1000VAR补偿
    (5000, 230, 60, 8.35e-5),   # 230V, 60Hz, 5000VAR补偿
    (0, 400, 50, 0.0)           # 无补偿量
]
for qc, v, freq, expected in test_cap:
    res = calculate_capacitance_delta(qc, v, freq)
    assert math.isclose(res, expected, rel_tol=1e-2)

General solution:

General tests: