-
Notifications
You must be signed in to change notification settings - Fork 55
/
numpyext.py
2700 lines (2230 loc) · 85.1 KB
/
numpyext.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python
# -*- coding: utf-8 -*-
#------------------------------------------------------------------------------------------#
# This file is part of Pyccel which is released under MIT License. See the LICENSE file or #
# go to https://github.com/pyccel/pyccel/blob/master/LICENSE for full license details. #
#------------------------------------------------------------------------------------------#
""" Module containing objects from the numpy module understood by pyccel
"""
import numpy
from pyccel.errors.errors import Errors
from pyccel.errors.messages import WRONG_LINSPACE_ENDPOINT, NON_LITERAL_KEEP_DIMS, NON_LITERAL_AXIS
from pyccel.utilities.stage import PyccelStage
from .basic import TypedAstNode
from .builtins import (PythonInt, PythonBool, PythonFloat, PythonTuple,
PythonComplex, PythonReal, PythonImag, PythonList,
PythonType, PythonConjugate, DtypePrecisionToCastFunction)
from .core import Module, Import, PyccelFunctionDef, FunctionCall
from .datatypes import PythonNativeBool, PythonNativeInt, PythonNativeFloat
from .datatypes import PrimitiveBooleanType, PrimitiveIntegerType, PrimitiveFloatingPointType, PrimitiveComplexType
from .datatypes import HomogeneousTupleType, FixedSizeNumericType, GenericType, HomogeneousContainerType
from .datatypes import InhomogeneousTupleType, ContainerType
from .internals import PyccelInternalFunction, Slice
from .internals import PyccelArraySize, PyccelArrayShapeElement
from .literals import LiteralInteger, LiteralString, convert_to_literal
from .literals import LiteralTrue, LiteralFalse
from .literals import Nil
from .mathext import MathCeil
from .numpytypes import NumpyNumericType, NumpyInt8Type, NumpyInt16Type, NumpyInt32Type, NumpyInt64Type
from .numpytypes import NumpyFloat32Type, NumpyFloat64Type, NumpyFloat128Type, NumpyNDArrayType
from .numpytypes import NumpyComplex64Type, NumpyComplex128Type, NumpyComplex256Type, numpy_precision_map
from .operators import broadcast, PyccelMinus, PyccelDiv, PyccelMul, PyccelAdd
from .type_annotations import typenames_to_dtypes as dtype_registry
from .variable import Variable, Constant, IndexedElement
errors = Errors()
pyccel_stage = PyccelStage()
__all__ = (
'process_shape',
# ---
'NumpyAutoFill',
'NumpyUfuncBase',
'NumpyUfuncBinary',
'NumpyUfuncUnary',
# ---
'NumpyAbs',
'NumpyFloor',
'NumpySign',
# ---
'NumpySqrt',
'NumpySin',
'NumpyCos',
'NumpyExp',
'NumpyLog',
'NumpyTan',
'NumpyArcsin',
'NumpyArccos',
'NumpyArctan',
'NumpyArctan2',
'NumpySinh',
'NumpyCosh',
'NumpyTanh',
'NumpyArcsinh',
'NumpyArccosh',
'NumpyArctanh',
# ---
'NumpyAmax',
'NumpyAmin',
'NumpyArange',
'NumpyArray',
'NumpySize',
'NumpyBool',
'NumpyCountNonZero',
'NumpyComplex',
'NumpyComplex64',
'NumpyComplex128',
'NumpyConjugate',
'NumpyEmpty',
'NumpyEmptyLike',
'NumpyFabs',
'NumpyFloat',
'NumpyFloat32',
'NumpyFloat64',
'NumpyFull',
'NumpyFullLike',
'NumpyImag',
'NumpyHypot',
'NumpyInt',
'NumpyInt8',
'NumpyInt16',
'NumpyInt32',
'NumpyInt64',
'NumpyLinspace',
'NumpyMatmul',
'NumpyNewArray',
'NumpyMod',
'NumpyNonZero',
'NumpyNonZeroElement',
'NumpyNorm',
'NumpySum',
'NumpyOnes',
'NumpyOnesLike',
'NumpyProduct',
'NumpyRand',
'NumpyRandint',
'NumpyReal',
'NumpyResultType',
'NumpyTranspose',
'NumpyWhere',
'NumpyZeros',
'NumpyZerosLike',
'NumpyShape',
'NumpyIsInf',
'NumpyIsFinite',
'NumpyIsNan',
)
dtype_registry.update({
'int8' : NumpyInt8Type(),
'int16' : NumpyInt16Type(),
'int32' : NumpyInt32Type(),
'int64' : NumpyInt64Type(),
'i1' : NumpyInt8Type(),
'i2' : NumpyInt16Type(),
'i4' : NumpyInt32Type(),
'i8' : NumpyInt64Type(),
'float32' : NumpyFloat32Type(),
'float64' : NumpyFloat64Type(),
'float128' : NumpyFloat128Type(),
'f4' : NumpyFloat32Type(),
'f8' : NumpyFloat64Type(),
'complex64' : NumpyComplex64Type(),
'complex128' : NumpyComplex128Type(),
'complex256' : NumpyComplex256Type(),
'c8' : NumpyComplex64Type(),
'c16' : NumpyComplex128Type(),
})
#=======================================================================================
def process_shape(is_scalar, shape):
""" Modify the input shape to the expected type
Parameters
----------
is_scalar : bool
True if the result is a scalar, False if it is an array
shape : TypedAstNode/iterable/int
input shape
"""
if is_scalar:
return None
elif shape is None:
return ()
elif not hasattr(shape,'__iter__'):
shape = [shape]
new_shape = []
for s in shape:
if isinstance(s,(LiteralInteger, Variable, Slice, TypedAstNode, FunctionCall)):
new_shape.append(s)
elif isinstance(s, int):
new_shape.append(LiteralInteger(s))
else:
raise TypeError('shape elements cannot be '+str(type(s))+'. They must be one of the following types: LiteralInteger, Variable, Slice, TypedAstNode, int, FunctionCall')
return tuple(new_shape)
#=======================================================================================
class NumpyFloat(PythonFloat):
"""
Represents a call to `numpy.float()` function.
Represents a call to the NumPy cast function `float`.
Parameters
----------
arg : TypedAstNode
The argument passed to the function.
"""
__slots__ = ('_rank','_shape','_order','_class_type')
_static_type = NumpyFloat64Type()
name = 'float'
def __init__(self, arg):
self._shape = arg.shape
self._rank = arg.rank
self._order = arg.order
self._class_type = NumpyNDArrayType(self.static_type()) if self._rank else self.static_type()
super().__init__(arg)
@property
def is_elemental(self):
"""
Indicates whether the function can be applied elementwise.
Indicates whether the function should be
called elementwise for an array argument
"""
return True
class NumpyFloat32(NumpyFloat):
"""
Represents a call to numpy.float32() function.
Represents a call to numpy.float32() function.
Parameters
----------
arg : TypedAstNode
The argument passed to the function.
"""
__slots__ = ()
_static_type = NumpyFloat32Type()
name = 'float32'
class NumpyFloat64(NumpyFloat):
"""
Represents a call to numpy.float64() function.
Represents a call to numpy.float64() function.
Parameters
----------
arg : TypedAstNode
The argument passed to the function.
"""
__slots__ = ()
_static_type = NumpyFloat64Type()
name = 'float64'
#=======================================================================================
class NumpyBool(PythonBool):
"""
Represents a call to `numpy.bool()` function.
Represents a call to the NumPy cast function `bool`.
Parameters
----------
arg : TypedAstNode
The argument passed to the function.
"""
__slots__ = ('_shape','_rank','_order','_class_type')
name = 'bool'
def __init__(self, arg):
self._shape = arg.shape
self._rank = arg.rank
self._order = arg.order
self._class_type = NumpyNDArrayType(self.static_type()) if self._rank else self.static_type()
super().__init__(arg)
@property
def is_elemental(self):
"""
Indicates whether the function can be applied elementwise.
Indicates whether the function should be
called elementwise for an array argument
"""
return True
#=======================================================================================
# TODO [YG, 13.03.2020]: handle case where base != 10
class NumpyInt(PythonInt):
"""
Represents a call to `numpy.int()` function.
Represents a call to the NumPy cast function `int`.
Parameters
----------
arg : TypedAstNode
The argument passed to the function.
"""
__slots__ = ('_shape','_rank','_order','_class_type')
_static_type = numpy_precision_map[(PrimitiveIntegerType(), PythonInt._static_type.precision)]
name = 'int'
def __init__(self, arg=None, base=10):
self._shape = arg.shape
self._rank = arg.rank
self._order = arg.order
self._class_type = NumpyNDArrayType(self.static_type()) if self._rank else self.static_type()
super().__init__(arg)
@property
def is_elemental(self):
"""
Indicates whether the function can be applied elementwise.
Indicates whether the function should be
called elementwise for an array argument
"""
return True
class NumpyInt8(NumpyInt):
"""
Represents a call to numpy.int8() function.
Represents a call to numpy.int8() function.
Parameters
----------
arg : TypedAstNode
The argument passed to the function.
"""
__slots__ = ()
_static_type = NumpyInt8Type()
name = 'int8'
class NumpyInt16(NumpyInt):
"""
Represents a call to numpy.int16() function.
Represents a call to numpy.int16() function.
Parameters
----------
arg : TypedAstNode
The argument passed to the function.
"""
__slots__ = ()
_static_type = NumpyInt16Type()
name = 'int16'
class NumpyInt32(NumpyInt):
"""
Represents a call to numpy.int32() function.
Represents a call to numpy.int32() function.
Parameters
----------
arg : TypedAstNode
The argument passed to the function.
"""
__slots__ = ()
_static_type = NumpyInt32Type()
name = 'int32'
class NumpyInt64(NumpyInt):
"""
Represents a call to numpy.int64() function.
Represents a call to numpy.int64() function.
Parameters
----------
arg : TypedAstNode
The argument passed to the function.
"""
__slots__ = ()
_static_type = NumpyInt64Type()
name = 'int64'
#==============================================================================
class NumpyReal(PythonReal):
"""
Represents a call to numpy.real for code generation.
Represents a call to the NumPy function real.
> a = 1+2j
> np.real(a)
1.0
Parameters
----------
arg : TypedAstNode
The argument passed to the function.
"""
__slots__ = ('_rank','_shape','_order','_class_type')
name = 'real'
def __new__(cls, arg):
if isinstance(arg.dtype, PythonNativeBool):
if arg.rank:
return NumpyInt(arg)
else:
return PythonInt(arg)
else:
return super().__new__(cls, arg)
def __init__(self, arg):
super().__init__(arg)
self._order = arg.order
self._rank = arg.rank
self._shape = process_shape(self._rank == 0, self.internal_var.shape)
self._class_type = arg.class_type.switch_basic_type(arg.dtype.element_type)
@property
def is_elemental(self):
""" Indicates whether the function should be
called elementwise for an array argument
"""
return True
#==============================================================================
class NumpyImag(PythonImag):
"""
Represents a call to numpy.imag for code generation.
Represents a call to the NumPy function imag.
> a = 1+2j
> np.imag(a)
2.0
Parameters
----------
arg : TypedAstNode
The argument passed to the function.
"""
__slots__ = ('_rank','_shape','_order','_class_type')
name = 'imag'
def __new__(cls, arg):
if not isinstance(arg.dtype.primitive_type, PrimitiveComplexType):
dtype = PythonNativeInt() if isinstance(arg.dtype, PythonNativeBool) else arg.dtype
if arg.rank == 0:
return convert_to_literal(0, dtype)
dtype = DtypePrecisionToCastFunction[dtype].static_type()
return NumpyZeros(arg.shape, dtype=dtype)
return super().__new__(cls, arg)
def __init__(self, arg):
super().__init__(arg)
self._order = arg.order
self._rank = arg.rank
self._shape = process_shape(self._rank == 0, self.internal_var.shape)
self._class_type = arg.class_type.switch_basic_type(arg.dtype.element_type)
@property
def is_elemental(self):
""" Indicates whether the function should be
called elementwise for an array argument
"""
return True
#=======================================================================================
class NumpyComplex(PythonComplex):
"""
Represents a call to `numpy.complex()` function.
Represents a call to the NumPy cast function `complex`.
Parameters
----------
arg0 : TypedAstNode
The first argument passed to the function. Either the array/scalar being cast
or the real part of the complex.
arg1 : TypedAstNode, optional
The second argument passed to the function. The imaginary part of the complex.
"""
_real_cast = NumpyReal
_imag_cast = NumpyImag
__slots__ = ('_rank','_shape','_order','_class_type')
_static_type = NumpyComplex128Type()
name = 'complex'
def __init__(self, arg0, arg1 = None):
if arg1 is not None:
raise NotImplementedError("Use builtin complex function not deprecated np.complex")
self._shape = arg0.shape
self._rank = arg0.rank
self._order = arg0.order
self._class_type = NumpyNDArrayType(self.static_type()) if self._rank else self.static_type()
super().__init__(arg0)
@property
def is_elemental(self):
"""
Indicates whether the function can be applied elementwise.
Indicates whether the function should be
called elementwise for an array argument
"""
return True
class NumpyComplex64(NumpyComplex):
"""
Represents a call to numpy.complex64() function.
Represents a call to numpy.complex64() function.
Parameters
----------
arg0 : TypedAstNode
The argument passed to the function.
arg1 : TypedAstNode
Unused inherited argument.
"""
__slots__ = ()
_static_type = NumpyComplex64Type()
name = 'complex64'
class NumpyComplex128(NumpyComplex):
"""
Represents a call to numpy.complex128() function.
Represents a call to numpy.complex128() function.
Parameters
----------
arg0 : TypedAstNode
The argument passed to the function.
arg1 : TypedAstNode
Unused inherited argument.
"""
__slots__ = ()
_static_type = NumpyComplex128Type()
name = 'complex128'
#=======================================================================================
class NumpyResultType(PyccelInternalFunction):
"""
Class representing a call to the `numpy.result_type` function.
A class representing a call to the NumPy function `result_type` which returns
the datatype of an expression. This function can be used to access the `dtype`
property of a NumPy array.
Parameters
----------
*arrays_and_dtypes : TypedAstNode
Any arrays and dtypes passed to the function (currently only accepts one array
and no dtypes).
"""
__slots__ = ('_class_type',)
_rank = 0
_shape = None
_order = None
name = 'result_type'
def __init__(self, *arrays_and_dtypes):
types = [a.cls_name.static_type() if isinstance(a, PyccelFunctionDef) else a.class_type for a in arrays_and_dtypes]
self._class_type = sum(types, start=GenericType())
if isinstance(self._class_type, ContainerType):
self._class_type = self._class_type.element_type
super().__init__(*arrays_and_dtypes)
#==============================================================================
def process_dtype(dtype):
"""
Analyse a dtype passed to a NumPy array creation function.
This function takes a dtype passed to a NumPy array creation function,
processes it in different ways depending on its type, and finally extracts
the corresponding type and precision from the `dtype_registry` dictionary.
This function could be useful when working with numpy creation function
having a dtype argument, like numpy.array, numpy.arrange, numpy.linspace...
Parameters
----------
dtype : PythonType, PyccelFunctionDef, LiteralString, str
The actual dtype passed to the NumPy function.
Returns
-------
Datatype
The Datatype corresponding to the passed dtype.
int
The precision corresponding to the passed dtype.
Raises
------
TypeError: In the case of unrecognized argument type.
TypeError: In the case of passed string argument not recognized as valid dtype.
"""
if isinstance(dtype, PythonType):
if dtype.arg.rank > 0:
errors.report("Python's type function doesn't return enough information about this object for pyccel to fully define a type",
symbol=dtype, severity="fatal")
else:
dtype = dtype.arg.class_type
elif isinstance(dtype, NumpyResultType):
dtype = dtype.dtype
elif isinstance(dtype, PyccelFunctionDef):
dtype = dtype.cls_name.static_type()
elif isinstance(dtype, (LiteralString, str)):
try:
dtype = dtype_registry[str(dtype)]
except KeyError:
raise TypeError(f'Unknown type of {dtype}.')
if isinstance(dtype, (NumpyNumericType, PythonNativeBool, GenericType)):
return dtype
if isinstance(dtype, FixedSizeNumericType):
return numpy_precision_map[(dtype.primitive_type, dtype.precision)]
else:
raise TypeError(f'Unknown type of {dtype}.')
#==============================================================================
class NumpyNewArray(PyccelInternalFunction):
"""
Superclass for nodes representing NumPy array allocation functions.
Class from which all nodes representing a NumPy function which implies a call
to `Allocate` should inherit.
Parameters
----------
*args : tuple of TypedAstNode
The arguments of the superclass PyccelInternalFunction.
dtype : PyccelType
The datatype of the new array.
init_dtype : PythonType, PyccelFunctionDef, LiteralString, str
The actual dtype passed to the NumPy function.
"""
__slots__ = ('_init_dtype','_class_type')
def __init__(self, *args, dtype, init_dtype = None):
self._init_dtype = init_dtype
self._class_type = NumpyNDArrayType(dtype) # pylint: disable=no-member
super().__init__(*args)
@property
def init_dtype(self):
"""
The dtype provided to the function when it was initialised in Python.
The dtype provided to the function when it was initialised in Python.
If no dtype was provided then this should equal `None`.
"""
return self._init_dtype
#--------------------------------------------------------------------------
@staticmethod
def _process_order(rank, order):
"""
Treat the order to get an order in the format expected by Pyccel.
Process the order passed to the array creation function to get an order
in the format expected by Pyccel. The final format should be a string
containing either 'C' or 'F'.
Parameters
----------
rank : int
The rank of the array being created.
order : str | LiteralString
The order of the array as specified by the user or the subclass.
Returns
-------
str | None
The order in the format expected by Pyccel.
"""
if rank < 2:
return None
order = str(order).strip('\'"')
assert order in ('C', 'F')
return order
#==============================================================================
class NumpyArray(NumpyNewArray):
"""
Represents a call to `numpy.array` for code generation.
A class representing a call to the NumPy `array` function.
Parameters
----------
arg : list, tuple, PythonList
The data from which the array is initialised.
dtype : PythonType, PyccelFunctionDef, LiteralString, str
The data type passed to the NumPy function.
order : str
The ordering of the array (C/Fortran).
ndmin : LiteralInteger, int, optional
The minimum number of dimensions that the resulting array should
have.
"""
__slots__ = ('_arg','_shape','_rank','_order')
_attribute_nodes = ('_arg',)
name = 'array'
def __init__(self, arg, dtype=None, order='K', ndmin=None):
if not isinstance(arg, (PythonTuple, PythonList, Variable, IndexedElement)):
raise TypeError(f'Unknown type of {type(arg)}')
is_homogeneous_tuple = isinstance(arg.class_type, HomogeneousTupleType)
# Inhomogeneous tuples can contain homogeneous data if it is inhomogeneous due to pointers
if isinstance(arg.class_type, InhomogeneousTupleType):
if not isinstance(arg, PythonTuple):
arg = PythonTuple(*arg)
is_homogeneous_tuple = arg.is_homogeneous
# TODO: treat inhomogenous lists and tuples when they have mixed ordering
if not (is_homogeneous_tuple or isinstance(arg.class_type, HomogeneousContainerType)):
raise TypeError('we only accept homogeneous arguments')
if not isinstance(order, (LiteralString, str)):
raise TypeError("The order must be specified explicitly with a string.")
elif isinstance(order, LiteralString):
order = order.python_value
if ndmin is not None:
if not isinstance(ndmin, (LiteralInteger, int)):
raise TypeError("The minimum number of dimensions must be specified explicitly with an integer.")
elif isinstance(ndmin, LiteralInteger):
ndmin = ndmin.python_value
init_dtype = dtype
if isinstance(arg.class_type, InhomogeneousTupleType):
# If pseudo-inhomogeneous due to pointers, extract underlying dtype
if dtype is None:
dtype = arg[0].class_type.datatype
dtype = process_dtype(dtype)
shape = (LiteralInteger(len(arg)), *process_shape(False, arg[0].shape))
else:
# Verify dtype and get precision
if dtype is None:
dtype = arg.dtype
dtype = process_dtype(dtype)
shape = process_shape(False, arg.shape)
rank = len(shape)
if ndmin and ndmin>rank:
shape = (LiteralInteger(1),)*(ndmin-rank) + shape
rank = ndmin
if rank < 2:
order = None
else:
# ... Determine ordering
order = str(order).strip("\'")
assert order in ('K', 'A', 'C', 'F')
if order in ('K', 'A'):
order = arg.order or 'C'
# ...
self._arg = arg
self._shape = shape
self._rank = rank
self._order = order
super().__init__(dtype = dtype, init_dtype = init_dtype)
def __str__(self):
return str(self.arg)
@property
def arg(self):
return self._arg
#==============================================================================
class NumpyArange(NumpyNewArray):
"""
Represents a call to numpy.arange for code generation.
A class representing a call to the NumPy `arange` function.
Parameters
----------
start : Numeric
Start of interval, default value 0.
stop : Numeric
End of interval.
step : Numeric
Spacing between values, default value 1.
dtype : Datatype
The type of the output array, if dtype is not given,
infer the data type from the other input arguments.
"""
__slots__ = ('_start','_step','_stop','_shape')
_attribute_nodes = ('_start','_step','_stop')
_rank = 1
_order = None
name = 'arange'
def __init__(self, start, stop = None, step = None, dtype = None):
if stop is None:
self._start = LiteralInteger(0)
self._stop = start
else:
self._start = start
self._stop = stop
self._step = step if step is not None else LiteralInteger(1)
init_dtype = dtype
if dtype is None:
type_info = NumpyResultType(*self.arg)
dtype = type_info.dtype
self._shape = (MathCeil(PyccelDiv(PyccelMinus(self._stop, self._start), self._step)))
self._shape = process_shape(False, self._shape)
super().__init__(dtype = process_dtype(dtype), init_dtype = init_dtype)
@property
def arg(self):
return (self._start, self._stop, self._step)
@property
def start(self):
return self._start
@property
def stop(self):
return self._stop
@property
def step(self):
return self._step
def __getitem__(self, index):
step = PyccelMul(index, self.step, simplify=True)
return PyccelAdd(self.start, step, simplify=True)
#==============================================================================
class NumpySum(PyccelInternalFunction):
"""
Represents a call to numpy.sum for code generation.
Represents a call to numpy.sum for code generation.
Parameters
----------
arg : list , tuple , PythonTuple, PythonList, Variable
The argument passed to the sum function.
"""
__slots__ = ('_class_type',)
name = 'sum'
_rank = 0
_shape = None
_order = None
def __init__(self, arg):
if not isinstance(arg, TypedAstNode):
raise TypeError(f'Unknown type of {type(arg)}.')
super().__init__(arg)
lowest_possible_type = process_dtype(PythonNativeInt())
if isinstance(arg.dtype.primitive_type, (PrimitiveBooleanType, PrimitiveIntegerType)) and \
arg.dtype.precision <= lowest_possible_type.precision:
self._class_type = lowest_possible_type
else:
self._class_type = process_dtype(arg.dtype)
@property
def arg(self):
return self._args[0]
#==============================================================================
class NumpyProduct(PyccelInternalFunction):
"""
Represents a call to numpy.prod for code generation.
Represents a call to numpy.prod for code generation.
Parameters
----------
arg : list , tuple , PythonTuple, PythonList, Variable
The argument passed to the prod function.
"""
__slots__ = ('_arg','_class_type')
name = 'product'
_rank = 0
_shape = None
_order = None
def __init__(self, arg):
if not isinstance(arg, TypedAstNode):
raise TypeError(f'Unknown type of {type(arg)}.')
super().__init__(arg)
self._arg = PythonList(arg) if arg.rank == 0 else self._args[0]
lowest_possible_type = process_dtype(PythonNativeInt())
if isinstance(arg.dtype.primitive_type, (PrimitiveBooleanType, PrimitiveIntegerType)) and \
arg.dtype.precision <= lowest_possible_type.precision:
self._class_type = lowest_possible_type
else:
self._class_type = process_dtype(arg.dtype)
default_cast = DtypePrecisionToCastFunction[self._class_type]
self._arg = default_cast(self._arg) if arg.dtype != self._class_type else self._arg
@property
def arg(self):
return self._arg
#==============================================================================
class NumpyMatmul(PyccelInternalFunction):
"""
Represents a call to numpy.matmul for code generation.
Represents a call to NumPy's `matmul` function for code generation.
Parameters
----------
a : TypedAstNode
The first argument of the matrix multiplication.
b : TypedAstNode
The second argument of the matrix multiplication.
"""
__slots__ = ('_shape','_rank','_order','_class_type')
name = 'matmul'
def __init__(self, a ,b):
super().__init__(a, b)
if pyccel_stage == 'syntactic':
return
if not isinstance(a, TypedAstNode):
raise TypeError(f'Unknown type of {type(a)}.')
if not isinstance(b, TypedAstNode):
raise TypeError(f'Unknown type of {type(a)}.')
args = (a, b)
type_info = NumpyResultType(*args)
dtype = process_dtype(type_info.dtype)
if not (a.shape is None or b.shape is None):
m = 1 if a.rank < 2 else a.shape[0]
n = 1 if b.rank < 2 else b.shape[1]
self._shape = (m, n)
if a.rank == 1 and b.rank == 1:
self._rank = 0
self._shape = None
elif a.rank == 1 or b.rank == 1:
self._rank = 1
self._shape = (b.shape[1] if a.rank == 1 else a.shape[0],)
else:
self._rank = 2
if a.order == b.order:
self._order = a.order
else:
self._order = None if self._rank < 2 else 'C'
self._class_type = NumpyNDArrayType(dtype) if self.rank else dtype
@property
def a(self):
return self._args[0]
@property
def b(self):
return self._args[1]
#==============================================================================
class NumpyShape(PyccelInternalFunction):
"""
Represents a call to numpy.shape for code generation.
This wrapper class represents calls to the function `numpy.shape` in the
user code, or equivalently to the `shape` property of a `numpy.ndarray`.
Objects of this class are never present in the Pyccel AST, because the
class constructor always returns a PythonTuple with the required shape.
Parameters
----------
arg : TypedAstNode
The Numpy array whose shape is being investigated.
Returns
-------
PythonTuple
The shape of the Numpy array, i.e. its size along each dimension.
"""
__slots__ = ()
name = 'shape'
def __new__(cls, arg):
if isinstance(arg.shape, PythonTuple):
return arg.shape
else: