-
Notifications
You must be signed in to change notification settings - Fork 13
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Support for kernels with no known base kernel #163
Draft
isuruf
wants to merge
5
commits into
inducer:main
Choose a base branch
from
isuruf:unknown2
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
4e6894c
add get_pde_operators to find the diff op from a base kernel
isuruf ef8cc2e
filter zeros from diff op and add __add__
isuruf 5d597cf
Add more tests
isuruf 19d850c
make LinearPDESystemOperator.eqs hashable
isuruf 1e034e7
No need to enumerate
isuruf File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -36,12 +36,16 @@ | |
""" | ||
|
||
from pytools.tag import tag_dataclass | ||
from pytools import (single_valued, | ||
generate_nonnegative_integer_tuples_summing_to_at_most as gnitstam) | ||
from math import floor | ||
|
||
import numpy as np | ||
import sumpy.symbolic as sym | ||
from sumpy.tools import add_to_sac, add_mi | ||
from sumpy.tools import add_to_sac, add_mi, nullspace | ||
from sumpy.kernel import Kernel | ||
|
||
from typing import Dict, Tuple, Any | ||
from typing import Dict, Tuple, Any, Mapping, Text | ||
|
||
import logging | ||
|
||
|
@@ -404,6 +408,172 @@ def diff_derivative_coeff_dict(derivative_coeff_dict: DerivativeCoeffDict, | |
return {derivative: coeff for derivative, coeff in | ||
new_derivative_coeff_dict.items() if coeff != 0} | ||
|
||
|
||
def _get_sympy_kernel_expression(kernel: Kernel, | ||
kernel_arguments: Mapping[Text, Any]) -> sym.Basic: | ||
"""Convert a :mod:`pymbolic` expression to :mod:`sympy` expression | ||
after substituting kernel arguments. | ||
For eg: `exp(I*k*r)/r` with `{k: 1}` is converted to the sympy expression | ||
`exp(I*r)/r` | ||
""" | ||
from pymbolic.mapper.substitutor import substitute | ||
from sumpy.symbolic import PymbolicToSympyMapperWithSymbols | ||
|
||
expr = substitute(kernel.get_base_kernel().expression, kernel_arguments) | ||
expr = PymbolicToSympyMapperWithSymbols()(expr) | ||
|
||
dvec = sym.make_sym_vector("d", kernel.dim) | ||
res = kernel.postprocess_at_target(kernel.postprocess_at_source( | ||
expr, dvec), dvec) | ||
return res | ||
|
||
|
||
def evalf(expr: sym.Basic, dps: float): | ||
"""evaluate an expression numerically using ``dps`` | ||
number of digits. | ||
""" | ||
from sumpy.symbolic import USE_SYMENGINE | ||
if USE_SYMENGINE: | ||
import symengine | ||
prec = int(symengine.log(10**dps, 2)) | ||
return expr.n(prec=prec) | ||
else: | ||
return expr.n(n=dps) | ||
|
||
|
||
def chop(expr: sym.Basic, tol: float) -> sym.Basic: | ||
"""Given a symbolic expression, remove all occurences of numbers | ||
with absolute value less than a given tolerance and replace floating | ||
point numbers that are close to an integer up to a given relative | ||
tolerance by the integer. | ||
""" | ||
nums = expr.atoms(sym.Number) | ||
replace_dict = {} | ||
for num in nums: | ||
if float(abs(num)) < tol: | ||
replace_dict[num] = 0 | ||
else: | ||
new_num = float(num) | ||
if abs((int(new_num) - new_num)/new_num) < tol: | ||
new_num = int(new_num) | ||
replace_dict[num] = new_num | ||
return expr.xreplace(replace_dict) | ||
|
||
|
||
def get_deriv_sample(kernel, order, samples, kernel_arguments, atol): | ||
dim = kernel.dim | ||
sym_vec = sym.make_sym_vector("d", dim) | ||
base_expr = _get_sympy_kernel_expression(kernel, | ||
dict(kernel_arguments)) | ||
|
||
mis = sorted(gnitstam(order, dim), key=sum) | ||
assert samples.shape[0] == dim | ||
|
||
exprs = [] | ||
for mi in mis: | ||
expr = base_expr | ||
for var_idx, nderivs in enumerate(mi): | ||
if nderivs == 0: | ||
continue | ||
expr = expr.diff(sym_vec[var_idx], nderivs) | ||
exprs.append(expr) | ||
|
||
dps = -sym.log(atol, 10) | ||
mat = [] | ||
for isample in range(samples.shape[1]): | ||
row = [] | ||
for ideriv in range(len(mis)): | ||
expr = exprs[ideriv] | ||
replace_dict = dict(zip(sym_vec, samples[:, isample])) | ||
eval_expr = evalf(expr.xreplace(replace_dict), dps) | ||
row.append(eval_expr) | ||
mat.append(row) | ||
mat = sym.Matrix(mat) | ||
|
||
return mat, mis | ||
|
||
|
||
def get_dependent_columns(matrix, atol): | ||
import sympy | ||
m = matrix.T | ||
l, u, p = sympy.Matrix(m).LUdecomposition( | ||
iszerofunc=lambda x: abs(x) < atol) | ||
nrows = m.shape[0] | ||
idxs = list(range(nrows)) | ||
for i, j in p: | ||
idxs[i], idxs[j] = idxs[j], idxs[i] | ||
|
||
nonzero_rows = 0 | ||
for i in range(nrows - 1, -1, -1): | ||
if not all(abs(elem) < atol for elem in u[i, :]): | ||
nonzero_rows = i + 1 | ||
break | ||
|
||
return idxs[nonzero_rows:] | ||
|
||
|
||
def get_pde_operators(kernels, order, kernel_arguments, atol=1e-30): | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Type annotation? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Docstring? |
||
import sympy | ||
from sumpy.expansion.diff_op import diff, make_identity_diff_op | ||
dim = single_valued(kernel.dim for kernel in kernels) | ||
|
||
mis = sorted(gnitstam(order, dim), key=sum) | ||
|
||
# (-1, -1, -1) represents a constant | ||
# ((0,0,0) would be "function with no derivatives") | ||
# mis.append((-1,)*dim) | ||
|
||
n = len(kernels) | ||
nsamples = int(floor(len(mis) * n / (n-1))) + n + 1 | ||
rand = np.random.randint(1, 10**15, (dim, nsamples)) | ||
rand = rand.astype(object) | ||
for i in range(rand.shape[0]): | ||
for j in range(rand.shape[1]): | ||
rand[i, j] = sym.sympify(rand[i, j])/10**15 | ||
|
||
derivs_evaluated = [ | ||
get_deriv_sample(kernel, order, rand, kernel_arguments, atol)[0] | ||
for kernel in kernels] | ||
|
||
for mat in derivs_evaluated: | ||
dep_cols = get_dependent_columns(mat, atol * 1e10) | ||
zeros = [0]*mat.shape[0] | ||
for col in dep_cols: | ||
mat[:, col] = zeros | ||
|
||
full_mat = sym.zeros((n - 1) * nsamples, len(mis) * n) | ||
assert full_mat.shape[0] > full_mat.shape[1] | ||
for i in range(1, n): | ||
full_mat[(i - 1)*nsamples:i*nsamples, :len(mis)] = derivs_evaluated[i] | ||
full_mat[(i - 1)*nsamples:i*nsamples, i*len(mis):(i + 1)*len(mis)] = \ | ||
-derivs_evaluated[0] | ||
|
||
ns = nullspace(full_mat.tolist(), atol * 1e10) | ||
for col in range(ns.shape[1]): | ||
for i in range(n): | ||
if all(abs(elem) < atol * 1e10 for elem in | ||
ns[i*len(mis):(i + 1)*len(mis), col]): | ||
break | ||
else: | ||
ops = sym.Matrix(ns[:, col].tolist()).reshape(n, len(mis)) | ||
ops = ops.applyfunc(lambda x: sympy.nsimplify(x, tolerance=atol*1e10)) | ||
id_op = make_identity_diff_op(dim, 1) | ||
diff_ops = [] | ||
for i in range(n): | ||
diff_op = None | ||
for mi_idx, coeff in enumerate(ops[i, :]): | ||
if coeff == 0: | ||
continue | ||
mi = mis[mi_idx] | ||
if not diff_op: | ||
diff_op = coeff * diff(id_op, mi) | ||
else: | ||
diff_op += coeff * diff(id_op, mi) | ||
diff_ops.append(diff_op) | ||
return diff_ops | ||
|
||
raise RuntimeError("Could not find PDE operators") | ||
|
||
# }}} | ||
|
||
# vim: fdm=marker |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
__copyright__ = "Copyright (C) Isuru Fernando" | ||
|
||
__license__ = """ | ||
Permission is hereby granted, free of charge, to any person obtaining a copy | ||
of this software and associated documentation files (the "Software"), to deal | ||
in the Software without restriction, including without limitation the rights | ||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
copies of the Software, and to permit persons to whom the Software is | ||
furnished to do so, subject to the following conditions: | ||
|
||
The above copyright notice and this permission notice shall be included in | ||
all copies or substantial portions of the Software. | ||
|
||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN | ||
THE SOFTWARE. | ||
""" | ||
|
||
|
||
from typing import Union | ||
import numpy as np | ||
from pymbolic.primitives import Expression | ||
|
||
IntegralT = Union[int, np.integer] | ||
FloatT = Union[float, complex, np.floating, np.complexfloating] | ||
|
||
ExpressionT = Union[IntegralT, FloatT, Expression] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Naming? 🤷