Discrete.m 71.9 KB
Newer Older
1
classdef  (InferiorClasses = {?quantity.Symbolic}) Discrete < handle & matlab.mixin.Copyable
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
	properties (SetAccess = protected)
		% Discrete evaluation of the continuous quantity
		valueDiscrete double;
		
		% Name of the domains that generate the grid.
		gridName {mustBe.unique};
		
		% In this cell, already computed derivatives can be stored to avoid
		% multiple computations of the same derivative.
		derivatives cell = {};
	end
	
	properties (Hidden, Access = protected, Dependent)
		doNotCopy;
	end
	
	properties
19
20
21
22
23
24
25
26
		% Grid for the evaluation of the continuous quantity. For the
		% example with the function f(x,t), the grid would be
		%   {[<spatial domain>], [<temporal domain>]}
		% whereas <spatial domain> is the discret description of the
		% spatial domain and <temporal domain> the discrete description of
		% the temporal domain.
		grid; % in set.grid it is ensured that, grid is a (1,:)-cell-array
		
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
		% ID of the figure handle in which the handle is plotted
		figureID double = 1;
		
		% Name of this object
		name char;
	end
	
	methods
		%--------------------
		% --- Constructor ---
		%--------------------
		function obj = Discrete(valueOriginal, varargin)
			% The constructor requires valueOriginal to be
			% 1) a cell-array of double arrays with
			%	size(valueOriginal) == size(obj) and
			%	size(valueOriginal{it}) == gridSize
			% OR
			% 2) adouble-array with
			%	size(valueOriginal) == [gridSize, size(quantity)] 
			% Furthermore, 'gridName' must be part of the name-value-pairs
			% in varargin. Additional parameters can be specified using
			% name-value-pair-syntax in varargin.
			
			% to allow the initialization as object array, the constructor
51
52
53
54
55
			% must be allowed to be called without arguments, i.e. nargin == 0.
			% Then no parameters are set.
			if nargin == 1
				% if nargin == 1 it can be a conversion of child-classes or an empty
				% object
56
57
58
59
60
				if isa(valueOriginal, 'quantity.Discrete')
					% allows the conversion of a quantity object without
					% extra check if the object is already from class
					% quantity.Discrete
					obj = valueOriginal;
61
62
63
64
65
				else
					% empty object. this is neede for instance, to create
					% quantity.Discrete([]), which is useful for creating default 
					% values.
					obj = quantity.Discrete.empty(size(valueOriginal));
66
				end
67
			elseif nargin > 1
68
69
70
				
				%% input parser
				myParser = misc.Parser();
71
				myParser.addParameter('gridName', [], @(g) ischar(g) || iscell(g));
72
73
74
				myParser.addParameter('grid', [], @(g) isnumeric(g) || iscell(g));
				myParser.addParameter('name', string(), @isstr);
				myParser.addParameter('figureID', 1, @isnumeric);
75
76
77
78
79
80
81
82
83
84
				myParser.parse(varargin{:});
				assert(all(~contains(myParser.UsingDefaults, 'gridName')), ...
					'gridName is a mandatory input for quantity');
				
				if iscell(myParser.Results.gridName)
					myGridName = myParser.Results.gridName;
				else
					myGridName = {myParser.Results.gridName};
				end
				
85
86
87
88
89
90
91
92
93
94
95
96
97
				%% allow initialization of empty objects:
				valueOriginalSize = size(valueOriginal);
				if any(valueOriginalSize == 0)
					% If the size is specified in the arguements, it should
					% be chosen instead of the default size from the
					% valueOriginal.
					myParser = misc.Parser();
					myParser.addParameter('size', valueOriginalSize((1+numel(myGridName)):end));
					myParser.parse(varargin{:});
					obj = quantity.Discrete.empty(myParser.Results.size);
					return;
				end
				
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
				%% get the sizes of obj and grid
				if iscell(valueOriginal)
					if isempty(valueOriginal{1})
						% if valueOriginal is a cell-array with empty
						% cells, then grid must be specified as an input
						% parameter. This case is important for
						% constructing Symbolic or Function quantities
						% without discrete values.
						assert(all(~contains(myParser.UsingDefaults, 'grid')), ...
							['grid is a mandatory input for quantity, ', ...
							'if no discrete values are specified']);
						if ~iscell(myParser.Results.grid)
							gridSize = numel(myParser.Results.grid);
						else
							gridSize = cellfun(@(v) numel(v), myParser.Results.grid);
						end
					else
						gridSize = size(valueOriginal{1});
					end
					objSize = size(valueOriginal);
				elseif isnumeric(valueOriginal)
					gridSize = valueOriginalSize(1 : numel(myGridName));
					objSize = [valueOriginalSize(numel(myGridName)+1 : end), 1, 1];
				end
				
				%% get grid and check size
				if any(contains(myParser.UsingDefaults, 'grid'))
					myGrid = quantity.Discrete.defaultGrid(gridSize);
				else
					myGrid = myParser.Results.grid;
				end
				if ~iscell(myGrid)
					myGrid = {myGrid};
				end
				if isempty(myGridName) || isempty(myGrid)
					if ~(isempty(myGridName) && isempty(myGrid))
