comparison src/LazyTensors/tuple_manipulation.jl @ 1858:4a9be96f2569 feature/documenter_logo

Merge default
author Jonatan Werpers <jonatan@werpers.com>
date Sun, 12 Jan 2025 21:18:44 +0100
parents d7bc11053951
children
comparison
equal deleted inserted replaced
1857:ffde7dad9da5 1858:4a9be96f2569
1 """
2 split_index(dim_before, dim_view, dim_index, dim_after, I...)
3
4 Splits the multi-index `I` into two parts. One part which is expected to be
5 used as a view, and one which is expected to be used as an index.
6 E.g.
7 ```julia-repl
8 julia> LazyTensors.split_index(1, 3, 2, 1, (1,2,3,4)...)
9 ((1, Colon(), Colon(), Colon(), 4), (2, 3))
10 ```
11
12 `dim_view` controls how many colons are in the view, and `dim_index` controls
13 how many elements are extracted from the middle.
14 `dim_before` and `dim_after` decides the length of the index parts before and after the colons in the view index.
15
16 Arguments should satisfy `length(I) == dim_before+B_domain+dim_after`.
17
18 The returned values satisfy
19 * `length(view_index) == dim_before + dim_view + dim_after`
20 * `length(I_middle) == dim_index`
21 """
22 function split_index(dim_before, dim_view, dim_index, dim_after, I...)
23 @inline
24 I_before, I_middle, I_after = split_tuple(I, (dim_before, dim_index, dim_after))
25
26 view_index = (I_before..., ntuple((i)->:, dim_view)..., I_after...)
27
28 return view_index, I_middle
29 end
30
31
32 """
33 split_tuple(t, szs)
34
35 Split the tuple `t` into a set of tuples of the sizes given in `szs`.
36 `sum(szs)` should equal `length(t)`.
37
38 E.g
39 ```julia-repl
40 julia> LazyTensors.split_tuple((1,2,3,4,5,6), (3,1,2))
41 ((1, 2, 3), (4,), (5, 6))
42 ```
43 """
44 function split_tuple(t, szs)
45 @inline
46 if length(t) != sum(szs; init=0)
47 throw(ArgumentError("length(t) must equal sum(szs)"))
48 end
49
50 rs = sizes_to_ranges(szs)
51 return map(r->t[r], rs)
52 end
53
54 function sizes_to_ranges(szs)
55 cum_szs = cumsum((0, szs...))
56 return ntuple(i->cum_szs[i]+1:cum_szs[i+1], length(szs))
57 end
58
59
60 """
61 concatenate_tuples(t...)
62
63 Concatenate tuples.
64 """
65 concatenate_tuples(t::Tuple,ts::Vararg{Tuple}) = (t..., concatenate_tuples(ts...)...)
66 concatenate_tuples(t::Tuple) = t
67
68
69 """
70 left_pad_tuple(t, val, N)
71
72 Left pad the tuple `t` to length `N` using the value `val`.
73 """
74 function left_pad_tuple(t, val, N)
75 if N < length(t)
76 throw(DomainError(N, "Can't pad tuple of length $(length(t)) to $N elements"))
77 end
78
79 padding = ntuple(i->val, N-length(t))
80 return (padding..., t...)
81 end
82
83 """
84 right_pad_tuple(t, val, N)
85
86 Right pad the tuple `t` to length `N` using the value `val`.
87 """
88 function right_pad_tuple(t, val, N)
89 if N < length(t)
90 throw(DomainError(N, "Can't pad tuple of length $(length(t)) to $N elements"))
91 end
92
93 padding = ntuple(i->val, N-length(t))
94 return (t..., padding...)
95 end
96