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
DEIM.m
Go to the documentation of this file.
1 namespace testing{
2 
3 
4 /* (Autoinserted by mtoc++)
5  * This source code has been filtered by the mtoc++ executable,
6  * which generates code that can be processed by the doxygen documentation tool.
7  *
8  * On the other hand, it can neither be interpreted by MATLAB, nor can it be compiled with a C++ compiler.
9  * Except for the comments, the function bodies of your M-file functions are untouched.
10  * Consequently, the FILTER_SOURCE_FILES doxygen switch (default in our Doxyfile.template) will produce
11  * attached source files that are highly readable by humans.
12  *
13  * Additionally, links in the doxygen generated documentation to the source code of functions and class members refer to
14  * the correct locations in the source code browser.
15  * However, the line numbers most likely do not correspond to the line numbers in the original MATLAB source files.
16  */
17 
18 class DEIM
39  private:
40 
41  data;
42 
43 
44  public:
45 
46 
47  DEIM(sys,dim) {
48  this = this@dscomponents.ACompEvalCoreFun(sys);
49  if nargin < 1
50  dim = 200;
51  end
52  this.xDim= dim;
53  this.fDim= dim;
54  this.data= rand(dim,1);
55  /* Commenting this out will let KerMor issue a warning. */
56  this.JSparsityPattern= sparse(dim,dim);
57  }
58 
59 
60  function fx = evaluateCoreFun(unused1,double t) {
61  fx = bsxfun(@mtimes,this.data,this.mu(1,:)) + repmat(t,this.fDim,1);
62  }
63 
64 
65  protected:
66 
67  function fx = evaluateComponents(pts,ends,idx,self,colvec<double> x,double t) {
68  fx = evaluateComponentsMulti(this, pts, ends, idx, self, x, t, this.mu);
69  }
70 
71 
72  function fx = evaluateComponentsMulti(pts,ends,idx,self,colvec<double> x,double t,colvec<double> mu) {
73  fx = bsxfun(@mtimes,this.data(pts),mu(1,:)) + repmat(t,length(pts),1);
74  }
75 
76 
77  public: /* ( Static ) */
78 
79 
80  static function res = test_DEIMNoSpatialDependence() {
81  dim = 400;
82  f = testing.DEIM([],dim);
83 
84  d = general.DEIM;
85  d.MaxOrder= round(dim/2);
86 
87  x = rand(dim,dim*2);
88  fx = rand(dim,dim*2);
89  atd = data.ApproxTrainData(x,[],[]);/* #ok */
90 
91  atd.fxi= fx;
92 
93  d.computeDEIM(f,atd.fxi);
94 
95  x = double.empty(dim,0);
96  t = linspace(0,1,20);
97  mu = rand(1,20);
98 
99  fxall = f.evaluateMulti(x,t,mu);
100 
101  for k = 1:5:d.MaxOrder
102  d.Order= k;
103  afx = d.evaluateMulti(x,t,mu);
104  fprintf(" Relative errors for Order k=%d: %s\n ",k,...
105  sprintf(" %g ",sum(Norm.L2(fxall-afx)))); /* ./Norm.L2(fxall) */
106 
107  end
108  res = true;
109  }
110 
111 
112  static function analysis_DEIM_approx(m) {
113  ma = ModelAnalyzer(m.buildReducedModel);
114 
115  mu = m.Data.ParamSamples(:,5);
116 /* [t, pm] = ma.compareRedFull(mu);
117  * t.Format = 'tex';
118  * t.saveToFile('comp_red_full.tex');
119  * pm.savePlots('.',{'fig','jpg','eps'}, true); */
120 
121  d = m.Approx;
122  res = testing.DEIM.computeDEIMErrors(d, m.Data.ApproxTrainData);
123  /* pm = PlotManager(true); */
124  pm = PlotManager(false,1,2);
125  pm.FilePrefix= " DEIM_errors ";
126  testing.DEIM.plotDEIMErrs(res, pm);
127  /* pm.savePlots('.',{'fig','jpg','eps'}, true); */
128  pm.savePlots(" . ",[" fig "," jpg "], true);
129 
130  [etrue, EE, ED] = ma.getTrajApproxErrorDEIMEstimates(mu,[]);
131 /* pm = PlotManager(true); */
132  pm = PlotManager(false,1,2);
133  pm.FilePrefix= " traj_approx_err ";
134  ma.getTrajApproxErrorDEIMEstimates_plots(m.scaledTimes, etrue, EE, ED, pm);
135 /* pm.savePlots('.',{'fig','jpg','eps'}, true); */
136  pm.savePlots(" . ",[" fig "," jpg "], true);
137 
138  [minreq, relerrs, orders, t] = ma.getMeanRequiredErrorOrders;
139  t.Format= " tex ";
140  t.saveToFile(" meanrequirederrororders.tex ");
141 
143  }
144 
145 
146  static function res = computeDEIMErrors(general.DEIM deim,data.ApproxTrainData atd,rowvec<integer> orders,rowvec<integer> errorders) {
147  oldo = deim.Order;
148  if nargin < 4
149  if nargin < 3
150  orders = 1:deim.MaxOrder-1;
151  end
152  errorders = [];
153  neworders = [];
154  for i=1:length(orders)
155  new = 1:(deim.MaxOrder-orders(i));
156  errorders = [errorders new];/* #ok */
157 
158  neworders = [neworders orders(i)*ones(1,length(new))];/* #ok */
159 
160  end
161  orders = neworders;
162  elseif ~isempty(errorders) && length(orders) ~= length(errorders)
163  error(" If both the orders and error orders are given they must have same number of elements ");
164  end
165  n = length(orders);
166  res = zeros(14,n);
167  res(1,:) = orders;
168  res(2,:) = errorders;
169  /* State space error function */
170  efun = @Norm.L2;
171 
172  nb = atd.xi.nBlocks;
173  pi = ProcessIndicator(sprintf(" Computing DEIM errors and estimates for %d Order/ErrOrder settings over %d xi-Blocks ",n,nb),n*nb);
174  co = [];
175  m = atd.xi.m;
176  for k = 1:nb
177  pos = atd.xi.getBlockPos(k);
178  xi = atd.xi(:,pos);
179  fxi = atd.fxi(:,pos); /* must have same length, but may have different block size. */
180 
181  if ~isempty(deim.V)
182  xi = deim.V^t*xi;
183  end
184  fxinorm = efun(fxi);
185  deim.Order= deim.MaxOrder;
186  afximaxorder = deim.evaluate(xi,atd.ti(pos),atd.mui(:,pos));
187  for i = 1:n
188  deim.Order= [res(1,i) res(2,i)];
189  /* Check if new overall DEIM order m */
190  if isempty(co) || res(1,i) ~= co
191  afxi = deim.evaluate(xi,atd.ti(pos),atd.mui(:,pos));
192  /* Get true DEIM error against full function */
193  etrue = efun(fxi-afxi);
194  /* Get error measured against max order DEIM approx */
195  emaxorder = efun(afximaxorder-afxi);
196  /* 3: max abs true error (indep. of errororder) */
197  res(3,i) = max(res(3,i),max(etrue));
198  /* 4: max rel true error w.r.t true fxi norm (indep. of errororder) */
199  hlp = etrue./fxinorm;
200  hlp(isnan(hlp)) = 0;
201  res(4,i) = max(res(4,i),max(hlp));
202  /* 5: mean abs true error (indep. of errororder) */
203  res(5,i) = res(5,i) + sum(etrue)/m;
204  /* 6: mean rel true error w.r.t true fxi norm (indep. of errororder) */
205  res(6,i) = res(6,i) + sum(hlp)/m;
206  co = res(1,i);
207  else /* else copy */
208 
209  res(3:6,i) = res(3:6,i-1);
210  end
211  if res(2,i) > 0
212  /* Estimated absolute/rel errors */
213  eest = efun(deim.getEstimatedError(xi,atd.ti(pos),atd.mui(:,pos)));
214  /* 7: max abs estimated error */
215  res(7,i) = max(res(7,i),max(eest));
216  /* 8: max rel estimated error w.r.t true fxi norm */
217  hlp = eest./fxinorm;
218  hlp(isnan(hlp)) = 0;
219  res(8,i) = max(res(8,i),max(hlp));
220  /* 9: mean abs estimated error */
221  res(9,i) = res(9,i) + sum(eest)/m;
222  /* 10: mean rel estimated error w.r.t true fxi norm */
223  res(10,i) = res(10,i) + sum(hlp)/m;
224  /* 11: max rel error on (estimated-true error) w.r.t true error */
225  hlp = abs(eest-etrue)./etrue;
226  hlp(isnan(hlp)) = 0;
227  res(11,i) = max(res(11,i),max(hlp));
228  /* 12: mean rel error on (estimated-true error) w.r.t true error */
229  res(12,i) = res(12,i) + sum(hlp)/m;
230  /* 13: max rel error on (estimated-maxorder error) w.r.t maxorder error */
231  hlp = abs(eest-emaxorder)./emaxorder;
232  hlp(isnan(hlp)) = 0;
233  res(13,i) = max(res(13,i),max(hlp));
234  /* 14: mean rel error on (estimated-maxorder error) w.r.t maxorder error */
235  res(14,i) = res(14,i) + sum(hlp)/m;
236  end
237  pi.step;
238  end
239  end
240  deim.Order= oldo;
241  pi.stop;
242  }
283  static function pm = plotDEIMErrs(res,pm) {
284 
285  if nargin < 2
286  pm = PlotManager(false,2,3);
287  pm.FilePrefix= " comp_m_mdash ";
288  end
289  /* Not used yet:
290  * 5: mean abs true error (indep. of errororder)
291  * 6: mean rel true error w.r.t true fxi norm (indep. of errororder)
292  * 9: mean abs estimated error
293  * 10: mean rel estimated error w.r.t true fxi norm */
294 
295  /* Compute unique positions */
296  [orders, idx] = unique(res(1,:));
297  /* 1: order, 2: errororder */
298  tri = delaunay(res(1,:),res(2,:));
299 
300  /* 3: max abs true error (indep. of errororder) */
301  h = pm.nextPlot(" true_abs "," Linf-L2 absolute error "," m "," m ");
302  semilogy(h,orders,res(3,idx));
303  /* doplot(h,tri,res(1,:),res(2,:),res(3,:));
304  * 7: max abs estimated error */
305  h = pm.nextPlot(" est_abs "," Estimated absolute error "," m "," m ");
306  doplot(h,tri,res(1,:),res(2,:),res(7,:)," EdgeColor "," none ");
307 
308  /* 4: max rel true error w.r.t true fxi norm (indep. of errororder) */
309  h = pm.nextPlot(" true_rel "," Linf-L2 relative error "," m "," m ");
310  semilogy(h,orders,res(4,idx));
311  /* doplot(h,tri,res(1,:),res(2,:),res(4,:));
312  * 8: max rel estimated error w.r.t true fxi norm */
313  h = pm.nextPlot(" est_rel "," Estimated relative error "," m "," m ");
314  doplot(h,tri,res(1,:),res(2,:),res(8,:)," EdgeColor "," none ");
315 
316  /* % Reduced Triplots */
317  n = size(res,2);
318  /* sel = 1:step:n;
319  *sel = round(logspace(log10(1),log10(n),300)); */
320  sel = [1 2 3 4 5 7 9 11 13 15:3:30 31:20:n];
321  res = res(:,sel);
322  n = size(res,2);
323  /* 1: order
324  * 2: errororder */
325  tri = delaunay(res(1,:),res(2,:));
326 
327  /* 11: max rel error of (estimated-true error) w.r.t true error
328  * 12: mean rel error of (estimated-true error) w.r.t true error */
329  h = pm.nextPlot(" max_relerr_est_true_totrue "," 'max (true - estimated)/true' relative error "," m "," m ");
330  doplot(h,tri,res(1,:),res(2,:),res(11,:));
331  hold on;
332  sh = doplot(h,tri,res(1,:),res(2,:),1e-2*ones(1,n),...
333  " EdgeColor "," none "," FaceColor "," k ");
334  alpha(sh,.2);
335  hold off;
336  axis ij;
337  h = pm.nextPlot(" mean_relerr_est_true_totrue "," 'mean (true - estimated)/true' relative error "," m "," m ");
338  doplot(h,tri,res(1,:),res(2,:),res(12,:));
339  hold on;
340  sh = doplot(h,tri,res(1,:),res(2,:),1e-2*ones(1,n),...
341  " EdgeColor "," none "," FaceColor "," k ");
342  alpha(sh,.2);
343  hold off;
344  axis ij;
345  view(-40,34);
346 
347  /* 13: max rel error of (estimated-maxorder error) w.r.t maxorder error
348  * 14: mean rel error of (estimated-maxorder error) w.r.t maxorder error */
349  h = pm.nextPlot(" max_relerr_est_emaxo_toemaxo "," 'max (maxordererror - estimated)/maxordererror' relative error "," m "," m ");
350  doplot(h,tri,res(1,:),res(2,:),res(13,:));
351  hold on;
352  sh = doplot(h,tri,res(1,:),res(2,:),1e-2*ones(1,n),...
353  " EdgeColor "," none "," FaceColor "," k ");
354  alpha(sh,.2);
355  hold off;
356  axis ij;
357  h = pm.nextPlot(" mean_relerr_est_emaxo_toemaxo "," 'mean (maxordererror - estimated)/maxordererror' relative error "," m "," m ");
358  doplot(h,tri,res(1,:),res(2,:),res(14,:));
359  hold on;
360  sh = doplot(h,tri,res(1,:),res(2,:),1e-2*ones(1,n),...
361  " EdgeColor "," none "," FaceColor "," k ");
362  alpha(sh,.2);
363  hold off;
364  axis ij;
365  view(-40,34);
366 
367  h = pm.nextPlot(" abs_diff_est_true "," Absolute difference of estimated to true error "," m "," m ");
368  doplot(h,tri,res(1,:),res(2,:),abs(res(3,:)-res(7,:)));
369  view(75,34);
370 
371  pm.done;
372 
373  function p = doplot(h, tri, x, y, z, varargin)
374  p = LogPlot.logtrisurf(h, tri, x, y, z, varargin[:]);
375 /* hold on;
376  * [~, hc] = tricontour([x; y]', tri, z', get(h,'ZTick'));
377  * set(hc,'EdgeColor','k');
378  * hold off; */
379  view(0,0);
380  end
381  }
382 
383 
384  static function [doublet , nof , nor , o , pm ] = jacobian_tests(m,pm) {
385  atd = m.Data.JacobianTrainData;
386  n = min(size(atd.xi,2),500);
387  sp = logical(m.System.f.JSparsityPattern);
388  M = 3;
389  o = round(linspace(1,m.Approx.MaxOrder,M));
390  t = zeros(M,n);
391  nof = t;
392  nor = t;
393  r = m.buildReducedModel;
394  for k = 1:M
395  m.Approx.Order= o(k);
396  r.System.f.Order= o(k);
397  for i = 1:n
398  x = atd.xi(:,i);
399  z = m.Data.W^t*x;
400  x = m.Data.V*z;
401  aj = m.Approx.getStateJacobian(x,atd.ti(i),atd.mui(:,i));
402  j = m.System.f.getStateJacobian(x,atd.ti(i),atd.mui(:,i));
403  rj = r.System.f.getStateJacobian(z,atd.ti(i),atd.mui(:,i));
404  hlp = abs((aj-j)./j);
405  hlp(~sp) = 0;
406  t(k,i) = max(hlp(:));
407  nof(k,i) = norm(full(j));
408  nor(k,i) = norm(rj);
409  end
410  end
411  if nargin < 2
412  pm = PlotManager(false,3,1);
413  end
414  h = pm.nextPlot(" max_rel_err ",sprintf(" Maximum relative errors of DEIM jacobian vs. original one\nmasked to sparsity pattern "));
415  plot(h,t^t)
416  lbl = arrayfun(@(e)sprintf(" %d ",e),o," Uniform ",false);
417  legend(h, lbl[:]);
418 
419  h = pm.nextPlot(" jfull_norm "," Full Jacobian norms "," snapshot "," L2 matrix norm ");
420  plot(h,nof^t);
421  legend(h, lbl[:]);
422 
423  h = pm.nextPlot(" jred_norm "," Reduced Jacobian norms "," snapshot "," L2 matrix norm ");
424  plot(h,nor^t);
425  legend(h, lbl[:]);
426 
427  pm.done;
428  }
446  static function [efull , ered , fxno ] = getApproxErrorFullRed(r,xr,double t,colvec<double> mu,V) {
447  fm = r.FullModel;
448  fm.Approx.Order= r.System.f.Order;
449  fx = fm.System.f.evaluate(V*xr,t,mu);
450  efull = Norm.L2(fx-r.FullModel.Approx.evaluate(V*xr,t,mu));
451  ered = Norm.L2(fx-V*r.System.f.evaluate(xr,t,mu));
452  fxno = Norm.L2(fx);
453  }
454 
455 
456  static function [etrue , EE , ED , pm ] = getTrajApproxErrorDEIMEstimates(models.ReducedModel r,colvec<double> mu,integer inputidx) {
457  fm = r.FullModel;
458  if nargin < 3
459  inputidx = fm.TrainingInputs;
460  if nargin < 2
461  mu = fm.Data.ParamSamples;
462  end
463  end
464  f = fm.Approx;
465  olde = f.Order(2); /* store old setting */
466 
467  o = f.Order(1);
468  mo = f.MaxOrder;
469 
470  num_mu = max(1,size(mu,2));
471  num_in = max(1,length(inputidx));
472  etrue = zeros(num_mu*num_in,length(fm.Times));
473  EE = zeros(mo-o,length(fm.Times),num_mu*num_in);
474  ED = EE;
475 
476  ma = ModelAnalyzer(r);
477 
478  /* Assume no parameters or inputs */
479  curmu = [];
480  curin = [];
481  for eo = 1:mo-o
482  f.Order= [o eo];
483  /* Iterate through all input functions */
484  cnt = 1;
485  for inidx = 1:num_in
486  /* Iterate through all parameter samples */
487  for muidx = 1:num_mu
488  /* Check for inputs */
489  if ~isempty(inputidx)
490  curin = inputidx(inidx);
491  end
492  /* Check for parameters */
493  if size(mu,2) > 0
494  curmu = mu(:,muidx);
495  end
496 
497  [curetrue, ~, t, x] = ma.getTrajApproxError(curmu, curin);
498  eest = Norm.L2(f.getEstimatedError(x, t, repmat(curmu,1,length(t))));
499  EE(eo,:,cnt) = eest;
500  ED(eo,:,cnt) = abs(eest - curetrue);
501  etrue(cnt,:) = curetrue;
502  cnt = cnt+1;
503  end
504  end
505  end
506  f.Order= [o olde]; /* restore old setting */
507 
508 
509  if nargout == 4
510  pm = testing.DEIM.getTrajApproxErrorDEIMEstimates_plots(r, etrue(1,:), EE(:,:,1), ED(:,:,1));
511  end
512  }
543  static function pm = getTrajApproxErrorDEIMEstimates_plots(r,etrue,EE,ED,pm) {
544  f = r.FullModel.Approx;
545  o = f.Order(1);
546  mo = f.MaxOrder;
547  if nargin < 6
548  pm = PlotManager(false,2,2);
549  end
550  t = r.Times;
551  h = pm.nextPlot(" true_err "," True approximation error on trajectory "," time "," error ");
552  semilogy(h,t,etrue);
553  h = pm.nextPlot(" est_err ",sprintf(" Estimated approximation errors on trajectory\nDEIM order = %d / max %d ",f.Order(1),f.MaxOrder),...
554  " time ", " DEIM error order ");
555  [T,O] = meshgrid(t,1:mo-o);
556  LogPlot.logsurf(h,T,O,EE," EdgeColor "," none ");
557  view(-45,45);
558 
559  h = pm.nextPlot(" abs_diff ",sprintf(" Difference true to estimated error\nDEIM order = %d / max %d ",f.Order(1),f.MaxOrder),...
560  " time "," DEIM error order ");
561  LogPlot.logsurf(h,T,O,ED," EdgeColor "," none ");
562  view(-135,45);
563 
564  h = pm.nextPlot(" rel_diff ",sprintf(" Relative error between true to estimated error\nDEIM order = %d / max %d ",f.Order(1),f.MaxOrder),...
565  " time "," DEIM error order ");
566  LogPlot.logsurf(h,T,O,ED./repmat(etrue,mo-o,1)," EdgeColor "," none "," FaceColor "," interp ");
567  hold on;
568  p = surf(h,T,O,-ones(size(T))*2," EdgeColor "," red "," FaceColor "," k ");
569  alpha(p,.2);
570  view(-135,45);
571  hold off;
572  pm.done;
573  }
587  static function [doublet , values ] = getMinReqErrorOrdersTable(errordata,relerrs,tsize,maxorder) {
588  if nargin == 4
589  txt = sprintf(" DEIM MaxOrder %d error ",maxorder);
590  maxvidx = 13;
591  meanvidx = 14;
592  else
593  txt = " true DEIM error ";
594  maxvidx = 11;
595  meanvidx = 12;
596  end
597  t = PrintTable(" Required M "" over %d training samples for min/mean errors relative to %s ",...
598  tsize,txt);
599  t.HasHeader= true;
600  title = arrayfun(@(e)sprintf(" %g ",e),relerrs," Unif ",false);
601  t.addRow(" m / rel. error ",title[:]);
602  nr = length(relerrs);
603  orders = unique(errordata(1,:));
604  values = zeros(length(orders),1+2*nr);
605  for i = 1:length(orders)
606  o = orders(i);
607  values(i,1) = o;
608  pos = errordata(1,:) == o;
609  maxv = errordata(maxvidx,pos);
610  meanv = errordata(meanvidx,pos);
611  hlp = cell.empty(0,nr);
612  for j = 1:nr
613  /* Max rel errs */
614  maxidx = find(maxv <= relerrs(j),1," first ");
615  if isempty(maxidx),
616  maxidx = min(maxv);
617  end
618  /* Mean rel errs */
619  meanidx = find(meanv <= relerrs(j),1," first ");
620  if isempty(meanidx),
621  meanidx = min(meanv);
622  end
623  hlp[j] = sprintf(" %g/%g ",maxidx,meanidx);
624  values(i,1+[j j+nr]) = [maxidx meanidx];
625  end
626  t.addRow(o,hlp[:]);
627  end
628  if nargout < 1
629  t.display;
630  end
631  }
647  static function [matrix<double>mui , fxi , afxi ] = getDEIMErrorsAtXForParams(models.BaseFullModel m,colvec<double> x,integer numExtraSamples) {
648  if nargin < 3
649  numExtraSamples = 0;
650  end
651  mui = m.Data.ParamSamples;
652  s = sampling.RandomSampler;
653  s.Seed= 1;
654  s.Samples= numExtraSamples;
655  mui = [mui s.generateSamples(m)];
656  xi = repmat(x,1,size(mui,2));
657  ti = zeros(1,size(mui,2));
658  fxi = m.System.f.evaluate(xi,ti,mui);
659  afxi = m.Approx.evaluate(xi,ti,mui);
660  }
676  static function pm = getDEIMErrorsAtXForParams_plots(m,matrix<double> mui,fxi,afxi,pm) {
677  if nargin < 5
678  pm = PlotManager;
679  pm.LeaveOpen= true;
680  end
681 
682  tri = delaunay(mui(1,:),mui(2,:));
683 
684  err = Norm.L2(fxi-afxi);
685  h = pm.nextPlot(" abserr "," Absolute errors over mu range ");
686  /* trisurf(tri,mui(1,:),mui(2,:),err,'Parent',h); */
687  LogPlot.logtrisurf(h,tri,mui(1,:),mui(2,:),err);
688  n = m.Data.SampleCount;
689  hold on;
690  plot3(mui(1,1:n),mui(2,1:n),log10(err(1:n))," rx "," MarkerSize ",16);
691  view(-8,-20);
692  hold off;
693 
694  err = Norm.L2(fxi-afxi)./Norm.L2(fxi);
695  h = pm.nextPlot(" relerr "," Relative errors over mu range ");
696  /* trisurf(tri,mui(1,:),mui(2,:),err,'Parent',h); */
697  LogPlot.logtrisurf(h,tri,mui(1,:),mui(2,:),err);
698  n = m.Data.SampleCount;
699  hold on;
700  plot3(mui(1,1:n),mui(2,1:n),log10(err(1:n))," rx "," MarkerSize ",16);
701  hold off;
702  view(0,0);
703  }
704 
705 
706  static function [errs , relerrs , times , rowvec<integer>deim_orders ] = getDEIMReducedModelErrors(models.ReducedModel r,colvec<double> mu,integer inidx,rowvec<integer> deim_orders) {
707  d = r.System.f;
708  if nargin < 4
709  deim_orders = 1:(d.MaxOrder-r.System.f.Order(2));
710  end
711  oldo = d.Order;
712  no = length(deim_orders);
713  errs = zeros(no,length(r.Times));
714  relerrs = errs;
715  times = zeros(no+1,1);
716  [~, y, ct] = r.FullModel.simulate(mu, inidx);
717  times(end) = ct;
718  pi = ProcessIndicator(" Computing DEIM-reduced model simulation errors for %d orders ",no,false,no);
719  for m = 1:no
720  r.System.f.Order= [deim_orders(m) r.System.f.Order(2)];
721  [~, ~, ct] = r.simulate(mu, inidx);
722  errs(m,:) = r.ErrorEstimator.OutputError;
723  relerrs(m,:) = errs(m,:)./Norm.L2(y);
724  times(m) = ct;
725  pi.step;
726  end
727  pi.stop;
728  d.Order= oldo;
729  }
744  static function pm = getDEIMReducedModelErrors_plots(r,errs,relerrs,times,deim_orders,pm,tag) {
745  if nargin < 7
746  tag = ;
747  if nargin < 6
748  pm = PlotManager(false);
749  end
750  else
751  ftag = [tag " _ "];
752  end
753  [X, Y] = meshgrid(r.Times, deim_orders);
754  h = pm.nextPlot([ftag " abserr "],sprintf([" L2-absolute reduction errors\n "...
755  " (Linf in time for original view), tag: " tag]),...
756  " time "," DEIM order ");
757  LogPlot.logsurf(h,X,Y,errs," EdgeColor "," interp ");
758  view(90,0);
759 
760  h = pm.nextPlot([ftag " relerr "],[" L2-relative reduction errors, tag: " tag],...
761  " time "," DEIM order ");
762  LogPlot.logsurf(h,X,Y,relerrs," EdgeColor "," interp ");
763  view(-120,30);
764 
765 /* h = pm.nextPlot([ftag 'ctimes'],'Computation times for reduced models',...
766  * 'DEIM order');
767  * plot(h,deim_orders,times(1:end-1));
768  *
769  * h = pm.nextPlot([ftag 'speedup'],...
770  * sprintf('Speedup against full model simulation of %gs',times(end)),...
771  * 'DEIM order');
772  * plot(h,deim_orders,times(end)./times(1:end-1));
773  *
774  * if nargout == 0
775  * pm.done;
776  * end */
777  }
778 
779 
780  static function [e , aln , rowvec<integer>orders ] = compareDEIM_Full_Jacobian(models.BaseFullModel m,data.ApproxTrainData atd,rowvec<integer> orders) {
781  deim = m.ErrorEstimator.JacMDEIM;
782  if nargin < 3
783  orders = 1:deim.MaxOrder;
784  if nargin < 2
785  atd = m.Data.JacobianTrainData;
786  end
787  end
788  mo = length(orders);
789  n = size(atd.xi,2);
790  e = zeros(mo,n,3);
791  aln = zeros(mo,n);
792  oldo = deim.Order;
793  Qk = deim.Qk;
794  deim.setSimilarityTransform([]);
795  pi = ProcessIndicator(" Computing matrix DEIM approximation error and log norm errors for %d orders ",mo,false,mo);
797  for o = 1:mo
798  deim.Order= o;
799  for i=1:n
800  ti = atd.ti(i); mui = atd.mui(:,i);
801  J = m.System.f.getStateJacobian(atd.xi(:,i),ti,mui);
802  DJ = reshape(deim.evaluate(m.Data.V^t*atd.xi(:,i),ti,mui),...
803  size(J,1),[]);
804  diff = J-DJ;
805  diff = diff(JP);
806  e(o,i,1) = max(max(abs(diff)));
807  e(o,i,2) = Norm.L2(diff);
808  e(o,i,3) = mean(abs(diff));
809  e(o,i,4) = var(diff);
810 
811  /* Get log norm */
812  aln(o,i) = Utils.logNorm(DJ);
813  end
814  pi.step;
815  end
816  pi.stop;
817  deim.Order= oldo;
818  deim.setSimilarityTransform(Qk);
819  }
836  static function pm = compareDEIM_Full_Jacobian_plots(m,e,aln,orders,pm,atdsubset) {
837  if nargin < 5 || isempty(pm)
838  pm = PlotManager(false,1,2);
839  end
840  co = " none ";
841  td = 1:size(e,2);
842  [X,Y] = meshgrid(td,orders);
843  e = sort(e,2);
844  h = pm.nextPlot(" max_diff "," Maximum absolute difference ",...
845  " trajectory point "," DEIM order ");
846  LogPlot.logsurf(h,X,Y,e(:,:,1)," EdgeColor ",co);
847  h = pm.nextPlot(" max_diff_mean "," Mean maximum absolute difference "," DEIM order ");
848  semilogy(h,orders,mean(e(:,:,1),2));
849 
850  h = pm.nextPlot(" l2_diff "," L2 vector difference ",...
851  " trajectory point "," DEIM order ");
852  LogPlot.logsurf(h,X,Y,e(:,:,2)," EdgeColor ",co);
853  h = pm.nextPlot(" l2_diff_mean "," Mean L2 vector difference "," DEIM order ");
854  semilogy(h,orders,mean(e(:,:,2),2));
855 
856  h = pm.nextPlot(" mean_diff "," Mean difference value ",...
857  " trajectory point "," DEIM order ");
858  LogPlot.logsurf(h,X,Y,e(:,:,3)," EdgeColor ",co);
859  h = pm.nextPlot(" mean_diff_mean "," Mean mean difference value "," DEIM order ");
860  semilogy(h,orders,mean(e(:,:,3),2));
861 
862  h = pm.nextPlot(" var_diff "," Variance of difference ",...
863  " trajectory point "," DEIM order ");
864  LogPlot.logsurf(h,X,Y,e(:,:,4)," EdgeColor ",co);
865  h = pm.nextPlot(" var_diff_mean "," Mean variance of difference "," DEIM order ");
866  semilogy(h,orders,mean(e(:,:,4),2));
867 
868  ln = m.Data.JacSimTransData.LogNorms;
869  if length(ln) ~= size(aln,2)
870  ln = ln(atdsubset);
871  end
872  ln = repmat(ln,length(orders),1);
873  err = sort(abs(ln-aln),2);
874  h = pm.nextPlot(" log_norm_diff "," Differences of logarithmic norms ",...
875  " trajectory point "," DEIM order ");
876  LogPlot.logsurf(h,X,Y,err," EdgeColor "," none ");
877 
878  err = sort(abs((ln-aln) ./ ln),2);
879  h = pm.nextPlot(" log_norm_diff "," Differences of logarithmic norms ",...
880  " trajectory point "," DEIM order ");
881  LogPlot.logsurf(h,X,Y,err," EdgeColor "," none ");
882 
883  if nargout < 1
884  pm.done;
885  end
886  }
887 
888 
890  pm = PlotManager(false,2,1);
891  pm.SingleSize= [720 540];
892  pm.LeaveOpen= true;
893  [~,y] = r.FullModel.simulate(mu,inputidx);
894  [t,yr] = r.simulate(mu,inputidx);
895  err = Norm.L2(y-yr);
896  h = pm.nextPlot(" errors "," True and estimated error "," time "," error ");
897  semilogy(h,t,err," b ",t,r.ErrorEstimator.OutputError," r ");
898  h = pm.nextPlot(" errors "," True and estimated error "," time "," error ");
899  semilogy(h,t,r.ErrorEstimator.OutputError./err," g ");
900  }
917  static function structest = getDEIMEstimators_MDEIM_ST(models.ReducedModel rmodel,struct est,rowvec<integer> jdorders,rowvec<integer> stsizes) {
918  if nargin < 3
919  stsizes = [1 10];
920  if nargin < 2
921  jdorders = [1 10];
922  end
923  end
924  li = LineSpecIterator(length(jdorders)*length(stsizes)+4,1);
925  for i = 1:length(est)
926  li.excludeColor(est(i).Color);
927  end
928 
929  /* Different configurations */
930  e = rmodel.ErrorEstimator.clone;
931  for j = 1:length(jdorders)
932  cl = li.nextLineStyle;
933  li2 = LineSpecIterator;
934  for k = 1:length(stsizes)
935  str = sprintf(" e.JacMDEIM.Order = %d; e.JacSimTransSize = %d; ",...
936  jdorders(j),stsizes(k));
937  est(end+1).Name = sprintf(" $m_J:%d, k:%d$ ",...
938  jdorders(j),stsizes(k));/* #ok */
939 
940  est(end).Estimator = e;
941  est(end).Callback = @(e)eval(str);
942  est(end).MarkerStyle = li2.nextMarkerStyle;
943  est(end).LineStyle = cl;
944  est(end).Color = li.nextColor;
945  end
946  end
947  }
965  static function est = getDEIMEstimators_ErrOrders(models.ReducedModel rmodel,est,errororders) {
966  if nargin < 2
967  errororders = [1 2 5];
968  end
969  m = LineSpecIterator(2+length(errororders));
970  for i = 1:length(est)
971  m.excludeColor(est(i).Color);
972  end
973  /* Different configurations */
974  e = rmodel.ErrorEstimator.clone; /* need only one copy! */
975 
976  for j = 1:length(errororders)
977  str = sprintf(" e.ReducedModel.System.f.Order = [e.ReducedModel.System.f.Order(1) %d]; ",errororders(j));
978  est(end+1).Name = sprintf(" $m "" =%d$ ",errororders(j));/* #ok */
979 
980  est(end).Estimator = e;
981  est(end).Callback = @(e)eval(str);
982  est(end).MarkerStyle = m.nextMarkerStyle;
983  est(end).LineStyle = " -. ";
984  est(end).Color = m.nextColor;
985  end
986  }
987 
988 
989 };
990 }
991 
992 
ModelAnalyzer: Analysis tools for reduced models and approximations.
Definition: ModelAnalyzer.m:17
Collection of generally useful functions.
Definition: Utils.m:17
static function res = computeDEIMErrors(general.DEIM deim,data.ApproxTrainData atd,rowvec< integer > orders,rowvec< integer > errorders)
% DEIM approximation analysis over training data Computes the DEIM approximation error over the given...
Definition: DEIM.m:146
function copy = clone(copy)
Creates a copy of this error estimator. Call only allowed from subclasses.
DEIM(sys, dim)
Definition: DEIM.m:47
static function [ matrix< double > mui , fxi , afxi ] = getDEIMErrorsAtXForParams(models.BaseFullModel m,colvec< double > x,integer numExtraSamples)
% DEIM approximation analysis over parameters for specific state space location
Definition: DEIM.m:647
integer fDim
The current output dimension of the function.
Definition: ACoreFun.m:171
DEIM: Implements the DEIM-Algorithm from .
Definition: DEIM.m:18
data.FileMatrix xi
The state space samples , stored row-wise in a data.FileMatrix instance.
LogPlot: Class with static functions for logarithmic plotting.
Definition: LogPlot.m:17
function err = getEstimatedError(colvec< double > x,double t,colvec< double > mu)
Definition: DEIM.m:356
data.FileMatrix fxi
The evaluations of , stored row-wise in a data.FileMatrix.
function pos = getBlockPos(nr)
Returns the column indices of the block "nr" within the full matrix.
Definition: FileMatrix.m:314
error.BaseEstimator ErrorEstimator
The associated error estimator for this model.
static function est = getDEIMEstimators_ErrOrders(models.ReducedModel rmodel, est, errororders)
Definition: DEIM.m:965
The base class for any KerMor detailed model.
Definition: BaseFullModel.m:18
models.BaseFullModel FullModel
The full model this reduced model was created from.
Definition: ReducedModel.m:53
function J = getStateJacobian(x, t)
Default implementation of jacobian matrix evaluation via finite differences.
Definition: ACoreFun.m:395
models.BaseFirstOrderSystem System
The actual dynamical system used in the model.
Definition: BaseModel.m:102
Times
Evaluation points of the model.
Definition: BaseModel.m:206
A MatLab cell array or matrix.
integer MaxOrder
The maximum order up to which the DEIM approximation should be computed.
Definition: DEIM.m:60
OutputError
The output error from the last simulation.
static function pm = effectivityAnalysis(models.ReducedModel r,colvec< double > mu,integer inputidx)
% Effectivity analysis of error estimators Plots an effectivity graph for the current error estimator...
Definition: DEIM.m:889
function fx = evaluate(colvec< double > x,double t)
Definition: DEIM.m:303
sort
ort the handle objects in any array in ascending or descending order.
reshape
hanges the dimensions of the handle object array to the specified dimensions. See the MATLAB reshape ...
static function handle p = logtrisurf(handle h, tri,rowvec< double > x,rowvec< double > y,rowvec< double > z, varargin)
Creates a surface plot from a 2D triangulation in a logarithmic scale.
Definition: LogPlot.m:136
matrix ParamSamples
A Model's parameter samples as column vector collection.
Definition: ModelData.m:53
An integer value.
The KerMor reduced model class.
Definition: ReducedModel.m:18
static function pm = getTrajApproxErrorDEIMEstimates_plots(r, etrue, EE, ED, pm)
Visualizes the results of the ModelAnalyzer.getTrajApproxErrorDEIMEstimates method.
Definition: DEIM.m:543
static function [ double t , nof , nor , o , pm ] = jacobian_tests(m, pm)
Tis function computes the jacobians of both the full and DEIM approximated system functions...
Definition: DEIM.m:384
rowvec< integer > Order
The actual order for the current DEIM approximation.
Definition: DEIM.m:81
PlotManager: Small class that allows the same plots generated by some script to be either organized a...
Definition: PlotManager.m:17
static function handle p = logsurf(handle h,matrix< double > X,matrix< double > Y,matrix< double > Z, varargin)
Creates a nice surface plot in a logarithmic scale with the given data.
Definition: LogPlot.m:79
rowvec ti
The time samples .
A boolean value.
function fx = evaluateComponents(pts, ends, idx, self,colvec< double > x,double t)
Definition: DEIM.m:67
logical LeaveOpen
Flag indicating if the plots should be left open once the PlotManager is deleted (as variable) ...
Definition: PlotManager.m:213
A variable number of input arguments.
integer xDim
The current state space dimension of the function's argument .
Definition: ACoreFun.m:151
error.BaseEstimator ErrorEstimator
The error estimator for the reduced model.
Definition: ReducedModel.m:118
static function [ etrue , EE , ED , pm ] = getTrajApproxErrorDEIMEstimates(models.ReducedModel r,colvec< double > mu,integer inputidx)
[etrue, EE, ED, pm] = getTrajApproxErrorDEIMEstimates(this, mu, inputidx) Computes the DEIM approxima...
Definition: DEIM.m:456
V
The matrix of the biorthogonal pair .
Definition: AProjectable.m:61
colvec< double > mu
The current model parameter mu for evaluations. Will not be persisted as only valid for runtime durin...
Definition: ACoreFun.m:208
static function [ e , aln , rowvec< integer > orders ] = compareDEIM_Full_Jacobian(models.BaseFullModel m,data.ApproxTrainData atd,rowvec< integer > orders)
% Matrix DEIM approximation analysis Compares the MDEIM approximation with the full jacobian ...
Definition: DEIM.m:780
approx.BaseApprox Approx
The approximation method for the CoreFunction.
#define X(i, j)
data.ModelData Data
The full model's data container. Defaults to an empty container.
function fx = evaluate(x, t)
Evaluates the f-approximation. Depending on a possible projection and the CustomProjection-property t...
Definition: ACoreFun.m:296
static function pm = plotDEIMErrs(res, pm)
Definition: DEIM.m:283
integer m
The total number of columns.
Definition: FileMatrix.m:126
PrintTable: Class that allows table-like output spaced by tabs for multiple rows. ...
Definition: PrintTable.m:17
static function [ errs , relerrs , times , rowvec< integer > deim_orders ] = getDEIMReducedModelErrors(models.ReducedModel r,colvec< double > mu,integer inidx,rowvec< integer > deim_orders)
% Model DEIM reduction quality assessment pics
Definition: DEIM.m:706
sparse< logical > JSparsityPattern
Sparsity pattern for the jacobian matrix.
Definition: ACoreFun.m:127
matrix mui
The parameter samples used computing the parent trajectories of .
static function [ double t , values ] = getMinReqErrorOrdersTable(errordata, relerrs, tsize, maxorder)
Return values: t: A PrintTable containing the results. If not specified as a nargout argument...
Definition: DEIM.m:587
static function analysis_DEIM_approx(m)
Definition: DEIM.m:112
dscomponents.ACoreFun f
The core f function from the dynamical system.
ACompEvalCoreFun: A normal CoreFun which supports single-component evaluation.
static function struct est = getDEIMEstimators_MDEIM_ST(models.ReducedModel rmodel,struct est,rowvec< integer > jdorders,rowvec< integer > stsizes)
% Error estimator struct compilation Computes a set of DEIMEstimators for given MDEIM orders and simt...
Definition: DEIM.m:917
integer nBlocks
The number of blocks into which this matrix is separated.
Definition: FileMatrix.m:95
static function pm = compareDEIM_Full_Jacobian_plots(m, e, aln, orders, pm, atdsubset)
Definition: DEIM.m:836
data.ApproxTrainData JacobianTrainData
Training data for the jacobian approximation.
Definition: ModelData.m:120
#define Y(i, j)
static function rowvec< double > n = L2(matrix< double > x)
Returns the discrete norm for each column vector in x.
Definition: Norm.m:39
function fx = evaluateCoreFun(unused1,double t)
Definition: DEIM.m:60
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
function fx = evaluateComponentsMulti(pts, ends, idx, self,colvec< double > x,double t,colvec< double > mu)
Definition: DEIM.m:72
ApproxTrainData: Data class for approximation training data, containing several useful bounding box p...
DEIM: Tests regarding the DEIM method.
Definition: DEIM.m:18
Norm: Static class for commonly used norms on sets of vectors.
Definition: Norm.m:17
LinSpecIterator: Small helper class to automatically iterate through different line styles/markers/co...
static function res = test_DEIMNoSpatialDependence()
Definition: DEIM.m:80
static function pm = getDEIMReducedModelErrors_plots(r, errs, relerrs, times, deim_orders, pm, tag)
Definition: DEIM.m:744
static function [ efull , ered , fxno ] = getApproxErrorFullRed(r, xr,double t,colvec< double > mu, V)
Definition: DEIM.m:446
function [ rowvec< double > t , matrix< double > y , double sec , x ] = simulate(colvec< double > mu,integer inputidx)
Simulates the system and produces the system's output.
Definition: BaseModel.m:477
ProcessIndicator: A simple class that indicates process either via waitbar or text output...
static function pm = getDEIMErrorsAtXForParams_plots(m,matrix< double > mui, fxi, afxi, pm)
Definition: DEIM.m:676