-
Notifications
You must be signed in to change notification settings - Fork 5
/
RnO.py
3150 lines (2620 loc) · 126 KB
/
RnO.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
#Odor Spaces!
#Mitchell Gronowitz
#Spring 2014
"""QSpace, Odototope, Odorscene, and Receptor objects
Index of document:
1. Global variables
2. Defining all objects
3. Simple functions to create and activate each object
4. Experiments/Simulations utilizing objects"""
import math
import cells
import random
import layers
import os
#import matplotlib
#matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
from scipy.stats import multivariate_normal as mvn
import numpy as np
import matplotlib.pylab
from matplotlib.backends.backend_pdf import PdfPages
import copy
import time
#from matplotlib import mlab, cm
from matplotlib import patches
from matplotlib.patches import Ellipse
import numpy.random as rnd
import params
###Global Variables
peak_affinity = -8 # literally 10e-8, not influenced by minimum_affinity value
minimum_affinity = 2 # asymptotic affinity exponent, negligible
m = 1 #Hill Coefficient
ODOR_REPETITIONS = 2 #Amount of odorscene repetitions to create a smooth graph
ANGLES_REP = 2
#SD_NUMBER = 1.5
#SD_NUMBER = params.RECEPTOR_ELLIPSE_STANDARD_DEVIATION
###Global Variables when c!=1 (multiple conn between rec and glom)
glom_penetrance = .68 # primary glom:rec connection weight if c != 1
s_weights = [0.12,0.08,0.03,0.03,0.02,0.02,0.01,0.01] # The remaining glom:rec connection weights if c != 1
numRow = 6 # num of rows of glom
numCol = 5 # num of cols of glom (numRow*numCol = total number of Glom)
constant_attachments = True
class QSpace(object):
"""Defines the size of the sample space
***ex: [(0,5),(0,5)] means qspace extends from 0 to 5 (not including 5)
_size = [List of float tuples] defines the size of the sample space"""
def getSize(self):
#Returns the odors.
return self._size
def setSize(self, value):
"""Sets size equal to value.
Precondition: Value is a list of tuples"""
assert type(value) == list, "Value is not a list!"
assert type(value[0] == tuple), "Elements aren't tuples!"
self._size = value
def __init__(self, size):
self.setSize(size)
def __str__(self):
st = ""
for tup in self._size:
st = st + " " + str(tup)
return st[1:]
class Ligand(object):
"""Represents a simple smell embedded in Q space of dimensionality Q.
Instance Attributes:
_id = [Integer] identifies the odor
_loc = [List of floats] coordinates in chemical space. Dim=Q
_dim = [Integer] dimension of ligand (Q)
_conc = [float] concentration in molar, e.g., 1.5e-5 (NOT 0)
_aff = [float] temporary affinity value for a specific receptor
_eff = [float] temporary efficacy value for a specific receptor [0..1]
_occ = [float] temporary partial occupancy value for a specific receptor [0..1]
_affs = [list of floats] affs for all recepters
_effs = [list of floats] effs for all recepters
_odors2 = [list of ordors/ligands] nested for faster calcs
"""
#Getters and Setters
def getId(self):
"""Returns the id."""
return self._id
def setId(self, value):
"""Sets id equal to value.
Precondition: Value is an int"""
assert type(value) == int, "Value is not a int!"
self._id = value
def getLoc(self):
"""Returns the loc."""
return self._loc
def setLoc(self, value):
"""Sets loc equal to value.
Precondition: Value is a List"""
assert type(value) == list, "Value is not a List!"
self._loc = value
def getDim(self):
"""Returns the dim."""
return self._dim
def setDim(self, value):
"""Sets dim equal to value.
Precondition: Value is an int"""
assert type(value) == int, "Value is not a int!"
self._dim = value
def getConc(self):
"""Returns the conc."""
return self._conc
def setConc(self, value):
"""Sets conc equal to value.
Precondition: Value is a nonZero number"""
assert type(value) in [int,float], "Value is not a number!"
assert value != 0, "Conc can't be 0!"
self._conc = float(value)
def setAff(self, value):
"""Sets aff equal to value.
Precondition: Value is a float"""
assert type(value) == float, "Value is not a float!"
self._aff = value
def setEff(self, value):
"""Sets eff equal to value.
Precondition: Value is a float btwn 0..1"""
assert type(value) == float, "Value is not a float!"
assert value >= 0 and value <= 1, "Eff is not btwn 0 and 1"
self._eff = value
def setOcc(self, value):
"""Sets occ equal to value.
Precondition: Value is an float btwn 0..1"""
assert type(value) == float, "Value is not a float!"
assert value >= 0.0 and value <= 1.0, "Occ is not btwn 0 and 1"
self._occ = value
def appendToAffs(self, value):
"""adds aff equal to value.
Precondition: Value is a float"""
assert type(value) == float, "Value is not a float!"
self._affs.append(value)
def appendToEffs(self, value):
"""adds eff equal to value.
Precondition: Value is a float"""
assert type(value) == float, "Value is not a float!"
self._effs.append(value)
def appendToOdors2(self, value):
"""adds odor2 equal to value.
Precondition: odor2 is type of Ligand"""
assert type(value) == Ligand, "Value is not a Ligand!"
self._odors2.append(value)
def getOdors2(self):
"""Returns _odors2."""
return self._odors2
#Initializer
def __init__(self, Id, loc, conc):
"""Initializes ligand"""
self.setId(Id)
self.setLoc(loc)
self.setDim(len(loc))
self.setConc(conc)
self._aff = 0.0
self._eff = 0.0
self._occ = 0.0
self._affs = []
self._effs = []
self._odors2 = []
def __str__(self):
"""Returns description of Ligand"""
return "ID: " + str(self._id) + " Loc: " + str(self._loc) + " Conc: " + str(self._conc)
class Odorscene(object):
"""Represents a list of ligands embedded in Q-Space. Can resemble an odorant, a complex odorant,
or a mixture of odorants.
Instance Attributes:
_id = [Integer] identifies the odor
_dim = [Integer] dimension of odorscene (same as dim of attached ligands)
_odors = [List of ligands] List of ligands that define the odorscene
"""
#Getters and Setters
def getId(self):
"""Returns the id."""
return self._id
def setId(self, value):
"""Sets id equal to value.
Precondition: Value is an int"""
assert type(value) == int, "Value is not a int!"
self._id = value
def getDim(self):
"""Returns the dim."""
return self._dim
def setDim(self, value):
"""Sets dim equal to value.
Precondition: Value is an int"""
assert type(value) == int, "Value is not a int!"
self._dim = value
def getOdors(self):
"""Returns the odors."""
return self._odors
def setOdors(self, value):
"""Sets odors equal to value.
Precondition: Value is a List and dim of elements are equal."""
assert type(value) == list, "Value is not a List!"
self._odors = []
i = 0
while i < len(value):
assert value[0].getDim() == value[i].getDim(), "Odors aren't all the same dim."
self._odors.append(value[i])
i += 1
#Initializer
def __init__(self, Id, odors):
"""Initializes odorscene"""
self.setId(Id)
self.setDim(odors[0].getDim())
self.setOdors(odors)
def __str__(self):
"""Returns description of Odor"""
st = ""
for odor in self._odors:
st = st + str(odor) + '\n'
return "ID: " + str(self._id) + '\n' + "Odors: \n" + st
class Receptor(object):
"""Represents an odor receptor with center (x,y,z...) and radius of
sensitivity r.
Instance Attributes:
_id = [int] identifies the receptor
_mean = [list] list of means for affinity and efficacy Gaussian distributions. Length = Q
_sdA = [list] List of standard deviations for affinity. Length = Q
_sdE = [list] List of standard deviations for efficacy. Length = Q
_covA = [list] sdA ^^ 2
_covE = [list] sdE ^^ 2
_scale = [float] A heuristic scalar value for the "strongest available affinity"
_effScale = [float] A heuristic scalar value for the "strongest available affinity"
_activ = [float] Total activation level of receptor
_occ = [float] Total occupancy of receptor
_affs = np.array([]) aff values of all odors for this receptor
_effs = np.array([]) eff values of all odors for this receptor
"""
#Getters and Setters
def getId(self):
"""Returns id of receptor."""
return self._id
def setId(self, value):
"""Sets id to value
Precondtion: value is an int"""
assert type(value) == int, "Value is not a int!"
self._id = value
def getMean(self):
"""Returns mean of receptor."""
return self._mean
def setMean(self, value):
"""Sets id to value
Precondtion: value is an list"""
assert type(value) == list, "Value is not a float!"
self._mean = value
def getSdA(self):
"""Returns the standard deviations for Affinity."""
return self._sdA
def setSdA(self, value):
"""Sets sdA equal to value.
Precondition: Value is a List with dim Q"""
assert type(value) == list, "Value is not a List!"
assert len(value) == len(self._mean), "Dimension is not consistent with dim of mean"
self._sdA = value
def getSdE(self):
"""Returns the standard deviations for Efficacy."""
return self._sdE
def setSdE(self, value):
"""Sets sdE equal to value.
Precondition: Value is a List with dim Q"""
assert type(value) == list, "Value is not a List!"
assert len(value) == len(self._mean), "Dimension is not consistent with dim of mean"
self._sdE = value
def getCovA(self):
"""Returns the covariance for affinity"""
return self._covA
def setCovA(self):
"""Sets covariance of affinity by squaring the sd."""
covA = []
i = 0
while i < len(self._sdA):
covA.append(self._sdA[i]**2)
i += 1
self._covA = covA
def getCovE(self):
"""Returns the covariance for Efficacy"""
return self._covE
def setCovE(self):
"""Sets covariance of Efficacy by squaring the sd."""
covE = []
i = 0
while i < len(self._sdE):
covE.append(self._sdE[i]**2)
i += 1
self._covE = covE
def getScale(self):
"""Returns scale of receptor."""
return self._scale
def setScale(self):
"""Sets scale based on mean"""
self._scale = mvn.pdf(self.getMean(), self.getMean(), self.getCovA())
def getEffScale(self):
"""Returns eff scale of receptor."""
return self._effScale
def setEffScale(self):
"""Sets eff scale based on mean"""
self._effScale = float(mvn.pdf(self.getMean(), self.getMean(), self.getCovE()))
def getActiv(self):
return self._activ
def setActiv(self, value):
"""Sets activation level for receptor"""
self._activ = value
def setOcc(self, value):
"""Sets occupancy for receptor"""
self._occ = value
def setOdoAmt(self,value):
"""sets amount of ligands 'adjacent' (<2SD) to receptor"""
self._odoAmt = value
def getAffs(self):
"""Returns affs for all ordors"""
return self._affs
def setAffs(self, value):
"""Sets affs for all ordors"""
self._affs = value
def getEffs(self):
"""Returns effs for all ordors"""
return self._effs
def setEffs(self, value):
"""Sets effs for all ordors"""
self._effs = value
#Initializer
def __init__(self, Id, mean, sda, sde):
"""Initializes a receptor."""
self.setId(Id)
self.setMean(mean)
self.setSdA(sda)
self.setSdE(sde)
self.setCovA()
self.setCovE()
self.setScale()
self.setActiv(0)
self.setOcc(0)
self.setOdoAmt(0)
self.setEffScale()
def __str__(self):
"""Returns receptor description"""
st = ""
for num in self.getMean():
st = st + str(num) + ", "
return "ID " + str(self._id) + " Mean: " + st[:-2] + "." #Can add mean if prefer
class Epithelium(object):
"""Represents a list of receptors.
Instance Attributes:
_recs = [List of receptors]
"""
def getRecs(self):
"""Returns the receptors."""
return self._recs
def setRecs(self, value):
"""Sets receptors equal to value.
Precondition: Value is a List"""
assert type(value) == list, "Value is not a List!"
self._recs = value
def __init__(self, recs):
"""Initializes a epithelium."""
self.setRecs(recs)
def __str__(self):
"""Returns epithelium description"""
st = "Epithelium contains the following receptors: \n"
for recs in self.getRecs():
st = st + str(recs) + "\n"
return st[:-2]
class Text(object):
"""Holding experimental text to later store in text file"""
def __init__(self, st, name):
self._st = st
self._name = name
self._st2 = ""
######Functions for objects
def createLigand(dim, conc, qspace, ID=0):
"""Returns an ligand with randomly (uniformly) generated ligand point coordinates
in Q space."""
i = 0
loc = []
while (i<dim):
loc.append(random.uniform(-1000, 1000))
i += 1
return Ligand(ID, loc, conc)
def createOdorscene(dim, conc, amt, qspace, Id = 0):
"""Returns an odorscene object with a certain amount of randomly generated ligands.
Conc is a list of concentrations and amt is the amt of each conc (matched by index).
Ex: conc = [1e-5, 5e-6, 1e-6] and amt = [6, 4, 2] This means:
six randomly generated ligands at 1x10e-5 molar, four at 5x10e-6 molar,
and two at 1x10e-6 molar.
qspace is a qspace object.
Precondition: Conc and amt are lists of equal length"""
assert len(conc) == len(amt), "conc and amt are not lists of equal length"
odors = []
ID = 0
i = 0
while i < len(amt):
ind = 0
while ind < amt[i]:
odor = createLigand(dim, conc[i], qspace, ID)
odor = modifyLoc(odor, qspace, dim)
odors.append(odor)
ind += 1
ID += 1
i += 1
return Odorscene(Id, odors)
def modifyLoc(odorant, qspace, dim):
"""Modifies an odorant's location to be within the given qspace of the odorscene
Precondition: QSpace dimensions are consistent with dim"""
assert len(qspace.getSize()) == dim, "QSpace dimensions are not consistent with ligand locations"
i = 0
loc = odorant.getLoc()
while i < dim:
loc[i] = ((loc[i] + (abs(qspace.getSize()[i][0]))) % (abs(qspace.getSize()[i][0]) +
abs(qspace.getSize()[i][1]))) + -1 * abs(qspace.getSize()[i][0])
i += 1
odorant.setLoc(loc)
return odorant
def createEpithelium(n, dim, qspace, scale=[.5,1.5], scaleEff=[], constMean=False):
"""Returns an epithelium with n receptors by calling createReceptor n times.
SD of each receptor is a uniformly chosen # btwn scale[0] and scale[1]
Precondition: n is an int"""
assert type(n) == int, "n is not an integer"
i = 0
recs= []
while i < n:
recs.append(createReceptor(dim, qspace, scale, scaleEff, constMean, i))
i += 1
return Epithelium(recs)
def createReceptor(dim, qspace, scale=[0.5,1.5], scaleEff=[], constMean=False, Id=0):
"""Creates a receptor using meanType sdAtype and sdEtype as descriptions
to how to randomly distribute those values.
scaleEff is empty unless want to have a diff sd for aff and eff.
Precondition: qspace must have "dim" dimensions"""
assert len(qspace._size) == dim, "Qspace doesn't have right dimensions"
mean = _distributeMean(dim, qspace, constMean)
sdA = _distributeSD(dim, scale, [])
sdE = _distributeSD(dim, scale, scaleEff)
return Receptor(Id, mean, sdA, sdE)
def _distributeMean(dim, qspace, constMean):
"""Returns a list of means randomly distributed within the qspace based on the Type"""
mean = []
i = 0
if constMean:
while i < dim:
mean.append(qspace.getSize()[i][1]/2.0)
i+=1
else:
while i < dim:
if params.DIST_TYPE_UNIF:
mean.append(random.uniform(qspace.getSize()[i][0], qspace.getSize()[i][1]))
elif params.DIST_TYPE_GAUSS:
while True:
g = random.gauss(params.MU, params.SIG)
#if ((i==0 and g <= qspace.getSize()[i][1] and g >= 0) or (i==1 and g <= qspace.getSize()[i][1]) and g >= 0):
if (g <= qspace.getSize()[i][1] and g >= 0):
mean.append(g)
break
#mean.append(random.gauss(params.MU, params.SIG))
i += 1
return mean
def _distributeSD(dim, scale, scaleEff):
"""Returns a list of standard deviations between scale[0] and scale[1] randomly distributed based on the Type
Precondition: scale is a 2d list with #'s>=0"""
assert scale[0] > 0, "scale is not a valid list"
sd = []
i = 0
if len(scaleEff) == 0: #Want sd for aff and eff to be the same
while i < dim:
sd.append(random.uniform(scale[0],scale[1]))
i += 1
else:
while i < dim:
sd.append(random.uniform(scaleEff[0],scaleEff[1]))
i += 1
return sd
######## Activating Receptors/corresponding GL
def ActivateGL_QSpace(epith, odorscene, gl, fixed=True, c=1, sel="avg"):
"""Given an epithelium, odorscene, and Glomerular Layer, the GL is activated based on
its corresponding 1:1 receptors. Returns string of data about odorscene and epithelium.
If c!=1 (convergence ratio of glom:rec, then use updated function to calc non 1:1 glom:rec activation.
Precondition: Epith and odorscene have the same dimension Q and # of receptors = len(gl)"""
assert len(epith.getRecs()[0].getMean()) == odorscene.getOdors()[0].getDim(), "Dimensions aren't equal"
assert len(epith.getRecs()) == len(gl), "Receptors:GL is not 1:1"
layers.clearGLactiv(gl)
#Loop through each receptor and eventually calculate activation level
for rec in epith.getRecs():
#Set everything to 0
activ = 0.0
odors = []
df = 0
effScale = float(mvn.pdf(rec.getMean(), rec.getMean(), rec.getCovE()) )
for odor in odorscene.getOdors():
#First odorscene
aff = mvn.pdf(odor.getLoc(), rec.getMean(), rec.getCovA())
aff = aff / rec.getScale() #Scales it from 0 to 1
#Now convert gaussian aff to kda
aff = 10**((aff * (peak_affinity - minimum_affinity)) + minimum_affinity) ##peak_affinity etc. are global variables
#print "aff is " + str(aff)
odor.setAff(float(aff))
if fixed:
odor.setEff(1.0)
else:
eff = mvn.pdf(odor.getLoc(), rec.getMean(), rec.getCovE())
eff = float(eff) / effScale #Scales it from 0 to 1
odor.setEff(eff)
#print "eff is " + str(eff)
odors.append(odor)
df += odor.getConc()/odor._aff
i = 1
for odor in odors:
odor.setOcc( (1) / (1 + ( (odor._aff/odor.getConc()) * (1 + df - (odor.getConc() / odor._aff ) ) ) **m) ) #m=1
activ += odor._eff * odor._occ
#print "Occ is: " + str(odor._occ)
#print str(i) + " activation due to odorscene 1: " + str(activ_1)
i += 1
#print "activ level for rec " + str(activ)
rec.setActiv(activ)
gl[rec.getId()].setActiv(activ)
if c != 1:
glomRecConnNew(epithelium.getRecs(), gl, c)
#######Loading and Saving objecsts using CSV files
def saveLigand(odor, name):
"""Stores odor as one row in a CSV file with the following columns:
A = ID# of ligand
B = text label ('odorant membership')
C = concentration of ligand in molar
D...(Q-3) = the Q coordinates of the ligand point
Precondtion: Name is a str"""
assert type(name) == str, "name is not a string"
st = "ID, Label, Conc "
i = 0
while i < odor.getDim():
st = st + ", coord " + str(i)
i += 1
st = st + "\n" + str(odor.getId()) + ",' '," + str(odor.getConc())
for loc in odor.getLoc():
st = st + "," + str(loc)
test = open(name + ".csv", "w")
test.write(st)
test.close
def saveOdorscene(odorScene, name):
"""Stores odor as a CSV file with the following format:
First and second row: contains ID and dim of odorscene
Every row after that symbolizes an odor with the following columns:
A = ID# of ligand
B = text label ('odorant membership')
C = concentration of ligand in molar
D...(Q-3) = the Q coordinates of the ligand point
Precondtion: Name is a str"""
assert type(name) == str, "name is not a string"
st = "\n OdorSceneID, dim \n"
st = st + str(odorScene.getId()) + "," + str(len(odorScene.getOdors())) + '\n'
st = st + "ID, Label, Conc "
i = 0
while i < odorScene.getOdors()[0].getDim():
st = st + ", coord " + str(i)
i += 1
for odor in odorScene.getOdors():
st = st + "\n" + str(odor.getId()) + ",' '," + str(odor.getConc())
for ii, loc in enumerate(odor.getLoc()):
st = st + "," + str(loc)
test = open(name + ".csv", "a")
test.write(st)
test.close
"""
plt.plot(xaxis,yaxis, label="Odor Locations")
plt.legend()
plt.title("All Odors")
plt.xlabel("x coordinates")
plt.ylabel("y coordinates")
#Set y_axis limit
#axes = plt.gca()
#axes.set_ylim([0,1.0]) #*****Change if using >30 recs
pp = PdfPages('All Odors.pdf')
pp.savefig()
pp.close()
if close == True: #No more data to add to the graph
plt.close()
"""
def loadLigand(name, helper=False):
"""Returns an ligand from a CSV file with the given name.
If helper is true, then it's being called from loadOdorscene and we
don't want to skip the first line.
Precondition: name exists and it's in CSV format AND the file is <= 2 lines"""
assert type(name) == str, "name isn't a string"
if helper == False:
text = open(name)
i = 0
for l in text: #essentially just skip the first line and save the second
if i == 1:
line = l
i += 1
else:
line = name
comma1 = line.find(",")
comma2 = line.find(",", comma1+1)
comma3 = line.find(",", comma2+1) #Comma before first loc coord
commas = [line.find(",", comma3+1)]
k = 0
while commas[-1] != -1:
commas.append(line.find(",", commas[k] + 1))
k+=1
ID = int(line[:comma1])
conc = float(line[comma2+1:comma3])
index = 0
loc = [float(line[comma3+1:commas[index]])]
while commas[index] != -1:
loc.append(float(line[commas[index]+1:commas[index+1]])) #when commas[index+1]=-1 it cuts off the last digit
index += 1
loc[index] = float(str(loc[index]) + line[-1]) #Accounts for missing digit
if helper == False:
text.close()
return Ligand(ID, loc, conc)
def loadOdorscene(name):
"""Returns an odorscene from a CSV file with the given name.
Precondtion: name existsand it's in CSV format"""
assert type(name) == str, "name isn't a string"
text = open(name)
i = 0
odors = []
for line in text:
if i == 1:
comma1 = line.find(",")
Id = int(line[:comma1])
if i > 2:
odors.append(loadLigand(line, True))
i += 1
text.close()
return Odorscene(Id, odors)
def saveReceptor(rec, name, helper=False):
"""Stores receptor as one row in a CSV file with the following columns:
A = ID# of receptor
B = text label ('receptor membership')
C...X = list of mean
X...Y = list of SD for affinity
y...Z = list of SD for efficacy
Precondtion: Name is a str"""
assert type(name) == str, "name is not a string"
dim = len(rec.getMean())
i = 0
st = ''
m = ''
a = ''
e = ''
mean = ''
aff = ''
eff = ''
while i < dim:
m = m + ", Mean " + str(i)
a = a + ", Aff " + str(i)
e = e + ", Eff " + str(i)
mean = mean + "," + str(rec.getMean()[i])
aff = aff + "," + str(rec.getSdA()[i])
eff = eff + "," + str(rec.getSdE()[i])
i += 1
if helper == False:
st = st + "ID, Label" + m + a + e + '\n'
st = st + str(rec.getId()) + ",' '" + mean + aff + eff
if helper:
return st
test = open(name + ".csv", "w")
test.write(st)
test.close
def saveEpithelium(epi, name):
"""Stores each receptor as one row in a CSV file with the following columns:
A = ID# of receptor
B = text label ('receptor membership')
C...X = list of mean
X...Y = list of SD for affinity
y...Z = list of SD for efficacy
Precondtion: Name is a str"""
assert type(name) == str, "name is not a string"
st = ''
m = ''
a = ''
e = ''
i = 0
while i < len(epi.getRecs()[0].getMean()):
m = m + ", Mean " + str(i)
a = a + ", Aff " + str(i)
e = e + ", Eff " + str(i)
i += 1
st = st + "ID, Label" + m + a + e + '\n'
for rec in epi.getRecs():
st = st + saveReceptor(rec, name, True) + '\n'
test = open(name + ".csv", "w")
test.write(st)
test.close
def loadReceptor(name, helper=False):
"""Returns a receptor from a CSV file with the given name.
If helper is true, then it's being called from loadEpithelium and some
adjustments are made.
Precondition: name exists and it's in CSV format AND the file is <= 2 lines"""
assert type(name) == str, "name isn't a string"
if helper == False:
text = open(name)
i = 0
for l in text: #essentially just skip the first line and save the second
if i == 1:
line = l
i += 1
else:
line = name
comma1 = line.find(",")
comma2 = line.find(",", comma1+1) #Comma before first mean coord
commas = [line.find(",", comma2+1)]
i = 0
while commas[i] != -1:
commas.append(line.find(",", commas[i]+1))
i += 1
dim = len(commas) / 3
Id = int(line[:comma1])
mean = [float(line[comma2+1:commas[0]])]
index = 1
while index < dim:
mean.append(float(line[commas[index-1]+1:commas[index]]))
index += 1
aff = []
while index < (2*dim):
aff.append(float(line[commas[index-1]+1:commas[index]]))
index += 1
eff = []
while index < (3*dim):
eff.append(float(line[commas[index-1]+1:commas[index]])) #Last index of aff loses last digit due to -1
index += 1
eff[dim-1] = float(str(eff[dim-1]) + line[-1]) #Accounts for missing digit
if helper == False:
text.close()
return Receptor(Id, mean, aff, eff)
def loadEpithelium(name):
"""Returns an epithelium from a CSV file with the given name.
Precondition: name exists and it's in CSV format"""
assert type(name) == str, "name isn't a string"
recs = []
text = open(name)
i = 0
for line in text:
if i > 0:
recs.append(loadReceptor(line, True))
i += 1.
text.close()
return Epithelium(recs)
##### Making a list of sequentially different odorscenes
#createOdorscene(dim, conc, amt, qspace, Id = 0)
def sequentialOdorscenes(n, amt, dim, change, qspace):
"""Returns a list of n odorscenes, each one differs by change
Amt=amount of ligand per odorscene
warning: Doesn't call modify loc so loc could be out of qspace range"""
odorscenes = []
ligands = []
#make amt ligands starting with [0,0,0...],[.1,.1,.1...]
i = 0
while i < amt:
loc = []
x = 0
while x < dim:
loc.append(i/10.0)
x += 1
ligands.append(Ligand(i, loc, 1e-5))
i += 1
odorscenes.append(Odorscene(0, ligands))
#Creating rest of odorscenes
i = 1
while i < n:
ligands = []
numOdors = 0
odors = odorscenes[i-1].getOdors()
while numOdors < amt:
newOdorLoc = []
for num in odors[numOdors].getLoc():
newOdorLoc.append(num + change)
ligands.append(Ligand(numOdors, newOdorLoc, 1e-5))
numOdors += 1
odorscenes.append(Odorscene(i, ligands))
i += 1
return odorscenes
####### Sum of Squares differentiation calculation - original
##Definitions: phi = receptor activation
## dphi = difference in receptor activation due to two diff odorscenes
## dpsi = difference in epithelium activation due to two diff odorscenes
## Maximum dpsi value = # of receptors in epithelium (if the first odorscene
## always activates the receptor = 1.0 and the other activates = 0.0)
def sumOfSquares(epithelium, odorscene, dn, fixed=False, c=1, gl=[]):
"""Calculates differentiation between epithelium activation of odorscene before
and after dn using sum of squares. Returns dpsi of the epithelium.
If fixed=true, then efficacy will be fixed at 1 (only agonists)
If c!=1, then use function to activate glom with 1:c ratio of Glom:Rec
Precondtion: dn=list in correct dim"""
assert odorscene.getDim()== len(dn), "dimension not consistent with dn"
dPsi = 0
recs2 = copy.deepcopy(epithelium.getRecs())
layers.clearGLactiv(gl) #Sets gl activations and recConn back to 0.0
counter = 0 #for storing info in rec2
for rec in epithelium.getRecs():
#Set everything to 0
activ_1 = 0.0
activ_2 = 0.0
totOcc = 0.0
odors = []
odors2 = []
rec._activ = 0.0
rec._occ = 0.0
rec._odoAmt = 0.0
df = 0
df2 = 0
dphi = 0
effScale = float(mvn.pdf(rec.getMean(), rec.getMean(), rec.getCovE()) )
for odor in odorscene.getOdors():
#First odorscene
aff = mvn.pdf(odor.getLoc(), rec.getMean(), rec.getCovA())
aff = aff / rec.getScale() #Scales it from 0 to 1
#Now convert gaussian aff to kda
aff = 10**((aff * (peak_affinity - minimum_affinity)) + minimum_affinity) ##peak_affinity etc. are global variables
#print "aff is " + str(aff)
odor.setAff(float(aff))
if fixed:
odor.setEff(1.0)
else:
eff = mvn.pdf(odor.getLoc(), rec.getMean(), rec.getCovE())
eff = float(eff) / effScale #Scales it from 0 to 1
odor.setEff(eff)
odors.append(odor)
df += odor.getConc()/odor._aff
#Second Odorscene
newLoc = [] #Calculating new location
index = 0
while index < len(dn):
newLoc.append(odor.getLoc()[index] + dn[index])
index += 1
newOdor = Ligand(odor.getId(), newLoc, odor.getConc())
aff2 = mvn.pdf(newLoc, rec.getMean(), rec.getCovA())
aff2 = aff2 / rec.getScale() #Scales it from 0 to 1
aff2 = 10**((aff2 * (peak_affinity - minimum_affinity)) + minimum_affinity)
#print "aff2 is " + str(aff2)
newOdor.setAff(float(aff2))
if fixed:
newOdor.setEff(1.0)
else:
eff2 = mvn.pdf(newLoc, rec.getMean(), rec.getCovE())
eff2 = float(eff2) / effScale #Scales it from 0 to 1
newOdor.setEff(eff2)
odors2.append(newOdor)
df2 += newOdor.getConc()/newOdor._aff
i = 1
for odor in odors:
odor.setOcc( (1) / (1 + ( (odor._aff/odor.getConc()) * (1 + df - (odor.getConc() / odor._aff ) ) ) **m) ) #m=1
activ_1 += odor._eff * odor._occ
rec._occ += odor._occ #Solely for printing individual receptor activations in experiments
rec._odoAmt += adjOdors(rec, odor)
#print str(i) + " activation due to odorscene 1: " + str(activ_1)
i += 1
i = 1
rec.setActiv(activ_1) #Solely for printing individual receptor activations in experiments
for odor2 in odors2:
odor2.setOcc( (1) / (1 + ( (odor2._aff/odor2.getConc()) * (1 + df2 - (odor2.getConc() / odor2._aff ) ) ) **m) ) #m=1
activ_2 += odor2._eff * odor2._occ
#print str(i) + " activation due to odorscene 2: " + str(activ_2)
i += 1
recs2[counter].setActiv(activ_2)