Home > Source > Registration > build_1d_bump_model.m

build_1d_bump_model

PURPOSE ^

BUILD_1D_BUMP_MODEL: Builds a 1-D model for some bump data

SYNOPSIS ^

function [status] = build_1d_bump_model(spline_type, placement_type, objective_function, apply_intensity_offset, save_movie, do_plot, movie_type, progress_bar, user_menu, produce_statistics, see_model_before_each_iteration, show_pixels, show_score_vs_iteration, show_model_after_optimisation, show_specificity_statistics, verbose_score, movie_name, window, average_smooth_enabled, gaussian_smooth_enabled, bump_width, bump_width_variation, bump_height, bump_height_variation, bump_position_freedom, initial_diminish_factor, smoothness_factor, plot_before_and_after, number_of_bins, model_evaluation_method, show_score_using_model, handle, n_modes, shape_weight, weighting_normalisation_method, variation_kept, run_all_objective_functions, kernel, save_data, load_data, save_bumps, draw_warp_curve, overlap_scores, show_target, format, filter, filter_level, model_score_type, gen_iters, spec_iters, draw_curve_by_images, show_mesh, mesh_type, exit_at_end, show_all_score_figure_types, close_at_end, frames_per_second, show_score_bar, n_points, show_warp_targets, show_registration_target, produce_record, initialise_warps_close_to_target, save_in_log, perturbation_method, offset_extent, force_reference, cycle, verbose, save_stats, n_modes_display, n_standard_deviations_display, show_warps_while_optimising, description, find_perfect_warp, force_first_reference, display_shape_model, display_intensity_model, plot_alignment, error_verbosity, precision_required, background_red, background_green, background_blue, dynamic_precision, precision_automation_type, rotate_surface, draw_final_warps, distance_type, retain_original_peak, peak_type, add_points, add_points_cycle)

