-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathyao.i
5054 lines (4339 loc) · 174 KB
/
yao.i
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
/*
* yao.i
*
* This file is part of the yao package, an adaptive optics simulation tool.
*
* Copyright (c) 2002-2021, Francois Rigaut
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details (to receive a copy of the GNU
* General Public License, write to the Free Software Foundation, Inc., 675
* Mass Ave, Cambridge, MA 02139, USA).
*
*/
extern aoSimulVersion, aoSimulVersionDate;
aoSimulVersion = yaoVersion = aoYaoVersion = yao_version = "5.14.2";
aoSimulVersionDate = yaoVersionDate = aoYaoVersionDate = "2024jun25";
write,format=" Yao version %s, Last modified %s\n",yaoVersion,yaoVersionDate;
// find and include yao.conf now if any:
Y_CONF = get_env("Y_CONF");
y_user = streplace(Y_USER,strfind("~",Y_USER),get_env("HOME"))
if (noneof(Y_CONF)) \
Y_CONF = "./:"+y_user+":"+pathform(_(y_user,Y_SITES,Y_SITE)+"conf/");
path2conf = find_in_path("yao.conf",takefirst=1,path=Y_CONF);
if (!is_void(path2conf)) {
path2conf = dirname(path2conf)+"/";
write,format=" Found and included yao.conf in %s\n",path2conf;
require,path2conf+"yao.conf";
}
// before we do anything else (to avoid forking a large process),
// let's try to determine what OS we are in:
//f = popen("uname",0);
//rep = ""; read,f,format="%s",rep;
//close,f;
//rep = strcase(0,rep);
//if ( (rep=="darwin") || (rep=="linux") ) os_env = rep; else os_env="unknown";
os_env="unknown";
plug_in,"yao";
require,"yao_utils.i";
require,"yao_fast.i";
require,"yao_wfs.i";
require,"yao_dm.i";
require,"aoutil.i";
require,"yao_gui.i";
require,"utils.i";
require,"yao_newfits.i";
require,"yao_util.i";
require,"yao_lgs.i";
require,"turbulence.i";
require,"plot.i"; // in yorick-yutils
require,"yao_structures.i";
require,"yaodh.i";
include, "lapack.i", 2; // load lapack if it exists
func LUsolve2(A,b){
/* DOCUMENT LUsolve2(a, b)
or a_inverse= LUsolve2(a)
returns the solution x of the matrix equation:
A(,+)*x(+) = B
using lpk_gesv in lapack for the matrix inversion
If A is an n-by-n matrix then B must have length n, and the returned
x will also have length n.
SEE ALSO: LUsolve, lpk_gesv
*/
local b;
// b can be a matrix or a vector. If it does not exist, make it the identity matrix
if (b == []){
nr = (dimsof(A))(2);
b = unit(nr);
if (typeof(A) != "double"){
b = float(unit(nr));
}
}
return lpk_gesv(A,b);
}
// can't call use_sincos_approx directly in yao.conf, as not defined, work around:
if (use_sincos_approx_default!=[]) use_sincos_approx,use_sincos_approx_default;
// compatibility with GUI (yaopy.i)
func null (arg,..) { return 0; }
// set up for notify. Disabled by default. Set "use_notify" to enable
// we have to do that as soon as possible to avoid forking large a process
// this spawned bash session can actually be used for other purposes if
// needed.
func on_bash_out(msg) { write,msg; }
func notify(msg) {
if (!use_notify) return; // allows to turn off/on notify within the session
bash,swrite(format="notify-send -i %s \"%s\"\n",icon,msg);
}
icon = "/home/frigaut/Pictures/logos/yao_64_inv.png";
if (use_notify) bash = spawn("/bin/bash",on_bash_out); else bash=null;
func parse_yao_version(ver)
{
extern yao_major_version,yao_minor_version;
tmp = strtok(ver,".",3);
yao_major_version = tonum(tmp(1));
yao_minor_version = tonum(tmp(2));
}
parse_yao_version,yao_version;
// import fftw wisdom file:
if (fftw_wisdom_file==[]) fftw_wisdom_file=Y_USER+"fftw_wisdom_file.dat";
if (_import_wisdom(expand_path(fftw_wisdom_file))){
write,format=" Warning: Can't read FFTW wisdom from %s\n",expand_path(fftw_wisdom_file);
write, "Run init_fftw_wisdom to create a new file";
}
// All below is designed to be overwritten by appropriate values
// in yaopy.i when using yao through the GUI
pyk_error = pyk_info = pyk_warning = null;
gui_message = gui_message1 = gui_progressbar_frac = gui_progressbar_text = null;
clean_progressbar = gui_show_statusbar1 = gui_hide_statusbar1 = pyk_flush = null;
if (YAO_SAVEPATH==[]) YAO_SAVEPATH = get_cwd();
//----------------------------------------------------
func comp_dm_shape_init(nm)
{
extern wpupil;
if (numberof(wpupil)!=ndm) wpupil = array(pointer,ndm);
wpupil(nm) = &long(where((abs(*dm(nm)._def))(,,sum)));
}
func comp_dm_shape(nm,command,extrap=)
/* DOCUMENT comp_dm_shape(nm,command,extrap=)
Fast compute of DM #nm shape from a command vector.
Branch over _dmsum or _dmsumelt according to case.
nm: DM yao #
command: POINTER to a float vector containing the commands
length of vector = numberof(*dm(nm)._command) = dm(nm)._nact
extrap : Compute for extrapolated only (otherwise compute for valid only)
so that to compute valid + extrap, you have to make 2 calls,
one with and one without the extrap keyword set.
SEE ALSO:
*/
{
if (dmsum_use_new&&(wpupil==[])) for (i=1;i<=ndm;i++) comp_dm_shape_init,i;
if (typeof(*command)!="float") error,"command is not float";
n1 = dm(nm)._n1; n2 = dm(nm)._n2; nxy = int(n2-n1+1);
sphase = array(float,[2,nxy,nxy]);
if (!is_set(extrap)) {
// pegged valid actuators (right now, set to position 0):
if (dm(nm).pegged) {
com = *command;
com(*dm(nm).pegged) = 0.0f;
command = &com; // this way this does not go up in integrated commands
}
if (dm(nm)._flat_command) {
com = *command;
com -= float(*dm(nm)._flat_command);
command = &com;
}
if (dm(nm).elt == 1) { //use fast dm shape computation
_dmsumelt, dm(nm)._def, dm(nm)._eltdefsize, dm(nm)._eltdefsize, int(dm(nm)._nact),
dm(nm)._i1, dm(nm)._j1, command, &sphase,nxy,nxy;
} else { // use standard
if (dmsum_use_new) _dmsum2, dm(nm)._def, wpupil(nm), \
numberof(*wpupil(nm)), dm(nm)._nact, command, &sphase, numberof(sphase);
else _dmsum, dm(nm)._def, nxy, nxy, dm(nm)._nact, command, &sphase;
// }
}
} else { // extrapolated actuators
// pegged extrapolated actuators (right now, set to position 0):
if (dm(nm).epegged) {
com = *command;
com(*dm(nm).epegged) = 0.0f;
command = &com; // this way this does not go up in integrated commands
}
if (dm(nm).elt == 1) { //use fast dm shape computation
_dmsumelt, dm(nm)._edef, dm(nm)._eltdefsize, dm(nm)._eltdefsize, int(dm(nm)._enact),
dm(nm)._ei1, dm(nm)._ej1, command, &sphase,nxy,nxy;
} else { // use standard
if (dmsum_use_new) _dmsum2, dm(nm)._edef, wpupil(nm), \
numberof(*wpupil(nm)), dm(nm)._enact, command, &sphase, numberof(sphase);
else _dmsum, dm(nm)._edef, nxy, nxy, dm(nm)._enact, command, &sphase;
}
}
// temporary method for shifting DMs/influence functions
// one cannot anymore use the straight (*dm._def)(,,sum),
// but instead should always use comp_dm_shape.
if (dm(nm)._puppixoffset!=[]) {
sphase = roll(sphase,dm(nm)._puppixoffset);
}
if (dm(nm).disjointpup) { // we have to filter by disjointpup(,,nm)
sphase *= disjointpup(dm(nm)._n1:dm(nm)._n2,dm(nm)._n1:dm(nm)._n2,nm);
}
return sphase;
}
//----------------------------------------------------
func control_screen(i,init=)
/* DOCUMENT control_screen(i,init=)
While the loop is running, brings up another graphic window in which
some loop parameters are displayed. I rarely use this feature anymore.
i is the loop counter. Not intended for use by the end user.
SEE ALSO:
*/
{
local x0,y0,x,y;
y0 = 0.80;
x0 = 0.150;
ygstep = 0.03;
mygstep = 0.022;
sygstep = 0.017;
csize = 12;
if ( (xft!=[]) && (xft()==1) ) {
csfont = "Courier:antialias=0";
} else csfont="courier";
/* y0 = 0.86;
x0 = 0.05;
ygstep = 0.037;
mygstep = 0.030;
sygstep = 0.025;
csize = 18;
*/
if (is_set(init) || !window_exists(2)) {
// dheight = (nwfs+target._nlambda+1)*sygstep + 10*ygstep;
// dheight = long(dheight/0.77*570);
if (window_exists(2)) winkill,2; // make sure
window,2,width=410,height=320,style="letter.gs",wait=1,dpi=70;
// window,2,width=570,height=dheight,style="letter.gs",wait=1,dpi=70;
limits,0.,1.,0.,1.;
progress_bar,0,pbid1,init=[x0,y0-ygstep,x0+0.25,y0-ygstep+0.015];
if (is_set(init)) {
window_select,0;
return;
}
}
window,2;
fma;
y = y0;
if (!remainingTimestring) remainingTimestring="N/A";
plt,sim.name+" / Time left: "+remainingTimestring,x0,y,tosys=1,\
height=csize,justify="LA";
y -= ygstep;
it = swrite(format="%d/%d iterations",i,loop.niter);
plt,it,x0+0.27,y,tosys=1,height=csize,justify="LA",font=csfont;
y -= ygstep;
progress_bar,i*100./loop.niter,pbid1;
// s = "WFS rms Tip Tilt ";
s = "WFS Tip Tilt ";
if (anyof(wfs.correctUpTT)) {
s = s+"UpTip UpTilt ";
if (anyof(wfs.centGainOpt)) {
s = s+"CentG ";
}
}
plt,s,x0,y,tosys=1,height=csize,justify="LA",font=csfont;
y -= mygstep;
for (i=1;i<=nwfs;i++) {
s = swrite(format="%3i % 6.3f % 6.3f ",i,
wfs(i)._lastvalidtt(1),wfs(i)._lastvalidtt(2));
if (anyof(wfs.correctUpTT)) {
if (wfs(i).correctUpTT) {
s = s+swrite(format="% 6.3f % 6.3f ",
wfs(i)._upttcommand(1),wfs(i)._upttcommand(2));
} else {
s = s+" - - ";
}
if (anyof(wfs.centGainOpt)) {
if (wfs(i).centGainOpt) {
s = s+swrite(format="% 6.3f ",wfs(i)._centroidgain);
} else {
s = s+"- ";
}
}
}
plt,s,x0,y,tosys=1,height=csize,justify="LA",font=csfont;
y -= sygstep;
}
// print out TTM command
wtt = where(dm.type == "tiptilt");
if (numberof(wtt) != 0) {
wtt = wtt(0);
s = swrite(format="TT Mirror: % 6.3f % 6.3f",(*dm(wtt)._command)(1),
(*dm(wtt)._command)(2));
y -= sygstep;
plt,s,x0,y,tosys=1,height=csize,justify="LA",font=csfont;
y -= ygstep;
}
// print out Strehls:
plt,"Strehl Ratio Lambda Avg rms Min Max",x0,y,tosys=1,height=csize,
justify="LA",font=csfont;
y -= sygstep;
for (jl=1;jl<=target._nlambda;jl++) {
strehlle = imav(max,max,,jl)/sairy/(niterok+1e-5);
s = swrite(format="Since Start %6.3f %6.3f %6.3f %6.3f %6.3f",
(*target.lambda)(jl),strehlle(avg),strehlle(rms),
min(strehlle),max(strehlle));
plt,s,x0,y,tosys=1,height=csize,justify="LA",font=csfont;
y -= sygstep;
if (jl == target._nlambda) {
strehlse = im(max,max,)/sairy;
s = swrite(format="Instantaneous %6.3f %6.3f %6.3f %6.3f %6.3f",
(*target.lambda)(jl),strehlse(avg),strehlse(rms),
min(strehlse),max(strehlse));
plt,s,x0,y,tosys=1,height=csize,justify="LA",font=csfont;
y -= sygstep;
}
}
window_select,0;
}
//----------------------------------------------------
func mcao_rayleigh(nwfs,xsubap,ysubap,fov,aspp,zenith)
/* DOCUMENT mcao_rayleigh(nwfs,xsubap,ysubap,fov,aspp,zenith)
Computes the rayleigh backscattering from other LGS beams (fratricide)
Called from shwfs_init()
SEE ALSO: shwfs_init
*/
{
extern wfs;
as2rd = dtor/3600.;
cobs = 0;
zenith *= dtor;
// position of GS/WFS in arcsec:
w = where(wfs._gsalt > 0);
ns = where(w == nwfs)(1);
xwfs = wfs(w).gspos(1,);
ywfs = wfs(w).gspos(2,);
nbeams = numberof(xwfs);
// note that the incoming xsubap and ysubap have been switched!
// hence
lltx = wfs(w).LLTxy(2,);
llty = wfs(w).LLTxy(1,);
if (wfs(w)(ns).LLT1overe2diam==0) {wfs(w)(ns).LLT1overe2diam=0.3;}
beamdiameter = wfs(w)(ns).LLT1overe2diam; // Gaussian laser beam FWHM [m]
laserlambda = wfs(w)(ns).lambda*1e-6; //589e-9;
diamsubap = tel.diam/wfs(w)(ns).shnxsub; // side of a subaperture [m]
r0 = (tel.diam/atm.dr0at05mic)*cos(zenith)^0.6;
seeing = laserlambda/r0/4.848e-6;
d = 1e-2; // linear size of aperture for flux (/cm^2) <???
altsod = wfs(w)(ns)._gsalt;
fwhmsod = wfs(w)(ns)._gsdepth;
// definitions of the image array to return to caller
dim = long(ceil(fov/aspp));
imrayl = array(float,[2,dim,dim]);
imstar = array(float,[2,dim,dim]);
// looking at GS #n with WFS #n -> some angle
phin = sqrt(xwfs(ns)^2.+ywfs(ns)^2.)*as2rd;
thetan = atan(xwfs(ns),ywfs(ns));
// range vector to sample h (for Rayleigh only)
rvec = spanl(1000,altsod,50);
// definitions for sodium GS:
// range vector for sodium:
rvecsod = span(altsod-fwhmsod,altsod+fwhmsod,20);
// loop on beams
for (beam=1;beam<=nbeams;beam++) {
// define "beam" position angles
phib = sqrt(xwfs(beam)^2.+ywfs(beam)^2.)*as2rd;
thetab = atan(xwfs(beam),ywfs(beam));
// loop on altitude for RAYLEIGH
for (i=1;i<=numberof(rvec)-1;i++) {
// range
r = (rvec(i+1)+rvec(i))/2.;
// altitude
z = r*cos(zenith);
// delta range
deltar = rvec(i+1)-rvec(i);
// fit to the lidar equation:
sbnr = 16.12*exp(-z*0.14177e-3)*1e-6;
// total number of photons received per cm^2 and period (800Hz)
rayleigh = wfs(w)(beam).laserpower/(6.62e-34*3e8/589e-9)*sbnr*d^2/(4*pi*r^2.)*deltar*loop.ittime*wfs(w)(ns).optthroughput;
if (rayleigh_fudge) rayleigh *= rayleigh_fudge;
// compute position angles of the beam center for this altitude
alpha = sin(phib)*cos(thetab)-sin(phin)*cos(thetan) - (xsubap-lltx(beam))/r + (xsubap-lltx(beam))/altsod;
beta = sin(phib)*sin(thetab)-sin(phin)*sin(thetan) - (ysubap-llty(beam))/r + (ysubap-llty(beam))/altsod;
alpha /= 4.848e-6; // in arcsec
beta /= 4.848e-6;
if (sim.debug > 3) {
write,format="range = %f, alpha = %f, beta = %f\n",r,alpha,beta;
}
// generate gaussian:
fwhm = beamdiameter/r/as2rd; // in arcsec
// blur due to finite range of this layer of rayleigh scatering
blur = (altsod - r)/altsod*diamsubap/r/4.848e-6;
fwhm = sqrt(fwhm^2. + seeing^2.+blur^2.);
g = makegaussian(dim,fwhm/aspp,xc=0.5+dim/2+alpha/aspp,yc=0.5+dim/2+beta/aspp,norm=1);
if (cobs) {
fwhmobs = fwhm/2;
fwhmobs = sqrt(fwhmobs^2. + seeing^2.);
gobs = makegaussian(dim,fwhmobs/aspp,xc=0.5+dim/2+alpha/aspp,yc=0.5+dim/2+beta/aspp);
gobs = gobs*max(g); g = g-gobs;
}
// add contribution from this slab. Correctly normalized
// in photons/cm^2/exptime/laser_power/telescope+system_throughput
imrayl += g*rayleigh;
}
// loop on altitude for SODIUM
// Na return detected on WFSCCD in ph/cm^2/exptime/laser_power/telescope+system_throughput:
nPhotonFromSodStar = wfs(w)(beam).laserpower*gs.lgsreturnperwatt*loop.ittime*
cos(zenith)*wfs(w)(ns).optthroughput;
sodprofile = exp(-((rvecsod-altsod)/(fwhmsod/2.))^4.);
sodprofile = sodprofile/sum(sodprofile)*nPhotonFromSodStar;
for (i=1;i<=numberof(rvecsod)-1;i++) {
// range
r = rvecsod(i);
sodium = sodprofile(i);
// compute position angles of the beam center for this altitude
alpha = sin(phib)*cos(thetab)-sin(phin)*cos(thetan) - (xsubap-lltx(beam))/r + (xsubap-lltx(beam))/altsod;
beta = sin(phib)*sin(thetab)-sin(phin)*sin(thetan) - (ysubap-llty(beam))/r + (ysubap-llty(beam))/altsod;
alpha /= 4.848e-6; // in arcsec
beta /= 4.848e-6;
if (sim.debug > 3) {
write,format="range = %f, alpha = %f, beta = %f\n",r,alpha,beta;
}
// generate gaussian:
fwhm = beamdiameter/r/as2rd; // in arcsec
// here I'll have to take the defocus of range r into account
fwhm = sqrt(fwhm^2. + seeing^2.);
g = makegaussian(dim,fwhm/aspp,xc=0.5+dim/2+alpha/aspp,yc=0.5+dim/2+beta/aspp,norm=1);
// add contribution from this slab. Correctly normalized
// in photons/cm^2/exptime/laser_power/telescope+system_throughput
imstar += g*sodium;
}
if (sim.debug > 3) {
fma;
pli,imrayl+imstar,-dim/2*aspp,-dim/2*aspp,+dim/2*aspp,+dim/2*aspp;
pause,20;
}
}
return [imrayl,imstar];
}
//----------------------------------------------------
func do_imat(disp=)
/* DOCUMENT do_imat(disp=)
Measure the interaction matrix.
Each actuator are actuated in a row, a measurement vector is taken
and placed into the iMat. The reference (for phase=0) is subtracted.
disp = set to display stuff as it goes.
This routine uses:
- dm._nact, _n1, _n2, _def (extern)
- mircube (extern)
This routine calls:
- mult_wfs_int_mat
This routine sets:
- iMat (extern)
SEE ALSO: prep_svd, build_cmat
*/
{
extern wfs;
gui_progressbar_frac,0.;
gui_progressbar_text,"Doing interaction matrix";
if (mat.method == "mmse-sparse"){
extern MR, MN;
MR = mat.sparse_MR;
MN = mat.sparse_MN;
}
indexDm = array(long,2,ndm);
indexDm(,1) = [1,dm(1)._nact];
for (nm=2;nm<=ndm;nm++) {
indexDm(,nm) = [indexDm(2,nm-1)+1,sum(dm(1:nm)._nact)];
}
ntot = sum(dm._nact);
ncur=1;
if (disp) { plsys,1; animate,1; }
// save state of noise/nintegcycle/etc: everything that is not desired
// when doing the iMat:
store_noise_etc_for_imat,noise_orig, cycle_orig, kconv_orig, \
skyfluxpersub_orig, bckgrdcalib_orig, bias_orig, \
flat_orig,darkcurrent_orig,use_sincos_approx_orig,\
rayleigh_orig;
// sync forks if needed:
if ( (anyof(wfs.type=="hartmann"))&&(anyof(wfs.svipc>1))) s = sync_wfs_forks();
// for imat ETA:
tic; ndone=0;
// Loop on each mirror:
for (nm=1;nm<=ndm;nm++) {
n1 = dm(nm)._n1;
n2 = dm(nm)._n2;
// if (sim.verbose>1) {write,format="\rDoing DM# %d, actuator %s",nm," ";}
if (sim.verbose) write,"";
subsys = dm(nm).subsystem;
// Loop on each actuator:
command = array(float,dm(nm)._nact);
for (i=1;i<=dm(nm)._nact;i++) {
ncur++;
gui_progressbar_frac,float(ncur)/ntot;
gui_progressbar_text,\
swrite(format="Doing interaction matrix, DM#%d, actuator#%d",nm,i);
if (sim.verbose) {
eta = (ndone?(ntot-ndone)*tac()/ndone:0.0f);
write,format="\rDoing DM# %d, actuator %d/%d, ETA %.1fs",\
nm,i,dm(nm)._nact,eta;
}
// if (sim.verbose>1) {write,format="%d ",i;}
mircube *= 0.0f; command *= 0.0f;
command(i) = float(dm(nm).push4imat);
mircube(n1:n2,n1:n2,nm) = comp_dm_shape(nm,&command);
if (mat.method != "mmse-sparse"){
if (!dm(nm).ncp){
// Fill iMat (reference vector subtracted in mult_wfs_int_mat):
iMat(,i+indexDm(1,nm)-1) = mult_wfs_int_mat(disp=disp,subsys=subsys)/dm(nm).push4imat;
}
} else {
if (!dm(nm).ncp){
rcobuild, iMatSP, float(mult_wfs_int_mat(disp=disp,subsys=subsys)/dm(nm).push4imat), mat.sparse_thresh;
} else {
rcobuild, iMatSP, float(mult_wfs_int_mat(disp=disp,subsys=subsys)/dm(nm).push4imat*0.), mat.sparse_thresh;
}
}
// display, if requested:
// WFS spots:
if (is_set(disp)) {
fma;
plt,escapechar(swrite(format="YAO %s | %s | %s",aoSimulVersion,parprefix,sim.name)),0.01,0.227,tosys=0;
if (!allof(wfs.shmethod ==1)) {
if (wfs_display_mode=="spatial") {
disp2d,wfs._dispimage,wfs.pupoffset(1,),wfs.pupoffset(2,),2;
mypltitle,"WFSs spots (spatial mode)",[0.,-0.005],height=12;
} else {
disp2d,wfs._dispimage,wfs.gspos(1,),wfs.gspos(2,),2;
mypltitle,"WFSs spots",[0.,-0.005],height=12;
}
}
if ((nm==1) && (i==1)) { plsys,2; limits,square=1; limits; }
// mirror surface
plsys,3;
limits,square=1;
if (mergedms4disp) { //e.g. GMT case
tmp = mircube(,,sum);
pli,(tmp-min(tmp))*ipupil,1,0.,2,1.;
range,0.25,0.75;
} else {
pli,(mircube(,,1)-min(mircube(,,1)))*ipupil,1,0.,2,1.;
if (ndm==1) range,0.25,0.75;
for (jj=2;jj<=ndm;jj++) {
if (dm(jj).alt==0) {
pli,(mircube(,,jj)-min(mircube(,,jj)))*ipupil,jj,0.,jj+1,1.;
} else {
pli,(mircube(,,jj)-min(mircube(,,jj))),jj,0.,jj+1,1.;
}
}
}
myxytitles,"","DM(s)",[0.010,0.],height=12;
if ((dm(nm).type == "aniso") && (sim.debug >= 2)) hitReturn;
} // end of display section
if (sleep) usleep,sleep;
if ((sim.debug>=3) && (i==(dm(nm)._nact/2))) hitReturn;
ndone++;
}
if (sim.verbose) {write," ";}
}
// restore original values to WFS structure:
restore_noise_etc_for_imat,noise_orig, cycle_orig, kconv_orig, \
skyfluxpersub_orig,bckgrdcalib_orig, bias_orig, \
flat_orig,darkcurrent_orig,use_sincos_approx_orig,\
rayleigh_orig;
// sync forks if needed:
if ( (anyof(wfs.type=="hartmann"))&&(anyof(wfs.svipc>1))) s = sync_wfs_forks();
// Display if needed:
if ((mat.method != "mmse-sparse") && ((sim.debug>=1) || (disp == 1))) {
tv,-iMat,square=1;
mypltitle,"Interaction Matrix",[0.,-0.005],height=12;
if (sim.debug >= 1) typeReturn;
}
if (disp) {plsys,1; animate,0; }
clean_progressbar;
}
func store_noise_etc_for_imat(&noise_orig, &cycle_orig, &kconv_orig,
&skyfluxpersub_orig, &bckgrdcalib_orig,
&bias_orig, &flat_orig, &darkcurrent_orig,
&use_sincos_approx_orig,&rayleigh_orig)
{
extern wfs;
noise_orig = cycle_orig = kconv_orig = array(0n,nwfs);
darkcurrent_orig = rayleigh_orig = array(float,nwfs);
skyfluxpersub_orig = bckgrdcalib_orig = bias_orig = flat_orig = array(pointer,nwfs);
use_sincos_approx_orig = [use_sincos_approx()]; // & need a vector
use_sincos_approx,0;
for (ns=1;ns<=nwfs;ns++) {
// Impose noise = rmsbias = rmsflat = 0 for interaction matrix measurements
noise_orig(ns) = wfs(ns).noise;
wfs(ns).noise = 0n;
cycle_orig(ns) = wfs(ns).nintegcycles;
wfs(ns).nintegcycles = 1n;
darkcurrent_orig(ns) = wfs(ns).darkcurrent;
wfs(ns).darkcurrent = float(0.);
rayleigh_orig(ns) = wfs(ns).rayleighflag;
wfs(ns).rayleighflag = 0n;
if (*wfs(ns)._skyfluxpersub!=[]) {
skyfluxpersub_orig(ns) = &(*wfs(ns)._skyfluxpersub);
*wfs(ns)._skyfluxpersub *= 0;
}
if (*wfs(ns)._bckgrdcalib!=[]) {
bckgrdcalib_orig(ns) = &(*wfs(ns)._bckgrdcalib);
*wfs(ns)._bckgrdcalib *= 0;
}
if (wfs(ns).type == "hartmann" ) {
kconv_orig(ns) = wfs(ns)._kernelconv;
wfs(ns)._kernelconv = 1n;
bias_orig(ns) = &(*wfs(ns)._bias);
*wfs(ns)._bias = *wfs(ns)._bias*0.0f;
flat_orig(ns) = &(*wfs(ns)._flat);
*wfs(ns)._flat = *wfs(ns)._flat*0.0f+1.0f;
}
}
}
func restore_noise_etc_for_imat(noise_orig, cycle_orig, kconv_orig,
skyfluxpersub_orig,bckgrdcalib_orig,
bias_orig, flat_orig, darkcurrent_orig,
use_sincos_approx_orig,rayleigh_orig)
{
extern wfs;
use_sincos_approx,use_sincos_approx_orig(1);
for (ns=1;ns<=nwfs;ns++) {
wfs(ns).noise = noise_orig(ns);
wfs(ns).darkcurrent = darkcurrent_orig(ns);
wfs(ns).rayleighflag = rayleigh_orig(ns);
wfs(ns).nintegcycles = cycle_orig(ns);
if (*wfs(ns)._skyfluxpersub!=[]) \
wfs(ns)._skyfluxpersub = skyfluxpersub_orig(ns);
if (*wfs(ns)._bckgrdcalib!=[]) \
wfs(ns)._bckgrdcalib = bckgrdcalib_orig(ns);
if (wfs(ns).type == "hartmann" ) {
wfs(ns)._kernelconv = kconv_orig(ns);
wfs(ns)._bias = bias_orig(ns);
wfs(ns)._flat = flat_orig(ns);
}
}
}
//----------------------------------------------------
func prep_svd(imat,subsystem,svd=,disp=)
/* DOCUMENT prep_svd(imat,subsystem,svd=,disp=)
Does the SVD decomposition and fill out the modToAct (V)
and mesToMod (UT) matrices for further use by build_cmat()
imat = the imat to inverse
disp = set if display is required.
This routine uses:
- imat (input)
This routine calls:
- SVdec
This routine sets:
- eigenvalues (extern)
- modToAct (extern)
- mesToMod (extern)
Note: The Mode-to-Actuator (modToAct) matrix has to be used as follow:
modes-coef = actToMod(,+) * command-coef(+)
SEE ALSO: do_imat, build_cmat
*/
{
// Define some extern variables:
extern modToAct,mesToMod,eigenvalues;
// Decompose to prepare inversion:
if (sim.verbose>1) {write,"Doing SVD\n";}
eigenvalues = SVdec(imat,u,vt);
// Some debug output if needed:
if (sim.verbose) {
write,format="Smallests 2 normalized eigenvalues = %f",
eigenvalues(-1)/max(eigenvalues),eigenvalues(0)/max(eigenvalues);
}
if (sim.verbose>1) {
write,"Normalized eigenvalues:";
write,eigenvalues/max(eigenvalues);
th = 1.0f/(*mat.condition)(subsystem);
do {
plot,eigenvalues/max(eigenvalues);
plg,array(1/(*mat.condition)(subsystem),numberof(eigenvalues)),color="red",type=2;
limits,square=0;
mypltitle,"Normalized eigenvalues",[0.,-0.005],height=12;
if (yaopy) break;
if (is_set(svd)) {
th = kinput("New Threshold ? (return to continue)",th);
change = ( (th==1/(*mat.condition)(subsystem))? 0:1);
if (change) (*mat.condition)(subsystem) = 1/th;
}
} while (change == 1);
if (!yaopy) typeReturn;
}
modToAct = transpose(vt);
// actToMod = LUsolve(modToAct);
mesToMod = transpose(u); // used to be called ut
// Some debug display if needed:
if (sim.debug>=2) {
tv,modToAct;
mypltitle,"modToAct Matrix",[0.,-0.005],height=12;
if (!yaopy) typeReturn;
if (sim.debug>=3) {
tv,modToAct(,+)*modToAct(,+);
mypltitle,"modToAct(,+)*modToAct(,+)",[0.,-0.005],height=12;
if (!yaopy) typeReturn;
}
tv,mesToMod;
mypltitle,"mesToMod Matrix",[0.,-0.005],height=12;
if (!yaopy) typeReturn;
if (sim.debug>=3) {
tv,mesToMod(,+)*mesToMod(,+);
mypltitle,"mesToMod(,+)*mesToMod(,+)",[0.,-0.005],height=12;
if (!yaopy) typeReturn;
}
}
}
//----------------------------------------------------
// func svdmodes_variance(void)
// {
// prepzernike,sim._size,sim.pupildiam,sim._size/2.+0.5,sim._size/2.+0.5;
// fma; pli,zernike(1)+ipupil
// }
//----------------------------------------------------
func build_cmat(condition,modalgain,subsystem=,all=,nomodalgain=,disp=)
/* DOCUMENT build_cmat(condition,modalgain,subsystem=,all=,nomodalgain=,disp=)
Build the command matrix from V,UT, the eigenvalues and the modal gains
F.Rigaut, June 17,2002
condition = Filter eigenvalues ev (and modes) for max(ev)/ev > condition
modalgain = vector of system mode gains to pre-multiply the control matrix
with. rarely used as these modes are not generally natural
w.r.t. the turbulence.
all = if not set, one (1) mode is forced to be discarded (useful if regular
AO system using a DM with a piston component and condition number
too large). Normally, set all=1.
nomodalgain = if set, the modal gain are not taken into account.
disp = set to display stuff.
This routine uses:
- dm._def, _nact, _n1, _n2 (extern)
- ipupil (extern)
- mat.condition (extern)
- modalgain (extern)
- eigenvalues (extern)
- modToAct (extern)
- mesToMod (extern)
This routine calls:
- Nothing
This routine sets:
- NModesControlled (extern)
This routine returns:
- cMat
SEE ALSO: do_imat, prep_svd
*/
{
extern NModesControlled;
neigen = numberof(eigenvalues);
mev = array(float,neigen,neigen);
mask = ((eigenvalues/max(eigenvalues)) > (1./condition));
if (numberof(ev_user_mask)==numberof(mask)) mask = (mask|ev_user_mask);
if (is_set(nomodalgain)) {
ev = eigenvalues;
} else {
ev = eigenvalues/modalgain;
}
// Including the mode gains and eigenvalues here:
for (i=1;i<=neigen;i++) {
if (mask(i) == 1) {mev(i,i)=1./ev(i);}
}
// the last eigenvalue is filtered except if all is set.
if (!is_set(all)) {mev(0,0) = 0.;}
NModesControlled = sum(mev != 0.);
// Compute the Command matrix:
cmat = (modToAct(,+)*mev(+,))(,+) * mesToMod(+,);
if (sim.verbose) {
write,long(clip(sum(mask == 0),1-long(is_set(all)),)),
format="%i modes discarded in the inversion\n";
}
//=========================================
// DISPLAY OF THE FILTERED MODES:
// BEGINNING OF DISPLAY, NOTHING IMPORTANT
// UNTIL "END OF DISPLAY"
//=========================================
if ((sim.debug>=1) && (disp >= 1) ) {
n1 = (sim._size-sim.pupildiam)/2-2;
n2 = (sim._size+sim.pupildiam)/2+2;
nxy = n2-n1+1;
sswfs = where(wfs.subsystem == subsystem);
cubphase = array(float,[3,nxy,nxy,numberof(sswfs)]);
subpos = wfs(sswfs).gspos;
disp2d,cubphase,subpos(1,),subpos(2,),1,zoom=0.9,init=1;
// find out to where is DM N in this subsystem "modToAct" matrix:
ssdm = where(dm.subsystem == subsystem);
// indexDm = array(long,[2,2,numberof(ssdm)]);
indexDm = array(long,[2,2,ndm]);
index = 0;
for (nm=1;nm<=ndm;nm++) {
if (dm(nm).subsystem == subsystem) {
indexDm(,nm) = [index+1,index+dm(nm)._nact];
index = index+dm(nm)._nact;
}
}
write,"Displaying filtered modes, type 'q' to exit display";
// loop on modes
mircube *= 0.0f;
for (i=neigen;i>=NModesControlled+1;i--) {
// loop over dm to build mircube
for (nm=1; nm<=ndm; nm++) {
if (dm(nm).subsystem == subsystem) {
n1 = dm(nm)._n1; n2 = dm(nm)._n2; nxy = n2-n1+1;
scommand = float(modToAct(indexDm(1,nm):indexDm(2,nm),i));
mircube(n1:n2,n1:n2,nm) = comp_dm_shape(nm,&scommand);
}
}
// Loop over WFS to get integrated phase
n1 = (sim._size-sim.pupildiam)/2-2;
n2 = (sim._size+sim.pupildiam)/2+2;
nxy = n2-n1+1;
nnss = 1;
for (ns=1;ns<=nwfs;ns++) {
if (wfs(ns).subsystem == subsystem) {
phase = get_phase2d_from_dms(ns,"wfs")*ipupil;
// fill cubphase
cubphase(,,nnss) = phase(n1:n2,n1:n2);
nnss++;
}
}
// display using disp2d of integrated phases
fma;
plt,escapechar(swrite(format="YAO %s | %s | %s",aoSimulVersion,parprefix,sim.name)),0.01,0.227,tosys=0;
disp2d,cubphase,subpos(1,),subpos(2,),1;
mypltitle,swrite(format="Mode %d, Normalized eigenvalue = %f",
i,eigenvalues(i)/max(eigenvalues)),[0.,-0.005],height=12;
// display of DM shapes
plsys,3;
limits,square=1;
tmp = [];
for (nm=1;nm<=ndm;nm++) {
if (dm(nm).subsystem == subsystem) {
if (dm(nm).alt == 0.) {mircube(,,nm) *= ipupil;}
grow,tmp,transpose(mircube(,,nm));
}
}
if (tmp != []) {pli,transpose(tmp);}
mypltitle,"DM(s)",[0.,0.008],height=12;
rep = typeReturn();
if (rep == "q") break;
}
}
//=========================================
// END OF DISPLAY
//=========================================
return cmat;
}
//----------------------------------------------------
func swap_screens(void)
/* DOCUMENT swap_screens
Swap the phase screens. This is to get better statistics
out of fewer phase screens and iterations.
The 2nd phase screen becomes the 1rst one, 3->2, etc...
This routine uses the phase screens and normalization
factor stored in extern by get_turb_phase_init
SEE ALSO:
*/
{
extern pscreens;