0% found this document useful (0 votes)
2 views19 pages

APEE Python Programe

The document contains multiple Python code snippets that demonstrate various electrical engineering concepts, including AC circuit analysis, current division, voltage dividers, RC circuits, RL circuits, LC circuits, solar panel I-V characteristics, wind power calculation, and DC motor speed analysis. Each code snippet includes calculations and visualizations relevant to the respective topic. The codes utilize libraries such as NumPy and Matplotlib for numerical computations and plotting.

Uploaded by

apurvphatangare
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views19 pages

APEE Python Programe

The document contains multiple Python code snippets that demonstrate various electrical engineering concepts, including AC circuit analysis, current division, voltage dividers, RC circuits, RL circuits, LC circuits, solar panel I-V characteristics, wind power calculation, and DC motor speed analysis. Each code snippet includes calculations and visualizations relevant to the respective topic. The codes utilize libraries such as NumPy and Matplotlib for numerical computations and plotting.

Uploaded by

apurvphatangare
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python Code

1 import numpy as np
2 import [Link] as plt
3
4 # Given values
5 Vm = 100 # Peak voltage in volts
6 R = 50 # Resistance in ohms
7 f = 60 # Frequency in Hz
8 omega = 2 * [Link] * f # Angular frequency (rad/s)
9
10 def calculate_current(Vm, R):
11 Im = Vm / R # Peak current in amps
12 return Im
13
14 # Time array for one cycle
15 t = [Link](0, 1 / f, 1000) # 1000 points within one cycle
16
17 # Voltage and current waveforms
18 v_t = Vm * [Link](omega * t) # Voltage as a function of time
19 Im = calculate_current(Vm, R) # Peak current
20 i_t = Im * [Link](omega * t) # Current as a function of time
21
22 # RMS values
23 Vrms = Vm / [Link](2) # RMS voltage
24 Irms = Im / [Link](2) # RMS current
25
26 # Average power
27 P_avg = Vrms * Irms
28
29 # Display results
30 print(f"Peak Voltage (Vm): {Vm} V")
31 print(f"Peak Current (Im): {Im:.2f} A")
32 print(f"RMS Voltage (Vrms): {Vrms:.2f} V")
33 print(f"RMS Current (Irms): {Irms:.2f} A")
34 print(f"Average Power (P_avg): {P_avg:.2f} W")
35
36 # Plot voltage and current waveforms
37 [Link](figsize=(10, 6))
38 [Link](t, v_t, label="Voltage (v(t))", color="blue")
39 [Link](t, i_t, label="Current (i(t))", color="red")
40 [Link](Vrms, color="blue", linestyle="--", label="Vrms")
41 [Link](-Vrms, color="blue", linestyle="--")
42 [Link](Irms, color="red", linestyle="--", label="Irms")
43 [Link](-Irms, color="red", linestyle="--")
44
45 [Link]("Voltage and Current in an AC Circuit with Resistor")
46 [Link]("Time (s)")
47 [Link]("Amplitude")
48 [Link]()
49 [Link]()
50 [Link]()
51
Python Code

1 # Define the resistances and input current


2 R1 = 4 # Resistance of R1 in ohms
3 R2 = 6 # Resistance of R2 in ohms
4 I_in = 10 # Input current in amperes
5
6 # Calculate the current through each resistor using the current divider formula
7 I1 = (R2 / (R1 + R2)) * I_in # Current through R1
8 I2 = (R1 / (R1 + R2)) * I_in # Current through R2
9
10 # Display the results
11 print(f"Current through R1 (I1): {I1:.2f} A")
12 print(f"Current through R2 (I2): {I2:.2f} A")
13
14 # Verification
15 total_current = I1 + I2
16 print(f"Total current (I_in): {total_current:.2f} A")
17
Python Code

1 def voltage_divider(v_in, r1, r2, r3):


