Discrete.m 77.2 KB
Newer Older
1
classdef  (InferiorClasses = {?quantity.Symbolic}) Discrete < handle & matlab.mixin.Copyable & matlab.mixin.CustomDisplay
2
3
4
5
6
7
8
9
10
11
	properties (SetAccess = protected)
		% Discrete evaluation of the continuous quantity
		valueDiscrete double;
	end
	
	properties (Hidden, Access = protected, Dependent)
		doNotCopy;
	end
	
	properties
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
		% ID of the figure handle in which the handle is plotted
		figureID double = 1;
		
		% Name of this object
		name char;
		
		% domain
		domain;
	end
	
	properties ( Dependent )
		
		% Name of the domains that generate the grid.
		gridName {mustBe.unique};
		
27
28
29
30
31
32
33
		% 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
34
35
36
37
38
39
40
	end
	
	methods
		%--------------------
		% --- Constructor ---
		%--------------------
		function obj = Discrete(valueOriginal, varargin)
41
42
43
44
			% DISCRETE a quantity, represented by discrete values.
			%	obj = Discrete(valueOriginal, varargin) initializes a
			%	quantity. The parameters to be set are:
			% 'valueOrigin' must be
45
46
47
			% 1) a cell-array of double arrays with
			%	size(valueOriginal) == size(obj) and
			%	size(valueOriginal{it}) == gridSize
48
49
50
51
52
			%	Example: valueOrigin = { f(Z, T), g(Z, T) } is a cell array
			%	wich contains the functions f(z,t) and g(z,t) evaluated on
			%	the discrete domain (Z x T). Then, the name-value-pair
			%	parameter 'domain' must be set with quantity.Domain
			%	objects, according to the domains Z and T.
53
54
			% OR
			% 2) adouble-array with
55
			%	size(valueOriginal) == [gridSize, size(quantity)]
56
57
58
59
60
			% 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
61
62
63
64
65
			% 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
66
67
68
69
70
				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;
71
				else
72
					% empty object. this is needed for instance, to create
73
					% quantity.Discrete([]), which is useful for creating default
74
75
					% values.
					obj = quantity.Discrete.empty(size(valueOriginal));
76
				end
77
			elseif nargin > 1
78
79
80
				
				%% input parser
				myParser = misc.Parser();
81
82
				myParser.addParameter('name', string(), @isstr);
				myParser.addParameter('figureID', 1, @isnumeric);
83
84
				myParser.parse(varargin{:});
				
85
				%% domain parser
86
				myDomain = quantity.Domain.parser(varargin{:});
87
88
89
90
91
92
93
94
95
96
97
98
99
100
												
				%% get the sizes of obj and grid
				gridLength = myDomain.gridLength;

				% convert double valued valueOriginal to cell-valued value
				% original
				if ~iscell(valueOriginal)
					valueOriginal = quantity.Discrete.value2cell(valueOriginal, gridLength);
				end
				
				% Check if the grid fits to the values. In addition, catch
				% the case if all values are empty. This is required for
				% the initialization of quantity.Function and
				% quantity.Symbolic objects
101
102
				assert( misc.alln( cellfun(@isempty, valueOriginal ) ) || ...
					numGridElements(myDomain) == numel(valueOriginal{1}), ...
103
104
105
					'grids do not fit to valueOriginal');				
				
				% allow initialization of empty objects
106
107
108
109
110
111
				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();
112
					myParser.addParameter('size', valueOriginalSize((1+ndims(myDomain)):end));
113
114
115
116
117
					myParser.parse(varargin{:});
					obj = quantity.Discrete.empty(myParser.Results.size);
					return;
				end
				
118
119
120
121
122
123
				% set valueDiscrete
				for k = 1:numel(valueOriginal)
					if numel(myDomain) == 1
						% TODO: Which case is this? Why does it need extra
						% treatment?
						obj(k).valueDiscrete = valueOriginal{k}(:); %#ok<AGROW>
124
					else
125
						obj(k).valueDiscrete = valueOriginal{k}; %#ok<AGROW>
126
127
128
129
					end
				end
				
				%% set further properties
130
				[obj.domain] = deal(myDomain);
131
132
133
134
				[obj.name] = deal(myParser.Results.name);
				[obj.figureID] = deal(myParser.Results.figureID);
				
				%% reshape object from vector to matrix
