/
vlsvutility.jl
1553 lines (1258 loc) · 47.8 KB
/
vlsvutility.jl
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
# Utility functions for processing VLSV data.
"""
getcell(meta::MetaVLSV, location:::AbstractVector{<:AbstractFloat}) -> Int
Return cell ID containing the given spatial `location` in meter, excluding domain
boundaries. Only accept 3D location.
"""
function getcell(meta::MetaVLSV, loc::AbstractVector{<:AbstractFloat})
(;coordmin, coordmax, dcoord, ncells, celldict, maxamr) = meta
foreach( (i,comp) -> coordmin[i] < loc[i] < coordmax[i] ? nothing :
error("$comp coordinate out of bound!"), 1:3, 'x':'z')
indices = @inbounds ntuple(i -> round(Int, (loc[i] - coordmin[i]) ÷ dcoord[i]), Val(3))
cid = @inbounds indices[1] + indices[2]*ncells[1] + indices[3]*ncells[1]*ncells[2] + 1
ncells_lowerlevel = 0
ncell = prod(ncells)
@inbounds for ilevel in 0:maxamr
haskey(celldict, cid) && break
ncells_lowerlevel += (8^ilevel)*ncell
ratio = 2^(ilevel+1)
indices = ntuple(i -> floor(Int, (loc[i] - coordmin[i]) / dcoord[i] * ratio), Val(3))
cid = ncells_lowerlevel + indices[1] +
ratio*ncells[1]*indices[2] + ratio^2*ncells[1]*ncells[2]*indices[3] + 1
end
cid
end
"""
getlevel(meta::MetaVLSV, cid::Int) -> Int
Return the AMR level of a given cell ID `cid`.
!!! warning
This function does not check if the VLSV file of `meta` actually contains `cid`; it may
be shadowed by refined children.
"""
function getlevel(meta::MetaVLSV, cid::Int)
ncell = prod(meta.ncells)
ilevel = 0
c = Int(cid) - ncell
while c > 0
ilevel += 1
c -= (8^ilevel)*ncell
end
ilevel
end
"""
getparent(meta::MetaVLSV, cid::Int) -> Int
Return the parent cell ID of given child `cid`.
"""
function getparent(meta::MetaVLSV, cid::Int)
@inbounds xcell, ycell = meta.ncells[1], meta.ncells[2]
ncell = prod(meta.ncells)
mylvl = getlevel(meta, cid)
parentlvl = mylvl - 1
if parentlvl < 0
throw(ArgumentError("Cell ID $cid has no parent cell!"))
else
# get the first cell ID on my level
cid1st = get1stcell(mylvl, ncell)
# get row and column sequence on my level (starting with 0)
xcell <<= mylvl
ycell <<= mylvl
myseq = cid - cid1st
ix = myseq % xcell
iz = myseq ÷ (xcell*ycell)
iy = (myseq - iz*xcell*ycell) ÷ xcell
# indexes on the parent level
ixparent = ix ÷ 2
iyparent = iy ÷ 2
izparent = iz ÷ 2
# get the first cell ID on parent level
cid1st -= ncell*8^parentlvl
# get parent cell ID (may not exist!!!)
parentid = cid1st + izparent*xcell*ycell÷4 + iyparent*xcell÷2 + ixparent
end
parentid
end
"""
getchildren(meta::MetaVLSV, cid::Int) -> Vector{Int}
Return direct children of `cid`.
"""
function getchildren(meta::MetaVLSV, cid::Int)
xcell, ycell, zcell = meta.ncells
ncell = prod(meta.ncells)
mylvl = getlevel(meta, cid)
# get the first cell ID on the my level
cid1st = 1
for i in 0:mylvl-1
cid1st += ncell * 8^i
end
# get my row and column sequence on my level (starting with 0)
xcell <<= mylvl
ycell <<= mylvl
myseq = cid - cid1st
ix = myseq % xcell
iz = myseq ÷ (xcell*ycell)
iy = (myseq - iz*xcell*ycell) ÷ xcell
# get the children sequences on the finer level
ix <<= 1
iy <<= 1
iz <<= 1
nchildren = 2^ndims(meta)
cid = Vector{Int}(undef, nchildren)
# get the first cell ID on the finer level
cid1st += ncell << (3*mylvl)
ix_, iy_ = (ix, ix+1), (iy, iy+1)
iz_ = zcell != 1 ? (iz, iz+1) : iz
for (n,i) in enumerate(Iterators.product(ix_, iy_, iz_))
@inbounds cid[n] = cid1st + i[3]*xcell*ycell*4 + i[2]*xcell*2 + i[1]
end
(cid)
end
"""
getsiblings(meta::MetaVLSV, cid::Int) -> Vector{Int}
Return sibling cells of a given `cid`, including itself.
"""
function getsiblings(meta::MetaVLSV, cid::Int)
xcell, ycell, zcell = meta.ncells
ncell = prod(meta.ncells)
mylvl = getlevel(meta, cid)
mylvl == 0 && throw(ArgumentError("CellID $cid is not a child cell!"))
xcell = xcell << mylvl
ycell = ycell << mylvl
# 1st cell ID on my level
cid1st = get1stcell(mylvl, ncell)
# xyz sequences on my level (starting with 0)
myseq = cid - cid1st
ix = myseq % xcell
iz = myseq ÷ (xcell*ycell)
iy = (myseq - iz*xcell*ycell) ÷ xcell
ix1 = iseven(ix) ? ix + 1 : ix - 1
iy1 = iseven(iy) ? iy + 1 : iy - 1
iz1 = iseven(iz) ? iz + 1 : iz - 1
# reorder
ix, ix1 = minmax(ix, ix1)
iy, iy1 = minmax(iy, iy1)
iz, iz1 = minmax(iz, iz1)
nsiblings = 2^ndims(meta)
cid = Vector{Int}(undef, nsiblings)
ix_, iy_ = (ix, ix1), (iy, iy1)
iz_ = zcell != 1 ? (iz, iz1) : iz
for (n,i) in enumerate(Iterators.product(ix_, iy_, iz_))
@inbounds cid[n] = cid1st + i[3]*xcell*ycell + i[2]*xcell + i[1]
end
(cid)
end
"""
isparent(meta::MetaVLSV, cid::Int) -> Bool
Check if `cid` is a parent cell.
"""
function isparent(meta::MetaVLSV, cid::Int)
ncell_accum = get1stcell(meta.maxamr, prod(meta.ncells))
!haskey(meta.celldict, cid) && 0 < cid < ncell_accum
end
"""
getcellcoordinates(meta::MetaVLSV, cid::Int) -> SVector{3,Float64}
Return a given cell's spatial coordinates.
"""
function getcellcoordinates(meta::MetaVLSV, cid::Int)
(;ncells, coordmin, coordmax) = meta
cid -= 1 # for easy divisions
ncells_refmax = collect(ncells)
reflevel = 0
subtraction = prod(ncells) * (2^reflevel)^3
# sizes on the finest level
while cid ≥ subtraction
cid -= subtraction
reflevel += 1
subtraction <<= 3
ncells_refmax .<<= 1
end
indices = @inbounds (
cid % ncells_refmax[1],
cid ÷ ncells_refmax[1] % ncells_refmax[2],
cid ÷ (ncells_refmax[1] * ncells_refmax[2]) )
coords = @inbounds @SVector [
coordmin[i] + (indices[i] + 0.5) * (coordmax[i] - coordmin[i]) / ncells_refmax[i]
for i = 1:3]
coords
end
"""
getvcellcoordinates(meta::MetaVLSV, vcellids::Vector; species="proton")
Return velocity cells' coordinates of `species` and `vcellids`.
"""
function getvcellcoordinates(meta::MetaVLSV, vcellids::Vector{Int32};
species::String="proton")
(;vblocks, vblocksize, dv, vmin) = meta.meshes[species]
bsize = prod(vblocksize)
blockid = @. vcellids ÷ bsize
# Get block coordinates
blockInd = [(
bid % vblocks[1],
bid ÷ vblocks[1] % vblocks[2],
bid ÷ (vblocks[1] * vblocks[2]) )
for bid in blockid]
blockCoord = [(
bInd[1] * dv[1] * vblocksize[1] + vmin[1],
bInd[2] * dv[2] * vblocksize[2] + vmin[2],
bInd[3] * dv[3] * vblocksize[3] + vmin[3] )
for bInd in blockInd]
# Get cell indices
vcellblockids = @. vcellids % bsize
cellidxyz = [(
cid % vblocksize[1],
cid ÷ vblocksize[1] % vblocksize[2],
cid ÷ (vblocksize[1] * vblocksize[2]) )
for cid in vcellblockids]
# Get cell coordinates
cellCoords = [
@SVector [Float32(blockCoord[i][j] + (cellidxyz[i][j] + 0.5) * dv[j]) for j in 1:3]
for i in eachindex(vcellblockids)]
cellCoords
end
"""
getdensity(meta, VDF; species="proton")
getdensity(meta, vcellf; species="proton")
getdensity(vmesh::VMeshInfo, vcellf)
Get density from `VDF` of `species` associated with `meta`, n = ∫ f(r,v) dV. Alternatively,
one can directly pass `vcellids` as original indices of nonzero VDFs and `vcellf` as their
corresponding values.
"""
function getdensity(meta::MetaVLSV, VDF::Array{T};
species::String="proton") where T <: AbstractFloat
(;dv) = meta.meshes[species]
n = sum(VDF) * convert(T, prod(dv))
end
function getdensity(vmesh::VMeshInfo, vcellf::Vector{T}) where T <: AbstractFloat
n = sum(vcellf) * convert(T, prod(vmesh.dv))
end
getdensity(meta::MetaVLSV, vcellf::Vector{<:AbstractFloat}; species::String="proton") =
getdensity(meta.meshes[species], vcellf)
"""
getvelocity(meta, VDF; species="proton")
getvelocity(meta, vcellids, vcellf; species="proton")
getvelocity(vmesh::VMeshInfo, vcellids, vcellf)
Get bulk velocity from `VDF` of `species`, u = ∫ v * f(r,v) dV / n. Alternatively, one can
directly pass `vcellids`, `vcellf`, as in [`getdensity`](@ref).
"""
function getvelocity(meta::MetaVLSV, VDF::Array{T};
species::String="proton") where T <: AbstractFloat
(;dv, vmin) = meta.meshes[species]
u = @SVector zeros(T, 3)
@inbounds for k in axes(VDF,3), j in axes(VDF,2), i in axes(VDF,1)
vx = vmin[1] + (i - 0.5f0)*dv[1]
vy = vmin[2] + (j - 0.5f0)*dv[2]
vz = vmin[3] + (k - 0.5f0)*dv[3]
u += VDF[i,j,k] .* SVector(vx, vy, vz)
end
n = sum(VDF)
u /= n
u
end
function getvelocity(vmesh::VMeshInfo, vcellids::Vector{Int32}, vcellf::Vector{T}) where
T <: AbstractFloat
(;vblocksize, vblocks, dv, vmin) = vmesh
vsize = @inbounds ntuple(i -> vblocksize[i] * vblocks[i], Val(3))
slicez = vsize[1]*vsize[2]
blocksize = prod(vblocksize)
sliceBz = vblocks[1]*vblocks[2]
sliceCz = vblocksize[1]*vblocksize[2]
u = @SVector zeros(T, 3)
@inbounds @simd for ic in eachindex(vcellids)
id = findindex(vcellids[ic], vblocks, vblocksize, blocksize, vsize, sliceBz, sliceCz)
i = id % vsize[1]
j = id % slicez ÷ vsize[1]
k = id ÷ slicez
vx = vmin[1] + (i + 0.5f0)*dv[1]
vy = vmin[2] + (j + 0.5f0)*dv[2]
vz = vmin[3] + (k + 0.5f0)*dv[3]
u += vcellf[ic] .* SVector(vx, vy, vz)
end
n = sum(vcellf)
u /= n
u
end
getvelocity(meta::MetaVLSV, vcellids::Vector{Int32}, vcellf::Vector{T};
species::String="proton") where T <: AbstractFloat =
getvelocity(meta.meshes[species], vcellids, vcellf)
"""
getpressure(meta, VDF; species="proton")
getpressure(meta, vcellids, vcellf; species="proton")
getpressure(vmesh::VMeshInfo, vcellids, vcellf)
Get pressure tensor (6 components: Pxx, Pyy, Pzz, Pyz, Pzx, Pxy) of `species` from `VDF`
associated with `meta`, pᵢⱼ = m * ∫ (v - u)ᵢ(v - u)ⱼ * f(r,v) dV.
Alternatively, one can directly pass `vcellids`, `vcellf`, as in [`getdensity`](@ref).
"""
function getpressure(meta::MetaVLSV, VDF::Array{T};
species::String="proton") where T <: AbstractFloat
(;dv, vmin) = meta.meshes[species]
p = @SVector zeros(T, 6)
u = getvelocity(meta, VDF; species)
@inbounds for k in axes(VDF,3), j in axes(VDF,2), i in axes(VDF,1)
vx = vmin[1] + (i - 0.5f0)*dv[1]
vy = vmin[2] + (j - 0.5f0)*dv[2]
vz = vmin[3] + (k - 0.5f0)*dv[3]
p += VDF[i,j,k] .* SVector(
(vx - u[1])*(vx - u[1]),
(vy - u[2])*(vy - u[2]),
(vz - u[3])*(vz - u[3]),
(vy - u[2])*(vz - u[3]),
(vx - u[1])*(vz - u[3]),
(vx - u[1])*(vy - u[2]))
end
factor = mᵢ * convert(T, prod(dv))
p *= factor
p
end
function getpressure(vmesh::VMeshInfo, vcellids::Vector{Int32}, vcellf::Vector{T}) where
T <: AbstractFloat
(;vblocksize, vblocks, dv, vmin) = vmesh
vsize = @inbounds ntuple(i -> vblocksize[i] * vblocks[i], Val(3))
slicez = vsize[1]*vsize[2]
blocksize = prod(vblocksize)
sliceBz = vblocks[1]*vblocks[2]
sliceCz = vblocksize[1]*vblocksize[2]
u = getvelocity(vmesh, vcellids, vcellf)
p = @SVector zeros(T, 6)
@inbounds @simd for ic in eachindex(vcellids)
id = findindex(vcellids[ic], vblocks, vblocksize, blocksize, vsize, sliceBz, sliceCz)
i = id % vsize[1]
j = id % slicez ÷ vsize[1]
k = id ÷ slicez
vx = vmin[1] + (i + 0.5f0)*dv[1]
vy = vmin[2] + (j + 0.5f0)*dv[2]
vz = vmin[3] + (k + 0.5f0)*dv[3]
p += vcellf[ic] .* SVector(
(vx - u[1])*(vx - u[1]),
(vy - u[2])*(vy - u[2]),
(vz - u[3])*(vz - u[3]),
(vy - u[2])*(vz - u[3]),
(vx - u[1])*(vz - u[3]),
(vx - u[1])*(vy - u[2]))
end
factor = mᵢ * convert(T, prod(dv))
p *= factor
p
end
getpressure(meta::MetaVLSV, vcellids::Vector{Int32}, vcellf::Vector{<:AbstractFloat};
species::String="proton") =
getpressure(meta.meshes[species], vcellids, vcellf)
"""
getheatfluxvector(meta, VDF; species="proton")
getheatfluxvector(meta, vcellids, vcellf; species="proton")
getheatfluxvector(vmesh::VMeshInfo, vcellids, vcellf)
Get heat flux vector (3 components) of `species` from `VDF` associated with `meta`,
qᵢ = m/2 * ∫ (v - u)²(v - u)ᵢ * f(r,v) dV. Alternatively, one can directly pass `vcellids`,
`vcellf`, as in [`getdensity`](@ref).
"""
function getheatfluxvector(meta::MetaVLSV, VDF::Array{T}; species::String="proton") where
T <: AbstractFloat
(;dv, vmin) = meta.meshes[species]
q = @SVector zeros(T, 3)
u = getvelocity(meta, VDF; species)
@inbounds for k in axes(VDF,3), j in axes(VDF,2), i in axes(VDF,1)
vx = vmin[1] + (i - 0.5f0)*dv[1]
vy = vmin[2] + (j - 0.5f0)*dv[2]
vz = vmin[3] + (k - 0.5f0)*dv[3]
q += VDF[i,j,k] .* SVector(
(vx - u[1])*(vx - u[1])*(vx - u[1]),
(vy - u[2])*(vy - u[2])*(vy - u[2]),
(vz - u[3])*(vz - u[3])*(vz - u[3]))
end
factor = mᵢ * convert(T, prod(dv))
q *= factor
q
end
function getheatfluxvector(vmesh::VMeshInfo, vcellids::Vector{Int32}, vcellf::Vector{T}
) where T <: AbstractFloat
(;vblocksize, vblocks, dv, vmin) = vmesh
vsize = @inbounds ntuple(i -> vblocksize[i] * vblocks[i], Val(3))
slicez = vsize[1]*vsize[2]
blocksize = prod(vblocksize)
sliceBz = vblocks[1]*vblocks[2]
sliceCz = vblocksize[1]*vblocksize[2]
u = getvelocity(vmesh, vcellids, vcellf)
q = @SVector zeros(T, 3)
@inbounds @simd for ic in eachindex(vcellids)
id = findindex(vcellids[ic], vblocks, vblocksize, blocksize, vsize, sliceBz, sliceCz)
i = id % vsize[1]
j = id % slicez ÷ vsize[1]
k = id ÷ slicez
vx = vmin[1] + (i + 0.5f0)*dv[1]
vy = vmin[2] + (j + 0.5f0)*dv[2]
vz = vmin[3] + (k + 0.5f0)*dv[3]
q += vcellf[ic] .* SVector(
(vx - u[1])*(vx - u[1])*(vx - u[1]),
(vy - u[2])*(vy - u[2])*(vy - u[2]),
(vz - u[3])*(vz - u[3])*(vz - u[3]))
end
factor = mᵢ * convert(T, prod(dv))
q *= factor
q
end
getheatfluxvector(meta::MetaVLSV, vcellids::Vector{Int32}, vcellf::Vector{<:AbstractFloat};
species::String="proton") =
getheatfluxvector(meta.meshes[species], vcellids, vcellf)
"Get the original vcell index without blocks from raw vcell index `i` (0-based)."
@inline function findindex(i::Int32, vblocks::NTuple{3, Int}, vblocksize::NTuple{3,Int},
blocksize::Int, vsize::NTuple{3, Int}, sliceBz::Int, sliceCz::Int)
iB = i ÷ blocksize
iBx = iB % vblocks[1]
iBy = iB % sliceBz ÷ vblocks[1]
iBz = iB ÷ sliceBz
iCellInBlock = i % blocksize
iCx = iCellInBlock % vblocksize[1]
iCy = iCellInBlock % sliceCz ÷ vblocksize[1]
iCz = iCellInBlock ÷ sliceCz
iBCx = iBx*vblocksize[1] + iCx
iBCy = iBy*vblocksize[2] + iCy
iBCz = iBz*vblocksize[3] + iCz
iOrigin = iBCz*vsize[1]*vsize[2] + iBCy*vsize[1] + iBCx
end
"""
reorder(vmesh::VMeshInfo, vcellids::Vector{Int32}) -> vcellids_origin
Reorder vblock-organized VDF indexes into x-->y-->z indexes. `vcellids` are raw indices
of nonzero VDFs ordered by blocks.
"""
function reorder(vmesh::VMeshInfo, vcellids::Vector{Int32})
(;vblocksize, vblocks) = vmesh
blocksize = prod(vblocksize)
sliceBz = vblocks[1]*vblocks[2]
vsize = @inbounds ntuple(i -> vblocksize[i] * vblocks[i], Val(3))
sliceCz = vblocksize[1]*vblocksize[2]
vcellids_origin = similar(vcellids)
# IDs are 0-based
@inbounds @simd for i in eachindex(vcellids)
vcellids_origin[i] = 1 +
findindex(vcellids[i], vblocks, vblocksize, blocksize, vsize, sliceBz, sliceCz)
end
vcellids_origin
end
"""
reconstruct(vmesh::VMeshInfo, vcellids::Vector{Int32}, vcellf::Vector{<:AbstractFloat})
Reconstruct the full VDFs in 3D. `vcellids` are raw indices of nonzero VDFs ordered by
blocks, and `vcellf` are the corresponding values in each cell.
"""
function reconstruct(vmesh::VMeshInfo, vcellids::Vector{Int32},
vcellf::Vector{<:AbstractFloat})
(;vblocksize, vblocks) = vmesh
blocksize = prod(vblocksize)
sliceBz = vblocks[1]*vblocks[2]
vsize = @inbounds ntuple(i -> vblocksize[i] * vblocks[i], Val(3))
sliceCz = vblocksize[1]*vblocksize[2]
# Reconstruct the full velocity space
VDF = zeros(Float32, vsize)
# Raw IDs are 0-based
@inbounds @simd for i in eachindex(vcellids)
j = 1 +
findindex(vcellids[i], vblocks, vblocksize, blocksize, vsize, sliceBz, sliceCz)
VDF[j] = vcellf[i]
end
VDF
end
"""
getmaxwellianity(meta, VDF; species="proton")
getmaxwellianity(meta, vcellids, vcellf; species="proton")
Obtain the Maxwellian similarity factor -log(1/(2n) * ∫ |f - g| dv), where `f` is the VDF
from Vlasiator and `g` is the analytical Maxwellian distribution that generates the same
density as `f`. The value ranges from [0, +∞], with 0 meaning not Maxwellian-distributed at
all, and +∞ a perfect Maxwellian distribution.
Alternatively, one can pass original `vcellids` and `vcellf` directly.
"""
function getmaxwellianity(meta::MetaVLSV, VDF::Array{<:AbstractFloat};
species::String="proton")
(;dv, vmin) = meta.meshes[species]
n = getdensity(meta, VDF)
u = getvelocity(meta, VDF)
P = getpressure(meta, VDF)
p = (P[1] + P[2] + P[3]) / 3
T = p / (n *kB) # temperature from scalar pressure
ϵₘ = zero(eltype(VDF))
vth2⁻¹ = mᵢ / (2kB*T)
coef = √(vth2⁻¹/π) * (vth2⁻¹/π)
@inbounds for k in axes(VDF,3), j in axes(VDF,2), i in axes(VDF,1)
vx = vmin[1] + (i - 0.5f0)*dv[1]
vy = vmin[2] + (j - 0.5f0)*dv[2]
vz = vmin[3] + (k - 0.5f0)*dv[3]
dv2 = (vx - u[1])^2 + (vy - u[2])^2 + (vz - u[3])^2
g = n * coef * ℯ^(-vth2⁻¹*dv2)
ϵₘ += abs(VDF[i,j,k] - g)
end
ϵₘ = -log(0.5 / n * convert(eltype(VDF), prod(dv)) * ϵₘ)
end
function getmaxwellianity(meta::MetaVLSV, vcellids::Vector{Int32},
vcellf::Vector{<:AbstractFloat}; species::String="proton")
(;vblocksize, vblocks, dv, vmin) = meta.meshes[species]
vsize = @inbounds ntuple(i -> vblocksize[i] * vblocks[i], Val(3))
slicez = vsize[1]*vsize[2]
blocksize = prod(vblocksize)
sliceBz = vblocks[1]*vblocks[2]
sliceCz = vblocksize[1]*vblocksize[2]
n = getdensity(meta, vcellf)
u = getvelocity(meta, vcellids, vcellf)
P = getpressure(meta, vcellids, vcellf)
p = (P[1] + P[2] + P[3]) / 3
T = p / (n *kB) # temperature from scalar pressure
ϵₘ = zero(eltype(vcellf))
vth2⁻¹ = mᵢ / (2kB*T)
coef = √(vth2⁻¹/π) * (vth2⁻¹/π)
@inbounds @simd for ic in eachindex(vcellids)
id = findindex(vcellids[ic], vblocks, vblocksize, blocksize, vsize, sliceBz, sliceCz)
i = id % vsize[1]
j = id % slicez ÷ vsize[1]
k = id ÷ slicez
vx = vmin[1] + (i + 0.5f0)*dv[1]
vy = vmin[2] + (j + 0.5f0)*dv[2]
vz = vmin[3] + (k + 0.5f0)*dv[3]
dv2 = (vx - u[1])^2 + (vy - u[2])^2 + (vz - u[3])^2
g = n * coef * ℯ^(-vth2⁻¹*dv2)
ϵₘ += abs(vcellf[ic] - g)
end
ϵₘ = -log(0.5 / n * convert(eltype(vcellf), prod(dv)) * ϵₘ)
end
"""
getKLdivergence(meta, VDF; species="proton")
getKLdivergence(meta, vcellids, vcellf; species="proton")
Obtain the KL-divergence ∫ f*log(f/g)dv, where `f` is the VDF from Vlasiator and `g` is the
analytical Maxwellian distribution that generates the same density as `f`. The value ranges
from [0, +∞], with 0 meaning perfect Maxwellian. Usually the values are quite small.
Alternatively, one can pass original `vcellids` and `vcellf` directly.
"""
function getKLdivergence(meta::MetaVLSV, VDF::Array{<:AbstractFloat};
species::String="proton")
(;dv, vmin) = meta.meshes[species]
n = getdensity(meta, VDF)
u = getvelocity(meta, VDF)
P = getpressure(meta, VDF)
p = (P[1] + P[2] + P[3]) / 3
T = p / (n *kB) # temperature from scalar pressure
ϵₘ = zero(eltype(VDF))
vth2⁻¹ = mᵢ / (2kB*T)
coef = √(vth2⁻¹/π) * (vth2⁻¹/π)
@inbounds for k in axes(VDF,3), j in axes(VDF,2), i in axes(VDF,1)
vx = vmin[1] + (i - 0.5f0)*dv[1]
vy = vmin[2] + (j - 0.5f0)*dv[2]
vz = vmin[3] + (k - 0.5f0)*dv[3]
dv2 = (vx - u[1])^2 + (vy - u[2])^2 + (vz - u[3])^2
p = VDF[i,j,k] / n
q = coef * ℯ^(-vth2⁻¹*dv2)
f = p*log(p/q)
ϵₘ += ifelse(isnan(f), zero(f), f)
end
ϵₘ * convert(eltype(VDF), prod(dv))
end
function getKLdivergence(meta::MetaVLSV, vcellids::Vector{Int32},
vcellf::Vector{<:AbstractFloat}; species::String="proton")
(;vblocksize, vblocks, dv, vmin) = meta.meshes[species]
vsize = @inbounds ntuple(i -> vblocksize[i] * vblocks[i], Val(3))
slicez = vsize[1]*vsize[2]
blocksize = prod(vblocksize)
sliceBz = vblocks[1]*vblocks[2]
sliceCz = vblocksize[1]*vblocksize[2]
n = getdensity(meta, vcellf)
u = getvelocity(meta, vcellids, vcellf)
P = getpressure(meta, vcellids, vcellf)
p = (P[1] + P[2] + P[3]) / 3
T = p / (n *kB) # temperature from scalar pressure
ϵₘ = zero(eltype(vcellf))
vth2⁻¹ = mᵢ / (2kB*T)
coef = √(vth2⁻¹/π) * (vth2⁻¹/π)
@inbounds @simd for ic in eachindex(vcellids)
id = findindex(vcellids[ic], vblocks, vblocksize, blocksize, vsize, sliceBz, sliceCz)
i = id % vsize[1]
j = id % slicez ÷ vsize[1]
k = id ÷ slicez
vx = vmin[1] + (i + 0.5f0)*dv[1]
vy = vmin[2] + (j + 0.5f0)*dv[2]
vz = vmin[3] + (k + 0.5f0)*dv[3]
dv2 = (vx - u[1])^2 + (vy - u[2])^2 + (vz - u[3])^2
p = vcellf[ic] / n
q = coef * ℯ^(-vth2⁻¹*dv2)
f = p*log(p/q)
ϵₘ += ifelse(isnan(f), zero(f), f)
end
ϵₘ * convert(eltype(vcellf), prod(dv))
end
function isInsideDomain(meta::MetaVLSV, point::Vector{<:Real})
(;coordmin, coordmax) = meta
if coordmin[1] < point[1] ≤ coordmax[1] &&
coordmin[2] < point[2] ≤ coordmax[2] &&
coordmin[3] < point[3] ≤ coordmax[3]
return true
else
return false
end
end
"""
getcellinline(meta, point1::Vector, point2::Vector) -> cellids, distances, coords
Returns cell IDs, distances and coordinates for every cell in a line between two given
points `point1` and `point2`. TODO: preallocation?
"""
function getcellinline(meta::MetaVLSV, point1::Vector{T}, point2::Vector{T}) where T
(;coordmin, coordmax, ncells) = meta
if !isInsideDomain(meta, point1)
throw(DomainError(point1, "point location outside simulation domain!"))
elseif !isInsideDomain(meta, point2)
throw(DomainError(point2, "point location outside simulation domain!"))
end
dcell = @inbounds ntuple(i -> (coordmax[i] - coordmin[i]) / ncells[i], Val(3))
distances = [zero(T)]
cellids = [getcell(meta, point1)]
coords = [SVector{3}(point1)]
ϵ = eps(T)
unit_vector = @. (point2 - point1) / $norm(point2 - point1 + ϵ)
p = coords[1]
coef_min = Vector{T}(undef, 3)
coef_max = Vector{T}(undef, 3)
@inbounds while true
cid = getcell(meta, p)
amrlvl = getlevel(meta, cid)
# Get the max and min cell boundaries
Δ = dcell .* 0.5.^amrlvl
min_bounds = getcellcoordinates(meta, cid) .- 0.5.*Δ
max_bounds = min_bounds .+ Δ
# Check which face we hit first
@. coef_min = (min_bounds - p) / unit_vector
@. coef_max = (max_bounds - p) / unit_vector
# Negative coefficients indicates the opposite direction
for i in 1:3
if unit_vector[i] == 0.0
coef_min[i] = Inf
coef_max[i] = Inf
end
if coef_min[i] ≤ 0 coef_min[i] = Inf end
if coef_max[i] ≤ 0 coef_max[i] = Inf end
end
# Find the minimum distance from a boundary times a factor
d = min(minimum(coef_min), minimum(coef_max)) * 1.00001
coordnew = SVector(
p[1] + d*unit_vector[1],
p[2] + d*unit_vector[2],
p[3] + d*unit_vector[3])
dot(point2 .- coordnew, unit_vector) ≥ 0 || break
cellidnew = getcell(meta, coordnew)
push!(cellids, cellidnew)
push!(coords, coordnew)
push!(distances, norm(coordnew .- point1))
p = coordnew
end
cellids, distances, coords
end
"""
getslicecell(meta, sliceoffset, dir, minCoord, maxCoord) -> idlist, indexlist
Find the cell IDs `idlist` which are needed to plot a 2d cut through of a 3d mesh, in a
direction `dir` at `sliceoffset`, and the `indexlist`, which is a mapping from original
order to the cut plane and can be used to select data onto the plane.
"""
function getslicecell(meta::MetaVLSV, sliceoffset::Float64, dir::Int,
minCoord::Float64, maxCoord::Float64)
dir ∉ (1,2,3) && @error "Unknown slice direction $dir"
(;ncells, maxamr, celldict) = meta
nsize = ncells[dir]
sliceratio = sliceoffset / (maxCoord - minCoord)
0.0 ≤ sliceratio ≤ 1.0 || error("slice plane index out of bound!")
# Find the ids
nlen = 0
ncell = prod(ncells)
# number of cells up to each refinement level
nStart = (vcat(0, accumulate(+, (ncell*8^ilvl for ilvl in 0:maxamr))))
indexlist = Int[]
idlist = Int[]
cellidsorted = sort(collect(keys(celldict)))
@inbounds for ilvl in 0:maxamr
nLow, nHigh = nStart[ilvl+1], nStart[ilvl+2]
idfirst_ = searchsortedfirst(cellidsorted, nLow+1)
idlast_ = searchsortedlast(cellidsorted, nHigh)
ids = @view cellidsorted[idfirst_:idlast_]
ix, iy, iz = getindexes(ilvl, ncells[1], ncells[2], nLow, ids)
coords =
if dir == 1
ix
elseif dir == 2
iy
else # 3
iz
end
# Find the cut plane index for each refinement level (0-based)
depth = floor(Int, sliceratio*nsize<<ilvl)
# Find the needed elements to create the cut and save the results
elements = coords .== depth
append!(indexlist, (nlen+1:nlen+length(ids))[elements])
append!(idlist, ids[elements])
nlen += length(ids)
end
idlist, indexlist
end
"""
refineslice(meta, idlist::Vector{Int}, data::AbstractVector, normal::Symbol) -> Vector
refineslice(meta, idlist::Vector{Int}, data::AbstractMatrix, normal::Symbol) -> Matrix
refineslice(meta, idlist::Vector{Int}, data::AbstractArray, dir::Int)
Generate data on the finest refinement level given cellids `idlist` and variable `data` on
the slice perpendicular to `normal`. If `data` is 2D, then the first dimension is treated as
vector components.
"""
function refineslice(meta::MetaVLSV, idlist::Vector{Int}, data::AbstractVector,
normal::Symbol)
(;ncells, maxamr) = meta
dims = _getdim2d(ncells, maxamr, normal)
dpoints = zeros(eltype(data), dims...)
# Create the plot grid
ncell = prod(ncells)
nHigh, nLow = ncell, 0
@inbounds for i in 0:maxamr
idfirst_ = searchsortedfirst(idlist, nLow+1)
idlast_ = searchsortedlast(idlist, nHigh)
ids = @view idlist[idfirst_:idlast_]
d = @view data[idfirst_:idlast_]
ix, iy, iz = getindexes(i, ncells[1], ncells[2], nLow, ids)
# Get the correct coordinate values and the widths for the plot
a, b =
if normal == :x
iy, iz
elseif normal == :y
ix, iz
elseif normal == :z
ix, iy
end
# Insert the data values into dpoints
refineRatio = 2^(maxamr - i)
iRange = 0:refineRatio-1
X, Y = ndgrid(iRange, iRange)
coords = [(0, 0) for _ in a, _ in 1:2^(2*(maxamr-i))]
@inbounds for ir in 1:2^(2*(maxamr-i)), ic in eachindex(a, b)
@fastmath coords[ic,ir] = (muladd(a[ic], refineRatio, 1+X[ir]),
muladd(b[ic], refineRatio, 1+Y[ir]) )
end
for ir in 1:2^(2*(maxamr-i)), ic in eachindex(d)
dpoints[ coords[ic,ir]... ] = d[ic]
end
nLow = nHigh
nHigh += ncell << (3*(i+1))
end
dpoints
end
function refineslice(meta::MetaVLSV, idlist::Vector{Int}, data::AbstractArray, dir::Int)
if dir == 1
refineslice(meta, idlist, data, :x)
elseif dir == 2
refineslice(meta, idlist, data, :y)
elseif dir == 3
refineslice(meta, idlist, data, :z)
else
error("Normal direction index $normal out of range!")
end
end
function refineslice(meta::MetaVLSV, idlist::Vector{Int}, data::AbstractMatrix,
normal::Symbol)
dims = _getdim2d(meta.ncells, meta.maxamr, normal)
dout = zeros(eltype(data), size(data,1), dims...)
for i in axes(data,1)
dout[i,:,:] = @views refineslice(meta, idlist, data[i,:], normal)
end
dout
end
@inline function _getdim2d(ncells::NTuple{3, Int}, maxamr::Int, normal::Symbol)
if normal == :x
i1, i2 = 2, 3
elseif normal == :y
i1, i2 = 1, 3
elseif normal == :z
i1, i2 = 1, 2
end
ratio = 2^maxamr
dims = (ncells[i1]*ratio, ncells[i2]*ratio)
end
"Compute x, y and z indexes of all cell `ids` on the given refinement level (0-based)."
@inline function getindexes(ilevel::Int, xcells::Int, ycells::Int, nCellUptoLowerLvl::Int,
ids::AbstractVector{Int})
ratio = 2^ilevel
slicesize = xcells*ycells*ratio^2
iz = @. (ids - nCellUptoLowerLvl - 1) ÷ slicesize
iy = similar(iz)
ix = similar(iz)
@inbounds for i in eachindex(ids, iz)
# number of ids up to the coordinate z in the refinement level ilevel
idUpToZ = muladd(iz[i], slicesize, nCellUptoLowerLvl)
iy[i] = (ids[i] - idUpToZ - 1) ÷ (xcells*ratio)
ix[i] = ids[i] - idUpToZ - iy[i]*xcells*ratio - 1
end
ix, iy, iz
end
"Compute x, y and z index of cell `id` on a given refinement level `ilevel`(0-based)."
@inline function getindexes(ilevel::Int, xcells::Int, ycells::Int, nCellUptoLowerLvl::Int,
id::Int)
ratio = 2^ilevel
slicesize = xcells*ycells*ratio^2
iz = (id - nCellUptoLowerLvl - 1) ÷ slicesize
idUpToZ = muladd(iz, slicesize, nCellUptoLowerLvl)
iy = (id - idUpToZ - 1) ÷ (xcells*ratio)
ix = id - idUpToZ - iy*xcells*ratio - 1
ix, iy, iz
end
"""
getnearestcellwithvdf(meta, id::Int, species::String="proton") -> Int
Find the nearest spatial cell with VDF saved for `species` of a given cell `id` associated
with `meta`.