source: MML/trunk/machine/SOLEIL/StorageRing/bpm/orbitcontrol.m @ 4

Last change on this file since 4 was 4, checked in by zhangj, 11 years ago

Initial import--MML version from SOLEIL@2013

File size: 151.8 KB
Line 
1function orbitcontrol(action, Input2, Input3)
2%ORBITCONTROL - GUI for orbit correction and SOFB
3%
4%  INPUTS
5%  None to launch the programme
6%  1. action - Callback to execute
7%  2. Input2 - First argument for callback function
8%  3. Input3  First argument for callback function
9%
10%  OUPUTS
11%  None
12%
13%  NOTES
14%  1. Settings for SOFB and manual orbit correction are often different
15%  2. Manual Correction : 3 iterations are done in a row
16%
17%  See Also setorbit
18
19% TODO
20% look for marker TEST LAURENT MASTERCLOCK KO, SOFB
21
22% For Compiler
23%#function lat_2020_3170b
24%#function lat_2020_3170a
25%#function lat_2020_3170e
26%#function lat_2020_3170f
27%#function solamor2linb
28%#function solamor2linc
29%#function gethbpmaverage
30%#function getvbpmaverage
31%#function gethbpmgroup
32%#function getvbpmgroup
33%#function lat_pseudo_nanoscopium_juin2011_122BPM
34%#function lat_nano_176_234_122BPM
35
36%
37%  Written by Laurent S. Nadolski (inspired by ALS srcontrol programme)
38%  28 September 2009. Retry flag added for avoiding direct SOFB stop if communication issue with MasterClock device
39%  TODO
40%  Weight edition ?
41%  HWarnNum, VwarnNum
42%  publisher SOFB as a global variable in the function
43%  Add Flag for FB interaction
44
45
46% FLAG for interaction between FOFB and SOFB
47FB.UPDATE_FOFB = 0; % to be replaced by FOFB.SOFBandFOFB
48
49devFOFBManager = 'ANS/DG/FOFB-MANAGER';
50
51XBPMFlag = 0;
52
53% Check if the AO exists
54checkforao;
55devSpeakerName = getfamilydata('TANGO', 'TEXTTALKERS');
56devLockName = 'ANS/CA/SERVICE-LOCKER';
57
58% Arguments
59if nargin < 1
60    action = 'Initialize';
61end
62
63if nargin < 2
64    Input2 = 0;
65end
66
67if nargin < 3
68    Input3 = 0;
69end
70
71% Common variables
72SR_GEV = getenergy('Energy');
73
74% BPM Families
75BPMxFamily = gethbpmfamily;
76
77if XBPMFlag
78    BPMyFamily = 'PBPMz';
79else
80    BPMyFamily = getvbpmfamily;
81end
82
83% Corrector Families
84HCMFamily  = gethcmfamily;
85VCMFamily  = getvcmfamily;
86
87% Minimum stored current to allow correction
88%DCCTMIN = 0.001; % mA
89
90
91%%%%%%%%%%%%%%%%
92%% Main Program
93%%%%%%%%%%%%%%%%
94
95switch(action)
96    %% StopOrbitFeedback
97    case 'StopOrbitFeedback'
98       
99        setappdata(findobj(gcbf,'Tag','ORBITCTRLFig1'),'FEEDBACK_STOP_FLAG', 1);
100        set(findobj(gcbf,'Tag','ORBITCTRLStaticTextInformation'),'String','SOFB STOP');
101        pause(0);
102       
103        %% Initialize
104    case 'Initialize'
105       
106        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
107        % GUI  CONSTRUCTION
108        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
109        ButtonWidth   = 200;
110        ButtonHeight  = 25;
111       
112        Offset1     = 3*(ButtonHeight+3);            % Frame around Text information
113        Offset2     = Offset1 + 2*(ButtonHeight+3);  % Frame around SOFB
114        Offset3     = Offset2 + 11*(ButtonHeight+3); % Manual Orbit
115        FigWidth    = ButtonWidth + 6;               % Figure width
116        FigHeight   = Offset3 + 5.5*(ButtonHeight+3);% Figure heigth
117        ButtonWidth = 200-6;
118       
119        % Change figure position
120        set(0,'Units','pixels');
121        p = get(0,'screensize');
122       
123        orbfig = findobj(allchild(0),'tag','ORBITCTRLFig1');
124       
125        if ~isempty(orbfig)
126            return; % IHM already exists
127        end
128       
129        h0 = figure( ...
130            'Color',[0.1 0.1 1], ...
131            'HandleVisibility','Off', ...
132            'Interruptible', 'on', ...
133            'MenuBar','none', ...
134            'Name','SOLEIL ORBIT CONTROL', ...
135            'NumberTitle','off', ...
136            'Units','pixels', ...
137            'Position',[30 p(4)-FigHeight-40 FigWidth FigHeight], ...
138            'Resize','off', ...
139            'HitTest','off', ...
140            'IntegerHandle', 'off', ...
141            'Tag','ORBITCTRLFig1');
142       
143        % Frame Box I
144        uicontrol('Parent',h0, ...
145            'BackgroundColor',[0.8 0.8 0.8], ...
146            'ListboxTop',0, ...
147            'Position',[3 Offset3 ButtonWidth+6 4.5*ButtonHeight+25], ...
148            'Style','frame');
149       
150        uicontrol('Parent',h0, ...
151            'BackgroundColor',[0.8 0.8 0.8], ...
152            'FontSize',10, ...
153            'ListboxTop',0, ...
154            'Position',[6 3 + 4*(ButtonHeight+3)+Offset3  ButtonWidth .6*ButtonHeight], ...
155            'String','Manual Orbit Correction', ...
156            'Style','text');
157       
158        uicontrol('Parent',h0, ...
159            'BackgroundColor',[0.8 0.8 0.8], ...
160            'Enable','on', ...
161            'Interruptible', 'on', ...
162            'Position',[26 3 + 3*(ButtonHeight+3) + Offset3 ButtonWidth-32 .8*ButtonHeight], ...
163            'String','H-plane', ...
164            'Style','checkbox', ...
165            'Value',1,...
166            'Tag','ORBITCTRLCheckboxHcorrection');
167       
168        uicontrol('Parent',h0, ...
169            'BackgroundColor',[0.8 0.8 0.8], ...
170            'Enable','on', ...
171            'Interruptible', 'on', ...
172            'Position',[26 3+2*(ButtonHeight+3)+Offset3 ButtonWidth-32 .8*ButtonHeight], ...
173            'String','V-plane', ...
174            'Style','checkbox', ...
175            'Value',1,...
176            'Tag','ORBITCTRLCheckboxVcorrection');
177       
178        uicontrol('Parent',h0, ...
179            'Callback','orbitcontrol(''OrbitCorrection'');', ...
180            'Interruptible','Off', ...
181            'Enable','On', ...
182            'Position',[6 3+1*(ButtonHeight+3)+Offset3 ButtonWidth ButtonHeight], ...
183            'String','Correct Orbit', ...
184            'Tag','ORBITCTRLButtonOrbitCorrection');
185       
186        uicontrol('Parent',h0, ...
187            'CreateFcn','orbitcontrol(''OrbitCorrectionSetup'',1);', ...
188            'callback','orbitcontrol(''OrbitCorrectionSetup'',0);', ...
189            'Enable','on', ...
190            'Interruptible', 'off', ...
191            'Position',[6 3+Offset3 ButtonWidth 0.8*ButtonHeight], ...
192            'String','Edit BPM, CM Lists', ...
193            'Style','PushButton', ...
194            'Value',0,...
195            'Tag','ORBITCTRLButtonOrbitCorrectionSetup');
196       
197        uicontrol('Parent',h0, ...
198            'callback','orbitcontrol(''InteractionMode'',0);', ...
199            'BackgroundColor',[1 0 0], ...
200            'Enable','on', ...
201            'Interruptible', 'on', ...
202            'Position',[26 3 + Offset3 - ButtonHeight ButtonWidth-32 .8*ButtonHeight], ...
203            'String','SOFB + FOFB interaction', ...
204            'Style','checkbox', ...
205            'Value',0,...
206            'Tag','ORBITCTRLCheckboxInteractionMode');
207       
208       
209        % Frame Box II
210        uicontrol('Parent',h0, ...
211            'BackgroundColor',[0.8 0.8 0.8], ...
212            'ListboxTop',0, ...
213            'Position',[3 Offset2 ButtonWidth+6 11*ButtonHeight+5], ...
214            'Style','frame');
215       
216        uicontrol('Parent',h0, ...
217            'BackgroundColor',[0.8 0.8 0.8], ...
218            'FontSize',10, ...
219            'ListboxTop',0, ...
220            'Position',[6 3+9*(ButtonHeight+3)+ Offset2 ButtonWidth .55*ButtonHeight], ...
221            'String','Orbit Feedback', ...
222            'Style','text');
223       
224           uicontrol('Parent',h0, ...
225            'BackgroundColor',[0.8 0.8 0.8], ...
226            'FontSize',10, ...
227            'ListboxTop',0, ...
228            'Position',[6 3+8.4*(ButtonHeight+3)+ Offset2 ButtonWidth-6 .6*ButtonHeight], ...
229            'String','Min Current to Start = ', ...
230            'Style','text',...
231            'Tag','ORBITCTRLStaticTextDCCT');
232
233        uicontrol('Parent',h0, ...
234            'BackgroundColor',[0.8 0.8 0.8], ...
235            'callback','orbitcontrol(''SOFBHSelected'');', ...
236            'Enable','on', ...
237            'Interruptible', 'on', ...
238            'Position',[26 3 + 7.4*(ButtonHeight+3) + Offset2 ButtonWidth-32 .8*ButtonHeight], ...
239            'String','H-plane', ...
240            'Style','checkbox', ...
241            'Value',1,...
242            'Tag','ORBITCTRLCheckboxHSOFB');
243       
244           uicontrol('Parent',h0, ...
245            'BackgroundColor',[0.8 0.8 0.8], ...
246            'FontSize',10, ...
247            'ListboxTop',0, ...
248            'Position',[6 3+6.9*(ButtonHeight+3)+ Offset2 0.5*ButtonWidth-20 .6*ButtonHeight], ...
249            'String','Gain = ', ...
250            'Style','text',...
251            'Tag','ORBITCTRLStaticTextGainH');
252
253           uicontrol('Parent',h0, ...
254            'BackgroundColor',[0.8 0.8 0.8], ...
255            'FontSize',10, ...
256            'ListboxTop',0, ...
257            'Position',[0.5*ButtonWidth-10 3+6.9*(ButtonHeight+3)+ Offset2 0.5*ButtonWidth-6 .6*ButtonHeight], ...
258            'String','Min = ', ...
259            'Style','text',...
260            'Tag','ORBITCTRLStaticTextThresholdH');
261
262        uicontrol('Parent',h0, ...
263            'BackgroundColor',[0.8 0.8 0.8], ...
264            'Enable','on', ...
265            'Interruptible', 'on', ...
266            'Position',[26 3+6*(ButtonHeight+3)+Offset2 ButtonWidth-32 .8*ButtonHeight], ...
267            'String','V-plane', ...
268            'Style','checkbox', ...
269            'Value',1,...
270            'Tag','ORBITCTRLCheckboxVSOFB');
271       
272       
273            uicontrol('Parent',h0, ...
274            'BackgroundColor',[0.8 0.8 0.8], ...
275            'FontSize',10, ...
276            'ListboxTop',0, ...
277            'Position',[6 3+5.3*(ButtonHeight+3)+ Offset2 0.5*ButtonWidth-20 .8*ButtonHeight], ...
278            'String','Gain = ', ...
279            'Style','text',...
280            'Tag','ORBITCTRLStaticTextGainV');
281
282           uicontrol('Parent',h0, ...
283            'BackgroundColor',[0.8 0.8 0.8], ...
284            'FontSize',10, ...
285            'ListboxTop',0, ...
286            'Position',[0.5*ButtonWidth-10 3+5.3*(ButtonHeight+3)+ Offset2 0.5*ButtonWidth-6 .8*ButtonHeight], ...
287            'String','Min = ', ...
288            'Style','text',...
289            'Tag','ORBITCTRLStaticTextThresholdV');
290
291        uicontrol('Parent',h0, ...
292            'BackgroundColor',[0.8 0.8 0.8], ...
293            'Enable','on', ...
294            'Interruptible', 'on', ...
295            'Position',[26 3+5*(ButtonHeight+3)+Offset2 ButtonWidth-32 .8*ButtonHeight], ...
296            'String','Fast Orbit Correction (Not implemented)', ...
297            'Style','checkbox', ...
298            'Value',0,...
299            'Visible', 'Off', ...
300            'Tag','ORBITCTRLCheckboxFOFB');
301       
302        uicontrol('Parent',h0, ...
303            'BackgroundColor',[0.8 0.8 0.8], ...
304            'Enable','on', ...
305            'Interruptible', 'on', ...
306            'Position',[26 3+4.6*(ButtonHeight+3)+Offset2 ButtonWidth-32 .8*ButtonHeight], ...
307            'String','Correct RF Frequency', ...
308            'Style','checkbox', ...
309            'Value',1,...
310            'Tag','ORBITCTRLCheckboxRF');
311       
312          uicontrol('Parent',h0, ...
313            'BackgroundColor',[0.8 0.8 0.8], ...
314            'FontSize',10, ...
315            'ListboxTop',0, ...
316            'Position',[6 3+4*(ButtonHeight+3)+ Offset2 0.5*ButtonWidth-6 .6*ButtonHeight], ...
317            'String','Min = ', ...
318            'Style','text',...
319            'Tag','ORBITCTRLStaticTextMinRF');
320
321             uicontrol('Parent',h0, ...
322            'BackgroundColor',[0.8 0.8 0.8], ...
323            'FontSize',10, ...
324            'ListboxTop',0, ...
325            'Position',[0.5*ButtonWidth+6 3+4*(ButtonHeight+3)+ Offset2 0.5*ButtonWidth-6 .6*ButtonHeight], ...
326            'String','Max = ', ...
327            'Style','text',...
328            'Tag','ORBITCTRLStaticTextMaxRF');
329
330        uicontrol('Parent',h0, ...
331            'callback','orbitcontrol(''Feedback'');', ...
332            'Enable','on', ...
333            'FontSize',12, ...
334            'Interruptible', 'on', ...
335            'ListboxTop',0, ...
336            'Position',[8 3+3*(ButtonHeight+3)+ Offset2 .5*ButtonWidth-6 1.0*ButtonHeight], ...
337            'String','Start FB', ...
338            'Value',0, ...
339            'Tag','ORBITCTRLPushbuttonStart');
340       
341        uicontrol('Parent',h0, ...
342            'callback','orbitcontrol(''StopOrbitFeedback'');pause(0);', ...
343            'Enable','off', ...
344            'FontSize',12, ...
345            'Interruptible', 'on', ...
346            'ListboxTop',0, ...
347            'Position',[.5*FigWidth+3 3+3*(ButtonHeight+3)+Offset2 .5*ButtonWidth-6 1.0*ButtonHeight], ...
348            'String','Stop FB', ...
349            'Value',0, ...
350            'Tag','ORBITCTRLPushbuttonStop');
351       
352        uicontrol('Parent',h0, ...
353            'BackgroundColor',[0.8 0.8 0.8], ...
354            'HorizontalAlignment','left', ...
355            'ListboxTop',0, ...
356            'Position',[14 3 + 2*(ButtonHeight)+Offset2 ButtonWidth-14 .75*ButtonHeight], ...
357            'String','Horizontal RMS = _____ mm', ...
358            'Style','text', ...
359            'Tag','ORBITCTRLStaticTextHorizontal');
360       
361        uicontrol('Parent',h0, ...
362            'BackgroundColor',[0.8 0.8 0.8], ...
363            'HorizontalAlignment','left', ...
364            'ListboxTop',0, ...
365            'Position',[26 3 + 1*(ButtonHeight) + Offset2 ButtonWidth-26 .75*ButtonHeight], ...
366            'String','Vertical RMS = _____ mm', ...
367            'Style','text', ...
368            'Tag','ORBITCTRLStaticTextVertical');
369       
370        uicontrol('Parent',h0, ...
371            'CreateFcn','orbitcontrol(''FeedbackSetup'',1);', ...
372            'callback','orbitcontrol(''FeedbackSetup'',0);', ...
373            'Enable','on', ...
374            'Interruptible', 'off', ...
375            'Position',[8 3 + Offset2 ButtonWidth-5 .75*ButtonHeight], ...
376            'String','Edit SOFB Setup', ...
377            'Style','PushButton', ...
378            'Value',0,...
379            'Tag','ORBITCTRLButtonFeedbackSetup');
380       
381        % Frame Box III
382        uicontrol('Parent',h0, ...
383            'BackgroundColor',[0.8 0.8 0.8], ...
384            'ListboxTop',0, ...
385            'Position',[3 Offset1  ButtonWidth+6 ButtonHeight+12], ...
386            'Style','frame');
387       
388        uicontrol('Parent',h0, ...
389            'BackgroundColor',[0.8 0.8 0.8], ...
390            'HorizontalAlignment','center', ...
391            'ListboxTop',0, ...
392            'Position',[6 Offset1 + 0.7*ButtonHeight ButtonWidth .7*ButtonHeight], ...
393            'String','Experimental Interface', ...
394            'Style','text', ...
395            'Tag','ORBITCTRLStaticTextHeader');
396       
397        uicontrol('Parent',h0, ...
398            'BackgroundColor',[0.8 0.8 0.8], ...
399            'ForegroundColor','b', ...
400            'HorizontalAlignment','center', ...
401            'ListboxTop',0, ...
402            'Position',[6 3 + Offset1 + .05*ButtonHeight ButtonWidth .7*ButtonHeight], ...
403            'String','   Startup', ...
404            'Style','text', ...
405            'Tag','ORBITCTRLStaticTextInformation');
406       
407        uicontrol('Parent',h0, ...
408            'Enable','on', ...
409            'Interruptible', 'on', ...
410            'Position',[26 3 + Offset1 - ButtonHeight ButtonWidth-32 .8*ButtonHeight], ...
411            'String','FOFB ready for interaction', ...
412            'Style','checkbox', ...
413            'Value',0,...
414            'Enable','inactive', ...
415            'Tag','ORBITCTRLCheckboxFB');
416       
417        % Frame Box "Close"
418        uicontrol('Parent',h0, ...
419            'BackgroundColor',[0.8 0.8 0.8], ...
420            'ListboxTop',0, ...
421            'Position',[3 8 ButtonWidth+6 ButtonHeight+8], ...
422            'Style','frame');
423       
424        uicontrol('Parent',h0, ...
425            'Callback', 'close(gcbf);', ...
426            'Enable','On', ...
427            'Interruptible','Off', ...
428            'Position',[6 13 ButtonWidth ButtonHeight], ...
429            'String','Close', ...
430            'Tag','ORBITCTRLClose');
431       
432        %setup average data for reading BPMs
433        %setfamilydata('gethbpmaverage',BPMxFamily,'Monitor', 'SpecialFunctionGet')
434        %setfamilydata('getvbpmaverage',BPMyFamily,'Monitor', 'SpecialFunctionGet')
435       
436       
437       
438        %% OrbitCorrectionSetup
439    case 'OrbitCorrectionSetup'
440        % NOTES setting for SOFB and manual orbit correction are often
441        % different
442       
443        InitFlag = Input2;  % Input #2: if InitFlag, then initialize variables
444       
445        if InitFlag % just at startup
446           
447            % Setup orbit correction elements : DEFAULT configuration
448            %disp('Orbit correction condition: InitFlag=1 -- debugging message');
449           
450            % Get list of BPMs et corrector magnets
451            [HCMlist VCMlist BPMlist] = getlocallist;
452           
453            % SVD orbit correction singular values
454            Xivec = 1:57;
455            Yivec = 1:57;
456           
457           % Correction Gain values
458            Xgain = 1;
459            Ygain = 1;
460         
461            % Correctors Thresholds
462            dhcmStd=0.0003;
463            dvcmStd=0.0003;
464           
465            %RF Thresholds
466            deltaRFmax=10e-6;
467            deltaRFmin=0.3e-6;
468
469             %DCCT Threshold
470            DCCTMIN=0.001;
471           
472            % initialize RFCorrFlag
473            %RFCorrFlag = 'No';
474            RFCorrFlag = 'Yes';
475           
476            % Goal orbit
477            Xgoal = getgolden(BPMxFamily, BPMlist, 'numeric');
478            Ygoal = getgolden(BPMyFamily, BPMlist, 'numeric');
479           
480            % BPM weights
481            Xweight = ones(size(BPMlist,1), 1);
482            Yweight = ones(size(BPMlist,1), 1);
483           
484            % Correctors weights
485            HCMweight = ones(size(HCMlist,1), 1);
486            VCMweight = ones(size(VCMlist,1), 1);
487           
488        else % For orbit correction Configuration
489            % Get vector for orbit correction
490            FB = get(findobj(gcbf,'Tag','ORBITCTRLButtonOrbitCorrectionSetup'),'Userdata');
491            BPMlist = FB.BPMlist;
492            HCMlist = FB.HCMlist;
493            VCMlist = FB.VCMlist;
494            Xivec = FB.Xivec;
495            Yivec = FB.Yivec;
496            Xgoal = FB.Xgoal;
497            Ygoal = FB.Ygoal;
498           
499            Xgain = FB.Xgain;
500            Ygain = FB.Ygain;
501         
502            dhcmStd=FB.dhcmStd;
503            dvcmStd=FB.dvcmStd;
504           
505            deltaRFmax=FB.deltaRFmax;
506            deltaRFmin=FB.deltaRFmin;
507
508            DCCTMIN=FB.DCCTMIN
509           
510            RFCorrFlag = FB.RFCorrFlag;
511           
512            HCMweight = FB.OCSx.CMWeight;
513            VCMweight = FB.OCSx.CMWeight;
514            Xweight = FB.OCSx.BPMWeight;
515            Yweight = FB.OCSy.BPMWeight;
516           
517            % Add button to change #ivectors, CMs, IDBPMs,
518            EditFlag = 0;
519            h_fig1 = figure;
520           
521            while EditFlag ~= 12
522               
523                % get Sensitivity matrices
524                Sx = getrespmat(BPMxFamily, BPMlist, HCMFamily, HCMlist, [], SR_GEV);
525                Sy = getrespmat(BPMyFamily, BPMlist, VCMFamily, VCMlist, [], SR_GEV);
526               
527                % Computes SVD to get singular values
528                [Ux, SVx, Vx] = svd(Sx);
529                [Uy, SVy, Vy] = svd(Sy);
530               
531                % Remove singular values greater than the actual number of singular values
532                i = find(Xivec>length(diag(SVx)));
533                if ~isempty(i)
534                    disp('   Horizontal singular value vector scaled since there were more elements in the vector than singular values.');
535                    pause(0);
536                    Xivec(i) = [];
537                end
538                i = find(Yivec>length(diag(SVy)));
539                if ~isempty(i)
540                    disp('   Vertical singular value vector scaled since there were more elements in the vector than singular values.');
541                    pause(0);
542                    Yivec(i) = [];
543                end
544               
545                % Display singular value plot for both planes
546               
547                figure(h_fig1);
548               
549                subplot(2,1,1);
550                semilogy(diag(SVx),'b');
551                hold on;
552                semilogy(diag(SVx(Xivec,Xivec)),'xr');
553                ylabel('Horizontal');
554                title('Response Matrix Singular Values');
555                hold off; grid on;
556               
557                subplot(2,1,2);
558                semilogy(diag(SVy),'b');
559                hold on;
560                semilogy(diag(SVy(Yivec,Yivec)),'xr');
561                xlabel('Singular Value Number');
562                ylabel('Vertical');
563                hold off; grid on;
564                drawnow;
565               
566                % End of display
567               
568                if strcmpi(RFCorrFlag,'No')
569                    RFCorrState = 'NOT CORRECTED';
570                elseif strcmp(RFCorrFlag,'Yes')
571                    RFCorrState = 'CORRECTED';
572                else
573                    RFCorrState = '???';
574                end
575               
576                EditFlag = menu('Change Parameters?','Singular Values','Correction Gains', 'Correction Thresholds', ...
577                    'Horizontal corrector magnet list', 'Horizontal corrector magnet weights', ...
578                    'Vertical corrector magnet list', 'Vertical corrector magnet weights',  ...
579                    'BPM list', 'BPM weights', 'Golden Orbit value',...
580                    sprintf('RF Frequency (currently %s)',RFCorrState),'Return');
581               
582                % Edition switchyard for orbit correction
583                switch EditFlag
584                    case 1 % Singular value edition
585                       
586                        % Build up matlab prompt
587                        prompt = {'Enter the horizontal singular value vector (Matlab vector format):', ...
588                            'Enter the vertical singular value vector (Matlab vector format):'};
589                        % default values
590                        def = {sprintf('[%d:%d]',1,Xivec(end)),sprintf('[%d:%d]',1,Yivec(end))};
591                        titlestr = 'SVD Orbit Correction';
592                        lineNo = 1;
593                       
594                        answer = inputdlg(prompt,titlestr,lineNo,def);
595                       
596                        % Answer parsing
597                        if ~isempty(answer)
598                            % Horizontal plane
599                            XivecNew = fix(str2num(answer{1}));
600                            if isempty(XivecNew)
601                                disp('   Horizontal singular value number cannot be empty.  No change made.');
602                            else
603                                if any(XivecNew<=0) || max(XivecNew)>length(diag(SVx))
604                                    disp('   Error reading horizontal singular value vector  No change made.');
605                                else
606                                    Xivec = XivecNew;
607                                end
608                            end
609                            % Vertical plane
610                            YivecNew = fix(str2num(answer{2}));
611                            if isempty(YivecNew)
612                                disp('   Vertical singular value vector cannot be empty.  No change made.');
613                            else
614                                if any(YivecNew<=0) || max(YivecNew)>length(diag(SVy))
615                                    disp('   Error reading vertical singular value vector.  No change made.');
616                                else
617                                    Yivec = YivecNew;
618                                end
619                            end
620                        end
621                       
622                       
623                    case 2 % Correction Gain edition
624
625                        % Build up matlab prompt1
626                        prompt = {'Enter the horizontal loop gain value :', ...
627                            'Enter the vertical loop gain value :'};
628                        % default values
629                        def = {sprintf('%d',Xgain),sprintf('%d',Ygain)};
630                        titlestr = 'Change loop gain value';
631                        lineNo = 1;
632
633                        answer = inputdlg(prompt,titlestr,lineNo,def);
634
635                        % Answer parsing
636                        if ~isempty(answer)
637                            % Horizontal plane
638                            XgainNew = str2num(answer{1});
639                            if isempty(XgainNew)
640                                disp('   Horizontal gain value cannot be empty.  No change made.');
641                            else
642                                if (XgainNew<=0)
643                                    disp('   Error reading horizontal gain value. No change made.');
644                                else
645                                    Xgain = XgainNew;
646                                    % Display new value on main pannel
647                                    set(findobj(gcbf,'Tag','orbitcontrolXgain'),'string',['H-Loop-Gain = ',num2str(Xgain)]);
648                                 end
649                            end
650                            % Vertical plane
651                            YgainNew = str2num(answer{2});
652                            if isempty(YgainNew)
653                                disp('   Vertical gain value cannot be empty.  No change made.');
654                            else
655                                if (YgainNew<=0)
656                                    disp('   Error reading vertical gain value.  No change made.');
657                                else
658                                    Ygain = YgainNew;
659                                    % Display new value on main pannel
660                                    set(findobj(gcbf,'Tag','orbitcontrolgain'),'string',['V-Loop-Gain = ',num2str(Ygain)]);
661                                end
662                            end
663                        end
664                       
665                    case 3 % Correction Threshold edition
666
667                        % Build up matlab prompt
668                        prompt = {'Enter the horizontal corrector threshold value (A):', ...
669                            'Enter the vertical corrector threshold value (A):',...
670                           'Enter the maximum RF correction value (MHz):', ...
671                            'Enter the minimum RF correction value (MHz):',...
672                            'Enter the DCCT Threshold value (A):'};
673                        % default values
674                        def = {sprintf('%d',dhcmStd),sprintf('%d',dvcmStd),sprintf('%d',deltaRFmax),sprintf('%d',deltaRFmin),sprintf('%d',DCCTMIN)};
675                        titlestr = 'Change Correction Threshold values';
676                        lineNo = 1;
677
678                        answer = inputdlg(prompt,titlestr,lineNo,def);
679
680                        % Answer parsing
681                        if ~isempty(answer)
682                            % Horizontal plane
683                            dhcmStdNew = str2num(answer{1});
684                            if isempty(dhcmStdNew)
685                                disp('   Horizontal corrector threshold value cannot be empty.  No change made.');
686                            else
687                                if (dhcmStdNew<=0)
688                                    disp('   Error reading horizontalcorrector threshold value. No change made.');
689                                else
690                                    dhcmStd = dhcmStdNew;
691                                end
692                            end
693                            % Vertical plane
694                            dvcmStdNew = str2num(answer{2});
695                            if isempty(dvcmStdNew)
696                                disp('   Vertical corrector threshold value cannot be empty.  No change made.');
697                            else
698                                if (dvcmStdNew<=0)
699                                    disp('   Error reading vertical corrector threshold value.  No change made.');
700                                else
701                                    dvcmStd = dvcmStdNew;
702                               end
703                            end
704                            % RF max
705                            deltaRFmaxNew = str2num(answer{3});
706                            if isempty( deltaRFmaxNew)
707                                disp('   Maximum RF threshold value cannot be empty.  No change made.');
708                            else
709                                if ( deltaRFmaxNew<=0)
710                                    disp('   Error reading Maximum RF threshold value. No change made.');
711                                else
712                                     deltaRFmax =  deltaRFmaxNew;
713                                end
714                            end
715                           % RF min
716                            deltaRFminNew = str2num(answer{4});
717                            if isempty( deltaRFminNew)
718                                disp('   Minimum RF threshold value cannot be empty.  No change made.');
719                            else
720                                if ( deltaRFminNew<=0)
721                                    disp('   Error reading Minimum RF threshold value. No change made.');
722                                else
723                                     deltaRFmin =  deltaRFminNew;
724                                end
725                            end
726                          % DCCT min
727                            DCCTMINNew = str2num(answer{5});
728                            if isempty( DCCTMINNew)
729                                disp('   Minimum DCCT threshold value cannot be empty.  No change made.');
730                            else
731                                if ( DCCTMINNew<=0)
732                                    disp('   Error reading Minimum DCCT threshold value. No change made.');
733                                else
734                                     DCCTMIN =  DCCTMINNew;
735                                end
736                            end
737                          end
738                       
739                    case 4 % Horizontal corrector list edition
740                        List = getlist(HCMFamily);
741                        ListOld = HCMlist;
742                        CheckList = zeros(size(List,1));
743                        Elem = dev2elem(HCMFamily, HCMlist);
744                        CheckList(Elem) = ones(size(Elem));
745                        CheckList = CheckList(dev2elem(HCMFamily,List));
746                        newList = editlist(List, HCMFamily, CheckList);
747                       
748                        if isempty(newList)
749                            fprintf('   Horizontal corrector magnet list cannot be empty.  No change made.\n');
750                        else
751                            HCMlist = newList;
752                        end
753                       
754                        %set correctors weight values
755                        HCMweightOld = HCMweight;
756                        HCMweight = ones(size(HCMlist,1), 1);
757                       
758                        %if a new corrector is added, then set the weight values to
759                        %one.
760                        % Otherwise keep the present weight values
761                        for i = 1:size(HCMlist,1)
762                           
763                            % Is it a new corrector?
764                            k = find(HCMlist(i,1)==ListOld(:,1));
765                            l = find(HCMlist(i,2)==ListOld(k,2));
766                           
767                            if isempty(k) || isempty(l)
768                                % New corrector
769                            else
770                                % Use the old value for old correctors
771                                HCMweight(i) = HCMweightOld(k(l));
772                            end
773                        end
774                         
775                    case 5 % Horizontal corrector weight edition
776                       
777                        % Ask user to select HCM for modifying weight
778                        ChangeList = editlist(HCMlist, 'Change HCM', ...
779                            zeros(size(HCMlist,1),1));
780                       
781                        % Ask the new weight for each selected corrector
782                        for i = 1:size(ChangeList,1)
783                           
784                            k = find(ChangeList(i,1) == HCMlist(:,1));
785                            l = find(ChangeList(i,2) == HCMlist(k,2));
786                           
787                            prompt = {sprintf('Enter the new weight for HCM(%d,%d):', ...
788                                HCMlist(k(l),1), HCMlist(k(l),2))};
789                            def = {sprintf('%f',HCMweight(k(l))),sprintf('%f',HCMweight(k(l)))};
790                            titlestr = 'CHANGE THE HCM WEIGHTS';
791                            lineNo = 1;
792                            answer = inputdlg(prompt, titlestr, lineNo, def);
793                           
794                            if isempty(answer)
795                                % No change
796                                fprintf('   No change was made to the VCM weight.\n');
797                            else
798                                HCMweightnew = str2num(answer{1});
799                                if isempty(HCMweightnew)
800                                    fprintf('   No change was made to the horizontal BPM weight.\n');
801                                else
802                                    HCMweight(k(l)) = HCMweightnew;
803                                end
804                            end
805                        end
806                       
807                        if ~isempty(ChangeList)
808                            fprintf('   Note:  changing the HCM weight for "Orbit Correction" does not change the goal orbit for "Slow Orbit Feedback."\n');
809                        end
810                       
811                    case 6 % Vertical corrector list edition
812                        List = getlist(VCMFamily);
813                        CheckList = zeros(size(List,1));
814                        ListOld = VCMlist;
815                        Elem = dev2elem(VCMFamily, VCMlist);
816                        CheckList(Elem) = ones(size(Elem));
817                        CheckList = CheckList(dev2elem(VCMFamily,List));
818                        newList = editlist(List, VCMFamily, CheckList);
819                        if isempty(newList)
820                            fprintf('   Vertical corrector magnet cannot be empty.  No change made.\n');
821                        else
822                            VCMlist = newList;
823                        end
824                       
825                        %set correctors weight values
826                        VCMweightOld = VCMweight;
827                        VCMweight = ones(size(VCMlist,1), 1);
828                       
829                        %if a new corrector is added, then set the weight values to
830                        %one.
831                        % Otherwise keep the present weight values
832                        for i = 1:size(VCMlist,1)
833                           
834                            % Is it a new corrector?
835                            k = find(VCMlist(i,1)==ListOld(:,1));
836                            l = find(VCMlist(i,2)==ListOld(k,2));
837                           
838                            if isempty(k) || isempty(l)
839                                % New corrector
840                            else
841                                % Use the old value for old correctors
842                                VCMweight(i) = VCMweightOld(k(l));
843                            end
844                        end
845                    case 7 % Vertical corrector weight edition
846                        % Ask user to select VCM for modifying weight
847                        ChangeList = editlist(VCMlist, 'Change VCM', ...
848                            zeros(size(VCMlist,1),1));
849                       
850                        % Ask the new weight for each selected corrector
851                        for i = 1:size(ChangeList,1)
852                           
853                            k = find(ChangeList(i,1) == VCMlist(:,1));
854                            l = find(ChangeList(i,2) == VCMlist(k,2));
855                           
856                            prompt = {sprintf('Enter the new weight for VCM(%d,%d):', ...
857                                VCMlist(k(l),1), VCMlist(k(l),2))};
858                            def = {sprintf('%f',VCMweight(k(l))),sprintf('%f',VCMweight(k(l)))};
859                            titlestr = 'CHANGE THE VCM WEIGHTS';
860                            lineNo = 1;
861                            answer = inputdlg(prompt, titlestr, lineNo, def);
862                           
863                            if isempty(answer)
864                                % No change
865                                fprintf('   No change was made to the VCM weight.\n');
866                            else
867                                VCMweightnew = str2num(answer{1});
868                                if isempty(VCMweightnew)
869                                    fprintf('   No change was made to the horizontal BPM weight.\n');
870                                else
871                                    VCMweight(k(l)) = VCMweightnew;
872                                end
873                            end
874                        end
875                       
876                        if ~isempty(ChangeList)
877                            fprintf('   Note:  changing the VCM weight for "Orbit Correction" does not change the goal orbit for "Slow Orbit Feedback."\n');
878                        end
879                       
880                    case 8 % BPM list edition
881                        % Backup element before edition
882                        ListOld = BPMlist;
883                        XgoalOld = Xgoal;
884                        YgoalOld = Ygoal;
885                        XweightOld = Xweight;
886                        YweightOld = Yweight;
887                       
888                        % Get full BPM list
889                        List = family2dev(BPMxFamily);
890                       
891                        % Check BPM already in the list CheckList(i) = 1
892                        %       BPM not in the list CheckList(i) = 0
893                        CheckList = zeros(size(List,1),1);
894                        if ~isempty(BPMlist)
895                            for i = 1:size(List,1)
896                                k = find(List(i,1) == BPMlist(:,1));
897                                l = find(List(i,2) == BPMlist(k,2));
898                                if isempty(k) || isempty(l)
899                                    % Item not in list
900                                else
901                                    CheckList(i) = 1;
902                                end
903                            end
904                        end
905                       
906                        % User edition of the BPM list
907                        newList = editlist(List, 'BPM', CheckList);
908                        if isempty(newList)
909                            fprintf('   BPM list cannot be empty.  No change made.\n');
910                        else
911                            BPMlist = newList;
912                        end
913                       
914                        % Set the goal orbit to the golden orbit
915                        Xgoal = getgolden(BPMxFamily, BPMlist);
916                        Ygoal = getgolden(BPMyFamily, BPMlist);
917                        Xweight = ones(size(BPMlist,1),1);
918                        Yweight = ones(size(BPMlist,1),1);
919                       
920                        % If a new BPM is added, then set the goal orbit to the golden orbit
921                        % For other BPMs, present goal orbit is kept
922                        for i = 1:size(BPMlist,1)
923                           
924                            % Is it a new BPM?
925                            k = find(BPMlist(i,1) == ListOld(:,1));
926                            l = find(BPMlist(i,2) == ListOld(k,2));
927                           
928                            if isempty(k) || isempty(l)
929                                % New BPM
930                            else
931                                % Use the old value for old BPM
932                                Xgoal(i) = XgoalOld(k(l));
933                                Ygoal(i) = YgoalOld(k(l));
934                                Xweight(i) = XweightOld(k(l));
935                                Yweight(i) = YweightOld(k(l));
936                            end
937                        end
938                       
939                    case 9 % BPM weight edition
940                        % Ask user to select BPM for modifying weight
941                        ChangeList = editlist(BPMlist, 'Change BPM', ...
942                            zeros(size(BPMlist,1),1));
943                       
944                        % Ask the new weight for each selected BPM
945                        for i = 1:size(ChangeList,1)
946                           
947                            k = find(ChangeList(i,1) == BPMlist(:,1));
948                            l = find(ChangeList(i,2) == BPMlist(k,2));
949                           
950                            prompt = {sprintf('Enter the new weight for BPMx(%d,%d):', ...
951                                BPMlist(k(l),1), BPMlist(k(l),2)), ...
952                                sprintf('Enter the new weight for BPMz(%d,%d):', ...
953                                BPMlist(k(l),1),BPMlist(k(l),2))};
954                            def = {sprintf('%f',Xweight(k(l))),sprintf('%f',Yweight(k(l)))};
955                            titlestr = 'CHANGE THE BPM WEIGHTS';
956                            lineNo = 1;
957                            answer = inputdlg(prompt, titlestr, lineNo, def);
958                           
959                            if isempty(answer)
960                                % No change
961                                fprintf('   No change was made to the BPM weight.\n');
962                            else
963                                Xweightnew = str2num(answer{1});
964                                if isempty(Xweightnew)
965                                    fprintf('   No change was made to the horizontal BPM weight.\n');
966                                else
967                                    Xweight(k(l)) = Xweightnew;
968                                end
969                               
970                                Yweightnew = str2num(answer{2});
971                                if isempty(Yweightnew)
972                                    fprintf('   No change was made to the vertical BPM weight.\n');
973                                else
974                                    Yweight(k(l)) = Yweightnew;
975                                end
976                            end
977                        end
978                       
979                        if ~isempty(ChangeList)
980                            fprintf('   Note:  changing the BPM weight for "Orbit Correction" does not change the goal orbit for "Slow Orbit Feedback."\n');
981                        end
982                       
983                       
984                    case 10 % Golden orbit manual edition
985                       
986                        % Ask user to select BPM for modifying golden orbit
987                        ChangeList = editlist(BPMlist, 'Change BPM', ...
988                            zeros(size(BPMlist,1),1));
989                       
990                        % Ask the new golden orbit for each selected BPM
991                        for i = 1:size(ChangeList,1)
992                           
993                            k = find(ChangeList(i,1) == BPMlist(:,1));
994                            l = find(ChangeList(i,2) == BPMlist(k,2));
995                           
996                            prompt = {sprintf('Enter the new horizontal goal orbit for BPMx(%d,%d):', ...
997                                BPMlist(k(l),1), BPMlist(k(l),2)), ...
998                                sprintf('Enter the new vertical goal orbit for BPMz(%d,%d):', ...
999                                BPMlist(k(l),1),BPMlist(k(l),2))};
1000                            def = {sprintf('%f',Xgoal(k(l))),sprintf('%f',Ygoal(k(l)))};
1001                            titlestr = 'CHANGE THE GOAL ORBIT';
1002                            lineNo = 1;
1003                            answer = inputdlg(prompt, titlestr, lineNo, def);
1004                           
1005                            if isempty(answer)
1006                                % No change
1007                                fprintf('   No change was made to the golden orbit.\n');
1008                            else
1009                                Xgoalnew = str2num(answer{1});
1010                                if isempty(Xgoalnew)
1011                                    fprintf('   No change was made to the horizontal golden orbit.\n');
1012                                else
1013                                    Xgoal(k(l)) = Xgoalnew;
1014                                end
1015                               
1016                                Ygoalnew = str2num(answer{2});
1017                                if isempty(Ygoalnew)
1018                                    fprintf('   No change was made to the vertical golden orbit.\n');
1019                                else
1020                                    Ygoal(k(l)) = Ygoalnew;
1021                                end
1022                            end
1023                        end
1024                       
1025                        if ~isempty(ChangeList)
1026                            fprintf('   Note:  changing the goal orbit for "Orbit Correction" does not change the goal orbit for "Slow Orbit Feedback."\n');
1027                            fprintf('          Re-running soleilinit will restart the goal orbit to the golden orbit."\n');
1028                        end
1029                       
1030                    case 11 % RF flag edition
1031                        RFCorrFlag = questdlg(sprintf('Set RF Frequency during Orbit Correction?'),'RF Frequency','Yes','No', 'No');
1032                        if strcmp(RFCorrFlag,'No')
1033                            disp('   RF Frequency will not be included in global orbit correction.');
1034                        elseif strcmp(RFCorrFlag,'Yes')
1035                            disp('   RF Frequency will be included in global orbit correction.');
1036                        end
1037                        FB.RFCorrFlag = RFCorrFlag;
1038                end
1039            end
1040            close(h_fig1);
1041        end
1042        % END of switchyard for orbit correction edition
1043       
1044        % This part is common for case 'orbit correction edition'
1045       
1046        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1047        % Build up Orbit correction Structures   %
1048        %  for setorbit programme : OCSx and OCSy%
1049        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1050        %  ORBIT CORRECTION STRUCTURE (OCS)
1051        %    OCS.BPM (data structure)
1052        %    OCS.CM  (data structure)
1053        %    OCS.GoalOrbit
1054        %    OCS.NIter
1055        %    OCS.SVDIndex
1056        %    OCS.IncrementalFlag = 'Yes'/'No'
1057        %    OCS.BPMWeight
1058        %    OCS.Flags = { 'FitRF' , etc.  }
1059       
1060       
1061        % Horizontal plane
1062        OCSx.BPM = getx(BPMlist, 'struct');
1063        OCSx.GoalOrbit = Xgoal;
1064        OCSx.CM  = getsp(HCMFamily, HCMlist, 'struct','Model');
1065        OCSx.NIter = 1; % Number of iteration
1066        OCSx.SVDIndex = Xivec; % number of eigenvectors for correction
1067        OCSx.IncrementalFlag = 'No';
1068        if strcmp(RFCorrFlag,'Yes')
1069            OCSx.FitRF = 1; % take RF as a corrector
1070        else
1071            OCSx.FitRF = 0;
1072        end
1073       
1074        %Default weight for correctores and BPMs
1075        OCSx.CMWeight  = HCMweight;
1076        OCSx.BPMWeight = Xweight;
1077       
1078        % Vertical plane
1079        OCSy.BPM = getz(BPMlist, 'struct');
1080        OCSy.CM  = getsp(VCMFamily, VCMlist, 'struct','Model');
1081        OCSy.GoalOrbit = Ygoal;
1082        OCSy.NIter = 1;
1083        OCSy.SVDIndex = Yivec;
1084        OCSy.IncrementalFlag = 'No';
1085        OCSy.FitRF = 0;
1086       
1087        %Default weight for correctors and BPMs
1088        OCSy.CMWeight  = VCMweight;
1089        OCSy.BPMWeight = Yweight;
1090       
1091        % Save structures for later orbit correction
1092        FB.OCSx = OCSx;
1093        FB.OCSy = OCSy;
1094       
1095        % List of BPM et correctors to be used
1096        FB.BPMlist = BPMlist;
1097        FB.HCMlist = HCMlist;
1098        FB.VCMlist = VCMlist;
1099       
1100        % List of singular values
1101        FB.Xivec = Xivec;
1102        FB.Yivec = Yivec;
1103       
1104        % Goal orbit
1105        FB.Xgoal = OCSx.GoalOrbit;
1106        FB.Ygoal = OCSy.GoalOrbit;
1107       
1108        % Correction Gain
1109        FB.Xgain = Xgain;
1110        FB.Ygain = Ygain;
1111       
1112        % Correction Thresholds
1113        FB.dhcmStd = dhcmStd;
1114        FB.dvcmStd = dvcmStd;
1115        FB.deltaRFmax=deltaRFmax;
1116        FB.deltaRFmin=deltaRFmin;       
1117        FB.DCCTMIN=DCCTMIN;
1118       
1119        % RF corrector flag
1120        FB.RFCorrFlag = RFCorrFlag;
1121       
1122        % save FB structure in application
1123        set(findobj(gcbf,'Tag','ORBITCTRLButtonOrbitCorrectionSetup'),'Userdata',FB);
1124       
1125        %% OrbitCorrection
1126    case 'OrbitCorrection' % Manual Orbit Correction
1127       
1128        try
1129            if strcmp(getmode(BPMxFamily),'Online') && strcmp(getmode(BPMyFamily),'Online')
1130                %look for already running SOFB
1131                check4feedbackflag(devLockName, FB.UPDATE_FOFB)
1132            end
1133            %setup average data for reading BPMs
1134            setfamilydata('gethbpmaverage',BPMxFamily,'Monitor', 'SpecialFunctionGet')
1135            setfamilydata('getvbpmaverage',BPMyFamily,'Monitor', 'SpecialFunctionGet')
1136           
1137        catch err
1138            fprintf('\n  %s \n',lasterr);
1139            fprintf('   %s \n', datestr(clock));
1140            disp('   ********************************');
1141            disp('   **  Orbit Correction Aborted  **');
1142            disp('   ********************************');
1143            fprintf('\n');
1144            return
1145        end
1146       
1147        OrbitLoopIter = 4; % a 4 step iteration
1148       
1149        fprintf('\n');
1150        fprintf('   *********************************\n');
1151        fprintf('   **  Starting Orbit Correction  **\n');
1152        fprintf('   *********************************\n');
1153        fprintf('   %s \n', datestr(clock));
1154       
1155        StartFlag = questdlg(sprintf('Start orbit correction ?'),'Orbit Correction','Yes','No','No');
1156        if strcmp(StartFlag,'No')
1157            disp('   ********************************');
1158            disp('   **  Orbit Correction Aborted  **');
1159            disp('   ********************************');
1160            fprintf('\n');
1161            return
1162        end
1163       
1164        % get Structure for correction
1165        FB = get(findobj(gcbf,'Tag','ORBITCTRLButtonOrbitCorrectionSetup'),'Userdata');
1166        DCCTMIN=FB.DCCTMIN;
1167           
1168        if getdcct < DCCTMIN    % Don't correct the orbit if the current is too small
1169            fprintf('   Orbit not corrected due to small current.\n');
1170            return
1171        end
1172       
1173       
1174        fprintf('   Starting horizontal and vertical global orbit correction (SVD method).\n');
1175       
1176        % Number of steerer magnet correctors
1177        N_HCM = size(FB.HCMlist,1);
1178        N_VCM = size(FB.VCMlist,1);
1179       
1180        %Compare OrbitCorrection and feedback BPM lists and display a warning if different
1181        OC_BPMlist = FB.BPMlist
1182        SOFB = get(findobj(gcbf,'Tag','ORBITCTRLButtonFeedbackSetup'),'Userdata');
1183        FB_BPMlist= SOFB.BPMlist;
1184        if size(OC_BPMlist,1)==size(FB_BPMlist,1)
1185            for i=1:size(OC_BPMlist,1)
1186                k = find(OC_BPMlist(i,1) == FB_BPMlist(:,1));
1187                l = find(OC_BPMlist(i,2) == FB_BPMlist(k,2));
1188                if isempty(k) || isempty(l)
1189                   list_comparison(i)=0;
1190                else
1191                   list_comparison(i)=1;
1192                end
1193            end
1194            if ~isempty(find(list_comparison==0))
1195                BPMlist_difference=1;
1196            else
1197                BPMlist_difference=0;
1198            end
1199        else
1200            BPMlist_difference=1;
1201        end
1202        if BPMlist_difference
1203            ListFlag = questdlg(sprintf('Manual correction and feedback BPM lists are different.\n Do you want to continue ?'),'Warning','Yes','No','No');
1204                if strcmp(ListFlag,'No')
1205                    disp('   ********************************');
1206                    disp('   **  Orbit Correction Aborted  **');
1207                    disp('   ********************************');
1208                    fprintf('\n');
1209                    return
1210                else
1211                   fprintf('** Correction started with different BPM list compared to feedback one** \n');
1212                end
1213        end
1214
1215       
1216        for iloop = 1:OrbitLoopIter,
1217            try
1218                %%%%%%%%%%%%%%%%%
1219                % use the following to get corrector settings in OCS and
1220                % check everything seems Ok and gives back predicted correction
1221                %% H-plane checks
1222                if get(findobj(gcbf,'Tag','ORBITCTRLCheckboxHcorrection'),'Value') == 1
1223                    HOrbitCorrectionFlag = 1;
1224                    % Get new corrector values without applying
1225                    FB.OCSx = setorbit(FB.OCSx,'Nodisplay','Nosetsp');
1226                    %FB.OCSx = setorbit(FB.OCSx,'Nodisplay','Nosetsp','FitRFHCM0');
1227                                       
1228                    HCMSP = getsp(HCMFamily, FB.HCMlist);  % present corrector values
1229                    HCMSP_next = HCMSP + FB.OCSx.CM.Delta(1:N_HCM); % next corrector values, just slow correctors (no RF)
1230                   
1231                    % get max values for the correctors
1232                    MaxSP = maxsp(HCMFamily,FB.HCMlist);
1233                    MinSP = minsp(HCMFamily,FB.HCMlist);
1234                   
1235                    % Check values
1236                    if any(MaxSP - HCMSP_next  < 0)
1237                        HCMnum = find(HCMSP_next > MaxSP);
1238                        % message to screen
1239                        fprintf('**One or more of the horizontal correctors is at its maximum positive value!! Stopping orbit feedback. \n');
1240                        fprintf('%s\n',datestr(now));
1241                        fprintf('**%s is one of the problem correctors.\n', ...
1242                            cell2mat(family2tango(HCMFamily,'Setpoint',FB.HCMlist(HCMnum(1),:))));
1243                        HOrbitCorrectionFlag = 0;
1244                    end
1245                   
1246                    if any(MinSP - HCMSP_next  > 0)
1247                        HCMnum = find(HCMSP_next < MinSP);
1248                        % message to screen
1249                        fprintf('**One or more of the horizontal correctors is at its maximum negative value!! Stopping orbit feedback. \n');
1250                        fprintf('%s\n',datestr(now));
1251                        fprintf('**%s is one of the problem correctors.\n', ...
1252                            cell2mat(family2tango(HCMFamily,'Setpoint',FB.HCMlist(HCMnum(1),:))));
1253                        HOrbitCorrectionFlag = 0;
1254                    end
1255                   
1256                    if any(HCMSP_next > MaxSP - 1)
1257                        HCMnum = find(HCMSP_next > MaxSP - 1);
1258                        for ik = 1:length(HCMnum)
1259                            fprintf('**Horizontal correctors %s is above %f! \n', ...
1260                                cell2mat(family2tango(HCMFamily,'Setpoint',FB.HCMlist(HCMnum(ik),:))), ...
1261                                MaxSP(HCMnum(ik)) - 1);
1262                        end
1263                        fprintf('%s\n',datestr(now));
1264                        fprintf('**The orbit correction is still working but this problem should be investigated. \n');
1265                    end
1266                   
1267                    if any(HCMSP_next < MinSP + 1)
1268                        HCMnum = find(HCMSP_next < MinSP + 1);
1269                        for ik = 1:length(HCMnum)
1270                            fprintf('**Horizontal correctors %s is below %f! \n', ...
1271                                cell2mat(family2tango(HCMFamily,'Setpoint',FB.HCMlist(HCMnum(ik),:))), ...
1272                                MinSP(HCMnum(ik)) + 1);
1273                        end
1274                        fprintf('%s\n',datestr(now));
1275                        fprintf('**The orbit correction is still working but this problem should be investigated. \n');
1276                    end
1277                end
1278               
1279                %% V-plane checks
1280                if get(findobj(gcbf,'Tag','ORBITCTRLCheckboxVcorrection'),'Value') ==1
1281                    FB.OCSy = setorbit(FB.OCSy,'Nodisplay','Nosetsp');
1282                    VOrbitCorrectionFlag = 1;
1283                    VCMSP = getsp(VCMFamily,FB.VCMlist); % Get corrector values before correction
1284                    VCMSP_next = VCMSP + FB.OCSy.CM.Delta(1:N_VCM); % New corrector values to be set in
1285                   
1286                    MaxSP = maxsp(VCMFamily,FB.VCMlist);
1287                    MinSP = minsp(VCMFamily,FB.VCMlist);
1288                   
1289                    if any(MaxSP - VCMSP_next  < 0)
1290                        VCMnum = find(VCMSP_next > MaxSP);
1291                        % message to screen
1292                        fprintf('**One or more of the vertical correctors is at its maximum positive value!! Stopping orbit feedback. \n');
1293                        fprintf('%s\n',datestr(now));
1294                        fprintf('**%s is one of the problem correctors.\n', ...
1295                            cell2mat(family2tango(VCMFamily,'Setpoint',FB.VCMlist(VCMnum(1),:))));
1296                    end
1297                   
1298                    if any(MinSP - VCMSP_next  > 0)
1299                        VCMnum = find(VCMSP_next < MinSP);
1300                        % message to screen
1301                        fprintf('**One or more of the vertical correctors is at its maximum negative value!! Stopping orbit feedback. \n');
1302                        fprintf('%s\n',datestr(now));
1303                        fprintf('**%s is one of the problem correctors.\n', ...
1304                            cell2mat(family2tango(VCMFamily,'Setpoint',FB.VCMlist(VCMnum(1),:))));
1305                    end
1306                   
1307                    if any(VCMSP_next > MaxSP - 1)
1308                        VCMnum = find(VCMSP_next > MaxSP - 1);
1309                        for ik = 1:length(VCMnum)
1310                            fprintf('**Vertical correctors %s is above %f! \n', ...
1311                                cell2mat(family2tango(VCMFamily,'Setpoint',FB.VCMlist(VCMnum(ik),:))), ...
1312                                MaxSP(VCMnum(ik)) - 1);
1313                        end
1314                        fprintf('%s\n',datestr(now));
1315                        fprintf('**The orbit correction is still working but this problem should be investigated. \n');
1316                    end
1317                   
1318                    if any(VCMSP_next < MinSP + 1)
1319                        VCMnum = find(VCMSP_next < MinSP + 1);
1320                        for ik = 1:length(VCMnum)
1321                            fprintf('**Vertical correctors %s is below %f! \n', ...
1322                                cell2mat(family2tango(VCMFamily,'Setpoint',FB.VCMlist(VCMnum(ik),:))), ...
1323                                MinSP(VCMnum(ik)) + 1);
1324                        end
1325                        fprintf('%s\n',datestr(now));
1326                        fprintf('**The orbit correction is still working but this problem should be investigated. \n');
1327                    end
1328                end
1329               
1330                %%%%%%%%%%%%%%%%%%%%%%
1331               
1332                %                 if FB.UPDATE_FOFB && 1
1333                %                     figure;
1334                %                     subplot(2,1,1)
1335                %                     plot(getspos('BPMx', FB.OCSx.BPM.DeviceList),  FB.OCSx.BPM.PredictedOrbitDelta)
1336                %                     grid on;
1337                %                     ylabel('Delta X (mm)');
1338                %                     title(sprintf('%s RMS', max(abs(FB.OCSx.CM.Delta))));
1339                %
1340                %                     subplot(2,1,2)
1341                %                     plot(getspos('BPMz', FB.OCSy.BPM.DeviceList),  FB.OCSy.BPM.PredictedOrbitDelta)
1342                %                     grid on;
1343                %                     xlabel('S-position (m)')
1344                %                     ylabel('Delta Z (mm)');
1345                %                     title(sprintf('%s RMS', max(abs(FB.OCSy.CM.Delta))));
1346                %                     suptitle('Orbit Predicted')
1347                %                 end
1348               
1349                %% manual correction and interaction with FOFB
1350                if FB.UPDATE_FOFB
1351                    %% update reference orbit for FOFB
1352                    xRefFOFB = getx(FB.OCSx.BPM.DeviceList) + FB.OCSx.BPM.PredictedOrbitDelta;
1353                    tango_write_attribute2(devFOFBManager, 'xRefOrbit', xRefFOFB');
1354                    tango_command_inout2(devFOFBManager, 'StartStep04LoadXRefOrbit');
1355                    fprintf(' New X-Reference orbit updated for FOFB \n')
1356                   
1357                    zRefFOFB = getz(FB.OCSy.BPM.DeviceList) + FB.OCSy.BPM.PredictedOrbitDelta;
1358                    tango_write_attribute2(devFOFBManager, 'zRefOrbit', zRefFOFB');
1359                    tango_command_inout2(devFOFBManager, 'StartStep05LoadZRefOrbit');
1360                    fprintf(' New Z-Reference orbit updated for FOFB \n')
1361                end
1362               
1363               
1364                if (get(findobj(gcbf,'Tag','ORBITCTRLCheckboxHcorrection'),'Value') == 1) && HOrbitCorrectionFlag
1365                    % Correct horizontal orbit
1366                    FB.OCSx = setorbit(FB.OCSx,'NoDisplay');
1367                    %FB.OCSx = setorbit(FB.OCSx,'NoDisplay', 'FitRFHCM0');
1368                end
1369               
1370                if (get(findobj(gcbf,'Tag','ORBITCTRLCheckboxVcorrection'),'Value') == 1) && VOrbitCorrectionFlag
1371                    % Correct vertical orbit
1372                    FB.OCSy = setorbit(FB.OCSy,'NoDisplay');
1373                end
1374               
1375                % Check for current in machine - stop orbit correction if
1376                % DCCT < DCCTMIN
1377                if (getdcct < DCCTMIN)
1378                    error('**There is less than %d in the machine! Stopping orbit correction.', DCCTMIN);
1379                end
1380               
1381                % Residual orbit
1382                Horbit = getx(FB.OCSx.BPM.DeviceList);
1383                Vorbit = getz(FB.OCSy.BPM.DeviceList);
1384               
1385                % compute new Delta of closed orbit
1386                x = FB.OCSx.GoalOrbit - Horbit;
1387                y = FB.OCSy.GoalOrbit - Vorbit;
1388               
1389                fprintf('   %d. Horizontal RMS = %.3f mm (absolute %.3f mm)\n', iloop, std(x), std(Horbit));
1390                fprintf('   %d.   Vertical RMS = %.3f mm (absolute %.3f mm)\n', iloop, std(y), std(Vorbit));
1391               
1392                pause(2);
1393               
1394            catch err
1395                fprintf('   %s \n',lasterr);
1396                fprintf('   Orbit correction failed due to error condition!\n  Fix the problem, reload the lattice (refreshthering), and try again.  \n\n');
1397                return
1398            end
1399        end
1400       
1401        fprintf('   %s \n', datestr(clock));
1402        fprintf('   *********************************\n');
1403        fprintf('   **  Orbit Correction Complete  **\n');
1404        fprintf('   *********************************\n\n');
1405       
1406        %setup manager data for reading BPMs
1407        setfamilydata('gethbpmgroup',BPMxFamily,'Monitor', 'SpecialFunctionGet')
1408        setfamilydata('getvbpmgroup',BPMyFamily,'Monitor', 'SpecialFunctionGet')
1409       
1410        %% FeedbackSetup
1411    case 'FeedbackSetup' % Slow orbit Feedback (SOFB)
1412       
1413        InitFlag = Input2;           % Input #2: if InitFlag, then initialize variables
1414       
1415        if InitFlag % Used only at startup
1416            %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1417            % Edit the following lists to change default configuration of Orbit Correction %
1418            %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1419           
1420            % WARNING CAN BE DIFFERENT FROM THE ORBIT CORRECTION
1421            % To start with same correctors and Bpms are used as in manual
1422            % correction
1423            % Corrector magnets
1424           
1425           
1426            if 1 || FB.UPDATE_FOFB
1427                [HCMlist VCMlist BPMlist FHCMlist FVCMlist] = getlocallist;
1428            else
1429                [HCMlist VCMlist BPMlist] = getlocallist;
1430            end
1431           
1432            % Singular value number
1433            Xivec = 1:57;
1434            Yivec = 1:57;
1435
1436            % Correction Gain values
1437            Xgain = 1;
1438            Ygain = 1;
1439            % Display default value on main pannel
1440            set(findobj(gcbf,'Tag','ORBITCTRLStaticTextGainH'),'string',['Gain = ',num2str(Xgain)]);
1441            set(findobj(gcbf,'Tag','ORBITCTRLStaticTextGainV'),'string',['Gain = ',num2str(Ygain)]);
1442         
1443            % Correctors Thresholds
1444            dhcmStd=0.0003;
1445            dvcmStd=0.0003;
1446            % Display default value on main pannel
1447            set(findobj(gcbf,'Tag','ORBITCTRLStaticTextThresholdH'),'string',['Min = ',num2str(dhcmStd),' A']);
1448            set(findobj(gcbf,'Tag','ORBITCTRLStaticTextThresholdV'),'string',['Min = ',num2str(dvcmStd),' A']);
1449         
1450            %RF Thresholds
1451            deltaRFmax=10e-6;
1452            deltaRFmin=0.3e-6;
1453            % Display new value on main pannel
1454            set(findobj(gcbf,'Tag','ORBITCTRLStaticTextMinRF'),'string',['Min = ',num2str(deltaRFmin),' Hz']);
1455            set(findobj(gcbf,'Tag','ORBITCTRLStaticTextMaxRF'),'string',['Min = ',num2str(deltaRFmax),' Hz']);
1456           
1457            %DCCT threshold
1458            DCCTMIN=0.001;
1459            % Display new value on main pannel
1460            set(findobj(gcbf,'Tag','ORBITCTRLStaticTextDCCT'),'string',['Min Current to Start = ',num2str(DCCTMIN),' A']);
1461           
1462            % Get goal orbit for SOFB
1463            Xgoal = getgolden(BPMxFamily, BPMlist);
1464            Ygoal = getgolden(BPMyFamily, BPMlist);
1465           
1466            % BPM weights
1467            Xweight = ones(size(BPMlist,1), 1);
1468            Yweight = ones(size(BPMlist,1), 1);
1469           
1470            % Correctors weights
1471            HCMweight = ones(size(HCMlist,1), 1);
1472            VCMweight = ones(size(VCMlist,1), 1);
1473           
1474            if 1 || FB.UPDATE_FOFB
1475                set(findobj(gcbf,'Tag','ORBITCTRLCheckboxFB'), 'BackgroundColor', [0 1 0], 'Value', 1);
1476            else
1477                set(findobj(gcbf,'Tag','ORBITCTRLCheckboxFB'), 'BackgroundColor', [0 0 0], 'Value', 0);
1478            end
1479           
1480            if 1 || FB.UPDATE_FOFB
1481                % Read configuration of FOFB sotred into a file by FOFB gui
1482                FOFBstruct = makeFOFBstruct;
1483            end
1484           
1485        else % use for SOFB Edition
1486           
1487            % Get FB structure
1488            FB = get(findobj(gcbf,'Tag','ORBITCTRLButtonFeedbackSetup'),'Userdata');
1489           
1490            BPMlist = FB.BPMlist;
1491            HCMlist = FB.HCMlist;
1492            VCMlist = FB.VCMlist;
1493           
1494            Xivec = FB.Xivec;
1495            Yivec = FB.Yivec;
1496           
1497            Xgoal = FB.Xgoal;
1498            Ygoal = FB.Ygoal;
1499         
1500            Xgain = FB.Xgain;
1501            Ygain = FB.Ygain;
1502         
1503            dhcmStd=FB.dhcmStd;
1504            dvcmStd=FB.dvcmStd;
1505           
1506            deltaRFmax=FB.deltaRFmax;
1507            deltaRFmin=FB.deltaRFmin;
1508           
1509            DCCTMIN=FB.DCCTMIN;
1510           
1511            HCMweight = FB.OCSx.CMWeight;
1512            VCMweight = FB.OCSy.CMWeight;
1513            Xweight = FB.OCSx.BPMWeight;
1514            Yweight = FB.OCSy.BPMWeight;
1515           
1516            % Add button to change #ivectors, cm
1517            EditFlag = 0;
1518            h_fig1 = figure;
1519           
1520            while EditFlag ~= 11
1521               
1522                % get Sensitivity matrices
1523                Sx = getrespmat(BPMxFamily, BPMlist, HCMFamily, HCMlist, [], SR_GEV);
1524                Sy = getrespmat(BPMyFamily, BPMlist, VCMFamily, VCMlist, [], SR_GEV);
1525               
1526                % Compute SVD
1527                [Ux, SVx, Vx] = svd(Sx);
1528                [Uy, SVy, Vy] = svd(Sy);
1529               
1530                % Remove singular values greater than the actual number of singular values
1531                i = find(Xivec>length(diag(SVx)));
1532                if ~isempty(i)
1533                    disp('   Horizontal singular value vector scaled since there were more elements in the vector than singular values.');
1534                    pause(0);
1535                    Xivec(i) = [];
1536                end
1537                i = find(Yivec>length(diag(SVy)));
1538                if ~isempty(i)
1539                    disp('   Vertical singular value vector scaled since there were more elements in the vector than singular values.');
1540                    pause(0);
1541                    Yivec(i) = [];
1542                end
1543               
1544                % Display singular value plot
1545                figure(h_fig1);
1546                subplot(2,1,1);
1547                semilogy(diag(SVx),'b');
1548                hold on;
1549                semilogy(diag(SVx(Xivec,Xivec)),'xr');
1550                ylabel('Horizontal');
1551                title('Response Matrix Singular Values');
1552                hold off;
1553                subplot(2,1,2);
1554                semilogy(diag(SVy),'b');
1555                hold on;
1556                semilogy(diag(SVy(Yivec,Yivec)),'xr');
1557                xlabel('Singular Value Number');
1558                ylabel('Vertical');
1559                hold off;
1560                drawnow;
1561               
1562                % Build up menu edition
1563                EditFlag = menu('Change Parameters?','Singular Values',...
1564                    'Correction Gains', 'Correction Thresholds',...
1565                    'HCM List', 'HCM weight', ...
1566                    'VCM List', 'VCM weight', ...
1567                    'BPM List', 'BPM weight', 'Change the Goal Orbit', 'Return');
1568               
1569                % Begin SOFB edition switchyard
1570                switch EditFlag
1571                    case 1
1572                        prompt = {'Enter the horizontal singular value number (Matlab vector format):', ...
1573                            'Enter the vertical singular value numbers (Matlab vector format):'};
1574                        def = {sprintf('[%d:%d]',1,Xivec(end)),sprintf('[%d:%d]',1,Yivec(end))};
1575                        titlestr='SVD Orbit Feedback';
1576                        lineNo=1;
1577                        answer=inputdlg(prompt,titlestr,lineNo,def);
1578                        if ~isempty(answer)
1579                            XivecNew = fix(str2num(answer{1}));
1580                            if isempty(XivecNew)
1581                                disp('   Horizontal singular value vector cannot be empty.  No change made.');
1582                            else
1583                                if any(XivecNew<=0) || max(XivecNew)>length(diag(SVx))
1584                                    disp('   Error reading horizontal singular value vector.  No change made.');
1585                                else
1586                                    Xivec = XivecNew;
1587                                end
1588                            end
1589                            YivecNew = fix(str2num(answer{2}));
1590                            if isempty(YivecNew)
1591                                disp('   Vertical singular value vector cannot be empty.  No change made.');
1592                            else
1593                                if any(YivecNew<=0) || max(YivecNew)>length(diag(SVy))
1594                                    disp('   Error reading vertical singular value vector.  No change made.');
1595                                else
1596                                    Yivec = YivecNew;
1597                                end
1598                            end
1599                        end
1600                       
1601                       
1602                    case 2 % Correction Gain edition
1603
1604                        % Build up matlab prompt
1605                        prompt = {'Enter the horizontal loop gain value :', ...
1606                            'Enter the vertical loop gain value :'};
1607                        % default values
1608                        def = {sprintf('%d',Xgain),sprintf('%d',Ygain)};
1609                        titlestr = 'Change loop gain value';
1610                        lineNo = 1;
1611
1612                        answer = inputdlg(prompt,titlestr,lineNo,def);
1613
1614                        % Answer parsing
1615                        if ~isempty(answer)
1616                            % Horizontal plane
1617                            XgainNew = str2num(answer{1});
1618                            if isempty(XgainNew)
1619                                disp('   Horizontal gain value cannot be empty.  No change made.');
1620                            else
1621                                if (XgainNew<=0)
1622                                    disp('   Error reading horizontal gain value. No change made.');
1623                                else
1624                                    Xgain = XgainNew;
1625                                    % Display new value on main pannel
1626                                    set(findobj(gcbf,'Tag','ORBITCTRLStaticTextGainH'),'string',['Gain = ',num2str(Xgain)]);
1627                                 end
1628                            end
1629                            % Vertical plane
1630                            YgainNew = str2num(answer{2});
1631                            if isempty(YgainNew)
1632                                disp('   Vertical gain value cannot be empty.  No change made.');
1633                            else
1634                                if (YgainNew<=0)
1635                                    disp('   Error reading vertical gain value.  No change made.');
1636                                else
1637                                    Ygain = YgainNew;
1638                                    % Display new value on main pannel
1639                                    set(findobj(gcbf,'Tag','ORBITCTRLStaticTextGainV'),'string',['Gain = ',num2str(Ygain)]);
1640                                end
1641                            end
1642                        end
1643                       
1644                    case 3 % Correction Threshold edition
1645
1646                        % Build up matlab prompt
1647                        prompt = {'Enter the horizontal corrector threshold value (A):', ...
1648                            'Enter the vertical corrector threshold value (A):',...
1649                           'Enter the maximum RF correction value (MHz):', ...
1650                            'Enter the minimum RF correction value (MHz):',...
1651                            'Enter the DCCT threshold value (mA):'};
1652                        % default values
1653                        def = {sprintf('%d',dhcmStd),sprintf('%d',dvcmStd),sprintf('%d',deltaRFmax),sprintf('%d',deltaRFmin),sprintf('%d',DCCTMIN)};
1654                        titlestr = 'Change Correction Threshold values';
1655                        lineNo = 1;
1656
1657                        answer = inputdlg(prompt,titlestr,lineNo,def);
1658
1659                        % Answer parsing
1660                        if ~isempty(answer)
1661                            % Horizontal plane
1662                            dhcmStdNew = str2num(answer{1});
1663                            if isempty(dhcmStdNew)
1664                                disp('   Horizontal corrector threshold value cannot be empty.  No change made.');
1665                            else
1666                                if (dhcmStdNew<=0)
1667                                    disp('   Error reading horizontalcorrector threshold value. No change made.');
1668                                else
1669                                    dhcmStd = dhcmStdNew;
1670                                    % Display new value on main pannel
1671                                    set(findobj(gcbf,'Tag','ORBITCTRLStaticTextThresholdH'),'string',['Min = ',num2str(dhcmStd),' A']);
1672                                 end
1673                            end
1674                            % Vertical plane
1675                            dvcmStdNew = str2num(answer{2});
1676                            if isempty(dvcmStdNew)
1677                                disp('   Vertical corrector threshold value cannot be empty.  No change made.');
1678                            else
1679                                if (dvcmStdNew<=0)
1680                                    disp('   Error reading vertical corrector threshold value.  No change made.');
1681                                else
1682                                    dvcmStd = dvcmStdNew;
1683                                     % Display new value on main pannel
1684                                    set(findobj(gcbf,'Tag','ORBITCTRLStaticTextThresholdV'),'string',['Min = ',num2str(dvcmStd),' A']);
1685                              end
1686                            end
1687                            % RF max
1688                            deltaRFmaxNew = str2num(answer{3});
1689                            if isempty( deltaRFmaxNew)
1690                                disp('   Maximum RF threshold value cannot be empty.  No change made.');
1691                            else
1692                                if ( deltaRFmaxNew<=0)
1693                                    disp('   Error reading Maximum RF threshold value. No change made.');
1694                                else
1695                                     deltaRFmax =  deltaRFmaxNew;
1696                                     % Display new value on main pannel
1697                                    set(findobj(gcbf,'Tag','ORBITCTRLStaticTextMaxRF'),'string',['Max = ',num2str(deltaRFmax),' Hz']);
1698                               end
1699                            end
1700                           % RF min
1701                            deltaRFminNew = str2num(answer{4});
1702                            if isempty( deltaRFminNew)
1703                                disp('   Minimum RF threshold value cannot be empty.  No change made.');
1704                            else
1705                                if ( deltaRFminNew<=0)
1706                                    disp('   Error reading Minimum RF threshold value. No change made.');
1707                                else
1708                                     deltaRFmin =  deltaRFminNew;
1709                                    % Display new value on main pannel
1710                                    set(findobj(gcbf,'Tag','ORBITCTRLStaticTextMinRF'),'string',['Min = ',num2str(deltaRFmin),' Hz']);
1711                                 end
1712                            end
1713                            % DCCT min
1714                            DCCTMINNew = str2num(answer{5});
1715                            if isempty( DCCTMINNew)
1716                                disp('   Minimum DCCT threshold value cannot be empty.  No change made.');
1717                            else
1718                                if ( DCCTMINNew<=0)
1719                                    disp('   Error reading Minimum DCCT threshold value. No change made.');
1720                                else
1721                                     DCCTMIN =  DCCTMINNew;
1722                                     % Display new value on main pannel
1723                                    set(findobj(gcbf,'Tag','ORBITCTRLStaticTextDCCT'),'string',['Min Current to Start = ',num2str(DCCTMIN),' mA']);
1724                                end
1725                            end
1726   
1727                        end
1728                       
1729                    case 4 % Horizontal corrector list edition
1730                        List= getlist(HCMFamily);
1731                        CheckList = zeros(size(List,1));
1732                        ListOld = HCMlist;
1733                        Elem = dev2elem(HCMFamily, HCMlist);
1734                        CheckList(Elem) = ones(size(Elem));
1735                        CheckList = CheckList(dev2elem(HCMFamily,List));
1736                       
1737                        newList = editlist(List, HCMFamily, CheckList);
1738                       
1739                        if isempty(newList)
1740                            fprintf('   Horizontal corrector magnet list cannot be empty.  No change made.\n');
1741                        else
1742                            HCMlist = newList;
1743                        end
1744                       
1745                        %set correctors weight values
1746                        HCMweightOld = HCMweight;
1747                        HCMweight = ones(size(HCMlist,1), 1);
1748                       
1749                        %if a new corrector is added, then set the weight values to
1750                        %one.
1751                        % Otherwise keep the present weight values
1752                        for i = 1:size(HCMlist,1)
1753                           
1754                            % Is it a new corrector?
1755                            k = find(HCMlist(i,1)==ListOld(:,1));
1756                            l = find(HCMlist(i,2)==ListOld(k,2));
1757                           
1758                            if isempty(k) || isempty(l)
1759                                % New corrector
1760                            else
1761                                % Use the old value for old correctors
1762                                HCMweight(i) = HCMweightOld(k(l));
1763                            end
1764                        end
1765                       
1766                    case 5 % Horizontal corrector weight edition
1767                       
1768                        % Ask user to select HCM for modifying weight
1769                        ChangeList = editlist(HCMlist, 'Change HCM', ...
1770                            zeros(size(HCMlist,1),1));
1771                       
1772                        % Ask the new weight for each selected corrector
1773                        for i = 1:size(ChangeList,1)
1774                           
1775                            k = find(ChangeList(i,1) == HCMlist(:,1));
1776                            l = find(ChangeList(i,2) == HCMlist(k,2));
1777                           
1778                            prompt = {sprintf('Enter the new weight for HCM(%d,%d):', ...
1779                                HCMlist(k(l),1), HCMlist(k(l),2))};
1780                            def = {sprintf('%f',HCMweight(k(l))),sprintf('%f',HCMweight(k(l)))};
1781                            titlestr = 'CHANGE THE HCM WEIGHTS';
1782                            lineNo = 1;
1783                            answer = inputdlg(prompt, titlestr, lineNo, def);
1784                           
1785                            if isempty(answer)
1786                                % No change
1787                                fprintf('   No change was made to the VCM weight.\n');
1788                            else
1789                                HCMweightnew = str2num(answer{1});
1790                                if isempty(HCMweightnew)
1791                                    fprintf('   No change was made to the horizontal BPM weight.\n');
1792                                else
1793                                    HCMweight(k(l)) = HCMweightnew;
1794                                end
1795                            end
1796                        end
1797                       
1798                        if ~isempty(ChangeList)
1799                            fprintf('   Note:  changing the HCM weight for "Slow Orbit Feedback" does not change the goal orbit for "Orbit Correction."\n');
1800                        end
1801                       
1802                    case 6 % Vertical corrector list edition
1803                        List = getlist(VCMFamily);
1804                        CheckList = zeros(size(List,1));
1805                        ListOld = VCMlist;
1806                        Elem = dev2elem(VCMFamily, VCMlist);
1807                        CheckList(Elem) = ones(size(Elem));
1808                        CheckList = CheckList(dev2elem(VCMFamily,List));
1809                       
1810                        newList = editlist(List, VCMFamily, CheckList);
1811                       
1812                        if isempty(newList)
1813                            fprintf('   Vertical corrector magnet cannot be empty.  No change made.\n');
1814                        else
1815                            VCMlist = newList;
1816                        end
1817                       
1818                        %set correctors weight values
1819                        VCMweightOld = VCMweight;
1820                        VCMweight = ones(size(VCMlist,1), 1);
1821                       
1822                        %if a new corrector is added, then set the weight values to
1823                        %one.
1824                        % Otherwise keep the present weight values
1825                        for i = 1:size(VCMlist,1)
1826                           
1827                            % Is it a new corrector?
1828                            k = find(VCMlist(i,1)==ListOld(:,1));
1829                            l = find(VCMlist(i,2)==ListOld(k,2));
1830                           
1831                            if isempty(k) || isempty(l)
1832                                % New corrector
1833                            else
1834                                % Use the old value for old correctors
1835                                VCMweight(i) = VCMweightOld(k(l));
1836                            end
1837                        end
1838                       
1839                    case 7 % Vertical corrector weight edition
1840                        % Ask user to select VCM for modifying weight
1841                        ChangeList = editlist(VCMlist, 'Change VCM', ...
1842                            zeros(size(VCMlist,1),1));
1843                       
1844                        % Ask the new weight for each selected corrector
1845                        for i = 1:size(ChangeList,1)
1846                           
1847                            k = find(ChangeList(i,1) == VCMlist(:,1));
1848                            l = find(ChangeList(i,2) == VCMlist(k,2));
1849                           
1850                            prompt = {sprintf('Enter the new weight for VCM(%d,%d):', ...
1851                                VCMlist(k(l),1), VCMlist(k(l),2))};
1852                            def = {sprintf('%f',VCMweight(k(l))),sprintf('%f',VCMweight(k(l)))};
1853                            titlestr = 'CHANGE THE VCM WEIGHTS';
1854                            lineNo = 1;
1855                            answer = inputdlg(prompt, titlestr, lineNo, def);
1856                           
1857                            if isempty(answer)
1858                                % No change
1859                                fprintf('   No change was made to the VCM weight.\n');
1860                            else
1861                                VCMweightnew = str2num(answer{1});
1862                                if isempty(VCMweightnew)
1863                                    fprintf('   No change was made to the horizontal BPM weight.\n');
1864                                else
1865                                    VCMweight(k(l)) = VCMweightnew;
1866                                end
1867                            end
1868                        end
1869                       
1870                        if ~isempty(ChangeList)
1871                            fprintf('   Note:  changing the VCM weight for "Slow Orbit Feedback" does not change the goal orbit for "Orbit Correction."\n');
1872                        end
1873                       
1874                    case 8 % BPM List edition
1875                        % Back present BPM list and goal orbit
1876                        ListOld = BPMlist;
1877                        XgoalOld = Xgoal;
1878                        YgoalOld = Ygoal;
1879                        XweightOld = Xweight;
1880                        YweightOld = Yweight;
1881                       
1882                        List = family2dev(BPMxFamily);
1883                       
1884                        %Check BPM already in the list CheckList(i) = 1
1885                        %      BPM not in the list CheckList(i) = 0
1886                        CheckList = zeros(size(List,1),1);
1887                        if ~isempty(BPMlist)
1888                            for i = 1:size(List,1)
1889                                k = find(List(i,1)==BPMlist(:,1));
1890                                l = find(List(i,2)==BPMlist(k,2));
1891                               
1892                                if isempty(k) || isempty(l)
1893                                    % Item not in list
1894                                else
1895                                    CheckList(i) = 1;
1896                                end
1897                            end
1898                        end
1899                       
1900                        % User edition of the BPM lsit
1901                        newList = editlist(List, 'BPM', CheckList);
1902                        if isempty(newList)
1903                            fprintf('   BPM list cannot be empty.  No change made.\n');
1904                        else
1905                            BPMlist = newList;
1906                        end
1907                       
1908                        % Set the goal orbit to the golden orbit and weight values
1909                        Xgoal = getgolden(BPMxFamily, BPMlist);
1910                        Ygoal = getgolden(BPMyFamily, BPMlist);
1911                        Xweight = ones(size(BPMlist,1),1);
1912                        Yweight = ones(size(BPMlist,1),1);
1913                       
1914                        %if a new BPM is added, then set the goal orbit to
1915                        %the golden orbit.
1916                        % Otherwise keep the present goal orbit
1917                        for i = 1:size(BPMlist,1)
1918                           
1919                            % Is it a new BPM?
1920                            k = find(BPMlist(i,1)==ListOld(:,1));
1921                            l = find(BPMlist(i,2)==ListOld(k,2));
1922                           
1923                            if isempty(k) || isempty(l)
1924                                % New BPM
1925                            else
1926                                % Use the old value for old BPM
1927                                Xgoal(i) = XgoalOld(k(l));
1928                                Ygoal(i) = YgoalOld(k(l));
1929                                Xweight(i) = XweightOld(k(l));
1930                                Yweight(i) = YweightOld(k(l));
1931                            end
1932                        end
1933                       
1934                    case 9 % BPM weight edition
1935                        % Ask user to select BPM for modifying weight
1936                        ChangeList = editlist(BPMlist, 'Change BPM', ...
1937                            zeros(size(BPMlist,1),1));
1938                       
1939                        % Ask the new weight for each selected BPM
1940                        for i = 1:size(ChangeList,1)
1941                           
1942                            k = find(ChangeList(i,1) == BPMlist(:,1));
1943                            l = find(ChangeList(i,2) == BPMlist(k,2));
1944                           
1945                            prompt = {sprintf('Enter the new weight for BPMx(%d,%d):', ...
1946                                BPMlist(k(l),1), BPMlist(k(l),2)), ...
1947                                sprintf('Enter the new weight for BPMz(%d,%d):', ...
1948                                BPMlist(k(l),1),BPMlist(k(l),2))};
1949                            def = {sprintf('%f',Xweight(k(l))),sprintf('%f',Yweight(k(l)))};
1950                            titlestr = 'CHANGE THE BPM WEIGHTS';
1951                            lineNo = 1;
1952                            answer = inputdlg(prompt, titlestr, lineNo, def);
1953                           
1954                            if isempty(answer)
1955                                % No change
1956                                fprintf('   No change was made to the BPM weight.\n');
1957                            else
1958                                Xweightnew = str2num(answer{1});
1959                                if isempty(Xweightnew)
1960                                    fprintf('   No change was made to the horizontal BPM weight.\n');
1961                                else
1962                                    Xweight(k(l)) = Xweightnew;
1963                                end
1964                               
1965                                Yweightnew = str2num(answer{2});
1966                                if isempty(Yweightnew)
1967                                    fprintf('   No change was made to the vertical BPM weight.\n');
1968                                else
1969                                    Yweight(k(l)) = Yweightnew;
1970                                end
1971                            end
1972                        end
1973                       
1974                        if ~isempty(ChangeList)
1975                            fprintf('   Note:  changing the BPM weight for "Slow Orbit Feedback" does not change the goal orbit for "Orbit Correction."\n');
1976                        end
1977                       
1978                    case 10 % Goal orbit edition
1979                        ChangeList = editlist(BPMlist, 'Change BPM', zeros(size(BPMlist,1),1));
1980                       
1981                        for i = 1:size(ChangeList,1)
1982                           
1983                            k = find(ChangeList(i,1)==BPMlist(:,1));
1984                            l = find(ChangeList(i,2)==BPMlist(k,2));
1985                           
1986                            prompt={sprintf('Enter the new horizontal goal orbit for BPMx(%d,%d):', ...
1987                                BPMlist(k(l),1),BPMlist(k(l),2)), ...
1988                                sprintf('Enter the new vertical goal orbit for BPMz(%d,%d):', ...
1989                                BPMlist(k(l),1),BPMlist(k(l),2))};
1990                            def={sprintf('%f',Xgoal(k(l))),sprintf('%f',Ygoal(k(l)))};
1991                            titlestr='CHANGE THE GOAL ORBIT';
1992                            lineNo=1;
1993                            answer = inputdlg(prompt, titlestr, lineNo, def);
1994                           
1995                            if isempty(answer)
1996                                % No change
1997                                fprintf('   No change was made to the golden orbit.\n');
1998                            else
1999                                Xgoalnew = str2num(answer{1});
2000                                if isempty(Xgoalnew)
2001                                    fprintf('   No change was made to the horizontal golden orbit.\n');
2002                                else
2003                                    Xgoal(k(l)) = Xgoalnew;
2004                                end
2005                               
2006                                Ygoalnew = str2num(answer{2});
2007                                if isempty(Ygoalnew)
2008                                    fprintf('   No change was made to the vertical golden orbit.\n');
2009                                else
2010                                    Ygoal(k(l)) = Ygoalnew;
2011                                end
2012                            end
2013                        end
2014                       
2015                        if ~isempty(ChangeList)
2016                            fprintf('   Note:  Changing the goal orbit for "Slow Orbit Feedback" does not change the goal orbit for "Orbit Correction."\n');
2017                            fprintf('          Re-running srcontrol will restart the goal orbit to the golden orbit."\n');
2018                        end
2019                end
2020            end
2021            close(h_fig1);
2022        end
2023       
2024        % End of SOFB edition switchyard
2025       
2026        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2027        %         Build up SOFB Structures       %
2028        %  for setorbit programme : OCSx and OCSy%
2029        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2030        %  ORBIT CORRECTION STRUCTURE (OCS)
2031        %    OCS.BPM (data structure)
2032        %    OCS.CM  (data structure)
2033        %    OCS.GoalOrbit
2034        %    OCS.NIter
2035        %    OCS.SVDIndex
2036        %    OCS.IncrementalFlag = 'Yes'/'No'
2037        %    OCS.BPMWeight
2038        %    OCS.Flags = { 'FitRF' , etc.  }
2039       
2040        OCSx.BPM = getx(BPMlist, 'struct');
2041        OCSx.CM =  getsp(HCMFamily, HCMlist, 'struct');
2042        OCSx.GoalOrbit = Xgoal;
2043        OCSx.NIter = 2;
2044        OCSx.SVDIndex = Xivec;
2045        OCSx.IncrementalFlag = 'No';
2046        OCSx.CMWeight  = HCMweight;
2047        OCSx.BPMWeight = Xweight;
2048        OCSx.FitRF = 0;
2049       
2050        OCSy.BPM = getz(BPMlist, 'struct');
2051        OCSy.CM = getsp(VCMFamily, VCMlist, 'struct');
2052        OCSy.GoalOrbit = Ygoal;
2053        OCSy.NIter = 2;
2054        OCSy.SVDIndex = Yivec;
2055        OCSy.IncrementalFlag = 'No';
2056        OCSy.CMWeight  = VCMweight;
2057        OCSy.BPMWeight = Yweight;
2058        OCSy.FitRF = 0;
2059       
2060        % Save SOFB strucutre
2061        FB.OCSx = OCSx;
2062        FB.OCSy = OCSy;
2063       
2064        % BPM and CM list
2065        FB.BPMlist = BPMlist;
2066        FB.HCMlist = HCMlist;
2067        FB.VCMlist = VCMlist;
2068       
2069        % Singular value number
2070        FB.Xivec = Xivec;
2071        FB.Yivec = Yivec;
2072       
2073        % Goal orbit list
2074        FB.Xgoal = Xgoal;
2075        FB.Ygoal = Ygoal;
2076       
2077        % Correction Gain
2078        FB.Xgain = Xgain;
2079        FB.Ygain = Ygain;
2080       
2081        % Correction Thresholds
2082        FB.dhcmStd = dhcmStd;
2083        FB.dvcmStd = dvcmStd;
2084        FB.deltaRFmax=deltaRFmax;
2085        FB.deltaRFmin=deltaRFmin;
2086       
2087        FB.DCCTMIN=DCCTMIN;
2088       
2089        % save Feedback struture
2090        set(findobj(gcbf,'Tag','ORBITCTRLButtonFeedbackSetup'),'Userdata',FB);
2091       
2092        % save configuration data for FOFB into a file!
2093        DirName = getfamilydata('Directory', 'FOFBdata');
2094        save(fullfile(DirName, 'SOFBconfiguration'), 'FB');
2095       
2096        % Construction of the data set for FOFB part
2097        %         if FB.UPDATE_FOFB
2098        %             %FOFBstruct.BPMlist = FBPMlist;
2099        %             %FOFBstruct.HCMlist = HCMlist;
2100        %             %FOFBstruct.VCMlist= VCMlist;
2101        %             %FOFBstruct.Xivec = FXivec;
2102        %             %FOFBstruct.Yivec = FYivec;
2103        %             set(findobj(gcbf,'Tag','ORBITCTRLButtonFeedbackSetup'),'FOFB',FOFB);
2104        %         end
2105        %
2106       
2107        %% Feedback
2108    case 'Feedback'
2109        %FBloopIter = 3; % number of iterations for each loop
2110       
2111        FEEDBACK_STOP_FLAG = 0;
2112       
2113        % Warning Flag for stale correctors
2114        HWarnNum = 0;
2115        VWarnNum = 0;
2116       
2117        % Feedback loop setup
2118        LoopDelay = 10.0;    % Period of feedback loop [seconds], make sure the BPM averaging is correct
2119       
2120        FB=get(findobj(gcbf,'Tag','ORBITCTRLButtonFeedbackSetup'),'Userdata');
2121       
2122        % Percentage of correction to apply at each iteration
2123        %Xgain  = 0.8;
2124        %Ygain  = 0.8;
2125        %Xgain  = 1.0;
2126        %Ygain  = 1.0;
2127        Xgain = FB.Xgain; 
2128        Ygain = FB.Ygain;
2129 
2130        % Minimum corrector strength for applying correction
2131        %dhcmStd = 0.0015/4;
2132        %dvcmStd = 0.0005/2;
2133       
2134        % thresholds for multibunch filling pattern
2135        %dhcmStd = 0.0001;
2136        %dvcmStd = 0.0001;
2137       
2138        % thresholds for multibunch filling pattern FOFB
2139        %dhcmStd = 0.0003;
2140        %dvcmStd = 0.0003;
2141        dhcmStd = FB.dhcmStd; 
2142        dvcmStd = FB.dvcmStd;
2143 
2144       
2145        % thresholds for 8 bunch filling pattern
2146        %dhcmStd = 0.00; %15/15/10;
2147        %dvcmStd = 0.00; % 05/5/10;
2148       
2149        % Maximum allowed frequency shift during a single correction
2150        %deltaRFmax = 10e-6; % MHz
2151        %deltaRFmin = 0.3e-6; % MHz ie 0.1 Hz
2152        deltaRFmax = FB.deltaRFmax;
2153        deltaRFmin = FB.deltaRFmin;
2154       
2155        DCCTMIN=FB.DCCTMIN;
2156       
2157        % Load lattice set for tune feed forward
2158       
2159        set(0,'showhiddenhandles','on');
2160        BPMxfullList = family2dev('BPMx',0); % included status 0
2161        BPMyfullList = family2dev('BPMz',0);
2162       
2163        try
2164           
2165            %setup average data for reading BPMs
2166            setfamilydata('gethbpmaverage',BPMxFamily,'Monitor', 'SpecialFunctionGet')
2167            setfamilydata('getvbpmaverage',BPMyFamily,'Monitor', 'SpecialFunctionGet')
2168           
2169            fprintf('\n');
2170            fprintf('   *******************************\n');
2171            fprintf('   **  Starting Orbit Feedback  **\n');
2172            fprintf('   *******************************\n');
2173            fprintf('   %s \n', datestr(clock));
2174            fprintf('   Note: the Matlab command window will be used to display status information.\n');
2175            fprintf('         It cannot be used to enter commands during slow orbit feedback.\n');
2176           
2177            % Get SOFB Structure
2178            FB = get(findobj(gcbf,'Tag','ORBITCTRLButtonFeedbackSetup'),'Userdata');
2179            if get(findobj(gcbf,'Tag','ORBITCTRLCheckboxRF'),'Value') == 1
2180                FB.OCSx.FitRF = 1;
2181            else
2182                FB.OCSx.FitRF = 0;
2183            end
2184           
2185            % look for already running SOFB
2186            if strcmp(getmode(BPMxFamily),'Online') && strcmp(getmode(BPMyFamily),'Online')
2187                check4feedbackflag(devLockName, FB.UPDATE_FOFB);
2188            end
2189        catch
2190            fprintf('\n  %s \n',lasterr);
2191            fprintf('   %s \n', datestr(clock));
2192            fprintf('   *************************************************************\n');
2193            fprintf('   **  Orbit feedback could not start due to error condition  **\n');
2194            fprintf('   *************************************************************\n\n');
2195            warndlg('Orbit feedback could not start due to error condition');
2196            set(0,'showhiddenhandles','off');
2197            pause(0);
2198            return
2199        end
2200       
2201        %Compare OrbitCorrection and feedback BPM lists and display a warning if different
2202        FB_BPMlist = FB.BPMlist
2203        OC = get(findobj(gcbf,'Tag','ORBITCTRLButtonOrbitCorrectionSetup'),'Userdata');
2204        OC_BPMlist= OC.BPMlist;
2205        if size(OC_BPMlist,1)==size(FB_BPMlist,1)
2206            for i=1:size(OC_BPMlist,1)
2207                k = find(OC_BPMlist(i,1) == FB_BPMlist(:,1));
2208                l = find(OC_BPMlist(i,2) == FB_BPMlist(k,2));
2209                if isempty(k) || isempty(l)
2210                   list_comparison(i)=0;
2211                else
2212                   list_comparison(i)=1;
2213                end
2214            end
2215            if ~isempty(find(list_comparison==0))
2216                BPMlist_difference=1;
2217            else
2218                BPMlist_difference=0;
2219            end
2220        else
2221            BPMlist_difference=1;
2222        end
2223        if BPMlist_difference
2224            ListFlag = questdlg(sprintf('Manual correction and feedback BPM lists are different.\n Do you want to continue ?'),'Warning','Yes','No','No');
2225                if strcmp(ListFlag,'No')
2226                    disp('   ********************************');
2227                    disp('   **  Orbit Correction Aborted  **');
2228                    disp('   ********************************');
2229                    fprintf('\n');
2230                    return
2231                else
2232                   fprintf('** Correction started with different BPM list compared to manualorbit correction one** \n');
2233                end
2234        end
2235
2236       
2237        % Confirmation dialogbox
2238        StartFlag = questdlg('Start orbit feedback?', 'Orbit Feedback','Yes','No','No');
2239        set(findobj(gcbf,'Tag','ORBITCTRLStaticTextInformation'),'String','SOFB Started');
2240       
2241        % Retrieve FOFB Data
2242        if FB.UPDATE_FOFB
2243            %FOFBstruct = getappdata(findobj(gcbf,'Tag','ORBITCTRLButtonFeedbackSetup'), 'FOFBstruct');
2244            FOFBstruct = makeFOFBstruct;
2245            % test if same BPM in SOFB and FOFB
2246            % if not. For now error message
2247            % Later if necessary, set to zero the orbit coming from the reconstruction of FOFB steerer values
2248            BPMError = 0;
2249            [iFound iNotFound] = findrowindex(FOFBstruct.BPMlist,FB.BPMlist);
2250            if isempty(iNotFound)
2251                [iFound iNotFound] = findrowindex(FB.BPMlist, FOFBstruct.BPMlist);
2252                if ~isempty(iNotFound)
2253                    for ik=1:length(iNotFound),
2254                        fprintf('BPM [%2d %2d] missing in FOFB\n', FB.BPMlist(iNotFound(ik),:))
2255                    end
2256                    BPMError = 1;
2257                end
2258            else
2259                for ik=1:length(iNotFound),
2260                    fprintf('BPM [%2d %2d] missing in SOFB\n', FOFBstruct.BPMlist(iNotFound(ik),:))
2261                end
2262                BPMError = 1;
2263            end
2264           
2265            if BPMError
2266                fprintf('Not same BPM in SOFB anf FOFB. Check configuration first\n');
2267                fprintf('SOFB not started\n');
2268                StartFlag = 'No';
2269            end
2270            if FOFBstruct.SOFBandFOFB == 0
2271                fprintf('FOFB not set properly\n');
2272                fprintf('SOFB not started\n');
2273                StartFlag = 'No';
2274            end
2275        end
2276       
2277        if strcmp(StartFlag,'No')
2278            fprintf('   %s \n', datestr(clock));
2279            fprintf('   ***************************\n');
2280            fprintf('   **  Orbit Feedback Exit  **\n');
2281            fprintf('   ***************************\n\n');
2282            pause(0);
2283            return
2284        end
2285       
2286        set(0,'showhiddenhandles','on');
2287       
2288        % Display information
2289       
2290        if get(findobj(gcbf,'Tag','ORBITCTRLCheckboxHSOFB'),'Value') == 1
2291            fprintf('   Using %d singular values horizontally.\n', length(FB.Xivec));
2292        end
2293        if get(findobj(gcbf,'Tag','ORBITCTRLCheckboxVSOFB'),'Value') == 1
2294            fprintf('   Using %d singular values vertically.\n',   length(FB.Yivec));
2295        end
2296        fprintf('   Starting slow orbit correction every %.1f seconds.\n', LoopDelay);
2297       
2298        try
2299            % Compute residual closed orbit
2300            x = FB.Xgoal - getx(FB.BPMlist);
2301            y = FB.Ygoal - getz(FB.BPMlist);
2302           
2303            %STDx = norm(x)/sqrt(length(x));
2304            %STDy = norm(y)/sqrt(length(y));
2305            STDx = std(x);
2306            STDy = std(y);
2307           
2308            set(findobj(gcbf,'Tag','ORBITCTRLStaticTextHorizontal'),'String', ...
2309                sprintf('Horizontal RMS = %.4f mm',STDx),'ForegroundColor',[0 0 0]);
2310            set(findobj(gcbf,'Tag','ORBITCTRLStaticTextVertical'),'String', ...
2311                sprintf('Vertical RMS = %.4f mm',STDy),'ForegroundColor',[0 0 0]);
2312           
2313            if strcmp(getmode(BPMxFamily),'Online') && strcmp(getmode(BPMyFamily),'Online')
2314                % Lock  SOFB service
2315                Locktag  = tango_command_inout2(devLockName,'Lock', 'sofb');
2316            end
2317            pause(0);
2318        catch
2319           
2320            fprintf('\n  %s \n',lasterr);
2321           
2322            fprintf('   %s \n', datestr(clock));
2323            fprintf('   *************************************************************\n');
2324            fprintf('   **  Orbit feedback could not start due to error condition  **\n');
2325            fprintf('   *************************************************************\n\n');
2326            warndlg(' Orbit feedback could not start due to error condition ');
2327            set(0,'showhiddenhandles','off');
2328            pause(0);
2329            return
2330        end
2331       
2332       
2333        % Disable buttons in GUI
2334        set(0,'showhiddenhandles','on');
2335        set(findobj(gcbf,'Tag','ORBITCTRLPushbuttonStart'),'Enable','off');
2336        set(findobj(gcbf,'Tag','ORBITCTRLPushbuttonStop'),'Enable','on');
2337        set(findobj(gcbf,'Tag','ORBITCTRLButtonOrbitCorrection'),'Enable','off');
2338        set(findobj(gcbf,'Tag','ORBITCTRLButtonOrbitCorrectionSetup'),'Enable','off');
2339        set(findobj(gcbf,'Tag','ORBITCTRLButtonFeedbackSetup'),'Enable','off');
2340        set(findobj(gcbf,'Tag','ORBITCTRLClose'),'Enable','off');
2341        set(findobj(gcbf,'Tag','ORBITCTRLCheckboxHSOFB'),'Enable','off');
2342        set(findobj(gcbf,'Tag','ORBITCTRLCheckboxVSOFB'),'Enable','off');
2343        set(findobj(gcbf,'Tag','ORBITCTRLCheckboxHcorrection'),'Enable','off');
2344        set(findobj(gcbf,'Tag','ORBITCTRLCheckboxVcorrection'),'Enable','off');
2345        set(findobj(gcbf,'Tag','ORBITCTRLCheckboxRF'),'Enable','off');
2346        set(findobj(gcbf,'Tag','ORBITCTRLCheckboxFOFB'),'Enable','off')
2347        set(findobj(gcbf,'Tag','ORBITCTRLCheckboxInteractionMode'),'Enable','off')
2348        pause(0);
2349       
2350       
2351        % Initialize feedback loop
2352        StartTime = gettime;
2353        StartErrorTime = gettime;
2354       
2355        % Get orbit before SOFB startup
2356        Xold = getx(FB.BPMlist);
2357        Yold = getz(FB.BPMlist);
2358        % For avoiding stall message for BPM: make a pause
2359        pause(0.2);
2360        % Stale number
2361        RF_frequency_stalenum = 0;
2362       
2363        % Number of steerer magnet corrector
2364        N_HCM = size(FB.HCMlist,1);
2365        N_VCM = size(FB.VCMlist,1);
2366       
2367        % Number of RF actuator
2368        N_RFMO = 1;
2369       
2370        %%%%%%%%%%%%%%%%%%%%%%%
2371        % Start feedback loop %
2372        %%%%%%%%%%%%%%%%%%%%%%%
2373       
2374        setappdata(findobj(gcbf,'Tag','ORBITCTRLFig1'),'FEEDBACK_STOP_FLAG',0);
2375       
2376        %first time
2377        %         if FB.UPDATE_FOFB
2378        %             %% update reference orbit for FOFB
2379        %             tempx = getx(FB.OCSx.BPM.DeviceList);
2380        %             tempz = getz(FB.OCSy.BPM.DeviceList);
2381        %             xRefFOFB = tempx - OffsetSA_FA.X_offset;
2382        %             zRefFOFB = tempz - OffsetSA_FA.Z_offset;
2383        %             % load reference orbit in TANGO
2384        %             tango_write_attribute2(devFOFBManager, 'xRefOrbit', xRefFOFB');
2385        %             tango_write_attribute2(devFOFBManager, 'zRefOrbit', zRefFOFB');
2386        %             % update Libera
2387        %             tango_command_inout2(devFOFBManager, 'StartStep04LoadXRefOrbit');
2388        %             tango_command_inout2(devFOFBManager, 'StartStep05LoadZRefOrbit');
2389        %             fprintf(' A startup Golden orbit updated for FOFB \n')
2390        %         end
2391       
2392       
2393        while FEEDBACK_STOP_FLAG == 0 % infinite loop
2394            try
2395                t00 = gettime;
2396                fprintf('\nIteration time %s\n',datestr(clock));
2397               
2398                % Check if GUI has been closed
2399                if isempty(gcbf)
2400                    FEEDBACK_STOP_FLAG = 1;
2401                    lasterr('SRCONTROL GUI DISAPPEARED!');
2402                    error('SRCONTROL GUI DISAPPEARED!');
2403                end
2404               
2405                %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2406                % Horizontal plane "feedback" %
2407                %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2408               
2409                % Get orbit and check that the BPMs are different from the last update
2410                Xnew = getx(FB.BPMlist);
2411               
2412                if any(isnan(Xnew))
2413                    FEEDBACK_STOP_FLAG = 1;
2414                    fprintf('%s         Orbit feedback stopped due to bad BPMs\n',datestr(now));
2415                    BadBPMName = family2tangodev(BPMxFamily, FB.BPMlist(isnan(Xnew),:));
2416                    for k=1:size(BadBPMName,1),
2417                        fprintf('Bad Horizontal BPM (Nan) %s\n',BadBPMName{k});
2418                    end
2419                    if strcmp(getmode(BPMxFamily),'Online')
2420                        strgMessage = 'Arret de la correction d''orbite : problÚme BPM';
2421                        tango_giveInformationMessage(devSpeakerName,  strgMessage);
2422                    end
2423                    warndlg(' Arret de la correction d''orbite : problÚme BPM ');
2424                    break;
2425                end
2426               
2427                if getdcct < DCCTMIN     % Don't feedback if the current is too small
2428                    FEEDBACK_STOP_FLAG = 1;
2429                    fprintf('%s         Orbit feedback stopped due to low beam current (<%d mA)\n',datestr(now), DCCTMIN);
2430                    if strcmp(getmode(BPMxFamily),'Online')
2431                        strgMessage = 'Arret de la correction d''orbite : courant trop bas';
2432                        tango_giveInformationMessage(devSpeakerName,  strgMessage);
2433                    end
2434                    warndlg(' Arret de la correction d''orbite : courant trop bas ');
2435                    break;
2436                end
2437               
2438                x = FB.Xgoal - Xnew;
2439                STDx = std(x);
2440               
2441                if get(findobj(gcbf,'Tag','ORBITCTRLCheckboxHSOFB'),'Value') == 1
2442                    if any(Xold == Xnew)
2443                        N_Stale_Data_Points = find((Xold==Xnew)==1);
2444                        for i = N_Stale_Data_Points'
2445                            fprintf('   Stale data: BPMx(%2d,%d), feedback step skipped (%s). \n', ...
2446                                FB.BPMlist(i,1), FB.BPMlist(i,2), datestr(clock));
2447                        end
2448                    else
2449                        if FB.UPDATE_FOFB
2450                            % recontruction of the orbit from DC part of fast correctors
2451                            %dxFOFB = gethorbitFOFB;
2452                            % TODO select only valid BPM and correctors
2453                            FHCM = getpv('FHCOR' ,'SetpointMean', FOFBstruct.HCMlist);
2454                            fprintf('FHCOR I = %4.2f A RMS   I = %4.2f A PEAK   I = %4.2f A PEAK\n', ...
2455                                std(FHCM), mean(FHCM), max(abs(FHCM)));
2456                           
2457                            % building orbit from steerer value
2458                            % Alternative use singular values (to be done if required)
2459                            FOFBstruct.OCSx.dx = FOFBstruct.OCSx.Rmat*FHCM; % Rmat has only valid BPM and CM
2460                           
2461                            % Update Goal orbit  by subtracting the rebuild orbit from FOFB steerers
2462                            FB.OCSx.GoalOrbit = getgolden('BPMx', FB.BPMlist) + FOFBstruct.OCSx.dx;
2463                        end
2464                       
2465                        % Computes correction only
2466                        FB.OCSx = setorbit(FB.OCSx,'Nodisplay','Nosetsp');
2467                       
2468                        X = Xgain .* FB.OCSx.CM.Delta;
2469                       
2470                        % check for corrector values and next step values, warn or stop FB as necessary
2471                        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2472                        HCMSP = getsp(HCMFamily, FB.HCMlist);  % present corrector values
2473                        HCMSP_next = HCMSP + X(1:N_HCM);       % next corrector values, just slow correctors (no RF)
2474                       
2475                        MaxSP = maxsp(HCMFamily,FB.HCMlist);
2476                        MinSP = minsp(HCMFamily,FB.HCMlist);
2477                       
2478                        if any(MaxSP - HCMSP_next  < 0)
2479                            HCMnum = find(HCMSP_next > MaxSP);
2480                            % message to screen
2481                            fprintf('**One or more of the horizontal correctors is at its maximum positive value!! Stopping orbit feedback. \n');
2482                            fprintf('%s\n',datestr(now));
2483                            fprintf('**%s is one of the problem correctors.\n', ...
2484                                cell2mat(family2tango(HCMFamily,'Setpoint',FB.HCMlist(HCMnum(1),:))));
2485                            if strcmp(getmode(BPMxFamily),'Online')
2486                                strgMessage = 'ProblÚme de la correction d''orbite';
2487                                tango_giveInformationMessage(devSpeakerName,  strgMessage);
2488                            end
2489                            FEEDBACK_STOP_FLAG = 1;
2490                        end
2491                       
2492                        if any(MinSP - HCMSP_next  > 0)
2493                            HCMnum = find(HCMSP_next < MinSP);
2494                            % message to screen
2495                            fprintf('**One or more of the horizontal correctors is at its maximum negative value!! Stopping orbit feedback. \n');
2496                            fprintf('%s\n',datestr(now));
2497                            fprintf('**%s is one of the problem correctors.\n', ...
2498                                cell2mat(family2tango(HCMFamily,'Setpoint',FB.HCMlist(HCMnum(1),:))));
2499                            FEEDBACK_STOP_FLAG = 1;
2500                            if strcmp(getmode(BPMxFamily),'Online')
2501                                strgMessage = 'ProblÚme de la correction d''orbite';
2502                                tango_giveInformationMessage(devSpeakerName,  strgMessage);
2503                            end
2504                            warndlg('One or more of the horizontal correctors is at its maximum negative value!! Stopping orbit feedback.')
2505                        end
2506                       
2507                        pause(0);
2508                       
2509                        if any(HCMSP_next > MaxSP - 1)
2510                            HCMnum = find(HCMSP_next > MaxSP - 1);
2511                            for ik = 1:length(HCMnum)
2512                                HWarnNum = HWarnNum+1;
2513                                fprintf('**Horizontal correctors %s is above %f! \n', ...
2514                                    cell2mat(family2tango(HCMFamily,'Setpoint',FB.HCMlist(HCMnum(ik),:))), ...
2515                                    MaxSP(HCMnum(ik)) - 1);
2516                            end
2517                            fprintf('%s\n',datestr(now));
2518                            fprintf('**The orbit feedback is still working but this problem should be investigated. \n');
2519                            if strcmp(getmode(BPMxFamily),'Online')
2520                                strgMessage = 'ProblÚme de la correction d''orbite';
2521                                tango_giveInformationMessage(devSpeakerName,  strgMessage);
2522                            end
2523                        end
2524                       
2525                        if any(HCMSP_next < MinSP + 1)
2526                            HCMnum = find(HCMSP_next < MinSP + 1);
2527                            for ik = 1:length(HCMnum)
2528                                HWarnNum = HWarnNum+1;
2529                                fprintf('**Horizontal correctors %s is below %f! \n', ...
2530                                    cell2mat(family2tango(HCMFamily,'Setpoint',FB.HCMlist(HCMnum(ik),:))), ...
2531                                    MinSP(HCMnum(ik)) + 1);
2532                            end
2533                            fprintf('%s\n',datestr(now));
2534                            fprintf('**The orbit feedback is still working but this problem should be investigated. \n');
2535                            if strcmp(getmode(BPMxFamily),'Online')
2536                                strgMessage = 'ProblÚme de la correction d''orbite';
2537                                tango_giveInformationMessage(devSpeakerName,  strgMessage);
2538                            end
2539                        end
2540                       
2541                        if getdcct < DCCTMIN     % Don't feedback if the current is too small
2542                            FEEDBACK_STOP_FLAG = 1;
2543                            fprintf('%s         Orbit feedback stopped due to low beam current (<%d mA)\n',datestr(now), DCCTMIN);
2544                            if strcmp(getmode(BPMxFamily),'Online')
2545                                strgMessage = 'Arret de la correction d''orbite : courant trop bas';
2546                                tango_giveInformationMessage(devSpeakerName,  strgMessage);
2547                            end
2548                            warndlg(sprintf('%s         Orbit feedback stopped due to low beam current (<%d mA)\n',datestr(now), DCCTMIN))
2549                            break;
2550                        end
2551                       
2552                       
2553                        %% interaction with FOFB
2554                        % Warning Reference orbit for all BPMs has to be updated
2555                        if FB.UPDATE_FOFB
2556                            try
2557                                isxFOFBRunning = readattribute([devFOFBManager '/xFofbRunning']);
2558                                FOFBManagerState = readattribute([devFOFBManager, '/State']);
2559                                %FOFBManagerState = 0 if no error and Feedback running at least in one plane
2560                            catch
2561                                fprintf('UPDATEFOFB  SOFB stopped (H-plane).\n');
2562                                if strcmp(getmode(BPMxFamily),'Online')
2563                                    strgMessage = 'Arret de la correction d''orbite : problÚme TANGO';
2564                                    tango_giveInformationMessage(devSpeakerName,  strgMessage);
2565                                end
2566                                FEEDBACK_STOP_FLAG = 1;
2567                                break;
2568                            end
2569                           
2570                            if isxFOFBRunning && ~FOFBManagerState
2571                                %% update reference orbit for FOFB
2572                                tempx = getx(FB.OCSx.BPM.DeviceList) + FB.OCSx.BPM.PredictedOrbitDelta - FOFBstruct.OCSx.dx;
2573                               
2574                                % figure;
2575                                %  plot(getspos('BPMx'), FB.OCSx.BPM.PredictedOrbitDelta); hold on;
2576                                % plot(getspos('BPMx'), FOFBstruct.OCSx.dx, 'r')
2577                               
2578                                % Keep allvalue for BPM not in the loop
2579                                FOFBstruct.OCSx.XRefOrbit = tango_read_attribute2(devFOFBManager, 'xRefOrbit');
2580                                FOFBstruct.OCSx.XRefOrbit = FOFBstruct.OCSx.XRefOrbit.value;
2581                               
2582                                % Check out all BPMs in the loop
2583                                BPMxIdx = findrowindex(FOFBstruct.BPMlist, BPMxfullList);
2584                               
2585                                % Retrieve offsets between FOFB and SOFB
2586                                FOFBstruct.OCSx.XRefOrbit(BPMxIdx) = tempx;
2587                               
2588                                % Chexk delta RF as it is a condition for
2589                                % FOFB reference update
2590                                if FB.OCSx.FitRF
2591                                    deltaRF = Xgain .* FB.OCSx.DeltaRF;
2592                                else
2593                                    deltaRF=0;
2594                                end
2595                                % update either RF or corrector correction
2596                                % is required
2597                                %isupdateFOFB = (N_HCM > 0 && std(X(1:N_HCM)) > dhcmStd) || (FB.OCSx.FitRF && N_RFMO > 0 &&  abs(deltaRF) > deltaRFmin);
2598                                %isupdateFOFB = (N_HCM > 0 && std(X(1:N_HCM)) > dhcmStd);
2599                                isupdateFOFB = ((N_HCM > 0) && (std(X(1:N_HCM)) > dhcmStd))  || ((FB.OCSx.FitRF && N_RFMO > 0) &&  (abs(deltaRF) > deltaRFmin));
2600                                if isupdateFOFB
2601                                    if strcmp(getmode(BPMxFamily),'Online')
2602                                        % Update reference orbit in TANGO device server
2603                                        tango_write_attribute2(devFOFBManager, 'xRefOrbit', FOFBstruct.OCSx.XRefOrbit);
2604                                       
2605                                        % load reference orbit on all Liberas
2606                                        tango_command_inout2(devFOFBManager, 'StartStep04LoadXRefOrbit');
2607                                       
2608                                        fprintf(' New X-Reference orbit updated for FOFB \n')
2609%                                        fprintf(' N_HCM=%f  std=%f   FB.OCSx.FitRF=%f  N_RFMO=%f   deltaRF=%f \n',N_HCM,std(X(1:N_HCM)),FB.OCSx.FitRF,N_RFMO,abs(deltaRF));
2610                                    end
2611                                else
2612                                    fprintf(' No X-Reference update for FOFB \n')
2613                                end
2614                               
2615                            else
2616                                fprintf('UPDATEFOFB         Orbit feedback stopped. FOFB stopped in H-plane \n');
2617                                fprintf('FOFBmanagerstate is %d (should be O) H-plane is %d (should be 1: running 0: stopped)\n',FOFBManagerState, isxFOFBRunning);
2618                                if strcmp(getmode(BPMxFamily),'Online')
2619                                    strgMessage = 'Arret de la correction d''orbite : plan horizontal';
2620                                    tango_giveInformationMessage(devSpeakerName,  strgMessage);
2621                                end
2622                                FEEDBACK_STOP_FLAG = 1;
2623                                break;
2624                            end
2625                        else
2626                            isupdateFOFB=0;
2627                        end
2628                       
2629                       
2630                        % Apply new corrector values
2631 %                       if N_HCM > 0 && std(X(1:N_HCM)) > dhcmStd                     
2632                        if ((N_HCM > 0 && std(X(1:N_HCM)) > dhcmStd) || isupdateFOFB)
2633                           
2634                            fprintf('HCOR: I= %5.4f A RMS I = %5.4f A MEAN I = %5.4f A PEAK\n', std(X(1:N_HCM)), mean(X(1:N_HCM)), max(abs((X(1:N_HCM)))));
2635                            if strcmp(getmode(HCMFamily),'Online')
2636                                profibus_sync(HCMFamily); pause(0.2);
2637                            end
2638                            stepsp(HCMFamily, X(1:N_HCM), FB.HCMlist, 0);
2639                            if strcmp(getmode(HCMFamily),'Online')
2640                                profibus_unsyncall(HCMFamily);
2641                            end
2642                        else
2643                            fprintf('No horizontal correction  applied, std corrector = %5.4f mA rms < threshold = %5.4f \n', ...
2644                                std(X(1:N_HCM)),dhcmStd);
2645                        end
2646                       
2647                        % Apply RF correction
2648                       
2649                        if FB.OCSx.FitRF
2650                            deltaRF = Xgain .* FB.OCSx.DeltaRF;
2651                            if N_RFMO > 0
2652                                RFfrequency_last = getrf('Retry');
2653                                fprintf('RF frequency shift computed is %5.1f Hz \n', hw2physics('RF','Setpoint', deltaRF));
2654
2655                                %if abs(deltaRF) > deltaRFmin % MHz
2656                                if ((abs(deltaRF) > deltaRFmin) || isupdateFOFB) % MHz
2657                                    if abs(deltaRF) < deltaRFmax % For avoiding too large RF step on orbit
2658                                        ErrorFlag = steprf(deltaRF, 'Retry'); % Masterclock locked, Retry 3 times
2659                                        fprintf('RF change applied by %5.1f Hz\n', hw2physics('RF','Setpoint', deltaRF));
2660                                    else % Apply deltaRFmax only
2661                                        % In this case, FOFB ref orbit is
2662                                        % updated according to the full RF
2663                                        % value -> to be corrected?
2664                                        warning('RF change too large: %5.1f Hz (max is %5.1f Hz)', ...
2665                                            hw2physics('RF','Setpoint', deltaRF), hw2physics('RF','Setpoint', deltaRFmax));
2666                                        ErrorFlag = steprf(deltaRFmax*sign(deltaRF), 'Retry');
2667                                        fprintf('RF change changed by %5.1f Hz\n', hw2physics('RF','Setpoint', deltaRFmax*sign(deltaRF)));
2668                                    end
2669                                   
2670                                    % TEST LAURENT MASTERCLOCK KO, SOFB
2671                                    % does not stop. This is not normal. To
2672                                    % be tested with BEAM
2673                                    if (ErrorFlag == -1)  && strcmp(getmode(BPMxFamily),'Online')
2674                                        strgMessage = 'Arret de la correction d''orbite : problÚme RF';
2675                                        tango_giveInformationMessage(devSpeakerName,  strgMessage);
2676                                        break;
2677                                    end
2678                                   
2679                                    RFfrequency_now = getrf('Retry');
2680                                   
2681                                    % Check for stale RF feedback
2682                                   
2683                                    if (RFfrequency_last == RFfrequency_now)
2684                                        RF_frequency_stalenum = RF_frequency_stalenum + 1;
2685                                        if RF_frequency_stalenum == 30 % - warn and message if stale for 30 secs
2686                                            fprintf('**The RF is not responding to orbit feedback changes! \n');
2687                                            fprintf('%s\n',datestr(now));
2688                                            fprintf('**The orbit feedback is still working but this problem should be investigated. \n');
2689                                        end
2690                                        if rem(RF_frequency_stalenum,120)==0 % - message to screen every 2 minutes
2691                                            fprintf('**The RF is not responding to orbit feedback changes! (%s)\n',datestr(now));
2692                                        end
2693                                    else
2694                                        RF_frequency_stalenum = 0;
2695                                    end
2696                                   
2697                                    fprintf('RF Done: time = %f \n', gettime-t00);
2698                                end
2699                            end
2700                        end
2701                    end
2702                   
2703                    Xold = Xnew;
2704                end % End horizontal correction
2705               
2706               
2707                %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2708                % Vertical plane "feedback" %
2709                %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2710               
2711                % Get orbit and check that the BPMs are different from the last update
2712                Ynew = getz(FB.BPMlist);
2713               
2714                if any(isnan(Ynew))
2715                    FEEDBACK_STOP_FLAG = 1;
2716                    fprintf('%s         Orbit feedback stopped due to bad BPMs\n',datestr(now));
2717                    BadBPMName = family2tangodev(BPMxFamily, FB.BPMlist(isnan(Xnew),:));
2718                    for k=1:size(BadBPMName,1),
2719                        fprintf('Bad Vertical BPM %s\n',BadBPMName{k});
2720                    end
2721                    if strcmp(getmode(BPMxFamily),'Online')
2722                        strgMessage = 'Arret de la correction d''orbite : problÚme BPM';
2723                        tango_giveInformationMessage(devSpeakerName,  strgMessage);   
2724                    end
2725                    break;
2726                end
2727               
2728                if getdcct < DCCTMIN     % Don't feedback if the current is too small
2729                    FEEDBACK_STOP_FLAG = 1;
2730                    fprintf('%s         Orbit feedback stopped due to low beam current (< %d mA)\n', datestr(now), DCCTMIN);
2731                    if strcmp(getmode(BPMxFamily),'Online')
2732                        strgMessage = 'Arret de la correction d''orbite : courant trop bas';
2733                        tango_giveInformationMessage(devSpeakerName,  strgMessage);
2734                    end
2735                    break;
2736                end
2737               
2738                y = FB.Ygoal - Ynew;
2739                STDy = norm(y)/sqrt(length(y));
2740               
2741               
2742                if get(findobj(gcbf,'Tag','ORBITCTRLCheckboxVSOFB'),'Value') == 1
2743                   
2744                    if any(Yold == Ynew)
2745                        fprintf('Info: Stale vertical BPM data, feedback step skipped (%s). \n', datestr(clock));
2746                        N_Stale_Data_Points = find((Yold==Ynew)==1);
2747                        for i = N_Stale_Data_Points'
2748                            fprintf('   Stale data: BPMz(%2d,%d), feedback step skipped (%s). \n', ...
2749                                FB.BPMlist(i,1), FB.BPMlist(i,2), datestr(clock));
2750                        end
2751                       
2752                    else
2753                        if FB.UPDATE_FOFB
2754                            %reconstruction of the orbit from DC part of fast correctors
2755                            %dxFOFB = gethorbitFOFB;
2756                            % TODO select only valid BPM and correctors
2757                            FVCM = getpv('FVCOR','SetpointMean', FOFBstruct.VCMlist, 'Online');
2758                            fprintf('FVCOR I = %4.2f A RMS   I = %4.2f A MEAN   I = %4.2f A PEAK\n', ...
2759                                std(FVCM), mean(FVCM), max(abs(FVCM)));
2760                           
2761                            % building orbit from steerer value
2762                            % Alternative use singular values (to be done if required)
2763                            FOFBstruct.OCSy.dz = FOFBstruct.OCSy.Rmat*FVCM; % Rmat has only valid BPM and CM
2764                           
2765                            % Update GoalOrbot by sustracting the rebuild orbit from FOFB steerers
2766                            % SOFB correction
2767                            FB.OCSy.GoalOrbit = getgolden('BPMz', FB.BPMlist) + FOFBstruct.OCSy.dz;
2768                        end
2769                       
2770                        % Compute correction only
2771                        FB.OCSy = setorbit(FB.OCSy,'Nodisplay','Nosetsp');
2772                        % set to gains for correction
2773                        Y = Ygain .* FB.OCSy.CM.Delta;
2774                       
2775                        % check for trim values+next step values, warn or stop FB as necessary
2776                       
2777                        VCMSP = getsp(VCMFamily,FB.VCMlist); % Get corrector values before correction
2778                        VCMSP_next = VCMSP + Y(1:N_VCM); % New corrector values to be set in
2779                       
2780                        pause(0);
2781                       
2782                        if getdcct < DCCTMIN     % Don't feedback if the current is too small
2783                            fprintf('%s         Orbit feedback stopped due to low beam current (<%d mA)\n',datestr(now), DCCTMIN);
2784                            if strcmp(getmode(BPMxFamily),'Online')
2785                                strgMessage = 'Arret de la correction d''orbite : courant trop bas';
2786                                tango_giveInformationMessage(devSpeakerName,  strgMessage);
2787                            end
2788                            FEEDBACK_STOP_FLAG = 1;
2789                            break;
2790                        end
2791                       
2792                        MaxSP = maxsp(VCMFamily,FB.VCMlist);
2793                        MinSP = minsp(VCMFamily,FB.VCMlist);
2794                       
2795                        if any(MaxSP - VCMSP_next  < 0)
2796                            VCMnum = find(VCMSP_next > MaxSP);
2797                            % message to screen
2798                            fprintf('**One or more of the vertical correctors is at its maximum positive value!! Stopping orbit feedback. \n');
2799                            fprintf('%s\n',datestr(now));
2800                            fprintf('**%s is one of the problem correctors.\n', ...
2801                                cell2mat(family2tango(VCMFamily,'Setpoint',FB.VCMlist(VCMnum(1),:))));
2802                            FEEDBACK_STOP_FLAG = 1;
2803                        end
2804                       
2805                        if any(MinSP - VCMSP_next  > 0)
2806                            VCMnum = find(VCMSP_next < MinSP);
2807                            % message to screen
2808                            fprintf('**One or more of the vertical correctors is at its maximum negative value!! Stopping orbit feedback. \n');
2809                            fprintf('%s\n',datestr(now));
2810                            fprintf('**%s is one of the problem correctors.\n', ...
2811                                cell2mat(family2tango(VCMFamily,'Setpoint',FB.VCMlist(VCMnum(1),:))));
2812                            FEEDBACK_STOP_FLAG = 1;
2813                        end
2814                       
2815                        pause(0);
2816                       
2817                        if any(VCMSP_next > MaxSP - 1)
2818                            VCMnum = find(VCMSP_next > MaxSP - 1);
2819                            for ik = 1:length(VCMnum)
2820                                VWarnNum = VWarnNum+1;
2821                                fprintf('**Vertical correctors %s is above %f! \n', ...
2822                                    cell2mat(family2tango(VCMFamily,'Setpoint',FB.VCMlist(VCMnum(ik),:))), ...
2823                                    MaxSP(VCMnum(ik)) - 1);
2824                            end
2825                            fprintf('%s\n',datestr(now));
2826                            fprintf('**The orbit feedback is still working but this problem should be investigated. \n');
2827                        end
2828                       
2829                        if any(VCMSP_next < MinSP + 1)
2830                            VCMnum = find(VCMSP_next < MinSP + 1);
2831                            for ik = 1:length(VCMnum)
2832                                VWarnNum = VWarnNum+1;
2833                                fprintf('**Vertical correctors %s is below %f! \n', ...
2834                                    cell2mat(family2tango(VCMFamily,'Setpoint',FB.VCMlist(VCMnum(ik),:))), ...
2835                                    MinSP(VCMnum(ik)) + 1);
2836                            end
2837                            fprintf('%s\n',datestr(now));
2838                            fprintf('**The orbit feedback is still working but this problem should be investigated. \n');
2839                        end
2840                       
2841                        % Apply vertical correction
2842                       
2843                        %% interaction with FOFB
2844                        % Warning Reference orbit for all BPMs has to be updated
2845                        if FB.UPDATE_FOFB
2846                            try
2847                                iszFOFBRunning = readattribute([devFOFBManager '/zFofbRunning']);
2848                                FOFBManagerState = readattribute([devFOFBManager, '/State']);
2849                            catch
2850                                fprintf('UPDATEFOFB      SOFB stopped.\n');
2851                                if strcmp(getmode(BPMxFamily),'Online')
2852                                    strgMessage = 'Arret de la correction d''orbite : problÚme TANGO';
2853                                    tango_giveInformationMessage(devSpeakerName,  strgMessage);
2854                                end
2855                                FEEDBACK_STOP_FLAG = 1;
2856                                break;
2857                            end
2858                           
2859                            if iszFOFBRunning && ~FOFBManagerState
2860                                %% update reference orbit for FOFB
2861                                tempz = getz(FB.OCSy.BPM.DeviceList) + FB.OCSy.BPM.PredictedOrbitDelta - FOFBstruct.OCSy.dz;
2862                               
2863                                % figure;
2864                                %  plot(getspos('BPMz'), FB.OCSy.BPM.PredictedOrbitDelta); hold on;
2865                                % plot(getspos('BPMz'), FOFBstruct.OCSy.dz, 'r')
2866                               
2867                                % Keep allvalue for BPM not in the loop
2868                                FOFBstruct.OCSy.ZRefOrbit = tango_read_attribute2(devFOFBManager, 'zRefOrbit');
2869                                FOFBstruct.OCSy.ZRefOrbit = FOFBstruct.OCSy.ZRefOrbit.value;
2870                               
2871                                % Change all BPM in the loop
2872                                BPMyIdx = findrowindex(FOFBstruct.BPMlist, BPMyfullList);
2873                               
2874                                % Retrieve offsets between FOFB and SOFB
2875                                % 21 November Offset disapeared !!!!
2876                                FOFBstruct.OCSy.ZRefOrbit(BPMyIdx) = tempz;
2877                               
2878                                if N_VCM > 0 && std(Y(1:N_VCM)) > dvcmStd
2879                                    if strcmp(getmode(BPMxFamily),'Online')
2880                                        fprintf('VCOR: I= %5.4f A RMS I = %5.4f A MEAN I = %5.4f A PEAK\n', ...
2881                                            std(Y(1:N_VCM)), mean(Y(1:N_VCM)), max(abs((Y(1:N_VCM)))));
2882                                       
2883                                        % Update reference orbit in TANGO device server
2884                                        tango_write_attribute2(devFOFBManager, 'zRefOrbit', FOFBstruct.OCSy.ZRefOrbit);
2885                                       
2886                                        % load reference orbit on all Liberas
2887                                        tango_command_inout2(devFOFBManager, 'StartStep05LoadZRefOrbit');
2888                                       
2889                                        fprintf(' New Z-Reference orbit updated for FOFB \n');
2890                                    end
2891                                else
2892                                    fprintf('No Z-Reference update for FOFB \n');
2893                                end
2894                               
2895                            else
2896                                fprintf('UPDATEFOFB         Orbit feedback stopped. FOFB stopped in V-plane \n');
2897                                fprintf('FOFBmanagerstate is %d (should be O) V-plane is %d (should be 1: running 0: stopped)\n',FOFBManagerState, iszFOFBRunning);
2898                                if strcmp(getmode(BPMxFamily),'Online')
2899                                    strgMessage = 'Arret de la correction d''orbite : plan vertical';
2900                                    tango_giveInformationMessage(devSpeakerName,  strgMessage);
2901                                end
2902                                FEEDBACK_STOP_FLAG = 1;
2903                                break;
2904                            end
2905                        end
2906                       
2907                        if N_VCM > 0 && std(Y(1:N_VCM)) > dvcmStd
2908                            fprintf('VCOR: I= %5.4f A RMS I = %5.4f A MEAN I = %5.4f A PEAK\n', std(Y(1:N_VCM)), mean(Y(1:N_VCM)), max(abs((Y(1:N_VCM)))));
2909                            if strcmp(getmode(VCMFamily),'Online')
2910                                profibus_sync(VCMFamily); pause(0.2);
2911                            end
2912                            stepsp(VCMFamily, Y(1:N_VCM), FB.VCMlist, 0);
2913                            if strcmp(getmode(VCMFamily),'Online')
2914                                profibus_unsyncall(VCMFamily);
2915                            end
2916                        else
2917                            fprintf('No vertical correction  applied, std corrector = %5.4f mA rms < threshold = %5.4f \n', ...
2918                                std(Y(1:N_VCM)),dvcmStd);
2919                        end
2920                    end
2921                end
2922               
2923                Yold = Ynew;
2924               
2925                % Output info to screen
2926                set(findobj(gcbf,'Tag','ORBITCTRLStaticTextHorizontal'), ...
2927                    'String',sprintf('Horizontal RMS = %.4f mm',STDx), ...
2928                    'ForegroundColor',[0 0 0]);
2929                set(findobj(gcbf,'Tag','ORBITCTRLStaticTextVertical'), ...
2930                    'String',sprintf('Vertical RMS = %.4f mm',STDy),...
2931                    'ForegroundColor',[0 0 0]);
2932                pause(0);
2933               
2934                % Wait for next update time or stop request
2935                while FEEDBACK_STOP_FLAG == 0 && (gettime-t00) < LoopDelay
2936                    pause(.1);
2937                    % Check if GUI has been closed
2938                    if isempty(gcbf)
2939                        FEEDBACK_STOP_FLAG = 1;
2940                        lasterr('SRCONTROL GUI DISAPPEARED!');
2941                        error('SRCONTROL GUI DISAPPEARED!');
2942                    end
2943                    if FEEDBACK_STOP_FLAG == 0
2944                        FEEDBACK_STOP_FLAG = getappdata(findobj(gcbf,'Tag','ORBITCTRLFig1'),'FEEDBACK_STOP_FLAG');
2945                    end
2946                end
2947               
2948                StartErrorTime = gettime;
2949               
2950                if strcmp(getmode(BPMxFamily),'Online')
2951                    % Maintain lock on SOFB service
2952                    argin.svalue={'sofb'};
2953                    argin.lvalue=int32(Locktag);
2954                    tango_command_inout2(devLockName,'MaintainLock', argin);
2955                end
2956            catch
2957                fprintf('\n  %s \n',lasterr);
2958                FEEDBACK_STOP_FLAG = 1;
2959                if strcmp(getmode(BPMxFamily),'Online')
2960                    strgMessage = 'Arret de la correction d''orbite : ATTENTION';
2961                    tango_giveInformationMessage(devSpeakerName,  strgMessage);
2962                    profibus_unsyncall(HCMFamily); % to be sure that correctors are controllable
2963                    profibus_unsyncall(VCMFamily); % to be sure that correctors are controllable
2964                end
2965            end
2966           
2967            % Check whether user asked for stopping SOFB
2968            if FEEDBACK_STOP_FLAG == 0
2969                FEEDBACK_STOP_FLAG = getappdata(findobj(gcbf,'Tag','ORBITCTRLFig1'),'FEEDBACK_STOP_FLAG');
2970            end
2971           
2972           
2973        end  % End of feedback loop
2974       
2975       
2976        % End feedback, reset all parameters
2977        try
2978           
2979            % Enable buttons
2980            set(findobj(gcbf,'Tag','ORBITCTRLPushbuttonStart'),'Enable','on');
2981            set(findobj(gcbf,'Tag','ORBITCTRLPushbuttonStop'),'Enable','off');
2982            set(findobj(gcbf,'Tag','ORBITCTRLButtonOrbitCorrection'),'Enable','on');
2983            set(findobj(gcbf,'Tag','ORBITCTRLButtonOrbitCorrectionSetup'),'Enable','on');
2984            set(findobj(gcbf,'Tag','ORBITCTRLButtonFeedbackSetup'),'Enable','on');
2985            set(findobj(gcbf,'Tag','ORBITCTRLClose'),'Enable','on');
2986            set(findobj(gcbf,'Tag','ORBITCTRLCheckboxHSOFB'),'Enable','on');
2987            set(findobj(gcbf,'Tag','ORBITCTRLCheckboxVSOFB'),'Enable','on');
2988            set(findobj(gcbf,'Tag','ORBITCTRLCheckboxHcorrection'),'Enable','on');
2989            set(findobj(gcbf,'Tag','ORBITCTRLCheckboxVcorrection'),'Enable','on');
2990            set(findobj(gcbf,'Tag','ORBITCTRLCheckboxRF'),'Enable','on');
2991            set(findobj(gcbf,'Tag','ORBITCTRLCheckboxFOFB'),'Enable','on')
2992            set(findobj(gcbf,'Tag','ORBITCTRLCheckboxInteractionMode'),'Enable','on')
2993            set(findobj(gcbf,'Tag','ORBITCTRLStaticTextHorizontal'),'String',sprintf('Horizontal RMS = _____ mm'),'ForegroundColor',[0 0 0]);
2994            set(findobj(gcbf,'Tag','ORBITCTRLStaticTextVertical'),'String',sprintf('Vertical RMS = _____ mm'),'ForegroundColor',[0 0 0]);
2995            pause(0);
2996           
2997        catch
2998           
2999            % GUI must have been closed
3000           
3001        end
3002       
3003        fprintf('   %s \n', datestr(clock));
3004        fprintf('   ******************************\n');
3005        fprintf('   **  Orbit Feedback Stopped  **\n');
3006        fprintf('   ******************************\n\n');
3007        set(0,'showhiddenhandles','off');
3008        pause(0);
3009       
3010        if strcmp(getmode(BPMxFamily),'Online') && strcmp(getmode(BPMyFamily),'Online')
3011            % Unlock SOFB service
3012            argin.svalue={'sofb'};
3013            argin.lvalue=int32(Locktag);
3014            tango_command_inout2(devLockName,'Unlock', argin);
3015            %setup average data for reading BPMs
3016            setfamilydata('gethbpmgroup',BPMxFamily,'Monitor', 'SpecialFunctionGet')
3017            setfamilydata('getvbpmgroup',BPMyFamily,'Monitor', 'SpecialFunctionGet')
3018        end
3019       
3020        %% InteractionMode
3021    case 'InteractionMode'
3022       
3023        val = get(findobj(gcbf,'Tag','ORBITCTRLCheckboxInteractionMode'),'Value');
3024       
3025        FOFBstruct = makeFOFBstruct;
3026       
3027        if FOFBstruct.SOFBandFOFB == 0
3028            val = 0;
3029            set(findobj(gcbf,'Tag','ORBITCTRLCheckboxInteractionMode'),'Value', val);
3030            fprintf('FOFB not set properly. Action aborted\n');
3031        end
3032       
3033        set(findobj(gcbf,'Tag','ORBITCTRLCheckboxFB'), 'Value', FOFBstruct.SOFBandFOFB)
3034       
3035        if val % Interaction between feedbacks
3036            set(findobj(gcbf,'Tag','ORBITCTRLFig1'),'Color', [0.84 0 0.89]);
3037        else
3038            set(findobj(gcbf,'Tag','ORBITCTRLFig1'),'Color', [0.1 0.1 1]);
3039        end
3040       
3041        % Load feedback structure
3042        FB = get(findobj(gcbf,'Tag','ORBITCTRLButtonFeedbackSetup'),'Userdata');
3043       
3044        % Set interaction flag
3045        FB.UPDATE_FOFB = val;
3046       
3047        % Save feedback structure
3048        set(findobj(gcbf,'Tag','ORBITCTRLButtonFeedbackSetup'),'Userdata',FB);
3049
3050        %% SOFB H Selected
3051    case 'SOFBHSelected'
3052        %disable RF correction if plane H is not selected
3053         if get(findobj(gcbf,'Tag','ORBITCTRLCheckboxHSOFB'), 'Value')
3054            set(findobj(gcbf,'Tag','ORBITCTRLCheckboxRF'),'Enable','on');
3055            set(findobj(gcbf,'Tag','ORBITCTRLCheckboxRF'), 'Value', 1)
3056        else
3057           set(findobj(gcbf,'Tag','ORBITCTRLCheckboxRF'),'Enable','off'); 
3058           set(findobj(gcbf,'Tag','ORBITCTRLCheckboxRF'), 'Value', 0)
3059         end
3060         
3061    otherwise
3062        fprintf('   Unknown action name: %s.\n', action);
3063       
3064end
3065
3066%% getlocallist
3067function [HCMlist, VCMlist, BPMlist, FHCMlist, FVCMlist] = getlocallist
3068
3069%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3070% Edit the following lists to change default configuration of Orbit Correction %
3071%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3072
3073%TODO:full list and just remove specific device cf LOCO
3074
3075HCMlist = family2dev('HCOR');
3076VCMlist = family2dev('VCOR');
3077
3078FHCMlist = family2dev('FHCOR');
3079FVCMlist = family2dev('FVCOR');
3080
3081% BPMlist = [
3082%     1     2
3083%     1     3
3084%     1     4
3085%     1     5
3086%     1     6
3087%     1     7
3088%     2     1
3089%     2     2
3090%     2     3
3091%     2     4
3092%     2     5
3093%     2     6
3094%     2     7
3095%     2     8
3096%     3     1
3097%     3     2
3098%     3     3
3099%     3     4
3100%     3     5
3101%     3     6
3102%     3     7
3103%     3     8
3104%     4     1
3105%     4     2
3106%     4     3
3107%     4     4
3108%     4     5
3109%     4     6
3110%     4     7
3111%     5     1
3112%     5     2
3113%     5     3
3114%     5     4
3115%     5     5
3116%     5     6
3117%     5     7
3118%     6     1
3119%     6     2
3120%     6     3
3121%     6     4
3122%     6     5
3123%     6     6
3124%     6     7
3125%     6     8
3126%     7     1
3127%     7     2
3128%     7     3
3129%     7     4
3130%     7     5
3131%     7     6
3132%     7     7
3133%     7     8
3134%     8     1
3135%     8     2
3136%     8     3
3137%     8     4
3138%     8     5
3139%     8     6
3140%     8     7
3141%     9     1
3142%     9     2
3143%     9     3
3144%     9     4
3145%     9     5
3146%     9     6
3147%     9     7
3148%     10     1
3149%     10     2
3150%     10     3
3151%     10     4
3152%     10     5
3153%     10     6
3154%     10     7
3155%     10     8
3156%     11     1
3157%     11     2
3158%     11     3
3159%     11     4
3160%     11     5
3161%     11     6
3162%     11     7
3163%     11     8
3164%     12     1
3165%     12     2
3166%     12     3
3167%     12     4
3168%     12     5
3169%     12     6
3170%     12     7
3171%     13     1
3172%     13     2
3173%     13     3
3174%     13     4
3175%     13     5
3176%     13     6
3177%     13     7
3178%     14     1
3179%     14     2
3180%     14     3
3181%     14     4
3182%     14     5
3183%     14     6
3184%     14     7
3185%     14     8
3186%     15     1
3187%     15     2
3188%     15     3
3189%     15     4
3190%     15     5
3191%     15     6
3192%     15     7
3193%     15     8
3194%     16     1
3195%     16     2
3196%     16     3
3197%     16     4
3198%     16     5
3199%     16     6
3200%     16     7
3201%     1     1
3202%     ];
3203
3204BPMlist = [
3205    1     2
3206    1     3
3207    1     4
3208    1     5
3209    1     6
3210    1     7
3211    2     1
3212    2     2
3213    2     3
3214    2     4
3215    2     5
3216    2     6
3217    2     7
3218    2     8
3219    3     1
3220    3     2
3221    3     3
3222    3     4
3223    3     5
3224    3     6
3225    3     7
3226    3     8
3227    4     1
3228    4     2
3229    4     3
3230    4     4
3231    4     5
3232    4     6
3233    4     7
3234    5     1
3235    5     2
3236    5     3
3237    5     4
3238    5     5
3239    5     6
3240    5     7
3241    6     1
3242    6     2
3243    6     3
3244    6     4
3245    6     5
3246    6     6
3247    6     7
3248    6     8
3249    7     1
3250    7     2
3251    7     3
3252    7     4
3253    7     5
3254    7     6
3255    7     7
3256    7     8
3257    8     1
3258    8     2
3259    8     3
3260    8     4
3261    8     5
3262    8     6
3263    8     7
3264    9     1
3265    9     2
3266    9     3
3267    9     4
3268    9     5
3269    9     6
3270    9     7
3271    10     1
3272    10     2
3273    10     3
3274    10     4
3275    10     5
3276    10     6
3277    10     7
3278    10     8
3279    11     1
3280    11     2
3281    11     3
3282    11     4
3283    11     5
3284    11     6
3285    11     7
3286    11     8
3287    12     1
3288    12     2
3289    12     3
3290    12     4
3291    12     5
3292    12     6
3293    12     7
3294    13     1
3295    13     8
3296    13     9
3297    13     2
3298    13     3
3299    13     4
3300    13     5
3301    13     6
3302    13     7
3303    14     1
3304    14     2
3305    14     3
3306    14     4
3307    14     5
3308    14     6
3309    14     7
3310    14     8
3311    15     1
3312    15     2
3313    15     3
3314    15     4
3315    15     5
3316    15     6
3317    15     7
3318    15     8
3319    16     1
3320    16     2
3321    16     3
3322    16     4
3323    16     5
3324    16     6
3325    16     7
3326    1     1
3327    ];
3328
3329%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3330function check4feedbackflag(devLockName,UPDATE_FOFB)
3331
3332BPMxFamily = 'BPMx';
3333BPMyFamily = 'BPMz';
3334devFOFBManager = 'ANS/DG/FOFB-MANAGER';
3335devRFFBManager = 'ANS/DG/RFFB-MANAGER';
3336
3337if strcmp(getmode(BPMxFamily),'Online') && strcmp(getmode(BPMyFamily),'Online')
3338   
3339    if ~UPDATE_FOFB
3340        %look for already running FOFB
3341        xval = readattribute([devFOFBManager '/xFofbRunning']);
3342        zval = readattribute([devFOFBManager '/zFofbRunning']);
3343        if xval == 1 || zval == 1
3344            error('FOFB already running. Stop other application first!')
3345        end
3346    end
3347   
3348    val = readattribute([devLockName '/rffb']);
3349    rfval = readattribute([devRFFBManager '/isRunning']);
3350    if val == 1 || rfval == 1
3351        error('RF FB already running. Stop other application first!')
3352    end
3353    val = readattribute([devLockName '/sofb']);
3354    if val == 1
3355        error('SOFB already running. Stop other application first!')
3356    end
3357    val = readattribute([devLockName '/dcfb']);
3358    if val == 1
3359        error('DC FB already running. Stop other application first!')
3360    end
3361end
3362
3363% make FOFB strucutre
3364function FOFBstruct = makeFOFBstruct
3365
3366% Read FOFB configuration from a file
3367DirName  = getfamilydata('Directory', 'FOFBdata');
3368FileName = fullfile(DirName, 'FOFBconfiguration');
3369temp = load(FileName, 'FB');
3370FOFBstruct = temp.FB;
3371
3372% Compute Response matrix
3373RmatFOFB           = getbpmresp('BPMx', FOFBstruct.BPMlist, 'BPMz', FOFBstruct.BPMlist, 'FHCOR', FOFBstruct.OCSx.CM.DeviceList, 'FVCOR', FOFBstruct.OCSy.CM.DeviceList,  [getfamilydata('Directory','OpsData') getfamilydata('OpsData', 'BPMResp4FOFBFile')], 'Struct');
3374
3375FOFBstruct.OCSx.Rmat     = RmatFOFB(1,1).Data;
3376FOFBstruct.OCSy.Rmat     = RmatFOFB(2,2).Data;
3377
3378% Offsets from FA and SA sources
3379% OffsetSA_FA        = load('/home/operateur/GrpDiagnostics/matlab/FOFB/GUI/golden/offsetSA_FA_02_fevrier_09.mat');
3380%
3381% FOFBstruct.OCSx.OffsetSA_FA = OffsetSA_FA.X_offset; %Becareful need all BPM for FPGA
3382% FOFBstruct.OCSy.OffsetSA_FA = OffsetSA_FA.Z_offset; %Becareful need all BPM for FPGA
3383
3384%setappdata(findobj(gcbf,'Tag','ORBITCTRLButtonFeedbackSetup'), 'FOFBstruct',FOFBstruct);
Note: See TracBrowser for help on using the repository browser.