Skip to content

Commit f0a675e

Browse files
committed
add gufunc string signature parsing
1 parent 6b170d0 commit f0a675e

File tree

1 file changed

+23
-3
lines changed

1 file changed

+23
-3
lines changed

xarray/core/computation.py

Lines changed: 23 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,18 @@
11
import itertools
2+
import re
23
from collections import namedtuple
34

45
from .core.pycompat import dask_array_type
56

67

8+
# see http://docs.scipy.org/doc/numpy/reference/c-api.generalized-ufuncs.html
9+
DIMENSION_NAME = r'\w+'
10+
CORE_DIMENSION_LIST = '(?:' + DIMENSION_NAME + '(?:,' + DIMENSION_NAME + ')*)?'
11+
ARGUMENT = r'\(' + CORE_DIMENSION_LIST + r'\)'
12+
ARGUMENT_LIST = ARGUMENT + '(?:,'+ ARGUMENT + ')*'
13+
SIGNATURE = '^' + ARGUMENT_LIST + '->' + ARGUMENT_LIST + '$'
14+
15+
716
class Signature(object):
817
"""Core dimensions signature for a given function
918
@@ -12,9 +21,9 @@ class Signature(object):
1221
Attributes
1322
----------
1423
input_core_dims : list of tuples
15-
A list of tuples of dimension names expected on each input variable.
24+
A list of tuples of core dimension names on each input variable.
1625
output_core_dims : list of tuples
17-
A list of tuples of dimension names expected on each output variable.
26+
A list of tuples of core dimension names on each output variable.
1827
"""
1928
def __init__(self, input_core_dims, output_core_dims=((),)):
2029
if dtypes is None:
@@ -40,7 +49,18 @@ def all_output_core_dims(self):
4049

4150
@classmethod
4251
def from_string(cls, string):
43-
raise NotImplementedError
52+
"""Create a Signature object from a NumPy gufunc signature.
53+
54+
Parameters
55+
----------
56+
string : str
57+
Signature string, e.g., (m,n),(n,p)->(m,p).
58+
"""
59+
if not re.match(SIGNATURE, string):
60+
raise ValueError('not a valid gufunc signature: {}'.format(string))
61+
return cls(*[[re.findall(DIMENSION_NAME, arg)
62+
for arg in re.findall(ARGUMENT, arg_list)]
63+
for arg_list in string.split('->')])
4464

4565
@classmethod
4666
def from_ufunc(cls, ufunc):

0 commit comments

Comments
 (0)