forked from ThorstenHellert/SC
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSClocoLib.m
More file actions
1166 lines (1041 loc) · 38.9 KB
/
SClocoLib.m
File metadata and controls
1166 lines (1041 loc) · 38.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
function varargout = SClocoLib(funName,varargin)
% SClocoLib
% =========
%
% NAME
% ----
% SClocoLib - Function library to use LOCO with SC
%
% SYNOPSIS
% --------
% `varargout = SClocoLib(funName, varargin])`
%
%
% DESCRIPTION
% -----------
% `SClocoLib` is a function library intended to connect the workflows and data
% structures of the AT/MML function `loco` with the `SC` workflow. The input
% string `funName` defines the function which should be used. Additional input
% arguments and the return values of `SClocoLib` differ, depending on the
% called function. The following will describe each provided function in
% detail:
%
% >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
%
% NAME
% ----
% setupLOCOmodel - Sets up the LOCO model
%
% SYNOPSIS
% --------
% `[RINGdata, LOCOflags, Init] = SClocoLib('setupLOCOmodel', SC [, options])`
%
% DESCRIPTION
% -----------
% This function sets up the LOCO model used by the function `loco` based on the
% `SC` structure. Additionally lattice properties of `SC.RING` are calculated
% by *SCcalcLatticeProperties* and stored together with `SC` in the structure
% `Init`. This is usefull for further LOCO steps.
%
% INPUTS
% ------
% `SC`::
% SC base structure.
%
% OPTIONS
% -------
% Additional arguments can be given as name-value pairs and are written as
% fields in `LOCOflags`.
%
% RETURN VALUE
% ------------
% `RINGdata`::
% RING data used by `locoresponsematrix`.
% `LOCOflags`::
% LOCO flags used by `loco`.
% `Init`::
% Structure containing the initial `SC` structure and (disturbed) lattice
% properties.
%
% EXAMPLES
% --------
% Set up the LOCO model, include dispersion and set the horizontal and vertical
% dispersion weights to 100.
% ------------------------------------------------------------------
% [RINGdata,LOCOflags,Init] = SClocoLib('setupLOCOmodel',SC,...
% 'Dispersion','Yes',...
% 'HorizontalDispersionWeight',.1E2,...
% 'VerticalDispersionWeight',.1E2);
% ------------------------------------------------------------------
%
% >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
%
% NAME
% ----
% getBPMCMstructure - Sets up the BPM and CM data structure for LOCO
%
% SYNOPSIS
% --------
% `[BPMData, CMData] = SClocoLib('getBPMCMstructure', SC, CMstep [, options])`
%
% DESCRIPTION
% -----------
% This function sets up the BPM and CM data structure used by the function
% `loco` based on the `SC` registration.
%
% INPUTS
% ------
% `SC`::
% SC base structure.
% `CMstep`::
% CM step [rad] for `locoresponsematrix`.
%
% OPTIONS
% -------
% Additional arguments can be given as cell arrays of strings as
% type-name-value triples and are written as fields in in the BPM or CM structure
% (see examples) or to specify the used BPMs and CMs.
%
% RETURN VALUE
% ------------
% `BPMData`::
% BPM data structure.
% `CMData`::
% CM data structure.
%
% EXAMPLES
% --------
% Set up the BPM and CM data structures with a CM step of `0.1mrad` and include
% fitting the BPM gains and CM kicks and use only every second CM and BPM in both planes.
% ------------------------------------------------------------------
% [BPMData,CMData] = SClocoLib('getBPMCMstructure',SC,1E-4,...
% {'BPM','FitGains','Yes'},...
% {'CM','FitKicks','Yes'},...
% {'CMords',SC.ORD.CM{1}(1:2:end),SC.ORD.CM{2}(1:2:end)},...
% {'BPMords',SC.ORD.BPM(1:2:end),SC.ORD.BPM(1:2:end)};
% ------------------------------------------------------------------
%
% >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
%
% NAME
% ----
% getMeasurement - Simulates the response matrix measurement
%
% SYNOPSIS
% --------
% `LOCOmeasData = SClocoLib('getMeasurement', SC, CMstep, RFstep [, options])`
%
% DESCRIPTION
% -----------
% Sets up the 'measured' response matrix data structure used by `loco`. Optional arguments
% are passed to *SCgetRespMat*.
%
% INPUTS
% ------
% `SC`::
% SC base structure.
% `CMstep`::
% CM step [rad] for *SCgetRespMat*.
% `RFstep`::
% RF frequency step [Hz] for *SCgetDispersion*.
%
% RETURN VALUE
% ------------
% `LOCOmeasData`::
% Data structure containing the response matrix.
%
% EXAMPLES
% --------
% Get the orbit response matrix and the dispersion measurement using CM steps
% of 0.1mrad and an rf frequency step of 1kHz, respectively.
% ------------------------------------------------------------------
% LOCOmeasData = SClocoLib('getMeasurement',SC,1E-4,1E3);
% ------------------------------------------------------------------
% Get the orbit response matrix and the dispersion measurement using a BPM variation
% of 0.1mm and an rf frequency step of 1kHz, respectively and save the used CM steps.
% ------------------------------------------------------------------
% [LOCOmeasData, CMsteps] = SClocoLib('getMeasurement',SC,1E-4,1E3,'mode','fixedOffset');
% ------------------------------------------------------------------
%
% >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
%
% NAME
% ----
% setupFitparameters - Set up the LOCO fit parameter structure
%
% SYNOPSIS
% --------
% `FitParameters = SClocoLib('setupFitparameters', SC, RING0, RINGdata, RFstep [, parameters])`
%
% DESCRIPTION
% -----------
% Sets up the fit parameter structure which shall be used by `loco`.
% Additionally the initial values of the fit parameters are stored, which is
% needed in order to eventually apply the lattice correction.
%
% INPUTS
% ------
% `SC`::
% SC base structure.
% `RING0`::
% Initial (disturbed) lattice cell structure which was used for the response matrix measurement.
% `RINGdata`::
% RING data structure.
% `RFstep`::
% RF frequency step [Hz] for `locoresponsematrix`.
%
% PARAMETERS
% ----------
% Additional arguments are given as cell arrays and specify the
% fit parameters. Each cell must be given as {`ordinates`, `normal/skew`,
% `individual/family`, `deltaK`} quadrupole, see examples.
%
% RETURN VALUE
% ------------
% `FitParameters`::
% Fit parameter structure for `loco`.
%
% EXAMPLES
% --------
% Set up the LOCO fit parameter structure using all `QF` and `QD` normal
% quadrupoles (see also *SCgetOrds*) which are individually powered and using a
% strength variation of 1E-3 and 1E-4 to calculate the derivatives,
% respectively. The disturbed lattice `RING0` is used to identify the initial
% setpoints of the fit parameters and an rf frequency step of 1kHz is assumed.
% ------------------------------------------------------------------
% ordQF = SCgetOrds(SC.RING,'QF');
% ordQD = SCgetOrds(SC.RING,'QD');
% FitParameters = SClocoLib('setupFitparameters',SC,RING0,RINGdata,1E3,...
% {ordQF,'normal','individual',1E-3},...
% {ordQD,'normal','individual',1E-4});
% ------------------------------------------------------------------
%
% Set up the LOCO fit parameter structure using all `QFA` normal quadrupoles
% which are powered as a group (one fit parameter), using a strength variation
% of 1E-4 to calculate the derivatives. The previously described structure
% `Init` (see `'setupLOCOmodel'`) is used to identify the initial setpoints of
% the fit parameters and an rf frequency step of 1kHz is assumed.
% ------------------------------------------------------------------
% FitParameters = SClocoLib('setupFitparameters',SC,Init.SC.RING,RINGdata,1E3,...
% {SCgetOrds(SC.RING,'QFA'),'normal','family',1E-4},...
% ------------------------------------------------------------------
%
% >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
%
%
% NAME
% ----
% applyLatticeCorrection - Applies the LOCO lattice correction
%
% SYNOPSIS
% --------
% `SC = SClocoLib('applyLatticeCorrection', SC, FitParameters)`
%
% DESCRIPTION
% -----------
% Applies the calculated lattice correction by adjusting the setpoints in
% `SC.RING`.
%
% INPUTS
% ------
% `SC`::
% SC base structure.
% `FitParameters`::
% Fit parameter structure (calculated by `loco`).
%
% OPTIONS
% -------
% The following options can be given as name/value-pairs:
%
% `'dipCompensation'` (1)::
% Used for combined function quadrupoles (see `SCsetMags2SetPoints`). If this flag is set and if
% there is a horizontal CM registered in the considered magnet, the CM is used to compensate
% the bending angle difference if the applied quadrupole setpoints differs from the design value.
% `'damping'` (1)::
% Damping factor applied to each lattice correction step, e.g. `0.7` meaning that the correction
% is only applied with 70% of it's calculated amplitude.
%
% RETURN VALUE
% ------------
% `SC`::
% SC base structure with applied lattice correction.
%
% >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
%
%
% NAME
% ----
% applyDiagnosticCorrection - Applies the LOCO result to BPMs and CMs
%
% SYNOPSIS
% --------
% `SC = SClocoLib('applyDiagnosticCorrection', SC, CMstep, CMData, BPMData [, options])`
%
% DESCRIPTION
% -----------
% Corrects the BPM and CM errors in `SC` by applying the LOCO fit results. If quadrupoles are used
% as CMs, the actual CM kick differs from the setpoint due to feed down effects. The (linear)
% routine used by LOCO to calculate the response matrices does not include that effect. Thus, the
% fitted CM calibration will differ from the actual calibration error of the CMs. This effect can be
% mitigated by using the optional 'CMcalOffsets'. The option 'meanToZero' helps to deal with cases
% where e.g. all fitted horizontal CM kicks are 2% too large while all horizontal BPM gains are 2%
% too low.
%
% INPUTS
% ------
% `SC`::
% SC base structure.
% `CMstep`::
% CM step [rad] used in `getBPMCMstructure`.
% `BPMData`::
% BPM data structure.
% `CMData`::
% CM data structure.
%
% OPTIONS
% -------
% The following options can be given as name/value-pairs:
%
% `'CMcalOffsets'` ([])::
% 1x2 cell aray containg the horizontal and vertical CM calibration offsets
% `'meanToZero'` (0)::
% If true, the fitted calibration factors are subtracted by their mean value
% before the correction is aplied
% `'outlierRemovalAt'` ([])::
% If this option is set, any fitted calibration error above the threshold is
% discarded and not applied to the SC structure.
%
% RETURN VALUE
% ------------
% `SC`::
% SC base structure with applied correction to BPM and CM errors.
%
% >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
%
%
% NAME
% ----
% applyOrbitCorrection - Applies orbit correction
%
% SYNOPSIS
% --------
% `SC = SClocoLib('applyOrbitCorrection', SC [, options])`
%
% DESCRIPTION
% -----------
% Applies orbit feedback using *SCfeedbackRun*.
%
% INPUTS
% ------
% `SC`::
% SC base structure.
%
% OPTIONS
% -------
% The following options can be given as name/value-pairs:
%
% `'Minv'` ([])::
% Pseudo inverse of the response matrix. If not given explicitly,
% *SCgetModelRM* is called and the Tikhonov regularization is used by
% *SCgetPinv* to calculate `Minv`.
% `'alpha'` (50)::
% Tikhonov regularization parameter.
% `'CMords'` (SC.ORD.CM)::
% CM oridnates used for orbit correction.
% `'BPMords'` (SC.ORD.BPM)::
% BPM oridnates used for orbit correction.
% `'verbose'` (0)::
% If true, debug information is printed.
%
% RETURN VALUE
% ------------
% `SC`::
% SC base structure with applied orbit correction.
%
% >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
%
% NAME
% ----
% fitChromaticity - Fit chromaticity
%
% SYNOPSIS
% --------
% `SC = SClocoLib('fitChromaticity', SC, sFamOrds, [, options])`
%
% DESCRIPTION
% -----------
% Applies a chromaticity correction using two sextupole families. The absolute initial
% setpoint variation wihtin one family remains unchanged. Note:
% this is not beam based but assumes the chromaticities can be measured reasonably well.
%
% INPUTS
% ------
% `SC`::
% SC base structure.
% `sFamOrds`::
% [1x2] cell array of sextupole ordinates used for matching
%
% OPTIONS
% -------
% The following options can be given as name/value-pairs:
%
% `'targetChrom'` ([])::
% [1x2] array of target chromaticities. If not specified, the chromaticities as
% calcualted from `SC.IDEALRING` are being used.
% `'InitStepSize'` ([2 2])::
% Initial step size for `fminsearch`
% `'TolX'` (1E-4)::
% Step size tolerance used by `fminsearch`
% `'TolFun'` (1E-3)::
% Merrit function tolerance used by `fminsearch`
% `verbose` (0)::
% If true, debug information is printed.
%
% RETURN VALUE
% ------------
% `SC`::
% SC base structure with corrected chromaticity.
%
% EXAMPLES
% --------
% Match the chromaticity in both planes to 1 using all magnets named `'SF'` and
% `'SD'` (see also *SCgetOrds*).
% ------------------------------------------------------------------
% SC = SClocoLib('fitChromaticity',SC,SCgetOrds(SC.RING,{'SF','SD'}),[1 1]);
% ------------------------------------------------------------------
%
% >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
%
% NAME
% ----
% fitTune - Fit tunes
%
% SYNOPSIS
% --------
% `SC = SClocoLib('fitTune', SC, qFamOrds, [, options])`
%
% DESCRIPTION
% -----------
% Applies a tune correction using two quadrupole families. The absolute initial
% setpoint variation wihtin one family, e.g. from LOCO remains unchanged. Note:
% this is not beam based but assumes the tunes can be measured reasonably well.
%
% INPUTS
% ------
% `SC`::
% SC base structure.
% `qFamOrds`::
% [1x2] cell array of quadrupole ordinates used for matching
%
% OPTIONS
% -------
% The following options can be given as name/value-pairs:
%
% `'FitInteger'` (1)::
% Flag specifying if the integer part should be fitted as well.
% `'targetTune'` ([])::
% [1x2] array of target tunes. If not specified, the tunes as
% calcualted from `SC.IDEALRING` are being used.
% `'TolX'` (1E-4)::
% Step size tolerance used by `fminsearch`
% `'InitStepSize'` ([.01 .01])::
% Initial step size for `fminsearch`
% `'TolFun'` (1E-3)::
% Merrit function tolerance used by `fminsearch`
% `verbose` (0)::
% If true, debug information is printed.
%
% RETURN VALUE
% ------------
% `SC`::
% SC base structure with corrected chromaticity.
%
% EXAMPLES
% --------
% Match the fractional tunes in both planes to the ideal tunes using all
% magnets named `'QF'` and `'QD'` (see also *SCgetOrds*).
% ------------------------------------------------------------------
% SC = SClocoLib('fitTune',SC,SCgetOrds(SC.RING,{'QF','QD'}),'FitInteger',0);
% ------------------------------------------------------------------
%
% >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
%
% NAME
% ----
% plotStatus - Plots the current LOCO correction
%
% SYNOPSIS
% --------
% `SClocoLib('plotStatus', SC, Init, BPMData, CMData)`
%
% DESCRIPTION
% -----------
% Plots the current beta beat, dispersion error and BPM and CM calibration and
% roll errors.
%
% INPUTS
% ------
% `SC`::
% SC base structure.
% `Init`::
% Structure containing the initial `SC` structure and (disturbed) lattice
% properties.
% `BPMData`::
% BPM data structure.
% `CMData`::
% CM data structure.
% Call function
eval([funName,'(varargin{:})']);
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Set up LOCO model
function setupLOCOmodel(SC,varargin)
% Create LOCO model from ideal ring
RINGdata.CavityFrequency = mean(atgetfieldvalues(SC.IDEALRING,SC.ORD.Cavity,'Frequency'));
RINGdata.CavityHarmNumber = round(mean(atgetfieldvalues(SC.IDEALRING,SC.ORD.Cavity,'HarmNumber')));
RINGdata.Lattice = SC.IDEALRING;
% Calculate disturbed lattice properties and save initial machine state
Init.SC = SC;
% Define LOCO parameters
LOCOflags.HorizontalDispersionWeight = 10; % Hor. dispersion VS. ORM elements
LOCOflags.VerticalDispersionWeight = 10; % Ver. dispersion VS. ORM elements
LOCOflags.Dispersion = 'No'; % Include dispersion
LOCOflags.FitHCMEnergyShift = 'No'; % Fit HCM energy Shift
LOCOflags.FitVCMEnergyShift = 'No'; % Fit VCM energy Shift
LOCOflags.SVmethod = 1E-3; % Cut off
LOCOflags.AutoCorrectDelta = 'No'; % NO!
LOCOflags.Normalize = 'Yes'; % Normalization flag
LOCOflags.Linear = 'Yes'; % Response matrix calculator
LOCOflags.Coupling = 'No'; % Include off-diagonal ORM elements
LOCOflags.Dispersion = 'No'; % Include dispersion
% Set name/pair-values in LOCO flags structure
for i=1:2:(length(varargin)-1)
LOCOflags.(varargin{i}) = varargin{i+1};
end
% Define output arguments
varargout{1} = RINGdata;
varargout{2} = LOCOflags;
varargout{3} = Init;
end
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Set up BPM and CM data structure structures
function getBPMCMstructure(SC,CMsteps,varargin)
% Default BPM data
BPMData.FamName = 'BPM';
BPMData.BPMIndex = SC.ORD.BPM(:);
BPMData.HBPMIndex = [1:length(SC.ORD.BPM)]';
BPMData.VBPMIndex = [1:length(SC.ORD.BPM)]';
BPMData.FitGains = 'No';
% Default CM data
CMData.FamName = 'CM';
CMData.HCMIndex = SC.ORD.CM{1}(:);
CMData.VCMIndex = SC.ORD.CM{2}(:);
CMData.FitKicks = 'No';
% Set name/pair-values in BPM/CM data structure
for i=1:(length(varargin))
switch varargin{i}{1}
case 'CMords'
CMData.HCMIndex = varargin{i}{2}(:);
CMData.VCMIndex = varargin{i}{3}(:);
case 'BPMords'
BPMData.BPMIndex = unique([varargin{i}{2}(:),varargin{i}{3}(:)]);
BPMData.HBPMIndex = find(ismember(BPMData.BPMIndex,varargin{i}{2}));
BPMData.VBPMIndex = find(ismember(BPMData.BPMIndex,varargin{i}{3}));
case 'BPM'
BPMData.(varargin{i}{2}) = varargin{i}{3};
case 'CM'
CMData.(varargin{i}{2}) = varargin{i}{3};
otherwise
error('Unsuported type.')
end
end
% If CM step is given as single number, expand to the right dimensions
if isnumeric(CMsteps) && length(CMsteps)==1
CMsteps = {repmat(CMsteps,length(CMData.HCMIndex),1),repmat(CMsteps,length(CMData.VCMIndex),1)};
end
CMData.CMsteps = CMsteps;
% Set other default values
BPMData.HBPMGain = ones(size(BPMData.HBPMIndex));
BPMData.VBPMGain = ones(size(BPMData.VBPMIndex));
BPMData.HBPMCoupling = zeros(size(BPMData.HBPMIndex));
BPMData.VBPMCoupling = zeros(size(BPMData.VBPMIndex));
CMData.HCMCoupling = zeros(size(CMData.HCMIndex));
CMData.VCMCoupling = zeros(size(CMData.VCMIndex));
% Set CM kicks in LOCO structure
CMData.HCMKicks = 1E3*2*CMData.CMsteps{1}(:).*ones(size(CMData.HCMIndex)); % [mrad]
CMData.VCMKicks = 1E3*2*CMData.CMsteps{2}(:).*ones(size(CMData.VCMIndex)); % [mrad]
% Define output arguments
varargout{1} = BPMData;
varargout{2} = CMData;
end
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Get orbit response matrix and dispersion from measurement
function getMeasurement(SC,CMstep,deltaRF,BPMords,CMords,varargin)
LocoMeasData.RF = SC.RING{SC.ORD.Cavity(1)}.Frequency;
LocoMeasData.DeltaRF = deltaRF;
LocoMeasData.BPMSTD = 1E-3*ones(1,2*length(BPMords)); % [mm]
[RM,Err,CMsteps] = SCgetRespMat(SC,CMstep,BPMords,CMords,varargin{:});
% Take only absolute amplitude and transpose to match LOCO data
CMsteps = cellfun(@transpose,cellfun(@max,cellfun(@abs,CMsteps,'UniformOutput',false),'UniformOutput',false),'UniformOutput',false);
LocoMeasData.M = 2*1000* repmat([CMsteps{1};CMsteps{2}]',size(RM,1),1) .* RM;
% LocoMeasData.BPMSTD = Err;
LocoMeasData.Eta = LocoMeasData.DeltaRF*1000 * SCgetDispersion(SC,LocoMeasData.DeltaRF,'BPMords',BPMords,'nSteps',3);
% Define output arguments
varargout{1} = LocoMeasData;
varargout{2} = CMsteps;
end
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Set up LOCO fit parameter structure
function setupFitparameters(SC,RING0,RINGdata,DeltaRF,varargin)
FitParameters.FitRFFrequency = 'Yes';
FitParameters.DeltaRF = DeltaRF;
nGroup=1;
for nFam = 1:length(varargin)
% Reset element index
nElem = 1;
% Loop over family ordinates
for ord = varargin{nFam}{1}
% Swith type
switch varargin{nFam}{2}
case 'normal'
FitParameters.Params{nGroup,1}(nElem).FieldName = 'PolynomB';
FitParameters.Params{nGroup,1}(nElem).SCFieldName = 'SetPointB';
case 'skew'
FitParameters.Params{nGroup,1}(nElem).FieldName = 'PolynomA';
FitParameters.Params{nGroup,1}(nElem).SCFieldName = 'SetPointA';
otherwise
error('Unsoported type.')
end
% Create structure for LOCO
FitParameters.Params{nGroup,1}(nElem).ElemIndex = ord;
FitParameters.Params{nGroup,1}(nElem).FieldIndex = {1,2};
FitParameters.Params{nGroup,1}(nElem).Function = @(x) x;
FitParameters.Params{nGroup,1}(nElem).Args = {};
% Get fit parameter values
FitParameters.Values(nGroup,1) = RINGdata.Lattice{ord}.(FitParameters.Params{nGroup}(nElem).FieldName)(2);
FitParameters.IdealValues(nGroup,1) = SC.IDEALRING{ ord}.(FitParameters.Params{nGroup}(nElem).FieldName)(2);
FitParameters.OrigValues(nGroup,1) = RING0{ord}.( FitParameters.Params{nGroup}(nElem).SCFieldName)(2);
% Define initial deltas
FitParameters.Deltas(nGroup,1) = varargin{nFam}{4};
% Determine if group or element index gets increased
if strcmp(varargin{nFam}{3},'family')
nElem = nElem + 1;
if ord==varargin{nFam}{1}(end)
nGroup = nGroup + 1;
end
else
nGroup = nGroup + 1;
end
end
end
% Define output arguments
varargout{1} = FitParameters;
end
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Apply lattice correction step
function applyLatticeCorrection(SC,FitParameters,varargin)
% Parse optional arguments
p = inputParser;
addOptional(p,'dipCompensation',1);
addOptional(p,'damping',1);
parse(p,varargin{:});
% Loop over fit parameters
for nGroup = 1:length(FitParameters.Params)
% Loop over elements in group
for nElem = 1:length(FitParameters.Params{nGroup})
ord = FitParameters.Params{nGroup}(nElem).ElemIndex;
field = FitParameters.Params{nGroup}(nElem).SCFieldName;
% New quadrupole setpoint
setpoint = FitParameters.OrigValues(nGroup) + p.Results.damping * (FitParameters.IdealValues(nGroup)-FitParameters.Values(nGroup));
% Apply setpoint correction
switch field
case 'SetPointB' % Normal quadrupole
SC = SCsetMags2SetPoints(SC,ord,2,2,setpoint,'dipCompensation',p.Results.dipCompensation);
case 'SetPointA' % Skew quadrupole
SC = SCsetMags2SetPoints(SC,ord,1,2,setpoint);
end
end
end
% Update magnets
SC = SCupdateMagnets(SC,SC.ORD.Magnet);
% Define output arguments
varargout{1} = SC;
end
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Apply BPM and CM corrections
function applyDiagnosticCorrection(SC,CMstep,CMData,BPMData,varargin)
% Parse optional arguments
p = inputParser;
addOptional(p,'CMcalOffsets',[]);
addOptional(p,'meanToZero',0);
addOptional(p,'outlierRemovalAt',[]);
parse(p,varargin{:});
if strcmp(CMData.FitCoupling,'Yes')
warning('CM roll correction not implemented yet.')
end
% Check if CM step is specified for each CM
if (~iscell(CMstep) && ~length(CMstep)==1 ) || (iscell(CMstep) && ( length(CMstep{1})~=length(CMData.HCMIndex) && length(CMstep{2})~=length(CMData.VCMIndex) ))
error('CM steps must be defined as single value or cell array matching the number of used HCM and VCM.')
end
% Expand CM steps to cell array
if ~iscell(CMstep)
CMstep = {repmat(CMstep,length(CMData.HCMIndex),1),repmat(CMstep,length(CMData.VCMIndex),1)};
end
% Apply CM calibration error correction
fields={'H','V'};SCfields={'CalErrorB','CalErrorA'};
for nDim=1:2
if strcmp(CMData.FitKicks,'Yes')
fitCalCM{ nDim} = CMData.([fields{nDim} 'CMKicks'])./CMstep{nDim}/1000/2;
% Add CM calibration offset
if ~isempty(p.Results.CMcalOffsets)
fitCalCM{nDim} = fitCalCM{nDim} - p.Results.CMcalOffsets{nDim};
end
% Check for outlier removal
if ~isempty(p.Results.outlierRemovalAt)
fitCalCM{nDim}(abs(1-fitCalCM{nDim})>=p.Results.outlierRemovalAt) = 1;
end
% Set mean CM calibration to zero
if p.Results.meanToZero==1
fitCalCM{nDim} = fitCalCM{nDim} + mean(1-fitCalCM{nDim});
end
% Apply CM calibration correction
i=1;
for ord=CMData.([fields{nDim} 'CMIndex'])'
SC.RING{ord}.(SCfields{nDim})(1) = SC.RING{ord}.(SCfields{nDim})(1) + (1-fitCalCM{nDim}(i));
i=i+1;
end
end
% Apply BPM calibration error correction
if strcmp(BPMData.FitGains,'Yes')
% Get fitted BPM calibration errors
fitCalBPM = BPMData.([fields{nDim} 'BPMGain']);
% Check for outlier removal
if ~isempty(p.Results.outlierRemovalAt)
fitCalBPM(abs(1-fitCalBPM)>=p.Results.outlierRemovalAt) = 1;
end
% Set mean BPM calibration to zero
if p.Results.meanToZero==1
fitCalBPM = fitCalBPM + mean(1-fitCalBPM);
end
% Apply BPM calibration error correction
i=1;
for ord=BPMData.BPMIndex(BPMData.([fields{nDim} 'BPMIndex']))'
SC.RING{ord}.CalError(nDim) = SC.RING{ord}.CalError(nDim) + (1-fitCalBPM(i));
i=i+1;
end
end
end
% Apply BPM roll error correction
if strcmp(BPMData.FitCoupling,'Yes')
% Get fitted BPM rolls
fitRollBPM = [BPMData.VBPMCoupling-BPMData.HBPMCoupling]'/2;
% Apply BPM calibration error correction
i=1;
for ord=BPMData.BPMIndex'
SC.RING{ord}.Roll = SC.RING{ord}.Roll - fitRollBPM(i);
i=i+1;
end
end
% Define output arguments
varargout{1} = SC;
end
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Perform orbit correction
function applyOrbitCorrection(SC,varargin)
% Parse optional arguments
p = inputParser;
addOptional(p,'Minv',[]);
addOptional(p,'alpha',50);
addOptional(p,'CMords',SC.ORD.CM);
addOptional(p,'BPMords',SC.ORD.BPM);
addOptional(p,'verbose',0);
parse(p,varargin{:});
par=p.Results;
if isempty(par.Minv)
% Calculate orbit reponse matrix
M = SCgetModelRM(SC,par.BPMords,par.CMords,'trackMode','ORB');
% Check if something went wrong
if any(isnan(M(:)));error('NaN in model response, aborting.');end
% Get pseudo inverse
par.Minv = SCgetPinv(M,'alpha',par.alpha);
end
% Apply orbit feedback
[CUR,ERROR] = SCfeedbackRun(SC,par.Minv,'target',0,'maxsteps',30,'BPMords',par.BPMords,'CMords',par.CMords,'verbose',par.verbose);
if ERROR;warning('Feedback crashed.');else;SC=CUR;end
% Define output arguments
varargout{1} = SC;
end
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Match chromaticity (so far not beam based)
function matchChromaticity(SC,sFamOrds,chromTarget)
warning('This function will be removed in a future release. Use ''fitChromaticity'' within this library instead')
% Match chromaticity
[tmp,~]=atmatchchromdelta(SC.RING,chromTarget(:),sFamOrds);
% Apply fit to setpoints
for nFam=1:length(sFamOrds)
factor = tmp{sFamOrds{nFam}(1)}.PolynomB(3)/SC.RING{sFamOrds{nFam}(1)}.PolynomB(3);
for ord=sFamOrds{nFam}
SC.RING{ ord}.SetPointB(3) = SC.RING{ ord}.SetPointB(3) * factor;
end
end
% Update magnets
SC = SCupdateMagnets(SC,SC.ORD.Magnet);
% Define output arguments
varargout{1} = SC;
end
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Fit chromaticity (not beam based)
function fitChromaticity(SC,sOrds,varargin)
% Parse optional arguments
p = inputParser;
addOptional(p,'targetChrom',[]);
addOptional(p,'verbose',0);
addOptional(p,'InitStepSize',[2 2]);
addOptional(p,'TolX',1E-4);
addOptional(p,'TolFun',1E-3);
addOptional(p,'sepTunesWithOrds',[]);
addOptional(p,'sepTunesDeltaK',[]);
parse(p,varargin{:});
par = p.Results;
% Select target chromaticity
if isempty(par.targetChrom)
[~, ~, par.targetChrom] = atlinopt(SC.IDEALRING,0,[]);
end
% Check if something went wrong
if any(isnan(par.targetChrom))
fprintf('Target chromaticity must not contain NaN. Aborting.\n')
varargout{1} = SC;
return
end
% Copy intial SC state (for convinience)
SC0 = SC;
% Seperate tunes for fitting
if ~isempty(par.sepTunesWithOrds) && ~isempty(par.sepTunesDeltaK)
for nFam=1:length(par.sepTunesWithOrds)
SC = SCsetMags2SetPoints(SC,par.sepTunesWithOrds{nFam},2,2,par.sepTunesDeltaK(nFam),'method','add');
end
end
% Print initial conditions
if par.verbose
[~, ~, xi0] = atlinopt(SC.RING,0,[]); fprintf('Fitting chromaticities from [%.3f,%.3f] to [%.3f,%.3f].\n',xi0,par.targetChrom)
end
% Initial setpoints
for nFam=1:length(sOrds)
for n=1:length(sOrds{nFam})
SP0{nFam}(n) = SC.RING{sOrds{nFam}(n)}.SetPointB(3);
end
end
% Define fit function
fun = @(x) fitFunction(SC,sOrds,x,SP0,par.targetChrom);
% Run solver
sol = fminsearch(fun,par.InitStepSize,optimset('TolX',par.TolX,'TolFun',par.TolFun));
% Apply solution
SC = applySetpoints(SC0,sOrds,sol,SP0);
% Print final falues
if par.verbose
[~, ~, xi1] = atlinopt(SC.RING,0,[]); fprintf(' Final chromaticity: [%.3f,%.3f]\n Setpoints change: [%.2f,%.2f]\n',xi1,sol)
end
% Define output arguments
varargout{1} = SC;
% Define the fitting function
function out = fitFunction(SC,qOrds,setpoints,SP0,target)
% Apply setpoints
SC = applySetpoints(SC,qOrds,setpoints,SP0);
% Get chromaticity
[~, ~, xi] = atlinopt(SC.RING,0,[]);
% Get figure of merrit
out = sqrt(mean( (xi(:) - target(:)).^2 ));
end
% Apply setpoints
function SC = applySetpoints(SC,ords,setpoints,SP0)
for nF=1:length(ords)
SC = SCsetMags2SetPoints(SC,ords{nF},2,3,setpoints(nF)+SP0{nF},'method','abs');
end
end
end
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Plot status of the correction chain
function fitTune(SC,qOrds,varargin)
% Parse optional arguments
p = inputParser;
addOptional(p,'targetTune',[]);
addOptional(p,'verbose',0);
addOptional(p,'TolX',1E-4);
addOptional(p,'TolFun',1E-3);
addOptional(p,'InitStepSize',[.01 .01]);
addOptional(p,'FitInteger',1);
parse(p,varargin{:});
par = p.Results;
% Select target tune
if isempty(par.targetTune)
if par.FitInteger
[ld, ~, ~] = atlinopt(SC.IDEALRING,0,1:length(SC.IDEALRING)+1);
par.targetTune = ld(end).mu/2/pi;
else
[~, par.targetTune, ~] = atlinopt(SC.IDEALRING,0);
end
end
% Print initial conditions
if p.Results.verbose
nu0 = getLatProps(SC,par.FitInteger); fprintf('Fitting tunes from [%.4f,%.4f] to [%.4f,%.4f].\n',nu0,par.targetTune)
end
% Initial setpoints
for nFam=1:length(qOrds)
for n=1:length(qOrds{nFam})
SP0{nFam}(n) = SC.RING{qOrds{nFam}(n)}.SetPointB(2);
end
end
% Define fit function
fun = @(x) fitFunction(SC,qOrds,x,SP0,par.targetTune,par.FitInteger);
% Run solver
sol = fminsearch(fun,par.InitStepSize,optimset('TolX',par.TolX,'TolFun',par.TolFun));
% Apply solution
SC = applySetpoints(SC,qOrds,sol,SP0);
% Print final falues
if p.Results.verbose
nu1 = getLatProps(SC,par.FitInteger); fprintf(' Final tune: [%.4f,%.4f]\n Setpoints change: [%.3f,%.3f]\n',nu1,sol)
end