-
Notifications
You must be signed in to change notification settings - Fork 1
/
solver.py
1776 lines (1382 loc) · 68.8 KB
/
solver.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
import ctypes as _c
import numpy as _n
import os as _os
import spinmob as _s
import spinmob.egg as _egg; _g = _egg.gui
import pyqtgraph.opengl as _gl
import pyqtgraph as _pg
from sys import platform as _platform
import traceback as _t
import time as _time
_p = _t.print_last
# Find the path to the compiled c-code (only Windows and Linux supported so far.)
if _platform in ['win32']: _path_dll = _os.path.join(_os.path.split(__file__)[0],'engine-windows.dll')
elif _platform in ['darwin']: _path_dll = _os.path.join(_os.path.split(__file__)[0],'engine-osx.so')
else: _path_dll = _os.path.join(_os.path.split(__file__)[0],'engine-linux.so')
# Used to get the path to included scripts
import macrospinmob as _ms
# Get the engine.
_engine = _c.cdll.LoadLibrary(_path_dll)
# Constants
pi = _n.pi
u0 = 1.25663706212e-6 # Vacuum permeability [H/m | N/A^2]
ec = 1.60217662e-19 # Elementary charge [Coulomb]
me = 9.1093837015e-31 # Electron mass [kg]
hbar = 1.0545718e-34 # [m^2 kg/s | J s]
uB = 9.274009994e-24 # Bohr magneton [J/T]
c = 299792458.0 # Speed of light [m/s]
kB = 1.380649e-23 # Boltzmann constant [J/K]
# Debug
debug_enabled = False
def debug(*a):
if debug_enabled: print('DEBUG:', *a)
def _to_pointer(numpy_array):
"""
Converts the supplied numpy_array (assumed to be the usual 64-bit float)
to a pointer, allowing it ot be "connected" to the C-code engine. If None
is supplied, this returns None.
SUPER IMPORTANT
---------------
Make sure you assign your array to a variable name prior to calling this.
If you do not keep a handle on the numpy array, garbage collection can
delete it while the simulation is running!
Parameters
----------
numpy_array
1D ndarray of 64-bit floats.
Returns
-------
C-pointer to the first element, or None if numpy_array=None
Examples
--------
my_solver.Bxs = _to_pointer(my_Bxs).
"""
if numpy_array is None: return None
return numpy_array.ctypes.data_as(_c.POINTER(_c.c_double))
def set_log_level(self, level=0):
"""
Sets the log level for the engine.
"""
_c.c_int.in_dll(_engine, 'log_level').value = level
class _domain(_c.Structure):
"""
Structure for sending all the simulation parameters to the c library.
The user should not interact with this for the most part.
"""
# NOTE: The order here and structure here REALLY has to match the struct
# in the C-code! This class will be sent by reference, and the c-code
# will expect everything to be in its place.
# We use underscores on the array pointers, so that the solver_api can
# store the numpy arrays without them for easy user interfacing.
_fields_ = [
# Whether to let it evolve
('enable', _c.c_bool),
# Index of valid Langevin field
('n_langevin_valid', _c.c_long),
# Temperature [K]
('enable_T', _c.c_bool),
('T', _c.c_double), ("_Ts", _c.POINTER(_c.c_double)),
# Volume of domain [m^3]
('V', _c.c_double), ("_Vs", _c.POINTER(_c.c_double)),
# Magnitude of the gyromagnetic ratio [radians / (sec T)]
('gyro', _c.c_double), ("_gyros", _c.POINTER(_c.c_double)),
# Magnetization [T]
('M', _c.c_double), ("_Ms", _c.POINTER(_c.c_double)),
# Gilbert damping
('enable_damping', _c.c_bool),
('damping', _c.c_double), ('_dampings', _c.POINTER(_c.c_double)),
# Exchange-like field strength [T], applied in the direction of the other domain's unit vector
('enable_X', _c.c_bool),
('X', _c.c_double), ('_Xs', _c.POINTER(_c.c_double)),
# Spin transfer torque (rate) parallel to other domain [rad / s]
('enable_S', _c.c_bool),
('S', _c.c_double), ('_Ss', _c.POINTER(_c.c_double)),
# Other torQues (rate) unrelated to either domain [rad / s]
('enable_Q', _c.c_bool),
('Qx', _c.c_double), ('_Qxs', _c.POINTER(_c.c_double)),
('Qy', _c.c_double), ('_Qys', _c.POINTER(_c.c_double)),
('Qz', _c.c_double), ('_Qzs', _c.POINTER(_c.c_double)),
# Externally applied field [T]
('enable_B', _c.c_bool),
('Bx', _c.c_double), ('_Bxs', _c.POINTER(_c.c_double)),
('By', _c.c_double), ('_Bys', _c.POINTER(_c.c_double)),
('Bz', _c.c_double), ('_Bzs', _c.POINTER(_c.c_double)),
# Anisotropy tensor elements [T]
('enable_N', _c.c_bool),
('Nxx', _c.c_double), ('_Nxxs', _c.POINTER(_c.c_double)),
('Nxy', _c.c_double), ('_Nxys', _c.POINTER(_c.c_double)),
('Nxz', _c.c_double), ('_Nxzs', _c.POINTER(_c.c_double)),
('Nyx', _c.c_double), ('_Nyxs', _c.POINTER(_c.c_double)),
('Nyy', _c.c_double), ('_Nyys', _c.POINTER(_c.c_double)),
('Nyz', _c.c_double), ('_Nyzs', _c.POINTER(_c.c_double)),
('Nzx', _c.c_double), ('_Nzxs', _c.POINTER(_c.c_double)),
('Nzy', _c.c_double), ('_Nzys', _c.POINTER(_c.c_double)),
('Nzz', _c.c_double), ('_Nzzs', _c.POINTER(_c.c_double)),
# Dipole tensor [T]
('enable_D', _c.c_bool),
('Dxx', _c.c_double), ('_Dxxs', _c.POINTER(_c.c_double)),
('Dxy', _c.c_double), ('_Dxys', _c.POINTER(_c.c_double)),
('Dxz', _c.c_double), ('_Dxzs', _c.POINTER(_c.c_double)),
('Dyx', _c.c_double), ('_Dyxs', _c.POINTER(_c.c_double)),
('Dyy', _c.c_double), ('_Dyys', _c.POINTER(_c.c_double)),
('Dyz', _c.c_double), ('_Dyzs', _c.POINTER(_c.c_double)),
('Dzx', _c.c_double), ('_Dzxs', _c.POINTER(_c.c_double)),
('Dzy', _c.c_double), ('_Dzys', _c.POINTER(_c.c_double)),
('Dzz', _c.c_double), ('_Dzzs', _c.POINTER(_c.c_double)),
# Initial conditions
('x0', _c.c_double),
('y0', _c.c_double),
('z0', _c.c_double),
# Solution arrays
('_x', _c.POINTER(_c.c_double)),
('_y', _c.POINTER(_c.c_double)),
('_z', _c.POINTER(_c.c_double)),
# Calculated Langevin fields
('_Lx', _c.POINTER(_c.c_double)),
('_Ly', _c.POINTER(_c.c_double)),
('_Lz', _c.POINTER(_c.c_double)),
] # End of _data structure
def keys(self):
"""
Returns a list of keys that can be used in set() or get().
"""
return ['enable', 'V', 'x0', 'y0', 'z0', 'gyro', 'M',
'enable_T', 'T',
'enable_damping', 'damping',
'enable_X', 'X',
'enable_S', 'S',
'enable_Q', 'Qx', 'Qy', 'Qz',
'enable_B', 'Bx', 'By', 'Bz',
'enable_N', 'Nxx', 'Nxy', 'Nxz', 'Nyx', 'Nyy', 'Nyz', 'Nzx', 'Nzy', 'Nzz',
'enable_D', 'Dxx', 'Dxy', 'Dxz', 'Dyx', 'Dyy', 'Dyz', 'Dzx', 'Dzy', 'Dzz']
def set(self, key, value):
"""
Sets the specified parameter (key) to the specified value. Specifically,
will be set by evaluating self.keyword = value. In the case of an array,
it will convert it to a pointer and (64-bit float) use an underscore, as needed,
saving a "local" copy of the supplied value, such that garbage
collection doesn't automatically delete it.
Parameters
----------
key:
Parameter name to set, e.g. 'Bx'.
value:
Value to set it to. Can be a number or ndarray.
Example
-------
my_solver.a.set(By=numpy.linspace(0,5,my_solver.steps), gyro=27)
Returns
-------
self
"""
# Store the "local" copy, to make sure we keep it from getting
# deleted by the garbage collection.
exec('self.'+key+"s=v", dict(self=self,v=value))
# If it's an array, convert it before setting and use _*s
if type(value)==list: value = _n.ndarray(value)
if type(value)==_n.ndarray:
exec('self._'+key+"s=v", dict(self=self,v=_to_pointer(value)))
# Otherwise it's a number, so we need to kill the old pointer and
# array
else:
exec('self.' +key+'=v', dict(self=self,v=value))
exec('self.' +key+'s=None', dict(self=self)) # Local copy
exec('self._'+key+"s=None", dict(self=self)) # Converted copy
return self
__setitem__ = set
def set_multiple(self, **kwargs):
"""
Sends all keyword arguments to self.set().
"""
for k in kwargs: self[k] = kwargs[k]
__call__ = set_multiple
def get(self, key='Bx'):
"""
Returns the specified parameter. Will return the array (e.g., Bxs)
if there is one, and the value if there is not.
"""
# If it's an array, return that
if hasattr(self, key+'s'):
x = eval('self.'+key+'s', dict(self=self))
if x is not None: return x
# Otherwise just return the value.
return eval('self.'+key, dict(self=self))
__getitem__ = get
def clear_arrays(self):
"""
This sets all array pointers to NULL (None).
"""
self['T'] = self.T
self['V'] = self.V
self['gyro'] = self.gyro
self['M'] = self.M
self['damping'] = self.damping
self['X'] = self.X
self['S'] = self.S
self['Bx'] = self.Bx
self['By'] = self.By
self['Bz'] = self.Bz
self['Nxx'] = self.Nxx
self['Nxy'] = self.Nxy
self['Nxz'] = self.Nxz
self['Nyx'] = self.Nyx
self['Nyy'] = self.Nyy
self['Nyz'] = self.Nyz
self['Nzx'] = self.Nzx
self['Nzy'] = self.Nzy
self['Nzz'] = self.Nzz
self['Dxx'] = self.Dxx
self['Dxy'] = self.Dxy
self['Dxz'] = self.Dxz
self['Dyx'] = self.Dyx
self['Dyy'] = self.Dyy
self['Dyz'] = self.Dyz
self['Dzx'] = self.Dzx
self['Dzy'] = self.Dzy
self['Dzz'] = self.Dzz
class solver_api():
"""
Scripted interface for the solver engine.
"""
_solver_keys = ['dt', 'steps', 'continuous']
def __init__(self, **kwargs):
# Store the default run parameters
self.dt = 1e-12
self.steps = 1e3
self.continuous = True
self.valid_solution = False
self.log_level = 0
# Create the settings structure, and set the default values.
self.a = _domain()
self.b = _domain()
# Store the default magnetic parameters
self['T'] = 0
self['gyro'] = 1.76085963023e11
self['M'] = 1
self['V'] = 1000e-27
self['damping'] = 0.01
self['X'] = 0
self['S'] = 0
self['Bx'] = 0
self['By'] = 0
self['Bz'] = 1
# Default initial conditions
self.a.x0 = 1.0
self.a.y0 = 0.0
self.a.z0 = 0.0
self.b.x0 = 1.0
self.b.y0 = 0.0
self.b.z0 = 0.0
# Solution arrays
self.a.x = self.a.y = self.a.z = None
self.b.x = self.b.y = self.b.z = None
self.a.Lx = self.a.Ly = self.a.Lz = None
self.b.Lx = self.b.Ly = self.b.Lz = None
# Index up to which the langevin field has been calculated
self.a.n_langevin_valid = -1
self.b.n_langevin_valid = -1
# Null all the array pointers, just to be safe
# (different platforms, Python versions, etc...)
self.a._Ts = self.b._Ts = None
self.a._Vs = self.b._Vs = None
self.a._gyros = self.b._gyros = None
self.a._Ms = self.b._Ms = None
self.a._dampings = self.b._dampings = None
self.a._Xs = self.b._Xs = None
self.a._Ss = self.b._Ss = None
self.a._Bxs = self.b._Bxs = None
self.a._Bys = self.b._Bys = None
self.a._Bzs = self.b._Bzs = None
self.a._Qxs = self.b._Qxs = None
self.a._Qys = self.b._Qys = None
self.a._Qzs = self.b._Qzs = None
self.a._Nxxs = self.b._Nxxs = None
self.a._Nxys = self.b._Nxys = None
self.a._Nxzs = self.b._Nxzs = None
self.a._Nyxs = self.b._Nyxs = None
self.a._Nyys = self.b._Nyys = None
self.a._Nyzs = self.b._Nyzs = None
self.a._Nzxs = self.b._Nzxs = None
self.a._Nzys = self.b._Nzys = None
self.a._Nzzs = self.b._Nzzs = None
self.a._Dxxs = self.b._Dxxs = None
self.a._Dxys = self.b._Dxys = None
self.a._Dxzs = self.b._Dxzs = None
self.a._Dyxs = self.b._Dyxs = None
self.a._Dyys = self.b._Dyys = None
self.a._Dyzs = self.b._Dyzs = None
self.a._Dzxs = self.b._Dzxs = None
self.a._Dzys = self.b._Dzys = None
self.a._Dzzs = self.b._Dzzs = None
# By default, enable the two domains and their components
self.a.enable = True
self.a.enable_damping = True
self.a.enable_X = True
self.a.enable_T = True
self.a.enable_S = True
self.a.enable_B = True
self.a.enable_D = True
self.a.enable_N = True
self.a.enable_Q = True
self.b.enable = True
self.b.enable_damping = True
self.b.enable_X = True
self.b.enable_T = True
self.b.enable_S = True
self.b.enable_B = True
self.b.enable_D = True
self.b.enable_N = True
self.b.enable_Q = True
# No solution arrays initially
self.a._x = self.a._y = self.a._z = None
self.a._Lx = self.a._Ly = self.a._Lz = None
self.b._x = self.b._y = self.b._z = None
self.b._Lx = self.b._Ly = self.b._Lz = None
# Send any supplied parameters
self.set_multiple(**kwargs)
def set(self, key, value):
"""
Sets a parameter for the solver. Magnetic parameters without a domain
specified, e.g., 'gyro' (not 'a/gyro') will be applied to both domains.
Parameters
----------
key:
Parameter name to set, e.g. 'Bx'.
value:
Value to set it to. Can be a number or ndarray.
Example
-------
my_solver.a.set(By=numpy.linspace(0,5,my_solver.steps), gyro=27)
Returns
-------
self
"""
s = key.split('/')
# If it's a property of the solver [dt, steps], store it in the solver
if key in self._solver_keys:
exec('self.'+key+"=v", dict(self=self,v=value))
# If we've specified a domain
elif s[0] == 'a': self.a.set(s[-1], value)
elif s[0] == 'b': self.b.set(s[-1], value)
# Otherwise, if it's something that we send to both a and b.
elif key in self.a.keys():
self.a.set(key, value)
self.b.set(key, value)
else:
print('OOPS solver_api.set(): Cannot find key "'+key+'"')
return self
__setitem__ = set
def set_multiple(self, **kwargs):
"""
Sends all keyword arguments to self.set().
"""
for k in kwargs: self[k] = kwargs[k]
return self
__call__ = set_multiple
def get(self, key='a/Bx'):
"""
Returns the specified parameter. Will return the array (e.g., Bxs)
if there is one, and the value if there is not.
Parameters
----------
key='a/Bx'
Key of item to retrieve. Specify domain 'a' or 'b' with a '/' as in
the example for domain-specific items, and just the parameter for
the solver itself, e.g., 'steps'.
Returns
-------
The value (or array if present).
"""
# First split by '/'
s = key.split('/')
# If length is 1, this is a solver parameter
if len(s) == 1: return eval('self.'+key)
# Otherwise, it's a domain parameter
domain = eval('self.'+s[0])
key = s[1]
return domain.get(key)
__getitem__ = get
def create_solution_arrays(self):
"""
If no solution arrays exist, or their length does not match self['steps'],
create new ones and specify self['valid_solution'] = False, so we know
they are not valid solutions.
"""
# If no solution arrays exist or they are the wrong length,
# create new ones (and specify that there is no valid solution yet!)
if self.a.x is None \
or not type(self.a.x) == _n.ndarray \
or not len(self.a.x) == self.steps:
# Create a bunch of zeros arrays for the solver to fill.
# Also get the pointer to these arrays for the solver engine.
self.a.x = _n.zeros(self.steps); self.a._x = _to_pointer(self.a.x)
self.a.y = _n.zeros(self.steps); self.a._y = _to_pointer(self.a.y)
self.a.z = _n.zeros(self.steps); self.a._z = _to_pointer(self.a.z)
self.b.x = _n.zeros(self.steps); self.b._x = _to_pointer(self.b.x)
self.b.y = _n.zeros(self.steps); self.b._y = _to_pointer(self.b.y)
self.b.z = _n.zeros(self.steps); self.b._z = _to_pointer(self.b.z)
# Only create langevin arrays if the temperature is nonzero or
self.a.Lx = _n.zeros(self.steps); self.a._Lx = _to_pointer(self.a.Lx)
self.a.Ly = _n.zeros(self.steps); self.a._Ly = _to_pointer(self.a.Ly)
self.a.Lz = _n.zeros(self.steps); self.a._Lz = _to_pointer(self.a.Lz)
self.a.n_langevin_valid = -1
self.b.Lx = _n.zeros(self.steps); self.b._Lx = _to_pointer(self.b.Lx)
self.b.Ly = _n.zeros(self.steps); self.b._Ly = _to_pointer(self.b.Ly)
self.b.Lz = _n.zeros(self.steps); self.b._Lz = _to_pointer(self.b.Lz)
self.b.n_langevin_valid = -1
# Remember that we don't have a valid solution yet.
self.valid_solution = False
# Otherwise, just use the arrays we've been using.
return self
def reset(self):
"""
Resets the magnetization to the specified initial conditions.
Specifically, this creates solution arrays if necessary, and then
sets the first element as per self['a/x0'], self['a/y0'], etc.
Then sets n_langevin_valid = -1 for both domains, ensuring that
the Langevin field will be calculated for index n=0 onward.
Finally, sets self.valid_solution = False, because now the
current solution is not valid.
"""
# If we don't have solution arrays, create them.
self.create_solution_arrays()
# User-specified initial conditions
self.a.x[0] = self.a.x0
self.a.y[0] = self.a.y0
self.a.z[0] = self.a.z0
self.b.x[0] = self.b.x0
self.b.y[0] = self.b.y0
self.b.z[0] = self.b.z0
# Make sure to calculate the first value of the langevin field
self.a.n_langevin_valid = -1
self.b.n_langevin_valid = -1
# We don't have a valid solution
self.valid_solution = False
return self
def transfer_last_to_initial(self):
"""
Sets the initial values of the magnetizations and Langevin fields
to the last element of the previously calculated arrays (if we have
a valid solution!). Also sets self.n_langevin_valid=0 so that the
engine doesn't re-calculate the zero'th element of the Langevin field.
"""
if self.valid_solution:
# Set the initial magnetization to the final value
self.a.x[0] = self.a.x[-1]
self.a.y[0] = self.a.y[-1]
self.a.z[0] = self.a.z[-1]
self.b.x[0] = self.b.x[-1]
self.b.y[0] = self.b.y[-1]
self.b.z[0] = self.b.z[-1]
# Do the same for Langevin components
self.a.Lx[0] = self.a.Lx[-1]
self.a.Ly[0] = self.a.Ly[-1]
self.a.Lz[0] = self.a.Lz[-1]
self.a.n_langevin_valid = 0 # Engine won't calculate for n=0
self.b.Lx[0] = self.b.Lx[-1]
self.b.Ly[0] = self.b.Ly[-1]
self.b.Lz[0] = self.b.Lz[-1]
self.b.n_langevin_valid = 0 # Engine won't calculate for n=0
else:
print("ERROR in transfer_last_to_initial(): no valid solution!")
return self
def run(self):
"""
Creates the solution arrays (self.a.x, self.a.Lx, etc) and runs
the solver to fill them up. Afterward, the initial conditions are
(by default) set to the last value of the solution arrays.
"""
self.steps = int(self.steps)
# Create solution arrays
self.create_solution_arrays()
# If we have a valid previous solution and are in continuous mode,
# Set the initial values to the last calculated values
if self.continuous and self.valid_solution:
self.transfer_last_to_initial()
# Otherwise, we just reset the solver
else: self.reset()
# Really large exponents seem to slow this thing way down!
# I think 100 digits of precision is a bit much anyway, but...
roundoff = 1e-200
if abs(self.a.x[0]) < roundoff: self.a.x[0] = 0.0
if abs(self.a.y[0]) < roundoff: self.a.y[0] = 0.0
if abs(self.a.z[0]) < roundoff: self.a.z[0] = 0.0
if abs(self.b.x[0]) < roundoff: self.b.x[0] = 0.0
if abs(self.b.y[0]) < roundoff: self.b.y[0] = 0.0
if abs(self.b.z[0]) < roundoff: self.b.z[0] = 0.0
# Solve it.
_engine.solve_heun.restype = None
_engine.solve_heun(_c.byref(self.a), _c.byref(self.b),
_c.c_double(self.dt), _c.c_long(self.steps),
_c.c_int(self.log_level))
# Let future runs know there is a valid solution for initialization
self.valid_solution = True
return self
class solver():
"""
Graphical and scripted interface for the solver_api. Creating an instance
should pop up a graphical interface.
Keyword arguments are sent to self.set_multiple().
"""
def __init__(self, **kwargs):
# Timer ticks for benchmarking
self._t0 = 0
self._t1 = 1
self._t2 = 2
self._t3 = 3
# Dictionary for values needing a rescale
self._rescale = dict(V=1e-27) # Rescale GUI volumes from nm^3 to m^3
# Solver application programming interface.
self.api = solver_api()
self.a = self.api.a
self.b = self.api.b
# Set up the GUI
self._build_gui()
# Send kwargs to set_multiple()
self.set_multiple(**kwargs)
def _build_gui(self):
"""
Creates the window, puts all the widgets in there, and then shows it.
"""
# Graphical interface
self.window = _g.Window(title='Macrospin(mob)', autosettings_path='solver.window.txt', size=[1000,550])
# Top row controls for the "go" button, etc
self.grid_top = self.window .add(_g.GridLayout(False), alignment=1)
self.button_run = self.grid_top.add(_g.Button('Go!', True))
self.button_get_energy = self.grid_top.add(_g.Button('Get Energy')).disable()
self.label_iteration = self.grid_top.add(_g.Label(''))
self.grid_top.set_column_stretch(3)
# Bottom row controls for settings and plots.
self.window.new_autorow()
self.grid_bottom = self.window.add(_g.GridLayout(False), alignment=0)
### SETTINGS TABS
self.tabs_settings = self.grid_bottom.add(_g.TabArea(autosettings_path='solver.tabs_settings'), alignment=1)
self.tab_solver = self.tabs_settings.add('Solver')
self.tab_a = self.tabs_settings.add('a')
self.tab_b = self.tabs_settings.add('b')
### SOLVER
self.settings_solver = self.tab_solver.add(_g.TreeDictionary(autosettings_path='solver.settings_solver.txt')).set_width(250)
self.settings_solver.add_parameter('solver/iterations', 0, bounds=(0,None))
self.settings_solver.add_parameter('solver/dt', 1e-12, dec=True, siPrefix=True, suffix='s')
self.settings_solver.add_parameter('solver/steps', 5000.0, dec=True, bounds=(2,None), siPrefix=True, suffix='steps')
self.settings_solver.add_parameter('solver/continuous', False)
self.settings_solver.add_parameter('solver/get_energy', False)
### DOMAIN A
self.settings_a = self.tab_a.add(_g.TreeDictionary(autosettings_path='solver.settings_a.txt'), row_span=2).set_width(250)
self.settings_a.add_parameter('a/enable', True, tip='Allow the domain to evolve')
self.settings_a.add_parameter('a/initial/x0', 1.0, tip='Initial magnetization direction (will be normalized to unit length)')
self.settings_a.add_parameter('a/initial/y0', 1.0, tip='Initial magnetization direction (will be normalized to unit length)')
self.settings_a.add_parameter('a/initial/z0', 0.0, tip='Initial magnetization direction (will be normalized to unit length)')
self.settings_a.add_parameter('a/domain/gyro', 1.760859644e11, siPrefix=True, suffix='rad/(s*T)', tip='Magnitude of gyromagnetic ratio')
self.settings_a.add_parameter('a/domain/M', 1.0, siPrefix=True, suffix='T', tip='Saturation magnetization [T] (that is, u0*Ms)')
self.settings_a.add_parameter('a/domain/V', 100*50*3, bounds=(1e-3, None), siPrefix=False, suffix=' nm^3', tip='Volume of domain [nm^3].')
self.settings_a.add_parameter('a/temperature', True)
self.settings_a.add_parameter('a/temperature/T', 300.0, siPrefix=True, suffix='K', dec=True, bounds=(0,None), tip='Temperature [K] of the domain.')
self.settings_a.add_parameter('a/dissipation', True)
self.settings_a.add_parameter('a/dissipation/damping', 0.01, step=0.01, tip='Gilbert damping parameter')
self.settings_a.add_parameter('a/applied_field', True)
self.settings_a.add_parameter('a/applied_field/Bx', 0.0, siPrefix=True, suffix='T', tip='Externally applied magnetic field')
self.settings_a.add_parameter('a/applied_field/By', 0.0, siPrefix=True, suffix='T', tip='Externally applied magnetic field')
self.settings_a.add_parameter('a/applied_field/Bz', 0.0, siPrefix=True, suffix='T', tip='Externally applied magnetic field')
self.settings_a.add_parameter('a/exchange', True)
self.settings_a.add_parameter('a/exchange/X', 0.0, siPrefix=True, suffix='T', tip='Exchange field parallel to domain b\'s magnetization')
self.settings_a.add_parameter('a/spin_transfer', True)
self.settings_a.add_parameter('a/spin_transfer/S', 0.0, siPrefix=True, suffix='rad/s', tip='Spin-transfer-like torque, aligned with domain a\'s magnetization')
self.settings_a.add_parameter('a/applied_torque', True)
self.settings_a.add_parameter('a/applied_torque/Qx', 0.0, siPrefix=True, suffix='rad/s', tip='Other externally applied torque')
self.settings_a.add_parameter('a/applied_torque/Qy', 0.0, siPrefix=True, suffix='rad/s', tip='Other externally applied torque')
self.settings_a.add_parameter('a/applied_torque/Qz', 0.0, siPrefix=True, suffix='rad/s', tip='Other externally applied torque')
self.settings_a.add_parameter('a/anisotropy', True)
self.settings_a.add_parameter('a/anisotropy/Nxx', 0.01, siPrefix=True, suffix='T', tip='Anisotropy matrix (diagonal matrix has values adding to 1)')
self.settings_a.add_parameter('a/anisotropy/Nyy', 0.10, siPrefix=True, suffix='T', tip='Anisotropy matrix (diagonal matrix has values adding to 1)')
self.settings_a.add_parameter('a/anisotropy/Nzz', 0.89, siPrefix=True, suffix='T', tip='Anisotropy matrix (diagonal matrix has values adding to 1)')
self.settings_a.add_parameter('a/anisotropy/Nxy', 0.0, siPrefix=True, suffix='T', tip='Anisotropy matrix (diagonal matrix has values adding to 1)')
self.settings_a.add_parameter('a/anisotropy/Nxz', 0.0, siPrefix=True, suffix='T',tip='Anisotropy matrix (diagonal matrix has values adding to 1)')
self.settings_a.add_parameter('a/anisotropy/Nyx', 0.0, siPrefix=True, suffix='T',tip='Anisotropy matrix (diagonal matrix has values adding to 1)')
self.settings_a.add_parameter('a/anisotropy/Nyz', 0.0, siPrefix=True, suffix='T',tip='Anisotropy matrix (diagonal matrix has values adding to 1)')
self.settings_a.add_parameter('a/anisotropy/Nzx', 0.0, siPrefix=True, suffix='T',tip='Anisotropy matrix (diagonal matrix has values adding to 1)')
self.settings_a.add_parameter('a/anisotropy/Nzy', 0.0, siPrefix=True, suffix='T',tip='Anisotropy matrix (diagonal matrix has values adding to 1)')
self.settings_a.add_parameter('a/dipole', True)
self.settings_a.add_parameter('a/dipole/Dxx', 0.0, siPrefix=True, suffix='T', tip='Dipolar field matrix exerted by domain b.')
self.settings_a.add_parameter('a/dipole/Dyy', 0.0, siPrefix=True, suffix='T', tip='Dipolar field matrix exerted by domain b.')
self.settings_a.add_parameter('a/dipole/Dzz', 0.0, siPrefix=True, suffix='T', tip='Dipolar field matrix exerted by domain b.')
self.settings_a.add_parameter('a/dipole/Dxy', 0.0, siPrefix=True, suffix='T', tip='Dipolar field matrix exerted by domain b.')
self.settings_a.add_parameter('a/dipole/Dxz', 0.0, siPrefix=True, suffix='T', tip='Dipolar field matrix exerted by domain b.')
self.settings_a.add_parameter('a/dipole/Dyx', 0.0, siPrefix=True, suffix='T', tip='Dipolar field matrix exerted by domain b.')
self.settings_a.add_parameter('a/dipole/Dyz', 0.0, siPrefix=True, suffix='T', tip='Dipolar field matrix exerted by domain b.')
self.settings_a.add_parameter('a/dipole/Dzx', 0.0, siPrefix=True, suffix='T', tip='Dipolar field matrix exerted by domain b.')
self.settings_a.add_parameter('a/dipole/Dzy', 0.0, siPrefix=True, suffix='T', tip='Dipolar field matrix exerted by domain b.')
### DOMAIN B
self.settings_b = self.tab_b.add(_g.TreeDictionary(autosettings_path='solver.settings_b.txt'), row_span=2).set_width(250)
self.settings_b.add_parameter('b/enable', False, tip='Allow the domain to evolve')
self.settings_b.add_parameter('b/initial/x0', 1.0, tip='Initial magnetization direction (will be normalized to unit length)')
self.settings_b.add_parameter('b/initial/y0', 1.0, tip='Initial magnetization direction (will be normalized to unit length)')
self.settings_b.add_parameter('b/initial/z0', 0.0, tip='Initial magnetization direction (will be normalized to unit length)')
self.settings_b.add_parameter('b/domain/gyro', 1.760859644e11, siPrefix=True, suffix='rad/(s*T)', tip='Magnitude of gyromagnetic ratio')
self.settings_b.add_parameter('b/domain/M', 1.0, siPrefix=True, suffix='T', tip='Saturation magnetization [T] (that is, u0*Ms)')
self.settings_b.add_parameter('b/domain/V', 100*50*3, bounds=(1e-3, None), siPrefix=False, suffix=' nm^3', tip='Volume of domain [nm^3].')
self.settings_b.add_parameter('b/temperature', True)
self.settings_b.add_parameter('b/temperature/T', 300.0, siPrefix=True, suffix='K', dec=True, bounds=(0,None), tip='Temperature [K] of the domain.')
self.settings_b.add_parameter('b/dissipation', True)
self.settings_b.add_parameter('b/dissipation/damping', 0.01, step=0.01, tip='Gilbert damping parameter')
self.settings_b.add_parameter('b/applied_field', True)
self.settings_b.add_parameter('b/applied_field/Bx', 0.0, siPrefix=True, suffix='T', tip='Externally applied magnetic field')
self.settings_b.add_parameter('b/applied_field/By', 0.0, siPrefix=True, suffix='T', tip='Externally applied magnetic field')
self.settings_b.add_parameter('b/applied_field/Bz', 0.0, siPrefix=True, suffix='T', tip='Externally applied magnetic field')
self.settings_b.add_parameter('b/exchange', True)
self.settings_b.add_parameter('b/exchange/X', 0.0, siPrefix=True, suffix='T', tip='Exchange field parallel to domain b\'s magnetization')
self.settings_b.add_parameter('b/spin_transfer', True)
self.settings_b.add_parameter('b/spin_transfer/S', 0.0, siPrefix=True, suffix='rad/s', tip='Spin-transfer-like torque, aligned with domain b\'s magnetization')
self.settings_b.add_parameter('b/applied_torque', True)
self.settings_b.add_parameter('b/applied_torque/Qx', 0.0, siPrefix=True, suffix='rad/s', tip='Other externally applied torque')
self.settings_b.add_parameter('b/applied_torque/Qy', 0.0, siPrefix=True, suffix='rad/s', tip='Other externally applied torque')
self.settings_b.add_parameter('b/applied_torque/Qz', 0.0, siPrefix=True, suffix='rad/s', tip='Other externally applied torque')
self.settings_b.add_parameter('b/anisotropy', True)
self.settings_b.add_parameter('b/anisotropy/Nxx', 0.01, siPrefix=True, suffix='T', tip='Anisotropy matrix (diagonal matrix has values adding to 1)')
self.settings_b.add_parameter('b/anisotropy/Nyy', 0.10, siPrefix=True, suffix='T', tip='Anisotropy matrix (diagonal matrix has values adding to 1)')
self.settings_b.add_parameter('b/anisotropy/Nzz', 0.89, siPrefix=True, suffix='T', tip='Anisotropy matrix (diagonal matrix has values adding to 1)')
self.settings_b.add_parameter('b/anisotropy/Nxy', 0.0, siPrefix=True, suffix='T', tip='Anisotropy matrix (diagonal matrix has values adding to 1)')
self.settings_b.add_parameter('b/anisotropy/Nxz', 0.0, siPrefix=True, suffix='T', tip='Anisotropy matrix (diagonal matrix has values adding to 1)')
self.settings_b.add_parameter('b/anisotropy/Nyx', 0.0, siPrefix=True, suffix='T', tip='Anisotropy matrix (diagonal matrix has values adding to 1)')
self.settings_b.add_parameter('b/anisotropy/Nyz', 0.0, siPrefix=True, suffix='T', tip='Anisotropy matrix (diagonal matrix has values adding to 1)')
self.settings_b.add_parameter('b/anisotropy/Nzx', 0.0, siPrefix=True, suffix='T', tip='Anisotropy matrix (diagonal matrix has values adding to 1)')
self.settings_b.add_parameter('b/anisotropy/Nzy', 0.0, siPrefix=True, suffix='T', tip='Anisotropy matrix (diagonal matrix has values adding to 1)')
self.settings_b.add_parameter('b/dipole', True)
self.settings_b.add_parameter('b/dipole/Dxx', 0.0, siPrefix=True, suffix='T', tip='Dipolar field matrix exerted by domain a.')
self.settings_b.add_parameter('b/dipole/Dyy', 0.0, siPrefix=True, suffix='T', tip='Dipolar field matrix exerted by domain a.')
self.settings_b.add_parameter('b/dipole/Dzz', 0.0, siPrefix=True, suffix='T', tip='Dipolar field matrix exerted by domain a.')
self.settings_b.add_parameter('b/dipole/Dxy', 0.0, siPrefix=True, suffix='T', tip='Dipolar field matrix exerted by domain a.')
self.settings_b.add_parameter('b/dipole/Dxz', 0.0, siPrefix=True, suffix='T', tip='Dipolar field matrix exerted by domain a.')
self.settings_b.add_parameter('b/dipole/Dyx', 0.0, siPrefix=True, suffix='T', tip='Dipolar field matrix exerted by domain a.')
self.settings_b.add_parameter('b/dipole/Dyz', 0.0, siPrefix=True, suffix='T', tip='Dipolar field matrix exerted by domain a.')
self.settings_b.add_parameter('b/dipole/Dzx', 0.0, siPrefix=True, suffix='T', tip='Dipolar field matrix exerted by domain a.')
self.settings_b.add_parameter('b/dipole/Dzy', 0.0, siPrefix=True, suffix='T', tip='Dipolar field matrix exerted by domain a.')
### TESTS
self.grid_test = self.tab_solver.add(_g.GridLayout(False),0,1)
self.button_run_test = self.grid_test.add(_g.Button('Run Test'))
self.label_test = self.grid_test.add(_g.Label(''))
self.grid_test.new_autorow()
self.settings_test = self.grid_test.add(_g.TreeDictionary(autosettings_path='solver.settings_test.txt'),0,2, column_span=3).set_width(250)
self.grid_bottom.set_row_stretch(0)
self.settings_test.add_parameter('test',
['thermal_noise',
'field_sweep'], tip='Which test to perform')
self.settings_test.add_parameter('iterations', 0, bounds=(0,None), tip='How many test iterations to perform. Zero means "keep doing it."')
self.settings_test.add_parameter('thermal_noise/bins', 100, bounds=(1,None), tip='How many bins for the histogram')
self.settings_test.add_parameter('field_sweep/steps', 100, bounds=(1, None), dec=True)
self.settings_test.add_parameter('field_sweep/solver_iterations', 10, bounds=(1,None), dec=True, tip='How many times to push "Go!" per step.')
self.settings_test.add_parameter('field_sweep/B_start', 0.0, suffix='T', tip='Start value.')
self.settings_test.add_parameter('field_sweep/B_stop', 0.0, suffix='T', tip='Stop value.')
self.settings_test.add_parameter('field_sweep/theta_start', 90.0, suffix=' deg', tip='Start value of spherical coordinates angle from z-axis.')
self.settings_test.add_parameter('field_sweep/theta_stop', 90.0, suffix=' deg', tip='Stop value of spherical coordinates angle from z-axis.')
self.settings_test.add_parameter('field_sweep/phi_start', 0.0, suffix=' deg', tip='Start value of spherical coordinates angle from x-axis.')
self.settings_test.add_parameter('field_sweep/phi_stop', 0.0, suffix=' deg', tip='Stop value of spherical coordinates angle from x-axis.')
### PLOTS AND PROCESSORS
# Plot tabs
self.tabs_plot = self.grid_bottom.add(_g.TabArea(autosettings_path='solver.tabs_plot.txt'), alignment=0)
# Inspection plot for all arrays
self.tab_inspect = self.tabs_plot.add_tab('Inspect')
self.plot_inspect = self.tab_inspect.add(_g.DataboxPlot(autoscript=6, autosettings_path='solver.plot_inspect.txt'), alignment=0)
self.initialize_plot_inspect()
self.plot_inspect.after_clear = self.initialize_plot_inspect
self.plot_inspect.autoscript_custom = self._user_script
# Analysis of inspection
self.tab_process1 = self.tabs_plot.add_tab('Process 1')
self.process1 = self.tab_process1.add(_g.DataboxProcessor('process1'), alignment=0)
self.tab_process2 = self.tabs_plot.add_tab('Process 2')
self.process2 = self.tab_process2.add(_g.DataboxProcessor('process2'), alignment=0)
self.tab_process3 = self.tabs_plot.add_tab('Process 3')
self.process3 = self.tab_process3.add(_g.DataboxProcessor('process3'), alignment=0)
### 3D
self.tab_3d = self.tabs_plot.add_tab('3D')
self.button_3d_a = self.tab_3d.add(_g.Button('a', checkable=True, checked=True))
self.button_3d_b = self.tab_3d.add(_g.Button('b', checkable=True, checked=False))
self.button_3d_sum = self.tab_3d.add(_g.Button('Sum', checkable=True, checked=False))
self.button_plot_3d = self.tab_3d.add(_g.Button('Update Plot'))
self.tab_3d.new_autorow()
# Make the 3D plot window
self._widget_3d = _gl.GLViewWidget()
self._widget_3d.opts['distance'] = 50
# Make the grids
self._gridx_3d = _gl.GLGridItem()
self._gridx_3d.rotate(90,0,1,0)
self._gridx_3d.translate(-10,0,0)
self._widget_3d.addItem(self._gridx_3d)
self._gridy_3d = _gl.GLGridItem()
self._gridy_3d.rotate(90,1,0,0)
self._gridy_3d.translate(0,-10,0)
self._widget_3d.addItem(self._gridy_3d)
self._gridz_3d = _gl.GLGridItem()
self._gridz_3d.translate(0,0,-10)
self._widget_3d.addItem(self._gridz_3d)
# Trajectories
color_a = _pg.glColor(100,100,255)
color_b = _pg.glColor(255,100,100)
color_n = _pg.glColor(50,255,255)
self._trajectory_a_3d = _gl.GLLinePlotItem(color=color_a, width=2.5, antialias=True)
self._trajectory_b_3d = _gl.GLLinePlotItem(color=color_b, width=2.5, antialias=True)
self._trajectory_sum_3d = _gl.GLLinePlotItem(color=color_n, width=2.5, antialias=True)
self._widget_3d.addItem(self._trajectory_a_3d)
self._widget_3d.addItem(self._trajectory_b_3d)
self._widget_3d.addItem(self._trajectory_sum_3d)
# Other items
self._start_dot_a_3d = _gl.GLScatterPlotItem(color=color_a, size=7.0, pos=_n.array([[10,0,0]]))
self._start_dot_b_3d = _gl.GLScatterPlotItem(color=color_b, size=7.0, pos=_n.array([[-10,0,0]]))
self._start_dot_sum_3d = _gl.GLScatterPlotItem(color=color_n, size=7.0, pos=_n.array([[-10,0,0]]))
self._widget_3d.addItem(self._start_dot_a_3d)
self._widget_3d.addItem(self._start_dot_b_3d)
self._widget_3d.addItem(self._start_dot_sum_3d)
self._update_start_dots()
# Add the 3D plot window to the tab
self.tab_3d.add(self._widget_3d, column_span=4, alignment=0)
self.tab_3d.set_column_stretch(3)
self.button_3d_a .signal_clicked.connect(self._button_plot_3d_clicked)
self.button_3d_b .signal_clicked.connect(self._button_plot_3d_clicked)
self.button_3d_sum .signal_clicked.connect(self._button_plot_3d_clicked)
self.button_plot_3d.signal_clicked.connect(self._button_plot_3d_clicked)
### CONNECT SIGNALS, PLOT GLOBALS
# Connect the other controls
self.button_run .signal_clicked.connect(self._button_run_clicked)
self.button_run_test .signal_clicked.connect(self._button_run_test_clicked)
self.button_get_energy.signal_clicked.connect(self._button_get_energy_clicked)
# Always update the start dots when we change a setting
self.settings_a.connect_any_signal_changed(self._update_start_dots)
self.settings_b.connect_any_signal_changed(self._update_start_dots)
# Add extra globals to the plotters
self.plot_script_globals = dict(solver = self)
self.plot_inspect.plot_script_globals = self.plot_script_globals
self.process1.plot.plot_script_globals = self.plot_script_globals
self.process2.plot.plot_script_globals = self.plot_script_globals
self.process3.plot.plot_script_globals = self.plot_script_globals
# Let's have a look!
self.window.show()
def _user_script(self):
"""
Creates a "useful" default script.
"""
f = open(_os.path.join(_ms.__path__[0], 'plot_scripts', 'inspect_basic.py'))
s = f.read()
f.close()
return s
def initialize_plot_inspect(self):
"""
Clears the Inspect plot and populates it with empty arrays.
"""
self.plot_inspect.clear()
self.button_get_energy.disable()
def _update_start_dots(self):
"""
Gets the initial condition from the settings and updates the start
dot positions.
"""
ax = self.settings_a['a/initial/x0']
ay = self.settings_a['a/initial/y0']
az = self.settings_a['a/initial/z0']
an = 1.0/_n.sqrt(ax*ax+ay*ay+az*az)
ax = ax*an
ay = ay*an
az = az*an
bx = self.settings_b['b/initial/x0']
by = self.settings_b['b/initial/y0']
bz = self.settings_b['b/initial/z0']
bn = 1.0/_n.sqrt(bx*bx+by*by+bz*bz)
bx = bx*bn
by = by*bn
bz = bz*bn
self._start_dot_a_3d .setData(pos=10*_n.array([[ax, ay, az]]))
self._start_dot_b_3d .setData(pos=10*_n.array([[bx, by, bz]]))
self._start_dot_sum_3d.setData(pos=10*_n.array([[ax+bx, ay+by, az+bz]]))
self._start_dot_a_3d .setVisible(self.button_3d_a .is_checked())
self._start_dot_b_3d .setVisible(self.button_3d_b .is_checked())
self._start_dot_sum_3d.setVisible(self.button_3d_sum.is_checked())