Jakob Gabriel's avatar
Jakob Gabriel committed
134
						error(['If one of grid and gridName is empty, ', ...
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
							'then both must be empty.']);
					end
				else
					assert(isequal(size(myGrid), size(myGridName)), ...
						'number of grids and gridNames must be equal');
					myGridSize = cellfun(@(v) numel(v), myGrid);
					assert(isequal(gridSize(gridSize>1), myGridSize(myGridSize>1)), ...
						'grids do not fit to valueOriginal');
				end
				
				%% set valueDiscrete
				if ~iscell(valueOriginal)
					valueOriginal = quantity.Discrete.value2cell(valueOriginal, gridSize, objSize);
				end
				for k = 1:prod(objSize)
					if numel(myGrid) == 1
						obj(k).valueDiscrete = valueOriginal{k}(:);
					else
						obj(k).valueDiscrete = valueOriginal{k};
					end
				end
				
				%% set further properties
				[obj.grid] = deal(myGrid);
				[obj.gridName] = deal(myGridName);
				[obj.name] = deal(myParser.Results.name);
				[obj.figureID] = deal(myParser.Results.figureID);
				
				%% reshape object from vector to matrix
				obj = reshape(obj, objSize);
			end
		end% Discrete() constructor

		%---------------------------
		% --- getter and setters ---
Ferdinand Fischer's avatar
Ferdinand Fischer committed
170
 		%---------------------------
Jakob Gabriel's avatar
Jakob Gabriel committed
171
		function itIs = isConstant(obj)
Ferdinand Fischer's avatar
Ferdinand Fischer committed
172
173
			% the quantity is interpreted as constant if it has no grid or
			% it has a grid that is only one point.
Jakob Gabriel's avatar
Jakob Gabriel committed
174
			itIs = isempty(obj.gridSize) || prod(obj.gridSize) == 1;
Ferdinand Fischer's avatar
Ferdinand Fischer committed
175
		end
176
177
178
179
180
181
182
183
184
		function doNotCopy = get.doNotCopy(obj)
			doNotCopy = obj.doNotCopyPropertiesName();
		end
		function set.gridName(obj, name)
			if ~iscell(name)
				name = {name};
			end
			obj.gridName = name;
		end
Ferdinand Fischer's avatar
Ferdinand Fischer committed
185
	
186
187
188
189
190
		function set.grid(obj, grid)
			if ~iscell(grid)
				grid = {grid};
			end
			
Jakob Gabriel's avatar
Jakob Gabriel committed
191
			isV = cellfun(@(v) (sum(size(v)>1) == 1) || (numel(v) == 1), grid); % also allow 1x1x1x41 grids
192
193
194
195
196
197
198
199
200
201
202
			assert(all(isV(:)), 'Please use vectors for the grid entries!');
			
			[obj.grid] = deal(grid);
		end
		function valueDiscrete = get.valueDiscrete(obj)
			if isempty(obj.valueDiscrete)
				obj.valueDiscrete = obj.on(obj.grid);
			end
			valueDiscrete = obj.valueDiscrete;
		end
		
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
		%-------------------
		% --- converters ---
		%-------------------
		function exportData = exportData(obj, varargin)
			
			% make the object names:
			if obj.nargin == 1
				headers = cell(1, numel(obj) + 1);
				headers{1} = obj(1).gridName{1};
				for i= 1:numel(obj) %TODO use easier to read headers
					headers{i+1} = [obj(i).name '' num2str(i)];
				end				
				exportData = export.dd(...
					'M', [obj.grid{:}, obj.valueDiscrete], ...
					'header', headers, varargin{:});
			elseif obj.nargin == 2
				error('Not yet implemented')
			else
				error('Not yet implemented')
			end
		end
224
225
226
		function d = double(obj)
			d = obj.on();
		end
Ferdinand Fischer's avatar
Ferdinand Fischer committed
227
228
		
		function o = quantity.Operator(obj)
229
			A = cell(size(obj, 3), 1);
Ferdinand Fischer's avatar
Ferdinand Fischer committed
230
231
232
			for k = 1:size(obj, 3)
				A{k} = obj(:,:,k);
			end
233
			o = quantity.Operator(A);
Ferdinand Fischer's avatar
Ferdinand Fischer committed
234
235
236
237
238
239
240
241
242
		end
		
		function o = quantity.Symbolic(obj)
			if isempty(obj)
				o = quantity.Symbolic.empty(size(obj));
			else
				error('Not yet implemented')
			end
		end
243
			
244
		function obj = setName(obj, newName)
245
246
247
			% Function to set all names of all elements of the quantity obj to newName.
			[obj.name] = deal(newName);
		end % setName()
248
249
250
251
	end
	
	methods (Access = public)
		function value = on(obj, myGrid, myGridName)
252
			% TODO es sieht so aus als w�rde die Interpolation bei
253
254
255
256
257
258
259
			% konstanten werten ziemlichen Quatsch machen!
			%	Da muss man nochmal ordentlich drauf schauen!
			if isempty(obj)
				value = zeros(size(obj));
			else
				if nargin == 1
					myGrid = obj(1).grid;
Jakob Gabriel's avatar
Jakob Gabriel committed
260
					myGridName = obj(1).gridName;
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
				elseif nargin >= 2 && ~iscell(myGrid)
					myGrid = {myGrid};
				end
				gridPermuteIdx = 1:obj(1).nargin;
				if nargin == 3
					if ~iscell(myGridName)
						myGridName = {myGridName};
					end
					assert(numel(myGrid) == numel(myGridName), ...
						['If on() is called by using gridNames as third input', ...
						', then the cell-array of grid and gridName must have ', ...
						'equal number of elements.']);
					assert(numel(myGridName) == obj(1).nargin, ...
						'All (or none) gridName must be specified');
					gridPermuteIdx = cellfun(@(v) obj(1).gridIndex(v), myGridName);
					myGrid = myGrid(gridPermuteIdx);
				end
				
				value = obj.obj2value();
				
				if nargin >= 2 && (prod(obj(1).gridSize) > 1)
					indexGrid = arrayfun(@(s)linspace(1,s,s), size(obj), 'UniformOutput', false);
					tempInterpolant = numeric.interpolant(...
						[obj(1).grid, indexGrid{:}], value);
					value = tempInterpolant.evaluate(myGrid{:}, indexGrid{:});