135
				obj = reshape(obj, size(valueOriginal));
136
137
			end
		end% Discrete() constructor
138
		
139
140
		%---------------------------
		% --- getter and setters ---
141
142
		%---------------------------
		function gridName = get.gridName(obj)
Ferdinand Fischer's avatar
tmp    
Ferdinand Fischer committed
143
144
145
146
147
			if isempty(obj.domain)
				gridName = {};
			else
				gridName = {obj.domain.name};
			end
148
149
150
		end
		
		function grid = get.grid(obj)
Ferdinand Fischer's avatar
tmp    
Ferdinand Fischer committed
151
152
153
154
155
			if isempty(obj.domain)
				grid = {};
			else
				grid = {obj.domain.grid};
			end
156
157
		end
		
Jakob Gabriel's avatar
Jakob Gabriel committed
158
		function itIs = isConstant(obj)
Ferdinand Fischer's avatar
Ferdinand Fischer committed
159
160
			% 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
161
			itIs = isempty(obj.gridSize) || prod(obj.gridSize) == 1;
Ferdinand Fischer's avatar
Ferdinand Fischer committed
162
		end
163
164
165
166
		function doNotCopy = get.doNotCopy(obj)
			doNotCopy = obj.doNotCopyPropertiesName();
		end
		function valueDiscrete = get.valueDiscrete(obj)
167
168
			% check if the value discrete for this object
			% has already been computed.
169
			empty = isempty(obj.valueDiscrete);
170
			if any(empty(:))
171
				obj.valueDiscrete = obj.obj2value(obj.domain, true);
172
173
174
175
			end
			valueDiscrete = obj.valueDiscrete;
		end
		
176
177
178
179
180
181
182
183
184
185
186
		%-------------------
		% --- 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)];
187
				end
188
189
190
191
192
193
194
195
196
				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
197
198
199
		function d = double(obj)
			d = obj.on();
		end
200
201
		function o = quantity.Function(obj)
			props = nameValuePair( obj(1) );
202
			