2 # Calculate total resistance
3 r_total = r1 + r2 + r3
4
5 # Voltage across R1 (V_out1)
6 v_out1 = v_in * (r1 / r_total)
7
8 # Voltage across R2 (V_out2)
9 v_out2 = v_in * (r2 / r_total)
10
11 # Voltage across R3 (V_out3)
12 v_out3 = v_in * (r3 / r_total)
13
14 return v_out1, v_out2, v_out3
15
16 # Example values
17 v_in = 12 # Input voltage in volts
18 r1 = 1000 # R1 in ohms (2kΩ)
19 r2 = 2000 # R2 in ohms (3kΩ)
20 r3 = 3000 # R3 in ohms (5kΩ)
21
22 # Calculate output voltages
23 v_out1, v_out2, v_out3 = voltage_divider(v_in, r1, r2, r3)
24
25 # Display results
26 print(f"Input Voltage (V_in): {v_in} V")
27 print(f"Resistance R1: {r1 / 1000} kΩ, R2: {r2 / 1000} kΩ, R3: {r3 / 1000} kΩ")
28 print(f"Output Voltage across R1 (V_out1): {v_out1:.2f} V")
29 print(f"Output Voltage across R2 (V_out2): {v_out2:.2f} V")
30 print(f"Output Voltage across R3 (V_out3): {v_out3:.2f} V")
31
Python Code

1 import numpy as np
2 import [Link] as plt
3
4 # Parameters
5 Vs = 10 # Voltage source (V)
6 R = 100e3 # Resistance (Ohms)
7 C = 1e-6 # Capacitance (Farads)
8 tau = R * C # Time constant (seconds)
9
10 # Time range
11 t = [Link](0, 5 * tau, 500) # 0 to 5 time constants, 500 points
12
13 # Functions
14 Vc = Vs * (1 - [Link](-t / tau)) # Capacitor voltage
15 Ic = (Vs / R) * [Link](-t / tau) # Capacitor current
16
17 # Plotting
18 [Link](figsize=(12, 6))
19
20 # Plot Vc(t)
21 [Link](2, 1, 1)
22 [Link](t, Vc, label='$V_C(t)$', color='blue')
23 [Link](Vs, color='gray', linestyle='--', label='$V_s = 10V$')
24 [Link]('Capacitor Voltage and Current in RC Circuit')
25 [Link]('Voltage (V)')
26 [Link]()
27 [Link]()
28
29 # Plot Ic(t)
30 [Link](2, 1, 2)
31 [Link](t, Ic * 1e6, label='$I_C(t)$', color='red') # Convert A to µA
32 [Link]('Current (µA)')
33 [Link]('Time (s)')
34 [Link]()
35 [Link]()
36
37 # Show the plots
38 plt.tight_layout()
39 [Link]()
40
Python Code

1 import numpy as np
2 import [Link] as plt
3
4 # Given values
5 R = 4 # Ohms
6 L = 4e-3 # Henries (4mH)
7 V0 = 5 # Volts (DC source)
8 time = [Link](0, 0.01, 1000) # Time from 0 to 10 ms
9
10 # Solution for current i(t) = V0/R * (1 - exp(-t * R / L))
11 i_t = (V0 / R) * (1 - [Link](-time * R / L))
12
13 # Voltage across the inductor V_L(t) = L * di(t)/dt
14 d_i_t = [Link](i_t, time) # Numerical derivative of i(t)
15 V_L_t = L * d_i_t
16
17 # Plotting
18 [Link](figsize=(10, 6))
19
20 # Plot current
21 [Link](2, 1, 1)
22 [Link](time, i_t, label="Current (i(t))", color='b')
23 [Link]('Current through Circuit')
24 [Link]('Time (s)')
25 [Link]('Current (A)')
26 [Link](True)
27
28 # Plot voltage across the inductor
29 [Link](2, 1, 2)
30 [Link](time, V_L_t, label="Voltage across Inductor (V_L(t))", color='r')
31 [Link]('Voltage across Inductor')
32 [Link]('Time (s)')
33 [Link]('Voltage (V)')
34 [Link](True)
35
36 plt.tight_layout()
37 [Link]()
38
Python Code

