1function optimizer_asco_sim( optimdir, inputfile, outputfile, simfun )
2%optimizer_asco_sim( optimdir, inputfile, outputfile, simfun )
3%
4% This function is called from general.sh. Do not call it yourself.
5%
6% tasks:
7%  - set correct matlab path
8%  - evaluate input file
9%  - start simulation or get result from cache
10%  - post-process simulation results
11%  - create output file (important: needs single \n at the first line and double \n at the last line!)
12
13error( nargchk(4,4,nargin) );
14
15% add CSXCAD and openEMS to the matlab path
16folder = fileparts( mfilename('fullpath') );
17addpath( folder );
18addpath( [folder '/../../CSXCAD/matlab'] );
19
20% change to optimdir
21olddir = pwd;
22cd( optimdir );
23
24% read parameters set by asco
25if ~isempty( strfind(inputfile,'-') )
26    % matlab cannot execute a file with dashes...
27    inputfile2 = strrep( inputfile,'-','_' );
28    movefile( [inputfile '.m'], [inputfile2 '.m'] );
29    run( inputfile2 );
30    movefile( [inputfile2 '.m'], [inputfile '.m'] );
31end
32% now a structure named 'params' is available
33
34% check cache
35folder = create_folder_name( params );
36if exist( ['./' folder], 'dir' ) && exist( ['./' folder '/result.mat'], 'file' )
37    % read cache
38    disp( 'CACHE HIT' );
39    result = load( [folder '/result.mat'], 'result' );
40    result = result.result;
41else
42    % start simulation in folder <folder>
43    disp( ['starting simulation function ' simfun] );
44    disp( ['         simulation folder   ' folder] );
45    [simfun_folder,simfun] = fileparts(simfun);
46    oldpath = path;
47    addpath( simfun_folder );
48    fhandle = str2func(simfun); % does not work for octave-3.2.4!
49    path( oldpath );
50    mkdir( folder );
51    result = fhandle(folder,params);
52    save( [folder '/result.mat'], 'result', '-mat' );
53end
54
55% write results for asco
56fid = fopen( outputfile, 'wt' );
57fprintf( fid, '\nvalue= %e\n\n', result );
58fclose( fid );
59
60% update best result
61best = [];
62best.result = result;
63best.params = params;
64if exist( [pwd '/best_result.mat'], 'file' )
65    old = load( 'best_result.mat', 'best' );
66    if old.best.result > best.result
67        save( 'best_result.mat', 'best', '-mat' );
68    end
69else
70    save( 'best_result.mat', 'best', '-mat' );
71end
72
73% restore old folder
74cd( olddir );
75
76
77
78
79
80
81
82function folder = create_folder_name( params )
83params = orderfields( params );
84folder = 'opt';
85fnames = fieldnames(params);
86for n=1:numel(fnames)
87    folder = [folder '_' fnames{n} '=' num2str(params.(fnames{n}))];
88end
89