-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
zeta.py
66 lines (50 loc) · 1.73 KB
/
zeta.py
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
from chainer.backends import cuda
from chainer import function_node
from chainer import utils
from chainer.utils import type_check
_zeta_cpu = None
class Zeta(function_node.FunctionNode):
def __init__(self, x):
self._x = x
@property
def label(self):
return 'zeta'
def check_type_forward(self, in_types):
type_check._argname(in_types, ('q'))
q_type, = in_types
type_check.expect(
q_type.dtype.kind == 'f'
)
def forward_cpu(self, inputs):
q, = inputs
global _zeta_cpu
if _zeta_cpu is None:
try:
from scipy import special
_zeta_cpu = special.zeta
except ImportError:
raise ImportError('Scipy is not available. Forward computation'
' of zeta cannot be done.')
self.retain_inputs((0,))
return utils.force_array(_zeta_cpu(self._x, q), dtype=q.dtype),
def forward_gpu(self, inputs):
q, = inputs
self.retain_inputs((0,))
return utils.force_array(
cuda.cupyx.scipy.special.zeta(self._x, q), dtype=q.dtype),
def backward(self, indexes, gy):
q, = self.get_retained_inputs()
return gy[0] * -self._x * zeta(self._x + 1, q),
def zeta(x, q):
"""Zeta function.
Differentiable only with respect to q
.. note::
Forward computation in CPU can not be done if
`SciPy <https://www.scipy.org/>`_ is not available.
Args:
x (:class:`~chainer.Variable` or :ref:`ndarray`): Input variable.
q (:class:`~chainer.Variable` or :ref:`ndarray`): Input variable.
Returns:
~chainer.Variable: Output variable.
"""
return Zeta(x).apply((q,))[0]