Ferdinand Fischer's avatar
Ferdinand Fischer committed
286
287
288
				elseif obj.isConstant
					value = repmat(value, [cellfun(@(v) numel(v), myGrid), ones(1, length(size(obj)))]);
					gridPermuteIdx = 1:numel(myGrid);
289
290
291
292
293
294
				end
				value = permute(reshape(value, [cellfun(@(v) numel(v), myGrid), size(obj)]), ...
					[gridPermuteIdx, numel(gridPermuteIdx)+(1:ndims(obj))]);
			end
		end
		
Jakob Gabriel's avatar
Jakob Gabriel committed
295
296
297
		function assertSameGrid(a, varargin)
			% check if all elements of a have same grid and gridName. If
			% further quantites are inputs via varargin, it is verified if
298
299
			% that quantity has same grid and gridName as quantity a as
			% well.
Ferdinand Fischer's avatar
Ferdinand Fischer committed
300
			if isempty(a)
301
302
				if nargin > 1
					varargin{1}.assertSameGrid(varargin{2:end});
303
				end
304
				return;
Ferdinand Fischer's avatar
Ferdinand Fischer committed
305
306
307
308
			else
				referenceGridName = a(1).gridName;
				referenceGrid= a(1).grid;
			end
Jakob Gabriel's avatar
Jakob Gabriel committed
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
			for it = 1 : numel(a)
				assert(isequal(referenceGridName, a(it).gridName), ...
					'All elements of a quantity must have same gridNames');
				assert(isequal(referenceGrid, a(it).grid), ...
					'All elements of a quantity must have same grid');
			end
			if nargin > 1
				b = varargin{1};
				for it = 1 : numel(b)
					assert(isequal(referenceGridName, b(it).gridName), ...
						'All elements of a quantity must have same gridNames');
					assert(isequal(referenceGrid, b(it).grid), ...
						'All elements of a quantity must have same grid');
				end
			end
			if nargin > 2
				% if more then 1 quantity is in varargin, they are checked
				% iteratively by calling assertSameGrid() again.
				assertSameGrid(varargin{:});
			end
		end
		
		function [referenceGrid, referenceGridName] = getFinestGrid(a, varargin)
			% find the finest grid of all input quantities by comparing
			% gridSize for each iteratively.
Ferdinand Fischer's avatar
Ferdinand Fischer committed
334
335
			
			if isempty(a)
336
337
338
339
				if nargin > 1
					[referenceGrid, referenceGridName] = varargin{1}.getFinestGrid(varargin{2:end});
				else
					referenceGrid = {};
Ferdinand Fischer's avatar
Ferdinand Fischer committed
340
				referenceGridName = '';
341
342
				end
				return;
Ferdinand Fischer's avatar
Ferdinand Fischer committed
343
344
345
346
347
348
			else
				referenceGridName = a(1).gridName;
				referenceGrid = a(1).grid;
				referenceGridSize = a(1).gridSize(referenceGridName);				
			end

Jakob Gabriel's avatar
Jakob Gabriel committed
349
			for it = 1 : numel(varargin)
Ferdinand Fischer's avatar
Ferdinand Fischer committed
350
351
352
				if isempty(varargin{it})
					continue;
				end
Jakob Gabriel's avatar
Jakob Gabriel committed
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
				assert(numel(referenceGridName) == numel(varargin{it}(1).gridName), ...
					['For getFinestGrid, the gridName of all objects must be equal', ...
					'. Maybe gridJoin() does what you want?']);
				comparisonGridSize = varargin{it}.gridSize(referenceGridName);
				for jt = 1 : numel(referenceGridName)
					comparisonGrid = varargin{it}.gridOf(referenceGridName{jt});
					assert(referenceGrid{jt}(1) == comparisonGrid(1), 'Grids must have same domain for combining them')
					assert(referenceGrid{jt}(end) == comparisonGrid(end), 'Grids must have same domain for combining them')
					if comparisonGridSize(jt) > referenceGridSize(jt)
						referenceGrid{jt} = comparisonGrid;
						referenceGridSize(jt) = comparisonGridSize(jt);
					end
				end
			end
		end
		
		function [gridJoined, gridNameJoined] = gridJoin(obj1, obj2)
			%% gridJoin combines the grid and gridName of two objects (obj1,
			% obj2), such that every gridName only occurs once and that the
			% finer grid of both is used.
			
			gridNameJoined = unique([obj1(1).gridName, obj2(1).gridName]);
			gridJoined = cell(1, numel(gridNameJoined));
			for it = 1 : numel(gridNameJoined)
				currentGridName = gridNameJoined{it};
				[index1, lolo1] = obj1.gridIndex(currentGridName);
				[index2, lolo2] = obj2.gridIndex(currentGridName);
				if ~any(lolo1)
					gridJoined{it} = obj2(1).grid{index2};
				elseif ~any(lolo2)
					gridJoined{it} = obj1(1).grid{index1};
				else
					tempGrid1 = obj1(1).grid{index1};
					tempGrid2 = obj2(1).grid{index2};
387
388
					
					if ~obj1.isConstant && ~obj2.isConstant				
Jakob Gabriel's avatar
Jakob Gabriel committed
389
390
					assert(tempGrid1(1) == tempGrid2(1), 'Grids must have same domain for gridJoin')
					assert(tempGrid1(end) == tempGrid2(end), 'Grids must have same domain for gridJoin')
391
					end
