-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstart.py
1553 lines (1298 loc) · 43.6 KB
/
start.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
"""A visual programming tool for use with Tensorflow
by Paul Bird
You will need to install: wxpython, pil, tensorflow, numpy, opencv
"""
import random
import os
import math
import sys
import threading
import numpy as np
import wx
import tensorflow as tf
import PIL.Image
import PIL.ImageDraw
import PIL.ImageTk
#import PIL.ImageFont
#import aggdraw
import json
import inspect
import about
import time
import json
import cv2
import about
#import skvideo.io as sk
#font = PIL.ImageFont.truetype("Arialbd.ttf",30)
customNodes = []
camera = None
#Create list of tensorflow functions
tfFunctions = ["functions","add","subtract","multiply","divide","assign","reshape",""]
for name in dir(tf):
obj = getattr(tf, name)
if inspect.isfunction(obj) and not name[0].istitle():
tfFunctions.append(name)
tfNNFunctions = ["tf.nn"]
for name in dir(tf.nn):
obj = getattr(tf.nn, name)
if inspect.isfunction(obj) and not name[0].istitle():
tfNNFunctions.append(name)
tfLayerFunctions = ["tf.layers"]
for name in dir(tf.layers):
obj = getattr(tf.layers, name)
if inspect.isfunction(obj) and not name[0].istitle():
tfLayerFunctions.append(name)
#tf.nn
updateSpeed = 1
class MainWindow(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, wx.ID_ANY, "Nodes for Tensorflow")
#self.SetDoubleBuffered(True)
self.SetInitialSize((WIDTH,HEIGHT))
self.SetPosition((0,0))
self.Bind(wx.EVT_CLOSE, self.OnClose)
self.timer = wx.Timer(self, 101)
self.Bind(wx.EVT_TIMER, self.OnTimer)
self.timer.Start(updateSpeed) # 1 second interval
#self.Maximize(True)
def OnClose(self, event):
print("On Close")
self.timer.Stop()
if camera!=None:
camera.release()
self.Destroy()
def OnTimer(self, event):
update()
WIDTH = 1280#int(window.winfo_screenwidth()/1)
HEIGHT = 720#int(window.winfo_screenheight()/2)
WIDTH = int(1920/1.25)
HEIGHT = int(1080/1.25)
sess = tf.Session()
app = wx.App(False)
window = MainWindow()
window.SetTitle("Visual Programming with Tensorflow")
fullscreen = not True
#window.wm_attributes("-topmost", 1)
if fullscreen:
WIDTH = window.winfo_screenwidth()
HEIGHT = window.winfo_screenheight()
##PUT FULLSCREEN CODE HERE##
img = PIL.Image.new("RGB", (WIDTH, HEIGHT), "black")
#dc2 = aggdraw.Draw(img)
dc = PIL.ImageDraw.Draw(img)
#pen = aggdraw.Pen("white", 1)
#brush= aggdraw.Brush("red")
def updateImage():
bitmap = bitmapFromPIL(img)
label.SetBitmap(bitmap)
class Input:
node = 0
def __init__(self, node, output):
self.node = node
self.output = output
value = 0
def drawBezier(dc, points):
(x1, y1, x2, y2, x3, y3, x4, y4) = points
steps = 50
X = x1
Y = y2
for t in range(1, steps+1):
a = t*1.0/steps
b = (1-a)
x = b*b*b*x1 + 3*b*b*a*x2 + 3*b*a*a*x3 + a*a*a*x4
y = b*b*b*y1 + 3*b*b*a*y2 + 3*b*a*a*y3 + a*a*a*y4
dc.line((X, Y, x, y), fill=(255, 255, 255))
X = x
Y = y
class Node:
x = 50
y = 50
height = 60
width = 80
titleHeight = 13
drag = False
name = "Image"
inputs = [0, 0]
color = (0, 0, 255)
inputNames = ["a", "b", "c", "d", "e", "f", "g", "h"]
outputs = []
value = 0
type = ""
showvalue = True
issetup = True
def __init__(self):
global currentNode
self.inputs = [0, 0]
self.outputs = [Input(self, 0)]
if currentNode:
self.x = currentNode.x+currentNode.width + 40
self.y = currentNode.y
currentNode = self
def setup(self):
self.issetup = True
for n in self.inputs:
if n != 0:
if n.node != 0 and not n.node.issetup:
n.node.setup()
def draw(self, dc):
self.drawBackground(dc)
if self.showvalue:
self.showValue(dc)
self.drawForeground(dc)
def calc(self):
z = 0
def drawBackground(self, dc):
(r, g, b) = self.color
normalColor = self.color
darkColor = (int(r/2), int(g/2), int(b/2))
lightColor = (int((255+r)/2), int((255+g)/2), int((255+b)/2))
if self==currentNode:
dc.rectangle((self.x-2, self.y-1, self.x+self.width+1, self.y+self.height+1), outline=lightColor, fill=normalColor)
dc.rectangle((self.x-1, self.y, self.x+self.width, self.y+self.titleHeight), outline=lightColor, fill=normalColor)
title = self.name
if self.value != 0 and self.type != "value" and self.type != "optimizer":
title += " "+str(self.value.get_shape())
dc.text((self.x+5, self.y+1), title+"\0")
dc.rectangle((self.x-1, self.y+self.titleHeight, self.x+self.width, self.y+self.height),
outline=lightColor, fill=darkColor)
y = self.y+len(self.inputs)*self.spacing + self.titleHeight
dc.line((self.x-1, y, self.x+self.width, y), fill=lightColor)
circCenter = []
circInputCenter = []
spacing = 16
def drawForeground(self, dc):
circleSize = 6
self.circInputCenter = []
for n in range(0, len(self.inputs)):
y = self.y+self.titleHeight + self.spacing * n + 5
x = self.x+5
self.circInputCenter.append((x+circleSize/2, y+circleSize/2))
dc.ellipse((x, y, x+circleSize, y+circleSize), fill=(255, 255, 0))
if n < len(self.inputNames):
dc.text((x+10, y-3), self.inputNames[n]+"\0", fill=(255, 255, 255))
#dc2.ellipse((x,y ,x+circleSize,y+circleSize),pen,brush)
if self.inputs[n] != 0:
node2 = self.inputs[n].node
X = node2.x + node2.width - 5 - circleSize
Y = node2.y + node2.titleHeight + 5 + self.spacing * self.inputs[n].output
#dc.line((x+circleSize/2, y+circleSize/2 , X +circleSize/2,Y + circleSize/2 ) ,fill=(255,255,0) )
away = 50
drawBezier(dc,
(x+circleSize/2, y+circleSize/2,
x+circleSize/2-away, y+circleSize/2,
X+circleSize/2+away, Y+circleSize/2,
X+circleSize/2, Y+circleSize/2)
)
#dc2.flush()
self.circCenter = []
for n in range(0, len(self.outputs)):
y = self.y+self.titleHeight + self.spacing * n + 5
x = self.x+self.width-5-circleSize
self.circCenter.append((x+circleSize/2, y+circleSize/2))
dc.ellipse((x, y, x+circleSize, y+circleSize), fill=(255, 255, 0))
def inside(self, pos):
(px, py) = pos
return px > self.x and py > self.y and px < self.x+self.width and py < self.y+self.height
def insideShowButton(self, pos):
(px, py) = pos
buttonSize = self.titleHeight
return px > self.x+self.width-buttonSize and py > self.y and px < self.x+self.width and py < self.y+buttonSize
def insideOutput(self, pos):
global dragStartPos
(px, py) = pos
for n in range(0, len(self.circCenter)):
(cx, cy) = self.circCenter[n]
if (px-cx)*(px-cx)+(py-cy)*(py-cy) < 8*8:
dragStartPos = (cx, cy)
return n
return -1
def insideInput(self, pos):
(px, py) = pos
for n in range(0, len(self.circInputCenter)):
(cx, cy) = self.circInputCenter[n]
if (px-cx)*(px-cx)+(py-cy)*(py-cy) < 8*8:
dragStartPos = (cx, cy)
return n
return -1
def showValue(self, dc):
yOffset = len(self.inputs)*self.spacing + 5
xOffset = 5
xPadding = 15
if self.value == 0:
return
if self.type == "value":
t = str(self.value)
dc.text((self.x+xOffset, self.y+yOffset+self.titleHeight), t+"\0")
charWidth = 6
self.width = max(len(t)*charWidth+xOffset+xPadding, self.width)
return
try:
array = sess.run(self.value, feed_dict={i: d for i, d in zip(placeholders, callbackvalues)})
except Exception as e:
SetText(infoLabel, "Error")
return
if self.type == "optimizer":
return
shape = self.value.get_shape()
if shape._dims is None:
return
#self.name = str(shape)
if len(shape) >= 2:
if(shape[0]+self.titleHeight>self.height):
self.height = int(shape[0])+self.titleHeight
if(shape[1] > self.width):
self.width = int(shape[1])
if len(shape) == 2:
if shape[0]<=4 and shape[1]<=4:
maxt = 0
for y in range(0, shape[0]):
t = str(array[y])
maxt = max(len(t),maxt)
dc.text((self.x+xOffset, self.y+yOffset+self.titleHeight+y*self.spacing), t+"\0")
self.height = int(shape[0])*self.spacing+self.titleHeight+yOffset
charWidth = 6
self.width = max(maxt*charWidth+xOffset+xPadding, self.width)
else:
if array.dtype == np.complex128 or array.dtype==np.complex64:
data = np.reshape(array,(shape[0], shape[1],1))
data = np.concatenate( (
(np.angle(data)*255/np.pi/2).astype(np.uint8),
#np.full((shape[0],shape[1],1),255).astype(np.uint8),
(np.clip(np.abs(data),0,1) *255).astype(np.uint8),
(np.clip(1.0/np.abs(data),0,1) *255*1).astype(np.uint8)
) ,axis=2 )
image = PIL.Image.fromarray(data, mode="HSV")
img.paste(image,(self.x, self.y+self.titleHeight))
else:
data = np.reshape(array*255, (shape[0], shape[1])).astype(np.uint8)
image = PIL.Image.fromarray(data, mode="L")
#scale image
m = max(image.width, image.height)
if m < 128:
image = image.resize( [int(128.0/m*image.width), int(128.0/m*image.height)] , PIL.Image.BICUBIC )
if(image.width > self.width):
self.width = image.width
if(image.height > self.height):
self.height = image.height + self.titleHeight
img.paste(image,(self.x,self.y+self.titleHeight))
elif len(shape) == 3:
if shape[2] == 3: #RGB
data = np.reshape(array*255,(shape[0], shape[1], shape[2])).astype(np.uint8)
image = PIL.Image.fromarray(data, mode="RGB")
img.paste(image, (self.x, self.y+self.titleHeight))
elif shape[2] == 2: #?
iscomplex = 1 #(doesnt do anything)
elif len(shape) <= 1:
if self.value.dtype == tf.string:
if len(shape)==0:
t = array.decode("latin-1")
else:
return
if len(t)>1000:
t = t[:1000]+"..."
else:
t = str(array)
t1 = t.split("\n")
maxW = 0
for n in range(0,len(t1)):
dc.text((self.x+xOffset, self.y+yOffset+self.titleHeight+n*self.spacing), t1[n]+"\0")
maxW = max(len(t1[n]), maxW)
charWidth = 6
self.width = max(maxW * charWidth+xOffset+xPadding, self.width)
self.height = max(len(t1)*self.spacing+yOffset+self.titleHeight, self.height)
dragStartPos = (0,0)
class ConstantNode(Node):
value = 0
height = 30
type="constant"
name="Constant"
inputs = []
color = (0,128,0)
val = 0
def __init__(self):
Node.__init__(self)
self.inputs=[]
def setup(self):
Node.setup(self)
self.value = tf.constant(self.val)
self.outputs[0].value=self.value
class PlaceholderNode(Node):
value = 0
height = 30
name="Placeholder"
inputs = []
color = (255,0,128)
val = 0
type="placeholder"
def __init__(self):
Node.__init__(self)
self.inputs=[]
def setup(self):
Node.setup(self)
shape= np.array(self.val()).shape
self.value = tf.placeholder(tf.float32,shape=shape)
placeholders.append(self.value)
def callback():
return self.val()
callbacks.append(callback)
self.outputs[0].value=self.value
class ListNode(Node):
value = 0
height = 30
width = 100
type="value"
name="Value"
inputs = []
color = (200,0,0)
val = 0
def __init__(self):
Node.__init__(self)
self.inputs=[]
def setup(self):
Node.setup(self)
self.value = self.val
self.outputs[0].value=self.value
class VariableNode(Node):
value = 0
height = 30
width = 100
val = 0
color = (128,0,128)
name="Variable"
def __init__(self):
Node.__init__(self)
self.inputs=[]
def setup(self):
Node.setup(self)
self.value = tf.Variable(self.val)
sess.run(tf.initialize_variables([self.value]))
self.outputs[0].value=self.value
class RandomNode(VariableNode):
value = 0
height = 30
width = 100
name="Random Float32"
op = 0
def __init__(self):
Node.__init__(self)
self.inputs=[]
def setup(self):
Node.setup(self)
self.value = tf.cast(tf.random_uniform([],-0.5,0.5),tf.float32)
self.outputs[0].value = self.value
class Random3x3(VariableNode):
value = 0
height = 50
width = 100
name="Random 3x3 Matrix"
op=0
def __init__(self):
Node.__init__(self)
self.inputs=[]
def setup(self):
Node.setup(self)
self.value = tf.cast(tf.random_uniform([3,3],-0.5,0.5),tf.float32)
self.outputs[0].value = self.value
class Random3(VariableNode):
value = 0
height = 30
width = 100
name="Random 3Vector"
op = 0
def __init__(self):
Node.__init__(self)
self.inputs=[]
def setup(self):
Node.setup(self)
self.value = tf.cast(tf.random_uniform([3],-0.5,0.5),tf.float32)
self.outputs[0].value = self.value
class DotNode(Node):
name="A.B"
height = 50
width = 100
inputs = [0,0]
showvalue = not False
def setup(self):
Node.setup(self)
if self.inputs[0]!=0 and self.inputs[1]!=0:
A = self.inputs[0].value
B = self.inputs[1].value
shape1 = A.get_shape()
shape2 = B.get_shape()
#contract last indices
if len(shape1)>0 and len(shape2)>0:
a = len(shape1)-1
b = len(shape2)-1
self.value = tf.reduce_sum( A * B, a )
self.outputs[0].value = self.value
customNodes.append(DotNode.__name__)
#Node takes an image and draws a filled circle
class DrawCircle(Node):
name="Draw Circle"
height = 100
width = 100
inputs = [0,0,0,0]
inputNames = ["image ref","position","radius","RGB"]
color = (255,0,0)
showvalue = not False
def __init__(self):
Node.__init__(self)
self.inputs = [0,0,0,0]
def setup(self):
Node.setup(self)
if self.inputs[0]!=0:# and self.inputs[1]!=0 and self.inputs[2]!=0 and self.inputs[3]!=0:
image = self.inputs[0].value
#position = self.inputs[1].value
#radius = self.inputs[2].value
#color = self.inputs[3].value
#imageSize = tf.shape(image) #width x height x channels
#circle = (tf.random_uniform(imageSize) + image)/2
size = self.inputs[0].value.get_shape()
w = size[0]
h = size[1]
print(str(w)+"................"+str(h))
uv = np.array([[[u,v] for u in range(0,w) ] for v in range(0,h)])
uvConst = tf.constant(uv)
pos = [50,50]
radius=25
if self.inputs[1]!=0:
pos = self.inputs[1].value
if self.inputs[2]!=0:
radius = self.inputs[2].value
d = uv-pos
circle = tf.cast(tf.reduce_sum(d*d,2) < radius, tf.float32)
self.value = tf.assign(image , circle )
self.outputs[0].value = self.value
customNodes.append(DrawCircle.__name__)
class DrawingNode(Node):
name="Drawing"
height = 100
width = 100
inputs = [0,0,0,0]
inputNames = ["image ref"]
color = (255,0,0)
showvalue = not False
coords = []
def __init__(self):
Node.__init__(self)
self.inputs = [0]
def setup(self):
Node.setup(self)
self.coords = CursorPosition() #cursor position node
self.coords.setup()
#nodes.append(self.coords)
if self.inputs[0]!=0:
image = self.inputs[0].value
size = self.inputs[0].value.get_shape()
#type = self.inputs[0].value.type()
w = size[0]
h = size[1]
print(str(w)+"................"+str(h))
uv = np.array([[[u,v] for u in range(0,w) ] for v in range(0,h)])
uvConst = tf.constant(uv)
radius=10
pos = self.coords.outputs[0].value # - placeholder for topleft
d = uv-pos
circle = image + tf.cast(tf.reduce_sum(d*d,2) < radius, tf.float32)
self.value = tf.assign(image , circle )
self.outputs[0].value = self.value
customNodes.append(DrawingNode.__name__)
placeholders = []
callbacks = []
callbackvalues = []
currentNode = 0
minstData = None
def loadMinstData():
global minstData
file = open("minst.bytes")
file.seek(16)
data = np.fromfile(file, dtype=np.uint8).astype(np.float32)/255.0
minstData = np.reshape(data,[-1,28,28])
#print(str(minstData[0]))
minstLabels = None
def loadMinstLabels():
global minstLabels
file = open("mnist_labels.bytes")
file.seek(8)
minstLabels = np.fromfile(file, dtype=np.byte).astype(np.int32)
class MINSTdata(Node):
name="MNIST data"
height = 100
width = 100
inputs = []
inputNames = []
color = (255,0,0)
showvalue = not False
def setup(self):
loadMinstData()
Node.setup(self)
self.value = tf.placeholder(tf.float32,shape=[28,28])
placeholders.append(self.value)
callbacks.append(getRandomMINST)
self.outputs[0].value = self.value
customNodes.append(MINSTdata.__name__)
class MINSTnumber(Node):
name="MNIST number"
height = 100
width = 100
inputs = []
inputNames = []
color = (255,0,0)
showvalue = not False
def setup(self):
loadMinstLabels()
Node.setup(self)
self.value = tf.placeholder(tf.float32,shape=[1,10])
placeholders.append(self.value)
callbacks.append(getRandomMINSTNumber)
self.outputs[0].value = self.value
customNodes.append(MINSTnumber.__name__)
def getRandomMINSTNumber():
#print("labels="+str(len(minstLabels)))
i = randomNumber % len(minstLabels)
num = minstLabels[i]
val = np.zeros([1,10])
val[0][num] = 1
return val
def getRandomMINST():
#print("data="+str(len(minstData)))
#print("shape="+str(np.shape(minstData)))
i = randomNumber % len(minstData) #random.randint(0, len(minstData)-1)
return minstData[i]
#Node takes an image and draws a filled circle
class CursorPosition(Node):
name="Cursor Position"
height = 30
width = 100
inputs = []
inputNames = []
color = (255,0,0)
showvalue = not False
def __init__(self):
Node.__init__(self)
self.inputs=[]
def setup(self):
Node.setup(self)
self.value = tf.placeholder(tf.int32,shape=[2])
placeholders.append(self.value)
callbacks.append(getMousePos)
self.outputs[0].value = self.value
customNodes.append(CursorPosition.__name__)
WEBCAM_WIDTH=320
WEBCAM_HEIGHT=240
class WebcamNode(Node):
name="Webcam Node"
height = 100
width = 100
inputs = []
inputNames = []
color = (255,0,0)
showvalue = not False
def setup(self):
global camera
Node.setup(self)
if camera==None:
camera = cv2.VideoCapture(0)
self.value = tf.placeholder(tf.float32,shape=[WEBCAM_HEIGHT, WEBCAM_WIDTH, 3])
placeholders.append(self.value)
callbacks.append(getWebcamImage)
self.outputs[0].value = self.value
customNodes.append(WebcamNode.__name__)
def getTime():
return time.clock()
class TimeNode(Node):
name="Time"
height = 100
width = 100
inputs = []
inputNames = []
color = (255,0,0)
showvalue = not False
def setup(self):
Node.setup(self)
self.value = tf.placeholder(tf.float32,shape=[])
placeholders.append(self.value)
callbacks.append(getTime)
self.outputs[0].value = self.value
customNodes.append(TimeNode.__name__)
#train your neural network or find solutions
class OptimizerNode(Node):
name="Optimizer"
height = 50
width = 100
inputs = [0,0]
color = (255,0,0)
inputNames = ["input","expected"]
type = "optimizer"
showvalue = not False
def setup(self):
Node.setup(self)
if self.inputs[0]!=0 and self.inputs[1]!=0:
A = self.inputs[0].value
B = self.inputs[1].value
loss_op = tf.reduce_sum(tf.square(tf.subtract(A,B) ) )
optimizer = tf.train.AdamOptimizer(learning_rate=0.03)
self.value = optimizer.minimize(loss_op)
self.outputs[0].value = self.value
class RNNNode(Node):
inputs = [0, 0]
outputs = [0, 0]
inputNames = ["input","state"]
name = "RNN"
def __init__(self):
Node.__init__(self)
self.outputs = [Input(self, 0),Input(self,1)]
def setup(self):
Node.setup(self)
if self.inputs[0]!=0 and self.inputs[1]!=0:
INPUT = self.inputs[0].value
INPUT_STATE = self.inputs[1].value
SIZE = INPUT.get_shape()[0]
RNN = tf.contrib.rnn.BasicRNNCell( SIZE )
try:
OUTPUT, NEW_STATE = tf.nn.dynamic_rnn( RNN , INPUT , initial_state=INPUT_STATE, dtype=tf.float32)
self.outputs[0].value = OUTPUT
self.outputs[1].value = NEW_STATE
except Exception as e:
SetText(infoLabel, e)
customNodes.append(RNNNode.__name__)
class FullyConnectedSigmoid(Node):
inputs = [0]
outputs = [0]
inputNames = ["input","num nodes"]
name = "Fully Connected Sigmoid"
def __init__(self):
Node.__init__(self)
def setup(self):
Node.setup(self)
if self.inputs[0]!=0 and self.inputs[1]!=0:
INPUT = self.inputs[0].value
OUTPUT_SIZE = self.inputs[1].value
try:
OUTPUT = tf.contrib.layers.fully_connected( INPUT , OUTPUT_SIZE ,activation_fn=tf.nn.sigmoid)
self.value = OUTPUT
self.outputs[0].value = OUTPUT
sess.run(tf.global_variables_initializer())
except Exception as e:
SetText(infoLabel, e)
customNodes.append(FullyConnectedSigmoid.__name__)
class FullyConnectedSoftmax(Node):
inputs = [0]
outputs = [0]
inputNames = ["input","num nodes"]
name = "Fully Connected Softmax"
def __init__(self):
Node.__init__(self)
def setup(self):
Node.setup(self)
if self.inputs[0]!=0 and self.inputs[1]!=0:
INPUT = self.inputs[0].value
OUTPUT_SIZE = self.inputs[1].value
try:
OUTPUT = tf.contrib.layers.fully_connected( INPUT , OUTPUT_SIZE ,activation_fn=tf.nn.softmax)
self.value = OUTPUT
self.outputs[0].value = OUTPUT
sess.run(tf.global_variables_initializer())
except Exception as e:
SetText(infoLabel, e)
customNodes.append(FullyConnectedSoftmax.__name__)
class ConvolutionalLayer(Node):
inputs = [0]
outputs = [0]
inputNames = ["input"]
name = "Convolutional"
def __init__(self):
Node.__init__(self)
def setup(self):
Node.setup(self)
if self.inputs[0]!=0:
INPUT = self.inputs[0].value
shape = INPUT.get_shape()
try:
if len(shape)==3:
INPUT = tf.reshape(INPUT, [1, shape[0], shape[1], shape[2]])
if len(shape)==2:
INPUT = tf.reshape(INPUT, [1,shape[0], shape[1], 1])
numfilters=3
if self.inputs[1]!=0:
numfilters = self.inputs[1].value
OUTPUT = tf.layers.conv2d(inputs=INPUT, filters=numfilters, kernel_size=[3, 3], padding="same")
#if len(shape)==3:
# OUTPUT = tf.reshape(OUTPUT,(shape[0],shape[1],shape[2]))
#if len(shape)==2:
# OUTPUT = tf.reshape(OUTPUT,(shape[0],shape[1]))
self.value = OUTPUT
self.outputs[0].value = OUTPUT
sess.run(tf.global_variables_initializer())
except Exception as e:
SetText(infoLabel, e)
customNodes.append(ConvolutionalLayer.__name__)
class MaxPoolingLayer(Node):
inputs = [0]
outputs = [0]
inputNames = ["input"]
name = "Max Pooling"
def __init__(self):
Node.__init__(self)
def setup(self):
Node.setup(self)
if self.inputs[0]!=0:
INPUT = self.inputs[0].value
shape = INPUT.get_shape()
try:
OUTPUT = tf.layers.max_pooling2d(inputs=INPUT, pool_size=[2, 2], strides=2)
self.value = OUTPUT
self.outputs[0].value = OUTPUT
sess.run(tf.global_variables_initializer())
except Exception as e:
SetText(infoLabel, e)
customNodes.append(MaxPoolingLayer.__name__)
#General node for any tensorflow function
class FunctionNode(Node):
name="x"
inputs = [0,0]
showvalue = not False
args = []
func = 0
funcCompiled = 0
def __init__(self,func,args):
Node.__init__(self)
self.func=func
print("func="+func)
self.funcCompiled = eval(func)
self.args=args
self.inputs = [0] * len(args)
self.height = 16 * len(args) + self.titleHeight
self.name = self.funcCompiled.__name__
for a in range(0,len(self.args)):
if self.args[a]!=0:
self.inputs[a] = self.args[a].outputs[0]
def setup(self):
Node.setup(self)
fargs=[]
for a in range(0,len(self.inputs)):
if self.inputs[a]==0:
break
fargs.append(self.inputs[a].value)
try:
self.value = self.funcCompiled(*fargs)
self.outputs[0].value = self.value
except Exception as e:
SetText(infoLabel, e)
#Matrix multiplication for each element in a grid
class MatMultNode(Node):
name="AB"
height = 50
width = 100
inputs = [0,0]
showvalue = not False
def setup(self):
Node.setup(self)
if(self.inputs[0]!=0 and self.inputs[1]!=0):
a = len(self.inputs[0].value.get_shape())-1
b = len(self.inputs[1].value.get_shape())-2
self.value =tf.tensordot( self.inputs[0].value , self.inputs[1].value , [[a],[b]])
self.outputs[0].value = self.value
customNodes.append(MatMultNode.__name__)
class WatchNode(Node):
name="watch"
inputs = [0]
def setup(self):
Node.setup(self)
if(self.inputs[0]!=0):
self.value = self.inputs[0].value
self.outputs[0] = self.value
customNodes.append(WatchNode.__name__)
ar = np.zeros([256,256])
for x in range(0,256):
for y in range(0,256):
ar[y][x] = ((x+y)%256)/255.0
W=128
H=128
ar3 = np.zeros([H,W,3]).astype(np.float32)
for x in range(0,W):
for y in range(0,H):
ar3[y][x][0] = x*2.0/W-1
ar3[y][x][1] = y*2.0/H-1
nodes=[]
def defaultNodes():
global nodes
X = ConstantNode()
X.val = ar3
M = Random3x3()
MX = MatMultNode()
MX.inputs[0]=X.outputs[0]
MX.inputs[1]=M.outputs[0]
MX.x=500
XMX = DotNode()
XMX.inputs[0]=MX.outputs[0]
XMX.inputs[1]=X.outputs[0]
XMX.x=800
XMX.y=300
B = Random3()
BX = DotNode()
BX.inputs[0]=X.outputs[0]
BX.inputs[1]=B.outputs[0]
BX.x=800
XMX_BX = FunctionNode("tf.add",[BX,XMX])
XMX_BX.x = 1000
W = WatchNode()
W.inputs[0]=XMX_BX.outputs[0]
RNN = RNNNode()
nodes = [X,M,MX,XMX,B,BX,XMX_BX,RNN]
def defaultNodes2():
global nodes
img1 = PIL.Image.open("abc.png").convert("RGB")
ar2 = np.array(img1) /256.0
c1 = ConstantNode()
c1.value = tf.constant(ar3)
c2 = ConstantNode()
c2.value = tf.constant(ar3)
m = Random3x3()
u = Random3()
t=MatMultNode()
t.inputs[0] = c1.outputs[0]
t.inputs[1] = m.outputs[0]
a = DotNode()
a.inputs[0] = t.outputs[0]
a.inputs[1] = u.outputs[0]
w=WatchNode()
w.inputs[0]=a.outputs[0]
nodes = [c1,m,t,u,a,w]
def setupNodes():
for n in nodes:
n.issetup = False
for n in nodes:
if not n.issetup: