Discrete.m 92.8 KB
Newer Older
1
2
classdef  (InferiorClasses = {?quantity.Symbolic}) Discrete ...
		< handle & matlab.mixin.Copyable & matlab.mixin.CustomDisplay
3

4
5
6
7
8
9
10
11
12
13
	properties (SetAccess = protected)
		% Discrete evaluation of the continuous quantity
		valueDiscrete double;
	end
	
	properties (Hidden, Access = protected, Dependent)
		doNotCopy;
	end
	
	properties
14
15
16
17
		% ID of the figure handle in which the handle is plotted
		figureID double = 1;
		
		% Name of this object
18
		name (1,1) string;
19
20
21
22
23
24
		
		% domain
		domain;
	end
	
	properties ( Dependent )
25
				
26
27
28
		% Name of the domains that generate the grid.
		gridName {mustBe.unique};
		
29
30
31
32
33
34
35
		% 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
36
37
38
39
40
41
	end
	
	methods
		%--------------------
		% --- Constructor ---
		%--------------------
42
		function obj = Discrete(valueOriginal, myDomain, varargin)
43
			% DISCRETE a quantity, represented by discrete values.
44
			%	obj = Discrete(valueOriginal, myDomain, varargin) initializes a
45
46
			%	quantity. The parameters to be set are:
			% 'valueOrigin' must be
47
48
49
			% 1) a cell-array of double arrays with
			%	size(valueOriginal) == size(obj) and
			%	size(valueOriginal{it}) == gridSize
50
51
52
53
54
			%	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.
55
			% OR
56
			% 2) a double-array with
57
			%	size(valueOriginal) == [gridSize, size(quantity)]
58
59
60
            % 'myDomain' must be a quantity.Domain object
            % 
			% Additional parameters can be specified using
61
			% name-value-pair-syntax in varargin.
62
63
			% TODO specify the name-value-pair arguments
                        
64
			% to allow the initialization as object array, the constructor
65
66
67
68
69
			% 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
70
71
72
73
74
				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;
75
				else
76
					% empty object. this is needed for instance, to create
77
					% quantity.Discrete([]), which is useful for creating default
78
79
					% values.
					obj = quantity.Discrete.empty(size(valueOriginal));
80
				end
81
			elseif nargin > 1
82
83
84
				
				%% input parser
				myParser = misc.Parser();
85
				myParser.addParameter('name', "", @mustBe.gridName);
86
				myParser.addParameter('figureID', 1, @isnumeric);
87
				myParser.parse(varargin{:});
88
															
89
90
91
92
93
94
95
96
97
98
99
100
101
				%% 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
102
103
104
105
106
107
				assert(isempty(myDomain) ... % constant case
					|| all( cellfun(@isempty, valueOriginal ), 'all' ) ... % empty case
					|| isequal([myDomain.n], size(valueOriginal{1}, 1 : max(1, numel(myDomain)))) ... % usual case
					|| (isrow(valueOriginal{1}) && ... % row-vector case (including next line)
						isequal([1, myDomain.n], size(valueOriginal{1}, 1 : max(1, numel(myDomain)+1)))), ...
					'grids do not fit to valueOriginal');
108
109
				
				% allow initialization of empty objects
110
111
112
113
114
115
				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();
116
					myParser.addParameter('size', valueOriginalSize((1+ndims(myDomain)):end));
117
118
119
120
121
					myParser.parse(varargin{:});
					obj = quantity.Discrete.empty(myParser.Results.size);
					return;
				end
				
122
123
124
				% set valueDiscrete
				for k = 1:numel(valueOriginal)
					if numel(myDomain) == 1
125
126
127
						% for quantities on a single domain, ensure that
						% the discrete values are stored as column-vector
						% by using the (:) operator.
128
						obj(k).valueDiscrete = valueOriginal{k}(:); %#ok<AGROW>
129
					else
130
						obj(k).valueDiscrete = valueOriginal{k}; %#ok<AGROW>
131
132
133
134
					end
				end
				
				%% set further properties
135
				[obj.domain] = deal(myDomain);
136
				obj.setName(myParser.Results.name);
