-
Notifications
You must be signed in to change notification settings - Fork 18
/
DAT.jl
1222 lines (1138 loc) · 37 KB
/
DAT.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
module DAT
using DocStringExtensions
import ..Cubes
using ..YAXTools
using Distributed:
nworkers,
pmap,
@everywhere,
workers,
remotecall_fetch,
myid,
nprocs,
remotecall,
@spawn,
AbstractWorkerPool,
default_worker_pool,
CachingPool
import ..Cubes: cubechunks, iscompressed, chunkoffset, YAXArray, caxes, YAXSlice
import ..Cubes: cubechunks, iscompressed, chunkoffset, YAXArray, caxes, YAXSlice
import ..YAXArrays: findAxis, getOutAxis, getAxis
#import ..Cubes.Axes:
# AxisDescriptor, axname, ByInference, axsym, getOutAxis, getAxis, findAxis, match_axis
import ..Datasets: Dataset, createdataset
using ..YAXArrays: ByInference, YAXArrays
import ...YAXArrays.workdir
import YAXArrayBase
import ProgressMeter: Progress, next!, progress_pmap, progress_map
using YAXArrayBase
using DiskArrays: grid_offset, approx_chunksize, max_chunksize, RegularChunks,
IrregularChunks, GridChunks, eachchunk, ChunkType
using OffsetArrays: OffsetArray
using Dates
using DimensionalData: DimensionalData as DD
export mapCube,
getAxis,
InDims,
OutDims,
Dataset,
CubeTable,
cubefittable,
fittable,
MovingWindow
global const debugDAT = [false]
const WindowDescriptor = Tuple{Int,Int}
#TODO use a logging package
macro debug_print(e)
debugDAT[1] && return (:(println($e)))
:()
end
include("registration.jl")
"""
Internal representation of an input cube for DAT operations
$(FIELDS)
"""
mutable struct InputCube{N}
"The input data"
cube::Any
"The input description given by the user/registration"
desc::InDims
"List of axes that were actually selected through the description"
axesSmall::Vector
icolon::Vector{Int}
colonperm::Union{Vector{Int},Nothing}
"Indices of loop axes that this cube does not contain, i.e. broadcasts"
loopinds::Vector{Int}
"Number of elements to keep in cache along each axis"
cachesize::Vector{Int} # TODO: delete
window::Vector{WindowDescriptor}
iwindow::Vector{Int}
windowloopinds::Vector{Int}
iall::Vector{Int}
end
function InputCube(c, desc::InDims)
internalaxes = findAxis.(desc.axisdesc, Ref(c))
any(isequal(nothing), internalaxes) &&
error("One of the input axes not found in input cubes")
fullaxes = internalaxes[findall(i -> !isa(i, MovingWindow), desc.axisdesc)]
axlist = caxes(c)
axesSmall = map(i -> axlist[i], fullaxes)
colonperm =
issorted(internalaxes) ? nothing :
collect(Base.invperm(sortperm(collect(internalaxes))))
_window = findall(i -> isa(i, MovingWindow), desc.axisdesc)
iwindow = collect(internalaxes[_window])
window =
WindowDescriptor[(desc.axisdesc[i].pre, desc.axisdesc[i].after) for i in _window]
InputCube{ndims(c)}(
c,
desc,
collect(axesSmall),
collect(fullaxes),
colonperm,
Int[],
Int[],
window,
iwindow,
Int[],
collect(internalaxes),
)
end
geticolon(ic::InputCube) = ic.icolon
getwindowoob(ic::InputCube) = ic.desc.window_oob_value
createworkarrays(T, s, ntr) = [Array{T}(undef, s...) for i = 1:ntr]
getwindow(ic::InputCube) = zip(ic.windowloopinds, ic.window)
function getworksize(ic::InputCube{N}) where {N}
r = map(ic.iall) do i
i1 = findfirst(isequal(i), ic.icolon)
i1 === nothing || return size(ic.cube, i)
i2 = findfirst(isequal(i), ic.iwindow)
return sum(ic.window[i2]) + 1
end
(r...,)
end
"""
Internal representation of an output cube for DAT operations
## Fields
$(FIELDS)
"""
mutable struct OutputCube
"The actual outcube cube, once it is generated"
cube::Any
"The unpermuted output cube"
cube_unpermuted::Any
"The description of the output axes as given by users or registration"
desc::OutDims
"The list of output axes determined through the description"
axesSmall::Array{DD.Dimension} # Should this be a Vector?
"List of all the axes of the cube"
allAxes::Vector{DD.Dimension}
"Index of the loop axes that are broadcasted for this output cube"
loopinds::Vector{Int}
innerchunks::Any
"Elementtype of the outputcube"
outtype::Any
end
getwindow(::OutputCube) = []
const InOutCube = Union{InputCube,OutputCube}
getsmallax(c::InOutCube) = c.axesSmall
geticolon(c::OutputCube) = 1:length(c.axesSmall)
getAxis(desc, c::InOutCube) = getAxis(desc, c.cube)
has_window(c::InOutCube) = !isempty(getwindow(c))
function getworksize(oc::OutputCube)
(length.(oc.axesSmall)...,)
end
function getworkarray(c::InOutCube, ntr)
wa = createworkarrays(eltype(c.cube), getworksize(c), ntr)
map(wa) do w
if !has_window(c)
wrapWorkArray(c.desc.artype, w, c.axesSmall)
else
axes = map(c.iall) do i
i1 = findfirst(isequal(i), c.icolon)
i1 === nothing || return caxes(c.cube)[c.icolon[i1]]
i2 = findfirst(isequal(i), c.iwindow)
DD.rebuild(DD.key2dim(DD.name(caxes(c.cube)[c.iwindow[i2]])),UnitRange(-c.window[i2][1], c.window[i2][2]))
end
wrapWorkArray(c.desc.artype, w, axes)
end
end
end
function interpretoutchunksizes(desc, axesSmall, incubes)
if desc.chunksize == :max
map(ax -> string(DD.name(ax)) => RegularChunks(length(ax),0,length(ax)), axesSmall)
elseif desc.chunksize == :input
map(axesSmall) do ax
for cc in incubes
i = findAxis(string(DD.name(ax)), cc)
if i !== nothing
return string(DD.name(ax)) => eachchunk(cc.data).chunks[i]
end
end
return string(DD.name(ax)) => length(ax)
end
else
desc.chunksize
end
end
getOutAxis(desc::Tuple, inAxes, incubes, pargs, f) =
map(i -> getOutAxis(i, inAxes, incubes, pargs, f), desc)
function OutputCube(desc::OutDims, inAxes, incubes, pargs, f)
axesSmall = getOutAxis(desc.axisdesc, inAxes, incubes, pargs, f)
outtype = getOuttype(desc.outtype, incubes)
innerchunks = interpretoutchunksizes(desc, axesSmall, incubes)
OutputCube(
nothing,
nothing,
desc,
collect(DD.Dimension, axesSmall),
DD.Dimension[],
Int[],
innerchunks,
outtype,
)
end
"""
Configuration object of a DAT process. This holds all necessary information to perform the calculations.
It contains the following fields:
$TYPEDFIELDS
"""
mutable struct DATConfig{NIN,NOUT}
"The input data cubes"
incubes::NTuple{NIN,InputCube}
"The output data cubes"
outcubes::NTuple{NOUT,OutputCube}
"List of all axes of the input cubes"
allInAxes::Vector
"List of axes that are looped through"
LoopAxes::Vector
"Flag whether the computation is parallelized"
ispar::Bool
""
loopcachesize::Vector{Int}
""
allow_irregular_chunks::Bool
"Maximal size of the in memory cache"
max_cache::Any
"Inner function which is computed"
fu::Any
"Flag whether the computation happens in place"
inplace::Bool
""
include_loopvars::Bool
""
ntr::Any
"Flag if GC should be called explicitly. Probably necessary for many runs in Julia 1.9"
do_gc::Bool
"Additional arguments for the inner function"
addargs::Any
"Additional keyword arguments for the inner function"
kwargs::Any
end
function DATConfig(
cdata,
indims,
outdims,
inplace,
max_cache,
fu,
ispar,
include_loopvars,
allow_irregular,
nthreads,
do_gc,
addargs,
kwargs,
)
isa(indims, InDims) && (indims = (indims,))
isa(outdims, OutDims) && (outdims = (outdims,))
length(cdata) == length(indims) || error(
"Number of input cubes ($(length(cdata))) differs from registration ($(length(indims)))",
)
incubes = ([InputCube(o[1], o[2]) for o in zip(cdata, indims)]...,)
allInAxes = vcat([ic.axesSmall for ic in incubes]...)
outcubes = ((
map(1:length(outdims), outdims) do i, desc
OutputCube(desc, allInAxes, cdata, addargs, fu)
end
)...,)
DATConfig(
incubes,
outcubes,
allInAxes,
DD.Dimension[], # LoopAxes
ispar,
Int[],
allow_irregular,
max_cache, # max_cache
fu, # fu # loopcachesize
inplace, # inplace
include_loopvars,
nthreads,
do_gc,
addargs, # addargs
kwargs,
)
end
"""
getOuttype(outtype, cdata)
# Internal function
Get the element type for the output cube
"""
getOuttype(outtype::Int, cdata) = eltype(cdata[outtype])
function getOuttype(outtype::DataType, cdata)
outtype
end
mapCube(fu::Function, cdata, addargs...; kwargs...) =
mapCube(fu, (cdata,), addargs...; kwargs...)
"""
mapCube(fun, cube, addargs...;kwargs...)
Map a given function `fun` over slices of all cubes of the dataset `ds`.
Use InDims to discribe the input dimensions and OutDims to describe the output dimensions of the function.
For Datasets, only one output cube can be specified.
In contrast to the mapCube function for cubes, additional arguments for the inner function should be set as keyword arguments.
For the specific keyword arguments see the docstring of the mapCube function for cubes.
"""
function mapCube(
f::Function,
in_ds::Dataset,
addargs...;
indims = InDims(),
outdims = OutDims(),
inplace = true,
kwargs...,
)
allars = values(in_ds.cubes)
allaxes = collect(values(in_ds.axes))
arnames = keys(in_ds.cubes)
sarnames = (arnames...,)
any(ad -> findAxis(ad, allaxes) === nothing, indims.axisdesc) &&
error("One of the Dimensions does not exist in Dataset")
idar = collect(indims.axisdesc)
allindims = map(allars) do c
idshort = filter(idar) do ad
findAxis(ad, c) !== nothing
end
InDims((idshort...,); artype=indims.artype, filter=indims.procfilter)
end
isa(outdims, OutDims) || error("Only one output cube currently supported for datasets")
isempty(addargs) || error(
"Additional arguments currently not supported for datasets, use kwargs instead",
)
if inplace
# Why do we specify arnames here again, this seems to be unused in the let block?
fnew = let arnames = collect(arnames), f = f
function dsfun(xout, xin...; kwargs...)
incubes = NamedTuple{sarnames,typeof(xin)}(xin)
f(xout, incubes; kwargs...)
end
end
else
fnew = let arnames = collect(arnames), f = f
function dsfun(xin...; kwargs...)
incubes = NamedTuple{sarnames,typeof(xin)}(xin)
f(incubes; kwargs...)
end
end
end
allcubes = collect(values(in_ds.cubes))
mapCube(
fnew,
(allcubes...,);
indims = allindims,
outdims = outdims,
inplace = inplace,
kwargs...,
)
end
import Base.mapslices
function mapslices(f, d::Union{YAXArray,Dataset}, addargs...; dims, kwargs...)
isa(dims, String) && (dims = (dims,))
mapCube(
f,
d,
addargs...;
indims = InDims(dims...),
outdims = OutDims(ByInference()),
inplace = false,
kwargs...,
)
end
"""
mapCube(fun, cube, addargs...;kwargs...)
Map a given function `fun` over slices of the data cube `cube`.
The additional arguments `addargs` will be forwarded to the inner function `fun`.
Use InDims to discribe the input dimensions and OutDims to describe the output dimensions of the function.
### Keyword arguments
* `max_cache=YAXDefaults.max_cache` Float64 maximum size of blocks that are read into memory in bits e.g. `max_cache=5.0e8`. Or String. e.g. `max_cache="10MB"` or `max_cache=1GB` defaults to approx 10Mb.
* `indims::InDims` List of input cube descriptors of type [`InDims`](@ref) for each input data cube.
* `outdims::OutDims` List of output cube descriptors of type [`OutDims`](@ref) for each output cube.
* `inplace` does the function write to an output array inplace or return a single value> defaults to `true`
* `ispar` boolean to determine if parallelisation should be applied, defaults to `true` if workers are available.
* `showprog` boolean indicating if a ProgressMeter shall be shown
* `include_loopvars` boolean to indicate if the varoables looped over should be added as function arguments
* `nthreads` number of threads for the computation, defaults to Threads.nthreads for every worker.
* `loopchunksize` determines the chunk sizes of variables which are looped over, a dict
* `kwargs` additional keyword arguments are passed to the inner function
The first argument is always the function to be applied, the second is the input cube or
a tuple of input cubes if needed.
"""
function mapCube(
fu::Function,
cdata::Tuple,
addargs...;
max_cache = YAXArrays.YAXDefaults.max_cache[],
indims = InDims(),
outdims = OutDims(),
inplace = true,
ispar = nprocs() > 1,
debug = false,
include_loopvars = false,
showprog = true,
irregular_loopranges = false,
nthreads = ispar ? Dict(i => remotecall_fetch(Threads.nthreads, i) for i in workers()) :
[Threads.nthreads()],
loopchunksize = Dict(),
do_gc = true,
kwargs...,
)
if typeof(max_cache) == String
if last(max_cache, 2) == "MB"
max_cache = parse(Float64, max_cache[begin:end-2]) / (10^-6)
elseif last(max_cache, 2) == "GB"
max_cache = parse(Float64, max_cache[begin:end-2]) / (10^-9)
else
error("only MB or GB values are accepted for max_cache")
end
end
#Translate slices
if any(i -> isa(i, YAXSlice), cdata)
inew = map(cdata) do d
isa(d, YAXSlice) ? InDims(axname.(d.sliceaxes[2])...) : InDims()
end
cnew = map(i -> isa(i, YAXSlice) ? i.c : i, cdata)
return mapCube(
fu,
cnew,
addargs...;
indims = inew,
outdims = outdims,
inplace = inplace,
ispar = ispar,
debug = debug,
include_loopvars = include_loopvars,
irregular_loopranges = irregular_loopranges,
showprog = showprog,
nthreads = nthreads,
kwargs...,
)
end
@debug_print "Generating DATConfig"
dc = DATConfig(
cdata,
indims,
outdims,
inplace,
max_cache,
fu,
ispar,
include_loopvars,
irregular_loopranges,
nthreads,
do_gc,
addargs,
kwargs,
)
@debug_print "Analysing Axes"
analyzeAxes(dc)
@debug_print "Permuting loop axes"
permuteloopaxes(dc)
@debug_print "Calculating Cache Sizes"
getCacheSizes(dc, loopchunksize)
@debug_print "Generating Output Cube"
generateOutCubes(dc)
@debug_print "Running main Loop"
debug && return (dc)
runLoop(dc, showprog)
@debug_print "Finalizing Output Cube"
if length(dc.outcubes) == 1
return dc.outcubes[1].cube_unpermuted
else
return (map(i -> i.cube_unpermuted, dc.outcubes)...,)
end
end
function makeinplace(f)
(args...; kwargs...) -> begin
first(args) .= f(Base.tail(args)...; kwargs...)
nothing
end
end
function to_chunksize(c::RegularChunks, cs, _ = true)
offset = if c.cs==cs
c.offset
else
0
end
RegularChunks(cs, offset, c.s)
end
function to_chunksize(c::IrregularChunks, cs, allow_irregular=true)
fac = cs ÷ approx_chunksize(c)
ll = length.(c)
newchunks = sum.(Iterators.partition(ll,fac))
if length(newchunks)==1
RegularChunks(cs, 0, newchunks[1])
elseif length(newchunks) == 2 || all(==(cs),newchunks[2:end-1])
RegularChunks(cs, cs-newchunks[1], sum(newchunks))
else
if allow_irregular
IrregularChunks(chunksizes = newchunks)
else
RegularChunks(cs, 0, last(last(c)))
end
end
end
"""
getloopchunks(dc::DATConfig)
# Internal function
Returns the chunks that can be looped over toghether for all dimensions.
This computation of the size of the chunks is handled by [`DiskArrays.approx_chunksize`](@ref)
"""
function getloopchunks(dc::DATConfig)
lc = dc.loopcachesize
co = map(lc,dc.LoopAxes) do cs, ax
allchunks = map(dc.incubes) do ic
ii = findAxis(ax, caxes(ic.cube))
ii === nothing ? nothing : eachchunk(ic.cube.data).chunks[ii]
end
allchunks = unique(filter(!isnothing, allchunks))
if length(allchunks) == 1
return to_chunksize(only(allchunks),cs,dc.allow_irregular_chunks)
end
allchunks_offset = filter(i->mod(cs,approx_chunksize(i))==0, allchunks)
allchunks = isempty(allchunks_offset) ? allchunks : allchunks_offset
if length(allchunks) == 1
return to_chunksize(allchunks[1],cs,dc.allow_irregular_chunks)
end
if !dc.allow_irregular_chunks
allchunks = filter(i->isa(i,RegularChunks),allchunks)
end
if length(allchunks) == 1
return to_chunksize(allchunks[1],cs)
end
allchunks = to_chunksize.(allchunks,cs)
allchunks = unique(allchunks)
if length(allchunks)>1
@warn "Multiple chunk offset resolutions possible: $allchunks for dim $(axname(ax))"
end
first(allchunks)
end
(co...,)
end
"""
permuteloopaxes(dc)
# Internal function
Permute the dimensions of the cube, so that the axes that are looped through are in the first positions.
This is necessary for a faster looping through the data.
"""
function permuteloopaxes(dc)
foreach(dc.incubes) do ic
if !issorted(ic.loopinds)
p = sortperm(ic.loopinds)
iloopax = setdiff(1:ndims(ic.cube),ic.iall)
perm = collect(1:ndims(ic.cube))
perm[iloopax] = perm[iloopax[p]]
ic.cube = permutedims(ic.cube,perm)
ic.loopinds = ic.loopinds[p]
end
end
end
updatears(clist, r, f, caches) =
foreach(clist, caches) do ic, ca
if !has_window(ic)
updatear(f, r, ic.cube, geticolon(ic), ic.loopinds, ca)
else
updatear_window(
r,
ic.cube,
geticolon(ic),
ic.loopinds,
ca,
zip(ic.iwindow, ic.window),
getwindowoob(ic),
)
end
end
getindsall(indscol, loopinds, rfunc, colfunc = _ -> Colon()) =
getindsall((), 1, (sort(indscol)...,), (loopinds...,), rfunc, colfunc)
function getindsall(indsall, inow, indscol, loopinds, rfunc, colfunc)
if !isempty(indscol) && first(indscol) == inow
getindsall(
(indsall..., colfunc(inow)),
inow + 1,
Base.tail(indscol),
loopinds,
rfunc,
colfunc,
)
else
getindsall(
(indsall..., rfunc(first(loopinds))),
inow + 1,
indscol,
Base.tail(loopinds),
rfunc,
colfunc,
)
end
end
getindsall(indsall, inow, ::Tuple{}, ::Tuple{}, r, c) = indsall
function updatear_window(r, cube, indscol, loopinds, cache, windows, windowoob)
indsall = getindsall(indscol, loopinds, i -> r[i])
for (iw, pa) in windows
iold = indsall[iw]
indsall = Base.setindex(indsall, first(iold)-pa[1]:last(iold)+pa[2], iw)
end
data = getdata(cube)
l2 = map((i, s) -> isa(i, Colon) ? s : length(i), indsall, size(cache))
oo = map(indsall, axes(cache), axes(data)) do i, c, d
if isa(i, Colon)
return Base.OneTo(length(c)), Base.OneTo(length(c))
else
precut, aftercut = max(0, first(d) - first(i)), max(0, last(i) - last(d))
icube = first(i)+precut:last(i)-aftercut
icache = first(c)+precut:first(c)+precut+length(icube)-1
return icache, icube
end
end
hinds = first.(oo)
indsall2 = last.(oo)
fill!(cache, windowoob)
cache[hinds...] = data[indsall2...]
end
function updatear(f, r, cube, indscol, loopinds, cache)
indsall = getindsall(indscol, loopinds, i -> r[i])
l2 = map((i, s) -> isa(i, Colon) ? s : length(i), indsall, size(cache))
if size(cache) != l2
hinds = map((i, s) -> isa(i, Colon) ? (1:s) : 1:length(i), indsall, size(cache))
if f == :read
cache[hinds...] = getdata(cube)[indsall...]
else
getdata(cube)[indsall...] = cache[hinds...]
end
else
if f == :read
d = getdata(cube)[indsall...]
cache[:] = d
else
_writedata(getdata(cube), cache, indsall)
end
end
end
_writedata(d,cache,indsall) = d[indsall...] = cache
_writedata(d::Array{<:Any,0},cache::Array{<:Any,0},::Tuple{}) = d[] = cache[]
updateinars(dc, r, incaches) = updatears(dc.incubes, r, :read, incaches)
writeoutars(dc, r, outcaches) = updatears(dc.outcubes, r, :write, outcaches)
function moduleloadedeverywhere()
try
isloaded = map(workers()) do w
#We try calling a function defined inside this module, thi will error when YAXArrays is not loaded on the remote workers
remotecall(() -> true, w)
end
fetch.(isloaded)
catch e
return false
end
return true
end
function runLoop(dc::DATConfig, showprog)
allRanges = GridChunks(getloopchunks(dc)...)
if dc.ispar
#Test if YAXArrays is loaded on all workers:
moduleloadedeverywhere() || error(
"YAXArrays is not loaded on all workers. Please run `@everywhere using YAXArrays` to fix.",
)
mapfun = showprog ? progress_pmap : pmap
m = mapfun(CachingPool(workers()),allRanges) do r
incaches, outcaches, args = getallargs(dc)
updateinars(dc, r, incaches)
if dc.ntr[myid()] > 1
innerLoop_threaded(r, args...)
else
innerLoop(r,args...)
end
writeoutars(dc, r, outcaches)
dc.do_gc && GC.gc()
end
else
incaches, outcaches, args = getallargs(dc)
mapfun = showprog ? progress_map : map
mapfun(allRanges) do r
updateinars(dc, r, incaches)
if dc.ntr[1] > 1
innerLoop_threaded(r, args...)
else
innerLoop(r,args...)
end
writeoutars(dc, r, outcaches)
dc.do_gc && GC.gc()
end
end
dc.outcubes
end
abstract type AxValCreator end
struct NoLoopAxes <: AxValCreator end
struct AllLoopAxes{S,V} <: AxValCreator
loopsyms::S
loopaxvals::V
end
AllLoopAxes(a) = AllLoopAxes(map(DD.name, a), map(i -> i.val, a))
getlaxvals(::NoLoopAxes, cI, offscur) = ()
getlaxvals(a::AllLoopAxes, cI, offscur) = (
NamedTuple{a.loopsyms}(
map((ax, i, of) -> (i + of, ax[i+of]), a.loopaxvals, cI.I, offscur),
),
)
function getallargs(dc::DATConfig)
incache, outcache = getCubeCache(dc)
filters = map(ic -> ic.desc.procfilter, dc.incubes)
axvals = if dc.include_loopvars
lax = (dc.LoopAxes...,)
AllLoopAxes(lax)
else
NoLoopAxes()
end
adda = dc.addargs
kwa = dc.kwargs
fu = if !dc.inplace
makeinplace(dc.fu)
else
dc.fu
end
inarsbc = map(dc.incubes, incache) do ic, cache
allax = getindsall(geticolon(ic), 1:length(dc.LoopAxes), i -> i in ic.loopinds ? true : false)
if has_window(ic)
for (iw, pa) in zip(ic.iwindow, ic.window)
allax = Base.setindex(allax, pa, iw)
end
end
if ic.colonperm === nothing
pa = PickAxisArray(cache, allax)
else
pa = PickAxisArray(cache, allax, ic.colonperm)
end
end
outarsbc = map(dc.outcubes, outcache) do oc, cache
allax = getindsall(1:length(oc.axesSmall), oc.loopinds, i -> true)
pa = PickAxisArray(cache, allax)
pa
end
incache,
outcache,
(fu, inarsbc, outarsbc, filters, axvals, adda, kwa)
end
function getbackend(oc, ispar, max_cache)
elementtype = Union{oc.outtype,Missing}
outsize =
sizeof(elementtype) * (length(oc.allAxes) > 0 ? prod(map(length, oc.allAxes)) : 1)
rt = oc.desc.backend
ispath = get(oc.desc.backendargs, :path, nothing)
b = if rt == :auto && !isnothing(ispath)
YAXArrayBase.backendfrompath(ispath)
elseif rt == :auto
if ispar[] || outsize > max_cache
YAXArrayBase.backendlist[:zarr]
else
YAXArrayBase.backendlist[:array]
end
else
YAXArrayBase.backendlist[Symbol(rt)] # Handle non-auto rt case
end
if !allow_parallel_write(b)
ispar[] = false
end
elementtype, b
end
function generateOutCube(
::Type{T},
elementtype,
oc::OutputCube,
loopcachesize,
co;
kwargs...,
) where {T}
cs_inner = (map(length, oc.axesSmall)...,)
cs = (cs_inner..., loopcachesize...)
co = (map(_->0, oc.axesSmall)...,co...)
for (i, cc) in enumerate(oc.innerchunks)
if cc !== nothing && i <= length(oc.axesSmall)
cs = Base.setindex(cs, approx_chunksize(cc), i)
co = Base.setindex(co,grid_offset(cc), i)
end
end
cube1, cube2 = createdataset(
T,
oc.allAxes;
T = elementtype,
chunksize = cs,
chunkoffset = co,
kwargs...,
)
oc.cube = cube1
oc.cube_unpermuted = cube2
end
function generateOutCube(
::Type{T},
elementtype,
oc::OutputCube,
loopcachesize,
co;
kwargs...,
) where {T<:Array}
newsize = map(length, oc.allAxes)
outar = Array{elementtype}(undef, newsize...)
fill!(outar,_zero(elementtype))
# @show oc.desc.backendargs[:properties]
properties = get(oc.desc.backendargs, :properties, Dict{String, Any}())
# @show properties
oc.cube = YAXArray(tuple(oc.allAxes...), outar, properties) # properties ? include properties!
oc.cube_unpermuted = oc.cube
end
_zero(T) = zero(T)
_zero(T::Type{<:AbstractString}) = convert(T, "")
function generateOutCubes(dc::DATConfig)
rr = getloopchunks(dc)
cs = approx_chunksize.(rr)
offs = grid_offset.(rr)
foreach(dc.outcubes) do c
generateOutCube(c, Ref(dc.ispar), dc.max_cache, cs, offs)
end
end
function generateOutCube(oc::OutputCube, ispar::Ref{Bool}, max_cache, loopcachesize, co)
elementtype, cubetype = getbackend(oc, ispar, max_cache)
generateOutCube(cubetype, elementtype, oc, loopcachesize, co; oc.desc.backendargs...)
end
function getCubeCache(dc::DATConfig)
allranges = getloopchunks(dc)
outcaches = map(i -> allocatecachebuf(i, max_chunksize.(allranges)), dc.outcubes)
incaches = map(i -> allocatecachebuf(i, max_chunksize.(allranges)), dc.incubes)
incaches, outcaches
end
function allocatecachebuf(ic::Union{InputCube,OutputCube}, loopcachesize)
s = size(ic.cube)
indsall = getindsall(geticolon(ic), ic.loopinds, i -> loopcachesize[i], i -> s[i])
if has_window(ic)
indsall = Base.OneTo.(indsall)
for (iw, (pre, after)) in zip(ic.iwindow, ic.window)
old = indsall[iw]
new = (first(old)-pre):(last(old)+after)
indsall = Base.setindex(indsall, new, iw)
end
#@show indsall
OffsetArray(Array{eltype(ic.cube)}(undef, length.(indsall)...), indsall...)
else
Array{eltype(ic.cube)}(undef,indsall...)
end
end
function init_DATworkers()
freshworkermodule()
end
function analyzeAxes(dc::DATConfig{NIN,NOUT}) where {NIN,NOUT}
loopaxsyms = Symbol[]
for cube in dc.incubes
for (iax,a) in enumerate(caxes(cube.cube))
if !in(a, cube.axesSmall)
s = DD.name(a)
is = findfirst(isequal(s), loopaxsyms)
if is === nothing
push!(dc.LoopAxes, a)
push!(loopaxsyms, s)
is = length(loopaxsyms)
else
a == dc.LoopAxes[is] || error("Axes $a and $(dc.LoopAxes[is]) have the same name but are note identical")
end
push!(cube.loopinds,is)
if iax in cube.iwindow
push!(cube.windowloopinds, is)
end
end
end
end
for outcube in dc.outcubes
LoopAxesAdd = DD.Dimension[]
for (il, loopax) in enumerate(dc.LoopAxes)
push!(outcube.loopinds, il)
push!(LoopAxesAdd, loopax)
end
outcube.allAxes = DD.Dimension[outcube.axesSmall; LoopAxesAdd]
dold = outcube.innerchunks
newchunks = ntuple(_->nothing, length(outcube.allAxes))
for (k, v) in dold
ii = findAxis(k, outcube.allAxes)
if ii !== nothing
if v isa Integer
v = RegularChunks(v,0,length(outcube.allAxes[ii]))
end
newchunks = Base.setindex(newchunks, v, ii)
end
end
outcube.innerchunks = newchunks
end
#And resolve names in chunk size dicts
return dc
end
mysizeof(x) = sizeof(x)
mysizeof(x::Type{String}) = 1
"""
Function that compares two cache miss specifiers by their importance
"""
function cmpcachmisses(x1, x2)
#First give preference to compressed misses
if xor(x1.iscompressed, x2.iscompressed)
return x1.iscompressed
#Now compare the size of the miss multiplied with the inner size
else
return approx_chunksize(x1.cs) * x1.innerleap > approx_chunksize(x2.cs) * x2.innerleap
end
end
function getCacheSizes(dc::DATConfig, loopchunksizes)
inAxlengths = Vector{Int}[Int.(length.(cube.axesSmall)) for cube in dc.incubes]
inblocksizes = map(
(x, T) ->
isempty(x) ? mysizeof(eltype(T.cube)) : prod(x) * mysizeof(eltype(T.cube)),
inAxlengths,
dc.incubes,
)
inblocksize = sum(inblocksizes)
outblocksizes = map(
C ->
length(C.axesSmall) > 0 ?
sizeof(C.outtype) * prod(map(Int ∘ length, C.axesSmall)) : 1,
dc.outcubes,
)
outblocksize = length(outblocksizes) > 0 ? sum(outblocksizes) : 1
#Now add cache miss information for each input cube to every loop axis
cmisses = NamedTuple{
(:iloopax, :cs, :iscompressed, :innerleap, :preventpar),
Tuple{Int64,ChunkType,Bool,Int64,Bool},
}[]
userchunks = Dict{Int,Int}()
for (k, v) in loopchunksizes
ii = findAxis(k, dc.LoopAxes)
if ii !== nothing
v isa ChunkType || error("Loop chunks must be provided as ChunkType object")
userchunks[ii] = v
end
end