1 import numpy as np
2 import [Link] as plt
3
4 # Given parameters
5 L = 2.0 # Inductance in henries
6 C = 0.5 # Capacitance in farads
7 V_dc = 10 # DC voltage in volts
8 omega_0 = 1 / [Link](L * C) # Natural frequency (rad/s)
9
10 # Time vector for simulation
11 t = [Link](0, 10, 1000) # Time from 0 to 10 seconds
12
13 # Current in the circuit (solution to the differential equation)
14 # i(t) = 5 * sin(omega_0 * t)
15 i_t = 5 * [Link](omega_0 * t)
16
17 # Voltage across the inductor: v_L = L * di/dt
18 v_L = L * omega_0 * 5 * [Link](omega_0 * t)
19
20 # Voltage across the capacitor: v_C = V_dc - v_L
21 v_C = V_dc - v_L
22
23 # Plotting the results
24 [Link](figsize=(12, 8))
25
26 # Plot current
27 [Link](3, 1, 1)
28 [Link](t, i_t, label="Current (i(t))", color="blue")
29 [Link]("Time (s)")
30 [Link]("Current (A)")
31 [Link]("Current in the Series LC Circuit")
32 [Link](True)
33 [Link]()
34
35 # Plot voltage across the inductor
36 [Link](3, 1, 2)
37 [Link](t, v_L, label="Voltage across Inductor (v_L)", color="green")
38 [Link]("Time (s)")
39 [Link]("Voltage (V)")
40 [Link]("Voltage Across the Inductor")
41 [Link](True)
42 [Link]()
43
44 # Plot voltage across the capacitor
45 [Link](3, 1, 3)
46 [Link](t, v_C, label="Voltage across Capacitor (v_C)", color="red")
47 [Link]("Time (s)")
48 [Link]("Voltage (V)")
49 [Link]("Voltage Across the Capacitor")
50 [Link](True)
51 [Link]()
52
53 # Adjust layout and show the plots
54 plt.tight_layout()
55 [Link]()
56
Python Code

1 import numpy as np
2 import [Link] as plt
3
4 # Constants
5 q = 1.6e-19 # Charge of electron (C)
6 k = 1.38e-23 # Boltzmann constant (J/K)
7 T = 298 # Temperature in Kelvin (25°C)
8 n = 1.3 # Ideality factor
9 Iph = 5 # Photo current (A)
10 Io = 1e-10 # Saturation current (A)
11 Rs = 0.01 # Series resistance
12 Vt = (k * T) / q
13
14 # Voltage range
15 V = [Link](0, 0.7, 100)
16
17 # Current equation (simplified diode model)
18 I = Iph - Io * ([Link]((V + Iph * Rs) / (n * Vt)) - 1)
19
20 # Power
21 P = V * I
22
23 # Plot I-V curve
24 [Link]()
25 [Link](V, I, label="I-V Curve")
26 [Link]("Voltage (V)")
27 [Link]("Current (A)")
28 [Link]("Solar Panel I-V Characteristics")
29 [Link](True)
30 [Link]()
31 [Link]()
32
33 # Plot P-V curve
34 [Link]()
35 [Link](V, P, label="P-V Curve", color="orange")
36 [Link]("Voltage (V)")
37 [Link]("Power (W)")
38 [Link]("Solar Panel P-V Characteristics")
39 [Link](True)
40 [Link]()
41 [Link]()
42
Python Code

