-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdata_generation_experiments.py
More file actions
1241 lines (1070 loc) · 38.2 KB
/
Copy pathdata_generation_experiments.py
File metadata and controls
1241 lines (1070 loc) · 38.2 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
# ---
# jupyter:
# jupytext:
# comment_magics: false
# text_representation:
# extension: .py
# format_name: percent
# format_version: '1.3'
# jupytext_version: 1.16.4
# kernelspec:
# display_name: .venv
# language: python
# name: python3
# ---
# %% [markdown]
# # Modelling Of Rectangular Copuled coil for WPT
# %% [markdown]
# ## Obtaining Self Inductance of single stranded coil
# %% [markdown]
# ## Twisted Strand Self Inductance
#
#
# 
#
# https://drive.google.com/drive/u/1/folders/1BTUm7Y0_uVSXSQ1wlAuN0aInFpQHv49P
#
# ### Explanation:
# 1. **`calculate_self_inductance(ls, R)`**: Calculates the self-inductance $ L $ using the formula provided:
# $$
# L = 0.002 \left[ \log_e \left(\frac{2l_s}{R}\right) - 1 \right] \text{\microH}
# $$
#
# 2. **`calculate_R(RGMD, n, r)`**: Computes $ R $ using:
# $$
# R = \left(\text{RGMD} \cdot n \cdot r^{n-1}\right)^{\frac{1}{n}}
# $$
#
# 3. **`calculate_RGMD(rho)`**: Calculates the geometric mean distance $ \text{RGMD} $ using:
# $$
# \log_e(\text{RGMD}) = \log_e(\rho) - \frac{1}{4}
# $$
#
# (`ls`, `rho`, `r`, `n`) are in cm to obtain the self-inductance $ L $ in \microH.
#
# %%
import numpy as np
def L_Litz(ls, R):
# Given formula: L = 0.002 * [log_e(2ls/R) - 1] \microH
L = 0.002 *ls* (np.log(2 * ls / R) - 1)
return L
def calculate_R(RGMD, n, r):
# Given formula: R = ((RGMD * n * r^(n-1))^(1/n))
R = (RGMD * n * r**(n-1))**(1/n)
# print(f"R = {R:.4f}")
return R
def calculate_RGMD(rho):
# Given formula: log_e(RGMD) = log_e(rho) - 1/4
RGMD = np.exp(np.log(rho) - 1/4)
return RGMD
# Example values (in cm)
ls = 100.0 # length of wires
rho = 0.05 # radius of a single strand
r = 0.5 # radius of the bundle
n = 10 # number of strands
# Step 1: Calculate RGMD
RGMD = calculate_RGMD(rho)
# Step 2: Calculate R
R = calculate_R(RGMD, n, r)
# Step 3: Calculate L (in \microH)
L = L_Litz(ls, R)
print(f"Self-Inductance L = {L:.4f} \micro H")
# %%
def L_litz_coil(ls,rho,n,r):
'''Finding the self-inductance of a Litz coil:
Inputs:
ls = length of the wire
rho = radius of a single strand
n = number of strands
r = radius of the bundle
Output:
L = self-inductance of the Litz coil'''
RGMD = calculate_RGMD(rho)
R = calculate_R(RGMD, n, r)
L = L_Litz(ls, R)
return L
# %% [markdown]
# ### Mutual Inductance of a Two Equal Length wires
#
#
# ### Explanation:
# 1. **`calculate_lambda(ls, dxy)`**: Computes the value of $ \lambda $ using the formula:
# $$
# \lambda = \frac{l_s}{d_{xy}}
# $$
# where:
# - $l_{s}, d_{xy}$ are length of the conductor and distance between conductors respectively
#
# 2. **`calculate_mutual_inductance(ls, lam)`**: Calculates the mutual inductance $ M $ using:
# $$
# M = 0.002 \cdot l_s \cdot \log_e \left(\lambda + \sqrt{1 + \lambda^2} - \sqrt{1 + \frac{1}{\lambda^2} + \frac{1}{\lambda}}\right) \text{\microH}
# $$
#
# 3. **Example Values**: You can replace `ls` and `dxy` with your specific values to obtain the mutual inductance $ M $ in \microH.
#
# This code will help you calculate the mutual inductance for two closely spaced parallel filaments with the specified parameters.
# %%
import numpy as np
def M_L(ls, dxy):
'''
Caluclate the mutual inductance between two parallel conductors
Inputs:
ls = length of the conductors
dxy = distance between the two conductors
Output:
M = mutual inductance between the two conductors
'''
# Given formula for mutual inductance M:
lam = ls/dxy
if lam == 0:
return 0
M = 0.002 * ls * (np.log(lam + np.sqrt(1 + lam**2)) - np.sqrt(1 + 1/(lam**2) + 1/lam))
return M
# Example values (in cm)
ls = 10.0 # length of the conductors
dxy = 0.1 # distance between the two conductors
# Step 1: Calculate λ
# Step 2: Calculate M (in \microH)
M = M_L(ls, dxy)
print(f"Mutual Inductance M = {M:.4f} \microH")
# %% [markdown]
# ### M for Unequal wires:
#
# 
#
# ### Explanation:
#
# 1. **Unequal Parallel Conductors**:
# - The mutual inductance $ M $ is calculated by subtracting $ M_p $ (mutual inductance of pair $ p $) from $ M_{m+p} $ (mutual inductance of combined pair $ m+p $):
# $$
# M = M_{m+p} - M_p
# $$
#
# 2. **Misaligned Parallel Conductors**:
# - The mutual inductance $ M $ for misaligned parallel conductors is calculated using:
# $$
# 2M = (M_{l+m−Δ} + M_{Δ}) − (M_{l−Δ} + M_{m−Δ})
# $$
# - The resulting value is then divided by 2 to get the mutual inductance $ M $.
#
# You can replace the example values with your specific data to compute the mutual inductance for both scenarios.
# %%
def mutual_inductance(l, d):
"""
Calculate the mutual inductance between two parallel conductors.
Parameters:
l : float : Length of the conductors (in meters).
d : float : Distance between the two conductors (in meters).
mu0 : float : Permeability of free space (in H/m). Default is 4π × 10^-7 H/m.
Returns:
M : float : Mutual inductance (in Henrys).
"""
term1 = l * np.log((l + np.sqrt(l**2 + d**2)) / d)
term2 = np.sqrt(l**2 + d**2) - d
M = (1e-3)* 2 * (term1 - term2)
return M
# Example usage
l = 30 # length in meters
d = 0.1 # distance in meters
M = mutual_inductance(l, d)
print(f"The mutual inductance M is {M:.5f} \microH")
# %%
def M_L_unequal2(L1,L2,dxy):
'''
Caluclate the mutual inductance between two parallel conductors of unequal length
Inputs:
L1 = length of the first conductor
L2 = length of the second conductor
dxy = distance between the two conductors
Output:
M = mutual inductance between the two conductors of unequal length
'''
M_mp = mutual_inductance(abs((L1-L2)/2) + L2, dxy)
M_p = mutual_inductance(abs((L1-L2)/2), dxy)
M = M_mp - M_p
return M
# %%
# Calculate M for unequal parallel conductors
# dxy is dxy
def M_L_unequal(L1,L2,dxy):
'''
Caluclate the mutual inductance between two parallel conductors of unequal length
Inputs:
L1 = length of the first conductor
L2 = length of the second conductor
dxy = distance between the two conductors
Output:
M = mutual inductance between the two conductors of unequal length
'''
M_mp = M_L(abs((L1-L2)/2) + L2, dxy)
M_p = M_L(abs((L1-L2)/2), dxy)
M = M_mp - M_p
return M
# Calculate M for misaligned parallel conductors
def M_L_misaligned(L1,L2,dxy,Misalignment):
'''
Caluculate the mutual inductance between two parallel conductors with misalignment
Inputs:
L1 = length of the first conductor
L2 = length of the second conductor
dxy = distance between the two conductors
Misalignment = misalignment between the two conductors
Output:
M = mutual inductance between the two misaligned conductors
'''
M_l_m_delta = mutual_inductance(L1+L2-Misalignment,dxy)
M_delta = mutual_inductance(Misalignment,dxy)
M_l_delta = mutual_inductance(L1-Misalignment,dxy)
M_m_delta = mutual_inductance(L2-Misalignment,dxy)
M = ((M_l_m_delta + M_delta) - (M_l_delta + M_m_delta)) / 2
return M
L1 = 10.0 # length of the first conductor
L2 = 8.0 # length of the second conductor
dxy = 0.1 # distance between the two conductors
Misalignment = 0.1 # misalignment between the two conductors
M_misaligned = M_L_misaligned(L1,L2,dxy,Misalignment)
print(f"Mutual Inductance M_misaligned = {M_misaligned:.4f} \microH")
M_unequal = M_L_unequal2(L1,L2,dxy)
print(f"Mutual Inductance M_unequal = {M_unequal: .4f} \microH")
# %% [markdown]
# ## Rectangular Spiral Coil Modelling
#
# 
# %% [markdown]
# #### Assumptions:
# * Rectangular Coil with dimensions $a$, $b$
# * diameter-$d$, $N$-turns, $h$-Airdxy
# * distance between two turns $d_{xy} = \rho_{xy} + d $
# * Effective Lengths: $a_{1} = a-d, b_{1} = b-d, h_{1} = h-d$
# * Diameter of wire: $d$
# %% [markdown]
# ### Effective Inductance of a Coil in System Settings:
#
# To calculate the self-inductance $ L_{\text{coil}} $ of a rectangular coil with $ N $ turns, the inductance can be computed based on the contributions from the two sides of the rectangle using the following formula:
#
# $$
# L_{\text{coil}} = 2(L_{\text{side}_a} + L_{\text{side}_b})
# $$
#
# Where:
# - $ L_{\text{side}_a} $ is the self-inductance contribution from the sides of the coil with length $ a $.
# - $ L_{\text{side}_b} $ is the self-inductance contribution from the sides of the coil with length $ b $.
#
# The inductance contribution from any side, $ L_{\text{side}} $, is calculated as:
#
# $$
# L_{\text{side}} = L_w + M_{\text{ss}} - M_{\text{os}}
# $$
#
# Where:
# - $ L_w $ is the self-inductance of the $ N $ straight wires present on one side.
# - $ M_{\text{ss}} $ is the mutual inductance among the $ N $ wires on the same side.
# - $ M_{\text{os}} $ is the mutual inductance among the $ N $ wires on opposite sides.
#
# ### Explanation:
#
# 1. **Self-Inductance of the Wires $ L_{w} $**:
# - This term represents the self-inductance of the $ N $ wires on a single side of the coil. It's the inductance due to each wire's magnetic field acting on itself.
# $$
# L_{w} = \sum_{i=0}^{N-1} L(l_i, \rho)
# $$
# where:
# - $ N $ No of coils
# - $ l_{i} $ length of ith segment
# - which is equal to:
# $$
# l_{i} = l_{side} - 2*i*d_{xy}
# $$
# - distance between two turns $$ d_{xy} = \rho_{xy} + 2*R $$
# - $\rho_{xy}$ is pitch (saperation between turns of the coil)
# - $ \rho $ radius of single strand
#
# 2. **Mutual Inductance on the Same Side $ M_{\text{ss}} $**:
# - This term accounts for the interaction between the magnetic fields of the wires that lie on the same side. Since the currents flow in the same direction, their magnetic fields add up, increasing the total magnetic field and the self-inductance $ L_{\text{side}} $.
#
# Mutual Inductance of Unequal Length:
# - Contains Two terms: $ M = M_{m+p} - M_p $
# - For each coil pair choosen for same side:
# $$
# M_{ss} = \sum_{i=0}^{N-1} \sum_{i' = 0, i' \neq i}^{N-1} M(F1(side length,i,i'), d_{i-i'}) - \sum_{i=0}^{N-1} \sum_{i' = 0, i' \neq i}^{N-1} M(F2(i,i'), d_{i-i'})
# $$
# where:
# - $F1(side_length,i,i') = side length - (i)*2*d_{xy} + |i-i'|*d_{xy}$ -- m + p
# - $F2(i,i') = |i-i'|*d_{xy}$ -- p
# - $d_{i-i'} = |(i-i')*d_{xy}|$
# - side_length can be a1 or b1
#
# 3. **Mutual Inductance on Opposite Sides $ M_{\text{os}} $**:
# - This term captures the interaction between the magnetic fields of wires on opposite sides of the coil. Here, the currents flow in opposite directions, causing the magnetic fields to partially cancel each other out, which reduces the total magnetic field and the self-inductance $ L_{\text{side}} $.
# - For each coil pair choosen opposite side:
# $$
# M_{os} = \sum_{i=0}^{N-1} \sum_{j = 0, j \neq i}^{N-1} M(F1(side length,i,j), d_{ij}) - \sum_{i=0}^{N-1} \sum_{j = 0, j \neq i}^{N-1} M(F2(i,j), d_{ij})
# $$
# where:
# - $F1(side_length,i,j) = side length - (i)*2*d_{xy} + |i-j|*d_{xy}$ -- m + p
# - $F2(i,i') = |i-j|*d_{xy}$ -- p
# - $d_{i+j} = |(i+j)*d_{xy}|$
# - side_length can be a1 or b1
#
#
# 4. **Negligibility of Perpendicular Mutual Inductance**:
# <details> <summary>The mutual inductance between perpendicular sides of the coil is considered negligible, which is why it's not included in the equation.</summary>
# <p>
#
# 1. **Magnetic Field Orientation**:
# - When current flows through a coil, it generates a magnetic field around it. This magnetic field is generally aligned with the axis of the coil.
# - If two coils are perpendicular to each other, the magnetic field generated by one coil will be oriented at a 90-degree angle relative to the other coil.
#
# 2. **Magnetic Flux Linkage**:
# - Mutual inductance depends on the amount of magnetic flux from one coil that links with the other coil.
# - In the case of perpendicular coils, the magnetic field lines from one coil are mostly parallel to the plane of the other coil. Therefore, very few magnetic field lines actually pass through the other coil, leading to minimal magnetic flux linkage.
# - Since mutual inductance is a measure of this flux linkage, it becomes very small or negligible.
#
# 3. **Mathematical Perspective**:
# - Mathematically, mutual inductance $ M $ between two coils is given by $ M = \frac{\Phi_{21}}{I_1} $, where $ \Phi_{21} $ is the magnetic flux through coil 2 due to the current $ I_1 $ in coil 1.
# - When the coils are perpendicular, $ \Phi_{21} $ is almost zero because the magnetic field from coil 1 does not pass through coil 2. Hence, $ M $ is negligible. </p>
# </details>
#
#
# %% [markdown]
# 
# %%
# Self-Inductance of a coil single sided
def L_self_single_sided(side_length, rho, n, r, dxy, N):
'''
L_single_sided calculates the self-inductance of a single sided coil
Inputs:
side_length = length of side
rho = radius of a single strand
n = number of strands
r = radius of the bundle
dxy = distance between the two conductors
N = number of turns
Output:
L = self-inductance of the coil
'''
L = 0.0
for i in range(N):
try:
length = side_length - 2 * dxy * i
if length <= 0:
raise ValueError("Length is zero, which will cause division by zero.")
L += L_litz_coil(length, rho, n, r)
except ZeroDivisionError:
print(f"Error: Division by zero encountered at iteration {i}.")
except ValueError as ve:
print(f"Error: {ve}")
return L
def M_same_side(side_length, dxy, N):
'''
M_same_side calculates the mutual inductance of a coil with the same side
Inputs:
side_length = length of side
rho = radius of a single strand
dxy = distance between the two conductors
N = number of turns
Output:
M = mutual inductance of the coil
'''
M = 0.0
for i in range(N):
for j in range(N):
if i != j:
try:
k = abs(i - j)
length_1 = side_length - 2 * dxy * i
length_2 = side_length - 2 * dxy * j
if length_1 == 0 or length_2 == 0:
raise ValueError("Length is zero, which will cause division by zero.")
M += M_L_unequal2(length_1, length_2, k*dxy)
except ZeroDivisionError:
print(f"Error: Division by zero encountered at iteration i={i}, j={j}.")
except ValueError as ve:
print(f"Error: {ve}")
return M
def M_opposite_side(side_length, opp_side_length,dxy, N):
'''
M_same_side calculates the mutual inductance of a coil with the same side
Inputs:
side_length = length of side
rho = radius of a single strand
dxy = distance between the two conductors
N = number of turns
Output:
M = mutual inductance of the coil
'''
M = 0.0
for i in range(N):
for j in range(N):
length_1 = side_length - 2*dxy*i
length_2 = side_length - 2*dxy*j
k = opp_side_length - (i+j)*dxy
M+= M_L_unequal2(length_1,length_2,k)
return M
# %%
import numpy as np
def L_eff_single_sided(side_length,opp_side_length, rho, n, r, dxy, N):
'''
Calculate the self-inductance of a single side of the rectangular coil.
'''
# Calculate the self-inductance of a single side
Lw = L_self_single_sided(side_length, rho, n, r, dxy, N)
# print(Lw)
# Calculate mutual inductance on the same side
Mss = M_same_side(side_length,dxy,N)
# print(Mss)
# Calculate mutual inductance on the opposite side
Mos = M_opposite_side(side_length,opp_side_length,dxy,N)
# print(Mos)
# Total inductance for one side
Lside = Lw + Mss - Mos
# print(Lside)
return Lside
def calculate_L_coil(a, b, rho, n, r, dxy, N):
'''
Calculate the total self-inductance of the rectangular coil.
'''
if N > min((a-2*r)/(2*dxy),(b-2*r)/(2*dxy))or a < 4*r or b < 4*r:
raise ValueError("The side length of the coil is too small.")
# Calculate the inductance for each side
Lside_a = L_eff_single_sided((a-2*r), (b-2*r), rho, n, r, dxy, N)
Lside_b = L_eff_single_sided((b-2*r),(a-2*r),rho, n, r, dxy, N)
# Total inductance of the coil
Lcoil = 2 * (Lside_a + Lside_b)
return Lcoil
# %%
def Mutual_same_side(side_length, dxy, N, h):
'''
M_same_side calculates the mutual inductance of a coil with the same side
Inputs:
side_length = length of side
rho = radius of a single strand
dxy = distance between the two conductors
N = number of turns
h = air gap between the two coils
Output:
M = mutual inductance of the coil
'''
M = 0.0
for i in range(N):
for j in range(N):
try:
d_eff = np.sqrt(np.square((i - j)*dxy) + np.square(h))
length_1 = side_length - 2 * dxy * i
length_2 = side_length - 2 * dxy * j
if length_1 == 0 or length_2 == 0:
raise ValueError("Length is zero, which will cause division by zero.")
M += M_L_unequal2(length_1, length_2, d_eff)
except ZeroDivisionError:
print(f"Error: Division by zero encountered at iteration i={i}, j={j}.")
except ValueError as ve:
print(f"Error: {ve}")
return M
def Mutual_opposite_side(side_length, opp_side_length,dxy, N,h):
'''
M_Opposite_side calculates the mutual inductance of a coil with the Opposite side
Inputs:
side_length = length of side
rho = radius of a single strand
dxy = distance between the two conductors
N = number of turns
h = air gap between the two coils
Output:
M = mutual inductance of the coil
'''
M = 0.0
for i in range(N):
for j in range(N):
length_1 = side_length - 2*dxy*i
length_2 = side_length - 2*dxy*j
k = opp_side_length - (i+j)*dxy
d_eff = np.sqrt(np.square(k) + np.square(h))
M+= M_L_unequal2(length_1,length_2,d_eff)
return M
def M_eff_single_sided(side_length,opp_side_length,dxy, N,h):
'''
Calculate the self-inductance of a single side of the rectangular coil.
'''
# Calculate mutual inductance on the same side
Mss = Mutual_same_side(side_length,dxy,N,h)
# print(Mss)
# Calculate mutual inductance on the opposite side
Mos = Mutual_opposite_side(side_length,opp_side_length,dxy,N,h)
# print(Mos)
# Total inductance for one side
Lside = Mss - Mos
# print(Lside)
return Lside
def calculate_M_coil(a, b ,r, dxy, N,h):
'''
Calculate the total self-inductance of the rectangular coil.
'''
if N > min(a/(2*dxy),b/(2*dxy))or a < 2*r or b < 2*r:
raise ValueError("The side length of the coil is too small.")
h = h - 4*r
# Calculate the inductance for each side
Lside_a = M_eff_single_sided((a-2*r), (b-2*r), dxy, N,h)
Lside_b = M_eff_single_sided((b-2*r),(a-2*r), dxy, N,h)
# Total inductance of the coil
Lcoil = 2 * (Lside_a + Lside_b)
return Lcoil
# %%
a = 31
b = 24
r = 0.2
dxy = 0.4
N = 10
h = 12.5
X0 = 10
Y0 = 10
calculate_M_coil(a, b ,r, dxy, N,h)
# %%
import pandas as pd
# Geeting I/p O/p dataset
'''
# Input Parameters (I/P): [a, b, rho, n, dxy, N, h]
Range of a: Approximately 10 to 50 (absolute values from a uniform distribution).
Range of b: Approximately 10 to 50 (absolute values from a uniform distribution).
Range of rho: 0.005 to 0.01 (uniform distribution).
Range of r: 0.15 to 0.3 (uniform distribution).
Range of n: Discrete values {100, 200, 300}.
Range of dxy: 0.2 to 0.5 (uniform distribution).
Range of N: 5 to 50 (random integer based on conditions).
Range of h: 5 to 35 (uniform distribution).
Note: The value of N depends on the condition min(a - 2*r, b - 2*r) / (2*dxy) > 5. If the condition is not satisfied, the inputs are regenerated recursively.
'''
data_len = 10000
def generate_inputs():
a = abs(np.random.uniform(10,50))
b =abs(np.random.uniform(10,50))
dxy = np.random.uniform(0.2, 0.5)
r = np.random.uniform(0.15, 0.3)
if int(min(a-2*r,b-2*r)/(2*dxy)) <= 5:
return generate_inputs()
k = min(min((a-2*r)/(2*dxy),(b-2*r)/(2*dxy)) -1, 50)
N = np.random.randint(5, int(k))
h = np.random.uniform(5,35)
rho = np.random.uniform(0.005, 0.01)
n = np.random.choice([100,200,300])
return (a, b, rho, n, r, dxy, N,h)
data = []
for i in range(data_len):
x = generate_inputs()
data.append(x)
# convert the data to dict list by taking first element of the tuple as a and second element as b
data_dict = {'a': [x[0] for x in data], 'b': [x[1] for x in data], 'rho': [x[2] for x in data], 'n': [x[3] for x in data], 'r': [x[4] for x in data], 'dxy': [x[5] for x in data], 'N': [x[6] for x in data],'h': [x[7] for x in data]}
# print(data_dict)
df = pd.DataFrame(data_dict, columns=['a', 'b', 'rho', 'n', 'r','dxy', 'N','h'])
# df.to_csv('data1.csv', index=False)
# %%
M = []
L = []
for i in range(data_len):
rho = df.iloc[i]['rho']
n = df.iloc[i]['n']
r = df.iloc[i]['r']
a = df.iloc[i]['a']
b = df.iloc[i]['b']
N = int(df.iloc[i]['N'])
dxy = df.iloc[i]['dxy']
h = df.iloc[i]['h']
# print(a,b,N,r,dxy,h,int(min(a-2*r,b-2*r)/(2*dxy))-1)
M.append(calculate_M_coil(a, b ,r, dxy, N,h))
L.append(calculate_L_coil(a, b, rho, n, r, dxy, N))
# get 35897 values of df
df_new = df.copy()
df_new['M'] = M
df_new['L'] = L
df_new.to_csv('analytical_data.csv', index=False)
df_new.head()
# %%
# %pip install xgboost lightgbm catboost
# %%
from sklearn.linear_model import Lasso
from sklearn.linear_model import Ridge
from sklearn.linear_model import ElasticNet
from sklearn.neighbors import KNeighborsRegressor
from sklearn.svm import SVR
from xgboost import XGBRegressor
from lightgbm import LGBMRegressor
from catboost import CatBoostRegressor
from sklearn.ensemble import AdaBoostRegressor
from sklearn.ensemble import GradientBoostingRegressor
def run_model(model, X_train, X_test, y_train, y_test):
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
mse = mean_squared_error(y_test, y_pred)
mae = mean_absolute_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred)
return mse, mae, r2
def run_models(models, X_train, X_test, y_train, y_test):
results = {}
for name, model in models.items():
mse, mae, r2 = run_model(model, X_train, X_test, y_train, y_test)
results[name] = {'mse': mse, 'mae': mae, 'r2': r2}
return results
def plot_metrics(results):
plt.figure(figsize=(10, 6))
metrics = ['mse', 'mae', 'r2']
for i, metric in enumerate(metrics):
plt.subplot(1, 3, i+1)
values = [result[metric] for result in results.values()]
plt.bar(results.keys(), values, color=['blue', 'orange', 'green'])
plt.title(metric.upper())
plt.ylabel(metric.upper())
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()
# Models
models = {
'Linear Regression': LinearRegression(),
'Random Forest': RandomForestRegressor(),
'Decision Tree': DecisionTreeRegressor(),
'AdaBoostRegressor': AdaBoostRegressor(),
'GradientBoostingRegressor': GradientBoostingRegressor(),
'Lasso': Lasso(),
'Ridge': Ridge(),
'ElasticNet': ElasticNet(),
'KNeighborsRegressor': KNeighborsRegressor(),
'SVR': SVR(),
'XGBRegressor': XGBRegressor(),
# 'LGBMRegressor': LGBMRegressor(),
# 'CatBoostRegressor': CatBoostRegressor(verbose=0)
}
# %%
# load data
df = pd.read_csv('analytical_data.csv')
df.head()
# %%
# get the features and target
X = df.drop(columns=['M','L'])
y = df['M']
# Split the data
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# %%
metrics = run_models(models, X_train, X_test, y_train, y_test)
metrics
# %%
xgb = XGBRegressor()
xgb.fit(X_train, y_train)
y_pred = xgb.predict(X_test)
mse = mean_squared_error(y_test, y_pred)
mae = mean_absolute_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred)
print(f"XGBRegressor: mse={mse:.4f}, mae={mae:.4f}, r2={r2:.4f}")
# %%
# plot actual vs predicted values in a scatter plot
plt.figure(figsize=(10, 6))
plt.scatter(y_test, y_pred)
plt.xlabel('Actual')
plt.ylabel('Predicted')
plt.title('Actual vs Predicted values')
# %%
# make a parametric study to see the effect of each parameter on the mutual inductance - set the other parameters to their mean values
# h parametric study
h = np.linspace(5, 35, 100)
# other values are first row of the dataframe
a = df.iloc[0]['a']
b = df.iloc[0]['b']
rho = df.iloc[0]['rho']
n = df.iloc[0]['n']
r = df.iloc[0]['r']
dxy = df.iloc[0]['dxy']
N = df.iloc[0]['N']
print(a,b,rho,n,r,dxy,N)
M = []
# analytical calculation
for i in h:
# set N as integer
N = int(N)
M.append(calculate_M_coil(a, b ,r, dxy, N,i))
plt.figure(figsize=(10, 6))
plt.plot(h, M)
plt.xlabel('h')
plt.ylabel('Mutual Inductance')
plt.title('Effect of h on Mutual Inductance')
# fix the grid
plt.grid()
# add the ml plot also in the same plot
M_ml = []
#xgb model predictions parametric study
for i in h:
X = [[a, b, rho, n, r, dxy, N, i]]
y = xgb.predict(X)
M_ml.append(y[0])
# print(f"h={i}, M={y[0]:.4f}")
# single plot
# plt.figure(figsize=(10, 6))
plt.plot(h, M_ml)
plt.xlabel('h')
plt.ylabel('Mutual Inductance')
plt.title('Effect of h on Mutual Inductance')
plt.show()
# %%
# %pip install torch torchvision
# %%
import torch
from torch import nn
from torch.utils.data import DataLoader
from torchvision import datasets
from torchvision.transforms import ToTensor
# %%
# basic model with pytorch
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader, TensorDataset
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score
# Convert data to tensors
X_tensor = torch.tensor(X.values, dtype=torch.float32)
y_tensor = torch.tensor(y.values, dtype=torch.float32)
# Split the data
X_train, X_test, y_train, y_test = train_test_split(X_tensor, y_tensor, test_size=0.2, random_state=42)
# use standard scaler to scale the data before feeding to the model
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
train_data = TensorDataset(torch.tensor(X_train, dtype=torch.float32), torch.tensor(y_train, dtype=torch.float32))
# Create DataLoader
train_loader = DataLoader(train_data, batch_size=32, shuffle=True)
# test data
test_data = TensorDataset(torch.tensor(X_test, dtype=torch.float32), torch.tensor(y_test, dtype=torch.float32))
test_loader = DataLoader(test_data, batch_size=32, shuffle=False)
# %%
# create a simple neural network
class Model(nn.Module):
def __init__(self):
super(Model, self).__init__()
self.fc1 = nn.Linear(8, 64)
self.fc2 = nn.Linear(64, 64)
self.fc3 = nn.Linear(64, 1)
self.relu = nn.ReLU()
def forward(self, x):
x = self.relu(self.fc1(x))
x = self.relu(self.fc2(x))
x = self.fc3(x)
return x
def predict(self, x):
x = self.relu(self.fc1(x))
x = self.relu(self.fc2(x))
x = self.fc3(x)
return x
# %%
# ml models - with comparison
# then select the best model and predict the values
# then compare the results with the analytical results
# then take the FEM data and fine tune the model
# then predict the values for the FEM data and compare the results with the analytical results for the FEM data
# plot the mse for Analytical, FEM, ML, ML - analytical, ML_analytical fine tuned with FEM data
# we got xgboost as the best model
# now we will fine tune the model with the FEM data
# S.No. Litz Wire(h) Litz Wire(h-0.4) Hardware Prototype FEM MODEL Error(%)=[(actual-expected)/expected]*100
# Height(cm) Hardware to Litz wire analysis
# 1 L (\microH) 47.608 49.51 47.713745 4.00
# 2 MI (\microH) 5 19.461 20.842 19.95 18.606359 2.51
# 3 MI (\microH) 7.5 13.699 14.253 13.8376 12.921677 1.01
# 3 MI (\microH) 10 10.021 10.021 9.897 9.366536 1.24
# 4 MI (\microH) 12.5 7.5249 8.2133 7.599 6.964954 0.98
# %%
# grid search of hyperparameters
# neural networks
# %%
#
# %% [markdown]
# # Misalignment Modelling
#
#
# ## Grover Chap -6
# 
#
# 
# 
#
# 
#
# 
# %% [markdown]
# 
# %%
def mod(a):
if a<0:
return -a
else:
return a
def Mutual_Between_Equal_Length(l,d):
l = mod(l)
# print(l)
if l == 0:
return 0
M = 0.002 * l * (np.log(l/d + np.sqrt(1 + np.square(l/d))) + d/l - np.sqrt(1 + np.square(d/l)))
return M
def Mutual_Between_Misaligned(l, m, d, delta):
'''
l = length of the first conductor
m = length of the second conductor
d = distance between the two conductors
delta = misalignment between the two conductors --> this distance is from the end of the first conductor to the start of the second conductor i.e (Xs2 - Xe1) - let's fix the Xs2 as k
refer image above
### Units are in cm ###
'''
# print(f"l = {l}, m = {m}, d = {d}, delta = {delta}")
if delta < 0:
q = -delta - m
p = l + delta
# print("case_2")
M_net = (Mutual_Between_Equal_Length(p + m, d) + Mutual_Between_Equal_Length(m+q, d)- Mutual_Between_Equal_Length(p, d) - Mutual_Between_Equal_Length(q, d))/2
# Laws of Summation - Overlapping Case
else:
M_l_m_delta = Mutual_Between_Equal_Length(l+m + delta, d)
M_delta = Mutual_Between_Equal_Length(delta, d)
M_l_delta = Mutual_Between_Equal_Length(l+delta, d)
M_m_delta = Mutual_Between_Equal_Length(m+delta, d)
M_net = ((M_l_m_delta + M_delta) - (M_l_delta + M_m_delta))/2
return M_net
# %%
def feet_to_meter(feet):
meter = feet * 0.3048
return meter
a = feet_to_meter(10)
b = feet_to_meter(5)
h = feet_to_meter(0.5)
delta = feet_to_meter(-5)
# plot the mutual inductance between two parallel conductors for different values of delta
Mutual_Between_Misaligned(a, b, h, delta)
# %%
import matplotlib.pyplot as plt
# Define the range of delta values
delta_values = np.linspace(-10, 10, 100)
mutual_inductance_values = [Mutual_Between_Misaligned(a, b, h, feet_to_meter(delta)) for delta in delta_values]
plt.plot(delta_values, mutual_inductance_values)
plt.xlabel("Delta (m)")
plt.ylabel("Mutual Inductance (H)")
plt.title("Mutual Inductance vs Delta")
plt.grid(True)
plt.show()
# %%
def Mutual_Between_Misaligned_2(l, m, d, delta):
'''
l = length of the first conductor
m = length of the second conductor
d = distance between the two conductors
delta = misalignment between the two conductors --> this distance is from the end of the first conductor to the start of the second conductor i.e (Xs2 - Xe1) - let's fix the Xs2 as k
refer image above
### Units are in cm ###
'''
delta = mod(delta)
# print(f"l = {l}, m = {m}, d = {d}, delta = {delta}")
# Laws of Summation - Overlapping Case
# M_l_m_delta = Mutual_Between_Equal_Length(l+m + delta, d)
# M_delta = Mutual_Between_Equal_Length(delta, d)
# M_l_delta = Mutual_Between_Equal_Length(l+delta, d)
# M_m_delta = Mutual_Between_Equal_Length(m+delta, d)