source: MML/trunk/applications/loco/locogui.m

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

Initial import--MML version from SOLEIL@2013

File size: 140.6 KB
Line 
1function varargout = locogui(varargin)
2%LOCOGUI - Graphical interface for running the LOCO algorithm
3%
4%  There are a number of inputs when running LOCO.
5%
6%  I. File menu
7%  A.  Open -> open a loco data file. The input file can be a .mat file or a .m script. 
8%  B.  Save as -> save file to a different name.
9%  C.  Save as (one iteration) -> saves only one iteration.
10%  D.  Print,
11%  E.  Pop Plot #1 -> copies plot #1 in locogui to a Matlab figure so that it can
12%                 be modified in any way the user wants.  Locogui has the axes
13%                 handles hiddlen.  If a user wants to change this issue,
14%                 set(0,'ShowHiddenHandles','on') (at your own risk).   
15%  E.  Pop Plot #2 -> copies plot #2 in locogui to a Matlab figure.
16%  F.  Diary -> Starts/Ends a diary file.
17
18%  All the information for each iteration is saved in the data file.  Anytime a selection
19%  is made from the "Start From" popup menu, all the items in the input menu are restored. 
20%  This includes the BPM and CM lists.  One potential awkwardness in this application is
21%  respect to viewing the BPM and CM lists.  If one edits a BPM or CM list, then the displayed
22%  list is relative to the "Start From" popup menu and not the "Plot Iteration" popup menu.
23
24%  II. Input menu
25%  A.  Auto-Correct deltas
26%  LocoFlags.AutoCorrectDelta = 'Yes' or 'No'
27
28%  Automatically adjust the delta used to compute the response matrix gradient. 
29%  If AutoCorrectDeltaFlag = 'Yes', then the parameter deltas are adjusted to
30%  keep the RMS change in the response matrix change equal to 1 micron. 
31%  If the RMS is within a factor of ten, then the delta is corrected but
32%  the response matrix is not recomputed.  Note: if FitParameters.Deltas = NaN
33%  and Autocorrect is off, then Fdelta will still be autocorrected once.
34%
35%  B. Options for selecting the number of singular values
36%  LocoFlags.SVmethod = 'Rank,' [], threshold, or an index vector
37%
38%  If SVmethod is a scalar, then all singular values will be greater than Smax * SVmethod.
39%  If SVmethod is empty, then singular values will be choosen manually (graphically).
40%  If SVmethod is a vector, then that vector corresponds to the index of singular values.
41%  If SVmethod is 'Rank', then singular values are removed if a Matlab warning for rank tolerance is exceeded.
42%
43%  C. Include dispersion as a column of the response matrix
44%  LocoFlags.Dispersion = 'Yes' or 'No'
45%
46%  D. Use the fully coupled response matrix
47%  LocoFlags.Coupling = 'Yes' or 'No'
48%
49%  E. Normalize the parameter fit response matrix to the same RMS as the model response matrix
50%  LocoFlags.Normalization.Flag = 'Yes' or 'No'
51%  Note: if the RF frequency is fit, it is always normalized.
52%
53%  F. Use linear response matrix calculator
54%  LocoFlags.ResponseMatrixCalculator = 'Linear'
55%
56%  G. Outlier rejection
57%  LocoFlags.OutlierFactor = number of sigma
58%
59%  H.  Output U,S,V, and A matrices to a file
60%  LocoFlags.SVDDataFileName = Directory\FileName or [] (ignored if empty)
61%
62%  NOTE
63%  1. When saving A, S, V, U the outliers have been removed, however,
64%     the saved response matrix (measured and model) do not.
65%
66%  See LocoManual.doc, James SaFranek (the LOCO creator), Andrei Terebilo, or Greg Portmann for more information.
67%
68%  Writen by Greg Portmann
69
70
71% LOCOGUI Application M-file for locogui.fig
72%    FIG = LOCOGUI launch locogui GUI.
73%    LOCOGUI('callback_name', ...) invoke the named callback.
74
75% Last Modified by GUIDE v2.0 21-Nov-2001 16:26:19
76
77if nargin == 0  % LAUNCH GUI
78
79        fig = openfig(mfilename,'new');  % 'reuse'
80
81        % Use system color scheme for figure (this seems to create platform dependent problems)
82        %set(fig,'Color',get(0,'defaultUicontrolBackgroundColor'));
83
84        % Generate a structure of handles to pass to callbacks, and store it.
85    handles = guihandles(fig);
86    guidata(fig, handles);
87   
88    if nargout > 0
89        varargout{1} = fig;
90    end
91
92       
93    % Change menu locations
94    % set(findobj(fig,'tag','FileName'),'Position',1);
95    % set(findobj(fig,'tag','FileName'),'Separator','Off');
96    % set(findobj(fig,'tag','FileName'),'Interruptible','Off');
97    % set(findobj(fig,'tag','Flags'),'Position',2);
98    % set(findobj(fig,'tag','Flags'),'Separator','On');
99    % set(findobj(fig,'tag','Flags'),'Interruptible','Off');
100    % set(findobj(fig,'tag','Help'),'Interruptible','Off');
101   
102    % set(findobj(gcf,'tag','linear'),'enable','off')
103    %% Add on Laurent
104    h1 = fig;
105   
106    appdata = [];
107    appdata.lastValidTag = 'Untitled_1';
108
109    h148 = uimenu(...
110        'Parent',h1,...
111        'Callback','%automatic',...
112        'Label','Addons',...
113        'Tag','Untitled_1');
114
115        %'CreateFcn', {@local_CreateFcn, blanks(0), appdata} );
116       
117    appdata = [];
118    appdata.lastValidTag = 'uimenu_plotK';
119
120    h149 = uimenu(...
121        'Parent',h148,...
122        'Callback','locogui(''uimenu_plotK_Callback'',gcbo,[],guidata(gcbo))',...
123        'Label','Plot DK/K', ...
124        'Tag','uimenu_plotK');
125   
126        %'CreateFcn', {@local_CreateFcn, blanks(0), appdata} );
127
128    appdata = [];
129    appdata.lastValidTag = 'uimenu_exporK';
130
131    h150 = uimenu(...
132        'Parent',h148,...
133        'Callback','locogui(''uimenu_exportK_Callback'',gcbo,[],guidata(gcbo))',...
134        'Label','Export DK/K',...
135        'Tag','uimenu_exporK');
136
137        %'CreateFcn', {@local_CreateFcn, blanks(0), appdata} );
138   
139    % End Add on Laurent
140   
141elseif ischar(varargin{1}) % INVOKE NAMED SUBFUNCTION OR CALLBACK
142
143        try
144                [varargout{1:nargout}] = feval(varargin{:}); % FEVAL switchyard
145        catch
146                disp(lasterr);
147        end
148
149end
150
151
152%| ABOUT CALLBACKS:
153%| GUIDE automatically appends subfunction prototypes to this file, and
154%| sets objects' callback properties to call them through the FEVAL
155%| switchyard above. This comment describes that mechanism.
156%|
157%| Each callback subfunction declaration has the following form:
158%| <SUBFUNCTION_NAME>(H, EVENTDATA, HANDLES, VARARGIN)
159%|
160%| The subfunction name is composed using the object's Tag and the
161%| callback type separated by '_', e.g. 'slider2_Callback',
162%| 'figure1_CloseRequestFcn', 'axis1_ButtondownFcn'.
163%|
164%| H is the callback object's handle (obtained using GCBO).
165%|
166%| EVENTDATA is empty, but reserved for future use.
167%|
168%| HANDLES is a structure containing handles of components in GUI using
169%| tags as fieldnames, e.g. handles.figure1, handles.slider2. This
170%| structure is created at GUI startup using GUIHANDLES and stored in
171%| the figure's application data using GUIDATA. A copy of the structure
172%| is passed to each callback.  You can store additional information in
173%| this structure at GUI startup, and you can change the structure
174%| during callbacks.  Call guidata(h, handles) after changing your
175%| copy to replace the stored original so that subsequent callbacks see
176%| the updates. Type "help guihandles" and "help guidata" for more
177%| information.
178%|
179%| VARARGIN contains any extra arguments you have passed to the
180%| callback. Specify the extra arguments by editing the callback
181%| property in the inspector. By default, GUIDE sets the property to:
182%| <MFILENAME>('<SUBFUNCTION_NAME>', gcbo, [], guidata(gcbo))
183%| Add any extra arguments after the last argument, before the final
184%| closing parenthesis.
185
186
187% --------------------------------------------------------------------
188function varargout = Start_Callback(h, eventdata, handles, varargin)
189
190% Get filename and try to load
191FileName = get(findobj(gcbf,'Tag','FileName'),'Userdata');
192try
193    load(FileName);
194    FileName = get(findobj(gcbf,'Tag','FileName'),'Userdata');     % Just in case FileName happens to be saved in the .mat file
195catch
196    fprintf('   File does not exist or is not a *.mat file type.\n');
197    axes(findobj(gcbf,'Tag','Axes1'));
198    set(gca,'XTick',[]); set(gca,'YTick',[]); cla; title(' '); xlabel(' '); ylabel(' ');
199    axes(findobj(gcbf,'Tag','Axes2'));
200    set(gca,'XTick',[]); set(gca,'YTick',[]); cla; title(' '); xlabel(' '); ylabel(' ');
201    return
202end
203
204
205% Check inputs and add defaults (should already be done)
206%[BPMData, CMData, LocoMeasData, LocoModel, FitParameters, LocoFlags, RINGData] = locofilecheck({BPMData, CMData, LocoMeasData, LocoModel, FitParameters, LocoFlags, RINGData});
207
208
209StartFrom  = get(findobj(gcbf,'Tag','StartFrom'),'Value')-1;
210Iterations = get(findobj(gcbf,'Tag','Iterations'),'Value');
211
212   
213% Clear old iterations if they exist
214if StartFrom+2 <= length(FitParameters)
215    fprintf('   Note:  You are writing over previous iterations.\n');
216    LocoFlags(StartFrom+2:end) = [];
217    BPMData(StartFrom+2:end) = [];
218    CMData(StartFrom+2:end) = [];
219    FitParameters(StartFrom+2:end) = [];
220    LocoModel(:,StartFrom+2:end) = [];
221end
222
223
224for i = StartFrom+2:(StartFrom+2+Iterations-1)
225    fprintf('   Iteration #%d\n', i-1);
226   
227    % Start with the old values
228    BPMData(i) = BPMData(i-1);
229    CMData(i) = CMData(i-1);
230    FitParameters(i) = FitParameters(i-1);
231    LocoFlags(i) = LocoFlags(i-1);
232   
233    % Check for a new (user input) BPM and CM good data lists 
234    if ~isempty(get(findobj(gcbf,'Tag','HBPMIndex'), 'Userdata'))
235        %fprintf('   Horizontal BPM list changed based on user input.\n');
236        BPMData(i).HBPMGoodDataIndex = get(findobj(gcbf,'Tag','HBPMIndex'), 'Userdata');
237    end
238    if ~isempty(get(findobj(gcbf,'Tag','VBPMIndex'), 'Userdata'))
239        %fprintf('   Vertical BPM list changed based on user input.\n');
240        BPMData(i).VBPMGoodDataIndex = get(findobj(gcbf,'Tag','VBPMIndex'), 'Userdata');
241    end
242    if ~isempty(get(findobj(gcbf,'Tag','HCMIndex'), 'Userdata'))
243        %fprintf('   Horizontal corrector magnet list changed based on user input.\n');
244        CMData(i).HCMGoodDataIndex = get(findobj(gcbf,'Tag','HCMIndex'), 'Userdata');
245    end
246    if ~isempty(get(findobj(gcbf,'Tag','VCMIndex'), 'Userdata'))
247        %fprintf('   Vertical corrector magnet list changed based on user input.\n');
248        CMData(i).VCMGoodDataIndex = get(findobj(gcbf,'Tag','VCMIndex'), 'Userdata');
249    end
250
251
252    % Get flags
253    if strcmpi((get(findobj(gcbf,'Tag','Rank'),'Checked')),'on')
254        % Rank method
255        LocoFlags(i).SVmethod = 'Rank';
256    elseif strcmpi((get(findobj(gcbf,'Tag','Threshold'),'Checked')),'on')
257        % Threshold method
258        LocoFlags(i).SVmethod = get(findobj(gcbf,'Tag','Threshold'),'Userdata');
259    elseif strcmpi((get(findobj(gcbf,'Tag','Interactive'),'Checked')),'on')
260        % Interactive method
261        LocoFlags(i).SVmethod = [];
262    elseif strcmpi((get(findobj(gcbf,'Tag','UserInput'),'Checked')),'on')
263        % User Input method
264        LocoFlags(i).SVmethod = get(findobj(gcbf,'Tag','UserInput'),'Userdata');
265    else
266        % Threshold method
267        LocoFlags(i).SVmethod = get(findobj(gcbf,'Tag','Threshold'),'Userdata');       
268    end
269   
270    LocoFlags(i).Threshold = get(findobj(gcbf,'Tag','Threshold'),'Userdata');
271    LocoFlags(i).OutlierFactor = get(findobj(gcbf,'Tag','Outlier'),'Userdata');
272    LocoFlags(i).HorizontalDispersionWeight = getappdata(gcbf,'HorizontalDispersionWeight');
273    LocoFlags(i).VerticalDispersionWeight = getappdata(gcbf,'VerticalDispersionWeight');
274
275    if strcmpi((get(findobj(gcf,'Tag','AutoCorrect'),'Checked')),'on')
276        LocoFlags(i).AutoCorrectDelta = 'Yes';
277    else
278        LocoFlags(i).AutoCorrectDelta = 'No';
279    end
280       
281    if strcmpi((get(findobj(gcf,'Tag','Coupling'),'Checked')),'on')
282        LocoFlags(i).Coupling = 'Yes';
283    else
284        LocoFlags(i).Coupling = 'No';
285    end
286   
287    if strcmpi((get(findobj(gcf,'Tag','Normalize'),'Checked')),'on')
288        LocoFlags(i).Normalization.Flag = 'Yes';
289    else
290        LocoFlags(i).Normalization.Flag = 'No';
291    end
292   
293    if strcmpi((get(findobj(gcf,'Tag','Dispersion'),'Checked')),'on')
294        LocoFlags(i).Dispersion = 'Yes';
295    else
296        LocoFlags(i).Dispersion = 'No';
297    end
298   
299    if strcmpi((get(findobj(gcf,'Tag','FitHCMEnergyShift'),'Checked')),'on')
300        CMData(i).FitHCMEnergyShift = 'Yes';
301    else
302        CMData(i).FitHCMEnergyShift = 'No';
303    end
304
305    if strcmpi((get(findobj(gcf,'Tag','FitVCMEnergyShift'),'Checked')),'on')
306        CMData(i).FitVCMEnergyShift = 'Yes';
307    else
308        CMData(i).FitVCMEnergyShift = 'No';
309    end
310
311    if strcmpi((get(findobj(gcf,'Tag','Linear'),'Checked')),'on')
312        LocoFlags(i).ResponseMatrixCalculator = 'Linear';
313    else %strcmpi((get(findobj(gcf,'Tag','Full'),'Checked')),'on')
314        LocoFlags(i).ResponseMatrixCalculator = 'Full';
315    end
316
317    if strcmpi((get(findobj(gcf,'Tag','CM'),'Checked')),'on')
318        LocoFlags(i).ClosedOrbitType = 'FixedMomentum';
319    else %strcmpi((get(findobj(gcf,'Tag','CPL'),'Checked')),'on')
320        LocoFlags(i).ClosedOrbitType = 'FixedPathLength';
321    end
322
323    if strcmpi((get(findobj(gcf,'Tag','RespMatBiDirectional'),'Checked')),'on')
324        LocoFlags(i).ResponseMatrixMeasurement = 'BiDirectional';
325    else %strcmpi((get(findobj(gcf,'Tag','RespMatOneWay'),'Checked')),'on')
326        LocoFlags(i).ResponseMatrixMeasurement = 'OneWay';
327    end
328
329    if strcmpi((get(findobj(gcf,'Tag','DispBiDirectional'),'Checked')),'on')
330        LocoFlags(i).DispersionMeasurement = 'BiDirectional';
331    else %strcmpi((get(findobj(gcf,'Tag','DispOneWay'),'Checked')),'on')
332        LocoFlags(i).DispersionMeasurement = 'OneWay';
333    end
334   
335    if strcmpi((get(findobj(gcf,'Tag','ErrorBars'),'Checked')),'on')
336        LocoFlags(i).CalculateSigma = 'Yes';
337    else
338        LocoFlags(i).CalculateSigma = 'No';
339    end
340
341    if strcmpi((get(findobj(gcf,'Tag','SinglePrecision'),'Checked')),'on')
342        LocoFlags(i).SinglePrecision = 'Yes';
343    else
344        LocoFlags(i).SinglePrecision = 'No';
345    end
346
347    if strcmpi((get(findobj(gcf,'Tag','SVD_FileName'),'Checked')),'on')
348        LocoFlags(i).SVDDataFileName = get(findobj(gcbf,'Tag','SVD_FileName'),'Userdata');
349    else
350        LocoFlags(i).SVDDataFileName = '';
351    end
352           
353    if strcmpi((get(findobj(gcf,'Tag','FitRF'),'Checked')),'on')
354        FitParameters(i).FitRFFrequency = 'Yes';
355    else
356        FitParameters(i).FitRFFrequency = 'No';
357    end
358
359    if strcmpi((get(findobj(gcf,'Tag','BPMGains'),'Checked')),'on')
360        BPMData(i).FitGains = 'Yes';
361    else
362        BPMData(i).FitGains = 'No';
363    end
364
365    if strcmpi((get(findobj(gcf,'Tag','BPMCoupling'),'Checked')),'on')
366        BPMData(i).FitCoupling = 'Yes';
367    else
368        BPMData(i).FitCoupling = 'No';
369    end
370   
371    if strcmpi((get(findobj(gcf,'Tag','CMKicks'),'Checked')),'on')
372        CMData(i).FitKicks = 'Yes';
373    else
374        CMData(i).FitKicks = 'No';
375    end
376
377    if strcmpi((get(findobj(gcf,'Tag','CMRolls'),'Checked')),'on')
378        CMData(i).FitCoupling = 'Yes';
379    else
380        CMData(i).FitCoupling = 'No';
381    end   
382   
383    if strcmpi(get(handles.GaussNewton,'Checked'),'on')
384        LocoFlags(i).Method.Name    = 'Gauss-Newton';
385    elseif strcmpi(get(handles.GaussNewtonWithCost,'Checked'),'on')
386        LocoFlags(i).Method.Name    = 'Gauss-Newton With Cost Function';
387        LocoFlags(i).Method.CostScaleFactor  = get(handles.CostScaleFactor,'Userdata');
388    elseif strcmpi(get(handles.LevenbergMarquardt,'Checked'),'on')
389        LocoFlags(i).Method.Name    = 'Levenberg-Marquardt';
390        LocoFlags(i).Method.MaxIter = get(handles.MaxIterLM,'Userdata');
391        LocoFlags(i).Method.Lambda  = get(handles.LambdaLM,'Userdata');
392    elseif strcmpi(get(handles.ScaledLevenbergMarquardt,'Checked'),'on')
393        LocoFlags(i).Method.Name    = 'Scaled Levenberg-Marquardt';
394        LocoFlags(i).Method.MaxIter = get(handles.MaxIterLM,'Userdata');
395        LocoFlags(i).Method.Lambda  = get(handles.LambdaLM,'Userdata');
396    else
397        error('Method unknown');
398    end
399   
400   
401    % Run loco
402    [LocoModel(i), BPMData(i), CMData(i), FitParameters(i), LocoFlags(i), RINGData] = loco(LocoMeasData, BPMData(i), CMData(i), FitParameters(i), LocoFlags(i), RINGData);
403
404    % Was a better solution found?
405    if any(strcmpi(LocoFlags(i).Method.Name, {'Levenberg-Marquardt', 'Scaled Levenberg-Marquardt'}))
406        if strcmpi(LocoFlags(i).Method.BetterSolution, 'No')
407            % not needed: LocoModel(i) = []; BPMData(i) = []; CMData(i) = []; FitParameters(i) = []; LocoFlags(i) = [];
408            fprintf('\n   Stopping at iteration %d since no better solution was found.\n\n', i-1);
409            iLast = i-1;
410            break;
411        end
412    end
413    iLast = i;
414   
415    save(FileName, 'LocoModel', 'FitParameters', 'BPMData', 'CMData', 'RINGData', 'LocoMeasData', 'LocoFlags');
416    setappdata(gcbf, 'LocoDataCell', {BPMData, CMData, LocoMeasData, LocoModel, FitParameters, LocoFlags, RINGData});
417   
418    % Plot
419    set(findobj(gcbf,'Tag','PlotIteration'),'String',num2str((0:iLast-1)'));
420    set(findobj(gcbf,'Tag','PlotIteration'),'Value', iLast);
421    MenuAxes_Callback(findobj(gcbf,'Tag','PlotMenu1'));
422    MenuAxes_Callback(findobj(gcbf,'Tag','PlotMenu2'));
423    load(FileName);
424    drawnow;
425end
426
427set(findobj(gcbf,'Tag','StartFrom'),'String',num2str((0:iLast-1)'));
428set(findobj(gcbf,'Tag','StartFrom'),'Value',iLast);
429
430% Update menu items in case something was changed in loco
431setmenuinputs(BPMData(end), CMData(end), LocoFlags(end), FitParameters(end), handles);
432
433
434% --------------------------------------------------------------------
435function varargout = LevenbergMarquardt_Callback(h, eventdata, handles, varargin)
436set(handles.GaussNewton,             'Checked','off');
437set(handles.GaussNewtonWithCost,     'Checked','off');
438set(handles.LevenbergMarquardt,      'Checked','on');
439set(handles.ScaledLevenbergMarquardt,'Checked','off');
440set(handles.CostScaleFactor, 'Enable','off');
441set(handles.LambdaLM,        'Enable','on');
442set(handles.MaxIterLM,       'Enable','on');
443
444%set(handles.LambdaLM, 'Label',['    Lambda = ',            num2str(get(handles.LambdaLM, 'Userdata'))]);
445%set(handles.MaxIterLM,'Label',['    Maximum Iterations = ',num2str(get(handles.MaxIterLM,'Userdata'))]);
446
447% --------------------------------------------------------------------
448function varargout = ScaledLevenbergMarquardt_Callback(h, eventdata, handles, varargin)
449set(handles.GaussNewton,             'Checked','off');
450set(handles.GaussNewtonWithCost,     'Checked','off');
451set(handles.LevenbergMarquardt,      'Checked','off');
452set(handles.ScaledLevenbergMarquardt,'Checked','on');
453set(handles.CostScaleFactor, 'Enable','off');
454set(handles.LambdaLM,        'Enable','on');
455set(handles.MaxIterLM,       'Enable','on');
456
457%set(handles.LambdaLM, 'Label',['    Lambda = ',            num2str(get(handles.LambdaLM, 'Userdata'))]);
458%set(handles.MaxIterLM,'Label',['    Maximum Iterations = ',num2str(get(handles.MaxIterLM,'Userdata'))]);
459
460
461% --------------------------------------------------------------------
462function varargout = CostScaleFactor_Callback(h, eventdata, handles, varargin)
463
464CostScaleFactor = get(handles.CostScaleFactor,'Userdata');
465if isempty(CostScaleFactor)
466    CostScaleFactor = 1;
467end
468
469AnswerString = inputdlg({'CostScaleFactor (Levenberg-Marquardt):'},'LOCO',1,{num2str(CostScaleFactor)});
470if ~isempty(AnswerString);
471    CostScaleFactor = str2num(AnswerString{1});
472    set(handles.CostScaleFactor, 'Label', ['    Cost Scale Factor = ',num2str(CostScaleFactor)]);
473    set(handles.CostScaleFactor, 'Userdata', CostScaleFactor);
474end
475
476% --------------------------------------------------------------------
477function varargout = LambdaLM_Callback(h, eventdata, handles, varargin)
478
479LambdaLM = get(handles.LambdaLM,'Userdata');
480if isempty(LambdaLM)
481    LambdaLM = .001;
482end
483
484AnswerString = inputdlg({'Lambda (Levenberg-Marquardt):'},'LOCO',1,{num2str(LambdaLM)});
485if ~isempty(AnswerString);
486    LambdaLM = str2num(AnswerString{1});
487    set(handles.LambdaLM, 'Label', ['    Lambda = ',num2str(LambdaLM)]);
488    set(handles.LambdaLM, 'Userdata', LambdaLM);
489end
490
491
492% --------------------------------------------------------------------
493function varargout = MaxIterLM_Callback(h, eventdata, handles, varargin)
494MaxIterLM = get(handles.MaxIterLM, 'Userdata');
495if isempty(MaxIterLM)
496    MaxIterLM = 10;
497end
498
499AnswerString = inputdlg({'Maximum Iterations (Levenberg-Marquardt):'},'LOCO',1,{num2str(MaxIterLM)});
500if ~isempty(AnswerString);
501    MaxIterLM = ceil(str2num(AnswerString{1}));
502    set(handles.MaxIterLM, 'Label', ['   Maximum Iterations = ',num2str(MaxIterLM)]);
503    set(handles.MaxIterLM, 'Userdata', MaxIterLM);
504end
505
506
507% --------------------------------------------------------------------
508function varargout = PlotIteration_Callback(h, eventdata, handles, varargin)
509MenuAxes_Callback(handles.PlotMenu1);
510MenuAxes_Callback(handles.PlotMenu2);
511
512
513% --------------------------------------------------------------------
514function varargout = OpenFile_Callback(h, eventdata, handles, varargin)
515
516% Get filename and try to load
517%FileName = deblank(get(h,'String'));
518[FileName, PathName] = uigetfile({'*.*'}, 'Choose the desired loco data file');
519if isequal(FileName,0) || isequal(PathName,0)
520    return
521end
522
523set(gcbf,'Pointer','watch');
524
525axes(findobj(gcbf,'Tag','Axes1'));
526cla
527set(gca, 'UIContextMenu', []);   % Clear content menu
528set(gca,'XTick',[]); set(gca,'YTick',[]); cla; title(' '); xlabel(' '); ylabel(' ');
529axes(findobj(gcbf,'Tag','Axes2'));
530cla
531set(gca, 'UIContextMenu', []);  % Clear content menu
532set(gca,'XTick',[]); set(gca,'YTick',[]); cla; title(' '); xlabel(' '); ylabel(' ');
533
534try
535    idot = find(FileName=='.');
536   
537    % If the variable exist as a matlab script file, just read it
538    if strcmp(FileName(idot:end),'.m')
539        % Convert .m file to a .mat file
540        PresentDirectory = pwd;
541        cd(PathName);
542        eval(FileName(1:end-2));
543        cd(PresentDirectory);
544        FileName = [PathName,FileName,'at'];   % Make a mat file
545        save(FileName, 'LocoModel', 'FitParameters', 'BPMData', 'CMData', 'RINGData', 'LocoMeasData', 'LocoFlags');
546    elseif strcmp(FileName(idot:end),'.mat')
547        % .mat file
548        FileName = [PathName, FileName];
549        %load(FileName);
550    else
551        fprintf('   File must be of type .mat or .m.\n');
552        error('  ');
553    end
554catch
555    fprintf('   File open problem\n');
556    axes(findobj(gcbf,'Tag','Axes1'));
557    cla;
558    axes(findobj(gcbf,'Tag','Axes2'));
559    cla;
560    set(gcbf,'Pointer','arrow');
561    return
562end
563
564% Check the file then reload
565try
566    [BPMData, CMData, LocoMeasData, LocoModel, FitParameters, LocoFlags, RINGData] = locofilecheck(FileName);
567    %[BPMData, CMData, LocoMeasData, LocoModel, FitParameters, LocoFlags, RINGData] = locofilecheck({BPMData, CMData, LocoMeasData, LocoModel, FitParameters, LocoFlags, RINGData});
568    %save(FileName, 'LocoModel', 'FitParameters', 'BPMData', 'CMData', 'RINGData', 'LocoMeasData', 'LocoFlags');
569    setappdata(gcbf, 'LocoDataCell', {BPMData, CMData, LocoMeasData, LocoModel, FitParameters, LocoFlags, RINGData});
570catch
571    fprintf('   File open problem.\n');
572    axes(findobj(gcbf,'Tag','Axes1'));
573    cla;
574    axes(findobj(gcbf,'Tag','Axes2'));
575    cla;
576    fprintf('%s\n', lasterr);   
577    set(gcbf,'Pointer','arrow');
578    return
579end
580
581set(findobj(gcbf,'Tag','FileName'),'Userdata',FileName);
582set(gcbf,'Name',['LOCO:  ',FileName]);
583
584set(findobj(gcbf,'Tag','PlotIteration'),'String',num2str([0:length(CMData)-1]'));
585set(findobj(gcbf,'Tag','PlotIteration'),'Value', length(CMData));
586set(findobj(gcbf,'Tag','StartFrom'),'String',num2str([0:length(CMData)-1]'));
587set(findobj(gcbf,'Tag','StartFrom'),'Value',length(CMData));
588
589set(findobj(gcbf,'Tag','HBPMIndex'), 'Userdata', []);
590set(findobj(gcbf,'Tag','VBPMIndex'), 'Userdata', []);
591set(findobj(gcbf,'Tag','HCMIndex'), 'Userdata', []);
592set(findobj(gcbf,'Tag','VCMIndex'), 'Userdata', []);
593
594
595% Force plot #2 and #3 to avoid an error with response matrix plots which cache the filename
596StringCell = get(handles.PlotMenu1,'String');
597StringNumber = get(handles.PlotMenu1,'Value');
598if ~isempty(strfind('response matrix',lower(StringCell{StringNumber})))
599    set(handles.PlotMenu1,'Value', 2);
600end
601StringCell = get(handles.PlotMenu2,'String');
602StringNumber = get(handles.PlotMenu2,'Value');
603if ~isempty(strfind('response matrix',lower(StringCell{StringNumber})))
604    set(handles.PlotMenu2,'Value', 3);
605end
606MenuAxes_Callback(findobj(gcbf,'Tag','PlotMenu1'), 1);
607MenuAxes_Callback(findobj(gcbf,'Tag','PlotMenu2'), 1);
608
609% Update menu items
610setmenuinputs(BPMData(end), CMData(end), LocoFlags(end), FitParameters(end), handles);
611
612set(gcbf,'Pointer','arrow');
613
614
615% --------------------------------------------------------------------
616function varargout = SVDDataSave_Callback(h, eventdata, handles, varargin)
617
618if strcmpi((get(findobj(gcbf,'Tag','SVD_FileName'),'Checked')), 'on')
619    set(findobj(gcbf,'Tag','SVD_FileName'),'Checked','Off');
620    set(findobj(gcbf,'Tag','SVD_FileName'),'Label',['Save A,S,V,U,CovFit to File']);
621    set(findobj(gcbf,'Tag','SVD_FileName'),'Userdata',[]);   
622else
623    [FileName, PathName] = uiputfile('*.mat', 'SVD data file name');
624    if isequal(FileName,0) || isequal(PathName,0)
625        set(findobj(gcbf,'Tag','SVD_FileName'),'Checked','Off');
626        set(findobj(gcbf,'Tag','SVD_FileName'),'Label',['Save A,S,V,U,CovFit to File']);
627        return
628    end
629    FileName = [PathName,FileName];
630    set(findobj(gcbf,'Tag','SVD_FileName'),'Checked','On');
631    set(findobj(gcbf,'Tag','SVD_FileName'),'Label',['Save A,S,V,U,CovFit to File: ', FileName]);
632    set(findobj(gcbf,'Tag','SVD_FileName'),'Userdata',FileName);
633end
634
635
636% --------------------------------------------------------------------
637function varargout = Diary_Callback(h, eventdata, handles, varargin)
638
639if strcmpi((get(findobj(gcbf,'Tag','Diary'),'Checked')), 'on')
640    set(findobj(gcbf,'Tag','Diary'),'Checked','Off');
641    set(findobj(gcbf,'Tag','Diary'),'Label','Diary');
642    set(findobj(gcbf,'Tag','Diary'),'Userdata',[]);
643    diary off
644else
645    [FileName, PathName] = uiputfile('*.*', 'Diary file name');
646    if isequal(FileName,0) || isequal(PathName,0)
647        set(findobj(gcbf,'Tag','Diary'),'Checked','Off');
648        set(findobj(gcbf,'Tag','Diary'),'Label','Diary');
649        return
650    end
651    FileName = [PathName,FileName];
652    set(findobj(gcbf,'Tag','Diary'),'Checked','On');
653    set(findobj(gcbf,'Tag','Diary'),'Label',['Diary: ', FileName]);
654    set(findobj(gcbf,'Tag','Diary'),'Userdata',FileName);
655    diary(FileName);
656end
657
658
659% --------------------------------------------------------------------
660function varargout = NewMeasRespMat_Callback(h, eventdata, handles, varargin)
661FileName = get(findobj(gcbf,'Tag','FileName'),'Userdata');
662if isempty(FileName)
663    fprintf('   LOCO data file does not exist (use File->Open).\n');
664    return
665end
666
667% Get response matrix filename and try to load
668fprintf('\n');
669[FileNameMeas, PathNameMeas] = uigetfile('*.mat', 'New LOCO response mastrix data file name');
670if isequal(FileNameMeas,0) || isequal(PathNameMeas,0)
671    fprintf('   Measured response data file does not exist.\n\n');
672    return
673end
674try
675    load(FileNameMeas);   
676    %if ~exist('LocoMeasData','var')
677    %    fprintf('   LocoMeasData variable does not exist.\n');
678    %    return
679    %end
680    if exist('LocoMeasData','var')
681        fprintf('   LocoMeasData will be replaced\n');
682    end
683    if exist('BPMData','var')
684        fprintf('   BPMData will be replaced\n');
685    end
686    if exist('CMData','var')
687        fprintf('   CMData will be replaced\n');
688    end
689    if exist('FitParameters','var')
690        fprintf('   FitParameters will be replaced\n');
691    end
692    if exist('LocoFlags','var')
693        fprintf('   LocoFlags will be replaced\n');
694    end
695    if exist('RINGData','var')
696        fprintf('   RINGData will be replaced\n');
697    end
698    %if exist('LocoModel','var')
699    %    fprintf('   LocoModel will be replaced\n');
700    %end
701catch
702    fprintf('   Measured response data file does not exist or is not a *.mat file type\n\n');
703    return
704end
705
706AllExistFlag = (exist('LocoMeasData','var') & exist('BPMData','var') & exist('CMData','var') & exist('LocoModel','var') & exist('FitParameters','var') & exist('LocoFlags','var') & exist('RINGData','var'));
707NoneExistFlag = (~exist('LocoMeasData','var') & ~exist('BPMData','var') & ~exist('CMData','var') & ~exist('LocoModel','var') & ~exist('FitParameters','var') & ~exist('LocoFlags','var') & ~exist('RINGData','var'));
708
709if NoneExistFlag
710    fprintf('   No LOCO variable found in this file\n\n');
711    return;
712end
713
714fprintf('   LocoModel will be recomputed\n');
715if AllExistFlag
716    % Replace all variables (just like a OPEN)
717else
718    % Get filename and try to load
719    try
720        load(FileName);
721    catch
722        fprintf('   LOCO file does not exist or is not a *.mat file type\n\n');
723        cla;
724        return
725    end
726   
727    % Which iteration do you want to associate the measured response matrix with
728    if length(CMData) > 1
729        for i = 1:length(CMData)
730            NumList{i} = num2str(i-1);
731        end
732        IterNum = menu({'Which iteration # do you want the ','new data associated with?'}, NumList);
733        if IterNum == 0
734            fprintf('   No change made to the measured response matrix\n\n');
735            return
736        end
737    else
738        IterNum = 1;
739    end
740   
741    FitParameters = FitParameters(IterNum);
742    BPMData = BPMData(IterNum);
743    CMData = CMData(IterNum);
744    %LocoModel = LocoModel(IterNum);
745    LocoFlags = LocoFlags(IterNum);
746end
747
748% Write over with the new data
749load(FileNameMeas);   
750
751
752% Double check length of new variables (should be one if adding new variables)
753if ~AllExistFlag
754    if length(CMData) > 1
755        for i = 1:length(CMData)
756            NumList{i} = num2str(i-1);
757        end
758        IterNum = menu({'New data has more than one iteration #','Which iteration do you want to use?'}, NumList);
759        if IterNum == 0
760            fprintf('   No change made to the LOCO input file.\n');
761            return
762        end
763       
764        NewFileFlag = questdlg({sprintf('Only iteration #%d will be saved.',IterNum-1),'Do you want to change the LOCO file name?'},'New Response Matrix','Yes','No','No');
765        if strcmp(NewFileFlag,'Yes')
766            [FileName, PathName] = uiputfile('*.mat', 'New LOCO data file name');
767            if isequal(FileName,0) || isequal(PathName,0)
768                axes(findobj(gcbf,'Tag','Axes1'));
769                cla;
770                axes(findobj(gcbf,'Tag','Axes2'));
771                cla;
772                return
773            end
774            FileName = [PathName,FileName];
775        end
776    else
777        IterNum = 1;
778    end
779   
780    FitParameters = FitParameters(IterNum);
781    BPMData = BPMData(IterNum);
782    CMData = CMData(IterNum);
783    %LocoModel = LocoModel(IterNum);
784    LocoFlags = LocoFlags(IterNum);
785end
786
787try
788    LocoModel = [];   % Clear the model because the RINGData, BPMData, or CMData may be different
789    [BPMData, CMData, LocoMeasData, LocoModel, FitParameters, LocoFlags, RINGData] = locofilecheck({BPMData, CMData, LocoMeasData, LocoModel, FitParameters, LocoFlags, RINGData});
790catch
791    fprintf('   There were problems with the input file, so no changes were made.\n');
792    return
793end
794
795fprintf('\n');
796
797save(FileName, 'LocoModel', 'FitParameters', 'BPMData', 'CMData', 'RINGData', 'LocoMeasData', 'LocoFlags');
798setappdata(gcbf, 'LocoDataCell', {BPMData, CMData, LocoMeasData, LocoModel, FitParameters, LocoFlags, RINGData});
799
800set(findobj(gcbf,'Tag','FileName'),'Userdata',FileName);
801set(gcbf,'Name',['LOCO:  ',FileName]);
802
803set(findobj(gcbf,'Tag','HBPMIndex'), 'Userdata', []);
804set(findobj(gcbf,'Tag','VBPMIndex'), 'Userdata', []);
805set(findobj(gcbf,'Tag','HCMIndex'), 'Userdata', []);
806set(findobj(gcbf,'Tag','VCMIndex'), 'Userdata', []);
807
808set(findobj(gcbf,'Tag','PlotIteration'),'String',num2str([0:length(CMData)-1]'));
809set(findobj(gcbf,'Tag','PlotIteration'),'Value', length(CMData));
810set(findobj(gcbf,'Tag','StartFrom'),'String',num2str([0:length(CMData)-1]'));
811set(findobj(gcbf,'Tag','StartFrom'),'Value',length(CMData));
812
813MenuAxes_Callback(findobj(gcbf,'Tag','PlotMenu1'));
814MenuAxes_Callback(findobj(gcbf,'Tag','PlotMenu2'));
815
816
817% --------------------------------------------------------------------
818function varargout = SaveAs_Callback(h, eventdata, handles, varargin)
819
820% Get filename and try to load
821FileName = get(findobj(gcbf,'Tag','FileName'),'Userdata');
822if isempty(FileName)
823    fprintf('   Old data file does not exist.\n');
824    return
825end
826try
827    load(FileName);
828catch
829    fprintf('   Old data file does not exist or is not a *.mat file type.\n');
830    cla;
831    return
832end
833
834if strcmp(get(h,'Tag'),'SaveAsLastIteration')
835    if length(CMData) > 1
836        for i = 1:length(CMData)
837            NumList{i} = num2str(i-1);
838        end
839       
840        IterNum = menu('Which iteration #', NumList);
841        if IterNum == 0
842            fprintf('   Save aborted.\n');
843            return
844        end
845
846        % Always keep the first iteration
847        if IterNum ~= 1
848            IterNum = [1 IterNum];
849        end
850       
851        FitParameters = FitParameters(IterNum);
852        BPMData = BPMData(IterNum);
853        CMData = CMData(IterNum);
854        LocoModel = LocoModel(IterNum);
855        LocoFlags = LocoFlags(IterNum);
856    end
857end
858
859[FileName, PathName] = uiputfile('*.mat', 'Loco data file name');
860if isequal(FileName,0) || isequal(PathName,0)
861    axes(findobj(gcbf,'Tag','Axes1'));
862    cla;
863    axes(findobj(gcbf,'Tag','Axes2'));
864    cla;
865    return
866end
867FileName = [PathName,FileName];
868
869save(FileName, 'LocoModel', 'FitParameters', 'BPMData', 'CMData', 'RINGData', 'LocoMeasData', 'LocoFlags');
870setappdata(gcbf, 'LocoDataCell', {BPMData, CMData, LocoMeasData, LocoModel, FitParameters, LocoFlags, RINGData});
871
872set(findobj(gcbf,'Tag','FileName'),'Userdata',FileName);
873set(gcbf,'Name',['LOCO:  ',FileName]);
874
875set(findobj(gcbf,'Tag','PlotIteration'),'String',num2str([0:length(CMData)-1]'));
876set(findobj(gcbf,'Tag','PlotIteration'),'Value', length(CMData));
877set(findobj(gcbf,'Tag','StartFrom'),'String',num2str([0:length(CMData)-1]'));
878set(findobj(gcbf,'Tag','StartFrom'),'Value',length(CMData));
879
880MenuAxes_Callback(findobj(gcbf,'Tag','PlotMenu1'));
881MenuAxes_Callback(findobj(gcbf,'Tag','PlotMenu2'));
882
883
884% --------------------------------------------------------------------
885function varargout = MenuUserInput_Callback(h, eventdata, handles, varargin)
886AnswerString=inputdlg({'Which singular values:'},'LOCO',1,{sprintf('[%d:1]',1)});
887if ~isempty(AnswerString);
888    Ivec = str2num(AnswerString{1});
889    set(findobj(gcbf,'Tag','UserInput'),'Userdata',Ivec);
890    set(findobj(gcbf,'Tag','UserInput'),'Checked','on');
891    set(findobj(gcbf,'Tag','Rank'),'Checked','off');
892    set(findobj(gcbf,'Tag','Threshold'),'Checked','off');
893    set(findobj(gcbf,'Tag','Interactive'),'Checked','off');
894end
895
896% --------------------------------------------------------------------
897function varargout = MenuThreshold_Callback(h, eventdata, handles, varargin)
898Threshold = get(findobj(gcbf,'Tag','Threshold'),'Userdata');
899
900AnswerString=inputdlg({'Threshold:'},'LOCO',1,{num2str(Threshold)});
901if ~isempty(AnswerString);
902    Threshold = str2num(AnswerString{1});
903    set(findobj(gcbf,'Tag','Threshold'),'Label',['Threshold (',num2str(Threshold),')']);
904    set(findobj(gcbf,'Tag','Threshold'),'Userdata',Threshold);
905    set(findobj(gcbf,'Tag','UserInput'),'Checked','off');
906    set(findobj(gcbf,'Tag','Rank'),'Checked','off');
907    set(findobj(gcbf,'Tag','Threshold'),'Checked','on');
908    set(findobj(gcbf,'Tag','Interactive'),'Checked','off');
909end
910
911% --------------------------------------------------------------------
912function varargout = Outlier_Callback(h, eventdata, handles, varargin)
913OutlierFactor = get(findobj(gcbf,'Tag','Outlier'),'Userdata');
914
915AnswerString=inputdlg({'Outlier Factor: enter the # of sigma'},'LOCO',1,{num2str(OutlierFactor)});
916if ~isempty(AnswerString)
917    OutlierFactor = str2num(AnswerString{1});
918    set(findobj(gcbf,'Tag','Outlier'),'Label',['Outlier Rejection (',num2str(OutlierFactor),' sigma)']);
919    set(findobj(gcbf,'Tag','Outlier'),'Userdata', OutlierFactor);
920    set(findobj(gcbf,'Tag','Outlier'),'Checked', 'on');
921end
922
923
924% --------------------------------------------------------------------
925function varargout = HorizontalDispersion_Callback(h, eventdata, handles, varargin)
926HorizontalDispersionWeight = getappdata(gcbf, 'HorizontalDispersionWeight');
927
928AnswerString = inputdlg({'Horizontal Dispersion Weight'},'LOCO',1,{num2str(HorizontalDispersionWeight)});
929if ~isempty(AnswerString)
930    HorizontalDispersionWeight = abs(str2num(AnswerString{1}));
931    set(findobj(gcbf,'Tag','HorizontalDispersionWeight'),'Label', sprintf('    Weigh for Horizontal Dispersion = %f', HorizontalDispersionWeight));
932    setappdata(gcbf,'HorizontalDispersionWeight', HorizontalDispersionWeight);
933end
934
935% --------------------------------------------------------------------
936function varargout = VerticalDispersion_Callback(h, eventdata, handles, varargin)
937VerticalDispersionWeight = getappdata(gcbf, 'VerticalDispersionWeight');
938
939AnswerString = inputdlg({'Vertical Dispersion Weight'},'LOCO',1,{num2str(VerticalDispersionWeight)});
940if ~isempty(AnswerString)
941    VerticalDispersionWeight = abs(str2num(AnswerString{1}));
942    set(findobj(gcbf,'Tag','VerticalDispersionWeight'),'Label', sprintf('    Weigh for Vertical     Dispersion = %f', VerticalDispersionWeight));
943    setappdata(gcbf,'VerticalDispersionWeight', VerticalDispersionWeight);
944end
945
946
947% --------------------------------------------------------------------
948function varargout = HBPMIndex_Callback(h, eventdata, handles, varargin)
949
950LocoDataCell = getappdata(gcbf, 'LocoDataCell');
951if isempty(LocoDataCell)
952    FileName = get(findobj(gcbf,'Tag','FileName'),'Userdata');
953    if isempty(FileName)
954        fprintf('   File does not exist.\n');
955        return
956    end
957    try
958        load(FileName);
959    catch
960        fprintf('   File does not exist or is not a *.mat file type.\n');
961        cla;
962        return
963    end
964else
965    BPMData = LocoDataCell{1};
966end
967
968StartFrom = get(findobj(gcbf,'Tag','StartFrom'),'Value');
969
970if isempty(get(findobj(gcbf,'Tag','HBPMIndex'), 'Userdata'))
971    Index = BPMData(StartFrom).HBPMGoodDataIndex;
972else
973    Index = get(findobj(gcbf,'Tag','HBPMIndex'), 'Userdata');
974end
975
976Checked = zeros(size(BPMData(StartFrom).HBPMIndex));
977Checked(Index) = 1;
978
979tmp = BPMData(StartFrom).BPMIndex(BPMData(StartFrom).HBPMIndex);
980Index = locoeditlist([(1:length(BPMData(StartFrom).HBPMIndex))' tmp(:)], 'BPM', Checked);
981Index = Index(:,1);
982
983set(findobj(gcbf,'Tag','HBPMIndex'), 'Userdata', Index);
984
985% --------------------------------------------------------------------
986function varargout = VBPMIndex_Callback(h, eventdata, handles, varargin)
987
988LocoDataCell = getappdata(gcbf, 'LocoDataCell');
989if isempty(LocoDataCell)
990    FileName = get(findobj(gcbf,'Tag','FileName'),'Userdata');
991    if isempty(FileName)
992        fprintf('   File does not exist.\n');
993        return
994    end
995    try
996        load(FileName);
997    catch
998        fprintf('   File does not exist or is not a *.mat file type.\n');
999        cla;
1000        return
1001    end
1002else
1003    BPMData = LocoDataCell{1};
1004end
1005
1006StartFrom = get(findobj(gcbf,'Tag','StartFrom'),'Value');
1007
1008if isempty(get(findobj(gcbf,'Tag','VBPMIndex'), 'Userdata'))
1009    Index = BPMData(StartFrom).VBPMGoodDataIndex;
1010else
1011    Index = get(findobj(gcbf,'Tag','VBPMIndex'), 'Userdata');
1012end
1013
1014Checked = zeros(size(BPMData(StartFrom).VBPMIndex));
1015Checked(Index) = 1;
1016
1017tmp = BPMData(StartFrom).BPMIndex(BPMData(StartFrom).VBPMIndex);
1018Index = locoeditlist([(1:length(BPMData(StartFrom).VBPMIndex))' tmp(:)], 'BPM', Checked);
1019Index = Index(:,1);
1020
1021set(findobj(gcbf,'Tag','VBPMIndex'), 'Userdata', Index);
1022
1023
1024% --------------------------------------------------------------------
1025function varargout = HCMIndex_Callback(h, eventdata, handles, varargin)
1026
1027LocoDataCell = getappdata(gcbf, 'LocoDataCell');
1028if isempty(LocoDataCell)
1029    FileName = get(findobj(gcbf,'Tag','FileName'),'Userdata');
1030    if isempty(FileName)
1031        fprintf('   File does not exist.\n');
1032        return
1033    end
1034    try
1035        load(FileName);
1036    catch
1037        fprintf('   File does not exist or is not a *.mat file type.\n');
1038        cla;
1039        return
1040    end
1041else
1042    CMData = LocoDataCell{2};
1043end
1044
1045StartFrom = get(findobj(gcbf,'Tag','StartFrom'),'Value');
1046
1047if isempty(get(findobj(gcbf,'Tag','HCMIndex'), 'Userdata'))
1048    Index = CMData(StartFrom).HCMGoodDataIndex;
1049else
1050    Index = get(findobj(gcbf,'Tag','HCMIndex'), 'Userdata');
1051end
1052
1053Checked = zeros(size(CMData(StartFrom).HCMIndex));
1054Checked(Index) = 1;
1055
1056Index = locoeditlist([(1:length(CMData(StartFrom).HCMIndex))'  CMData(StartFrom).HCMIndex(:)], 'HCM', Checked);
1057Index = Index(:,1);
1058
1059set(findobj(gcbf,'Tag','HCMIndex'), 'Userdata', Index);
1060
1061
1062% --------------------------------------------------------------------
1063function varargout = VCMIndex_Callback(h, eventdata, handles, varargin)
1064
1065LocoDataCell = getappdata(gcbf, 'LocoDataCell');
1066if isempty(LocoDataCell)
1067    FileName = get(findobj(gcbf,'Tag','FileName'),'Userdata');
1068    if isempty(FileName)
1069        fprintf('   File does not exist.\n');
1070        return
1071    end
1072    try
1073        load(FileName);
1074    catch
1075        fprintf('   File does not exist or is not a *.mat file type.\n');
1076        cla;
1077        return
1078    end
1079else
1080    CMData = LocoDataCell{2};
1081end
1082
1083StartFrom = get(findobj(gcbf,'Tag','StartFrom'),'Value');
1084
1085if isempty(get(findobj(gcbf,'Tag','VCMIndex'), 'Userdata'))
1086    Index = CMData(StartFrom).VCMGoodDataIndex;
1087else
1088    Index = get(findobj(gcbf,'Tag','VCMIndex'), 'Userdata');
1089end
1090
1091Checked = zeros(size(CMData(StartFrom).VCMIndex));
1092Checked(Index) = 1;
1093
1094Index = locoeditlist([(1:length(CMData(StartFrom).VCMIndex))'  CMData(StartFrom).VCMIndex(:)], 'VCM', Checked);
1095Index = Index(:,1);
1096
1097set(findobj(gcbf,'Tag','VCMIndex'), 'Userdata', Index);
1098
1099
1100% --------------------------------------------------------------------
1101function varargout = StartFrom_Callback(h, eventdata, handles, varargin)
1102LocoDataCell = getappdata(gcbf, 'LocoDataCell');
1103if isempty(LocoDataCell)
1104    FileName = get(findobj(gcbf,'Tag','FileName'),'Userdata');
1105    if isempty(FileName)
1106        fprintf('   File does not exist.\n');
1107        return
1108    end
1109    try
1110        load(FileName);
1111    catch
1112        fprintf('   File does not exist or is not a *.mat file type.\n');
1113        cla;
1114        return
1115    end
1116else
1117    BPMData       = LocoDataCell{1};
1118    CMData        = LocoDataCell{2};
1119    FitParameters = LocoDataCell{5};
1120    LocoFlags     = LocoDataCell{6};
1121end
1122
1123StartFrom = get(findobj(gcbf,'Tag','StartFrom'),'Value') + 1;
1124StartFromSize = size(get(findobj(gcbf,'Tag','StartFrom'),'String'),1);
1125if StartFrom > StartFromSize
1126    StartFrom = StartFromSize;
1127end
1128setmenuinputs(BPMData(StartFrom), CMData(StartFrom), LocoFlags(StartFrom), FitParameters(StartFrom), handles);
1129
1130
1131% --------------------------------------------------------------------
1132function setmenuinputs(BPMData, CMData, LocoFlags, FitParameters, handles)
1133
1134% Set BPM Indexes
1135set(findobj(gcbf,'Tag','HBPMIndex'), 'Userdata', BPMData.HBPMGoodDataIndex);
1136set(findobj(gcbf,'Tag','VBPMIndex'), 'Userdata', BPMData.VBPMGoodDataIndex);
1137set(findobj(gcbf,'Tag','HCMIndex'),  'Userdata', CMData.HCMGoodDataIndex);
1138set(findobj(gcbf,'Tag','VCMIndex'),  'Userdata', CMData.VCMGoodDataIndex);
1139
1140
1141% Set flags
1142set(findobj(gcbf,'Tag','Rank'),       'Checked','Off');
1143set(findobj(gcbf,'Tag','Threshold'),  'Checked','Off');
1144set(findobj(gcbf,'Tag','Interactive'),'Checked','Off');
1145set(findobj(gcbf,'Tag','UserInput'),  'Checked','Off');
1146set(findobj(gcbf,'Tag','Threshold'),  'Checked','Off');
1147if strcmpi((LocoFlags.SVmethod),'rank')
1148    set(findobj(gcbf,'Tag','Rank'),'Checked','On');
1149elseif length(LocoFlags.SVmethod) > 1
1150    set(findobj(gcbf,'Tag','UserInput'),'Userdata',LocoFlags.SVmethod);
1151    set(findobj(gcbf,'Tag','UserInput'),'Checked','On');
1152elseif  length(LocoFlags.SVmethod) == 1
1153    set(findobj(gcbf,'Tag','Threshold'),'Checked','On');
1154elseif  isempty(LocoFlags.SVmethod)
1155    set(findobj(gcbf,'Tag','Interactive'),'Checked','On');
1156else
1157    set(findobj(gcbf,'Tag','Threshold'),'Checked','On');   
1158end
1159
1160set(findobj(gcbf,'Tag','Threshold'),'Userdata', LocoFlags.Threshold);
1161set(findobj(gcbf,'Tag','Threshold'),'Label',['Threshold (',num2str(LocoFlags.Threshold),')']);
1162
1163set(findobj(gcbf,'Tag','Outlier'),'Userdata',LocoFlags.OutlierFactor);
1164set(findobj(gcbf,'Tag','Outlier'),'Label',['Outlier Rejection (',num2str(LocoFlags.OutlierFactor),' sigma)']);
1165
1166setappdata(gcbf,'HorizontalDispersionWeight', LocoFlags.HorizontalDispersionWeight);
1167set(findobj(gcbf,'Tag','HorizontalDispersionWeight'),'Label', sprintf('    Weight for Horizontal Dispersion = %f', LocoFlags.HorizontalDispersionWeight));
1168
1169setappdata(gcbf,'VerticalDispersionWeight', LocoFlags.VerticalDispersionWeight);
1170set(findobj(gcbf,'Tag','VerticalDispersionWeight'),'Label', sprintf('    Weight for Vertical     Dispersion = %f', LocoFlags.VerticalDispersionWeight));
1171
1172if ischar(LocoFlags.Coupling)
1173    if strcmpi((LocoFlags.Coupling),'yes')
1174        set(findobj(gcbf,'Tag','Coupling'),'Checked','On');
1175    else
1176        set(findobj(gcbf,'Tag','Coupling'),'Checked','Off');
1177    end
1178end
1179
1180if ischar(LocoFlags.AutoCorrectDelta)
1181    if strcmpi((LocoFlags.AutoCorrectDelta),'yes')
1182        set(findobj(gcbf,'Tag','AutoCorrect'),'Checked','On');
1183    else
1184        set(findobj(gcbf,'Tag','AutoCorrect'),'Checked','Off');
1185    end
1186end
1187
1188if ischar(LocoFlags.Normalization.Flag)
1189    if strcmpi((LocoFlags.Normalization.Flag),'yes')
1190        set(findobj(gcbf,'Tag','Normalize'),'Checked','On');
1191    else
1192        set(findobj(gcbf,'Tag','Normalize'),'Checked','Off');
1193    end
1194end
1195
1196if ischar(LocoFlags.Dispersion)
1197    if strcmpi((LocoFlags.Dispersion),'yes')
1198        set(findobj(gcbf,'Tag','Dispersion'),'Checked','On');
1199    else
1200        set(findobj(gcbf,'Tag','Dispersion'),'Checked','Off');
1201    end
1202end
1203
1204if ischar(CMData.FitHCMEnergyShift)
1205    if strcmpi((CMData.FitHCMEnergyShift),'yes')
1206        set(findobj(gcbf,'Tag','FitHCMEnergyShift'),'Checked','On');
1207    else
1208        set(findobj(gcbf,'Tag','FitHCMEnergyShift'),'Checked','Off');
1209    end
1210end
1211
1212if ischar(CMData.FitVCMEnergyShift)
1213    if strcmpi((CMData.FitVCMEnergyShift),'yes')
1214        set(findobj(gcbf,'Tag','FitVCMEnergyShift'),'Checked','On');
1215    else
1216        set(findobj(gcbf,'Tag','FitVCMEnergyShift'),'Checked','Off');
1217    end
1218end
1219
1220if ischar(LocoFlags.ResponseMatrixCalculator)
1221    if strcmpi((LocoFlags.ResponseMatrixCalculator),'linear')
1222        set(findobj(gcbf,'Tag','Linear'),'Checked','On');
1223        set(findobj(gcbf,'Tag','Full'),'Checked','Off');
1224    else %strcmpi((LocoFlags.ResponseMatrixCalculator),'full')
1225        set(findobj(gcbf,'Tag','Linear'),'Checked','Off');
1226        set(findobj(gcbf,'Tag','Full'),'Checked','On');
1227    end
1228end
1229
1230if ischar(LocoFlags.ClosedOrbitType)
1231    if strcmpi((LocoFlags.ClosedOrbitType),'fixedmomentum')
1232        set(findobj(gcbf,'Tag','CM'),'Checked','On');
1233        set(findobj(gcbf,'Tag','CPL'),'Checked','Off');
1234    else %strcmpi((LocoFlags.ClosedOrbitType),'fixedpathlength')
1235        set(findobj(gcbf,'Tag','CM'),'Checked','Off');
1236        set(findobj(gcbf,'Tag','CPL'),'Checked','On');
1237    end
1238end
1239   
1240if ischar(LocoFlags.ResponseMatrixMeasurement)
1241    if strcmpi((LocoFlags.ResponseMatrixMeasurement),'bidirectional')
1242        set(findobj(gcbf,'Tag','RespMatBiDirectional'),'Checked','On');
1243        set(findobj(gcbf,'Tag','RespMatOneWay'),'Checked','Off');
1244    else %strcmpi((LocoFlags.ResponseMatrixMeasurement),'oneway')
1245        set(findobj(gcbf,'Tag','RespMatBiDirectional'),'Checked','Off');
1246        set(findobj(gcbf,'Tag','RespMatOneWay'),'Checked','On');
1247    end
1248end
1249
1250if ischar(LocoFlags.DispersionMeasurement)
1251    if strcmpi((LocoFlags.DispersionMeasurement),'bidirectional')
1252        set(findobj(gcbf,'Tag','DispBiDirectional'),'Checked','On');
1253        set(findobj(gcbf,'Tag','DispOneWay'),'Checked','Off');
1254    else %strcmpi((LocoFlags.DispersionMeasurement),'oneway')
1255        set(findobj(gcbf,'Tag','DispBiDirectional'),'Checked','Off');
1256        set(findobj(gcbf,'Tag','DispOneWay'),'Checked','On');
1257    end
1258end
1259
1260if isfield(LocoFlags, 'CalculateSigma')
1261    if ischar(LocoFlags.CalculateSigma)
1262        if strcmpi(LocoFlags.CalculateSigma, 'Yes')
1263            set(findobj(gcf,'Tag','ErrorBars'),'Checked','on');
1264        else
1265            set(findobj(gcf,'Tag','ErrorBars'),'Checked','off');
1266        end
1267    end
1268end
1269
1270if isfield(LocoFlags, 'SinglePrecision')
1271    if ischar(LocoFlags.SinglePrecision)
1272        if strcmpi(LocoFlags.SinglePrecision, 'Yes')
1273            set(findobj(gcf,'Tag','SinglePrecision'),'Checked','on');
1274        else
1275            set(findobj(gcf,'Tag','SinglePrecision'),'Checked','off');
1276        end
1277    end
1278end
1279
1280if ~isempty(LocoFlags.SVDDataFileName) && ischar(LocoFlags.SVDDataFileName)
1281    set(findobj(gcbf,'Tag','SVD_FileName'),'Checked','On');
1282    set(findobj(gcbf,'Tag','SVD_FileName'),'Userdata',LocoFlags.SVDDataFileName);   
1283    set(findobj(gcbf,'Tag','SVD_FileName'),'Label',['Save A,S,V,U,CovFit to File: ', LocoFlags.SVDDataFileName]);
1284else
1285    set(findobj(gcbf,'Tag','SVD_FileName'),'Checked','Off');
1286    set(findobj(gcbf,'Tag','SVD_FileName'),'Userdata',[]);   
1287    set(findobj(gcbf,'Tag','SVD_FileName'),'Label',['Save A,S,V,U,CovFit to File: ', LocoFlags.SVDDataFileName]);
1288    set(findobj(gcbf,'Tag','SVD_FileName'),'Label',['Save A,S,V,U,CovFit to File']);
1289end
1290
1291if ischar(FitParameters.FitRFFrequency)
1292    if strcmpi((FitParameters.FitRFFrequency),'yes')
1293        set(findobj(gcbf,'Tag','FitRF'),'Checked','On');
1294    else
1295        set(findobj(gcbf,'Tag','FitRF'),'Checked','Off');
1296    end
1297end
1298
1299if ischar(BPMData.FitGains)
1300    if strcmpi((BPMData.FitGains),'yes')
1301        set(findobj(gcbf,'Tag','BPMGains'),'Checked','On');
1302    else
1303        set(findobj(gcbf,'Tag','BPMGains'),'Checked','Off');
1304    end
1305end
1306
1307if ischar(BPMData.FitCoupling)
1308    if strcmpi((BPMData.FitCoupling),'yes')
1309        set(findobj(gcbf,'Tag','BPMCoupling'),'Checked','On');
1310    else
1311        set(findobj(gcbf,'Tag','BPMCoupling'),'Checked','Off');
1312    end
1313end
1314
1315if ischar(CMData.FitKicks)
1316    if strcmpi((CMData.FitKicks),'yes')
1317        set(findobj(gcbf,'Tag','CMKicks'),'Checked','On');
1318    else
1319        set(findobj(gcbf,'Tag','CMKicks'),'Checked','Off');
1320    end
1321end
1322
1323if ischar(CMData.FitCoupling)
1324    if strcmpi((CMData.FitCoupling),'yes')
1325        set(findobj(gcbf,'Tag','CMRolls'),'Checked','On');
1326    else
1327        set(findobj(gcbf,'Tag','CMRolls'),'Checked','Off');
1328    end
1329end
1330
1331if isfield(LocoFlags,'Method')
1332    if strcmpi(LocoFlags.Method.Name, 'Gauss-Newton')
1333        set(handles.GaussNewton,             'Checked','on');
1334        set(handles.GaussNewtonWithCost,     'Checked','off');
1335        set(handles.LevenbergMarquardt,      'Checked','off');
1336        set(handles.ScaledLevenbergMarquardt,'Checked','off');
1337        set(handles.CostScaleFactor, 'Enable','off');
1338        set(handles.LambdaLM,        'Enable','off');
1339        set(handles.MaxIterLM,       'Enable','off');
1340    elseif strcmpi(LocoFlags.Method.Name, 'Gauss-Newton With Cost Function')
1341        set(handles.GaussNewton,             'Checked','off');
1342        set(handles.GaussNewtonWithCost,     'Checked','on');
1343        set(handles.LevenbergMarquardt,      'Checked','off');
1344        set(handles.ScaledLevenbergMarquardt,'Checked','off');
1345        set(handles.CostScaleFactor, 'Enable','on');
1346        set(handles.LambdaLM,        'Enable','off');
1347        set(handles.MaxIterLM,       'Enable','off');
1348    elseif strcmpi(LocoFlags.Method.Name, 'Levenberg-Marquardt')
1349        set(handles.GaussNewton,             'Checked','off');
1350        set(handles.GaussNewtonWithCost,     'Checked','off');
1351        set(handles.LevenbergMarquardt,      'Checked','on');
1352        set(handles.ScaledLevenbergMarquardt,'Checked','off');
1353        set(handles.CostScaleFactor, 'Enable','off');
1354        set(handles.LambdaLM,        'Enable','on');
1355        set(handles.MaxIterLM,       'Enable','on');
1356    elseif strcmpi(LocoFlags.Method.Name, 'Scaled Levenberg-Marquardt')
1357        set(handles.GaussNewton,             'Checked','off');
1358        set(handles.GaussNewtonWithCost,     'Checked','off');
1359        set(handles.LevenbergMarquardt,      'Checked','off');
1360        set(handles.ScaledLevenbergMarquardt,'Checked','on');
1361        set(handles.CostScaleFactor, 'Enable','off');
1362        set(handles.LambdaLM,        'Enable','on');
1363        set(handles.MaxIterLM,       'Enable','on');
1364    end
1365
1366    if isfield(LocoFlags(end),'Method') && isfield(LocoFlags.Method,'Lambda') &&  ~isempty(LocoFlags.Method.Lambda)
1367        set(handles.LambdaLM, 'Userdata', LocoFlags.Method.Lambda);
1368        set(handles.MaxIterLM,'Userdata', LocoFlags.Method.MaxIter);
1369    end
1370    set(handles.LambdaLM, 'Label',['    Lambda = ',num2str(get(handles.LambdaLM, 'Userdata'))]);
1371    set(handles.MaxIterLM,'Label',['    Maximum Iterations = ',num2str(get(handles.MaxIterLM,'Userdata'))]);
1372
1373    if isfield(LocoFlags,'Method') && isfield(LocoFlags.Method,'CostScaleFactor') &&  ~isempty(LocoFlags.Method.CostScaleFactor)
1374        set(handles.CostScaleFactor, 'Userdata', LocoFlags.Method.CostScaleFactor);
1375    end
1376    set(handles.CostScaleFactor, 'Label',['    Cost Scale Factor = ',num2str(get(handles.CostScaleFactor, 'Userdata'))]);
1377end
1378
1379
1380% --------------------------------------------------------------------
1381function varargout = MenuAxes_Callback(h, eventdata, handles, varargin)
1382
1383if nargin > 1
1384    setappdata(gcbf,'OtherParameterPlot1',[]);
1385    setappdata(gcbf,'OtherParameterPlot2',[]);
1386end
1387
1388TagString = get(h,'Userdata');            % Axis tag is storage in the menu pulldown
1389PlotNumber = get(h,'Value');
1390h_axis = findobj(gcbf,'Tag',TagString);
1391axes(h_axis);
1392locoplots(PlotNumber);
1393set(h_axis,'Tag',TagString);                 % axes tag is lost if plot function is used
1394set(h_axis,'HandleVisibility','Callback');   % So no one else can plot to it.
1395%axes(h_axis);
1396%legend
1397%set(gca,'Tag',TagString);                 % axes tag is lost if plot function is used
1398%set(gca,'HandleVisibility','Callback');   % So no one else can plot to it.
1399
1400
1401% -------------------------------------------------------------------
1402function locoplots(PlotNumber, FieldName)
1403
1404% Save the current axes
1405H_Axes = gca;
1406
1407if nargin < 2
1408    FieldName = [];
1409end
1410
1411LocoDataCell = getappdata(gcbf, 'LocoDataCell');
1412if isempty(LocoDataCell)
1413    FileName = get(findobj(gcbf,'Tag','FileName'),'Userdata');
1414    if isempty(FileName)
1415        fprintf('   File does not exist.\n');
1416        return
1417    end
1418    try
1419        load(FileName);
1420    catch
1421        fprintf('   File does not exist or is not a *.mat file type.\n');
1422        cla;
1423        return
1424    end
1425else
1426    BPMData       = LocoDataCell{1};
1427    CMData        = LocoDataCell{2};
1428    LocoMeasData  = LocoDataCell{3};
1429    LocoModel     = LocoDataCell{4};
1430    FitParameters = LocoDataCell{5};
1431    LocoFlags     = LocoDataCell{6};
1432    RINGData      = LocoDataCell{7};
1433end
1434
1435% Get the iteration number to plot
1436i = get(findobj(gcbf,'Tag','PlotIteration'),'Value');  % The first point in the array is starting point
1437
1438
1439% If the LocoModel does not exist, then compute it
1440if isempty(LocoModel(i).M) || isempty(LocoModel(i).ChiSquare)
1441    AxesTag = get(H_Axes,'Tag');
1442    [LocoModel(i).M, LocoModel(i).Eta, LocoModel(i).ChiSquare] = getmodelresponsematrix(BPMData(i), CMData(i), FitParameters(i), LocoFlags(i), LocoMeasData, RINGData);
1443    FileName = get(findobj(gcbf,'Tag','FileName'),'Userdata');
1444    save(FileName, 'LocoModel', 'FitParameters', 'BPMData', 'CMData', 'RINGData', 'LocoMeasData', 'LocoFlags');
1445    setappdata(gcbf, 'LocoDataCell', {BPMData, CMData, LocoMeasData, LocoModel, FitParameters, LocoFlags, RINGData});
1446    set(H_Axes, 'Tag', AxesTag);
1447end
1448
1449
1450% Compute Chi2 verses parameter and save data
1451if PlotNumber == 16
1452    if ~isfield(LocoFlags(i),'Method') || ~isfield(LocoFlags(i).Method,'DeltaChi2') || ~isfield(LocoFlags(i).Method.DeltaChi2,'FitParameter') ...
1453            || isempty(LocoFlags(i).Method.DeltaChi2.FitParameter) || length(LocoFlags(i).Method.DeltaChi2.FitParameter)~=length(FitParameters(i).Values)
1454        LocoFlags(i).Method.DeltaChi2 = lococalcdeltachi2(LocoModel, LocoMeasData, BPMData, CMData, FitParameters, LocoFlags, RINGData,i-1, 'Display');
1455        FileName = get(findobj(gcbf,'Tag','FileName'),'Userdata');
1456        save(FileName, 'LocoModel', 'FitParameters', 'BPMData', 'CMData', 'RINGData', 'LocoMeasData', 'LocoFlags');
1457        setappdata(gcbf, 'LocoDataCell', {BPMData, CMData, LocoMeasData, LocoModel, FitParameters, LocoFlags, RINGData});
1458    end
1459end
1460
1461
1462% Patch for a iteration zero bug fixed on 1-29-2004
1463NHBPM = length(BPMData(i).HBPMGoodDataIndex);
1464NVBPM = length(BPMData(i).VBPMGoodDataIndex);
1465NBPM  = NHBPM + NVBPM;
1466NHCM = length(CMData(i).HCMGoodDataIndex);
1467NVCM = length(CMData(i).VCMGoodDataIndex);
1468if any(size(LocoModel(i).M) ~= [NBPM NHCM+NVCM])
1469    AxesTag = get(H_Axes,'Tag');
1470    [LocoModel(i).M, LocoModel(i).Eta, LocoModel(i).ChiSquare] = getmodelresponsematrix(BPMData(i), CMData(i), FitParameters(i), LocoFlags(i), LocoMeasData, RINGData);
1471    FileName = get(findobj(gcbf,'Tag','FileName'),'Userdata');
1472    save(FileName, 'LocoModel', 'FitParameters', 'BPMData', 'CMData', 'RINGData', 'LocoMeasData', 'LocoFlags');
1473    setappdata(gcbf, 'LocoDataCell', {BPMData, CMData, LocoMeasData, LocoModel, FitParameters, LocoFlags, RINGData});
1474    set(H_Axes, 'Tag', AxesTag);
1475end
1476
1477Mmodel = LocoModel(i).M;
1478
1479% Clear content menu
1480set(H_Axes, 'UIContextMenu', []);
1481
1482legend off
1483
1484try
1485    switch PlotNumber
1486        case 1
1487            plot(H_Axes,[0 1],[0 1],'w');
1488            title(H_Axes,'LOCO Input Parameter');
1489            set(H_Axes,'box','on');
1490            set(H_Axes,'XTick',[]);
1491            set(H_Axes,'YTick',[]);
1492           
1493            N = 1;
1494            if exist('LocoFlags','var')
1495                if ~isempty(LocoFlags)
1496                   
1497                    if isfield(LocoFlags(i), 'SinglePrecision')
1498                        if ischar(LocoFlags(i).SinglePrecision)
1499                            text(2,N,sprintf('Single Precision = %s', LocoFlags(i).SinglePrecision),'units','characters');
1500                            N = N + 1;
1501                        end
1502                    end
1503
1504                    if isfield(LocoFlags(i), 'CalculateSigma')
1505                        if ischar(LocoFlags(i).CalculateSigma)
1506                            text(2,N,sprintf('Calculate Error Bars = %s', LocoFlags(i).CalculateSigma),'units','characters');
1507                            N = N + 1;
1508                        end
1509                    end
1510                   
1511                    if isfield(LocoFlags(i),'Dispersion')
1512                        text(2,N,sprintf('Include Dispersion = %s', LocoFlags(i).Dispersion),'units','characters');
1513                        N = N + 1;
1514                    end
1515                    if isfield(LocoFlags(i),'AutoCorrectDelta')
1516                        text(2,N,sprintf('Auto Correct Deltas = %s', LocoFlags(i).AutoCorrectDelta),'units','characters');
1517                        N = N + 1;
1518                    end
1519                    if isfield(LocoFlags(i),'Coupling')
1520                        text(2,N,sprintf('Include Off-Diagonal Terms = %s', LocoFlags(i).Coupling),'units','characters');
1521                        N = N + 1;
1522                    end
1523                    if isfield(LocoFlags(i),'ResponseMatrixCalculator')
1524                        text(2,N,sprintf('Response Matrix Calculator = %s', LocoFlags(i).ResponseMatrixCalculator),'units','characters');
1525                        N = N + 1;
1526                    end
1527                    if isfield(LocoFlags(i),'ClosedOrbitType')
1528                        text(2,N,sprintf('Response Matrix Closed Orbit = %s', LocoFlags(i).ClosedOrbitType),'units','characters');
1529                        N = N + 1;
1530                    end
1531                    if isfield(LocoFlags(i),'SVmethod')
1532                        if isempty(LocoFlags(i))
1533                            text(2,N,sprintf('Singular Value Selection = '),'units','characters');
1534                        elseif isempty(LocoFlags(i).SVmethod)
1535                            text(2,N,sprintf('Singular Value Selection = Interactive'),'units','characters');
1536                        elseif strcmpi((LocoFlags(i).SVmethod),'rank')
1537                            text(2,N,sprintf('Singular Value Selection = Rank'),'units','characters');
1538                        elseif length(LocoFlags(i).SVmethod) > 1
1539                            text(2,N,sprintf('Singular Value Selection = User Input'),'units','characters');
1540                        else   
1541                            text(2,N,sprintf('Singular Value Selection = Threshold (%f)',LocoFlags(i).Threshold),'units','characters');
1542                        end
1543                        N = N + 1;
1544                    end
1545                    if isfield(LocoFlags(i),'Normalize')
1546                        text(2,N,sprintf('Normalize = %s', LocoFlags(i).Normalization.Flag),'units','characters');
1547                        N = N + 1;
1548                    end
1549                end
1550            end   
1551            if isfield(FitParameters(i),'FitRFFrequency')
1552                text(2,N,sprintf('Fit RF Frequency = %s', FitParameters(i).FitRFFrequency),'units','characters');
1553                N = N + 1;
1554            end
1555            if isfield(CMData(i),'FitVCMEnergyShift')
1556                text(2,N,sprintf('Fit Energy Shifts at VCM = %s', CMData(i).FitVCMEnergyShift),'units','characters');
1557                N = N + 1;
1558            end
1559            if isfield(CMData(i),'FitHCMEnergyShift')
1560                text(2,N,sprintf('Fit Energy Shifts at HCM = %s', CMData(i).FitHCMEnergyShift),'units','characters');
1561                N = N + 1;
1562            end
1563            if isfield(CMData(i),'FitKicks')
1564                text(2,N,sprintf('Fit Corrector Magnet Gains = %s', CMData(i).FitKicks),'units','characters');
1565                N = N + 1;
1566            end
1567            if isfield(CMData(i),'FitCoupling')
1568                text(2,N,sprintf('Fit Corrector Magnet Rolls = %s', CMData(i).FitCoupling),'units','characters');
1569                N = N + 1;
1570            end
1571            if isfield(BPMData(i),'FitGains')
1572                text(2,N,sprintf('Fit BPM Gains = %s', BPMData(i).FitGains),'units','characters');
1573                N = N + 1;
1574            end
1575            if isfield(BPMData(i),'FitCoupling')
1576                text(2,N,sprintf('Fit BPM Coupling = %s', BPMData(i).FitCoupling),'units','characters');
1577                N = N + 1;
1578            end   
1579            if isfield(CMData(i),'VCMGoodDataIndex')
1580                text(2,N,sprintf('%d horizontal %d vertical CMs', length(CMData(i).HCMGoodDataIndex), length(CMData(i).VCMGoodDataIndex)),'units','characters');
1581                N = N + 1;
1582            end
1583            if isfield(BPMData(i),'HBPMGoodDataIndex')
1584                text(2,N,sprintf('%d horizontal %d vertical BPMs', length(BPMData(i).HBPMGoodDataIndex), length(BPMData(i).VBPMGoodDataIndex)),'units','characters');
1585                N = N + 1;
1586            end
1587           
1588        case 2       
1589            x = 1:length(CMData(i).HCMKicks);
1590            if isempty(CMData(i).HCMKicksSTD)
1591                plot(x(CMData(i).HCMGoodDataIndex), CMData(i).HCMKicks(CMData(i).HCMGoodDataIndex));
1592            else
1593                errorbar(x(CMData(i).HCMGoodDataIndex), CMData(i).HCMKicks(CMData(i).HCMGoodDataIndex), CMData(i).HCMKicksSTD(CMData(i).HCMGoodDataIndex));
1594            end
1595            title(sprintf('Corrector Magnet Parameter Fits (%d)',length(CMData(i).HCMKicks(CMData(i).HCMGoodDataIndex))));
1596            ylabel(H_Axes,'Horizontal Kick [mrad]');
1597            xlabel(H_Axes,'Horizontal Corrector Number');
1598            axis tight
1599           
1600        case 3
1601            x = 1:length(CMData(i).VCMKicks);
1602            if isempty(CMData(i).VCMKicksSTD)
1603                plot(x(CMData(i).VCMGoodDataIndex), CMData(i).VCMKicks(CMData(i).VCMGoodDataIndex));
1604            else
1605                errorbar(x(CMData(i).VCMGoodDataIndex), CMData(i).VCMKicks(CMData(i).VCMGoodDataIndex), CMData(i).VCMKicksSTD(CMData(i).VCMGoodDataIndex));
1606            end
1607            title(sprintf('Corrector Magnet Parameter Fits (%d)',length(CMData(i).VCMKicks(CMData(i).VCMGoodDataIndex))));
1608            ylabel(H_Axes,'Vertical Kick [mrad]');
1609            xlabel(H_Axes,'Vertical Corrector Number');
1610            axis tight;
1611           
1612        case 4
1613            if ~isempty(CMData(i).HCMCoupling)
1614                x = 1:length(CMData(i).HCMCoupling);
1615                if isempty(CMData(i).HCMCouplingSTD)
1616                    plot(x(CMData(i).HCMGoodDataIndex), CMData(i).HCMCoupling(CMData(i).HCMGoodDataIndex));
1617                else
1618                    errorbar(x(CMData(i).HCMGoodDataIndex), CMData(i).HCMCoupling(CMData(i).HCMGoodDataIndex), CMData(i).HCMCouplingSTD(CMData(i).HCMGoodDataIndex));
1619                end
1620                title(sprintf('Corrector Magnet Parameter Fits (%d)',length(CMData(i).HCMCoupling(CMData(i).HCMGoodDataIndex))));
1621                ylabel(H_Axes,'Horizontal Coupling');
1622                xlabel(H_Axes,'Horizontal Corrector Number');
1623                axis tight
1624            else
1625                set(H_Axes,'XTick',[]); set(H_Axes,'YTick',[]); cla; title(H_Axes,' '); xlabel(H_Axes,' '); ylabel(H_Axes,' ');
1626            end
1627           
1628        case 5
1629            if ~isempty(CMData(i).VCMCoupling)
1630                x = 1:length(CMData(i).VCMCoupling);
1631                if isempty(CMData(i).VCMCouplingSTD)
1632                    plot(x(CMData(i).VCMGoodDataIndex), CMData(i).VCMCoupling(CMData(i).VCMGoodDataIndex));
1633                else   
1634                    errorbar(x(CMData(i).VCMGoodDataIndex), CMData(i).VCMCoupling(CMData(i).VCMGoodDataIndex), CMData(i).VCMCouplingSTD(CMData(i).VCMGoodDataIndex));
1635                end
1636                title(sprintf('Corrector Magnet Parameter Fits (%d)',length(CMData(i).VCMCoupling(CMData(i).VCMGoodDataIndex))));
1637                ylabel(H_Axes,'Vertical Coupling');
1638                xlabel(H_Axes,'Vertical Corrector Number');
1639                axis tight;
1640            else
1641                set(H_Axes,'XTick',[]); set(H_Axes,'YTick',[]); cla; title(H_Axes,' '); xlabel(H_Axes,' '); ylabel(H_Axes,' ');
1642            end
1643           
1644        case 6   
1645            if ~isempty(CMData(i).HCMEnergyShift)
1646                x = 1:length(CMData(i).HCMEnergyShift);
1647                if isempty(CMData(i).HCMEnergyShiftSTD)
1648                    plot(x(CMData(i).HCMGoodDataIndex), CMData(i).HCMEnergyShift(CMData(i).HCMGoodDataIndex));
1649                else
1650                    errorbar(x(CMData(i).HCMGoodDataIndex), CMData(i).HCMEnergyShift(CMData(i).HCMGoodDataIndex), CMData(i).HCMEnergyShiftSTD(CMData(i).HCMGoodDataIndex));
1651                end
1652                title(sprintf('Corrector Magnet Parameter Fits (%d)',length(CMData(i).HCMEnergyShift(CMData(i).HCMGoodDataIndex))));
1653                ylabel(H_Axes,'Horizontal Energy Shift');
1654                xlabel(H_Axes,'Horizontal Corrector Number');
1655                axis tight
1656            else
1657                set(H_Axes,'XTick',[]); set(H_Axes,'YTick',[]); cla; title(H_Axes,' '); xlabel(H_Axes,' '); ylabel(H_Axes,' ');
1658            end
1659           
1660        case 7
1661            if ~isempty(CMData(i).VCMEnergyShift)
1662                x = 1:length(CMData(i).VCMEnergyShift);
1663                if isempty(CMData(i).VCMEnergyShiftSTD)
1664                    plot(x(CMData(i).VCMGoodDataIndex), CMData(i).VCMEnergyShift(CMData(i).VCMGoodDataIndex));
1665                else
1666                    errorbar(x(CMData(i).VCMGoodDataIndex), CMData(i).VCMEnergyShift(CMData(i).VCMGoodDataIndex), CMData(i).VCMEnergyShiftSTD(CMData(i).VCMGoodDataIndex));
1667                end
1668                title(sprintf('Corrector Magnet Parameter Fits (%d)',length(CMData(i).VCMEnergyShift(CMData(i).VCMGoodDataIndex))));
1669                ylabel(H_Axes,'Vertical Energy Shift');
1670                xlabel(H_Axes,'Vertical Corrector Number');
1671                axis tight
1672            else
1673                set(H_Axes,'XTick',[]); set(H_Axes,'YTick',[]); cla; title(H_Axes,' '); xlabel(H_Axes,' '); ylabel(H_Axes,' ');
1674            end
1675           
1676        case 8
1677            x = 1:length(BPMData(i).HBPMGain);
1678            if isempty(BPMData(i).HBPMGainSTD)
1679                plot(x(BPMData(i).HBPMGoodDataIndex), BPMData(i).HBPMGain(BPMData(i).HBPMGoodDataIndex));
1680            else
1681                errorbar(x(BPMData(i).HBPMGoodDataIndex), BPMData(i).HBPMGain(BPMData(i).HBPMGoodDataIndex), BPMData(i).HBPMGainSTD(BPMData(i).HBPMGoodDataIndex));
1682            end
1683            title(sprintf('BPM Parameter Fits (%d)',length(BPMData(i).HBPMGain(BPMData(i).HBPMGoodDataIndex))));
1684            ylabel(H_Axes,'BPMx Gain');
1685            xlabel(H_Axes,'Horizontal BPM Number');
1686            axis tight
1687           
1688        case 9
1689            x = 1:length(BPMData(i).VBPMGain);
1690            if isempty(BPMData(i).VBPMGainSTD)
1691                plot(x(BPMData(i).VBPMGoodDataIndex), BPMData(i).VBPMGain(BPMData(i).VBPMGoodDataIndex));
1692            else
1693                errorbar(x(BPMData(i).VBPMGoodDataIndex), BPMData(i).VBPMGain(BPMData(i).VBPMGoodDataIndex), BPMData(i).VBPMGainSTD(BPMData(i).VBPMGoodDataIndex));
1694            end
1695            title(sprintf('BPM Parameter Fits (%d)',length(BPMData(i).VBPMGain(BPMData(i).VBPMGoodDataIndex))));
1696            ylabel(H_Axes,'BPMy Gain');
1697            xlabel(H_Axes,'Vertical BPM Number');
1698            axis tight;
1699           
1700        case 10
1701            x = 1:length(BPMData(i).HBPMCoupling);
1702            if ~isempty(BPMData(i).HBPMCoupling)
1703                if isempty(BPMData(i).HBPMCouplingSTD)
1704                    plot(x(BPMData(i).HBPMGoodDataIndex), BPMData(i).HBPMCoupling(BPMData(i).HBPMGoodDataIndex));
1705                else
1706                    errorbar(x(BPMData(i).HBPMGoodDataIndex), BPMData(i).HBPMCoupling(BPMData(i).HBPMGoodDataIndex), BPMData(i).HBPMCouplingSTD(BPMData(i).HBPMGoodDataIndex));
1707                end
1708                title(sprintf('BPM Parameter Fits (%d)',length(BPMData(i).HBPMCoupling(BPMData(i).HBPMGoodDataIndex))));
1709                ylabel(H_Axes,'BPMx Coupling');
1710                xlabel(H_Axes,'Horizontal BPM Number');
1711                axis tight
1712            else
1713                set(H_Axes,'XTick',[]); set(H_Axes,'YTick',[]); cla; title(H_Axes,' '); xlabel(H_Axes,' '); ylabel(H_Axes,' ');
1714            end
1715           
1716        case 11
1717            x = 1:length(BPMData(i).VBPMCoupling);
1718            if ~isempty(BPMData(i).VBPMCoupling)
1719                if isempty(BPMData(i).VBPMCouplingSTD)
1720                    plot(x(BPMData(i).VBPMGoodDataIndex), BPMData(i).VBPMCoupling(BPMData(i).VBPMGoodDataIndex));
1721                else
1722                    errorbar(x(BPMData(i).VBPMGoodDataIndex), BPMData(i).VBPMCoupling(BPMData(i).VBPMGoodDataIndex), BPMData(i).VBPMCouplingSTD(BPMData(i).VBPMGoodDataIndex));
1723                end
1724                title(sprintf('BPM Parameter Fits (%d)',length(BPMData(i).VBPMCoupling(BPMData(i).VBPMGoodDataIndex))));
1725                ylabel(H_Axes,'BPMy Coupling');
1726                xlabel(H_Axes,'Vertical BPM Number');
1727                axis tight;
1728            else
1729                set(H_Axes,'XTick',[]); set(H_Axes,'YTick',[]); cla; title(H_Axes,' '); xlabel(H_Axes,' '); ylabel(H_Axes,' ');
1730            end
1731
1732        case 12
1733            % HBPM Standard Deviations           
1734            BPMstd = LocoMeasData.BPMSTD(BPMData(i).HBPMGoodDataIndex);
1735           
1736            %BPMstd = LocoMeasData.BPMSTD([BPMData(i).HBPMGoodDataIndex length(BPMData(i).HBPMIndex)+BPMData(i).VBPMGoodDataIndex]);
1737            %if ~isempty(BPMstd)
1738            %    plot(BPMstd)
1739            %    ylabel(H_Axes,'Standard Deviation [mm]');
1740            %    axis tight
1741            %   
1742            %    % Change label to BPM numbers
1743            %    Nx = length(BPMstd);
1744            %    Ticks = 1:ceil(Nx/10):Nx;
1745            %    set(H_Axes, 'XTick', Ticks);     
1746            %    TickNumber = [BPMData(i).HBPMGoodDataIndex BPMData(i).VBPMGoodDataIndex];
1747            %    TickNumber = TickNumber(Ticks);
1748            %    set(H_Axes, 'XTickLabel', num2cell(TickNumber));         
1749            %    xlabel(H_Axes,'HBPM# and VBPM#');
1750            %end
1751           
1752            if ~isempty(BPMstd)               
1753                plot(BPMstd);
1754                title(H_Axes,'Horizontal BPM Standard Deviations');
1755                ylabel(H_Axes,'Standard Deviation [mm]');
1756                xlabel(H_Axes,'BPM Number');
1757                axis tight
1758            end
1759
1760        case 13
1761            % VBPM Standard Deviations           
1762            BPMstd = LocoMeasData.BPMSTD(length(BPMData(i).HBPMIndex)+BPMData(i).VBPMGoodDataIndex);
1763           
1764            if ~isempty(BPMstd)               
1765                plot(BPMstd);
1766                title(H_Axes,'Vertical BPM Standard Deviations');
1767                ylabel(H_Axes,'Standard Deviation [mm]');
1768                xlabel(H_Axes,'BPM Number');
1769                axis tight
1770            end
1771
1772        case 14
1773            if isempty(FitParameters(i).DeltaRF)
1774                set(H_Axes,'XTick',[]); set(H_Axes,'YTick',[]); cla; title(H_Axes,' '); xlabel(H_Axes,' '); ylabel(H_Axes,' ');
1775            else
1776                plot(H_Axes,[0 1],[0 1],'w');
1777                title(H_Axes,'RF Frequency');
1778                set(H_Axes,'box','on');
1779                set(H_Axes,'XTick',[]);
1780                set(H_Axes,'YTick',[]);
1781                text(4,10,sprintf('Dispersion Measurement'),'units','characters');
1782                text(4,9,sprintf('RF Frequency Change:'),'units','characters');
1783                text(4,8,sprintf('%8.3f Hz Measured',  LocoMeasData.DeltaRF),'units','characters');
1784                text(4,7,sprintf('%8.3f Hz Model', FitParameters(i).DeltaRF),'units','characters');
1785               
1786                text(4,6,sprintf('%10.5f Hz \\sigma-Model', FitParameters(i).DeltaRFSTD),'units','characters');
1787                if isfield(FitParameters(i),'FitRFFrequency')
1788                    text(4,5,sprintf('Fit Delta RF Frequency = %s', FitParameters(i).FitRFFrequency),'units','characters');
1789                end   
1790                if isfield(LocoMeasData,'RF')
1791                    text(4,3,sprintf('RF Frequency = %.1f Hz (Measured)', LocoMeasData.RF),'units','characters');
1792                end   
1793                if isfield(RINGData,'CavityFrequency')
1794                    text(4,2,sprintf('RF Frequency = %.1f Hz (Model)', RINGData.CavityFrequency'),'units','characters');
1795                end   
1796            end           
1797           
1798        case 15
1799            % Other parameters
1800            if isempty(FitParameters(i).Values)
1801                set(H_Axes,'XTick',[]); set(H_Axes,'YTick',[]); cla; title(H_Axes,' '); xlabel(H_Axes,' '); ylabel(H_Axes,' ');
1802                return;
1803            elseif length(FitParameters(i).Values) > 1
1804                ATFlag = 0;
1805                if iscell(RINGData.Lattice)
1806                    if isfield(RINGData.Lattice{1},'FamName')
1807                        ATFlag = 1;
1808                    end
1809                end
1810               
1811                AxesTag = get(H_Axes,'Tag');
1812                if strcmp(AxesTag,'Axes1')
1813                    FieldName = getappdata(gcbf,'OtherParameterPlot1');
1814                elseif strcmp(AxesTag,'Axes2')
1815                    FieldName = getappdata(gcbf,'OtherParameterPlot2');
1816                end
1817               
1818                if isempty(FieldName) || strcmp(FieldName, 'All')
1819                    if isempty(FitParameters(i).ValuesSTD) || all(isnan(FitParameters(i).ValuesSTD))
1820                        plot(1:length(FitParameters(i).Values), FitParameters(i).Values, '.-b');
1821                    else
1822                        errorbar(1:length(FitParameters(i).Values), FitParameters(i).Values, FitParameters(i).ValuesSTD);
1823                    end
1824                    title(H_Axes,'LOCO Parameter Fits');
1825                    ylabel(H_Axes,'');
1826                    xlabel(H_Axes,'Parameter Number');
1827                    axis tight
1828                    %fprintf('   Right click in the axis to select different parameter plots.\n');
1829                   
1830                else
1831                    ParameterNumber = [];Values=[]; ValuesSTD=[];
1832                    for j = 1:length(FitParameters(i).Params)
1833                        if ATFlag
1834                            Name = RINGData.Lattice{FitParameters(i).Params{j}(1).ElemIndex}.FamName;
1835                            SubField = FitParameters(i).Params{j}(1).FieldName;
1836                            Name = [Name,'.',SubField];
1837                        else
1838                            Name = FitParameters(i).Params{j}(1).FieldName;
1839                        end
1840                       
1841                        if strcmp(Name, FieldName)
1842                            Values = [Values FitParameters(i).Values(j)];
1843                            ParameterNumber = [ParameterNumber j];
1844                            if isempty(FitParameters(i).ValuesSTD)
1845                                ValuesSTD = [];
1846                            else
1847                                ValuesSTD = [ValuesSTD FitParameters(i).ValuesSTD(j)];
1848                            end
1849                        end
1850                    end
1851                    if isempty(ValuesSTD) || all(isnan(ValuesSTD))
1852                        if length(Values) == 1
1853                            plot(ParameterNumber, Values, 'squareb','MarkerFaceColor','b');
1854                        else
1855                            %plot(1:length(Values), Values);
1856                            plot(ParameterNumber, Values, '.-b');
1857                        end
1858                    else
1859                        %errorbar(1:length(Values), Values, ValuesSTD);
1860                        errorbar(ParameterNumber, Values, ValuesSTD);
1861                    end
1862                    title(H_Axes,['LOCO Parameter Fits for Field: ', FieldName]);
1863                    ylabel(H_Axes,'');
1864                    xlabel(H_Axes,'Parameter Number');
1865                    axis tight
1866                end
1867               
1868                % Add a context menu
1869                hcmenu = uicontextmenu;
1870               
1871                % Define the line and associate it with the context menu
1872                set(H_Axes, 'UIContextMenu', hcmenu);
1873               
1874                % Define the context menu items       
1875                cb = 'locogui(''ContextMenuPlot_Callback'',gcbo,[],[])';
1876                h = uimenu(hcmenu, 'Label', 'All', 'Callback', cb);
1877                set(h,'Userdata','All');
1878                if ATFlag
1879                    % When using the AT model this will work
1880                    j = 1;
1881                    cb = 'locogui(''ContextMenuPlot_Callback'',gcbo,[],[])';
1882                    NameNew = RINGData.Lattice{FitParameters(i).Params{j}(1).ElemIndex}.FamName;
1883                    SubField = FitParameters(i).Params{j}(1).FieldName;
1884                    %h = uimenu(hcmenu, 'Label', NameNew, 'Callback', cb);
1885                    h = uimenu(hcmenu, 'Label',[NameNew,'.',SubField], 'Callback', cb);
1886                    %set(h,'Userdata',NameNew);
1887                    set(h,'Userdata',[NameNew,'.',SubField]);
1888                    %Names{1} = NameNew;
1889                    Names{1} = [NameNew,'.',SubField];
1890                    for j = 2:length(FitParameters(i).Params)
1891                        NameNew = RINGData.Lattice{FitParameters(i).Params{j}(1).ElemIndex}.FamName;
1892                        SubField = FitParameters(i).Params{j}(1).FieldName;
1893                        %if ~any(strcmp(NameNew, Names))
1894                        if ~any(strcmp([NameNew,'.',SubField], Names))
1895                            %Names{end+1} = NameNew;
1896                            Names{end+1} = [NameNew,'.',SubField];
1897                            cb = 'locogui(''ContextMenuPlot_Callback'',gcbo,[],[])';
1898                            %h = uimenu(hcmenu, 'Label', NameNew, 'Callback', cb);
1899                            h = uimenu(hcmenu, 'Label',[NameNew,'.',SubField], 'Callback', cb);
1900                            %set(h,'Userdata',NameNew);
1901                            set(h,'Userdata',[NameNew,'.',SubField]);
1902                        end
1903                    end
1904                else
1905                    % Base names on paramgroup
1906                    j = 1;
1907                    cb = 'locogui(''ContextMenuPlot_Callback'',gcbo,[],[])';
1908                    h = uimenu(hcmenu, 'Label', FitParameters(i).Params{1}(1).FieldName, 'Callback', cb);
1909                    set(h,'Userdata',FitParameters(i).Params{j}(1).FieldName);
1910                    for j = 2:length(FitParameters(i).Params)
1911                        if ~strcmp(FitParameters(i).Params{j}(1).FieldName, FitParameters(i).Params{j-1}(1).FieldName)
1912                            cb = 'locogui(''ContextMenuPlot_Callback'',gcbo,[],[])';
1913                            h = uimenu(hcmenu, 'Label', FitParameters(i).Params{j}(1).FieldName, 'Callback', cb);
1914                            set(h,'Userdata',FitParameters(i).Params{j}(1).FieldName);
1915                        end
1916                    end
1917                end
1918               
1919            else
1920                plot(H_Axes,[0 1],[0 1],'w');
1921                title(H_Axes,'LOCO Parameter Fits');
1922                set(H_Axes,'box','on');
1923                set(H_Axes,'XTick',[]);
1924                set(H_Axes,'YTick',[]);
1925                text(4,6,sprintf('Parameter Fit #1'),'units','characters');
1926                text(4,5,sprintf('Value = %f', FitParameters(i).Values),'units','characters');
1927                text(4,4,sprintf('\\sigma = %f', FitParameters(i).ValuesSTD),'units','characters');
1928                %text(.05,.6,sprintf('Parameter Fit #1:  Value = %f, \\sigma = %f', FitParameters(i).Values, FitParameters(i).Values));
1929            end
1930
1931        case 16
1932            % Plot delta chi^2 w.r.t. fit parameter
1933            if isfield(LocoFlags(i),'Method') && isfield(LocoFlags(i).Method,'DeltaChi2') && isfield(LocoFlags(i).Method.DeltaChi2,'FitParameter') && ~isempty(LocoFlags(i).Method.DeltaChi2.FitParameter)
1934                axes(H_Axes);
1935                if 1
1936                    plot(1:length(LocoFlags(i).Method.DeltaChi2.FitParameter), LocoFlags(i).Method.DeltaChi2.FitParameter,'.-');
1937                    ylabel(H_Axes,'\Delta \chi^2', 'FontSize', 14); grid on
1938                else
1939                    semilogy(1:length(LocoFlags(i).Method.DeltaChi2.FitParameter), abs(LocoFlags(i).Method.DeltaChi2.FitParameter),'.-');
1940                    ylabel(H_Axes,'\mid\Delta \chi^2\mid', 'FontSize', 14);
1941                end
1942                title(H_Axes,'');
1943                xlabel(H_Axes,'Fit Parameter Index', 'FontSize', 10);
1944                title(H_Axes,'\Delta \chi^2 vs Fit Parameter', 'FontSize', 10);
1945                %grid  on;
1946                axis tight;
1947                d = .08;
1948                text(.03,.9-0*d, sprintf('\\Delta \\chi^2(All BPMs) = %.1e',          LocoFlags(i).Method.DeltaChi2.BPMGroup),          'FontSize', 10, 'Units','Normalized');
1949                text(.03,.9-1*d, sprintf('\\Delta \\chi^2(All CMs)  = %.1e',          LocoFlags(i).Method.DeltaChi2.CMGroup),           'FontSize', 10, 'Units','Normalized');
1950                text(.03,.9-2*d, sprintf('\\Delta \\chi^2(All FitParameters) = %.1e', LocoFlags(i).Method.DeltaChi2.FitParameterGroup), 'FontSize', 10, 'Units','Normalized');
1951            else
1952                % No data probably because delta chi^2 calculation was canceled
1953                cla;
1954                plot(H_Axes,[0 1],[0 1],'w');
1955                set(H_Axes,'XTick',[]);
1956                set(H_Axes,'YTick',[]);
1957                title(H_Axes,' ');
1958                xlabel(H_Axes,' '); ylabel(H_Axes,' ');
1959                text(.45,.5,sprintf('No Data'),'Units','Normalized');
1960                return
1961            end
1962
1963        case 17
1964            % Plot partial chi^2 w.r.t. fit parameter
1965            if isfield(LocoFlags(i),'Method') && isfield(LocoFlags(i).Method,'PartialChi2') && ~isempty(fieldnames(LocoFlags(i).Method.PartialChi2))
1966                AxesTag = get(H_Axes,'Tag');
1967                if strcmp(AxesTag,'Axes1')
1968                    Userdata = getappdata(gcbf, 'PartialChi2Plot1');
1969                elseif strcmp(AxesTag,'Axes2')
1970                    Userdata = getappdata(gcbf, 'PartialChi2Plot2');
1971                end
1972                if isempty(Userdata)
1973                    Userdata = {'All', H_Axes};
1974                    if strcmp(AxesTag,'Axes1')
1975                        setappdata(gcbf, 'PartialChi2Plot1', Userdata);
1976                    elseif strcmp(AxesTag,'Axes2')
1977                        setappdata(gcbf, 'PartialChi2Plot2', Userdata);
1978                    end
1979                end
1980
1981                PlotPartialChi2;
1982               
1983                % Define the context menu for the plot
1984                hcmenu = uicontextmenu('Tag','PartialChi2Plot');
1985                set(H_Axes, 'UIContextMenu', hcmenu);
1986                h = uimenu(hcmenu, 'Label', 'All', 'Callback', 'locogui(''ContextPartialChi2Plot_Callback'',gcbo,[],[])');
1987                set(h,'Userdata',{'All', H_Axes});
1988                FieldCell = fieldnames(LocoFlags(i).Method.PartialChi2);
1989                for ifield = 1:length(FieldCell)
1990                    h = uimenu(hcmenu, 'Label', FieldCell{ifield}, 'Callback', 'locogui(''ContextPartialChi2Plot_Callback'',gcbo,[],[])');
1991                    set(h,'Userdata',{FieldCell{ifield}, H_Axes});
1992                end
1993                %fprintf('   Right click in the axis to select different plots.\n');
1994
1995            else
1996                % No data
1997                cla;
1998                plot(H_Axes,[0 1],[0 1],'w');
1999                set(H_Axes,'XTick',[]);
2000                set(H_Axes,'YTick',[]);
2001                title(H_Axes,' ');
2002                xlabel(H_Axes,' '); ylabel(H_Axes,' ');
2003                text(.35,.5,sprintf('No  \\partial\\chi^2 / \\partialFitParamter Data'),'Units','Normalized');
2004                return
2005            end
2006           
2007                       
2008        case 18
2009            % Plot cost function
2010            if isfield(LocoFlags(i),'Method') && isfield(LocoFlags(i).Method,'Cost')&& isstruct(LocoFlags(i).Method.Cost) && ~isempty(fieldnames(LocoFlags(i).Method.Cost))
2011                AxesTag = get(H_Axes,'Tag');
2012                if strcmp(AxesTag,'Axes1')
2013                    Userdata = getappdata(gcbf, 'CostFunctionPlot1');
2014                elseif strcmp(AxesTag,'Axes2')
2015                    Userdata = getappdata(gcbf, 'CostFunctionPlot2');
2016                end
2017                if isempty(Userdata)
2018                    Userdata = {'All', H_Axes};
2019                    if strcmp(AxesTag,'Axes1')
2020                        setappdata(gcbf, 'CostFunctionPlot1', Userdata);
2021                    elseif strcmp(AxesTag,'Axes2')
2022                        setappdata(gcbf, 'CostFunctionPlot2', Userdata);
2023                    end
2024                end
2025
2026                PlotCostFunction;
2027               
2028                % Define the context menu for the plot
2029                hcmenu = uicontextmenu('Tag','PlotCostFunction');
2030                set(H_Axes, 'UIContextMenu', hcmenu);
2031                h = uimenu(hcmenu, 'Label', 'All', 'Callback', 'locogui(''ContextCostFunctionPlot_Callback'',gcbo,[],[])');
2032                set(h,'Userdata',{'All', H_Axes});
2033                FieldCell = fieldnames(LocoFlags(i).Method.Cost);
2034                for ifield = 1:length(FieldCell)
2035                    h = uimenu(hcmenu, 'Label', FieldCell{ifield}, 'Callback', 'locogui(''ContextCostFunctionPlot_Callback'',gcbo,[],[])');
2036                    set(h,'Userdata',{FieldCell{ifield}, H_Axes});
2037                end
2038                %fprintf('   Right click in the axis to select different parameter costs.\n');
2039
2040            else
2041                % No data
2042                cla;
2043                plot(H_Axes,[0 1],[0 1],'w');
2044                set(H_Axes,'XTick',[]);
2045                set(H_Axes,'YTick',[]);
2046                title(H_Axes,' ');
2047                xlabel(H_Axes,' '); ylabel(H_Axes,' ');
2048                text(.35,.5,sprintf('No Cost Function Data'),'Units','Normalized');
2049                return
2050            end
2051       
2052        case 19
2053            if ~exist('LocoFlags','var') || ~isfield(LocoFlags(i), 'Method') || ~isfield(LocoFlags(i).Method, 'SV') || isempty(LocoFlags(i).Method.SV)
2054                cla;
2055                plot(H_Axes,[0 1],[0 1],'w');
2056                set(H_Axes,'XTick',[]);
2057                set(H_Axes,'YTick',[]);
2058                title(H_Axes,' ');
2059                xlabel(H_Axes,' '); ylabel(H_Axes,' ');
2060                text(.45,.5,sprintf('No Data'),'Units','Normalized');
2061                return
2062            else
2063                SValues = LocoFlags(i).Method.SV;
2064                Ivec = LocoFlags(i).Method.SVIndex;
2065               
2066                semilogy(SValues,'b');
2067                hold on;
2068                semilogy(Ivec, SValues(Ivec),'og','MarkerSize',2);
2069                axis([1 length(SValues) min(SValues) max(SValues)]);
2070               
2071                x=1:length(SValues);
2072                x(Ivec)=[];
2073                SValues(Ivec)=[];
2074                semilogy(x, SValues,'xr','MarkerSize',4);
2075                hold off
2076               
2077                title(H_Axes,'Singular Values');
2078                xlabel(H_Axes,'Singular Value Number');
2079                ylabel(H_Axes,'Magnitude');
2080            end
2081           
2082        case 20
2083            % Response matrix plot
2084           
2085            AxesTag = get(H_Axes,'Tag');
2086            if strcmp(AxesTag,'Axes1')
2087                h = findobj(gcbf,'Tag','SurfPlot1');
2088                FieldName = get(h,'Userdata');
2089            elseif strcmp(AxesTag,'Axes2')
2090                h = findobj(gcbf,'Tag','SurfPlot2');
2091                FieldName = get(h,'Userdata');
2092            end
2093           
2094            if ~iscell(FieldName)
2095                FieldName = {'Model', 'All'};
2096                %FieldName = {'Measured', 'All'};
2097                %fprintf('   Right click in the axis to select different plots.\n');
2098            else
2099                % Force the field to Model when a new file or one of the pulldown menus is selected
2100                %FieldName = {'Model', 'All'};
2101            end
2102           
2103           
2104            PlotString  = FieldName{1};
2105            PlaneString = FieldName{2};
2106            if length(FieldName) > 2
2107                ElementsInput = FieldName{3};
2108            else
2109                ElementsInput = [];
2110            end
2111           
2112            set(H_Axes,'XTick',[]); set(H_Axes,'YTick',[]); cla; title(H_Axes,' '); xlabel(H_Axes,' '); ylabel(H_Axes,' ');
2113            FieldName{3} = locoplot({BPMData, CMData, LocoMeasData, LocoModel, FitParameters, LocoFlags, RINGData}, i-1, PlotString, PlaneString, ElementsInput);
2114            % if isempty(Mmodel)
2115            %     set(H_Axes,'XTick',[]); set(H_Axes,'YTick',[]); cla; title(H_Axes,' '); xlabel(H_Axes,' '); ylabel(H_Axes,' ');
2116            %     return
2117            % end
2118            set(h,'Userdata', FieldName);
2119           
2120           
2121            % Define the context menu items for surf plot
2122            hcmenu = uicontextmenu('Tag','3dsurfplot');
2123            set(H_Axes, 'UIContextMenu', hcmenu);
2124           
2125            h = uimenu(hcmenu, 'Label', 'Model: 3-D, All', 'Callback', 'locogui(''ContextMenuSurfPlot_Callback'',gcbo,[],[])');
2126            set(h,'Userdata',{'Model','All'});
2127            h = uimenu(hcmenu, 'Label', 'Model: 3-D, HBPM vs HCM', 'Callback', 'locogui(''ContextMenuSurfPlot_Callback'',gcbo,[],[])');
2128            set(h,'Userdata',{'Model','XX'});
2129            h = uimenu(hcmenu, 'Label', 'Model: 3-D, HBPM vs VCM', 'Callback', 'locogui(''ContextMenuSurfPlot_Callback'',gcbo,[],[])');
2130            set(h,'Userdata',{'Model','XY'});
2131            h = uimenu(hcmenu, 'Label', 'Model: 3-D, VBPM vs VCM', 'Callback', 'locogui(''ContextMenuSurfPlot_Callback'',gcbo,[],[])');
2132            set(h,'Userdata',{'Model','YY'});
2133            h = uimenu(hcmenu, 'Label', 'Model: 3-D, VBPM vs HCM', 'Callback', 'locogui(''ContextMenuSurfPlot_Callback'',gcbo,[],[])');
2134            set(h,'Userdata',{'Model','YX'});
2135           
2136            h = uimenu(hcmenu, 'Label', 'Model: 2-D, HBPM (Rows)', 'Callback', 'locogui(''ContextMenuSurfPlot_Callback'',gcbo,[],[])');
2137            set(h,'Userdata',{'Model','HBPM'});
2138            h = uimenu(hcmenu, 'Label', 'Model: 2-D, VBPM (Rows)', 'Callback', 'locogui(''ContextMenuSurfPlot_Callback'',gcbo,[],[])');
2139            set(h,'Userdata',{'Model','VBPM'});
2140            h = uimenu(hcmenu, 'Label', 'Model: 2-D, HCM (Columns)', 'Callback', 'locogui(''ContextMenuSurfPlot_Callback'',gcbo,[],[])');
2141            set(h,'Userdata',{'Model','HCM'});
2142            h = uimenu(hcmenu, 'Label', 'Model: 2-D, VCM (Columns)', 'Callback', 'locogui(''ContextMenuSurfPlot_Callback'',gcbo,[],[])');
2143            set(h,'Userdata',{'Model','VCM'});
2144           
2145            h = uimenu(hcmenu, 'Label', ' ', 'Callback', '');
2146           
2147            h = uimenu(hcmenu, 'Label', 'Measured: 3-D, All', 'Callback', 'locogui(''ContextMenuSurfPlot_Callback'',gcbo,[],[])');
2148            set(h,'Userdata',{'Measured','All'});
2149            h = uimenu(hcmenu, 'Label', 'Measured: 3-D, HBPM vs HCM', 'Callback', 'locogui(''ContextMenuSurfPlot_Callback'',gcbo,[],[])');
2150            set(h,'Userdata',{'Measured','XX'});
2151            h = uimenu(hcmenu, 'Label', 'Measured: 3-D, HBPM vs VCM', 'Callback', 'locogui(''ContextMenuSurfPlot_Callback'',gcbo,[],[])');
2152            set(h,'Userdata',{'Measured','XY'});
2153            h = uimenu(hcmenu, 'Label', 'Measured: 3-D, VBPM vs VCM', 'Callback', 'locogui(''ContextMenuSurfPlot_Callback'',gcbo,[],[])');
2154            set(h,'Userdata',{'Measured','YY'});
2155            h = uimenu(hcmenu, 'Label', 'Measured: 3-D, VBPM vs HCM', 'Callback', 'locogui(''ContextMenuSurfPlot_Callback'',gcbo,[],[])');
2156            set(h,'Userdata',{'Measured','YX'});
2157           
2158            h = uimenu(hcmenu, 'Label', 'Measured: 2-D, HBPM (Rows)', 'Callback', 'locogui(''ContextMenuSurfPlot_Callback'',gcbo,[],[])');
2159            set(h,'Userdata',{'Measured','HBPM'});
2160            h = uimenu(hcmenu, 'Label', 'Measured: 2-D, VBPM (Rows)', 'Callback', 'locogui(''ContextMenuSurfPlot_Callback'',gcbo,[],[])');
2161            set(h,'Userdata',{'Measured','VBPM'});
2162            h = uimenu(hcmenu, 'Label', 'Measured: 2-D, HCM (Columns)', 'Callback', 'locogui(''ContextMenuSurfPlot_Callback'',gcbo,[],[])');
2163            set(h,'Userdata',{'Measured','HCM'});
2164            h = uimenu(hcmenu, 'Label', 'Measured: 2-D, VCM (Columns)', 'Callback', 'locogui(''ContextMenuSurfPlot_Callback'',gcbo,[],[])');
2165            set(h,'Userdata',{'Measured','VCM'});
2166           
2167            h = uimenu(hcmenu, 'Label', ' ', 'Callback', '');
2168           
2169            h = uimenu(hcmenu, 'Label', 'Model-Measured: 3-D, All', 'Callback', 'locogui(''ContextMenuSurfPlot_Callback'',gcbo,[],[])');
2170            set(h,'Userdata',{'Model-Measured','All'});
2171            h = uimenu(hcmenu, 'Label', 'Model-Measured: 3-D, HBPM vs HCM', 'Callback', 'locogui(''ContextMenuSurfPlot_Callback'',gcbo,[],[])');
2172            set(h,'Userdata',{'Model-Measured','XX'});
2173            h = uimenu(hcmenu, 'Label', 'Model-Measured: 3-D, HBPM vs VCM', 'Callback', 'locogui(''ContextMenuSurfPlot_Callback'',gcbo,[],[])');
2174            set(h,'Userdata',{'Model-Measured','XY'});
2175            h = uimenu(hcmenu, 'Label', 'Model-Measured: 3-D, VBPM vs VCM', 'Callback', 'locogui(''ContextMenuSurfPlot_Callback'',gcbo,[],[])');
2176            set(h,'Userdata',{'Model-Measured','YY'});
2177            h = uimenu(hcmenu, 'Label', 'Model-Measured: 3-D, VBPM vs HCM', 'Callback', 'locogui(''ContextMenuSurfPlot_Callback'',gcbo,[],[])');
2178            set(h,'Userdata',{'Model-Measured','YX'});
2179            h = uimenu(hcmenu, 'Label', 'Model-Measured: 2-D, HBPM (Rows)', 'Callback', 'locogui(''ContextMenuSurfPlot_Callback'',gcbo,[],[])');
2180            set(h,'Userdata',{'Model-Measured','HBPM'});
2181            h = uimenu(hcmenu, 'Label', 'Model-Measured: 2-D, VBPM (Rows)', 'Callback', 'locogui(''ContextMenuSurfPlot_Callback'',gcbo,[],[])');
2182            set(h,'Userdata',{'Model-Measured','VBPM'});
2183            h = uimenu(hcmenu, 'Label', 'Model-Measured: 2-D, HCM (Columns)', 'Callback', 'locogui(''ContextMenuSurfPlot_Callback'',gcbo,[],[])');
2184            set(h,'Userdata',{'Model-Measured','HCM'});
2185            h = uimenu(hcmenu, 'Label', 'Model-Measured: 2-D, VCM (Columns)', 'Callback', 'locogui(''ContextMenuSurfPlot_Callback'',gcbo,[],[])');
2186            set(h,'Userdata',{'Model-Measured','VCM'});
2187           
2188            h = uimenu(hcmenu, 'Label', ' ', 'Callback', '');
2189           
2190            h = uimenu(hcmenu, 'Label', 'Model-Measured+EnergyShifts: 3-D, All', 'Callback', 'locogui(''ContextMenuSurfPlot_Callback'',gcbo,[],[])');
2191            set(h,'Userdata',{'Model-Measured+EnergyShifts','All'});
2192            h = uimenu(hcmenu, 'Label', 'Model-Measured+EnergyShifts: 3-D, HBPM vs HCM', 'Callback', 'locogui(''ContextMenuSurfPlot_Callback'',gcbo,[],[])');
2193            set(h,'Userdata',{'Model-Measured+EnergyShifts','XX'});
2194            h = uimenu(hcmenu, 'Label', 'Model-Measured+EnergyShifts: 3-D, HBPM vs VCM', 'Callback', 'locogui(''ContextMenuSurfPlot_Callback'',gcbo,[],[])');
2195            set(h,'Userdata',{'Model-Measured+EnergyShifts','XY'});
2196            h = uimenu(hcmenu, 'Label', 'Model-Measured+EnergyShifts: 3-D, VBPM vs VCM', 'Callback', 'locogui(''ContextMenuSurfPlot_Callback'',gcbo,[],[])');
2197            set(h,'Userdata',{'Model-Measured+EnergyShifts','YY'});
2198            h = uimenu(hcmenu, 'Label', 'Model-Measured+EnergyShifts: 3-D, VBPM vs HCM', 'Callback', 'locogui(''ContextMenuSurfPlot_Callback'',gcbo,[],[])');
2199            set(h,'Userdata',{'Model-Measured+EnergyShifts','YX'});
2200            h = uimenu(hcmenu, 'Label', 'Model-Measured+EnergyShifts: 2-D, HBPM (Rows)', 'Callback', 'locogui(''ContextMenuSurfPlot_Callback'',gcbo,[],[])');
2201            set(h,'Userdata',{'Model-Measured+EnergyShifts','HBPM'});
2202            h = uimenu(hcmenu, 'Label', 'Model-Measured+EnergyShifts: 2-D, VBPM (Rows)', 'Callback', 'locogui(''ContextMenuSurfPlot_Callback'',gcbo,[],[])');
2203            set(h,'Userdata',{'Model-Measured+EnergyShifts','VBPM'});
2204            h = uimenu(hcmenu, 'Label', 'Model-Measured+EnergyShifts: 2-D, HCM (Columns)', 'Callback', 'locogui(''ContextMenuSurfPlot_Callback'',gcbo,[],[])');
2205            set(h,'Userdata',{'Model-Measured+EnergyShifts','HCM'});
2206            h = uimenu(hcmenu, 'Label', 'Model-Measured+EnergyShifts: 2-D, VCM (Columns)', 'Callback', 'locogui(''ContextMenuSurfPlot_Callback'',gcbo,[],[])');
2207            set(h,'Userdata',{'Model-Measured+EnergyShifts','VCM'});
2208           
2209        case 21
2210            % Error function histogram
2211            plot(0,0); set(H_Axes,'XTick',[]); set(H_Axes,'YTick',[]); cla; title(H_Axes,' '); xlabel(H_Axes,' '); ylabel(H_Axes,' ');
2212           
2213            ErrorFunction = locodata({BPMData, CMData, LocoMeasData, LocoModel, FitParameters, LocoFlags, RINGData}, i-1, 'ErrorDistribution');
2214            if ~isempty(ErrorFunction)
2215                hist(ErrorFunction,2000);
2216                xlabel(H_Axes,'Error in Units of Standard Deviations');
2217                ylabel(H_Axes,['Number of Points (',num2str(length(ErrorFunction)),' total points)']);
2218                %title(texlabel(['Histogram: (M_meas - M_model)']));
2219                title(texlabel(['Histogram: (M_meas - M_model) / sigma_bpm']));
2220                %title(texlabel(['Histogram: (M_meas - M_model)^2 / sigma^2_bpm']));
2221               
2222                a = axis;
2223                axis([a(1)-(a(2)-a(1))/60 a(2) a(3) a(4)]);
2224                %OutlierFactor = LocoFlags(i).OutlierFactor;
2225            end
2226
2227        case 22
2228            % Horizontal dispersion function   
2229            plot(0,0); set(H_Axes,'XTick',[]); set(H_Axes,'YTick',[]); cla; title(H_Axes,' '); xlabel(H_Axes,' '); ylabel(H_Axes,' ');
2230           
2231            if 1
2232                % Only plotting horizontal dispersion   
2233                NHBPM = length(BPMData(i).HBPMGoodDataIndex);
2234                x = 1:length(BPMData(i).HBPMIndex);
2235                x = x(BPMData(i).HBPMGoodDataIndex);
2236               
2237                if isempty(LocoModel(i).Eta)
2238                    EtaModel = NaN*ones(size(x))';
2239                    fprintf('   Model dispersion is empty.\n');
2240                else
2241                    EtaModel = LocoModel(i).Eta(1:NHBPM);                   
2242                end
2243                if isempty(LocoMeasData.Eta)
2244                    EtaMeas = NaN*ones(size(x))';
2245                    fprintf('   Measured dispersion is empty.\n');
2246                else
2247                    EtaMeas = LocoMeasData.Eta(BPMData(i).HBPMGoodDataIndex);
2248                end
2249               
2250                plot(x, EtaMeas,'-b');
2251                hold on;
2252                plot(x, EtaModel,'--r');       
2253               
2254                % Add circles for the outliers                   
2255                EtaOutliers = LocoModel(i).EtaOutlierIndex;
2256                j = find(EtaOutliers <= NHBPM);      % Only horizontal data
2257                if ~isempty(j)
2258                    plot(x(EtaOutliers(j)),EtaMeas(EtaOutliers(j)),'og','MarkerSize',2);
2259                    legend('Measured','Model','Outliers',0);
2260                else
2261                    legend('Measured','Model',0);
2262                end
2263               
2264                hold off
2265                title(sprintf('"Dispersion" Function (%d BPMs)',length(EtaModel)));
2266                ylabel(H_Axes,'"Dispersion" [mm]');
2267                xlabel(H_Axes,'Horizontal BPM Number');
2268                axis tight
2269            else
2270                % Horizontal and vertical dispersion
2271                NHBPM = length(BPMData(i).HBPMGoodDataIndex);
2272                NVBPM = length(BPMData(i).VBPMGoodDataIndex);
2273                NBPM  = NHBPM + NVBPM;
2274                NHCM = length(CMData(i).HCMGoodDataIndex);
2275                NVCM = length(CMData(i).VCMGoodDataIndex);
2276               
2277                if isempty(LocoModel(i).Eta)
2278                    EtaModel = NaN;
2279                    fprintf('   Model dispersion is empty.\n');
2280                else
2281                    EtaModel = LocoModel(i).Eta;                   
2282                end
2283                if isempty(LocoMeasData.Eta)
2284                    EtaMeas = NaN;
2285                    fprintf('   Measured dispersion is empty.\n');
2286                else
2287                    EtaMeas = LocoMeasData.Eta([BPMData(i).HBPMGoodDataIndex length(BPMData(i).HBPMIndex)+BPMData(i).VBPMGoodDataIndex]);
2288                end
2289               
2290                plot(EtaMeas,'-b');
2291                hold on;
2292                plot(EtaModel,'--r');       
2293               
2294                % Add circles for the outliers                   
2295                EtaOutliers = LocoModel(i).EtaOutlierIndex;
2296                x = 1:length(EtaMeas);
2297                if ~isempty(EtaOutliers)
2298                    plot(x(EtaOutliers),EtaMeas(EtaOutliers),'ob','MarkerSize',2);
2299                    if all(isnan(EtaModel))
2300                        fprintf('   Model dispersion is NaN.\n');
2301                        legend('Measured','Outliers',0);
2302                    else
2303                        legend('Measured','Model','Outliers',0);
2304                    end
2305                else
2306                    if all(isnan(EtaModel))
2307                        fprintf('   Model dispersion is NaN.\n');
2308                        %legend off
2309                        legend('Measured',0);
2310                    else
2311                        legend('Measured','Model',0);
2312                    end
2313                end
2314               
2315                hold off
2316                title(sprintf('"Dispersion" Function (%d BPMs)',length(EtaModel)));
2317                ylabel(H_Axes,'"Dispersion" [mm]');
2318                xlabel(H_Axes,'BPM Number');
2319               
2320                % Change label to BPM numbers
2321                Nx = length(EtaMeas);
2322                Ticks = 1:ceil(Nx/10):Nx;
2323                set(H_Axes, 'XTick', Ticks);     
2324                TickNumber = [BPMData(i).HBPMGoodDataIndex BPMData(i).VBPMGoodDataIndex];
2325                TickNumber = TickNumber(Ticks);
2326                set(H_Axes, 'XTickLabel', num2cell(TickNumber));         
2327                xlabel(H_Axes,'HBPM# and VBPM#');
2328               
2329                axis tight
2330            end
2331           
2332        case 23
2333            % Vertical dispersion function   
2334            plot(0,0); set(H_Axes,'XTick',[]); set(H_Axes,'YTick',[]); cla; title(H_Axes,' '); xlabel(H_Axes,' '); ylabel(H_Axes,' ');
2335           
2336            % Only plotting vertical dispersion   
2337            NHBPM = length(BPMData(i).HBPMGoodDataIndex);
2338            NVBPM = length(BPMData(i).VBPMGoodDataIndex);
2339            NBPM  = NHBPM + NVBPM;
2340            NHCM = length(CMData(i).HCMGoodDataIndex);
2341            NVCM = length(CMData(i).VCMGoodDataIndex);
2342           
2343            x = 1:length(BPMData(i).VBPMIndex);
2344            x = x(BPMData(i).VBPMGoodDataIndex);
2345           
2346            if isempty(LocoModel(i).Eta)
2347                EtaModel = NaN*ones(size(x))';
2348                fprintf('   Model dispersion is empty.\n');
2349            else
2350                EtaModel = LocoModel(i).Eta(NHBPM+(1:NVBPM));
2351            end
2352            if isempty(LocoMeasData.Eta)
2353                EtaMeas = NaN*ones(size(x))';
2354                fprintf('   Measured dispersion is empty.\n');
2355            else
2356                EtaMeas = LocoMeasData.Eta(length(BPMData(i).HBPMIndex)+BPMData(i).VBPMGoodDataIndex);
2357            end
2358           
2359            plot(x, EtaMeas,'-b');
2360            hold on;
2361            plot(x, EtaModel,'--r');       
2362           
2363            % Add circles for the outliers                   
2364            EtaOutliers = LocoModel(i).EtaOutlierIndex;
2365            j = find(EtaOutliers > NHBPM);      % Only vertical data
2366            EtaOutliers = EtaOutliers(j) - NHBPM;
2367            if ~isempty(j)
2368                hold on
2369                plot(x(EtaOutliers), EtaMeas(EtaOutliers), 'og', 'MarkerSize',2);
2370                hold off
2371                legend('Measured', 'Model', 'Outliers', 0);
2372            else
2373                legend('Measured','Model',0);
2374            end
2375           
2376            hold off
2377            title(sprintf('"Dispersion" Function (%d BPMs)',length(EtaModel)));
2378            ylabel(H_Axes,'"Dispersion" [mm]');
2379            xlabel(H_Axes,'Vertical BPM Number');
2380            axis tight
2381           
2382        case 24 
2383            % Dispersion function error
2384            plot(0,0); set(H_Axes,'XTick',[]); set(H_Axes,'YTick',[]); cla; title(H_Axes,' '); xlabel(H_Axes,' '); ylabel(H_Axes,' ');
2385           
2386            % Horizontal dispersion
2387            if 1
2388                % Only plot horizontal dispersion 
2389                NHBPM = length(BPMData(i).HBPMGoodDataIndex);
2390                x = 1:length(BPMData(i).HBPMIndex);
2391                x = x(BPMData(i).HBPMGoodDataIndex);
2392               
2393                if isempty(LocoModel(i).Eta)
2394                    EtaModel = NaN*ones(size(x))';
2395                    fprintf('   Model dispersion is empty.\n');
2396                else
2397                    EtaModel = LocoModel(i).Eta(1:NHBPM);                   
2398                end
2399                if isempty(LocoMeasData.Eta)
2400                    EtaMeas = NaN*ones(size(x))';
2401                    fprintf('   Measured dispersion is empty.\n');
2402                else
2403                    EtaMeas = LocoMeasData.Eta(BPMData(i).HBPMGoodDataIndex);
2404                end
2405               
2406                plot(x, EtaMeas-EtaModel,'-b');
2407               
2408                % Add circles for the outliers                   
2409                EtaOutliers = LocoModel(i).EtaOutlierIndex;
2410                j = find(EtaOutliers <= NHBPM);      % Only horizontal data
2411                if ~isempty(j)
2412                    hold on;
2413                    plot(x(EtaOutliers(j)),EtaMeas(EtaOutliers(j))-EtaModel(EtaOutliers(j)),'og','MarkerSize',2);
2414                    hold off;
2415                    legend('Measured-Model','Outliers',0);
2416                end
2417               
2418                if all(isnan(EtaModel))
2419                    fprintf('   Model dispersion is NaN.\n');
2420                    legend off
2421                end
2422               
2423                hold off
2424                title(sprintf('"Dispersion" Function Error (%d BPMs)',length(EtaModel)));
2425                ylabel(H_Axes,'"Dispersion" Error [mm]');
2426                xlabel(H_Axes,'Horizontal BPM Number');
2427                axis tight
2428            else
2429                % Horizontal and vertical dispersion
2430                NHBPM = length(BPMData(i).HBPMGoodDataIndex);
2431                NVBPM = length(BPMData(i).VBPMGoodDataIndex);
2432                NBPM  = NHBPM + NVBPM;
2433                NHCM = length(CMData(i).HCMGoodDataIndex);
2434                NVCM = length(CMData(i).VCMGoodDataIndex);
2435               
2436                if isempty(LocoModel(i).Eta)
2437                    EtaModel = NaN;
2438                    fprintf('   Model dispersion is empty.\n');
2439                else
2440                    EtaModel = LocoModel(i).Eta;                   
2441                end
2442                if isempty(LocoMeasData.Eta)
2443                    EtaMeas = NaN;
2444                    fprintf('   Measured dispersion is empty.\n');
2445                else
2446                    EtaMeas = LocoMeasData.Eta([BPMData(i).HBPMGoodDataIndex length(BPMData(i).HBPMIndex)+BPMData(i).VBPMGoodDataIndex]);
2447                end
2448               
2449                plot(EtaMeas-EtaModel,'-b');
2450               
2451                % Add circles for the outliers                   
2452                EtaOutliers = LocoModel(i).EtaOutlierIndex;
2453                x = 1:length(EtaMeas);
2454                if ~isempty(EtaOutliers)
2455                    hold on;
2456                    plot(x(EtaOutliers),EtaMeas(EtaOutliers)-EtaModel(EtaOutliers),'og','MarkerSize',2);
2457                    hold off;
2458                    legend('Measured-Model','Outliers',0);
2459                end
2460               
2461                hold off
2462                title(sprintf('"Dispersion" Function Error (%d BPMs)',length(EtaModel)));
2463                ylabel(H_Axes,'"Dispersion" Error [mm]');
2464                xlabel(H_Axes,'BPM Number');
2465               
2466                % Change label to BPM numbers
2467                Nx = length(EtaMeas);
2468                Ticks = 1:ceil(Nx/10):Nx;
2469                set(H_Axes, 'XTick', Ticks);     
2470                TickNumber = [BPMData(i).HBPMGoodDataIndex BPMData(i).VBPMGoodDataIndex];
2471                TickNumber = TickNumber(Ticks);
2472                set(H_Axes, 'XTickLabel', num2cell(TickNumber));         
2473                xlabel(H_Axes,'HBPM# and VBPM#');
2474               
2475                axis tight
2476            end
2477           
2478        case 25
2479            % Vertical dispersion error function   
2480            plot(0,0); set(H_Axes,'XTick',[]); set(H_Axes,'YTick',[]); cla; title(H_Axes,' '); xlabel(H_Axes,' '); ylabel(H_Axes,' ');
2481           
2482            % Only plotting vertical dispersion   
2483            NHBPM = length(BPMData(i).HBPMGoodDataIndex);
2484            NVBPM = length(BPMData(i).VBPMGoodDataIndex);
2485            NBPM  = NHBPM + NVBPM;
2486            NHCM = length(CMData(i).HCMGoodDataIndex);
2487            NVCM = length(CMData(i).VCMGoodDataIndex);
2488           
2489            x = 1:length(BPMData(i).VBPMIndex);
2490            x = x(BPMData(i).VBPMGoodDataIndex);
2491           
2492            if isempty(LocoModel(i).Eta)
2493                EtaModel = NaN*ones(size(x))';
2494                fprintf('   Model dispersion is empty.\n');
2495            else
2496                EtaModel = LocoModel(i).Eta(NHBPM+(1:NVBPM));
2497            end
2498            if isempty(LocoMeasData.Eta)
2499                EtaMeas = NaN*ones(size(x))';
2500                fprintf('   Measured dispersion is empty.\n');
2501            else
2502                EtaMeas = LocoMeasData.Eta(length(BPMData(i).HBPMIndex)+BPMData(i).VBPMGoodDataIndex);
2503            end
2504           
2505            plot(x, EtaMeas-EtaModel,'-b');
2506           
2507            % Add circles for the outliers                   
2508            EtaOutliers = LocoModel(i).EtaOutlierIndex;
2509            j = find(EtaOutliers > NHBPM);      % Only vertical data
2510            EtaOutliers = EtaOutliers(j) - NHBPM;
2511            if ~isempty(j)
2512                hold on
2513                plot(x(EtaOutliers), EtaMeas(EtaOutliers)-EtaModel(EtaOutliers), 'og', 'MarkerSize',2);
2514                hold off
2515                legend('Measured-Model','Outliers',0);
2516            end
2517           
2518            title(sprintf('"Dispersion" Function Error (%d BPMs)',length(EtaModel)));
2519            ylabel(H_Axes,'"Dispersion" Error [mm]');
2520            xlabel(H_Axes,'Vertical BPM Number');
2521            axis tight
2522           
2523        case 26
2524            % Horizontal Beta
2525            plot(H_Axes,[0 1],[0 1],'w'); set(H_Axes,'XTick',[]); set(H_Axes,'YTick',[]); cla; title(H_Axes,' '); xlabel(H_Axes,' '); ylabel(H_Axes,' ');
2526            set(H_Axes,'box','on');
2527            text(4,11,sprintf('Please wait ...'),'units','characters');
2528            text(4, 9,sprintf('Computing Beta Functions'),'units','characters');
2529            drawnow;
2530           
2531            [Beta1, Tune1] = locodata({BPMData, CMData, LocoMeasData, LocoModel, FitParameters, LocoFlags, RINGData}, i-1, 'Beta',[],'Tune',[]);
2532            if ~isempty(Beta1) && isreal(Beta1)
2533                plot(Beta1(:,3), Beta1(:,1), 'b');
2534                xlabel(H_Axes,'Position [meters]');
2535                ylabel(H_Axes,'Horizontal Beta Function [meters]');
2536                title(texlabel(sprintf('Model Beta Function (nu_x=%.4f)',Tune1(1))));
2537                try
2538                    L = findspos(RINGData.Lattice,length(RINGData.Lattice)+1);
2539                    if ~isempty(Beta1)
2540                        set(H_Axes, 'XLim', [0 L]);
2541                    end
2542                catch
2543                end
2544            else
2545                plot(H_Axes,[0 1],[0 1],'w');
2546                title(H_Axes,'');
2547                set(H_Axes,'box','on');
2548                set(H_Axes,'XTick',[]);
2549                set(H_Axes,'YTick',[]);
2550                text(4, 9,sprintf('There was a problem computing the beta function.'),'units','characters');
2551                drawnow;
2552            end
2553           
2554        case 27
2555            % Vertical Beta
2556            plot(H_Axes,[0 1],[0 1],'w'); set(H_Axes,'XTick',[]); set(H_Axes,'YTick',[]); cla; title(H_Axes,' '); xlabel(H_Axes,' '); ylabel(H_Axes,' ');
2557            set(H_Axes,'box','on');
2558            text(4,11,sprintf('Please wait ...'),'units','characters');
2559            text(4, 9,sprintf('Computing Beta Functions'),'units','characters');
2560            drawnow;
2561           
2562            [Beta1, Tune1] = locodata({BPMData, CMData, LocoMeasData, LocoModel, FitParameters, LocoFlags, RINGData}, i-1, 'Beta',[],'Tune',[]);
2563            if ~isempty(Beta1) && isreal(Beta1)
2564                plot(Beta1(:,3), Beta1(:,2), 'b');
2565                xlabel(H_Axes,'Position [meters]');
2566                ylabel(H_Axes,'Vertical Beta Function [meters]');
2567                title(texlabel(sprintf('Model Beta Function (nu_y=%.4f)', Tune1(2))));
2568                try
2569                    L = findspos(RINGData.Lattice,length(RINGData.Lattice)+1);
2570                    if ~isempty(Beta1)
2571                        set(H_Axes, 'XLim', [0 L]);
2572                    end
2573                catch
2574                end
2575            else
2576                plot(H_Axes,[0 1],[0 1],'w');
2577                title(H_Axes,'');
2578                set(H_Axes,'box','on');
2579                set(H_Axes,'XTick',[]);
2580                set(H_Axes,'YTick',[]);
2581                text(4, 9,sprintf('There was a problem computing the beta function.'),'units','characters');
2582                drawnow;
2583            end
2584
2585        case 28
2586            % Horizontal Beta Beat
2587            plot(H_Axes,[0 1],[0 1],'w'); set(H_Axes,'XTick',[]); set(H_Axes,'YTick',[]); cla; title(H_Axes,' '); xlabel(H_Axes,' '); ylabel(H_Axes,' ');
2588            set(H_Axes,'box','on');
2589            text(4,11,sprintf('Please wait ...'),'units','characters');
2590            text(4, 9,sprintf('Computing Beta Functions'),'units','characters');
2591            drawnow;
2592           
2593            [Beta1, Tune1] = locodata({BPMData, CMData, LocoMeasData, LocoModel, FitParameters, LocoFlags, RINGData}, i-1, 'Beta',[],'Tune',[]);
2594            [Beta0, Tune0] = locodata({BPMData, CMData, LocoMeasData, LocoModel, FitParameters, LocoFlags, RINGData},   0, 'Beta',[],'Tune',[]);
2595            if ~isempty(Beta1) && ~isempty(Beta0) && isreal(Beta1) && isreal(Beta0)
2596                %plot(Beta1(:,3), Beta1(:,1)-Beta0(:,1), 'b');
2597                %ylabel(sprintf('Horizontal Beta(%d)-Beta(0) [meters]',i-1));
2598                plot(Beta1(:,3), Beta1(:,1)./Beta0(:,1), 'b');
2599                ylabel(sprintf('Horizontal Beta(%d)/Beta(0)',i-1));
2600                xlabel(H_Axes,'BPM Position [meters]');
2601                title(texlabel(sprintf('Beta Beat (nu_x(%d)=%.4f, nu_x(0)=%.4f)',i-1, Tune1(1),Tune0(1))));
2602                try
2603                    L = findspos(RINGData.Lattice,length(RINGData.Lattice)+1);
2604                    if ~isempty(Beta1)
2605                        set(H_Axes, 'XLim', [0 L]);
2606                    end
2607                catch
2608                end
2609            else
2610                plot(H_Axes,[0 1],[0 1],'w');
2611                title(H_Axes,'');
2612                set(H_Axes,'box','on');
2613                set(H_Axes,'XTick',[]);
2614                set(H_Axes,'YTick',[]);
2615                text(4, 9,sprintf('There was a problem computing the beta function.'),'units','characters');
2616                drawnow;
2617            end
2618
2619            %h = uimenu(hcmenu, 'Label', 'Beta Beat', 'Callback', 'locogui(''ContextMenuBetaBeat_Callback'',gcbo,[],[])');
2620            %set(h,'Userdata',{'Model-Measured','VCM'});
2621           
2622        case 29
2623            % Vertical Beta Beat
2624            plot(H_Axes,[0 1],[0 1],'w'); set(H_Axes,'XTick',[]); set(H_Axes,'YTick',[]); cla; title(H_Axes,' '); xlabel(H_Axes,' '); ylabel(H_Axes,' ');
2625            set(H_Axes,'box','on');
2626            text(4,11,sprintf('Please wait ...'),'units','characters');
2627            text(4, 9,sprintf('Computing Beta Functions'),'units','characters');
2628            drawnow;
2629           
2630            [Beta1, Tune1] = locodata({BPMData, CMData, LocoMeasData, LocoModel, FitParameters, LocoFlags, RINGData}, i-1, 'Beta',[],'Tune',[]);
2631            [Beta0, Tune0] = locodata({BPMData, CMData, LocoMeasData, LocoModel, FitParameters, LocoFlags, RINGData},   0, 'Beta',[],'Tune',[]);
2632            if ~isempty(Beta1) && ~isempty(Beta0) && isreal(Beta1) && isreal(Beta0)
2633                %plot(Beta1(:,3), Beta1(:,2)-Beta0(:,2), 'b');
2634                %ylabel(sprintf('Vertical Beta(%d)-Beta(0) [meters]',i-1));
2635                plot(Beta1(:,3), Beta1(:,2)./Beta0(:,2), 'b');
2636                ylabel(sprintf('Vertical Beta(%d)/Beta(0)',i-1));
2637                xlabel(H_Axes,'BPM Position [meters]');
2638                title(texlabel(sprintf('Beta Beat (nu_y(%d)=%.4f, nu_y(0)=%.4f)',i-1, Tune1(2),Tune0(2))));
2639                try
2640                    L = findspos(RINGData.Lattice,length(RINGData.Lattice)+1);
2641                    if ~isempty(Beta1)
2642                        set(H_Axes, 'XLim', [0 L]);
2643                    end
2644                catch
2645                end
2646            else
2647                plot(H_Axes,[0 1],[0 1],'w');
2648                title(H_Axes,'');
2649                set(H_Axes,'box','on');
2650                set(H_Axes,'XTick',[]);
2651                set(H_Axes,'YTick',[]);
2652                text(4, 9,sprintf('There was a problem computing the beta function.'),'units','characters');
2653                drawnow;
2654            end
2655           
2656        case 30
2657            if isempty(Mmodel)
2658                set(H_Axes,'XTick',[]); set(H_Axes,'YTick',[]); cla; title(H_Axes,' '); xlabel(H_Axes,' '); ylabel(H_Axes,' ');
2659            else
2660                locoplotrms({BPMData, CMData, LocoMeasData, LocoModel, FitParameters, LocoFlags, RINGData}, i-1, 1);
2661            end
2662        case 31
2663            if isempty(Mmodel)
2664                set(H_Axes,'XTick',[]); set(H_Axes,'YTick',[]); cla; title(H_Axes,' '); xlabel(H_Axes,' '); ylabel(H_Axes,' ');
2665            else
2666                locoplotrms({BPMData, CMData, LocoMeasData, LocoModel, FitParameters, LocoFlags, RINGData}, i-1, 3);
2667            end
2668
2669        case 32
2670            if isempty(Mmodel)
2671                set(H_Axes,'XTick',[]); set(H_Axes,'YTick',[]); cla; title(H_Axes,' '); xlabel(H_Axes,' '); ylabel(H_Axes,' ');
2672            else
2673                locoplotrms({BPMData, CMData, LocoMeasData, LocoModel, FitParameters, LocoFlags, RINGData}, i-1, 2);
2674            end
2675        case 33
2676            if isempty(Mmodel)
2677                set(H_Axes,'XTick',[]); set(H_Axes,'YTick',[]); cla; title(H_Axes,' '); xlabel(H_Axes,' '); ylabel(H_Axes,' ');
2678            else
2679                locoplotrms({BPMData, CMData, LocoMeasData, LocoModel, FitParameters, LocoFlags, RINGData}, i-1, 4);
2680            end
2681    end
2682   
2683catch
2684    set(H_Axes,'XTick',[]); set(H_Axes,'YTick',[]); cla; title(H_Axes,' '); xlabel(H_Axes,' '); ylabel(H_Axes,' ');
2685    fprintf('Plot failed: %s\n', lasterr);
2686end
2687
2688axes(findobj(gcbf,'Tag','ChiSquare'));
2689cla;
2690if ~isempty(LocoModel(i).ChiSquare)
2691    if LocoModel(i).ChiSquare~=0
2692        text(0,.5,sprintf('\\fontsize{12}\\chi^{2}_{\\fontsize{8}total} \\fontsize{9}/ D.O.F \\fontsize{10}= %f', LocoModel(i).ChiSquare));
2693    end
2694end
2695
2696drawnow;
2697
2698
2699% % --------------------------------------------------------------------
2700% function varargout = ContextMenuBetaBeat_Callback(h, eventdata, handles, varargin)
2701% %FieldName = get(h,'Userdata');
2702%
2703% FileName = get(findobj(gcbf,'Tag','FileName'),'Userdata');
2704% if isempty(FileName)
2705%     return
2706% end
2707% try
2708%     load(FileName);
2709% catch
2710%     fprintf('   File does not exist or is not a *.mat file type.\n');
2711%     cla;
2712%     return
2713% end
2714%
2715% i = get(findobj(gcbf,'Tag','PlotIteration'),'Value');  % The first point in the array is starting point
2716
2717
2718
2719% --------------------------------------------------------------------
2720function varargout = ContextCostFunctionPlot_Callback(h, eventdata, handles, varargin)
2721Userdata = get(h,'Userdata');
2722FieldName = Userdata{1};
2723H_Axes = Userdata{2};
2724
2725AxesTag = get(gca,'Tag');
2726if strcmp(AxesTag,'Axes1')
2727    setappdata(gcbf, 'CostFunctionPlot1', Userdata);
2728elseif strcmp(AxesTag,'Axes2')
2729    setappdata(gcbf, 'CostFunctionPlot2', Userdata);
2730end
2731
2732PlotCostFunction;
2733
2734
2735function PlotCostFunction
2736
2737LogPlotFlag = 1;
2738
2739AxesTag = get(gca,'Tag');
2740if strcmp(AxesTag,'Axes1')
2741    Userdata = getappdata(gcbf, 'CostFunctionPlot1');
2742    TagString = get(findobj(gcbf,'Tag','PlotMenu1'),'Userdata');   % Axis tag is storage in the menu pulldown
2743elseif strcmp(AxesTag,'Axes2')
2744    Userdata = getappdata(gcbf, 'CostFunctionPlot2');
2745    TagString = get(findobj(gcbf,'Tag','PlotMenu2'),'Userdata');   % Axis tag is storage in the menu pulldown
2746end
2747
2748FieldName = Userdata{1};
2749H_Axes = Userdata{2};
2750
2751FileName = get(findobj(gcbf,'Tag','FileName'),'Userdata');
2752if isempty(FileName)
2753    return
2754end
2755try
2756    load(FileName);
2757catch
2758    fprintf('   File does not exist or is not a *.mat file type.\n');
2759    cla;
2760    return
2761end
2762i = get(findobj(gcbf,'Tag','PlotIteration'),'Value');  % The first point in the array is starting point
2763
2764axes(H_Axes);
2765
2766
2767CostScaleFactor = 1;
2768if strcmpi(LocoFlags(i).Method.Name, 'Gauss-Newton With Cost Function') && isfield(LocoFlags(i).Method, 'CostScaleFactor') && ~isempty(LocoFlags(i).Method.CostScaleFactor)
2769    CostScaleFactor = LocoFlags(i).Method.CostScaleFactor;
2770end
2771
2772
2773if strcmpi(FieldName, 'All')
2774    FieldCell = fieldnames(LocoFlags(i).Method.Cost);
2775    Total = [];
2776    for ifield = 1:length(FieldCell)
2777        NewData = LocoFlags(i).Method.Cost.(FieldCell{ifield});
2778        Total = [Total; NewData(:)];
2779    end
2780    axes(H_Axes);
2781    if LogPlotFlag && all(Total>0)
2782        semilogy(1:length(Total), CostScaleFactor * Total);
2783    else
2784        plot(1:length(Total), CostScaleFactor * Total);
2785    end
2786    title(H_Axes,'');
2787    xlabel(H_Axes,'All Fit Parameters', 'FontSize', 10);
2788    ylabel(H_Axes,'Cost');
2789    title(H_Axes,'Parameter Cost', 'FontSize', 10);
2790else
2791    if LogPlotFlag && all(LocoFlags(i).Method.Cost.(FieldName)>0)
2792        semilogy(1:length(LocoFlags(i).Method.Cost.(FieldName)), CostScaleFactor * LocoFlags(i).Method.Cost.(FieldName));
2793    else
2794        plot(1:length(LocoFlags(i).Method.Cost.(FieldName)), CostScaleFactor * LocoFlags(i).Method.Cost.(FieldName));
2795    end
2796    title(H_Axes,'');
2797    xlabel(H_Axes,sprintf('%s Number', FieldName), 'FontSize', 10);
2798    ylabel(H_Axes,'Cost');
2799    title(H_Axes,sprintf('Parameter Cost for %s', FieldName), 'FontSize', 10);
2800end
2801%grid  on;
2802a1 = axis;
2803axis tight;
2804a2 = axis;
2805axis([a2(1:2) a1(3:4)]);
2806
2807set(gca,'Tag',TagString);                 % axes tag is lost if plot function is used
2808set(gca,'HandleVisibility','Callback');   % So no one else can plot to it.
2809
2810
2811
2812
2813% --------------------------------------------------------------------
2814function varargout = ContextPartialChi2Plot_Callback(h, eventdata, handles, varargin)
2815Userdata = get(h,'Userdata');
2816FieldName = Userdata{1};
2817H_Axes = Userdata{2};
2818
2819AxesTag = get(gca,'Tag');
2820if strcmp(AxesTag,'Axes1')
2821    setappdata(gcbf, 'PartialChi2Plot1', Userdata);
2822elseif strcmp(AxesTag,'Axes2')
2823    setappdata(gcbf, 'PartialChi2Plot2', Userdata);
2824end
2825
2826PlotPartialChi2;
2827
2828
2829function PlotPartialChi2
2830
2831LogPlotFlag = 1;
2832
2833AxesTag = get(gca,'Tag');
2834if strcmp(AxesTag,'Axes1')
2835    Userdata = getappdata(gcbf, 'PartialChi2Plot1');
2836    TagString = get(findobj(gcbf,'Tag','PlotMenu1'),'Userdata');   % Axis tag is storage in the menu pulldown
2837elseif strcmp(AxesTag,'Axes2')
2838    Userdata = getappdata(gcbf, 'PartialChi2Plot2');
2839    TagString = get(findobj(gcbf,'Tag','PlotMenu2'),'Userdata');   % Axis tag is storage in the menu pulldown
2840end
2841
2842FieldName = Userdata{1};
2843H_Axes = Userdata{2};
2844
2845FileName = get(findobj(gcbf,'Tag','FileName'),'Userdata');
2846if isempty(FileName)
2847    return
2848end
2849try
2850    load(FileName);
2851catch
2852    fprintf('   File does not exist or is not a *.mat file type.\n');
2853    cla;
2854    return
2855end
2856i = get(findobj(gcbf,'Tag','PlotIteration'),'Value');  % The first point in the array is starting point
2857
2858axes(H_Axes);
2859
2860if strcmpi(FieldName, 'All')
2861    FieldCell = fieldnames(LocoFlags(i).Method.PartialChi2);
2862    Total = [];
2863    for ifield = 1:length(FieldCell)
2864        NewData = LocoFlags(i).Method.PartialChi2.(FieldCell{ifield});
2865        Total = [Total; NewData(:)];
2866    end
2867    axes(H_Axes);
2868    if LogPlotFlag
2869        semilogy(1:length(Total), Total);
2870    else
2871        plot(1:length(Total), Total);
2872    end
2873    title(H_Axes,'');
2874    xlabel(H_Axes,'All Fit Parameters', 'FontSize', 10);
2875    ylabel(H_Axes,'\fontsize{14}\partial \chi^2 / \partial \fontsize{9}Fit Parameter');
2876    title(H_Axes,'Change in \chi^2 w.r.t. Each Fit Parameter', 'FontSize', 10);
2877else
2878    if LogPlotFlag
2879        semilogy(1:length(LocoFlags(i).Method.PartialChi2.(FieldName)), LocoFlags(i).Method.PartialChi2.(FieldName));
2880    else
2881        plot(1:length(LocoFlags(i).Method.PartialChi2.(FieldName)), LocoFlags(i).Method.PartialChi2.(FieldName));
2882    end
2883    title(H_Axes,'');
2884    xlabel(H_Axes,sprintf('%s Number', FieldName), 'FontSize', 10);
2885    ylabel(H_Axes,sprintf('\\fontsize{14}\\partial \\chi^2 / \\partial \\fontsize{10}%s', FieldName));
2886    title(H_Axes,sprintf('Change in \\chi^2 w.r.t. Each %s Fit Parameter', FieldName), 'FontSize', 10);
2887end
2888%grid  on;
2889a1 = axis;
2890axis tight;
2891a2 = axis;
2892axis([a2(1:2) a1(3:4)]);
2893
2894set(gca,'Tag',TagString);                 % axes tag is lost if plot function is used
2895set(gca,'HandleVisibility','Callback');   % So no one else can plot to it.
2896
2897
2898% --------------------------------------------------------------------
2899function varargout = ContextMenuPlot_Callback(h, eventdata, handles, varargin)
2900FieldName = get(h,'Userdata');
2901
2902AxesTag = get(gca,'Tag');
2903if strcmp(AxesTag,'Axes1')
2904    TagString = get(findobj(gcbf,'Tag','PlotMenu1'),'Userdata');   % Axis tag is storage in the menu pulldown
2905    setappdata(gcbf,'OtherParameterPlot1',FieldName);
2906elseif strcmp(AxesTag,'Axes2')
2907    TagString = get(findobj(gcbf,'Tag','PlotMenu2'),'Userdata');   % Axis tag is storage in the menu pulldown
2908    setappdata(gcbf,'OtherParameterPlot2',FieldName);
2909else
2910    %error('problem with AxesTag name')
2911end
2912h_axis = findobj(gcbf,'Tag',TagString);
2913axes(h_axis);
2914locoplots(15, FieldName);
2915
2916axes(h_axis);
2917legend
2918set(gca,'Tag',TagString);                 % axes tag is lost if plot function is used
2919set(gca,'HandleVisibility','Callback');   % So no one else can plot to it.
2920
2921
2922% --------------------------------------------------------------------
2923function varargout = ContextMenuSurfPlot_Callback(h, eventdata, handles, varargin)
2924FieldName = get(h,'Userdata');
2925
2926AxesTag = get(gca,'Tag');
2927if strcmp(AxesTag,'Axes1')
2928    TagString = get(findobj(gcbf,'Tag','PlotMenu1'),'Userdata');   % Axis tag is storage in the menu pulldown
2929    h1 = findobj(gcbf,'Tag','SurfPlot1');
2930    set(h1,'Userdata', FieldName);
2931elseif strcmp(AxesTag,'Axes2')
2932    TagString = get(findobj(gcbf,'Tag','PlotMenu2'),'Userdata');   % Axis tag is storage in the menu pulldown
2933    h1 = findobj(gcbf,'Tag','SurfPlot2');
2934    set(h1,'Userdata', FieldName);
2935else
2936    %error('problem with AxesTag name')
2937end
2938
2939h_axis = findobj(gcbf,'Tag',TagString);
2940axes(h_axis);
2941
2942%FileName = get(findobj(gcbf,'Tag','FileName'),'Userdata');
2943LocoDataCell = getappdata(gcbf, 'LocoDataCell');
2944Iteration = get(findobj(gcbf,'Tag','PlotIteration'),'Value')-1;
2945ElementsInput = locoplot(LocoDataCell, Iteration, FieldName{1}, FieldName{2});
2946
2947FieldName{3} = ElementsInput;
2948set(h1,'Userdata', FieldName);
2949
2950set(gca,'Tag',TagString);                 % axes tag is lost if plot function is used
2951set(gca,'HandleVisibility','Callback');   % So no one else can plot to it.
2952
2953
2954
2955function [Mmodel, Dispersion, ChiSquare] = getmodelresponsematrix(BPMData, CMData, FitParameters, LocoFlags, LocoMeasData, RINGData)
2956
2957% Save the current axes
2958H_Axes = gca;
2959
2960% UNITS CONVERSIONS (to be combatible with tracking code)
2961% Convert corrector kicks used in the response matrix to radians
2962CMData.HCMKicks = CMData.HCMKicks(:) / 1000;   % milliradian to radians (column vector)
2963CMData.VCMKicks = CMData.VCMKicks(:) / 1000;   % milliradian to radians (column vector)
2964
2965% Convert the measured response matrix to meters
2966LocoMeasData.M = LocoMeasData.M / 1000;
2967
2968% Convert the BPMSTD to meters and make the same size as a response matrix
2969LocoMeasData.BPMSTD = LocoMeasData.BPMSTD / 1000;    % mm to meters
2970
2971% Convert orbit for "dispersion" in meters in column vector format
2972LocoMeasData.Eta = LocoMeasData.Eta(:) / 1000;       % mm to meters
2973% END UNITS CONVERTSION
2974
2975
2976% % Check for a new (user input) BPM and CM good data lists 
2977% if ~isempty(get(findobj(gcbf,'Tag','HBPMIndex'), 'Userdata'))
2978%     BPMData.HBPMGoodDataIndex = get(findobj(gcf,'Tag','HBPMIndex'), 'Userdata');
2979% end
2980% if ~isempty(get(findobj(gcbf,'Tag','VBPMIndex'), 'Userdata'))
2981%     BPMData.VBPMGoodDataIndex = get(findobj(gcf,'Tag','VBPMIndex'), 'Userdata');
2982% end
2983% if ~isempty(get(findobj(gcbf,'Tag','HCMIndex'), 'Userdata'))
2984%     CMData.HCMGoodDataIndex = get(findobj(gcf,'Tag','HCMIndex'), 'Userdata');
2985% end
2986% if ~isempty(get(findobj(gcbf,'Tag','VCMIndex'), 'Userdata'))
2987%     CMData.VCMGoodDataIndex = get(findobj(gcf,'Tag','VCMIndex'), 'Userdata');
2988% end
2989
2990
2991% Limit the correctors to the good ones
2992if isfield(CMData, 'FamName')
2993    CMDataRM.FamName = CMData.FamName;
2994end
2995CMDataRM.HCMIndex = CMData.HCMIndex(CMData.HCMGoodDataIndex);
2996CMDataRM.VCMIndex = CMData.VCMIndex(CMData.VCMGoodDataIndex);
2997CMDataRM.HCMKicks = CMData.HCMKicks(CMData.HCMGoodDataIndex);
2998CMDataRM.VCMKicks = CMData.VCMKicks(CMData.VCMGoodDataIndex);
2999CMDataRM.HCMCoupling = CMData.HCMCoupling(CMData.HCMGoodDataIndex);
3000CMDataRM.VCMCoupling = CMData.VCMCoupling(CMData.VCMGoodDataIndex);
3001CMDataRM.HCMEnergyShift = CMData.HCMEnergyShift(CMData.HCMGoodDataIndex);
3002CMDataRM.VCMEnergyShift = CMData.VCMEnergyShift(CMData.VCMGoodDataIndex);
3003
3004% Set the lattice model to the starting LocoValues
3005for i = 1:length(FitParameters.Params)
3006    RINGData = locosetlatticeparam(RINGData, FitParameters.Params{i}, FitParameters.Values(i));
3007end
3008
3009plot(H_Axes,[0 1],[0 1],'w');
3010title(H_Axes,'RF Frequency');
3011set(gca,'box','on');
3012set(gca,'XTick',[]);
3013set(gca,'YTick',[]);
3014text(4,11,sprintf('Please wait ...'),'units','characters');
3015text(4, 9,sprintf('Computing nominal response matrix'),'units','characters');
3016text(4, 8,sprintf('                   and dispersion.'),'units','characters');
3017drawnow;
3018
3019% Find nominal response matrix and dispersion
3020if isempty(FitParameters.DeltaRF)
3021    fprintf('   Computing nominal response matrix (%s, %s) ... ', LocoFlags.ResponseMatrixCalculator, LocoFlags.ClosedOrbitType); tic
3022    LocoFlags.Dispersion = 'no';
3023    LocoFlags.ClosedOrbitType = 'FixedPathLength';
3024    Mmodel = locoresponsematrix(RINGData, BPMData, CMDataRM, LocoFlags);
3025else
3026    fprintf('   Computing nominal response matrix and dispersion (%s, %s) ... ', LocoFlags.ResponseMatrixCalculator, LocoFlags.ClosedOrbitType); tic
3027    Mmodel = locoresponsematrix(RINGData, BPMData, CMDataRM, LocoFlags, 'RF', FitParameters.DeltaRF);
3028end
3029fprintf('%f seconds. \n',toc);
3030
3031if isempty(LocoMeasData.Eta) || any(isnan(LocoMeasData.Eta))
3032    % Don't computer Chi^2 for with dispersion if the measured dispersion is emmpty or NaN
3033    LocoFlags.Dispersion = 'no';
3034end
3035
3036plot(0,0); set(gca,'XTick',[]); set(gca,'YTick',[]); cla; title(H_Axes,' '); xlabel(H_Axes,' '); ylabel(H_Axes,' ');
3037
3038% Rotate Mmodel and remove BPMs not in the measured response matrix
3039C11 = ones(length(BPMData.BPMIndex),1);
3040C11(BPMData.HBPMIndex(BPMData.HBPMGoodDataIndex)) = BPMData.HBPMGain(BPMData.HBPMGoodDataIndex);
3041
3042C12 = zeros(length(BPMData.BPMIndex),1);
3043C12(BPMData.HBPMIndex(BPMData.HBPMGoodDataIndex)) = BPMData.HBPMCoupling(BPMData.HBPMGoodDataIndex);
3044
3045C21 = zeros(length(BPMData.BPMIndex),1);
3046C21(BPMData.VBPMIndex(BPMData.VBPMGoodDataIndex)) = BPMData.VBPMCoupling(BPMData.VBPMGoodDataIndex);
3047
3048C22 = ones(length(BPMData.BPMIndex),1);
3049C22(BPMData.VBPMIndex(BPMData.VBPMGoodDataIndex)) = BPMData.VBPMGain(BPMData.VBPMGoodDataIndex);
3050
3051C = [diag(C11) diag(C12)
3052     diag(C21) diag(C22)];
3053
3054Mmodel = C * Mmodel;
3055
3056clear C C11 C12 C21 C22 
3057
3058% Remove unwanted BPMs  (Change by James S.  3-17-2006)
3059%Mmodel = Mmodel([BPMData.HBPMGoodDataIndex length(BPMData.HBPMIndex)+BPMData.VBPMGoodDataIndex], :);
3060BPMIndexShortX = BPMData.HBPMIndex(BPMData.HBPMGoodDataIndex);
3061BPMIndexShortY = BPMData.VBPMIndex(BPMData.VBPMGoodDataIndex) + length(BPMData.BPMIndex);
3062BPMIndexShort = [BPMIndexShortX(:)' BPMIndexShortY(:)'];
3063Mmodel = Mmodel(BPMIndexShort,:);
3064
3065if isempty(FitParameters.DeltaRF)
3066    Dispersion = [];
3067else
3068    Dispersion = Mmodel(:,end);
3069end
3070
3071
3072% When using the fixed momentum response matrix calculator, the merit function becomes:
3073%              Merit = Mmeas_ij - Mmod_ij - Dp/p_j * eta_i
3074%              where eta_i is the measured eta (not the model eta)
3075% This is done by changing Mmodel to (Mmodel_ij + Dp/p_j * eta_i)
3076%if strcmpi((CMData.FitHCMEnergyShift),'yes') | strcmpi((CMData.FitVCMEnergyShift),'yes')   
3077if strcmpi((LocoFlags.ClosedOrbitType), 'fixedmomentum')
3078    HCMEnergyShift = CMData.HCMEnergyShift(CMData.HCMGoodDataIndex);
3079    VCMEnergyShift = CMData.VCMEnergyShift(CMData.VCMGoodDataIndex);
3080   
3081    AlphaMCF = locomcf(RINGData);
3082    EtaXmcf = -AlphaMCF * LocoMeasData.RF * LocoMeasData.Eta(BPMData.HBPMGoodDataIndex) / LocoMeasData.DeltaRF;
3083    EtaYmcf = -AlphaMCF * LocoMeasData.RF * LocoMeasData.Eta(length(BPMData.HBPMIndex)+BPMData.VBPMGoodDataIndex) / LocoMeasData.DeltaRF;
3084   
3085    for i = 1:length(HCMEnergyShift)
3086        Mmodel(:,i) = Mmodel(:,i) + HCMEnergyShift(i) * [EtaXmcf; EtaYmcf];
3087    end
3088   
3089    NHCM = length(HCMEnergyShift);
3090    for i = 1:length(VCMEnergyShift)
3091        Mmodel(:,NHCM+i) = Mmodel(:,NHCM+i) + VCMEnergyShift(i) * [EtaXmcf; EtaYmcf];
3092    end
3093end
3094
3095
3096% Compute chi-squared based on new model
3097Mmeas = LocoMeasData.M;
3098Mmeas = Mmeas([BPMData.HBPMGoodDataIndex length(BPMData.HBPMIndex)+BPMData.VBPMGoodDataIndex], [CMData.HCMGoodDataIndex length(CMData.HCMIndex)+CMData.VCMGoodDataIndex]);
3099
3100Mstd = LocoMeasData.BPMSTD * ones(1,size(LocoMeasData.M,2));
3101Mstd = Mstd ([BPMData.HBPMGoodDataIndex length(BPMData.HBPMIndex)+BPMData.VBPMGoodDataIndex], [CMData.HCMGoodDataIndex length(CMData.HCMIndex)+CMData.VCMGoodDataIndex]);
3102
3103Xstd = LocoMeasData.BPMSTD(BPMData.HBPMGoodDataIndex);
3104Ystd = LocoMeasData.BPMSTD(length(BPMData.HBPMIndex)+BPMData.VBPMGoodDataIndex);
3105
3106if isempty(LocoMeasData.Eta)
3107    EtaX = NaN * ones(length(BPMData.HBPMGoodDataIndex),1);
3108    EtaY = NaN * ones(length(BPMData.VBPMGoodDataIndex),1);
3109else
3110    EtaX = LocoMeasData.Eta(BPMData.HBPMGoodDataIndex);
3111    EtaY = LocoMeasData.Eta(length(BPMData.HBPMIndex)+BPMData.VBPMGoodDataIndex);
3112end
3113   
3114Mstd  = Mstd(:);
3115Mmeas = Mmeas(:);
3116
3117if strcmpi((LocoFlags.Dispersion),'yes')
3118    Mstd  = [Mstd;  [Xstd; Ystd]];
3119    Mmeas = [Mmeas; [EtaX; EtaY]];
3120else
3121    % Remove dispersion from the model for ChiSquare
3122    if ~isempty(FitParameters.DeltaRF)
3123        Mmodel = Mmodel(:,1:end-1);
3124    end
3125end
3126
3127% Without NumberOfParameters (since no fits were done yet, but this is a little confusing to some)
3128ChiSquare = sum(((Mmeas - Mmodel(:)) ./ Mstd) .^ 2) / length(Mstd);
3129
3130
3131% Remove the disperion for the output is it has not been already removed
3132if strcmpi((LocoFlags.Dispersion),'yes') 
3133    Mmodel = Mmodel(:,1:end-1);
3134end
3135
3136
3137% Unit conversions (back to LOCO units)
3138%CMData.HCMKicks = 1000*CMData.HCMKicks;        % radian to milliradians
3139%CMData.VCMKicks = 1000*CMData.VCMKicks;        % radian to milliradians
3140Mmodel     = 1000 * Mmodel;         % meters to millimeters
3141Dispersion = 1000 * Dispersion;     % meters to millimeters
3142
3143% Start addon Laurent
3144function varargout = uimenu_plotK_Callback(h, eventdata, handles, varargin)
3145
3146LocoDataCell = getappdata(gcbf, 'LocoDataCell');
3147if isempty(LocoDataCell)
3148    FileName = get(findobj(gcbf,'Tag','FileName'),'Userdata');
3149    if isempty(FileName)
3150        fprintf('   File does not exist.\n');
3151        return
3152    end
3153    try
3154        load(FileName);
3155    catch err
3156        fprintf('   File does not exist or is not a *.mat file type.\n');
3157        cla;
3158        return
3159    end
3160else
3161    BPMData       = LocoDataCell{1};
3162    CMData        = LocoDataCell{2};
3163    LocoMeasData  = LocoDataCell{3};
3164    LocoModel     = LocoDataCell{4};
3165    FitParameters = LocoDataCell{5};
3166    LocoFlags     = LocoDataCell{6};
3167    RINGData      = LocoDataCell{7};
3168end
3169
3170i = get(findobj(gcbf,'Tag','PlotIteration'),'Value');  % The first point in the array is starting point
3171
3172% If the LocoModel does not exist, then compute it
3173if isempty(LocoModel(i).M) | isempty(LocoModel(i).Eta) | isempty(LocoModel(i).ChiSquare)
3174    [LocoModel(i).M, LocoModel(i).Eta, LocoModel(i).ChiSquare] = getmodelresponsematrix(BPMData(i), CMData(i), FitParameters(i), ...
3175LocoFlags(i), LocoMeasData, RINGData);
3176    FileName = get(findobj(gcbf,'Tag','FileName'),'Userdata');
3177    save(FileName, 'LocoModel', 'FitParameters', 'BPMData', 'CMData', 'RINGData', 'LocoMeasData', 'LocoFlags');
3178    setappdata(gcbf, 'LocoDataCell', {BPMData, CMData, LocoMeasData, LocoModel, FitParameters, LocoFlags, RINGData});
3179end
3180
3181Mmodel = LocoModel(i).M;
3182 
3183figure
3184[K1, Tune1] = locodata({BPMData, CMData, LocoMeasData, LocoModel,FitParameters, LocoFlags, RINGData}, i-1, 'FitValues',[],'Tune',[]);
3185[K0, Tune0] = locodata({BPMData, CMData, LocoMeasData, LocoModel, FitParameters, LocoFlags, RINGData},   0, 'FitValues',[],'Tune',[]);
3186
3187% count number of quadrupoles, 2 parameters to fit and K
3188quadnum = 0;
3189for k=1:length(FitParameters(1).Params),
3190    if size(FitParameters(1).Params{k},2) == 2 && strcmpi(FitParameters(1).Params{1}(1).FieldName,'K')
3191        quadnum = quadnum+1;
3192    end
3193end
3194
3195if ~isempty(K1) & ~isempty(K0)
3196    if length(K1) > 10 % individual quads
3197        bar((K1(1:quadnum)-K0(1:quadnum))./K1(1:quadnum)*100, 'b');
3198        xlabel('Quadrupole number');
3199        ylabel(sprintf('(K(%d)-K(0))/K0 [%%]',i-1));
3200        title(texlabel(sprintf('DK (nu_x(%d)=%.4f, nu_x(0)=%.4f) (nu_y(%d)=%.4f, nu_y(0)=%.4f)', ...
3201            i-1, Tune1(1),Tune0(1), i-1, Tune1(2),Tune0(2))));
3202        xaxis([0 length(K1(1:quadnum))+1]); grid on; hold on;
3203        a = axis;
3204        plot([9 9], [-8 8],'r-.')
3205        plot([17 17], [-8 8],'r-.')
3206        plot([25 25], [-8 8],'r-.')
3207        plot([41 41], [-8 8],'r-.')
3208        plot([57 57], [-8 8],'r-.')
3209        plot([81 81], [-8 8],'r-.')
3210        plot([105 105], [-8 8],'r-.')
3211        plot([129 129], [-8 8],'r-.')
3212        plot([145 145], [-8 8],'r-.')
3213        if quadnum == 163, % Nanoscopium
3214            plot([161 163], [-8 8],'r-.')
3215        end
3216       
3217        hold off
3218        axis(a);
3219       
3220        % quadrupoles sorted in machine order
3221        quadpos = [getspos('Q1'); getspos('Q2') ; getspos('Q3') ; getspos('Q4'); ...
3222            getspos('Q5') ; getspos('Q6') ; getspos('Q7') ; getspos('Q8'); ...
3223            getspos('Q9'); getspos('Q10')];
3224
3225        if quadnum == 163,  % Nanoscopium
3226            quadpos = [getspos('Q1'); getspos('Q2') ; getspos('Q3') ; getspos('Q4'); ...
3227                getspos('Q5') ; getspos('Q6') ; getspos('Q7') ; getspos('Q8'); ...
3228                getspos('Q9'); getspos('Q10'); getspos('Q11'); getspos('Q12')];
3229        end
3230
3231        [y id] = sort(quadpos);
3232        figure;
3233        h(1) = subplot(5,1,(1:4));
3234        DKoK = (K1(1:quadnum)-K0(1:quadnum))./K0(1:quadnum)*100;
3235        stem(y,DKoK(id));
3236        grid on;
3237        ylabel(sprintf('(K(%d)-K(0))/K0 [%%]',i-1));
3238        h(2) = subplot(5,1,5);
3239        drawlattice
3240        linkaxes(h,'x')
3241       
3242        figure
3243        h(1) = subplot(5,1,(1:4));
3244        bar(getspos('QT'), physics2hw('QT', 'Monitor', K1(quadnum+1:end)), 'b');
3245        title('QT value');
3246        ylabel('Current (A)')
3247        h(2) = subplot(5,1,5);
3248        drawlattice
3249        xlabel('s-position(m)')
3250        linkaxes(h,'x')
3251        xlabel('s-position (m)');
3252    else
3253        bar((K1-K0)./K0*100, 'b');
3254        xlabel('Quadrupole family number');
3255        ylabel(sprintf('(K(%d)-K(0))/K0 [%%]',i-1));
3256        title(texlabel(sprintf('DK (nu_x(%d)=%.4f, nu_x(0)=%.4f) (nu_y(%d)=%.4f, nu_y(0)=%.4f)', ...
3257            i-1, Tune1(1),Tune0(1), i-1, Tune1(2),Tune0(2))));
3258        xaxis([0 length(K1)+1]); grid on; hold on;
3259    end
3260end
3261
3262% exporting data into matlab workspace
3263function varargout = uimenu_exportK_Callback(h, eventdata, handles, varargin)
3264
3265LocoDataCell = getappdata(gcbf, 'LocoDataCell');
3266if isempty(LocoDataCell)
3267    FileName = get(findobj(gcbf,'Tag','FileName'),'Userdata');
3268    if isempty(FileName)
3269        fprintf('   File does not exist.\n');
3270        return
3271    end
3272    try
3273        load(FileName);
3274    catch
3275        fprintf('   File does not exist or is not a *.mat file type.\n');
3276        cla;
3277        return
3278    end
3279else
3280    BPMData       = LocoDataCell{1};
3281    CMData        = LocoDataCell{2};
3282    LocoMeasData  = LocoDataCell{3};
3283    LocoModel     = LocoDataCell{4};
3284    FitParameters = LocoDataCell{5};
3285    LocoFlags     = LocoDataCell{6};
3286    RINGData      = LocoDataCell{7};
3287end
3288
3289i = get(findobj(gcbf,'Tag','PlotIteration'),'Value');  % The first point in the array is starting point
3290
3291% If the LocoModel does not exist, then compute it
3292if isempty(LocoModel(i).M) | isempty(LocoModel(i).Eta) | isempty(LocoModel(i).ChiSquare)
3293    [LocoModel(i).M, LocoModel(i).Eta, LocoModel(i).ChiSquare] = getmodelresponsematrix(BPMData(i), CMData(i), FitParameters(i), ...
3294LocoFlags(i), LocoMeasData, RINGData);
3295    FileName = get(findobj(gcbf,'Tag','FileName'),'Userdata');
3296    save(FileName, 'LocoModel', 'FitParameters', 'BPMData', 'CMData', 'RINGData', 'LocoMeasData', 'LocoFlags');
3297    setappdata(gcbf, 'LocoDataCell', {BPMData, CMData, LocoMeasData, LocoModel, FitParameters, LocoFlags, RINGData});
3298end
3299
3300%global LOCOstruct; % pas beau
3301
3302Mmodel = LocoModel(i).M;
3303 
3304[K1, Tune1] = locodata({BPMData, CMData, LocoMeasData, LocoModel,FitParameters, LocoFlags, RINGData}, i-1, 'FitValues',[],'Tune',[]);
3305[K0, Tune0] = locodata({BPMData, CMData, LocoMeasData, LocoModel, FitParameters, LocoFlags, RINGData},   0, 'FitValues',[],'Tune',[]);
3306
3307if ~isempty(K1) & ~isempty(K0)
3308    LOCOstruct.DKoK = (K1-K0)./K0*100;
3309    LOCOstruct.DK = (K1-K0);
3310    LOCOstruct.CreatedBy = 'locogui';
3311    LOCOstruct.TimeStamp = datestr(now)
3312end
3313
3314assignin('base', 'LOCOstruct', LOCOstruct);
3315% End addon Laurent
Note: See TracBrowser for help on using the repository browser.