-
Notifications
You must be signed in to change notification settings - Fork 1
/
MAG2305.py
1769 lines (1424 loc) · 60.3 KB
/
MAG2305.py
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
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 24 21:38:01 2022
Author: Li, Jiangnan
Kunming University of Science and Technology (KUST)
Email : [email protected]
-------------------
MAG2305 : An FDM-FFT micromagnetic simulator
Originated from MAG Group led by
Prof. Dan Wei in Tsinghua University
Library version : numpy 1.25.0
pytorch 2.0.1
-------------------
"""
__version__ = 'UnetHd_Public_2024.10.17'
print('MAG2305 version: {:s}\n'.format(__version__))
import torch
import numpy as np
import sys
# =============================================================================
# Load Unet model
# =============================================================================
def load_model(m):
global _ckpt_model
_ckpt_model = m
def MFNN(spin):
_ckpt_model.eval()
with torch.no_grad():
spin = spin.permute(2,3,0,1)
spin = spin.view(1, -1, spin.size(2), spin.size(3))
return _ckpt_model(spin).permute(2,3,0,1).view(spin.size(2), spin.size(3), -1, 3)
# =============================================================================
# Define constants here
# =============================================================================
class Const():
" Define constants in this class "
def __init__(self, value, unit):
self.__value = value
self.__unit = unit
@property
def value(self):
return self.__value
@property
def unit(self):
return self.__unit
"""
gamma0: Gyromagnetic ratio of spin
[Lande g factor] * [electron charge] / [electron mass] / [light speed]
"""
gamma0 = Const(1.75882e7, '[Oe s]^-1')
# =============================================================================
# Define general functions here
# =============================================================================
def get_randspin_2D(size=(1,1,1), split=1, rand_seed=0):
"""
To get a random spin distribution in 2D view
"""
size = tuple(size)
split = int(split)
np.random.seed(rand_seed) # initialize random seed
spin_cases = []
spin_cases.append([ 1.0, 0.0, 0.0]) # +x
spin_cases.append([ -1.0, 0.0, 0.0]) # -x
spin_cases.append([ 0.0, 1.0, 0.0]) # +y
spin_cases.append([ 0.0, -1.0, 0.0]) # -y
spin_cases.append([ 0.7071, 0.7071, 0.0]) # +x+y
spin_cases.append([ 0.7071,-0.7071, 0.0]) # +x-y
spin_cases.append([-0.7071, 0.7071, 0.0]) # -x+y
spin_cases.append([-0.7071,-0.7071, 0.0]) # -x-y
xsplit = size[0] / split # x length of each split area
ysplit = size[1] / split # y length of each split area
spin = np.empty( size + (3,) )
for nx in range(split):
for ny in range(split):
xlow_bound = int(nx * xsplit)
xhigh_bound = int((nx+1) * xsplit) if nx + 1 < split \
else size[0]
ylow_bound = int(ny * ysplit)
yhigh_bound = int((ny+1) * ysplit) if ny + 1 < split \
else size[1]
spin[xlow_bound:xhigh_bound, ylow_bound:yhigh_bound, :] \
= spin_cases[np.random.randint(len(spin_cases))]
return spin
def DemagCell(D, rv):
"""
To get the demag matrix of a cell at a certain distance
Arguments
---------
D : Float(3)
Cell size : DX,DY,DZ
rv : Float(3)
Distance vector from cell center : RX,RY,RZ
Returns
-------
DM : Float(3,3)
Demag Matrix
"""
D = np.array(D)
rv = np.array(rv)
DM = np.zeros((3,3))
pqw_range = [ [i,j,k] for i in [-1,1] for j in [-1,1] for k in [-1,1] ]
for pqw in pqw_range:
pqw = np.array(pqw)
R = 0.5*D + pqw*rv
RR = np.linalg.norm(R)
for i in range(3):
j = (i+1)%3
k = (i+2)%3
DM[i,i] += np.arctan(R[j]*R[k]/R[i]/RR)
DM[i,j] += 0.5*pqw[i]*pqw[j]*np.log((RR-R[k])/(RR+R[k]))
DM[j,i] = DM[i,j]
return DM/np.pi/4.
def numpy_roll(arr, shift, axis, pbc):
"""
Re-defined numpy.roll(), including pbc judgement
Arguments
---------
arr : Numpy Float(...)
Array to be rolled
shift : Int
Roll with how many steps
axis : Int
Roll along which axis
pbc : Int or Bool
Periodic condition for rolling; 1: pbc, 0: non-pbc
Returns
-------
arr_roll : Numpy Float(...)
arr after rolling
"""
arr_roll = np.roll(arr, shift=shift, axis=axis)
if not pbc:
if axis == 0:
if shift == 1:
arr_roll[ 0,...] = arr[ 0,...]
elif shift == -1:
arr_roll[-1,...] = arr[-1,...]
elif axis == 1:
if shift == 1:
arr_roll[:, 0,...] = arr[:, 0,...]
elif shift == -1:
arr_roll[:,-1,...] = arr[:,-1,...]
elif axis == 2:
if shift == 1:
arr_roll[:,:, 0,...] = arr[:,:, 0,...]
elif shift == -1:
arr_roll[:,:,-1,...] = arr[:,:,-1,...]
return arr_roll
def torch_roll(arr, shift, axis, pbc):
"""
Re-defined torch.roll(), including pbc judgement
Arguments
---------
arr : Torch Float(...)
Array to be rolled
shift : Int
Roll with how many steps
axis : Int
Roll along which axis
pbc : Int
Periodic condition for rolling; 1: pbc, 0: non-pbc
Returns
-------
arr_roll : Torch Float(...)
arr after rolling
"""
arr_roll = torch.roll(arr, shifts=shift, dims=axis)
if not pbc:
if axis == 0:
if shift == 1:
arr_roll[ 0,...] = arr[ 0,...]
elif shift == -1:
arr_roll[-1,...] = arr[-1,...]
elif axis == 1:
if shift == 1:
arr_roll[:, 0,...] = arr[:, 0,...]
elif shift == -1:
arr_roll[:,-1,...] = arr[:,-1,...]
elif axis == 2:
if shift == 1:
arr_roll[:,:, 0,...] = arr[:,:, 0,...]
elif shift == -1:
arr_roll[:,:,-1,...] = arr[:,:,-1,...]
return arr_roll
# =============================================================================
# Define mmModel here
# =============================================================================
class mmModel():
" Define a micromagnetic model "
# =============================================================================
# PART I - Initialize mmModel
# =============================================================================
def __init__(self, types="3DPBC", cell=(1,1,1),
size=(1,1,1), model=None,
Ms=(1,), Ax=(1.0e-6,),
Ku=(0.0e0,), Kvec=((0,0,1),),
matters=None, device='cuda' ):
"""
Arguments
---------
types : String
"3DPBC" : Periodic along all X,Y,Z directions
"film" : Periodic along X,Y directions, Z in-plane
"track" : Periodic along X direction, Y,Z finite, Z in-plane
"bulk" : Finite along all X,Y,Z directions
# Default = "3DPBC"
cell : Float(3)
Cell size: DX,DY,DZ [unit nm]
# Default = (1,1,1)
# Recorded as self.cell
size : Int(3)
Model cell count along each direction: RNX,RNY,RNZ
# Default = (1,1,1)
# Recorded as self.size
model : Int(size)
Input data of model, defining matter id for each cell
# Default = None
# If [model] not None, input [size] will be ignored
# Recorded as self.model
Ms : Float(Nmats)
Saturation magnetization [unit emu/cc] for each matter
# Default = 1
# Recorded as self.Ms
Ax : Float(Nmats)
Heisenberg exchange stiffness constant [unit erg/cm] for each matter
# Default = 1.0e-6
# Recorded as self.Ax
Ku : Float(Nmats)
1st order uniaxial anisotropy energy density [unit erg/cc] for each matter
# Default = 1
# Recorded as self.Ku
Kvec : Float(Nmats,3)
Easy axis for each matter
# Default = (0,0,1)
# Normalization will be performed on the input vectors
# Recorded as self.Kvec
matters : Float(Nmats,6)
Magnetic properties of matters
# Format : Ms[1], Ax[1], Ku[1], kx[1], ky[1], kz[1]
Ms[2], Ax[2], Ku[2], kx[2], ky[2], kz[2]
Ms[3], Ax[3], Ku[3], kx[3], ky[3], kz[3]
...
[Units] : emu/cc, erg/cm, erg/cc, 1 , 1 , 1
# Default = None
# If [matters] not None, inputs [Ms], [Ax], [Ku] and [Kvec] will be ignored
device : "cuda" or "cuda:x" or "cpu"
Calculation device for updating spin state (when using torch)
# Recorded as self.device
Parameters
----------
self.Nmats: Int
Number of matters
self.fftsize : Int(3)
fft model size FNX,FNY,FNZ
self.Spin : Torch Float(size,3)
Spin direction of each cell
self.He : Torch Float(size,3)
Exchange field distribution
self.Ha : Torch Float(size,3)
Anisotropy field distribution
self.Hd : Torch Float(size,3)
Demag field distribution
self.Heff : Torch Float(size,3)
Effective field distribution
self.FDMW : Torch Complex(3,3,FNX,FNY,FNZ//2+1)
DFT of the demagnetization matrix of the whole model
"""
print("\nInitialize an mmModel:\n")
# Basic inputs
self.types = types
self.cell = np.array(cell, dtype=float)
if "cuda" in device:
if torch.cuda.is_available():
if device == "cuda":
print(" Cuda device available. Spin evolution using cuda.\n")
device = "cuda"
else:
_, dev_index = device.split(":")
if dev_index == "":
print(" Cuda device available. Spin evolution using cuda.\n")
device = "cuda"
elif -1 < int(dev_index) < torch.cuda.device_count():
print(" Cuda:{0} available. Spin evolution using cuda:{0}.\n"
.format(int(dev_index)))
device = "cuda:" + dev_index
else:
print(" Cuda:{0} unavailable. Spin evolution using cpu instead.\n"
.format(int(dev_index)))
device = "cpu"
else:
print(" Cuda device unavailable. Spin evolution using cpu instead.\n")
device = "cpu"
else:
print(" Spin evolution using cpu.\n")
device = "cpu"
self.device = torch.device(device)
# model
if model is None:
self.size = np.array(size, dtype=int)
self.model = np.ones(tuple(self.size), dtype=int)
self.Nmats = 1
else:
self.model = np.array(model, dtype=int)
self.size = np.array(model.shape)
self.Nmats = self.model.max()
self.Ncells = np.prod(self.model.shape)
print(" # Cells : {:d}".format(self.Ncells))
print(" # Matters: {:d}".format(self.Nmats))
# model size && fft size
self.fftsize = np.array(self.size, dtype=int)
if self.types == 'film':
self.fftsize[-1] = 2*self.fftsize[-1]
if self.types == 'track':
self.fftsize[1] = 2*self.fftsize[1]
self.fftsize[-1] = 2*self.fftsize[-1]
if self.types == 'bulk':
self.fftsize = 2*self.fftsize
self.pbc = (self.size==self.fftsize)
# matters
if matters is None:
if type(Ms) == int or type(Ms) == float:
self.Ms = np.full(self.Nmats, Ms, dtype=float)
elif len(Ms) == self.Nmats:
self.Ms = np.array(Ms, dtype=float)
else:
print(" [Input Error] Length of Ms does not match with Matters Number !")
sys.exit(0)
if type(Ax) == int or type(Ax) == float:
self.Ax = np.full(self.Nmats, Ax, dtype=float)
elif len(Ax) == self.Nmats:
self.Ax = np.array(Ax, dtype=float)
else:
print(" [Input Error] Length of Ax does not match with Matters Number !")
sys.exit(0)
if type(Ku) == int or type(Ku) == float:
self.Ku = np.full(self.Nmats, Ku, dtype=float)
elif len(Ku) == self.Nmats:
self.Ku = np.array(Ku, dtype=float)
else:
print(" [Input Error] Length of Ku does not match with Matters Number !")
sys.exit(0)
if len(Kvec) == 3 and (type(Kvec[0]) == int or type(Kvec[0]) == float):
self.Kvec = np.full((self.Nmats,3), Kvec, dtype=float)
elif len(Kvec) == self.Nmats and len(Kvec[0]) == 3:
self.Kvec = np.array(Kvec, dtype=float)
else:
print(" [Input Error] Length of Kvec does not match with Matters Number !")
sys.exit(0)
else:
if len(matters) >= self.Nmats:
self.Ms = np.zeros(self.Nmats)
self.Ax = np.zeros(self.Nmats)
self.Ku = np.zeros(self.Nmats)
self.Kvec = np.zeros((self.Nmats,3))
matters = np.array(matters, dtype=float)
for i in range(self.Nmats):
self.Ms[i], self.Ax[i], self.Ku[i], \
self.Kvec[i,0], self.Kvec[i,1], self.Kvec[i,2] = matters[i]
else:
print(" [Input Error] Lines of matters less than model matters !")
sys.exit(0)
for i in range(self.Nmats):
Knorm = np.linalg.norm(self.Kvec[i])
if Knorm == 0 and self.Ku[i] != 0:
print(" [Input Error] Easy axis direction not assigned ! Matter {:d}".format(i+1))
sys.exit(0)
elif Knorm == 0 and self.Ku[i] == 0:
pass
else:
self.Kvec[i] /= Knorm
print(" Ms check : 1st {:8.3f}, last {:8.3f} [emu/cc]"
.format(self.Ms[0], self.Ms[-1]))
print(" Ax check : 1st {:.2e}, last {:.2e} [erg/cm]"
.format(self.Ax[0], self.Ax[-1]))
print(" Ku check : 1st {:.2e}, last {:.2e} [erg/cc]\n"
.format(self.Ku[0], self.Ku[-1]))
# Magnetization, anisotropy, and exchange matrix
self.MakeConstantMatrix()
# Torch tensors; spin, fields, and demag matrix
self.Spin = torch.zeros( tuple(self.size) + (3,), device=self.device)
self.He = torch.zeros( tuple(self.size) + (3,), device=self.device)
self.Ha = torch.zeros( tuple(self.size) + (3,), device=self.device)
self.Hd = torch.zeros( tuple(self.size) + (3,), device=self.device)
self.Heff = torch.zeros( tuple(self.size) + (3,), device=self.device)
self.FDMW = torch.zeros( (3,3) + ( self.fftsize[0], self.fftsize[1],
self.fftsize[2]//2+1 ),
dtype=torch.complex64, device=self.device)
# Field functions
self.Demag = self.DemagField_FFT
self.Anisotropy = self.AnisotropyField_uniaxial
self.Exchange = self.ExchangeField_Heisenberg
return None
def MakeConstantMatrix(self):
"""
To create constant matrix for further calculations
{ Called in self.__init__() }
Parameters
----------
self.Hk0 : Torch Float(self.size,3)
1st order uniaxial anisotropy field constant [unit Oe^1/2]
self.Hx0 : Torch Float(6,self.size,3)
Heisenberg exchange field constant [unit Oe]
self.Msmx : Torch Float(self.size)
Ms for each cell [unit emu/cc]
"""
# Magnetization, anisotropy, and exchange matrix
Msmx = np.zeros(tuple(self.size))
Hk0 = np.zeros( tuple(self.size) + (3,) )
for i in range(self.Nmats):
Msmx[ self.model == i+1 ] = self.Ms[i]
self.Energy_base = (self.model==i+1).sum() * self.Ku[i]
Hk0[ self.model == i+1 ] = np.sqrt(2.0 * self.Ku[i] / self.Ms[i]) * self.Kvec[i] \
if self.Ms[i] != 0.0 else 0.0
Hx0 = np.zeros( (6,3) + tuple(self.size) )
Ax = np.zeros_like(Msmx)
for i in range(self.Nmats):
Ax[ self.model == i+1 ] = self.Ax[i] if self.Ms[i] !=0.0 else 0.0
Ax_nb = numpy_roll(Ax, shift= 1, axis=0, pbc=self.pbc[0])
for l in range(3):
np.divide( 4.0 * 1.0e14 * Ax * Ax_nb,
Msmx * (Ax + Ax_nb) * self.cell[0]**2,
where= (Msmx!=0), out=Hx0[0,l] )
Ax_nb = numpy_roll(Ax, shift=-1, axis=0, pbc=self.pbc[0])
for l in range(3):
np.divide( 4.0 * 1.0e14 * Ax * Ax_nb,
Msmx * (Ax + Ax_nb) * self.cell[0]**2,
where= (Msmx!=0), out=Hx0[1,l] )
Ax_nb = numpy_roll(Ax, shift= 1, axis=1, pbc=self.pbc[1])
for l in range(3):
np.divide( 4.0 * 1.0e14 * Ax * Ax_nb,
Msmx * (Ax + Ax_nb) * self.cell[1]**2,
where= (Msmx!=0), out=Hx0[2,l] )
Ax_nb = numpy_roll(Ax, shift=-1, axis=1, pbc=self.pbc[1])
for l in range(3):
np.divide( 4.0 * 1.0e14 * Ax * Ax_nb,
Msmx * (Ax + Ax_nb) * self.cell[1]**2,
where= (Msmx!=0), out=Hx0[3,l] )
Ax_nb = numpy_roll(Ax, shift= 1, axis=2, pbc=self.pbc[2])
for l in range(3):
np.divide( 4.0 * 1.0e14 * Ax * Ax_nb,
Msmx * (Ax + Ax_nb) * self.cell[2]**2,
where= (Msmx!=0), out=Hx0[4,l] )
Ax_nb = numpy_roll(Ax, shift=-1, axis=2, pbc=self.pbc[2])
for l in range(3):
np.divide( 4.0 * 1.0e14 * Ax * Ax_nb,
Msmx * (Ax + Ax_nb) * self.cell[2]**2,
where= (Msmx!=0), out=Hx0[5,l] )
# Simple statistic
self.Msavg = Msmx.sum() / self.Ncells
self.Hmax = 2.0 * np.divide(self.Ku, self.Ms, where= self.Ms!=0 ).max() \
+ 6.0 * Hx0.max() + 4*np.pi* self.Ms.max()
np_warning = np.seterr()
np.seterr(divide='ignore', invalid='ignore') # Ignore divided by 0
np.seterr(**np_warning) # Reset to default
print(" Average magnetization : {:9.2f} [emu/cc]".format(self.Msavg))
print(" Maximal anisotropy Hk : {:9.3e} [Oe] ".format(Hk0.max()**2))
print(" Maximal Heisenberg Hx : {:9.3e} [Oe] ".format(Hx0.max()))
print(" Maximal effective Heff : {:9.3e} [Oe]\n ".format(self.Hmax))
# Torch tensors
self.Msmx = torch.Tensor(Msmx).to(self.device)
self.Hk0 = torch.Tensor(Hk0).to(self.device)
self.Hx0 = torch.Tensor(Hx0.transpose(0,2,3,4,1)).to(self.device)
return None
def NormSpin(self):
"""
Normalize self.Spin
Parameters
----------
self.Spin : Torch Float(self.size,3)
Spin direction of each cell
"""
norm = torch.sqrt( torch.einsum( 'ijkl,ijkl -> ijk',
self.Spin, self.Spin ) )
for l in range(3):
self.Spin[...,l] /= norm
self.Spin[~self.Spin.isfinite()] = 0.0
return None
def SpinInit(self, Spin_in):
"""
Initialize Spin state from input
Arguments
---------
Spin_in : Float(self.size,3)
Input Spin state
Returns
-------
self.Spin.clone.cpu
Parameters
----------
self.Spin : Torch Float(self.size,3)
Spin direction of each cell
"""
Spin_in = np.array(Spin_in, dtype=float)
if Spin_in.shape != tuple(self.size) + (3,):
print('[Input error] Spin size mismatched! Should be {}\n'
.format( tuple(self.size) + (3,) ) )
sys.exit(0)
else:
self.Spin = torch.Tensor(Spin_in).to(self.device)
print('Spin state initialized according to input.\n')
if (self.model <= 0).sum() > 0:
self.Spin[self.model<=0] = torch.zeros(size=(3,),
device=self.device)
self.NormSpin()
return self.Spin.clone().cpu()
def DemagInit(self):
"""
To get the demag matrix of the whole model
Periodic boundary conditions applied !
Parameters
----------
FN : Int(3)
FN = self.fftsize, model fft size FNX,FNY,FNZ
RN : Int(3)
RN = self.size, model size RNX,RNY,RNZ
D : Float(3)
D = self.cell, cell size DX,DY,DZ
DMW : Float(fftsize,3,3)
Demag matrix of the whole model
# DMW(0,0,0) , self-demag matrix
self.FDMW : Torch Complex(3,3,FNX,FNY,FNZ//2+1)
DFT of DMW
"""
FN = self.fftsize
RN = self.size
D = self.cell
DFN = D*FN
DMW = np.zeros( tuple(FN) + (3,3) )
# General demagmatrix for each cell
rvm = np.empty(tuple(FN) + (3,))
for ijk in np.ndindex(tuple(FN)):
for l in range(3):
rvm[ijk][l] = -1.*ijk[l]*D[l]
rvm[ijk][l] += DFN[l] if ijk[l] > FN[l]//2 else 0.0
pqw_range = [ [i,j,k] for i in [-1,1] for j in [-1,1] for k in [-1,1] ]
for pqw in pqw_range:
pqw = np.array(pqw)
R = 0.5*D + pqw*rvm
RR = np.sqrt( np.einsum( 'ijkl,ijkl -> ijk', R, R ) )
for i in range(3):
j = (i+1)%3
k = (i+2)%3
DMW[...,i,i] += np.arctan(R[...,j]*R[...,k]/R[...,i]/RR)
DMW[...,i,j] += 0.5*pqw[i]*pqw[j]*np.log((RR-R[...,k])/(RR+R[...,k]))
DMW[...,j,i] = DMW[...,i,j]
# Demagmatrix for cells on the facets
# surfaces x
D1 = 1.0*D
D1[0] = 0.5*D[0]
pqw_bd = np.zeros(tuple(FN))
for ijk in np.ndindex(tuple(FN)):
pqw_bd[ijk] = 0
if ijk[0] == FN[0]//2 and ijk[1] != FN[1]//2 and ijk[2] != FN[2]//2:
pqw_bd[ijk] = 1
for p in [+1, -1]:
if p > 0:
rvm1 = 1.0 * rvm
rvm1[...,0] -= 0.5 * pqw_bd * D1[0]
if p < 0:
rvm1[...,0] += pqw_bd * DFN[0]
for pqw in pqw_range:
pqw = np.array(pqw)
R = 0.5*D1 + pqw*rvm1
RR = np.sqrt( np.einsum( 'ijkl,ijkl -> ijk', R, R ) )
for i in range(3):
j = (i+1)%3
k = (i+2)%3
DMW[...,i,i] -= p * np.arctan(R[...,j]*R[...,k]/R[...,i]/RR)
DMW[...,i,j] -= p * 0.5*pqw[i]*pqw[j]*np.log((RR-R[...,k])/(RR+R[...,k]))
DMW[...,j,i] -= p * 0.5*pqw[j]*pqw[i]*np.log((RR-R[...,k])/(RR+R[...,k]))
for q,w in [ [1,1], [1,-1], [-1,1], [-1,-1] ]:
pqw = np.array([abs(p),q,w])
R = 0.5*D1 + pqw*rvm1
RR = np.sqrt( np.einsum( 'ijkl,ijkl -> ijk', R, R ) )
DMW[...,0,0] += p * np.arctan(R[...,1]*R[...,2]/R[...,0]/RR)
DMW[...,1,0] += p * 0.5*q*np.log((RR-R[...,2])/(RR+R[...,2]))
DMW[...,2,0] += p * 0.5*w*np.log((RR-R[...,1])/(RR+R[...,1]))
# surfaces y
D1 = 1.0*D
D1[1] = 0.5*D[1]
pqw_bd = np.zeros(tuple(FN))
for ijk in np.ndindex(tuple(FN)):
pqw_bd[ijk] = 0
if ijk[0] != FN[0]//2 and ijk[1] == FN[1]//2 and ijk[2] != FN[2]//2:
pqw_bd[ijk] = 1
for q in [+1, -1]:
if q > 0:
rvm1 = 1.0 * rvm
rvm1[...,1] -= 0.5 * pqw_bd * D1[1]
if q < 0:
rvm1[...,1] += pqw_bd * DFN[1]
for pqw in pqw_range:
pqw = np.array(pqw)
R = 0.5*D1 + pqw*rvm1
RR = np.sqrt( np.einsum( 'ijkl,ijkl -> ijk', R, R ) )
for i in range(3):
j = (i+1)%3
k = (i+2)%3
DMW[...,i,i] -= q * np.arctan(R[...,j]*R[...,k]/R[...,i]/RR)
DMW[...,i,j] -= q * 0.5*pqw[i]*pqw[j]*np.log((RR-R[...,k])/(RR+R[...,k]))
DMW[...,j,i] -= q * 0.5*pqw[j]*pqw[i]*np.log((RR-R[...,k])/(RR+R[...,k]))
for p,w in [ [1,1], [1,-1], [-1,1], [-1,-1] ]:
pqw = np.array([p,abs(q),w])
R = 0.5*D1 + pqw*rvm1
RR = np.sqrt( np.einsum( 'ijkl,ijkl -> ijk', R, R ) )
DMW[...,1,1] += q * np.arctan(R[...,2]*R[...,0]/R[...,1]/RR)
DMW[...,2,1] += q * 0.5*w*np.log((RR-R[...,0])/(RR+R[...,0]))
DMW[...,0,1] += q * 0.5*p*np.log((RR-R[...,2])/(RR+R[...,2]))
# surfaces z
D1 = 1.0*D
D1[2] = 0.5*D[2]
pqw_bd = np.zeros(tuple(FN))
for ijk in np.ndindex(tuple(FN)):
pqw_bd[ijk] = 0
if ijk[0] != FN[0]//2 and ijk[1] != FN[1]//2 and ijk[2] == FN[2]//2:
pqw_bd[ijk] = 1
for w in [+1, -1]:
if w > 0:
rvm1 = 1.0 * rvm
rvm1[...,2] -= 0.5 * pqw_bd * D1[2]
if w < 0:
rvm1[...,2] += pqw_bd * DFN[2]
for pqw in pqw_range:
pqw = np.array(pqw)
R = 0.5*D1 + pqw*rvm1
RR = np.sqrt( np.einsum( 'ijkl,ijkl -> ijk', R, R ) )
for i in range(3):
j = (i+1)%3
k = (i+2)%3
DMW[...,i,i] -= w * np.arctan(R[...,j]*R[...,k]/R[...,i]/RR)
DMW[...,i,j] -= w * 0.5*pqw[i]*pqw[j]*np.log((RR-R[...,k])/(RR+R[...,k]))
DMW[...,j,i] -= w * 0.5*pqw[j]*pqw[i]*np.log((RR-R[...,k])/(RR+R[...,k]))
for p,q in [ [1,1], [1,-1], [-1,1], [-1,-1] ]:
pqw = np.array([p,q,abs(w)])
R = 0.5*D1 + pqw*rvm1
RR = np.sqrt( np.einsum( 'ijkl,ijkl -> ijk', R, R ) )
DMW[...,2,2] += w * np.arctan(R[...,0]*R[...,1]/R[...,2]/RR)
DMW[...,0,2] += w * 0.5*p*np.log((RR-R[...,1])/(RR+R[...,1]))
DMW[...,1,2] += w * 0.5*q*np.log((RR-R[...,0])/(RR+R[...,0]))
DMW /= 4*np.pi
# Demag Matrix SumTest
sum = np.zeros((3,3))
for ijk in np.ndindex(tuple(RN)):
sum += DMW[ijk]
print("Demag Matrix SumTest:")
for i in range(3):
print(" [{:12.5e} {:12.5e} {:12.5e}]"
.format(sum[i,0], sum[i,1], sum[i,2]))
print(" trace = {:.5f}".format(sum[0,0]+sum[1,1]+sum[2,2]))
print("")
# FFT of Demag Matrix
for m in range(3):
for n in range(3):
self.FDMW[m,n] = torch.fft.rfftn( torch.Tensor(DMW[...,m,n]).
to(self.device) )
return None
# =============================================================================
# PART II - Calculate effective fields
# =============================================================================
def DemagField_FFT(self):
"""
To get demagfield distribution of the whole model
Returns
-------
None
Parameters
----------
FN : Int(3)
FN = self.fftsize, model fft size FNX,FNY,FNZ
RN : Int(3)
RN = self.size, model size RNX,RNY,RNZ
H : Torch Float(3,FN)
Demag field for whole fft model
FH : Torch Complex(3,FNX,FNY,FNZ//2+1)
DFT of H
FM : Torch Complex(3,FNX,FNY,FNZ//2+1)
DFT of spin for whole fft model
self.Msmx : Torch Float(RN)
Ms for each cell [unit emu/cc]
self.FDMW : Torch Complex(3,3,FNX,FNY,FNZ//2+1)
DFT of DMW
self.Hd : Torch Float(RN,3)
Demag field distribution
"""
FN = self.fftsize
RN = self.size
shape_out = (FN[0], FN[1], FN[2]//2+1)
M_tmp = torch.zeros( size= (3,) + tuple(FN),
dtype=torch.float32, device=self.device )
M_tmp[:, :RN[0], :RN[1], :RN[2]] = self.Spin.permute(3,0,1,2) * self.Msmx
FM = torch.fft.rfftn( M_tmp, dim=(1,2,3) )
FH = torch.zeros( size= (3,) + shape_out,
dtype=torch.complex64, device=self.device )
for m in range(3):
for n in range(3):
FH[m] -= self.FDMW[m,n] * FM[n]
H = torch.fft.irfftn( FH, dim=(1,2,3) )
self.Hd = H[:, :RN[0], :RN[1], :RN[2]].permute(1,2,3,0) * torch.pi*4.0
return None
def ExchangeField_Heisenberg(self):
"""
To get Heisenberg exchange field distribution of the whole model
Returns
-------
None
Parameters
----------
self.Hx0 : Torch Float(6,self.size,3)
Heisenberg exchange field constant [unit Oe]
self.He : Torch Float(self.size,3)
Exchange field distribution
"""
self.He = self.Hx0[0] * ( torch_roll( self.Spin, shift= 1,
axis=0, pbc=self.pbc[0] )
- self.Spin )
self.He += self.Hx0[1] * ( torch_roll( self.Spin, shift=-1,
axis=0, pbc=self.pbc[0] )
- self.Spin )
self.He += self.Hx0[2] * ( torch_roll( self.Spin, shift= 1,
axis=1, pbc=self.pbc[1] )
- self.Spin )
self.He += self.Hx0[3] * ( torch_roll( self.Spin, shift=-1,
axis=1, pbc=self.pbc[1] )
- self.Spin )
self.He += self.Hx0[4] * ( torch_roll( self.Spin, shift= 1,
axis=2, pbc=self.pbc[2] )
- self.Spin )
self.He += self.Hx0[5] * ( torch_roll( self.Spin, shift=-1,
axis=2, pbc=self.pbc[2] )
- self.Spin )
return None
def AnisotropyField_uniaxial(self):
"""
To get uniaxial anisotropy field distribution of the whole model
Returns
-------
None
Parameters
----------
self.Hk0 : Torch Float(self.size,3)
1st order uniaxial anisotropy field constant [unit Oe^1/2]
self.Ha : Torch Float(self.size,3)
Anisotropy field distribution
"""
SKdot = torch.einsum('ijkl,ijkl -> ijk', self.Spin, self.Hk0)
for l in range(3):
self.Ha[...,l] = self.Hk0[...,l] * SKdot
return None
def GetHeff_intrinsic(self):
"""
To get effective field distribution of the whole model
{ Without external field, Hext }
Returns
-------
None
Parameters
----------
self.Hd : Torch Float(self.size,3)
Demag field distribution
self.He : Torch Float(self.size,3)
Exchange field distribution
self.Ha : Torch Float(self.size,3)
Anisotropy field distribution
self.Heff : Torch Float(self.size,3)
Effective field distribution
"""
self.Demag()
self.Exchange()
self.Anisotropy()
self.Heff = self.Hd + self.He + self.Ha
return None
def GetHeff_woHd(self):
"""
To get effective field distribution of the whole model
{ Without external field, Hext && demag field, Hd }
Returns
-------
None
Parameters
----------
self.He : Torch Float(self.size,3)
Exchange field distribution
self.Ha : Torch Float(self.size,3)
Anisotropy field distribution
self.Heff : Torch Float(self.size,3)
Effective field distribution
"""
self.Exchange()
self.Anisotropy()
self.Heff = self.He + self.Ha
return None
def GetHeff_unetHd(self):
"""
To get effective field distribution; Hd from unet model
Returns
-------
None
Parameters
----------
self.Heff : Torch Float(self.size,3)
Effective field distribution
"""
self.Hd = MFNN( self.Spin ) * self.Ms[0] / 1000
self.Exchange()
self.Anisotropy()
self.Heff = self.Hd + self.He + self.Ha
return None