1 import math
2
3 def calculate_wind_power(radius, wind_speed, air_density=1.225, cp=0.4):
4 """
5 Calculates the power developed by a wind turbine.
6
7 Parameters:
8 radius (float): Radius of the rotor in meters
9 wind_speed (float): Wind speed in m/s
10 air_density (float): Density of air (default 1.225 kg/m^3)
11 cp (float): Power coefficient/efficiency (default 0.4)
12
13 Returns:
14 float: Power in Watts
15 """
16 # Calculate swept area: A = pi * r^2
17 area = [Link] * (radius ** 2)
18
19 # Calculate power: P = 0.5 * rho * A * V^3 * Cp
20 power = 0.5 * air_density * area * (wind_speed ** 3) * cp
21
22 return power
23
24 # Example Usage:
25 # Turbine with 30m radius at 12 m/s wind speed
26 rotor_radius = 30
27 wind_speed = 12
28 power_w = calculate_wind_power(rotor_radius, wind_speed)
29 power_kw = power_w / 1000
30
31 print(f"Wind Speed: {wind_speed} m/s")
32 print(f"Rotor Radius: {rotor_radius} m")
33 print(f"Developed Power: {power_w:.2f} W")
34 print(f"Developed Power: {power_kw:.2f} kW")
35
Python Code

1 import numpy as np
2 import [Link] as plt
3
4 # DC Motor Parameters
5 Ra = 0.5 # Armature resistance (Ohms)
6 Ke = 0.1 # Back EMF constant (V/(rad/s))
7 Ia = 10 # Armature current (Amps) - constant load
8 voltage_range = [Link](50, 250, 100) # Armature voltage range (V)
9
10 # Speed calculation: omega = (Va - Ia*Ra) / Ke
11 speeds = (voltage_range - (Ia * Ra)) / Ke
12
13 # Plotting the result
14 [Link](figsize=(8, 5))
15 [Link](voltage_range, speeds, label='Speed $\omega_m$', color='blue',
linewidth=2)
16 [Link]('DC Motor Speed vs Armature Voltage')
17 [Link]('Armature Voltage ($V_a$) [V]')
18 [Link]('Speed ($\omega_m$) [rad/s]')
19 [Link](True)
20 [Link]()
21 [Link]()
22
Python Code

