KerMor  0.9
Model order reduction for nonlinear dynamical systems and nonlinear approximation
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
Utils.m
Go to the documentation of this file.
1 
2 
3 /* (Autoinserted by mtoc++)
4  * This source code has been filtered by the mtoc++ executable,
5  * which generates code that can be processed by the doxygen documentation tool.
6  *
7  * On the other hand, it can neither be interpreted by MATLAB, nor can it be compiled with a C++ compiler.
8  * Except for the comments, the function bodies of your M-file functions are untouched.
9  * Consequently, the FILTER_SOURCE_FILES doxygen switch (default in our Doxyfile.template) will produce
10  * attached source files that are highly readable by humans.
11  *
12  * Additionally, links in the doxygen generated documentation to the source code of functions and class members refer to
13  * the correct locations in the source code browser.
14  * However, the line numbers most likely do not correspond to the line numbers in the original MATLAB source files.
15  */
16 
17 class Utils {
65  public: /* ( Static ) */
66 
67 
68  static function charshort = getHelpShort(char txt) {
69  pos = regexp(txt,sprintf(" \n[ ]*\n "));
70  short = ;
71  if ~isempty(pos)
72  short = txt(1:pos(1)-1);
73  else
74  /* Maybe only one line? */
75  pos = strfind(txt,char(10));
76  if ~isempty(pos)
77  short = txt(1:pos(1)-1);
78  end
79  end
80  short = strtrim(short);
81  }
96  static function [doublebmin , doublebmax ] = getBoundingBox(double vectors) {
97  bmin = min(vectors,[],2);
98  bmax = max(vectors,[],2);
99  }
114  static function comb = createCombinations(ranges,varargin) {
115 
116  if ~isa(ranges," cell ")
117  if isempty(varargin)
118  comb = ranges;
119  return;
120  end
121  r = cell(1,length(varargin)+1);
122  r[1] = ranges;
123  [r[2:end]] = varargin[:];
124  ranges = r;
125  end
126 
127  n = length(ranges);
128  /* Create nd-grids */
129  [matrices[1:n]] = ndgrid(ranges[:]);
130  /* Convert to np x params matrix */
131  comb = zeros(n,numel(matrices[1]));
132  for idx=1:n
133  /* Check if any range is empty - return empty then */
134  if isempty(matrices[idx])
135  comb = [];
136  return;
137  end
138 
139  comb(idx,:) = matrices[idx](:);
140  end
141  }
159  static function structtarget = copyStructFields(struct source,struct target) {
160  if ~isstruct(source) || ~isstruct(target)
161  error(" Both source and target arguments must be structs. ");
162  end
163  /* Get the field names from the source struct */
164  names = fieldnames(source);
165  for idx = 1:length(names)
166  /* For struct fields, recursively copy the inner struct */
167  if isstruct(source.(names[idx]))
168  /* Create target struct if not already set */
169  if isempty(target.(names[idx]))
170  target.(names[idx]) = struct;
171  end
172  target.(names[idx]) = Utils.copyStructFields(source.(names[idx]),target.(names[idx]));
173  /* Else just copy the field values */
174  else
175  target.(names[idx]) = source.(names[idx]);
176  end
177  end
178  }
194  static function str = getLatexStr(value,digits) {
195  if nargin < 2
196  digits = 3;
197  end
198  str = sprintf(sprintf(" %%.%de ",digits),value);
199  str = sprintf(" %s ",str(1:digits+2));
200  expo = floor(log10(value));
201  if expo ~= 0
202  str = sprintf(" %s\\times10^{%d} ",str,expo);
203  end
204  str = sprintf(" $%s$ ",str);
205  }
206 
207 
208  static function charstr = implode(char|rowvec data,char glue,char format) {
209  str = ;
210  if ~isempty(data)
211  if nargin < 3
212  format = " %2.3e ";
213  if nargin < 2
214  glue = " , ";
215  end
216  end
217  if isa(data," cell ")
218  fun = @(arg)arg;
219  if nargin == 4
220  fun = @(arg)sprintf(format,arg);
221  end
222  str = fun(data[1]);
223  for idx = 2:length(data)
224  str = [str glue fun(data[idx])];
225  end
226  elseif isnumeric(data)
227  /* first n-1 entries */
228  if numel(data) > 1
229  str = sprintf([format glue],data(1:end-1));
230  end
231  /* append last, no glue afterwards needed */
232  str = [str sprintf(format,data(end))];
233  else
234  error(" Can only pass cell arrays of strings or a vector with sprintf format pattern ");
235  end
236  end
237  }
259  static function idx = findVecInMatrix(A,b) {
260 
261  if size(A,1) ~= size(b,1)
262  error(" Invalid arguments. ");
263  end
264  idx = zeros(1,size(b,2));
265  for n = 1:size(b,2)
266  tmp = strfind(reshape(A,1,[]),b(:,n)^t);
267  /* Exclude positions where the position is not at the start
268  * of a found vector! */
269  tmp(mod(tmp,size(b,1)) ~= 1) = [];
270  if ~isempty(tmp)
271  idx(n) = (tmp(1)+size(b,1)-1)/size(b,1);
272  end
273  end
274  }
297  static function y = preparePlainPlot(y) {
298  if size(y,1) > 1000
299  fprintf(" Utils/preparePlainPlot: Number of graphs for plot > 1000, taking graphs with distinct y(T) values.\n ");
300  [v,idx] = unique(y(:,end));
301  [v,idxm] = unique(y(:,round(size(y,2)/2)));
302  y = y(union(idx,idxm),:);
303  sy = size(y,1);
304  if sy > 4000
305  fprintf(" Utils/preparePlainPlot: Number of graphs for plot still > 4000, taking 4000 graphs.\n ");
306  y = y(round(1:sy/4000:sy),:);
307  end
308  end
309  }
324  static function saveFigure(fig,filename,ext) {
325 
326  if any(~ishandle(fig))
327  error(" Invalid figure handle. ");
328  end
329 
330  ExportDPI = " 150 ";
331  JPEGQuality = " 95 ";
332  exts = [" fig "," pdf "," eps "," jpg "," png "," tif "];
333  extd = [" MatLab Figure ", " PDF Files ", " Extended PostScript ", " JPEG Image ",...
334  " Portable Network Graphic ", " TIFF Image "];
335 
336  /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */
337  file = [];
338  if nargin < 3
339  extidx = 1;
340  if nargin < 2
341  choices = cell(length(exts),2);
342  for i = 1:size(choices,1)
343  choices[i,1] = [" *. " exts[i]];
344  choices[i,2] = [extd[i] " (*. " exts[i] " ) "];
345  end
346  [filename, pathname, extidx] = uiputfile(choices, " Save figure as ", ...
347  getpref(KerMor.getPrefTag," LASTPATH ",pwd));
348  if ~isequal(filename, 0)
349  file = [pathname filename];
350  setpref(KerMor.getPrefTag," LASTPATH ",pathname)
351  end
352  else
353  file = [filename " . " exts[extidx]];
354  end
355  else
356  extidx = find(strcmp(ext,exts),1);
357  if isempty(extidx)
358  warning(" KerMor:Utils:invalidExtension "," Invalid extension: %s, using eps ",ext);
359  extidx = 1;
360  end
361  file = [filename " . " exts[extidx]];
362  end
363 
364  if ~isempty(file)
365 /* [d,fname] = fileparts(file); */
366  d = fileparts(file);
367  if ~isempty(d) && exist(d," file ") ~= 7
368  mkdir(d);
369  end
370 /* allax = findobj(get(gcf,'Children'),'Type','axes');
371  * if length(allax) > 1
372  * if (extidx == 1)
373  * saveas(fig,file,'eps2c');
374  * elseif extidx == 2
375  * print(fig,file,['-djpeg' JPEGQuality],['-r' ExportDPI]);
376  * elseif extidx == 3
377  * saveas(fig, file, 'fig');
378  * elseif extidx == 4
379  * print(fig,file,'-dpdf',['-r' ExportDPI]);
380  * elseif extidx == 5
381  * saveas(fig,file,'png');
382  * end
383  * else */
384  if extidx == 1 /* fig */
385 
386  saveas(fig, file, " fig ");
387  else
388  args = [file, [" - " exts[extidx]],[" -r " ExportDPI]];
389  if any(extidx == [2 3]) /* pdf, eps
390  *args{end+1} = '-painters'; */
391 
392  args[end+1] = " -transparent ";
393  elseif extidx == 4 /* jpg */
394 
395  args[end+1] = [" -q " JPEGQuality];
396  /* args{end+1} = '-opengl'; */
397  elseif extidx == 5 /* png */
398 
399  args[end+1] = " -transparent ";
400  end
401 
402 /* allax = findobj(get(fig,'Children'),'Type','axes');
403  * allax(strcmpi(get(allax,'Tag'),'legend')) = [];
404  * if length(allax) > 1
405  * args{end+1} = allax;
406  * else */
407  args[end+1] = fig;
408 /* end */
409 
410  /* export_fig ignores -transparent somehow.. */
411  c = get(fig," Color ");
412  set(fig," Color "," white ");
413 
414  export_fig(args[:]);
415 
416  set(fig," Color ",c);
417  /* saveas(fig, fullfile(d,fname), 'fig'); */
418  end
419 /* end */
420  else
421  fprintf(2," No file specified. Aborting\n ");
422  end
423  }
437  static function saveAxes(handle ax,varargin) {
438 
439  fig = figure(" Visible "," off "," MenuBar "," none "," ToolBar "," none ");
440  /* fig = figure('MenuBar','none','ToolBar','none');
441  *fig = figure;
442  * Set fig size to axis size
443  *set(fig,'Position', [fpos(1:2) (apos(3:4)+ti(3:4))/2]); */
444  copyobj(ax, fig);
445 
446  /* % Fit style
447  * Just copy the colormap
448  *set(fig,'Colormap',get(get(ax,'Parent'),'Colormap')); */
449 
450  /* % Save */
451  Utils.saveFigure(fig, varargin[:]);
452  close(fig);
453  }
465  static function removeMargin(f) {
466  a = gca(f);
467  fu = get(f," Units ");
468  au = get(a," Units ");
469 
470  set(f," Units "," pixels ");
471  set(a," Units "," pixels ");
472  fpos = get(f," Position ");
473  apos = get(a," Position ");
474  ati = get(a," TightInset ");
475  set(f," ActivePositionProperty "," Position ");
476  set(a," ActivePositionProperty "," Position ");
477  set(f," Position ",[fpos(1:2) apos(3:4)+ati(1:2)+ati(3:4)]);
478  set(a," Position ",[ati(1:2) apos(3:4)]);
479 
480  set(f," Units ",fu);
481  set(a," Units ",au);
482  }
493  static function h = getHash(vec) {
494  h = CalcMD5(vec);
495  /* h = sprintf('%d',typecast(vec,'uint8')); */
496  }
510  static function [matrix<double>x , colvec<double>farend ] = getTube(integer dim,integer num,double length,double spread,integer seed) {
511  if nargin < 5
512  seed = cputime*10;
513  if nargin < 4
514  spread = .15;
515  if nargin < 3
516  length = 1;
517  end
518  end
519  end
520  r = RandStream(" mt19937ar "," Seed ",seed);
521  farend = r.rand(dim,1)-.5;
522  farend = farend * length/norm(farend);
523  x = r.rand(dim,num)-.5;
524  x = bsxfun(@times, x, length*spread./Norm.L2(x));
525  x = x + bsxfun(@times, farend, r.rand(1,num));
526  }
551  static function [doubleln , colvec<double>v ] = logNorm(matrix<double> A,matrix<double> G,colvec<double> v0) {
552  if nargin == 2
553  L = chol(G," lower ");
554  A = L\(A^t*L);
555  end
556 
557  hlp = .5*(A + A^t);
558  dim = size(hlp,1);
559  if dim > 1000
560  if nargin == 3
561  opts.v0= v0;
562  end
563  opts.maxit= 1000;
564  opts.p= 20+ceil(.1*log(dim)*(dim^.35));
565  if dim > 10000 && KerMor.App.Verbose > 2
566  fprintf(" Starting log norm computation for %d-dimensional matrix (eigs:maxit=%d, p=%d)\n ",...
567  dim,opts.maxit,opts.p);
568  end
569  lastwarn();
570  [v, ln] = eigs(hlp,1," la ",opts);
571  [s,id] = lastwarn;
572  if ~isempty(s) && strcmp(id," MATLAB:eigs:NoEigsConverged ")
573  fprintf(" Single eigenvalue not converged with p=%d. Re-trying with p=%d...\n ",...
574  opts.p,opts.p*2);
575  opts.p= opts.p*2;
576  [v, ln] = eigs(hlp,1," la ",opts);
577  end
578  if ln < 0
579  opts.p= 20+ceil(.1*log(dim)*(dim^.35));
580  [v, ln] = eigs(hlp,1,-ln,opts);
581  [s,id] = lastwarn;
582  if ~isempty(s) && strcmp(id," MATLAB:eigs:NoEigsConverged ")
583  fprintf(" Single (shifted by %g) eigenvalue not converged with p=%d. Re-trying with p=%d...\n ",...
584  -ln,opts.p,opts.p*2);
585  opts.p= opts.p*2;
586  [v, ln] = eigs(hlp,1," la ",opts);
587  end
588  end
589  else
590  if issparse(hlp)
591  hlp = full(hlp);
592  end
593  [v, d] = eig(hlp);
594  [ln, idx] = max(diag(d));
595  v = v(:,idx);
596  end
597 /* t = tic;
598  * % Get smallest and largest magnitude eigenvalues
599  * [v, ln2] = eigs(hlp,2,'be',opts);
600  * [ln2, idx] = max([ln2(1) ln2(4)]);
601  * v = v(:,idx);
602  * t3 = toc(t);
603  * fprintf('eig-full: %g/%gs, eigs-shift: %g/%gs, eigs-be: %g/%gs\n',...
604  * ln1,t1,ln,t2,ln2,t3); */
605  }
629  static function S = sprand(integer n,integer m,double dens,RandStream rs) {
630  if nargin < 4
631  rs = RandStream(" mt19937ar "," Seed ",0);
632  end
633  total = n*m*dens;
634  i = rs.randi(n,total,1);
635  j = rs.randi(m,total,1);
636  s = rs.rand(total,1);
637  S = sparse(i,j,s,n,m);
638  }
658  static function closeAllFigures() {
659  while true
660  f = get(0," CurrentFigure ");
661  if isempty(f)
662  return;
663  end
664  close(f);
665  end
666  }
667 
668 
669  static function folder = getDir(caption,initial_path) {
670  if all(get(0," Screensize ") == 1)
671  if nargin < 1
672  caption = " Please specify a directory ";
673  end
674  folder = input([caption " : "]," s ");
675  if isempty(folder)
676  folder = 0;
677  end
678  else
679  if nargin < 2
680  initial_path = cd;
681  end
682  folder = uigetdir(initial_path, caption);
683  end
684  }
700  static function logicalsuccess = ensureDir(char dir) {
701  success = true;
702  if ~isempty(dir) && exist(dir," dir ") ~= 7
703  try
704  mkdir(dir);
705  catch ME
706  if nargout < 1
707  me = MException(" Utils:ensureDir "," Could not create directory '%s' ",dir);
708  me.addCause(ME);
709  me.throw;
710  end
711  success = false;
712  end
713  end
714  }
730  static function copyPrefGroup(char from,char to) {
731  p = getprefs;
732  localp = p.(from);
733  pfn = fieldnames(localp);
734  for k = 1:numel(pfn)
735  setpref(to,pfn[k],localp.(pfn[k]));
736  end
737  }
747  static function entries = getLegendFromVector(values,format_string) {
748  if nargin < 2
749  format_string = " %g ";
750  end
751  entries = cellfun(@(v)sprintf(format_string,v),num2cell(values)," UniformOutput ",false);
752  }
753 
754 
755  public: /* ( Static ) */
756 
757  static function res = test_Tube() {
758  num = 1000;
759  res = true;
760  for i=1:50
761  dim = round(rand*30);
762  length = rand*100;
763  spread = rand/2;
764 
765  x = Utils.getTube(dim, num, length, spread);
766  res = res & all(Norm.L2(x) <= length*(1+spread));
767  end
768  }
769 
770 
771  static function res = test_createCombinations() {
772  res = true;
773 
774  res = res && isequal([1 2 3 1 2 3; 1 1 1 2 2 2],Utils.createCombinations(1:3,1:2));
775 
776  res = res && isempty(Utils.createCombinations(1:3,1:2,[],1:54));
777 
778  res = res && isequal(1:20,Utils.createCombinations(1:20));
779  }
788  static function res = test_findVec() {
789  a = rand(40,40);
790  idx = randperm(40);
791  idx = idx(1:10);
792  b = a(:,idx);
793 
794  /* Add nonexistent */
795  b(:,end+1) = rand(40,1);
796  idx = [idx 0];
797 
798  /* Add multiples */
799  a(:,end+1:end+2) = a(:,[idx(1) idx(5)]);
800 
801  res = all(idx - Utils.findVecInMatrix(a,b) == 0);
802  }
812 };
813 
814 
815 
static function tag = getPrefTag()
Returns the tag used to store the KerMor preferences and settings.
Definition: KerMor.m:1098
Collection of generally useful functions.
Definition: Utils.m:17
function MD5 = CalcMD5(Data, InClass, OutClass)
128 bit MD5 checksum: file, string, byte stream [MEX] This function calculates a 128 bit checksum for...
Definition: CalcMD5.m:17
static function closeAllFigures()
Definition: Utils.m:658
static function comb = createCombinations(ranges, varargin)
Creates the cartesian product of the vectors passed as a matrix containing elements of each vector pe...
Definition: Utils.m:114
static function idx = findVecInMatrix(A, b)
Finds column vectors inside a matrix.
Definition: Utils.m:259
A MatLab cell array or matrix.
static function res = test_Tube()
Definition: Utils.m:757
function [ im , alpha ] = export_fig(varargin)
Make sure the figure is rendered correctly now so that properties like axes limits are up-to-date...
Definition: export_fig.m:17
An integer value.
static function copyPrefGroup(char from,char to)
Copies the preferences from one group to another.
Definition: Utils.m:730
Matlab's base handle class (documentation generation substitute)
A variable number of input arguments.
static function entries = getLegendFromVector(values, format_string)
Definition: Utils.m:747
static function saveFigure(fig, filename, ext)
Opens a matlab save dialog and saves the given figure to the file selected.
Definition: Utils.m:324
static function [ matrix< double > x , colvec< double > farend ] = getTube(integer dim,integer num,double length,double spread,integer seed)
Computes num random vectors inside a tube of length length inside a dim dimensional space...
Definition: Utils.m:510
static function h = getHash(vec)
Returns a hash code for the given vector.
Definition: Utils.m:493
Speed test * all(1:3)
static function folder = getDir(caption, initial_path)
Prompts the user to select a directory.
Definition: Utils.m:669
#define G(x, y, z)
Definition: CalcMD5.c:169
static function logical success = ensureDir(char dir)
Ensures that a directory exists.
Definition: Utils.m:700
static function char str = implode(char|rowvec data,char glue,char format)
Implodes the elements of data using glue.
Definition: Utils.m:208
static function rowvec< double > n = L2(matrix< double > x)
Returns the discrete norm for each column vector in x.
Definition: Norm.m:39
Global configuration class for all KerMor run-time settings.
Definition: KerMor.m:17
A matlab row vector.
static function [ double ln , colvec< double > v ] = logNorm(matrix< double > A,matrix< double > G,colvec< double > v0)
Computes the logarithmic norm of a matrix , optionally using a positive definite symmetric matrix in...
Definition: Utils.m:551
static function struct target = copyStructFields(struct source,struct target)
Recursively copies struct fields from one struct to another.
Definition: Utils.m:159
static function KerMor theinstance = App()
The singleton KerMor instance.
Definition: KerMor.m:910
Norm: Static class for commonly used norms on sets of vectors.
Definition: Norm.m:17
static function res = test_findVec()
Tests the findVecInMatrix function.
Definition: Utils.m:788
static function removeMargin(f)
Requires the axes and figure units to be the same.
Definition: Utils.m:465
static function S = sprand(integer n,integer m,double dens,RandStream rs)
Creates a random sparse matrix with given density (approximately).
Definition: Utils.m:629
static function char short = getHelpShort(char txt)
Extracts the help short subtext from a given text.
Definition: Utils.m:68
static function str = getLatexStr(value, digits)
Definition: Utils.m:194
static function saveAxes(handle ax, varargin)
Convenience function. Allows to save a custom axes instead of a whole figure which allows to drop any...
Definition: Utils.m:437
static function res = test_createCombinations()
Tests the createCombinations function.
Definition: Utils.m:771
static function y = preparePlainPlot(y)
Memory-saving plotting for plain result plots.
Definition: Utils.m:297
static function [ double bmin , double bmax ] = getBoundingBox(double vectors)
Gets the bounding box for a matrix containing column vectors.
Definition: Utils.m:96