203
204
205
206
207
			for k = 1:numel(obj)
				F = griddedInterpolant(obj(k).grid{:}', obj(k).on());
				o(k) = quantity.Function(@(varargin) F(varargin{:}), ...
					props{:});
			end
208
209
			
			o = reshape(o, size(obj));
210
		end
Ferdinand Fischer's avatar
Ferdinand Fischer committed
211
		function o = quantity.Operator(obj)
212
			A = cell(size(obj, 3), 1);
Ferdinand Fischer's avatar
Ferdinand Fischer committed
213
214
215
			for k = 1:size(obj, 3)
				A{k} = obj(:,:,k);
			end
216
			o = quantity.Operator(A);
Ferdinand Fischer's avatar
Ferdinand Fischer committed
217
218
219
220
221
222
223
224
225
		end
		
		function o = quantity.Symbolic(obj)
			if isempty(obj)
				o = quantity.Symbolic.empty(size(obj));
			else
				error('Not yet implemented')
			end
		end
226
		
227
		function obj = setName(obj, newName)
228
229
230
			% Function to set all names of all elements of the quantity obj to newName.
			[obj.name] = deal(newName);
		end % setName()
231
232
233
	end
	
	methods (Access = public)
234
235
236
237
238
239
240
241
242
243
244
245
246
247
		function value = on(obj, myDomain, gridNames)
			% ON evaluation of the quantity on a certain domain.
			%	value = on(obj) or value = obj.on(); evaluates the quantity
			%	on its standard grid. 
			%	value = obj.on( myDomain ) evalutes the quantity on the
			%	grid specified by myDomain. The order of the domains in
			%	domain, will be the same as from myDomain. 
			%	value = obj.on( grid ) evaluates the quantity specified by
			%	grid. Grid must be a cell-array with the grids as elements.
			%	value = obj.on( grid, gridName ) evaluates the quantity
			%	specified by grid. Grid must be a cell-aary with the grids
			%	as elements. By the gridName parameter the order of the
			%	grid can be specified.

248
249
250
			if isempty(obj)
				value = zeros(size(obj));
			else
251
252
253
254
255
256
257
258
				if nargin == 2
					% case 1: a domain is specified by myDomain or by
					% myDomain as a cell-array with grid entries
					if iscell(myDomain) || isnumeric(myDomain)
						myDomain = misc.ensureIsCell(myDomain);
						assert(all(cellfun(@(v)isvector(v), myDomain)), 'The cell entries for a new grid have to be vectors')
						newGrid = myDomain;
						myDomain = quantity.Domain.empty();
259
260
261
262
263
264
265
						
						if obj(1).isConstant()
							gridNames = repmat({''}, length(newGrid));
						else
							gridNames = {obj(1).domain.name};
						end
						
266
						for k = 1:length(newGrid)
267
							myDomain(k) = quantity.Domain('grid', newGrid{k}, 'name', gridNames{k});
268
						end
269
					end
270
271
272
273
274
275
276
277
278
279
280
281
282
				elseif nargin == 3
					assert(iscell(myDomain), 'If the domain is specified by cell-array pairs, the value myDomain must be a cell-array with grid entries')
					assert(all(cellfun(@(v)isvector(v), myDomain)), 'The cell entries for a new grid have to be vectors')
					assert(iscell(gridNames), 'The gridNames parameter must be cell array')
					assert(all(cellfun(@ischar, gridNames)), 'The gridNames must be strings')
					
					newGrid = myDomain;
					myDomain = quantity.Domain.empty();
					for k = 1:length(newGrid)
						myDomain(k) = quantity.Domain('grid', newGrid{k}, 'name', gridNames{k});
					end
				else
					myDomain = obj(1).domain;
283
				end
284
285
 				
				% verify the domain
286
287
288
289
290
291
				if obj(1).isConstant
					gridPermuteIdx = 1:length(myDomain);
				else
					assert(numel(myDomain) == numel(obj(1).domain), ['Wrong grid for the evaluation of the object']);
					[myDomain, gridPermuteIdx] = obj(1).domain.permute(myDomain);
				end			
292
293
294
295
296
				% get the valueDiscrete data for this object. Apply the
				% permuted myDomain. Then the obj2value will be evaluated
				% in the order of the original domain. The permuatation to
				% the new order will be done in the next step.
				value = obj.obj2value(myDomain(gridPermuteIdx));
297
				
298
				value = permute(reshape(value, [cellfun(@(v) numel(v), {myDomain(gridPermuteIdx).grid}), size(obj)]), ...
299
300
301
302
					[gridPermuteIdx, numel(gridPermuteIdx)+(1:ndims(obj))]);
			end
		end
		
303
304
305
306
307
308
		function interpolant = interpolant(obj)
			% get the interpolant of the obj;
			if isempty(obj)
				value = zeros(size(obj));
				indexGrid = arrayfun(@(s)linspace(1,s,s), size(obj), 'UniformOutput', false);
				interpolant = numeric.interpolant(...
309
					[indexGrid{:}], value);
310
			else
311
				myGrid = obj(1).grid;
312
313
314
				value = obj.obj2value();
				indexGrid = arrayfun(@(s)linspace(1,s,s), size(obj), 'UniformOutput', false);
				interpolant = numeric.interpolant(...
315
					[myGrid, indexGrid{:}], value);
316
317
318
319
			end
		end
		
		
Jakob Gabriel's avatar
Jakob Gabriel committed
320
321
322
		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
323
324
			% that quantity has same grid and gridName as quantity a as
			% well.
Ferdinand Fischer's avatar
Ferdinand Fischer committed
325
			if isempty(a)
326
327
				if nargin > 1
					varargin{1}.assertSameGrid(varargin{2:end});
328
				end
329
				return;
Ferdinand Fischer's avatar
Ferdinand Fischer committed
330
331
332
333
			else
				referenceGridName = a(1).gridName;
				referenceGrid= a(1).grid;
			end
Jakob Gabriel's avatar
Jakob Gabriel committed
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
			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
359
			
360
			if isempty(a) || isempty(a(1).grid)
361
362
363
364
				if nargin > 1
					[referenceGrid, referenceGridName] = varargin{1}.getFinestGrid(varargin{2:end});
				else
					referenceGrid = {};
365
					referenceGridName = '';
366
367
				end
				return;
Ferdinand Fischer's avatar
Ferdinand Fischer committed
368
369
370
			else
				referenceGridName = a(1).gridName;
				referenceGrid = a(1).grid;
371
				referenceGridSize = a(1).gridSize(referenceGridName);
Ferdinand Fischer's avatar
Ferdinand Fischer committed
372
			end
373
			
Jakob Gabriel's avatar
Jakob Gabriel committed
374
			for it = 1 : numel(varargin)
375
				if isempty(varargin{it}) || isempty(varargin{it}(1).domain)
Ferdinand Fischer's avatar
Ferdinand Fischer committed
376
377
					continue;
				end
Jakob Gabriel's avatar
Jakob Gabriel committed
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
				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
		
394
395
		function obj = sort(obj, varargin)
			%SORT sorts the grid of the object in a desired order
396
			% obj = sortGrid(obj) sorts the grid in alphabetical order.
397
398
			% obj = sort(obj, 'descend') sorts the grid in descending
			% alphabetical order.
Ferdinand Fischer's avatar
tmp    
Ferdinand Fischer committed
399
						
400
401
			% only sort the grids if there is something to sort
			if obj(1).nargin > 1
402
				
Ferdinand Fischer's avatar
tmp    
Ferdinand Fischer committed
403
404
				[sortedDomain, I] = obj(1).domain.sort(varargin{:});
				[obj.domain] = deal(sortedDomain);
405
				
406
407
				for k = 1:numel(obj)
					obj(k).valueDiscrete = permute(obj(k).valueDiscrete, I);
408
				end
409
410
			end
		end% sort()
Ferdinand Fischer's avatar
tmp    
Ferdinand Fischer committed
411
		
Jakob Gabriel's avatar
Jakob Gabriel committed
412
		function c = horzcat(a, varargin)
413
			%HORZCAT Horizontal concatenation.
414
415
416
417
418
419
			%   [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].
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
			%
			%   [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.
439
			c = cat(2, a, varargin{:});
Jakob Gabriel's avatar
Jakob Gabriel committed
440
441
		end
		function c = vertcat(a, varargin)
442
443
444
445
			%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
446
447
448
			%   can be concatenated within one pair of brackets. Horizontal
			%   and vertical concatenation can be combined together as in
			%   [1 2;3 4].
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
			%
			%   [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.
468
			c = cat(1, a, varargin{:});
Jakob Gabriel's avatar
Jakob Gabriel committed
469
		end
470
		function c = cat(dim, a, varargin)
471
472
473
			%CAT Concatenate arrays.
			%   CAT(DIM,A,B) concatenates the arrays of objects A and B
			%   from the class quantity.Discrete along the dimension DIM.
474
475
			%   CAT(2,A,B) is the same as [A,B]. CAT(1,A,B) is the same as
			%   [A;B].
476
			%
477
478
			%   B = CAT(DIM,A1,A2,A3,A4,...) concatenates the input arrays
			%   A1, A2, etc. along the dimension DIM.
479
			%
480
481
482
483
			%   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.
484
485
			%
			%   Examples:
486
			%     a = magic(3); b = pascal(3);
487
488
489
			%     c = cat(4,a,b)
			%   produces a 3-by-3-by-1-by-2 result and
			%     s = {a b};
490
			%     for i=1:length(s),
491
492
493
494
			%       siz{i} = size(s{i});
			%     end
			%     sizes = cat(1,siz{:})
			%   produces a 2-by-2 array of size vectors.
495
			
Jakob Gabriel's avatar
Jakob Gabriel committed
496
			if nargin == 1
497
				objCell = {a};
Jakob Gabriel's avatar
Jakob Gabriel committed
498
			else
499
				objCell = [{a}, varargin(:)'];
500
				
501
502
503
				% 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
504
				% quantity.Discrete object. This is considered to give
505
506
507
				% the basic values for the initialization of new
				% quantity.Discrete values
				isAquantityDiscrete = cellfun(@(o) isa(o, 'quantity.Discrete'), objCell);
508
509
				isEmpty = cellfun(@(o) isempty(o), objCell);
				objIdx = find(isAquantityDiscrete & (~isEmpty), 1);
510
				
511
512
513
514
				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);
515
					if dim == 1
516
						S = sum(cat(3, s{:}), 3);
517
518
519
520
521
					elseif dim == 2
						S = s{1};
					else
						error('Not implemented')
					end
522
523
524
					c = quantity.Discrete.empty(S);
					return
				else
525
					obj = objCell{objIdx};
526
527
528
				end
				
				for k = 1:numel(objCell(~isEmpty))
529
					
530
531
					if isa(objCell{k}, 'quantity.Discrete')
						o = objCell{k};
532
					else
533
						value = objCell{k};
534
						for l = 1:numel(value)
535
							M(:,l) = repmat(value(l), prod(obj(1).gridSize), 1);
536
537
538
						end
						if isempty(value)
							M = zeros([prod(obj(1).gridSize), size(value(l))]);
539
						end
540
						M = reshape(M, [obj(1).gridSize, size(value)]);
541
						o = quantity.Discrete( M, ...
542
							'size', size(value), ...
543
544
							'gridName', obj(1).gridName, ...
							'grid', obj(1).grid);
545
546
					end
					
547
					objCell{k} = o;
548
549
				end
				
Jakob Gabriel's avatar
Jakob Gabriel committed
550
			end
551
			
552
553
554
555
556
			% sort the grid names of each quantity
			for it = 1: (numel(varargin) + 1)
				objCell{it} = objCell{it}.sort;
			end
			
557
			[fineGrid, fineGridName] = getFinestGrid(objCell{~isEmpty});
558
			for it = 1 : (numel(varargin) + 1)  % +1 because the first entry is a
559
				% change the grid to the finest
560
				objCell{it} = objCell{it}.changeGrid(fineGrid, fineGridName);
561
			end
Jakob Gabriel's avatar
Jakob Gabriel committed
562
			assertSameGrid(objCell{:});
563
564
			argin = [{dim}, objCell(:)'];
			c = builtin('cat', argin{:});
Jakob Gabriel's avatar
Jakob Gabriel committed
565
566
		end
		
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
		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()
		
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
		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));
623
624
				gridSelector([max(1, find(gridSelector, 1, 'first')-1), ...
					min(find(gridSelector, 1, 'last')+1, numel(gridSelector))]) = 1;
625
626
				limitedGrid = obj(1).grid{1}(gridSelector);
				objCopy = obj.copy();
Jakob Gabriel's avatar
Jakob Gabriel committed
627
				objCopy = objCopy.changeGrid({limitedGrid}, gridName);
628
629
630
631
632
633
				objInverseTemp = objCopy.invert(gridName);
			else
				objInverseTemp = obj.invert(gridName);
			end
			
			solution = objInverseTemp.on(rhs);
634
635
636
637
638
639
640
			
			% 			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));
