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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
Build a gradio engineering calculator web application that provides standard, scientific,  programming, and 
ngineering calculator functionality, as well as unit converters between various units of measurement and currencies.  

The users can use the calculator in different interface modes:
1.) standard - standard calculator button functionality which offers basic operations and evaluates commands immediately as they are entered.
2.) scientific - scientific calculator button functionality which offers basic operations and evaluates commands immediately as they are entered.
3.) engineering - engineering calculation functions
4.) programming - functionality which offers common mathematical operations for developers including conversion between common bases, scripting based calculations using  input text areas and output text area.

Common functionality for all modes:
* Calculation history and memory capabilities.
* Infinite precision for basic arithmetic operations (addition, subtraction, multiplication, division) so that calculations never lose precision.
* Embedded AI chat interface

Calculator Key Mapping:
Addition:
(x + y) Addition, also known as summing or, more colloquially, “plus” is used to sum numbers together.
Subtraction:
(x - y) Subtraction, the “minus” sign, or sometimes difference, is used to find the numerical separation between two numbers, thus the term “difference”.
Multiplication:
(x * y) Multiplication, the product or “times” is represented sometimes by an “x” and sometimes by an asterisk “*”.
Division:
(x / y) Division, sometimes referred to as the quotient, is sometimes shown as a fraction, a “/” or the “÷” symbol. Which is supposedly called an “obelus” - who knew?
Scientific functions: In mathematics and in various fields of engineering, trigonometric functions are frequently used to solve different problems. It could be as simple as solving an unknown value of a right-angled triangle or solving the instantaneous power absorbed by an electrical element. Here are the trigonometric functions that you will encounter as you study mathematics and engineering:
Sine
In a right-angled triangle, the sine function can be used to relate the angle to the ratio of the length of the side opposite the angle and the hypotenuse. The sine function can be used in this scientific calculator by clicking the “sin” button.
Cosecant
The cosecant function is a reciprocal of the sine function.
Cosine
The cosine function is another trigonometric function that can be used to relate the angle of a right triangle to the ratio of the length of the side adjacent to the angle and the hypotenuse. It can be used in this scientific calculator by clicking the “cos” button.
Secant
The secant function is a reciprocal of the cosine function.
Tangent
The tangent function relates the angle of a right-angled triangle to the ratio of the length of the side opposite the angle and the side adjacent to the angle. This function can be used in this scientific calculator by clicking the “tan” button.
Cotangent
The cotangent function is a reciprocal of the tangent function.
Inverse Sine
The inverse sine (arcsine) trigonometric function can be used to determine the angle of a sine value. This can be used in this scientific calculator by clicking the “asin” button. The domain of an inverse sine function is from -1 to +1 and the range is from -90° to +90°.
Inverse Cosine
The inverse cosine (arccosine) trigonometric function can be used to determine the angle of a cosine value. To use this function, just click the “acos” button of this scientific calculator. The domain of the arccosine function is just the same with the arcsine function but its range is from 0 to +180°.
Inverse Tangent
The inverse tangent (arctangent) trigonometric function can be used to determine the angle of a tangent value from a domain covering all real numbers. The range of the arctangent function is from -90° to +90°. To use this function, click the “atan” button of this scientific calculator.
Other Functions:
Imaginary Unit
Whenever you multiply a negative number with a negative number, the result is a positive number. Specifically, any number squared will be a positive number, as it’ll either be a positive number multiplied by itself, yielding another positive number, or a negative number multiplied by itself, again yielding a positive number. Yet sometimes, you need something that, somehow, when multiplied by itself, gives a negative number. Mathematicians have called this number “i”, wherein (i2 = -1) To avoid confusion with the symbol for electrical current, in electrical engineering we frequently use “j” instead of “i”. In the calculator, simply use it as you would any other number, though you can’t use your keyboard to put it in - click on the bolded “i” box instead.
Factorial
Factorials are odd beasts that don’t show up very frequently but are important when you need them. Factorial is where you take a positive number, multiply it by...


