types.py 14.1 KB
Newer Older
1
import ctypes
2
import sympy as sp
3
import numpy as np
4
from sympy.core.cache import cacheit
5

6
from pystencils.cache import memorycache
7
8
9
from pystencils.utils import allEqual

castFunc = sp.Function("cast")
10
11
12


class TypedSymbol(sp.Symbol):
Martin Bauer's avatar
Martin Bauer committed
13
14
    def __new__(cls, *args, **kwds):
        obj = TypedSymbol.__xnew_cached_(cls, *args, **kwds)
15
16
        return obj

17
    def __new_stage2__(cls, name, dtype):
18
        obj = super(TypedSymbol, cls).__xnew__(cls, name)
19
20
21
22
23
        try:
            obj._dtype = createType(dtype)
        except TypeError:
            # on error keep the string
            obj._dtype = dtype
24
25
26
27
28
29
30
31
32
33
34
        return obj

    __xnew__ = staticmethod(__new_stage2__)
    __xnew_cached_ = staticmethod(cacheit(__new_stage2__))

    @property
    def dtype(self):
        return self._dtype

    def _hashable_content(self):
        superClassContents = list(super(TypedSymbol, self)._hashable_content())
35
        return tuple(superClassContents + [hash(str(self._dtype))])
36
37

    def __getnewargs__(self):
38
39
40
        return self.name, self.dtype


41
def createType(specification):
Jan Hoenig's avatar
Jan Hoenig committed
42
43
44
45
46
    """
    Create a subclass of Type according to a string or an object of subclass Type
    :param specification: Type object, or a string
    :return: Type object, or a new Type object parsed from the string
    """
47
48
49
50
51
52
    if isinstance(specification, Type):
        return specification
    elif isinstance(specification, str):
        return createTypeFromString(specification)
    else:
        npDataType = np.dtype(specification)
53
54
55
56
        if npDataType.fields is None:
            return BasicType(npDataType, const=False)
        else:
            return StructType(npDataType, const=False)
57
58


59
@memorycache(maxsize=64)
60
def createTypeFromString(specification):
Jan Hoenig's avatar
Jan Hoenig committed
61
62
63
64
65
    """
    Creates a new Type object from a c-like string specification
    :param specification: Specification string
    :return: Type object
    """
66
67
68
69
70
71
72
    specification = specification.lower().split()
    parts = []
    current = []
    for s in specification:
        if s == '*':
            parts.append(current)
            current = [s]
73
        else:
74
75
76
            current.append(s)
    if len(current) > 0:
        parts.append(current)
Jan Hoenig's avatar
Jan Hoenig committed
77
        # Parse native part
78
79
80
81
82
83
    basePart = parts.pop(0)
    const = False
    if 'const' in basePart:
        const = True
        basePart.remove('const')
    assert len(basePart) == 1
Jan Hoenig's avatar
Jan Hoenig committed
84
85
86
    if basePart[0][-1] == "*":
        basePart[0] = basePart[0][:-1]
        parts.append('*')
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
    baseType = BasicType(basePart[0], const)
    currentType = baseType
    # Parse pointer parts
    for part in parts:
        restrict = False
        const = False
        if 'restrict' in part:
            restrict = True
            part.remove('restrict')
        if 'const' in part:
            const = True
            part.remove("const")
        assert len(part) == 1 and part[0] == '*'
        currentType = PointerType(currentType, const, restrict)
    return currentType


def getBaseType(type):
    while type.baseType is not None:
        type = type.baseType
    return type


def toCtypes(dataType):
Jan Hoenig's avatar
Jan Hoenig committed
111
112
113
114
115
    """
    Transforms a given Type into ctypes
    :param dataType: Subclass of Type
    :return: ctypes type object
    """
116
117
    if isinstance(dataType, PointerType):
        return ctypes.POINTER(toCtypes(dataType.baseType))
118
119
    elif isinstance(dataType, StructType):
        return ctypes.POINTER(ctypes.c_uint8)
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
    else:
        return toCtypes.map[dataType.numpyDtype]