641
642
643
644
645
646
647
648
		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).
649
650
651
652
653
654
655
			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
			
656
657
658
659
			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]}, ...
660
				'name', gridName);
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
			
		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{:});
			
Ferdinand Fischer's avatar
tmp    
Ferdinand Fischer committed
682
			variableGrid = myParser.Results.variableGrid(:);
683
			myGridSize = [numel(variableGrid), ...
684
685
				numel(myParser.Results.initialValueGrid)];
			
686
687
			% the time (s) vector has to start at 0, to ensure the IC. If
			% variableGrid does not start with 0, it is separated in
688
			% negative and positive parts and later combined again.
Ferdinand Fischer's avatar
tmp    
Ferdinand Fischer committed
689
690
			positiveVariableGrid = [0; variableGrid(variableGrid > 0)];
			negativeVariableGrid = [0; flip(variableGrid(variableGrid < 0))];
691
692
693
694
695
696
697
698
699
700
701
702
703
			
			% 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), ...
704
705
							positiveVariableGrid, ...
							myParser.Results.initialValueGrid(icIdx), options);
706
707
708
709
					end
					if numel(negativeVariableGrid) >1
						[resultGridNegative, odeSolutionNegative] = ...
							ode45(@(y, z) obj(it).on(z), ...
710
711
							negativeVariableGrid, ...
							myParser.Results.initialValueGrid(icIdx), options);
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
					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