137
138
139
				[obj.figureID] = deal(myParser.Results.figureID);
				
				%% reshape object from vector to matrix
140
				obj = reshape(obj, size(valueOriginal));
141
142
			end
		end% Discrete() constructor
143
		
144
145
		%---------------------------
		% --- getter and setters ---
146
147
		%---------------------------
		function gridName = get.gridName(obj)
Ferdinand Fischer's avatar
tmp    
Ferdinand Fischer committed
148
			if isempty(obj.domain)
149
				gridName = [];
Ferdinand Fischer's avatar
tmp    
Ferdinand Fischer committed
150
			else
151
				gridName = [obj.domain.name];
Ferdinand Fischer's avatar
tmp    
Ferdinand Fischer committed
152
			end
153
154
155
		end
		
		function grid = get.grid(obj)
Ferdinand Fischer's avatar
tmp    
Ferdinand Fischer committed
156
157
158
159
160
			if isempty(obj.domain)
				grid = {};
			else
				grid = {obj.domain.grid};
			end
161
162
		end
		
Jakob Gabriel's avatar
Jakob Gabriel committed
163
		function itIs = isConstant(obj)
Ferdinand Fischer's avatar
Ferdinand Fischer committed
164
			% the quantity is interpreted as constant if it has no grid or
165
			% it has a grid that is only defined at one point.
166
			itIs = isempty(obj(1).domain);
167
168
		end % isConstant()
		
169
170
171
172
		function doNotCopy = get.doNotCopy(obj)
			doNotCopy = obj.doNotCopyPropertiesName();
		end
		function valueDiscrete = get.valueDiscrete(obj)
173
174
			% check if the value discrete for this object
			% has already been computed.
175
			empty = isempty(obj.valueDiscrete);
176
			if any(empty(:))
177
				obj.valueDiscrete = obj.obj2value(obj.domain, true);
178
179
180
181
			end
			valueDiscrete = obj.valueDiscrete;
		end
		
182
183
184
185
186
187
188
189
190
191
		%-------------------
		% --- 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
192
					headers{i+1} = obj(i).name + "" + num2str(i);
193
				end
194
				exportData = export.dd(...
195
					'M', [obj(1).grid{:}, obj.valueDiscrete], ...
196
197
198
199
200
201
202
					'header', headers, varargin{:});
			elseif obj.nargin == 2
				error('Not yet implemented')
			else
				error('Not yet implemented')
			end
		end
203
204
205
		function d = double(obj)
			d = obj.on();
		end
206
		function o = quantity.Function(obj)
207
208
			
			args = obj(1).optArgList;
209
			
