-
Notifications
You must be signed in to change notification settings - Fork 1
/
TreecloudFunctions.py
1367 lines (1223 loc) · 59.2 KB
/
TreecloudFunctions.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
#!/usr/sfw/bin/python
import sys, os, re, string, time, random
from math import *
#=====================#
# TREECLOUD FUNCTIONS #
#=====================#
#####################################################
# Copyright 2008-2023 Philippe Gambette
#
# This file is part of TreeCloud v1.5beta (13/04/2023).
#
# TreeCloud 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 3 of the License, or
# (at your option) any later version.
#
# TreeCloud 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 TreeCloud. If not, see <http://www.gnu.org/licenses/>.
#
# For more information:
# http://www.treecloud.org
#####################################################
# Return the input string where all punctuation signs have been replaced by spaces.
def removePunct(line):
new_string = ''
for char in line:
if char=="_":
new_string = new_string+char
else :
if char in string.punctuation:
new_string = new_string+" "
else :
new_string = new_string+char
return new_string
# Return the input string where all punctuation signs have been replaced by spaces.
def doubleAntislash(line):
new_string = ''
for char in line:
if char=='\\':
new_string = new_string+"\\\\"
else :
new_string = new_string+char
return new_string
# Open a text file and put into a 2-element table:
# -> a table containing the sequence of all words in the text
# -> a dict containing all distinct words of the text with associated nb of occurrences
# * filename: string
# * sepchar: string, used to separate cooccurrence windows, will not be added to wordlist
def openText(filename,sepchar):
fd = open(filename,"r")
lines = fd.readlines()
wordlist={}
text=[]
i=0
#------------------------------
#go through the text to extract the words, store them in dict "wordlist" with frequencies
#and in table "text" in the order they appear
#------------------------------
for line in lines:
remaining = line;
remaining = removePunct(remaining);
while len(remaining)>2 :
word=""
#res=re.search("^[ '.,:;?!()-]*([a-zA-Z0-9]+)([ '.,:;?!()-].*)",remaining)
res=re.search("^[ ]*([^ ]+)(.*)",remaining)
if res:
remaining=res.group(2)
word=res.group(1).lower()
res=re.search("(.*)\n",word)
if res:
word=res.group(1)
#print "Treating word '"+word+"'."
else:
#print "Not treating '"+remaining+"'."
res=re.search("^[ '.,:;?!()-]*([a-zA-Z0-9]+)",remaining)
if res:
remaining=""
word=res.group(1).lower()
else:
remaining=""
word=""
if word!="":
#print i,word
text.append(word)
if word!=sepchar:
i+=1
if word in wordlist:
wordlist[word]+=1
else:
wordlist[word]=1
#print word,wordlist[word]
fd.close()
results=[]
results.append(text)
results.append(wordlist)
return results
# Open a distance matrix stored in a csv file and put into a 2-element table:
# -> names is a string list
# -> matrix is a real matrix
# * filename: string
def openMatrix(filename):
fd = open(filename,"r")
lines = fd.readlines()
matrix=[]
names=[]
i=0
for line in lines:
if i>0:
j=0
res=re.search("([^;]*);(.*)",line)
matrixline=[]
while res:
line=res.group(2)
if j>0:
matrixline.append(res.group(1))
else:
names.append(res.group(1))
j+=1
res=re.search("([^;]*);(.*)",line)
matrixline.append(line)
matrix.append(matrixline)
i+=1
#Transform strings to reals
realmatrix=[]
for i in range(0,len(matrix)):
matrixrow=matrix[i]
realmatrixrow=[]
for j in range(0,len(matrixrow)):
if matrix[i][j]=='':
realmatrixrow.append(float(matrix[j][i]))
else :
realmatrixrow.append(float(matrix[i][j]))
realmatrix.append(realmatrixrow)
print(realmatrix)
print(names)
fd.close()
result=[]
result.append(names)
result.append(realmatrix)
return result
# Open a dict stored in a csv file and returns a dict
# * filename: string
def openDict(filename):
fd = open(filename,"r")
lines = fd.readlines()
result={}
for line in lines:
res=re.search("([^;]*);(.*)",line.lower())
if res:
result[res.group(1)]=res.group(2)
fd.close()
return result
# Open a dict stored in a csv file and returns a dict
# * filename: string
def createConcordance(text,filename,left,right):
fd = open(filename,"r")
output = open(filename+"conc.txt","w")
lines = fd.readlines()
result={}
mode=1;
if mode==1:
# for each word in the file, find its concordances, one after the other
for line in lines:
res=re.search("(.*$)",line.lower())
if res:
word=res.group(1)
print("Looking for -"+word+"-")
for i in range(0,len(text)):
if text[i]==word:
chaine=""
j=i-left
if j<0:
j=0
while (j<i+right+1) and (j<len(text)):
chaine=chaine+" "+text[j]
j=j+1
print(chaine)
output.writelines(chaine+" aaaaa\n")
else:
# find the concordances in the text of all words, following their order of appearance
allWords=[]
for line in lines:
res=re.search("(.*$)",line.lower())
if res:
word=res.group(1)
allWords.append(word)
for i in range(0,len(text)):
for word in allWords:
if text[i]==word:
chaine=""
j=i-left
if j<0:
j=0
while (j<i+right+1) and (j<len(text)):
chaine=chaine+" "+text[j]
j=j+1
print(chaine)
output.writelines(chaine+" aaaaa\n")
fd.close()
output.close()
return result
# Returns a dict freqs, which associates for any n (in decreasing order):
# a dict of all words which appeared n times
def sortByFrequency(wordlist):
freqs={}
words=list(wordlist.keys())
words.sort()
for word in words:
val=wordlist[word]
if val in freqs:
freqs[val][word]=1
else :
freqs[val]={}
freqs[val][word]=1
return freqs
# Returns the stoplist words in a table:
def loadStoplist(stoplistfile):
stoplist={}
if os.path.isfile(stoplistfile):
fd = open(stoplistfile,"r")
lines = fd.readlines()
for line in lines:
res=re.search("(.*)\n",line.lower())
if res:
stoplist[(res.group(1).rstrip('\n\r'))]=1
fd.close()
return stoplist
# Save into a csv file (word;nb of occurrences) ordered by decreasing frequency:
# * freqs is a dict which associates for any n: a dict of all words which appeared n times (in decreasing order)
# * stoplist is a table containing loaded stopwords
# * filename is a string
def saveFrequencies(freqs,stoplist,filename):
frequencies=list(freqs.keys())
frequencies.sort()
j=len(frequencies)-1
freqoutput = open(filename,"w")
while j>=0:
theseWords=list(freqs[frequencies[j]].keys())
k=0
while k<len(theseWords):
if not(theseWords[k] in stoplist):
freqoutput.writelines(theseWords[k]+";"+str(frequencies[j])+"\n")
k+=1
j+=-1
freqoutput.close();
# Map every kept word to an integer
# Return a table of 3 elements
# -> a dict which associates an integer to each word
# -> a table which associates a word to each integer between 0 and the nb of kept words -1
# -> a table which associates the nb of occurrences of the corresponding word to each integer...
# * freqs is a dict which associates for any n: a dict of all words which appeared n times (in decreasing order)
# * stoplist is a table containing loaded stopwords
# * minnb is the minimum number of occurrences of the words in the treecloud.
# -1 if not set
# * nbwords is the minimum number of words in the treecloud.
# -1 if not set, 30 if not set and minnb not set
# * sepchar contains a string with a special character used to separate sliding windows (alternative to winsize)
def wordList(freqs,stoplist,minnb,nbwords,sepchar):
theResult=[]
keptWordsId={}
keptWords=[]
keptWordsFrequencies=[]
frequencies=list(freqs.keys())
frequencies.sort()
j=len(frequencies)-1
i=0
while (j>=0) and (frequencies[j]>=minnb):
theseWords=list(freqs[frequencies[j]].keys())
k=0
while k<len(theseWords):
if (theseWords[k]!=sepchar) and (not(theseWords[k] in stoplist) and (i<nbwords)):
keptWordsId[theseWords[k]]=i
keptWordsFrequencies.append(frequencies[j])
#print theseWords[k]
keptWords.append(theseWords[k])
i+=1
#else :
#print theseWords[k],"not kept!"
k+=1
j+=-1
theResult.append(keptWordsId)
theResult.append(keptWords)
theResult.append(keptWordsFrequencies)
#print keptWords
return theResult
# With an imposed list of kept words, map every kept word to an integer
# Return a table of 3 elements
# -> a dict which associates an integer to each word
# -> a table which associates a word to each integer between 0 and the nb of kept words -1
# -> a table which associates the nb of occurrences of the corresponding word to each integer...
# * freqs is a dict which associates for any n: a dict of all words which appeared n times (in decreasing order)
# * thekeptwords is a dict of all kept words
# * sepchar contains a string with a special character used to separate sliding windows (alternative to winsize)
def imposedWordList(freqs,thekeptwords,sepchar):
theResult=[]
keptWordsId={}
keptWords=[]
keptWordsFrequencies=[]
frequencies=list(freqs.keys())
frequencies.sort()
j=len(frequencies)-1
i=0
while j>=0:
theseWords=freqs[frequencies[j]].keys()
k=0
while k<len(theseWords):
#print theseWords[k]
if (theseWords[k]!=sepchar) and (theseWords[k] in thekeptwords):
keptWordsId[theseWords[k]]=i
keptWordsFrequencies.append(frequencies[j])
#print theseWords[k],i,frequencies[j]
keptWords.append(theseWords[k])
i+=1
#print "kept"
#else :
#print theseWords[k],"not kept!"
k+=1
j+=-1
theResult.append(keptWordsId)
theResult.append(keptWords)
theResult.append(keptWordsFrequencies)
return theResult
# Transforms into "" the elements of table text
# which are not present as keys in dict keptWordsId
# * text contains the text stored in a table (each word in a cell)
# * keptWordsId is a dict which associates an integer to each kept word
# * sepchar contains a string with a special character used to separate sliding windows (alternative to winsize)
def filterText(text,keptWordsId,sepchar):
i=0
while i<len(text):
if not(text[i] in keptWordsId):
if text[i]!=sepchar:
text[i]=""
i+=1
return text
# Alter text, by deleting words with probabililty proba
# text: table of strings
# proba: real number
def alterText(text,proba):
i=0
alteredText=[]
while i<len(text):
if random.random()>proba:
alteredText.append(text[i])
i+=1
return alteredText
# Alter text, by deleting x percent of randmoly chosen blocks
# text: table of strings
# percent: integer < 100
def alterBlocks(text,percent):
i=0
alteredText=[]
blockNumbers=random.sample(xrange(0,99,1), int(floor(percent)))
next=-0.0000001
while i<len(text):
if i>next:
next+=len(text)/100
blockNumber=int(floor(i*100.0/len(text)))
selectedBlock=1
for j in blockNumbers:
if blockNumber==j:
selectedBlock=0
if selectedBlock==0:
i=int(floor(i+len(text)/100))
alteredText.append(text[i])
i+=1
return alteredText
# Computes the cooccurrence matrix using sliding windows
# -> returns coocc, a matrix of tables of 4 reals:
# coocc[j][k][0] is the number of windows containing word j and word k
# coocc[j][k][1] is the number of windows not containing word j but containing word k
# coocc[j][k][2] is the number of windows containing word j but not word k
# coocc[j][k][3] is the number of windows containing neither word j nor word k
# * text contains the filtered text (the only words are kept words) stored in a table
# * keptWordsId is a dict which associates an integer to each kept word
# * winSize is the size of the sliding window
# * step is the sliding step of the sliding window
def computeCooccurrence(text,keptWordsId,winSize,step):
#initialize variables
coocc=[]
freqWin=[]
i=0
while i<len(keptWordsId):
coocRow=[]
freqWin.append(0)
j=0
while j<len(keptWordsId):
coocCase=[]
coocCase.append(0);
coocCase.append(0);
coocCase.append(0);
coocCase.append(0);
coocRow.append(coocCase)
j+=1
coocc.append(coocRow)
i+=1
window = {}
i=0
previousPercent=0
while i<len(text)+winSize :
if (100*i/(len(text)+winSize))>previousPercent+5:
previousPercent+=5
#print previousPercent,'%'
#------------------------------
#update the content of the sliding window:
#------------------------------
if i<len(text):
#------------------------------
#the end of sliding window has not reached the end of the text yet
#------------------------------
if text[i]!="":
if text[i] in window:
window[text[i]]+=1
else:
window[text[i]]=1
if i>=winSize:
#------------------------------
#the beginning of the sliding window has not reached the beginning of the text yet
#------------------------------
if text[i-winSize]!="":
window[text[i-winSize]]+=-1
if window[text[i-winSize]]==0 :
del window[text[i-winSize]]
#------------------------------
#update the cooccurrence matrix by using all words in the window
#------------------------------
# window currently contains all the words in the window, as well as their number of occurrences in the window
if i % step==0:
windowWords=list(window.keys());
j=0;
while j<len(windowWords):
k=j+1;
posj=keptWordsId[windowWords[j]]
if window[windowWords[j]]>0:
#print windowWords[j],freqWin[posj],keptWordsFrequencies[posj]
#this window contains the j-th word
freqWin[posj]+=1
while k<len(windowWords):
posk=keptWordsId[windowWords[k]]
coocc[posj][posk][0]+=min(1,window[windowWords[j]])*min(1,window[windowWords[k]])
coocc[posk][posj][0]=coocc[posj][posk][0]
k+=1;
j+=1
i+=1;
j=0
while j<len(freqWin):
k=0;
while k<len(freqWin):
coocc[j][k][1]=freqWin[j]-coocc[j][k][0]
coocc[k][j][2]=coocc[j][k][1]
coocc[k][j][1]=freqWin[k]-coocc[k][j][0]
coocc[j][k][2]=coocc[k][j][1]
coocc[j][k][3]=len(text)+winSize-coocc[j][k][0]-coocc[j][k][1]-coocc[j][k][2]
coocc[k][j][3]=coocc[j][k][3]
k+=1;
j+=1
return coocc
# Computes the cooccurrence matrix according to text windows separated by a special character
# -> returns coocc, a matrix of tables of 4 reals:
# coocc[j][k][0] is the number of windows containing word j and word k
# coocc[j][k][1] is the number of windows not containing word j but containing word k
# coocc[j][k][2] is the number of windows containing word j but not word k
# coocc[j][k][3] is the number of windows containing neither word j nor word k
# * text contains the filtered text (the only words are kept words) stored in a table
# * keptWordsId is a dict which associates an integer to each kept word
# * sepchar contains a string with a special character used to separate sliding windows (alternative to winsize)
def computeCooccurrenceDisjoint(text,keptWordsId,sepchar):
#initialize variables
coocc=[]
freqWin=[]
winnb=0
i=0
while i<len(keptWordsId):
coocRow=[]
freqWin.append(0)
j=0
while j<len(keptWordsId):
coocCase=[]
coocCase.append(0);
coocCase.append(0);
coocCase.append(0);
coocCase.append(0);
coocRow.append(coocCase)
j+=1
coocc.append(coocRow)
i+=1
window = {}
i=0
previousPercent=0
while i<len(text) :
if (100*i/len(text))>previousPercent+5:
previousPercent+=5
#print previousPercent,'%'
#------------------------------
#update the content of the sliding window:
#------------------------------
if text[i]!=sepchar:
if text[i]!="":
window[text[i]]=1
else:
#------------------------------
#update the cooccurrence matrix by using all words in the window
#------------------------------
winnb+=1
windowWords=list(window.keys());
#print winnb,"cooccurrence windows found.",len(windowWords),i
j=0;
while j<len(windowWords):
k=j+1;
posj=keptWordsId[windowWords[j]]
if window[windowWords[j]]>0:
#print windowWords[j],freqWin[posj],keptWordsFrequencies[posj]
freqWin[posj]+=1
while k<len(windowWords):
posk=keptWordsId[windowWords[k]]
coocc[posj][posk][0]+=1
coocc[posk][posj][0]=coocc[posj][posk][0]
k+=1;
j+=1
window = {}
i+=1;
if text[i-1]!=sepchar:
winnb+=1
windowWords=list(window.keys());
j=0;
while j<len(windowWords):
k=j+1;
posj=keptWordsId[windowWords[j]]
if window[windowWords[j]]>0:
freqWin[posj]+=1
while k<len(windowWords):
posk=keptWordsId[windowWords[k]]
coocc[posj][posk][0]+=1
coocc[posk][posj][0]=coocc[posj][posk][0]
k+=1;
j+=1
if winnb>1:
print(winnb,"cooccurrence windows found.")
else:
print(winnb,"cooccurrence window found.")
j=0
while j<len(freqWin):
k=0;
while k<len(freqWin):
coocc[j][k][1]=freqWin[j]-coocc[j][k][0]
coocc[k][j][2]=coocc[j][k][1]
coocc[k][j][1]=freqWin[k]-coocc[k][j][0]
coocc[j][k][2]=coocc[k][j][1]
coocc[j][k][3]=winnb-coocc[j][k][0]-coocc[j][k][1]-coocc[j][k][2]
coocc[k][j][3]=coocc[j][k][3]
k+=1;
j+=1
return coocc
# Computes the distance matrix from the cooccurrence matrix
# -> returns a real matrix
# * coocc contains a cooccurrence matrix where cooc[i][j] is
# in fact a table of 4 reals: O11, O12, O21, O22
# in the formalism by Evert (2005)
# * formula contains a string, the name of the formula to apply
def distanceFromCooccurrence(coocc,formula):
distance=[]
j=0
while j<len(coocc[0]):
k=0
distancerow=[]
while k<len(coocc[0]):
if k==j :
distancerow.append(0)
else :
O11=coocc[j][k][0]
O12=coocc[j][k][1]
O21=coocc[j][k][2]
O22=coocc[j][k][3]
R1=O11+O12
R2=O21+O22
C1=O11+O21
C2=O12+O22
N=R1+R2
E11=R1*C1*1.0/N
E12=R1*C2*1.0/N
E21=R2*C1*1.0/N
E22=R2*C2*1.0/N
if formula=="chisquared":
if R1*R2*C1*C2>0:
distancerow.append(1000-(1.0*N*(O11*O22-O12*O21)*(O11*O22-O12*O21)/(R1*R2*C1*C2)))
else:
distancerow.append(0)
if formula=="mi":
distancerow.append(log(1.0*max(0.0000000000001,O11)/max(0.0000000000001,E11)))
if formula=="liddell":
if C1*C2>0:
distancerow.append(1-(1.0*O11*O22-O12*O21)/(C1*C2))
else :
distancerow.append(0)
if formula=="dice":
distancerow.append(1-2.0*O11/max(0.00000000001,(R1+C1)))
if formula=="jaccard":
distancerow.append(1-1.0*O11/max(0.00000000001,(O11+O12+O21)))
if formula=="gmean":
distancerow.append(1-1.0*O11/(max(0.00000000001,sqrt(R1*C1))))
if formula=="hyperlex":
distancerow.append(1-max(1.0*O11/max(0.00000000001,C1),1.0*O11/max(0.00000000001,R1)))
if formula=="ms":
distancerow.append(1-min(1.0*O11/max(0.00000000001,C1),1.0*O11/max(0.00000000001,R1)))
if formula=="oddsratio":
distancerow.append(1-log((max(0.00000000001,O11*O22/(max(0.00000000001,O12*O21))))))
if formula=="zscore":
distancerow.append(1-(O11-E11)*1.0/max(0.00000000001,sqrt(E11)))
if formula=="loglikelihood":
distancerow.append(1-(O11*log(max(0.00000000001,O11)*1.0/max(0.00000000001,E11)))
-(O12*log(max(0.00000000001,O12)*1.0/max(0.00000000001,E12)))
-(O21*log(max(0.00000000001,O21)*1.0/max(0.00000000001,E21)))
-(O22*log(max(0.00000000001,O22)*1.0/max(0.00000000001,E22)))
)
if formula=="poissonstirling":
distancerow.append(1-O11*(log(max(O11,0.00000001))-log(max(E11,0.00000001))-1))
if formula=="ngd":
distancerow.append((max(log(max(R1,0.00000001)),log(max(C1,0.00000001)))-log(max(O11,0.00000001)))/(N-min(log(max(R1,0.00000001)),log(max(C1,0.00000001)))))
k+=1;
distance.append(distancerow)
j+=1
return distance
# Normalize the distance matrix from the cooccurrence matrix
# -> returns a real matrix
# * mat contains a real matrix
# * mode is a string to choose the normalization mode: "linear" or "affine"
# or "auto": apply affine only if the matrix contains a negative number.
def normalizeMatrix(mat,mode):
themax=1
themin=mat[0][0]
for i in range(0,len(mat[0])):
for j in range(0,len(mat[0])):
themax=max(themax,mat[i][j])
themin=min(themin,mat[i][j])
if mode=="auto":
if themin<0:
mode="affine"
else:
mode="linear"
#print mode,themax
for i in range(0,len(mat[0])):
for j in range(0,len(mat[0])):
if mode=="linear":
mat[i][j]=((mat[i][j])*1.0)/themax
else:
if mode=="log":
mat[i][j]=log(1+99*(mat[i][j]-themin)*1.0/(themax-themin))
else:
coeff=2.0/(2*(log(len(mat[0])))+1)
#coeff=0.1
mat[i][j]=coeff+(1-coeff)*(mat[i][j]-themin)*1.0/(themax-themin)
return mat
# Computes the discrete and continuous arboricity of a dissimilarity matrix
# -> returns the result in a list
# * distance contains a real matrix
def computeArboricity(distance):
theResult=[]
nbQuad=0
nbCorrectQuad=0
sum=0
for x in range(0, len(distance[0])):
for y in range(x+1, len(distance[0])):
for z in range(y+1, len(distance[0])):
for t in range(z+1, len(distance[0])):
fourPointDistances=[]
fourPointDistances.append(distance[x][y]+distance[z][t])
fourPointDistances.append(distance[x][z]+distance[y][t])
fourPointDistances.append(distance[x][t]+distance[y][z])
fourPointDistances.sort()
Smin=fourPointDistances[0]
Smed=fourPointDistances[1]
Smax=fourPointDistances[2]
nbQuad+=1
if Smax-Smin==0:
sum+=0
else :
sum+=(Smed-Smin)/(Smax-Smin)
if Smax-Smed<Smed-Smin:
nbCorrectQuad+=1
theResult.append(100*nbCorrectQuad/nbQuad)
theResult.append(100*sum/nbQuad)
return theResult
# Export a matrix labeled by a list into a csv file
# * distance contains a real matrix
# * keptWords contains a string list
# * exportfilename contains a string
def exportToCsv(distance,keptWords,exportfilename):
csvoutput = open(exportfilename,"w")
j=0
while j<len(keptWords):
csvoutput.writelines(";"+keptWords[j])
j+=1
csvoutput.writelines("\n")
j=0
while j<len(keptWords):
k=0;
csvoutput.writelines(keptWords[j])
while k<len(keptWords):
csvoutput.writelines(";"+str(distance[j][k]))
k+=1;
j+=1
csvoutput.writelines("\n")
csvoutput.close();
# Export a matrix labeled by a list into a csv file
# * matrix contains a real matrix
# * exportfilename contains a string
def saveMatrixToCsv(matrix,exportfilename):
csvoutput = open(exportfilename,"w")
j=0
while j<len(matrix):
row=matrix[j]
j+=1
i=0
while i<len(row):
csvoutput.writelines(str(row[i])+";")
i+=1
csvoutput.writelines("\n")
csvoutput.close();
# Export a matrix labeled by a list into a nexus file
# * distance contains a real matrix
# * keptWords contains a string list
# * exportfilename contains a string
# * unit equals 1 if the edges of the treecloud have the same length, 0 otherwise
def exportToNexus(distance,keptWords,exportfilename,unit):
nexusoutput = open(exportfilename+".nexus","w")
nexusoutput.writelines("#nexus\n")
nexusoutput.writelines("\n")
nexusoutput.writelines("BEGIN Taxa;\n")
nexusoutput.writelines("DIMENSIONS ntax="+str(len(keptWords))+";\n")
nexusoutput.writelines("TAXLABELS\n")
j=0
while j<len(keptWords):
nexusoutput.writelines("["+str(j+1)+"] '"+keptWords[j]+"'\n")
j+=1
nexusoutput.writelines(";\n")
nexusoutput.writelines("END; [Taxa]\n")
nexusoutput.writelines("\n")
nexusoutput.writelines("BEGIN Distances;\n")
nexusoutput.writelines("DIMENSIONS ntax="+str(len(keptWords))+";\n")
nexusoutput.writelines("FORMAT labels=left diagonal triangle=both;\n")
nexusoutput.writelines("MATRIX\n")
j=0
while j<len(keptWords):
k=0;
nexusoutput.writelines("["+str(j+1)+"] '"+keptWords[j]+"' ")
while k<len(keptWords):
nexusoutput.writelines(" "+str(distance[j][k]))
k+=1;
j+=1
nexusoutput.writelines("\n")
nexusoutput.writelines(";\n")
nexusoutput.writelines("END; [Distances]\n")
nexusoutput.writelines(" \n");
nexusoutput.writelines("BEGIN st_Assumptions;\n");
nexusoutput.writelines(" disttransform=NJ;\n");
#nexusoutput.writelines(" disttransform=NeighborNet Variance = OrdinaryLeastSquares Threshold = 1.0E-6;\n");
nexusoutput.writelines(" treestransform=TreeSelector;\n");
if unit==1:
nexusoutput.writelines(" splitstransform=EqualAngle UseWeights=false RunConvexHull=true DaylightIterations=0 OptimizeBoxesIterations=5 SpringEmbedderIterations=0;\n");
else:
nexusoutput.writelines(" splitstransform=EqualAngle UseWeights=true RunConvexHull=true DaylightIterations=0 OptimizeBoxesIterations=5 SpringEmbedderIterations=0;\n");
nexusoutput.writelines(" SplitsPostProcess filter=dimension value=4;\n");
nexusoutput.writelines(" autolayoutnodelabels;\n");
nexusoutput.writelines("END; [st_Assumptions]\n");
nexusoutput.close();
# Export a matrix labeled by a list into a nexus file
# * distance contains a real matrix
# * keptWords contains a string list
# * exportfilename contains a string
# * invisible = 1 if invisible mode, 0 otherwise
def nexusOrders(distance,keptWords,exportfilename,invisible):
nexusoutput = open(exportfilename+".nexorders","w")
nexusoutput.writelines("#nexus\n")
nexusoutput.writelines("\n")
nexusoutput.writelines("BEGIN Taxa;\n")
nexusoutput.writelines("DIMENSIONS ntax="+str(len(keptWords))+";\n")
nexusoutput.writelines("TAXLABELS\n")
j=0
while j<len(keptWords):
nexusoutput.writelines("["+str(j+1)+"] '"+keptWords[j]+"'\n")
j+=1
nexusoutput.writelines(";\n")
nexusoutput.writelines("END; [Taxa]\n")
nexusoutput.writelines("\n")
nexusoutput.writelines("BEGIN Distances;\n")
nexusoutput.writelines("DIMENSIONS ntax="+str(len(keptWords))+";\n")
nexusoutput.writelines("FORMAT labels=left diagonal triangle=both;\n")
nexusoutput.writelines("MATRIX\n")
j=0
while j<len(keptWords):
k=0;
nexusoutput.writelines("["+str(j+1)+"] '"+keptWords[j]+"' ")
while k<len(keptWords):
nexusoutput.writelines(" "+str(distance[j][k]))
k+=1;
j+=1
nexusoutput.writelines("\n")
nexusoutput.writelines(";\n")
nexusoutput.writelines("END; [Distances]\n")
nexusoutput.writelines("\n")
nexusoutput.writelines("BEGIN Splitstree;\n")
nexusoutput.writelines(" EXECUTE FILE="+doubleAntislash(exportfilename)+".nexus;\n")
nexusoutput.writelines(" SAVE FILE="+doubleAntislash(exportfilename)+".nocol.nexus REPLACE=yes;\n")
if invisible==1 :
nexusoutput.writelines(" QUIT;\n")
nexusoutput.writelines("END;\n")
nexusoutput.close()
# return the splits of the tree contained in the nexus file:
# -> {0,1} matrix where the columns are the leaves (word ids)
# the rows are the splits
# * keptWords contains a string list
# * filename is a string
def splitsFromNexus(keptWords,filename):
fd = open(filename+".nocol.nexus","r")
lines = fd.readlines()
treeline=0
splits=[]
for line in lines:
if treeline==0:
res=re.search(".*BEGIN Trees.*",line)
if res:
treeline=1
else:
treeline=0
res=re.search("[^(] ([(].*[)]);.*",line)
if res:
splits=splitsFromNewick(res.group(1),keptWords)
fd.close()
return splits
# return the union split of two splits
# * split1 and split2 are two tables
def splitUnion(split1,split2):
union=[]
for i in range(0,len(split1)):
union.append(max(split1[i],split2[i]))
return union
# return 1 if the splits are equal, 0 otherwise
# * splits1 and splits2 are two tables with the same number of columns
def splitEqual(split1,split2):
opposite=0
if split1[0]!=split2[0]:
opposite=1
i=1
while (i<len(split1)) and (opposite==abs(split1[i]-split2[i])):
i+=1
if i<len(split1):
return 0
else:
return 1
# return the line number in splits2 where split1 has been found, -1 otherwise
# * split1 is a table which represents a split
# * splits2 is a table which represents a set of splits with the same number of columns as split1
def findSplit(split1,splits2):
found=-1
i=0
while i<len(splits2) and found<0:
if splitEqual(split1,splits2[i]):
found=i
i+=1
return found
# return the size of the split = the size of one of the two separated clusters
# * split1 is a table which represents a split
def splitSize(split):
i=0
size=0
while i<len(split):
if split[i]==1:
size+=1
i+=1
return size
# return the Robinson-Foulds similarity between splits1 and splits2
# (percentage of non trivial splits common to splits1 and splits2)
# * splits1 and splits2 are two tables with the same number of columns
def RFsimilarity(splits1,splits2):
percentage=0
nonTrivialSplits=0
for i in range(0,len(splits1)):
splitLen=splitSize(splits1[i])
if splitLen>1 and splitLen<len(splits1[i])-1:
nonTrivialSplits+=1
if findSplit(splits1[i],splits2)>=0:
percentage+=1
return percentage*1.0/nonTrivialSplits
# return the splits of the tree contained in the newick string:
# -> {0,1} matrix where the columns are the leaves (word ids)
# the rows are the splits
# * string is a newick string
# * keptWords contains a string list
def splitsFromNewick(string,keptWords):
splits=[]
nbwords=len(list(keptWords.keys()))
if string[0]=="(":
subtrees=findSubtrees(string)