for engineering mode the UI for Engineering mode should have a drop down combobox that updates the interface below the 
combobox to enable users to perform the engineering function (calculation).  The functions should 
include these Engineering Functions:			

3Ph Equivalent Impedance - calculates equivalent impedance and line currents for specified 5-wire (A,B,C,N,PE) system.  source code for the calculations are provided for you, use it.:

import numpy as np
import pandas as pd
from typing import Dict, List, Tuple, Union
from dataclasses import dataclass
import matplotlib.pyplot as plt
import seaborn as sns

@dataclass
class ConductorParams:
#Data class for conductor electrical parameters"""
  resistance: float  # Ω/mile
  gmr: float        # feet (Geometric Mean Radius)

@dataclass
class Coordinate:
#Data class for conductor coordinates”””
  x: float  # feet
  y: float  # feet

class PowerSystemImpedanceCalculator:

#Advanced impedance calculator for 5-wire power systems using modified Carson’s equations
#and Kron reduction technique.

#The calculator implements industry-standard methods for computing equivalent impedance
#matrices in multi-conductor transmission and distribution lines.


  # Carson's equation constants for 60 Hz, 100 Ω⋅m earth resistivity
  CARSON_REAL_CONSTANT = 0.09530  # Ω/mile
  CARSON_IMAG_COEFFICIENT = 0.12134  # Ω/mile
  CARSON_IMAG_CONSTANT = 7.93402  # dimensionless

  def __init__(self):
    """Initialize the calculator with default conductor labels"""
    self.conductor_labels = ['a', 'b', 'c', 'n', 'pe']
    self.phase_labels = ['a', 'b', 'c']
    
  def calculate_distance_from_coordinates(self, coord1: Coordinate, coord2: Coordinate) -> float:
    """
    Calculate Euclidean distance between two conductor coordinates.
    
    Args:
        coord1: First conductor coordinate
        coord2: Second conductor coordinate
        
    Returns:
        Distance in feet
    """
    dx = coord1.x - coord2.x
    dy = coord1.y - coord2.y
    return np.sqrt(dx**2 + dy**2)

  def calculate_all_distances_from_coordinates(self, coordinates: Dict[str, Coordinate]) -> Dict[str, float]:
    """
    Calculate all pairwise distances from conductor coordinates.
    
    Args:
        coordinates: Dictionary mapping conductor labels to coordinates
        
    Returns:
        Dictionary of pairwise distances with keys like 'ab', 'ac', etc.
    """
    distances = {}
    conductors = self.conductor_labels
    
    # Generate all unique pairs
    for i, cond1 in enumerate(conductors):
        for j, cond2 in enumerate(conductors[i+1:], i+1):
            key = f"{cond1}{cond2}"
            distance = self.calculate_distance_from_coordinates(
                coordinates[cond1], coordinates[cond2]
            )
            distances[key] = distance
            
    return distances

  def calculate_primitive_impedance_matrix(self, 
                                       distances: Dict[str, float], 
                                       conductor_params: Dict[str, ConductorParams]) -> np.ndarray:
    """
    Calculate the 5×5 primitive impedance matrix using modified Carson's equations.
    
    The primitive matrix includes all conductors (phases, neutral, PE) before reduction.
    Self-impedances account for conductor resistance and earth return effects.
    Mutual impedances account for electromagnetic coupling and earth return effects.
    
    Args:
        distances: Dictionary of pairwise distances between conductors
        conductor_params: Dictionary of conductor electrical parameters
        
    Returns:
        5×5 complex impedance matrix [Ω/mile]
    """
    n_conductors = len(self.conductor_labels)
    matrix = np.zeros((n_conductors, n_conductors), dtype=complex)
    
    # Calculate self-impedances (diagonal elements)
    for i, conductor in enumerate(self.conductor_labels):
        params = conductor_params[conductor]
        
        # Modified Carson's equation for self-impedance
        real_part = params.resistance + self.CARSON_REAL_CONSTANT
        imag_part = self.CARSON_IMAG_COEFFICIENT * (
            np.log(1.0 / params.gmr) + self.CARSON_IMAG_CONSTANT
        )
        
        matrix[i, i] = complex(real_part, imag_part)
    
    # Calculate mutual impedances (off-diagonal elements)
    # Mapping from matrix indices to distance dictionary keys
    distance_map = {
        (0, 1): 'ab', (0, 2): 'ac', (0, 3): 'an', (0, 4): 'ape',
        (1, 2): 'bc', (1, 3): 'bn', (1, 4): 'bpe',
        (2, 3): 'cn', (2, 4): 'cpe',
        (3, 4): 'npe'
    }
    
    for (i, j), distance_key in distance_map.items():
        distance = distances[distance_key]
        
        # Modified Carson's equation for mutual impedance
        real_part = self.CARSON_REAL_CONSTANT
        imag_part = self.CARSON_IMAG_COEFFICIENT * (
            np.log(1.0 / distance) + self.CARSON_IMAG_CONSTANT
        )
        
        mutual_impedance = complex(real_part, imag_part)
        matrix[i, j] = mutual_impedance
        matrix[j, i] = mutual_impedance  # Symmetry
        
    return matrix

  def apply_kron_reduction(self, primitive_matrix: np.ndarray) -> np.ndarray:
    """
    Apply Kron reduction to eliminate neutral and PE conductors from the impedance matrix.
    
    Kron reduction preserves the electrical behavior of the phase conductors while
    eliminating the neutral and protective earth conductors from the analysis.
    The reduction formula is: Z_abc = Z_pp - Z_pq @ Z_qq^(-1) @ Z_qp
    
    Args:
        primitive_matrix: 5×5 primitive impedance matrix
        
    Returns:
        3×3 reduced impedance matrix for phase conductors only [Ω/mile]
    """
    # Extract sub-matrices for Kron reduction
    # Z_pp: phase-to-phase impedances (3×3) - indices 0,1,2 (a,b,c)
    # Z_qq: neutral/PE impedances (2×2) - indices 3,4 (n,pe)  
    # Z_pq: phase-to-neutral/PE coupling (3×2)
    # Z_qp: neutral/PE-to-phase coupling (2×3) - transpose of Z_pq
    
    Z_pp = primitive_matrix[0:3, 0:3]  # Phase conductors
    Z_qq = primitive_matrix[3:5, 3:5]  # Neutral and PE
    Z_pq = primitive_matrix[0:3, 3:5]  # Phase to neutral/PE coupling
    Z_qp = primitive_matrix[3:5, 0:3]  # Neutral/PE to phase coupling
    
    # Calculate Z_qq inverse using robust numerical methods
    try:
        Z_qq_inv = np.linalg.inv(Z_qq)
    except np.linalg.LinAlgError:
        # Fallback to pseudo-inverse if matrix is singular
        Z_qq_inv = np.linalg.pinv(Z_qq)
        print("Warning: Z_qq matrix is singular, using pseudo-inverse")
    
    # Apply Kron reduction formula
    # Z_abc = Z_pp - Z_pq @ Z_qq^(-1) @ Z_qp
    correction_term = Z_pq @ Z_qq_inv @ Z_qp
    reduced_matrix = Z_pp - correction_term
    
    return reduced_matrix

  def calculate_impedance_from_distances(self, 
                                     distances: Dict[str, float],
                                     conductor_params: Dict[str, ConductorParams]) -> Tuple[np.ndarray, np.ndarray]:
    """
    Complete impedance calculation from conductor distances.
    
    Args:
        distances: Dictionary of pairwise conductor distances
        conductor_params: Dictionary of conductor electrical parameters
        
    Returns:
        Tuple of (primitive_matrix, reduced_matrix)
    """
    primitive_matrix = self.calculate_primitive_impedance_matrix(distances, conductor_params)
    reduced_matrix = self.apply_kron_reduction(primitive_matrix)
    
    return primitive_matrix, reduced_matrix

  def calculate_impedance_from_coordinates(self, 
                                       coordinates: Dict[str, Coordinate],
                                       conductor_params: Dict[str, ConductorParams]) -> Tuple[np.ndarray, np.ndarray, Dict[str, float]]:
    """
    Complete impedance calculation from conductor coordinates.
    
    Args:
        coordinates: Dictionary mapping conductor labels to coordinates
        conductor_params: Dictionary of conductor electrical parameters
        
    Returns:
        Tuple of (primitive_matrix, reduced_matrix, calculated_distances)
    """
    distances = self.calculate_all_distances_from_coordinates(coordinates)
    primitive_matrix, reduced_matrix = self.calculate_impedance_from_distances(distances, conductor_params)
    
    return primitive_matrix, reduced_matrix, distances

  def format_complex_matrix(self, matrix: np.ndarray, precision: int = 6) -> List[List[str]]:
    """
    Format complex matrix for readable display.
    
    Args:
        matrix: Complex numpy array
        precision: Number of decimal places
        
    Returns:
        List of lists containing formatted complex number strings
    """
    formatted = []
    for row in matrix:
        formatted_row = []
        for element in row:
            real = f"{element.real:.{precision}f}"
            imag = f"{element.imag:.{precision}f}"
            sign = "+" if element.imag >= 0 else ""
            formatted_row.append(f"{real} {sign} j{imag}")
        formatted.append(formatted_row)
    
    return formatted

  def create_impedance_dataframe(self, matrix: np.ndarray, labels: List[str]) -> pd.DataFrame:
    """
    Create a pandas DataFrame from impedance matrix for easier analysis.
    
    Args:
        matrix: Complex impedance matrix
        labels: Row/column labels
        
    Returns:
        DataFrame with complex impedance values
    """
    return pd.DataFrame(matrix, index=labels, columns=labels)

  def analyze_matrix_properties(self, matrix: np.ndarray) -> Dict[str, Union[float, bool]]:
    """
    Analyze impedance matrix properties for engineering insights.
    
    Args:
        matrix: Complex impedance matrix
        
    Returns:
        Dictionary containing matrix analysis results
    """
    properties = {}
    
    # Basic properties
    properties['condition_number'] = np.linalg.cond(matrix)
    properties['determinant'] = np.linalg.det(matrix)
    properties['is_symmetric'] = np.allclose(matrix, matrix.T, rtol=1e-10)
    properties['is_positive_definite'] = np.all(np.linalg.eigvals(matrix.real) > 0)
    
    # Eigenvalue analysis
    eigenvalues = np.linalg.eigvals(matrix)
    properties['min_eigenvalue_real'] = np.min(eigenvalues.real)
    properties['max_eigenvalue_real'] = np.max(eigenvalues.real)
    properties['eigenvalue_spread'] = properties['max_eigenvalue_real'] / properties['min_eigenvalue_real']
    
    # Impedance magnitude analysis
    magnitudes = np.abs(matrix)
    properties['min_impedance_magnitude'] = np.min(magnitudes)
    properties['max_impedance_magnitude'] = np.max(magnitudes)
    properties['avg_self_impedance_magnitude'] = np.mean(np.abs(np.diag(matrix)))
    
    return properties

  def plot_impedance_heatmap(self, matrix: np.ndarray, labels: List[str], title: str = "Impedance Matrix"):
    """
    Create a heatmap visualization of impedance matrix magnitudes.
    
    Args:
        matrix: Complex impedance matrix
        labels: Conductor labels
        title: Plot title
    """
    # Create magnitude matrix for visualization
    magnitude_matrix = np.abs(matrix)
    
    plt.figure(figsize=(10, 8))
    sns.heatmap(magnitude_matrix, 
               annot=True, 
               fmt='.4f', 
               xticklabels=labels, 
               yticklabels=labels,
               cmap='viridis',
               cbar_kws={'label': 'Impedance Magnitude (Ω/mile)'})
    plt.title(f"{title} - Magnitude")
    plt.tight_layout()
    plt.show()


