-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDataset.m
More file actions
1921 lines (1806 loc) · 82.4 KB
/
Dataset.m
File metadata and controls
1921 lines (1806 loc) · 82.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
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
134
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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
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
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
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
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
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
560
561
562
563
564
565
566
567
568
569
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
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
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
665
666
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
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
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
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
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
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
classdef Dataset
properties (SetAccess = public, GetAccess = public)
phase % phase [length(wavelength) x polarization x N]
absEff % absulute efficiency [length(wavelength) x polarization x N]
relEff % relative efficiency [length(wavelength) x polarization x N]
pattern % 1xN cell array of pattern geometries, generator functions
% that take a two integer (or a scalal) value as argument for the
% size of the image
object (1,1) Optimizer % Optimizer object for record. It's assumed (and verified) that
% devices in a given dataset are identical (at least the
% properties that Optimizer's eq method compares)
end
properties (Dependent)
wavelength % returns wavelength property from the Optimizer in the 'object' property
end
properties (Dependent, Hidden = true)
property % returns all (even hidden and private), but not Dependent properties
end
properties (SetAccess = public, GetAccess = public, Hidden = false)
tgtPhiCoeffs % 3xnumPol vector, where rows are delta2_phi, delta_phi, phi_zero
phiCoeffs % for the output of getPhi
start StartDataset % stores start patterns and their characteristics used for the optimizations
hash % SHA-1 hash cell array of devices (some of the methods use it)
end
properties (Access = public)
info % comment and information string
end
methods
%------------------------------------------
%%% Constructor
%------------------------------------------
function obj = Dataset(data)
% data can be:
% - instance or array of class Optimizer
% - a struct with fields of the same names as Dataset properties
% arrays of struct give arrays of Dataset, while arrays of
% Optimizer are gathered into instances of Dataset according to
% their eq method
if nargin > 0
if isa(data, 'Optimizer')
if numel(data) > 1
test = eq(data(1), data, false);
% if there are objects that correspond to different
% geometries, group them together
if sum(test) ~= numel(data)
obj = [Dataset(data(test)) Dataset(data(~test))];
return
end
end
obj.object = rmres(data(1));
nwl = length(data(1).wavelength);
numPol = data(1).numPol;
robustInd = data(1).robustStartDeviation == 0;
% avoid squeeze for the fear of dimensions of length 1 that we'd like
% to keep (what if nwl == 1 and numPol == 1)
fields = {'phase', 'absEff', 'relEff'};
for f = 1:length(fields)
val = cat(5, data.(fields{f}));
if ~isempty(val)
obj.(fields{f}) = reshape(val(end, :, :, robustInd, :), nwl, numPol, []);
end
end
obj.tgtPhiCoeffs = cat(3, data.tgtPhiCoeffs);
if size(obj.tgtPhiCoeffs,1) < 3
% exact values given, return to order:
% [wavelength, polarization, device] and get
% the coefficients
tgtphase = permute(obj.tgtPhiCoeffs, [2 1 3]);
[~, obj.tgtPhiCoeffs] = getPhi(set(obj,'phase',tgtphase));
obj.tgtPhiCoeffs = obj.tgtPhiCoeffs(:,:,:,1);
end
% this if prevents infinite loops
if ~isa(obj, 'StartDataset') % isa(obj, 'Dataset') says yes for subclasses
obj.start = StartDataset(data);
end
obj = obj.getPhi;
obj.pattern = {data.finalPattern};
obj.hash = cellfun(@(x) DataHash(x, 'SHA-1'), obj.pattern, 'UniformOutput', false);
else
switch class(data)
case 'struct'
obj = repmat(obj, size(data));
names = fieldnames(data);
for n = 1:length(names)
try
[obj.(names{n})] = data.(names{n});
catch
disp(['There is no ', names{n}, ' property. Skipping...'])
end
end
if length([obj.hash]) ~= length([obj.pattern])
for n = 1:numel(obj)
if ~iscell(obj(n).pattern)
obj(n).pattern = {obj(n).pattern};
end
obj(n).hash = arrayfun(@(x) DataHash(x{1}, 'SHA-1'), obj(n).pattern, 'UniformOutput', false);
end
end
case 'StartDataset'
% just copying all the fields that are preset in
% Dataset (subclasses can have additional ones)
obj = repmat(obj, size(data));
names = properties(Dataset);
for n = 1:length(names)
[obj.(names{n})] = data.(names{n});
end
case 'Dataset'
obj = data;
otherwise
error('Object of class %s is not convertible to Dataset', class(data))
end
end
end
end
%------------------------------------------
%%% End constructor
%------------------------------------------
%------------------------------------------
%%% Basic operations methods
%------------------------------------------
function varargout = subsref(self, s)
% overload dot-indexing, so that we can reference object's
% properties without having to type the word object, i.e.
% d.period (d.p), instead of d.object.period
if strcmp(s(1).type, '.') && ~isprop(self(1), s(1).subs) && ~ismethod(self, s(1).subs)
s(1).subs = self.object.substituteShortNames(s(1).subs);
if isprop(self.object, s(1).subs)
varargout = cellfun(@(x)subsref(x,s(1)),{self.object},'UniformOutput',false);
s = s(2:end);
end
if ~isempty(s)
[varargout{:}] = cellfun(@(x)subsref(x,s), varargout, 'UniformOutput', false);
end
else
f = find(strcmp({s.type}, '.'));
% fix for function call with no arguments
if ~isempty(f) && any(cellfun(@(m)ismethod(self,m),{s(f).subs}))
varargout = cell(1, nargout);
else
varargout = cell(1, max(1,nargout));
end
try
[varargout{:}] = builtin('subsref', self, s);
catch ME
if strcmp(ME.identifier,'MATLAB:TooManyOutputs')
try
builtin('subsref', self, s);
catch
rethrow(ME)
end
else
rethrow(ME)
end
end
end
end
function self = append(self, data, force)
% case 1: data - object, array, or cell arry of objects of class Optimizer
% case 2: data - struct with (at least some of) the same fields as Dataset
% case 3: data - object, array, or cell arry of objects of class Dataset
% force == 1,-1,0 -> if wavelength array have different step, but
% the same boundaries, interpolate (get missing values for the
% Dataset with less sampled points), downsample (remove values from
% Dataset with more sampled points), or ask, respecively.
% -2, 2 -> prepend/append to the array
% In the end, number of wavelength points has to be the same,
% because otherwise, some properties would be matrices of different
% size in the first dimension and could be contactentated.
% If imag(force) ~= 0, i.e. force = -1i, 1i, we ignore the object
% comparisoin step. It's useful when we want to visualize devices of
% various geometries (like periods, heights), but in the same band
if nargin == 2
force = 0;
end
if isa(data, 'cell')
data = [data{:}];
end
% convert convertable classes to Dataset
if ~isa(data, 'Dataset')
data = Dataset(data);
end
if numel(self) > 1
for ii = 1:length(data)
% adding data one by one
self = append(data(ii), self, force);
end
return
end
%%% At this stage self is considered a scalar object
% In the case where data is an array, we choose the first
% Dataset with the same object, append to it and return the
% whole array, or look for potential interpolate candidates.
% One could have this code work for verctor data, but it's
% simpler like that and it is done so that we append self
% only to one of the data element, instead of merging them
if numel(data) > 1
I = find(cellfun(@(x) eq(self.object, x, false), {data.object}), 1);
if isempty(I)
% check for potential interpolation candidates
I = cellfun(@(x) isequal(self.wavelength([1 end]), x([1 end])), {data.wavelength});
% make sure that other than the wavelength objects are equal
II = cellfun(@(x) eq(set(self.object, 'wavelength', []), ...
set(x, 'wavelength', []), false), {data.object});
I = find(I & II);
if I
% act according to force on the first match
% (attention note below applies)
data(I(1)) = append(self, data(I(1)), force);
else
switch force
case -2
data = [self, data];
case 2
data = [data, self];
otherwise
error('Cannot expand dataset, geometries appear to be different.');
end
end
else
% attention: output has to be the same size as data(I)
% In principle, should be the case, as, even if passed
% with abs(force)==2, objects in data and self have
% already been compared.
data(I) = append(self, data(I), force);
end
self = data;
return
end
%%% At this stage data, in addition to self, is considered a scalar object
% this is rather for empty instances that cause errors otherwise
if isempty(self)
self = data;
return
elseif all(isempty(data))
return
end
if imag(force)
force = imag(force);
else
% wavelengths will be taken care of later
assert(set(self.object,'wavelength',[]) == set(data.object,'wavelength',[]), ...
'Dataset objects appear to be different. Use imaginary force parameter to igone this.')
end
% if the wavelength arrays are not equal, check if we can
% interpolate or downsample the values, or if we should simply
% append to the Dataset array
if ~isequal(self.wavelength, data.wavelength)
if force == -2
self = [self, data];
return
elseif force == 2
self = [data, self];
return
end
if length(self.wavelength) > 1 && length(data.wavelength) > 1 && isequal(self.wavelength([1 end]), data.wavelength([1 end]))
if ~force
while true
reply = input('Wavelength properties have different step sizes, interpolate [i], downsample [d], or quit [q]? ([i] by default): ', 's');
if isempty(reply) || strcmpi(reply, 'i')
force = 1;
break
elseif strcmpi(reply, 'd')
force = -1;
break
elseif strcmpi(reply, 'q')
error('Cannot expand dataset, wavelengths appear to be different')
else
disp("Didn't catch it, try again.");
end
end
end
if force == 1 % force interpolation
% disp('Interpolating....')
if length(self.wavelength) < length(data.wavelength)
self = interpData(self, data.wavelength);
else
data = interpData(data, self.wavelength);
end
elseif force == -1 % force downsampling
% disp('Downsampling....')
if length(self.wavelength) < length(data.wavelength)
data = interpData(data, self.wavelength);
else
self = interpData(self, data.wavelength);
end
end
elseif ~isempty(intersect(self.wavelength, data.wavelength))
if force == -1
self = interpData(self, intersect(self.wavelength, data.wavelength));
data = interpData(data, intersect(data.wavelength, data.wavelength));
else
error(['Cannot expand dataset, wavelengths appear to be different. Cannot extrapolate.\n',...
'Use option force == -1 or -1i to downsample at the intersection wavelengths.'])
end
else
error('Cannot expand dataset, wavelengths appear to be different')
end
end
% not necessarily "better" than having a case for each
% property, but at least we do not have to hard-code their
% names
props = self.property;
for ii = 1:length(props)
if ~isempty(self.(props{ii})) % to prevent annoying 0x0xN matrices and infinite loops on 'start'
switch class(self.(props{ii}))
case 'double'
self.(props{ii}) = cat(3, self.(props{ii}), data.(props{ii}));
case 'cell'
self.(props{ii}) = [self.(props{ii}), data.(props{ii})];
case 'StartDataset'
self.(props{ii}) = append(self.(props{ii}), data.(props{ii}), force*1i);
% explanation for the force argument: if we reached this line,
% objects are either compared or ignored already, if force was
% 0, we don't ask the second time for the start Dataset
case {'string', 'char'}
% add to string array strings that are not equal
self.(props{ii}) = [self.(props{ii}), data(~strcmpi(self.(props{ii}), data.(props{ii}))).(props{ii})];
end
end
end
end % function append
function self = plus(self, data, varargin)
% basically redundant, but it's tied to '+' and I'm used to append
self = self.append(data, varargin{:});
end
function self = minus(self, data, ignoreObject)
% when substracting with ignoreObject option set to true,
% we compare the patterns (through hashes) only, nothing else,
% thus the data could be for different bands, but as
% long as the patterns are identical, they're considered equal.
% ignoreObject = true by default, since usually, it would mean the patterns are
% the result of the same calculation, we just have modified the
% band, which we can always do again
if nargin < 3
ignoreObject = true;
end
if ~isa(data, 'Dataset')
data = Dataset(data);
end
if self.object ~= data.object && ~ignoreObject
error("The two datasets seem to have different ojects, use ignoreObject=true to proceed anyway.")
end
self = self.remove(data.hash);
end
function self = merge(self, data, force, opt)
% self and data can each be Dataset arrays which are merged into a
% single Dataset object. See append for force options.
% opt can be specified as 'nounique' to skip the use of the unique
% function
if nargin < 3
force = 0;
end
if nargin < 2
data = [];
end
if length(self) > 1
[self, data] = deal(self(1), [self(2:end), data]);
end
for ii = 1:length(data)
self = self.append(data(ii), force);
end
if nargin == 4 && strcmpi(opt,'nounique')
elseif nargin == 4 && ~strcmpi(opt,'nounique')
error("Argument #4 can only be 'nounique'")
else
self = unique(self);
end
end
function self = sum(self, varargin)
% merges array of Dataset instances into a single one.
% See merge for varargin options.
self = merge(self(1), self(2:end), varargin{:});
end
function [tf, equals] = eq(obj1, obj2)
% checks equality of two dataset objects, or arrays thereof,
% tf is the answer whether they are equal or not,
% equals is a logical array of elements that are.
% Note: it's not very good for much, since it compare two arrays in
% sequence, checking if they are basically identical copies of each
% other. For sorting-independent inquiries, use functions like
% setdiff and such
if length([obj1.hash]) == length([obj2.hash])
equals = strcmp(obj1.hash, obj2.hash);
tf = all(equals);
else
error(['Two sets seem to have a different number of elements. ',...
'Use other functions, like setdiff and such, for more info.'])
end
end
function [d, I] = reduce(d, tol_pz, tol_dp, tol_d2p)
% reduces the number of entries in the dataset by considering all
% the devices in the phase plane (volume) of size tol_pz x tol_dp
% (x tol_d2p) and choosing only one with the highest absEff among
% them. Units = radians
% if tol_d2p is not given (or is empty), first order fit is used.
% If only tol_pz is given, tol_dp = tol_pz.
% I - logical vector of length d.numdev where 1 stand for entries
% to keep.
if nargin < 4 || isempty(tol_d2p)
order = 1;
else
order = 2;
end
if nargin < 2; tol_pz = 0.025*pi; end
if nargin < 3; tol_dp = tol_pz; end
if numel(d) > 1
if nargin == 4
[d, I] = arrayfun(@(d)reduce(d, tol_pz, tol_dp, tol_d2p), d, 'UniformOutput', false);
else
[d, I] = arrayfun(@(d)reduce(d, tol_pz, tol_dp), d, 'UniformOutput', false);
end
d = reshape([d{:}], size(d));
return
end
for ipol = 1:size(d.phiCoeffs,2)
if ~isempty(d.phiCoeffs)
coeffs = squeeze(d.phiCoeffs(:,ipol,:,order));
else
error('phiCoeffs property empty. Run getPhi function on the Dataset to calculate them.')
end
avreff = squeeze(mean(d.absEff, 1));
dpGrid = min(coeffs(2,:)) : tol_dp : max(coeffs(2,:)) + tol_dp;
pzGrid = min(coeffs(3,:)) : tol_pz : max(coeffs(3,:)) + tol_pz;
if order == 1
d2pGrid = [0 1.e-6];
else
d2pGrid = min(coeffs(1,:)) : tol_d2p : max(coeffs(1,:)) + tol_d2p;
end
I = false(1,d.numdev);
for ii = 1:length(dpGrid)-1
for jj = 1:length(pzGrid)-1
for kk = 1:length(d2pGrid)-1
J = coeffs(2,:) >= dpGrid(ii) & coeffs(2,:) < dpGrid(ii+1) & ...
coeffs(3,:) >= pzGrid(jj) & coeffs(3,:) < pzGrid(jj+1) & ...
coeffs(1,:) >= d2pGrid(kk) & coeffs(1,:) < d2pGrid(kk+1);
[~, ia] = max(avreff(J));
f = find(J);
I(f(ia)) = true;
end
end
end
if ipol == 1
Itmp = I;
else
I = I & Itmp;
end
end
d = d.get(I);
end
%------------------------------------------
%%% End operations methods
%------------------------------------------
%------------------------------------------
%%% Lookup and get methods
%------------------------------------------
function tf = isempty(self)
if numel(self) > 1
tf = arrayfun(@isempty, self);
return
end
if numel(self) == 0
tf = true;
return
end
tf = isempty(self.phase) && isempty(self.absEff) && ...
isempty(self.relEff) && isempty(self.pattern);
end
function [tf, I] = contains(self, device)
% device can be either a pattern, hash, or an Optimizer object, or
% a matrix of those, or even cell array of objects of mixed kind
% tf - True/False answer
% I - index where match was found
if numel(device) > 1
[tf, I] = arrayfun(@(d)contains(self, d), device);
return
end
if iscell(device)
device = device{1};
end
if isa(device, 'Optimizer')
device = device.finalPattern;
elseif isnumeric(device)
device = DataHash(device, 'SHA-1');
elseif ~ischar(device)
error('Wrong device format');
end
I = find(strcmp(self.hash, device));
if I
tf = true;
else
tf = false;
end
end
function self = remove(self, device)
% device can be specified as either a:
% - scalar index
% - array of indices
% - hash/cell arry of hashes
% - pattern/cell array of patterns
% - Optimizer object or their array/cell array
if numel(self) > 1
self = arrayfun(@(x) remove(x, device), self);
return
end
if isa(device, 'Optimizer')
device = device.finalPattern;
end
if isnumeric(device) || islogical(device)
if all(size(device) > 1) % single pattern image
device = {device};
else % a single or an arry of indices
I = device;
end
elseif ischar(device) || ... % single hash
isa(device, 'function_handle') % single generator function
device = {device};
end
if iscell(device)
if ~ischar(device{1}) % not already a hash
device = cellfun(@(x) DataHash(x, 'SHA-1'), device, 'UniformOutput', false);
end
% 'UniformOutput',false prevents error if one of the
% devices is not found in the hash array
I = cellfun(@(x) find(strcmp(self.hash, x)), device, 'UniformOutput', false);
I = cell2mat(I);
end
% at this stage, I stores indices to be removed
props = self.property;
for ii = 1:length(props)
if ~isempty(self.(props{ii})) % to prevent annoying 0x0xN matrices and infinite loops on 'start'
switch class(self.(props{ii}))
case 'double'
self.(props{ii})(:,:,I,:) = [];
case 'cell'
self.(props{ii})(I) = [];
case 'StartDataset'
self.(props{ii}) = remove(self.(props{ii}), I);
end
end
end
end
function [I, devs] = find(self, device)
% device is specified by a scalar or vector of either a pattern,
% a hash, or an Optimizer
if isa(device, 'Optimizer')
device = device.finalPattern;
end
if ischar(device) || isnumeric(device) || ... % single hash or single pattern
isa(device, 'function_handle') % single generator function
device = {device};
end
if ~ischar(device{1})
device = cellfun(@(x) DataHash(x, 'SHA-1'), device, 'UniformOutput', false);
end
% 'UniformOutput',false, again, to deal with empty vectors,
% when match not found
I = arrayfun(@(x) find(strcmp(self.hash, x)), device, 'UniformOutput', false);
I = cell2mat(I);
if nargout == 2
devs = self.get(I);
end
end
function self = get(self, I)
% returns subset of devices given by indices in I
if numel(self) > 1
if iscell(I) && numel(I) == numel(self)
self = arrayfun(@(x,y)get(x,y{1}),self,I);
elseif ~iscell(I)
self = arrayfun(@(x)get(x,I),self);
else
error('Wrong input')
end
return
end
I = I(:);
props = self.property;
for ii = 1:length(props)
if ~isempty(self.(props{ii})) % to prevent annoying 0x0xN matrices and infinite loops on 'start'
switch class(self.(props{ii}))
case 'double'
self.(props{ii}) = self.(props{ii})(:,:,I,:);
case 'cell'
self.(props{ii}) = self.(props{ii})(I);
case 'StartDataset'
self.(props{ii}) = get(self.(props{ii}),I);
end
end
end
end
function [self, I] = rmnan(self)
% remove patterns that are all nans
I = find(cellfun(@(x) any(isnan(x(:))), self.pattern));
self = remove(self, I);
end
function N = numdev(self)
% returns the number of devices in the Dataset or their array
if numel(self) > 1
N = arrayfun(@numdev, self);
N = sum(N(:));
return
elseif numel(self) == 0
N = 0;
return
end
if ~isempty(self.pattern)
N = length(self.pattern);
elseif ~isempty(self.phase)
N = size(self.phase, 3);
elseif ~isempty(self.absEff)
N = size(self.phase, 3);
else
N = 0;
end
end
function N = numsdev(self)
N = numdev([self.start]);
end
function N = numsunique(self)
s = [self.start];
s = s.recalcHash;
N = length(unique([s.hash]));
end
function phase = targetPhase(self)
if numel(self) > 1
phase = arrayfun(@targetPhase, self, 'UniformOutput', false);
return
end
if size(self.tgtPhiCoeffs,1) == 3 % coefficients given
phase = self.get_phase(self.tgtPhiCoeffs);
else
phase = self.tgtPhiCoeffs;
end
end
function wl = get.wavelength(self)
wl = self.object.wavelength;
end
function self = set.wavelength(self, wl)
self.object.wavelength = wl;
end
function self = set.pattern(self, p)
if ~iscell(p) && ~isempty(p), p = {p}; end
self.pattern = p;
end
function props = get.property(self)
m = metaclass(self);
props = {m.PropertyList.Name};
props = props(~[m.PropertyList.Dependent]);
end
%------------------------------------------
%%% End lookup and get methods
%------------------------------------------
%------------------------------------------
%%% Set methods
%------------------------------------------
function [C, ia, ib] = intersect(A, B)
% Similar to built in intersect, overloaded for Dataset. See help intersect.
[~, ia, ib] = intersect(A.hash, B.hash, 'stable');
C = A.get(ia);
end
function [Lia, Locb] = ismember(A, B)
% Similar to built in ismember, overloaded for Dataset. See help ismember.
[Lia, Locb] = ismember(A.hash, B.hash, 'stable');
end
function [C, ia] = setdiff(A, B)
% Similar to built in setdiff, overloaded for Dataset. See help setdiff.
[~, ia] = setdiff(A.hash, B.hash, 'stable');
C = A.get(ia);
end
function [C, ia, ib] = setxor(A, B)
% returns the data of A and B that are not in their intersection,
% with no repetitions, in other words, the data that occurs in A or B, but not both
[~, ia, ib] = setxor(A.hash, B.hash, 'stable');
C = A.get(ia) + B.get(ib);
end
function [C, ia, ib] = union(A, B)
% Similar to built in union, overloaded for Dataset. See help union.
% Kind of repeats basic functionality of merge, but merge is still
% useful on dataset arrays.
[~, ia, ib] = union(A.hash, B.hash, 'stable');
C = A.get(ia) + B.get(ib);
end
function [C, ia, ic] = unique(A)
% Similar to built in unique, overloaded for Dataset. See help unique.
if numel(A) > 1
sz = size(A);
[C, ia, ic] = arrayfun(@unique, A, 'UniformOutput', false);
C = [C{:}];
C = reshape(C, sz);
return
end
if numel(A.hash) ~= numel(A.pattern)
A = recalcHash(A);
end
[~, ia, ic] = unique(A.hash, 'stable');
C = A.get(ia);
end
%------------------------------------------
%%% End set methods
%------------------------------------------
%----------------------------------------------------
%%% Filtering and sorting methods
%----------------------------------------------------
function self = cutwl(self, varargin)
% cutwl(d, arr) -- arr=array of discreet wavelengths of length >= 1
% cutwl(d, wl_min, wl_max) -- closest min and max
% leaves data in the dataset that is related to a specific single
% wavelength, bounded by some min and max values, or for specific
% wavelengths in an array arr
if numel(self) > 1
self = arrayfun(@(s) cutwl(s,varargin{:}), self);
return
end
[wl_max, wl_min, I] = deal([]);
switch length(varargin)
case 1
[~, I] = intersect(self.wavelength, varargin{1});
case 2
[wl_min, wl_max] = varargin{:};
otherwise
error('Too many input arguments');
end
if isempty(I)
[~, imin] = min(abs(self.wavelength - wl_min));
[~, imax] = min(abs(self.wavelength - wl_max));
I = imin:imax;
end
self.wavelength = self.wavelength(I);
props = self.property;
for ii = 1:length(props)
if ~isempty(self.(props{ii}))
switch class(self.(props{ii}))
case 'double'
if ~contains(props{ii}, 'hiCoeffs')
self.(props{ii}) = self.(props{ii})(I,:,:);
end
case 'StartDataset'
self.(props{ii}) = cutwl(self.(props{ii}), varargin{:});
end
end
end
end
function [self, I] = cuteff(self, eff, opt)
if nargin < 3
opt = 'mean';
end
switch opt
case 'mean'
fun = @(x) reshape(mean(x, 1), [], 1);
case 'min'
fun = @(x) reshape(min(x, [], 1), [], 1);
end
I = fun(self.absEff) > eff;
self = self.get(I);
end
function [self, I] = cutphi(self, opt, varargin)
% [self, I] = cutphi(self, opt, phi_min, phi_max)
% [self, I] = cutphi(self, opt, [phi_min, phi_max])
% [self, I] = cutphi(self, opt, phi_val)
% [self, I] = cutphi(_____, polopt)
% leaves only entries whose phase fit coefficient, specified by opt,
% is in the given interval, or equal to a specific value phi_val.
% opt can be 'pz' or 'dp' for phi_zero and delta_phi in linear fit,
% or 'd2p' for delta^2_phi in the quadratic one
% I is a logical vector such that self_new = self_old.get(I);
% polopt is a char array which is either 'both' or 'either'. It is
% appropriate in the case of both polarizations, when we have two
% different sets of phase coefficient and we want to leave the
% intersection or union of their subsets, respectively. Default:
% 'either'.
if numel(self) > 1
[self, I] = arrayfun(@(x)cutphi(x,opt,varargin{:}), self, 'UniformOutput', false);
self = reshape([self{:}], size(self));
return
end
polopt = 'either';
switch length(varargin)
case 3
[phi_min, phi_max, polopt] = varargin{:};
case 2
[phi_min, phi_max] = varargin{:};
if length(phi_min) == 2
polopt = phi_max;
phi_max = phi_min(2);
phi_min = phi_min(1);
end
case 1
phi_min = varargin{1}(1);
phi_max = varargin{1}(end);
end
for ipol = 1:size(self.phiCoeffs,2)
if ~isempty(self.phiCoeffs)
switch opt
case 'dp'
coeffs = squeeze(self.phiCoeffs(2,ipol,:,1));
case 'pz'
coeffs = squeeze(self.phiCoeffs(3,ipol,:,1));
case 'd2p'
coeffs = squeeze(self.phiCoeffs(1,ipol,:,2));
end
else
error('phiCoeffs property empty. Run getPhi function on the Dataset to calculate them.')
end
I = coeffs >= phi_min & coeffs <= phi_max;
if ipol == 1
Itmp = I;
else
switch polopt
case 'both'
I = Itmp & I;
case 'either'
I = Itmp | I;
otherwise
error("polopt argument can be either 'both' or 'either'")
end
end
end
self = self.get(I);
end
function [self, I] = cutpz(self, varargin)
% alias for cutphi with the pz option
[self, I] = cutphi(self, 'pz', varargin{:});
end
function [self, I] = cutdp(self, varargin)
% alias for cutphi with the dp option
[self, I] = cutphi(self, 'dp', varargin{:});
end
function [self, I] = cutoutliers(self)
% removes outliers in terms of the delta phi value
if numel(self) > 1
[self, I] = arrayfun(@cutoutliers, self, 'UniformOutput', false);
self = reshape([self{:}], size(self));
else
med = median(squeeze(self.phiCoeffs(2,:,:,1)));
sig = sqrt(std(squeeze(self.phiCoeffs(2,:,:,1))));
[self, I] = cutphi(self, 'dp', med-sig, med+sig);
end
end
function [self, I] = cutff(self, ffmin, ffmax)
% filters the dataset, leaving the entries whose filling fraction
% of the material is between the ffmax and ffmin values.
% I is a logical vector such that self_new = self_old.get(I);
if nargin < 3 || isempty(ffmax)
ffmax = 1;
end
if isempty(ffmin)
ffmin = 0;
end
I = false(1,self.numdev);
for ii = 1:numel(I)
pat = self.gp(ii);
ff = sum(pat(:))/numel(pat);
I(ii) = ff >= ffmin & ff <= ffmax;
end
self = self.get(I);
end
function [self, I] = filtMinSize(self, varargin)
% [self, I] = filtMinSize(self, mfs) - checks both min distance
% (equal to mfs) and area (equal to pi*(mfs/2)^2)
% [self, I] = filtMinSize(self, mfs, mfa) - checks min distance mfs
% and min area mfa
% [self, I] = filtMinSize(self, mfs, 'd') - checks only min
% distance mfs
% [self, I] = filtMinSize(self, mfa, 'a') - checks only min area
% mfa
% ______ = filtMinSize(_______, 'inverted', true/false) - flag that
% says whether to look at the image where pixel values are flipped
% Units are those of self.object.unit.
% Outputs: self - filtered Dataset, I - array of length self.numdev,
% where true's are in the position of entries that passed one or
% both checks, according to the input, and false's for those that
% did not (false by default).
% varargin pre-processing. At the moment there's only one real
% name/value pair. If more are added, one should switch to
% using updatestruct, as usual.
if length(varargin) > 2 % inverted option given
assert(strcmp(varargin{end-1}, 'inverted'), 'Wrong input arguments.')
try_inverted = varargin{end};
varargin = varargin(1:end-2);
else
try_inverted = false;
end
if length(varargin) == 1
mfs = varargin{1};
mfa = pi*(mfs./2).^2;
elseif length(varargin) == 2
switch varargin{2}
case 'd'
mfs = varargin{1};
mfa = 0;
case 'a'
mfs = 0;
mfa = varargin{1};
otherwise
[mfs, mfa] = varargin{:};
end
else
error('Wrong input arguments.')
end
I = true(size(self.pattern));
gridSize = @(x) mean(size(x)./self.object.period);
% try again only those not already rejected by the previous test
% Narrow feature test is stricter, so it goes first
ispost = polarity(self);
patterns = self.gp;
patterns(~ispost) = cellfun(@(x)~x, patterns(~ispost), 'UniformOutput', false);
if mfa
I = cellfun(@(x) checkNarrowFeat(x, 2*sqrt(mfa/pi)*gridSize(x), try_inverted, true), patterns);
I(I) = cellfun(@(x) checkMinArea(x, mfa*gridSize(x)^2, try_inverted), patterns(I));
end
if mfs
I(I) = cellfun(@(x) checkNarrowFeat(~x, mfs*gridSize(x), try_inverted, true), patterns(I));
I(I) = cellfun(@(x) checkMinDist(x, mfs*gridSize(x), try_inverted), patterns(I));
end
self = self.get(I);
end
function [d, dd, ispost] = polsort(d)
% splits Dataset d into two: d - with patterns being hole-like
% (continuous region of 1s), and dd - post-like (continuous region of 0s).
% ispost is a logical vector of length being the input number of
% patterns, true stands for posts and false for holes
ispost = polarity(d.gp);
if nargout > 1
dd = d.get(ispost);
end
d = d.get(~ispost);
end
function [d, ia, ib] = filtpershift(d)