toCtypes.map = {
    np.dtype(np.int8): ctypes.c_int8,
    np.dtype(np.int16): ctypes.c_int16,
    np.dtype(np.int32): ctypes.c_int32,
    np.dtype(np.int64): ctypes.c_int64,

    np.dtype(np.uint8): ctypes.c_uint8,
    np.dtype(np.uint16): ctypes.c_uint16,
    np.dtype(np.uint32): ctypes.c_uint32,
    np.dtype(np.uint64): ctypes.c_uint64,

    np.dtype(np.float32): ctypes.c_float,
    np.dtype(np.float64): ctypes.c_double,
}


139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
def peelOffType(dtype, typeToPeelOff):
    while type(dtype) is typeToPeelOff:
        dtype = dtype.baseType
    return dtype


def collateTypes(types):
    """
    Takes a sequence of types and returns their "common type" e.g. (float, double, float) -> double
    Uses the collation rules from numpy.
    """

    # Pointer arithmetic case i.e. pointer + integer is allowed
    if any(type(t) is PointerType for t in types):
        pointerType = None
        for t in types:
            if type(t) is PointerType:
                if pointerType is not None:
                    raise ValueError("Cannot collate the combination of two pointer types")
                pointerType = t
            elif type(t) is BasicType:
                if not (t.is_int() or t.is_uint()):
                    raise ValueError("Invalid pointer arithmetic")
            else:
                raise ValueError("Invalid pointer arithmetic")
        return pointerType

    # peel of vector types, if at least one vector type occurred the result will also be the vector type
    vectorType = [t for t in types if type(t) is VectorType]
    if not allEqual(t.width for t in vectorType):
        raise ValueError("Collation failed because of vector types with different width")
    types = [peelOffType(t, VectorType) for t in types]

    # now we should have a list of basic types - struct types are not yet supported
    assert all(type(t) is BasicType for t in types)

    # use numpy collation -> create type from numpy type -> and, put vector type around if necessary
    resultNumpyType = np.result_type(*(t.numpyDtype for t in types))
    result = BasicType(resultNumpyType)
    if vectorType:
        result = VectorType(result, vectorType[0].width)
    return result


@memorycache(maxsize=2048)
184
def getTypeOfExpression(expr):
185
186
187
188
189
190
191
192
193
    from pystencils.astnodes import ResolvedFieldAccess
    expr = sp.sympify(expr)
    if isinstance(expr, sp.Integer):
        return createTypeFromString("int")
    elif isinstance(expr, sp.Rational) or isinstance(expr, sp.Float):
        return createTypeFromString("double")
    elif isinstance(expr, ResolvedFieldAccess):
        return expr.field.dtype
    elif isinstance(expr, TypedSymbol):
194
        return expr.dtype
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
    elif isinstance(expr, sp.Symbol):
        raise ValueError("All symbols inside this expression have to be typed!")
    elif hasattr(expr, 'func') and expr.func == castFunc:
        return expr.args[1]
    elif hasattr(expr, 'func') and expr.func == sp.Piecewise:
        branchResults = [a[0] for a in expr.args]
        return collateTypes(tuple(getTypeOfExpression(a) for a in branchResults))
    elif isinstance(expr, sp.Indexed):
        typedSymbol = expr.base.label
        return typedSymbol.dtype
    elif isinstance(expr, sp.Expr):
        types = tuple(getTypeOfExpression(a) for a in expr.args)
        return collateTypes(types)
    elif isinstance(expr, sp.boolalg.Boolean):
        return createTypeFromString("bool")

    raise NotImplementedError("Could not determine type for " + str(expr))
212
213


214
215
216
class Type(sp.Basic):
    def __new__(cls, *args, **kwargs):
        return sp.Basic.__new__(cls)
217

Jan Hoenig's avatar
Jan Hoenig committed
218
219
220
221
222
223
    def __lt__(self, other):
        # Needed for sorting the types inside an expression
        if isinstance(self, BasicType):
            if isinstance(other, BasicType):
                return self.numpyDtype < other.numpyDtype  # TODO const
            if isinstance(other, PointerType):
224
                return False