210
211
			for k = 1:numel(obj)
				F = griddedInterpolant(obj(k).grid{:}', obj(k).on());
212
				o(k) = quantity.Function(@(varargin) F(varargin{:}), obj(1).domain, args{:});
213
			end
214
215
			
			o = reshape(o, size(obj));
216
		end
217
		function o = signals.PolynomialOperator(obj)
218
			A = cell(size(obj, 3), 1);
Ferdinand Fischer's avatar
Ferdinand Fischer committed
219
220
221
			for k = 1:size(obj, 3)
				A{k} = obj(:,:,k);
			end
222
			o = signals.PolynomialOperator(A);
Ferdinand Fischer's avatar
Ferdinand Fischer committed
223
224
225
226
227
228
229
230
231
		end
		
		function o = quantity.Symbolic(obj)
			if isempty(obj)
				o = quantity.Symbolic.empty(size(obj));
			else
				error('Not yet implemented')
			end
		end
232
		
233
		function obj = setName(obj, newName)
234
			% Function to set all names of all elements of the quantity obj to newName.
235
236
237
238
% 			if ischar(newName)
% 				warning("Depricated: use string and not char for name-property!")
% 				newName = string(newName);
% 			end
239
240
			[obj.name] = deal(newName);
		end % setName()
241
242
243
		
		
		
244
245
246
	end
	
	methods (Access = public)
247
		
Ferdinand Fischer's avatar
...    
Ferdinand Fischer committed
248
		function [z_idx, z_grid, z_value] = findZeros(obj, optArg)
249
250
251
252
253
254
255
256
			arguments
				obj,
				optArg.tol = 100*eps;
			end
			assert(obj(1).nargin == 1, "This function is only implemented for function dependent on one argument so far");
						
			for i = 1:numel(obj)
				
257
				data = obj(i).valueDiscrete;
258
259
260
261
262
263
264
265
266
				
				zeros = find( abs(data) <= optArg.tol);
				upCrossing = find( data(1:end-1) <= 0 & data(2:end) > 0);
				downCrossing = find( data(1:end-1) >= 0 & data(2:end) < 0);
				
				% todo: do a interpolation:
				%ZeroX = @(x0,y0,x1,y1) x0 - (y0.*(x0 - x1))./(y0 - y1); % Interpolated x value for Zero-Crossing 
				
				z_idx{i} = unique( [zeros; upCrossing; downCrossing]);
Ferdinand Fischer's avatar
...    
Ferdinand Fischer committed
267
				z_grid{i} = obj(1).domain.grid(z_idx{i});
268
269
270
271
				z_value{i} = data(z_idx{i});
			end
		end
		
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
		function h = hash(obj)
			%HASH create a SHA-1 hash value for this object
			% h = hash(obj) will copmute the SHA-1 hash value based on the
			% data "valueDiscrete", "domain.name", "domain.grid",
			% "obj.name"
			% The hash value can be used to get a "short" identifier for
			% this object.
			
			% create a huge array of all relevant quantity data
			data = {[ obj.valueDiscrete ], obj(1).domain.name, ...
				    obj(1).domain.grid, obj(1).name};
			h = misc.hash(data);
			
		end
		
287
		function d = compositionDomain(obj, domainName)
288
			
289
290
291
			assert(isscalar(obj));
					
			d = obj.on();
292
293
			
			% the evaluation of obj.on( compositionDomain ) is done by:
294
			d_size = size(d);
295
			
296
297
			% vectorization of the n-d-grid: compositionDomain	
			d = quantity.Domain(domainName, d(:));
298
299
		end
		
300
		function obj_hat = compose(obj, g, optionalArgs)
301
			% COMPOSE compose two functions
302
			%	OBJ_hat = compose(obj, G, varargin) composes the function f
303
			%	defined by OBJ with the function given by G. In particular,
304
			%		f_hat(z,t) = f( z, g(z,t) )
305
			%	if f(t) = obj, g is G and f_hat is OBJ_hat.
306
307
308
309
310
311
312
			arguments
				obj
				g quantity.Discrete;
				optionalArgs.domain quantity.Domain = obj(1).domain;
			end
			myCompositionDomain = optionalArgs.domain;
			originalDomain = obj(1).domain;
313
			
314
315
316
317
318
319
320
321
322
323
			% quick workaround to apply to marix valued quantities
			if numel(obj) > 1
				optArgs = misc.struct2namevaluepair( optionalArgs );
				for k = 1:numel(obj)
					obj_hat(k) = compose(obj(k), g, optArgs{:});
				end
				obj_hat = reshape(obj_hat, size(obj));
				return
			end
			
324
325
326
327
328
			assert( length( myCompositionDomain ) == 1 );
			[idx, logOfDomain] = originalDomain.gridIndex(myCompositionDomain);
			assert( isequal( originalDomain(idx), myCompositionDomain ), ...
				'Composition of functions: The domains for the composition must be equal. A grid join is not implemented yet.');
			assert( any( logOfDomain )  )
329
			
330
			% get the composition domain:
331
332
333
			%	For the argument y of a function f(y) which should be
			%	composed by y = g(z,t) a new dommain will be created on the
			%	basis of evaluation of g(z,t).
334
			composeOnDomain = ...
335
336
				g.compositionDomain(myCompositionDomain.name);
			
337
338
			% check if the composition domain is in the range of definition
			% of obj.
339
			if ~composeOnDomain.isSubDomainOf( myCompositionDomain )
340
341
				warning('quantity:Discrete:compose', ....
					'The composition domain is not a subset of obj.domain! The missing values will be extrapolated.');
342
			end			
343
			
344
			% evaluation on the new grid:
345
346
347
348
349
350
			%	the order of the domains is important. At first, the
			%	domains which will not be replaced are taken. The last
			%	domain must be the composed domain. For example: a function
			%	f(x, y, z, t), where y should be composed with g(z, t) will
			%	be resorted to f_(x, z, t, y) and then evaluated with y =
			%	g(z,t)
351
352
353
354
355
			
			% #TODO: optimize the memory consumption of this function.
			%	1) only consider the unqiue grid points in evaluationDomain
			%	2) do the conversion of the evaluationDomain directly to
			%	the target domain.			