733
		
734
		function solution = subs(obj, gridName2Replace, values)
735
			% SUBS substitute variables of a quantity
736
737
738
739
740
741
742
743
744
745
746
747
			%	solution = SUBS(obj, NEWDOMAIN), replaces the original
			%	domain of the object with the new domain specified by
			%	NEWDOMAIN. NEWDOMAIN must have the same grid name as the
			%	original domain.
			%
			%	solution = SUBS(obj, GRIDNAMES2REPLACE, VALUES) replaces
			%	the domains which are specified by GRIDNAMES2REPLACE by
			%	VALUES. GRIDNAMES2REPLACE must be a cell-array with the
			%	names of the domains or an object-array with
			%	quantity.Domain objects which should be replaced by VALUES.
			%	VALUES must be a cell-array of the new values or new grid
			%	names.
748
749
750
751
752
753
754
755
			%
			%	Example: 
			%		q = q.subs('z', 't')
			%		will replace the domain with the name 'z' by a domain
			%		with the name 't' but with the same discretization.
			%		q = q.subs('z', linspace(0,1)')
			%		will replace the grid of domain with the name 'z' by
			%		the new grid specified by linspace.
756
757
758
			if nargin == 1 || isempty(gridName2Replace)
				% if gridName2Replace is empty, then nothing must be done.
				solution = obj;
759
			elseif isempty(obj)
Ferdinand Fischer's avatar
Ferdinand Fischer committed
760
761
				% if the object is empty, nothing must be done.
				solution = obj;
762
763
			else
				% input checks
764
765
766
767
768
769
770
771
772
773
				if nargin == 2
					assert(isa(gridName2Replace, 'quantity.Domain'), 'If only two parameters are specified, the second parameter must be a quantiy.Domain');

					values = {gridName2Replace.grid};
					gridName2Replace = {gridName2Replace.name};
					
				elseif nargin == 3
					
					gridName2Replace = misc.ensureIsCell(gridName2Replace);
					values = misc.ensureIsCell(values);
774
				end
775
				
Jakob Gabriel's avatar
Jakob Gabriel committed
776
777
				assert(numel(values) == numel(gridName2Replace), ...
					'gridName2Replace and values must be of same size');
778
				
779
780
				% here substitution starts:
				% The first (gridName2Replace{1}, values{1})-pair is
781
782
783
784
785
786
787
788
789
790
				% 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
791
792
						% substituion subs(f, z, zeta) the result would be
						% f(zeta, zeta) -> the 2nd subs(f, zeta, z) will
793
794
795
796
797
798
799
						% 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
800
801
802
803
804
805
806
					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))
