diff --git a/3rdParty/mcmcstat/%mcmcrun_compile.m b/3rdParty/mcmcstat/%mcmcrun_compile.m index ca98dfa72..477f7867b 100644 --- a/3rdParty/mcmcstat/%mcmcrun_compile.m +++ b/3rdParty/mcmcstat/%mcmcrun_compile.m @@ -502,7 +502,7 @@ rej=0; reju=0; ii=1; rejl = 0; %% setup waitbar -if (wbarupd && display); triggerEvent(coderEnums.eventTypes.Progress, 'init', 0); end +if (wbarupd && display); triggerEvent(coderEnums.eventTypes.Progress, 'Bayes', 0); end % covariance update uses these to store previous values covchain = []; meanchain = []; wsum = initqcovn; lasti = 0; @@ -914,7 +914,7 @@ end end -triggerEvent(coderEnums.eventTypes.Progress, 'end', 1); +triggerEvent(coderEnums.eventTypes.Progress, 'Bayes', 1); diff --git a/3rdParty/mcmcstat/mcmcrun.m b/3rdParty/mcmcstat/mcmcrun.m index e89fac95c..bb6325975 100644 --- a/3rdParty/mcmcstat/mcmcrun.m +++ b/3rdParty/mcmcstat/mcmcrun.m @@ -449,7 +449,7 @@ rej=0; reju=0; ii=1; rejl = 0; %% setup waitbar -if wbarupd; triggerEvent(coderEnums.eventTypes.Progress, 'init', 0); end +if wbarupd; triggerEvent(coderEnums.eventTypes.Progress, 'Bayes', 0); end % covariance update uses these to store previous values covchain = []; meanchain = []; wsum = initqcovn; lasti = 0; @@ -841,7 +841,7 @@ end end -triggerEvent(coderEnums.eventTypes.Progress, 'end', 1); +triggerEvent(coderEnums.eventTypes.Progress, 'Bayes', 1); diff --git a/3rdParty/mcmcstat/mcmcrun_compile.m b/3rdParty/mcmcstat/mcmcrun_compile.m index 51e4f361d..79d2504c1 100644 --- a/3rdParty/mcmcstat/mcmcrun_compile.m +++ b/3rdParty/mcmcstat/mcmcrun_compile.m @@ -479,7 +479,7 @@ rej=0; reju=0; ii=1; rejl = 0; %% setup waitbar -if wbarupd; triggerEvent(coderEnums.eventTypes.Progress, 'init', 0); end +if wbarupd; triggerEvent(coderEnums.eventTypes.Progress, 'Bayes', 0); end % covariance update uses these to store previous values covchain = []; meanchain = []; wsum = initqcovn; lasti = 0; @@ -887,7 +887,7 @@ end end -triggerEvent(coderEnums.eventTypes.Progress, 'end', 1); +triggerEvent(coderEnums.eventTypes.Progress, 'Bayes', 1); diff --git a/3rdParty/mcmcstat/mcmcrun_compile_scaled.m b/3rdParty/mcmcstat/mcmcrun_compile_scaled.m index 65d648bf1..b1394bb6b 100644 --- a/3rdParty/mcmcstat/mcmcrun_compile_scaled.m +++ b/3rdParty/mcmcstat/mcmcrun_compile_scaled.m @@ -479,7 +479,7 @@ rej=0; reju=0; ii=1; rejl = 0; %% setup waitbar -if wbarupd; triggerEvent(coderEnums.eventTypes.Progress, 'init', 0); end +if wbarupd; triggerEvent(coderEnums.eventTypes.Progress, 'Bayes', 0); end % covariance update uses these to store previous values covchain = []; meanchain = []; wsum = initqcovn; lasti = 0; @@ -887,7 +887,7 @@ end end -triggerEvent(coderEnums.eventTypes.Progress, 'end', 1); +triggerEvent(coderEnums.eventTypes.Progress, 'Bayes', 1); diff --git a/API/RAT.m b/API/RAT.m index fdfc47bb0..f5ed61080 100644 --- a/API/RAT.m +++ b/API/RAT.m @@ -9,19 +9,20 @@ end % Call the main RAT routine... - +display = ~strcmpi(controls.display, displayOptions.Off.value); +textProgressBar(0, 0, display); % If display is not silent print a line confirming RAT is starting -if ~strcmpi(controls.display, displayOptions.Off.value) +if display fprintf('Starting RAT ________________________________________________________________________________________________\n\n'); end tic [problemStruct,result,bayesResults] = RATMain_mex(problemStruct,problemCells,problemLimits,controls,priors); -if ~strcmpi(controls.display, displayOptions.Off.value) +if display toc end - +textProgressBar(0, 0, true); if any(strcmpi(controls.procedure, {procedures.NS.value, procedures.Dream.value})) result = mergeStructs(result, bayesResults); end diff --git a/API/RATMain.m b/API/RATMain.m index 136f199ae..df119af56 100644 --- a/API/RATMain.m +++ b/API/RATMain.m @@ -1,5 +1,5 @@ function [problemStruct,result,bayesResults] = RATMain(problemStruct,problemCells,problemLimits,controls,priors) -coderEnums.initialize() +coderEnums.initialise() if strcmpi(problemStruct.TF, coderEnums.calculationTypes.Domains) domains = true; diff --git a/API/controlsClass.m b/API/controlsClass.m index c81ff385b..48e3bbe0b 100644 --- a/API/controlsClass.m +++ b/API/controlsClass.m @@ -1,4 +1,4 @@ -classdef controlsClass < matlab.mixin.CustomDisplay +classdef controlsClass < handle & matlab.mixin.CustomDisplay properties % Parallelisation Option (Default: parallelOptions.Single) @@ -41,7 +41,7 @@ % Target stopping tolerance for Nested Sampler (Default: 0.1) nsTolerance = 0.1 - % Total number of samples for DREAM (Default: 50000) + % Total number of samples for DREAM (Default: 20000) nSamples = 20000; % Number of MCMC chains (Default: 10) nChains = 10 @@ -53,32 +53,37 @@ adaptPCR = true; end + + properties (SetAccess = private, Hidden = true) + IPCFilePath = '' + end + %------------------------- Set and Get ------------------------------ methods - function obj = set.parallel(obj,val) + function set.parallel(obj,val) message = sprintf('parallel must be a parallelOptions enum or one of the following strings (%s)', ... strjoin(parallelOptions.values(), ', ')); obj.parallel = validateOption(val, 'parallelOptions', message).value; end - function obj = set.procedure(obj,val) + function set.procedure(obj,val) message = sprintf('procedure must be a procedures enum or one of the following strings (%s)', ... strjoin(procedures.values(), ', ')); obj.procedure = validateOption(val, 'procedures', message).value; end - function obj = set.calcSldDuringFit(obj,val) + function set.calcSldDuringFit(obj,val) validateLogical(val, 'calcSldDuringFit must be logical ''true'' or ''false'''); obj.calcSldDuringFit = val; end - function obj = set.display(obj,val) + function set.display(obj,val) message = sprintf('display must be a displayOptions enum or one of the following strings (%s)', ... strjoin(displayOptions.values(), ', ')); obj.display = validateOption(val, 'displayOptions', message).value; end - function obj = set.updatePlotFreq(obj, val) + function set.updatePlotFreq(obj, val) validateNumber(val, 'updatePlotFreq must be a number'); if val < 1 throw(exceptions.invalidValue('updatePlotFreq must be greater or equal to 1')); @@ -86,7 +91,7 @@ obj.updatePlotFreq = val; end - function obj = set.resampleParams(obj,val) + function set.resampleParams(obj,val) if length(val) ~= 2 throw(exceptions.invalidValue('resampleParams must have length of 2')); end @@ -103,24 +108,24 @@ end % Simplex control methods - function obj = set.xTolerance(obj, val) + function set.xTolerance(obj, val) obj.xTolerance = validateNumber(val, 'xTolerance must be a number'); end - function obj = set.funcTolerance(obj, val) + function set.funcTolerance(obj, val) obj.funcTolerance = validateNumber(val, 'funcTolerance must be a number'); end - function obj = set.maxFuncEvals(obj, val) + function set.maxFuncEvals(obj, val) obj.maxFuncEvals = validateNumber(val, 'maxFuncEvals must be a number'); end - function obj = set.maxIterations(obj, val) + function set.maxIterations(obj, val) obj.maxIterations = validateNumber(val, 'maxIterations must be a number'); end % DE controls methods - function obj = set.populationSize(obj, val) + function set.populationSize(obj, val) validateNumber(val, 'populationSize must be a number'); if val < 1 throw(exceptions.invalidValue('populationSize must be greater or equal to 1')); @@ -128,11 +133,11 @@ obj.populationSize = val; end - function obj = set.fWeight(obj,val) + function set.fWeight(obj,val) obj.fWeight = validateNumber(val,'fWeight must be a number'); end - function obj = set.crossoverProbability(obj,val) + function set.crossoverProbability(obj,val) validateNumber(val, 'crossoverProbability must be a number'); if (val < 0 || val > 1) throw(exceptions.invalidValue('crossoverProbability must be between 0 and 1')); @@ -140,14 +145,14 @@ obj.crossoverProbability = val; end - function obj = set.strategy(obj,val) + function set.strategy(obj,val) message = sprintf('strategy must be a searchStrategy enum or one of the following integers (%s)', ... strjoin(string(searchStrategy.values()), ', ')); obj.strategy = validateOption(val, 'searchStrategy', message).value; end - function obj = set.targetValue(obj,val) + function set.targetValue(obj,val) validateNumber(val, 'targetValue must be a number'); if val < 1 throw(exceptions.invalidValue('targetValue must be greater or equal to 1')); @@ -155,7 +160,7 @@ obj.targetValue = val; end - function obj = set.numGenerations(obj, val) + function set.numGenerations(obj, val) validateNumber(val, 'numGenerations value must be a number'); if val < 1 throw(exceptions.invalidValue('numGenerations must be greater or equal to 1')); @@ -164,7 +169,7 @@ end % NS control methods - function obj = set.nLive(obj, val) + function set.nLive(obj, val) validateNumber(val, 'nLive must be a number'); if val < 1 throw(exceptions.invalidValue('nLive must be greater or equal to 1')); @@ -172,7 +177,7 @@ obj.nLive = val; end - function obj = set.nMCMC(obj, val) + function set.nMCMC(obj, val) validateNumber(val, 'nMCMC must be a number'); if val < 0 throw(exceptions.invalidValue('nMCMC must be greater or equal than 0')); @@ -180,7 +185,7 @@ obj.nMCMC = val; end - function obj = set.propScale(obj, val) + function set.propScale(obj, val) validateNumber(val, 'propScale must be a number'); if (val < 0 || val > 1) throw(exceptions.invalidValue('propScale must be between 0 and 1')); @@ -188,7 +193,7 @@ obj.propScale = val; end - function obj = set.nsTolerance(obj,val) + function set.nsTolerance(obj,val) validateNumber(val, 'nsTolerance must be a number '); if val < 0 throw(exceptions.invalidValue('nsTolerance must be greater or equal to 0')); @@ -197,7 +202,7 @@ end % DREAM methods - function obj = set.nSamples(obj,val) + function set.nSamples(obj,val) validateNumber(val, 'nSample must be a number '); if val < 0 throw(exceptions.invalidValue('nSample must be greater or equal to 0')); @@ -205,7 +210,7 @@ obj.nSamples = val; end - function obj = set.nChains(obj,val) + function set.nChains(obj,val) validateNumber(val, 'nChains must be a number '); if (~(round(val) == val) || val <= 0 || isnan(val) || isinf(val)) throw(exceptions.invalidValue('nChains must be a finite integer greater than 0')); @@ -213,7 +218,7 @@ obj.nChains = val; end - function obj = set.jumpProbability(obj,val) + function set.jumpProbability(obj,val) validateNumber(val, 'jumpProbability must be a number'); if (val < 0 || val > 1) throw(exceptions.invalidValue('JumpProbability must be a fraction between 0 and 1')); @@ -221,7 +226,7 @@ obj.jumpProbability = val; end - function obj = set.pUnitGamma(obj,val) + function set.pUnitGamma(obj,val) validateNumber(val, 'pUnitGamma must be a number'); if (val < 0 || val > 1) throw(exceptions.invalidValue('pUnitGamma must be a fraction between 0 and 1')); @@ -229,13 +234,13 @@ obj.pUnitGamma = val; end - function obj = set.boundHandling(obj,val) + function set.boundHandling(obj,val) message = sprintf('boundHandling must be a boundHandlingOptions enum or one of the following strings (%s)', ... strjoin(boundHandlingOptions.values(), ', ')); obj.boundHandling = validateOption(val, 'boundHandlingOptions', message).value; end - function obj = set.adaptPCR(obj,val) + function set.adaptPCR(obj,val) validateLogical(val, 'adaptPCR must be logical ''true'' or ''false'''); obj.adaptPCR = val; end @@ -299,6 +304,38 @@ end end + + function obj = initialiseIPC(obj) + % Method setup the inter-process communication file. + % + % USAGE: + % obj.initialiseIPC() + obj.IPCFilePath = tempname(); + fileID = fopen(obj.IPCFilePath, 'w'); + fwrite(fileID, false, 'uchar'); + fclose(fileID); + end + + function path = getIPCFilePath(obj) + % Returns the path of the IPC file. + % + % USAGE: + % path = obj.getIPCFilePath() + path = obj.IPCFilePath; + end + + function obj = sendStopEvent(obj) + % Sends the stop event via IPC file. + % + % USAGE: + % obj.sendStopEvent() + if isempty(obj.IPCFilePath) + return + end + fileID = fopen(obj.IPCFilePath, 'w'); + fwrite(fileID, true, 'uchar'); + fclose(fileID); + end end %------------------------- Display Methods -------------------------- diff --git a/API/enums/coderEnums.m b/API/enums/coderEnums.m index 6fe013ad9..daaff013d 100644 --- a/API/enums/coderEnums.m +++ b/API/enums/coderEnums.m @@ -17,7 +17,7 @@ supportedLanguages = supportedLanguages.toStruct() end methods (Static) - function initialize() + function initialise() % initializes enum struct field as a coder const like so % coder.const(coderEnums.procedures.Dream); props = properties(coderEnums); diff --git a/API/events/isRATStopped.m b/API/events/isRATStopped.m new file mode 100644 index 000000000..338668110 --- /dev/null +++ b/API/events/isRATStopped.m @@ -0,0 +1,15 @@ +function state = isRATStopped(IPCFilePath) + % Checks if the stop event was set via the IPC file. The expected input + % is the path to the inter-process communication file + % + % stopped = isRATStopped(filePath); + if isempty(IPCFilePath) + state = false; + return + end + + fileID = fopen(IPCFilePath); + state = logical(fread(fileID, 1, '*uchar')); + fclose(fileID); +end + diff --git a/API/parseClassToStructs.m b/API/parseClassToStructs.m index 75e2844ce..fe73c0eb7 100644 --- a/API/parseClassToStructs.m +++ b/API/parseClassToStructs.m @@ -434,6 +434,7 @@ end controls.checks = checks; +controls.IPCFilePath = inputControls.getIPCFilePath(); %% Finally, populate the fitParams, otherParams, fitLimits, otherLimits arrays [problemStruct,~] = packParams(problemStruct,problemCells,problemLimits,controls.checks); diff --git a/compile/fullCompile/makeCompileArgsFull.m b/compile/fullCompile/makeCompileArgsFull.m index c78d657c4..2b269c567 100644 --- a/compile/fullCompile/makeCompileArgsFull.m +++ b/compile/fullCompile/makeCompileArgsFull.m @@ -134,6 +134,7 @@ ARGS_1_4_checks.fitResolutionParam = coder.typeof(0,[1 maxArraySize],[0 1]); ARGS_1_4_checks.fitDomainRatio = coder.typeof(0,[1 maxArraySize],[0 1]); ARGS_1_4.checks = coder.typeof(ARGS_1_4_checks); +ARGS_1_4.IPCFilePath = coder.typeof('X',[1 maxArraySize],[0 1]); ARGS{1}{4} = coder.typeof(ARGS_1_4); ARGS_1_5 = struct; ARG_20 = cell([1 4]); diff --git a/compile/fullCompile/ratMainCodeGen.m b/compile/fullCompile/ratMainCodeGen.m index 80d08bbc7..197a86dcf 100644 --- a/compile/fullCompile/ratMainCodeGen.m +++ b/compile/fullCompile/ratMainCodeGen.m @@ -5,9 +5,8 @@ % See also CODER, CODER.CONFIG, CODER.TYPEOF, CODEGEN. %% Deal with globals -global verbose DEBUG +global DEBUG DEBUG = 0; -verbose = 1; %% Create configuration object of class 'coder.MexCodeConfig'. cfg = coder.config('lib'); diff --git a/compile/fullCompile/ratMainCompileScript.m b/compile/fullCompile/ratMainCompileScript.m index 37c7bbba2..bc0bbe573 100644 --- a/compile/fullCompile/ratMainCompileScript.m +++ b/compile/fullCompile/ratMainCompileScript.m @@ -5,9 +5,8 @@ % See also CODER, CODER.CONFIG, CODER.TYPEOF, CODEGEN. %% Deal with globals -global verbose DEBUG +global DEBUG DEBUG = 0; -verbose = 1; %% Create configuration object of class 'coder.MexCodeConfig'. cfg = coder.config('mex'); diff --git a/compile/reflectivityCalculation/makeCompileArgs.m b/compile/reflectivityCalculation/makeCompileArgs.m index 080e24488..ef58e63b6 100644 --- a/compile/reflectivityCalculation/makeCompileArgs.m +++ b/compile/reflectivityCalculation/makeCompileArgs.m @@ -134,6 +134,7 @@ ARGS_1_4_checks.fitResolutionParam = coder.typeof(0,[1 maxArraySize],[0 1]); ARGS_1_4_checks.fitDomainRatio = coder.typeof(0,[1 maxArraySize],[0 1]); ARGS_1_4.checks = coder.typeof(ARGS_1_4_checks); +ARGS_1_4.IPCFilePath = coder.typeof('X',[1 maxArraySize],[0 1]); ARGS{1}{4} = coder.typeof(ARGS_1_4); end \ No newline at end of file diff --git a/compile/reflectivityCalculation/setCompilePaths.m b/compile/reflectivityCalculation/setCompilePaths.m deleted file mode 100644 index b9535088d..000000000 --- a/compile/reflectivityCalculation/setCompilePaths.m +++ /dev/null @@ -1,54 +0,0 @@ -function setCompilePaths() - -% This function sets the paths for compiling, depending on whether a mex -% file of source code is being generated. - -% The difference is in the handling of Matlab custom models. Currently for -% mex, these are run in the base Matlab workspace (the fastest option). -% This doesn't exist if source code is being generated, and so code -% generation will fail. - -% To deal with this, we have two directories with alternate functions of -% the same filenames, and we can switch between them by manipulating the -% Matlab path between the two compile cases. Currently, the 'source' -% functions just output zeros, so building the toolbox outside Matlab will give -% nonsense results for custom models. However, soon the source version will -% launch an external Matlab engine to deal with custom layers, although that -% is not fully implemented yet. The C++ option for user custom models will -% work for both cases. - -% To choose between the two options, we select between the following -% directories.... - -% /targetFunctions/common/loopMatlabCustomLayers/mexCompile -% /targetFunctions/common/loopMatlabCustomLayers/sourceCompile - -% First get the RAT root directory -% root = getappdata(0,'root'); - -% Get a list of all the paths currently on paths list... -% pathCell = regexp(path, pathsep, 'split'); - -% Choose the relevant directory based on the input... -% switch which -% case 'mex' -% addDir = fullfile(root,'targetFunctions','common','loopMatlabCustomLayers','mexCompile'); -% rmDir = fullfile(root,'targetFunctions','common','loopMatlabCustomLayers','sourceCompile'); -% otherwise -% addDir = fullfile(root,'targetFunctions','common','loopMatlabCustomLayers','sourceCompile'); -% rmDir = fullfile(root,'targetFunctions','common','loopMatlabCustomLayers','mexCompile'); -% end - -% Add the 'add dir' if it is not currently on the Matlab path list.. -% if ~any(strcmpi(addDir,pathCell)) -% addpath(addDir); -% fprintf('Added directory %s to path \n',addDir); -% end - -% Remove the 'revove dir' if it is currently on the Matlab path list.. -% if any(strcmpi(rmDir,pathCell)) -% rmpath(rmDir); -% fprintf('Removed directory %s from path \n',rmDir); -% end - -end \ No newline at end of file diff --git a/minimisers/DE/deopt.m b/minimisers/DE/deopt.m index 0685d611a..6f77f6dc8 100644 --- a/minimisers/DE/deopt.m +++ b/minimisers/DE/deopt.m @@ -88,7 +88,7 @@ coder.varsize('FVr_bestmem',[1 Inf],[0 1]); coder.varsize('FVr_bestmemit',[1 Inf],[0 1]); -stopflag = 0; +% stopflag = 0; I_best_index = 1; I_NP = S_struct.I_NP; @@ -120,7 +120,7 @@ I_refresh = floor(I_refresh); %-----Initialize population and some arrays------------------------------- -FM_pop = zeros(I_NP,I_D); %initialize FM_pop to gain speed +FM_pop = zeros(I_NP,I_D); %initialise FM_pop to gain speed %----FM_pop is a matrix of size I_NPx(I_D+1). It will be initialized------ %----with random values between the min and max values of the------------- @@ -160,12 +160,12 @@ %------static through one iteration. FM_pop is the newly-------------- %------emerging population.---------------------------------------- -FM_pm1 = zeros(I_NP,I_D); % initialize population matrix 1 -FM_pm2 = zeros(I_NP,I_D); % initialize population matrix 2 -FM_pm3 = zeros(I_NP,I_D); % initialize population matrix 3 -FM_pm4 = zeros(I_NP,I_D); % initialize population matrix 4 -FM_pm5 = zeros(I_NP,I_D); % initialize population matrix 5 -FM_bm = zeros(I_NP,I_D); % initialize FVr_bestmember matrix +FM_pm1 = zeros(I_NP,I_D); % initialise population matrix 1 +FM_pm2 = zeros(I_NP,I_D); % initialise population matrix 2 +FM_pm3 = zeros(I_NP,I_D); % initialise population matrix 3 +FM_pm4 = zeros(I_NP,I_D); % initialise population matrix 4 +FM_pm5 = zeros(I_NP,I_D); % initialise population matrix 5 +FM_bm = zeros(I_NP,I_D); % initialise FVr_bestmember matrix FM_ui = zeros(I_NP,I_D); % intermediate population of perturbed vectors FM_mui = zeros(I_NP,I_D); % mask for intermediate population FM_mpo = zeros(I_NP,I_D); % mask for old population @@ -187,7 +187,7 @@ % %FM_pop = zeros(I_NP,2); I_iter = 1; -while ((I_iter < I_itermax) & (S_bestval.FVr_oa(1) > F_VTR)) +while ((I_iter < I_itermax) && (S_bestval.FVr_oa(1) > F_VTR)) FM_popold = FM_pop; % save the old population %S_struct.FM_pop = FM_pop; S_struct.FVr_bestmem = FVr_bestmem; @@ -316,7 +316,7 @@ % if (I_plotting == 1) % PlotIt(FVr_bestmem,problem); % end - stopflag = 0; +% stopflag = 0; end @@ -325,19 +325,18 @@ [~,result] = fname(FVr_bestmem,problem,problemCells,problemLimits,controls); triggerEvent(coderEnums.eventTypes.Plot, result, problem, problemCells); end - - end - if stopflag == 0 - I_iter = I_iter + 1; - else - I_iter = I_itermax + 1; + + if isRATStopped(controls.IPCFilePath) + if ~strcmpi(controls.display, coderEnums.displayOptions.Off) + fprintf('Optimisation terminated by user\n'); + end + break; + end end +% if stopflag == 0 + I_iter = I_iter + 1; +% else +% I_iter = I_itermax + 1; +% end end %---end while ((I_iter < I_itermax) ... - - - -% problemStruct.fitParams = x; -% problemStruct = unpackParams(problemStruct,controls); -% res = reflectivityCalculation(problemStruct,problemCells,problemLimits,controls); - - +end diff --git a/minimisers/DREAM/functions/GL.m b/minimisers/DREAM/functions/GL.m index 2baeb6326..9b4ec4746 100755 --- a/minimisers/DREAM/functions/GL.m +++ b/minimisers/DREAM/functions/GL.m @@ -79,7 +79,7 @@ %SIMULATION: generate response variables (SimY) switch iflag case 'sim' - rand('seed',sum(100*clock)); %initialize random number generators + rand('seed',sum(100*clock)); %initialise random number generators %Generate N i.i.d. errors (a) from skew exponential power distribution, SEP(0,1,xi,beta) %Step 1 - Generate N random variates from gamma distribution with shape parameter 1/p and scale parameter 1 p = 2/(1+beta); diff --git a/minimisers/DREAM/functions/ratDREAM.m b/minimisers/DREAM/functions/ratDREAM.m index 46b5438ad..c486e86e5 100644 --- a/minimisers/DREAM/functions/ratDREAM.m +++ b/minimisers/DREAM/functions/ratDREAM.m @@ -140,7 +140,7 @@ Meas_info.Y = 0; % Initialize the main variables used in DREAM -[inDREAMPar,paramInfo,Meas_info,chain,output,log_L,Table_gamma,iloc,iteration,... +[DREAMPar,paramInfo,Meas_info,chain,output,log_L,Table_gamma,iloc,iteration,... gen] = setupDREAM(dreamVariables,paramInfo,Meas_info); % Check for setup errors @@ -151,8 +151,20 @@ % if stop; return; end % Create computing environment (depending whether multi-core is used) -[DREAMPar] = setDREAMParam(inDREAMPar); +if ~DREAMPar.parallel + % We use 1 CPU (processor) + DREAMPar.CPU = 1; +else + DREAMPar.CPU = 0; +end +% Now print to screen all the settings +controls = ratInputs.controls; +if ~strcmpi(controls.display, coderEnums.displayOptions.Off) + fprintf('------------------ Summary of the main settings used ------------------\n'); + disp(DREAMPar); + fprintf('-----------------------------------------------------------------------\n'); +end % Now check how the measurement sigma is arranged (estimated or defined) % % ----------------------------------------- @@ -168,8 +180,7 @@ [chain,output,X,fx,CR,pCR,lCR,delta_tot,log_L] = initializeDREAM(DREAMPar,paramInfo,Meas_info,chain,output,log_L,ratInputs); % Initialize waitbar. -triggerEvent(coderEnums.eventTypes.Progress, 'init', 0); -% h = waitbar(0,'Running DREAM - Please wait...'); +triggerEvent(coderEnums.eventTypes.Progress, 'DREAM', 0); totaccept = 0; tic; % Now start iteration ... @@ -262,6 +273,13 @@ iteration = iteration + 1; gen = 1; totaccept = 0; end + + if isRATStopped(controls.IPCFilePath) + if ~strcmpi(controls.display, coderEnums.displayOptions.Off) + fprintf('Optimisation terminated by user\n'); + end + break; + end end % ------------------------------------------------------------------------- @@ -279,6 +297,6 @@ output.iloc = iloc; % Close the waitbar -triggerEvent(coderEnums.eventTypes.Progress, 'end', 1); +triggerEvent(coderEnums.eventTypes.Progress, 'DREAM', 1); %close(h); - +end diff --git a/minimisers/DREAM/functions/removeOutlier.m b/minimisers/DREAM/functions/removeOutlier.m index 94aea68f4..1897c8ddd 100755 --- a/minimisers/DREAM/functions/removeOutlier.m +++ b/minimisers/DREAM/functions/removeOutlier.m @@ -36,7 +36,7 @@ % If at least one outlier chain has been found --> reset its state if (Nid > 0) - % Re-initialize ecah outlier chain to current state random other chain + % Re-initialise ecah outlier chain to current state random other chain chain_select = [1:DREAMPar.nChains]; chain_select(chain_id) = []; % Randomly permute these available chains r = randperm(DREAMPar.nChains - Nid); chain_select = chain_select(r); diff --git a/minimisers/DREAM/functions/setDREAMParam.m b/minimisers/DREAM/functions/setDREAMParam.m deleted file mode 100644 index d303f9386..000000000 --- a/minimisers/DREAM/functions/setDREAMParam.m +++ /dev/null @@ -1,53 +0,0 @@ -function [DREAMPar] = setDREAMParam(DREAMPar) -% Sets up sequential / parallel - -% global DREAM_dir EXAMPLE_dir; - -% Now create the function handle - -% Currently using a function handle for RAT - AVH -% if isa(Func_name,'function_handle') -% f_handle = Func_name; -% else -% f_handle = eval(['@(x)',char(Func_name),'(x)']); -% end - -% Now check if we want parallel execution of chains or not? -if ~DREAMPar.parallel - - % We use 1 CPU (processor) - DREAMPar.CPU = 1; -else - DREAMPar.CPU = 0;% Treat this now as a flag - 0 is parfor. currenPool.NumWorkers; - - - % If input/output writing is done we need directories for each worker - % if DREAMPar.IO - % - % % Go to directory with problem files - % cd(EXAMPLE_dir) - % - % % Create first part of copy expression - % a = strcat('copy "'); - % - % % Create the directories - % for ii = 1:min(DREAMPar.CPU,DREAMPar.nChains), - % - % % Create the directories - % mkdir(strcat(num2str(ii))); - % - % % And copy the files - % b = strcat(a,EXAMPLE_dir,'\*.*"',{' '},'"',EXAMPLE_dir,'\',strcat(num2str(ii)),'"'); dos(char(b)); - % - % end; - % - % cd(DREAM_dir); - % - % end; - -end - -% Now print to screen all the settings -disp('------------------ Summary of the main settings used ------------------'); -DREAMPar -disp('-----------------------------------------------------------------------'); diff --git a/minimisers/NS/drawMCMC.m b/minimisers/NS/drawMCMC.m index 13e1ec956..452aa423b 100644 --- a/minimisers/NS/drawMCMC.m +++ b/minimisers/NS/drawMCMC.m @@ -13,8 +13,8 @@ % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -global verbose; - +% global verbose; +controls = data{2}; logL = logLmin; mcmcfrac = 0.9; l2p = 0.5*log(2*pi); % useful constant @@ -24,7 +24,7 @@ Ndegs = 2; % degrees of freedom of Students't distribution -% initialize counters +% initialise counters acctot = 0; Ntimes = 1; @@ -183,7 +183,7 @@ end % print out acceptance ratio -if verbose +if ~strcmpi(controls.display, coderEnums.displayOptions.Off) fprintf('Acceptance ratio: %1.4f, \n\n', acctot/(Ntimes*nMCMC)); end diff --git a/minimisers/NS/nestedSampler.m b/minimisers/NS/nestedSampler.m index 6fb1ad299..c5952e028 100644 --- a/minimisers/NS/nestedSampler.m +++ b/minimisers/NS/nestedSampler.m @@ -46,13 +46,13 @@ % 'x', 4}; % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -global verbose; +% global verbose; global DEBUG; extraparvals = []; - -verbose = 1; +controls = data{2}; +% verbose = 1; DEBUG = 0; % get the number of parameters from the prior array @@ -70,7 +70,7 @@ % get the number of parameters from the prior array D = size(prior,1); -% initialize array of samples for posterior +% initialise array of samples for posterior nest_samples = zeros(1,D+1); coder.varsize('nest_samples',[1e5 50],[1 1]); @@ -142,7 +142,7 @@ VEs = zeros(D,1); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% initialize iteration counter +% initialise iteration counter j = 1; @@ -261,11 +261,16 @@ tol = logPlus(logZ, logLmax - (j/nLive)) - logZ; % display progress (optional) - if verbose + if ~strcmpi(controls.display, coderEnums.displayOptions.Off) fprintf('log(Z): %.5e, tol = %.5e, K = %d, iteration = %d, H = %.5e\n', ... logZ, tol, int32(K), int32(j), H); end - + if isRATStopped(controls.IPCFilePath) + if ~strcmpi(controls.display, coderEnums.displayOptions.Off) + fprintf('Optimisation terminated by user\n'); + end + break; + end % update counter j = j+1; end diff --git a/minimisers/NS/runNestedSampler.m b/minimisers/NS/runNestedSampler.m index c4876d865..2afe78e68 100644 --- a/minimisers/NS/runNestedSampler.m +++ b/minimisers/NS/runNestedSampler.m @@ -43,7 +43,7 @@ % chain = nest_samples(:,1:end-1); chain = postSamples(:,1:nParams); -bayesOutputs.bestParams = mean(chain); +bayesOutputs.bestParams = mean(chain, 1); bayesOutputs.chain = chain; bayesOutputs.fitNames = fitNames; bayesOutputs.s2chain = []; diff --git a/minimisers/simplex/fMinSearch.m b/minimisers/simplex/fMinSearch.m index a9e8e68ae..6f380a0e2 100644 --- a/minimisers/simplex/fMinSearch.m +++ b/minimisers/simplex/fMinSearch.m @@ -313,6 +313,10 @@ if rem(itercount, controls.updatePlotFreq) == 0 triggerEvent(coderEnums.eventTypes.Plot, result, problemStruct, problemCells); end +if isRATStopped(controls.IPCFilePath) + [x, fval, exitflag, output] = cleanUpInterrupt(v(:,1), fv(:,1), itercount, func_evals, prnt); + return +end % OutputFcn and PlotFcns call % if haveoutputfcn || haveplotfcn % [xOutputfcn, optimValues, stop] = callOutputAndPlotFcns(outputfcn,plotfcns,v(:,1),xOutputfcn,'iter',itercount, ... @@ -428,6 +432,10 @@ if rem(itercount, controls.updatePlotFreq) == 0 triggerEvent(coderEnums.eventTypes.Plot, result, problemStruct, problemCells); end + if isRATStopped(controls.IPCFilePath) + [x, fval, exitflag, output] = cleanUpInterrupt(v(:,1), fv(:,1), itercount, func_evals, prnt); + return + end % OutputFcn and PlotFcns call % if haveoutputfcn || haveplotfcn % [xOutputfcn, optimValues, stop] = callOutputAndPlotFcns(outputfcn,plotfcns,v(:,1),xOutputfcn,'iter',itercount, ... @@ -455,14 +463,14 @@ printMsg = prnt > 0; if buildOutputStruct || printMsg %msg = getString(message('MATLAB:optimfun:fminsearch:ExitingMaxFunctionEvals', sprintf('%f',fval))); - sprintf('Exiting: Max function evals reached'); + msg = sprintf('Exiting: Max function evals reached'); end exitflag = 0; elseif itercount >= maxiter printMsg = prnt > 0; if buildOutputStruct || printMsg %msg = getString(message('MATLAB:optimfun:fminsearch:ExitingMaxIterations', sprintf('%f',fval))); - sprintf('Exiting: Max iterations reached'); + msg = sprintf('Exiting: Max iterations reached'); end exitflag = 0; else @@ -484,7 +492,7 @@ if printMsg fprintf('\n%s\n', msg); end - +end %-------------------------------------------------------------------------- % function [xOutputfcn, optimValues, stop] = callOutputAndPlotFcns(outputfcn,plotfcns,x,xOutputfcn,state,iter,... % numf,how,f,varargin) @@ -526,22 +534,18 @@ % ----------------------------------- %-------------------------------------------------------------------------- -% function [x,FVAL,EXITFLAG,OUTPUT] = cleanUpInterrupt(xOutputfcn,optimValues) -% CLEANUPINTERRUPT updates or sets all the output arguments of FMINBND when the optimization -% is interrupted. - -% Call plot function driver to finalize the plot function figure window. If -% no plot functions have been specified or the plot function figure no -% longer exists, this call just returns. -% callAllOptimPlotFcns('cleanuponstopsignal'); - -% x = xOutputfcn; -% FVAL = optimValues.fval; -% EXITFLAG = -1; -% OUTPUT.iterations = optimValues.iteration; -% OUTPUT.funcCount = optimValues.funccount; -% OUTPUT.algorithm = 'Nelder-Mead simplex direct search'; -% OUTPUT.message = fprintf('Optimisation terminated by user'); %getString(message('MATLAB:optimfun:fminsearch:OptimizationTerminatedPrematurelyByUser')); +function [x, fval, exitflag, output] = cleanUpInterrupt(optX, optVal, iteration, funccount, display) + x = optX; + fval = optVal; + exitflag = -1; + output.iterations = iteration; + output.funcCount = funccount; + output.algorithm = 'Nelder-Mead simplex direct search'; + output.message = sprintf('Optimisation terminated by user'); + if display > 0 + fprintf('\n%s\n', output.message); + end +end %-------------------------------------------------------------------------- % function f = checkfun(x,userfcn,varargin) diff --git a/tests/domainsTFReflectivityCalculation/domainsCustomLayersInputs.mat b/tests/domainsTFReflectivityCalculation/domainsCustomLayersInputs.mat index 037040435..9c7ce793b 100644 Binary files a/tests/domainsTFReflectivityCalculation/domainsCustomLayersInputs.mat and b/tests/domainsTFReflectivityCalculation/domainsCustomLayersInputs.mat differ diff --git a/tests/domainsTFReflectivityCalculation/domainsCustomLayersOutputs.mat b/tests/domainsTFReflectivityCalculation/domainsCustomLayersOutputs.mat index 9f8c13d56..0f0c06fa9 100644 Binary files a/tests/domainsTFReflectivityCalculation/domainsCustomLayersOutputs.mat and b/tests/domainsTFReflectivityCalculation/domainsCustomLayersOutputs.mat differ diff --git a/tests/domainsTFReflectivityCalculation/domainsCustomLayersTFParams.mat b/tests/domainsTFReflectivityCalculation/domainsCustomLayersTFParams.mat index a93aab518..1da1f8a4c 100644 Binary files a/tests/domainsTFReflectivityCalculation/domainsCustomLayersTFParams.mat and b/tests/domainsTFReflectivityCalculation/domainsCustomLayersTFParams.mat differ diff --git a/tests/domainsTFReflectivityCalculation/domainsCustomXYInputs.mat b/tests/domainsTFReflectivityCalculation/domainsCustomXYInputs.mat index 72829cb5d..8a2ff16d9 100644 Binary files a/tests/domainsTFReflectivityCalculation/domainsCustomXYInputs.mat and b/tests/domainsTFReflectivityCalculation/domainsCustomXYInputs.mat differ diff --git a/tests/domainsTFReflectivityCalculation/domainsCustomXYOutputs.mat b/tests/domainsTFReflectivityCalculation/domainsCustomXYOutputs.mat index d99542627..b0faf1934 100644 Binary files a/tests/domainsTFReflectivityCalculation/domainsCustomXYOutputs.mat and b/tests/domainsTFReflectivityCalculation/domainsCustomXYOutputs.mat differ diff --git a/tests/domainsTFReflectivityCalculation/domainsCustomXYTFParams.mat b/tests/domainsTFReflectivityCalculation/domainsCustomXYTFParams.mat index e9aeec5e0..1e80f8bed 100644 Binary files a/tests/domainsTFReflectivityCalculation/domainsCustomXYTFParams.mat and b/tests/domainsTFReflectivityCalculation/domainsCustomXYTFParams.mat differ diff --git a/tests/domainsTFReflectivityCalculation/domainsStandardLayersInputs.mat b/tests/domainsTFReflectivityCalculation/domainsStandardLayersInputs.mat index 85d57e46d..074ff1d3f 100644 Binary files a/tests/domainsTFReflectivityCalculation/domainsStandardLayersInputs.mat and b/tests/domainsTFReflectivityCalculation/domainsStandardLayersInputs.mat differ diff --git a/tests/domainsTFReflectivityCalculation/domainsStandardLayersOutputs.mat b/tests/domainsTFReflectivityCalculation/domainsStandardLayersOutputs.mat index 83f39a53f..2b506dbc8 100644 Binary files a/tests/domainsTFReflectivityCalculation/domainsStandardLayersOutputs.mat and b/tests/domainsTFReflectivityCalculation/domainsStandardLayersOutputs.mat differ diff --git a/tests/domainsTFReflectivityCalculation/domainsStandardLayersTFParams.mat b/tests/domainsTFReflectivityCalculation/domainsStandardLayersTFParams.mat index 9b4f3089c..0786abcc7 100644 Binary files a/tests/domainsTFReflectivityCalculation/domainsStandardLayersTFParams.mat and b/tests/domainsTFReflectivityCalculation/domainsStandardLayersTFParams.mat differ diff --git a/tests/nonPolarisedTFReflectivityCalculation/customLayersInputs.mat b/tests/nonPolarisedTFReflectivityCalculation/customLayersInputs.mat index e80acd5de..9696ad505 100644 Binary files a/tests/nonPolarisedTFReflectivityCalculation/customLayersInputs.mat and b/tests/nonPolarisedTFReflectivityCalculation/customLayersInputs.mat differ diff --git a/tests/nonPolarisedTFReflectivityCalculation/customLayersOutputs.mat b/tests/nonPolarisedTFReflectivityCalculation/customLayersOutputs.mat index 80bcddfd4..7015135c6 100644 Binary files a/tests/nonPolarisedTFReflectivityCalculation/customLayersOutputs.mat and b/tests/nonPolarisedTFReflectivityCalculation/customLayersOutputs.mat differ diff --git a/tests/nonPolarisedTFReflectivityCalculation/customLayersTFParams.mat b/tests/nonPolarisedTFReflectivityCalculation/customLayersTFParams.mat index 2fc0e1e2e..61c0aa80b 100644 Binary files a/tests/nonPolarisedTFReflectivityCalculation/customLayersTFParams.mat and b/tests/nonPolarisedTFReflectivityCalculation/customLayersTFParams.mat differ diff --git a/tests/nonPolarisedTFReflectivityCalculation/customXYInputs.mat b/tests/nonPolarisedTFReflectivityCalculation/customXYInputs.mat index b76deb7a8..74ee66277 100644 Binary files a/tests/nonPolarisedTFReflectivityCalculation/customXYInputs.mat and b/tests/nonPolarisedTFReflectivityCalculation/customXYInputs.mat differ diff --git a/tests/nonPolarisedTFReflectivityCalculation/customXYOutputs.mat b/tests/nonPolarisedTFReflectivityCalculation/customXYOutputs.mat index 0586713ba..4ad7da134 100644 Binary files a/tests/nonPolarisedTFReflectivityCalculation/customXYOutputs.mat and b/tests/nonPolarisedTFReflectivityCalculation/customXYOutputs.mat differ diff --git a/tests/nonPolarisedTFReflectivityCalculation/customXYTFParams.mat b/tests/nonPolarisedTFReflectivityCalculation/customXYTFParams.mat index 900e666c6..b5af9f4d7 100644 Binary files a/tests/nonPolarisedTFReflectivityCalculation/customXYTFParams.mat and b/tests/nonPolarisedTFReflectivityCalculation/customXYTFParams.mat differ diff --git a/tests/nonPolarisedTFReflectivityCalculation/standardLayersInputs.mat b/tests/nonPolarisedTFReflectivityCalculation/standardLayersInputs.mat index 1a94c6f4a..5202681eb 100644 Binary files a/tests/nonPolarisedTFReflectivityCalculation/standardLayersInputs.mat and b/tests/nonPolarisedTFReflectivityCalculation/standardLayersInputs.mat differ diff --git a/tests/nonPolarisedTFReflectivityCalculation/standardLayersOutputs.mat b/tests/nonPolarisedTFReflectivityCalculation/standardLayersOutputs.mat index bfab716ea..b92aad463 100644 Binary files a/tests/nonPolarisedTFReflectivityCalculation/standardLayersOutputs.mat and b/tests/nonPolarisedTFReflectivityCalculation/standardLayersOutputs.mat differ diff --git a/tests/nonPolarisedTFReflectivityCalculation/standardLayersTFParams.mat b/tests/nonPolarisedTFReflectivityCalculation/standardLayersTFParams.mat index 6f04d6b2d..75ef4816b 100644 Binary files a/tests/nonPolarisedTFReflectivityCalculation/standardLayersTFParams.mat and b/tests/nonPolarisedTFReflectivityCalculation/standardLayersTFParams.mat differ diff --git a/tests/testEventManager.m b/tests/testEventManager.m index 7e475e48f..94316829c 100644 --- a/tests/testEventManager.m +++ b/tests/testEventManager.m @@ -148,5 +148,17 @@ function testLivePlot(testCase) s2.closeFigure() testCase.verifyEmpty(eventManager.getEvents()); end + + function testStopEvent(testCase) + controls = controlsClass(); + testCase.assertEmpty(controls.getIPCFilePath(), 'IPC is not working'); + controls.initialiseIPC(); + path = controls.getIPCFilePath(); + testCase.assertNotEmpty(path, 'IPC is not working'); + testCase.assertFalse(isRATStopped(path), 'IPC is not working'); + controls.sendStopEvent(); + testCase.assertTrue(isRATStopped(path), 'IPC is not working'); + testCase.assertFalse(isRATStopped(''), 'IPC is not working'); + end end end diff --git a/utilities/misc/hdrload.m b/utilities/misc/hdrload.m index 9701feddc..40b35d1e6 100644 --- a/utilities/misc/hdrload.m +++ b/utilities/misc/hdrload.m @@ -54,7 +54,7 @@ ncols = 0; -% Finally, we initialize the data to []. +% Finally, we initialise the data to []. data = []; @@ -104,7 +104,7 @@ % line is stored in a unique variable using the 'eval' statement % within the loop. Note that, if we knew a priori that the % headers were 10 lines or less, we could use the STR2MAT -% function and save some work. First, initialize the header to an +% function and save some work. First, initialise the header to an % array of spaces. header = setstr(' '*ones(no_lines, max_line)); for i = 1:no_lines diff --git a/utilities/textProgressBar.m b/utilities/textProgressBar.m index 08fc8e80a..5f457fa01 100644 --- a/utilities/textProgressBar.m +++ b/utilities/textProgressBar.m @@ -1,35 +1,51 @@ -function textProgressBar(curm,pct) - -persistent lastNchar - -strDotsMax = 40; - -if strcmpi(curm,'init') - %fprintf('\n'); - lastNchar = 0; - return; -end - -if strcmpi(curm,'end') - fprintf('\n'); - return; -end - -if isempty(lastNchar) - lastNchar = 0; -end - -%curm = 'progress'; - -nDots = floor(pct * strDotsMax); -progressmsg = ['[' repmat('*',1,nDots) repmat('.',1,strDotsMax-nDots) ']']; - -% progressmsg=[183-uint16((1:40)<=(pct*40)).*(183-'*') '']; -% %curmtxt=sprintf('% 9.3g\n',curm(1:min(end,20),1)); -progressmsg=sprintf('\n %s %5.1f%% %s',curm,(pct*100),progressmsg); - -fprintf('%s%s',repmat(sprintf('\b'),1,lastNchar),progressmsg); -drawnow -lastNchar=length(progressmsg); - +function textProgressBar(curm, pct, varargin) + % Draws a progress bar in the console. The inputs are the message (char array) and + % percentage progress expressed as a decimal (i.e., between 0 and 1). + % Optionally a boolean value can be provided to disable the progress + % bar. + % + % textProgressBar("DREAM", 0.5, false) + persistent lastNchar + persistent display + + if ~isempty(varargin) + display = varargin{1}; + elseif isempty(display) + display = true; + end + + if ~display + return; + end + + strDotsMax = 40; + + if pct == 0 + %fprintf('\n'); + lastNchar = 0; + return; + end + + if lastNchar==0 && pct>=1 + return + end + + if isempty(lastNchar) + lastNchar = 0; + end + + nDots = floor(pct * strDotsMax); + progressmsg = ['[' repmat('*',1,nDots) repmat('.',1,strDotsMax-nDots) ']']; + + progressmsg=sprintf('\n%s %5.1f%% %s',curm,fix(pct*1000)/10,progressmsg); + + fprintf('%s%s',repmat(sprintf('\b'),1,lastNchar),progressmsg); + drawnow + lastNchar=length(progressmsg); + + if pct == 1 + fprintf('\n'); + lastNchar = 0; + return; + end end