356
			evaluationDomain = [originalDomain( ~logOfDomain ), composeOnDomain ];
357
			
358
359
360
361
362
363
364
365
			newValues = obj.on( evaluationDomain );
			
			% reshape the new values into a 2-d array so that the first
			% dimension is any domain but the composition domain and the
			% last dimension is the composition domain
			sizeOldDomain = prod( [originalDomain( ~logOfDomain ).n] );
			sizeComposeDomain = composeOnDomain.gridLength;
			newValues = reshape(newValues, [sizeOldDomain, sizeComposeDomain]);
366
367

			%rearrange the computed values, to have the same dimension
368
			% as the required domain
369
			% consider the domain 
370
371
372
373
374
			%		f( z, g(z,t) ) = f(z, g(zeta,t) )|_{zeta = z}
			tmpDomain = [originalDomain( ~logOfDomain ), g(1).domain ];
			% newValues will be reshaped into the form
			%	f(z, t, zeta)
			newValues = reshape( newValues, [tmpDomain.gridLength, 1] );
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
			
			if ~logOfDomain == 0
				intersectDomain = [];
			else
				% now the common domains, i.e., zeta = z must be merged:
				% For this, use intersect to find the common domains. The
				% comparison is applied to the domain names. This is
				% required, because intersect only works with objects of
				% the same type. If one of the domains is an
				% quantity.EquidistantDomain, the direct call of intersect
				% on the domains will lead to an error.
				intersectDomain = intersect( ...
					[originalDomain( ~logOfDomain ).name], ...
					[g(1).domain.name] );
			end
390
391
392
			
			if ~isempty(intersectDomain)
				
393
				idx = tmpDomain.gridIndex( intersectDomain );
394
395
396
397
398
				
				% take the diagonal values of the common domain, i.e., z = zeta		
				% use the diag_nd function because it seems to be faster
				% then the diagNd function, although the values must be
				% sorted.
399
				newValues = misc.diagNd(newValues, idx);
400
			end
401
			
402
			% *) build a new valueDiscrete on the correct grid.		
403
			obj_hat = quantity.Discrete( newValues, tmpDomain.join, ...
404
				'name', obj.name + "°" + g.name, ...
405
				'size', size(obj));
406
			
407
		end % compose()
408
		
409
410
411
412
413
414
415
416
417
418
419
420
421
422
		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.

423
424
425
			if isempty(obj)
				value = zeros(size(obj));
			else
426
427
428
				if nargin == 1
					% case 0: no domain was specified, hence the value is requested
					% on the default grid defined by obj(1).domain.
429
430
					value = reshape(cat(numel(obj(1).domain)+1, obj(:).valueDiscrete), ...
						[obj(1).domain.gridLength(), size(obj)]);
431
432
					
				elseif nargin == 2 && (iscell(myDomain) || isnumeric(myDomain))
433
					% case 1: a domain is specified by myDomain as agrid
434
435
436
437
438
439
440
441
442
					myDomain = misc.ensureIsCell(myDomain);
					newGrid = myDomain;

					if obj(1).isConstant()
						gridNames = repmat({''}, length(newGrid));
					else
						gridNames = {obj(1).domain.name};
					end

443
444
445
					% initialize the new domain
					clear('myDomain');
					myDomain(1:length(newGrid)) = quantity.Domain();					
446
447
448
					for k = 1:length(newGrid)
						myDomain(k) = quantity.Domain(gridNames{k}, newGrid{k});
					end
