-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtensor.py
88 lines (68 loc) · 2.94 KB
/
tensor.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
import abstractTensor
import pureTensor
import composite
class tensor(composite.composite,abstractTensor.abstractTensor):
"""
File: tensor.py
Author: Chris Campbell
Email: c (dot) j (dot) campbell (at) ed (dot) ac (dot) uk
Github: https://github.com/campbellC
Description: A composite class of pureTensors
"""
##############################################################################
###### CONSTRUCTORS
##############################################################################
def __init__(self,polynomials=()):
if polynomials == 0:
polynomials = ()
pureTensors = ()
if isinstance(polynomials, pureTensor.pureTensor):
pureTensors = (polynomials,)
if len(polynomials) >= 1:
if isinstance(polynomials[0], pureTensor.pureTensor): # If this is a list of pureTensors, just conver to tuple and carry on
pureTensors = tuple(polynomials)
else: #Otherwise, we assume it is a list of polynomials and try and seperate into a list of pure tensors
def pureTensorHelper(polynomials):
assert len(polynomials) > 0
for i in polynomials:
if i.isZero():
return tensor()
pureTensors = []
if len(polynomials) == 1:
for mono in polynomials[0]:
pureTensors.append(pureTensor.pureTensor( (mono,) ))
else:
tempTensors = pureTensorHelper(polynomials[1:])
for mono in polynomials[0]:
for pT in tempTensors:
pureTensors.append(pureTensor.pureTensor( (mono,) ).tensorProduct(pT))
return tuple(pureTensors)
pureTensors = pureTensorHelper(polynomials)
assert isinstance(pureTensors,tuple)
composite.composite.__init__(self,pureTensors)
self.pureTensors = self.components
##############################################################################
###### MATHEMATICAL METHODS
##############################################################################
def __mul__(self,other):
if len(self) == 0:
return self
else:
return tensor( map(lambda x: x * other, self))
def __rmul__(self,other):
if len(self) == 0:
return self
else:
return tensor( map(lambda x: other * x, self))
def __add__(self,other):
if other == 0:
return self
if isinstance(other,abstractTensor.abstractTensor):
return composite.composite.__add__(self,other)
else:
return NotImplemented
def tensorProduct(self,other):
answer = tensor()
for i in self:
answer = answer + i.tensorProduct(other)
return answer