-
Notifications
You must be signed in to change notification settings - Fork 1
/
NeuralNet.cpp
6431 lines (5013 loc) · 190 KB
/
NeuralNet.cpp
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
// NeuralNet.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "NeuralNet.h"
#define MY_DEBUG_TIME
#ifdef MY_DEBUG_TIME
#define TIMER_NO 10
CTimeSpan TimeSpan[TIMER_NO];
CTime StartTime[TIMER_NO];
CTime EndTime;
CTime ElapsedTime;
#define TIC(i) StartTime[i] = CTime::GetCurrentTime();
#define TOC(i) EndTime = CTime::GetCurrentTime(); TimeSpan[i] += (EndTime - StartTime[i]);
#define OUTPUT_TOC(k) TRACE("TIMER : timer %i returned %i seconds\n",k,TimeSpan[k].GetTotalSeconds());
#else
#define TIC(i)
#define TOC(i)
#define OUTPUT_TOC(k)
#endif
bool StartedTriangulation;
void NeuralNet::InitNeuralNet(int NumberOfNeuronsUDir,int NumberOfNeuronsVDir, PointList &PtLst,int NetType , LPCTSTR FileName){
// initialize with topology defined by net type
MyPoint MinVals,MaxVals;
int i,j;
Neuron *pN , *pNu , *pNv ;
if (!CheckNetworkTypeValidity(NetType)){
MyFatalError ("NetWorkType given is faulty in NeuralNet constructor");
}
LocationSizeX=LOCATION_ARRAY_SIZE_X;
LocationSizeY=LOCATION_ARRAY_SIZE_Y;
LocationSizeZ=LOCATION_ARRAY_SIZE_Z;
LocationArray = new (Neuron (*[LocationSizeX*LocationSizeY*LocationSizeZ]));
LocationArrayCount = new (int [LocationSizeX*LocationSizeY*LocationSizeZ]);
for (int k=0; k<LocationSizeX*LocationSizeY*LocationSizeZ; k++){
LocationArray[k]=NULL;
LocationArrayCount[k]=0;
}
// allocate memory for location array
LocationLowX=PtLst.MinVals.Pos[0];
LocationHighX=PtLst.MaxVals.Pos[0];
LocationLowY=PtLst.MinVals.Pos[1];
LocationHighY=PtLst.MaxVals.Pos[1];
LocationLowZ=PtLst.MinVals.Pos[2];
LocationHighZ=PtLst.MaxVals.Pos[2];
LocationDeltaX = (LocationHighX-LocationLowX)/LocationSizeX;
LocationDeltaY = (LocationHighY-LocationLowY)/LocationSizeY;
LocationDeltaZ = (LocationHighZ-LocationLowZ)/LocationSizeZ;
if (FileName!=NULL){
if (LoadNetFromFile(FileName)){
NetworkSizeU=Neurons.Size;
NetworkSizeV=0;
Tags=NetType;
ClassifySamplePointList(PtLst);
// more work needed here to detect the network type
}
else MyFatalError("could not read from file in NeuralNet constructor");
}
// growing neural gas with hebian learning
else if ((NetType & NN_NO_TOPOLOGY) &&
(NetType & NN_CAN_GROW_EDGES)){
NetworkSizeU=NumberOfNeuronsUDir;
NetworkSizeV=0;
Tags=NetType;
for (i=0;i<NumberOfNeuronsUDir;i++) {
MyPoint TempPt(PtLst.MinVals,PtLst.MaxVals);
AddNeuron (TempPt);
}
}
// simple self orgenizing map (or growing neural net) with rectangular topology
else if (NetType & NN_RECTANGULAR_TOPOLOGY){
NetworkSizeU=NumberOfNeuronsUDir;
NetworkSizeV=NumberOfNeuronsVDir;
Tags=NetType;
NeuronArray = new (Neuron (*[NumberOfNeuronsUDir*NumberOfNeuronsVDir]));
// first create the neurons
for (i=0;i<NumberOfNeuronsUDir;i++){
for (j=0;j<NumberOfNeuronsVDir;j++){
MyPoint TempPt(PtLst.MinVals,PtLst.MaxVals);
Neuron *TempNeuron = AddNeuron(TempPt); // create a neuron instance
TempNeuron->NeuronIdU=i;
TempNeuron->NeuronIdV=j;
RECTNN(i,j) = TempNeuron;
}
}
// create the edges
for (i=0;i<NumberOfNeuronsUDir;i++){
for (j=0;j<NumberOfNeuronsVDir;j++){
pN=RECTNN(i,j);
if (i != NumberOfNeuronsUDir-1) {
pNu=RECTNN(i+1,j);
Edges.CreateOrRefreshEdge(pN,pNu,EDGE_U_DIR);
}
if (j != NumberOfNeuronsVDir-1) {
pNv=RECTNN(i,j+1);
Edges.CreateOrRefreshEdge(pN,pNv,EDGE_V_DIR);
}
}
}
// handle cyclic conditions in U dir
if (NetType & NN_CYCLIC_U_DIR){
for (j=0;j<NumberOfNeuronsVDir;j++){
pN=RECTNN(NumberOfNeuronsUDir-1,j);
pNu=RECTNN(0,j);
Edges.CreateOrRefreshEdge(pN,pNu,EDGE_U_DIR);
}
}
// handle cyclic conditions in V dir
if (NetType & NN_CYCLIC_V_DIR){
for (i=0;i<NumberOfNeuronsUDir;i++){
pN=RECTNN(i,NumberOfNeuronsVDir-1);
pNv=RECTNN(i,0);
Edges.CreateOrRefreshEdge(pN,pNv,EDGE_V_DIR);
}
}
}
// growing neural gas - only three neurons connected between themselves
else if ((NetType & NN_HAS_TOPOLOGY) &&
(NetType & NN_CAN_GROW_NEURONS) &&
(NetType & NN_CAN_GROW_EDGES) ){
// file support is availiable only for growing neural gas now
NetworkSizeU=4;
NetworkSizeV=0;
Tags=NetType;
MyPoint TempPt1(PtLst.MinVals , PtLst.MaxVals);
MyPoint TempPt2(PtLst.MinVals , PtLst.MaxVals);
MyPoint TempPt3(PtLst.MinVals , PtLst.MaxVals);
MyPoint TempPt4 = (TempPt1 + TempPt2 + TempPt3)*(1.0/3);
Neuron *TempNeuron1 = AddNeuron(TempPt1); // create a neuron instance
Neuron *TempNeuron2 = AddNeuron(TempPt2); // create another neuron instance
Neuron *TempNeuron3 = AddNeuron(TempPt3); // create another neuron instance
// Neuron *TempNeuron4 = AddNeuron(TempPt4); // create another neuron instance
// mark boundary neurons as boundary
// TempNeuron1->Tags |= NEURON_ON_BOUNDARY;
// TempNeuron2->Tags |= NEURON_ON_BOUNDARY;
// TempNeuron3->Tags |= NEURON_ON_BOUNDARY;
// create the edges needed
Edge *E12=Edges.CreateOrRefreshEdge(TempNeuron1,TempNeuron2);
Edge *E13=Edges.CreateOrRefreshEdge(TempNeuron1,TempNeuron3);
Edge *E23=Edges.CreateOrRefreshEdge(TempNeuron2,TempNeuron3);
// Edge *E14=Edges.CreateOrRefreshEdge(TempNeuron1,TempNeuron4);
// Edge *E24=Edges.CreateOrRefreshEdge(TempNeuron2,TempNeuron4);
// Edge *E34=Edges.CreateOrRefreshEdge(TempNeuron3,TempNeuron4);
// now create the faces
// Faces.CreateOrRefreshFace(E12,E23,E13);
// Faces.CreateOrRefreshFace(E12,E14,E24);
// Faces.CreateOrRefreshFace(E23,E24,E34);
// Faces.CreateOrRefreshFace(E13,E14,E34);
// close manifold
// Faces.CreateOrRefreshFace(E13,E12,E23);
// init normals to rando vaues (intialized)
/*
NetworkSizeU=4*10;
NetworkSizeV=0;
Tags=NetType;
for (i=0;i<10;i++){
MyPoint TempPt1((PtLst.MinVals+PtLst.MaxVals)*0.5-(PtLst.MaxVals-PtLst.MinVals)*0.4 ,(PtLst.MinVals+PtLst.MaxVals)*0.5+(PtLst.MaxVals-PtLst.MinVals)*0.4);
MyPoint TempPt2((PtLst.MaxVals-PtLst.MinVals)*0.1 , (PtLst.MaxVals-PtLst.MinVals)*0.1);
TempPt2=TempPt2+TempPt1;
MyPoint TempPt3((PtLst.MaxVals-PtLst.MinVals)*0.1 , (PtLst.MaxVals-PtLst.MinVals)*0.1);
TempPt3=TempPt3+TempPt1;
MyPoint TempPt4 = (TempPt1 + TempPt2 + TempPt3)*(1.0/3);
Neuron *TempNeuron1 = AddNeuron(TempPt1); // create a neuron instance
Neuron *TempNeuron2 = AddNeuron(TempPt2); // create another neuron instance
Neuron *TempNeuron3 = AddNeuron(TempPt3); // create another neuron instance
Neuron *TempNeuron4 = AddNeuron(TempPt4); // create another neuron instance
// mark boundary neurons as boundary
TempNeuron1->Tags |= NEURON_ON_BOUNDARY;
TempNeuron2->Tags |= NEURON_ON_BOUNDARY;
TempNeuron3->Tags |= NEURON_ON_BOUNDARY;
// create the edges needed
Edge *E12=Edges.CreateOrRefreshEdge(TempNeuron1,TempNeuron2);
Edge *E13=Edges.CreateOrRefreshEdge(TempNeuron1,TempNeuron3);
Edge *E23=Edges.CreateOrRefreshEdge(TempNeuron2,TempNeuron3);
Edge *E14=Edges.CreateOrRefreshEdge(TempNeuron1,TempNeuron4);
Edge *E24=Edges.CreateOrRefreshEdge(TempNeuron2,TempNeuron4);
Edge *E34=Edges.CreateOrRefreshEdge(TempNeuron3,TempNeuron4);
// now create the faces
// Faces.CreateOrRefreshFace(E12,E23,E13);
Faces.CreateOrRefreshFace(E12,E14,E24);
Faces.CreateOrRefreshFace(E23,E24,E34);
Faces.CreateOrRefreshFace(E13,E14,E34);
// init normals to rando vaues (intialized)
}
*/
}
else {
Initialized=false;
MyFatalError("unknown topology type in NeuralNet constructor");
}
this->Tags = NetType;
Initialized=true;
}
NeuralNet::NeuralNet(){
DispListNumber=0;
Tags=NN_NOT_INITIALIZED; // combination of NeuralNetworkTypes
NeuronArray=NULL; // used only for rectangular topology SOM
Initialized=false;
NetworkSizeU=-1;
NetworkSizeV=-1;
NeuronIdMaxCounter=0;
LocationSizeX=0;
LocationSizeY=0;
LocationSizeZ=0;
LocationLowX=0;
LocationLowY=0;
LocationLowZ=0;
LocationHighX=0;
LocationHighY=0;
LocationHighZ=0;
LocationDeltaX=0;
LocationDeltaY=0;
LocationDeltaZ=0;
LocationArray=NULL;
LocationArrayCount=NULL;
}
NeuralNet::~NeuralNet(){
// delete the display list -I'll do it later
if (NeuronArray) delete [] NeuronArray;
if (LocationArray) delete [] LocationArray;
if (LocationArrayCount) delete [] LocationArrayCount;
}
int NeuralNet::TrainNeuralGasByPointList (PointList &PtLst, int BaseIteration, int RunLength, RealType EpsInit, RealType EpsFinal, RealType LambdaInit, RealType LambdaFinal, int MaximalEdgeAgeInit,int MaximalEdgeAgeFinal){
if (PtLst.Size == 0) {
TRACE ("TrainNeuralGasByPointList: no points to train");
return false;
}
if (EpsInit<0.0 || EpsFinal <0.0 || LambdaInit<0.0 || LambdaFinal<0.0 || MaximalEdgeAgeInit < 0 || MaximalEdgeAgeFinal < 0){
TRACE ("TrainNeuralGasByPointList: function parameters are are not in possible range");
return false;
}
if ( !((Tags & NN_HAS_TOPOLOGY) || (Tags & NN_RECTANGULAR_TOPOLOGY) || (Tags & NN_NO_TOPOLOGY)) ){
// neural gas can train all topological types.
TRACE ("TrainNeuralGasByPointList: cannot train this type of topology");
return false;
}
int MaximalEdgeAge;
int Index = BaseIteration % PtLst.Size;
for (int i=0; i<RunLength; i++){
/*
#ifdef MY_DEBUG
TRACE("Trained Point: %lf,%lf,%lf\n",CurrentSamplePoint.Pos[0],CurrentSamplePoint.Pos[1],CurrentSamplePoint.Pos[2]);
#endif
*/
TrainNeuralGasBySinglePoint(*PtLst.Array[Index],
EXP_DECAY(EpsInit,EpsFinal,i,RunLength),
EXP_DECAY(LambdaInit,LambdaFinal,i,RunLength), BaseIteration+i);
// if neural network can grow edges, it can also delete old edges
if (Tags & NN_CAN_GROW_EDGES){
if (Tags & NN_RECTANGULAR_TOPOLOGY) // if we have growin grid characteristics change net type to neural gas - since edges will be deleted
ChangeNetType(NN_NO_TOPOLOGY | NN_CAN_GROW_EDGES , PtLst);
MaximalEdgeAge = (int) (EXP_DECAY(MaximalEdgeAgeInit,MaximalEdgeAgeFinal,i,RunLength));
DelOldEdgesAndCascadeDelete(MaximalEdgeAge,false);
}
Index =(Index+1) % PtLst.Size;
}
return true;
}
void NeuralNet::TrainNeuralGasBySinglePoint (SamplePoint &Pt, RealType Eps, RealType Lambda ,int CurrentIteration , bool UseOnlyNeuronsWithFacesForNormalCalculation){
if (Neurons.Size==0) return;
//sort all neurons by increasing distance
NeuronSortByWinners(Pt,0,true);
Neuron *Nwin, *Nwin2, *Nwin3;
Nwin = Neurons.Head;
Nwin2 = Neurons.Head->Next;
Nwin3 = Neurons.Head->Next->Next;
// the boolean parameter marks if a face exists between the three winner neurons
bool FaceExists = false;
// update edge (Neurons are already ordered...) if the network can grow edges
if (Tags & NN_CAN_GROW_EDGES){
// create or refresh the edge between the two winners
Edge *E12 = Edges.CreateOrRefreshEdge(Nwin,Nwin2);
// now check if the two other edges exist.
// if so, we can create a face
Edge *E13 = Edges.FindEdge (Nwin,Nwin3);
Edge *E23 = Edges.FindEdge (Nwin2,Nwin3);
if (E12!=NULL && E13!=NULL && E23!=NULL){
Faces.CreateOrRefreshFace (E12,E13,E23);
FaceExists=true;
}
// age other edges from the winner neuron
Edges.Age(Nwin);
}
//modifiy each neuron
int k=0;
// adapt the normal
MyPoint Pt_N1,NormalDirection;
// normal is updated in the direction of the point
if (!UseOnlyNeuronsWithFacesForNormalCalculation || FaceExists){
Pt_N1 = Pt - *Nwin;
NormalDirection = Nwin->CalcNormalUsing3Points(Nwin2,Nwin3);
double Dir = NormalDirection * Pt_N1;
if (Dir<=0.0) NormalDirection = - NormalDirection;
}
else{
NormalDirection.Pos[0]=0.0;
NormalDirection.Pos[1]=0.0;
NormalDirection.Pos[2]=0.0;
}
Neuron *It=Neurons.Head;
do{
if (Pt.Weight == 1.0){
RealType d = It->PointDist;
It->ModifyPosBySamplePoint(Eps*exp(-k/Lambda),Pt);
//It->ModifyPosBySamplePoint(Eps*exp(-(Pt-*It)*(Pt-*It)/Lambda),Pt);
}
else
It->ModifyPosBySamplePoint(1.0-pow(1.0-Eps*exp(-k/Lambda),Pt.Weight),Pt);
//It->ModifyPosBySamplePoint(1.0-pow(1.0-Eps*exp(-(Pt-*It)*(Pt-*It)/Lambda),Pt.Weight),Pt);
//new corrected version
MyPoint NewNormal = It->Normal + ((NormalDirection-It->Normal) * (Eps*exp(-k/Lambda)));
//old problematic version
//MyPoint NewNormal = It->Normal + (NormalDirection * (Eps*exp(-k/Lambda)));
//MyPoint NewNormal = It->Normal + (NormalDirection * (Eps*exp(-(Pt-*It)*(Pt-*It)/Lambda)));
// now normalize
NewNormal = NewNormal * (1.0 / ~NewNormal);
if (NewNormal.IsFinite() )
It->Normal = NewNormal;
//It->UpdateNormalUsingPCA (Pt,0.1);
//It->CalcNormalUsingSemiMinimalBoundingCone();
// decide on normal calculation method (the code above)
It->LastUpdateAge=CurrentIteration;
k++;
It=It->Next;
} while (It!=Neurons.Head);
}
ostream& operator << ( ostream& os, NeuralNet &NNet ){
// output net characteristics
os << "Tags " << NNet.Tags <<" " << NNet.NetworkSizeU <<" "<< NNet.NetworkSizeV << "\n";
// output all neurons
Neuron *It=NNet.Neurons.Head;
if (NNet.Neurons.Head!=NULL) do{
os << *It;
It=It->Next;
} while (It!=NNet.Neurons.Head);
// output all edges
Edge *TempEdge = NNet.Edges.Head;
if (NNet.Edges.Head != NULL) do{
os << *TempEdge;
TempEdge=TempEdge->Next;
} while (TempEdge!=NNet.Edges.Head);
return os;
}
istream& operator >> ( istream& is, NeuralNet &NNet ){
char c;
while (!is.eof()){ // there may be a bug in here
c=is.peek();
switch (c){
case 'N' : // neuron at input
Neuron *N = NNet.AddNeuron();
is >> *N;
NNet.AddOrRemoveNeuronToLocationArray(N);
}
is>>ws; // this way the eof flag wil be set...
}
return is;
}
ostream& OutputToIritFormat(ostream& os, NeuralNet &NNet ){
// this code outputs a rectangular SOM neural net as a cubic B-Spline Surface wih open hand conditions (good for initial parameterization)
if (NNet.NeuronArray !=NULL &&
NNet.NetworkSizeU > 0 &&
NNet.NetworkSizeV > 0 ){
os <<"[OBJECT Neuralnet\n\t[SURFACE BSPLINE " <<NNet.NetworkSizeU << " " <<NNet.NetworkSizeV << " 4 4 E3\n";
//create U knot vector
os <<"\t\t[KV 0 0 0";
for (int i=0; i<NNet.NetworkSizeU - 2 ; i++){
os <<" "<< ((double)i / (NNet.NetworkSizeU-3) );
}
os <<" 1 1 1]\n";
//create V knot vector
os <<"\t\t[KV 0 0 0";
for (int i=0; i<NNet.NetworkSizeV-2 ; i++){
os <<" "<< ((double)i / (NNet.NetworkSizeV-3) );
}
os <<" 1 1 1]\n";
for (int j=0; j<NNet.NetworkSizeV ; j++){
for (int i=0; i<NNet.NetworkSizeU ; i++){
Neuron *It= NNet.NeuronArray[(i)*(NNet.NetworkSizeV)+(j)];
os <<" [ " << (MyPoint) (*It) ;
os.seekp( -2, ios::cur ); // eat last new line characer
os <<" ]\n";
}
os << "\n";
}
os<<" ]\n]\n";
}
else{
// this code outputs the neurons as point list to Irit
os << "[OBJECT NONE\n[POINTLIST " <<NNet.Neurons.Size <<"\n";
// output all neurons
Neuron *It = NNet.Neurons.Head;
if (NNet.Neurons.Head) do{
os <<" [ " << (MyPoint) (*It) ;
os.seekp( -2, ios::cur ); // eat last new line characer
os <<" ]\n";
It=It->Next;
} while (It != NNet.Neurons.Head);
os<<"]\n]\n";
}
return os;
}
void NeuralNet::RenumberNeurons(){
// this function renumbers the neurons again to give them consecutive ID numbers
// and changes NeuronIdMaxCounter accordingly
// if the net has rectangular topology then traverse the neurons using the rectanguar data array
NeuronIdMaxCounter=0;
if (Tags & NN_RECTANGULAR_TOPOLOGY){
for (int i=0; i<NetworkSizeU; i++) for (int j=0; j<NetworkSizeV; j++){
Neuron *It= RECTNN(i,j);
It->NeuronId = 1 + j + i*NetworkSizeV;
NeuronIdMaxCounter++;
It->PointDist = It->NeuronId;
}
// now sort the neurons using this index since we want to maintain rectangular order in the output
Neurons.Sort(0);
}
else{ // other topology network
Neuron *It = Neurons.Head;
if (Neurons.Head) do{
It->NeuronId = (++NeuronIdMaxCounter);
It=It->Next;
} while (It != Neurons.Head);
}
}
ostream& OutputToVrmlFormat(ostream& os, NeuralNet &NNet ){
os << "#VRML V1.0 ascii\n#date 11 October 1996\n";
// put some comments about the mesh
if (NNet.Tags & NN_RECTANGULAR_TOPOLOGY){
os<<"#@ rectangular grid of size " << NNet.NetworkSizeU << "," << NNet.NetworkSizeV << "\n";
if (NNet.Tags & NN_CYCLIC_U_DIR)
os<< "#@Grid is Cyclic in the U direction \n";
if (NNet.Tags & NN_CYCLIC_V_DIR)
os<< "#@Grid is Cyclic in the V direction \n";
}
else
os<<"#@ non rectangular grid with "<< NNet.Neurons.Size << " Neurons and " << NNet.Faces.Size << " faces \n";
os <<"Separator {\n\n DirectionalLight { direction 0 0 -1 }\n Separator { # Object Separator \n Material { emissiveColor 0.3 0.8 0.2 }\n Material { emissiveColor 0.752941 0.752941 0.752941 }\n";
// first make sure that the neurons are renumbered preperly
NNet.RenumberNeurons();
// output all neurons as points with additional information
os<<"# point format is : x y z, comment_mark number_of_edges_connected number_of_faces_connected\n";
os<<" Coordinate3\n {\n point [\n\n";
Neuron *It = NNet.Neurons.Head;
if (NNet.Neurons.Head) do{
os <<" ";
os << (MyPoint) (*It) ;
os.seekp( -2, ios::cur ); // eat last new line character
// the last neuron is not terminated with a comma
if (It->Next!= NNet.Neurons.Head){
os << ","; // add , seperator
}
os << " #@ " << It->EdgeCounter ; // add a vrml comment describing the vertex edge velance
int FaceVelance;
// since we do not hold faces for rectangular topology, we need to handle it differently
if (NNet.Tags & NN_RECTANGULAR_TOPOLOGY){
switch (It->EdgeCounter){
case 2:
FaceVelance=1;
break;
case 3:
FaceVelance=2;
break;
case 4:
FaceVelance=4;
break;
default:
MyFatalError("OutputToVrmlFormat :: bad number of eges for neuron");
}
}
else{
FaceVelance=It->FaceCounter;
}
os << " " << FaceVelance ; // add a vrml comment describing the vertex face velance
os << "\n"; // terminate line
It=It->Next;
} while (It != NNet.Neurons.Head);
os<<" ] # End of points\n } # End of coords \n";
// in rectangular topology output the boundary as a set of edges
if (NNet.Tags & NN_RECTANGULAR_TOPOLOGY){
NNet.OutputRectangularTopologyBoundaryToVRML(os);
}
os<<" IndexedFaceSet\n {\n coordIndex [\n\n";
// if this is a rectangular topology network then declare its size in a remark and create traingular faces for output
if (NNet.Tags & NN_RECTANGULAR_TOPOLOGY){
NNet.OutputRectangularTopologyFacesToVRML(os);
}
else{
Face *F = NNet.Faces.Head;
if (NNet.Faces.Head) do{
os <<" ";
OutputToVrmlFormat(os,(*F));
//os.seekp( -2, ios::cur ); // eat last new line character
//os <<",\n";
F=F->Next;
} while (F != NNet.Faces.Head);
}
os.seekp( -3, ios::cur ); // eat last new line character and comma
os <<"\n";
os <<" ] # End of coord index\n } # End of indexedfaceset\n\n } # End of object separator\n\n } # End of main separator \n";
return os;
}
ostream& NeuralNet::OutputRectangularTopologyFacesToVRML(ostream& os){
// the function simulates the rectangular faces of the grid and outputs them in vrml format
int UCyclicIndexCorrection = (Tags & NN_CYCLIC_U_DIR)?0:-1;
int VCyclicIndexCorrection = (Tags & NN_CYCLIC_V_DIR)?0:-1;
for (int i=0; i < (NetworkSizeU + UCyclicIndexCorrection) ; i++)
for (int j=0; j < (NetworkSizeV + VCyclicIndexCorrection) ; j++){
Neuron *N1, *N2, *N3, *N4;
N1=RECTNN(i,j);
N2=RECTNN((i+1) % NetworkSizeU,j);
N3=RECTNN((i+1) % NetworkSizeU,(j+1) % NetworkSizeV);
N4=RECTNN(i,(j+1) % NetworkSizeV);
os <<" ";
OutputToVrmlFormat(os,N1,N2,N3,N4);
}
return os;
}
ostream& NeuralNet::OutputRectangularTopologyBoundaryToVRML(ostream& os){
// the function traverses the boundaries of the mesh and outputs the cycle of vertices creating it
int UCyclicIndexCorrection = (Tags & NN_CYCLIC_U_DIR)?1:0;
int VCyclicIndexCorrection = (Tags & NN_CYCLIC_V_DIR)?1:0;
// if cyclic conditions in both directions, then do nothing (no boundary)
if ((Tags & NN_CYCLIC_U_DIR) && (Tags & NN_CYCLIC_V_DIR))
return os;
// output the boundary as a strip of points
os << " # Grid Boundary is represented as by a set of point numbers terminated by -1\n";
os << " #@ Boundary{ \n";
if (!(Tags & NN_CYCLIC_U_DIR)){
os <<" #@ ";
for (int i=0; i < (NetworkSizeU + UCyclicIndexCorrection) ; i++) {
Neuron *N;
N=RECTNN(i% NetworkSizeU,0);
os << N->NeuronId-1 <<", ";
}
os << "-1\n"; // terminate boundary
}
if (!(Tags & NN_CYCLIC_V_DIR)){
os <<" #@ ";
for (int j=0; j < (NetworkSizeV + VCyclicIndexCorrection) ; j++) {
Neuron *N;
N=RECTNN(NetworkSizeU-1,j % NetworkSizeV);
os << N->NeuronId-1 <<", ";
}
os << "-1\n"; // terminate boundary
}
if (!(Tags & NN_CYCLIC_U_DIR)){
os <<" #@ ";
for (int i=0; i < (NetworkSizeU + UCyclicIndexCorrection) ; i++) {
Neuron *N;
N=RECTNN(i% NetworkSizeU,NetworkSizeV-1);
os << N->NeuronId-1 <<", ";
}
os << "-1\n"; // terminate boundary
}
if (!(Tags & NN_CYCLIC_V_DIR)){
os <<" #@ ";
for (int j=0; j < (NetworkSizeV + VCyclicIndexCorrection) ; j++) {
Neuron *N;
N=RECTNN(0,j % NetworkSizeV);
os << N->NeuronId-1 <<", ";
}
os << "-1\n"; // terminate boundary
}
os << " #@ } # end of boundary\n";
return os;
}
bool NeuralNet::CheckNetworkTypeValidity(int NewNetType){
bool result=false;
// neural gas - with or without hebian learning
result = result ||
(NewNetType & NN_NO_TOPOLOGY) &&
!(NewNetType & (
NN_RECTANGULAR_TOPOLOGY |
NN_CYCLIC_U_DIR |
NN_CYCLIC_V_DIR |
NN_CAN_GROW_NEURONS));
// self orgenizing map (rect topology) or growing grid
result = result ||
(NewNetType & NN_RECTANGULAR_TOPOLOGY) &&
!(NewNetType & (
NN_NO_TOPOLOGY |
NN_HAS_TOPOLOGY)) &&
~((NewNetType & (NN_CAN_GROW_NEURONS)) ^
(NewNetType & (NN_CAN_GROW_EDGES )) );
// self orgenizing feature map (arbitrary topology)
// or growing neural gas.
result = result ||
(NewNetType & NN_HAS_TOPOLOGY) &&
!(NewNetType & (
NN_NO_TOPOLOGY|
NN_RECTANGULAR_TOPOLOGY|
NN_CYCLIC_U_DIR|
NN_CYCLIC_V_DIR)) &&
~((NewNetType & (NN_CAN_GROW_NEURONS)) ^
(NewNetType & (NN_CAN_GROW_EDGES )) );
return(result);
}
bool NeuralNet::ChangeNetType(int NewNetType, PointList &PtLst){
if (!CheckNetworkTypeValidity(NewNetType)){
TRACE ("NetWorkType given is faulty in function ChangeNetType");
return false;
}
// in case the network now is neural gas
if ((Tags & NN_NO_TOPOLOGY) &&
(Tags & NN_CAN_GROW_EDGES)){
if (NewNetType & NN_RECTANGULAR_TOPOLOGY){
TRACE("NeuralNet::ChangeNet - Typecannot change from non rectangular topology to rectangular in function ChangeNetType");
return false;
}
else if (NewNetType & NN_HAS_TOPOLOGY){
TRACE ("NeuralNet::ChangeNet - changing from no topology to other topology - deleting unconnected neurons");
DeleteDisconnectedNeurons();
Tags=NewNetType;
return true;
}
else {
TRACE ("NeuralNet::ChangeNet - new net type not supported");
return false;
}
}
// in case the network now has rectangular topology
else if (Tags & NN_RECTANGULAR_TOPOLOGY){
// in case cyclic conditions have been introduced
// add the appropriate edges
if ((NewNetType & NN_CYCLIC_U_DIR) &&
!(Tags & NN_CYCLIC_U_DIR)){
for (int j=0;j<NetworkSizeV;j++){
Neuron *pN,*pNu;
pN=NeuronArray[(NetworkSizeU-1)*NetworkSizeV+j];
pNu=NeuronArray[j];
Edges.CreateOrRefreshEdge(pN,pNu,EDGE_U_DIR);
}
}
if ((NewNetType & NN_CYCLIC_V_DIR) &&
!(Tags & NN_CYCLIC_V_DIR)){
for (int i=0;i<NetworkSizeU;i++){
Neuron *pN,*pNv;
pN=NeuronArray[i*NetworkSizeV+NetworkSizeV-1];
pNv=NeuronArray[i*NetworkSizeV];
Edges.CreateOrRefreshEdge(pN,pNv,EDGE_V_DIR);
}
}
// if cyclic conditions have been removed, remove the
// the appropriate edges
if ((Tags & NN_CYCLIC_U_DIR) &&
!(NewNetType & NN_CYCLIC_U_DIR)){
for (int j=0;j<NetworkSizeV;j++){
Neuron *pN,*pNu;
pN=NeuronArray[(NetworkSizeU-1)*NetworkSizeV+j];
pNu=NeuronArray[j];
Edges.DelEdge(pN,pNu);
}
}
if ((Tags & NN_CYCLIC_V_DIR) &&
!(NewNetType & NN_CYCLIC_V_DIR)){
for (int i=0;i<NetworkSizeU;i++){
Neuron *pN,*pNv;
pN=NeuronArray[i*NetworkSizeV+NetworkSizeV-1];
pNv=NeuronArray[i*NetworkSizeV];
Edges.DelEdge(pN,pNv);
}
}
// in case rectangular topology is deleted
if ( (NewNetType & NN_NO_TOPOLOGY) |
(NewNetType & NN_HAS_TOPOLOGY) ){
// delete the helper array
delete [] NeuronArray;
NeuronArray=NULL; //we won't need it anymore
// now delete U and V direction Tags from the edges
Edge *It =Edges.Head;
if (Edges.Head!=NULL) do{
It->Tag &= ~(EDGE_U_DIR|EDGE_V_DIR);
It=It->Next;
} while (It != Edges.Head);
// reset the point list weights
PtLst.ResetPointWeight();
//networks size counting is now not in two directions
NetworkSizeU = NetworkSizeU*NetworkSizeV;
NetworkSizeV = 0;
}
Tags=NewNetType;
TRACE ("NeuralNet::ChangeNet - modifying rectangular topology");
return true;
}
// in case of growin neural gas of self orgenizing map (arbitrary topology)
else if (Tags & NN_HAS_TOPOLOGY){
if (NewNetType & NN_RECTANGULAR_TOPOLOGY){
TRACE("NeuralNet::ChangeNet - cannot change from non rectangular topology to rectangular in function ChangeNetType");
return false;
}
else{
TRACE("NeuralNet::ChangeNet - changing network type from has topology to other network type");
Tags=NewNetType;
return true;
}
}
TRACE("NeuralNet::ChangeNet - new net type not found");
Tags=NewNetType;
return false;
}
void NeuralNet::NeuronSortByWinners(SamplePoint &Pt,int k, bool ClassifySamplePoint , Edge *E){
// reorders the neuron list so that the first k neurons nearest to the sampled point are first (sorted by distance)
// if k is zero it means the whole array must be sorted
if (Neurons.Size==0) return;
if (k<0) MyFatalError(" NeuronSortByWinners : parameter k can't be negative");
#ifdef MY_DEBUG
Neuron *DebugWinners[3]={NULL,NULL,NULL};
#endif
// if we are looking for up to 3 neigbours - do it fast
if (k<=3 && k<Neurons.Size && k>0 && !ClassifySamplePoint){
TIC(8)
int HitCounter = 0;
int SearchRadius = 0;
int IndexX = (int) ((Pt.Pos[0] - LocationLowX) / LocationDeltaX);
int IndexY = (int) ((Pt.Pos[1] - LocationLowY) / LocationDeltaY);
int IndexZ = (int) ((Pt.Pos[2] - LocationLowZ) / LocationDeltaZ);
while (HitCounter <= k){
HitCounter = 0;
SearchRadius++;
for (int i= max(IndexX-SearchRadius,0) ; i<= min(LocationSizeX-1,IndexX+SearchRadius) ; i++){
for (int j= max(IndexY-SearchRadius,0) ; j<= min(LocationSizeY-1,IndexY+SearchRadius) ; j++){
for (int k= max(IndexZ-SearchRadius,0) ; k<= min(LocationSizeZ-1,IndexZ+SearchRadius) ; k++){
Neuron *N = NEURON_LOCATION(i,j,k);
while (N != NULL){
HitCounter++;
N->CalcDistFromSamplePoint(Pt);
Neurons.Remove(N,false);
Neurons.PushBack(*N,false);
N=N->NextInLoactionStuck;
}
}
}
}
}
// reset the start position of the sort to the first neuron we found
Neuron *SortHead=Neurons.Head;
for (int i=0; i<HitCounter; i++)
SortHead =SortHead->Prev;
//sort by increasing distance
Neurons.Sort(k,SortHead,HitCounter);
#ifdef MY_DEBUG
DebugWinners[0] = Neurons.Head;
DebugWinners[1] = Neurons.Head->Next;
DebugWinners[2] = Neurons.Head->Next->Next;
ASSERT (DebugWinners[0]->PointDist <= DebugWinners[1]->PointDist);
ASSERT (DebugWinners[1]->PointDist <= DebugWinners[2]->PointDist);
#endif
TOC(8)
}
// debug check - look if three first neurons are the same using both methods
else {
TIC(9)
Neuron *It = Neurons.Head;
//update distances
do{
RealType d = It->CalcDistFromSamplePoint(Pt);
It=It->Next;
}while (It!=Neurons.Head);
//sort by increasing distance
Neurons.Sort(k);
#ifdef MY_DEBUG
if (DebugWinners[0]!=NULL && DebugWinners[0] !=Neurons.Head)
MyFatalError ("did not find winner 1 correctly");
if (DebugWinners[1]!=NULL && DebugWinners[1] !=Neurons.Head->Next)
MyFatalError ("did not find winner 2 correctly");
if (DebugWinners[2]!=NULL && DebugWinners[2] !=Neurons.Head->Next->Next)
MyFatalError ("did not find winner 3 correctly");
#endif
TOC(9)
}
if (ClassifySamplePoint) // if classification is requested do it
Pt.Classification= Neurons.Head;
}
int NeuralNet::CalcTopologicalDistance (Neuron *N,int k,bool UseOnlyConnectedEdges){
//calculate the toplogical distance of all neurons using the new data and sort them by it, distances up to k are calculated
// we use simple BFS algorithm on the graph
// the function returns the number of neurons that fall under distance k
// when UseOnlyConnectedEdges is true, only edges with one or more faces connected to them are used
if (Neurons.Size==0) return (-1); // -1 in output means an error
if (k<0) MyFatalError(" CalcTopologicalDistance : parameter k can't be negative");
RealType MaxDist=Neurons.Size*2; // topological distance can't get so high
//init distances
Neuron *It=Neurons.Head;
do{
It->PointDist=MaxDist;
It=It->Next;
} while (It != Neurons.Head);
//search for initial neuron from the list
// put it at the back of the list and set the Iterator to it
// point to the last elemnt (our first neuron
N->PointDist=0; // initial neuron distance is 0
Neurons.Remove(N,false);
Neurons.PushBack(*N,false);
It=N;