449
					value = obj.obj2value(myDomain);
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
				else
					% Since in the remaining cases the order of the domains is not 
					% neccessarily equal to the order in obj(1).domain, this is 
					% more involved:
					if nargin == 2
						% case 2: a domain is specified by a myDomain = domain-array
						% nothing has to be done to obtain the domain.

					elseif nargin == 3
						% case 3: a domain is specified by a grid and a grid
						% name. Then, the first input parameter is the grid,
						% i.e., myGrid = myDomain and the second is the grid
						% name.
						% Since the order of the domains is not neccessarily equal to the
						% order in obj(1).domain, this is more involved:
465
						myDomain = misc.ensureIsCell(myDomain);
466
						gridNames = misc.ensureString(gridNames);
467
468
469
470

						assert(all(cellfun(@(v)isvector(v), myDomain)), ...
							'The cell entries for a new grid have to be vectors')

471
						newGrid = myDomain;
472
473
						clear('myDomain');
						myDomain(1:length(newGrid)) = quantity.Domain();	
474
						for k = 1:length(newGrid)
475
							myDomain(k) = quantity.Domain(gridNames{k}, newGrid{k});
476
						end
477
478
					else
						error('wrong number of input arguments')
479
					end
480

481
482
483
484
485
486
487
488
489
					% verify the domain
					if obj(1).isConstant
						gridPermuteIdx = 1:length(myDomain);
					else
						assert(numel(myDomain) == numel(obj(1).domain), ...
							'Wrong grid for the evaluation of the object');
						% compute the permutation index, in order to bring the
						% new domain in the same order as the original one.
						gridPermuteIdx = obj(1).domain.getPermutationIdx(myDomain);
490
						
491
						assert(any(gridPermuteIdx ~= 0), "grid could not be found.")
492
493
494
495
496
497
498
					end			
					% 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 permutation to
					% the new order will be done in the next step.
					originalOrderedDomain(gridPermuteIdx) = myDomain;
					value = obj.obj2value(originalOrderedDomain);
499
					value = permute(value, [gridPermuteIdx, numel(gridPermuteIdx)+(1:ndims(obj))]);
500
				end
501
502
			end % if isempty(obj)
		end % on()
503
		
504
505
506
507
		function interpolant = interpolant(obj)
			% get the interpolant of the obj;
			if isempty(obj)
				value = zeros(size(obj));
508
				indexGrid = misc.indexGrid(size(obj));
509
				interpolant = numeric.interpolant(...
510
					[indexGrid{:}], value);
511
			else
512
				myGrid = obj(1).grid;
513
				value = obj.obj2value();
514
				indexGrid = misc.indexGrid(size(obj));
515
				interpolant = numeric.interpolant(...
516
					[myGrid, indexGrid{:}], value);
517
			end
518
		end % interpolant()
519
520
		
		
Jakob Gabriel's avatar
Jakob Gabriel committed
521
522
523
		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
524
525
			% that quantity has same grid and gridName as quantity a as
			% well.
Ferdinand Fischer's avatar
Ferdinand Fischer committed
526
			if isempty(a)
527
528
				if nargin > 1
					varargin{1}.assertSameGrid(varargin{2:end});
529
				end
530
				return;
Ferdinand Fischer's avatar
Ferdinand Fischer committed
531
532
533
534
			else
				referenceGridName = a(1).gridName;
				referenceGrid= a(1).grid;
			end
Jakob Gabriel's avatar
Jakob Gabriel committed
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
			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
560
			
561
			if isempty(a) || isempty(a(1).grid)
562
563
564
565
				if nargin > 1
					[referenceGrid, referenceGridName] = varargin{1}.getFinestGrid(varargin{2:end});
				else
					referenceGrid = {};
566
					referenceGridName = '';
567
568
				end
				return;
Ferdinand Fischer's avatar
Ferdinand Fischer committed
569
570
571
			else
				referenceGridName = a(1).gridName;
				referenceGrid = a(1).grid;
572
				referenceGridSize = [a(1).domain.n];
Ferdinand Fischer's avatar
Ferdinand Fischer committed
573
			end