807
						% if for a quantity f(z, zeta) this method is
808
809
810
						% called with subs(f, zeta, z), then g(z) = f(z, z)
						% results, hence the dimensions z and zeta are
						% merged.
811
812
						gridIndices = [obj(1).domain.gridIndex(gridName2Replace{1}), ...
							obj(1).domain.gridIndex(values{1})];
813
814
815
816
817
818
819
820
						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
821
							newGridForOn{1:1:numel(newGridForOn) ~= gridIndices(1) ...
822
							& 1:1:numel(newGridForOn) ~= gridIndices(2)}};
823
						newGridName = {values{1}, ...
Jakob Gabriel's avatar
Jakob Gabriel committed
824
							obj(1).gridName{1:1:numel(obj(1).gridName) ~= gridIndices(1) ...
825
							& 1:1:numel(obj(1).gridName) ~= gridIndices(2)}};
826
827
828
829
830
					else
						% this is the default case. just grid name is
						% changed.
						newGrid = obj(1).grid;
						newGridName = obj(1).gridName;
831
						newGridName{obj(1).domain.gridIndex(gridName2Replace{1})} ...
832
833
834
835
836
837
838
839
840
841
842
843
844
							= 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;
845
					newGrid = newGrid((1:1:numel(newGrid)) ~= obj(1).domain.gridIndex(gridName2Replace{1}));
846
					newGridSize = cellfun(@(v) numel(v), newGrid);
847
848
849
					% newGridForOn is the similar to the original grid, but
					% the grid of gridName2Replace is set to values{1} for
					% evaluation of obj.on().
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
					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
876
		
877
878
879
880
		function [idx, logicalIdx] = gridIndex(obj, varargin)
			[idx, logicalIdx] = obj(1).domain.gridIndex(varargin{:});
		end 
		
881
		function value = at(obj, point)
882
			% at() evaluates the object at one point and returns it as array
883
			% with the same size as size(obj).
884
			value = reshape(obj.on(point), size(obj));
885
886
887
		end
		
		function value = atIndex(obj, varargin)
Ferdinand Fischer's avatar
Ferdinand Fischer committed
888
889
890
			% ATINDEX returns the valueDiscrete at the requested index.
			% value = atIndex(obj, varargin) returns the
			% quantity.Discrete.valueDiscrete at the index defined by