1 import numpy as np
2 import [Link] as plt
3
4 def calculate_breakdown_voltage(thicknesses, dielectric_strength):
5 """
6 Calculates breakdown voltage for given thicknesses.
7 V_bd = E_b * d
8 """
9 return dielectric_strength * thicknesses
10
11 # 1. Input Parameters
12 # Dielectric strength of material (e.g., Polyimide: 200-300 kV/mm)
13 # Let's use 250 kV/mm = 250,000 V/mm
14 dielectric_strength_kv_mm = 200
15
16 # Thicknesses in mm
17 thicknesses = [Link](0.01, 0.5, 50)
18
19 # 2. Calculate Breakdown Voltage (kV)
20 breakdown_voltages = calculate_breakdown_voltage(thicknesses,
dielectric_strength_kv_mm)
21
22 # 3. Plotting the Relationship
23 [Link](figsize=(10, 6))
24 [Link](thicknesses, breakdown_voltages, label=f'Dielectric Strength:
{dielectric_strength_kv_mm} kV/mm', linewidth=2)
25 [Link]('Breakdown Voltage vs. Insulation Thickness')
26 [Link]('Thickness (mm)')
27 [Link]('Breakdown Voltage (kV)')
28 [Link](True, which='both', linestyle='--', linewidth=0.5)
29 [Link]()
30 [Link]()
31
32 # Example Output
33 print(f"At {thicknesses[10]:.2f} mm, breakdown voltage is
{breakdown_voltages[10]:.2f} kV")
34
Python Code

1 import numpy as np
2 import [Link] as plt
3
4 def calculate_power(Vs, Vr, X_net, delta_degrees):
5 """
6 Calculates the real power transferred in an AC system.
7
8 Args:
9 Vs (float): Magnitude of sending-end voltage (Volts).
10 Vr (float): Magnitude of receiving-end voltage (Volts).
11 X_net (float): Net series reactance (Ohms).
12 delta_degrees (float): Power angle in degrees.
13
14 Returns:
15 float: Real power transferred in Watts.
16 """
17 # Convert angle from degrees to radians for Python's math functions
18 delta_radians = [Link](delta_degrees)
19
20 # Calculate power using the power-angle equation
21 P = (Vs * Vr / X_net) * [Link](delta_radians)
22
23 return P
24
25 # --- Example Usage ---
26 # Define system parameters
27 sending_voltage = 220e3 # 220 kV
28 receiving_voltage = 210e3 # 210 kV
29 net_reactance = 50 # Ohms
30
31 # 1. Calculate power at a specific angle (e.g., 30 degrees)
32 angle_specific = 30
33 power_at_angle = calculate_power(sending_voltage, receiving_voltage,
net_reactance, angle_specific)
34 print(f"Power transferred at {angle_specific} degrees: {power_at_angle:,.2f}
Watts or {power_at_angle/1e6:,.2f} MW\n")
35
36 # 2. Plot the power-angle curve
37 angles = [Link](0, 180, 100) # Range of angles from 0 to 180 degrees
38 power_values = [calculate_power(sending_voltage, receiving_voltage,
net_reactance, angle) for angle in angles]
39
40 # Find maximum power transfer value (occurs at 90 degrees)
41 max_power = (sending_voltage * receiving_voltage / net_reactance)
42 print(f"Theoretical maximum power transfer: {max_power:,.2f} Watts or
{max_power/1e6:,.2f} MW (at 90 degrees)")
43
44 # Plotting
45 [Link](figsize=(10, 6))
46 [Link](angles, power_values, label=f'P = (Vs*Vr/X) * sin(δ)')
47 [Link](angle_specific, power_at_angle, color='red', marker='o',
label=f'Power at {angle_specific}°: {power_at_angle/1e6:,.2f} MW')
48 [Link](x=90, color='gray', linestyle='--', label='Max Power Angle (90°)')
49 [Link](y=max_power, color='green', linestyle='--', label='Max Power (Pmax)')
50 [Link]('Power-Angle Relationship Curve')
51 [Link]('Power Angle $\\delta$ (degrees)')
52 [Link]('Real Power P (Watts)')
53 [Link](True)
54 [Link]()
55 [Link]()
56
Python Code

1 def calculate_transformer_efficiency():
2 print("--- Transformer Efficiency Calculator ---")
3
4 # 1. Inputs
5 try:
6 kva_rating = float(input("Enter Transformer Rating (kVA): "))
7 power_factor = float(input("Enter Power Factor (0-1): "))
8 load_ratio = float(input("Enter Load Factor/Ratio (e.g., 0.5 for half
load, 1.0 for full): "))
9 iron_loss_kw = float(input("Enter Iron Loss / Core Loss (kW): "))
10 full_load_cu_loss_kw = float(input("Enter Full Load Copper Loss (kW): "))
11 except ValueError:
12 print("Please enter valid numerical values.")
13 return
14
15 # 2. Calculations
16 # Output Power in kW
17 output_kw = load_ratio * kva_rating * power_factor
18
19 # Copper loss at specific loading is proportional to square of load ratio
20 copper_loss_kw = (load_ratio ** 2) * full_load_cu_loss_kw
21
22 # Total Losses
23 total_losses = iron_loss_kw + copper_loss_kw
24
25 # Input Power
26 input_kw = output_kw + total_losses
27
28 # Efficiency Calculation
29 efficiency = (output_kw / input_kw) * 100
30
31 # 3. Output
32 print("\n--- Efficiency Results ---")
33 print(f"Output Power: {output_kw:.2f} kW")
34 print(f"Total Losses: {total_losses:.2f} kW (Iron: {iron_loss_kw:.2f}kW,
Copper: {copper_loss_kw:.2f}kW)")
35 print(f"Efficiency at {load_ratio*100}% load: {efficiency:.2f} %")
36
37 # Run the program
38 if __name__ == "__main__":
39 calculate_transformer_efficiency()
40
Python Code

1 import numpy as np
2 import [Link] as plt
3
4 def calculate_kwh_from_load_curve(load_data, time_intervals):
5 """
6 Calculates total kWh consumption using the trapezoidal rule.
7
8 :param load_data: List/Array of load in kW (e.g., [20, 50, 30])
9 :param time_intervals: List/Array of hours between loads (e.g., [4, 2, 6])
10 :return: Total kWh, Average Load
11 """
12 total_energy = 0
13 total_time = sum(time_intervals)
14
15 # Using Trapezoidal Rule for Area Calculation:
16 # Area = sum of ( (load1 + load2) / 2 * time_difference )
17 for i in range(len(load_data) - 1):
18 avg_power = (load_data[i] + load_data[i+1]) / 2
19 energy_step = avg_power * time_intervals[i]
20 total_energy += energy_step
21
22 avg_load = total_energy / total_time
23
24 return total_energy, avg_load
25
26 # --- Example Usage ---
27 # Scenario: 24-hour daily load curve
28 # Load values in kW at specific time points
29 loads = [20, 30, 50, 70, 60, 40, 20, 30]
30 # Time duration (hours) between consecutive load points
31 intervals = [4, 2, 4, 2, 6, 4, 2] # Sum = 24 hours
32
33 # Ensure data alignment
34 if len(loads) != len(intervals) + 1:
35 print("Error: Loads should be one more than intervals for trapezoidal.")
36 else:
37 kwh, avg = calculate_kwh_from_load_curve(loads, intervals)
38 max_demand = max(loads)
39 load_factor = (kwh / (max_demand * sum(intervals))) * 100
40
41 print(f"--- Load Curve Analysis ---")
42 print(f"Total Consumption: {kwh:.2f} kWh")
43 print(f"Average Load: {avg:.2f} kW")
44 print(f"Maximum Demand: {max_demand:.2f} kW")
45 print(f"Load Factor: {load_factor:.2f}%")
46
47 # Cumulative time in hours (must start at 0)
48 time_points = [Link]([0, 4, 6, 10, 12, 18, 22, 24])
49
50 # Plot graph
51 [Link]()
52 [Link](time_points, loads, marker='o')
53
54 # Labels and title
55 [Link]("Time (hours)")
56 [Link]("Load (kW)")
57 [Link]("Load Curve (Load vs Time)")
58
59 # Grid for better readability
60 [Link]()
61
62 # Show plot
63 [Link]()
64
Python Code

1 import numpy as np
2
3 # Coefficient matrix
4 A = [Link]([
5 [0.5595238, -0.142857],
6 [-0.142857, 0.353968]
7 ])
8
9 # Constant matrix
10 B = [Link]([7, -6.8888])
11
12 # Solve the linear system Ax = B
13 solution = [Link](A, B)
14
15 # Print the results
16 V2, V3 = solution
17 print(f"V2 = {V2}")
18 print(f"V3 = {V3}")
19
20
21
22
23 def solve_kvl_dependent(Vs, R1, R2, k):
24 """
25 Solves a single loop circuit with a dependent voltage source.
26
27 Vs : Independent voltage source (Volts)
28 R1, R2 : Resistances (Ohms)
29 k : Gain of dependent voltage source (V/A)
30
31 Returns:
32 Current (I) in the circuit
33 """
34 # Total resistance including dependent source effect
35 total = R1 + R2 + k
36
37 # Using KVL
38 I = Vs / total
39
40 return I
41
42
43 # ---- Example values ----
44 Vs = 20 # Volts
45 R1 = 5 # Ohms
46 R2 = 10 # Ohms
47 k = 2 # Dependent source coefficient
48
49 current = solve_kvl_dependent(Vs, R1, R2, k)
50
51 print("Circuit Current (I): {:.3f} A".format(current))
52

You might also like