574
			
Jakob Gabriel's avatar
Jakob Gabriel committed
575
			for it = 1 : numel(varargin)
576
				if isempty(varargin{it}) || isempty(varargin{it}(1).domain)
Ferdinand Fischer's avatar
Ferdinand Fischer committed
577
578
					continue;
				end
Jakob Gabriel's avatar
Jakob Gabriel committed
579
580
581
582
				assert(numel(referenceGridName) == numel(varargin{it}(1).gridName), ...
					['For getFinestGrid, the gridName of all objects must be equal', ...
					'. Maybe gridJoin() does what you want?']);
				for jt = 1 : numel(referenceGridName)
583
					comparisonGridSize = varargin{it}(1).domain.find(referenceGridName{jt}).n;
Jakob Gabriel's avatar
Jakob Gabriel committed
584
585
586
					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')
587
					if comparisonGridSize > referenceGridSize(jt)
Jakob Gabriel's avatar
Jakob Gabriel committed
588
						referenceGrid{jt} = comparisonGrid;
589
						referenceGridSize(jt) = comparisonGridSize;
Jakob Gabriel's avatar
Jakob Gabriel committed
590
591
592
593
594
					end
				end
			end
		end
		
595
596
		function obj = sort(obj, varargin)
			%SORT sorts the grid of the object in a desired order
597
			% obj = sortGrid(obj) sorts the grid in alphabetical order.
598
599
			% obj = sort(obj, 'descend') sorts the grid in descending
			% alphabetical order.
Ferdinand Fischer's avatar
tmp    
Ferdinand Fischer committed
600
						
601
			% only sort the grids if there is something to sort
602
			if ~isempty(obj) && obj(1).nargin > 1
603
				
Ferdinand Fischer's avatar
tmp    
Ferdinand Fischer committed
604
605
				[sortedDomain, I] = obj(1).domain.sort(varargin{:});
				[obj.domain] = deal(sortedDomain);
606
				
607
608
				for k = 1:numel(obj)
					obj(k).valueDiscrete = permute(obj(k).valueDiscrete, I);
609
				end
610
611
			end
		end% sort()
Ferdinand Fischer's avatar
tmp    
Ferdinand Fischer committed
612
		
Jakob Gabriel's avatar
Jakob Gabriel committed
613
		function c = horzcat(a, varargin)
614
			%HORZCAT Horizontal concatenation.