# Example usage and test functions

def create_test_data():
  #Create sample data for testing the calculator”””


  # Sample conductor parameters (typical values)
  conductor_params = {
    'a': ConductorParams(resistance=0.055, gmr=0.038),    # 4/0 ACSR
    'b': ConductorParams(resistance=0.055, gmr=0.038),    # 4/0 ACSR  
    'c': ConductorParams(resistance=0.055, gmr=0.038),    # 4/0 ACSR
    'n': ConductorParams(resistance=8.0, gmr=0.012),      # #6 ACSR
    'pe': ConductorParams(resistance=8.0, gmr=0.012)      # #6 ACSR
  }

  # Sample coordinates (typical distribution line configuration)
  coordinates = {
    'a': Coordinate(x=0, y=42),
    'b': Coordinate(x=23.5, y=42), 
    'c': Coordinate(x=47, y=42),
    'n': Coordinate(x=10, y=74),
    'pe': Coordinate(x=37, y=72)
}

  return conductor_params, coordinates


def run_comprehensive_test():
  #Run comprehensive test of the impedance calculator


  print("=== Power System Impedance Calculator Test ===\n")

  # Initialize calculator
  calc = PowerSystemImpedanceCalculator()



  # Create test data
  conductor_params, coordinates = create_test_data()

  print("1. Input Parameters:")
  print("   Conductor Parameters:")
  for label, params in conductor_params.items():
    print(f"     {label.upper()}: R={params.resistance:.3f} Ω/mile, GMR={params.gmr:.3f} ft")

  print("\n   Conductor Coordinates:")
  for label, coord in coordinates.items():
    print(f"     {label.upper()}: ({coord.x:.1f}, {coord.y:.1f}) ft")

  # Calculate impedances
  print("\n2. Performing Calculations...")
  primitive_matrix, reduced_matrix, distances = calc.calculate_impedance_from_coordinates(
    coordinates, conductor_params
  )

  print("   ✓ Calculated distances from coordinates")
  print("   ✓ Built primitive impedance matrix")
  print("   ✓ Applied Kron reduction")

  # Display calculated distances
  print("\n3. Calculated Distances:")
  for pair, distance in distances.items():
    conductor1, conductor2 = pair[0].upper(), pair[1].upper()
    print(f"     {conductor1}-{conductor2}: {distance:.3f} ft")

  # Display results
  print("\n4. Primitive Impedance Matrix (5×5) [Ω/mile]:")
  primitive_df = calc.create_impedance_dataframe(primitive_matrix, calc.conductor_labels)
  for i, label in enumerate(calc.conductor_labels):
    print(f"     {label.upper()}: ", end="")
    for j in range(5):
        z = primitive_matrix[i, j]
        print(f"{z.real:>8.3f}{z.imag:>+8.3f}j ", end="")
    print()

  print("\n5. Reduced Phase Impedance Matrix (3×3) [Ω/mile]:")
  reduced_df = calc.create_impedance_dataframe(reduced_matrix, calc.phase_labels)
  for i, label in enumerate(calc.phase_labels):
    print(f"     {label.upper()}: ", end="")
    for j in range(3):
        z = reduced_matrix[i, j]
        print(f"{z.real:>8.3f}{z.imag:>+8.3f}j ", end="")
    print()

  # Matrix analysis
  print("\n6. Matrix Analysis:")
  properties = calc.analyze_matrix_properties(reduced_matrix)
  print(f"     Condition Number: {properties['condition_number']:.2e}")
  print(f"     Is Symmetric: {properties['is_symmetric']}")
  print(f"     Average Self-Impedance Magnitude: {properties['avg_self_impedance_magnitude']:.5f} Ω/mile")
  print(f"     Eigenvalue Spread: {properties['eigenvalue_spread']:.2f}")

  print("\n7. Test completed successfully!")ß