Jan Hoenig's avatar
Jan Hoenig committed
225
226
227
228
            if isinstance(other, StructType):
                raise NotImplementedError("Struct type comparison is not yet implemented")
        if isinstance(self, PointerType):
            if isinstance(other, BasicType):
229
                return True
Jan Hoenig's avatar
Jan Hoenig committed
230
231
232
233
234
235
            if isinstance(other, PointerType):
                return self.baseType < other.baseType  # TODO const, restrict
            if isinstance(other, StructType):
                raise NotImplementedError("Struct type comparison is not yet implemented")
        if isinstance(self, StructType):
            raise NotImplementedError("Struct type comparison is not yet implemented")
236
237
238
239
240


class BasicType(Type):
    @staticmethod
    def numpyNameToC(name):
Jan Hoenig's avatar
Jan Hoenig committed
241
242
243
244
        if name == 'float64':
            return 'double'
        elif name == 'float32':
            return 'float'
245
246
247
248
        elif name.startswith('int'):
            width = int(name[len("int"):])
            return "int%d_t" % (width,)
        elif name.startswith('uint'):
249
            width = int(name[len("uint"):])
250
251
252
253
254
255
256
257
            return "uint%d_t" % (width,)
        elif name == 'bool':
            return 'bool'
        else:
            raise NotImplemented("Can map numpy to C name for %s" % (name,))

    def __init__(self, dtype, const=False):
        self.const = const
258
259
260
261
        if isinstance(dtype, Type):
            self._dtype = dtype.numpyDtype
        else:
            self._dtype = np.dtype(dtype)
262
263
264
265
        assert self._dtype.fields is None, "Tried to initialize NativeType with a structured type"
        assert self._dtype.hasobject is False
        assert self._dtype.subdtype is None

266
267
268
    def __getnewargs__(self):
        return self.numpyDtype, self.const

269
270
271
    @property
    def baseType(self):
        return None
272

273
274
275
276
    @property
    def numpyDtype(self):
        return self._dtype

277
278
279
280
    @property
    def itemSize(self):
        return 1

281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
    def is_int(self):
        return self.numpyDtype in np.sctypes['int']

    def is_float(self):
        return self.numpyDtype in np.sctypes['float']

    def is_uint(self):
        return self.numpyDtype in np.sctypes['uint']

    def is_comlex(self):
        return self.numpyDtype in np.sctypes['complex']

    def is_other(self):
        return self.numpyDtype in np.sctypes['others']

296
297
298
299
    @property
    def baseName(self):
        return BasicType.numpyNameToC(str(self._dtype))

Jan Hoenig's avatar
Jan Hoenig committed
300
    def __str__(self):
301
302
303
304
        result = BasicType.numpyNameToC(str(self._dtype))
        if self.const:
            result += " const"
        return result
Jan Hoenig's avatar
Jan Hoenig committed
305
306

    def __eq__(self, other):
307
308
        if not isinstance(other, BasicType):
            return False
Jan Hoenig's avatar
Jan Hoenig committed
309
        else:
310
311
312
313
314
315
            return (self.numpyDtype, self.const) == (other.numpyDtype, other.const)

    def __hash__(self):
        return hash(str(self))


316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
class VectorType(Type):
    instructionSet = None

    def __init__(self, baseType, width=4):
        self._baseType = baseType
        self.width = width

    @property
    def baseType(self):
        return self._baseType

    @property
    def itemSize(self):
        return self.width * self.baseType.itemSize

    def __eq__(self, other):
        if not isinstance(other, VectorType):
            return False
        else:
            return (self.baseType, self.width) == (other.baseType, other.width)

    def __str__(self):
        if self.instructionSet is None:
            return "%s[%d]" % (self.baseType, self.width)
        else:
            if self.baseType == createTypeFromString("int64"):
                return self.instructionSet['int']
            elif self.baseType == createTypeFromString("double"):
                return self.instructionSet['double']
            elif self.baseType == createTypeFromString("float"):
                return self.instructionSet['float']
            else:
                raise NotImplementedError()

    def __hash__(self):
        return hash(str(self))


354
355
356
357
358
359
class PointerType(Type):
    def __init__(self, baseType, const=False, restrict=True):
        self._baseType = baseType
        self.const = const
        self.restrict = restrict