Jakob Gabriel's avatar
Jakob Gabriel committed
392
393
394
395
396
397
398
399
400
401
					if numel(tempGrid1) > numel(tempGrid2)
						gridJoined{it} = tempGrid1;
					else
						gridJoined{it} = tempGrid2;
					end
				end
			end
		end
		
		function c = horzcat(a, varargin)
402
			%HORZCAT Horizontal concatenation.
403
404
405
406
407
408
			%   [A B] is the horizontal concatenation of objects A and B
			%   from the class quantity.Discrete. A and B must have the
			%   same number of rows and the same grid. [A,B] is the same
			%   thing. Any number of matrices can be concatenated within
			%   one pair of brackets. Horizontal and vertical concatenation
			%   can be combined together as in [1 2;3 4].
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
			%
			%   [A B; C] is allowed if the number of rows of A equals the
			%   number of rows of B and the number of columns of A plus the
			%   number of columns of B equals the number of columns of C.
			%   The matrices in a concatenation expression can themselves
			%   by formed via a concatenation as in [A B;[C D]].  These
			%   rules generalize in a hopefully obvious way to allow fairly
			%   complicated constructions.
			%
			%   N-D arrays are concatenated along the second dimension. The
			%   first and remaining dimensions must match.
			%
			%   C = HORZCAT(A,B) is called for the syntax '[A  B]' when A
			%   or B is an object.
			%
			%   Y = HORZCAT(X1,X2,X3,...) is called for the syntax '[X1 X2
			%   X3 ...]' when any of X1, X2, X3, etc. is an object.
			%
			%	See also HORZCAT, CAT.
428
			 c = cat(2, a, varargin{:});
Jakob Gabriel's avatar
Jakob Gabriel committed
429
430
		end
		function c = vertcat(a, varargin)
431
432
433
434
			%VERTCAT Vertical concatenation.
			%   [A;B] is the vertical concatenation of objects A and B from
			%   the class quantity.Discrete. A and B must have the same
			%   number of columns and the same grid. Any number of matrices
435
436
437
			%   can be concatenated within one pair of brackets. Horizontal
			%   and vertical concatenation can be combined together as in
			%   [1 2;3 4].
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
			%
			%   [A B; C] is allowed if the number of rows of A equals the
			%   number of rows of B and the number of columns of A plus the
			%   number of columns of B equals the number of columns of C.
			%   The matrices in a concatenation expression can themselves
			%   by formed via a concatenation as in [A B;[C D]].  These
			%   rules generalize in a hopefully obvious way to allow fairly
			%   complicated constructions.
			%
			%   N-D arrays are concatenated along the first dimension. The
			%   remaining dimensions must match.
			%
			%   C = VERTCAT(A,B) is called for the syntax '[A; B]' when A
			%   or B is an object.
			%
			%   Y = VERTCAT(X1,X2,X3,...) is called for the syntax '[X1;
			%   X2; X3; ...]' when any of X1, X2, X3, etc. is an object.
			%
			%   See also HORZCAT, CAT.
457
			c = cat(1, a, varargin{:});
Jakob Gabriel's avatar
Jakob Gabriel committed
458
		end
459
		function c = cat(dim, a, varargin)
460
461
462
			%CAT Concatenate arrays.
			%   CAT(DIM,A,B) concatenates the arrays of objects A and B
			%   from the class quantity.Discrete along the dimension DIM.
463
464
			%   CAT(2,A,B) is the same as [A,B]. CAT(1,A,B) is the same as
			%   [A;B].
465
			%
466
467
			%   B = CAT(DIM,A1,A2,A3,A4,...) concatenates the input arrays
			%   A1, A2, etc. along the dimension DIM.
468
			%
469
470
471
472
			%   When used with comma separated list syntax, CAT(DIM,C{:})
			%   or CAT(DIM,C.FIELD) is a convenient way to concatenate a
			%   cell or structure array containing numeric matrices into a
			%   single matrix.
473
474
475
476
477
478
479
480
481
482
483
484
			%
			%   Examples:
			%     a = magic(3); b = pascal(3); 
			%     c = cat(4,a,b)
			%   produces a 3-by-3-by-1-by-2 result and
			%     s = {a b};
			%     for i=1:length(s), 
			%       siz{i} = size(s{i});
			%     end
			%     sizes = cat(1,siz{:})
			%   produces a 2-by-2 array of size vectors.

Jakob Gabriel's avatar
Jakob Gabriel committed
485
			if nargin == 1
Ferdinand Fischer's avatar
Ferdinand Fischer committed
486
				objCell = {a};			
Jakob Gabriel's avatar
Jakob Gabriel committed
487
			else