615
616
617
618
619
620
			%   [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].
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
			%
			%   [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.
640
			c = cat(2, a, varargin{:});
Jakob Gabriel's avatar
Jakob Gabriel committed
641
642
		end
		function c = vertcat(a, varargin)
643
644
645
646
			%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
647
648
649
			%   can be concatenated within one pair of brackets. Horizontal
			%   and vertical concatenation can be combined together as in
			%   [1 2;3 4].
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
			%
			%   [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.
669
			c = cat(1, a, varargin{:});
Jakob Gabriel's avatar
Jakob Gabriel committed
670
		end
671
		function c = cat(dim, a, varargin)
672
673
674
			%CAT Concatenate arrays.
			%   CAT(DIM,A,B) concatenates the arrays of objects A and B
			%   from the class quantity.Discrete along the dimension DIM.
675
676
			%   CAT(2,A,B) is the same as [A,B]. CAT(1,A,B) is the same as
			%   [A;B].
677
			%
678
679
			%   B = CAT(DIM,A1,A2,A3,A4,...) concatenates the input arrays
			%   A1, A2, etc. along the dimension DIM.
680
			%
681
682
683
684
			%   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.
685
686
			%
			%   Examples:
687
			%     a = magic(3); b = pascal(3);
688
689
690
			%     c = cat(4,a,b)
			%   produces a 3-by-3-by-1-by-2 result and
			%     s = {a b};
691
			%     for i=1:length(s),
692
693
694
695
			%       siz{i} = size(s{i});
			%     end
			%     sizes = cat(1,siz{:})
			%   produces a 2-by-2 array of size vectors.
696
			
Jakob Gabriel's avatar
Jakob Gabriel committed
697
			if nargin == 1
698
				objCell = {a};
Jakob Gabriel's avatar
Jakob Gabriel committed
699
			else
700
				objCell = [{a}, varargin(:)'];
701
				
702
703
704
				% 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
705
				% quantity.Discrete object. This is considered to give
706
707
708
				% the basic values for the initialization of new
				% quantity.Discrete values
				isAquantityDiscrete = cellfun(@(o) isa(o, 'quantity.Discrete'), objCell);
709
710
				isEmpty = cellfun(@(o) isempty(o), objCell);
				objIdx = find(isAquantityDiscrete & (~isEmpty), 1);
711
				
712
713
714
715
				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);
716
					if dim == 1
717
						S = sum(cat(3, s{:}), 3);
718
719
720
721
722
					elseif dim == 2
						S = s{1};
					else
						error('Not implemented')
					end
723
724
725
					c = quantity.Discrete.empty(S);
					return
				else
726
					obj = objCell{objIdx};
727
728
729
				end
				
				for k = 1:numel(objCell(~isEmpty))
730
					
731
732
					if isa(objCell{k}, 'quantity.Discrete')
						o = objCell{k};
733
					else
734
						value = objCell{k};
735
						for l = 1:numel(value)
736
							M(:,l) = repmat(value(l), prod(obj(1).domain.gridLength), 1);
737
738
						end
						if isempty(value)
739
							M = zeros([prod(obj(1).domain.gridLength), size(value(l))]);
740
						end
741
						M = reshape(M, [obj(1).domain.gridLength, size(value)]);
742
743
						o = quantity.Discrete( M, obj(1).domain, ...
							'size', size(value));
744
745
					end
					
746
					objCell{k} = o;
747
748
				end
				
Jakob Gabriel's avatar
Jakob Gabriel committed
749
			end
750
			
751
752
753
754
755
			% sort the grid names of each quantity
			for it = 1: (numel(varargin) + 1)
				objCell{it} = objCell{it}.sort;
			end
			
756
			[fineGrid, fineGridName] = getFinestGrid(objCell{~isEmpty});
757
			for it = 1 : (numel(varargin) + 1)  % +1 because the first entry is a
758
				% change the grid to the finest
759
				objCell{it} = objCell{it}.changeGrid(fineGrid, fineGridName);
760
			end
Jakob Gabriel's avatar
Jakob Gabriel committed
761
			assertSameGrid(objCell{:});
762
763
			argin = [{dim}, objCell(:)'];
			c = builtin('cat', argin{:});
Jakob Gabriel's avatar
Jakob Gabriel committed
764
765
		end
		
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
		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()
		
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
		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));
822
823
				gridSelector([max(1, find(gridSelector, 1, 'first')-1), ...
					min(find(gridSelector, 1, 'last')+1, numel(gridSelector))]) = 1;
824
825
				limitedGrid = obj(1).grid{1}(gridSelector);
				objCopy = obj.copy();
Jakob Gabriel's avatar
Jakob Gabriel committed
826
				objCopy = objCopy.changeGrid({limitedGrid}, gridName);
827
828
829
830
831
832
				objInverseTemp = objCopy.invert(gridName);
			else
				objInverseTemp = obj.invert(gridName);
			end
			
			solution = objInverseTemp.on(rhs);
833
834
835
836
837
838
839
			
			% 			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));
840
		end % solveAlgebraic()
841
842
843
844
845
846
847
		
		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).
848
849
850
851
852
853
854
			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
			
855
856
			assert(numel(obj(1).gridName) == 1);
			assert(isequal(size(obj), [1, 1]));
857
858
859
			inverse = quantity.Discrete(...
                repmat(obj(1).grid{obj(1).domain.gridIndex(gridName)}(:), [1, size(obj)]), ...
                quantity.Domain([obj(1).name], obj.on()), ...
860
				'name', gridName);
861
		end % invert()
862
863
		
		function solution = solveDVariableEqualQuantity(obj, varargin)
864
			% solves the first order ODE
865
			%	dvar / ds = obj(var(s))
866
			%	var(0) = ic
867
			% to obtain var(s, ic) depending on both the argument s and the initial
