-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnode.py
More file actions
263 lines (201 loc) · 8.3 KB
/
Copy pathnode.py
File metadata and controls
263 lines (201 loc) · 8.3 KB
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
import numpy as np
class Node:
# other types that are capable of being converted to Node
_COMPATIBLE_TYPES = (int, float, np.ndarray)
# store nodes that have been computed previously
_NODE_REGISTRY = {}
def __init__(self, symbol, value, derivative=1):
"""
Represents a node which is the foundation of a computational graph.
:param symbol: Symbolic representation of a Node instance that acts as a unique identifier.
:param value: Analytical value of the node.
:param derivative: Derivative with respect to the value attribute. Default=1.
Example Instantiations:
> x = Node('x', 10, 1)
> y = Node('y', 20)
"""
self._symbol = symbol
self._value = value
self._derivative = derivative
@property
def value(self):
return self._value
@property
def symbol(self):
return self._symbol
@property
def derivative(self):
return self._derivative
@staticmethod
def _check_foreign_type_compatibility(other_type):
"""
Checks to see if a datatype can be represented as a node.
:param other_type: Type to check for conversion compatibility.
:return: boolean. True if other_type is a supported type. False otherwise.
"""
return isinstance(other_type, Node._COMPATIBLE_TYPES)
@staticmethod
def _convert_to_node(to_convert):
"""
Attempts to convert an object into an instance of class Node.
:param to_convert: Object that will convert to type Node.
:return: Node instance created from to_convert.
:raises: TypeError if to_convert is an unsupported data type.
"""
if isinstance(to_convert, Node):
return to_convert
if Node._check_foreign_type_compatibility(to_convert):
return Node(symbol=str(to_convert), value=to_convert)
raise TypeError(
f"Unsupported type {type(to_convert)} for instance of class Node"
)
@staticmethod
def _check_node_exists(key):
"""
Checks if an instance of class Node has already been created.
:param key: Symbolic representation of a Node instance that acts as a unique identifier.
:return: boolean. True if key argument is found. False otherwise.
"""
return key in Node._NODE_REGISTRY
@staticmethod
def _get_existing_node(key):
"""
Returns existing Node instance to avoid recomputing nodes.
:param key: Symbolic representation of a Node instance that acts as a unique identifier.
:return: Node instance that matches the specified key.
"""
return Node._NODE_REGISTRY[key]
@staticmethod
def _insert_node_to_registry(node):
"""
Adds Node instance to the registry. Allows computational graph to keep track of what nodes have
already been computed .
:param node: Instance of class Node.
:return: None.
"""
Node._NODE_REGISTRY[node._symbol] = node
def __add__(self, other):
symbolic_representation = "({}+{})".format(*sorted([self._symbol, str(other)]))
if self._check_node_exists(symbolic_representation):
return self._get_existing_node(symbolic_representation)
other = self._convert_to_node(other)
primal_trace = self._value + other._value
tangent_trace = self._derivative + other._derivative
new_node = Node(
symbol=symbolic_representation,
value=primal_trace,
derivative=tangent_trace,
)
Node._insert_node_to_registry(new_node)
return new_node
def __radd__(self, other):
return self.__add__(other)
def __sub__(self, other):
symbolic_representation = "({}-{})".format(self._symbol, str(other))
if self._check_node_exists(symbolic_representation):
return self._get_existing_node(symbolic_representation)
other = self._convert_to_node(other)
primal_trace = self._value - other._value
tangent_trace = self._derivative - other._derivative
new_node = Node(
symbol=symbolic_representation,
value=primal_trace,
derivative=tangent_trace,
)
Node._insert_node_to_registry(new_node)
return new_node
def __rsub__(self, other):
symbolic_representation = "({}-{})".format(str(other), self._symbol)
if self._check_node_exists(symbolic_representation):
return self._get_existing_node(symbolic_representation)
other = self._convert_to_node(other)
primal_trace = other._value - self._value
tangent_trace = other._derivative - self._derivative
new_node = Node(
symbol=symbolic_representation,
value=primal_trace,
derivative=tangent_trace,
)
Node._insert_node_to_registry(new_node)
return new_node
def __mul__(self, other):
symbolic_representation = "({}*{})".format(*sorted([self._symbol, str(other)]))
if self._check_node_exists(symbolic_representation):
return self._get_existing_node(symbolic_representation)
other = self._convert_to_node(other)
primal_trace = self._value * other._value
tangent_trace = (
self._value * other._derivative + other._value * self._derivative
)
new_node = Node(
symbol=symbolic_representation,
value=primal_trace,
derivative=tangent_trace,
)
Node._insert_node_to_registry(new_node)
return new_node
def __rmul__(self, other):
return self.__mul__(other)
def __truediv__(self, other):
symbolic_representation = "({}/{})".format(self._symbol, str(other))
if self._check_node_exists(symbolic_representation):
return self._get_existing_node(symbolic_representation)
other = self._convert_to_node(other)
primal_trace = self._value / other._value
tangent_trace = (
self._derivative * other._value - self._value * other._derivative
) / other._derivative**2
new_node = Node(
symbol=symbolic_representation,
value=primal_trace,
derivative=tangent_trace,
)
Node._insert_node_to_registry(new_node)
return new_node
def __rtruediv__(self, other):
symbolic_representation = "({}/{})".format(str(other), self._symbol)
if self._check_node_exists(symbolic_representation):
return self._get_existing_node(symbolic_representation)
other = self._convert_to_node(other)
primal_trace = self._value / other._value
tangent_trace = (
other._derivative * self._value - other._value * self._derivative
) / self._derivative**2
new_node = Node(
symbol=symbolic_representation,
value=primal_trace,
derivative=tangent_trace,
)
Node._insert_node_to_registry(new_node)
return new_node
def __neg__(self):
symbolic_representation = "-{}".format(self._symbol)
if self._check_node_exists(symbolic_representation):
return self._get_existing_node(symbolic_representation)
primal_trace = -1 * self._value
tangent_trace = -1 * self._derivative
new_node = Node(symbolic_representation, primal_trace, tangent_trace)
self._insert_node_to_registry(new_node)
return new_node
def __pow__(self, exponent):
symbolic_representation = "({}**{})".format(str(exponent), self._symbol)
if self._check_node_exists(symbolic_representation):
return self._get_existing_node(symbolic_representation)
exponent = self._convert_to_node(exponent)
primal_trace = self._value**exponent._value
tangent_trace = exponent._value * self._value ** (exponent._value - 1)
new_node = Node(
symbol=symbolic_representation,
value=primal_trace,
derivative=tangent_trace,
)
self._insert_node_to_registry(new_node)
return new_node
def __str__(self):
return self._symbol
def __repr__(self):
return f"Node({self._symbol},{self._value},{self._derivative})"
if __name__ == "__main__":
x = Node("x", 3, 1)
z = -x
print(z._NODE_REGISTRY)