DESCRIPTION ^

 BUILD_1D_BUMP_MODEL: Builds a 1-D model for some bump data
                      and returns some related statistics.

 Code originally written by Katherine Smith, 2003

    GENERAL

      Omitted. Much of the explanation is included in the section where
      default arguments are being assigned.

    INPUT/S

      -- No arguments will lead to defaults

      -spline_type: 
           The type of spline to be used. 'single_point' or
           'multi_point' at present.

      -placement_type:
           Placement type for 'multi_point':
                    'grid' or 'edges' or 'random'
           placement type for 'single_point':
                    'overlap_grid' or 'edges_and_scale'
                    or 'random_and_scale'.

      -objective_function:
           'msd_opt_together' or 'model_opt_separare' or
           'msd_opt_separate' or 'model_opt_together'.

      .....
           
    OUTPUT/S

      -status:
           The status of the operation of this routine (to be returned at
           the end

      -Figures produced and results displayed are main
       data to be utilised.

    PENDING WORK

      -

    KNOWN BUG/S

      -

    COMMENT/S

      -Different video outputs are generated but controlling which
       one is chosen is not trivial. It currently just does the
       job of experimentation and showing results as pixels
       or bumps.

    RELATED FUNCTION/S

      See other functions in same directory, filenames
      beginning with "build" in particular. There seem to be much
      overlap due to cut-and-paste.

    ABOUT

      -Created:     December 29rd, 2003
      -Last update: March 30th, 2004
      -Revision:    0.9.2
      -Author:      R. S. Schestowitz, University of Manchester
 ==============================================================

CROSS-REFERENCE INFORMATION ^

This function calls: This function is called by:

SOURCE CODE ^

0001 function [status] = build_1d_bump_model( ...
0002     spline_type ...
0003     , placement_type ...
0004     , objective_function ...
0005     , apply_intensity_offset ...
0006     , save_movie ...
0007     , do_plot ...
0008     , movie_type ...
0009     , progress_bar ...
0010     , user_menu ...
0011     , produce_statistics ...
0012     , see_model_before_each_iteration ...
0013     , show_pixels ...
0014     , show_score_vs_iteration ...
0015     , show_model_after_optimisation ...
0016     , show_specificity_statistics ...
0017     , verbose_score ...
0018     , movie_name ...
0019     , window ...
0020     , average_smooth_enabled ...
0021     , gaussian_smooth_enabled ...
0022     , bump_width ...
0023     , bump_width_variation ...
0024     , bump_height ...
0025     , bump_height_variation ...
0026     , bump_position_freedom ...
0027     , initial_diminish_factor ...
0028     , smoothness_factor ...
0029     , plot_before_and_after ...
0030     , number_of_bins ...
0031     , model_evaluation_method ...
0032     , show_score_using_model ...
0033     , handle ...
0034     , n_modes ...
0035     , shape_weight ...
0036     , weighting_normalisation_method ...
0037     , variation_kept ...
0038     , run_all_objective_functions ...
0039     , kernel ...
0040     , save_data ...
0041     , load_data ...
0042     , save_bumps ...
0043     , draw_warp_curve ...
0044     , overlap_scores ...
0045     , show_target ...
0046     , format ...
0047     , filter ...
0048     , filter_level ...
0049     , model_score_type ...
0050     , gen_iters ...
0051     , spec_iters ...
0052     , draw_curve_by_images ...
0053     , show_mesh ...
0054     , mesh_type ...
0055     , exit_at_end ...
0056     , show_all_score_figure_types ...
0057     , close_at_end ...
0058     , frames_per_second ...
0059     , show_score_bar ...
0060     , n_points ...
0061     , show_warp_targets ...
0062     , show_registration_target ...
0063     , produce_record ...
0064     , initialise_warps_close_to_target ...
0065     , save_in_log ...
0066     , perturbation_method ...
0067     , offset_extent ...
0068     , force_reference ...
0069     , cycle ...
0070     , verbose ...
0071     , save_stats ...
0072     , n_modes_display ...
0073     , n_standard_deviations_display ...
0074     , show_warps_while_optimising ...
0075     , description ...
0076     , find_perfect_warp ...
0077     , force_first_reference ...
0078     , display_shape_model ...
0079     , display_intensity_model ...
0080     , plot_alignment ...
0081     , error_verbosity ...
0082     , precision_required ...
0083     , background_red ...
0084     , background_green ...
0085     , background_blue ...
0086     , dynamic_precision ...
0087     , precision_automation_type ...
0088     , rotate_surface ...
0089     , draw_final_warps ...
0090     , distance_type ...
0091     , retain_original_peak ...
0092     , peak_type ...
0093     , add_points ...
0094     , add_points_cycle ...    
0095    )
0096 
0097 % BUILD_1D_BUMP_MODEL: Builds a 1-D model for some bump data
0098 %                      and returns some related statistics.
0099 %
0100 % Code originally written by Katherine Smith, 2003
0101 %
0102 %    GENERAL
0103 %
0104 %      Omitted. Much of the explanation is included in the section where
0105 %      default arguments are being assigned.
0106 %
0107 %    INPUT/S
0108 %
0109 %      -- No arguments will lead to defaults
0110 %
0111 %      -spline_type:
0112 %           The type of spline to be used. 'single_point' or
0113 %           'multi_point' at present.
0114 %
0115 %      -placement_type:
0116 %           Placement type for 'multi_point':
0117 %                    'grid' or 'edges' or 'random'
0118 %           placement type for 'single_point':
0119 %                    'overlap_grid' or 'edges_and_scale'
0120 %                    or 'random_and_scale'.
0121 %
0122 %      -objective_function:
0123 %           'msd_opt_together' or 'model_opt_separare' or
0124 %           'msd_opt_separate' or 'model_opt_together'.
0125 %
0126 %      .....
0127 %
0128 %    OUTPUT/S
0129 %
0130 %      -status:
0131 %           The status of the operation of this routine (to be returned at
0132 %           the end
0133 %
0134 %      -Figures produced and results displayed are main
0135 %       data to be utilised.
0136 %
0137 %    PENDING WORK
0138 %
0139 %      -
0140 %
0141 %    KNOWN BUG/S
0142 %
0143 %      -
0144 %
0145 %    COMMENT/S
0146 %
0147 %      -Different video outputs are generated but controlling which
0148 %       one is chosen is not trivial. It currently just does the
0149 %       job of experimentation and showing results as pixels
0150 %       or bumps.
0151 %
0152 %    RELATED FUNCTION/S
0153 %
0154 %      See other functions in same directory, filenames
0155 %      beginning with "build" in particular. There seem to be much
0156 %      overlap due to cut-and-paste.
0157 %
0158 %    ABOUT
0159 %
0160 %      -Created:     December 29rd, 2003
0161 %      -Last update: March 30th, 2004
0162 %      -Revision:    0.9.2
0163 %      -Author:      R. S. Schestowitz, University of Manchester
0164 % ==============================================================
0165       
0166 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
0167 %% variables (parameters) initialisation           %%
0168   
0169 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
0170 %% Input Defaults              %%
0171 
0172 % When the function is not called from the GUI, various arguments must be
0173 % initialised so that the function performs a registration task.
0174 
0175 % A possible extension would allow for _partial_ arguments to be given so
0176 % that a script can run different experiments and then logs are necessary
0177 % too.
0178 
0179 if (nargin == 0),
0180     disp(' ');
0181     disp('Argument(s) omitted. Using defaults instead.');
0182     disp(' ');
0183          % notify user about default values being used.
0184     spline_type = 'single_point';
0185          % SMITH: spline type 'single_point' or 'multi_point'
0186          % SMITH: placement type for multipoint: 'grid' or 'edges' or 'random'
0187          % SMITH: placement type for singlepoint: 'overlap_grid' or 'edges_and_scal or 'random_and_scale'
0188     placement_type = 'random_and_scale';
0189          % controls knot-point selection on the grid
0190     objective_function = 'model_opt_together';
0191          % choice of objective function
0192     apply_intensity_offset = 1;
0193          % 0: Offset should not be applied to data
0194          % 1: Offset enabled
0195     exit_at_end = 0;
0196          % indicates whether AART quits at the end of registration
0197     description = '';
0198          % a name provided for describing registration
0199     cycle = 0;
0200           % cycle size for user display of objective function evaluation
0201     produce_record = 0;
0202           % indicates if results should be displayed to the user in the
0203           % console
0204     save_in_log = 0;
0205           % indicates if an HTML file or network of files will be used to
0206           % record the results
0207     close_at_end = 0;
0208           % indicates if the GUI should be closed when registration is done
0209     save_movie = 0;
0210           % a flag for movie output
0211     force_reference = 0;
0212          % should movie be saved (boolean)
0213          % 0: No
0214          % 1: Yes
0215     frames_per_second = 15;
0216          % number of frames per second for the video generated.
0217     n_standard_deviations_display = 2;
0218          % the number of standard deviation to be displayed when a model is
0219          % presented to the user
0220     n_modes_display = 2;
0221          % as above, for number of modes
0222     perturbation_method = 'CPS warp';
0223          % the type of perturbation applied to the data
0224     offset_extent = 0;
0225          % the extent of perturbation or the level of distortion which
0226          % accompanies the parameter 'perturbation_method'
0227     precision_automation_type = 'default';
0228        % the way to set precision for the optimiser
0229     do_plot = 0;
0230          % should bumps be plotted as it changes? (Boolean)
0231          % (Old comment: this also enables frames being captured which slows down the
0232          % process. Capturing of frames and plotting can potentially be separated to make
0233          % this routine more useful).
0234     movie_type = 1;
0235          % type of movie to save
0236          % 0: bumps as pixels. do_plot may be 0 for a pixel clip to be recorded.
0237          % 1: bump plots. Remember to set do_plot to 1.
0238     show_warps_while_optimising = 0; 
0239          % indicates if the warps applied to the data should be dynamically
0240          % displayed to the user
0241     movie_name = 'undefined';
0242           % the name of the AVI movie to be saved. It will be folloed by
0243           % '.avi' eventually and contain the movie.
0244     format = 'png';
0245          % if data is saved as an image, this paramater defines the format
0246          % as which it shall be saved.
0247     show_warp_targets = 0;
0248          % defines whether or not the target of the warps, i.e. that at
0249          % alignment, should be displayed to the user.
0250     dynamic_precision = 0;
0251        % defines whether or not precision is chosen wisely at each stage
0252     gen_iters = 25;
0253        % generalisability iterations = 25;
0254        % specificity iterations
0255     spec_iters = 25;
0256        % specificity iterations
0257     progress_bar = 1;
0258          % display progress bar or text instead
0259          % 0: Hierarchical Text
0260          % 1: Progress bar
0261          % 2: Quiet
0262          % 3: Console progress bar
0263     model_score_type = 'Default';
0264          % Defined the way in which a model is scored.
0265     force_first_reference = 0;
0266          % depending on its numeric value, this parameter defines the
0267          % reference selection method
0268     user_menu = 0;
0269          % indicates the way in which registration parameters are entered.
0270          % If not via pop-up menu, then probably via top menu in the
0271          % application.
0272     number_of_bins = 50;
0273          % 0: parameters need to be set in file
0274          % 1: menu input
0275     background_red = 1;
0276     background_green = 1;
0277     background_blue = 1;
0278          % the background colourn for the plots
0279     distance_type = 'sum_of_squared_distances';
0280          % The way to meausre distance from mean
0281     show_registration_target = 0;
0282          % indicates if the estimated target of registration should be
0283          % super-imposed in score plots.
0284     produce_statistics = 0;
0285          % should statistics be displayed at the end (boolean)
0286     see_model_before_each_iteration = 0;
0287          % should a combined model be produced and displayed before each
0288          % iteration, this should be set to 1
0289     show_pixels = 0;
0290          % show pixels representation (boolean). Mandatory for pixel movie
0291          % capture
0292     show_score_vs_iteration = 0;
0293          % when enabled, evaluation of the objective function will be
0294          % displayed against the iteration at which it was evaluated.
0295     find_perfect_warp = 1;
0296          % This argument should not be tempered with. It defined the need
0297          % to check for the value and state at conceived registration
0298          % target
0299     show_model_after_optimisation = 0;
0300          % if enabled, then a model produces from the data is displayed
0301          % after registration.
0302     show_specificity_statistics = 0;
0303          % more booleans which are self-explanatory
0304     verbose_score = 0;
0305          % boolean: display score or not after optimisation
0306     show_score_bar = 0;
0307          % The score bar gives a visual indication of the 'goodness' of a
0308          % model construced from the data
0309     average_smooth_enabled = 0;
0310     gaussian_smooth_enabled = 0;
0311          % flags indicating the smoothness to be applied, if any at all
0312     n_points = 5;
0313          % an argument that is passed to the model optimisation function.
0314          % it refers to the number of knotpoint, e.g. for random and scale.
0315     window = 1;
0316          % the size of the window for average smoothing or sigma for
0317          % gaussian smoothing
0318     show_all_score_figure_types = 0;
0319          % defines the need for an abundant number of plots depicting
0320          % quality of model versus iteration
0321     plot_before_and_after = 0;
0322          % will only ever be used if the two above are set
0323     bump_width = 0.2;
0324     bump_width_variation = 0.5;
0325     bump_height = 0.2;
0326     bump_height_variation = 0.3;
0327     bump_position_freedom = 0.9;
0328     initial_diminish_factor = 2;
0329     smoothness_factor = 17;
0330          % set the bump parameters
0331     precision_required = 1e-7;
0332         % the precision required from the optimiser
0333     model_evaluation_method = 1;
0334                       % 1: Determinant
0335                       % 0: MDL
0336                       % 2: Sum of log of Eigenvalues
0337     show_score_using_model = 0;
0338     handle = 'Default';
0339       % give figures a fefault name
0340     n_modes = 20;
0341       % maximal number of modes to be accounted for when evaluating a model
0342     variation_kept = 0.99;
0343       % keep 99%
0344       % number of modes in the model to be accounted for
0345     retain_original_peak = 0;
0346       % determines whether or not to keep the same maximal data height
0347     error_verbosity = 'normal';
0348       % the level of verbosity for errors
0349     initialise_warps_close_to_target = 0;
0350       % determines the requirement to start registration with warps near
0351       % their target (at completion of registration)
0352     shape_weight = 0.06;
0353       % the constant weight Ws for the model constructed. 1 is 100%, 0 is
0354       % 0% and legal range is 0..1
0355     weighting_normalisation_method = 'edge';
0356      % the scheme for Ws weighting selection
0357     run_all_objective_functions = 0;
0358        % do not try running all the objective functions
0359     called_from_gui = 0;
0360        % indicate that GUI was not used in this case
0361     kernel = 'Exponential';
0362        % the kernel type for PDF objective function
0363     save_data = 0;
0364        % Indicated if the data needs to be saved to files after opening or
0365        % generation
0366     peak_type = 'average_position';
0367          % The type of peak to be retained
0368     load_data = 0;
0369        % indicates if data needs to be loaded from file rather than being
0370        % generated.
0371     save_bumps = 0;
0372        % indicated if bumps need to be saved as images (not data)
0373     draw_warp_curve = 0;
0374        % An option for overlapping warps display
0375     draw_curve_by_images = 0;
0376        % The option for warp target maps (images x iterations)
0377     overlap_scores = 0;
0378       % defines the need for scores to be drawn on the same space if
0379       % different objective functions are compared by being run
0380       % sequentially
0381     show_mesh = 0;
0382      % simply indicates if a mesh of the data needs to be displayed
0383     show_target = 0;
0384         % do not show perfectly aligned images estimate
0385     verbose = 'off';
0386          % be verbose or not during general-purpose optimisation
0387     save_stats = 0;
0388        % indicated if statistics need to be saved as HTML
0389     display_shape_model = 0;
0390       % If enabled, shape model is shown
0391     display_intensity_model = 0;
0392       % likewise for intensity model
0393     n_images = 2;
0394              % how many images to try to register in each set
0395     n_iterations = 2;
0396              % how many iterations of the optimisation to run, default was 50.
0397     n_sets = 1;
0398              % how many sets of images to register (in order to get better statistics)
0399     image_width = 50;
0400              % the number of pixels or the lenght of the data vector
0401     figure_handle_number = 1;
0402              % increments applied when figures are saved
0403     plot_alignment = 0; 
0404              % Indicates if a plot for alignment and perturbation should be
0405              % displayed
0406     rotate_surface = 0;
0407              % Indicated if the surface should be rotated horizontally at
0408              % each frame
0409     draw_final_warps = 0;
0410              % indicates if final warps need to be displayed
0411     add_points = 0;
0412              % point stuffing where difference in warp curve is greatest
0413     add_points_cycle = 1;
0414              % the frequency (measured in terms of iteration) for stuffing;
0415 else
0416     called_from_gui = 1;
0417         % indicate that default values were not set and that the function
0418         % was called from REGISTER
0419 end
0420 
0421        
0422 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
0423 %% Input / Output              %%
0424 
0425 rand('state',sum(100*clock))
0426           % seeding for random numbers.
0427 
0428 figure_handle_number = 1;
0429           % A number to be incremented every time a figure is saved. It
0430           % manages the number of figures that are generated.
0431 warning off;
0432          % keeps st_pca.m quiet
0433 error_found = 0;
0434          % status flag
0435 current_viewpoint = 45;
0436          % the starting horizontal viewpoint for surfaces
0437          % Optimisation note: initiliase this variables only when surfaces
0438          % are displayed.
0439 status = ['                      '];
0440          % set intitial status message. Messages are aggregated before
0441          % being returned to the GUI and displayed to the user.
0442 if (run_all_objective_functions == 1),
0443          % If all objective functions will run sequentially, then some
0444          % output parameters need to be updated.
0445     colour = 'r';
0446         % set initial colour for overlaid plots
0447     style = ':';
0448         % similarly to style of line in the overlaid plots
0449     progress_bar = 2;
0450 end
0451      % the progress indicators will not work for this routine so disable
0452      % them
0453 
0454 if strcmp(movie_name, 'undefined'),
0455     movie_name = ['movie_', spline_type, '_', placement_type, '_', objective_function,'_width', num2str(image_width), '_images', num2str(n_images), '_iterations', num2str(n_iterations), '.avi'];
0456          % name for the AVI to be saved
0457          % The name will attempt to encompass all construction details
0458          % It will replace the default name given when the function is not
0459          % called from the GUI. If called from the GUI, it usually have a
0460          % user defined name or 'Default.avi'
0461 end
0462 
0463 
0464 frame_counter = 0;
0465          % counter for video frames. Do not fiddle with this variable. It
0466          % keeps track of the current frame number to be captured.
0467          
0468 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
0469 %% Others (most are obsolete and are remains of old code.)  %%
0470                        
0471 % white_ctr = 0;
0472          % white counter? Was used for simple bumps in code that is now
0473          % commented out
0474 % ref_shift = 0.2;
0475        % shift in reference image??
0476 % max_shift = 0.2;
0477        % maximum allowed shift?
0478 % step = 0.1;
0479        % used in two lines below only
0480 % los = zeros(n_images,floor((max_shift-ref_shift)/step));
0481 % his = zeros(n_images,floor((max_shift-ref_shift)/step));
0482        % not understood yet
0483 % blurred = 0;
0484        % image blurring has been applied to images (boolean)
0485 % min_error = 0;
0486 % max_error = 1;
0487        % define error range??
0488 % error_step = 0.1;
0489 % n_error_steps = (max_error-min_error) / error_step;
0490 
0491 
0492          
0493 switch model_evaluation_method,
0494     case 0
0495         model_evaluation_method = 'minimum_description_length';
0496     case 1
0497         model_evaluation_method = 'determinant';     
0498     case 2
0499         model_evaluation_method = 'sum_of_log_eigenvalues';
0500     case 3
0501         model_evaluation_method = 'specificity';
0502     case 4
0503         model_evaluation_method = 'generalisability';    
0504     otherwise
0505         error('Unknown model evaluation method. Wrong numeric identifier passed.');
0506 end
0507          % The conversion above can one day be embedded in the GUI to make
0508          % everything more readable. Values are overwritten here too.
0509          
0510 switch progress_bar,
0511     case 0
0512      progress_indicator_type = 'Hierarchical Text';
0513     case 1
0514      progress_indicator_type = 'Progress Bar';
0515     case 2
0516      progress_indicator_type = 'Quiet'; 
0517     case 3
0518      progress_indicator_type = 'Console Progress Bar';
0519     otherwise
0520      error('Callback value for progress indicator is not recognised');
0521 end
0522 
0523          % do type conversions for input to make code below readable
0524          
0525 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
0526 %% Begin Set initialisation    %%
0527 
0528 switch user_menu,
0529   case 0
0530     
0531     %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
0532     %% Optimisation Controllers: Default   %%
0533     
0534     % Original settings from 2003: The values below will be defaults if user menu does not appear
0535     
0536     n_images = 2;
0537              % how many images to try to register in each set
0538     n_iterations = 2;
0539              % how many iterations of the optimisation to run, default was 50.
0540     n_sets = 1;
0541              % how many sets of images to register (in order to get better statistics)
0542     image_width = 50;
0543              % the number of pixels or the length of the data vector
0544              
0545     % A few extra popular choices, added March 2004 to speed up experiments
0546     % construction and customisation
0547     
0548   case 1
0549     [n_sets, n_iterations, n_images, image_width] = get_parameters_from_user('Default');
0550        % Prompts the user for the main registartion parameters using menus
0551 
0552   case 2    
0553     n_images = 10;
0554     n_iterations = 50;
0555     n_sets = 1;
0556     image_width = 50;
0557     
0558   case 3   
0559     n_images = 5;
0560     n_iterations = 5;
0561     n_sets = 1;
0562     image_width = 50; 
0563     
0564   case 4    
0565     n_images = 10;
0566     n_iterations = 10;
0567     n_sets = 1;
0568     image_width = 50;
0569     
0570   case 5   
0571     n_images = 20;
0572     n_iterations = 10;
0573     n_sets = 1;
0574     image_width = 50; 
0575     
0576   case 6
0577     n_images = 20;
0578     n_iterations = 1000;
0579     n_sets = 1;
0580     image_width = 50;
0581     
0582   case 7 
0583     n_images = 10;
0584     n_iterations = 1000;
0585     n_sets = 1;
0586     image_width = 50;
0587     
0588   case 8
0589     n_images = 10;
0590     n_iterations = 10000;
0591     n_sets = 1;
0592     image_width = 50;
0593     
0594   otherwise
0595     error('Unknown parameters option. Internal failure.');
0596     
0597 end 
0598 
0599 % in all the above cases, meaningful names rather than numbers are a
0600 % possible extension which requires time.
0601 
0602 
0603 
0604 
0605 tic;
0606        % start counting time
0607 for this_set = 1:n_sets
0608        % for all sets
0609        % Old: user gets status about set number. Multiple sets generate reliable
0610        %      statistics
0611   tic;
0612        % This is called again (stack of time counters????? Doesn't seem so)
0613        % This will need to be changed (one tic omitted) for the statistics
0614        % to work properly. Only one stopwatch can work at a time.
0615        % Smith: for each set of n_sets images, build a model
0616        % calculate obj fn values from these models, plot the mean with error
0617        % bars given by 1 stddev away
0618   if (strcmp(progress_indicator_type,'Hierarchical Text')),      
0619     disp(['calculating set ', num2str(this_set), ' out of ', num2str(n_sets), ' sets...']);
0620       % display command-line status indicators
0621   elseif (strcmp(progress_indicator_type,'Progress Bar')),
0622       gui_active(1);
0623           % will add an abort button
0624       if (strcmp(getenv('OS'), 'Linux')),
0625          h = progressbar([], 0, 'Preparing for registration', [['Registration Progress on '], [get_host]]);
0626       else
0627          h = progressbar([], 0, 'Preparing for registration', 'Registration Progress');
0628       end
0629         % initiate progress bar if necessary
0630       h = progressbar( h, 0, 'Fetching Data');
0631   end    
0632 
0633   % initiate score bar if necessary
0634 
0635 
0636   if (show_score_bar == 1),
0637      score_bar = waitbar(0, 'Score');
0638   end
0639      
0640 
0641   switch load_data,
0642       
0643    case 0
0644       [imagelist, images, points] = make_1d_bump(n_images, image_width...
0645           , bump_width, bump_width_variation, bump_height, bump_height_variation...
0646           , bump_position_freedom, initial_diminish_factor, smoothness_factor...
0647           , save_bumps, format);
0648        % create a set of images given several parameters
0649        
0650       points = -1 + 2 * (points - 1) / (image_width - 1);
0651         % Smith: normalise points from -1 to 1
0652              
0653       if (called_from_gui == 1 & save_bumps == 1),
0654         status = [[status];['(**) Images saved     '];['                      ']];
0655       end
0656         % notify user using the status bar that data has been saved.
0657  
0658        %% keep = 0.999999; NOTE (RSS Feb. 2004): became obsolete and
0659        %% replaced by <variation kept> which relates to PCA
0660        
0661        % Nov. 2003: Is this precision required? Perhaps in optimisation.
0662        
0663    case 1
0664       output = open([[handle],['.mat']]);
0665       points = output.points;
0666       images = output.images;
0667                   % copy the data structures from the file
0668                   
0669    case 2
0670       output = open('Default.mat');
0671       points = output.points;
0672       images = output.images; 
0673       
0674    case 3
0675       output = open('flat.mat');
0676       points = output.points;
0677       images = output.images; 
0678       
0679    case 4
0680       output = open('plain.mat');
0681       points = output.points;
0682       images = output.images;  
0683       
0684    case 5
0685       output = open('plainran.mat');
0686       points = output.points;
0687       images = output.images;  
0688       
0689    case 6
0690       [imagelist, images, points] = make_elliptic_bumps(n_images, image_width, save_bumps, format, bump_height, bump_position_freedom, bump_height_variation, bump_width_variation);
0691        % create a set of images given several parameters
0692       points = -1 + 2 * (points - 1) / (image_width - 1);
0693              
0694       if (called_from_gui == 1 & save_bumps == 1),
0695         status = [[status];['(**) Images saved     '];['                      ']];
0696       end
0697       
0698    case 7
0699       [imagelist, images, points, dummy1, dummy2] = make_1d_images(n_images, image_width, 0.2);
0700        % 0.2. is the value used by Kate for <white width>
0701       if (save_bumps == 1),
0702           msgbox('Data save is not supported with simple bumps.');
0703       end
0704        % create a set of images given several parameters
0705       points = -1 + 2 * (points - 1) / (image_width - 1);
0706              
0707       if (called_from_gui == 1 & save_bumps == 1),
0708         status = [[status];['(**) Images not saved '];['                      ']];
0709       end    
0710       
0711    otherwise
0712       error('Invalid value passed from open submenu. Internal error.');
0713       
0714   end     
0715   
0716   
0717   if (average_smooth_enabled),
0718       images = average_smooth(images, window);
0719   end  
0720   
0721   if (gaussian_smooth_enabled),
0722       images = gaussian_smooth(images, window); 
0723   end
0724        % smooth all images - used to be disabled and set <blurred> to 1
0725        
0726 
0727   ref_points_vec = points(:,1);
0728   ref_image_vec = images(:,1);
0729        % set first image generated to be reference when calculating a
0730        % perfect warp and also as reference in pair-wise objective
0731        % functions. This has been made more generalised later on.
0732   % ref_hi = his(1);
0733   % ref_lo = los(1);
0734        % and get its upper and lower boundaries. his and lois were
0735        % generated and returned as output for simple bumps. They were
0736        % used to find the perfect warps and defined points of importance in
0737        % the input data.
0738   
0739   % Now choose the image which will not be changed. Note a possible
0740 % optimisation: only if a reference is forced, then the code below should
0741 % be run to choose the reference. The section below that is to do with
0742 % alignment means however that for target to be shown an immutable image
0743 % must always be chosen
0744 
0745       switch force_first_reference,
0746        case 0        
0747            immutable_image = 2;
0748                 % see comments later about the choice of first or second
0749                 % image as an immutable reference. These options will only
0750                 % have an effect if a reference is forced (not as in the
0751                 % default reference in MSD-based algorithms)
0752                 
0753                 % OPTIMISATION NOTE: score can also be set to 0 in all
0754                 % cases without breaking registration. It would then need
0755                 % not be repeated in all the cases below.
0756                 
0757        case 1
0758            immutable_image = 1;
0759            score = 0;
0760                 % the score needs to be initilialised because no previous
0761                 % scoring will be avaliable
0762                 
0763        case 2
0764           % closest data to average (mean)
0765            immutable_image = find_image_closest_to_mean(images, image_width, n_images, 'closest', distance_type);
0766            score = 0;
0767            
0768        case 3
0769               % random reference
0770            immutable_image = ceil(rand * n_images);
0771            score = 0;
0772            
0773        case 4
0774           % closest data to average (mean)
0775            immutable_image = find_image_closest_to_mean(images, image_width, n_images, 'farthest', distance_type);
0776            score = 0;
0777            
0778        case 5
0779            % highest peak
0780            immutable_image = find_image_by_height(images, image_width, n_images, 'highest');
0781            score = 0;
0782            
0783        case 6
0784            % lowest peak
0785            immutable_image = find_image_by_height(images, image_width, n_images, 'lowest');
0786            score = 0;
0787            
0788        otherwise
0789           error('Reference error. Wrong values passed from callback.');
0790           
0791       end  
0792 
0793       % NOTE PROBLEM: If teh refrence chosen is the first then evaluation at
0794       % the start is 0 and the optimisation plot is not suitable
0795        
0796        
0797        
0798        
0799   %%%%% Do warp analysis here
0800   
0801   % The check for perfect warps does not work for corrective offsets,
0802   % non-bump data, and data that is significantly smoothed. In all of these
0803   % cases, the flag below must be set to 0, or else piece wise linear will
0804   % not work.
0805   check_perfect_warps = find_perfect_warp;
0806           % currently always enabled, but computationally expensive and in
0807           % some cases not necessary. A test for the value of this part to
0808           % be implemented in the future.
0809       if (check_perfect_warps == 1),   
0810           if (strcmp(progress_indicator_type,'Progress Bar')),
0811              h = progressbar( h, 0, 'Calculating Correct Warps');
0812           end
0813         % (Old - November 2003 - Smith)
0814           % correctly_warped_points = points;
0815           % correctly_warped_images = images;
0816           for i = 1:n_images,
0817               % Smith: now bung in the right deformations to get them back
0818               % NOTE: THE VARIABLE ref_image_vec BELOW ASSUMED A FIRST
0819               % IMAGE REFERENCE although this is not the case for the <force
0820               % reference> option which makes it the second (implicitly).
0821               % Somthing richer than a second image might be used in
0822               % future.
0823               
0824               %possible optimisation: do not interpolate for the first
0825               %image which is usually a reference and is not affected
0826               %anyhow
0827               %images(:,i)
0828             correctly_warped_points(i,:) = find_target_warp(images(:,immutable_image), images(:,i), image_width);
0829               % correctly_warped_points(i,:)
0830               % get the warp that appears most desirable
0831             correctly_warped_points(i,:) = -1 + 2 * (correctly_warped_points(i,:) - 1) / (image_width - 1);
0832               % normalise points so that they lie in the range x where -1 < x < 1
0833             correctly_warped_points_vec = correctly_warped_points(i,:);              
0834             image_vec = images(:,i);
0835               % RSS: copy original image and copy piece-wise linear warp
0836               % Smith: resample at the warped points - point on reg. grid has value of point at same index in warpy grid
0837               % need to interpolate
0838               % size(ref_points_vec)
0839               % size(image_vec)
0840               % size(correctly_warped_points_vec')
0841             correctly_warped_images(i,:) = interp1(ref_points_vec, image_vec, correctly_warped_points_vec);
0842             % correct_model = build_model(correctly_warped_images,correctly_warped_points,1,'','edge',0);
0843             % converging_score(i) =
0844             % measure_model(correct_model.variances,50);
0845             % correctly_warped_images(i,:)
0846           end
0847           % figure;
0848           % plot(log(converging_score));
0849           % title('Log of score as model converges');
0850       end
0851       % figure;
0852       % (test curve) plot(correctly_warped_points(2,:))
0853       
0854   
0855 
0856       if (show_warp_targets == 1),
0857          warp_handle = figure('Name','On the left: piece-wise linear optimal registration warps; On the right: results of warp');
0858          % title('On the left: piece-wise linear optimal registration warps; On the right: results of warp');
0859          save_handle = figure(warp_handle);
0860          hold on;
0861          subplot(n_images, 2, 1);
0862          for i=1:n_images,
0863              subplot(n_images, 2, i * 2 - 1);
0864              hold on;
0865              axis off;
0866              plot(correctly_warped_points(i,:));
0867              axis([-1 image_width -1 1]);
0868              hold off;
0869          end
0870          for i=1:n_images,
0871              subplot(n_images, 2, i * 2);
0872              hold on;
0873              axis off;
0874              plot(correctly_warped_images(i,:));
0875              axis([0 image_width 0 1]);
0876              hold off;
0877          end
0878          hold off;
0879          if (save_in_log == 1),
0880            saveas(save_handle,[[handle],'-', num2str(figure_handle_number)], 'jpg');
0881            figure_handle_number = figure_handle_number + 1;
0882          end
0883       end
0884       
0885   
0886     
0887   if (initialise_warps_close_to_target == 1),
0888       % offset_extent = 5;
0889       % perturbation_method = 'CPS warp';
0890       
0891     if (plot_alignment == 1),
0892         % if a plot is required to show this step of perturbation after
0893         % alignment the right-hand side solumn will be occupied by the
0894         % plots
0895       subplot_alignment_fig = figure('Name',[[handle],[': Left: Aligned images ; Right (if existent): Aligned images after perturbation']]);
0896       alignment_handle=figure(subplot_alignment_fig);
0897       for i=1:n_images,
0898        subplot(n_images, 2, 2 * i - 1);
0899        hold on;
0900        plot(correctly_warped_images(i,:));
0901        % title(['Unwarped image #',num2str(i)]);
0902        axis([0 image_width 0 1]);
0903        grid on;
0904        hold off;
0905       end
0906     end
0907       
0908       if (offset_extent == 0),
0909           % if no perturbation is required then the values can be simply
0910           % copied.
0911          for i = 1:n_images,
0912            % copy registration target
0913           points(:,i) = correctly_warped_points(i,:)';
0914            % images(:,i) = correctly_warped_images(i,:)';
0915          end
0916       else
0917           % if some noise is required, then add it in the form of Gaussian
0918           % noise or CPS warps to points and interpolate original images
0919           % accordingly. To be controlled from GUI.
0920            for i = 1:n_images,
0921                 tweaked_points(i,:) = apply_perturbation_to_points(correctly_warped_points(i,:), offset_extent, perturbation_method);
0922         %         figure
0923         %         hold on
0924         %         plot(tweaked_points(i,:));
0925         %         plot(correctly_warped_points(i,:));
0926         %         hold off
0927                    % apply noise to the correct points
0928                 % images(:,i) = interp1(ref_points_vec, images(:,i), tweaked_points(i,:))';
0929                    % interpolation to get current images
0930                 points = tweaked_points';
0931                    % copy the points found to become current
0932                    % inconsistent column and row form is due to initial
0933                    % implementation. Optimally (when our task becomes optimising performance),
0934                    % all transposes should be ridden of.
0935            end
0936            if (plot_alignment == 1),
0937               for i = 1:n_images,
0938                 perturbed_aligned_images(:,i) = interp1(ref_points_vec, images(:,i), points(:,i));
0939               end    
0940                 % inerpolate to show some plots at this earlier stage
0941               alignment_handle = figure(subplot_alignment_fig);
0942               for i = 1:n_images,
0943                    subplot(n_images, 2, 2 * i);
0944                    hold on;
0945                    plot(perturbed_aligned_images(:,i));
0946                    % title(['Unwarped image #',num2str(i)]);
0947                    axis([0 image_width 0 1]);
0948                    grid on;
0949                    hold off;
0950                end
0951              if (save_in_log == 1)
0952                saveas(alignment_handle,[[handle],'-', num2str(figure_handle_number)], 'jpg');
0953                figure_handle_number = figure_handle_number + 1;
0954              end
0955            end
0956       end
0957       
0958   end
0959   
0960   
0961   if (save_data == 1),
0962       % note that data will be saved with modified warp curves if option is
0963       % set. This is intentional. Data in this cotext is vectors, not
0964       % images.
0965       save([[handle],['.mat']], 'images','points');
0966       if (called_from_gui == 1),
0967         status = [[status];['(**) Data saved       '];['                      ']];
0968       end
0969   elseif (save_data == 2),
0970       % if data needs to be saved as default
0971       save([[handle],['.mat']], 'images','points');
0972       save(['Default.mat'], 'images','points');
0973       if (called_from_gui == 1),
0974         status = [[status];['(**) Data saved (Def) '];['                      ']];
0975       end
0976   end
0977 
0978 
0979   
0980   if (retain_original_peak),  
0981        for current_image = 1:n_images,
0982            maximum_height(current_image) = max(images(:, current_image));
0983               % find out the maximum height of each data instance
0984            
0985            for j=1:image_width,
0986                switch peak_type,
0987                    case 'initial_position'
0988                          if (images(j,current_image) == maximum_height(current_image)),
0989                            maximum_position(current_image) = j;
0990                             % find the position where height is maximal. Currently
0991                             % this search is very inefficient.
0992                          end
0993                          
0994                    case 'average_position'
0995                          if (images(j,current_image) == maximum_height(current_image)),
0996                            maximum_position(current_image) = j;
0997                          end
0998                          % same as above
0999                end
1000            end
1001        end
1002  
1003   
1004        switch peak_type,
1005          case 'average_position'
1006            average_position = floor(mean(maximum_position));
1007            for current_image = 1:n_images,
1008              maximum_position(current_image) = average_position;
1009            end 
1010        end
1011    end
1012            
1013            
1014            
1015            
1016 % plot3(1:2,1:2,images(1,:))
1017 %
1018 %
1019 %       s = surface(L, ...
1020 %         'EdgeColor','none', ...
1021 %         'FaceColor',[0.8 0.2 0.2], ...
1022 %         'FaceLighting','phong', ...
1023 %         'AmbientStrength',0.3, ...
1024 %         'DiffuseStrength',0.6, ...
1025 %         'Clipping','off',...
1026 %         'BackFaceLighting','lit', ...
1027 %         'SpecularStrength',1.1, ...
1028 %         'SpecularColorReflectance',1, ...
1029 %         'SpecularExponent',7);
1030 %     l1 = light('Position',[40 100 20], ...
1031 %         'Style','local', ...
1032 %         'Color',[0 0.7 0.7]);
1033 %     l2 = light('Position',[.5 -1 .4], ...
1034 %         'Color',[1 1 0]);
1035 
1036 % modify the progress bar if required
1037 
1038   if (strcmp(progress_indicator_type,'Progress Bar')),
1039            h = progressbar( h, 0, 'Pre-processing Data');
1040   end
1041   
1042 % depending on whether intensity offset was applied, record the number of
1043 % columns required for the plots
1044        
1045   if (apply_intensity_offset),
1046       vertical_pane_location = 3;
1047                        % Need is for only 3 columns in plot
1048   else
1049       vertical_pane_location = 2;
1050                        % Need is for only 2 columns in plot
1051   end
1052   % Note: intensity offsets are considered a possible way of solving the
1053   % problem, but not natural form for our input data. Hence, saving of data
1054   % precedes this offset.
1055 
1056 
1057 % prepare a figure if a plot of all warp curves needs to be rendered
1058        
1059   if (draw_warp_curve == 1),
1060        overlap_curve_fig = figure('Name','Overlapping Warp Curves');
1061   end
1062   
1063   % if pixel representation is required, prepare the figure
1064   
1065   if (show_pixels == 1),
1066     pixels_figure = figure('Name','Pixel Representation');
1067   end
1068   
1069   % and likewise for meshes/surfaces
1070 
1071   if (show_mesh == 1),
1072     mesh_subfigure = figure('Name','1-D Data Mesh');
1073   end 
1074   
1075   % if a matrix of warps is required, preapre the figure and draw the
1076   % initial warps in its left side
1077   
1078   if (draw_curve_by_images == 1),
1079     curve_subplot_fig = figure('Name',[['Warp Curves for all data - objective function: '],[objective_function]]);
1080     curves = figure(curve_subplot_fig);
1081     % title('Warp Curves for all data');
1082     for i=1:n_images,
1083        subplot(n_images, n_iterations + 1, i * (n_iterations + 1) - n_iterations);
1084        hold on;
1085        axis off;
1086        plot(points(:,i));
1087        plot(correctly_warped_points(i,:),'r-')
1088        if (i == 1 ),
1089          legend('Initial warp', 'Target warp'); 
1090             % only display the legend once at the top
1091        end
1092        axis([-1 image_width -1 1]);
1093        hold off;
1094     end
1095   end
1096   
1097 
1098 %%             END OF INITIALISATION               %%
1099 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1100 
1101 
1102 
1103 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1104 %% Warping images, then modelling warped images    %%
1105 %% attempt to register images by warping.          %%
1106 
1107 
1108 
1109   if (plot_before_and_after),
1110     for i=1:n_images,
1111        images_before_offset(:,i) = images(:,i);
1112        % copy these original values in case 3 columns are necessary for plot representation of the data.
1113     end
1114   end
1115   
1116   % draw the original data at the leftmost column
1117   
1118   if (do_plot),
1119     subplot_fig = figure('Name',[[handle],[': Left: Original images ; Right: Images subjected to warping']]);
1120     H=figure(subplot_fig);
1121     for i=1:n_images,
1122        subplot(n_images, vertical_pane_location, (vertical_pane_location * i) - vertical_pane_location + 1);
1123        hold on;
1124        plot(images(:,i));
1125        whitebg(H, [background_red, background_green, background_blue]); 
1126        % title(['Unwarped image #',num2str(i)]);
1127        axis([0 image_width 0 1]);
1128        grid on;
1129        hold off;
1130     end
1131   else
1132     subplot_fig = 0;
1133       % pass a void figure to the optimisation functions
1134   end
1135   
1136   % draw the data after intensity offset has been applied (when applicable)
1137   
1138   if (apply_intensity_offset),
1139       for index = 1:n_images,
1140          peak (index) = max(images(:,index));
1141       end
1142       peak_reference = max (peak);  
1143       for index = 1:n_images,
1144         peak_difference = peak_reference - max(images(:,index));
1145         images(:,index) = images(:,index) + peak_difference;
1146         if (do_plot),
1147             subplot(n_images, vertical_pane_location, (vertical_pane_location * index) - vertical_pane_location + 2);
1148             hold on;
1149             plot(images(:,index));
1150             % title(['Unwarped image #',num2str(i)]);
1151             axis([0 image_width 0 1]);
1152             grid on;
1153             hold off;
1154         end
1155       end        
1156   end 
1157 %% NOTE: Change here in traversal above (RSS, December 2003)
1158   
1159     still_to_go = 1;
1160           % condition for while loop. This will enable the program to
1161           % continually try all objective functions.
1162     
1163     
1164     while (still_to_go == 1),
1165     
1166     if (run_all_objective_functions == 0)
1167         still_to_go = 0;
1168            % break out of while loop after just one iteration
1169     else
1170            % If new objective functions are added, an entry must be added
1171            % here to include it in the more comprehensive cycle.
1172            
1173            % try all objective functions sequentially
1174        switch objective_function,    
1175            case 'all'
1176            % meaning that it is in its first iteration
1177              objective_function = 'model_opt_together';
1178            case 'model_opt_together'
1179              objective_function = 'model_opt_separate';    
1180            case 'model_opt_separate'
1181              objective_function = 'msd_opt_together';
1182            case 'msd_opt_together'
1183              objective_function = 'msd_opt_separate';
1184            case 'msd_opt_separate'
1185              objective_function = 'mi_opt_together';
1186            case 'mi_opt_together'
1187              objective_function = 'mi_opt_separate';
1188            case 'mi_opt_separate'
1189              objective_function = 'nmi_opt_together';
1190            case 'nmi_opt_together'
1191              objective_function = 'nmi_opt_separate';
1192            case 'nmi_opt_separate'          
1193              objective_function = 'mixed_msd_model';
1194            case 'mixed_msd_model'
1195              objective_function = 'model_post_msd';
1196            case 'model_post_msd'        
1197              objective_function = 'tfc_eccv';
1198            case 'tfc_eccv'
1199              objective_function = 'wavelet_complexity';
1200            case 'wavelet_complexity'
1201              objective_function = 'model_pairs_together';
1202            case 'model_pairs_together'
1203              objective_function = 'model_pairs_separate';
1204            case 'model_pairs_separate'
1205              objective_function = 'void'; 
1206              still_to_go = 0;
1207               % signal to break out of the while loop because the test of
1208               % all objective functions is finished.
1209            otherwise
1210              error('Problem with <Run All Objective Functions> option');
1211        end
1212     end   
1213       % warped_images = images
1214       % size(images)
1215       for i=1:n_images,
1216         warped_images(:,i) = interp1(ref_points_vec, images(:,i), points(:,i)')';
1217       end
1218       % size(warped_images)
1219       warped_points = points;
1220           % set this initial state to plot the examples before change
1221   
1222           
1223        
1224       
1225       
1226   
1227       if ((strcmp(progress_indicator_type,'Console Progress Bar')) | (strcmp(progress_indicator_type,'Progress Bar')))
1228          progress_bar_position = 0;
1229          time_for_this_iteration = 10;
1230          total_images = n_images * n_iterations;
1231          step_size = 50 / total_images;
1232             % these variables are used for some progress statistics
1233       end   
1234         % initialise progress bar
1235         
1236 
1237 
1238         
1239       for n = 1:n_iterations,
1240         
1241         if (dynamic_precision == 1),
1242            iterations_ratio = n_iterations / n;
1243              % get iterations ratio. In future, looking at the optimisation
1244              % state and behaviour, for example whether it is stuck,
1245              % should give better results.
1246            precision_required = set_precision(iterations_ratio, precision_automation_type);
1247         end
1248         
1249         if (show_score_bar == 1),
1250             % subplot('position',[0,0,1,0.1]);
1251             Epsilon = 0.0001;
1252             c_model = build_model(warped_images, warped_points, variation_kept, '', weighting_normalisation_method, shape_weight);
1253             % waitbar((measure_model(c_model.variances, n_modes, 2, c_model) - log(Epsilon.^n_modes)) / log(Epsilon.^n_modes), score_bar);
1254             waitbar((measure_model(c_model.variances, n_modes, 'sum_of_log_eigenvalues', c_model) ...
1255                / log(Epsilon.^n_modes) - 0.8) * 5, score_bar);
1256             % (measure_model(c_model.variances, n_modes, 2, c_model) - log(Epsilon.^n_modes)) / log(Epsilon.^n_modes) * 100
1257             % axis off;
1258             % subplot(1,1,1);
1259         end            
1260           
1261           
1262           
1263         if (show_mesh == 1),
1264           meshview = figure(mesh_subfigure);
1265           whitebg(meshview, [background_red, background_green, background_blue]);
1266                % set viewpoint
1267           [X,Y] = meshgrid(1:n_images * 5 + 2, -image_width / 2 - 1:1:image_width / 2);
1268                % two zero buffers and 5 rows of each bump
1269           for i = 1:n_images,
1270             Z(2:image_width + 1,1 + i * 5) = warped_images(1:image_width,i);
1271             Z(2:image_width + 1,1 + i * 5 - 1) = warped_images(1:image_width,i);
1272             Z(2:image_width + 1,1 + i * 5 - 2) = warped_images(1:image_width,i);
1273             Z(2:image_width + 1,1 + i * 5 - 3) = warped_images(1:image_width,i);
1274             Z(2:image_width + 1,1 + i * 5 - 4) = warped_images(1:image_width,i);
1275             % copy the data values
1276           end
1277           Z(:,1) = zeros(1:image_width, 1);
1278                 % set bottom buffer
1279           Z(:, n_images * 5 + 2) = zeros(1:image_width, 1);
1280                 % and upper buffer to close mesh
1281           Z(1,:) = zeros(1, 1:n_images * 5);
1282                 % set left buffer
1283           Z(image_width+2,:) = zeros(1, 1:n_images * 5);
1284                 % and right buffer to close mesh
1285           switch mesh_type,  
1286            case 'Surface Red'  
1287             surf(X,Y,Z,'FaceColor', 'red', 'EdgeColor', 'none');
1288             camlight left;
1289             lighting phong;
1290             axis([0 n_images*5 -image_width/2 image_width/2 0 1]);     
1291            case 'Surface Blue'     
1292             surf(X,Y,Z,'FaceColor', 'blue', 'EdgeColor', 'none');
1293             camlight left;
1294             lighting phong;
1295             axis([0 n_images*5 -image_width/2 image_width/2 0 1]);     
1296            case 'Polygons'   
1297             mesh(X,Y,Z);
1298             axis([0 n_images*5 -image_width/2 image_width/2 0 1]);     
1299            case 'Illuminated Surface'
1300             if (rotate_surface),
1301               current_viewpoint = current_viewpoint + 1;
1302                % shift viewpoint slightly
1303             end
1304             view(current_viewpoint, 37.5); 
1305             surface(X,Y,Z, ...
1306               'EdgeColor','none', ...
1307               'FaceColor',[0.5 0.5 0.5], ...
1308               'FaceLighting','phong', ...
1309               'AmbientStrength',0.3, ...
1310               'DiffuseStrength',0.6, ... 
1311               'Clipping','off',...
1312               'BackFaceLighting','lit', ...
1313               'SpecularStrength',1.1, ...
1314               'SpecularColorReflectance',1, ...
1315               'SpecularExponent',7);
1316             if (n == 1), % set lights only at the start
1317                 l1 = light('Position',[40 100 20], ...
1318                   'Style','local', ...
1319                   'Color',[0 0.5 0.7]);
1320                 l2 = light('Position',[.5 -1 .4], ...
1321                   'Color',[1 1 0]);
1322             end
1323            otherwise
1324             error ('Mesh type not recognised. Internal error.');
1325           end
1326           
1327           axis off; 
1328           if (movie_type == 2 & save_movie == 1),
1329                   frame_counter = frame_counter + 1;
1330                   M(frame_counter) = getframe(meshview);
1331           end
1332           if (save_in_log == 1 & n == n_iterations), 
1333              saveas(meshview,[[handle],'-', num2str(figure_handle_number)], 'jpg');
1334              figure_handle_number = figure_handle_number + 1;
1335           end
1336          
1337         end  
1338           
1339         if (strcmp(progress_indicator_type,'Hierarchical Text'))  
1340            % iterations aim to get good statistical results by averaging
1341           disp(['    +-Running iteration number ',num2str(n), ' out of ',num2str(n_iterations), ' iterations...']);
1342         end
1343         
1344            % Smith: correct registration
1345            % attempt to register
1346                
1347         if (see_model_before_each_iteration),  
1348           w_c_model = build_model(warped_images, warped_points, variation_kept,'Optimised warp', weighting_normalisation_method, shape_weight);
1349                   % create an appearance model...
1350           model_view = show_combined_model(w_c_model,ref_points_vec, n_standard_deviations_display, n_modes_display, [[handle],[': Combined model before iteration number ', num2str(n)]]);
1351                   % and show the model before each iteration while saving
1352                   % the figure handle
1353           if (movie_type == 3 & save_movie == 1),
1354                 % if moview needs to be saved and it is a model
1355                   frame_counter = frame_counter + 1;
1356                   M(frame_counter) = getframe(model_view);
1357           end        
1358         end          
1359         for i = 1:n_images,
1360            % start iteration time counter
1361          if (strcmp(progress_indicator_type,'Hierarchical Text')),
1362            disp(['        +-Warping image ',num2str(i),' out of ',num2str(n_images), ' images in total...']);
1363          end
1364          
1365          this_step = ((n-1) * n_images) + i;
1366                     
1367          if (strcmp(progress_indicator_type,'Progress Bar')),
1368            tic;
1369            progress_bar_position = progress_bar_position + step_size;
1370            steps_remaining = (n_images * n_iterations) - this_step;
1371            percentage_progress = ceil(this_step / (n_images * n_iterations) * 100);
1372            minutes = floor(time_for_this_iteration * steps_remaining / 60);
1373            seconds = rem(floor(time_for_this_iteration *  steps_remaining), 60);
1374            max_count   = 50;
1375                % The console-based GUI is 50 units wide
1376            if (seconds > 9),
1377                h = progressbar( h, step_size/50,[num2str(percentage_progress),'% Completed ---- Estimated remaining time: ', num2str(minutes), ':', num2str(seconds)]);
1378            else
1379                h = progressbar( h, step_size/50,[num2str(percentage_progress),'% Completed ---- Estimated remaining time: ', num2str(minutes), ':0', num2str(seconds)]);
1380            end    
1381            if ~gui_active,
1382                     error_found = 1;
1383                     break; 
1384                % If aborted was pressed
1385            end
1386               % use the third-party GUI-like progress bar (added February
1387               % 2004)
1388          end
1389          if (strcmp(progress_indicator_type,'Console Progress Bar')),
1390                                % if console progress bar
1391            tic;
1392            progress_bar_position = progress_bar_position + step_size;
1393            clc;
1394            disp(['|=================================================|']);
1395            progress_string='|';       
1396            for counter = 1:floor(progress_bar_position),
1397                progress_string = [progress_string, '#'];
1398            end
1399            disp(progress_string);
1400            disp(['|================= ',num2str(floor(progress_bar_position * 2)),'% completed =================|']);
1401                           % display progress per cent
1402            steps_remaining = (n_images * n_iterations) - this_step;
1403            minutes = floor(time_for_this_iteration * steps_remaining / 60);
1404            seconds = rem(floor(time_for_this_iteration *  steps_remaining), 60);
1405            disp(' ');
1406            if (seconds > 9),
1407              disp(['            Estimated remaining time: ', num2str(minutes), ':', num2str(seconds)]);
1408                           % show time indicators
1409            else
1410              disp(['            Estimated remaining time: ', num2str(minutes), ':0', num2str(seconds)]);
1411            end
1412          end
1413          
1414          image_vec = warped_images(:,i);
1415          points_vec = warped_points(:,i);     
1416          
1417          if (show_pixels == 1),   
1418              appended_vector=[];
1419              for current_image=1:n_images,
1420                appended_vector=[[appended_vector],[warped_images(:,current_image),[warped_images(:,current_image)]],[warped_images(:,current_image)]];
1421                    % append bump data 3 times for width which is visible
1422              end
1423            
1424                  %% appended_vector=appended_vector * 256
1425                  %% use if scale of 0..255 used
1426     
1427              G = figure(pixels_figure);
1428              hold on;
1429               % title('Bumps as pixels');
1430              imshow(appended_vector',[0,1]);
1431                        % show as an image
1432              if (movie_type == 0 & save_movie == 1),
1433                                    % Note: already nested in a show_pixels
1434                                    % 'if' statement
1435                   frame_counter = frame_counter + 1;
1436                   M(frame_counter) = getframe(G);
1437              end
1438              hold off;
1439          end
1440          
1441          if (movie_type == 1 & save_movie == 1 & do_plot == 1),
1442                    frame_counter = frame_counter + 1;
1443                    M(frame_counter) = getframe(H);
1444          end
1445                    % capture pixels frame
1446          
1447          
1448          if (i ~= immutable_image | force_reference == 0), % make sure one image (second because score evaluation from a predecessor must exist) remains unchanged if reference is forced
1449                        % Somthing richer than a second image might be used
1450                        % in future e.g. mean image
1451              switch objective_function,     
1452                  case 'model_opt_together'
1453                      
1454 %                      if (i==1 & n==1),
1455 %                          score=0;
1456 %                      end
1457 %
1458 %                      last_score = score;
1459 %
1460 %                      % disp(score);
1461 %                   if (i==3)
1462 %                       figure(101);
1463 %                       plot(image_vec);
1464 %                   end
1465                      [param_list, warped_point, warped_image, score] = optimise_all_warps_model([warped_images(:,1:i-1), warped_images(:,i+1:n_images)], [warped_points(:,1:i-1), warped_points(:,i+1:n_images)], image_vec, points_vec, spline_type, placement_type, n_points, verbose, do_plot, subplot_fig, i * vertical_pane_location, vertical_pane_location, image_width, n_images, verbose_score, model_evaluation_method, n_modes, weighting_normalisation_method, shape_weight, variation_kept, show_warps_while_optimising, precision_required);
1466                      
1467                      %if (n==1),
1468                      %  [param_list, warped_point, warped_image, score] = optimise_all_warps_model([warped_images(:,1:i-1),warped_images(:,i+1:n_images)], [warped_points(:,1:i-1),warped_points(:,i+1:n_images)], image_vec, points_vec,spline_type,placement_type,n_points, verbose, do_plot, subplot_fig, i * vertical_pane_location, vertical_pane_location, image_width, n_images, verbose_score, model_evaluation_method, n_modes, weighting_normalisation_method, shape_weight, variation_kept, 0);
1469                      %else
1470                      %   [param_list, warped_point, warped_image, score] = optimise_all_warps_model([warped_images(:,1:i-1),warped_images(:,i+1:n_images)], [warped_points(:,1:i-1),warped_points(:,i+1:n_images)], image_vec, points_vec,spline_type,placement_type,n_points, verbose, do_plot, subplot_fig, i * vertical_pane_location, vertical_pane_location, image_width, n_images, verbose_score, model_evaluation_method, n_modes, weighting_normalisation_method, shape_weight, variation_kept, 1, param_list);
1471                      % end
1472                      
1473                      
1474 %                      if (last_score < score),
1475 %                          disp(num2str((n - 1) * i + i))
1476 %                      end
1477 
1478                  case 'model_pairs_together'    
1479                      [param_list, warped_point, warped_image, score] = optimise_all_warps_model(warped_images(:,1), warped_points(:,1), image_vec, points_vec, spline_type, placement_type, n_points, verbose, do_plot, subplot_fig, i * vertical_pane_location, vertical_pane_location, image_width, n_images, verbose_score, model_evaluation_method, n_modes, weighting_normalisation_method, shape_weight, variation_kept, show_warps_while_optimising, precision_required);    
1480                  case 'model_pairs_separate'  
1481                      [param_list, warped_point, warped_image, score] = optimise_warps_model(warped_images(:,1), warped_points(:,1), image_vec, points_vec, spline_type,placement_type,n_points, verbose, do_plot, subplot_fig, i * vertical_pane_location, vertical_pane_location, image_width, n_images, verbose_score, model_evaluation_method, n_modes, weighting_normalisation_method, shape_weight, variation_kept, show_warps_while_optimising, precision_required);
1482                  case 'model_opt_separate'
1483                      [param_list, warped_point, warped_image, score] = optimise_warps_model([warped_images(:,1:i-1), warped_images(:,i+1:n_images)], [warped_points(:,1:i-1),warped_points(:,i+1:n_images)], image_vec, points_vec,spline_type, placement_type,n_points, verbose, do_plot, subplot_fig, i * vertical_pane_location, vertical_pane_location, image_width, n_images, verbose_score, model_evaluation_method, n_modes, weighting_normalisation_method, shape_weight, variation_kept, show_warps_while_optimising, precision_required);
1484                  case 'msd_opt_together'         
1485                      [param_list, warped_point, warped_image, score] = optimise_all_warps_msd(ref_image_vec, ref_points_vec, image_vec, points_vec, spline_type, placement_type, n_points, verbose, do_plot, subplot_fig, i * vertical_pane_location, vertical_pane_location, image_width, n_images, verbose_score, precision_required);
1486                  case 'msd_opt_separate'
1487                      [param_list, warped_point, warped_image, score] = optimise_warps_msd(ref_image_vec, ref_points_vec, image_vec, points_vec, spline_type, placement_type, n_points, verbose, do_plot, subplot_fig, i * vertical_pane_location, vertical_pane_location, image_width, n_images, verbose_score, precision_required);
1488                  case 'mi_opt_together'       
1489                      [param_list, warped_point, warped_image, score] = optimise_all_warps_mi(ref_image_vec, ref_points_vec, image_vec, points_vec, spline_type, placement_type, n_points, verbose, do_plot, subplot_fig, i * vertical_pane_location, vertical_pane_location, image_width, n_images, verbose_score, number_of_bins, precision_required);
1490                  case 'mi_opt_separate'
1491                      [param_list, warped_point, warped_image, score] = optimise_warps_mi(ref_image_vec, ref_points_vec, image_vec, points_vec, spline_type, placement_type, n_points, verbose, do_plot, subplot_fig, i * vertical_pane_location, vertical_pane_location, image_width, n_images, verbose_score, number_of_bins, precision_required);
1492                  case 'nmi_opt_together'        
1493                      [param_list, warped_point, warped_image, score] = optimise_all_warps_nmi(ref_image_vec, ref_points_vec, image_vec, points_vec, spline_type, placement_type, n_points, verbose, do_plot, subplot_fig, i * vertical_pane_location, vertical_pane_location, image_width, n_images, verbose_score, number_of_bins, precision_required);
1494                  case 'nmi_opt_separate'
1495                      [param_list, warped_point, warped_image, score] = optimise_warps_nmi(ref_image_vec, ref_points_vec, image_vec, points_vec, spline_type, placement_type, n_points, verbose, do_plot, subplot_fig, i * vertical_pane_location, vertical_pane_location, image_width, n_images, verbose_score, number_of_bins, precision_required);
1496                  case 'mixed_msd_model'
1497                         if (((n / n_iterations < 2 / 10) & (n / n_iterations >= 1 / 10)) |...
1498                             ((n / n_iterations < 4 / 10) & (n / n_iterations >= 3 / 10)) |...
1499                             ((n / n_iterations < 6 / 10) & (n / n_iterations >= 5 / 10)) |...
1500                             ((n / n_iterations < 8 / 10) & (n / n_iterations >= 7 / 10)) |...
1501                             ((n / n_iterations < 10 / 10) & (n / n_iterations >= 9 / 10))),
1502                           [param_list, warped_point, warped_image, score] = optimise_all_warps_msd(ref_image_vec, ref_points_vec, image_vec, points_vec, spline_type, placement_type, n_points, verbose, do_plot, subplot_fig, i * vertical_pane_location, vertical_pane_location, image_width, n_images, verbose_score, precision_required);
1503                         else
1504                           [param_list, warped_point, warped_image, score] = optimise_all_warps_model([warped_images(:,1:i-1),warped_images(:,i+1:n_images)], [warped_points(:,1:i-1),warped_points(:,i+1:n_images)], image_vec, points_vec,spline_type,placement_type,n_points, verbose, do_plot, subplot_fig, i * vertical_pane_location, vertical_pane_location, image_width, n_images, verbose_score, model_evaluation_method, n_modes, weighting_normalisation_method, shape_weight, variation_kept, show_warps_while_optimising, precision_required);
1505                         end                    
1506                  case 'model_post_msd'
1507                         if (n / n_iterations < 1 / 2),
1508                             % for the first half
1509                           [param_list, warped_point, warped_image, score] = optimise_all_warps_msd(ref_image_vec, ref_points_vec, image_vec, points_vec, spline_type, placement_type, n_points, verbose, do_plot, subplot_fig, i * vertical_pane_location, vertical_pane_location, image_width, n_images, verbose_score, precision_required);
1510                         else
1511                             % and for the second half
1512                           [param_list, warped_point, warped_image, score] = optimise_all_warps_model([warped_images(:,1:i-1),warped_images(:,i+1:n_images)], [warped_points(:,1:i-1),warped_points(:,i+1:n_images)], image_vec, points_vec,spline_type,placement_type,n_points, verbose, do_plot, subplot_fig, i * vertical_pane_location, vertical_pane_location, image_width, n_images, verbose_score, model_evaluation_method, n_modes, weighting_normalisation_method, shape_weight, variation_kept, show_warps_while_optimising, precision_required);
1513                         end
1514                  case 'tfc_eccv'
1515                      % msgbox('TFC ECCV 2004: Under Construction.');
1516                      pdf_evalution_method = 'Default';
1517                      [param_list, warped_point, warped_image, score] = optimise_groupwise([warped_images(:,1:i-1),warped_images(:,i+1:n_images)], [warped_points(:,1:i-1),warped_points(:,i+1:n_images)], image_vec, points_vec,spline_type,placement_type,n_points, verbose, do_plot, subplot_fig, i * vertical_pane_location, vertical_pane_location, image_width, n_images, verbose_score, model_evaluation_method, n_modes, weighting_normalisation_method, shape_weight, variation_kept, pdf_evalution_method, kernel, precision_required);         
1518                  case 'wavelet_complexity'
1519                      % msgbox('Wavelets: Under Construction.');
1520                      wavelet_evalution_method = 'Default';
1521                      [param_list, warped_point, warped_image, score] = optimise_wavelet([warped_images(:,1:i-1),warped_images(:,i+1:n_images)], [warped_points(:,1:i-1),warped_points(:,i+1:n_images)], image_vec, points_vec,spline_type,placement_type,n_points, verbose, do_plot, subplot_fig, i * vertical_pane_location, vertical_pane_location, image_width, n_images, verbose_score, model_evaluation_method, n_modes, weighting_normalisation_method, shape_weight, variation_kept, wavelet_evalution_method, filter, filter_level, precision_required);                      
1522                  case 'void'
1523                     % This is used for repeated experiments with overlaid
1524                     % plots. It is not well tested and score may need to be
1525                     % assigned to a value here
1526                      break;
1527                      % It is not obsolutely clear id the above is necessary
1528                      % or works
1529                  otherwise
1530                      error(['Unknown objective function: ', objective_function]);
1531              end
1532          else
1533             % score = 0;
1534             warped_image = warped_images(:,i);
1535             warped_point = warped_points(:,i); 
1536                   % copy some values to make up for the skip
1537             if (do_plot == 1),
1538               figure(subplot_fig);
1539               subplot(n_images, vertical_pane_location , vertical_pane_location * i, 'replace');
1540               plot(warped_image);
1541               axis([0 image_width 0 1]);
1542               drawnow;
1543             end
1544                   % draw the plot
1545          end
1546 
1547 
1548          warped_images(:,i) = warped_image;
1549            
1550 
1551          if (retain_original_peak), 
1552            warped_images(maximum_position(i), i) = maximum_height(i);
1553               % always retain the maximum height
1554          end     
1555               
1556               
1557               
1558               
1559          warped_points(:,i) = warped_point;
1560          
1561          if (draw_warp_curve == 1),
1562            figure(overlap_curve_fig);
1563            hold on;
1564            plot(warped_points(:,i));
1565            hold off;
1566            if (save_in_log == 1 & n == n_iterations & i == n_images), 
1567                saveas(overlap_curve_fig,[[handle],'-', num2str(figure_handle_number)], 'jpg');
1568                figure_handle_number = figure_handle_number + 1;
1569            end
1570          end     
1571          
1572          if (draw_curve_by_images == 1),
1573              figure(curves);
1574              subplot(n_images, n_iterations + 1, i * (n_iterations + 1) - (n_iterations - n));
1575              hold on;
1576              axis off;
1577              plot(warped_points(:,i));
1578              axis([-1 image_width -1 1]);
1579              hold off;
1580              if (save_in_log == 1 & n == n_iterations & i == n_images), 
1581                saveas(curves,[[handle],'-', num2str(figure_handle_number)], 'jpg');
1582                figure_handle_number = figure_handle_number + 1;
1583              end
1584          end
1585          if (show_pixels == 1 & save_in_log == 1 & n == n_iterations & i == n_images), 
1586                saveas(G,[[handle],'-', num2str(figure_handle_number)], 'jpg');
1587                figure_handle_number = figure_handle_number + 1;
1588          end
1589          if (do_plot == 1 & save_in_log == 1 & n == n_iterations & i == n_images), 
1590                saveas(H,[[handle],'-', num2str(figure_handle_number)], 'jpg');
1591                figure_handle_number = figure_handle_number + 1;
1592          end
1593          
1594          % figure(subplot_fig),title(['Warped images, after image ',num2str(i),' iteration ',num2str(n)]);
1595          % dummy = waitforbuttonpress;
1596          if (show_score_using_model == 1),           
1597              % if evaluation is through model then always overwrite score
1598             c_model = build_model(warped_images, warped_points, variation_kept, '', weighting_normalisation_method, shape_weight);
1599                 % first build a model
1600             if (strcmp(model_score_type, 'Default')),
1601                 score = measure_model(c_model.variances, n_modes, model_evaluation_method, c_model);
1602             elseif (strcmp(model_score_type, 'Specificity')),
1603                 if (mod(n_images * (n - 1) + i, cycle) == 0),
1604                     % disp('ok')
1605                   [score, std_spec] = find_specificity(c_model, images, spec_iters, ref_points_vec);
1606                   standard_deviation(n_images * (n - 1) + i) = std_spec;
1607                 else
1608                     % set to -1 (or copy from predecessor - the original
1609                     % intension
1610                   score = -1; 
1611                 end
1612             elseif (strcmp(model_score_type, 'Generalisability')), 
1613                if (mod(n_images * (n - 1) + i, cycle) == 0),
1614                   [score, std_gen] = find_generalisability(c_model, gen_iters);
1615                   standard_deviation(n_images * (n - 1) + i) = std_gen;
1616                else   
1617                   score = -1;
1618                end  
1619             elseif (strcmp(model_score_type, 'Mean MSD')),
1620                 if (mod(n_images * (n - 1) + i, cycle) == 0),
1621                     score = measure_model_msd(warped_images);
1622                 else
1623                     score = -1; 
1624                 end
1625             elseif (strcmp(model_score_type, 'All')),
1626               % score = measure_model(c_model.variances, n_modes, model_evaluation_method, c_model);
1627                             % use deafult as score that is primary
1628                 all_scores = [[find_specificity(c_model, images, spec_iters, ref_points_vec)], [find_generalisability(c_model, gen_iters)], [measure_model_msd(warped_images)]];    
1629                            % get all scores above and store them in a
1630                            % matrix
1631             else
1632                error(['Wrong scoring method (', [model_score_type], ') passed. Internal error.']);
1633             end
1634             
1635          end    
1636     
1637     
1638          if(n == n_iterations),
1639             final_score(i, this_set) = score;
1640                 % give the final score for the set if end is reached
1641          end
1642          
1643          score_for_iteration(i,n) = score;
1644                % record the score for this iteration and this image to be later
1645                % plotted for analysis
1646          if (strcmp(model_score_type, 'All')),
1647              all_scores_for_iteration(i,n,1) = all_scores(1);
1648              all_scores_for_iteration(i,n,2) = all_scores(2);
1649              all_scores_for_iteration(i,n,3) = all_scores(3);
1650          end    
1651          if ((strcmp(progress_indicator_type,'Progress Bar')) | (strcmp(progress_indicator_type,'Console Progress Bar'))),
1652            times(this_step) = toc;
1653            time_for_this_iteration = mean (times);
1654          end
1655         end  % end:images
1656         
1657         % The next section deals with point stuffing
1658         
1659         %% Note: cycle scale option here... perform this stage every
1660         %% <add_points_cycle> iterations
1661         if (mod(n, add_points_cycle) == 0)
1662           if (add_points),
1663             for i = 1:n_images,  
1664               for j = 1:image_width - 1, 
1665                 % -Find region in <points> where height difference is high
1666                   difference(j, i) = warped_points(j + 1, i) - warped_points(j, i);
1667               end
1668               
1669               maximum_difference(i) = max(difference(:, i));
1670               for current_position_number = 1:size(difference(:, i), 1),
1671                 if (difference(current_position_number, i) == maximum_difference(i)),
1672                      maximum_difference_location(i) = current_position_number;
1673                         % maximal diffference in position n means that the
1674                         % internal between points(n) and points(n + 1) is
1675                         % maximal
1676                 end
1677               end
1678             end
1679             
1680             
1681               
1682             % -Add points in between that range
1683             % -Set them to some values
1684             % in between.
1685             % -Update <image_width> and all data including
1686             % references
1687             for i = 1:n_images,
1688                 temp_image = warped_images(:, i);
1689                 temp_points = warped_points(:, i);
1690                 for j = maximum_difference_location(i) + 1:image_width,
1691                   warped_points(j + 1,i) = temp_points(j);
1692                   warped_images(j + 1,i) = temp_image(j);
1693               end
1694               
1695                  % shift points one position onwards where stuffing occurs
1696                 warped_points(maximum_difference_location(i) + 1, i) = warped_points(maximum_difference_location(i), i) + maximum_difference(i) / 2;
1697                  % NOTE: THE DIFFERENCE SHOULD NOT BE UNIFORM FOR ALL DATA,
1698                  % It was calculated specifically for each data instance.
1699                  % set new point to lie at the average of its two neighbouring points
1700                 warped_images(maximum_difference_location(i) + 1, i) = mean(warped_images(maximum_difference_location(i) + 1, :)); 
1701                  % -Set new <image> points with similar structures and set their
1702                  % value to one which is projected from the mean.
1703                  % NOTE: REFERENCES ARE BEING CHANGED TOO
1704             end
1705               image_width = image_width + 1;
1706               
1707                 % modify the size of images
1708 %               size(warped_points)
1709 %               size(warped_images)
1710 %               warped_points
1711 %               warped_images
1712             
1713           end % end: point stuffing if
1714         end % end: clcle if
1715         
1716       end  % end:iterations
1717       if (strcmp(progress_indicator_type,'Progress Bar')),
1718                 h = progressbar( h, 0, 'Finalising');
1719       end
1720       if (show_score_vs_iteration),
1721           if (show_all_score_figure_types == 1)            
1722               score_figure = figure('Name', [[handle],[': Score versus iterations for every image warping step - objective function: '],[objective_function]]);
1723                      % create a new figure to show graph of optimisation for
1724                      % all steps and all images individually
1725               hold on;
1726               title('Score versus iterations for every image warping step');
1727               xlabel('Iteration number');
1728               ylabel('Score');
1729               for i=1:n_images,
1730                     plot(score_for_iteration(i,:));
1731               end
1732               hold off;
1733               
1734               figure('Name', [[handle],[': Score versus iterations - objective function: '],[objective_function]]);
1735                      % create a new figure to show graph of optimisation
1736               hold on;
1737               title('Score versus iterations');
1738               xlabel('Iteration number');
1739               ylabel('Mean score');
1740               for i=1:n_iterations,
1741                  mean_score(i) = mean(score_for_iteration(:,i));
1742               end   
1743               plot(mean_score);
1744               hold off;
1745           end   
1746           
1747           if (overlap_scores == 0),
1748              score_figure = figure('Name', [[handle],[': Score versus image warping step - objective function: '],[objective_function]]);
1749                  % create a new figure to show graph of optimisation
1750           else
1751               
1752              score_figure = figure(101);
1753           end
1754           
1755           hold on;
1756           
1757           if (strcmp(model_score_type, 'All')),
1758             title('Proportional score versus image warping step');
1759             xlabel('Warping Step');
1760             ylabel('% Change');  
1761             position_counter = 0;  
1762             for i=1:n_iterations,
1763               for j=1:n_images,
1764                 position_counter = position_counter + 1;
1765                 all_warp_step_score_vector(position_counter,1) = all_scores_for_iteration(j,i,1);
1766                 all_warp_step_score_vector(position_counter,2) = all_scores_for_iteration(j,i,2);
1767                 all_warp_step_score_vector(position_counter,3) = all_scores_for_iteration(j,i,3);
1768               end
1769             end
1770             all_warp_step_percent_vector(1,1) = 0;
1771                                % no change
1772             all_warp_step_percent_vector(2,1) = 0;
1773             all_warp_step_percent_vector(3,1) = 0;
1774                 
1775             for i = 2:n_iterations * n_images,
1776                     all_warp_step_percent_vector(1,i) = (all_warp_step_score_vector(i,1) - all_warp_step_score_vector(i-1,1)) / (all_warp_step_score_vector(i-1,1) + 0.001) * 100;
1777                     all_warp_step_percent_vector(2,i) = (all_warp_step_score_vector(i,2) - all_warp_step_score_vector(i-1,2)) / (all_warp_step_score_vector(i-1,2) + 0.001) * 100;
1778                     all_warp_step_percent_vector(3,i) = (all_warp_step_score_vector(i,3) - all_warp_step_score_vector(i-1,3)) / (all_warp_step_score_vector(i-1,3) + 0.001) * 100;              
1779             end          
1780           else
1781               title('Score versus image warping step');
1782               xlabel('Warping Step');
1783               ylabel('Score');
1784               position_counter = 0;
1785               for i=1:n_iterations,
1786                   for j=1:n_images,
1787                     position_counter = position_counter + 1;
1788                     warp_step_score_vector(position_counter) = score_for_iteration(j,i);
1789                   end
1790               end
1791           end
1792           if (run_all_objective_functions == 1),
1793               if strcmp(colour,'r'),
1794                 colour = 'g';
1795               elseif strcmp(colour,'g')
1796                 colour = 'b';
1797               else
1798                 colour = 'r';
1799               end 
1800               
1801               if strcmp(style,':'),
1802                 style = '-';
1803               elseif strcmp(style,'-')
1804                 style = '--';
1805               elseif strcmp(style,'--')
1806                 style = '-.'; 
1807               else
1808                 style = ':';
1809               end 
1810               plot(warp_step_score_vector,[[colour],[style]]);
1811               % The next line needs to be updated when new objective
1812               % functions are added
1813               legend('Joint MSD','Sequential MSD','Joint Model-based','Sequential Model-based','Joint MI',...
1814                      'Sequential MI', 'Joint NMI', 'Sequential NMI', 'PDF', 'Wavelets', 'Joint Model-based Pair-wise', 'Sequential Model-based Pair-wise', 'Void');
1815           else
1816                 % if a normal single plot will suffice
1817                 if (strcmp(model_score_type, 'All')),
1818                          plot (all_warp_step_percent_vector(1,:), 'r');
1819                          plot (all_warp_step_percent_vector(2,:), 'g');
1820                          plot (all_warp_step_percent_vector(3,:), 'b');
1821                          legend('Specificity', 'Generalisability', 'Mean MSD');
1822                 else 
1823                           if (strcmp(progress_indicator_type,'Progress Bar')),
1824                               h = progressbar( h, 0, 'Generating Scores Plot');
1825                           end    
1826                          % find any -1 entries and "destroy" them to get
1827                          % correct cycle evaluation
1828                          % optimisation tip: use cycle to pick out the
1829                          % right entries rather than the naive -1 flag
1830                          counter = 1;
1831                          for index=1:n_images*n_iterations,
1832                              if (warp_step_score_vector(index) ~= -1),
1833                                  if (strcmp(model_score_type, 'Generalisability') | strcmp(model_score_type, 'Specificity')),
1834                                    standard_deviation_truncated(counter) = standard_deviation (index);
1835                                  end   
1836                                  warp_step_score_vector_truncated(counter) =  warp_step_score_vector(index);
1837                                  counter = counter + 1;
1838                              end
1839                          end    
1840                          if (strcmp(model_score_type, 'Generalisability') | strcmp(model_score_type, 'Specificity')),
1841                              errorbar(warp_step_score_vector_truncated, standard_deviation_truncated);
1842                              title([model_score_type, ' every ', num2str(cycle), ' steps']);
1843                          elseif (strcmp(model_score_type, 'Mean MSD'))
1844                               % for mean MSD
1845                              plot (warp_step_score_vector_truncated); 
1846                              title(['Mean MSD every ', num2str(cycle), ' steps']);
1847                          else % model defaults
1848                              plot (warp_step_score_vector); 
1849                              title(['Registration score versus iterations']);
1850                          end
1851                          
1852                 end
1853                 if (show_target == 1),
1854                     Epsilon = 0.0001;
1855                     plot (repmat([log(Epsilon.^n_modes)], 1,n_iterations * n_images),'--');
1856                     legend('Current Evaluation','Log eigenvalues of perfectly registered images');
1857                 end
1858                 if (show_registration_target == 1),
1859                     w_c_model = build_model(correctly_warped_images', correctly_warped_points', variation_kept, 'Optimised warp', weighting_normalisation_method, shape_weight);      
1860                     model_score =  measure_model(w_c_model.variances, n_modes, model_evaluation_method, w_c_model);
1861                     plot(repmat(model_score, 1,n_iterations * n_images),'r-.');
1862                     if (show_target == 1),
1863                       legend('Current Evaluation','Log eigenvalues of perfectly registered images','Log eigenvalues of registration target');
1864                     else 
1865                       legend('Current Evaluation','Log eigenvalues of registration target');
1866                     end  
1867                 end    
1868           end   
1869           
1870           hold off;
1871           if (save_in_log == 1),
1872                score_handle = figure(score_figure);
1873                saveas(score_handle,[[handle],'-', num2str(figure_handle_number)], 'jpg');
1874                figure_handle_number = figure_handle_number + 1;
1875           end
1876       end
1877       
1878       w_c_model = build_model(warped_images, warped_points, variation_kept, 'Optimised warp', weighting_normalisation_method, shape_weight);      
1879          % Smith: build model from warped images
1880       w_intensity_total_vars = w_c_model.intensity_model.total_var;
1881       w_shape_total_vars = w_c_model.shape_model.total_var;
1882          % get these two values to be used later
1883       model_score(this_set) = measure_model(w_c_model.variances, n_modes, model_evaluation_method, w_c_model);
1884       msd_score(this_set) = measure_model_msd(warped_images);
1885       shape_modes(this_set) = w_c_model.n_shape_modes;
1886       intensity_modes(this_set) = size(w_c_model.intensity_model.pcs,2);
1887       shape_variance(this_set) = sum(w_c_model.shape_model.variances);
1888       intensity_variance(this_set) = sum(w_c_model.intensity_model.variances);
1889          % copy some values to be displayed for statistics
1890       
1891       if (show_model_after_optimisation == 1),
1892           model_handle = show_combined_model(w_c_model, ref_points_vec, n_standard_deviations_display, n_modes_display, [[handle],[': Final combined model built from optimised warps - objective function: '],[objective_function]], image_width);
1893           if (save_in_log == 1),
1894                saveas(model_handle,[[handle],'-', num2str(figure_handle_number)], 'jpg');
1895                figure_handle_number = figure_handle_number + 1;
1896           end
1897       end
1898       
1899       
1900       if (display_intensity_model == 1),
1901         [intensity_model.pcs,intensity_model.variances,intensity_model.params, intensity_model.mean, intensity_model.var_r, intensity_model.total_var, intensity_model.impdata] = st_pca(warped_images', variation_kept);
1902           % perform PCA
1903         intensity_model.sd = std(intensity_model.params);
1904               % get standard deviation from the models (of shape and intensity)
1905         intensity_total_vars = intensity_model.total_var;
1906         total_intensity_variance = sum(intensity_model.variances);
1907         fig_title = 'After registration: ';
1908         intensity_model_handle = show_intensity_model(intensity_model, 2, 2, fig_title, image_width);
1909         if (save_in_log == 1),
1910                saveas(intensity_model_handle, [[handle], '-', num2str(figure_handle_number)], 'jpg');
1911                figure_handle_number = figure_handle_number + 1;
1912         end
1913       end  
1914       
1915       if (display_shape_model == 1),  
1916         [shape_model.pcs,shape_model.variances,shape_model.params, shape_model.mean, shape_model.var_r, shape_model.total_var, shape_model.impdata] = st_pca(warped_points', variation_kept);
1917         shape_model.sd = std(shape_model.params);
1918         shape_total_vars = shape_model.total_var;
1919         total_shape_variance = sum(shape_model.variances);
1920         shape_model_handle = show_shape_model(shape_model, ref_points_vec, ref_image_vec, 2, image_width);
1921         if (save_in_log == 1),
1922                saveas(shape_model_handle, [[handle], '-', num2str(figure_handle_number)], 'jpg');
1923                figure_handle_number = figure_handle_number + 1;
1924         end        
1925       end  
1926           
1927       if (show_specificity_statistics),
1928         [w_c_model.mean_specificity, w_c_model.std_specificity] = find_specificity(w_c_model, images, spec_iters, ref_points_vec);
1929         disp(' ');
1930         disp([['Objective function: '], [objective_function]]);
1931         disp(['Mean of specificity:               ', num2str(w_c_model.mean_specificity)]);
1932         disp(['Standard deviation of specificity: ', num2str(w_c_model.std_specificity)]);
1933       end
1934       
1935       if (draw_final_warps),
1936           final_warps = figure('Name',[['Warp Curves - objective function: '], [objective_function]]);
1937           final_warps_handle = figure(final_warps);
1938           % title('Warp Curves at end);
1939           for i=1:n_images,
1940             subplot(n_images, 1, i);
1941             hold on;
1942             axis off;
1943             plot(warped_points(:,i));
1944             plot(correctly_warped_points(i,:),'r-')
1945             if (i == 1 ),
1946               legend('Final warp', 'Piece-wise linear target warp'); 
1947               % only display the legend once at the top
1948             end
1949             axis([-1 image_width -1 1]);
1950           end
1951           hold off;       
1952           if (save_in_log == 1),
1953                saveas(final_warps_handle, [[handle], '-', num2str(figure_handle_number)], 'jpg');
1954                figure_handle_number = figure_handle_number + 1;
1955           end  
1956        end
1957      
1958     
1959     % fig_title = 'Automatically aligned: ';
1960     % show_shape_model(w_shape_model, ref_points_vec, ref_image_vec, 2, white_width)
1961     % show_intensity_model(w_intensity_model, 2, white_width, fig_title)
1962     % show_combined_model(w_c_model, ref_points_vec, 2, white_width, fig_title)
1963     
1964     
1965     
1966     
1967     %%             END OF MODEL-BUILDING                    %%
1968     %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1969     
1970     
1971     
1972     %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1973     %% Now provide some statistics on the                   %%
1974     %% simulation/experiment                                %%
1975     
1976       
1977       %% Warping images, then modelling warped images    %%
1978     %% attempt to register images by warping.          %%
1979     
1980       if (plot_before_and_after == 1),
1981         subplot_fig = figure('Name', [[handle],[': Left: Before registration; Right: After registration - Objective function: '], [objective_function]]);
1982         H=figure(subplot_fig);
1983         for i=1:n_images,
1984            subplot(n_images, vertical_pane_location, (vertical_pane_location * i) - vertical_pane_location + 1);
1985            hold on;
1986            plot(images_before_offset(:,i));
1987            % title(['Unwarped image #',num2str(i)]);
1988            axis([0 image_width 0 1]);
1989            grid on;
1990            hold off;
1991         end
1992         if (apply_intensity_offset),
1993           for index = 1:n_images,
1994              peak (index) = max(images(:,index));
1995           end
1996           peak_reference = max (peak);  
1997           for index = 1:n_images,
1998             peak_difference = peak_reference - max(images(:,index));
1999             images(:,index) = images(:,index) + peak_difference;
2000             subplot(n_images, vertical_pane_location, (vertical_pane_location * index) - vertical_pane_location + 2);
2001             hold on;
2002             plot(images(:,index));
2003             % title(['Unwarped image #',num2str(i)]);
2004             axis([0 image_width 0 1]);
2005             grid on;
2006             hold off;
2007           end        
2008         end    
2009     
2010           % pass a void figure to the optimisation functions
2011         for i=1:n_images,
2012            subplot(n_images, vertical_pane_location, i * vertical_pane_location);
2013            hold on;
2014            plot(warped_images(:,i));
2015            % title(['Unwarped image #',num2str(i)]);
2016            axis([0 image_width 0 1]);
2017            grid on;
2018            hold off;
2019         end  
2020         if (save_in_log == 1), 
2021                saveas(subplot_fig,[[handle],'-', num2str(figure_handle_number)], 'jpg');
2022                figure_handle_number = figure_handle_number + 1;
2023         end
2024       else
2025         subplot_fig = 0; 
2026       end
2027     
2028       
2029  end % while
2030  
2031  t = toc;
2032       
2033  if (strcmp(progress_indicator_type,'Hierarchical Text')),
2034          disp(['Time for set ',num2str(this_set),': ',num2str(t)]);
2035  end
2036  time(this_set) = t;
2037  
2038 end % end set
2039 
2040 
2041 
2042 if (produce_statistics == 1),
2043     disp(' ');
2044     disp(['======================================================']); 
2045     disp(['================= SET STATISTICS =====================']);
2046     disp(['| Objective function:                       ', objective_function]);
2047     disp(['| Mean of match score:                      ', num2str(mean(final_score(:)))]);    
2048     disp(['| Standard deviation of match score:        ', num2str(std(final_score(:)))]);
2049     disp(['| Mean of model score:                      ', num2str(mean(model_score(:)))]);
2050     disp(['| Log of mean of model score:               ', num2str(log(mean(model_score(:))))]);
2051     disp(['| Standard deviation of model score:        ', num2str(std(model_score(:)))]);
2052     disp(['| Mean of MSD score:                        ', num2str(mean(msd_score(:)))]);
2053     disp(['| Standard deviation of MSD score:          ', num2str(std(msd_score(:)))]);
2054     disp(['| Mean of shape modes:                      ', num2str(mean(shape_modes(:)))]);
2055     disp(['| Standard deviation of shape modes:        ', num2str(std(shape_modes(:)))]);
2056     disp(['| Mean of intensity modes:                  ', num2str(mean(intensity_modes(:)))]);
2057     disp(['| Standard deviation of intensity modes:    ', num2str(std(intensity_modes(:)))]);
2058     disp(['| Mean of shape variance:                   ', num2str(mean(shape_variance(:)))]);
2059     disp(['| Standard deviation of shape variance:     ', num2str(std(shape_variance(:)))]);        
2060     disp(['| Mean of intensity variance:               ', num2str(mean(intensity_variance(:)))]);    
2061     disp(['| Standard deviation of intensity variance: ', num2str(std(intensity_variance(:)))]);    
2062     disp(['| Mean time:                                ', num2str(mean(time(:)))]);    
2063     disp(['| Standard deviation of time:               ', num2str(std(time(:)))]);    
2064     t = toc;
2065          % get time from the counter, initiated by <tic>
2066     disp(['| Total time:                               ', num2str(t)]);
2067          % display total time
2068     disp(['======================================================']); 
2069 end
2070 
2071 if (save_stats == 1),
2072     fid = fopen([[handle], ['.htm']],'w');
2073     add_html_headers(fid);
2074     fprintf(fid, ['\n<CENTER><TABLE BORDER=BOX CELLPADDING=10 CELLSPACING=3 BACKGROUND="../../scbg.gif"><TR>']);
2075     fprintf(fid, ['\n<TD><H2>Ststistics for ', [handle], '</H2>']);
2076     fprintf(fid, ['\n<BR><U>Objective function:</U> ', objective_function]);
2077     fprintf(fid, ['\n<BR><U>Mean of match score:</U> ', num2str(mean(final_score(:)))]);
2078     fprintf(fid, ['\n<BR><U>Standard deviation of match score:</U> ', num2str(std(final_score(:)))]);
2079     fprintf(fid, ['\n<BR><U>Mean of model score:</U> ', num2str(mean(model_score(:)))]);
2080     fprintf(fid, ['\n<BR><U>Log of mean of model score:</U> ', num2str(log(mean(model_score(:))))]);
2081     fprintf(fid, ['\n<BR><U>Standard deviation of model score:</U> ', num2str(std(model_score(:)))]);
2082     fprintf(fid, ['\n<BR><U>Mean of MSD score:</U> ', num2str(mean(msd_score(:)))]);
2083     fprintf(fid, ['\n<BR><U>Standard deviation of MSD score:</U> ', num2str(std(msd_score(:)))]);
2084     fprintf(fid, ['\n<BR><U>Mean of shape modes:</U> ', num2str(mean(shape_modes(:)))]);
2085     fprintf(fid, ['\n<BR><U>Standard deviation of shape modes:</U> ', num2str(std(shape_modes(:)))]);
2086     fprintf(fid, ['\n<BR><U>Mean of intensity modes:</U> ', num2str(mean(intensity_modes(:)))]);
2087     fprintf(fid, ['\n<BR><U>Standard deviation of intensity modes:</U> ', num2str(std(intensity_modes(:)))]);
2088     fprintf(fid, ['\n<BR><U>Mean of shape variance:</U> ', num2str(mean(shape_variance(:)))]);
2089     fprintf(fid, ['\n<BR><U>Standard deviation of shape variance:</U> ', num2str(std(shape_variance(:)))]);
2090     fprintf(fid, ['\n<BR><U>Mean of intensity variance:</U> ', num2str(mean(intensity_variance(:)))]);   
2091     fprintf(fid, ['\n<BR><U>Standard deviation of intensity variance:</U> ', num2str(std(intensity_variance(:)))]);
2092     fprintf(fid, ['\n<BR><U>Mean time:</U> ', num2str(mean(time(:)))]);
2093     fprintf(fid, ['\n<BR><U>Standard deviation of time:</U> ', num2str(std(time(:)))]);    
2094     fprintf(fid, ['\n<BR><U>Total time:</U> ', num2str(t)]);
2095     fprintf(fid, ['\n</TD></TR>']);     
2096     fprintf(fid, '\n</TABLE></CENTER><BR><BR>');
2097     fclose(fid);
2098 end
2099 
2100 
2101 
2102 if (produce_record == 1),
2103      % In the GUI it has been renamed to "Display Record"
2104     clc;
2105     disp(' ');
2106     disp(' ');
2107     disp('===============================================');
2108     disp(['| Simulation Handle: ', [handle]]);
2109     disp(['| Description: ', [description]]);
2110     disp('|==============================================');
2111     disp(['| AART - ', [get_month], ' ', [get_year], ' - Version ', [get_version], ' - ', [getenv('OS')]]);
2112     disp(['| Run on machine: ', [get_host], '| Domain: ', [get_domain], '| Image width: ', num2str(image_width)]);
2113     disp('|==============================================');
2114     disp(' ');
2115     disp('|== GENERAL ===================================');
2116     disp(['| Objective Function: ', objective_function]);
2117     disp(['| Data type identifier: ', num2str(load_data)]); 
2118     disp(['| Iterations: ', num2str(n_iterations)]);
2119     disp(['| Images: ', num2str(n_images)]);
2120     disp(['| Sets: ', num2str(n_sets)]);
2121     disp(['| Corrective Offset (boolean): ', num2str(apply_intensity_offset)]);
2122     disp('|==============================================');
2123     disp(' ');
2124     disp('|== SMOOTHING =================================');
2125     disp(['| Smoothing window: ', num2str(window)]);
2126     disp(['| Gaussian smoothing (boolean): ', num2str(gaussian_smooth_enabled)]);  
2127     disp(['| Average smoothing (boolean): ', num2str(average_smooth_enabled)]);
2128     disp('|==============================================');
2129     disp(' ');
2130     disp('|== OBJECTIVE FUNCTION-SPECIFIC ===============');
2131      disp(['| Precision Required (All): ', num2str(precision_required)]);
2132     disp(['| Number of bins (MI, NMI): ', num2str(number_of_bins)]);
2133     disp(['| Number of model modes: ', num2str(n_modes)]);
2134     disp(['| Variation Kept (PCA): ', num2str(variation_kept)]);
2135     disp(['| Weighting normalisation method: ', weighting_normalisation_method]);
2136     disp(['| Contant weighting value: ', num2str(shape_weight)]);
2137     disp(['| PDF type: ', kernel]);
2138     disp(['| Wavelet filter: ', filter]);
2139     disp(['| Compression level: ', num2str(filter_level) ]); 
2140     disp(['| Model evaluation method: ',  num2str(model_evaluation_method)]);
2141     disp(['| Specificity iterations: ', num2str(spec_iters)  ]);
2142     disp(['| Generalisability iterations: ', num2str(gen_iters)  ]);
2143     disp(['| Evaluation cycle: ', num2str(cycle)  ]);    
2144     disp('|==============================================');
2145     disp(' ');
2146     disp('|== TRANSFORMATION ============================');
2147     disp(['| CPS Spline type: ', spline_type  ]);
2148     disp(['| Knot-point placement method: ', placement_type]);  
2149     disp(['| Number of knot-points: ', num2str(n_points)]);
2150     disp(['| Automatic precision (boolean): ', num2str(dynamic_precision)]);
2151     disp(['| Initialise near target (boolean): ', num2str(initialise_warps_close_to_target)]);
2152     disp(['| Offset extent: ', num2str(offset_extent)]);
2153     disp(['| Perturbation method: ', [perturbation_method]]);
2154     disp(['| Force reference (boolean): ', num2str(force_reference)]);
2155     disp(['| Reference type: ', num2str(force_first_reference)]);
2156     disp(['| Distance type: ', num2str(distance_type)]);    
2157     disp(['| Retain peak (boolean): ', num2str(retain_original_peak)]);    
2158     disp(['| Peak type: ', [peak_type]]);    
2159     disp(['| Stuff points (boolean): ', num2str(add_points)]);    
2160     disp(['| Point stuffing cycle: ', num2str(add_points_cycle)]);    
2161     disp('|==============================================');
2162     disp(' ');
2163     disp('|== DATA ======================================');
2164     disp(['| Base height variation: ', num2str(bump_height)  ]);
2165     disp(['| Height variation: ', num2str(bump_height_variation) ]);
2166     disp(['| Base width variation: ', num2str(bump_width)  ]);
2167     disp(['| Width variation: ', num2str(bump_width_variation) ]);
2168     disp(['| Position Freedom: ', num2str(bump_position_freedom)  ]);
2169     disp(['| Smoothness: ', num2str(smoothness_factor)]);
2170     disp('|==============================================');
2171     disp(' ');
2172     disp('|==============================================');
2173     disp('| Results and outputs to be located by handle |');
2174     disp('===============================================');    
2175        
2176 end  
2177 
2178 if (save_in_log == 1),
2179      % if the parameters need to be included in the log file
2180     
2181 %     fid_test = fopen('aartlo.htm','r');
2182 %     f = fread(fid_test,1);
2183 %     c = char (f')
2184 %     a=2
2185 %     fclose(fid_test);
2186     if (save_movie == 1),
2187       movie_name = [[handle], '-1'];
2188     end 
2189     % modify the name of the movie to fit the HTML link
2190     % if multiple movies are added in the future, then the HTML structure
2191     % needs to fit the extra links (slots)
2192 
2193     if (strcmp(which('aartlog.htm'), '')),
2194         add_headers = 1;
2195     else
2196         add_headers = 0;
2197     end
2198 
2199     
2200     
2201     fid = fopen('aartlog.htm','a');
2202     if (add_headers == 1),
2203       add_html_headers(fid);
2204     end
2205     
2206     fprintf(fid, ['\n<BR><CENTER><A HREF="index.htm"><IMG src="../../back.jpg" border="0" ALT="Back to sub-index"></A></CENTER><BR><BR><A NAME="', [handle],'"><HR SIZE=5></A><H1>Simulation Handle: ', [handle], '</H1>']);
2207     fprintf(fid, ['\n<BR>', '<CENTER><TABLE BORDER=BOX CELLPADDING=10 CELLSPACING=3 BACKGROUND="../../scbg.gif"><TR><TD>']);
2208     fprintf(fid, ['\n<H2>Main</H2>']);
2209     
2210     if (strcmp(getenv('OS'), 'Linux')), 
2211       fprintf(fid, ['<BR>AART - ', [get_month], ' ', [get_year], ' - Version ', [get_version], ' - ', [getenv('OS')]]);
2212       fprintf(fid, ['\n<BR><U>Time</U>: ', [get_date]]); 
2213       fprintf(fid, ['\n<BR><U>Run on machine:</U> ', [get_host], '<BR><U>Domain:</U> ', [get_domain], '<BR><U>Image width:</U> ', num2str(image_width)]);
2214     end
2215     
2216     fprintf(fid, ['\n<BR><U>Description:</U> ', [description]], '</TD>');
2217     fprintf(fid, ['\n<TD><H2>General</H2>']);
2218     fprintf(fid, ['\n<BR><U>Objective Function:</U> ', objective_function]);
2219     fprintf(fid, ['\n<BR><U>Data type identifier:</U> ', num2str(load_data)]);    
2220     fprintf(fid, ['\n<BR><U>Iterations:</U> ', num2str(n_iterations)]);
2221     fprintf(fid, ['\n<BR><U>Images:</U> ', num2str(n_images)]);
2222     fprintf(fid, ['\n<BR><U>Sets:</U> ', num2str(n_sets)]);
2223     fprintf(fid, ['\n<BR><U>Corrective Offset (boolean):</U> ', num2str(apply_intensity_offset), '</TD></TR><TR><TD>']);
2224     
2225     fprintf(fid, ['\n<BR><BR><H2>Smoothing</H2>']);
2226     fprintf(fid, ['\n<BR><U>Smoothing window:</U> ', num2str(window)]);
2227     fprintf(fid, ['\n<BR><U>Gaussian smoothing (boolean):</U> ', num2str(gaussian_smooth_enabled)]);
2228     fprintf(fid, ['\n<BR><U>Average smoothing (boolean):</U> ', num2str(average_smooth_enabled)]);
2229     
2230     fprintf(fid, ['\n<BR><BR><H2>Objective Function-Specific</H2>']);
2231     fprintf(fid, ['\n<BR><U>Precision Required (All):</U> ', num2str(precision_required)]);
2232     fprintf(fid, ['\n<BR><U>Number of bins (MI, NMI):</U> ', num2str(number_of_bins)]);
2233     fprintf(fid, ['\n<BR><U>Number of model modes:</U> ', num2str(n_modes)]);
2234     fprintf(fid, ['\n<BR><U>Variation Kept (PCA):</U> ', num2str(variation_kept)]);
2235     fprintf(fid, ['\n<BR><U>Weighting normalisation method:</U> ', weighting_normalisation_method]);
2236     fprintf(fid, ['\n<BR><U>Contant weighting value:</U> ', num2str(shape_weight)]);
2237     fprintf(fid, ['\n<BR><U>PDF type:</U> ', kernel]);
2238     fprintf(fid, ['\n<BR><U>Wavelet filter:</U> ', filter]);
2239     fprintf(fid, ['\n<BR><U>Compression level:</U> ', num2str(filter_level)]);
2240     fprintf(fid, ['\n<BR><U>Model evaluation method:</U> ',  num2str(model_evaluation_method)]);
2241     fprintf(fid, ['\n<BR><U>Specificity iterations:</U> ', num2str(spec_iters)]);
2242     fprintf(fid, ['\n<BR><U>Generalisability iterations:</U> ', num2str(gen_iters), '</TD><TD>']);
2243     
2244     fprintf(fid, ['\n<H2>Transformation</H2>']);
2245     fprintf(fid, ['\n<BR><U>Evaluation cycle:</U> ', num2str(cycle)]);  
2246     fprintf(fid, ['\n<BR><U>CPS Spline type:</U> ', spline_type]);
2247     fprintf(fid, ['\n<BR><U>Knot-point placement method:</U> ', placement_type]);
2248     fprintf(fid, ['\n<BR><U>Number of knot-points:</U> ', num2str(n_points)]);
2249     fprintf(fid, ['\n<BR><U>Automatic precision (boolean):</U> ', num2str(dynamic_precision)]);
2250     fprintf(fid, ['\n<BR><U>Initialise near target (boolean):</U> ', num2str(initialise_warps_close_to_target)]);
2251     fprintf(fid, ['\n<BR><U>Offset extent:</U> ', num2str(offset_extent)]);
2252     fprintf(fid, ['\n<BR><U>Perturbation method:</U> ', [perturbation_method]]);
2253     fprintf(fid, ['\n<BR><U>Force reference (boolean):</U> ', num2str(force_reference)]);
2254     fprintf(fid, ['\n<BR><U>Reference type:</U> ', num2str(force_first_reference)]);
2255     fprintf(fid, ['\n<BR><U>Distance type:</U> ', num2str(distance_type)]);    
2256     fprintf(fid, ['\n<BR><U>Retain peak (boolean):</U> ', num2str(retain_original_peak)]);    
2257     fprintf(fid, ['\n<BR><U>Peak type:</U> ', [peak_type]]);
2258     fprintf(fid, ['\n<BR><U>Stuff points (boolean):</U> ', num2str(add_points)]);    
2259     fprintf(fid, ['\n<BR><U>Point stuffing cycle:</U> ', num2str(add_points_cycle)]);  
2260     
2261     fprintf(fid, ['\n<BR><BR><H2>Data</H2>']);    
2262     fprintf(fid, ['\n<BR><U>Base height variation:</U> ', num2str(bump_height)]);
2263     fprintf(fid, ['\n<BR><U>Height variation:</U> ', num2str(bump_height_variation)]);
2264     fprintf(fid, ['\n<BR><U>Base width variation:</U> ', num2str(bump_width)]);
2265     fprintf(fid, ['\n<BR><U>Width variation:</U> ', num2str(bump_width_variation)]);    
2266     fprintf(fid, ['\n<BR><U>Position Freedom:</U> ', num2str(bump_position_freedom)]);
2267     fprintf(fid, ['\n<BR><U>Smoothness:</U> ', num2str(smoothness_factor)]);
2268     fprintf(fid, ['\n</TD></TR>']);
2269     
2270     fprintf(fid, '\n<TR><TD><H2>Image Preview 1</H2><BR><A HREF="');
2271     fprintf(fid, [[handle],'-1.jpg"><IMG HEIGHT=200 WIDTH=300 BORDER=0 SRC="']);
2272     fprintf(fid, [[handle],'-1.jpg"></A></TD><TD><H2>Image Preview 2</H2><BR><A HREF="']);
2273     fprintf(fid, [[handle],'-2.jpg"><IMG HEIGHT=200 WIDTH=300 BORDER=0 SRC="']);
2274     fprintf(fid, [[handle], '-2.jpg"></A></TD></TR>']);
2275     fprintf(fid, '\n<TR><TD><H2>Image Preview 3</H2><BR><A HREF="');
2276     fprintf(fid, [[handle],'-3.jpg"><IMG HEIGHT=200 WIDTH=300 BORDER=0 SRC="']);
2277     fprintf(fid, [[handle],'-3.jpg"></A></TD><TD><H2>Image Preview 4</H2><BR><A HREF="']);
2278     fprintf(fid, [[handle],'-4.jpg"><IMG HEIGHT=200 WIDTH=300 BORDER=0 SRC="']);
2279     fprintf(fid, [[handle], '-4.jpg"></A></TD></TR>']);    
2280     fprintf(fid, '\n<TR><TD><A HREF="');
2281     fprintf(fid, [[handle],'-1.avi">Video #1</A></TD><TD><A HREF="']);
2282     fprintf(fid, [[handle],'-2.avi">Video #2</A></TD></TR>']); 
2283     fprintf(fid, '\n<TR><TD><A HREF="');
2284     fprintf(fid, [[handle],'.mat">Input Data</A></TD><TD><A HREF="']);
2285     fprintf(fid, [[handle],'.htm">Statistics</A></TD></TR>']);     
2286     fprintf(fid, '\n</TABLE></CENTER><BR><BR>');
2287     fclose(fid);
2288     
2289       % save in index file
2290 
2291     fid = fopen('index.htm','a');
2292     if (add_headers == 1),
2293       add_html_headers(fid);
2294       add_table_index(fid);
2295     end
2296     if (strcmp(getenv('OS'), 'Linux')),
2297       fprintf(fid, ['\n<P><CENTER><TABLE WIDTH=100%% BORDER=BOX CELLPADDING=10 CELLSPACING=3 BACKGROUND="../../scbg.gif"><TD ALIGN=CENTER WIDTH=33%%><A HREF="aartlog.htm#', [handle], '">', [handle], '</A></TD><TD ALIGN=CENTER WIDTH=33%%>', [get_date], '</TD><TD ALIGN=CENTER WIDTH=33%%>']);
2298       fprintf(fid, ['\n', [description], '</P></TD></TABLE></CENTER>']);
2299     else
2300       fprintf(fid, ['\n<P><CENTER><TABLE WIDTH=100%% BORDER=BOX CELLPADDING=10 CELLSPACING=3 BACKGROUND="../../scbg.gif"><TD ALIGN=CENTER WIDTH=33%%><A HREF="aartlog.htm#', [handle], '">', [handle], '</A> ', '</TD><TD ALIGN=CENTER WIDTH=33%%>']);
2301       fprintf(fid, ['\n', [description], '</P></TD></TABLE></CENTER>']);
2302     end
2303     fclose(fid);
2304 end
2305 
2306 % a=figure('Name','test');
2307 % b=figure(a);
2308 % hold on;
2309 % plot([-1,2,3]);
2310 % hold off;
2311 % saveas(b,[[handle],'-', num2str(figure_handle_number)], 'jpg');
2312 % figure_handle_number = figure_handle_number + 1;
2313 
2314 
2315 %% END OF STATISTICS                                  %%
2316 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2317 
2318 
2319 if (save_movie == 1),
2320   if (strcmp(progress_indicator_type,'Progress Bar')),
2321            h = progressbar( h, 0, 'Saving Video');
2322   end  
2323   movie(M);
2324   movie2avi(M, movie_name, 'FPS', frames_per_second);
2325   if (called_from_gui == 1),
2326       % send this to the GUI status bar
2327       status = [[status];['(**) Video saved      '];['                      ']];
2328   else
2329       % indicate to user that a video has been save
2330         disp(' ');
2331         disp([movie_name, ' saved']);
2332           % process the movie and save it
2333   end
2334 end
2335 
2336 if (strcmp(progress_indicator_type,'Progress Bar')),
2337    progressbar( h,-1 );
2338       % destroy progress bar
2339 end
2340 
2341 if (error_found == 0),
2342               % if the error flag is not set
2343     if (called_from_gui == 1),
2344       status = [[status];['Registration Completed'];
2345              ['                      '];       
2346              ['Status: OK            ']];
2347          % send message
2348     else
2349       status = 'Status: OK'; 
2350          % indicate that everything was okay
2351     end
2352 elseif (error_found == 1),
2353     if (called_from_gui == 1),
2354       status = [[status];['Registration Completed'];
2355              ['                      '];       
2356              ['Status: Error         '];
2357              ['                      '];
2358              ['Operation Aborted     ']];
2359          % send message about error
2360     else
2361       status = 'Status: Operation Aborted'; 
2362          % indicate that something had gone wrong
2363     end    
2364 else
2365     if (called_from_gui == 1),
2366       status = [[status];['Registration Completed'];
2367              ['                      '];       
2368              ['Status: Error         '];
2369              ['                      '];
2370              ['Exit code unknown     ']];
2371          % send message about error
2372     else
2373       status = 'Status: Error'; 
2374          % indicate that something had gone wrong
2375     end
2376 end    
2377 
2378 if (exit_at_end == 1),
2379     exit;
2380 end  
2381 
2382 if (close_at_end == 1),
2383     close;
2384 end

Generated on Fri 14-May-2004 10:05:30 by m2html © 2003