source: MML/trunk/machine/SOLEIL/StorageRing/FOFB/FOFBguiTango.m @ 4

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

Initial import--MML version from SOLEIL@2013

File size: 162.0 KB
Line 
1function FOFBguiTango(action, Input2, Input3)
2%FOFBguiTango - GUI for FOFB correction configurion and RF Feedback
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 FOFB and manual orbit correction are often different
15%  2. Manual Correction : 3 iterations are done in a row
16
17%
18%  See Also setorbit, FOFBgui
19
20% For Compiler
21%#function lat_2020_3170a
22%#function solamor2linb
23%#function solamor2linc
24%#function gethbpmaverage
25%#function getvbpmaverage
26%#function gethbpmgroup
27%#function getvbpmgroup
28
29
30
31
32%
33%  Written by Laurent S. Nadolski
34
35% Check if the AO exists
36checkforao;
37devSpeakerName = getfamilydata('TANGO', 'TEXTTALKERS');
38devLockName    = 'ANS/CA/SERVICE-LOCKER';
39devRFFBManager = 'ANS/DG/RFFB-MANAGER';
40devFOFBManager = 'ANS/DG/FOFB-MANAGER';
41
42% orbit golden
43fileName = 'GoldenMatrix4FPGA.mat';
44
45
46% Arguments
47if nargin < 1
48    action = 'Initialize';
49end
50
51if nargin < 2
52    Input2 = 0;
53end
54
55if nargin < 3
56    Input3 = 0;
57end
58
59% Common variables
60SR_GEV = getenergy('Energy');
61
62% BPM Families
63BPMxFamily = 'BPMx';
64BPMyFamily = 'BPMz';
65
66% Corrector Families
67HCMFamily  = 'FHCOR';
68VCMFamily  = 'FVCOR';
69
70% number of correctors and BPMs
71HCMfullList  = family2dev(HCMFamily,0);
72VCMfullList  = family2dev(VCMFamily,0);
73BPMxfullList = family2dev(BPMxFamily,0);
74BPMyfullList = family2dev(BPMyFamily,0);
75
76nHCM =  size(HCMfullList,1);
77nVCM =  size(VCMfullList,1);
78nBPMx=  size(BPMxfullList,1);
79nBPMy=  size(BPMyfullList,1);
80%
81
82% Minimum stored current to allow correction
83DCCTMIN = 1; % mA
84
85%%%%%%%%%%%%%%%%
86%% Main Program
87%%%%%%%%%%%%%%%%
88
89switch(action)
90
91%% StopOrbitFeedback   
92    case 'StopOrbitFeedback'
93
94        setappdata(findobj(gcbf,'Tag','FOFBguiTangoFig1'),'RF_FEEDBACK_STOP_FLAG', 1);
95        set(findobj(gcbf,'Tag','FOFBguiTangoStaticTextInformation'),'String','RF Feedback stopped');
96        pause(0);
97
98%% StopOrbitDCFeedback       
99    case 'StopOrbitDCFeedback'
100
101        setappdata(findobj(gcbf,'Tag','FOFBguiTangoFig1'),'DC_FEEDBACK_STOP_FLAG', 1);
102        %set(findobj(gcbf,'Tag','FOFBguiTangoStaticTextInformation'),'String','DC Feedback stopped');
103        pause(0);
104
105%% Initialize       
106    case 'Initialize'
107
108        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
109        % GUI  CONSTRUCTION
110        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
111        ButtonWidth   = 250;
112        ButtonHeight  = 25;
113
114        Offset1f    = 2*(ButtonHeight+3);             % Frame around Text information
115        Offset5f    = Offset1f + 3*(ButtonHeight+3);  % Frame around DC DB
116        Offset2f    = Offset5f + 4*(ButtonHeight+3);  % Frame around FOFB and RF FB
117        Offset3f    = Offset2f + 11*(ButtonHeight+3); % FOFB Configuration
118        FigWidth    = ButtonWidth + 6;                % Figure width
119        FigHeight   = Offset3f + 5.5*(ButtonHeight+3);% Figure heigth
120        ButtonWidth = ButtonWidth-6;
121
122        % Change figure position
123        set(0,'Units','pixels');
124        p = get(0,'screensize');
125
126        orbfig = findobj(allchild(0),'tag','FOFBguiTangoFig1');
127
128        if ~isempty(orbfig)
129            return; % IHM already exists
130        end
131
132        h0 = figure( ...
133            'Color',[0.1 0.1 1], ...
134            'HandleVisibility','Off', ...
135            'Interruptible', 'on', ...
136            'MenuBar','none', ...
137            'Name','FOFB CONTROL TANGO', ...
138            'NumberTitle','off', ...
139            'Units','pixels', ...
140            'Position',[30 p(4)-FigHeight-40 FigWidth FigHeight], ...
141            'Resize','off', ...
142            'HitTest','off', ...
143            'IntegerHandle', 'off', ...
144            'Tag','FOFBguiTangoFig1');
145
146        % Frame Box I
147        uicontrol('Parent',h0, ...
148            'BackgroundColor',[1 1 0], ...
149            'ListboxTop',0, ...
150            'Position',[3 Offset3f ButtonWidth+6 4.5*ButtonHeight+25], ...
151            'Style','frame');
152
153        uicontrol('Parent',h0, ...
154            'BackgroundColor',[1 1 0], ...
155            'FontSize',10, ...
156            'FontWeight', 'Bold', ...
157            'ListboxTop',0, ...
158            'Position',[6 3 + 4*(ButtonHeight+3)+Offset3f  ButtonWidth .6*ButtonHeight], ...
159            'String','FOFB configuration', ...
160            'Style','text');
161
162        uicontrol('Parent',h0, ...
163            'BackgroundColor',[1 1 0], ...
164            'Enable','on', ...
165            'Interruptible', 'on', ...
166            'Position',[26 3 + 3*(ButtonHeight+3) + Offset3f ButtonWidth-32 .8*ButtonHeight], ...
167            'String','H-plane', ...
168            'Style','checkbox', ...
169            'Value',1,...
170            'Tag','FOFBguiTangoCheckboxHcorrection');
171
172        uicontrol('Parent',h0, ...
173            'BackgroundColor',[1 1 0], ...
174            'Enable','on', ...
175            'Interruptible', 'on', ...
176            'Position',[26 3+2*(ButtonHeight+3)+Offset3f ButtonWidth-32 .8*ButtonHeight], ...
177            'String','V-plane', ...
178            'Style','checkbox', ...
179            'Value',1,...
180            'Tag','FOFBguiTangoCheckboxVcorrection');
181
182        uicontrol('Parent',h0, ...
183            'Callback','FOFBguiTango(''OrbitCorrectionFOFB'');', ...
184            'Interruptible','Off', ...
185            'Enable','On', ...
186            'Position',[6 3+1*(ButtonHeight+3)+Offset3f ButtonWidth ButtonHeight], ...
187            'String','Correct Orbit', ...
188            'Tag','FOFBguiTangoButtonOrbitCorrection');
189
190        uicontrol('Parent',h0, ...
191            'CreateFcn','FOFBguiTango(''OrbitCorrectionSetupFOFB'',1);', ...
192            'callback','FOFBguiTango(''OrbitCorrectionSetupFOFB'',0);', ...
193            'Enable','on', ...
194            'Interruptible', 'off', ...
195            'Position',[6 3+0*(ButtonHeight+3)+Offset3f ButtonWidth 0.8*ButtonHeight], ...
196            'String','Edit BPM, CM Lists', ...
197            'Style','PushButton', ...
198            'Value',0,...
199            'Tag','FOFBguiTangoButtonOrbitCorrectionSetupFOFB');
200 
201        % modif 03/01/2012 pour suppression bouton Generate new Matrix for
202        % FPGA
203%         uicontrol('Parent',h0, ...
204%             'callback','FOFBguiTango(''ConvertMatrix4FPGA'',0);', ...
205%             'Enable','on', ...
206%             'Interruptible', 'off', ...
207%             'Position',[6 3+Offset3f ButtonWidth 0.8*ButtonHeight], ...
208%             'String','Generate new Matrix for FPGA', ...
209%             'Style','PushButton', ...
210%             'Value',0,...
211%             'Tag','FOFBguiTangoButtonConvertMatrix4FPGA');
212
213        % Frame Box II
214        uicontrol('Parent',h0, ...
215            'BackgroundColor',[0.8 0.8 0.8], ...
216            'ListboxTop',0, ...
217            'Position',[3 Offset2f ButtonWidth+6 11*ButtonHeight+5], ...
218            'Style','frame');
219
220        uicontrol('Parent',h0, ...
221            'BackgroundColor',[0.8 0.8 0.8], ...
222            'FontSize',10, ...
223            'FontWeight', 'Bold', ...
224            'ListboxTop',0, ...
225            'Position',[6 3+9*(ButtonHeight+3)+ Offset2f ButtonWidth .55*ButtonHeight], ...
226            'String','FOFB and RF Feedback', ...
227            'Style','text');
228
229        h1 = uicontrol('Parent',h0, ...
230            'callback','FOFBguiTango(''TOGGLEHPLANEFOFB'');', ...
231            'BackgroundColor',[0.8 0.8 0.8], ...
232            'Enable','on', ...
233            'Interruptible', 'on', ...
234            'Position',[26 3 + 8*(ButtonHeight+3) + Offset2f ButtonWidth-32 .8*ButtonHeight], ...
235            'String','H-plane', ...
236            'Style','checkbox', ...
237            'Value',0,...
238            'Tag','FOFBguiTangoCheckboxHFOFB');
239
240        h2 = uicontrol('Parent',h0, ...
241            'callback','FOFBguiTango(''TOGGLEVPLANEFOFB'');', ...
242            'BackgroundColor',[0.8 0.8 0.8], ...
243            'Enable','on', ...
244            'Interruptible', 'on', ...
245            'Position',[26 3+7*(ButtonHeight+3)+Offset2f ButtonWidth-32 .8*ButtonHeight], ...
246            'String','V-plane', ...
247            'Style','checkbox', ...
248            'Value',0,...
249            'Tag','FOFBguiTangoCheckboxVFOFB');
250
251        h3 = uicontrol('Parent',h0, ...
252            'BackgroundColor',[0.8 0.8 0.8], ...
253            'Enable','off', ...
254            'Interruptible', 'on', ...
255            'Position',[26 3+6*(ButtonHeight+3)+Offset2f ButtonWidth-32 .8*ButtonHeight], ...
256            'String','Correct RF Frequency', ...
257            'Style','checkbox', ...
258            'Value',1,...
259            'Tag','FOFBguiTangoCheckboxRF');
260   
261        h4 = uicontrol('Parent',h0, ...
262            'BackgroundColor',[0.8 0.8 0.8], ...
263            'Enable','on', ...
264            'Interruptible', 'on', ...
265            'Position',[26 + 0.5*ButtonWidth  3 + 8*(ButtonHeight+3) + Offset2f 0.5*ButtonWidth-32 .8*ButtonHeight], ...
266            'String','H-Loop-Gain = ', ...
267            'Style','text', ...
268            'Tag','FOFBguiTangoXgain');
269 
270        h5 = uicontrol('Parent',h0, ...
271            'BackgroundColor',[0.8 0.8 0.8], ...
272            'Enable','on', ...
273            'Interruptible', 'on', ...
274            'Position',[26 + 0.5*ButtonWidth  3+7*(ButtonHeight+3)+Offset2f 0.5*ButtonWidth-32 .8*ButtonHeight], ...
275            'String','V-Loop-Gain = ', ...
276            'Style','text', ...
277            'Tag','FOFBguiTangoYgain');
278
279        uicontrol('Parent',h0, ...
280            'callback','FOFBguiTango(''FOFBRunningMode'');', ...
281            'BackgroundColor',[1 0.4 0.4], ...
282            'Enable','on', ...
283            'Interruptible', 'on', ...
284            'Position',[26 + 0.5*ButtonWidth 3+6*(ButtonHeight+3)+Offset2f 0.5*ButtonWidth-32 .8*ButtonHeight], ...
285            'String','FOFB+SOFB', ...
286            'Style','checkbox', ...
287            'Value',0,...
288            'Tag','FOFBguiTangoCheckboxFOFB_SOFB');
289
290        uicontrol('Parent',h0, ...
291            'callback','FOFBguiTango(''STARTRFFOFB'');', ...
292            'Enable','on', ...
293            'FontSize',12, ...
294            'Interruptible', 'on', ...
295            'ListboxTop',0, ...
296            'Position',[8 3+5*(ButtonHeight+3)+ Offset2f .5*ButtonWidth-6 1.0*ButtonHeight], ...
297            'String','Start RFFB', ...
298            'Value',0, ...
299            'Tag','FOFBguiTangoPushbuttonStartRFFB');
300
301        uicontrol('Parent',h0, ...
302            'callback','FOFBguiTango(''STOPRFFOFB'');pause(0);', ...
303            'Enable','on', ...
304            'FontSize',12, ...
305            'Interruptible', 'on', ...
306            'ListboxTop',0, ...
307            'Position',[.5*FigWidth+3 3+5*(ButtonHeight+3)+Offset2f .5*ButtonWidth-6 1.0*ButtonHeight], ...
308            'String','Stop RFFB', ...
309            'Value',0, ...
310            'Tag','FOFBguiTangoPushbuttonStopRFFB');
311       
312        uicontrol('Parent',h0, ...
313            'callback','FOFBguiTango(''StartFOFB'');pause(0);', ...
314            'Enable','on', ...
315            'FontSize',12, ...
316            'Interruptible', 'on', ...
317            'ListboxTop',0, ...
318            'Position',[8 3+4*(ButtonHeight+3)+Offset2f .5*ButtonWidth-6 1.0*ButtonHeight], ...
319            'String','Start FOFB', ...
320            'Value',0, ...
321            'Tag','FOFBguiTangoPushbuttonStop2CurrentValues');
322
323        uicontrol('Parent',h0, ...
324            'callback','FOFBguiTango(''StartFOFBConfig'');pause(0);', ...
325            'BackgroundColor', [1 0 0], ...
326            'Enable','on', ...
327            'FontSize',12, ...
328            'Interruptible', 'on', ...
329            'ListboxTop',0, ...
330            'Position',[.5*FigWidth+3 3+4*(ButtonHeight+3)+ Offset2f .5*ButtonWidth-6 1.0*ButtonHeight], ...
331            'String','Start FOFB+config', ...
332            'Value',0, ...
333            'Tag','FOFBguiTangoPushbuttonStart');
334
335
336        uicontrol('Parent',h0, ...
337            'callback','FOFBguiTango(''StopFOFB2CurrentValues'');pause(0);', ...
338            'Enable','on', ...
339            'FontSize',12, ...
340            'Interruptible', 'on', ...
341            'ListboxTop',0, ...
342            'Position',[8 3+3*(ButtonHeight+3)+Offset2f .5*ButtonWidth-6 1.0*ButtonHeight], ...
343            'String','Stop to current', ...
344            'Value',0, ...
345            'Tag','FOFBguiTangoPushbuttonStop2CurrentValues');
346
347        uicontrol('Parent',h0, ...
348            'callback','FOFBguiTango(''StopFOFB2Zero'');pause(0);', ...
349            'Enable','on', ...
350            'FontSize',12, ...
351            'Interruptible', 'on', ...
352            'ListboxTop',0, ...
353            'Position',[.5*FigWidth+3 3+3*(ButtonHeight+3)+Offset2f .5*ButtonWidth-6 1.0*ButtonHeight], ...
354            'String','Stop FOFB to zero', ...
355            'Value',0, ...
356            'Tag','FOFBguiTangoPushbuttonStop2Zero');
357
358        uicontrol('Parent',h0, ...
359            'callback','FOFB_defauts;', ...
360            'BackgroundColor', [1 1 0], ...
361            'Enable','on', ...
362            'FontSize',12, ...
363            'Interruptible', 'on', ...
364            'ListboxTop',0, ...
365            'Position',[8 3+2*(ButtonHeight+3)+Offset2f .5*ButtonWidth-6 1.0*ButtonHeight], ...
366            'String','Defaults', ...
367            'Value',0, ...
368            'Tag','FOFBguiTangoPushbuttonFOFBDefaults');
369
370        uicontrol('Parent',h0, ...
371            'callback','system(''atkpanel ANS/DG/FOFB-MANAGER &'')', ...
372            'BackgroundColor', [1 1 0], ...
373            'Enable','on', ...
374            'FontSize',12, ...
375            'Interruptible', 'on', ...
376            'ListboxTop',0, ...
377            'Position',[.5*FigWidth+3 3+2*(ButtonHeight+3)+Offset2f .5*ButtonWidth-6 1.0*ButtonHeight], ...
378            'String','FOFB-Manager', ...
379            'Value',0, ...
380            'Tag','FOFBguiTangoPushbuttonFOFBManager');
381
382        uicontrol('Parent',h0, ...
383            'callback','system(''atkpanel ANS/DG/RFFB-MANAGER &'');', ...
384            'BackgroundColor', [1 1 0], ...
385            'Enable','on', ...
386            'FontSize',12, ...
387            'Interruptible', 'on', ...
388            'ListboxTop',0, ...
389            'Position',[.5*FigWidth+3 3+1*(ButtonHeight+3)+Offset2f .5*ButtonWidth-6 1.0*ButtonHeight], ...
390            'String','RFFB-Manager', ...
391            'Value',0, ...
392            'Tag','FOFBguiTangoPushbuttonRFFBManager');
393
394        uicontrol('Parent',h0, ...
395            'callback','FOFBguiTango(''ZeroingFHCOR'');pause(0);', ...
396            'BackgroundColor', [1 0 0], ...
397            'Enable','on', ...
398            'FontSize',12, ...
399            'Interruptible', 'on', ...
400            'ListboxTop',0, ...
401            'Position',[6 3+0*(ButtonHeight+3)+Offset2f .5*ButtonWidth-6 1.0*ButtonHeight], ...
402            'String','FHCOR2zeros', ...
403            'Value',0, ...
404            'Tag','FOFBguiTangoPushbuttonHfcm2zero');
405
406        uicontrol('Parent',h0, ...
407            'callback','FOFBguiTango(''ZeroingFVCOR'');pause(0);', ...
408            'BackgroundColor', [1 0 0], ...
409            'Enable','on', ...
410            'FontSize',12, ...
411            'Interruptible', 'on', ...
412            'ListboxTop',0, ...
413            'Position',[.5*FigWidth+3 3+0*(ButtonHeight+3)+Offset2f .5*ButtonWidth-6 1.0*ButtonHeight], ...
414            'String','FVCOR2zeros', ...
415            'Value',0, ...
416            'Tag','FOFBguiTangoPushbuttonVfcm2zero');
417
418%         uicontrol('Parent',h0, ...
419%             'CreateFcn','FOFBguiTango(''FeedbackSetupFOFB'',1);', ...
420%             'callback','FOFBguiTango(''FeedbackSetupFOFB'',0);', ...
421%             'Enable','on', ...
422%             'Interruptible', 'off', ...
423%             'Position',[8 3 + Offset2f ButtonWidth-5 .75*ButtonHeight], ...
424%             'String','Edit FOFB Setup', ...
425%             'Style','PushButton', ...
426%             'Value',0,...
427%             'Tag','FOFBguiTangoButtonFeedbackSetup');
428%
429        % Frame Box III % Orbit DC Feedback
430
431        uicontrol('Parent',h0, ...
432            'BackgroundColor',[0.8 0.8 0.8], ...
433            'ListboxTop',0, ...
434            'Position',[3 Offset5f ButtonWidth+6 4*ButtonHeight+5], ...
435            'Style','frame');
436
437        uicontrol('Parent',h0, ...
438            'BackgroundColor',[0.8 0.8 0.8], ...
439            'FontSize',10, ...
440            'FontWeight', 'Bold', ...
441            'ListboxTop',0, ...
442            'Position',[26 3+3*(ButtonHeight+3)+Offset5f 0.8*ButtonWidth .55*ButtonHeight], ...
443            'String','Orbit DC Feedback', ...
444            'Style','text');
445
446        uicontrol('Parent',h0, ...
447            'BackgroundColor',[0.8 0.8 0.8], ...
448            'FontSize',10, ...
449            'ListboxTop',0, ...
450            'Position',[26 3+2*(ButtonHeight+3)+Offset5f ButtonWidth-32 .8*ButtonHeight], ...
451            'String','H-plane', ...
452            'Style','checkbox', ...
453            'Value',1,...
454            'Tag','FOFBguiTangoCheckboxHDCFB');
455
456        uicontrol('Parent',h0, ...
457            'BackgroundColor',[0.8 0.8 0.8], ...
458            'FontSize',10, ...
459            'ListboxTop',0, ...
460            'Position',[6+0.4*ButtonWidth 3+2*(ButtonHeight+3)+Offset5f 0.6*ButtonWidth-32 .8*ButtonHeight], ...
461            'String','V-plane', ...
462            'Style','checkbox', ...
463            'Value',1,...
464            'Tag','FOFBguiTangoCheckboxVDCFB');
465
466        uicontrol('Parent',h0, ...
467            'BackgroundColor',[0.8 0.8 0.8], ...
468            'Enable','on', ...
469            'Interruptible', 'on', ...
470            'Position',[26 3+1*(ButtonHeight+3)+Offset5f ButtonWidth-32 .8*ButtonHeight], ...
471            'String','Correct DC RF Frequency', ...
472            'Style','checkbox', ...
473            'Value',1,...
474            'Tag','FOFBguiTangoCheckboxDCRF');
475
476        uicontrol('Parent',h0, ...
477            'callback','FOFBguiTango(''StartDCFB'');', ...
478            'Enable','on', ...
479            'FontSize',12, ...
480            'Interruptible', 'on', ...
481            'ListboxTop',0, ...
482            'Position',[8 6+Offset5f .5*ButtonWidth-6 1.0*ButtonHeight], ...
483            'String','Start DCFB', ...
484            'Value',0, ...
485            'Tag','FOFBguiTangoPushbuttonStartDC');
486
487        uicontrol('Parent',h0, ...
488            'callback','FOFBguiTango(''StopOrbitDCFeedback'');pause(0);', ...
489            'Enable','off', ...
490            'FontSize',12, ...
491            'Interruptible', 'on', ...
492            'ListboxTop',0, ...
493            'Position',[.5*FigWidth+3 6 + Offset5f .5*ButtonWidth-6 1.0*ButtonHeight], ...
494            'String','Stop DC FB', ...
495            'Value',0, ...
496            'Tag','FOFBguiTangoPushbuttonStopDC');
497
498        % Frame Box IV
499        uicontrol('Parent',h0, ...
500            'BackgroundColor',[0.8 0.8 0.8], ...
501            'ListboxTop',0, ...
502            'Position',[3 Offset1f  ButtonWidth+6 2*ButtonHeight+12], ...
503            'Style','frame');
504
505        uicontrol('Parent',h0, ...
506            'BackgroundColor',[0.8 0.8 0.8], ...
507            'HorizontalAlignment','center', ...
508            'FontWeight', 'Bold', ...
509            'ListboxTop',0, ...
510            'Position',[6 Offset1f + 1.80*ButtonHeight 1*ButtonWidth .7*ButtonHeight], ...
511            'String','FOFB status ', ...
512            'Style','text');
513
514        uicontrol('Parent',h0, ...
515            'BackgroundColor',[0.8 0.8 0.8], ...
516            'HorizontalAlignment','center', ...
517            'ListboxTop',0, ...
518            'Position',[6 Offset1f + 1*ButtonHeight 0.6*ButtonWidth .7*ButtonHeight], ...
519            'String','To get Status Push button: ', ...
520            'Style','text', ...
521            'Tag','FOFBguiTangoStaticTextHeader');
522
523        uicontrol('Parent',h0, ...
524            'callback','FOFBguiTango(''UpdateStatusFOFB'');pause(0);', ...
525            'BackgroundColor',[0.8 0.8 0.8], ...
526            'HorizontalAlignment','center', ...
527            'ListboxTop',0, ...
528            'Position',[6 + 0.6*ButtonWidth Offset1f + 1.1*ButtonHeight 0.3*ButtonWidth .7*ButtonHeight], ...
529            'String','Update', ...
530            'Style','PushButton', ...
531            'Tag','FOFBguiTangoUpdateStatusFOFB');
532
533        uicontrol('Parent',h0, ...
534            'BackgroundColor',[1 1 1], ...
535            'ForegroundColor','b', ...
536            'ListboxTop',0, ...
537            'Position',[6+ 0*ButtonWidth 3 + Offset1f + .05*ButtonHeight 0.18*ButtonWidth .7*ButtonHeight], ...
538            'String','H-plane', ...
539            'Style','text', ...
540            'Tag','FOFBguiTangoisxFOFBRunning');
541
542        uicontrol('Parent',h0, ...
543            'BackgroundColor',[1 1 1], ...
544            'ForegroundColor','b', ...
545            'ListboxTop',0, ...
546            'Position',[6+0.2*ButtonWidth 3 + Offset1f + .05*ButtonHeight 0.18*ButtonWidth .7*ButtonHeight], ...
547            'String','V-plane', ...
548            'Style','text', ...
549            'Tag','FOFBguiTangoiszFOFBRunning');
550
551        uicontrol('Parent',h0, ...
552            'BackgroundColor',[1 1 1], ...
553            'ForegroundColor','b', ...
554            'ListboxTop',0, ...
555            'Position',[6+0.4*ButtonWidth 3 + Offset1f + .05*ButtonHeight 0.18*ButtonWidth .7*ButtonHeight], ...
556            'String','RF', ...
557            'Style','text', ...
558            'Tag','FOFBguiTangoisRFRunning');
559       
560        uicontrol('Parent',h0, ...
561            'BackgroundColor',[1 1 1], ...
562            'ForegroundColor','b', ...
563            'ListboxTop',0, ...
564            'Position',[6+0.6*ButtonWidth 3 + Offset1f + .05*ButtonHeight 0.18*ButtonWidth .7*ButtonHeight], ...
565            'String','DC', ...
566            'Style','text', ...
567            'Tag','FOFBguiTangoisDCFBRunning');
568
569        uicontrol('Parent',h0, ...
570            'BackgroundColor',[1 1 1], ...
571            'ForegroundColor','b', ...
572            'ListboxTop',0, ...
573            'Position',[6+0.8*ButtonWidth 3 + Offset1f + .05*ButtonHeight 0.18*ButtonWidth .7*ButtonHeight], ...
574            'String','SOFB', ...
575            'Style','text', ...
576            'Tag','FOFBguiTangoisSOFBRunning');
577       
578
579        % Frame Box "Close"
580        uicontrol('Parent',h0, ...
581            'BackgroundColor',[0.8 0.8 0.8], ...
582            'ListboxTop',0, ...
583            'Position',[3 8 ButtonWidth+6 ButtonHeight+8], ...
584            'Style','frame');
585
586        uicontrol('Parent',h0, ...
587            'Callback', 'close(gcbf);', ...
588            'Enable','On', ...
589            'Interruptible','Off', ...
590            'Position',[6 13 ButtonWidth ButtonHeight], ...
591            'String','Close', ...
592            'Tag','FOFBguiTangoClose');
593
594        % Read planes for FOFB correction in device server
595        attr_list={'applyCmdsToXPlane','applyCmdsToZPlane'};
596        result=tango_read_attributes2(devFOFBManager,attr_list);
597
598        set(h1, 'Value',result(1).value(1));
599        set(h2, 'value',result(2).value(1));
600        set(h3, 'value',readattribute([devRFFBManager, '/isRunning']));
601
602        % Read default loop gain and display it
603        FB=get(findobj(h0,'Tag','FOFBguiTangoButtonOrbitCorrectionSetupFOFB'),'Userdata');
604        set(h4,'string',['H-Loop-Gain = ',num2str(FB.Xgain)]);
605        set(h5,'string',['V-Loop-Gain = ',num2str(FB.Ygain)]);
606         
607       
608        % Does not work. Need to get the full interfaced built!
609        %FOFBguiTango('UpdateStatusFOFB');pause(0);
610       
611        % Lock RF FB now that RF is taken care by fast horizontal steerers
612        set(findobj(h0,'Tag','FOFBguiTangoPushbuttonStartRFFB'), 'Enable','off');
613        set(findobj(h0,'Tag','FOFBguiTangoPushbuttonStopRFFB'), 'Enable','off');
614       
615        isRFRunning    = readattribute([devRFFBManager, '/isRunning']);
616        isxFOFBRunning = readattribute([devFOFBManager, '/xFofbRunning']);
617        iszFOFBRunning = readattribute([devFOFBManager, '/zFofbRunning']);
618
619        set(findobj(h0,'Tag','FOFBguiTangoButtonOrbitCorrection'),'Enable','off');
620
621        if isRFRunning || isxFOFBRunning || iszFOFBRunning
622            % Disable buttons in GUI
623            set(0,'showhiddenhandles','on');
624            set(findobj(h0,'Tag','FOFBguiTangoButtonOrbitCorrection'),'Enable','off');
625            set(findobj(h0,'Tag','FOFBguiTangoButtonOrbitCorrectionSetupFOFB'),'Enable','on');
626            set(findobj(h0,'Tag','FOFBguiTangoButtonFeedbackSetup'),'Enable','off');
627            set(findobj(h0,'Tag','FOFBguiTangoClose'),'Enable','on');
628            set(findobj(h0,'Tag','FOFBguiTangoCheckboxHSOFB'),'Enable','off');
629            set(findobj(h0,'Tag','FOFBguiTangoCheckboxVSOFB'),'Enable','off');
630            set(findobj(h0,'Tag','FOFBguiTangoCheckboxHcorrection'),'Enable','off');
631            set(findobj(h0,'Tag','FOFBguiTangoCheckboxVcorrection'),'Enable','off');
632            set(findobj(h0,'Tag','FOFBguiTangoCheckboxRF'),'Enable','off');
633            set(findobj(h0,'Tag','FOFBguiTangoCheckboxSOFB'),'Enable','off')
634            set(findobj(h0,'Tag','FOFBguiTangoCheckboxFOFB'),'Enable','off')
635            set(findobj(h0,'Tag','FOFBguiTangoButtonConvertMatrix4FPGA'),'Enable','on');
636            %set(findobj(h0,'Tag','FOFBguiTangoPushbuttonStartDC'),'Enable','off');
637            pause(0);
638        end
639       
640        % init FOFB structure
641        pause(0.5)
642        FOFBguiTango('UpdateStatusFOFB');
643                   
644       
645%%  UpdateStatusFOFB       
646    case 'UpdateStatusFOFB'
647        try
648            isRFRunning    = readattribute([devRFFBManager, '/isRunning']);
649            isxFOFBRunning = readattribute([devFOFBManager, '/xFofbRunning']);
650            iszFOFBRunning = readattribute([devFOFBManager, '/zFofbRunning']);
651            isDCFBRunning  = readattribute([devLockName, '/dcfb']);
652            isSOFBRunning  = readattribute([devLockName, '/sofb']);
653
654            %FOFBguiTangoiszFOFBRunning
655            %FOFBguiTangoUpdateStatusFOFB
656            if isempty(gcbf)
657                %mainFig = gcf;
658                mainFig = findobj(allchild(0),'tag','FOFBguiTangoFig1');
659            else
660                mainFig = gcbf;
661            end
662           
663            if isRFRunning
664                set(findobj(mainFig,'Tag','FOFBguiTangoisRFRunnning'),'BackGroundColor', [0 1 0]);
665            else
666                set(findobj(mainFig,'Tag','FOFBguiTangoisRFRunnning'),'BackGroundColor', [1 1 1]);
667            end
668
669            if isxFOFBRunning
670                set(findobj(mainFig,'Tag','FOFBguiTangoisxFOFBRunning'),'BackGroundColor', [0 1 0]);
671            else
672                set(findobj(mainFig,'Tag','FOFBguiTangoisxFOFBRunning'),'BackGroundColor', [1 1 1]);
673            end
674
675            if iszFOFBRunning
676                set(findobj(mainFig,'Tag','FOFBguiTangoiszFOFBRunning'),'BackGroundColor', [0 1 0]);
677            else
678                set(findobj(mainFig,'Tag','FOFBguiTangoiszFOFBRunning'),'BackGroundColor', [1 1 1]);
679            end
680
681            if isDCFBRunning
682                set(findobj(mainFig,'Tag','FOFBguiTangoisDCFBRunning'),'BackGroundColor', [0 1 0]);
683            else
684                set(findobj(mainFig,'Tag','FOFBguiTangoisDCFBRunning'),'BackGroundColor', [1 1 1]);
685            end
686
687            if isSOFBRunning
688                set(findobj(mainFig,'Tag','FOFBguiTangoisSOFBRunning'),'BackGroundColor', [0 1 0]);
689            else
690                set(findobj(mainFig,'Tag','FOFBguiTangoisSOFBRunning'),'BackGroundColor', [1 1 1]);
691            end
692
693            % Update time on status
694            set(findobj(mainFig,'Tag','FOFBguiTangoStaticTextHeader'),'String', datestr(clock));
695
696        catch
697            fprintf('\n  %s \n',lasterr);
698            fprintf('Error in UpdateStatusFOFB\n') ;
699        end
700
701%% OrbitCorrectionSetupFOFB       
702    case 'OrbitCorrectionSetupFOFB'
703        % NOTES setting for FOFB and manual orbit correction are often
704        % different
705
706        InitFlag = Input2;  % Input #2: if InitFlag, then initialize variables
707
708        if InitFlag % just at startup
709
710            % Setup orbit correction elements : DEFAULT configuration
711            %disp('Orbit correction condition: InitFlag=1 -- debugging message');
712
713            % Get list of BPMs et corrector magnets
714            [HCMlist VCMlist BPMlist] = getlocallist;
715           
716            % Read configuration of FOFB from file having R-matrix for FPGA
717            try
718                data = load([getfamilydata('Directory' , 'OpsData') fileName]);
719            catch exception
720                data = load(fullfile(getfamilydata('Directory', 'FOFBdata'), 'GoldenMatrix4FPGADefault.mat'));
721                warndlg('Generate Matrix for FPGA, Wrong default values loaded');
722            end
723
724            % Look for removed BPM
725            idx = find(sum(abs(data.matrixX)) == 0);
726           
727            % becarefull does not work if missing BPM in BPMlist           
728            BPMlist(idx,:) = [];
729
730            % Look for removed HFCOR
731            idx = find(sum(abs(data.matrixX')) == 0);
732            HCMlist(idx,:) = [];
733           
734            % Look for removed HFCOR
735            idz = find(sum(abs(data.matrixZ')) == 0);
736            VCMlist(idz,:) = [];
737
738            % SVD orbit correction singular values
739            Xivec = 1:45; % 40 w/o Orthogonal correction 41 if orthogonal correction
740            Yivec = 1:44;
741           
742            % Gain correction values
743            Xgain = 90 ; % ajusted for 45 vp for H-plane, nominal alpha
744            Ygain = 90;% ajusted for 44 vp for V-plane, nominal alpha
745               
746
747            % initialize RFCorrFlag
748            %RFCorrFlag = 'No';
749            RFCorrFlag = 'Yes';
750
751            % Goal orbit
752            Xgoal = getgolden(BPMxFamily, BPMlist, 'numeric');
753            Ygoal = getgolden(BPMyFamily, BPMlist, 'numeric');
754
755            % BPM weights
756            Xweight = ones(size(BPMlist,1), 1);
757            Yweight = ones(size(BPMlist,1), 1);
758
759            % Correctors weights
760            HCMweight = ones(size(HCMlist,1), 1);
761            VCMweight = ones(size(VCMlist,1), 1);
762
763        else % For orbit correction Configuration
764            % Get vector for orbit correction
765            FB = get(findobj(gcbf,'Tag','FOFBguiTangoButtonOrbitCorrectionSetupFOFB'),'Userdata');
766            BPMlist = FB.BPMlist;
767            HCMlist = FB.HCMlist;
768            VCMlist = FB.VCMlist;
769            Xivec = FB.Xivec;
770            Yivec = FB.Yivec;
771            Xgain = FB.Xgain;
772            Ygain = FB.Ygain;
773            Xgoal = FB.Xgoal;
774            Ygoal = FB.Ygoal;
775            RFCorrFlag = FB.RFCorrFlag;
776
777            HCMweight = FB.OCSx.CMWeight;
778            VCMweight = FB.OCSy.CMWeight;
779            Xweight = FB.OCSx.BPMWeight;
780            Yweight = FB.OCSy.BPMWeight;
781
782            % Add button to change #ivectors, CMs, IDBPMs,
783            EditFlag = 0;
784            h_fig1 = figure;
785
786            while EditFlag ~= 11
787
788                % get Sensitivity matrices
789                Sh = getrespmat(BPMxFamily, BPMlist, HCMFamily, HCMlist, [], SR_GEV);
790                Sv = getrespmat(BPMyFamily, BPMlist, VCMFamily, VCMlist, [], SR_GEV);
791                % Computes SVD to get singular values
792                [Ux, SVx, Vx] = svd(Sh);
793                [Uy, SVy, Vy] = svd(Sv);
794
795                % Remove singular values greater than the actual number of singular values
796                i = find(Xivec>length(diag(SVx)));
797                if ~isempty(i)
798                    disp('   Horizontal singular value vector scaled since there were more elements in the vector than singular values.');
799                    pause(0);
800                    Xivec(i) = [];
801                end
802                i = find(Yivec>length(diag(SVy)));
803                if ~isempty(i)
804                    disp('   Vertical singular value vector scaled since there were more elements in the vector than singular values.');
805                    pause(0);
806                    Yivec(i) = [];
807                end
808
809                % Display singular value plot for both planes
810
811                figure(h_fig1);
812
813                subplot(2,1,1);
814                semilogy(diag(SVx),'b');
815                hold on;
816                semilogy(diag(SVx(Xivec,Xivec)),'xr');
817                ylabel('Horizontal');
818                title('Response Matrix Singular Values');
819                hold off; grid on;
820
821                subplot(2,1,2);
822                semilogy(diag(SVy),'b');
823                hold on;
824                semilogy(diag(SVy(Yivec,Yivec)),'xr');
825                xlabel('Singular Value Number');
826                ylabel('Vertical');
827                hold off; grid on;
828                drawnow;
829
830                % End of display
831
832                if strcmpi(RFCorrFlag,'No')
833                    RFCorrState = 'NOT CORRECTED';
834                elseif strcmp(RFCorrFlag,'Yes')
835                    RFCorrState = 'CORRECTED';
836                else
837                    RFCorrState = '???';
838                end
839
840                EditFlag = menu('Change Parameters?','Singular Values',  ...
841                    'Horizontal corrector magnet list', 'Horizontal corrector magnet weights', ...
842                    'Vertical corrector magnet list', 'Vertical corrector magnet weights',  ...
843                    'BPM list', 'BPM weights','Correction Gain', 'Golden Orbit value',...
844                    sprintf('RF Frequency (currently %s)',RFCorrState),'Return');
845
846                % Edition switchyard for orbit correction
847                switch EditFlag
848                    case 1 % Singular value edition
849
850                        % Build up matlab prompt
851                        prompt = {'Enter the horizontal singular value vector (Matlab vector format):', ...
852                            'Enter the vertical singular value vector (Matlab vector format):'};
853                        % default values
854                        def = {sprintf('[%d:%d]',1,Xivec(end)),sprintf('[%d:%d]',1,Yivec(end))};
855                        titlestr = 'SVD Orbit Correction';
856                        lineNo = 1;
857
858                        answer = inputdlg(prompt,titlestr,lineNo,def);
859
860                        % Answer parsing
861                        if ~isempty(answer)
862                            % Horizontal plane
863                            XivecNew = fix(str2num(answer{1}));
864                            if isempty(XivecNew)
865                                disp('   Horizontal singular value number cannot be empty.  No change made.');
866                            else
867                                if any(XivecNew<=0) || max(XivecNew)>length(diag(SVx))
868                                    disp('   Error reading horizontal singular value vector  No change made.');
869                                else
870                                    Xivec = XivecNew;
871                                end
872                            end
873                            % Vertical plane
874                            YivecNew = fix(str2num(answer{2}));
875                            if isempty(YivecNew)
876                                disp('   Vertical singular value vector cannot be empty.  No change made.');
877                            else
878                                if any(YivecNew<=0) || max(YivecNew)>length(diag(SVy))
879                                    disp('   Error reading vertical singular value vector.  No change made.');
880                                else
881                                    Yivec = YivecNew;
882                                end
883                            end
884                        end
885
886                    case 2 % Horizontal corrector list edition
887                        List = getlist(HCMFamily);
888                        ListOld = HCMlist;
889                        CheckList = zeros(size(List,1));
890                        Elem = dev2elem(HCMFamily, HCMlist);
891                        CheckList(Elem) = ones(size(Elem));
892                        CheckList = CheckList(dev2elem(HCMFamily,List));
893                        newList = editlist(List, HCMFamily, CheckList);
894
895                        if isempty(newList)
896                            fprintf('   Horizontal corrector magnet list cannot be empty.  No change made.\n');
897                        else
898                            HCMlist = newList;
899                        end
900
901                        %set correctors weight values
902                        HCMweightOld = HCMweight;
903                        HCMweight = ones(size(HCMlist,1), 1);
904
905                        %if a new corrector is added, then set the weight values to
906                        %one.
907                        % Otherwise keep the present weight values
908                        for i = 1:size(HCMlist,1)
909
910                            % Is it a new corrector?
911                            k = find(HCMlist(i,1)==ListOld(:,1));
912                            l = find(HCMlist(i,2)==ListOld(k,2));
913
914                            if isempty(k) || isempty(l)
915                                % New corrector
916                            else
917                                % Use the old value for old correctors
918                                HCMweight(i) = HCMweightOld(k(l));
919                            end
920                        end
921
922                    case 3 % Horizontal corrector weight edition
923
924                        % Ask user to select HCM for modifying weight
925                        ChangeList = editlist(HCMlist, 'Change HCM', ...
926                            zeros(size(HCMlist,1),1));
927
928                        % Ask the new weight for each selected corrector
929                        for i = 1:size(ChangeList,1)
930
931                            k = find(ChangeList(i,1) == HCMlist(:,1));
932                            l = find(ChangeList(i,2) == HCMlist(k,2));
933
934                            prompt = {sprintf('Enter the new weight for HCM(%d,%d):', ...
935                                HCMlist(k(l),1), HCMlist(k(l),2))};
936                            def = {sprintf('%f',HCMweight(k(l))),sprintf('%f',HCMweight(k(l)))};
937                            titlestr = 'CHANGE THE HCM WEIGHTS';
938                            lineNo = 1;
939                            answer = inputdlg(prompt, titlestr, lineNo, def);
940
941                            if isempty(answer)
942                                % No change
943                                fprintf('   No change was made to the VCM weight.\n');
944                            else
945                                HCMweightnew = str2num(answer{1});
946                                if isempty(HCMweightnew)
947                                    fprintf('   No change was made to the horizontal BPM weight.\n');
948                                else
949                                    HCMweight(k(l)) = HCMweightnew;
950                                end
951                            end
952                        end
953
954                        if ~isempty(ChangeList)
955                            fprintf('   Note:  changing the HCM weight for "Orbit Correction" does not change the goal orbit for "Slow Orbit FeedbackFOFB."\n');
956                        end
957
958                    case 4 % Vertical corrector list edition
959                        List = getlist(VCMFamily);
960                        CheckList = zeros(size(List,1));
961                        ListOld = VCMlist;
962                        Elem = dev2elem(VCMFamily, VCMlist);
963                        CheckList(Elem) = ones(size(Elem));
964                        CheckList = CheckList(dev2elem(VCMFamily,List));
965                        newList = editlist(List, VCMFamily, CheckList);
966                        if isempty(newList)
967                            fprintf('   Vertical corrector magnet cannot be empty.  No change made.\n');
968                        else
969                            VCMlist = newList;
970                        end
971
972                        %set correctors weight values
973                        VCMweightOld = VCMweight;
974                        VCMweight = ones(size(VCMlist,1), 1);
975
976                        %if a new corrector is added, then set the weight values to
977                        %one.
978                        % Otherwise keep the present weight values
979                        for i = 1:size(VCMlist,1)
980
981                            % Is it a new corrector?
982                            k = find(VCMlist(i,1)==ListOld(:,1));
983                            l = find(VCMlist(i,2)==ListOld(k,2));
984
985                            if isempty(k) || isempty(l)
986                                % New corrector
987                            else
988                                % Use the old value for old correctors                             
989                                VCMweight(i) = VCMweightOld(k(l));
990                            end
991                        end
992                    case 5 % Vertical corrector weight edition
993                        % Ask user to select VCM for modifying weight
994                        ChangeList = editlist(VCMlist, 'Change VCM', ...
995                            zeros(size(VCMlist,1),1));
996
997                        % Ask the new weight for each selected corrector
998                        for i = 1:size(ChangeList,1)
999
1000                            k = find(ChangeList(i,1) == VCMlist(:,1));
1001                            l = find(ChangeList(i,2) == VCMlist(k,2));
1002
1003                            prompt = {sprintf('Enter the new weight for VCM(%d,%d):', ...
1004                                VCMlist(k(l),1), VCMlist(k(l),2))};
1005                            def = {sprintf('%f',VCMweight(k(l))),sprintf('%f',VCMweight(k(l)))};
1006                            titlestr = 'CHANGE THE VCM WEIGHTS';
1007                            lineNo = 1;
1008                            answer = inputdlg(prompt, titlestr, lineNo, def);
1009
1010                            if isempty(answer)
1011                                % No change
1012                                fprintf('   No change was made to the VCM weight.\n');
1013                            else
1014                                VCMweightnew = str2num(answer{1});
1015                                if isempty(VCMweightnew)
1016                                    fprintf('   No change was made to the horizontal BPM weight.\n');
1017                                else
1018                                    VCMweight(k(l)) = VCMweightnew;
1019                                end
1020                            end
1021                        end
1022
1023                        if ~isempty(ChangeList)
1024                            fprintf('   Note:  changing the VCM weight for "Orbit Correction" does not change the goal orbit for "Slow Orbit FeedbackFOFB."\n');
1025                        end
1026
1027                    case 6 % BPM list edition
1028                        % Backup element before edition
1029                        ListOld = BPMlist;
1030                        XgoalOld = Xgoal;
1031                        YgoalOld = Ygoal;
1032                        XweightOld = Xweight;
1033                        YweightOld = Yweight;
1034
1035                        % Get full BPM list
1036                        List = family2dev(BPMxFamily);
1037
1038                        % Check BPM already in the list CheckList(i) = 1
1039                        %       BPM not in the list CheckList(i) = 0
1040                        CheckList = zeros(size(List,1),1);
1041                        if ~isempty(BPMlist)
1042                            for i = 1:size(List,1)
1043                                k = find(List(i,1) == BPMlist(:,1));
1044                                l = find(List(i,2) == BPMlist(k,2));
1045                                if isempty(k) || isempty(l)
1046                                    % Item not in list
1047                                else
1048                                    CheckList(i) = 1;
1049                                end
1050                            end
1051                        end
1052
1053                        % User edition of the BPM list
1054                        newList = editlist(List, 'BPM', CheckList);
1055                        if isempty(newList)
1056                            fprintf('   BPM list cannot be empty.  No change made.\n');
1057                        else
1058                            BPMlist = newList;
1059                        end
1060
1061                        % Set the goal orbit to the golden orbit
1062                        Xgoal = getgolden(BPMxFamily, BPMlist);
1063                        Ygoal = getgolden(BPMyFamily, BPMlist);
1064                        Xweight = ones(size(BPMlist,1),1);
1065                        Yweight = ones(size(BPMlist,1),1);
1066
1067                        % If a new BPM is added, then set the goal orbit to the golden orbit
1068                        % For other BPMs, present goal orbit is kept
1069                        for i = 1:size(BPMlist,1)
1070
1071                            % Is it a new BPM?
1072                            k = find(BPMlist(i,1) == ListOld(:,1));
1073                            l = find(BPMlist(i,2) == ListOld(k,2));
1074
1075                            if isempty(k) || isempty(l)
1076                                % New BPM
1077                            else
1078                                % Use the old value for old BPM
1079                                Xgoal(i) = XgoalOld(k(l));
1080                                Ygoal(i) = YgoalOld(k(l));
1081                                Xweight(i) = XweightOld(k(l));
1082                                Yweight(i) = YweightOld(k(l));
1083                            end
1084                        end
1085
1086                    case 7 % BPM weight edition
1087                        % Ask user to select BPM for modifying weight
1088                        ChangeList = editlist(BPMlist, 'Change BPM', ...
1089                            zeros(size(BPMlist,1),1));
1090
1091                        % Ask the new weight for each selected BPM
1092                        for i = 1:size(ChangeList,1)
1093
1094                            k = find(ChangeList(i,1) == BPMlist(:,1));
1095                            l = find(ChangeList(i,2) == BPMlist(k,2));
1096
1097                            prompt = {sprintf('Enter the new weight for BPMx(%d,%d):', ...
1098                                BPMlist(k(l),1), BPMlist(k(l),2)), ...
1099                                sprintf('Enter the new weight for BPMz(%d,%d):', ...
1100                                BPMlist(k(l),1),BPMlist(k(l),2))};
1101                            def = {sprintf('%f',Xweight(k(l))),sprintf('%f',Yweight(k(l)))};
1102                            titlestr = 'CHANGE THE BPM WEIGHTS';
1103                            lineNo = 1;
1104                            answer = inputdlg(prompt, titlestr, lineNo, def);
1105
1106                            if isempty(answer)
1107                                % No change
1108                                fprintf('   No change was made to the BPM weight.\n');
1109                            else
1110                                Xweightnew = str2num(answer{1});
1111                                if isempty(Xweightnew)
1112                                    fprintf('   No change was made to the horizontal BPM weight.\n');
1113                                else
1114                                    Xweight(k(l)) = Xweightnew;
1115                                end
1116
1117                                Yweightnew = str2num(answer{2});
1118                                if isempty(Yweightnew)
1119                                    fprintf('   No change was made to the vertical BPM weight.\n');
1120                                else
1121                                    Yweight(k(l)) = Yweightnew;
1122                                end
1123                            end
1124                        end
1125
1126                        if ~isempty(ChangeList)
1127                            fprintf('   Note:  changing the BPM weight for "Orbit Correction" does not change the goal orbit for "Slow Orbit FeedbackFOFB."\n');
1128                        end
1129
1130                    case 8 % Correction Gain edition
1131
1132                        % Build up matlab prompt
1133                        prompt = {'Enter the horizontal loop gain value :', ...
1134                            'Enter the vertical loop gain value :'};
1135                        % default values
1136                        def = {sprintf('%d',Xgain),sprintf('%d',Ygain)};
1137                        titlestr = 'Change loop gain value';
1138                        lineNo = 1;
1139
1140                        answer = inputdlg(prompt,titlestr,lineNo,def);
1141
1142                        % Answer parsing
1143                        if ~isempty(answer)
1144                            % Horizontal plane
1145                            XgainNew = fix(str2num(answer{1}));
1146                            if isempty(XgainNew)
1147                                disp('   Horizontal gain value cannot be empty.  No change made.');
1148                            else
1149                                if (XgainNew<=0)
1150                                    disp('   Error reading horizontal gain value. No change made.');
1151                                else
1152                                    Xgain = XgainNew;
1153                                    % Display new value on main pannel
1154                                    set(findobj(gcbf,'Tag','FOFBguiTangoXgain'),'string',['H-Loop-Gain = ',num2str(Xgain)]);
1155                                 end
1156                            end
1157                            % Vertical plane
1158                            YgainNew = fix(str2num(answer{2}));
1159                            if isempty(YgainNew)
1160                                disp('   Vertical gain value cannot be empty.  No change made.');
1161                            else
1162                                if (YgainNew<=0)
1163                                    disp('   Error reading vertical gain value.  No change made.');
1164                                else
1165                                    Ygain = YgainNew;
1166                                    % Display new value on main pannel
1167                                    set(findobj(gcbf,'Tag','FOFBguiTangoYgain'),'string',['V-Loop-Gain = ',num2str(Ygain)]);
1168                                end
1169                            end
1170                        end
1171                       
1172                    case 9 % Golden orbit manual edition
1173
1174                        % Ask user to select BPM for modifying golden orbit
1175                        ChangeList = editlist(BPMlist, 'Change BPM', ...
1176                            zeros(size(BPMlist,1),1));
1177
1178                        % Ask the new golden orbit for each selected BPM
1179                        for i = 1:size(ChangeList,1)
1180
1181                            k = find(ChangeList(i,1) == BPMlist(:,1));
1182                            l = find(ChangeList(i,2) == BPMlist(k,2));
1183
1184                            prompt = {sprintf('Enter the new horizontal goal orbit for BPMx(%d,%d):', ...
1185                                BPMlist(k(l),1), BPMlist(k(l),2)), ...
1186                                sprintf('Enter the new vertical goal orbit for BPMz(%d,%d):', ...
1187                                BPMlist(k(l),1),BPMlist(k(l),2))};
1188                            def = {sprintf('%f',Xgoal(k(l))),sprintf('%f',Ygoal(k(l)))};
1189                            titlestr = 'CHANGE THE GOAL ORBIT';
1190                            lineNo = 1;
1191                            answer = inputdlg(prompt, titlestr, lineNo, def);
1192
1193                            if isempty(answer)
1194                                % No change
1195                                fprintf('   No change was made to the golden orbit.\n');
1196                            else
1197                                Xgoalnew = str2num(answer{1});
1198                                if isempty(Xgoalnew)
1199                                    fprintf('   No change was made to the horizontal golden orbit.\n');
1200                                else
1201                                    Xgoal(k(l)) = Xgoalnew;
1202                                end
1203
1204                                Ygoalnew = str2num(answer{2});
1205                                if isempty(Ygoalnew)
1206                                    fprintf('   No change was made to the vertical golden orbit.\n');
1207                                else
1208                                    Ygoal(k(l)) = Ygoalnew;
1209                                end
1210                            end
1211                        end
1212
1213                        if ~isempty(ChangeList)
1214                            fprintf('   Note:  changing the goal orbit for "Orbit Correction" does not change the goal orbit for "Slow Orbit Feedback."\n');
1215                            fprintf('          Re-running soleilinit will restart the goal orbit to the golden orbit."\n');
1216                        end
1217
1218                    case 10 % RF flag edition
1219                        RFCorrFlag = questdlg(sprintf('Set RF Frequency during Orbit Correction?'),'RF Frequency','Yes','No', 'No');
1220                        if strcmp(RFCorrFlag,'No')
1221                            disp('   RF Frequency will not be included in global orbit correction.');
1222                        elseif strcmp(RFCorrFlag,'Yes')
1223                            disp('   RF Frequency will be included in global orbit correction.');
1224                        end
1225                        FB.RFCorrFlag = RFCorrFlag;
1226                end
1227            end
1228            close(h_fig1);
1229        end
1230        % END of switchyard for orbit correction edition
1231
1232        % This part is common for case 'orbit correction edition'
1233
1234        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1235        % Build up Orbit correction Structures   %
1236        %  for setorbit programme : OCSx and OCSy%
1237        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1238        %  ORBIT CORRECTION STRUCTURE (OCS)
1239        %    OCS.BPM (data structure)
1240        %    OCS.CM  (data structure)
1241        %    OCS.GoalOrbit
1242        %    OCS.NIter
1243        %    OCS.SVDIndex
1244        %    OCS.IncrementalFlag = 'Yes'/'No'
1245        %    OCS.BPMWeight
1246        %    OCS.Flags = { 'FitRF' , etc.  }
1247
1248        % Horizontal plane
1249        OCSx.BPM = getx(BPMlist, 'struct');
1250        OCSx.GoalOrbit = Xgoal;
1251        OCSx.CM  = getam(HCMFamily, HCMlist, 'struct','Model');
1252        OCSx.NIter = 1; % Number of iteration
1253        OCSx.SVDIndex = Xivec; % number of eigenvectors for correction
1254        OCSx.IncrementalFlag = 'No';
1255        if strcmp(RFCorrFlag,'Yes')
1256            OCSx.FitRF = 1; % take RF as a corrector
1257        else
1258            OCSx.FitRF = 0;
1259        end
1260
1261        %Default weight for correctores and BPMs
1262        OCSx.CMWeight  = HCMweight;
1263        OCSx.BPMWeight = Xweight;
1264
1265        % Vertical plane
1266        OCSy.BPM = getz(BPMlist, 'struct');
1267        OCSy.CM  = getam(VCMFamily, VCMlist, 'struct','Model');
1268        OCSy.GoalOrbit = Ygoal;
1269        OCSy.NIter = 1;
1270        OCSy.SVDIndex = Yivec;
1271        OCSy.IncrementalFlag = 'No';
1272        OCSy.FitRF = 0;
1273
1274        %Default weight for correctors and BPMs
1275        OCSy.CMWeight  = VCMweight;
1276        OCSy.BPMWeight = Yweight;
1277
1278        % Save structures for later orbit correction
1279        FB.OCSx = OCSx;
1280        FB.OCSy = OCSy;
1281
1282        % List of BPM et correctors to be used
1283        FB.BPMlist = BPMlist;
1284        FB.HCMlist = HCMlist;
1285        FB.VCMlist = VCMlist;
1286
1287        % List of singular values
1288        FB.Xivec = Xivec;
1289        FB.Yivec = Yivec;
1290
1291        % Loop gain values
1292        FB.Xgain = Xgain;
1293        FB.Ygain = Ygain;
1294
1295        % Goal orbit
1296        FB.Xgoal = OCSx.GoalOrbit;
1297        FB.Ygoal = OCSy.GoalOrbit;
1298
1299        % RF corrector flag
1300        FB.RFCorrFlag = RFCorrFlag;
1301
1302        FB.SOFBandFOFB = 0;
1303
1304        % save FB structure in application
1305        set(findobj(gcbf,'Tag','FOFBguiTangoButtonOrbitCorrectionSetupFOFB'),'Userdata',FB);
1306       
1307        % save data for SOFB
1308        savaData2File;
1309       
1310        % modif 03/01/2012 pour suppression bouton Generate new Matrix for
1311        % FPGA
1312        if ~InitFlag
1313        FOFBguiTango('ConvertMatrix4FPGA');
1314        end
1315%% OrbitCorrectionFOFB
1316    case 'OrbitCorrectionFOFB' % Manual Orbit Correction
1317
1318        try
1319            check4feedbackflag(devLockName);
1320            %setup average data for reading BPMs
1321            setfamilydata('gethbpmaverage','BPMx','Monitor', 'SpecialFunctionGet')
1322            setfamilydata('getvbpmaverage','BPMz','Monitor', 'SpecialFunctionGet')
1323
1324        catch
1325            fprintf('\n  %s \n',lasterr);
1326            fprintf('   %s \n', datestr(clock));
1327            disp('   ********************************');
1328            disp('   **  Orbit Correction Aborted  **');
1329            disp('   ********************************');
1330            fprintf('\n');
1331            return
1332        end
1333
1334        OrbitLoopIter = 3; % a 3 step iteration
1335
1336        fprintf('\n');
1337        fprintf('   *********************************\n');
1338        fprintf('   **  Starting Orbit Correction  **\n');
1339        fprintf('   *********************************\n');
1340        fprintf('   %s \n', datestr(clock));
1341
1342        StartFlag = questdlg(sprintf('Start orbit correction ?'),'Orbit Correction','Yes','No','No');
1343        if strcmp(StartFlag,'No')
1344            disp('   ********************************');
1345            disp('   **  Orbit Correction Aborted  **');
1346            disp('   ********************************');
1347            fprintf('\n');
1348            return
1349        end
1350
1351        if getdcct < DCCTMIN    % Don't correct the orbit if the current is too small
1352            fprintf('   Orbit not corrected due to small current.\n');
1353            return
1354        end
1355
1356        % get Structure for correction
1357        FB = get(findobj(gcbf,'Tag','FOFBguiTangoButtonOrbitCorrectionSetupFOFB'),'Userdata');
1358
1359        fprintf('   Starting horizontal and vertical global orbit correction (SVD method).\n');
1360
1361        % Number of steerer magnet correctors
1362        N_HCM = size(FB.HCMlist,1);
1363        N_VCM = size(FB.VCMlist,1);
1364
1365
1366        for iloop = 1:OrbitLoopIter,
1367            try
1368                %%%%%%%%%%%%%%%%%
1369                % use the following to get corrector settings in OCS and
1370                % check everything seems Ok and gives back predicted correction
1371                %% V-plane checks
1372                if get(findobj(gcbf,'Tag','FOFBguiTangoCheckboxHcorrection'),'Value') == 1
1373                    HOrbitCorrectionFlag = 1;
1374                    %FB.OCSx = setorbit(FB.OCSx,'Nodisplay','Nosetsp');
1375                    FB.OCSx = setorbit(FB.OCSx,'Nodisplay','Nosetsp','FitRFHCM0');
1376
1377                    HCMSP = getAM(HCMFamily, FB.HCMlist);  % present corrector values
1378                    HCMSP_next = HCMSP + FB.OCSx.CM.Delta(1:N_HCM);       % next corrector values, just slow correctors (no RF)
1379
1380                    MaxSP = maxsp(HCMFamily,FB.HCMlist);
1381                    MinSP = minsp(HCMFamily,FB.HCMlist);
1382
1383                    if any(MaxSP - HCMSP_next  < 0)
1384                        HCMnum = find(HCMSP_next > MaxSP);
1385                        % message to screen
1386                        fprintf('**One or more of the horizontal correctors is at its maximum positive value!! Stopping orbit Feedback. \n');
1387                        fprintf('%s\n',datestr(now));
1388                        fprintf('**%s is one of the problem correctors.\n', ...
1389                            cell2mat(family2tango(HCMFamily,'Setpoint',FB.HCMlist(HCMnum(1),:))));
1390                        HOrbitCorrectionFlag = 0;
1391                    end
1392
1393                    if any(MinSP - HCMSP_next  > 0)
1394                        HCMnum = find(HCMSP_next < MinSP);
1395                        % message to screen
1396                        fprintf('**One or more of the horizontal correctors is at its maximum negative value!! Stopping orbit Feedback. \n');
1397                        fprintf('%s\n',datestr(now));
1398                        fprintf('**%s is one of the problem correctors.\n', ...
1399                            cell2mat(family2tango(HCMFamily,'Setpoint',FB.HCMlist(HCMnum(1),:))));
1400                        HOrbitCorrectionFlag = 0;
1401                    end
1402
1403                    if any(HCMSP_next > MaxSP - 1)
1404                        HCMnum = find(HCMSP_next > MaxSP - 1);
1405                        for ik = 1:length(HCMnum)
1406                            fprintf('**Horizontal correctors %s is above %f! \n', ...
1407                                cell2mat(family2tango(HCMFamily,'Setpoint',FB.HCMlist(HCMnum(ik),:))), ...
1408                                MaxSP(HCMnum(ik)) - 1);
1409                        end
1410                        fprintf('%s\n',datestr(now));
1411                        fprintf('**The orbit correction is still working but this problem should be investigated. \n');
1412                    end
1413
1414                    if any(HCMSP_next < MinSP + 1)
1415                        HCMnum = find(HCMSP_next < MinSP + 1);
1416                        for ik = 1:length(HCMnum)
1417                            fprintf('**Horizontal correctors %s is below %f! \n', ...
1418                                cell2mat(family2tango(HCMFamily,'Setpoint',FB.HCMlist(HCMnum(ik),:))), ...
1419                                MinSP(HCMnum(ik)) + 1);
1420                        end
1421                        fprintf('%s\n',datestr(now));
1422                        fprintf('**The orbit correction is still working but this problem should be investigated. \n');
1423                    end
1424
1425                end
1426
1427                %% V-plane checks
1428                if get(findobj(gcbf,'Tag','FOFBguiTangoCheckboxVcorrection'),'Value') ==1
1429                    FB.OCSy = setorbit(FB.OCSy,'Nodisplay','Nosetsp');
1430                    VOrbitCorrectionFlag = 1;
1431                    VCMSP = getAM(VCMFamily,FB.VCMlist); % Get corrector values before correction
1432                    VCMSP_next = VCMSP + FB.OCSy.CM.Delta(1:N_VCM); % New corrector values to be set in
1433
1434                    MaxSP = maxsp(VCMFamily,FB.VCMlist);
1435                    MinSP = minsp(VCMFamily,FB.VCMlist);
1436
1437                    if any(MaxSP - VCMSP_next  < 0)
1438                        VCMnum = find(VCMSP_next > MaxSP);
1439                        % message to screen
1440                        fprintf('**One or more of the vertical correctors is at its maximum positive value!! Stopping orbit Feedback. \n');
1441                        fprintf('%s\n',datestr(now));
1442                        fprintf('**%s is one of the problem correctors.\n', ...
1443                            cell2mat(family2tango(VCMFamily,'Setpoint',FB.VCMlist(VCMnum(1),:))));
1444                    end
1445
1446                    if any(MinSP - VCMSP_next  > 0)
1447                        VCMnum = find(VCMSP_next < MinSP);
1448                        % message to screen
1449                        fprintf('**One or more of the vertical correctors is at its maximum negative value!! Stopping orbit Feedback. \n');
1450                        fprintf('%s\n',datestr(now));
1451                        fprintf('**%s is one of the problem correctors.\n', ...
1452                            cell2mat(family2tango(VCMFamily,'Setpoint',FB.VCMlist(VCMnum(1),:))));
1453                    end
1454
1455                    if any(VCMSP_next > MaxSP - 1)
1456                        VCMnum = find(VCMSP_next > MaxSP - 1);
1457                        for ik = 1:length(VCMnum)
1458                            fprintf('**Vertical correctors %s is above %f! \n', ...
1459                                cell2mat(family2tango(VCMFamily,'Setpoint',FB.VCMlist(VCMnum(ik),:))), ...
1460                                MaxSP(VCMnum(ik)) - 1);
1461                        end
1462                        fprintf('%s\n',datestr(now));
1463                        fprintf('**The orbit correction is still working but this problem should be investigated. \n');
1464                    end
1465
1466                    if any(VCMSP_next < MinSP + 1)
1467                        VCMnum = find(VCMSP_next < MinSP + 1);
1468                        for ik = 1:length(VCMnum)
1469                            fprintf('**Vertical correctors %s is below %f! \n', ...
1470                                cell2mat(family2tango(VCMFamily,'Setpoint',FB.VCMlist(VCMnum(ik),:))), ...
1471                                MinSP(VCMnum(ik)) + 1);
1472                        end
1473                        fprintf('%s\n',datestr(now));
1474                        fprintf('**The orbit correction is still working but this problem should be investigated. \n');
1475                    end
1476                end
1477
1478                %%%%%%%%%%%%%%%%%%%%%%
1479
1480
1481                if (get(findobj(gcbf,'Tag','FOFBguiTangoCheckboxHcorrection'),'Value') == 1) && HOrbitCorrectionFlag
1482                    % Correct horizontal orbit
1483                    %FB.OCSx = setorbit(FB.OCSx,'NoDisplay');
1484                    FB.OCSx = setorbit(FB.OCSx,'NoDisplay', 'FitRFHCM0');
1485                end
1486
1487                if (get(findobj(gcbf,'Tag','FOFBguiTangoCheckboxVcorrection'),'Value') == 1) && VOrbitCorrectionFlag
1488                    % Correct vertical orbit
1489                    FB.OCSy = setorbit(FB.OCSy,'NoDisplay');
1490                end
1491
1492                % Check for current in machine - stop orbit correction if
1493                % DCCT < DCCTMIN
1494                if (getdcct < DCCTMIN)
1495                    error('**There is less than %d in the machine! Stopping orbit correction.', DCCTMIN);
1496                end
1497
1498                % Residual orbit
1499                Horbit = getx(FB.OCSx.BPM.DeviceList);
1500                Vorbit = getz(FB.OCSy.BPM.DeviceList);
1501
1502                x = FB.OCSx.GoalOrbit - Horbit;
1503                y = FB.OCSy.GoalOrbit - Vorbit;
1504
1505                fprintf('   %d. Horizontal RMS = %.3f mm (absolute %.3f mm)\n', iloop, std(x), std(Horbit));
1506                fprintf('   %d.   Vertical RMS = %.3f mm (absolute %.3f mm)\n', iloop, std(y), std(Vorbit));
1507
1508                pause(0);
1509
1510            catch
1511                fprintf('   %s \n',lasterr);
1512                fprintf('   Orbit correction failed due to error condition!\n  Fix the problem, reload the lattice (refreshthering), and try again.  \n\n');
1513                return
1514            end
1515        end
1516
1517        fprintf('   %s \n', datestr(clock));
1518        fprintf('   *********************************\n');
1519        fprintf('   **  Orbit Correction Complete  **\n');
1520        fprintf('   *********************************\n\n');
1521
1522        %setup manager data for reading BPMs
1523        setfamilydata('gethbpmgroup','BPMx','Monitor', 'SpecialFunctionGet')
1524        setfamilydata('getvbpmgroup','BPMz','Monitor', 'SpecialFunctionGet')
1525
1526%% FeedbackSetupFOFB       
1527    case 'FeedbackSetupFOFB' % Fast orbit Feedback (FOFB)
1528
1529        InitFlag = Input2;           % Input #2: if InitFlag, then initialize variables
1530
1531        if InitFlag % Used only at startup
1532            %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1533            % Edit the following lists to change default configuration of Orbit Correction %
1534            %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1535
1536            % WARNING CAN BE DIFFERENT FROM THE ORBIT CORRECTION
1537            % To start with same correctors and Bpms are used as in manual
1538            % correction
1539            % Corrector magnets
1540            [HCMlist VCMlist BPMlist] = getlocallist;
1541
1542            % Singular value number
1543            Xivec = 1:45; % 40 w/o Orthogonal correction 41 if orthogonal correction
1544            Yivec = 1:44;
1545
1546            % Get goal orbit for FOFB
1547            Xgoal = getgolden(BPMxFamily, BPMlist);
1548            Ygoal = getgolden(BPMyFamily, BPMlist);
1549
1550            % BPM weights
1551            Xweight = ones(size(BPMlist,1), 1);
1552            Yweight = ones(size(BPMlist,1), 1);
1553
1554            % Correctors weights
1555            HCMweight = ones(size(HCMlist,1), 1);
1556            VCMweight = ones(size(VCMlist,1), 1);
1557           
1558           
1559        else % use for FOFB Edition
1560
1561            % Get FB structure
1562            FB = get(findobj(gcbf,'Tag','FOFBguiTangoButtonFeedbackSetup'),'Userdata');
1563
1564            BPMlist = FB.BPMlist;
1565            HCMlist = FB.HCMlist;
1566            VCMlist = FB.VCMlist;
1567
1568            Xivec = FB.Xivec;
1569            Yivec = FB.Yivec;
1570
1571            Xgoal = FB.Xgoal;
1572            Ygoal = FB.Ygoal;
1573
1574            HCMweight = FB.OCSx.CMWeight;
1575            VCMweight = FB.OCSy.CMWeight;
1576            Xweight = FB.OCSx.BPMWeight;
1577            Yweight = FB.OCSy.BPMWeight;
1578
1579            % Add button to change #ivectors, cm
1580            EditFlag = 0;
1581            h_fig1 = figure;
1582
1583            while EditFlag ~= 9
1584
1585                % get Sensitivity matrices
1586                Sh = getrespmat(BPMxFamily, BPMlist, HCMFamily, HCMlist, [], SR_GEV);
1587                Sv = getrespmat(BPMyFamily, BPMlist, VCMFamily, VCMlist, [], SR_GEV);
1588
1589                % Compute SVD
1590                [Ux, SVx, Vx] = svd(Sh);
1591                [Uy, SVy, Vy] = svd(Sv);
1592
1593                % Remove singular values greater than the actual number of singular values
1594                i = find(Xivec>length(diag(SVx)));
1595                if ~isempty(i)
1596                    disp('   Horizontal singular value vector scaled since there were more elements in the vector than singular values.');
1597                    pause(0);
1598                    Xivec(i) = [];
1599                end
1600                i = find(Yivec>length(diag(SVy)));
1601                if ~isempty(i)
1602                    disp('   Vertical singular value vector scaled since there were more elements in the vector than singular values.');
1603                    pause(0);
1604                    Yivec(i) = [];
1605                end
1606
1607                % Display singular value plot
1608                figure(h_fig1);
1609                subplot(2,1,1);
1610                semilogy(diag(SVx),'b');
1611                hold on;
1612                semilogy(diag(SVx(Xivec,Xivec)),'xr');
1613                ylabel('Horizontal');
1614                title('Response Matrix Singular Values');
1615                hold off;
1616                subplot(2,1,2);
1617                semilogy(diag(SVy),'b');
1618                hold on;
1619                semilogy(diag(SVy(Yivec,Yivec)),'xr');
1620                xlabel('Singular Value Number');
1621                ylabel('Vertical');
1622                hold off;
1623                drawnow;
1624
1625                % Build up menu edition
1626                EditFlag = menu('Change Parameters?','Singular Values','HCM List', 'HCM weight', ...
1627                    'VCM List', 'VCM weight', ...
1628                    'BPM List', 'BPM weight', 'Change the Goal Orbit', 'Return');
1629
1630                % Begin FOFB edition switchyard
1631                switch EditFlag
1632                    case 1
1633                        prompt = {'Enter the horizontal singular value number (Matlab vector format):', ...
1634                            'Enter the vertical singular value numbers (Matlab vector format):'};
1635                        def = {sprintf('[%d:%d]',1,Xivec(end)),sprintf('[%d:%d]',1,Yivec(end))};
1636                        titlestr='SVD Orbit Feedback';
1637                        lineNo=1;
1638                        answer=inputdlg(prompt,titlestr,lineNo,def);
1639                        if ~isempty(answer)
1640                            XivecNew = fix(str2num(answer{1}));
1641                            if isempty(XivecNew)
1642                                disp('   Horizontal singular value vector cannot be empty.  No change made.');
1643                            else
1644                                if any(XivecNew<=0) || max(XivecNew)>length(diag(SVx))
1645                                    disp('   Error reading horizontal singular value vector.  No change made.');
1646                                else
1647                                    Xivec = XivecNew;
1648                                end
1649                            end
1650                            YivecNew = fix(str2num(answer{2}));
1651                            if isempty(YivecNew)
1652                                disp('   Vertical singular value vector cannot be empty.  No change made.');
1653                            else
1654                                if any(YivecNew<=0) || max(YivecNew)>length(diag(SVy))
1655                                    disp('   Error reading vertical singular value vector.  No change made.');
1656                                else
1657                                    Yivec = YivecNew;
1658                                end
1659                            end
1660                        end
1661
1662
1663                    case 2 % Horizontal corrector list edition
1664                        List= getlist(HCMFamily);
1665                        CheckList = zeros(size(List,1));
1666                        ListOld = HCMlist;
1667                        Elem = dev2elem(HCMFamily, HCMlist);
1668                        CheckList(Elem) = ones(size(Elem));
1669                        CheckList = CheckList(dev2elem(HCMFamily,List));
1670
1671                        newList = editlist(List, HCMFamily, CheckList);
1672
1673                        if isempty(newList)
1674                            fprintf('   Horizontal corrector magnet list cannot be empty.  No change made.\n');
1675                        else
1676                            HCMlist = newList;
1677                        end
1678
1679                        %set correctors weight values
1680                        HCMweightOld = HCMweight;
1681                        HCMweight = ones(size(HCMlist,1), 1);
1682
1683                        %if a new corrector is added, then set the weight values to
1684                        %one.
1685                        % Otherwise keep the present weight values
1686                        for i = 1:size(HCMlist,1)
1687
1688                            % Is it a new corrector?
1689                            k = find(HCMlist(i,1)==ListOld(:,1));
1690                            l = find(HCMlist(i,2)==ListOld(k,2));
1691
1692                            if isempty(k) || isempty(l)
1693                                % New corrector
1694                            else
1695                                % Use the old value for old correctors
1696                                HCMweight(i) = HCMweightOld(k(l));
1697                            end
1698                        end
1699                    case 3 % Horizontal corrector weight edition
1700
1701                        % Ask user to select HCM for modifying weight
1702                        ChangeList = editlist(HCMlist, 'Change HCM', ...
1703                            zeros(size(HCMlist,1),1));
1704
1705                        % Ask the new weight for each selected corrector
1706                        for i = 1:size(ChangeList,1)
1707
1708                            k = find(ChangeList(i,1) == HCMlist(:,1));
1709                            l = find(ChangeList(i,2) == HCMlist(k,2));
1710
1711                            prompt = {sprintf('Enter the new weight for HCM(%d,%d):', ...
1712                                HCMlist(k(l),1), HCMlist(k(l),2))};
1713                            def = {sprintf('%f',HCMweight(k(l))),sprintf('%f',HCMweight(k(l)))};
1714                            titlestr = 'CHANGE THE HCM WEIGHTS';
1715                            lineNo = 1;
1716                            answer = inputdlg(prompt, titlestr, lineNo, def);
1717
1718                            if isempty(answer)
1719                                % No change
1720                                fprintf('   No change was made to the VCM weight.\n');
1721                            else
1722                                HCMweightnew = str2num(answer{1});
1723                                if isempty(HCMweightnew)
1724                                    fprintf('   No change was made to the horizontal BPM weight.\n');
1725                                else
1726                                    HCMweight(k(l)) = HCMweightnew;
1727                                end
1728                            end
1729                        end
1730
1731                        if ~isempty(ChangeList)
1732                            fprintf('   Note:  changing the HCM weight for "Slow Orbit Feedback" does not change the goal orbit for "Orbit Correction."\n');
1733                        end
1734
1735                    case 4 % Vertical corrector list edition
1736                        List = getlist(VCMFamily);
1737                        CheckList = zeros(size(List,1));
1738                        ListOld = VCMlist;
1739                        Elem = dev2elem(VCMFamily, VCMlist);
1740                        CheckList(Elem) = ones(size(Elem));
1741                        CheckList = CheckList(dev2elem(VCMFamily,List));
1742
1743                        newList = editlist(List, VCMFamily, CheckList);
1744
1745                        if isempty(newList)
1746                            fprintf('   Vertical corrector magnet cannot be empty.  No change made.\n');
1747                        else
1748                            VCMlist = newList;
1749                        end
1750
1751                        %set correctors weight values
1752                        VCMweightOld = VCMweight;
1753                        VCMweight = ones(size(VCMlist,1), 1);
1754
1755                        %if a new corrector is added, then set the weight values to
1756                        %one.
1757                        % Otherwise keep the present weight values
1758                        for i = 1:size(VCMlist,1)
1759
1760                            % Is it a new corrector?
1761                            k = find(VCMlist(i,1)==ListOld(:,1));
1762                            l = find(VCMlist(i,2)==ListOld(k,2));
1763
1764                            if isempty(k) || isempty(l)
1765                                % New corrector
1766                            else
1767                                % Use the old value for old correctors
1768                                VCMweight(i) = VCMweightOld(k(l));
1769                            end
1770                        end
1771
1772                    case 5 % Vertical corrector weight edition
1773                        % Ask user to select VCM for modifying weight
1774                        ChangeList = editlist(VCMlist, 'Change VCM', ...
1775                            zeros(size(VCMlist,1),1));
1776
1777                        % Ask the new weight for each selected corrector
1778                        for i = 1:size(ChangeList,1)
1779
1780                            k = find(ChangeList(i,1) == VCMlist(:,1));
1781                            l = find(ChangeList(i,2) == VCMlist(k,2));
1782
1783                            prompt = {sprintf('Enter the new weight for VCM(%d,%d):', ...
1784                                VCMlist(k(l),1), VCMlist(k(l),2))};
1785                            def = {sprintf('%f',VCMweight(k(l))),sprintf('%f',VCMweight(k(l)))};
1786                            titlestr = 'CHANGE THE VCM WEIGHTS';
1787                            lineNo = 1;
1788                            answer = inputdlg(prompt, titlestr, lineNo, def);
1789
1790                            if isempty(answer)
1791                                % No change
1792                                fprintf('   No change was made to the VCM weight.\n');
1793                            else
1794                                VCMweightnew = str2num(answer{1});
1795                                if isempty(VCMweightnew)
1796                                    fprintf('   No change was made to the horizontal BPM weight.\n');
1797                                else
1798                                    VCMweight(k(l)) = VCMweightnew;
1799                                end
1800                            end
1801                        end
1802
1803                        if ~isempty(ChangeList)
1804                            fprintf('   Note:  changing the VCM weight for "Slow Orbit Feedback" does not change the goal orbit for "Orbit Correction."\n');
1805                        end
1806
1807                    case 6 % BPM List edition
1808                        % Back present BPM list and goal orbit
1809                        ListOld = BPMlist;
1810                        XgoalOld = Xgoal;
1811                        YgoalOld = Ygoal;
1812                        XweightOld = Xweight;
1813                        YweightOld = Yweight;
1814
1815                        List = family2dev(BPMxFamily);
1816
1817                        %Check BPM already in the list CheckList(i) = 1
1818                        %      BPM not in the list CheckList(i) = 0
1819                        CheckList = zeros(size(List,1),1);
1820                        if ~isempty(BPMlist)
1821                            for i = 1:size(List,1)
1822                                k = find(List(i,1)==BPMlist(:,1));
1823                                l = find(List(i,2)==BPMlist(k,2));
1824
1825                                if isempty(k) || isempty(l)
1826                                    % Item not in list
1827                                else
1828                                    CheckList(i) = 1;
1829                                end
1830                            end
1831                        end
1832
1833                        % User edition of the BPM lsit
1834                        newList = editlist(List, 'BPM', CheckList);
1835                        if isempty(newList)
1836                            fprintf('   BPM list cannot be empty.  No change made.\n');
1837                        else
1838                            BPMlist = newList;
1839                        end
1840
1841                        % Set the goal orbit to the golden orbit and weight values
1842                        Xgoal = getgolden(BPMxFamily, BPMlist);
1843                        Ygoal = getgolden(BPMyFamily, BPMlist);
1844                        Xweight = ones(size(BPMlist,1),1);
1845                        Yweight = ones(size(BPMlist,1),1);
1846
1847                        %if a new BPM is added, then set the goal orbit to
1848                        %the golden orbit.
1849                        % Otherwise keep the present goal orbit
1850                        for i = 1:size(BPMlist,1)
1851
1852                            % Is it a new BPM?
1853                            k = find(BPMlist(i,1)==ListOld(:,1));
1854                            l = find(BPMlist(i,2)==ListOld(k,2));
1855
1856                            if isempty(k) || isempty(l)
1857                                % New BPM
1858                            else
1859                                % Use the old value for old BPM
1860                                Xgoal(i) = XgoalOld(k(l));
1861                                Ygoal(i) = YgoalOld(k(l));
1862                                Xweight(i) = XweightOld(k(l));
1863                                Yweight(i) = YweightOld(k(l));
1864                            end
1865                        end
1866
1867                    case 7 % BPM weight edition
1868                        % Ask user to select BPM for modifying weight
1869                        ChangeList = editlist(BPMlist, 'Change BPM', ...
1870                            zeros(size(BPMlist,1),1));
1871
1872                        % Ask the new weight for each selected BPM
1873                        for i = 1:size(ChangeList,1)
1874
1875                            k = find(ChangeList(i,1) == BPMlist(:,1));
1876                            l = find(ChangeList(i,2) == BPMlist(k,2));
1877
1878                            prompt = {sprintf('Enter the new weight for BPMx(%d,%d):', ...
1879                                BPMlist(k(l),1), BPMlist(k(l),2)), ...
1880                                sprintf('Enter the new weight for BPMz(%d,%d):', ...
1881                                BPMlist(k(l),1),BPMlist(k(l),2))};
1882                            def = {sprintf('%f',Xweight(k(l))),sprintf('%f',Yweight(k(l)))};
1883                            titlestr = 'CHANGE THE BPM WEIGHTS';
1884                            lineNo = 1;
1885                            answer = inputdlg(prompt, titlestr, lineNo, def);
1886
1887                            if isempty(answer)
1888                                % No change
1889                                fprintf('   No change was made to the BPM weight.\n');
1890                            else
1891                                Xweightnew = str2num(answer{1});
1892                                if isempty(Xweightnew)
1893                                    fprintf('   No change was made to the horizontal BPM weight.\n');
1894                                else
1895                                    Xweight(k(l)) = Xweightnew;
1896                                end
1897
1898                                Yweightnew = str2num(answer{2});
1899                                if isempty(Yweightnew)
1900                                    fprintf('   No change was made to the vertical BPM weight.\n');
1901                                else
1902                                    Yweight(k(l)) = Yweightnew;
1903                                end
1904                            end
1905                        end
1906
1907                        if ~isempty(ChangeList)
1908                            fprintf('   Note:  changing the BPM weight for "Slow Orbit Feedback" does not change the goal orbit for "Orbit Correction."\n');
1909                        end
1910
1911                    case 8 % Goal orbit edition
1912                        ChangeList = editlist(BPMlist, 'Change BPM', zeros(size(BPMlist,1),1));
1913
1914                        for i = 1:size(ChangeList,1)
1915
1916                            k = find(ChangeList(i,1)==BPMlist(:,1));
1917                            l = find(ChangeList(i,2)==BPMlist(k,2));
1918
1919                            prompt={sprintf('Enter the new horizontal goal orbit for BPMx(%d,%d):', ...
1920                                BPMlist(k(l),1),BPMlist(k(l),2)), ...
1921                                sprintf('Enter the new vertical goal orbit for BPMz(%d,%d):', ...
1922                                BPMlist(k(l),1),BPMlist(k(l),2))};
1923                            def={sprintf('%f',Xgoal(k(l))),sprintf('%f',Ygoal(k(l)))};
1924                            titlestr='CHANGE THE GOAL ORBIT';
1925                            lineNo=1;
1926                            answer = inputdlg(prompt, titlestr, lineNo, def);
1927
1928                            if isempty(answer)
1929                                % No change
1930                                fprintf('   No change was made to the golden orbit.\n');
1931                            else
1932                                Xgoalnew = str2num(answer{1});
1933                                if isempty(Xgoalnew)
1934                                    fprintf('   No change was made to the horizontal golden orbit.\n');
1935                                else
1936                                    Xgoal(k(l)) = Xgoalnew;
1937                                end
1938
1939                                Ygoalnew = str2num(answer{2});
1940                                if isempty(Ygoalnew)
1941                                    fprintf('   No change was made to the vertical golden orbit.\n');
1942                                else
1943                                    Ygoal(k(l)) = Ygoalnew;
1944                                end
1945                            end
1946                        end
1947                        if ~isempty(ChangeList)
1948                            fprintf('   Note:  Changing the goal orbit for "Slow Orbit Feedback" does not change the goal orbit for "Orbit Correction."\n');
1949                            fprintf('          Re-running srcontrol will restart the goal orbit to the golden orbit."\n');
1950                        end
1951                end
1952            end
1953            close(h_fig1);
1954        end
1955
1956        % End of FOFB edition switchyard
1957
1958        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1959        %         Build up FOFB Structures       %
1960        %  for setorbit programme : OCSx and OCSy%
1961        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1962        %  ORBIT CORRECTION STRUCTURE (OCS)
1963        %    OCS.BPM (data structure)
1964        %    OCS.CM  (data structure)
1965        %    OCS.GoalOrbit
1966        %    OCS.NIter
1967        %    OCS.SVDIndex
1968        %    OCS.IncrementalFlag = 'Yes'/'No'
1969        %    OCS.BPMWeight
1970        %    OCS.Flags = { 'FitRF' , etc.  }
1971
1972        OCSx.BPM = getx(BPMlist, 'struct');
1973        OCSx.CM =  getam(HCMFamily, HCMlist, 'struct');
1974        OCSx.GoalOrbit = Xgoal;
1975        OCSx.NIter = 2;
1976        OCSx.SVDIndex = Xivec;
1977        OCSx.IncrementalFlag = 'No';
1978        OCSx.CMWeight  = HCMweight;
1979        OCSx.BPMWeight = Xweight;
1980        OCSx.FitRF = 0;
1981
1982        OCSy.BPM = getz(BPMlist, 'struct');
1983        OCSy.CM = getam(VCMFamily, VCMlist, 'struct');
1984        OCSy.GoalOrbit = Ygoal;
1985        OCSy.NIter = 2;
1986        OCSy.SVDIndex = Yivec;
1987        OCSy.IncrementalFlag = 'No';
1988        OCSy.CMWeight  = VCMweight;
1989        OCSy.BPMWeight = Yweight;
1990        OCSy.FitRF = 0;
1991
1992        % Save FOFB strucutre
1993        FB.OCSx = OCSx;
1994        FB.OCSy = OCSy;
1995
1996        % BPM and CM list
1997        FB.BPMlist = BPMlist;
1998        FB.HCMlist = HCMlist;
1999        FB.VCMlist = VCMlist;
2000
2001        % Singular value number
2002        FB.Xivec = Xivec;
2003        FB.Yivec = Yivec;
2004
2005        % Goal orbit list
2006        FB.Xgoal = Xgoal;
2007        FB.Ygoal = Ygoal;
2008
2009       
2010       
2011%% STARTRFFOFB
2012    case 'STARTRFFOFB'
2013
2014        % RF FeedbackFOFB only
2015        try
2016            % First check if current in storage ring
2017            if getdcct < DCCTMIN     % Don't Feedback if the current is too small
2018                fprintf('%s  Orbit Feedback not started due to low beam current (<%d mA)\n',datestr(now), DCCTMIN);
2019                return;
2020            end
2021            % read RF
2022
2023            % read status of RF feedback
2024            statusValue = readattribute([devRFFBManager '/State']);
2025            % Test masterclock
2026            rfvalue = getrf;
2027
2028            fprintf('\n');
2029            fprintf('   *******************************\n');
2030            fprintf('   **  Starting RF Feedback  **\n');
2031            fprintf('   *******************************\n');
2032            fprintf('   %s \n', datestr(clock));
2033
2034        catch
2035            fprintf('\n  %s \n',lasterr);
2036            fprintf('   %s \n', datestr(clock));
2037            fprintf('   *************************************************************\n');
2038            fprintf('   **  RF Feedback could not start due to error condition  **\n');
2039            fprintf('   *************************************************************\n\n');
2040            set(0,'showhiddenhandles','off');
2041            pause(0);
2042            return
2043        end
2044
2045        % Check whether RF feedback is already running
2046        isRunning = readattribute([devRFFBManager '/isRunning']);
2047
2048        if isRunning
2049            fprintf('\n  %s \n',lasterr);
2050            fprintf('   %s \n', datestr(clock));
2051            fprintf('   *************************************************************\n');
2052            fprintf('   **          RF feedback is already running                            **\n');
2053            fprintf('   *************************************************************\n\n');
2054            warndlg(' RF feedback is already running');
2055            return;
2056        end
2057
2058        %% Check if other errors
2059        if statusValue ~= 0 && statusValue ~= 1 && statusValue ~= 8
2060            fprintf('\n  %s \n',lasterr);
2061            fprintf('   %s \n', datestr(clock));
2062            fprintf('   *************************************************************\n');
2063            fprintf('   **  RF Feedback could not start due to error condition  **\n');
2064            fprintf('   *************************************************************\n\n');
2065            rep = readattribute([devRFFBManager '/Status']);
2066            fprintf('%s \n', rep{1});
2067            set(0,'showhiddenhandles','off');
2068            pause(0);
2069            return
2070        end
2071
2072        % Confirmation dialogbox
2073        StartFlag = questdlg('Start RF Feedback?', 'RF Feedback','Yes','No','No');
2074        set(findobj(gcbf,'Tag','FOFBguiTangoStaticTextInformation'),'String','RF Feedback Started');
2075
2076        if strcmp(StartFlag,'No')
2077            fprintf('   %s \n', datestr(clock));
2078            fprintf('   ***************************\n');
2079            fprintf('   **  RF Feedback Exit  **\n');
2080            fprintf('   ***************************\n\n');
2081            pause(0);
2082            return
2083        end
2084
2085        set(0,'showhiddenhandles','on');
2086
2087        try
2088
2089            tango_command_inout2(devRFFBManager,'Start');
2090
2091            %set(findobj(gcbf,'Tag','FOFBguiTangoStaticTextHorizontal'),'String', ...
2092            %    sprintf('Horizontal RMS = %.4f mm',STDx),'ForegroundColor',[0 0 0]);
2093            %set(findobj(gcbf,'Tag','FOFBguiTangoStaticTextVertical'),'String', ...
2094            %    sprintf('Vertical RMS = %.4f mm',STDy),'ForegroundColor',[0 0 0]);
2095
2096            check4feedbackflag(devLockName);
2097
2098            % Lock  SOFB service
2099            %Locktag  = tango_command_inout2(devLockName,'Lock', 'rffb');
2100
2101            pause(0);
2102            isRunning = readattribute([devRFFBManager '/isRunning']);
2103
2104            if ~isRunning
2105                fprintf('\n  %s \n',lasterr);
2106                fprintf('   %s \n', datestr(clock));
2107                fprintf('   *************************************************************\n');
2108                fprintf('   **          RF feedback no started                         **\n');
2109                fprintf('   *************************************************************\n\n');
2110                return;
2111            end
2112        catch
2113
2114            fprintf('\n  %s \n',lasterr);
2115
2116            fprintf('   %s \n', datestr(clock));
2117            fprintf('   *************************************************************\n');
2118            fprintf('   **  Orbit Feedback could not start due to error condition  **\n');
2119            fprintf('   *************************************************************\n\n');
2120
2121            set(0,'showhiddenhandles','off');
2122            pause(0);
2123            return
2124        end
2125
2126        pause(0.5)
2127        set(findobj(gcbf,'Tag','FOFBguiTangoCheckboxRF'), 'value',readattribute([devRFFBManager, '/isRunning']));
2128
2129        % Disable buttons in GUI
2130        set(0,'showhiddenhandles','on');
2131        %set(findobj(gcbf,'Tag','FOFBguiTangoCheckboxDCRF'),'Enable','off');
2132        %set(findobj(gcbf,'Tag','FOFBguiTangoPushbuttonStartRFFB'),'Enable','off');
2133        %set(findobj(gcbf,'Tag','FOFBguiTangoPushbuttonStopRFFB'),'Enable','on');
2134        set(findobj(gcbf,'Tag','FOFBguiTangoButtonOrbitCorrection'),'Enable','off');
2135        set(findobj(gcbf,'Tag','FOFBguiTangoButtonOrbitCorrectionSetupFOFB'),'Enable','on');
2136        set(findobj(gcbf,'Tag','FOFBguiTangoButtonFeedbackSetup'),'Enable','off');
2137        %set(findobj(gcbf,'Tag','FOFBguiTangoClose'),'Enable','off');
2138        set(findobj(gcbf,'Tag','FOFBguiTangoCheckboxHSOFB'),'Enable','off');
2139        set(findobj(gcbf,'Tag','FOFBguiTangoCheckboxVSOFB'),'Enable','off');
2140        set(findobj(gcbf,'Tag','FOFBguiTangoCheckboxHcorrection'),'Enable','off');
2141        set(findobj(gcbf,'Tag','FOFBguiTangoCheckboxVcorrection'),'Enable','off');
2142        set(findobj(gcbf,'Tag','FOFBguiTangoCheckboxRF'),'Enable','off');
2143        set(findobj(gcbf,'Tag','FOFBguiTangoCheckboxSOFB'),'Enable','off')
2144        set(findobj(gcbf,'Tag','FOFBguiTangoCheckboxFOFB'),'Enable','off')
2145        set(findobj(gcbf,'Tag','FOFBguiTangoButtonConvertMatrix4FPGA'),'Enable','off');
2146        %set(findobj(gcbf,'Tag','FOFBguiTangoPushbuttonStartDC'),'Enable','off');
2147        pause(0);
2148        FOFBguiTango('UpdateStatusFOFB');
2149
2150%%  STOPRFFOFB     
2151    case 'STOPRFFOFB'
2152
2153        isRunning = readattribute([devRFFBManager '/isRunning']);
2154        if ~isRunning
2155            fprintf(' Error: RFFB already stopped! \n')
2156            return;
2157        end
2158
2159        button=questdlg('Voulez-vous vraiment arreter le RFFB? ','Attention','Confirmer','Annuler','Annuler');
2160
2161        switch button
2162            case'Confirmer'
2163                statusValue = readattribute([devRFFBManager '/State']);
2164                if statusValue == 12 || statusValue == 10
2165
2166                    tango_command_inout2(devRFFBManager,'Stop');
2167
2168                    pause(0.5);
2169
2170                    isRunning = readattribute([devRFFBManager '/isRunning']);
2171
2172                    if isRunning
2173                        fprintf(' Error impossible to stop  RFFB! \n')
2174                    end
2175                else
2176                    fprintf(' Error, impossible to stop RFFB. Is it running? \n');
2177                    return;
2178                end
2179
2180                pause(0.5)
2181                set(findobj(gcbf,'Tag','FOFBguiTangoCheckboxRF'), 'value',readattribute([devRFFBManager, '/isRunning']));
2182
2183                % Disable buttons in GUI
2184                set(0,'showhiddenhandles','on');
2185                set(findobj(gcbf,'Tag','FOFBguiTangoCheckboxDCRF'),'Enable','off');
2186                %set(findobj(gcbf,'Tag','FOFBguiTangoPushbuttonStartRFFB'),'Enable','on');
2187                %set(findobj(gcbf,'Tag','FOFBguiTangoPushbuttonStopRFFB'),'Enable','off');
2188                set(findobj(gcbf,'Tag','FOFBguiTangoButtonOrbitCorrection'),'Enable','on');
2189                set(findobj(gcbf,'Tag','FOFBguiTangoButtonOrbitCorrectionSetupFOFB'),'Enable','on');
2190                set(findobj(gcbf,'Tag','FOFBguiTangoButtonFeedbackSetup'),'Enable','on');
2191                %set(findobj(gcbf,'Tag','FOFBguiTangoClose'),'Enable','on');
2192                set(findobj(gcbf,'Tag','FOFBguiTangoCheckboxHSOFB'),'Enable','on');
2193                set(findobj(gcbf,'Tag','FOFBguiTangoCheckboxVSOFB'),'Enable','on');
2194                set(findobj(gcbf,'Tag','FOFBguiTangoCheckboxHcorrection'),'Enable','on');
2195                set(findobj(gcbf,'Tag','FOFBguiTangoCheckboxVcorrection'),'Enable','on');
2196                set(findobj(gcbf,'Tag','FOFBguiTangoCheckboxRF'),'Enable','on');
2197                set(findobj(gcbf,'Tag','FOFBguiTangoCheckboxSOFB'),'Enable','on')
2198                set(findobj(gcbf,'Tag','FOFBguiTangoCheckboxFOFB'),'Enable','on')
2199                set(findobj(gcbf,'Tag','FOFBguiTangoButtonConvertMatrix4FPGA'),'Enable','on');
2200                set(findobj(gcbf,'Tag','FOFBguiTangoPushbuttonStartDC'),'Enable','on');
2201
2202            otherwise
2203                fprintf('Aborting STOPRFFOFB\n');
2204        end
2205        FOFBguiTango('UpdateStatusFOFB');
2206       
2207%% ZeroingFHCOR       
2208    case 'ZeroingFHCOR'
2209
2210        %check FOFB OFF and RFFB OFF
2211        isRFRunning = readattribute([devRFFBManager, '/isRunning']);
2212        isxFOFBRunning = readattribute([devFOFBManager, '/xFofbRunning']);
2213        iszFOFBRunning = readattribute([devFOFBManager, '/zFofbRunning']);
2214
2215        if isRFRunning
2216            fprintf('RFFB is running stop it first! \n');
2217            return;
2218        end
2219       
2220        if isxFOFBRunning
2221            fprintf('FOFB for H-plane is running. Stop it first! \n');
2222            return;
2223        end
2224
2225        if iszFOFBRunning
2226            fprintf('FOFB for V-plane is running. Stop it first! \n');
2227            return;
2228        end
2229
2230        isSOFBRunning = readattribute([devLockName, '/sofb']);
2231        if ~isSOFBRunning
2232            fprintf('SOFB is not running. Start it first! \n');
2233            return;
2234        end
2235
2236        %everything is OKh
2237       
2238        button=questdlg('!!!Attention!!!! Les correcteurs HFCOR vont etre forcés à Zéro par étapes. Voulez-vous continuer? ','Attention','Continuer','Annuler','Annuler');
2239
2240        switch button
2241            case 'Continuer'
2242                hfcm2zero
2243            otherwise
2244                fprintf('Zeroing HFCOR aborted\n')
2245        end
2246
2247%% ZeroingFVCOR
2248    case 'ZeroingFVCOR'
2249
2250        %check FOFB OFF and RFFB OFF
2251        isRFRunning = readattribute([devRFFBManager, '/isRunning']);
2252        isxFOFBRunning = readattribute([devFOFBManager, '/xFofbRunning']);
2253        iszFOFBRunning = readattribute([devFOFBManager, '/zFofbRunning']);
2254
2255        if isRFRunning
2256            fprintf('RFFB is running stop it first! \n');
2257            return;
2258        end
2259       
2260        if isxFOFBRunning
2261            fprintf('FOFB for H-plane is running. Stop it first! \n');
2262            return;
2263        end
2264
2265        if iszFOFBRunning
2266            fprintf('FOFB for V-plane is running. Stop it first! \n');
2267            return;
2268        end
2269
2270        isSOFBRunning = readattribute([devLockName, '/sofb']);
2271        if ~isSOFBRunning
2272            fprintf('SOFB is not running. Start it first! \n');
2273            return;
2274        end
2275
2276        %everything is OKh
2277       
2278        button=questdlg('!!!Attention!!!! Les correcteurs FVCOR vont etre forcés à Zéro par étapes. Voulez-vous continuer? ','Attention','Continuer','Annuler','Annuler');
2279
2280        switch button
2281            case 'Continuer'
2282                vfcm2zero
2283            otherwise
2284                fprintf('Zeroing HVCOR aborted\n')
2285        end
2286
2287%% TOGGLEHPLANEFOFB       
2288    case 'TOGGLEHPLANEFOFB'
2289        tango_write_attribute2(devFOFBManager,'applyCmdsToXPlane',uint8(get(findobj(gcbf,'Tag','FOFBguiTangoCheckboxHFOFB'),'Value')));
2290
2291%% TOGGLEVPLANEFOFB       
2292    case 'TOGGLEVPLANEFOFB'
2293        tango_write_attribute2(devFOFBManager,'applyCmdsToZPlane',uint8(get(findobj(gcbf,'Tag','FOFBguiTangoCheckboxVFOFB'),'Value')));
2294
2295%% StartFOFBConfig       
2296    case 'StartFOFBConfig'
2297        if get(findobj(gcbf,'Tag','FOFBguiTangoCheckboxHFOFB'),'value') || ...
2298                get(findobj(gcbf,'Tag','FOFBguiTangoCheckboxVFOFB'),'value')
2299
2300            button=questdlg('!!!Attention!!!! Les correcteurs vont etre forcés à Zéro pendant la phase d initialisation. Voulez-vous continuer? ','Attention','Continuer','Annuler','Annuler');
2301
2302            switch button
2303                case 'Continuer'
2304                    h=waitbar(0,'Initialisation en cours...');
2305
2306                % Reset Errors
2307                tango_command_inout2(devFOFBManager,'AcknowledgeError');
2308
2309                % Force reading of all BPMs to resfresh TANGO connections (BUg in Matlab)
2310                FOFBstruct = get(findobj(gcbf,'Tag','FOFBguiTangoButtonOrbitCorrectionSetupFOFB'),'Userdata');
2311                getx(FOFBstruct.BPMlist);
2312                pause(0.5);
2313             
2314                GoldenOrbitFlag = 0;
2315                if GoldenOrbitFlag % correction around FOFB golden orbit
2316                    A = load([getfamilydata('Directory' , 'OpsData') 'fofb_golden.mat']);
2317                else % Correction around current orbit
2318                    %get current orbit as reference
2319                    % Change all BPM in the loop                   
2320                    BPMxIdx = findrowindex(FOFBstruct.BPMlist, BPMxfullList);
2321
2322                    % Get Golden data for BPM with 0 status
2323                    %A = load([getfamilydata('Directory' , 'OpsData') 'fofb_golden.mat']);
2324                    % Offsets from FA and SA sources
2325                    % OffsetSA_FA = load([getfamilydata('Directory' , 'OpsBPMData') 'offsetSA_FA_golden.mat']);
2326                    %OffsetSA_FA = load('/home/operateur/GrpDiagnostics/matlab/FOFB/GUI/golden/offsetSA_FA_02_fevrier_09.mat');
2327                    % Update data for Status 1 BPMs
2328                    % 21 November 2009 Offsets disappeared !!!!
2329                    %OffsetSA_FA.X_offset = OffsetSA_FA.X_offset*0;
2330                    %OffsetSA_FA.Z_offset = OffsetSA_FA.Z_offset*0;
2331                    %A.new_goldenX(BPMxIdx) = (getx(FOFBstruct.BPMlist) - OffsetSA_FA.X_offset(BPMxIdx))*1e6;
2332                    %A.new_goldenZ(BPMxIdx) = (getz(FOFBstruct.BPMlist) - OffsetSA_FA.Z_offset(BPMxIdx))*1e6;
2333                   
2334                    A.new_goldenX = zeros(1,size(family2status('BPMx'),1));
2335                    A.new_goldenZ = A.new_goldenX;
2336                   
2337                    A.new_goldenX(BPMxIdx) = getx(FOFBstruct.BPMlist)*1e6;
2338                    A.new_goldenZ(BPMxIdx) = getz(FOFBstruct.BPMlist)*1e6;
2339                   
2340                    if any(isnan(A.new_goldenX(BPMxIdx))) || any(isnan(A.new_goldenZ(BPMxIdx)))
2341                        fprintf('Error in StartFOFBConfig: at least one BPM is a NaN\n');
2342                        fprintf('Error in StartFOFBConfig: Try again Start+Config\n');
2343                        return;
2344                    end
2345                   
2346                end
2347                B = load([getfamilydata('Directory' , 'OpsData') fileName]);
2348
2349                % set FOFB gain
2350               
2351                % gain is now edited in edit menu
2352                gainX = FOFBstruct.Xgain; 
2353                gainZ = FOFBstruct.Ygain;
2354   
2355                % gain for nominal operation
2356                %gainX = 90; % ajusted for 45 vp for H-plane
2357                %gainZ = 90; % ajusted for 44 vp for V-plane
2358               
2359                %test
2360                %gainX=80; % 41 vp for H-plane
2361                %gainZ=70; % 40 vp for V-plane
2362               
2363                % Low alpha sur 25
2364                %gainX = 30; % ajusted for 45 vp for H-plane in Low Alpha mode
2365                %gainZ = 65; % ajusted for 44 vp for V-plane in Low Alpha mode
2366               
2367               
2368                coeff = 1.77*1717.412;
2369               
2370                % build response matrix
2371                B.matrixX = -(B.matrixX.*coeff*gainX);
2372                B.matrixZ = -(B.matrixZ.*coeff*gainZ);
2373
2374                % Load configuration FOFBmanager
2375                % Load orbit
2376                tango_write_attribute2(devFOFBManager,'xRefOrbit',A.new_goldenX*1e-6);
2377                tango_write_attribute2(devFOFBManager,'zRefOrbit',A.new_goldenZ*1e-6);
2378
2379                % Load response matrices
2380                tango_write_attribute2(devFOFBManager,'xInvRespMatrix',B.matrixX);
2381                tango_write_attribute2(devFOFBManager,'zInvRespMatrix',B.matrixZ);
2382                pause(2)
2383
2384                % Load configuration on FPGA
2385                tango_command_inout2(devFOFBManager,'StartStep04LoadXRefOrbit');
2386                tango_command_inout2(devFOFBManager,'StartStep05LoadZRefOrbit');
2387                tango_command_inout2(devFOFBManager,'StartStep06LoadXInvRespMatrix');
2388                tango_command_inout2(devFOFBManager,'StartStep07LoadZInvRespMatrix');
2389
2390                pause(10)
2391
2392                tango_command_inout2(devFOFBManager,'ColdStart');
2393                pause(3)
2394                state_fofb_manager = tango_read_attribute(devFOFBManager,'State');
2395                if state_fofb_manager.value~=6
2396                    warndlg('StartFOFBConfig: L ''initialisation n''a pas pu demarrer. Verifier Defauts')
2397                else
2398                    i=0;
2399                    while state_fofb_manager.value == 6
2400                        state_fofb_manager = tango_read_attribute(devFOFBManager,'State');
2401                        i=i+1;
2402                        waitbar(i/50)
2403                        pause(1)
2404                    end
2405                    close(h)
2406                end
2407            otherwise
2408                fprintf('Error in StartFOFBConfig\n');
2409            end
2410
2411            FOFBguiTango('UpdateStatusFOFB');
2412       
2413        else
2414            warndlg('Aborting StartFOFBConfig: select a plane first')
2415        end
2416
2417%% StartFOFB
2418    case 'StartFOFB'
2419       
2420        % Check if FOFB is well configured
2421        rep = tango_read_attributes2(devFOFBManager, ...
2422            {'xInvRespMatrixLoadedOnBpms', 'zInvRespMatrixLoadedOnBpms', ...
2423            'xInvRespMatrixLoadedOnDevice', 'zInvRespMatrixLoadedOnDevice', ...
2424            'xRefOrbitLoadedOnBpms', 'zRefOrbitLoadedOnBpms' ...
2425            'xRefOrbitLoadedOnDevice', 'zRefOrbitLoadedOnDevice'});
2426
2427        isum = sum([rep.value]);
2428
2429        if isum ~= size(rep,2)
2430            warndlg('FOFB not configured anymore. Use START FOFB+Config');
2431            return;
2432        end
2433       
2434        if get(findobj(gcbf,'Tag','FOFBguiTangoCheckboxHFOFB'),'value') || ...
2435                get(findobj(gcbf,'Tag','FOFBguiTangoCheckboxVFOFB'),'value')
2436            button = questdlg('!!!Attention!!!! Le Feedback doit etre initialisé pour effectuer cette commande. Voulez-vous continuer? ', ...
2437                'Attention','Continuer','Annuler','Annuler');
2438            switch button
2439                case'Continuer'
2440                    % Reset Errors
2441                    tango_command_inout2(devFOFBManager,'AcknowledgeError');
2442                    pause(0.5);
2443                    % Start feedback
2444                    tango_command_inout2(devFOFBManager,'HotStart')
2445                otherwise
2446                    warndlg('Aborting StartFOFB');
2447            end
2448        else
2449            warndlg('Aborting RestartFOFB: select a plane first')
2450        end
2451        FOFBguiTango('UpdateStatusFOFB');
2452
2453%% StopFOFB2Zero       
2454    case 'StopFOFB2Zero'
2455        if get(findobj(gcbf,'Tag','FOFBguiTangoCheckboxHFOFB'),'value') || ...
2456                get(findobj(gcbf,'Tag','FOFBguiTangoCheckboxVFOFB'),'value')
2457
2458            button=questdlg('Voulez-vous vraiment arreter le FOFB en remettant à Zéro les correcteurs? ',...
2459                'Attention','Confirmer','Annuler','Annuler');
2460            switch button
2461                case'Confirmer'
2462                    %devFOFBManager='ANS/DG/FOFB-MANAGER';
2463                    tango_command_inout2(devFOFBManager,'StopToZero');
2464                    if get(findobj(gcbf,'Tag','FOFBguiTangoCheckboxHFOFB'),'value')
2465                        %tango_command_inout2(devFOFBManager,'StopStep01StopXFOFBToZero');
2466                        fprintf('   *************************************************************\n');
2467                        fprintf('   **          FOFB stopped to zeros in H-plane               **\n');
2468                        fprintf('   *************************************************************\n\n');
2469                        fprintf('   %s \n', datestr(clock));
2470
2471                    end
2472                    if get(findobj(gcbf,'Tag','FOFBguiTangoCheckboxVFOFB'),'value')
2473                        %tango_command_inout2(devFOFBManager,'StopStep02StopZFOFBToZero');
2474                        fprintf('   *************************************************************\n');
2475                        fprintf('   **          FOFB stopped to zeros  in V-plane              **\n');
2476                        fprintf('   *************************************************************\n\n');
2477                        fprintf('   %s \n', datestr(clock));
2478                    end
2479
2480                otherwise
2481                    fprintf('Aborting StopFOFB2Zero\n');
2482            end
2483        else
2484            warndlg('Aborting StopFOFB2Zero: select a plane first')
2485        end
2486        FOFBguiTango('UpdateStatusFOFB');
2487
2488
2489%% StopFOFB2CurrentValues     
2490    case 'StopFOFB2CurrentValues'
2491        if get(findobj(gcbf,'Tag','FOFBguiTangoCheckboxHFOFB'),'value') || ...
2492                get(findobj(gcbf,'Tag','FOFBguiTangoCheckboxVFOFB'),'value')
2493
2494            button=questdlg('Voulez-vous vraiment arreter le FOFB sur la valeur courante des correcteurs? ',...
2495                'Attention','Confirmer','Annuler','Annuler');
2496            switch button
2497                case'Confirmer'
2498                    tango_command_inout2(devFOFBManager,'Stop');
2499                    if get(findobj(gcbf,'Tag','FOFBguiTangoCheckboxHFOFB'),'value')
2500                        fprintf('   *************************************************************\n');
2501                        fprintf('   **          FOFB stopped to current values in H-plane      **\n');
2502                        fprintf('   *************************************************************\n\n');
2503                        fprintf('   %s \n', datestr(clock));
2504                    end
2505                    if get(findobj(gcbf,'Tag','FOFBguiTangoCheckboxVFOFB'),'value')
2506                        fprintf('   *************************************************************\n');
2507                        fprintf('   **          FOFB stopped to current values in V-plane      **\n');
2508                        fprintf('   *************************************************************\n\n');
2509                        fprintf('   %s \n', datestr(clock));
2510                    end
2511
2512                otherwise
2513                    fprintf('Aborting StopFOFB2CurrentValues\n');
2514            end
2515        else
2516            warndlg('Aborting StopFOFB2CurrentValues: select a plane first')
2517        end
2518        FOFBguiTango('UpdateStatusFOFB');
2519
2520%% ConvertMatrix4FPGA       
2521    case 'ConvertMatrix4FPGA'
2522
2523        % Flag for RF correction done by fast horizontal steerers
2524        RFIncludedInCORFlag = 1;
2525       
2526        % CONVERTMATRIX4FPGA - FPGA requires always 120x48 matrices whatever the numbers of BPM or corrector are
2527
2528        % get Feedback struture
2529        FBstruct = get(findobj(gcbf,'Tag','FOFBguiTangoButtonOrbitCorrectionSetupFOFB'),'Userdata');
2530
2531        Sh = getrespmat(BPMxFamily, FBstruct.BPMlist, HCMFamily, FBstruct.HCMlist, [], SR_GEV);
2532        Sv = getrespmat(BPMyFamily, FBstruct.BPMlist, VCMFamily, FBstruct.VCMlist, [], SR_GEV);
2533
2534        % H-plane
2535
2536        %compute matrix for valid BPM & correctors
2537
2538        Smat = Sh;
2539
2540        if ~RFIncludedInCORFlag
2541            Eta = getdisp(BPMxFamily, FBstruct.BPMlist); % todo: to be stored in application
2542            RFWeight = 10 * mean(std(Smat)) / std(Eta);
2543            Smat = [Smat RFWeight*Eta];
2544        end
2545
2546        % compute SVD
2547        [U, S, V] = svd(Smat, 0);  %'econ');
2548        S = diag(S);
2549
2550        %% Number of singular values
2551        SVDIndex = FBstruct.OCSx.SVDIndex;
2552        RinvH = V(:,SVDIndex)*diag(S(SVDIndex).^(-1))*U(:,SVDIndex)';
2553
2554        fprintf('Horizontal singular value number %d\n', SVDIndex(end));
2555
2556        %deltacm = RinvH*deltaXOrbit';
2557        %deltacm(end)*RFWeight
2558
2559        %build matrix for FPGA
2560        RinvHfull=zeros(nHCM,nBPMx);
2561
2562        % look for index of valid BPM and correctors
2563        HCMIdx  = findrowindex(FBstruct.HCMlist, HCMfullList);
2564        BPMxIdx = findrowindex(FBstruct.OCSx.BPM.DeviceList, BPMxfullList);
2565        %HCMIdx = [HCMIdx(2:end); HCMIdx(1)];
2566        %BPMxIdx = [BPMxIdx(2:end); BPMxIdx(1)];
2567
2568        % Remove RF part: last element of RinvH
2569        % Put zero where BPM and correctors are not taken into account
2570
2571        if ~RFIncludedInCORFlag
2572            RinvHfull(HCMIdx, BPMxIdx) = RinvH(1:end-1,:);
2573        else
2574            RinvHfull(HCMIdx, BPMxIdx) = RinvH(:,:);
2575        end
2576
2577        % V-plane
2578
2579        %compute matrix for valid BPMs & correctors
2580        Smat =  Sv;
2581
2582        % compute SVD
2583        [U, S, V] = svd(Smat, 0);  %'econ');
2584        S = diag(S);
2585
2586        %% Number of singular values
2587        SVDIndex = FBstruct.OCSy.SVDIndex;
2588        RinvV = V(:,SVDIndex)*diag(S(SVDIndex).^(-1))*U(:,SVDIndex)';
2589
2590        fprintf('Vertical singular value number %d\n', SVDIndex(end));
2591        %deltacm = RinvV*deltaXOrbit';
2592
2593        %build matrix for FPGA
2594        RinvVfull=zeros(nVCM,nBPMy);
2595
2596        % look for index of valid BPM and correctors
2597        VCMIdx = findrowindex(FBstruct.VCMlist, VCMfullList);
2598        BPMyIdx = findrowindex(FBstruct.OCSy.BPM.DeviceList, BPMyfullList);
2599
2600        %VCMIdx = [VCMIdx(2:end); VCMIdx(1)];
2601        %BPMyIdx = [BPMyIdx(2:end); BPMyIdx(1)];
2602
2603        % Put zero where BPM and correctors are not taken into account
2604        RinvVfull(VCMIdx, BPMyIdx) = RinvV(:,:);
2605
2606        fprintf('Matrices computed successfully')
2607
2608        % save data into a file
2609        dirName = getfamilydata('Directory' , 'OpsData');
2610        matrixX = RinvHfull;
2611        matrixZ = RinvVfull;
2612
2613        %fileName = 'matrix4FOFB';
2614        % Confirmation dialogbox
2615        StartFlag = questdlg('Save new Response matrix for FOFB? To apply your modifications, choose yes and do START+CONFIG at next FOFB start', 'Response matrix generation','Yes','No','No');
2616
2617        % Diag for Laurent
2618        if 0
2619            figure;
2620            mesh(matrixX)
2621            title('Horizontal Inverse Response Matrix')
2622
2623            figure;
2624            mesh(matrixZ)
2625            title('Vertical Inverse Response Matrix')
2626        end
2627
2628        if strcmp(StartFlag,'No')
2629            fprintf('   %s \n', datestr(clock));
2630            fprintf('   ***************************\n');
2631            fprintf('   **  No Data Saved         **\n');
2632            fprintf('   ***************************\n\n');
2633            pause(0);
2634            return
2635        end
2636
2637        save([dirName fileName], 'matrixX','matrixZ');
2638
2639        fprintf('   %s \n', datestr(clock));
2640        fprintf('   *************************************************\n');
2641        fprintf('   **  New Response matrix for FOFB Saved         **\n');
2642        fprintf('   ***********************************************\n\n');
2643       
2644        %% Configuration for BPM of the RF feedback
2645        FB = get(findobj(gcbf,'Tag','FOFBguiTangoButtonOrbitCorrectionSetupFOFB'),'Userdata');
2646        activeBPMs = zeros(1,size(family2dev('BPMx', 0),1));
2647        activeBPMs(dev2elem('BPMx', FB.BPMlist)) = 1;
2648        fprintf('Updating list of BPM for RFFB\n');
2649       
2650        %button=questdlg('Voulez-vous reconfigurer le FOFB et RFFB? ','Attention','Confirmer','Annuler','Annuler');
2651        % As RFFB is not used anymore, suppression of dialogbox. BPM list
2652        % always updated on RFFB dev. To be completly suppressed?
2653        button='Confirmer';
2654        switch button
2655            case'Confirmer'
2656                try
2657                    tango_write_attribute2(devRFFBManager,'activeBPM', int32(activeBPMs));
2658                    fprintf('Updating list of BPM done\n');
2659                catch
2660                    fprintf('\n  %s \n',lasterr);
2661                    fprintf('Error while updating list of BPM for RFFB\n');
2662                end
2663            otherwise
2664                fprintf('Configuration aborted\n')
2665        end
2666
2667        % save data for SOFB
2668        savaData2File;
2669       
2670
2671        FOFBMANAGERFLAG = 1;
2672        if FOFBMANAGERFLAG
2673            % get BPM list used in FOFB-Manager
2674            bpmdata  = tango_get_properties2(devFOFBManager, {'BPMList'});
2675
2676            % Configuration
2677            % H means H-plane only
2678            % V means V-plane only
2679            % B means both planes H and V (nominal config)
2680            % N means excluded for both planes, only survey on private network
2681            % O means out of order for both planes
2682
2683            % update all the list of BPM
2684            FullBPMDevList = family2dev('BPMx', 0);
2685
2686            %%WARNING may not work if added BPM
2687            % Idx = strfind(bpmdata.value, 'ANS-C01/DG/BPM.2')
2688            for ik = 1:size(FullBPMDevList,1),
2689                if bpmdata.value{ik}(end) ~= 'O'; % do nothing if out of order
2690                    if activeBPMs(ik)
2691                        bpmdata.value{ik}(end) = 'B';
2692                    else
2693                        bpmdata.value{ik}(end) = 'N'; % not more diagnostics on Orbit, BPM not used in correction
2694                        %bpmdata.value{ik}(end) = 'O'; % out of order by expectedbpm has to be changed
2695                        %ExpectedBpmCnt property has to be modified
2696                    end
2697                else
2698                    fprintf('Config not taken into account BPM(%2d, %2d) out of order\n ', FullBPMDevList(ik,:));
2699                end
2700            end
2701
2702            % set back BPM list used to FOFB-Manager
2703            tango_put_property2(devFOFBManager, 'BPMList', bpmdata.value);
2704
2705            % To be activated if out of Order Libera
2706            % rep = tango_get_properties2(devFOFBManager, {'ExpectedBpmCnt'});
2707            % val.value{1} = num2str(length(activeBPMs));
2708            % tango_put_property2(devFOFBManager, 'ExpectedBpmCnt', val.value);
2709
2710            % get H-corrector list used in FOFB-Manager
2711            HSteerer  = tango_get_properties2(devFOFBManager, {'HSteererList'});
2712           
2713            % Configuration
2714            % U means Up = OK
2715            % O means out of order for both planes
2716           
2717            for ik = 1:size(HCMfullList,1),
2718                if ~isempty(findrowindex(HCMfullList(ik,:),HCMfullList(HCMIdx,:)))
2719                    HSteerer.value{ik}(end) = 'U';
2720                else
2721                    HSteerer.value{ik}(end) = 'O'; % not more diagnostics on Orbit, BPM not used in correction
2722                end
2723            end
2724
2725            % set back HCOR list used to FOFB-Manager
2726            tango_put_property2(devFOFBManager, 'HSteererList', HSteerer.value);
2727
2728            % get V-corrector list used in FOFB-Manager
2729            VSteerer  = tango_get_properties2(devFOFBManager, {'VSteererList'});
2730           
2731            % Configuration
2732            % U means Up = OK
2733            % O means out of order for both planes
2734           
2735            for ik = 1:size(VCMfullList,1),
2736                if ~isempty(findrowindex(VCMfullList(ik,:),VCMfullList(VCMIdx,:)))
2737                    VSteerer.value{ik}(end) = 'U';
2738                else
2739                    VSteerer.value{ik}(end) = 'O'; % not more diagnotics on Orbit, BPM not used in correction
2740                end
2741            end
2742
2743            % set back VCOR list used to FOFB-Manager
2744            tango_put_property2(devFOFBManager, 'VSteererList', VSteerer.value);
2745
2746            % init on device to take into account the new property
2747            tango_command_inout2(devFOFBManager, 'Init');
2748        end
2749
2750%% StartDCFB
2751    case 'StartDCFB' %Retrieve DC part of fast correctors
2752
2753        FOFBguiTango('UpdateStatusFOFB');
2754       
2755        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2756        % H-plane: 1/ only corrector 2/ RF part
2757        % V-plane
2758        % Need to know configuration of the SOFB and of the FOFB
2759        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2760
2761        FBstruct = get(findobj(gcbf,'Tag','FOFBguiTangoButtonOrbitCorrectionSetupFOFB'),'Userdata');
2762
2763        Sh = getrespmat(BPMxFamily, FBstruct.BPMlist, HCMFamily, FBstruct.HCMlist, [], SR_GEV);
2764        Sv = getrespmat(BPMyFamily, FBstruct.BPMlist, VCMFamily, FBstruct.VCMlist, [], SR_GEV);
2765
2766        Eta = getdisp(BPMxFamily, FBstruct.BPMlist);
2767
2768        % reconstruct orbit
2769
2770        % Load current configuration data for FOFB from a file!
2771        DirName = getfamilydata('Directory', 'FOFBdata');
2772        tmp = load(fullfile(DirName, 'SOFBconfiguration'), 'FB');
2773        FB_SOFB = tmp.FB;
2774
2775        % Precompute matrices
2776
2777        %%%%%%%%%%%
2778        % H-plane %
2779        %%%%%%%%%%%
2780
2781        %compute matrix for valid BPM & correctors
2782
2783        Smat = Sh;
2784        RFWeight = 10 * mean(std(Smat)) / std(Eta);
2785        Smat = [Smat RFWeight*Eta];
2786
2787        % compute SVD
2788        [U, S, V] = svd(Smat, 0);  %'econ');
2789        S = diag(S);
2790
2791        % Number of singular values
2792        SVDIndex = FBstruct.OCSx.SVDIndex;
2793        RH = U(:,SVDIndex)*diag(S(SVDIndex))*V(:,SVDIndex)';
2794
2795        % retrieve H-plane response matrix with good BPM and correctors
2796        %SOFB_RMat = getrespmat(FB_SOFB.OCSx.BPM.FamilyName, FB_SOFB.OCSx.BPM.DeviceList, FB_SOFB.OCSx.CM.FamilyName, FB_SOFB.OCSx.CM.DeviceList, [], SR_GEV);
2797        %SOFB_Eta = getdisp(FB_SOFB.OCSx.BPM.FamilyName, FB_SOFB.OCSx.BPM.DeviceList);
2798        % Need to take BPM list from this program, i.e. FOFB.
2799        % TODO: may  not be OKay
2800        SOFB_RMat = getrespmat(FB_SOFB.OCSx.BPM.FamilyName, FBstruct.BPMlist, FB_SOFB.OCSx.CM.FamilyName, FB_SOFB.OCSx.CM.DeviceList, [], SR_GEV);
2801        SOFB_Eta  = getdisp(FB_SOFB.OCSx.BPM.FamilyName, FBstruct.BPMlist);
2802
2803        Smat = SOFB_RMat;
2804        RFWeight = 10* mean(std(Smat)) / std(SOFB_Eta); % TODO: global variable
2805        Smat = [Smat RFWeight*SOFB_Eta];
2806
2807        % Compute SVD and inverse matrix
2808        [SOFB_UH, SOFB_SH, SOFB_VH] = svd(Smat, 0);  %'econ');
2809        SOFB_SH = diag(SOFB_SH);
2810        SOFB_SVDIndexH = FB_SOFB.OCSx.SVDIndex;
2811        SOFB_RinvH = SOFB_VH(:,SOFB_SVDIndexH)*diag(SOFB_SH(SOFB_SVDIndexH).^(-1)) * SOFB_UH(:,SOFB_SVDIndexH)';
2812
2813        %%%%%%%%%%%
2814        % V-plane %
2815        %%%%%%%%%%%
2816        %compute matrix for valid BPM & correctors
2817
2818        Smat = Sv;
2819
2820        % compute SVD
2821        [U, S, V] = svd(Smat, 0);  %'econ');
2822        S = diag(S);
2823
2824        % Number of singular values
2825        SVDIndex = FBstruct.OCSy.SVDIndex;
2826        RV = U(:,SVDIndex)*diag(S(SVDIndex))*V(:,SVDIndex)';
2827
2828        % retrieve H-plane response matrix with good BPM and correctors
2829        % TODO flag saying data changed Then repcompute SVD and so on
2830        %SOFB_RMat = getrespmat(FB_SOFB.OCSy.BPM.FamilyName, FB_SOFB.OCSy.BPM.DeviceList, FB_SOFB.OCSy.CM.FamilyName, FB_SOFB.OCSy.CM.DeviceList, [], SR_GEV);
2831        SOFB_RMat = getrespmat(FB_SOFB.OCSy.BPM.FamilyName, FBstruct.BPMlist, FB_SOFB.OCSy.CM.FamilyName, FB_SOFB.OCSy.CM.DeviceList, [], SR_GEV);
2832
2833        [SOFB_UV, SOFB_SV, SOFB_VV] = svd(SOFB_RMat, 0);  %'econ');
2834        SOFB_SV = diag(SOFB_SV);
2835        SOFB_SVDIndexV=FB_SOFB.OCSy.SVDIndex;
2836        %N_VCM=length(SOFB_SVDIndexV);
2837        SOFB_RinvV = SOFB_VV(:,SOFB_SVDIndexV)*diag(SOFB_SV(SOFB_SVDIndexV).^(-1))*SOFB_UV(:,SOFB_SVDIndexV)';
2838
2839        %%%%%%%%%%%%%%%%%%%%%%%%%%
2840        % ORBIT DC FEEDBACK part %
2841        %%%%%%%%%%%%%%%%%%%%%%%%%%
2842
2843        %FBloopIter = 3; % number of iterations for each loop
2844
2845        DC_FEEDBACK_STOP_FLAG = 0;
2846
2847        % Warning Flag for stale correctors
2848        HWarnNum = 0;
2849        VWarnNum = 0;
2850
2851        % Feedback loop setup
2852        LoopDelay = 10.0;    % Period of Feedback loop [seconds], make sure the BPM averaging is correct
2853
2854        % Percentage of correction to apply at each iteration
2855        Xgain  = 1.0;
2856        Ygain  = 1.0;
2857
2858        % Maximum allowed frequency shift during a single correction
2859        deltaRFmax = 10e-6; % MHz
2860        deltaRFmin = 0.3e-6; % MHz ie 0.1 Hz
2861
2862        % Load lattice set for tune feed forward
2863
2864        set(0,'showhiddenhandles','on');
2865
2866        try
2867
2868            %setup average data for reading BPMs
2869            setfamilydata('gethbpmaverage','BPMx','Monitor', 'SpecialFunctionGet')
2870            setfamilydata('getvbpmaverage','BPMz','Monitor', 'SpecialFunctionGet')
2871
2872            fprintf('\n');
2873            fprintf('   *******************************\n');
2874            fprintf('   **  Starting DC Orbit Feedback  **\n');
2875            fprintf('   *******************************\n');
2876            fprintf('   %s \n', datestr(clock));
2877            fprintf('   Note: the Matlab command window will be used to display status information.\n');
2878            fprintf('         It cannot be used to enter commands during slow orbit DC Feedback.\n');
2879
2880            % Get FOFB Structure
2881            %FB = get(findobj(gcbf,'Tag','FOFBguiTangoButtonFeedbackSetup'),'Userdata');
2882            FB = get(findobj(gcbf,'Tag','FOFBguiTangoButtonOrbitCorrectionSetupFOFB'),'Userdata');
2883            if get(findobj(gcbf,'Tag','FOFBguiTangoCheckboxDCRF'),'Value') == 1
2884                FB.OCSx.FitRF = 1;
2885            else
2886                FB.OCSx.FitRF = 0;
2887            end
2888
2889            % look for already running FOFB
2890            check4DCfeedbackflag(devLockName);
2891        catch
2892            fprintf('\n  %s \n',lasterr);
2893            fprintf('   %s \n', datestr(clock));
2894            fprintf('   *************************************************************\n');
2895            fprintf('   **  Orbit DC Feedback could not start due to error condition  **\n');
2896            fprintf('   *************************************************************\n\n');
2897            set(0,'showhiddenhandles','off');
2898            pause(0);
2899            return
2900        end
2901
2902        % Confirmation dialogbox
2903        StartFlag = questdlg('Start orbit DC Feedback?', 'Orbit DC Feedback','Yes','No','No');
2904        set(findobj(gcbf,'Tag','FOFBguiTangoStaticTextInformation'),'String','DC FB Started');
2905
2906        if strcmp(StartFlag,'No')
2907            fprintf('   %s \n', datestr(clock));
2908            fprintf('   ***************************\n');
2909            fprintf('   **  Orbit DC Feedback Exit  **\n');
2910            fprintf('   ***************************\n\n');
2911            pause(0);
2912            return
2913        end
2914
2915        set(0,'showhiddenhandles','on');
2916
2917        % Display information
2918
2919        if get(findobj(gcbf,'Tag','FOFBguiTangoCheckboxHFOFB'),'Value') == 1
2920            fprintf('   Using %d singular values horizontally.\n', length(FB.Xivec));
2921        end
2922        if get(findobj(gcbf,'Tag','FOFBguiTangoCheckboxVFOFB'),'Value') == 1
2923            fprintf('   Using %d singular values vertically.\n',   length(FB.Yivec));
2924        end
2925        fprintf('   Starting FOFB DC correction every %.1f seconds.\n', LoopDelay);
2926
2927        try
2928            % Compute residual closed orbit
2929            %x = FB.Xgoal - getx(FB.BPMlist);
2930            %y = FB.Ygoal - getz(FB.BPMlist);
2931
2932            %STDx = norm(x)/sqrt(length(x));
2933            %STDy = norm(y)/sqrt(length(y));
2934            %STDx = std(x);
2935            %STDy = std(y);
2936
2937            %set(findobj(gcbf,'Tag','FOFBguiTangoStaticTextHorizontal'),'String', ...
2938            %    sprintf('Horizontal RMS = %.4f mm',STDx),'ForegroundColor',[0 0 0]);
2939            %set(findobj(gcbf,'Tag','FOFBguiTangoStaticTextVertical'),'String', ...
2940            %    sprintf('Vertical RMS = %.4f mm',STDy),'ForegroundColor',[0 0 0]);
2941
2942            if strcmp(getmode('BPMx'),'Online') && strcmp(getmode('BPMz'),'Online')
2943                % Lock FOFB FB service
2944                Locktag  = tango_command_inout2(devLockName,'Lock', 'dcfb');
2945            end
2946            pause(0);
2947        catch
2948
2949            fprintf('\n  %s \n',lasterr);
2950
2951            fprintf('   %s \n', datestr(clock));
2952            fprintf('   *************************************************************\n');
2953            fprintf('   **  Orbit DC Feedback could not start due to error condition  **\n');
2954            fprintf('   *************************************************************\n\n');
2955
2956            set(0,'showhiddenhandles','off');
2957            pause(0);
2958            return
2959        end
2960
2961
2962        % Disable buttons in GUI
2963        set(0,'showhiddenhandles','on');
2964        set(findobj(gcbf,'Tag','FOFBguiTangoPushbuttonStartDC'),'Enable','off');
2965        set(findobj(gcbf,'Tag','FOFBguiTangoPushbuttonStopDC'),'Enable','on');
2966        set(findobj(gcbf,'Tag','FOFBguiTangoButtonOrbitCorrection'),'Enable','off');
2967        set(findobj(gcbf,'Tag','FOFBguiTangoButtonOrbitCorrectionSetupFOFB'),'Enable','off');
2968        set(findobj(gcbf,'Tag','FOFBguiTangoButtonFeedbackSetup'),'Enable','off');
2969        set(findobj(gcbf,'Tag','FOFBguiTangoClose'),'Enable','off');
2970        set(findobj(gcbf,'Tag','FOFBguiTangoCheckboxHSOFB'),'Enable','off');
2971        set(findobj(gcbf,'Tag','FOFBguiTangoCheckboxVSOFB'),'Enable','off');
2972        set(findobj(gcbf,'Tag','FOFBguiTangoCheckboxHcorrection'),'Enable','off');
2973        set(findobj(gcbf,'Tag','FOFBguiTangoCheckboxVcorrection'),'Enable','off');
2974        set(findobj(gcbf,'Tag','FOFBguiTangoCheckboxRF'),'Enable','off');
2975        set(findobj(gcbf,'TdevSpeakerNameag','FOFBguiTangoCheckboxSOFB'),'Enable','off')
2976        set(findobj(gcbf,'Tag','FOFBguiTangoCheckboxFOFB'),'Enable','off')
2977        set(findobj(gcbf,'Tag','FOFBguiTangoButtonConvertMatrix4FPGA'),'Enable','off');
2978        %set(findobj(gcbf,'Tag','FOFBguiTangoPushbuttonStart'),'Enable','off');
2979        pause(0);
2980
2981
2982        % Initialize Feedback loop
2983        %StartTime = gettime;
2984        %StartErrorTime = gettime;
2985
2986        % Get orbit before FOFB startup
2987        %Xold = getx(FB.BPMlist);
2988        %Yold = getz(FB.BPMlist);
2989        % Stale number
2990        RF_frequency_stalenum = 0;
2991        %pause(LoopDelay);
2992
2993        % Number of steerer magnet corrector
2994        N_HCM = size(FB_SOFB.OCSx.CM.DeviceList,1);
2995        N_VCM = size(FB_SOFB.OCSy.CM.DeviceList,1);
2996
2997        % thresholds for multibunch filling pattern
2998        dhcmStd = 0.0002;
2999        dvcmStd = 0.0002;
3000       
3001        % Number of RF actuator
3002        N_RFMO = 1;
3003
3004        % Maximum current modification in correction for one iteration of  DC feedback
3005        HDCMAX = 0.1; %A in H-plane
3006        VDCMAX = 0.1; %A in V-plane
3007
3008        %%%%%%%%%%%%%%%%%%%%%%%%%%
3009        % Start DC Feedback loop %
3010        %%%%%%%%%%%%%%%%%%%%%%%%%%
3011
3012        setappdata(findobj(gcbf,'Tag','FOFBguiTangoFig1'),'DC_FEEDBACK_STOP_FLAG',0);
3013
3014        while DC_FEEDBACK_STOP_FLAG == 0 % infinite loop
3015            try
3016                t00 = gettime;
3017                fprintf('Iteration time %s\n',datestr(clock));
3018
3019                % Check if GUI has been closed
3020                if isempty(gcbf)
3021                    DC_FEEDBACK_STOP_FLAG = 1;
3022                    lasterr('FOFBguiTango GUI DISAPPEARED!');
3023                    error('FOFBguiTango GUI DISAPPEARED!');
3024                end
3025
3026                isxFOFBRunning = readattribute([devFOFBManager, '/xFofbRunning']);
3027                iszFOFBRunning = readattribute([devFOFBManager, '/zFofbRunning']);
3028                FOFBManagerState = readattribute([devFOFBManager, '/State']);
3029               
3030                %isRunningFOFB = readattribute([devLockName '/fofb']);
3031
3032                if (get(findobj(gcbf,'Tag','FOFBguiTangoCheckboxHDCFB'),'Value') == 1 && ~isxFOFBRunning)  || FOFBManagerState ~= 0
3033                    DC_FEEDBACK_STOP_FLAG = 1;
3034                    fprintf('\n %s Arret: Programme FOFB is stopped in H-plane. Restart it first!\n\n', datestr(clock));
3035                    strgMessage = 'Arret de la compensation des correcteurs. Vairifier FOFB';
3036                    tango_giveInformationMessage(devSpeakerName,  strgMessage);
3037                    break;
3038                end
3039               
3040                if (get(findobj(gcbf,'Tag','FOFBguiTangoCheckboxVDCFB'),'Value') == 1 && ~iszFOFBRunning) || FOFBManagerState ~= 0
3041                    DC_FEEDBACK_STOP_FLAG = 1;
3042                    fprintf('\n %s Arret: Programme FOFB is stopped in H-plane. Restart it first!\n\n', datestr(clock));
3043                    strgMessage = 'Arret de la compensation des correcteurs. Vérifier FOFB';
3044                    tango_giveInformationMessage(devSpeakerName,  strgMessage);
3045                    break;
3046                end
3047
3048                %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3049                % Horizontal plane DC Feedback %
3050                %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3051
3052                % Get orbit and check that the BPMs are different from the last update
3053                %Xnew = getx(FB.BPMlist);
3054
3055%                 if any(isnan(Xnew))
3056%                     DC_FEEDBACK_STOP_FLAG = 1;
3057%                     fprintf('%s         Orbit DC Feedback stopped due to bad BPMs\n',datestr(now));
3058%                     BadBPMName = family2tangodev(BPMxFamily, FB.BPMlist(isnan(Xnew),:));
3059%                     for k=1:size(BadBPMName,1),
3060%                         fprintf('Bad Horizontal BPM %s\n',BadBPMName{k});
3061%                     end
3062%                     tango_command_inout2(devSpeakerName,'DevTalk','Arret de la correction d''orbite : problÚme BPM');
3063%                     warndlg('Arret de la correction d''orbite : problÚme BPM');
3064%                     break;
3065%                 end
3066%
3067                if getdcct < DCCTMIN     % Don't Feedback if the current is too small
3068                    DC_FEEDBACK_STOP_FLAG = 1;
3069                    fprintf('%s         Orbit DC Feedback stopped due to low beam current (<%d mA)\n',datestr(now), DCCTMIN);
3070                    strgMessage = 'Arret de la correction d''orbite : courant trop bas';
3071                    tango_giveInformationMessage(devSpeakerName,  strgMessage);
3072                    warndlg('Arret de la correction d''orbite : courant trop bas');
3073                    break;
3074                end
3075
3076                %x = FB.Xgoal - Xnew;
3077                %STDx = std(x);
3078
3079                if get(findobj(gcbf,'Tag','FOFBguiTangoCheckboxHDCFB'),'Value') == 1
3080%                     if any(Xold == Xnew)
3081%                         N_Stale_Data_Points = find((Xold==Xnew)==1);
3082%                         for i = N_Stale_Data_Points'
3083%                             fprintf('   Stale data: BPMx(%2d,%d), Feedback step skipped (%s). \n', ...
3084%                                 FB.BPMlist(i,1), FB.BPMlist(i,2), datestr(clock));
3085%                         end
3086%                     else
3087                        % Compute horizontal correction
3088                        %%%%%%%%%%%
3089                        % H-plane %
3090                        %%%%%%%%%%%
3091
3092                        % read current of steerers
3093                        %hcm = getam(HCMFamily, FBstruct.HCMlist);
3094                        hcm = getpv(HCMFamily, 'SetpointMean', FBstruct.HCMlist);
3095
3096                        % Compute Delta orbit
3097                        hDeltaOrbit = RH*[hcm; 0];
3098
3099                        SOFB_Dhcm =  SOFB_RinvH*hDeltaOrbit;
3100                        SOFB_DeltaRF = SOFB_Dhcm(end)*RFWeight;
3101
3102                        % diagnostics to be put here
3103
3104                        % Apply correction here
3105
3106                        X = Xgain.*SOFB_Dhcm;
3107
3108                        % check for corrector values and next step values, warn or stop FB as necessary
3109                        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3110                        HCMSP = getam(FB_SOFB.OCSx.CM.FamilyName, FB_SOFB.OCSx.CM.DeviceList);  % present corrector values
3111                        HCMSP_next = HCMSP + X(SOFB_SVDIndexH);       % next corrector values, just slow correctors (no RF)
3112
3113                        MaxSP = maxsp(FB_SOFB.OCSx.CM.FamilyName, FB_SOFB.OCSx.CM.DeviceList);
3114                        MinSP = minsp(FB_SOFB.OCSx.CM.FamilyName, FB_SOFB.OCSx.CM.DeviceList);
3115
3116                        if any(MaxSP - HCMSP_next  < 0)
3117                            HCMnum = find(HCMSP_next > MaxSP);
3118                            % message to screen
3119                            fprintf('**One or more of the horizontal correctors is at its maximum positive value!! Stopping orbit Feedback. \n');
3120                            fprintf('%s\n',datestr(now));
3121                            fprintf('**%s is one of the problem correctors.\n', ...
3122                                cell2mat(family2tango(FB_SOFB.OCSx.CM.FamilyName,'Setpoint',FB_SOFB.OCSx.CM.DeviceList(HCMnum(1),:))));
3123                            strgMessage = 'DC feedback: ProblÚme correcteur horizontal';
3124                            tango_giveInformationMessage(devSpeakerName,  strgMessage);
3125                            warndlg('DC feedback: ProblÚme correcteur horizontal');
3126                            DC_FEEDBACK_STOP_FLAG = 1;
3127                        end
3128                       
3129                        if any(MinSP - HCMSP_next  > 0)
3130                            HCMnum = find(HCMSP_next < MinSP);
3131                            % message to screen
3132                            fprintf('**One or more of the horizontal correctors is at its maximum negative value!! Stopping orbit Feedback. \n');
3133                            fprintf('%s\n',datestr(now));
3134                            fprintf('**%s is one of the problem correctors.\n', ...
3135                                cell2mat(family2tango(FB_SOFB.OCSx.CM.FamilyName,'Setpoint',FB_SOFB.OCSx.CM.DeviceList(HCMnum(1),:))));
3136                            DC_FEEDBACK_STOP_FLAG = 1;
3137                            strgMessage = 'ProblÚme de la correction d''orbite';
3138                            tango_giveInformationMessage(devSpeakerName,  strgMessage);
3139                            warndlg('DC feedback: ProblÚme correcteur vertical');                   
3140                        end
3141
3142                        pause(0);
3143
3144                        if any(HCMSP_next > MaxSP - 1)
3145                            HCMnum = find(HCMSP_next > MaxSP - 1);
3146                            for ik = 1:length(HCMnum)
3147                                HWarnNum = HWarnNum+1;
3148                                fprintf('**Horizontal correctors %s is above %f! \n', ...
3149                                    cell2mat(family2tango(FB_SOFB.OCSx.CM.FamilyName,'Setpoint',FB_SOFB.OCSx.CM.DeviceList(HCMnum(ik),:))), ...
3150                                    MaxSP(HCMnum(ik)) - 1);
3151                            end
3152                            fprintf('%s\n',datestr(now));
3153                            fprintf('**The orbit DC Feedback is still working but this problem should be investigated. \n');
3154                            strgMessage = 'ProblÚme de la correction d''orbite';
3155                            tango_giveInformationMessage(devSpeakerName,  strgMessage);
3156                        end
3157
3158                        if any(HCMSP_next < MinSP + 1)
3159                            HCMnum = find(HCMSP_next < MinSP + 1);
3160                            for ik = 1:length(HCMnum)
3161                                HWarnNum = HWarnNum+1;
3162                                fprintf('**Horizontal correctors %s is below %f! \n', ...
3163                                    cell2mat(family2tango(FB_SOFB.OCSx.CM.FamilyName,'Setpoint',FB_SOFB.OCSx.CM.DeviceList(HCMnum(ik),:))), ...
3164                                    MinSP(HCMnum(ik)) + 1);
3165                            end
3166                            fprintf('%s\n',datestr(now));
3167                            fprintf('**The orbit Feedback is still working but this problem should be investigated. \n');
3168                            strgMessage = 'ProblÚme de la correction d''orbite';
3169                            tango_giveInformationMessage(devSpeakerName,  strgMessage);
3170                        end
3171
3172                        if getdcct < DCCTMIN     % Don't DC Feedback if the current is too small
3173                            DC_FEEDBACK_STOP_FLAG = 1;
3174                            fprintf('%s         Orbit DC Feedback stopped due to low beam current (<%d mA)\n',datestr(now), DCCTMIN);
3175                            strgMessage = 'Arret du DC feedback : courant trop bas';
3176                            tango_giveInformationMessage(devSpeakerName,  strgMessage);
3177                            warndlg('Arret du DC feedback : courant trop bas')
3178                            break;
3179                        end
3180
3181                        % Apply new corrector values
3182                       
3183                        % check if correction variation are small enough
3184                        % if not apply just a percentatge of the correction
3185                       
3186                        % Maximum current modification in correction for one iteration of  DC feedback                       
3187                        % scaling off all correctors to get a maximum variation of HDCMAX
3188                        if max(abs(X(SOFB_SVDIndexH))) > HDCMAX
3189                            HDCfact = HDCMAX/max(abs(X(SOFB_SVDIndexH)));
3190                            fprintf('H-plane: valeur max is %f A > %f A', max(abs(X(SOFB_SVDIndexH))), HDCMAX);
3191                        else
3192                            HDCfact = 1.0;
3193                        end
3194
3195                        if N_HCM > 0 && std(X(1:N_HCM)) > dhcmStd
3196                            fprintf('H-correction applied RMS HCOR was %f \n', std(X(1:N_HCM)))
3197                            if strcmp(getmode(HCMFamily),'Online')
3198                                profibus_sync(FB_SOFB.OCSx.CM.FamilyName); pause(0.2);
3199                            end
3200                            stepsp(FB_SOFB.OCSx.CM.FamilyName, HDCfact*X(1:N_HCM), FB_SOFB.OCSx.CM.DeviceList, 0);
3201                            if strcmp(getmode(HCMFamily),'Online')                           
3202                                profibus_unsyncall(FB_SOFB.OCSx.CM.FamilyName);
3203                            end
3204                        else
3205                            fprintf('No horizontal correction  applied, std corrector = %5.4f mA rms < threshold = %5.4f \n', ...
3206                                std(X(1:N_HCM)),dhcmStd);
3207                        end
3208
3209                        % Don't DC Feedback if the current is too small, remove iteration
3210                        if getdcct < DCCTMIN
3211                            profibus_sync(FB_SOFB.OCSx.CM.FamilyName); pause(0.2);
3212                            stepsp(FB_SOFB.OCSx.CM.FamilyName, -HDCfact*X(1:N_HCM), FB_SOFB.OCSx.CM.DeviceList, 0);
3213                            profibus_unsyncall(FB_SOFB.OCSx.CM.FamilyName);
3214                        end
3215                       
3216                        % Apply RF correction
3217
3218                        if FB.OCSx.FitRF
3219                            deltaRF = Xgain.*SOFB_DeltaRF;
3220                            if N_RFMO > 0
3221                                RFfrequency_last = getrf;
3222                                fprintf('Computed RF frequency correction is %5.1f Hz \n', hw2physics('RF','Setpoint', deltaRF));
3223
3224                                if abs(deltaRF) > deltaRFmin % MHz
3225                                    if abs(deltaRF) < deltaRFmax % For avoiding too large RF step on orbit
3226                                        steprf(deltaRF);
3227                                        fprintf('RF change applied by %5.1f Hz\n', ...
3228                                            hw2physics('RF','Setpoint', deltaRF));
3229                                    else
3230                                        warning('RF change too large: %5.1f Hz (max is %5.1f Hz)', ...
3231                                            hw2physics('RF','Setpoint', deltaRF), hw2physics('RF','Setpoint', deltaRFmax));
3232                                        steprf(deltaRFmax*sign(deltaRF));
3233                                        fprintf('RF change applied by %5.1f Hz\n', hw2physics('RF','Setpoint', deltaRFmax*sign(deltaRF)));
3234                                    end
3235
3236                                    RFfrequency_now = getrf;
3237
3238                                    % Check for stale RF DC Feedback
3239
3240                                    if RFfrequency_last == RFfrequency_now
3241                                        RF_frequency_stalenum = RF_frequency_stalenum + 1;
3242                                        if RF_frequency_stalenum == 30 % - warn and message if stale for 30 secs
3243                                            fprintf('**The RF is not responding to orbit DC Feedback changes! \n');
3244                                            fprintf('%s\n',datestr(now));
3245                                            fprintf('**The orbit DC Feedback is still working but this problem should be investigated. \n');
3246                                        end
3247                                        if rem(RF_frequency_stalenum,120)==0 % - message to screen every 2 minutes
3248                                            fprintf('**The RF is not responding to orbit DC Feedback changes! (%s)\n',datestr(now));
3249                                        end
3250                                    else
3251                                        RF_frequency_stalenum = 0;
3252                                    end
3253
3254                                    fprintf('RF Done: time = %f \n', gettime-t00);
3255                                end
3256                            end
3257                        end
3258                    %end
3259                    %Xold = Xnew;
3260                end % End horizontal correction
3261
3262
3263                %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3264                % Vertical plane "DC Feedback" %
3265                %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3266
3267                % Get orbit and check that the BPMs are different from the last update
3268                %Ynew = getz(FB.BPMlist);
3269
3270%                 if any(isnan(Ynew))
3271%                     DC_FEEDBACK_STOP_FLAG = 1;
3272%                     fprintf('%s         Orbit DC Feedback stopped due to bad BPMs\n',datestr(now));
3273%                     BadBPMName = family2tangodev(BPMxFamily, FB.BPMlist(isnan(Xnew),:));
3274%                     for k=1:size(BadBPMName,1),
3275%                         fprintf('Bad Vertical BPM %s\n',BadBPMName{k});
3276%                     end
3277%                     tango_command_inout2(devSpeakerName,'DevTalk','Arret de la correction d''orbite : problÚme BPM');
3278%                     break;
3279%                 end
3280
3281                if getdcct < DCCTMIN     % Don't DC Feedback if the current is too small
3282                    DC_FEEDBACK_STOP_FLAG = 1;
3283                    fprintf('%s         Orbit DC Feedback stopped due to low beam current (< %d mA)\n', datestr(now), DCCTMIN);
3284                    strgMessage = 'Arret de la correction d''orbite : courant trop bas';
3285                    tango_giveInformationMessage(devSpeakerName,  strgMessage);
3286                    break;
3287                end
3288
3289                %y = FB.Ygoal - Ynew;
3290                %STDy = norm(y)/sqrt(length(y));
3291
3292
3293                if get(findobj(gcbf,'Tag','FOFBguiTangoCheckboxVDCFB'),'Value') == 1
3294
3295%                     if any(Yold == Ynew)
3296%                         fprintf('Info: Stale vertical BPM data, DC Feedback step skipped (%s). \n', datestr(clock));
3297%                         N_Stale_Data_Points = find((Yold==Ynew)==1);
3298%                         for i = N_Stale_Data_Points'
3299%                             fprintf('   Stale data: BPMz(%2d,%d), DC Feedback step skipped (%s). \n', ...
3300%                                 FB.BPMlist(i,1), FB.BPMlist(i,2), datestr(clock));
3301%                         end
3302%
3303%                     else
3304
3305                        %%%%%%%%%%%
3306                        % V-plane %
3307                        %%%%%%%%%%%
3308
3309                        % read current of steerers
3310                        %vcm = getam(VCMFamily, FBstruct.VCMlist);
3311                        vcm = getpv(VCMFamily, 'SetpointMean', FBstruct.VCMlist);
3312                       
3313                        % Compute Delta orbit
3314                        % Load recorded offset between 10 Hz data and data build up from sniffer
3315                        %data = load('/home/operateur/GrpPhysiqueMachine/Laurent/matlab/FOFB/offset_sniffer_10Hz', 'hoffset', 'voffset');
3316                        vDeltaOrbit = RV*vcm;% - data.voffset*1e-6*0;
3317                        %                         figure(55)
3318                        %                         clf
3319                        %                         plot(getspos('BPMz'), vDeltaOrbit); hold on;
3320                        %                         plot(getspos('BPMz'), vDeltaOrbit+data.voffset*1e-6);
3321
3322                        % retrieve V-plane response matrix with good BPM and correctors
3323                        SOFB_Dvcm =  SOFB_RinvV*vDeltaOrbit;
3324
3325                        % set to gains for correction
3326                        Y = Ygain.*SOFB_Dvcm;
3327
3328                        N_VCM = length(FB_SOFB.OCSy.SVDIndex);
3329
3330                        % check for trim values+next step values, warn or stop FB as necessary
3331
3332                        VCMSP = getsp(FB_SOFB.OCSy.CM.FamilyName, FB_SOFB.OCSy.CM.DeviceList); % Get corrector values before correction
3333                        VCMSP_next = VCMSP + Y(1:N_VCM); % New corrector values to be set in
3334
3335                        pause(0);
3336
3337                        if getdcct < DCCTMIN     % Don't DC Feedback if the current is too small
3338                            fprintf('%s         Orbit DC Feedback stopped due to low beam current (<%d mA)\n',datestr(now), DCCTMIN);
3339                            strgMessage = 'Arret de la correction d''orbite : courant trop bas';
3340                            tango_giveInformationMessage(devSpeakerName,  strgMessage);
3341                            DC_FEEDBACK_STOP_FLAG = 1;
3342                            break;
3343                        end
3344
3345                        MaxSP = maxsp(FB_SOFB.OCSy.CM.FamilyName, FB_SOFB.OCSy.CM.DeviceList);
3346                        MinSP = minsp(FB_SOFB.OCSy.CM.FamilyName, FB_SOFB.OCSy.CM.DeviceList);
3347
3348                        if any(MaxSP - VCMSP_next  < 0)
3349                            VCMnum = find(VCMSP_next > MaxSP);
3350                            % message to screen
3351                            fprintf('**One or more of the vertical correctors is at its maximum positive value!! Stopping orbit DC Feedback. \n');
3352                            fprintf('%s\n',datestr(now));
3353                            fprintf('**%s is one of the problem correctors.\n', ...
3354                                cell2mat(family2tango(FB_SOFB.OCSy.CM.FamilyName,'Setpoint',FB_SOFB.OCSy.CM.DeviceList(VCMnum(1),:))));
3355                            DC_FEEDBACK_STOP_FLAG = 1;
3356                        end
3357
3358                        if any(MinSP - VCMSP_next  > 0)
3359                            VCMnum = find(VCMSP_next < MinSP);
3360                            % message to screen
3361                            fprintf('**One or more of the vertical correctors is at its maximum negative value!! Stopping orbit DC Feedback. \n');
3362                            fprintf('%s\n',datestr(now));
3363                            fprintf('**%s is one of the problem correctors.\n', ...
3364                                cell2mat(family2tango(FB_SOFB.OCSy.CM.FamilyName,'Setpoint',FB_SOFB.OCSy.CM.DeviceList(VCMnum(1),:))));
3365                            DC_FEEDBACK_STOP_FLAG = 1;
3366                        end
3367
3368                        pause(0);
3369
3370                        if any(VCMSP_next > MaxSP - 1)
3371                            VCMnum = find(VCMSP_next > MaxSP - 1);
3372                            for ik = 1:length(VCMnum)
3373                                VWarnNum = VWarnNum+1;
3374                                fprintf('**Vertical correctors %s is above %f! \n', ...
3375                                    cell2mat(family2tango(FB_SOFB.OCSy.CM.FamilyName,'Setpoint',FB_SOFB.OCSy.CM.DeviceList(VCMnum(ik),:))), ...
3376                                    MaxSP(VCMnum(ik)) - 1);
3377                            end
3378                            fprintf('%s\n',datestr(now));
3379                            fprintf('**The orbit DC Feedback is still working but this problem should be investigated. \n');
3380                        end
3381
3382                        if any(VCMSP_next < MinSP + 1)
3383                            VCMnum = find(VCMSP_next < MinSP + 1);
3384                            for ik = 1:length(VCMnum)
3385                                VWarnNum = VWarnNum+1;
3386                                fprintf('**Vertical correctors %s is below %f! \n', ...
3387                                    cell2mat(family2tango(FB_SOFB.OCSy.CM.FamilyName,'Setpoint',FB_SOFB.OCSy.CM.DeviceList(VCMnum(ik),:))), ...
3388                                    MinSP(VCMnum(ik)) + 1);
3389                            end
3390                            fprintf('%s\n',datestr(now));
3391                            fprintf('**The orbit DC Feedback is still working but this problem should be investigated. \n');
3392                        end
3393
3394                        % Maximum current modification in correction for one iteration of  DC feedback                       
3395                        % scaling off all correctors to get a maximum variation of VDCMAX
3396                        if max(abs(Y(SOFB_SVDIndexV))) > VDCMAX
3397                            VDCfact = VDCMAX/max(abs(Y(SOFB_SVDIndexV)));
3398                            fprintf('V-plane: valeur max is %f A > %f A', max(abs(Y(SOFB_SVDIndexV))), VDCMAX);
3399                        else
3400                            VDCfact = 1.0;
3401                        end
3402
3403                        % Apply vertical correction
3404                       
3405                        if N_VCM > 0 && std(Y(1:N_VCM)) > dvcmStd
3406                            fprintf('V-correction applied RMS VCOR was %f \n', std(Y(1:N_VCM)))
3407                            if strcmp(getmode(VCMFamily),'Online')
3408                                profibus_sync(FB_SOFB.OCSy.CM.FamilyName); pause(0.2);
3409                            end
3410
3411                            stepsp(FB_SOFB.OCSy.CM.FamilyName, VDCfact*Y(SOFB_SVDIndexV), FB_SOFB.OCSy.CM.DeviceList, 0);
3412                            if strcmp(getmode(VCMFamily),'Online')
3413                                profibus_unsyncall(FB_SOFB.OCSy.CM.FamilyName);
3414                            end
3415                        else
3416                            fprintf('No vertical correction  applied, std corrector = %5.4f mA rms < threshold = %5.4f \n', ...
3417                                std(Y(1:N_VCM)),dvcmStd);
3418                        end
3419
3420                        % Don't DC Feedback if the current is too small, remove iteration
3421                        if getdcct < DCCTMIN     
3422                            profibus_sync(FB_SOFB.OCSy.CM.FamilyName); pause(0.2);
3423                            stepsp(FB_SOFB.OCSy.CM.FamilyName, -VDCfact*Y(SOFB_SVDIndexV), FB_SOFB.OCSy.CM.DeviceList, 0);
3424                            profibus_unsyncall(FB_SOFB.OCSy.CM.FamilyName);
3425                        end
3426
3427                    %end
3428                end
3429
3430                %Yold = Ynew;
3431
3432                % Output info to screen
3433%                 set(findobj(gcbf,'Tag','FOFBguiTangoStaticTextHorizontal'), ...
3434%                     'String',sprintf('Horizontal RMS = %.4f mm',STDx), ...
3435%                     'ForegroundColor',[0 0 0]);
3436%                 set(findobj(gcbf,'Tag','FOFBguiTangoStaticTextVertical'), ...
3437%                     'String',sprintf('Vertical RMS = %.4f mm',STDy),...
3438%                     'ForegroundColor',[0 0 0]);
3439%                 pause(0);
3440
3441                argin.svalue={'dcfb'};
3442                argin.lvalue=int32(Locktag);
3443                % Wait for next update time or stop request
3444                while DC_FEEDBACK_STOP_FLAG == 0 && (gettime-t00) < LoopDelay
3445                    pause(.2);
3446                    % Check if GUI has been closed
3447                    if isempty(gcbf)
3448                        DC_FEEDBACK_STOP_FLAG = 1;
3449                        lasterr('FOFBguiTango GUI DISAPPEARED!');
3450                        error('FOFBguiTango GUI DISAPPEARED!');
3451                    end
3452                    if DC_FEEDBACK_STOP_FLAG == 0
3453                        DC_FEEDBACK_STOP_FLAG = getappdata(findobj(gcbf,'Tag','FOFBguiTangoFig1'),'DC_FEEDBACK_STOP_FLAG');
3454                        % read FOFB status and stop DC loop if KO
3455
3456                        isxFOFBRunning = readattribute([devFOFBManager, '/xFofbRunning']);
3457                        iszFOFBRunning = readattribute([devFOFBManager, '/zFofbRunning']);
3458                        if ~isxFOFBRunning || ~iszFOFBRunning
3459                            DC_FEEDBACK_STOP_FLAG = 1;
3460                            fprintf('DCFB stopped since FOFB is stopped!\n');
3461                        end                                                       
3462                   end
3463                    % Maintain lock on FOFB service
3464                    tango_command_inout2(devLockName,'MaintainLock', argin);
3465                end
3466
3467                StartErrorTime = gettime;
3468
3469                % Maintain lock on FOFB service
3470                tango_command_inout2(devLockName,'MaintainLock', argin);
3471
3472
3473            catch
3474                fprintf('\n  %s \n',lasterr);
3475                DC_FEEDBACK_STOP_FLAG = 1;
3476                strgMessage = 'Arret du daichargement des correcteurs';
3477                tango_giveInformationMessage(devSpeakerName,  strgMessage);
3478                profibus_unsyncall(VCMFamily); % to be sure that correctors are controllable
3479            end
3480
3481            % Check whether user asked for stopping FOFB
3482            if DC_FEEDBACK_STOP_FLAG == 0
3483                DC_FEEDBACK_STOP_FLAG = getappdata(findobj(gcbf,'Tag','FOFBguiTangoFig1'),'DC_FEEDBACK_STOP_FLAG');
3484            end
3485
3486
3487        end  % End of DC Feedback loop
3488
3489
3490        % End DC Feedback, reset all parameters
3491        try
3492
3493            % Enable buttons
3494            set(findobj(gcbf,'Tag','FOFBguiTangoPushbuttonStartDC'),'Enable','on');
3495            set(findobj(gcbf,'Tag','FOFBguiTangoPushbuttonStopDC'),'Enable','off');
3496            set(findobj(gcbf,'Tag','FOFBguiTangoButtonOrbitCorrection'),'Enable','on');
3497            set(findobj(gcbf,'Tag','FOFBguiTangoButtonOrbitCorrectionSetupFOFB'),'Enable','on');
3498            set(findobj(gcbf,'Tag','FOFBguiTangoButtonFeedbackSetup'),'Enable','on');
3499            set(findobj(gcbf,'Tag','FOFBguiTangoClose'),'Enable','on');
3500            set(findobj(gcbf,'Tag','FOFBguiTangoCheckboxHSOFB'),'Enable','on');
3501            set(findobj(gcbf,'Tag','FOFBguiTangoCheckboxVSOFB'),'Enable','on');
3502            set(findobj(gcbf,'Tag','FOFBguiTangoCheckboxHcorrection'),'Enable','on');
3503            set(findobj(gcbf,'Tag','FOFBguiTangoCheckboxVcorrection'),'Enable','on');
3504            %set(findobj(gcbf,'Tag','FOFBguiTangoCheckboxRF'),'Enable','on');
3505            set(findobj(gcbf,'Tag','FOFBguiTangoCheckboxSOFB'),'Enable','on');
3506            set(findobj(gcbf,'Tag','FOFBguiTangoCheckboxFOFB'),'Enable','on');
3507            set(findobj(gcbf,'Tag','FOFBguiTangoCheckboxHDCFB'),'Enable','on');
3508            set(findobj(gcbf,'Tag','FOFBguiTangoCheckboxVDCFB'),'Enable','on');
3509            set(findobj(gcbf,'Tag','FOFBguiTangoStaticTextHorizontal'),'String',sprintf('Horizontal RMS = _____ mm'),'ForegroundColor',[0 0 0]);
3510            set(findobj(gcbf,'Tag','FOFBguiTangoStaticTextVertical'),'String',sprintf('Vertical RMS = _____ mm'),'ForegroundColor',[0 0 0]);
3511            set(findobj(gcbf,'Tag','FOFBguiTangoButtonConvertMatrix4FPGA'),'Enable','on');
3512            set(findobj(gcbf,'Tag','FOFBguiTangoPushbuttonStart'),'Enable','on');
3513            pause(0);
3514
3515        catch
3516            % GUI must have been closed
3517            fprintf('GUI must have been closed\n');
3518        end
3519
3520        fprintf('   %s \n', datestr(clock));
3521        fprintf('   ******************************\n');
3522        fprintf('   **  Orbit DC Feedback Stopped  **\n');
3523        fprintf('   ******************************\n\n');
3524        set(0,'showhiddenhandles','off');
3525        pause(0);
3526
3527        % Unlock SOFB service
3528        argin.svalue={'dcfb'};
3529        argin.lvalue=int32(Locktag);
3530        tango_command_inout2(devLockName,'Unlock', argin);
3531
3532        %setup average data for reading BPMs
3533        setfamilydata('gethbpmgroup','BPMx','Monitor', 'SpecialFunctionGet')
3534        setfamilydata('getvbpmgroup','BPMz','Monitor', 'SpecialFunctionGet')
3535
3536%% FOFBRunningMode
3537    case 'FOFBRunningMode' %Switch between FOFB mode
3538        % 0 means FOFB without SOFB and with DCFB
3539        % 1 means FOFB with SOFB but wihtout DCFB
3540       
3541        if readattribute([devLockName '/dcfb'])
3542            set(findobj(gcbf,'Tag','FOFBguiTangoCheckboxFOFB_SOFB'),'Value', 0);
3543            warndlg('First Stop DCFB')
3544            return;
3545        end
3546       
3547        val = get(findobj(gcbf,'Tag','FOFBguiTangoCheckboxFOFB_SOFB'),'Value');
3548
3549        isxFOFBRunning = readattribute([devFOFBManager, '/xFofbRunning']);
3550        iszFOFBRunning = readattribute([devFOFBManager, '/zFofbRunning']);
3551
3552        if isxFOFBRunning || iszFOFBRunning
3553            set(findobj(gcbf,'Tag','FOFBguiTangoCheckboxFOFB_SOFB'),'Value', mod(val+1,2));
3554            fprintf('First Stop FOFB\n')
3555            return;
3556        end
3557
3558       
3559        if val == 1 % FOFB runs with SOFB but without DCFB
3560            set(findobj(gcbf,'Tag','FOFBguiTangoPushbuttonStopDC'),'Enable', 'off');
3561            set(findobj(gcbf,'Tag','FOFBguiTangoPushbuttonStartDC'),'Enable', 'off');
3562            set(findobj(gcbf,'Tag','FOFBguiTangoCheckboxDCRF'),'Enable', 'off');
3563            set(findobj(gcbf,'Tag','FOFBguiTangoCheckboxHDCFB'),'Enable', 'off');
3564            set(findobj(gcbf,'Tag','FOFBguiTangoCheckboxVDCFB'),'Enable', 'off');
3565            set(findobj(gcbf,'Tag','FOFBguiTangoFig1'),'Color', [0.84 0 0.89]);
3566
3567        else % FOFB runs without SOFB and with DCFB
3568            set(findobj(gcbf,'Tag','FOFBguiTangoPushbuttonStartDC'),'Enable', 'on');
3569            set(findobj(gcbf,'Tag','FOFBguiTangoCheckboxDCRF'),'Enable', 'on');
3570            set(findobj(gcbf,'Tag','FOFBguiTangoCheckboxHDCFB'),'Enable', 'on');
3571            set(findobj(gcbf,'Tag','FOFBguiTangoCheckboxVDCFB'),'Enable', 'on');           
3572            set(findobj(gcbf,'Tag','FOFBguiTangoFig1'),'Color', [0.1 0.1 1]);
3573        end
3574
3575        FB = get(findobj(gcbf,'Tag','FOFBguiTangoButtonOrbitCorrectionSetupFOFB'),'Userdata');
3576        FB.SOFBandFOFB = val;
3577        set(findobj(gcbf,'Tag','FOFBguiTangoButtonOrbitCorrectionSetupFOFB'),'Userdata',FB);
3578        savaData2File;
3579       
3580    otherwise
3581        fprintf('   Unknown action name: %s.\n', action);
3582
3583end
3584
3585
3586%% getlocallist
3587function [HCMlist, VCMlist, BPMlist] = getlocallist
3588
3589%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3590% Edit the following lists to change default configuration of Orbit Correction %
3591%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3592
3593
3594HCMlist = family2dev('FHCOR');
3595VCMlist = family2dev('FVCOR');
3596
3597% do not change this list
3598% otherwise incoherent state with matrix4fofb
3599
3600BPMlist = [
3601    1     2
3602    1     3
3603    1     4
3604    1     5
3605    1     6
3606    1     7
3607    2     1
3608    2     2
3609    2     3
3610    2     4
3611    2     5
3612    2     6
3613    2     7
3614    2     8
3615    3     1
3616    3     2
3617    3     3
3618    3     4
3619    3     5
3620    3     6
3621    3     7
3622    3     8
3623    4     1
3624    4     2
3625    4     3
3626    4     4
3627    4     5
3628    4     6
3629    4     7
3630    5     1
3631    5     2
3632    5     3
3633    5     4
3634    5     5
3635    5     6
3636    5     7
3637    6     1
3638    6     2
3639    6     3
3640    6     4
3641    6     5
3642    6     6
3643    6     7
3644    6     8
3645    7     1
3646    7     2
3647    7     3
3648    7     4
3649    7     5
3650    7     6
3651    7     7
3652    7     8
3653    8     1
3654    8     2
3655    8     3
3656    8     4
3657    8     5
3658    8     6
3659    8     7
3660    9     1
3661    9     2
3662    9     3
3663    9     4
3664    9     5
3665    9     6
3666    9     7
3667    10     1
3668    10     2
3669    10     3
3670    10     4
3671    10     5
3672    10     6
3673    10     7
3674    10     8
3675    11     1
3676    11     2
3677    11     3
3678    11     4
3679    11     5
3680    11     6
3681    11     7
3682    11     8
3683    12     1
3684    12     2
3685    12     3
3686    12     4
3687    12     5
3688    12     6
3689    12     7
3690    13     1
3691    13     8
3692    13     9
3693    13     2
3694    13     3
3695    13     4
3696    13     5
3697    13     6
3698    13     7
3699    14     1
3700    14     2
3701    14     3
3702    14     4
3703    14     5
3704    14     6
3705    14     7
3706    14     8
3707    15     1
3708    15     2
3709    15     3
3710    15     4
3711    15     5
3712    15     6
3713    15     7
3714    15     8
3715    16     1
3716    16     2
3717    16     3
3718    16     4
3719    16     5
3720    16     6
3721    16     7
3722    1     1
3723    ];
3724
3725function check4feedbackflag(devLockName)
3726
3727if strcmp(getmode('BPMx'),'Online') && strcmp(getmode('BPMz'),'Online')
3728    %look for already running FOFB
3729    val = readattribute([devLockName '/sofb']);
3730    if val == 1
3731        error('SOFB already running. Stop other application first!')
3732    end
3733    val = readattribute([devLockName '/rffb']);
3734    if val == 1
3735        error('RFFB already running. Stop other application first!')
3736    end
3737end
3738
3739function check4DCfeedbackflag(devLockName)
3740
3741if strcmp(getmode('BPMx'),'Online') && strcmp(getmode('BPMz'),'Online')
3742    %look for already running FOFB
3743    val = readattribute([devLockName '/sofb']);
3744    if val == 1
3745        error('SOFB already running. Stop other application first!')
3746    end
3747    val = readattribute([devLockName '/dcfb']);
3748    if val == 1
3749        error('DCFB already running. Stop other application first!')
3750    end
3751end
3752
3753% data saved to be used in another GUI by SOFB
3754function savaData2File
3755
3756FB = get(findobj(gcbf,'Tag','FOFBguiTangoButtonOrbitCorrectionSetupFOFB'),'Userdata');
3757% Save current configuration data for FOFB into a file!
3758% Ugly but first quick solution before merging both FB
3759DirName = getfamilydata('Directory', 'FOFBdata');
3760FileName = fullfile(DirName, 'FOFBconfiguration');
3761save(FileName, 'FB');
3762
3763fprintf('New FOFB configuration saved to file %s\n', FileName);
3764% %%
3765%       case Tango::ON:
3766%         lv_state = 0;
3767%         break;
3768%       case Tango::OFF:
3769%         lv_state = 1;
3770%         break;
3771%       case Tango::CLOSE:
3772%         lv_state = 2;
3773%         break;
3774%       case Tango::OPEN:
3775%         lv_state = 3;
3776%         break;
3777%       case Tango::INSERT:
3778%         lv_state = 4;
3779%         break;
3780%       case Tango::EXTRACT:
3781%         lv_state = 5;
3782%         break;
3783%       case Tango::MOVING:
3784%         lv_state = 6;
3785%         break;
3786%       case Tango::STANDBY:
3787%         lv_state = 7;
3788%         break;
3789%       case Tango::FAULT:
3790%         lv_state = 8;
3791%         break;
3792%       case Tango::INIT:
3793%         lv_state = 9;
3794%         break;
3795%       case Tango::RUNNING:
3796%         lv_state = 10;
3797%         break;
3798%       case Tango::ALARM:
3799%         lv_state = 11;
3800%         break;
3801%       case Tango::DISABLE:
3802%         lv_state = 12;
3803%         break;
3804%       default:
3805%       case Tango::UNKNOWN:
3806%         lv_state = 13;
3807%         break;
3808%
3809
Note: See TracBrowser for help on using the repository browser.