This repository has been archived by the owner on Dec 2, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
old_all_functions.py
1782 lines (1683 loc) · 79.6 KB
/
old_all_functions.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
"""This is all functions and scripts used by the simulation. All relevant abstraction in project_parameters and analyze_trap."""
# Primary Functions
def test_text():
"""Construct a pair of text files representing BEM-solver trap simulations.
This makes the primary synthetic data structure for testing."""
import numpy as np
from project_parameters import simulationDirectory,debug
low,high = -2,3 # defines data with i,j,k=(-2,-1,0,1,2), symmetric for saddle point at origin
electrode_count = 14 # number of DC electrodes, including the one equivalent to the RF
if debug.calibrate:
electrode_count= 9
axis_length = high-low # number of points along each axis
electrode_size = axis_length**3 # points per electrode
e = electrode_size
total = electrode_count*electrode_size # the length of each simulation data structure
for sim in range(1,3): # construct 2 simulations
data = np.zeros((4,total)) # 4 would be 7 instead if we had electric field data
elem = 0 # initialize the count of data points
for i in range(low,high):
for j in range(low,high):
if sim == 1:
zlow,zhigh = -4,1
if sim == 2:
zlow,zhigh = 0,5
for k in range(zlow,zhigh):
# there is no DC_0 and the final DC is also the RF
Ex,Ey,Ez = i,j,k
#Ex,Ey,Ez = i,-k,j
U1,U2,U3,U4,U5 = 0.5*(i**2-j**2),0.5*(2*k**2-i**2-j**2),i*j,k*j,i*k
# Change to python/math mapping from ion trap mapping
#U1,U2,U3,U4,U5 = U3,-U5,U2,-U4,-U1
#U1,U2,U3,U4,U5 = U5,U3,U1,U4,U2
#U1,U2,U3,U4,U5 = U5,U3,U1,U4,U2
#U1,U2,U3,U4,U5 = U1/5.6,U2/5.6,U3/27.45,U4/5.6,U5/11.2
#Ex,Ey,Ez = Ex/4.25,Ey/6.02,Ez/4.25
RF = U1+10**-3*(j**3-3*i**2*j)
# assign data points to each electrode
if debug.calibrate:
data[:,elem] = [i,j,k,RF] # DC_0 aka RF
data[:,elem+e] = [i,j,k,Ex] # DC_1
data[:,elem+2*e] = [i,j,k,Ey] # DC_2
data[:,elem+3*e] = [i,j,k,Ez] # DC_3
data[:,elem+4*e] = [i,j,k,U1] # DC_4
data[:,elem+5*e] = [i,j,k,U2] # DC_5
data[:,elem+6*e] = [i,j,k,U3] # DC_6
data[:,elem+7*e] = [i,j,k,U4] # DC_7
data[:,elem+8*e] = [i,j,k,U5] # DC_8
else:
data[:,elem] = [i,j,k,RF] # DC_0 aka RF
data[:,elem+e] = [i,j,k,Ex] # DC_1
data[:,elem+2*e] = [i,j,k,Ey] # DC_2
data[:,elem+3*e] = [i,j,k,Ez] # DC_3
data[:,elem+4*e] = [i,j,k,U1+U2] # DC_4
data[:,elem+5*e] = [i,j,k,U1+U3] # DC_5
data[:,elem+6*e] = [i,j,k,U1+U4] # DC_6
data[:,elem+7*e] = [i,j,k,U1+U5] # DC_7
data[:,elem+8*e] = [i,j,k,U2+U3] # DC_8
data[:,elem+9*e] = [i,j,k,U2+U4] # DC_9
data[:,elem+10*e] = [i,j,k,U2+U5] # DC_10
data[:,elem+11*e] = [i,j,k,U3+U4] # DC_11
data[:,elem+12*e] = [i,j,k,U3+U5] # DC_12
data[:,elem+13*e] = [i,j,k,U4+U5] # DC_13
# data[:,elem] = [i,j,k,Ex] # DC_1
# data[:,elem+e] = [i,j,k,Ey] # DC_2
# data[:,elem+2*e] = [i,j,k,Ez] # DC_3
# data[:,elem+3*e] = [i,j,k,U1] # DC_4
# data[:,elem+4*e] = [i,j,k,U2] # DC_5
# data[:,elem+5*e] = [i,j,k,U3] # DC_6
# data[:,elem+6*e] = [i,j,k,U4] # DC_7
# data[:,elem+7*e] = [i,j,k,U5] # DC_8
# data[:,elem+8*e] = [i,j,k,0] # DC_9
# data[:,elem+9*e] = [i,j,k,0] # DC_10
# data[:,elem+10*e] = [i,j,k,0] # DC_11
# data[:,elem+11*e] = [i,j,k,0] # DC_12
# data[:,elem+12*e] = [i,j,k,0] # DC_13
# data[:,elem+13*e] = [i,j,k,U5] # DC_14 aka RF
elem += 1
if debug.calibrate:
np.savetxt('{0}meshless-pt{1}.txt'.format(simulationDirectory,sim),data.T,delimiter=',')
else:
np.savetxt('{0}synthetic-pt{1}.txt'.format(simulationDirectory,sim),data.T,delimiter=',')
return 'test_text constructed, 2 simulations'
def import_data():
"""Originally created as importd by Mike and modified by Gebhard, Oct 2010.
Conventions redefined, cleaned up, and combined with new developments by Nikos, Jun 2013.
Converted to Python and simplified by William, Jan 2014.
Imports simulation data stored in text files, interpreting three coordinates, a scalar potential value,
and (optionally) three electric field components. It outputs a Python "pickle" for each text file.
Each pickle contains attributes: potentials (with an attribute for each electrode), grid vectors (X,Y,Z),
and system Information from project_parameters.
* All the electrodes are initially assumed to be DC.
* The sequence for counting DC electrodes runs through the left side of the RF (bottom to top), right side of
the RF (bottom to top), center electrodes inside of the RF (left center, then right center), and finally RF.
*All other conventions are defined and described in project_parameters."""
from project_parameters import simCount,perm,dataPointsPerAxis,numElectrodes,save,debug
from project_parameters import baseDataName,simulationDirectory,fileName,savePath,timeNow,useDate
from treedict import TreeDict
import pickle
import numpy as np
# renaming for convenience
na, ne = dataPointsPerAxis, numElectrodes
[startingSimulation,numSimulations] = simCount
# iterate through each simulation text file
for iterationNumber in range(startingSimulation,startingSimulation+numSimulations):
#########################################################################################
#0) Check if data already exists
def fileCheck(iterationNumber):
"""Helper function to determine if there already exists imported data."""
try:
file = open(savePath+fileName+'_simulation_{}'.format(iterationNumber)+'.pkl','rb')
file.close()
if iterationNumber==numSimulations+1:
return 'done'
return fileCheck(iterationNumber+1)
except IOError: # unable to open pickle because it does not exist
print('No pre-imported data in directory for simulation {}.'.format(iterationNumber))
return iterationNumber
iterationNumber=fileCheck(iterationNumber) # lowest iteration number that is not yet imported
if iterationNumber=='done':
return 'All files have been imported.'
#########################################################################################
# Read txt file
print('Importing '+''+baseDataName+str(iterationNumber)+'...')
dataName=(simulationDirectory+baseDataName+str(iterationNumber)+'.txt')
#1) check if there is BEM-solver data to import
try:
DataFromTxt=np.loadtxt(dataName,delimiter=',')
except IOError:
return ('No BEM-solver data to import for simulation {}. Import complete.'.format(iterationNumber))
#2) build the X,Y,Z grids
X = [0]
Y = [0]
Z = DataFromTxt[0:na,2]
for i in range(0,(na)):
if i==0:
X[0]=(DataFromTxt[na**2*i+1,0])
Y[0]=(DataFromTxt[na*i+1,1])
else:
X.append(DataFromTxt[na**2*i+1,0])
Y.append(DataFromTxt[na*i+1,1])
X = np.array(X).T
Y = np.array(Y).T
XY = np.vstack((X,Y))
coord=np.vstack((XY,Z))
coord=coord.T
X = coord[:,perm[0]]
Y = coord[:,perm[1]]
Z = coord[:,perm[2]]
#3) load all the voltages and E vector into struct using dynamic naming
struct=TreeDict() # begin intermediate shorthand.
for el in range(ne): #el refers to the electrode, +1 is to include EL_0, the RF electrode
struct['EL_DC_{}'.format(el)]=np.zeros((na,na,na))
struct['Ex_{}'.format(el)]=np.zeros((na,na,na))
struct['Ey_{}'.format(el)]=np.zeros((na,na,na))
struct['Ez_{}'.format(el)]=np.zeros((na,na,na))
for i in range(na):
for j in range (na):
lb = na**3*(el) + na**2*i + na*j # lower bound defined by electrodes complete and axes passed
ub = lb + na # upper bound defined by an increase by axis length
struct['EL_DC_{}'.format(el)][i,j,:]=DataFromTxt[lb:ub,3]
## if loop by Gebhard, Oct 2010; used if there is E field data in BEM
if (DataFromTxt.shape[1]>4): ### i.e. Ex,Ey,Ez are calculated in bemsolver (old version), fast
struct['Ex_{}'.format(el)][i,j,:]=DataFromTxt[lb:ub,4]
struct['Ey_{}'.format(el)][i,j,:]=DataFromTxt[lb:ub,5]
struct['Ez_{}'.format(el)][i,j,:]=DataFromTxt[lb:ub,6]
else:
## i.e. Ex, Ey, Ez are NOT calculated in bemsolver (slow bemsolver, more exact).
## E field of RF will be calculated by the numerical gradient in post_process_trap
struct['Ex_{}'.format(el)][i,j,:]=0
struct['Ey_{}'.format(el)][i,j,:]=0
struct['Ez_{}'.format(el)][i,j,:]=0
struct['EL_DC_{}'.format(el)]=np.transpose(struct['EL_DC_{}'.format(el)],perm)
struct['Ex_{}'.format(el)]=np.transpose(struct['Ex_{}'.format(el)],perm)
struct['Ey_{}'.format(el)]=np.transpose(struct['Ey_{}'.format(el)],perm)
struct['Ez_{}'.format(el)]=np.transpose(struct['Ez_{}'.format(el)],perm)
del DataFromTxt
#4) Build the simulation data structure
sim=struct # copy over intermediate dynamic data structure
sim.X,sim.Y,sim.Z=X,Y,Z # set grid vectors
sim.EL_RF = struct.EL_DC_0 # set RF potential field
s = sim # shorthand for defining import configuration branch
s.simulationDirectory = simulationDirectory
s.baseDataName = baseDataName
s.timeNow = timeNow
s.fileName = fileName
s.useDate = useDate
s.simCount = simCount
s.dataPointsPerAxis = na
s.numElectrodes = ne
s.savePath = savePath
s.perm = perm
sim = s
if debug.import_data: # Plot each electrode
from all_functions import plot_potential
print(plot_potential(sim.EL_RF,X,Y,Z,'1D plots','Debug: RF electrode'))
for el in range(1,ne):
print(plot_potential(sim['EL_DC_{}'.format(el)],X,Y,Z,'1D plots','Debug: DC electrode {}'.format(el)))
#5) save the particular simulation as a pickle data structure
if save == True:
name=savePath+fileName+'_simulation_{}'.format(iterationNumber)+'.pkl'
print ('Saving '+name+' as a data structure...')
output = open(name,'wb')
pickle.dump(sim,output)
output.close()
return 'Import Complete'
def get_trap():
"""Originally getthedata.
Create a new "trap" structure centered around the given position and composed of portions of the adjacent simulations.
The electrodes are ordered as E[1]=E[DC_1],...,E[max-1]=E[center],E[max]=E[RF].
Connect together a line of cubic matrices to describe a rectangular prism of data.
The consecutive data structures must have overlaping first and last points.
Used to create field configuration attributes on the trap that will be used by lower order functions.
These are now imported and saved wherever they are first used through the remaining higher order functions.
Recall that the grid vectors X,Y,Z are still attributes of potentials now and will become attributes of instance later.
Created by Nikos 2009, cleaned 26-05-2013, 10-23-2013.
Converted to Python and revised by William Jan 2014"""
#0) define parameters
from project_parameters import fileName,savePath,position,zMin,zMax,zStep,save,debug,name,simCount
import pickle
import numpy as np
from treedict import TreeDict
tf=TreeDict() # begin shorthand for trap data structure
pathName = savePath+fileName+'_simulation_'
#1) Check if the number of overlapping data structures is the same as the number of simulations.
# simCount was imported again (after import_data used it) because it is used as a check for user input consistency
numSim=int(np.ceil(float(zMax-zMin)/zStep))
if numSim!=simCount[1]:
print numSim,simCount
raise Exception('Inconsistency in simulation number. Check project_parameters for consistency.')
if numSim==1:
print('If there is only one simulation, use that one. Same debug as import_data.')
# This is redundant with the final save but is called here to avoid errors being raised with zLim below.
file = open(pathName+str(simCount[0])+'.pkl','rb')
tf.potentials = pickle.load(file)
file.close()
potential=tf.potentials # base potential to write over
ne=potential.numElectrodes
trap = tf
c=trap.configuration
c.position = position
c.numElectrodes = ne # also listed in systemInformation
c.numUsedElectrodes = ne-1 # will be changed in trap_knobs to fit electrodeMapping and manual electrodes, does not include RF
trap.configuration=c
if save:
import pickle
name=savePath+name+'.pkl'
print('Saving '+name+' as a data structure...')
output = open(name,'wb')
pickle.dump(trap,output)
output.close()
return 'Constructed trap from single file.'
#2) Define a background for files.
zLim=np.arange(zMin,zMax,zStep)
#3) helper function to find z-position of ion
def find_index(list,position): # Find which simulation position is in based on z-axis values.
"""Finds index of first element of list higher than a given position. Lowest index is 1, not 0"""
# replaces Matlab Code: I=find(zLim>position,1,'first')-1
i=0
for elem in list:
if elem>position:
index=i
return index
else:
index=0
i += 1
return index
index=find_index(zLim,position)
if (index<1) or (index>simCount[1]):
raise Exception('Invalid ion position. Quitting.')
#4) determine which side of the simulation the ion is on
pre_sign=2*position-zLim[index-1]-zLim[index] # determines
if pre_sign==0:
# position is exactly halfway between simulations
sign=-1 # could be 1 as well
else:
sign=int(pre_sign/abs(pre_sign))
#5) If position is in the first half of the first grid, just use that grid.
if (index==1) and (sign==-1):
print('If position is in the first or last grid, just use that grid.')
file = open(pathName+'1.pkl','rb')
tf.potentials = pickle.load(file)
file.close()
#6) If the ion is in the second half of the last grid, just use the last grid.
elif (index==simCount[1]) and (sign==1):
print('If the ion is in the second half of the last grid, just use the last grid.')
file = open(pathName+'{}.pkl'.format(numSimulations),'rb')
tf.potentials = pickle.load(file)
file.close()
#7) Somewhere in between. Build a new set of electrode potentials centered on the position.
else:
print('Somewhere in between. Build a new set of electrode potentials centered on the position.')
#a) open data structure
file = open(pathName+'{}.pkl'.format(index),'rb')
tf.potentials = pickle.load(file)
file.close()
lower=position-zStep/2 # lower bound z value
upper=position+zStep/2 # upper bound z value
shift=int(pre_sign) # index to start from in left sim and end on in right sim, how many idices the indexing shifts right by
if shift < 0:
index -= 1
shift = abs(shift)
#b) open left sim
file1 = open(pathName+'{}.pkl'.format(index),'rb')
left = pickle.load(file1)
file1.close()
#c) open right sim
file2 = open(pathName+'{}.pkl'.format(index+1),'rb')
right = pickle.load(file2)
file.close()
#d) build bases
cube=tf.potentials.EL_DC_1 # arbitrary electrode; assume each is cube of same length
w=len(cube[0,0,:]) # number of elements in each cube; width
potential=tf.potentials # base potential to write over
Z=potential.Z # arbitrary axis with correct length to build new grid vector
ne=potential.numElectrodes
#e) build up trap
for el in range(ne): # includes the RF
right_index,left_index,z_index=w-shift,0,0
temp=np.zeros((w,w,w)) # placeholder that becomes each new electrode
left_el=left['EL_DC_{}'.format(el)]
right_el=right['EL_DC_{}'.format(el)]
for z in range(shift-1,w): # build up the left side
temp[:,:,left_index]=left_el[:,:,z]
Z[z_index] = left.Z[z]
z_index += 1
left_index += 1
z_index -= 1 # counters double-counting of overlapping center point
for z in range(shift): # build up the right side; ub to include final point
temp[:,:,right_index]=right_el[:,:,z]
Z[z_index] = right.Z[z]
z_index += 1
right_index+=1
potential.Z = Z
potential['EL_DC_{}'.format(el)]=temp
tf.potentials = potential
#8) assign configuration variables to trap; originally trapConfiguration
trap = tf
c=trap.configuration
c.position = position
c.numElectrodes = ne # also listed in systemInformation
c.numUsedElectrodes = ne-1 # will be changed in trap_knobs to fit electrodeMapping and manual electrodes, excluding RF
trap.configuration=c
#9) check if field generated successfully
if debug.get_trap:
sim = tf.potentials
X,Y,Z = sim.X,sim.Y,sim.Z # grid vectors
import matplotlib.pyplot as plt
plt.plot(Z,np.arange(len(Z)))
plt.title('get_trap: contnuous straight line if successful')
plt.show()
sim = tf.potentials
from all_functions import plot_potential
print(plot_potential(sim.EL_RF,X,Y,Z,'2D plots','Debug: RF electrode'))
for el in range(1,ne):
print(plot_potential(sim['EL_DC_{}'.format(el)],X,Y,Z,'1D plots','Debug: DC electrode {}'.format(el)))
#10) save new data structure as a pickle
if save:
import pickle
name=savePath+name+'.pkl'
print('Saving '+name+' as a data structure...')
output = open(name,'wb')
pickle.dump(trap,output)
output.close()
return 'Constructed trap.'
def expand_field():
"""Originally regenthedata. Regenerates the potential data for all electrodes using multipole expansion to given order.
Also returns a attribute of trap, configuration.multipoleCoefficients, which contains the multipole coefficients for all electrodes.
The electrodes are ordered as E[1], ..., E[NUM_DC]=E[RF] though the final electrode is not included in the attribute.
(if center and RF are used)
( multipoles electrodes -> )
( | )
M = ( V )
( )
Multipole coefficients only up to order 8 are kept, but the coefficients are calculated up to order L.
trap is the path to a data structure that contains an instance with the following properties
.DC is a 3D matrix containing an electric potential and must solve Laplace's equation
.X,.Y,.Z are the vectors that define the grid in three directions
Xcorrection, Ycorrection: optional correction offsets from the RF saddle point,
in case that was wrong by some known offset
position: the axial position where the ion sits
Written by Nikos, Jun 2009, cleaned up 26-05-2013, 10-23-2013
Converted to by Python by William, Jan 2014"""
#0) establish parameters and open updated trap with including instance configuration attributes
from project_parameters import savePath,name,Xcorrection,Ycorrection,regenOrder,save,debug,E
from all_functions import spher_harm_exp,spher_harm_cmp,spher_harm_qlt,find_saddle,exact_saddle,plot_potential,dc_potential
import numpy as np
import pickle
trap = savePath+name+'.pkl'
file = open(trap,'rb')
tf = pickle.load(file)
file.close()
ne=tf.configuration.numElectrodes
if not debug.expand_field:
if tf.configuration.expand_field==True:
return 'Field is already expanded.'
if tf.instance.check!=True:
print 'No instance exists yet, so build one.'
VMULT= np.ones((ne,1)) # analogous to dcVolatages
VMAN = np.zeros((ne,1))# analogous to manualElectrodes
IMAN = np.zeros((ne,1))# analogous to weightElectrodes
# run dc_potential to create instance configuration
dc_potential(trap,VMULT,VMAN,IMAN,E,True)
file = open(trap,'rb')
tf = pickle.load(file)
file.close()
V,X,Y,Z=tf.instance.DC,tf.instance.X,tf.instance.Y,tf.instance.Z
tc=tf.configuration #intermediate shorthand for configuration
position = tc.position
tc.EL_RF = tf.potentials.EL_RF
if Xcorrection:
print('expand_field: Correction of XRF: {} mm.'.format(str(Xcorrection)))
if Ycorrection:
print('expand_field: Correction of YRF: {} mm.'.format(str(Ycorrection)))
# Order to expand to in spherharm for each electrode.
NUM_DC = ne-1 # exclude the RF electrode listed as the highest DC electrode
order = np.zeros(NUM_DC)
L = regenOrder
order[:]=int(L)
N=(L+1)**2 # regenOrder is typically 2, making this 9
#1) Expand the RF about the grid center, regenerate data from the expansion.
print('Expanding RF potential')
Irf,Jrf,Krf = int(np.floor(X.shape[0]/2)),int(np.floor(Y.shape[0]/2)),int(np.floor(Z.shape[0]/2))
Xrf,Yrf,Zrf = X[Irf],Y[Jrf],Z[Krf]
Qrf = spher_harm_exp(tc.EL_RF,Xrf,Yrf,Zrf,X,Y,Z,L)
# if debug.expand_field:
# print Qrf
# plot_potential(tc.EL_RF,X,Y,Z,'1D plots','EL_RF','V (Volt)',[Irf,Jrf,Krf])
print('Comparing RF potential')
tc.EL_RF = spher_harm_cmp(Qrf,Xrf,Yrf,Zrf,X,Y,Z,L)
# these flips only fix x and y, but not z after regen mirrors the array
tc.EL_RF=np.fliplr(tc.EL_RF)
tc.EL_RF=np.flipud(tc.EL_RF)
if debug.expand_field:
plot_potential(tc.EL_RF,X,Y,Z,'1D plots','EL_RF','V (Volt)',[Irf,Jrf,Krf])
#2) Expand the RF about its saddle point at the trapping position and save the quadrupole components.
print('Expanding RF about saddle point')
[Xrf,Yrf,Zrf] = exact_saddle(tc.EL_RF,X,Y,Z,2,position)
[Irf,Jrf,Krf] = find_saddle(tc.EL_RF,X,Y,Z,2,position)
Qrf = spher_harm_exp(tc.EL_RF,Xrf+Xcorrection,Yrf+Xcorrection,Zrf,X,Y,Z,L)
tc.Qrf = 2*[Qrf[7][0]*3,Qrf[4][0]/2,Qrf[8][0]*6,-Qrf[6][0]*3,-Qrf[5][0]*3]
tc.thetaRF = 45*((Qrf[8][0]/abs(Qrf[8][0])))-90*np.arctan((3*Qrf[7][0])/(3*Qrf[8][0]))/np.pi
#3) Regenerate each DC electrode
Mt=np.zeros((N,NUM_DC))
for el in range(1,NUM_DC+1): # do not include the RF
# Expand all the electrodes and regenerate the potentials from the multipole coefficients
print('Expanding DC Electrode {} ...'.format(el))
multipoleDCVoltages = np.zeros(NUM_DC)
multipoleDCVoltages[el-1] = 1
E = [0,0,0]
Vdc = dc_potential(trap,multipoleDCVoltages,np.zeros(NUM_DC),np.zeros(NUM_DC),E)
#if debug.expand_field:
#plot_potential(Vdc,X,Y,Z,'1D plots',('Old EL_{} DC Potential'.format(el)),'V (Volt)',[Irf,Jrf,Krf])
print('Applying correction to Electrode {} ...'.format(el))
Q = spher_harm_exp(Vdc,Xrf+Xcorrection,Yrf+Ycorrection,Zrf,X,Y,Z,int(order[el-1]))
print('Regenerating Electrode {} potential...'.format(el))
tf.potentials['EL_DC_{}'.format(el)]=spher_harm_cmp(Q,Xrf+Xcorrection,Yrf+Ycorrection,Zrf,X,Y,Z,int(order[el-1]))
tf.potentials['EL_DC_{}'.format(el)]=np.fliplr(tf.potentials['EL_DC_{}'.format(el)])
tf.potentials['EL_DC_{}'.format(el)]=np.flipud(tf.potentials['EL_DC_{}'.format(el)])
if debug.expand_field:
print(Q)
plot_potential(tf.potentials['EL_DC_{}'.format(el)],X,Y,Z,'1D plots',('EL_{} DC Potential'.format(el)),'V (Volt)',[Irf,Jrf,Krf])
check = np.real(Q[0:N].T)[0]
Mt[:,el-1] = Q[0:N].T
# Note: There used to be an auxiliary fuinction here that was not used: normalize.
#4) Define the multipole Coefficients
tc.multipoleCoefficients = Mt
print('expand_field: Size of the multipole coefficient matrix is {}'.format(Mt.shape))
print('expand_field: ended successfully.')
if save:
tc.expand_field=True
tf.configuration=tc
dataout=tf
if save:
output = open(trap,'wb')
pickle.dump(tf,output)
output.close()
return tf
def trap_knobs():
"""Updates trap.configuration with the matrix which controls the independent multipoles, and the kernel matrix.
Starting from the matrix multipoleCoefficients, return a field multipoleControl with
the linear combimations of trap electrode voltages that give 1 V/mm, or 1 V/mm**2 of the multipole number i.
Also return matrix multipoleKernel which is the kernel matrix of electrode linear combinations which do nothing to the multipoles.
The order of multipole coefficients is:
1/r0**[ x, y, z ] and
1/r0**2*[ (x^2-y^2)/2, (2z^2-x^2-y^2)/2, xy, yz, xz ], where r0 is 1 mm (unless rescaling is applied)
Before solving the system, compact the multipoleCoefficient matrix by removing all redundant electrodes.
After solving the system, expand the multipoleControl matric to include these.
If the system is underdetermined, then there is no Kernel or regularization.
"""
print('Executing trap_knobs...')
#0) Define parameters
from project_parameters import position,debug,reg,savePath,name,save,electrodeMapping,manualElectrodes,usedMultipoles
from project_parameters import expansionOrder,simulationDirectory
import numpy as np
import matplotlib.pyplot as plt
from all_functions import plotN,compact_matrix,expand_matrix_mult,expand_matrix_el
import pickle
trap = savePath+name+'.pkl'
file = open(trap,'rb')
tf = pickle.load(file)
file.close()
V,X,Y,Z=tf.instance.DC,tf.instance.X,tf.instance.Y,tf.instance.Z
numTotalMultipoles=len(usedMultipoles)
numMultipoles=np.sum(usedMultipoles)
eo = expansionOrder
NUM_DC = tf.configuration.numElectrodes - 1
#1) check to see what scripts have been run and build parameters from them
if tf.configuration.expand_field!=True:
return 'You must run expand_field first!'
if tf.configuration.trap_knobs and not debug.trap_knobs:
return 'Already executed trap_knobs.'
dataout = tf
tc=tf.configuration
multipoleCoefficients = tc.multipoleCoefficients # From expand_field (old regenthedata)
if debug.trap_knobs:
print(multipoleCoefficients)
for row in range(((eo+1)**2)-1):
row+=1
if abs(np.sum(multipoleCoefficients[row,:])) < 10**-50: # arbitrarily small
return 'trap_knobs: row {} is all 0, can not solve least square, stopping trap knobs'.format(row)
MR = compact_matrix(multipoleCoefficients, NUM_DC, ((eo+1)**2), electrodeMapping, manualElectrodes)
tc.multipoleCoefficientsReduced = MR
allM = MR[1:((eo+1)**2),:] # cut out the first multipole coefficient (constant)
print('trap_knobs: with electrode constraints, the coefficient matrix size is ({0},{1}).\n'.format(allM.shape[0],allM.shape[1]))
C = np.zeros((numMultipoles,allM.shape[1]))
usedM = np.zeros((numMultipoles,allM.shape[1]))
usmm = 0
for mm in range(numTotalMultipoles):
# keep only the multipoles you specified in usedMultipoles
if usedMultipoles[mm]:
usedM[usmm,:] = allM[mm,:]
usmm += 1
Mt = usedM
#2) iterate through multipoles to build multipole controls
for ii in range(numMultipoles):
Mf = np.zeros((numMultipoles,1))
Mf[ii] = 1
P = np.linalg.lstsq(Mt,Mf)[0]
Mout = np.dot(Mt,P)
err = Mf-Mout
if debug.trap_knobs:
fig=plt.figure()
plt.plot(err)
plt.title('Error of the fit elements')
plotN(P)
C[ii,:] = P.T
#3) Helper function From: http://wiki.scipy.org/Cookbook/RankNullspace
from numpy.linalg import svd
def nullspace(A, atol=1e-13, rtol=0):
"""Compute an approximate basis for the nullspace of A.
The algorithm used by this function is based on the singular value decomposition of `A`.
Parameters
----------
A : ndarray
A should be at most 2-D. A 1-D array with length k will be treated
as a 2-D with shape (1, k)
atol : float
The absolute tolerance for a zero singular value. Singular values
smaller than `atol` are considered to be zero.
rtol : float
The relative tolerance. Singular values less than rtol*smax are
considered to be zero, where smax is the largest singular value.
If both `atol` and `rtol` are positive, the combined tolerance is the
maximum of the two; that is::
tol = max(atol, rtol * smax)
Singular values smaller than `tol` are considered to be zero.
Return value
------------
ns : ndarray
If `A` is an array with shape (m, k), then `ns` will be an array
with shape (k, n), where n is the estimated dimension of the
nullspace of `A`. The columns of `ns` are a basis for the
nullspace; each element in numpy.dot(A, ns) will be approximately
zero.
"""
A = np.atleast_2d(A)
u, s, vh = svd(A)
tol = max(atol, rtol * s[0])
nnz = (s >= tol).sum()
ns = vh[nnz:].conj().T
return ns
if Mt.shape[0] < Mt.shape[1]:
K = nullspace(Mt)
else:
print('There is no nullspace because the coefficient matrix is rank deficient.')
print('There can be no regularization.')
K = None
reg = False
#4) regularize C with K
if reg:
for ii in range(numMultipoles):
Cv = C[ii,:].T
Lambda = np.linalg.lstsq(K,Cv)[0]
test=np.dot(K,Lambda)
C[ii,:] = C[ii,:]-test
#5) update instance configuration with expanded matrix
C = expand_matrix_mult(C,numTotalMultipoles,usedMultipoles)
C = expand_matrix_el(C,numTotalMultipoles,NUM_DC,electrodeMapping,manualElectrodes)
tc.multipoleKernel = K
tc.multipoleControl = C.T
tc.trap_knobs = True
dataout.configuration=tc
if save:
import pickle
print('Saving '+name+' as a data structure...')
output = open(trap,'wb')
pickle.dump(dataout,output)
output.close()
CT = C.T
print CT.shape
T = np.zeros(CT.shape[0]*CT.shape[1])
for j in range(CT.shape[1]):
for i in range(CT.shape[0]):
T[j*CT.shape[0]+i] = CT[i,j]
np.savetxt(simulationDirectory+name+'.txt',T,delimiter=',')
return 'Completed trap_knobs.'
def post_process_trap():
"""A post processing tool that analyzes the trap. This is the highest order function.
It plots an input trap in a manner of ways and returns the frequencies and positions determined by pfit.
Before 2/19/14, it was far more complicated. See ppt2 for the past version and variable names.
All necessary configuration parameters should be defined by dcpotential instance, trap knobs, and so on prior to use.
Change rfplot and dcplot to control the "dim" input to plot_potential for plotting the potential fields.
There is also an option to run findEfield that determines the stray electric field for given DC voltages.
As of May 2014, only "justAnalyzeTrap" is in use, so see older versions for the other optimizations.
This is primarily a plotting function beyond just calling pfit.
RF saddles are dim=2 because there ion is not contained along teh z-axis. DC saddles are dim=3.
Nikos, January 2009
William Python Feb 2014"""
#################### 0) assign internal values ####################
from project_parameters import manualElectrodes,weightElectrodes,save,debug,qe,mass,E,U1,U2,U3,U4,U5,ax,az,phi
from project_parameters import savePath,name,driveAmplitude,driveFrequency,justAnalyzeTrap,rfplot,dcplot
from all_functions import find_saddle,exact_saddle,plot_potential,dc_potential,d_e,pfit,spher_harm_exp
import numpy as np
import pickle
trap = savePath+name+'.pkl'
file = open(trap,'rb')
tf = pickle.load(file)
file.close()
VMULT = set_voltages()
VMAN = weightElectrodes
IMAN = manualElectrodes
tf.instance.DC = dc_potential(trap,VMULT,VMAN,IMAN,E,True)
V,X,Y,Z=tf.instance.DC,tf.instance.X,tf.instance.Y,tf.instance.Z
RFampl = driveAmplitude # drive amplitude of RF
f = driveFrequency # drive frequency of RF
Omega = 2*np.pi*f # angular frequency of RF
# old trap configuration attributes, now from project_parameters directly
tc = tf.configuration # trap configuration shorthand
e = qe #convenience shorthand for charge
mass = mass # mass of the ion
Zval = tc.position # position of ion on z-axis, given for get_trap
V0 = mass*(2*np.pi*f)**2/qe
out = tc # for quality checking at end of function; may no longer be needed
data = tf.potentials # shorthand for refernce to trapping field potentials; mostly RF
[x,y,z] = np.meshgrid(X,Y,Z) # only used for d_e
#1) rescale and plot the RF potential
print('Applying amplitude weight to RF')
[Irf,Jrf,Krf] = find_saddle(data.EL_RF,X,Y,Z,2,Zval)
Vrf = RFampl*data.EL_RF
plot_potential(Vrf/e,X,Y,Z,dcplot,'weighted RC potential','V_{rf} (eV)',[Irf,Jrf,Krf])
#2) plot the initial DC potential, defined by set_potrential
Vdc = dc_potential(trap,VMULT,VMAN,IMAN,E)
[Idum,Jdum,Kdum] = find_saddle(Vdc,X,Y,Z,2,Zval)
plot_potential(Vdc/e,X,Y,Z,dcplot,'DC potential (stray field included)','V_{dc} (eV)',[Idum,Jdum,Kdum])
#2.5) there are no longer had d_e or d_c optimization options
print('findEfield is no longer relevant')
print('findCompensation is no longer relevant')
#3) determine stray field (beginning of justAnalyzeTrap)
# this option means do not optimize anything, and just analyze the trap; this still uses d_e
print('Running post_process_trap in plain analysis mode (no optimizations).')
dist = d_e(E,Vdc,data,x,y,z,X,Y,Z,Zval)
print('Stray field is ({0}, {1}, {2}) V/m.'.format(1e3*E[0],1e3*E[1],1e3*E[2]))
print('With this field, the compensation is optimized to {} micron.'.format(1e3*dist))
#4) determine the exact saddles of the RF and DC
Vdc = dc_potential(trap,VMULT,VMAN,IMAN,E)
[XRF,YRF,ZRF] = exact_saddle(data.EL_RF,X,Y,Z,2,Zval)
[XDC,YDC,ZDC] = exact_saddle(Vdc,X,Y,Z,3,Zval)
print('RF saddle: ({0},{1},{2})\nDC saddle ({3},{4},{5}).'.format(XRF,YRF,ZRF,XDC,YDC,ZDC))
#4.5) plot the DC potential around the RF saddle
plot_potential(Vdc/e,X,Y,Z,dcplot,'RF saddle DC potential','V_{dc} (eV)',[Irf,Jrf,Krf]) #old Compensated DC potential
#5) call pfit to determine the trap characteristics
[IDC,JDC,KDC] = find_saddle(Vdc,X,Y,Z,2,Zval)
[fx,fy,fz,theta,Depth,rx,ry,rz,xe,ye,ze,superU] = pfit(trap,E,f,RFampl)
#6) Sanity testing; quality check no longer used
Qrf = spher_harm_exp(Vrf,XRF,YRF,ZRF,X,Y,Z,2)
if np.sqrt((XRF-XDC)**2+(YRF-YDC)**2+(ZRF-ZDC)**2)>0.008:
print('Expanding DC with RF')
Qdc = spher_harm_exp(Vdc,XRF,YRF,ZRF,X,Y,Z,2)
else:
print('Expanding DC without RF')
Qdc = spher_harm_exp(Vdc,XDC,YDC,ZDC,X,Y,Z,2)
Arf = 2*np.sqrt( (3*Qrf[7])**2+(3*Qrf[8])**2 )
Thetarf = 45*(Qrf[8]/abs(Qrf[8]))-90*np.arctan((3*Qrf[7])/(3*Qrf[8]))/np.pi
Adc = 2*np.sqrt( (3*Qdc[7])**2+(3*Qdc[8])**2 )
Thetadc = 45*(Qrf[8]/abs(Qrf[8]))-90*np.arctan((3*Qdc[7])/(3*Qdc[8]))/np.pi
out.E = E
out.miscompensation = dist
out.ionpos = [XRF,YRF,ZDC]
out.ionposIndex = [Irf,Jrf,Krf]
out.f = [fx,fy,fz]
out.theta = theta
out.trap_depth = Depth/qe
out.escapepos = [xe,ye,ze]
out.Quadrf = 2*np.array([Qrf[7]*3,Qrf[4]/2,Qrf[8]*6,-Qrf[6]*3,-Qrf[5]*3])
out.Quaddc = 2*np.array([Qdc[7]*3,Qdc[4]/2,Qdc[8]*6,-Qdc[6]*3,-Qdc[5]*3])
out.Arf = Arf
out.Thetarf = Thetarf
out.Adc = Adc
out.Thetadc = Thetadc
T = np.array([[2,-2,0,0,0],[-2,-2,0,0,0],[0, 4,0,0,0],[0, 0,1,0,0],[0, 0,0,1,0],[0, 0,0,0,1]])
Qdrf = out.Quadrf.T
Qddc = out.Quaddc.T
out.q = (1/V0)*T*Qdrf
out.alpha = (2/V0)*T*Qddc
out.Error = [X[IDC]-XDC,Y[JDC]-YDC,Z[KDC]-ZDC]
out.superU = superU
#7) update the trapping field data structure with instance attributes
tf.configuration=out
tf.instance.driveAmplitude = driveAmplitude
tf.instance.driveFrequency = driveFrequency
tf.instance.E = E
tf.instance.U1 = U1
tf.instance.U2 = U2
tf.instance.U3 = U3
tf.instance.U4 = U4
tf.instance.U5 = U5
tf.instance.ax = ax
tf.instance.az = az
tf.instance.phi = phi
tf.instance.ppt = True
tf.instance.out = out
if save==True:
import pickle
update=trap
print('Saving '+update+' as a data structure...')
output = open(update,'wb')
pickle.dump(tf,output)
output.close()
return 'post_proccess_trap complete' #out # no output needed really
print('Referencing all_functions...')
# Secondary Functions
def compact_matrix(MM,NUM_ELECTRODES,numMultipoles,electrodeMap,manualEl):
"""multipole compaction operation: combine paired electrodes and remove
manually controlled electrodes form multipoleCoefficients matrix
to test this function:
numMultipoles = 5
NUM_ELECTRODES = 9
electrodeMap = np.array([[1,1]; 2 1; 3 2; 4 2; 5 3; 6 4; 7 5; 8 6; 9 7])
manualEl = [1 1 0 0 0 0 0 0 1];
MM =[1 0 1 0 1 0 1 0 1;...
0 0 1 0 0 1 0 0 1;...
1 0 0 1 0 0 1 0 0;...
0 1 0 0 1 0 0 1 0;...
1 0 0 1 0 0 0 1 0];
then copy the following code to command line"""
import numpy as np
MR1 = np.zeros((numMultipoles,electrodeMap[NUM_ELECTRODES-1,1]))
mE = np.zeros(electrodeMap[NUM_ELECTRODES-1,1])
# combine paired electrodes (no longer needs to set manual ones to 0)
for ell in range(NUM_ELECTRODES):
if manualEl[ell]==0:
MR1[:,electrodeMap[ell,1]-1] = MR1[:,electrodeMap[ell,1]-1] + MM[:,ell]
else:
if not mE[electrodeMap[ell,1]-1]:
mE[electrodeMap[ell,1]-1] += 1
print('trap_knobs/compact_matrix/combine electrodes: {0}->{1}'.format(ell+1,electrodeMap[ell,1]))
RM = np.zeros((numMultipoles,(electrodeMap[NUM_ELECTRODES-1,1]-np.sum(mE))))
RMel = 0
for ell in range(MR1.shape[1]):
# remove the manually controlled electrodes
if (max(np.abs(MR1[:,ell]))>0): # more particularly, only add in nonmanual electrodes
RM[:,RMel] = MR1[:,ell]
print('trap_knobs/compact_matrix/keep multipole controlled electrodes: {}'.format(ell+1))
RMel += 1
return RM # temporary
def expand_matrix_mult(RM,numTotMultipoles,usedMultipoles):
"""expand the multipole control martix to cover all the multipoles
add zero rows to the positions where the multipoles are not
constrained by the code
RM is the reduced matrix
EM (output) is the expanded matrix"""
import numpy as np
em = np.zeros((numTotMultipoles,RM.shape[1]))
currmult = 0
for cc in range (numTotMultipoles):
if usedMultipoles[cc]:
em[cc,:] = RM[currmult,:]
currmult += 1
return em
def expand_matrix_el(RM, numTotMultipoles, NUM_ELECTRODES, electrodeMap, manualEl):
"""expand a multipole control matrix from the functional electrode
basis to the physical electrode basis. First step is to put back
the grounded electrodes as 0s. Second step is to split up the
paired up electrodes into their constituents.
RM is the reduced matrix
EM is the expanded matrix"""
import numpy as np
EM = np.zeros((numTotMultipoles,NUM_ELECTRODES))
Nfunctional = 0
if manualEl[0] == 0:
EM[:,0] = RM[:,0]
if electrodeMap[0,1] < electrodeMap[1,1]:
Nfunctional += 1
for ee in range(1,NUM_ELECTRODES):
if manualEl[ee] == 0:
EM[:,ee] = RM[:,Nfunctional]
if ee < NUM_ELECTRODES:
# Nfunctional increases only when the electrode is in multipole control and the map changes
if electrodeMap[ee-1,1] < electrodeMap[ee,1]:
Nfunctional +=1
return EM
def dc_potential(trap,VMULT,VMAN,IMAN,E,update=None):
""" Calculates the dc potential given the applied voltages and the stray field.
Creates a third attribute of trap, called instance, a 3D matrix of potential values
trap: file path and name, including '.pkl'
VMULT: electrode voltages determined by the multipole control algorithm
VMAN: electrode voltages determined by manual user control
e.g. VMAN = [0,0,-2.,0,...] applies -2 V to electrode 3
IMAN: array marking by an entry of 1 the electrodes which are under manual control,
e.g. IMAN = [0,0,1,0,...] means that electrode 3 is under manual control
BOTH above conditions are necessary to manually apply the -2 V to electrode 3
Ex,Ey,Ez: stray electric field; 3D matrices
update: name to save new file as; typically the same as the name used for get_trap
Nikos, cleaned up June 2013
William, converted to Python Jan 2014"""
import pickle, pprint
from all_functions import plot_potential
file = open(trap,'rb')
tf = pickle.load(file)
file.close()
p=tf.potentials # shorthand to refer to all potentials
nue=tf.configuration.numUsedElectrodes
X,Y,Z=tf.potentials.X,tf.potentials.Y,tf.potentials.Z # grid vectors
import numpy as np
x,y,z=np.meshgrid(X,Y,Z)
[Ex,Ey,Ez]=E
Vout = np.zeros((p['EL_DC_1'].shape[0],p['EL_DC_1'].shape[1],p['EL_DC_1'].shape[2]))
# build up the potential from the manual DC electrodes
for ii in range(nue):
if int(VMAN[ii])==1:
Vout = Vout + IMAN[ii]*p['EL_DC_{}'.format(ii+1)] # no mEL_DC
# build up the potential from the normal DC elctrodes
for ii in range(nue):
Vout = Vout + VMULT[ii]*p['EL_DC_{}'.format(ii+1)]
# subtract the stray E field
Vout = Vout-Ex*x-Ey*y-Ez*z
# update the trapping field data structure with instance attributes
tf.instance.DC=Vout
tf.instance.RF=p.EL_RF # not needed, but may be useful notation
tf.instance.X=X
tf.instance.Y=Y
tf.instance.Z=Z
tf.instance.check=True
if update==True:
name=trap
print('Saving '+name+' as a data structure...')
output = open(name,'wb')
pickle.dump(tf,output)
output.close()
return tf.instance.DC
def set_voltages():
"""Provides the DC voltages for all DC electrodes to be set to using the parameters and voltage controls from analyze_trap.
Outputs an array of values to set each electrode and used as VMULT for dc_potential in post_process_trap.
The Ui and Ei values control the weighting of each term of the multipole expansion.
In most cases, multipoleControls will be True, as teh alternative involves more indirect Mathiew calculations.
Nikos, July 2009, cleaned up October 2013
William Python 2014"""
#0) set parameters
from project_parameters import savePath,name,multipoleControls,reg,driveFrequency,E,U1,U2,U3,U4,U5,ax,az,phi
import numpy as np
import pickle
trap = savePath+name+'.pkl'
file = open(trap,'rb')
tf = pickle.load(file)
file.close()
V,X,Y,Z=tf.instance.DC,tf.instance.X,tf.instance.Y,tf.instance.Z
tc=tf.configuration
el = []
#1) check if trap_knobs has been run yet, creating multipoleControl and multipoleKernel
if tc.trap_knobs != True:
return 'WARNING: You must run trap_knobs first!'
#2a) determine electrode voltages directly
elif multipoleControls: # note plurality to contrast from attribute
inp = np.array([E[0], E[1], E[2], U1, U2, U3, U4, U5]).T
el = np.dot(tc.multipoleControl,inp) # these are the electrode voltages
#2b) determine electrode volages indirectly
else:
charge = tc.charge
mass = tc.mass
V0 = mass*(2*np.pi*frequencyRF)**2/charge
U2 = az*V0/8
U1 = U2+ax*V0/4
U3 = 2*U1*np.tan(2*np.pi*(phi+tc.thetaRF)/180)
U1p= np.sqrt(U1**2+U3**2/2)
U4 = U1p*tc.Qrf[4]/tc.Qrf[1]
U5 = U1p*tc.Qrf[5]/tc.Qrf[1]
inp = np.array([E[0], E[1], E[2], U1, U2, U3, U4, U5]).T
mCf = tc.multipoleCoefficients[1:9,:]
el = np.dot(mCf.T,inp) # these are the electrode voltages
el = np.real(el)
#3) regularize if set to do so
if reg:
C = el
Lambda = np.linalg.lstsq(tc.multipoleKernel,C)
Lambda=Lambda[0]
el = el-(np.dot(tc.multipoleKernel,Lambda))
return el
def d_e(Ei,Vdc,data,x,y,z,X,Y,Z,Zval):
"""find the miscompensation distance, d_e, for the rf and dc potential
given in the main program, in the presence of stray field Ei"""
from all_functions import exact_saddle
import numpy as np
dm = Ei
E1 = dm[0]
E2 = dm[1]
E3 = dm[2]
Vl = Vdc-E1*x-E2*y-E3*z
from all_functions import plot_potential
[Xrf,Yrf,Zrf] = exact_saddle(data.EL_RF,X,Y,Z,2,Zval)
#[Xdc,Ydc,Zdc] = exact_saddle(data.EL_RF,X,Y,Z,3)
[Idc,Jdc,Kdc] = find_saddle(data.EL_RF,X,Y,Z,3) # no saddle point with exact
Xdc,Ydc,Zdc=X[Idc],Y[Jdc],Z[Kdc]
f = np.sqrt((Xrf-Xdc)**2+(Yrf-Ydc)**2+(Zrf-Zdc)**2)
return f
def pfit(trap,E,driveFrequence,driveAmplitude):
"""find the secular frequencies, tilt angle, and position of the dc
saddle point for given combined input parameters.
fx,fy,fz are the secular frequencies
theta is the angle of rotation from the p2d transformation (rotation)
Depth is the distance between the potential at the trapping position and at the escape point
Xdc,Ydc,Zdc are the coordinates of the trapping position
Xe,Ye,Ze are the coordinates of the escape position
William Python February 2014."""
#0) open trap