-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCalcAllOrganizations.py
executable file
·3662 lines (3224 loc) · 132 KB
/
CalcAllOrganizations.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
# -*- coding: utf-8 -*-
import os
import sys
import gc
import random
import math
import copy
import time
import cPickle
import pickle
import shelve
import itertools
ShowUnion=False#True #False
ShowIntersection=False#True #False
### code is poetry ###
###########################################
######## Constants ########################
###########################################
os.environ['PATH'] += ":"+"/usr/local/bin"
from subprocess import check_call
Org2FillColor={}
################################################################################
def linearapproximation(minOvalue,maxOvalue,value,minIvalue=0,maxIvalue=1):
value=(float)(value-minIvalue)/maxIvalue
delta=maxOvalue-minOvalue
return (value*delta)+minOvalue
def next_string(s):
"returns the next alphabetic string, only works with lowercase"
strip_zs = s.rstrip('z')
if strip_zs:
return strip_zs[:-1] + chr(ord(strip_zs[-1]) + 1) + 'a' * (len(s) - len(strip_zs))
else:
return 'a' * (len(s) + 1)
def combinations(iterable, r):
# from the itertools for 2.6.1
# combinations('ABCD', 2) --> AB AC AD BC BD CD
# combinations(range(4), 3) --> 012 013 023 123
if len(iterable)<r : return#I added this line. Pietro Speroni
pool = tuple(iterable)
n = len(pool)
indices = range(r)
yield tuple(pool[i] for i in indices)
while 1:
for i in reversed(range(r)):
if indices[i] != i + n - r:
break
else:
return
indices[i] += 1
for j in range(i+1, r):
indices[j] = indices[j-1] + 1
yield tuple(pool[i] for i in indices)
def findsubsets(S,m):#given the set S find all the subsets of order m
return set(combinations(S, m))
def sumsequence(sequence,offset=0):
result=list(sequence[:])
result[0]+=offset
for t in xrange(1,len(result)):
result[t]+=result[t-1]
return result
def find_keys(dic, val):
"""return the key of dictionary dic given the value"""
return [k for k, v in symbol_dic.iteritems() if v == val]
def ValMolecules1(sequence): return sequence
def ValMolecules2(sequence): return sumsequence(sequence)
def LayoutDrawType():
while 1:
yield ValMolecules1
yield ValMolecules2
def findconvered(s,S):
coveringrelations=[]
for t in S:
if s == t: continue
if t < s:
for r in S:
if t < r < s:
break
else:
coveringrelations.append((s,t))
return coveringrelations
def FindCovers(S):
coverrelations=[]
for s in S:
a=findconvered(s,S)
for rel in a:
coverrelations.append(rel)
return coverrelations
def WriteLattice(S,directory,name,sublattice=set([]), Org2Color={}):
relations=FindCovers(S)
buf="digraph G {%s%s"%(os.linesep,os.linesep)
OrgBySize={}
for s in S:
try:
OrgBySize[len(s)]=OrgBySize[len(s)]+[s]
except KeyError:
OrgBySize[len(s)]=[s]
layers=[]
r0=""
for s in OrgBySize.values():
if len(s)<1:
continue
r0='{rank=same; '
# r0+="%s"%OrganizationName.check(s)
# r0+="\\n"
# print s
for o2 in s:
o=list(o2)
o.sort()
r0+=' "'
t=0
l=len(o)
width=math.ceil(l**.5)
for molecule in o:
r0+="%s"%molecule
t+=1
if t<l:
if (t%width):
r0+=" "
else:
r0+="\\n"
if not l:
r0+='∅'
r0+='" '
r0+=' "'
r0+='%s'%len(s[0])
layers.append(len(s[0]))
r0+='" '
r0+='};%s'%os.linesep
buf+=r0
layers.sort()
layers.reverse()
for lay in range(0,len(layers)-1):
r0+='"%s" -> "%s" [color=white];%s'%(layers[lay],layers[lay+1],os.linesep)
buf+=r0
for lay in range(0,len(layers)):
r0+='"%s" [color=white];%s'%(layers[lay],os.linesep)
buf+=r0
for r in relations:
r0=r1='"'
if r[0]:
rlist=list(r[0])
rlist.sort()
t=0
l=len(r[0])
width=math.ceil(l**.5)
# for molecule in r[0]:
for molecule in rlist:
r0+="%s"%molecule
t+=1
if t<l:
if (t%width):
r0+=" "
else:
r0+="\\n"
else:
r0+="∅"
if r[1]:
rlist=list(r[1])
rlist.sort()
t=0
l=len(r[1])
width=math.ceil(l**.5)
for molecule in rlist:
# for molecule in r[1]:
r1+="%s"%molecule
t+=1
if t<l:
if (t%width):
r1+=" "
else:
r1+="\\n"
else:
r1+="∅"
r0+='"'
r1+='"'
## if set(r)<set(sublattice):
## r2=" [color=red]"
## else:
## r2=""
print "r[0]=",r[0]
if r[0] in Org2Color:
r2=' [color="%s"]'%Org2Color[r[0]]
elif r[0] in Org2FillColor:
r2=' [color="%s"]'%Org2FillColor[r[0]]
else:
r2=''
buf+=r0+" -> "+r1+r2+"; %s"%os.linesep
for o2 in sublattice:#colors the sublattice red
o=list(o2)
o.sort()
r0='"'
t=0
l=len(o)
width=math.ceil(l**.5)
for molecule in o:
r0+="%s"%molecule
t+=1
if t<l:
if (t%width):
r0+=" "
else:
r0+="\\n"
if not l:
r0+='∅'
r0+='" [fillcolor=red, style=filled];%s'%os.linesep
buf+=r0
for o2 in Org2FillColor.keys():
o=list(o2)
o.sort()
r0='"'
t=0
l=len(o)
width=math.ceil(l**.5)
for molecule in o:
r0+="%s"%molecule
t+=1
if t<l:
if (t%width):
r0+=" "
else:
r0+="\\n"
if not l:
r0+='∅'
if o2 in Org2Color:
r0+='" [fillcolor="%s", peripheries=6, color="%s",style=filled];%s'%(Org2FillColor[o2],Org2Color[o2],os.linesep)
else:
r0+='" [fillcolor="%s", style=filled];%s'%(Org2FillColor[o2],os.linesep)
buf+=r0
buf+="}%s%s"%(os.linesep,os.linesep)
f=open("%s%s%s.dot"%(directory,os.sep,name),'w')
f.write(buf)
f.close()
def WriteLatticesKnownInGeneral():
AllOrg=GetAllKnownOrg()
WriteLattice(AllOrg,'.',"L_AllOrganizationsGeneral")
print "writing the graph"
print check_call(["dot", "-ogeneral.png", "-Tpng", "./L_AllOrganizationsGeneral.dot"])
print "graph drawn"
################################################################################
def LevDistance(a,b):
"""Calculates the Levenshtein distance between a and b.
From http://hetland.org/coding/python/levenshtein.py"""
n, m = len(a), len(b)
if n > m:
# Make sure n <= m, to use O(min(n,m)) space
a,b = b,a
n,m = m,n
current = range(n+1)
for i in range(1,m+1):
previous, current = current, [i]+[0]*n
for j in range(1,n+1):
add, delete = previous[j]+1, current[j-1]+1
change = previous[j-1]
if a[j-1] != b[i-1]:
change = change + 1
current[j] = min(add, delete, change)
return current[n]
def setuparchives(directory):
global AllStates, AllRndSeeds
print "I am setting up the ALLSTATES archive"
# AllStates=shelve.open("%s%sAllStates.shelve"%(directory,os.sep),writeback=False)
# AllStates=shelve.open("%s%sAllStates1.shelve"%(directory,os.sep))
AllStates=shelve.open("%s%sAllStates.shelve"%(directory,os.sep))
#if writeback=True the DB gets corrupted when I access all the entries
AllRndSeeds=shelve.open("%s%sAllRndSeeds.shelve"%(directory,os.sep),writeback=True)
def updatearchive(step,b):
print "I am updating the archive"
AllStates["%10s"%step]=list(b.molecules)
AllRndSeeds["%10s"%step]=random.getstate()
profiling=0
timelimit=0
def testtime(where,exceptionname):
if profiling:
if time.time()>timelimit:
print where
raise exceptionname
###########################################
######## Molecule #########################
###########################################
execfile("%smolecules.py"%chemistry)
###########################################
######## Molecule Library #################
###########################################
def GenerateBasicOrganizations():
# OrgLibrary.check(ReturnAllMolecules())
OrgLibrary.check(set([]))
class MoleculeLibraryDB(object):
"""a class the handles the Database of molecular reactions. Every time a reaction is tried it will call the function check.
if the reaction is present in the DB, the result is returned. If not it is calculated, added to the DB and returned
"""
def __repr__(self): return 'MoleculeLibraryDB('+`self.DB`+')'
def __str__(self): return self.DB.__str__()
# def __init__(self,DB={}): self.DB=DB
def __init__(self,directory=".",DB={}):
self.DB=shelve.open("%s%sMoleculeLibrary.shelve"%(directory,os.sep),writeback=True)
for k in DB.keys():
self.DB[str(k)]=DB[k]
def check(self,m0):
try:
return self.DB[str(m0)]
except KeyError:
molec=Molecule(m0)
self.DB[str(m0)]=molec #slightly faster by taking away a hash call
return molec
def initalisedatabases(DirectoryAC):
# global moleculelibrary, OrgLibrary, urllib, reactionDB, mutationsDB, LatticeLibrary, GeneratorsLibrary, OrganizationName, NameOrganization, TimeBiggerOrganizationName, IntersectionRelOrg, DirectoryAC
global moleculelibrary, OrgLibrary, reactionDB, mutationsDB, LatticeLibrary, GeneratorsLibrary, OrganizationName, NameOrganization, TimeBiggerOrganizationName, IntersectionRelOrg
# DirectoryAC="%s%s%s%s%s"%(directory,os.sep,os.pardir,os.sep,urllib)
# if not os.path.isdir(DirectoryAC):
# os.mkdir(DirectoryAC)
#if not os.path.isdir("%s%s%s%s%s"%(directory,os.sep,os.pardir,os.sep,urllib)):
# os.mkdir("%s%s%s%s%s"%(directory,os.sep,os.pardir,os.sep,urllib))
moleculelibrary=MoleculeLibraryDB(DirectoryAC)
# moleculelibrary=MoleculeLibraryDB("%s%s%s%s%s"%(directory,os.sep,os.pardir,os.sep,urllib))
OrgLibrary=OrganizationLibraryDB(DirectoryAC)
reactionDB=MoleculeRactionsDB(DirectoryAC)
mutationsDB=MoleculeMutationsDB(DirectoryAC)
LatticeLibrary=LatticeLibraryDB(DirectoryAC)
GeneratorsLibrary=GeneratorsLibraryDB(DirectoryAC)
OrganizationName=OrganizationNameDB(DirectoryAC)
NameOrganization=NameOrganizationDB(DirectoryAC)
TimeBiggerOrganizationName=TimeBiggerOrganizationNameDB(DirectoryAC)
IntersectionRelOrg=RelationOrganizationDB("Intersection",DirectoryAC)
print "I am opening the archives"
def syncdatabases():
global moleculelibrary, OrgLibrary, reactionDB, mutationsDB, LatticeLibrary,TimeBiggerOrganizationName,IntersectionRelOrg
moleculelibrary.DB.sync()
OrgLibrary.DB.sync()
reactionDB.DB.sync()
mutationsDB.DB.sync()
LatticeLibrary.DB.sync()
GeneratorsLibrary.DB.sync()
OrganizationName.DB.sync()
NameOrganization.DB.sync()
TimeBiggerOrganizationName.DB.sync()
IntersectionRelOrg.DB.sync()
global AllStates, AllRndSeeds
print "I am sync the archives"
AllStates.sync()
AllRndSeeds.sync()
def closedatabases():
global moleculelibrary, OrgLibrary, reactionDB, mutationsDB, LatticeLibrary,TimeBiggerOrganizationName,IntersectionRelOrg
moleculelibrary.DB.close()
OrgLibrary.DB.close()
reactionDB.DB.close()
mutationsDB.DB.close()
LatticeLibrary.DB.close()
GeneratorsLibrary.DB.close()
OrganizationName.DB.close()
NameOrganization.DB.close()
TimeBiggerOrganizationName.DB.close()
IntersectionRelOrg.DB.close()
global AllStates, AllRndSeeds
AllStates.close()
AllRndSeeds.close()
print "I am closing the archives"
class mydict(dict):
"""
an extension of the dictionary class. It has the extra function of being able to sort keys according to their
dictionary value
"""
def sorted_keys(self,reverse=False):
"""
a function that returns the list of allkeys sorted according to their value.
Important for histograms (among other things)
"""
aux=[(self[k],k)for k in self.keys()]
aux.sort()
if reverse:aux.reverse()
return [k for v, k in aux]
##################################################################################################################################################################################
######################## CHEMICAL ORGANIZATION THEORY ############################################################################################################################
##################################################################################################################################################################################
def Closure(molecules):
"""
Returns the set of the closure of a given list of molecules
"""
newmol=set(molecules)
oldmol=set([])
while newmol:
gen=ReactSets(newmol,newmol)
gen|=ReactSets(newmol,oldmol)
gen|=ReactSets(oldmol,newmol)
oldmol|=newmol
newmol=gen-oldmol
return oldmol
def SelfMaintainance(molecules):
"""
Returns the biggest self maintaining set inside a given list of molecules
"""
mol=set(molecules)
l=len(mol)
while l:
notgeneratedmolecules=copy.deepcopy(mol)
for t in mol:
for s in mol:
r=react(t,s)
if r!= None:
notgeneratedmolecules-=set([r])
if not len(notgeneratedmolecules):
return mol
mol-=notgeneratedmolecules
l=len(mol)
return set([])
def Organization(molecules):
"""
Returns the organization generated by a set of molecules
"""
return SelfMaintainance(Closure(molecules))
def IsOrganizationSlow(molecules):
"""
Returns True if the set of molecules is an organization
"""
mol=set(molecules)
gen=ReactSets(mol,mol)
if gen==mol:
return True
return False
def IsOrganization(molecules):
"""
Returns True if the set of molecules is an organization. It is about one order of magnitude faster (but messiers) than the previous one as it checks while it is running.
"""
mol=set(molecules)
tobegenerated=copy.deepcopy(mol)
for m in mol:
for n in mol:
res=react(m,n)
if res!= None:
if res not in mol:
return False #Not Closed
tobegenerated -= set([res])
if tobegenerated:
return False #Not Self Mainaining
return True
class NameOrganizationDB(object):
"""a class the handles the relation Name-Organization, takes a string and returns a frozenset"""
def __repr__(self): return 'NameOrganizationDB('+`self.DB`+')'
# def __repr__(self): return 'OrganizationLibraryDB('+`self.DB`+')'
def __str__(self): return self.DB.__str__()
def __init__(self,directory=".",DB={}):
self.DB=shelve.open("%s%sNameOrganization.shelve"%(directory,os.sep),writeback=True)
for k in DB.keys():
self.DB[str(k)]=DB[k]
def check(self,name):
name=str(name)
try:
org=self.DB[name]
if type(org)==type(""):
print "I stored it as a string, let me change that"
Temp="org="+org
exec(Temp)
org=frozenset(Temp)
self.DB[name]=org
elif type(org)==type(set([])):
print "I stored it as a set, let me change that"
org=frozenset(org)
self.DB[name]=org
return org
# return self.DB[name]
except KeyError:
org=OrganizationName.backtrack(name)
self.DB[name]=org
print "aaargh ERROR 783942,", name, org
return org
def add(self,name,org):
if type(org)==type(set([])):
org=frozenset(org)
assert type(org)==type(frozenset([]))
self.DB[str(name)]=org
class TimeBiggerOrganizationNameDB(object):
"""a class the handles the relation time to the Organization (by name), takes a number and returns the string of the organization"""
def __repr__(self): return 'TimeBiggerOrganizationNameDB('+`self.DB`+')'
def __str__(self): return self.DB.__str__()
def __init__(self,directory=".",DB={}):
self.DB=shelve.open("%s%sTimeBiggerOrganizationName.shelve"%(directory,os.sep),writeback=True)
for k in DB.keys():
self.DB[str(k)]=DB[k]
def check(self,step):
try:
return self.DB[step]
except KeyError:
# print "aaargh ERROR 23243"
b=Cell(AllStates["%10s"%step])
self.DB[step]=OrganizationLibrary.checkname(b.molecules)
def add(self,time,orgName):
self.DB[step]=orgName
class OrganizationNameDB(object):
"""a class that handles the relation Name-Organization, takes a frozenset and returns a string"""
# def __repr__(self): return 'OrganizationLibraryDB('+`self.DB`+')'
def __repr__(self): return 'OrganizationNameDB('+`self.DB`+')'
def __str__(self): return self.DB.__str__()
def __init__(self,directory=".",DB={}):
self.DB=shelve.open("%s%sOrganizationName.shelve"%(directory,os.sep),writeback=True)
for k in DB.keys():
self.DB[str(k)]=DB[k]
# OrganizationNameDB.max="aaaaa"
OrganizationNameDB.max=0
values=self.DB.values()
if len(values):
values=[int(v) for v in values]
OrganizationNameDB.max=max(values)
print OrganizationNameDB.max,
def backtrack(self,name):
org=[k for k, v in self.DB.iteritems() if v == name]
TempOrg="org="+org[0]
exec TempOrg
org=frozenset(org)
return org
#return org[0]
def check(self,org):
orglist=list(org)
orglist.sort()
orgstr=str(orglist)
try:
return int(self.DB[orgstr])
except KeyError:
# OrganizationNameDB.max=next_string(OrganizationNameDB.max)
OrganizationNameDB.max+=1
self.DB[orgstr]=str(OrganizationNameDB.max)
NameOrganization.add(OrganizationNameDB.max,org)
return OrganizationNameDB.max
class OrganizationLibraryDB(object):
"""a class the handles the Database from set of molecules to organizations"""
def __repr__(self): return 'OrganizationLibraryDB('+`self.DB`+')'
def __str__(self): return self.DB.__str__()
# def __init__(self,DB={}): self.DB=DB
def __init__(self,directory=".",DB={}):
self.DB=shelve.open("%s%sOrganizationLibrary.shelve"%(directory,os.sep),writeback=True)
for k in DB.keys():
self.DB[str(k)]=DB[k]
def check(self,molecules):#I return the organization
mollist=list(molecules)
mollist.sort()
frozm=str(mollist)
try:
return NameOrganization.check(self.DB[frozm]) #I return the organization
except KeyError:
Org=frozenset(Organization(molecules))
name=OrganizationName.check(Org)
self.DB[frozm]=name #slightly faster by taking away a hash call
GeneratorsLibrary.add(name,molecules)
return Org#I return the organization
def checkname(self,molecules):#I return the name of the organization
mollist=list(molecules)
mollist.sort()
frozm=str(mollist)
# frozm=str(molecules)
try:
return self.DB[frozm]#I return the name of the organization
except KeyError:
Org=frozenset(Organization(molecules))
name=OrganizationNameDB.check(Org)
self.DB[frozm]=name #slightly faster by taking away a hash call
GeneratorsLibrary.add(name,molecules)
return name#I return the name of the organization
class RelationOrganizationDB(object):
"""a class the handles the relation set of organizations, organization, takes a frozenset and returns an organization"""
def __repr__(self): return 'RelationOrganizationDB('+`self.DB`+')'
def __str__(self): return self.DB.__str__()
def __init__(self,nameRelation,directory=".",DB={}):
self.DB=shelve.open("%s%s%sRelOrg.shelve"%(directory,os.sep,nameRelation),writeback=True)
for k in DB.keys():
self.DB[str(k)]=DB[k]
def check(self,name):
name=str(name)
try:
return self.DB[name]
except KeyError:
return "none"
def add(self,name,org):
self.DB[str(name)]=org
def backtrack(self,name):
"""given an organizations tells you a series of couples of organizations that returns that"""
#keysinteresting=find_keys(self.DB, name)
keysinteresting=[k for k, v in self.DB.iteritems() if v == name and k[0]!= name and k[1]!=name]
keyinter=keysinteresting[0]
OrgA=NameOrganization.check(keyinter[0])
OrgB=NameOrganization.check(keyinter[1])
OrgAiOrgB = OrgLibrary.check(OrgA & OrgB)
return OrgAiOrgB
class GeneratorsLibraryDB(object):
"""a class the handles the Database from organization to the set of sets of molecules that generate them"""
def __repr__(self): return 'GeneratorsLibraryDB('+`self.DB`+')'
def __str__(self): return self.DB.__str__()
def __init__(self,directory=".",DB={}):
self.DB=shelve.open("%s%sGeneratorsLibrary.shelve"%(directory,os.sep),writeback=True)
for k in DB.keys():
self.DB[str(k)]=DB[k]
def check(self,name):
try:
return self.DB[name]
except KeyError:
molecules=NameOrganization.check(name)
generators=frozenset([molecules])
self.DB[name]=generators #slightly faster by taking away a hash call
return generators
def add(self,name,molecules):
name=str(name)
molecules=frozenset(molecules)
try:
generators=self.DB[name]|frozenset([molecules])
self.DB[name]=generators
return generators
except KeyError:
O=NameOrganization.check(name)
generators=frozenset([O])|frozenset([molecules])
self.DB[name]=generators
return generators
def ExpandOrganizationBy1Molecule(O,molecule):
if molecule in O:
return O
O_New=frozenset([OrgLibrary.check(O|molecule)])
return O_New
def ExpandOrganizationBy1Organization(O,O2):
if 02 in O:
return O
if O in O2:
return O2
O_New=frozenset([OrgLibrary.check(O|02)])
return O_New
def GetAllKnownOrg():
return set(NameOrganization.DB.values())
def GetNKnownOrg():
return len(NameOrganization.DB)
def FindOrgKnownBetween(Omin,Omax):
#this checks all the orgs and does not use the known information
return FindOrgKnownAbove(Omin)&FindOrgKnownBelow(Omax)
def FindOrgKnownAbove(Omin):
AllOrg=GetAllKnownOrg()
AboveOrg=set([])
for o in AllOrg:
if o>Omin:
AboveOrg|=set([o])
return AboveOrg
def FindOrgKnownBelow(Omax):
AllOrg=GetAllKnownOrg()
BelowOrg=set([])
for o in AllOrg:
if o<Omax:
BelowOrg|=set([o])
return BelowOrg
def FindOrgByUnionEtIntersection(Orgs):
"""Given a set of organizations considers all the possible unions and intersections to find all the possible organizations"""
NewNewOrgs=set([])
KnownOrgs=copy.deepcopy(Orgs)
for h in combinations(Orgs,2):
#checks only if one is not contained in the other
NewNewOrgs|=frozenset([OrgLibrary.check(h[0]|h[1])])
#checks only if one is not contained in the other
NewNewOrgs|=frozenset([OrgLibrary.check(h[0]&h[1])])
FoundOrgs=NewNewOrgs
NewOrgs=NewNewOrgs-KnownOrgs
while NewOrgs:
NewNewOrgs=set([])
for h in combinations(NewOrgs,2):
#checks only if one is not contained in the other
NewNewOrgs|=frozenset([OrgLibrary.check(h[0]|h[1])])
#checks only if one is not contained in the other
NewNewOrgs|=frozenset([OrgLibrary.check(h[0]&h[1])])
for h in NewOrgs:
for t in KnownOrgs:
#checks only if one is not contained in the other
NewNewOrgs|=frozenset([OrgLibrary.check(h|t)])
#checks only if one is not contained in the other
NewNewOrgs|=frozenset([OrgLibrary.check(h&t)])
KnownOrgs|=NewOrgs
NewOrgs=NewNewOrgs-KnownOrgs#NewOrgs is what we actually found
KnownOrgs-=Orgs
return KnownOrgs
def FindOrgByUnionEtIntersectionKnowingSome(NewOrgsOriginal,KnownOrgsOriginal):
"""Given a set of organizations considers all the possible unions and intersections to find all the possible organizations"""
KnownOrgs=copy.deepcopy(KnownOrgsOriginal)
NewOrgs =copy.deepcopy( NewOrgsOriginal)
KnownOrgs-=NewOrgs
while NewOrgs:
print "Organizations known:",GetNKnownOrg(), "number of new organizations in this research",len(NewOrgs),"Discovered Organization",len(KnownOrgs)
NewNewOrgs=set([])
for h in combinations(NewOrgs,2):
testtime("FindOrgByUnionEtIntersectionKnowingSome h h", OverflowError)
## if profiling:
## if time.time()>timelimit:
## print "FindOrgByUnionEtIntersectionKnowingSome h h"
## raise OverflowError
NewNewOrgs|=frozenset([OrgLibrary.check(h[0]|h[1])]) #checks only if one is not contained in the other
NewNewOrgs|=frozenset([OrgLibrary.check(h[0]&h[1])]) #checks only if one is not contained in the other
# print ":",
print
print "Organizations known:",GetNKnownOrg(),"recently discovered=",len(NewNewOrgs)
for h in NewOrgs:
for t in KnownOrgs:
if profiling:
if time.time()>timelimit:
print "FindOrgByUnionEtIntersectionKnowingSome h t"
raise OverflowError
NewNewOrgs|=frozenset([OrgLibrary.check(h|t)])
NewNewOrgs|=frozenset([OrgLibrary.check(h&t)])
# print ".",
print
print "Organizations known:",GetNKnownOrg(),"recently discovered=",len(NewNewOrgs)
KnownOrgs|=NewOrgs
print "Discovered Organization after intersection",len(KnownOrgs)
NewOrgs=NewNewOrgs-KnownOrgs#NewOrgs is what we actually found
print "Discovered Organization after subtractions",len(NewOrgs)
if profiling:
if time.time()>timelimit:
print "FindOrgByUnionEtIntersectionKnowingSome"
raise OverflowError
KnownOrgs-=KnownOrgsOriginal
KnownOrgs-=NewOrgsOriginal
return KnownOrgs
def FindOrgBetween(Omin, Omax,NMol2Test=2):
ProduceOrgBetween(Omin, Omax,NMol2Test=NMol2Test)
return FindOrgKnownBetween(Omin,Omax)
def ProduceOrgBetween(Omin, Omax,NMol2Test=2):
if len(Omax)<=len(Omin)+1:
return
AllOrg=GetAllKnownOrg()
OrganizationsFound=set([Omin,Omax])
OtherMolecules=Omax-Omin
SetsToTest=set([])
L=len(Omax)
n=NMol2Test#max number of size of sets to test
for m in range(1,n+1):
setsM=[p for p in combinations(OtherMolecules,m)]
for s in setsM:
SetsToTest|=frozenset([frozenset(s)|Omin])
if profiling:
if time.time()>timelimit:
print "FindOrgBetween making sets"
raise OverflowError
#check out all organizations that are in between
#check out all the generators for each organization that is in between
#maybe it is better to just check them all without checking the generators
for s in SetsToTest:
OrganizationsFound|=frozenset([OrgLibrary.check(s)])
if profiling:
if time.time()>timelimit:
print "FindOrgBetween"
raise OverflowError
FindOrgByUnionEtIntersectionKnowingSome(OrganizationsFound-AllOrg,AllOrg)
def CloseOrganizations():
"""
Takes all the organizations known, and adds any organization given from intersection or union that we might have missed
"""
FindOrgByUnionEtIntersection(GetAllKnownOrg())
def CheckAllSets(molecules):
"""
Returns the organizations generated by a set of molecules
"""
print "checking all organizations below ", molecules
Omin=frozenset([])
Omax=frozenset(OrgLibrary.check(molecules))
OrganizationsFound=frozenset([Omax,Omin])
OrganizationsFound|=FindOrgBetween(Omin=Omin,Omax=Omax)
return OrganizationsFound
class LatticeLibraryDB(object):
"""a class the handles the Database from set of molecules to organizations"""
def __repr__(self): return 'OrganizationLibraryDB('+`self.DB`+')'
def __str__(self): return self.DB.__str__()
def __init__(self,DB={}): self.DB=DB
def __init__(self,directory=".",DB={}):
self.DB=shelve.open("%s%sLatticeLibrary.shelve"%(directory,os.sep),writeback=True)
for k in DB.keys():
self.DB[str(k)]=DB[k]
def check(self,molecules):
molecules=OrgLibrary.check(molecules)#this only tests on the biggest organisation
try:
result=self.DB[str(molecules)]
return result
except KeyError:
# try:
# Os=CheckAllSets(frozenset(molecules))
# self.DB[str(molecules)]=Os
# print "added",len(Os)," orgs under",OrgLibrary.check(molecules)
try:
Os=CheckAllSets(frozenset(molecules))
self.DB[str(molecules)]=Os
print "added",len(Os)," orgs under",OrgLibrary.check(molecules)
except OverflowError:
Os=FindOrgKnownBelow(frozenset(OrgLibrary.check(molecules)))
return Os
IsLatticComplete=False
RecentlyDiscoveredOrgs=set([])
#LatticeLibrary=LatticeLibraryDB()
class MapStatesOrganizations(object):
"a class that holds the data about the organizations that are present in a series of states"
states=[0]
nOrganizations=1
OrganizationTime=numpy.zeros(shape=(1,1))
indexstate={}
def __init__(self, states, nOrganizations=1000):
# def ___new___(self,states,nOrganizations=1000):
print "called init"
self.states=states
self.nOrganizations=nOrganizations
self.OrganizationTime=numpy.zeros(shape=(self.nOrganizations,len(self.states)))
indexes=range(len(self.states))
self.indexstate=dict(zip(indexes, self.states))
self.stateindex=dict(zip(self.states, indexes))
def setvalue(self,state,orgname,value):
try:
index=self.stateindex[state]
except KeyError:
print "aaargh ERROR 234100 You need to expand the map"
self.OrganizationTime[orgname,index]=value
def getvalue(self,state,orgname):
index=self.stateindex[state]
return self.OrganizationTime[orgname,index]
def getLastPositiveValue(self,orgname,state):
"studying the organizations we need to find the last time an organization was active"
index=self.stateindex[state]
orghistory=self.OrganizationTime[orgname,0:index+1]#maybe is index, maybe is index-1, to be tested
i=index #again maybe it should start by index-1
for t in reversed(orghistory):
if t:
return self.indexstate[i]
i-=1
return "out of range"#a string is bigger than any number, as such this will not appear when later I will ask for the minimum
def getOrganizationsActive(self,state):
index=self.stateindex[state]
organizations=list(self.OrganizationTime[:,index])
orgnumbered=zip(organizations,range(self.nOrganizations))
return [t[1] for t in orgnumbered if t[0]>0]
def getSumLastValues(self,orgname,state):
"studying the organizations we need to find the last time an organization was active"
index=self.stateindex[state]
orghistory=self.OrganizationTime[orgname,0:index+1]#maybe is index, maybe is index-1, to be tested
return sum(orghistory)
def getOrganizationColor(self,state,orgname):
"""takes a set of organizations, and returns a dictionary that associates to each organization a color
based on when was the organization active the last time"""
last=self.getLastPositiveValue(orgname,state)
if last==0:
v=0
else:
try:
lastIndex=self.stateindex[last]
deltaIndex=self.stateindex[state]-lastIndex
v=1.0/deltaIndex
v=(float(last)-float(self.indexstate[0]))/(state-self.indexstate[0])
except ZeroDivisionError:
v=1
# if float(last)-float(self.indexstate[0]):
# v=1
# else:
# v=1
lightness=linearapproximation(0.3,.7,v)
saturation=linearapproximation(0.6,1,v) #how far from the white-gray-black axis mundi
hue=linearapproximation(0.6,1,v)
#print "step",state,"organization ",orgname,"last active on time",last, "color=",hue, saturation,lightness
return "%f %f %f"%(hue, saturation,lightness)
def getOrganizationsColors(self,state,organizations):
"""takes a set of organizations, and returns a dictionary that associates to each organization a color
based on when was the organization active the last time"""
lastvalues=[self.getLastPositiveValue(o,state) for o in organizations]
minvalue=min(lastvalues)
values=[]
for lastvalue in lastvalues:
try:
vtemp=(float(lastvalue)-float(minvalue))/(state-minvalue)
except ValueError:
vtemp="out of range"
except ZeroDivisionError:
vtemp=1.0
values.append(vtemp)
return [findcolor(v) for v in values]
def findcolor(v):
try:
lightness=linearapproximation(0.3,.7,v)
saturation=linearapproximation(0.6,1,v) #how far from the white-gray-black axis mundi
hue=linearapproximation(0.6,1,v)
except TypeError:
lightness=1.0
saturation=0.0
hue=0.0
return "%f %f %f"%(hue, saturation,lightness)
class SymetricTable(object):
"a class to create a table that is symetric. Given a tuple it will order it before checking"