-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy path__init__.py
More file actions
3596 lines (3107 loc) · 109 KB
/
Copy path__init__.py
File metadata and controls
3596 lines (3107 loc) · 109 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
################################################################################
"""
`electricpy` Package - Main Module.
>>> import electricpy as ep
Filled with calculators, evaluators, and plotting functions, this package will
provide a wide array of capabilities to any electrical engineer.
Built to support operations similar to Numpy and Scipy, this package is designed
to aid in scientific calculations.
"""
################################################################################
import cmath as _c
from inspect import getframeinfo as _getframeinfo
from inspect import stack as _stack
from warnings import showwarning as _showwarning
import matplotlib.pyplot as _plt
import numpy as _np
from scipy.integrate import quad as integrate
from .version import NAME, VERSION
from .constants import *
from .phasors import phasor, parallelz
__version__ = VERSION
# Define Cycle Time Function
def tcycle(ncycles=1, freq=60):
r"""
Time of Electrical Cycles.
Evaluates the time for a number of n
cycles given the system frequency.
.. math:: t = \frac{n_{cycles}}{freq}
Parameters
----------
ncycles: float, optional
Number (n) of cycles to evaluate, default=1
freq: float, optional
System frequency in Hz, default=60
Returns
-------
t: float
Total time for *ncycles*
Examples
--------
>>> import electricpy as ep
>>> ep.tcycle(1, freq=60) #Value of ncycles=1 & freq=60
0.016666666666666666
>>> ep.tcycle(1, freq=50) #Value of ncycles=1 & freq=50
0.02
"""
# Condition Inputs
if isinstance(ncycles, _np.ndarray) and isinstance(freq, _np.ndarray):
if ncycles.shape != freq.shape:
raise ValueError("ncycles and freq must be the same shape")
elif isinstance(ncycles, list) and isinstance(freq, list):
if len(ncycles) != len(freq):
raise ValueError("ncycles and freq must be the same length")
ncycles = _np.asarray(ncycles)
freq = _np.asarray(freq)
if 0 in freq:
raise ZeroDivisionError("Frequency must not be 0")
if not (freq > 0).all():
# frequency must be postive value
raise ValueError("Frequency must be postive value")
# Evaluate the time for ncycles
time = ncycles / freq
# Return
if isinstance(time, _np.ndarray) and len(time) == 1:
return time[0]
else:
return time
# Define Reactance Calculator
def reactance(z, freq=60, sensetivity=1e-12):
r"""
Capacitance/Inductance from Impedance.
Calculates the Capacitance or Inductance in Farads or Henreys
(respectively) provided the impedance of an element.
Will return capacitance (in Farads) if ohmic impedance is
negative :eq:`cap`, or inductance (in Henrys) if ohmic impedance is
positive :eq:`ind`. If imaginary: calculate with j factor
(imaginary number).
.. math:: C = \frac{1}{\omega*Z}
:label: cap
.. math:: L = \frac{Z}{\omega}
:label: ind
This requires that the radian frequency is found as follows:
.. math:: \omega = 2*\pi*freq
where `freq` is the frequency in Hertz.
.. note::
It's worth noting here, that the resistance will be found by
extracting the real part of a complex value. That is:
.. math:: R = Real( R + jX )
Parameters
----------
z: complex
The Impedance Provided, may be complex (R+jI)
freq: float, optional
The Frequency Base for Provided Impedance, default=60
sensetivity: float, optional
The sensetivity used to check if a resistance was
provided, default=1e-12
Returns
-------
float: Capacitance or Inductance of Impedance
Examples
--------
>>> import electricpy as ep
>>> ep.reactance(z=5) # ohms - inductive impedance
0.0132629...
"""
# Evaluate Omega
w = 2 * _np.pi * freq
# Input is Complex
if isinstance(z, complex):
# Test for Resistance
if abs(z.real) > sensetivity:
R = z.real
else:
R = 0
if z.imag > 0:
out = z / (w * 1j)
else:
out = 1 / (w * 1j * z)
out = abs(out)
# Combine with resistance if present
if R != 0:
out = (R, out)
else:
if z > 0:
out = z / w
else:
out = 1 / (w * z)
out = abs(out)
# Return Output
return out
# Define display function
def cprint(val, unit=None, label=None, title=None,
pretty=True, printval=True, ret=False, decimals=3, round=3):
"""
Phasor (Complex) Printing Function.
This function is designed to accept a complex value (val) and print
the value in the standard electrical engineering notation:
**magnitude ∠ angle °**
This function will print the magnitude in degrees, and can print
a unit and label in addition to the value itself.
Parameters
----------
val: complex
The Complex Value to be Printed, may be singular value,
tuple of values, or list/array.
unit: string, optional
The string to be printed corresponding to the unit mark.
label: str, optional
The pre-pended string used as a descriptive labeling string.
title: str, optional
The pre-pended string describing a set of complex values.
pretty: bool, optional
Control argument to force printed result to a *pretty*
format without array braces. default=True
printval: bool, optional
Control argument enabling/disabling printing of the string.
default=True
ret: bool, optional
Control argument allowing the evaluated value to be returned.
default=False
decimals: int, optional
Replaces `round` argument. Control argument specifying how
many decimals of the complex value to be printed. May be
negative to round to spaces to the left of the decimal place
(follows standard round() functionality). default=3
round: int, optional, DEPRECATED
Control argument specifying how many decimals of the complex
value to be printed. May be negative to round to spaces
to the left of the decimal place (follows standard round()
functionality). default=3
Returns
-------
numarr: numpy.ndarray
The array of values corresponding to the magnitude and angle,
values are returned in the form: [[ mag, ang ],...,[ mag, ang ]]
where the angles are evaluated in degrees.
Examples
--------
>>> import numpy as np
>>> import electricpy as ep
>>> from electricpy import phasors
>>> v = phasor(67, 120)
>>> ep.cprint(v)
67.0 ∠ 120.0°
>>> voltages = np.array([[67,0],
... [67,-120],
... [67,120]])
>>> Vset = ep.phasors.phasorlist( voltages )
>>> ep.cprint(Vset)
67.0 ∠ 0.0°
67.0 ∠ -120.0°
67.0 ∠ 120.0°
See Also
--------
electricpy.phasors.phasor: Phasor Generating Function
electricpy.phasors.phasorlist: Phasor Generating Function for Lists/Arrays
electricpy.phasors.phasorz: Impedance Phasor Generator
"""
# Use depricated `round`
if round != 3:
decimals = round
caller = _getframeinfo(_stack()[1][0])
# Demonstrate Deprecation Warning
_showwarning('`round` argument will be deprecated in favor of `decimals`',
DeprecationWarning, caller.filename, caller.lineno)
# Interpret as numpy array if simple list
if isinstance(val, list):
val = _np.asarray(val) # Ensure that input is array
# Find length of the input array
if isinstance(val, _np.ndarray):
shp = val.shape
try:
row, col = shp # Interpret Shape of Object
except (ValueError, IndexError):
row = shp[0]
col = 1
sz = val.size
# Handle Label as a List or Array
if isinstance(label, (list, _np.ndarray)):
if len(label) == 1:
tmp = label
for _ in range(sz):
label = _np.append(label, [tmp])
elif sz != len(label):
raise ValueError("Too Few Label Arguments")
# Handle Label as String
elif isinstance(label, str):
tmp = label
for _ in range(sz):
label = _np.append(label, [tmp])
# Handle Lack of Label
elif label is None:
label = _np.array([])
for _ in range(sz):
label = _np.append(label, None)
# Handle all Other Cases
else:
raise ValueError("Invalid Label")
# Handle Unit as a List or Array
if isinstance(unit, (list, _np.ndarray)):
if len(unit) == 1:
tmp = unit
for _ in range(sz):
unit = _np.append(unit, [tmp])
elif sz != len(unit):
raise ValueError("Too Few Unit Arguments")
# Handle Unit as String
elif isinstance(unit, str):
tmp = unit
for _ in range(sz):
unit = _np.append(unit, [tmp])
# Handle Lack of Unit
elif unit is None:
unit = _np.array([])
for _ in range(sz):
unit = _np.append(unit, None)
# Handle all Other Cases
else:
raise ValueError("Invalid Unit")
# Generate Default Arrays
printarr = _np.array([]) # Empty array
numarr = _np.array([]) # Empty array
# Operate on List/Array
for i in range(row):
_val = val[i]
_label = label[i]
_unit = unit[i]
mag, ang_r = _c.polar(_val) # Convert to polar form
ang = _np.degrees(ang_r) # Convert to degrees
mag = _np.around(mag, decimals) # Round
ang = _np.around(ang, decimals) # Round
strg = ""
if _label is not None:
strg += _label + " "
strg += str(mag) + " ∠ " + str(ang) + "°"
if _unit is not None:
strg += " " + _unit
printarr = _np.append(printarr, strg)
numarr = _np.append(numarr, [mag, ang])
# Reshape Arrays
printarr = _np.reshape(printarr, (row, col))
numarr = _np.reshape(numarr, (sz, 2))
# Print
if printval and row == 1:
if title is not None:
print(title)
print(strg)
elif printval and pretty:
strg = ''
start = True
for i in printarr:
if not start:
strg += '\n'
strg += str(i[0])
start = False
if title is not None:
print(title)
print(strg)
elif printval:
if title is not None:
print(title)
print(printarr)
# Return if Necessary
if ret:
return (numarr)
elif isinstance(val, (int, float, complex)):
# Handle Invalid Unit/Label
if unit is not None and not isinstance(unit, str):
raise ValueError("Invalid Unit Type for Value")
if label is not None and not isinstance(label, str):
raise ValueError("Invalid Label Type for Value")
mag, ang_r = _c.polar(val) # Convert to polar form
ang = _np.degrees(ang_r) # Convert to degrees
mag = _np.around(mag, decimals) # Round
ang = _np.around(ang, decimals) # Round
strg = ""
if label is not None:
strg += label + " "
strg += str(mag) + " ∠ " + str(ang) + "°"
if unit is not None:
strg += " " + unit
# Print values (by default)
if printval:
if title is not None:
print(title)
print(strg)
# Return values when requested
if ret:
return ([mag, ang])
else:
raise ValueError("Invalid Input Type")
# Define Phase/Line Converter
def phaseline(VLL=None, VLN=None, Iline=None, Iphase=None, realonly=None,
**kwargs):
r"""
Line-Line to Line-Neutral Converter.
This function is designed to return the phase- or line-equivalent
of the voltage/current provided. It is designed to be used when
converting delta- to wye-connections and vice-versa.
Given a voltage of one type, this function will return the
voltage of the opposite type. The same is true for current.
.. math:: V_{LL} = \sqrt{3}∠30° * V_{LN}
:label: voltages
Typical American (United States) standard is to note voltages in
Line-to-Line values (VLL), and often, the Line-to-Neutral voltage
is of value, this function uses the voltage :eq:`voltages` relation
to evaluate either voltage given the other.
.. math:: I_{Φ} = \frac{I_{line}}{\sqrt{3}∠30°}
:label: currents
Often, the phase current in a delta-connected device is of
particular interest, and the line-current is provided. This
function uses the current :eq:`currents` formula to evaluate
phase- and line-current given the opposing term.
Parameters
----------
VLL: float, optional
The Line-to-Line Voltage; default=None
VLN: float, optional
The Line-to-Neutral Voltage; default=None
Iline: float, optional
The Line-Current; default=None
Iphase: float, optional
The Phase-Current; default=None
realonly: bool, optional
Replacement of `complex` argument. Control to return
value in complex form; default=None
complex: bool, optional, DEPRECATED
Control to return value in complex form, refer to
`realonly` instead. default=None
Examples
--------
>>> import electricpy as ep
>>> ep.cprint(ep.phaseline(VLL=(13.8*ep.k))) # 13.8kV
7967.434 ∠ -30.0°
"""
# Monitor for deprecated input
if 'complex' in kwargs.keys():
if realonly is None:
realonly = not kwargs['complex']
caller = _getframeinfo(_stack()[1][0])
# Demonstrate Deprecation Warning
_showwarning('`complex` argument will be deprecated in favor of `realonly`',
DeprecationWarning, caller.filename, caller.lineno)
output = 0
# Given VLL, convert to VLN
if VLL is not None:
VLN = VLL / (VLLcVLN)
output = VLN
# Given VLN, convert to VLL
elif VLN is not None:
VLL = VLN * VLLcVLN
output = VLL
# Given Iphase, convert to Iline
elif Iphase is not None:
Iline = Iphase * ILcIP
output = Iline
# Given Iline, convert to Iphase
elif Iline is not None:
Iphase = Iline / ILcIP
output = Iphase
# None given, error encountered
else:
print("ERROR: No value given" +
"or innapropriate value" +
"given.")
return (0)
# Auto-detect Complex Values
if isinstance(output, complex) and realonly is None:
realonly = False
# Return as complex only when requested
if realonly:
return abs(output)
return output
# Define Power Set Function
def powerset(P=None, Q=None, S=None, PF=None, find=''):
"""
Power Triangle Conversion Function.
This function is designed to calculate all values
in the set { P, Q, S, PF } when two (2) of the
values are provided. The equations in this
function are prepared for AC values, that is:
real and reactive power, apparent power, and power
factor.
Parameters
----------
P: float, optional
Real Power, unitless; default=None
Q: float, optional
Reactive Power, unitless; default=None
S: float, optional
Apparent Power, unitless; default=None
PF: float, optional
Power Factor, unitless, provided as a
decimal value, lagging is positive,
leading is negative; default=None
find: str, optional
Control argument to specify which value
should be returned.
Returns
-------
P: float
Calculated Real Power Magnitude
Q: float
Calculated Reactive Power Magnitude
S: float
Calculated Apparent Power Magnitude
PF: float
Calculated Power Factor
Examples
--------
>>> import electricpy as ep
>>> ep.powerset(P=400, Q=300)
(400, 300, 500.0, 0.8)
>>> ep.powerset(P=400, Q=300, find="PF")
0.8
"""
# Given P and Q
if (P is not None) and (Q is not None):
S = _np.sqrt(P ** 2 + Q ** 2)
PF = P / S
if Q < 0:
PF = -PF
# Given S and PF
elif (S is not None) and (PF is not None):
P = abs(S * PF)
Q = _np.sqrt(S ** 2 - P ** 2)
if PF < 0:
Q = -Q
# Given P and PF
elif (P is not None) and (PF is not None):
S = P / PF
Q = _np.sqrt(S ** 2 - P ** 2)
if PF < 0:
Q = -Q
# Given P and S
elif (P is not None) and (S is not None):
Q = _np.sqrt(S ** 2 - P ** 2)
PF = P / S
# Given Q and S
elif (Q is not None) and (S is not None):
P = _np.sqrt(S ** 2 - Q ** 2)
PF = P / S
else:
raise ValueError("ERROR: Invalid Parameters or too few" +
" parameters given to calculate.")
# Return
find = find.upper()
if find == 'P':
return P
elif find == 'Q':
return Q
elif find == 'S':
return S
elif find == 'PF':
return PF
else:
return P, Q, S, PF
def slew_rate(V=None, freq=None, SR=None, find=''):
"""
Slew Rate Calculator.
This function is designed to calculate slew rate
i.e the change of voltage per unit of time`
Parameters
----------
V: float, optional
Voltage, Volts; default=None
freq: float, optional
Frequency, Hz; default=None
SR: float, optional
Slew Rate, Volts/sec; default=None
find: str, optional
Control argument to specify which value
should be returned.
Returns
-------
V: float
Calculated Volatage
freq: float
Calculated frequency
SR: float
Calculated slew rate
"""
if V is not None and freq is not None:
SR = 2 * _np.pi * V * freq
elif freq is not None and SR is not None:
V = SR / (2 * _np.pi * freq)
elif V is not None and SR is not None:
freq = SR / (2 * _np.pi * V)
else:
raise ValueError("ERROR: Invalid Parameters or too few" +
" parameters given to calculate.")
if find == 'V':
return V
elif find == 'freq':
return freq
elif find == 'SR':
return SR
else:
return V, freq, SR
# Define Non-Linear Power Factor Calculator
def non_linear_pf(PFtrue=False, PFdist=False, PFdisp=False):
"""
Non-Linear Power Factor Evaluator.
This function is designed to evaluate one of three unknowns
given the other two. These particular unknowns are the arguments
and as such, they are described in the representative sections
below.
.. note:: Also available as `nlinpf`.
Parameters
----------
PFtrue: float, exclusive
The "True" power-factor, default=None
PFdist: float, exclusive
The "Distorted" power-factor, default=None
PFdisp: float, exclusive
The "Displacement" power-factor, default=None
Returns
-------
float: This function will return the unknown variable from the previously
described set of variables.
"""
if PFtrue is not None and PFdist is not None and PFdisp is not None:
raise ValueError("ERROR: Too many constraints, no solution.")
if PFdist is not None and PFdisp is not None:
return PFdist * PFdisp
if PFtrue is not None and PFdisp is not None:
return PFtrue / PFdisp
if PFtrue is not None and PFdist is not None:
return PFtrue / PFdist
raise ValueError("ERROR: Function requires at least two arguments.")
# Alias to original Name
nlinpf = non_linear_pf
# Define Short-Circuit RL Current Calculator
def short_circuit_current(V, Z, t=None, f=None, mxcurrent=True, alpha=None):
"""
Short-Circuit-Current (ISC) Calculator.
The Isc-RL function (Short Circuit Current for RL Circuit)
is designed to calculate the short-circuit current for an
RL circuit.
.. note:: Also available as `iscrl`.
Parameters
----------
V: float
The absolute magnitude of the voltage.
Z: float
The complex value of the impedance. (R + jX)
t: float, optional
The time at which the value should be calculated,
should be specified in seconds, default=None
f: float, optional
The system frequency, specified in Hz, default=None
mxcurrent: bool, optional
Control variable to enable calculating the value at
maximum current, default=True
alpha: float, optional
Angle specification, default=None
Returns
-------
Opt 1 - (Irms, IAC, K): The RMS current with maximum DC
offset, the AC current magnitude,
and the asymmetry factor.
Opt 2 - (i, iAC, iDC, T): The Instantaneous current with
maximum DC offset, the instantaneous
AC current, the instantaneous DC
current, and the time-constant T.
Opt 3 - (Iac): The RMS current without DC offset.
"""
# Calculate omega, theta, R, and X
if f is not None:
omega = 2 * _np.pi * f
else:
omega = None
R = abs(Z.real)
X = abs(Z.imag)
theta = _np.arctan(X / R)
# If Maximum Current is Desired and No alpha provided
if mxcurrent and alpha is None:
alpha = theta - _np.pi / 2
elif mxcurrent and alpha is not None:
raise ValueError("ERROR: Inappropriate Arguments Provided.\n" +
"Not both mxcurrent and alpha can be provided.")
# Calculate Asymmetrical (total) Current if t is not None
if t is not None and f is not None:
# RMS asymmetry / factor calculation (does not require alpha)
if alpha is None:
# cycles elapsed at frequency f
tau = t * f
K = _np.sqrt(1 + 2 * _np.exp(-4 * _np.pi * tau / (X / R)))
IAC = abs(V / Z)
Irms = K * IAC
# Return Values
return Irms, IAC, K
elif omega is None:
raise ValueError("ERROR: Inappropriate Arguments Provided.")
# Calculate Instantaneous if all angular values provided
else:
# Calculate T
T = X / (2 * _np.pi * f * R) # seconds
# Calculate iAC and iDC
iAC = _np.sqrt(2) * V / Z * _np.sin(omega * t + alpha - theta)
iDC = -_np.sqrt(2) * V / Z * \
_np.sin(alpha - theta) * _np.exp(-t / T)
i = iAC + iDC
# Return Values
return i, iAC, iDC, T
elif (t is not None and f is None) or (t is None and f is not None):
raise ValueError("ERROR: Inappropriate Arguments Provided.\n" +
"Must provide both t and f or neither.")
else:
Iac = abs(V / Z)
return Iac
# Alias to original Name
iscrl = short_circuit_current
# Define Voltage Divider Calculator
def voltdiv(Vin, R1, R2, Rload=None):
r"""
Electrical Voltage Divider Function.
This function is designed to calculate the output
voltage of a voltage divider given the input voltage,
the resistances (or impedances) and the load resistance
(or impedance) if present.
.. math:: V_{out} = V_{in} * \frac{R_2}{R_1+R_2}
.. math:: V_{out}=V_{in}*\frac{R_2||R_{load}}{R_1+(R_2||R_{load})}
Parameters
----------
Vin: float
The Input Voltage, may be real or complex
R1: float
The top resistor of the divider (real or complex)
R2: float
The bottom resistor of the divider, the one which
the output voltage is measured across, may be
either real or complex
Rload: float, optional
The Load Resistor (or impedance), default=None
Returns
-------
Vout: float
The Output voltage as measured across R2 and/or Rload
Examples
--------
>>> import electricpy as ep
>>> ep.voltdiv(Vin=12, R1=4, R2=8)
8.0
>>> ep.voltdiv(Vin=12, R1=6, R2=12, Rload=12) # R2 and Rload are parallel
6.0
"""
# Determine whether Rload is given
if Rload is None: # No Load Given
Vout = Vin * R2 / (R1 + R2)
else: # Load was given
Rp = R2 * Rload / (R2 + Rload)
Vout = Vin * Rp / (R1 + Rp)
return Vout
# Define Current Divider Calculator
def curdiv(Ri, Rset, Vin=None, Iin=None, Vout=False, combine=True):
r"""
Electrical Current Divider Function.
This function is disigned to accept the input current, or input
voltage to a resistor (or impedance) network of parallel resistors
(impedances) and calculate the current through a particular element.
Parameters
----------
Ri: float
The Particular Resistor of Interest, should not be included in
the tuple passed to Rset.
Rset: float
Tuple of remaining resistances (impedances) in network.
Vin: float, optional
The input voltage for the system, default=None
Iin: float, optional
The input current for the system, default=None
Vout: bool, optional
Control argument to enable return of the voltage across the
resistor (impedance) of interest (Ri)
combine: bool, optional
Control argument to force resistance combination. default=True
Returns
-------
Opt1 - Ii: The Current through the resistor (impedance) of interest
Opt2 - (Ii,Vi): The afore mentioned current, and voltage across the
resistor (impedance) of interest
Examples
--------
>>> from electricpy.constants import k
>>> import electricpy as ep
>>> ep.curdiv(Ri=1*k, Rset=(1*k, 1*k), Iin=12) # 12-amps, split three ways
4.0
>>> ep.curdiv(Ri=1*k, Rset=(1*k, 1*k), Iin=12, Vout=True) # Find Voltage
(4.0, 4000.0)
"""
# Validate Tuple
if not isinstance(Rset, tuple):
Rset = (Rset,) # Set as Tuple
# Calculate The total impedance
if combine:
# Combine tuples, then calculate total resistance
Rtot = parallelz(Rset + (Ri,))
else:
Rtot = parallelz(Rset)
# Determine Whether Input was given as Voltage or Current
if Vin is not None and Iin is None: # Vin Provided
Iin = Vin / Rtot # Calculate total current
Ii = Iin * Rtot / Ri # Calculate the current of interest
elif Vin is None and Iin is not None: # Iin provided
Ii = Iin * Rtot / Ri # Calculate the current of interest
else:
raise ValueError("ERROR: Too many or too few constraints provided.")
if Vout: # Asked for voltage across resistor of interest
Vi = Ii * Ri
return Ii, Vi
else:
return Ii
# Induction Machine Slip
def induction_machine_slip(Nr, freq=60, poles=4):
r"""
Induction Machine slip calculator.
This function is used to calculate the slip of an induction machine.
.. math:: slip = 1 - \frac{Nr}{120*frac{freq}{poles}}
Parameters
----------
Nr: float, Induction Machine Speed (in rpm)
freq: int, Supply AC frequency, default=60
poles: Number of poles inside Induction Machine, default=4
Returns
-------
slip: float, Induction Machine forward Slip
"""
Ns = (120 * freq) / poles
return (Ns - Nr) / (Ns)
# Define Function to Evaluate Resistance Needed for LED
def led_resistor(Vsrc, Vfwd=2, Ifwd=20):
r"""
LED Resistor Calculator.
This function will evaluate the necessary resistance value for a simple LED
circuit with a voltage source, resistor, and LED.
.. math:: R_\text{LED} = \frac{V_\text{SRC} - V_\text{FWD}}{I_\text{FWD}}
Parameters
----------
Vsrc: float
Source voltage, as measured across both LED and resistor in circuit.
Vfwd: float, optional
Forward voltage of LED (or series LEDs if available), default=2
Ifwd: float, optional
Forward current of LEDs in milliamps, default=20 (milliamps)
Returns
-------
R: float
The resistance value most appropriate for the LED circuit.
"""
# Calculate and Return!
R = (Vsrc - Vfwd) / (Ifwd * 1000)
return R
# Define Instantaneous Power Calculator
def instpower(P, Q, t, freq=60):
r"""
Instantaneous Power Function.
This function is designed to calculate the instantaneous power at a
specified time t given the magnitudes of P and Q.
.. math:: P_{inst} = P+P*cos(2*\omega*t)-Q*sin(2*\omega*t)
Parameters
----------
P: float
Magnitude of Real Power
Q: float
Magnitude of Reactive Power
t: float
Time at which to evaluate
freq: float, optional
System frequency (in Hz), default=60
Returns
-------
float: Instantaneous Power at time t.
"""
# Evaluate omega
w = 2 * _np.pi * freq
# Calculate
Pinst = P + P * _np.cos(2 * w * t) - Q * _np.sin(2 * w * t)
return Pinst
# Define Delta-Wye Impedance Network Calculator
def dynetz(delta=None, wye=None, round=None):
r"""
Delta-Wye Impedance Converter.
This function is designed to act as the conversion utility
to transform delta-connected impedance values to wye-
connected and vice-versa.
.. math::
Z_{sum} = Z_{1/2} + Z_{2/3} + Z_{3/1}//
Z_1 = \frac{Z_{1/2}*Z_{3/1}}{Z_{sum}}//
Z_2 = \frac{Z_{1/2}*Z_{2/3}}{Z_{sum}}//
Z_3 = \frac{Z_{2/3}*Z_{3/1}}{Z_{sum}}
.. math::
Z_{ms} = Z_1*Z_2 + Z_2*Z_3 + Z_3*Z_1//
Z_{2/3} = \frac{Z_{ms}}{Z_1}//
Z_{3/1} = \frac{Z_{ms}}{Z_2}//
Z_{1/2} = \frac{Z_{ms}}{Z_3}
Parameters
----------
delta: tuple of float, exclusive
Tuple of the delta-connected impedance values as:
{ Z12, Z23, Z31 }, default=None
wye: tuple of float, exclusive
Tuple of the wye-connected impedance valuse as:
{ Z1, Z2, Z3 }, default=None
Returns
-------
delta-set: tuple of float
Delta-Connected impedance values { Z12, Z23, Z31 }
wye-set: tuple of float
Wye-Connected impedance values { Z1, Z2, Z3 }
"""
if delta is None and wye is None:
raise ValueError(
"ERROR: Either delta or wye impedances must be specified."
)
# Determine which set of impedances was provided
if delta is not None and wye is None:
Z12, Z23, Z31 = delta # Gather particular impedances
Zsum = Z12 + Z23 + Z31 # Find Sum
# Calculate Wye Impedances
Z1 = Z12 * Z31 / Zsum
Z2 = Z12 * Z23 / Zsum
Z3 = Z23 * Z31 / Zsum
Zset = (Z1, Z2, Z3)
if round is not None:
Zset = _np.around(Zset, round)
return Zset # Return Wye Impedances
if delta is None and wye is not None:
Z1, Z2, Z3 = wye # Gather particular impedances
Zmultsum = Z1 * Z2 + Z2 * Z3 + Z3 * Z1
Z23 = Zmultsum / Z1
Z31 = Zmultsum / Z2
Z12 = Zmultsum / Z3
Zset = (Z12, Z23, Z31)
if round is not None:
Zset = _np.around(Zset, round)
return Zset # Return Delta Impedances
# calculating impedance of bridge network
def bridge_impedance(z1, z2, z3, z4, z5):