891
			% varargin.
Ferdinand Fischer's avatar
Ferdinand Fischer committed
892
893
894
			%	value = atIndex(obj, 1) returns the first element of
			%	"valueDiscrete"
			%	value = atIndex(obj, ':') returns all elements of
895
			%	obj.valueDiscrete in vectorized form.
Ferdinand Fischer's avatar
Ferdinand Fischer committed
896
897
898
899
900
			%	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.
901
			if nargin == 1
902
903
904
905
906
907
				
				if numel(obj.gridSize) == 1
					value = zeros(obj.gridSize, 1);
				else
					value = zeros(obj.gridSize, 1);
				end
908
909
910
911
912
913
914
				if isempty(value)
					value = 0;
				end
			else
				if ~iscell(varargin)
					varargin = {varargin};
				end
915
				value = cellfun(@(v) v(varargin{:}), {obj.valueDiscrete}, ...
916
					'UniformOutput', false);
917
918
				
				valueSize = size(value{1});
919
				
Ferdinand Fischer's avatar
Ferdinand Fischer committed
920
921
922
923
				if all(cellfun(@numel, varargin) == 1) && all(cellfun(@isnumeric, varargin))
					outputSize = [];
				else
					outputSize = valueSize(1:obj(1).nargin);
924
925
				end
				
Ferdinand Fischer's avatar
Ferdinand Fischer committed
926
				value = reshape([value{:}], [outputSize, size(obj)]);
927
			end
928
929
930
931
932
		end
		
		function n = nargin(obj)
			% FIXME: check if all funtions in this object have the same
			% number of input values.
933
934
935
936
937
938
			
			% FIXME: for some combinations of constant objects, it seems to be
			% possible, that the quantity has a gridName but no grid.
			% Actually this should not be allowed. This is quick and dirty
			% work around.
			n = min(numel(obj(1).gridName), numel(obj(1).grid));
939
940
941
942
943
944
945
946
947
948
949
950
		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
951
		function s = gridSize(obj, myGridName)
952
			% GRIDSIZE returns the size of all grid entries.
953
			% todo: this should be called gridLength
Ferdinand Fischer's avatar
tmp    
Ferdinand Fischer committed
954
			if isempty(obj(1).domain)
955
956
				s = [];
			else
Jakob Gabriel's avatar
Jakob Gabriel committed
957
958
959
960
961
				if nargin == 1
					s = cellfun('length', obj(1).grid);
				elseif nargin == 2
					s = cellfun('length', obj(1).gridOf(myGridName));
				end
962
963
964
			end
		end
		
Ferdinand Fischer's avatar
Ferdinand Fischer committed
965
966
		function H = plot(obj, varargin)
			H = [];
967
968
			p = misc.Parser();
			p.addParameter('fig', []);
969
970
			p.addParameter('dock', quantity.Settings.instance().plot.dock);
			p.addParameter('showTitle', quantity.Settings.instance().plot.showTitle);
Jakob Gabriel's avatar
Jakob Gabriel committed
971
			p.addParameter('titleWithIndex', true');
972
			p.addParameter('hold', false);
973
974
975
976
977
978
			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}'});
979
			p.parse(varargin{:});
Ferdinand Fischer's avatar
Ferdinand Fischer committed
980
			additionalPlotOptions = misc.struct2namevaluepair(p.Unmatched);
981
982
983
984
			if prod(obj.gridSize) == 1
				additionalPlotOptions = [additionalPlotOptions(:)', ...
					{'x'}];
			end
Ferdinand Fischer's avatar
Ferdinand Fischer committed
985
			
986
987
988
989
990
			fig = p.Results.fig;
			dock = p.Results.dock;
			for figureIdx = 1:size(obj, 3)
				if isempty(p.Results.fig)
					h = figure();
991
992
				elseif p.Results.fig == 0
					h = gcf;
993
				else
Ferdinand Fischer's avatar
Ferdinand Fischer committed
994
					h = figure(fig + figureIdx - 1);
995
				end
Ferdinand Fischer's avatar
Ferdinand Fischer committed
996
				H = [H, h];
997
998
999
1000
				
				if dock
					set(h, 'WindowStyle', 'Docked');
				end
For faster browsing, not all history is shown. View entire blame