|
| 1 | +__copyright__ = "Copyright (C) 2022 Alexandru Fikl" |
| 2 | + |
| 3 | +__license__ = """ |
| 4 | +Permission is hereby granted, free of charge, to any person obtaining a copy |
| 5 | +of this software and associated documentation files (the "Software"), to deal |
| 6 | +in the Software without restriction, including without limitation the rights |
| 7 | +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
| 8 | +copies of the Software, and to permit persons to whom the Software is |
| 9 | +furnished to do so, subject to the following conditions: |
| 10 | +
|
| 11 | +The above copyright notice and this permission notice shall be included in |
| 12 | +all copies or substantial portions of the Software. |
| 13 | +
|
| 14 | +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 15 | +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 16 | +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 17 | +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 18 | +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
| 19 | +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN |
| 20 | +THE SOFTWARE. |
| 21 | +""" |
| 22 | + |
| 23 | +from dataclasses import dataclass |
| 24 | +from typing import Any, Dict, Iterable, Optional, Union |
| 25 | + |
| 26 | +import numpy as np |
| 27 | + |
| 28 | +from arraycontext import PyOpenCLArrayContext, ArrayOrContainerT |
| 29 | +from meshmode.dof_array import DOFArray |
| 30 | + |
| 31 | +from pytential import GeometryCollection, sym |
| 32 | +from pytential.linalg.cluster import ClusterTree, cluster |
| 33 | + |
| 34 | +__doc__ = """ |
| 35 | +Hierarical Matrix Construction |
| 36 | +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 37 | +""" |
| 38 | + |
| 39 | + |
| 40 | +# {{{ ProxyHierarchicalMatrix |
| 41 | + |
| 42 | +@dataclass(frozen=True) |
| 43 | +class ProxyHierarchicalMatrix: |
| 44 | + """ |
| 45 | + .. attribute:: ctree |
| 46 | +
|
| 47 | + A :class:`~pytential.linalg.cluster.ClusterTree`. |
| 48 | +
|
| 49 | + .. attribute:: skeletons |
| 50 | +
|
| 51 | + An :class:`~numpy.ndarray` containing skeletonization information |
| 52 | + for each level of the hierarchy. For additional details, see |
| 53 | + :class:`~pytential.linalg.skeletonization.SkeletonizationResult`. |
| 54 | +
|
| 55 | + This class implements the :class:`scipy.sparse.linalg.LinearOperator` |
| 56 | + interface. In particular, the following attributes and methods: |
| 57 | +
|
| 58 | + .. attribute:: shape |
| 59 | +
|
| 60 | + A :class:`tuple` that gives the matrix size ``(m, n)``. |
| 61 | +
|
| 62 | + .. attribute:: dtype |
| 63 | +
|
| 64 | + The data type of the matrix entries. |
| 65 | +
|
| 66 | + .. automethod:: matvec |
| 67 | + .. automethod:: __matmul__ |
| 68 | + """ |
| 69 | + |
| 70 | + ctree: ClusterTree |
| 71 | + skeletons: np.ndarray |
| 72 | + |
| 73 | + @property |
| 74 | + def shape(self): |
| 75 | + return self.skeletons[0].tgt_src_index.shape |
| 76 | + |
| 77 | + @property |
| 78 | + def dtype(self): |
| 79 | + # FIXME: assert that everyone has this dtype? |
| 80 | + return self.skeletons[0].R[0].dtype |
| 81 | + |
| 82 | + @property |
| 83 | + def nlevels(self): |
| 84 | + return self.skeletons.size |
| 85 | + |
| 86 | + def matvec(self, x: ArrayOrContainerT) -> ArrayOrContainerT: |
| 87 | + """Implements a matrix-vector multiplication :math:`H x`.""" |
| 88 | + from arraycontext import get_container_context_recursively_opt |
| 89 | + actx = get_container_context_recursively_opt(x) |
| 90 | + if actx is None: |
| 91 | + raise ValueError("input array is frozen") |
| 92 | + |
| 93 | + return apply_skeleton_matvec(actx, self, x) |
| 94 | + |
| 95 | + def __matmul__(self, x: ArrayOrContainerT) -> ArrayOrContainerT: |
| 96 | + """Same as :meth:`matvec`.""" |
| 97 | + return self.matvec(x) |
| 98 | + |
| 99 | + def rmatvec(self, x): |
| 100 | + raise NotImplementedError |
| 101 | + |
| 102 | + def matmat(self, mat): |
| 103 | + raise NotImplementedError |
| 104 | + |
| 105 | + def rmatmat(self, mat): |
| 106 | + raise NotImplementedError |
| 107 | + |
| 108 | + |
| 109 | +def apply_skeleton_matvec( |
| 110 | + actx: PyOpenCLArrayContext, |
| 111 | + hmat: ProxyHierarchicalMatrix, |
| 112 | + x: ArrayOrContainerT, |
| 113 | + ) -> ArrayOrContainerT: |
| 114 | + from arraycontext import flatten |
| 115 | + x = actx.to_numpy(flatten(x, actx, leaf_class=DOFArray)) |
| 116 | + |
| 117 | + from pytential.linalg.utils import split_array |
| 118 | + y = split_array(x, hmat.skeletons[0].tgt_src_index.sources) |
| 119 | + |
| 120 | + assert x.dtype == hmat.dtype |
| 121 | + assert x.shape == (hmat.shape[1],) |
| 122 | + |
| 123 | + d_dot_y = np.empty(hmat.nlevels, dtype=object) |
| 124 | + r_dot_y = np.empty(hmat.nlevels, dtype=object) |
| 125 | + |
| 126 | + # recurse down |
| 127 | + for k, clevel in enumerate(hmat.ctree.levels(root=True)): |
| 128 | + skeleton = hmat.skeletons[k] |
| 129 | + assert skeleton.tgt_src_index.shape[1] == sum(xi.size for xi in y) |
| 130 | + |
| 131 | + d_dot_y_k = np.empty(skeleton.nclusters, dtype=object) |
| 132 | + r_dot_y_k = np.empty(skeleton.nclusters, dtype=object) |
| 133 | + |
| 134 | + for i in range(skeleton.nclusters): |
| 135 | + r_dot_y_k[i] = skeleton.R[i] @ y[i] |
| 136 | + d_dot_y_k[i] = skeleton.D[i] @ y[i] |
| 137 | + |
| 138 | + r_dot_y[k] = r_dot_y_k |
| 139 | + d_dot_y[k] = d_dot_y_k |
| 140 | + y = cluster(r_dot_y_k, clevel) |
| 141 | + |
| 142 | + # recurse up |
| 143 | + for k, skeleton in reversed(list(enumerate(hmat.skeletons))): |
| 144 | + r_dot_y_k = r_dot_y[k] |
| 145 | + d_dot_y_k = d_dot_y[k] |
| 146 | + |
| 147 | + result = np.empty(skeleton.nclusters, dtype=object) |
| 148 | + for i in range(skeleton.nclusters): |
| 149 | + result[i] = skeleton.L[i] @ r_dot_y_k[i] + d_dot_y_k[i] |
| 150 | + |
| 151 | + from arraycontext import unflatten |
| 152 | + return unflatten( |
| 153 | + x, |
| 154 | + actx.from_numpy(np.concatenate(result)), |
| 155 | + actx) |
| 156 | + |
| 157 | +# }}} |
| 158 | + |
| 159 | + |
| 160 | +# {{{ build_hmatrix_matvec_by_proxy |
| 161 | + |
| 162 | +def build_hmatrix_matvec_by_proxy( |
| 163 | + actx: PyOpenCLArrayContext, |
| 164 | + places: GeometryCollection, |
| 165 | + exprs: Union[sym.Expression, Iterable[sym.Expression]], |
| 166 | + input_exprs: Union[sym.Expression, Iterable[sym.Expression]], *, |
| 167 | + domains: Optional[Iterable[sym.DOFDescriptorLike]] = None, |
| 168 | + context: Optional[Dict[str, Any]] = None, |
| 169 | + id_eps: float = 1.0e-8, |
| 170 | + |
| 171 | + # NOTE: these are dev variables and can disappear at any time! |
| 172 | + # TODO: plugin in error model to get an estimate for: |
| 173 | + # * how many points we want per cluster? |
| 174 | + # * how many proxy points we want? |
| 175 | + # * how far away should the proxy points be? |
| 176 | + # based on id_eps. How many of these should be user tunable? |
| 177 | + _tree_kind: Optional[str] = "adaptive-level-restricted", |
| 178 | + _max_particles_in_box: Optional[int] = None, |
| 179 | + |
| 180 | + _id_rank: Optional[int] = None, |
| 181 | + |
| 182 | + _approx_nproxy: Optional[int] = None, |
| 183 | + _proxy_radius_factor: Optional[float] = None, |
| 184 | + _proxy_cls: Optional[type] = None, |
| 185 | + ): |
| 186 | + from pytential.linalg.cluster import partition_by_nodes |
| 187 | + cluster_index, ctree = partition_by_nodes( |
| 188 | + actx, places, |
| 189 | + tree_kind=_tree_kind, |
| 190 | + max_particles_in_box=_max_particles_in_box) |
| 191 | + |
| 192 | + from pytential.linalg.utils import TargetAndSourceClusterList |
| 193 | + tgt_src_index = TargetAndSourceClusterList( |
| 194 | + targets=cluster_index, sources=cluster_index) |
| 195 | + |
| 196 | + from pytential.linalg.skeletonization import rec_skeletonize_by_proxy |
| 197 | + skeletons = rec_skeletonize_by_proxy( |
| 198 | + actx, places, ctree, tgt_src_index, exprs, input_exprs, |
| 199 | + domains=domains, |
| 200 | + context=context, |
| 201 | + id_eps=id_eps, |
| 202 | + id_rank=_id_rank, |
| 203 | + approx_nproxy=_approx_nproxy, |
| 204 | + proxy_radius_factor=_proxy_radius_factor, |
| 205 | + max_particles_in_box=_max_particles_in_box, |
| 206 | + _proxy_cls=_proxy_cls, |
| 207 | + ) |
| 208 | + |
| 209 | + return ProxyHierarchicalMatrix(ctree=ctree, skeletons=skeletons) |
| 210 | + |
| 211 | +# }}} |
0 commit comments