868
869
870
871
			% condition ic. Herein, obj may only depend on one variable / gridName / ...
			% domain.
			assert(numel(obj(1).domain) == 1, ...
				'this method is only implemented for quanitities with one domain');
872
873
874
875
876
877
878
			
			myParser = misc.Parser();
			myParser.addParameter('initialValueGrid', obj(1).grid{1});
			myParser.addParameter('variableGrid', obj(1).grid{1});
			myParser.addParameter('newGridName', 's');
			myParser.parse(varargin{:});
			
Ferdinand Fischer's avatar
tmp    
Ferdinand Fischer committed
879
			variableGrid = myParser.Results.variableGrid(:);
880
			myGridSize = [numel(variableGrid), ...
881
882
				numel(myParser.Results.initialValueGrid)];
			
883
884
			% the time (s) vector has to start at 0, to ensure the IC. If
			% variableGrid does not start with 0, it is separated in
885
			% negative and positive parts and later combined again.
Ferdinand Fischer's avatar
tmp    
Ferdinand Fischer committed
886
887
			positiveVariableGrid = [0; variableGrid(variableGrid > 0)];
			negativeVariableGrid = [0; flip(variableGrid(variableGrid < 0))];
888
889
890
891
892
893
894
895
896
897
898
899
			
			% solve ode for every entry in obj and for every initial value
			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), ...
900
							positiveVariableGrid, ...
901
							myParser.Results.initialValueGrid(icIdx));
902
903
904
905
					end
					if numel(negativeVariableGrid) >1
						[resultGridNegative, odeSolutionNegative] = ...
							ode45(@(y, z) obj(it).on(z), ...
906
							negativeVariableGrid, ...
907
							myParser.Results.initialValueGrid(icIdx));
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
					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)]), ...
925
926
				[quantity.Domain(myParser.Results.newGridName, variableGrid), ...
				 quantity.Domain('ic', myParser.Results.initialValueGrid)], ...
927
928
				'size', size(obj), ...
				'name', "solve(" + obj(1).name + ")");
929
		end % solveDVariableEqualQuantity()
930
		
931
		function solution = subs(obj, gridName2Replace, values)
932
			% SUBS substitute variables of a quantity
933
934
935
936
937
938
939
940
941
942
943
944
			%	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.
945
946
947
948
949
950
951
952
			%
			%	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.
953
954
955
			if nargin == 1 || isempty(gridName2Replace)
				% if gridName2Replace is empty, then nothing must be done.
				solution = obj;
956
			elseif isempty(obj)
Ferdinand Fischer's avatar
Ferdinand Fischer committed
957
958
				% if the object is empty, nothing must be done.
				solution = obj;
959
960
			else
				% input checks
961
962
963
964
965
966
967
968
				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);
969
970
971
972
973
					for k = 1:numel( gridName2Replace )
						if isa(gridName2Replace{k}, 'quantity.Domain')
							gridName2Replace{k} = gridName2Replace{k}.name;
						end
					end						
974
					values = misc.ensureIsCell(values);
975
				end
976
				
Jakob Gabriel's avatar
Jakob Gabriel committed
977
978
				assert(numel(values) == numel(gridName2Replace), ...
					'gridName2Replace and values must be of same size');
979
				
980
981
982
983
984
985
986
				% set the newDomain once. If obj(1).domain is a quantity.Equidistant domain, it can
				% not be mixed with other quantity.Domains in an array. Hence, it must be casted to
				% a quantity.Domain. The following strange form of concatenation an empty Domain
				% with the required domain, ensures that the result is an array of quantity.Domain
				% objects.
				newDomain = [quantity.Domain.empty, obj(1).domain];
				
987
988
				% here substitution starts:
				% The first (gridName2Replace{1}, values{1})-pair is
989
990
991
				% 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}).
992
				if ischar(values{1}) || isstring(values{1})
993
994
995
996
997
998
					% 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
999
1000
						% substituion subs(f, z, zeta) the result would be
						% f(zeta, zeta) -> the 2nd subs(f, zeta, z) will
For faster browsing, not all history is shown. View entire blame