360
361
362
    def __getnewargs__(self):
        return self.baseType, self.const, self.restrict

363
364
365
366
367
368
369
370
    @property
    def alias(self):
        return not self.restrict

    @property
    def baseType(self):
        return self._baseType

371
372
373
374
    @property
    def itemSize(self):
        return self.baseType.itemSize

375
376
    def __eq__(self, other):
        if not isinstance(other, PointerType):
Jan Hoenig's avatar
Jan Hoenig committed
377
            return False
378
379
380
        else:
            return (self.baseType, self.const, self.restrict) == (other.baseType, other.const, other.restrict)

Jan Hoenig's avatar
Jan Hoenig committed
381
    def __str__(self):
Jan Hoenig's avatar
Jan Hoenig committed
382
        return "%s *%s%s" % (self.baseType, " RESTRICT " if self.restrict else "", " const " if self.const else "")
383
384
385
386

    def __hash__(self):
        return hash(str(self))

Jan Hoenig's avatar
Jan Hoenig committed
387

388
class StructType(object):
389
390
    def __init__(self, numpyType, const=False):
        self.const = const
391
        self._dtype = np.dtype(numpyType)
Martin Bauer's avatar
Martin Bauer committed
392

393
394
395
    def __getnewargs__(self):
        return self.numpyDtype, self.const

396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
    @property
    def baseType(self):
        return None

    @property
    def numpyDtype(self):
        return self._dtype

    @property
    def itemSize(self):
        return self.numpyDtype.itemsize

    def getElementOffset(self, elementName):
        return self.numpyDtype.fields[elementName][1]

    def getElementType(self, elementName):
        npElementType = self.numpyDtype.fields[elementName][0]
        return BasicType(npElementType, self.const)

415
416
417
    def hasElement(self, elementName):
        return elementName in self.numpyDtype.fields

418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
    def __eq__(self, other):
        if not isinstance(other, StructType):
            return False
        else:
            return (self.numpyDtype, self.const) == (other.numpyDtype, other.const)

    def __str__(self):
        # structs are handled byte-wise
        result = "uint8_t"
        if self.const:
            result += " const"
        return result

    def __hash__(self):
        return hash((self.numpyDtype, self.const))
433

Jan Hoenig's avatar
Jan Hoenig committed
434
    # TODO this should not work at all!!!
Jan Hoenig's avatar
Jan Hoenig committed
435
436
437
438
439
440
441
    def __gt__(self, other):
        if self.ptr and not other.ptr:
            return True
        if self.dtype > other.dtype:
            return True


Jan Hoenig's avatar
Jan Hoenig committed
442
def get_type_from_sympy(node):
Jan Hoenig's avatar
Jan Hoenig committed
443
444
445
446
447
    """
    Creates a Type object from a Sympy object
    :param node: Sympy object
    :return: Type object
    """
Jan Hoenig's avatar
Jan Hoenig committed
448
449
450
451
452
453
454
455
456
457
    # Rational, NumberSymbol?
    # Zero, One, NegativeOne )= Integer
    # Half )= Rational
    # NAN, Infinity, Negative Inifinity,
    # Exp1, Imaginary Unit, Pi, EulerGamma, Catalan, Golden Ratio
    # Pow, Mul, Add, Mod, Relational
    if not isinstance(node, sp.Number):
        raise TypeError(node, 'is not a sp.Number')

    if isinstance(node, sp.Float) or isinstance(node, sp.RealNumber):
Jan Hoenig's avatar
Jan Hoenig committed
458
        return createType('double'), float(node)
Jan Hoenig's avatar
Jan Hoenig committed
459
    elif isinstance(node, sp.Integer):
Jan Hoenig's avatar
Jan Hoenig committed
460
        return createType('int'), int(node)
Jan Hoenig's avatar
Jan Hoenig committed
461
462
463
    elif isinstance(node, sp.Rational):
        raise NotImplementedError('Rationals are not supported yet')
    else:
Jan Hoenig's avatar
Jan Hoenig committed
464
        raise TypeError(node, ' is not a supported type (yet)!')