-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathClusterViz-0.2.tar
2231 lines (1794 loc) · 100 KB
/
ClusterViz-0.2.tar
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
ClusterViz-0.2/ 0000755 0001750 0000144 00000000000 10405136430 013170 5 ustar maaskola users ClusterViz-0.2/clusterdisplay.py 0000755 0001750 0000144 00000054014 10405127320 016616 0 ustar maaskola users #
# clusterdisplay.py - visualization routines to display clustering processes
#
# Copyright (C) 2005 Janne Grunau, Jonas Maaskola
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
"""This script displays a visualization of the clustering process of the family
of kmeans-algorithms."""
import colorsys, logging, Numeric, random, sys, time, threading
from OpenGL.GL import *
from OpenGL.GLUT import *
from OpenGL.GLU import *
import trackball
import visualkmeans
import guihelp
import auxiliary
DEBUGGING = 0
try:
import rpy
except ImportError:
rpy_available = False
else:
rpy_available = True
class clusterDisplay:
""" Class to incorporate the facilities to visualize a clustering process. """
def __init__(self,
data,
k,
transformation_matrix,
redraw_event = threading.Event(),
width = 800,
height = 600,
title = "Clustering using Python and OpenGL",
logger = None):
""" Intialize a clustering display.
Arguements are:
data a list of the three-dimensional data points
k the number of clusters in the kmeans algorithm
redraw_event an object used flag when to readraw and when not
width width of the window to be created
height height of the window to be created
title the title to be displayed in the window
logger a logging facility
"""
if logger is None:
# Organize logging.
self.logger = logging.getLogger("clusterDisplay")
hdlr = logging.StreamHandler()
if not bool(DEBUGGING):
self.logger.setLevel(logging.INFO)
formatter = logging.Formatter('%(message)s')
# formatter = logging.Formatter('%(asctime)s Display %(levelname)s %(message)s')
else:
self.logger.setLevel(logging.DEBUG)
formatter = logging.Formatter('Display %(levelname)s %(message)s')
# formatter = logging.Formatter('%(asctime)s Display %(levelname)s %(message)s')
hdlr.setFormatter(formatter)
self.logger.addHandler(hdlr)
else:
self.logger = logger
self.width = int(width)
self.height = int(height)
self.title = title
self.data = data
self.dataLen = len(self.data)
self.k = k
self.transformation_matrix = transformation_matrix
self.redraw_event = redraw_event
self.glutPostRedisplayLOCK = threading.Lock()
self.historyLocked = False
if self.transformation_matrix is not None:
self.data = Numeric.dot(data, transformation_matrix)
self.entropy = []
self.dataColors = []
for i in xrange(self.dataLen): self.dataColors.append([1.0, 1.0, 1.0, 1.0])
self.center = Numeric.sum(self.data)/self.dataLen # Set Center to the data mean
self.logger.info("Center of data = "+str(self.center))
self.clusterpositions = []
self.clusterhistory = []
self.sigmahistory = []
self.colors = []
self.showTrajectories = True
self.zoomFactor = 1.0
##//------ Trackball ------------
self.mouse_button = 0
self.drawData = True
self.drawClusters = True
self.cluster_rep_radius = 1.0
self.data_transparency = 0.8
self.line_width = 2.0
self.pointsize = 2.5 * 10
self.cluster_trans = 0.3
self.sphere_segments = 50
self.rel_axis_length = 1.0
self.timeIDX = 0
self.clusteringDone = False
self.displayPointInTime = None
self.show_gui_help = False
self.readmefile = "README"
self.statusText = "%i data points displayed" % self.dataLen
self.gui_help_text = guihelp.gui_help_text
self.DLs_initialized = False
self.regenData = False
self.clusteringPaused = False
self.clusteringThread = None
self.clusteringRestart = False
self.Exit = False
def initGL(self):
""" Intialize the OpenGL system by calling functions that set up the
lightning, shading, generate display lists and set up the trackball."""
ambient = [ 0.0, 0.0, 0.0, 0.0 ]
lmodel_ambient = [ 1.0, 1.0, 1.0, 1.0 ]
diffuse = [ 0.0, 0.0, 0.0, 0.0 ]
lightposition = [ 5.0, 10.0, 20.0, 0.0 ]
local_view = [ 0.0 ]
glLight(GL_LIGHT0, GL_AMBIENT, ambient)
glLightModel(GL_LIGHT_MODEL_AMBIENT, lmodel_ambient)
glLight(GL_LIGHT0, GL_DIFFUSE, diffuse)
glLight(GL_LIGHT0, GL_POSITION, lightposition)
glLightModel(GL_LIGHT_MODEL_AMBIENT, lmodel_ambient)
glLightModel(GL_LIGHT_MODEL_LOCAL_VIEWER, local_view)
glEnable(GL_DEPTH_TEST)
glDepthFunc(GL_LESS)
glEnable(GL_CULL_FACE)
glEnable(GL_LIGHTING)
glEnable(GL_LIGHT0)
glEnable(GL_BLEND)
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
glShadeModel(GL_SMOOTH)
glEnable(GL_ALPHA_TEST)
glAlphaFunc(GL_GREATER,0)
glEnable(GL_POINT_SMOOTH)
self.maximized = False
self.DLs_initialized = False
self.generate_display_lists()
self.tb = trackball.trackball()
self.tb.gltbInit(GLUT_LEFT_BUTTON)
self.logger.debug("GL settings initialized.")
def generate_display_lists(self):
""" Generate display lists. """
self.dataRepDL = glGenLists(1) # draws the data points
glNewList(self.dataRepDL,GL_COMPILE)
self.draw_data_representation()
glEndList()
self.crossDL = glGenLists(1) # draws a 3d-cross
glNewList(self.crossDL,GL_COMPILE)
self.draw_3d_cross()
glEndList()
self.DLs_initialized = True
def regen_data_display_list(self):
""" (Re-) Generate data representation display list. """
if self.DLs_initialized:
self.dataRepDL = glGenLists(1) # draws the data points
glNewList(self.dataRepDL,GL_COMPILE)
self.draw_data_representation()
glEndList()
else:
self.logger.error("Trying to recalculate the colors too early.")
def draw_text(self, value, x,y, font = GLUT_BITMAP_8_BY_13, step = 18):
"""Draw the given text at given 2D position in window.
Possiblities for the font include:
GLUT_BITMAP_8_BY_13
GLUT_BITMAP_9_BY_15
GLUT_BITMAP_TIMES_ROMAN_10
GLUT_BITMAP_TIMES_ROMAN_24
GLUT_BITMAP_HELVETICA_10
GLUT_BITMAP_HELVETICA_12
GLUT_BITMAP_HELVETICA_18
For reference see:
http://pyopengl.sourceforge.net/documentation/manual/glutBitmapCharacter.3GLUT.html
"""
glMatrixMode(GL_PROJECTION)
glPushMatrix()
glLoadIdentity()
glOrtho(0.0, self.height or 32, 0.0, self.width or 32, -1.0, 1.0)
glMatrixMode(GL_MODELVIEW)
glPushMatrix()
glLoadIdentity()
glRasterPos2i(x, y)
lines = 0
for character in value:
if character == '\n':
glRasterPos2i(x, y-(lines*step))
lines += 1
else:
glutBitmapCharacter(font, ord(character))
glPopMatrix()
glMatrixMode(GL_PROJECTION)
glPopMatrix()
glMatrixMode(GL_MODELVIEW)
def draw_help_info(self):
""" Writes self.gui_help_text approximately in the middle of the screen. """
glMaterial(GL_FRONT, GL_AMBIENT, (1.0,1.0,1.0,1.0))
glMaterial(GL_FRONT, GL_DIFFUSE, (1.0,1.0,1.0,1.0))
self.draw_text(self.gui_help_text,50,self.height-10)
#for i in range(self.height/20):
# self.draw_text(("Test %3i: h = %i" %(i, self.height)), 10, i*20)
def draw_status_info(self):
""" Writes self.statusText into a line at the bottom of the screen. """
glMaterial(GL_FRONT, GL_AMBIENT, (1.0,1.0,1.0,1.0))
glMaterial(GL_FRONT, GL_DIFFUSE, (1.0,1.0,1.0,1.0))
self.draw_text(self.statusText,10,10, GLUT_BITMAP_HELVETICA_18)
def draw_data_representation(self):
""" Draw data representations. """
glPointSize(self.pointsize)
glColorMaterial (GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE)
glEnable(GL_COLOR_MATERIAL)
glVertexPointerd(self.data)
glEnableClientState(GL_VERTEX_ARRAY)
glColorPointerd(self.dataColors)
glEnableClientState(GL_COLOR_ARRAY)
glDrawArrays(GL_POINTS, 0, self.dataLen)
glDisable( GL_VERTEX_ARRAY )
glDisable( GL_COLOR_ARRAY )
glDisable( GL_COLOR_MATERIAL )
def draw_3d_cross(self):
""" Draws a stippled three-dimensional cross. """
glEnable(GL_LINE_STIPPLE)
glLineStipple(1,0x00FF) # magic numbers 10101010101010
glMaterial(GL_FRONT_AND_BACK, GL_DIFFUSE, (1.0,1.0,1.0,1.0))
glMaterial(GL_FRONT, GL_AMBIENT, (1.0,1.0,1.0,1.0))
glLineWidth(self.line_width)
glBegin(GL_LINE_STRIP)
glVertex3f(-1.0, 0.0, 0.0)
glVertex3f(1.0, 0.0, 0.0)
glEnd()
glBegin(GL_LINE_STRIP)
glVertex3f(0.0, -1.0, 0.0)
glVertex3f(0.0, 1.0, 0.0)
glEnd()
glBegin(GL_LINE_STRIP)
glVertex3f(0.0, 0.0, -1.0)
glVertex3f(0.0, 0.0, 1.0)
glEnd()
glDisable(GL_LINE_STIPPLE)
def draw_cluster_representations(self):
""" Draw cluster representations: transparent spheres and stippled diameter lines. """
idx = 0
for cluster in self.clusterpositions:
glPushMatrix()
# Move to cluster center
glTranslate(cluster[0], cluster[1], cluster[2])
# Scale according to cluster's standard deviations' axiparallel extents
glScale(self.sdevs[idx][0] * self.cluster_rep_radius, self.sdevs[idx][1] * self.cluster_rep_radius, self.sdevs[idx][2] * self.cluster_rep_radius)
# Draw cluster sphere diameters
glPushMatrix()
glMaterial(GL_FRONT, GL_AMBIENT, (1.0,1.0,1.0,1.0))
glMaterial(GL_FRONT, GL_DIFFUSE, (1.0,1.0,1.0,1.0))
glScale(self.rel_axis_length, self.rel_axis_length, self.rel_axis_length)
glCallList(self.crossDL)
glPopMatrix()
# Draw actual spheres
glMaterial(GL_FRONT_AND_BACK, GL_DIFFUSE, self.colors[idx])
glMaterial(GL_FRONT, GL_AMBIENT, self.colors[idx])
glutSolidSphere(1.0, self.sphere_segments, self.sphere_segments)
glPopMatrix()
idx += 1
def draw_cluster_trajectories(self):
""" Draw cluster trajectories. """
# First draw stippled opaque white trajectory
glEnable(GL_LINE_STIPPLE)
glLineStipple(1,0x00FF) # magic numbers 10101010101010
glLineWidth(self.line_width)
glMaterial(GL_FRONT, GL_AMBIENT, (1.0,1.0,1.0,1.0))
glMaterial(GL_FRONT, GL_DIFFUSE, (1.0,1.0,1.0,1.0))
for clustertrajectory in self.clusterhistory:
glBegin(GL_LINE_STRIP)
for point in clustertrajectory[:self.timeIDX+1]:
glVertex3f(point[0], point[1], point[2])
glEnd()
glDisable(GL_LINE_STIPPLE)
# Then draw semi transparent colorful trajectory
glLineWidth(self.line_width*2)
color = 0
for clustertrajectory in self.clusterhistory:
glBegin(GL_LINE_STRIP)
glMaterial(GL_FRONT, GL_AMBIENT, self.colors[color])
glMaterial(GL_FRONT, GL_DIFFUSE, self.colors[color])
color += 1
for point in clustertrajectory[:self.timeIDX+1]:
glVertex3f(point[0], point[1], point[2])
glEnd()
def display(self):
self.redraw_event.clear()
if self.regenData:
self.regen_data_display_list()
self.regenData = False
glPushMatrix()
glClearColor(0.0, 0.0, 0.0, 0.0)
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
# Transform according to trackball status
self.tb.gltbMatrix()
# Move objects into the center of view (hopefully)
# Mind that self.center is the mean of the data.
glTranslate(-self.center[0],-self.center[1],-self.center[2])
# Draw status info
self.draw_status_info()
# Draw data
if self.drawData:
glCallList(self.dataRepDL)
# Draw cluster trajectories
if self.showTrajectories:
self.draw_cluster_trajectories()
# Draw cluster representations: transparent spheres and stippled diameter lines
if self.drawClusters:
self.draw_cluster_representations()
# Draw GUI usage info
if self.show_gui_help:
self.draw_help_info()
glPopMatrix()
glutSwapBuffers()
# Restart the Clustering
if self.clusteringRestart:
if not self.clusteringThread.isAlive():
self.clusteringThread = self.clThreadReInit()
self.clusteringThread.start()
self.clusteringRestart = False
# test for exit
if self.Exit:
if not self.clusteringThread.isAlive():
sys.exit(0)
def clThreadReInit(self):
self.entropy = []
data = self.clusteringThread.seqs
display = self
k = self.clusteringThread.k
dist = self.clusteringThread.distanceFunction
algorithm = self.clusteringThread.algorithm
redraw_ev = self.redraw_event
beta = self.clusteringThread.beta
return visualkmeans.Clustering(data, display, k, dist, algorithm, redraw_ev, beta)
def reshape(self, width, height):
self.width = width
self.height = height
if height==0:
return
# Trackball
self.tb.gltbReshape(width, height)
glViewport(0, 0, width, height)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluPerspective(45.0*self.tb.zoomFactor, width/height, 1.0, 100.0)
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
glTranslatef(0.0, 0.0, -18.0)
def keyboard (self, key, x, y):
#self.logger.debug(str(key)+" "+str(int(key)))
## FULLSCREEN
if key == 'f':
if not self.maximized:
glutFullScreen()
self.maximized = True
self.window_x = glutGet(GLUT_WINDOW_X)
self.window_y = glutGet(GLUT_WINDOW_Y)
self.window_width = glutGet(GLUT_WINDOW_WIDTH)
self.window_height = glutGet(GLUT_WINDOW_HEIGHT)
## WINDOWED
elif key == 'w':
if self.maximized:
glutPositionWindow(self.window_x, self.window_y)
#glutReshapeWindow(400,200)
glutReshapeWindow(self.window_width, self.window_height)
self.maximized = False
## HELP
elif key == 'h':
self.show_gui_help = not self.show_gui_help
## QUIT
elif key == "q" or ord(key) == 27:
self.statusText = "Exiting"
self.clusteringThread.abortNOW = True
self.Exit = True
## HISTORY_BACK
elif key == 'b':
if self.clusteringDone:
if not self.historyLocked:
self.historyLocked = True
self.displayHistoryItem(-1)
self.regen_data_display_list()
else:
self.statusText = "Please wait until clustering process has finished."
## HISTORY_NEXT
elif key == 'n':
if self.clusteringDone:
if not self.historyLocked:
self.historyLocked = True
self.displayHistoryItem(+1)
self.regen_data_display_list()
else:
self.statusText = "Please wait until clustering process has finished."
## TOGGLE_TRAJECTORIES_DISPLAY
elif key =='j':
self.showTrajectories = not self.showTrajectories
self.statusText = "Show trajectories: %s." % str(self.showTrajectories)
## TOGGLE_DATA_DISPLAY
elif key == 'd':
self.drawData = not self.drawData
self.statusText = "Draw data points: %s." % str(self.drawData)
if self.drawData:
self.regen_data_display_list()
## TOGLE_CLUSTER_REPRESENTATIONS_DISPLAY
elif key == 'c':
self.drawClusters = not self.drawClusters
self.statusText = "Draw cluster centers: %s." % str(self.drawClusters)
## RESTART_CLUSTERING
elif key == 'r':
if not self.clusteringRestart:
self.statusText = "Restarting cluster computation"
self.clusteringThread.abortNOW = True
self.clusteringRestart = True
## PAUSE_CLUSTERING
elif key == 'p':
self.clusteringPaused = not self.clusteringPaused
self.statusText = "Clustering thread paused: %s." % str(self.clusteringPaused)
if self.glutPostRedisplayLOCK.acquire(False):
glutPostRedisplay()
self.glutPostRedisplayLOCK.release()
def mouse(self, button, state, x, y):
#/* fix for two-button mice -- left mouse + shift = middle mouse */
if (button == GLUT_LEFT_BUTTON and glutGetModifiers() & GLUT_ACTIVE_SHIFT):
button = GLUT_MIDDLE_BUTTON
#save mouse state
self.mouse_button = button
self.mouse_x= x
self.mouse_y= y
if (state == GLUT_DOWN) and (button==GLUT_LEFT_BUTTON):
self.tb.gltbStartMotion(x, y, button, glutGet(GLUT_ELAPSED_TIME))
elif (state == GLUT_UP) and (button==GLUT_LEFT_BUTTON):
self.tb.gltbStopMotion(button, glutGet(GLUT_ELAPSED_TIME))
def motion(self, x, y):
#rotation
if self.mouse_button == GLUT_LEFT_BUTTON:
self.tb.gltbMotion(x, y)
#zooming
elif self.mouse_button == GLUT_RIGHT_BUTTON:
self.tb.gltbZoom(x, y, self.mouse_x, self.mouse_y)
#panning
elif self.mouse_button == GLUT_MIDDLE_BUTTON:
self.tb.gltbPan(x, y, self.mouse_x, self.mouse_y)
# save mouse position
self.mouse_x= x
self.mouse_y= y
if self.glutPostRedisplayLOCK.acquire(False):
glutPostRedisplay()
self.glutPostRedisplayLOCK.release()
def idle(self):
if not self.clusteringPaused:
self.redraw_event.set()
if self.tb.animate:
self.glutPostRedisplayLOCK.acquire(True)
self.tb.gltbAnimate()
self.glutPostRedisplayLOCK.release()
time.sleep(0.01)
self.historyLocked = False
def changeAssignment(self, point, cluster_ptr, entropy):
""" Assign one data point to a cluster. The data point's cluster
distribution's entropy is also given. """
self.dataColors[point] = [(1-entropy) * ko + entropy
for ko in self.colors[cluster_ptr]][:-1] + [self.data_transparency]
def clearClusters(self,k):
""" Reset everything touching the cluster representations to k at zero. """
self.k = k
self.clusterpositions = []
self.clusterhistory = []
self.sdevs = []
self.sigmahistory = []
for i in range(k):
self.clusterpositions.append((0.0,0.0,0.0))
self.clusterhistory.append([])
self.sigmahistory.append([])
self.sdevs.append((0.0,0.0,0.0))
self.colors = []
for x in range(k):
self.colors.append(colorsys.hls_to_rgb(float(x)/k ,0.5,1.0) + (self.cluster_trans,))
self.logger.debug("Colors: "+str(self.colors))
if self.glutPostRedisplayLOCK.acquire(False):
glutPostRedisplay()
self.glutPostRedisplayLOCK.release()
def updateCluster(self, cluster_nr, pos, sdevs = (1.0,1.0,1.0)):
self.logger.info("Cluster "+str(cluster_nr)+" updated to "+str(pos))
if self.transformation_matrix is not None:
pos = Numeric.dot(pos,self.transformation_matrix)
self.clusterpositions[cluster_nr] = pos
self.sdevs[cluster_nr] = sdevs
if not self.clusteringDone:
self.clusterhistory[cluster_nr].append(pos)
self.sigmahistory[cluster_nr].append(sdevs)
self.timeIDX = len(self.clusterhistory[0])-1
if self.glutPostRedisplayLOCK.acquire(False):
self.redraw_event.clear()
glutPostRedisplay()
self.glutPostRedisplayLOCK.release()
def addEntropy(self, v):
if (rpy_available):
self.entropy.append(v)
rpy.r.plot(self.entropy,main="Entropy of data distribution over the clusters",xlab="Clustering update steps",ylab="Nats")
def enableHistory (self, displayfunction):
self.clusteringDone = True
self.displayPointInTime = displayfunction
self.timeIDX = len(self.clusterhistory[0])-1
self.statusText = "Calculation finished."
if self.glutPostRedisplayLOCK.acquire(False):
glutPostRedisplay()
self.glutPostRedisplayLOCK.release()
def displayHistoryItem (self, step):
assert self.clusteringDone
if self.timeIDX+step >= len(self.clusterhistory[0]) or self.timeIDX+step < 0:
self.logger.info("End of history reached at step " + str(self.timeIDX))
self.statusText = "Time index = "+str(self.timeIDX)+" (start/end of history)"
else:
self.timeIDX += step
reps = []
sigma = []
k = len(self.clusterhistory)
for clustertrajec in self.clusterhistory:
reps.append(clustertrajec[self.timeIDX])
for s in self.sigmahistory:
sigma.append(s[self.timeIDX])
self.logger.info("Displaying time point " + str(self.timeIDX))
self.displayPointInTime (k, reps, sigma, .01)
self.statusText = "Time index = "+str(self.timeIDX)
if self.glutPostRedisplayLOCK.acquire(False):
glutPostRedisplay()
self.glutPostRedisplayLOCK.release()
def updateDisplay(self):
self.redraw_event.clear()
if self.glutPostRedisplayLOCK.acquire(False):
glutPostRedisplay()
self.glutPostRedisplayLOCK.release()
def mainLoop(self):
random.seed()
self.logger.debug("Initializing display.")
glutInit(sys.argv)
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH)
glutInitWindowSize(self.width,self.height)
glutInitWindowPosition(0, 0)
glutCreateWindow(self.title)
self.initGL()
glutDisplayFunc(self.display)
glutReshapeFunc(self.reshape)
glutKeyboardFunc(self.keyboard)
glutMouseFunc(self.mouse)
glutMotionFunc(self.motion)
glutIdleFunc(self.idle)
self.logger.debug("Display intialization finished. Entering main loop.")
glutMainLoop()
if __name__ == "__main__":
cl = clusterDisplay(auxiliary.readData())
cl.clearClusters(3)
cl.updateCluster(cl.data[0], 0)
cl.updateCluster(cl.data[1], 1)
cl.updateCluster(cl.data[2], 2)
for i in range(len(cl.data)):
cl.changeAssignment(i, i%3,0.5)
cl.mainLoop()