488
				objCell = [{a}, varargin(:)'];
489
				
490
491
492
493
494
495
496
				% this function has the very special thing that it a does
				% not have to be an quantity.Discrete object. So it has to
				% be checked which of the input arguments is an
				% quantity.Discrete object. This is considered to be give
				% the basic values for the initialization of new
				% quantity.Discrete values
				isAquantityDiscrete = cellfun(@(o) isa(o, 'quantity.Discrete'), objCell);
497
498
				isEmpty = cellfun(@(o) isempty(o), objCell);
				objIdx = find(isAquantityDiscrete & (~isEmpty), 1);
499
				
500
501
502
503
504
505
506
507
				if all(isEmpty)
					% if there are only empty entries, nothing can be
					% concatenated, so a new empty object is initialized.
					s = cellfun(@(o) size(o), objCell, 'UniformOutput', false);
					S = sum(cat(3, s{:}), 3);
					c = quantity.Discrete.empty(S);
					return
				else
508
					obj = objCell{objIdx};
509
510
511
				end
				
				for k = 1:numel(objCell(~isEmpty))
512
					
513
514
					if isa(objCell{k}, 'quantity.Discrete')
						o = objCell{k};
515
					else
516
						value = objCell{k};
517
						for l = 1:numel(value)
518
							M(:,l) = repmat(value(l), prod(obj(1).gridSize), 1);
519
520
521
						end
						if isempty(value)
							M = zeros([prod(obj(1).gridSize), size(value(l))]);
522
						end
523
							M = reshape(M, [obj(1).gridSize, size(value)]);
524
						o = quantity.Discrete( M, ...
525
							'size', size(value), ...
526
527
							'gridName', obj(1).gridName, ...
							'grid', obj(1).grid);
528
529
					end
					
530
					objCell{k} = o;
531
532
				end
				
Jakob Gabriel's avatar
Jakob Gabriel committed
533
			end
534
535
			
			[fineGrid, fineGridName] = getFinestGrid(objCell{~isEmpty});
536
			for it = 1 : (numel(varargin) + 1)  % +1 because the first entry is a
537
				assert(all(strcmp(fineGridName, objCell{it}(1).gridName)), ...
538
					'gridNames of objects that are concatenated must be equal');
539
				objCell{it} = objCell{it}.changeGrid(fineGrid, fineGridName);
540
			end
Jakob Gabriel's avatar
Jakob Gabriel committed
541
			assertSameGrid(objCell{:});
542
543
			argin = [{dim}, objCell(:)'];
			c = builtin('cat', argin{:});
Jakob Gabriel's avatar
Jakob Gabriel committed
544
545
		end
		
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
		function Y = blkdiag(A, varargin)
			% blkdiag  Block diagonal concatenation of matrix input arguments.
			%									|A 0 .. 0|
			% Y = blkdiag(A,B,...)  produces	|0 B .. 0|
			%									|0 0 ..  |
			% Yet, A, B, ... must have the same gridName and grid.
			if nargin == 1
				Y = copy(A);
			else
				B = varargin{1};
				if isempty(B)
					Y = A;
				else
					assert(isequal(A(1).gridName, B(1).gridName), 'only implemented for same grid and gridName');
					assert(isequal(A(1).grid, B(1).grid), 'only implemented for same grid and gridName');
					Y = [A, zeros(size(A, 1), size(B, 2)); ...
						zeros(size(B, 1), size(A, 2)), B];
				end
				if nargin > 2
					Y = blkdiag(Y, varargin{2:end});
				end
			end
		end % blkdiag()
		
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
		function solution = solveAlgebraic(obj, rhs, gridName, objLimit)
			%% this method solves
			%	obj(gridName) == rhs
			% for the variable specified by gridName.
			% rhs must be of apropriate size and gridName must
			% be an gridName of obj. If the result is constant (i.e., if
			% obj only depends on variable, then a double array is
			% returned. Else the solution is of the type as obj.
			% Yet, this is only implemented for obj with one variable
			% (grid) (see quantity.invert-method).
			% The input objLimit specifies minimum and maximum of the
			% values of obj, between which the solution should be searched.
			assert(numel(obj(1).gridName) == 1);
			assert(isequal(size(obj), [1, 1]));
			
			if ~isequal(size(rhs), size(obj))
				error('rhs has not the same size as quantity');
			end
			if ~iscell(gridName)
				gridName = {gridName};
			end
			if numel(gridName) ~= 1
				error('this function can only solve for one variable');
			end
			if isempty(strcmp(obj(1).gridName, gridName{1}))
				error('quantity does not depend on variable');
			end
			
			if nargin == 4
				assert(numel(objLimit)==2, 'a lower and upper limit must be specified (or neither)');
				objValueTemp = obj.on();
				gridSelector = (objValueTemp >= objLimit(1)) & (objValueTemp <= objLimit(2));
602
603
				gridSelector([max(1, find(gridSelector, 1, 'first')-1), ...
					min(find(gridSelector, 1, 'last')+1, numel(gridSelector))]) = 1;
604
605
				limitedGrid = obj(1).grid{1}(gridSelector);
				objCopy = obj.copy();
Jakob Gabriel's avatar
Jakob Gabriel committed
606
				objCopy = objCopy.changeGrid({limitedGrid}, gridName);
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
				objInverseTemp = objCopy.invert(gridName);
			else
				objInverseTemp = obj.invert(gridName);
			end
			
			solution = objInverseTemp.on(rhs);

% 			solution = zeros(numel(obj), 1);
% 			for it = 1 : numel(obj)
% 				objInverseTemp = obj(it).invert(gridName);
% 				solution(it) = objInverseTemp.on(rhs(it));				
% 			end
% 			solution = reshape(solution, size(obj));
		end
		
		function inverse = invert(obj, gridName)
			% inverse solves the function representet by the quantity for
			% its variable, for instance, if obj represents y = f(x), then
			% invert returns an object containing x = f^-1(y).
			% Yet, this is only implemented for obj with one variable
			% (grid).
628
629
630
631
632
633
634
			if iscell(gridName)
				% fixme: by default the first gridName is chosen as new
				% name. This works because the functions is only written
				% for quantities with one variable.
				gridName = gridName{1};
			end
			
635
636
637
638
			assert(numel(obj(1).gridName) == 1);
			assert(isequal(size(obj), [1, 1]));
			inverse = quantity.Discrete(repmat(obj(1).grid{obj.gridIndex(gridName)}(:), [1, size(obj)]), ...
				'size', size(obj), 'grid', obj.on(), 'gridName', {[obj(1).name]}, ...
639
				'name', gridName); 
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
			
		end
		
		function solution = solveDVariableEqualQuantity(obj, varargin)
			%% solves the first order ODE
			%	dvar / ds = obj(var(s))
			%	var(s=0) = ic
			% for var(s, ic). Herein, var is the (only) continuous variale
			% obj.variable. The initial condition of the IVP is a variable
			% of the result var(s, ic).
			assert(numel(obj(1).gridName) == 1, ...
				'this method is only implemented for quanitities with one gridName');
			
			myParser = misc.Parser();
			myParser.addParameter('initialValueGrid', obj(1).grid{1});
			myParser.addParameter('variableGrid', obj(1).grid{1});
			myParser.addParameter('newGridName', 's');
			myParser.addParameter('RelTol', 1e-6);
			myParser.addParameter('AbsTol', 1e-6);
			myParser.parse(varargin{:});
			
			variableGrid = myParser.Results.variableGrid;
			myGridSize = [numel(variableGrid), ... 
				numel(myParser.Results.initialValueGrid)];
			
665
666
			% the time (s) vector has to start at 0, to ensure the IC. If
			% variableGrid does not start with 0, it is separated in
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
			% negative and positive parts and later combined again.
			positiveVariableGrid = [0, variableGrid(variableGrid > 0)];
			negativeVariableGrid = [0, flip(variableGrid(variableGrid < 0))];
			
			% solve ode for every entry in obj and for every initial value
			options = odeset('RelTol', myParser.Results.RelTol, 'AbsTol', myParser.Results.AbsTol);
			odeSolution = zeros([myGridSize, numel(obj)]);
			for it = 1:numel(obj)
				for icIdx = 1:numel(myParser.Results.initialValueGrid)
					resultGridPositive = [];
					odeSolutionPositive = [];
					resultGridNegative = [];
					odeSolutionNegative = [];
					if numel(positiveVariableGrid) > 1
						[resultGridPositive, odeSolutionPositive] = ...
							ode45(@(y, z) obj(it).on(z), ...
								positiveVariableGrid, ...
								myParser.Results.initialValueGrid(icIdx), options);
					end
					if numel(negativeVariableGrid) >1
						[resultGridNegative, odeSolutionNegative] = ...
							ode45(@(y, z) obj(it).on(z), ...
								negativeVariableGrid, ...
								myParser.Results.initialValueGrid(icIdx), options);
					end
					if any(variableGrid == 0)
						resultGrid = [flip(resultGridNegative(2:end)); 0 ; resultGridPositive(2:end)];
						odeSolution(:, icIdx, it) = [flip(odeSolutionNegative(2:end)); ...
							myParser.Results.initialValueGrid(icIdx); odeSolutionPositive(2:end)];
					else
						resultGrid = [flip(resultGridNegative(2:end)); resultGridPositive(2:end)];
						odeSolution(:, icIdx, it) = [flip(odeSolutionNegative(2:end)); ...
							odeSolutionPositive(2:end)];
					end
					assert(isequal(resultGrid(:), variableGrid(:)));
				end
			end
			
			% return result as quantity-object
			solution = quantity.Discrete(...
				reshape(odeSolution, [myGridSize, size(obj)]), ...
				'gridName', {myParser.Results.newGridName, 'ic'}, 'grid', ...
				{variableGrid, myParser.Results.initialValueGrid}, ...
				'size', size(obj), 'name', ['solve(', obj(1).name, ')']);
		end
712
			
713
714
715
716
		function solution = subs(obj, gridName2Replace, values)
			if nargin == 1 || isempty(gridName2Replace)
				% if gridName2Replace is empty, then nothing must be done.
				solution = obj;
717
			elseif isempty(obj)
Ferdinand Fischer's avatar
Ferdinand Fischer committed
718
719
				% if the object is empty, nothing must be done.
				solution = obj;
720
721
722
723
724
725
726
727
728
729
			else
				% input checks
				assert(nargin == 3, ['Wrong number of input arguments. ', ...
					'gridName2Replace and values must be cell-arrays!']);
				if ~iscell(gridName2Replace)
					gridName2Replace = {gridName2Replace};
				end
				if ~iscell(values)
					values = {values};
				end
Jakob Gabriel's avatar
Jakob Gabriel committed
730
731
				assert(numel(values) == numel(gridName2Replace), ...
					'gridName2Replace and values must be of same size');
732
733
734
735
736
737
738
739
740
741
742
743
744
				
				% here substitution starts: 
				% The first (gridName2Replace{1}, values{1})-pair is 
				% replaced. If there are more cell-elements in those inputs
				% then subs() is called again for the remaining pairs
				% (gridName2Replace{2:end}, values{2:end}).
				if ischar(values{1})
					% if values{1} is a char-array, then the gridName is
					% replaced
					if any(strcmp(values{1}, gridName2Replace(2:end)))
						% in the case if a quantity f(z, zeta) should be
						% substituted like subs(f, {z, zeta}, {zeta, z})
						% this would cause an error, since after the first
745
746
						% substituion subs(f, z, zeta) the result would be
						% f(zeta, zeta) -> the 2nd subs(f, zeta, z) will
747
748
749
750
751
752
753
						% result in f(z, z) and not in f(zeta, z) as
						% intended. This is solved, by an additonal
						% substitution:
						values{end+1} = values{1};
						gridName2Replace{end+1} = [gridName2Replace{1}, 'backUp'];
						values{1} = [gridName2Replace{1}, 'backUp'];
					end
Jakob Gabriel's avatar
Jakob Gabriel committed
754
755
756
757
758
759
760
					if isequal(values{1}, gridName2Replace{1})
						% replace with same variable... everything stay the
						% same.
						newGrid = obj(1).grid;
						newGridName = obj(1).gridName;
						newValue = obj.on();
					elseif any(strcmp(values{1}, obj(1).gridName))
761
						% if for a quantity f(z, zeta) this method is
762
763
764
						% called with subs(f, zeta, z), then g(z) = f(z, z)
						% results, hence the dimensions z and zeta are
						% merged.
765
766
767
768
769
770
771
772
773
774
						gridIndices = [obj(1).gridIndex(gridName2Replace{1}), ...
							obj(1).gridIndex(values{1})];
						newGridForOn = obj(1).grid;
						if numel(obj(1).grid{gridIndices(1)}) > numel(obj(1).grid{gridIndices(2)})
							newGridForOn{gridIndices(2)} = newGridForOn{gridIndices(1)};
						else
							newGridForOn{gridIndices(1)} = newGridForOn{gridIndices(2)};
						end
						newValue = misc.diagNd(obj.on(newGridForOn), gridIndices);
						newGrid = {newGridForOn{gridIndices(1)}, ...
Jakob Gabriel's avatar
Jakob Gabriel committed
775
776
							newGridForOn{1:1:numel(newGridForOn) ~= gridIndices(1) ...
							 & 1:1:numel(newGridForOn) ~= gridIndices(2)}};
777
						newGridName = {values{1}, ...
Jakob Gabriel's avatar
Jakob Gabriel committed
778
779
							obj(1).gridName{1:1:numel(obj(1).gridName) ~= gridIndices(1) ...
							 & 1:1:numel(obj(1).gridName) ~= gridIndices(2)}};
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
						
					else
						% this is the default case. just grid name is
						% changed.
						newGrid = obj(1).grid;
						newGridName = obj(1).gridName;
						newGridName{obj(1).gridIndex(gridName2Replace{1})} ...
							= values{1};
						newValue = obj.on();
					end
					
				elseif isnumeric(values{1}) && numel(values{1}) == 1
					% if values{1} is a scalar, then obj is evaluated and
					% the resulting quantity loses that spatial grid and
					% gridName
					newGridName = obj(1).gridName;
					newGridName = newGridName(~strcmp(newGridName, gridName2Replace{1}));
					% newGrid is the similar to the original grid, but the
					% grid of gridName2Replace is removed.
					newGrid = obj(1).grid;
					newGrid = newGrid((1:1:numel(newGrid)) ~= obj.gridIndex(gridName2Replace{1}));
					newGridSize = cellfun(@(v) numel(v), newGrid);
802
803
804
					% newGridForOn is the similar to the original grid, but
					% the grid of gridName2Replace is set to values{1} for
					% evaluation of obj.on().
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
					newGridForOn = obj(1).grid;
					newGridForOn{obj.gridIndex(gridName2Replace{1})} = values{1};
					newValue = reshape(obj.on(newGridForOn), [newGridSize, size(obj)]);
					
				elseif isnumeric(values{1}) && numel(values{1}) > 1
					% if values{1} is a double vector, then the grid is
					% replaced.
					newGrid = obj(1).grid;
					newGrid{obj.gridIndex(gridName2Replace{1})} = values{1};
					newGridName = obj(1).gridName;
					newValue = obj.on(newGrid);
				else
					error('value must specify a gridName or a gridPoint');
				end
				if isempty(newGridName)
					solution = newValue;
				else
					solution = quantity.Discrete(newValue, ...
						'grid', newGrid, 'gridName', newGridName, ...
						'name', obj(1).name);
				end
				if numel(gridName2Replace) > 1
					solution = solution.subs(gridName2Replace(2:end), values(2:end));
				end
			end
			
		end
Jakob Gabriel's avatar
Jakob Gabriel committed
832
		
833
		function value = at(obj, point)
834
835
836
			% at() evaluates the object at one point and returns it as array 
			% with the same size as size(obj).
			value = shiftdim(obj.on(point), numel(obj(1).gridName));
837
838
839
		end
		
		function value = atIndex(obj, varargin)
Ferdinand Fischer's avatar
Ferdinand Fischer committed
840
841
842
843
844
845
846
847
848
849
850
851
852
			% ATINDEX returns the valueDiscrete at the requested index.
			% value = atIndex(obj, varargin) returns the
			% quantity.Discrete.valueDiscrete at the index defined by
			% varargin.  
			%	value = atIndex(obj, 1) returns the first element of
			%	"valueDiscrete"
			%	value = atIndex(obj, ':') returns all elements of
			%	obj.valueDiscrete in vectorized form. 
			%	value = atIndex(obj, 1, end) returns the obj.valueDiscrete
			%	at the index (1, end).
			%	If a range of index is requested, the result is returned
			%	with the grids as indizes. If scalar values are requested,
			%	than the grid dimensions are neglected.
853
			if nargin == 1
854
855
856
857
858
859
				
				if numel(obj.gridSize) == 1
					value = zeros(obj.gridSize, 1);
				else
					value = zeros(obj.gridSize, 1);
				end
860
861
862
863
864
865
866
				if isempty(value)
					value = 0;
				end
			else
				if ~iscell(varargin)
					varargin = {varargin};
				end
867
868
869
870
				value = cellfun(@(v) v(varargin{:}), {obj.valueDiscrete}, ...
					'UniformOutpu', false);
				
				valueSize = size(value{1});
Ferdinand Fischer's avatar
Ferdinand Fischer committed
871
872
873
874
875
								
				if all(cellfun(@numel, varargin) == 1) && all(cellfun(@isnumeric, varargin))
					outputSize = [];
				else
					outputSize = valueSize(1:obj(1).nargin);
876
			end
Ferdinand Fischer's avatar
Ferdinand Fischer committed
877
878

				value = reshape([value{:}], [outputSize, size(obj)]);
879
		end
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
		end
		
		function n = nargin(obj)
			% FIXME: check if all funtions in this object have the same
			% number of input values.
			n = numel(obj(1).gridName);
		end
		
		function d = gridDiff(obj)
			
			% #FIXME:
			%   1) test for multidimensional grids
			%   2) check that the grid is equally spaced
			
			d = diff(obj(1).grid{:});
			d = d(1);
		end
		
Jakob Gabriel's avatar
Jakob Gabriel committed
898
		function s = gridSize(obj, myGridName)
899
900
901
902
			% GRIDSIZE returns the size of all grid entries.
			if isempty(obj(1).grid)
				s = [];
			else
Jakob Gabriel's avatar
Jakob Gabriel committed
903
904
905
906
907
				if nargin == 1
					s = cellfun('length', obj(1).grid);
				elseif nargin == 2
					s = cellfun('length', obj(1).gridOf(myGridName));
				end
908
909
910
911
912
			end
		end
		
		function matGrid = ndgrid(obj, grid)
			% ndgrid calles ndgrid for the default grid, if no other grid
913
914
			% is specified. Empty grid as input returns empty cell as
			% result.
915
916
917
918
919
920
921
922
			if nargin == 1
				grid = obj.grid;
			end
			if isempty(grid)
				matGrid = {};
			else
				[matGrid{1:obj.nargin}] = ndgrid(grid{:});
			end
923
		end % ndgrid()
924
		
Ferdinand Fischer's avatar
Ferdinand Fischer committed
925
926
		function H = plot(obj, varargin)
			H = [];
927
928
			p = misc.Parser();
			p.addParameter('fig', []);
929
930
			p.addParameter('dock', quantity.Settings.instance().plot.dock);
			p.addParameter('showTitle', quantity.Settings.instance().plot.showTitle);
Jakob Gabriel's avatar
Jakob Gabriel committed
931
			p.addParameter('titleWithIndex', true');
932
933
934
935
936
937
			p.addParameter('export', false);
			p.addParameter('exportOptions',  ...
				{'height', [num2str(0.25*size(obj, 1)), '\textwidth'], ...
				'width', '0.8\textwidth', 'externalData', false, ...
				'showWarnings', false, 'showInfo', false, ...
				'extraAxisOptions', 'every axis title/.append style={yshift=-1.5ex}, every axis x label/.append style={yshift=2mm}'});
938
			p.parse(varargin{:});
Ferdinand Fischer's avatar
Ferdinand Fischer committed
939
			additionalPlotOptions = misc.struct2namevaluepair(p.Unmatched);
940
941
942
943
			if prod(obj.gridSize) == 1
				additionalPlotOptions = [additionalPlotOptions(:)', ...
					{'x'}];
			end
Ferdinand Fischer's avatar
Ferdinand Fischer committed
944
			
945
946
947
948
949
950
			fig = p.Results.fig;
			dock = p.Results.dock;
			for figureIdx = 1:size(obj, 3)
				if isempty(p.Results.fig)
					h = figure();
				else
Ferdinand Fischer's avatar
Ferdinand Fischer committed
951
					h = figure(fig + figureIdx - 1);
952
				end
Ferdinand Fischer's avatar
Ferdinand Fischer committed
953
				H = [H, h];
954
955
956
957
958
				
				if dock
					set(h, 'WindowStyle', 'Docked');
				end
				
959
				assert(~isempty(obj), 'Empty quantities can not be plotted');
Jakob Gabriel's avatar
Jakob Gabriel committed
960
				assert(obj.nargin() <= 2, 'plot only supports quantities with 2 gridNames');
961
962
963
964
965
966
967
968
969
970
971
				
				subplotRowIdx = 1:size(obj, 1);
				subpotColumnIdx = 1:size(obj, 2);
				
				i = 1: numel(obj(:,:,figureIdx));
				i = reshape(i, size(obj, 2), size(obj, 1))';
				
				for rowIdx = subplotRowIdx
					for columnIdx = subpotColumnIdx
						subplot(size(obj, 1), size(obj, 2), i(rowIdx, columnIdx));
						
972
973
974
975
976
						if obj.nargin() == 0
							plot(0, ...
								obj(rowIdx, columnIdx, figureIdx).valueDiscrete, ...
								additionalPlotOptions{:});
						elseif obj.nargin() == 1
977
							plot(...
Jakob Gabriel's avatar
Jakob Gabriel committed
978
								obj(rowIdx, columnIdx, figureIdx).grid{1}(:), ...
Ferdinand Fischer's avatar
Ferdinand Fischer committed
979
980
								obj(rowIdx, columnIdx, figureIdx).valueDiscrete, ...
								additionalPlotOptions{:});
981
982
983
						elseif obj.nargin() == 2
							misc.isurf(obj(rowIdx, columnIdx, figureIdx).grid{1}(:), ...
								obj(rowIdx, columnIdx, figureIdx).grid{2}(:), ...
Ferdinand Fischer's avatar
Ferdinand Fischer committed
984
985
								obj(rowIdx, columnIdx, figureIdx).valueDiscrete, ...
								additionalPlotOptions{:});
986
987
988
989
990
							ylabel(labelHelper(2), 'Interpreter','latex');
						else
							error('number inputs not supported');
						end
						xlabel(labelHelper(1), 'Interpreter','latex');
991
992
						
						if p.Results.showTitle
993
						title(titleHelper(), 'Interpreter','latex');
994
						end
995
996
997
						a = gca();
						a.TickLabelInterpreter = 'latex';
						
998
999
					end % for columnIdx = subpotColumnIdx
				end % for rowIdx = subplotRowIdx
1000
				
For faster browsing, not all history is shown. View entire blame