-
Notifications
You must be signed in to change notification settings - Fork 47
/
Copy pathPDist.m
4806 lines (4337 loc) · 184 KB
/
PDist.m
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 PDist < TSeries
properties (Access = protected)
type_
species_
depend_
ancillary_
end
properties (Dependent = true)
type
species
depend
ancillary
end
properties (SetAccess = immutable,Dependent = true)
% tensorOrder
% tensorBasis
end
properties (Constant = true, Hidden = true)
% MAX_TENSOR_ORDER = 2;
% BASIS = {'xyz','rtp','rlp','rpz','xy','rp'};
% BASIS_NAMES = {...
% 'Cartesian','Spherical,colatitude', 'Spherical,latitude','Cylindrical',...
% 'Cartesian 2D','Polar 2D'};
end
properties (SetAccess = protected)
% representation
end
properties
% name = '';
% units = '';
% siConversion = '';
% userData = [];
end
methods
function obj = PDist(t,data,varargin) % constructor
% PDIST Create PDIST object.
% Constructor method (PDIST.PDIST) for class PDist.
% Load and work with particle distributions from satellite missions
% such as MMS. For a complete set of methods type >> methods PDIST.
%
% PD = PDIST(time,data,type,depend_var1,...,depend_varN);
% N is the dimension of the input data
% nt is the number of time steps
% time - time in EpochTT format
% data - matrix of data in format [nt, sz1, ..., szN]
% type - type of distribution: 'moms-tens0', 'moms-tens1',
% 'moms-tens2', 'skymap', 'pitchangle', 'omni',
% 'line (reduced)' (same as '1Dcart'), 'plane (reduced)',
% 'plane (slice)', 'box' (same as '3Dcart')
% depend_var - dependent variables (should be as many depend_var
% as dimensions of the data set excluding time), e.g.:
% velocity (km/s),
% energy (eV),
% instrument azimuthal angle (deg),
% instrument polar angle (deg),
% pitchangle (deg)
%
% Note: PDist objects are typically constructed using some
% construction function like mms.make_pdist, mms.get_data for
% skymaps, or different methods of PDIST, like PDIST.reduce or
% PDIST.omni
%
% Example:
% % Note: mms.db_list_files and mms.get_data requires you have
% % database initiated:
% % If MMS data are located in directory:
% % /path/to/your/data/mms1/...
% % /path/to/your/data/mms2/...
% % etc..
% % >> mms.db_init('local_file_db','/path/to/your/data');
%
% % Create skymap distributions from MMS data using mms.get_data
% tint = irf.tint('2017-07-06T13:53:03.00Z/2017-07-06T13:55:33.00Z');
% mms_id = 1;
% iPDist1 = mms.get_data('PDi_fpi_brst_l2',tint,mms_id);
%
% % Create skymap distributions from MMS data using mms.make_pdist
% tint = irf.tint('2017-07-06T13:53:03.00Z/2017-07-06T13:55:33.00Z');
% list_files = mms.db_list_files('mms1_fpi_brst_l2_dis-dist',tint);
% ifile = 1; % in case there are several files, chose one
% filepath = [list_files(ifile).path '/' list_files(ifile).name];
% % It is of course possible to also directly type the path to your file.
% [iPDist1,iPDistErr1] = mms.make_pdist(filepath);
%
% % Create phony 3D distribution on cartesian grid
% m = 9.1094e-31; % electron mass
% n = 1*1e6; % 1/m3
% vd = 1000; % m/s
% T = 1000; % eV
% vt = @(T) sqrt(2*units.kB*T/m); % m/s, thermal speed from temperature
% % Maxwellian distribution
% f = @(vx,vy,vz,T,n,vd) n./((pi)^(3/2).*vt(T).^3).*exp(-(vx-vd).^2./vt(T).^2-(vy).^2./vt(T).^2-(vz).^2./vt(T).^2);
% % Set up velocity grid
% nvx = 50; nvy = 50; nvz = 50;
% vx = linspace(-50,50,nvx); % km/s, depend_var1
% vy = linspace(-50,50,nvy); % km/s, depend_var2
% vz = linspace(-50,50,nvz); % km/s, depend_var3
% t = 0:1; % s, depend_var0
% [~,VX,VY,VZ] = ndgrid(t,vx*1e-3,vy*1e-3,vz*1e-3);
% F = f(VX,VY,VZ,T,n,vd);
% time = EpochTT(t);
% % Create PDist object
% PD = PDIST(time,F,'3Dcart',vx,vy,vz);
%
% See also: TSeries, EpochTT, irf.ts_skymap, mms.get_data,
% mms.make_pdist, PDIST.reduce, PDIST.omni, PDIST.pitchangles,
% mms.db_init
if nargin<2, error('2 inputs required'), end
obj@TSeries(t,data,'to',0);
args = varargin;
if isa(args{1},'char'); obj.type_ = args{1}; args(1) = [];
else, error('3rd input must specify distribution type')
end
% collect required data, depend
switch obj.type_
case {'moms-tens0'} % eg. density or scalar temperature partial moments
obj.depend{1} = args{1}; args(1) = []; obj.representation{1} = {'energy'};
case {'moms-tens1'} % eg. velocitypartial moments
case {'moms-tens2'} % eg. pressure or temperature partial moments
case {'skymap'} % construct skymap distribution
obj.depend{1} = args{1}; args(1) = []; obj.representation{1} = {'energy'};
obj.depend{2} = args{1}; args(1) = []; obj.representation{2} = {'phi'};
obj.depend{3} = args{1}; args(1) = []; obj.representation{3} = {'theta'};
case {'pitchangle'} % construct pitchangle distribution
obj.depend{1} = args{1}; args(1) = []; obj.representation{1} = {'energy'};
obj.depend{2} = args{1}; args(1) = []; obj.representation{2} = {'pitchangle'};
case {'omni'} % construct omni directional distribution
obj.depend{1} = args{1}; args(1) = []; obj.representation{1} = {'energy'};
case {'line (reduced)','1Dcart'} % % construct 1D distribution, through integration over the other 2 dimensions
obj.depend{1} = args{1}; args(1) = []; obj.representation{1} = {'velocity'};
case {'plane (reduced)','2Dcart'} % construct 2D distribution, either through integration or by taking a slice
obj.depend{1} = args{1}; args(1) = []; obj.representation{1} = {'velocity1'};
obj.depend{2} = args{1}; args(1) = []; obj.representation{2} = {'velocity2'};
case {'plane (slice)'} % construct 2D distribution, either through integration or by taking a slice
obj.depend{1} = args{1}; args(1) = []; obj.representation{1} = {'velocity1'};
obj.depend{2} = args{1}; args(1) = []; obj.representation{2} = {'velocity2'};
case {'box','3Dcart'}
obj.depend{1} = args{1}; args(1) = []; obj.representation{1} = {'velocity1'};
obj.depend{2} = args{1}; args(1) = []; obj.representation{2} = {'velocity2'};
obj.depend{3} = args{1}; args(1) = []; obj.representation{3} = {'velocity3'};
otherwise
warning('Unknown distribution type')
end
% Enforce energy to be a timeseries (not much difference in data size anyways)
obj = obj.enforce_depend_timeseries('energy');
% Should check dimension of depends, and switch if they are wrong,
% time should always be first index, and it can be 1 or obj.nt
% This has only been partly implemented here...
% Should be moved to a private method to make code more easily readable.
size_data = size(obj.data);
for idep = 1:numel(obj.depend)
size_dep = size(obj.depend{idep});
if not(size_dep(1) == 1)
if size_dep(2) == 1
obj.depend{idep} = obj.depend{idep}';
end
end
end
% collect additional data into ancillary
while ~isempty(args)
x = args{1}; args(1) = [];
switch lower(x)
case {'energy0'}
obj.ancillary.energy0 = args{1}; args(1) = [];
case {'energy1'}
obj.ancillary.energy1 = args{1}; args(1) = [];
case {'esteptable'}
obj.ancillary.esteptable = args{1}; args(1) = [];
end
end
end
function varargout = subsref(obj,idx)
%SUBSREF handle indexing
switch idx(1).type
% Use the built-in subsref for dot notation
case '.'
[varargout{1:nargout}] = builtin('subsref',obj,idx);
case '()'
tmpEpoch = builtin('subsref',obj.time,idx(1));
obj.t_ = tmpEpoch;
idxTmp = repmat({':'}, ndims(obj.data), 1);
idxTmp(1) = idx(1).subs;
sizeData = size(obj.data_);
obj.data_ = obj.data_(idxTmp{:});
% on depend data
nDepend = numel(obj.depend);
for ii = 1:nDepend
sizeDepend = size(obj.depend{ii});
if sizeDepend(1) == 1 % same dependence for all times
obj.depend_{ii} = obj.depend{ii};
elseif sizeDepend(1) == sizeData(1)
obj.depend_{ii} = obj.depend_{ii}(idxTmp{:},:);
else
error('Depend has wrong dimensions.')
end
end
% pick out correct indices for ancillary data time tables, nb. this
% assumes anything with 'number of rows' = PDist.length is a timetable
if not(isempty(obj.ancillary))
ancillary_fieldnames = fieldnames(obj.ancillary);
new_ancillary_data = obj.ancillary;
for iField = 1:numel(ancillary_fieldnames)
field_data = getfield(obj.ancillary,ancillary_fieldnames{iField});
if isnumeric(field_data) && size(field_data,1) == sizeData(1) % has the same number of rows as the PDist has time indices, assume each row corresponds to the same time index
new_ancillary_data = setfield(new_ancillary_data,ancillary_fieldnames{iField},field_data(idxTmp{1},:,:,:,:,:,:)); % repeated :,:,:,:,:,:, used to support multidimensional data
end
end
obj.ancillary = new_ancillary_data;
end
if numel(idx) > 1
nargout_str = [];
if nargout == 0 % dont give varargout
obj = builtin('subsref',obj,idx(2:end));
else
for inout = 1:nargout % create [out1,out2,...outN] to get the correct number or nargout for rest of subsrefs (idx)
c_eval('nargout_str = [nargout_str ''tmp_vout?,''];',inout)
end
nargout_str = ['[' nargout_str(1:end-1) ']'];
varargout_str = ['{' nargout_str(2:end-1) '}'];
eval(sprintf('%s = builtin(''subsref'',obj,idx(2:end));',nargout_str)) % disp(sprintf('%s = builtin(''subsref'',obj,idx(2:end));',nargout_str))
eval(sprintf('varargout = %s;',varargout_str)); % varargout = {out1,out2,...outN}; % disp(sprintf('varargout = %s;',varargout_str))
end
else
[varargout{1:nargout}] = obj;
end
case '{}'
error('irf:TSeries:subsref',...
'Not a supported subscripted reference')
end
end
% set
function obj = set.species(obj,value)
obj.species_ = value;
end
function obj = set.type(obj,value)
obj.type_ = value;
end
function obj = set.depend(obj,value)
obj.depend_ = value;
end
function obj = set.ancillary(obj,value)
obj.ancillary_ = value;
end
% get
function value = get.species(obj)
value = obj.species_;
end
function value = get.type(obj)
value = obj.type_;
end
function value = get.depend(obj)
value = obj.depend_;
end
function value = get.ancillary(obj)
value = obj.ancillary_;
end
function obj = tlim(obj,tint)
%TLIM Returns data within specified time interval
%
% Ts1 = TLIM(Ts,Tint)
%
% See also: IRF_TLIM
% This needs to be modified from TSeries.m to include tlim on depend
% variables too.
[idx,obj.t_] = obj.time.tlim(tint);
sizeData = size(obj.data_);
nd = ndims(obj.data_);
if nd>6, error('we cannot support more than 5 dimensions'), end % we cannot support more than 5 dimensions
switch nd
case 2, obj.data_ = obj.data_(idx,:);
case 3, obj.data_ = obj.data_(idx,:,:,:);
case 4, obj.data_ = obj.data_(idx,:,:,:,:);
case 5, obj.data_ = obj.data_(idx,:,:,:,:,:);
case 6, obj.data_ = obj.data_(idx,:,:,:,:,:,:);
otherwise, error('should no be here')
end
% on depend data
nDepend = numel(obj.depend);
for ii = 1:nDepend
sizeDepend = size(obj.depend{ii});
if sizeDepend(1) == 1 % same dependence for all times
obj.depend_{ii} = obj.depend{ii};
elseif sizeDepend(1) == sizeData(1)
obj.depend_{ii} = reshape(obj.depend_{ii}(idx,:),[numel(idx) sizeDepend(2:end)]);
else
error('Depend has wrong dimensions.')
end
end
% on ancillary data
if not(isempty(obj.ancillary))
nameFields = fieldnames(obj.ancillary);
nFields = numel(nameFields);
for iField = 1:nFields
eval(['sizeField = size(obj.ancillary.' nameFields{iField} ');'])
if sizeField(1) == sizeData(1)
eval(['obj.ancillary.' nameFields{iField} ' = reshape(obj.ancillary.' nameFields{iField} '(idx,:),[numel(idx) sizeField(2:end)]);'])
end
end
end
end
function obj = resample_depend_ancillary(obj,NewTime,varargin)
TsTmp = obj;
tData = double(TsTmp.time.ttns - TsTmp.time.start.ttns)/10^9;
dataTmp = double(TsTmp.data);
newTimeTmp = double(NewTime.ttns - TsTmp.time.start.ttns)/10^9;
% % reshape data so it can be directly inserted into irf_resamp
% origDataSize = size(dataTmp);
% dataTmpReshaped = squeeze(reshape(dataTmp,[origDataSize(1) prod(origDataSize(2:end))]));
% newDataTmpReshaped = irf_resamp([tData dataTmpReshaped], newTimeTmp, varargin{:}); % resample
% newDataReshaped = squeeze(newDataTmpReshaped(:,2:end)); % take away time column
% newData = reshape(newDataReshaped,[length(newTimeTmp) origDataSize(2:end)]); % shape back to original dimensions
% depend data
sizeData = size(obj.data);
nDepend = numel(obj.depend);
for ii = 1:nDepend
sizeDepend = size(obj.depend{ii});
if sizeDepend(1) == 1 % same dependence for all times
obj.depend_{ii} = obj.depend{ii};
elseif sizeDepend(1) == TsTmp.length
dataTmp = obj.depend{ii};
origDataSize = size(dataTmp);
dataTmpReshaped = squeeze(reshape(dataTmp,[origDataSize(1) prod(origDataSize(2:end))]));
newDataTmpReshaped = irf_resamp([tData dataTmpReshaped], newTimeTmp, varargin{:}); % resample
newDataReshaped = squeeze(newDataTmpReshaped(:,2:end)); % take away time column
newData = reshape(newDataReshaped,[length(newTimeTmp) origDataSize(2:end)]); % shape back to original dimensions
obj.depend_{ii} = newData;
else
error('Depend has wrong dimensions.')
end
end
% ancillary data
if not(isempty(obj.ancillary))
nameFields = fieldnames(obj.ancillary);
nFields = numel(nameFields);
for iField = 1:nFields
eval(['sizeField = size(obj.ancillary.' nameFields{iField} ');'])
if sizeField(1) == TsTmp.length
old_ancillary = eval(['obj.ancillary.' nameFields{iField}]);
% temporary fix for upsampling any non single or double data (esteptable!)
if not(any([isa(old_ancillary,'double'),isa(old_ancillary,'single')]))
old_ancillary = single(old_ancillary);
end
new_ancillary = irf_resamp([tData old_ancillary], newTimeTmp, varargin{:});
eval(['obj.ancillary.' nameFields{iField} ' = new_ancillary(:,2:end);'])
end
end
end
end
function obj = mtimes(obj,value)
obj.data = obj.data*value;
end
function obj = times(obj,value)
obj.data = obj.data.*value;
end
function obj = mdivide(obj,value)
obj.data = obj.data/value;
end
function obj = divide(obj,obj2)
obj.data = obj.data./obj2.data;
end
function [x,y,z] = xyz(obj,varargin)
% PDIST.XYZ Get xyz coordinates of each detector bin.
% PLEASE REPORT ERRORS.
%
% [x,y,z] = PDIST.xyz(options);
% x, y, z - ntx32x16 matrices
% options:
% 'ts' - return x, y, z as TSeries
% xyz - transform x,y,z to new xyz = 3x3: [x,y,z] = PDIST.xyz(xyz);
% x,y,z - transform x,y,z to new x,y,z = 1x3 each: [x,y,z] = PDIST.xyz(x,y,z);
% 'plot' - plots grid, color coded to polar angle
% 'squeeze' - squeezes output data [1 32 16] -> [32 16] if PDist
% only has one time index for example
doReturnTSeries = 0;
doSqueeze = 0;
doRotation = 0;
have_options = 0;
nargs = numel(varargin);
if nargs > 0, have_options = 1; args = varargin(:); end
while have_options
l = 1;
if isnumeric(args{l})
if all(size(args{l}) == [3 3])
newx = args{l}(1,:);
newy = args{l}(2,:);
newz = args{l}(3,:);
args = args(l+1:end);
doRotation = 1;
elseif numel(args{l}) == 3 && numel(args{l+1}) && numel(args{l+2})
newx = args{l};
newy = args{l+1};
newz = args{l+2};
args = args(l+3:end);
doRotation = 1;
end
end
if isempty(args), break, end
switch(lower(args{1}))
case 'ts'
doReturnTSeries = 1;
args = args(l+1:end);
case 'squeeze'
doSqueeze = 1;
args = args(l+1:end);
otherwise
irf.log('warning',sprintf('Input ''%s'' not recognized.',args{1}))
args = args(l+1:end);
end
if isempty(args), break, end
end
phi = TSeries(obj.time,obj.depend{1,2});
azimuthal = phi.data*pi/180;
theta = obj.depend{1,3};
polar = repmat(theta*pi/180,obj.length,1);
x = nan(obj.length,size(azimuthal,2),size(polar,2));
y = nan(obj.length,size(azimuthal,2),size(polar,2));
z = nan(obj.length,size(azimuthal,2),size(polar,2));
for ii = 1:length(obj.time)
[POL,AZ] = meshgrid(polar(ii,:),azimuthal(ii,:));
X = -sin(POL).*cos(AZ); % '-' because the data shows which direction the particles were coming from
Y = -sin(POL).*sin(AZ);
Z = -cos(POL);
if doRotation % Transform into different coordinate system
xX = reshape(X,size(X,1)*size(X,2),1);
yY = reshape(Y,size(Y,1)*size(Y,2),1);
zZ = reshape(Z,size(Z,1)*size(Z,2),1);
newTmpX = [xX yY zZ]*newx';
newTmpY = [xX yY zZ]*newy';
newTmpZ = [xX yY zZ]*newz';
X = reshape(newTmpX,size(X,1),size(X,2));
Y = reshape(newTmpY,size(X,1),size(X,2));
Z = reshape(newTmpZ,size(X,1),size(X,2));
end
x(ii,:,:) = X;
y(ii,:,:) = Y;
z(ii,:,:) = Z;
end
%x = permute(x,[1 3 2]);
%y = permute(y,[1 3 2]);
%z = permute(z,[1 3 2]);
if doSqueeze
x = squeeze(x);
y = squeeze(y);
z = squeeze(z);
end
if doReturnTSeries
x = irf.ts_scalar(obj.time,x);
y = irf.ts_scalar(obj.time,y);
z = irf.ts_scalar(obj.time,z);
end
end
function [vx,vy,vz] = v(obj,varargin)
% PDIST.V Get velocity corresponding to each detector bin. DSL
% coordinates. PLEASE REPORT ERRORS.
%
% [vx,vy,vz] = PDIST.v(options);
% vx, vy, vz - ntx32x32x16 matrices - km/s
% options:
% 'ts' - return x, y, z as TSeries
% xyz - transform x,y,z to new xyz = 3x3: [x,y,z] = PDIST.xyz(xyz);
% x,y,z - transform x,y,z to new x,y,z = 1x3 each: [x,y,z] = PDIST.xyz(x,y,z);
% 'plot' - plots grid, color coded to polar angle
% 'squeeze' - squeezes output data [1 32 32 16] -> [32 32 16]
% if PDist only has one time index for example
% 'scpot' - correct velocity for spacecraft potential
%
% Example:
% f = ePDist(100).convertto('s^3/km^6'); % single time PDist
% f.data(f.data < 2e3) = NaN; % remove low values
% [vx,vy,vz] = f.v('squeeze');
% dotsize = 50;
% scatter3(vx(:)*1e-3,vy(:)*1e-3,vz(:)*1e-3,f.data(:)*0+dotsize,log10(f.data(:)),'filled');
% axis equal; colorbar;
% vlim = [-5 5]; clim = [3 5];
% set(gca,'clim',clim,'xlim',vlim,'ylim',vlim,'zlim',vlim)
units = irf_units;
doScpot = 0;
doReturnTSeries = 0;
doSqueeze = 0;
doRotation = 0;
have_options = 0;
doEdges = 0;
nargs = numel(varargin);
if nargs > 0, have_options = 1; args = varargin(:); end
while have_options
l = 1;
if isnumeric(args{l})
if all(size(args{l}) == [3 3])
newx = args{l}(1,:);
newy = args{l}(2,:);
newz = args{l}(3,:);
args = args(l+1:end);
doRotation = 1;
elseif numel(args{l}) == 3 && numel(args{l+1}) && numel(args{l+2})
newx = args{l};
newy = args{l+1};
newz = args{l+2};
args = args(l+3:end);
doRotation = 1;
end
end
if isempty(args), break, end
switch(lower(args{1}))
case 'ts'
doReturnTSeries = 1;
args = args(l+1:end);
case 'squeeze'
doSqueeze = 1;
args = args(l+1:end);
case 'scpot'
l = 2;
doScpot = 1;
scpot = args{2};
args = args(l+1:end);
case 'edges'
doEdges = 1;
args = args(l+1:end);
otherwise
irf.log('warning',sprintf('Input ''%s'' not recognized.',args{1}))
args = args(l+1:end);
end
if isempty(args), break, end
end
switch obj.type
case 'skymap'
phi = TSeries(obj.time,obj.depend{1,2});
azimuthal = phi.data*pi/180;
theta = obj.depend{1,3};
polar = repmat(theta*pi/180,obj.length,1);
energy = obj.depend{1};
if doEdges % get V at edges of bins
azimuthal = [azimuthal(:,1) - 0.5*(azimuthal(:,2)-azimuthal(:,1)) azimuthal(:,1:end-1) + 0.5*diff(azimuthal,1,2) azimuthal(:,end) + 0.5*(azimuthal(:,end)-azimuthal(:,end-1))];
polar = [polar(:,1) - 0.5*(polar(:,2)-polar(:,1)) polar(:,1:end-1) + 0.5*diff(polar,1,2) polar(:,end) + 0.5*(polar(:,end)-polar(:,end-1))];
de_minus = obj.ancillary.delta_energy_minus;
de_plus = obj.ancillary.delta_energy_plus;
energy = [energy(:,1) - de_minus(:,1) energy + de_plus];
end
if doScpot
if isa(scpot,'TSeries')
scpot = scpot.resample(obj).data;
elseif isa(scpot,'numeric') && isscalar(scpot)
scpot = repmat(scpot,obj.length,1);
elseif isa(scpot,'numeric') && numel(scpot) == obj.length
scpot = scpot;
end
else
scpot = zeros(obj.length,1);
end
vx = NaN*obj.data;
vy = NaN*obj.data;
vz = NaN*obj.data;
if doEdges
sizedata = size(obj.data);
sizedata(2:end) = sizedata(2:end) + 1;
vx = nan(sizedata);
vy = nan(sizedata);
vz = nan(sizedata);
end
sp = obj.species;
switch sp
case 'ions'
m = units.mp;
mult = 1;
case 'electrons'
m = units.me;
mult = -1;
end
for ii = 1:length(obj.time)
% Adjust for spacecraft potential
energy_tmp = energy(ii,:) + mult*scpot(ii);
energy_tmp(energy_tmp<0) = 0; % if scpot is not used, energy_tmp = energy and nothing is changed
% Energy -> speed
velocity = sqrt((energy_tmp)*units.eV*2/m)/1000; % km/s
% ndgrid of spherical coordinates
[VEL,AZ,POL] = ndgrid(velocity,azimuthal(ii,:),polar(ii,:));
% From spherical to cartesian coordinates
% '-' because the data shows which direction the particles were coming from
VX = -VEL.*sin(POL).*cos(AZ);
VY = -VEL.*sin(POL).*sin(AZ);
VZ = -VEL.*cos(POL);
if doRotation % Transform into different coordinate system
VxX = reshape(VX,numel(VX),1);
VyY = reshape(VY,numel(VX),1);
VzZ = reshape(VZ,numel(VX),1);
newTmpX = [VxX VyY VzZ]*newx';
newTmpY = [VxX VyY VzZ]*newy';
newTmpZ = [VxX VyY VzZ]*newz';
VX = reshape(newTmpX,size(VX));
VY = reshape(newTmpY,size(VY));
VZ = reshape(newTmpZ,size(VZ));
end
vx(ii,:,:,:) = VX;
vy(ii,:,:,:) = VY;
vz(ii,:,:,:) = VZ;
end
if 0 % Diagnostics
step = 2; %#ok<UNRCH>
subplot(1,3,1)
scatter3(VX(1:step:end),VY(1:step:end),VZ(1:step:end),VZ(1:step:end)*0+10,VEL(1:step:end)); axis equal
subplot(1,3,2)
scatter3(VX(1:step:end),VY(1:step:end),VZ(1:step:end),VZ(1:step:end)*0+10,AZ(1:step:end)); axis equal
subplot(1,3,3)
scatter3(VX(1:step:end),VY(1:step:end),VZ(1:step:end),VZ(1:step:end)*0+10,POL(1:step:end)); axis equal
end
if doSqueeze
vx = squeeze(vx);
vy = squeeze(vy);
vz = squeeze(vz);
end
if doReturnTSeries
vx = irf.ts_scalar(obj.time,vx);
vy = irf.ts_scalar(obj.time,vy);
vz = irf.ts_scalar(obj.time,vz);
end
case 'pitch'
end
end
function PD = d3v(obj,varargin)
% Calculate phase space volume of FPI bins.
%
% Get partial density by doing: dn = pdist*pdist.d3v;
%
% Options:
% 'scpot',scpot - Corrects for spacecraft potential. For better
% accordance with FPI, multiply scpot with 1.2,
% see mms.psd_moments.
% 'mat' - returns matrix (nt x nE x nAz x nPol) with phase space
% volume
% Default return is f_fpi*d3v, i.e. PDist multiplied with volume
% corresponding to each bin, giving the units of density.
units = irf_units;
doScpot = 0;
doReturnMat = 0;
nargs = numel(varargin);
have_options = 0;
if nargs > 0, have_options = 1; args = varargin(:); end
while have_options
l = 0;
switch(lower(args{1}))
case 'scpot'
scpot = varargin{2};
doScpot = 1;
l = 2;
args = args(l+1:end);
case 'mat'
doReturnMat = 1;
l = 1;
args = args(l+1:end);
otherwise
l = 1;
irf.log('warning',sprintf('Input ''%s'' not recognized.',args{1}))
args = args(l+1:end);
end
if isempty(args), break, end
end
switch obj.units % check units and if they are supported
case 's^3/cm^6' % m^3/s^3 = m^3/s^3 * cm^3/cm^3 = cm^3/s^3 * m^3/cm^3 = cm^3/s^3 * (10^-2)^3
d3v_scale = 1/10^(-2*3);
new_units = 'cm^3/s^3';
case 's^3/m^6' % m^3/s^3 = m^3/s^3 * m^3/m^3 = m^3/s^3 * m^3/m^3 = m^3/s^3 * (10^0)^3
d3v_scale = 1/10^0;
new_units = 'm^3/s^3';
case 's^3/km^6' % m^3/s^3 = m^3/s^3 * km^3/km^3 = km^3/s^3 * m^3/km^3 = km^3/s^3 * (10^3)^3
d3v_scale = 1/10^(3*3);
new_units = 'km^3/s^3';
otherwise
error(sprintf('PDist.d3v not supported for %s',obj.units))
end
% Calculate velocity volume of FPI bin
% int(sin(th)dth) -> x = -cos(th), dx = sin(th)dth -> int(dx) -> x = [-cos(th2) + cos(th1)] = [cos(th1) - cos(th1)]
bin_edge_polar = [obj.depend{3} - 0.5*mean(diff(obj.depend{3})) obj.depend{3}(end) + 0.5*mean(diff(obj.depend{3}))];
d_polar = cosd(bin_edge_polar(1:(end-1))) - cosd(bin_edge_polar(2:end));
d_polar_mat = zeros(size(obj.data));
c_eval('d_polar_mat(:,:,:,?) = d_polar(?);',1:16)
% int(dphi) -> phi
bin_azim = obj.depend{2}(1,2) - obj.depend{2}(1,1);
d_azim = bin_azim*pi/180;
% int(v^2dv) -> v^3/3
if doScpot
E_minus = (obj.depend{1} - obj.ancillary.delta_energy_minus) - repmat(scpot.data,1,size(obj.depend{1},2));
E_plus = (obj.depend{1} + obj.ancillary.delta_energy_plus) - repmat(scpot.data,1,size(obj.depend{1},2));
E_minus(E_minus<0)= 0;
E_plus(E_plus<0)= 0;
else
E_minus = (obj.depend{1} - obj.ancillary.delta_energy_minus);
E_plus = (obj.depend{1} + obj.ancillary.delta_energy_plus);
end
v_minus = sqrt(2*units.e*E_minus/units.me); % m/s
v_plus = sqrt(2*units.e*E_plus/units.me); % m/s
d_vel = (v_plus.^3 - v_minus.^3)/3; % (m/s)^3
d_vel_mat = repmat(d_vel,1,1,32,16);
d3v = d_vel_mat.*d_azim.*d_polar_mat; % (m/s)^3
if doReturnMat
PD = d3v*d3v_scale;
else
PD = obj;
PD.data = d3v*d3v_scale;
PD.units = new_units;
PD.name = 'd3v';
PD.siConversion = num2str(str2num(PD.siConversion)/d3v_scale,'%e');
end
end
function PD = solidangle(obj)
% Solid angle of bins, can for example be used when working with
% pitchangles, or fluxes (where units is flux/sr)
%
% The change in solid angle is only due to the changes in polar (or
% pitch) angle, you therefore get all the unique values as follows:
%
% squeeze(ePDist.solidangle.data(1,1,1,:))
% squeeze(ePDist(1).pitchangles(dmpaB1,15).solidangle.data(1,1,:))
%
% Total solid angle is 4*pi
%
% sum(ePDist.solidangle.data(1,1,:))
% sum(ePDist(1).pitchangles(dmpaB1,15).solidangle.data(1,1,:))
if strcmp(obj.type,'pitchangle')
if isfield(obj.ancillary,'pitchangle_edges') && not(isempty(obj.ancillary.pitchangle_edges))
bin_edge_polar = obj.ancillary.pitchangle_edges;
else
bin_edge_polar = [obj.depend{2} - 0.5*mean(diff(obj.depend{2})) obj.depend{2}(end) + 0.5*mean(diff(obj.depend{2}))];
end
d_polar = cosd(bin_edge_polar(1:(end-1))) - cosd(bin_edge_polar(2:end));
d_polar_mat = zeros(size(obj.data));
c_eval('d_polar_mat(:,:,?) = d_polar(?);',1:numel(obj.depend{2}))
% int(dphi) -> phi
d_azim = 2*pi; % all around
sr_mat = d_polar_mat*d_azim;
elseif strcmp(obj.type,'skymap')
bin_edge_polar = [obj.depend{3} - 0.5*mean(diff(obj.depend{3})) obj.depend{3}(end) + 0.5*mean(diff(obj.depend{3}))];
d_polar = cosd(bin_edge_polar(1:(end-1))) - cosd(bin_edge_polar(2:end));
d_polar_mat = zeros(size(obj.data));
c_eval('d_polar_mat(:,:,:,?) = d_polar(?);',1:16)
% int(dphi) -> phi
bin_azim = obj.depend{2}(1,2) - obj.depend{2}(1,1);
d_azim = bin_azim*pi/180;
sr_mat = d_azim.*d_polar_mat;
else
error(sprintf('PDist.type = %s not supported.',PDist.type))
end
PD = obj;
PD.data = sr_mat;
PD.units = 'sr';
if isfield(PD.ancillary,'meanorsum'), PD.ancillary = rmfield(PD.ancillary,'meanorsum'); end
end
function PD = flux(obj,varargin)
% Flux/sr [cm-2 s-1 sr-1] for skymaps and pitch angle distributions.
% j = int(fv d3v) = int(fv v^2dv sin(th)dth dphi)
% ~> (fv^4/4)*solidangle
%
% Reduced distributions to be added.
%
% To get flux in units [cm-2 s-1], multiply with solid angle:
% ePDist.flux.*ePDist.solidangle
%
% FPI flux in EDI energy range
% dv_FPI_485 = 1760; % km/s
% dv_EDI_500 = 660; % km/s
% ePitch1 = ePDist1.pitchangles(dmpaB1,[168.5 180]); % antiparallel flux
% irf_plot(ePitch1.elim(500).flux*dv_EDI_500/dv_FPI_485)
doScpot = 0;
doPerSr = 1;
doDiff = 0;
nargs = numel(varargin);
have_options = 0;
if nargs > 0, have_options = 1; args = varargin(:); end
while have_options
l = 0;
switch(lower(args{1}))
case 'scpot'
scpot = varargin{2};
doScpot = 1;
l = 2;
case 'sr'
doPerSr = varargin{2};
l = 2;
case 'diff'
doDiff = 1;
l = 1;
otherwise
l = 1;
irf.log('warning',sprintf('Input ''%s'' not recognized.',args{1}))
end
args = args(l+1:end);
if isempty(args), break, end
end
units = irf_units;
if doDiff
PD = obj;
E_mat = repmat(PD.depend{1},1,1,size(PD.depend{2},2)); % eV
E_mat_SI = E_mat*units.e;
if 0
%PD.data = PD.data*2.*E_mat_SI/PD.mass/PD.mass;
PD.data = PD.data*2.*E_mat*units.e/PD.mass/PD.mass; %#ok<UNRCH>
else
v_mat = sqrt(2*units.e*E_mat/obj.mass); % m/s
v_mat = v_mat*1e2; % cm/s
PD.data = PD.data.*v_mat.^2/PD.mass*1e-3;
end
PD.units = '1/(cm^2 s sr eV)';
return
end
% int(v^3dv) -> v^4/4
if doScpot
E_minus = (obj.depend{1} - obj.ancillary.delta_energy_minus) - repmat(scpot.data,1,size(obj.depend{1},2));
E_plus = (obj.depend{1} + obj.ancillary.delta_energy_plus) - repmat(scpot.data,1,size(obj.depend{1},2));
E_minus(E_minus<0)= 0;
E_plus(E_plus<0)= 0;
else
E_minus = (obj.depend{1} - obj.ancillary.delta_energy_minus);
E_plus = (obj.depend{1} + obj.ancillary.delta_energy_plus);
end
v_minus = sqrt(2*units.e*E_minus/units.me); % m/s
v_plus = sqrt(2*units.e*E_plus/units.me); % m/s
d_vel = (v_plus.^4 - v_minus.^4)/4; % (m/s)^3
if strcmp(obj.type,'skymap')
d_vel_mat = repmat(d_vel,1,1,size(obj.depend{2},2),size(obj.depend{3},2));
elseif strcmp(obj.type,'pitchangle')
d_vel_mat = repmat(d_vel,1,1,numel(obj.depend{2}));
end
if doPerSr
vd3v = d_vel_mat;
str_sr = '/sr';
else
solidangle = obj.solidangle;
vd3v = d_vel_mat.*solidangle;
str_sr = '';
end
old_units = obj.units;
switch obj.units
case 's^3/cm^6' % m^4/s^4 = m^4/s^4 * cm^4/cm^4 = cm^4/s^4 * m^4/cm^4 = cm^4/s^4 * (10^-2)^4
d3v_scale = 1/10^(-2*4);
new_units = sprintf('1/cm^2s%s',str_sr);
case 's^3/m^6' % m^4/s^4 = m^4/s^4 * m^4/m^4 = m^4/s^4 * m^4/m^4 = m^4/s^4 * (10^0)^4
d3v_scale = 1/10^0;
new_units = sprintf('1/m^2s%s',str_sr);
case 's^3/km^6' % m^4/s^4 = m^4/s^4 * km^4/km^4 = km^4/s^4 * m^4/km^4 = km^4/s^4 * (10^3)^4
d3v_scale = 1/10^(3*4);
new_units = sprintf('1/km^2s%s',str_sr);
end
PD = obj;
PD.data = PD.data.*vd3v*d3v_scale;
PD.units = new_units;
PD.siConversion = num2str(str2num(PD.siConversion)/d3v_scale,'%e');
end
function PD = flux_red(obj,varargin)
% Flux/sr [cm-2 s-1 sr-1], int(v^3dv) -> v^4/4, for skymaps and pitch angle distributions.
% Reduced distributions to be added.
%
% To get flux in units [cm-2 s-1], multiply with solid angle:
% ePDist.flux.*ePDist.solidangle
%
% FPI flux in EDI energy range
% dv_FPI_485 = 1760; % km/s
% dv_EDI_500 = 660; % km/s
% ePitch1 = ePDist1.pitchangles(dmpaB1,[168.5 180]); % antiparallel flux
% irf_plot(ePitch1.elim(500).flux*dv_EDI_500/dv_FPI_485)
doScpot = 0;
doPerSr = 1;
nargs = numel(varargin);
have_options = 0;
if nargs > 0, have_options = 1; args = varargin(:); end
while have_options
l = 0;
switch(lower(args{1}))
otherwise
l = 1;
irf.log('warning',sprintf('Input ''%s'' not recognized.',args{1}))
args = args(l+1:end);
end
if isempty(args), break, end
end
units = irf_units;
v_minus = obj.ancillary.v_edges(1:end-1); % m/s
v_plus = obj.ancillary.v_edges(2:end); % m/s
d_vel = abs(v_plus.^2 - v_minus.^2)/2; % (m/s)^3
d_vel_mat = repmat(d_vel,obj.length,1);
str_sr = '';
old_units = obj.units;
switch obj.units
case 's^3/cm^6' % m^4/s^4 = m^4/s^4 * cm^4/cm^4 = cm^4/s^4 * m^4/cm^4 = cm^4/s^4 * (10^-2)^4
d3v_scale = 1/10^(-2*4);
new_units = sprintf('1/cm^2s%s',str_sr);
case 's^3/m^6' % m^4/s^4 = m^4/s^4 * m^4/m^4 = m^4/s^4 * m^4/m^4 = m^4/s^4 * (10^0)^4
d3v_scale = 1/10^0;
new_units = sprintf('1/m^2s%s',str_sr);
case 's^3/km^6' % m^4/s^4 = m^4/s^4 * km^4/km^4 = km^4/s^4 * m^4/km^4 = km^4/s^4 * (10^3)^4
d3v_scale = 1/10^(3*4);
new_units = sprintf('1/km^2s%s',str_sr);
end
PD = obj;
PD.data = PD.data.*d_vel_mat*1;
PD.units = 's-1m-2';
PD.data = PD.data*1e-4;
PD.units = 's-1cm-2';
PD.siConversion = '>1e4';%num2str(str2num(PD.siConversion)/d3v_scale,'%e');
end
function PD = reduce(obj,dim,x,varargin)
%PDIST.REDUCE Reduces (integrates) 3D distribution to 1D (line).
% Example (1D):
% f1D = iPDist1.reduce('1D',dmpaB1,'vint',[0 10000]);
% irf_spectrogram(irf_panel('f1D'),f1D.specrec('velocity_1D'));
%
% Example (2D):
% f2D = iPDist1.reduce('2D',[1 0 0],[0 1 0]);
% f2D(100).plot_plane
% [h_surf,h_axis,h_all] = f2D(100).plot_plane;
%
% See more example uses in Example_MMS_reduced_ion_dist,
% Example_MMS_reduced_ele_dist, and Example_MMS_reduced_ele_dist_2D