Coverage for mlprodict/onnxrt/ops_cpu/op_constant_of_shape.py: 96%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

26 statements  

1# -*- encoding: utf-8 -*- 

2# pylint: disable=E0203,E1101,C0111 

3""" 

4@file 

5@brief Runtime operator. 

6""" 

7import numpy 

8from ._op import OpRun 

9from ..shape_object import ShapeObject 

10 

11 

12class ConstantOfShape(OpRun): 

13 

14 atts = {'value': numpy.array([0], dtype=numpy.float32)} 

15 

16 def __init__(self, onnx_node, desc=None, **options): 

17 OpRun.__init__(self, onnx_node, desc=desc, 

18 expected_attributes=ConstantOfShape.atts, 

19 **options) 

20 self.cst = (self.value[0] 

21 if isinstance(self.value, numpy.ndarray) 

22 else self.value) 

23 if not isinstance(self.cst, (float, numpy.float32, numpy.float64, 

24 numpy.int64, numpy.int32, numpy.bool_, 

25 numpy.float16)): 

26 raise TypeError( # pragma: no cover 

27 "cst must be a real not {}".format(type(self.cst))) 

28 

29 def _run(self, data): # pylint: disable=W0221 

30 try: 

31 res = numpy.full(tuple(data), self.cst) 

32 except TypeError as e: # pragma: no cover 

33 raise RuntimeError( 

34 "Unable to create a constant of shape %r with value %r " 

35 "(raw value=%r)." % (data, self.cst, self.value)) from e 

36 return (res, ) 

37 

38 def _infer_shapes(self, data): # pylint: disable=W0221 

39 # pref = str(hex(id(self))[2:]) 

40 return (ShapeObject(None, self.cst.dtype), ) 

41 

42 def _infer_types(self, data): # pylint: disable=W0221 

43 # pref = str(hex(id(self))[2:]) 

44 if isinstance(self.cst, numpy.ndarray): 

45 return (self.cst.dtype, ) 

46 return (type(self.cst), ) 

47 

48 def _infer_sizes(self, *args, **kwargs): 

49 res = self.run(*args, **kwargs) 

50 return (dict(temp=0), ) + res 

51 

52 def to_python(self, inputs): 

53 lines = ['cst = value[0] if isinstance(value, numpy.ndarray) else value', 

54 'return numpy.full(tuple(%s), cst)' % inputs[0]] 

55 return ("import numpy", "\n".join(lines))