-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathget_initial_specie_information.py
1307 lines (1132 loc) · 51.7 KB
/
get_initial_specie_information.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 -*-
from __future__ import division
import subprocess
import collections
import sys
import random
import argparse
import re
import numpy as np
import os.path
#import lxml
try:
from lxml import etree
print("running with lxml.etree")
except ImportError:
sys.exit("Do install lxml")
default_fn = ['all_species']
#Area calculation is going to be wrong in case of vertical dendrites -- Correct!!!
def calculate_volume_and_area(mesh_filename,segment_voxels,segment_area_voxels):
''' Function calculating volume of every segment present in the mesh file and
the information provided in the header of the results file.
'''
try:
meshfile = open(mesh_filename)
except IOError:
sys.exit('No such file or directory '+meshfile)
legend = meshfile.readline().split()
element_index = legend.index('element_index')
volume_index = legend.index('volume')
depth2D_index = legend.index('deltaZ')
x0_index = legend.index('x0')
y0_index = legend.index('y0')
z0_index = legend.index('z0')
x1_index = legend.index('x1')
y1_index = legend.index('y1')
z1_index = legend.index('z1')
volumes_dict = {}
areas_dict = {}
print segment_voxels
print 'submembrane', segment_area_voxels
for line in meshfile:
words = line.split()
voxel_index = int(words[element_index])
for key in segment_voxels:
if voxel_index in segment_voxels[key]:
if key in volumes_dict:
volumes_dict[key] = volumes_dict[key] + float(words[volume_index])
else:
volumes_dict[key] = float(words[volume_index])
for key in segment_area_voxels:
if voxel_index in segment_area_voxels[key]:
area = ((float(words[x0_index])-float(words[x1_index]))**2
+(float(words[y0_index])-float(words[y1_index]))**2
+(float(words[z0_index])-float(words[z1_index]))**2)**0.5*float(words[depth2D_index])
if key in areas_dict:
areas_dict[key] = areas_dict[key] + area
else:
areas_dict[key] = area
return areas_dict, volumes_dict
def read_header(headerline):
'''
Function parsing the header line of the results file.
'''
regions = set()
segment_voxels = collections.OrderedDict() #numbers of voxels of each segment
segment_area_voxels = collections.OrderedDict() #numbers of voxels of each segment surface
special_points = collections.OrderedDict() #labeled voxels
specie_type_dict = collections.OrderedDict()
# Return a list of the words in the string, using sep as the delimiter string.
for col,word in enumerate(headerline.split()[1:]):
information = word.split('_')
voxel_number = int(information[1])
spc_index = information.index('Spc')
specie_name = information[spc_index+1]
for part in information[spc_index+2:]:
specie_name = specie_name +'_' + part
if 'cytosol' in information:
voxel_type_index = information.index('cytosol')
elif 'submembrane' in information:
voxel_type_index = information.index('submembrane')
segment_name = information[2]
for i in range(3,voxel_type_index-1):
segment_name = segment_name + '_' + information[i]
if information[voxel_type_index] == 'submembrane':
if segment_name not in segment_area_voxels:
segment_area_voxels[segment_name] = [voxel_number]
elif voxel_number not in segment_area_voxels[segment_name]:
segment_area_voxels[segment_name].append(voxel_number)
if voxel_type_index + 1 != spc_index:
if information[voxel_type_index + 1] not in special_points:
special_points[information[voxel_type_index + 1]] = [voxel_number]
if segment_name not in segment_voxels:
segment_voxels[segment_name] = [voxel_number]
elif voxel_number not in segment_voxels[segment_name]:
#add the number of the voxel, only if it wasn't already added
segment_voxels[segment_name].append(voxel_number)
if segment_name not in regions and 'default' not in segment_name:
regions.add(segment_name)
if specie_name not in specie_type_dict:
specie_type_dict[specie_name] = collections.OrderedDict()
if segment_name not in specie_type_dict[specie_name]:
specie_type_dict[specie_name][segment_name] = collections.OrderedDict()
if information[voxel_type_index] not in specie_type_dict[specie_name][segment_name]:
specie_type_dict[specie_name][segment_name][information[voxel_type_index]] = [col+1]
else:
specie_type_dict[specie_name][segment_name][information[voxel_type_index]].append(col+1)
if voxel_type_index + 1 != spc_index:
specie_type_dict[specie_name][segment_name][information[voxel_type_index+1]] = [col+1]
return segment_voxels,segment_area_voxels,special_points, specie_type_dict, regions
def get_numbers_from_a_fileline(s,specie_type_dict):
'''
Read numbers of specie molecules in each voxel calculate number of each specie
molecules in the cytosol and submembrane of the segments
'''
if isinstance(s,str):
words = s.split()
else:
words = s
number_specie_segment = collections.OrderedDict()
for specie in specie_type_dict:
number_specie_segment[specie] = collections.OrderedDict()
for segment in specie_type_dict[specie]:
number_specie_segment[specie][segment]= collections.OrderedDict()
for voxel_type in specie_type_dict[specie][segment]:
number_specie_segment[specie][segment][voxel_type] = 0
for i in specie_type_dict[specie][segment][voxel_type]:
try:
how_much = int(words[i])
except ValueError:
sys.exit('Broken -conc.txt file')
number_specie_segment[specie][segment][voxel_type] = number_specie_segment[specie][segment][voxel_type] + how_much
return number_specie_segment
def concentrations(number_specie_segment,specie_location_dict,area_dict, vol_dict ):
'''
calculate specie concentrations in the submembrane and the cytosol.
'''
conc_dict = collections.OrderedDict()
conc_dict['cytosol'] = collections.OrderedDict()
conc_dict['submembrane'] = collections.OrderedDict()
for voxel_type in specie_location_dict:
for segment in specie_location_dict[voxel_type]:
for specie in specie_location_dict[voxel_type][segment]:
if segment not in conc_dict[voxel_type]:
conc_dict[voxel_type][segment] = collections.OrderedDict()
if voxel_type == 'submembrane':
conc_dict['submembrane'][segment][specie] = number_specie_segment[specie][segment]['submembrane']/area_dict[segment]*10/6.022
elif voxel_type == 'cytosol':
conc_dict[voxel_type][segment][specie] = number_specie_segment[specie][segment]['cytosol']
if 'submembrane' in number_specie_segment[specie][segment]:
conc_dict[voxel_type][segment][specie] += number_specie_segment[specie][segment]['submembrane']
conc_dict[voxel_type][segment][specie] = conc_dict[voxel_type][segment][specie]/vol_dict[segment]*10/6.022
return conc_dict
def totals(number_specie_segment,specie_location_dict,area_dict, vol_dict ):
'''
calculate total specie amounts in the submembrane and the cytosol.
'''
totals_dict = collections.OrderedDict()
totals_dict['cytosol'] = collections.OrderedDict()
totals_dict['submembrane'] = collections.OrderedDict()
for voxel_type in specie_location_dict:
for segment in specie_location_dict[voxel_type]:
for specie in specie_location_dict[voxel_type][segment]:
if segment not in totals_dict[voxel_type]:
totals_dict[voxel_type][segment] = collections.OrderedDict()
if voxel_type == 'submembrane':
totals_dict['submembrane'][segment][specie] = number_specie_segment[specie][segment]['submembrane']
elif voxel_type == 'cytosol':
totals_dict[voxel_type][segment][specie] = number_specie_segment[specie][segment]['cytosol']
if 'submembrane' in number_specie_segment[specie][segment]:
totals_dict[voxel_type][segment][specie] += number_specie_segment[specie][segment]['submembrane']
totals_dict[voxel_type][segment][specie] = totals_dict[voxel_type][segment][specie]
return totals_dict
def get_all_species(root):
'''
Read Initial Conditions file and make a set of species in the Initial Conditions file.
'''
species = set()
submembrane_species = root.xpath('//PicoSD')
cytosol_species = root.xpath('//NanoMolarity')
for specie in submembrane_species:
species.add(specie.get("specieID"))
for specie in cytosol_species:
species.add(specie.get("specieID"))
return species
def get_all_species_from_reactions_file(root):
'''
Read the reactions file and return the set of all species.
'''
species = set()
for son in root:
if son.tag == 'Specie':
species.add(son.get('id'))
return species
def get_diffusible_species(root):
'''
Read the reactions file and return the list of all diffusible species.
'''
species = set()
for son in root:
if son.tag == 'Specie':
if float(son.get('kdiff')) > 0:
species.add(son.get('id'))
return species
def get_submembrane_species(fname,regions):
'''
Read the initial conditions file to gain information which species
are solely in the submembrane and which in the whole cytosol. Read the
reactions file to check, which species are diffusible and account for that.
'''
root = xml_root(fname)
ic_filename = (root.xpath('initialConditionsFile')[-1].text).strip()+'.xml'
root_ic = xml_root(ic_filename)
all_species = get_all_species(root_ic)
reac_filename = (root.xpath('reactionSchemeFile')[-1].text).strip()+'.xml'
root_reac = xml_root(reac_filename)
diff_species = get_diffusible_species(root_reac)
specie_location_dict = collections.OrderedDict()
specie_location_dict['submembrane'] = collections.OrderedDict()
specie_location_dict['cytosol'] = collections.OrderedDict()
for region in regions:
specie_location_dict['cytosol'][region] = []
if '.' not in region:
specie_location_dict['submembrane'][region] = []
for specie in diff_species:
for region in regions:
specie_location_dict['cytosol'][region].append(specie)
for son in root_ic:
reg = son.get('region')
if not reg:
where = regions.copy()
else:
where = []
for region in regions:
if region.startswith(reg):
where.append(region)
for grandson in son:
specie = grandson.get('specieID')
tag = grandson.tag
if specie not in diff_species:
if tag == 'NanoMolarity':
for region in where:
if region in specie_location_dict['submembrane']:
if specie in specie_location_dict['submembrane'][region]:
specie_location_dict['submembrane'][region].remove(specie)
if specie not in specie_location_dict['cytosol'][region]:
specie_location_dict['cytosol'][region].append(specie)
if tag == 'PicoSD':
for region in where:
if specie in specie_location_dict['cytosol'][region]:
specie_location_dict['cytosol'][region].remove(specie)
if specie not in specie_location_dict['submembrane'][region]:
specie_location_dict['submembrane'][region].append(specie)
return specie_location_dict
def xml_root(filename):
'''get root of an xml file.
'''
tree = etree.parse(filename)
root = tree.getroot()
return root
def xml_write_to_file(filename,root):
'''
write xml tree to a file
'''
f = open(filename,'w')
f.write(etree.tostring(root, pretty_print=True))
def write_output_file(specie_set,output_file,dt,output_filename,species='all'):
root = etree.Element('OutputScheme')
son = etree.SubElement(root,'OutputSet')
son.set('filename',output_filename)
son.set('dt',dt)
for specie in specie_set:
grandson = etree.SubElement(son,'OutputSpecie')
grandson.set('name',specie)
xml_write_to_file(output_file,root)
def prepare_initial_information(model_file, run_time,dt,every_specie=True,new_seed=False,new_add=''):
root_mf = xml_root(model_file)
initial_conditions_file = (root_mf.xpath('initialConditionsFile')[-1].text).strip()
if not initial_conditions_file.endswith('.xml'):
initial_conditions_file += '.xml'
reactions_file = (root_mf.xpath('reactionSchemeFile')[-1].text).strip()+ '.xml'
root_ic = xml_root(initial_conditions_file)
root_reac = xml_root(reactions_file)
all_species = get_all_species(root_ic)
all_species_reactions = get_all_species_from_reactions_file(root_reac)
if all_species != all_species_reactions:
print 'There are different species in the initial conditions file, than in the reactions file'
print 'Excessive species in the Initial Conditions file:'
print all_species.difference(all_species_reactions)
print 'Spiecies from the Reactions file not present in the Initial conditions file:'
print all_species_reactions.difference(all_species)
sys.exit('Do fix your xml files, please.')
if every_specie:
output_file = model_file[:-4]+'_whole_output'
former_output_file = root_mf.xpath('outputSchemeFile')[-1]
former_output_file.text = output_file
write_output_file(all_species,output_file+'.xml',dt,'all_species')
default_fn = ['all_species']
else:
output_file = root_mf.xpath('outputSchemeFile')[-1].text
if '.xml' not in output_file:
output_file += '.xml'
output_root = xml_root(output_file)
default_fn = [elem.get('filename') for elem in output_root.xpath('OutputSet')]
print default_fn
#change runtime to
if run_time == 'short':
run_time = (root_mf.xpath('fixedStepDt')[-1].text).strip()
elif not isinstance(run_time, basestring):
run_time = str(run_time)
if not run_time.isdigit():
sys.exit('Not a proper run time')
length = root_mf.xpath('runtime')[-1]
length.text = run_time
if new_seed:
seed_tag = root_mf.xpath('simulationSeed')
seed_tag[-1].text = str(new_seed)
if new_add == '':
new_add = 'new_seed_'+str(new_seed)
else:
new_add += new_add+'_new_seed_'+str(new_seed)
if not new_add:
new_model_fname = model_file[:-4] + '_runtime_' + run_time + '.xml'
else:
new_model_fname = model_file[:-4] +'_'+new_add+'_runtime_' + run_time + '.xml'
xml_write_to_file(new_model_fname,root_mf)
conc_file = [new_model_fname[:-4]+'-'+default+'-conc.txt' for default in default_fn]
mesh_file = new_model_fname[:-4]+'-mesh.txt'
return new_model_fname, default_fn
def short_run(filename,NeuroRD_path='home/asia/NeuroRD/stochdiff2.1.10.jar'):
process = subprocess.Popen(['java','-jar',NeuroRD_path,filename])
ret = process.wait()
return ret
def write_totals(fname, number_specie_segment):
f = open(fname,'w')
f.write('Totals\n')
for specie in number_specie_segment:
total = 0
for segment in number_specie_segment[specie]:
for voxel_type in number_specie_segment[specie][segment]:
if voxel_type in ['cytosol','submembrane']:
total += number_specie_segment[specie][segment][voxel_type]
f.write( specie +' '+str(total) +'\n')
def write_new_initial_conditions(fname,conc, area_dict,vol_dict,tolerance,threshold_small):
submembrane_species = set()
cytosol_species = set()
for segment in conc['submembrane']:
for specie in conc['submembrane'][segment]:
submembrane_species.add(specie)
for segment in conc['cytosol']:
for specie in conc['cytosol'][segment]:
cytosol_species.add(specie)
new_conc = collections.OrderedDict()
new_conc['all'] = collections.OrderedDict()
new_conc['submembrane'] = collections.OrderedDict()
new_conc['cytosol'] = collections.OrderedDict()
for specie in submembrane_species:
new_conc['submembrane'][specie] = collections.OrderedDict()
for segment in conc['submembrane']:
if specie in conc['submembrane'][segment]:
if conc['submembrane'][segment][specie] > 0:
new_conc['submembrane'][specie][segment] = conc['submembrane'][segment][specie]
else:
new_conc['submembrane'][specie][segment] = 0
for specie in cytosol_species:
new_conc['cytosol'][specie] = collections.OrderedDict()
for segment in conc['cytosol']:
if specie in conc['cytosol'][segment]:
if conc['cytosol'][segment][specie] > 0:
new_conc['cytosol'][specie][segment] = conc['cytosol'][segment][specie]
else:
new_conc['cytosol'][specie][segment] = 0
full_area = 0
all_area_segments = []
for segment in area_dict:
full_area += area_dict[segment]
all_area_segments.append(segment)
for specie in new_conc['submembrane']:
average_conc = 0
for segment in new_conc['submembrane'][specie]:
average_conc += new_conc['submembrane'][specie][segment]*area_dict[segment]
average_conc = average_conc/full_area
similar_segment_list = []
for segment in new_conc['submembrane'][specie]:
if new_conc['submembrane'][specie][segment] < threshold_small:
similar_segment_list.append(segment)
else:
if abs(new_conc['submembrane'][specie][segment]-average_conc)/average_conc <= tolerance:
similar_segment_list.append(segment)
if similar_segment_list != [] and sorted(similar_segment_list)!=sorted(all_area_segments):
average_conc = 0
area_denominator = 0
for segment in similar_segment_list:
average_conc += new_conc['submembrane'][specie][segment]*area_dict[segment]
area_denominator += area_dict[segment]
average_conc = average_conc /area_denominator
for segment in similar_segment_list:
new_conc['submembrane'][specie][segment] = average_conc
full_volume = 0
all_volume_segments = []
for segment in vol_dict:
full_volume += vol_dict[segment]
all_volume_segments.append(segment)
all_volume_segments_no_defaults = []
for region in all_volume_segments:
if 'fake' not in region:
all_volume_segments_no_defaults.append(region)
for specie in new_conc['cytosol']:
average_conc = 0
for segment in new_conc['cytosol'][specie]:
average_conc += new_conc['cytosol'][specie][segment]*vol_dict[segment]
average_conc = average_conc/full_volume
similar_segment_list = []
for segment in new_conc['cytosol'][specie]:
if new_conc['cytosol'][specie][segment] < threshold_small:
similar_segment_list.append(segment)
elif abs(new_conc['cytosol'][specie][segment]-average_conc)/average_conc <= tolerance:
similar_segment_list.append(segment)
if similar_segment_list != [] and sorted(similar_segment_list)!=sorted(all_volume_segments):
average_conc = 0
volume_denominator = 0
for segment in similar_segment_list:
average_conc += new_conc['cytosol'][specie][segment]*vol_dict[segment]
volume_denominator += vol_dict[segment]
average_conc = average_conc /volume_denominator
similar_segment_list_no_defaults = []
for region in similar_segment_list:
if 'fake' not in region:
similar_segment_list_no_defaults.append(region)
if sorted(similar_segment_list_no_defaults) == sorted(all_volume_segments_no_defaults):
new_conc['all'][specie] = average_conc
del new_conc['cytosol'][specie]
else:
for segment in similar_segment_list:
new_conc['cytosol'][specie][segment] = average_conc
v_type_dict = {'cytosol':'ConcentrationSet',
'submembrane':'SurfaceDensitySet',
'all':'ConcentrationSet'
}
conc_type_dict = {'cytosol':'NanoMolarity',
'submembrane':'PicoSD',
'all':'NanoMolarity'
}
root = etree.Element('InitialConditions')
new_conc_2 = collections.OrderedDict()
new_conc_2['submembrane'] = collections.OrderedDict()
new_conc_2['cytosol'] = collections.OrderedDict()
new_conc_2['all'] = collections.OrderedDict()
for specie in new_conc['all']:
new_conc_2['all'][specie] = new_conc['all'][specie]
for voxel_type in ['cytosol','submembrane']:
for specie in new_conc[voxel_type]:
for segment in new_conc[voxel_type][specie]:
if 'fake' not in segment:
if segment not in new_conc_2[voxel_type]:
new_conc_2[voxel_type][segment] = collections.OrderedDict()
new_conc_2[voxel_type][segment][specie] = new_conc[voxel_type][specie][segment]
son = etree.SubElement(root,v_type_dict['all'])
for specie in new_conc_2['all']:
grandson = etree.SubElement(son,conc_type_dict['all'])
grandson.set('specieID',specie)
grandson.set('value',str(round(new_conc_2['all'][specie],0)))
for voxel_type in ['cytosol','submembrane']:
for segment in new_conc_2[voxel_type]:
son = etree.SubElement(root,v_type_dict[voxel_type])
son.set("region",segment.split('.')[0])
for specie in new_conc_2[voxel_type][segment]:
grandson = etree.SubElement(son,conc_type_dict[voxel_type])
grandson.set('specieID',specie)
grandson.set('value',str(round(new_conc_2[voxel_type][segment][specie],0)))
fname = fname+'_new_conc.xml'
print fname
xml_write_to_file(fname,root)
def get_concentrations(number_specie_segment, species_voxels, area,volume):
totals = collections.OrderedDict()
for specie in number_specie_segment:
total = 0
for segment in number_specie_segment[specie]:
for voxel_type in number_specie_segment[specie][segment]:
if voxel_type in ['cytosol','submembrane']:
total += number_specie_segment[specie][segment][voxel_type]
totals[specie] = total
for specie in totals:
if specie in species_voxels['cytosol']:
totals[specie] = totals[specie]/volume*10/6.022
else:
totals[specie] = totals[specie]/area*10/6.022
return totals
def get_totals(number_specie_segment):
totals = collections.OrderedDict()
for specie in number_specie_segment:
total = 0
for segment in number_specie_segment[specie]:
for voxel_type in number_specie_segment[specie][segment]:
if voxel_type in ['cytosol','submembrane']:
total += number_specie_segment[specie][segment][voxel_type]
totals[specie] = total
return totals
def initial_totals(model_fname):
for defa in default_fn:
conc_filename = model_fname[:-4] +'-'+ defa + '-conc.txt'
f = open(conc_filename,'r')
header = f.readline()
[segment_voxels,segment_area_voxels,special_points, specie_type_dict, regions] = read_header(header)
totals_filename = conc_filename+'_initial_totals'
fl = open(totals_filename,'w')
first_line = f.readline()
number_specie_segment = get_numbers_from_a_fileline(first_line,specie_type_dict)
totals = get_totals(number_specie_segment)
for specie in totals:
fl.write(specie+' '+str(totals[specie])+'\n')
print totals_filename
def write_header(fil,all_species):
fil.write('time ')
for specie in all_species:
fil.write(specie+' ')
fil.write('\n')
def long_totals(model_fname):
for default in default_fn:
conc_filename = model_fname[:-4] +'-'+ default + '-conc.txt'
f = open(conc_filename,'r')
header = f.readline()
[segment_voxels,segment_area_voxels,special_points, specie_type_dict, regions] = read_header(header)
totals_filename = conc_filename+'_totals'
totals_file = open(totals_filename,'w')
specie_list = []
for specie in specie_type_dict:
specie_list.append(specie)
write_header(totals_file,specie_list)
try:
conc_data = np.loadtxt(conc_filename, skiprows=1)
for conc_line in conc_data:
number_specie_segment = get_numbers_from_a_fileline(conc_line,specie_type_dict)
totals = get_totals(number_specie_segment)
try:
totals_file.write(str(conc_line[0])+' ')
except IndexError:
print "Broken file", conc_filename
break
for specie in specie_list:
totals_file.write(str(totals[specie])+' ')
totals_file.write('\n')
except ValueError:
for conc_line in f:
try:
number_specie_segment = get_numbers_from_a_fileline(conc_line,specie_type_dict)
totals = get_totals(number_specie_segment)
except:
print('Broken file'+conc_filename)
return
totals_file.write(str(conc_line.split()[0])+' ')
for specie in specie_list:
totals_file.write(str(totals[specie])+' ')
totals_file.write('\n')
print totals_file.name
def long_concentrations(filename, species_voxels, area,volume,add='concentrations'):
f = open(filename,'r')
header = f.readline()
[segment_voxels,segment_area_voxels,special_points, specie_type_dict, regions] = read_header(header)
totals_filename = filename+'_'+add
totals_file = open(totals_filename,'w')
specie_list = []
print filename
for specie in specie_type_dict:
specie_list.append(specie)
write_header(totals_file,specie_list)
try:
conc_data = np.loadtxt(filename,skiprows=1)
for conc_line in conc_data:
number_specie_segment = get_numbers_from_a_fileline(conc_line,specie_type_dict)
totals = get_concentrations(number_specie_segment,species_voxels, area,volume)
try:
totals_file.write(str(conc_line[0])+' ')
except IndexError:
print 'Errors in file', filename
break
for specie in specie_list:
totals_file.write(str(totals[specie])+' ')
totals_file.write('\n')
except ValueError:
for conc_line in f:
try:
number_specie_segment = get_numbers_from_a_fileline(conc_line,specie_type_dict)
except:
print('Broken conc file')
return
totals = get_concentrations(number_specie_segment,species_voxels, area,volume)
try:
totals_file.write(str(conc_line.split()[0])+' ')
except IndexError:
print 'Errors in file', filename
break
for specie in specie_list:
totals_file.write(str(totals[specie])+' ')
totals_file.write('\n')
def write_concentrations_in_segment(all_species,species_with_numbers,totals_file,conc,cytosol_species,time,target_list,total_volume,total_area,area_dict,vol_dict):
for specie in all_species:
species_with_numbers[specie] = 0
totals_file.write(str(time)+' ')
for region in target_list:
if region in conc['submembrane']:
for specie in conc['submembrane'][region]:
species_with_numbers[specie] += conc['submembrane'][region][specie]*area_dict[region]
if region in conc['cytosol']:
for specie in conc['cytosol'][region]:
species_with_numbers[specie] += conc['cytosol'][region][specie]*vol_dict[region]
for specie in all_species:
if specie in cytosol_species:
totals_file.write(str(species_with_numbers[specie]/total_volume)+' ')
else:
totals_file.write(str(species_with_numbers[specie]/total_area)+' ')
totals_file.write('\n')
def concentrations_in_segment(model_fname,segment_list):
'''
Writes cumulative concentrations in chosen segments (given in segment list).
'''
mesh_filename = model_fname[:-4] + '-mesh.txt'
for default in default_fn:
filename = model_fname[:-4] +'-'+ default + '-conc.txt'
try:
f = open(filename,'r')
except IOError:
sys.exit('No such file or directory '+filename)
header = f.readline()
[segment_voxels,segment_area_voxels,special_points, specie_type_dict, regions] = read_header(header)
target_list = set()
[area_dict, vol_dict] = calculate_volume_and_area(mesh_filename,segment_voxels,segment_area_voxels)
#Find NeuroRD region names corresponding with names given in running gisi
for region in segment_list:
for reg in regions:
if region in reg:
target_list.add(reg)
if target_list == set():
print "Segment list is empty"
continue
total_volume = 0
total_area = 0
for region in target_list:
total_volume += vol_dict[region]
try:
total_area += area_dict[region]
except:
pass
add = 'concentrations'
for region in target_list:
add += '_'
add +=region
all_species_mem = get_submembrane_species(model_fname,regions)
totals_filename = filename + '_' + add
totals_file = open(totals_filename,'w')
all_species = []
cytosol_species = []
species_mem = collections.OrderedDict()
for region in target_list:
for specie in all_species_mem['cytosol'][region]:
if specie in specie_type_dict:
if specie not in all_species:
all_species.append(specie)
if 'cytosol' not in species_mem:
species_mem['cytosol'] = collections.OrderedDict()
if region not in species_mem['cytosol']:
species_mem['cytosol'][region] = []
species_mem['cytosol'][region].append(specie)
if region in all_species_mem['submembrane']:
for specie in all_species_mem['submembrane'][region]:
if specie in specie_type_dict:
if specie not in all_species:
all_species.append(specie)
if 'submembrane' not in species_mem:
species_mem['submembrane'] = collections.OrderedDict()
if region not in species_mem['submembrane']:
species_mem['submembrane'][region] = []
species_mem['submembrane'][region].append(specie)
for region in regions:
for specie in all_species_mem['cytosol'][region]:
if specie not in cytosol_species:
cytosol_species.append(specie)
write_header(totals_file,all_species)
species_with_numbers = {}
print totals_filename
try:
conc_data = np.loadtxt(filename,skiprows=1)
print '1'
for conc_line in conc_data:
number_specie_segment = get_numbers_from_a_fileline(conc_line,specie_type_dict)
conc = concentrations(number_specie_segment,species_mem,area_dict, vol_dict)
write_concentrations_in_segment(all_species,species_with_numbers,totals_file,conc,cytosol_species,conc_line[0],target_list,total_volume,total_area,area_dict,vol_dict)
except ValueError:
print '2'
for conc_line in f:
try:
number_specie_segment = get_numbers_from_a_fileline(conc_line,specie_type_dict)
except:
print('Broken conc file')
return
conc = concentrations(number_specie_segment,species_mem,area_dict, vol_dict)
write_concentrations_in_segment(all_species,species_with_numbers,totals_file,conc,cytosol_species,conc_line.split()[0],target_list,total_volume,total_area,area_dict,vol_dict)
def write_long_segments(totals_files,regions,conc,time,specie_list_in_regions):
for region in regions:
totals_files[region].write(str(time)+' ')
for region in regions:
if region in conc['submembrane']:
for specie in specie_list_in_regions[region]:
if specie in conc['submembrane'][region]:
if specie in conc['cytosol'][region]:
totals_files[region].write(str(conc['cytosol'][region][specie])+' ')
else:
totals_files[region].write(str(conc['submembrane'][region][specie])+' ')
else:
totals_files[region].write(str(conc['cytosol'][region][specie])+' ')
else:
for specie in specie_list_in_regions[region]:
try:
totals_files[region].write(str(conc['cytosol'][region][specie])+' ')
except KeyError:
totals_files[region].write('0 ')
totals_files[region].write('\n')
def get_species_mem(regions,specie_list_in_regions,all_species_mem):
species_mem = collections.OrderedDict()
#make sure that the dictionary species_mem contains only the species that are in the result file
for region in regions:
for specie in specie_list_in_regions[region]:
if specie in all_species_mem['cytosol'][region]:
if 'cytosol' not in species_mem:
species_mem['cytosol'] = collections.OrderedDict()
if region not in species_mem['cytosol']:
species_mem['cytosol'][region] = []
species_mem['cytosol'][region].append(specie)
else:
if specie in all_species_mem['submembrane'][region]:
if 'submembrane' not in species_mem:
species_mem['submembrane'] = collections.OrderedDict()
if region not in species_mem['submembrane']:
species_mem['submembrane'][region] = []
species_mem['submembrane'][region].append(specie)
return species_mem
def prepare_for_segments(model_fname,specie_type_dict,filename,regions,add):
totals_files = {}
specie_list_in_regions = {}
all_species_mem = get_submembrane_species(model_fname,regions)
for region in regions:
totals_filename = filename+'_'+add+'_'+region
totals_file = open(totals_filename,'w')
totals_files[region]=totals_file
specie_list = []
for specie in all_species_mem['cytosol'][region]:
if specie in specie_type_dict:
specie_list.append(specie)
if region in all_species_mem['submembrane']:
for specie in all_species_mem['submembrane'][region]:
if specie in specie_type_dict:
specie_list.append(specie)
write_header(totals_file,specie_list)
specie_list_in_regions[region] = specie_list[:]
species_mem = get_species_mem(regions,specie_list_in_regions,all_species_mem)
return totals_files,specie_list_in_regions,species_mem
def long_totals_segments(model_fname,add='totals'):
mesh_filename = model_fname[:-4] +'-mesh.txt'
for default in default_fn:
filename = model_fname[:-4] +'-'+ default + '-conc.txt'
try:
f = open(filename,'r')
except IOError:
sys.exit('No such file or directory '+filename)
header = f.readline()
[segment_voxels,segment_area_voxels,special_points, specie_type_dict, regions] = read_header(header)
[area_dict, vol_dict] = calculate_volume_and_area(mesh_filename,segment_voxels,segment_area_voxels)
[totals_files,specie_list_in_regions,species_mem] = prepare_for_segments(model_fname,specie_type_dict,filename,regions,add=add)
try:
conc_data = np.loadtxt(filename,skiprows=1)
for conc_line in conc_data:
number_specie_segment = get_numbers_from_a_fileline(conc_line,specie_type_dict)
conc = totals(number_specie_segment,species_mem,area_dict, vol_dict)
try:
write_long_segments(totals_files,regions,conc,conc_line[0],specie_list_in_regions)
except IndexError:
print 'Broken file', filename
break
except ValueError:
for conc_line in f:
try:
number_specie_segment = get_numbers_from_a_fileline(conc_line,specie_type_dict)
except:
print('Broken conc file')
break
conc = totals(number_specie_segment,species_mem,area_dict, vol_dict)
try:
write_long_segments(totals_files,regions,conc,conc_line.split()[0],specie_list_in_regions)
except IndexError:
print 'Broken file', filename
break
for fil in totals_files:
print fil
def long_concentrations_segments_array(model_fname):
totals_array_list = []
mesh_filename = model_fname[:-4] + '-mesh.txt'
for default in default_fn:
filename = model_fname[:-4] +'-'+ default + '-conc.txt'
try:
f = open(filename,'r')
except IOError:
try:
print 'No such file or directory',filename, mesh_filename
filename = model_fname[:-4] +'.out-'+ default + '-conc.txt'
mesh_filename = model_fname[:-4] + '.out-mesh.txt'
f = open(filename,'r')
except IOError:
sys.exit('No such file or directory '+filename)
header = f.readline()
try:
conc_data = np.loadtxt(filename,skiprows=1)
except ValueError:
print('Broken conc file '+filename)
total = np.array([float(item) for item in f.readline().split()])
row_len = total.shape[0]
for line in f:
total_new = np.array([float(item) for item in line.split()])
if total_new.shape[0] == row_len:
total = np.concatenate((total,total_new),axis=0)
col_len= total.shape[0]/row_len
conc_data = total.reshape((col_len,row_len))
time = conc_data[:,0]
[segment_voxels,segment_area_voxels,special_points, specie_type_dict, regions] = read_header(header)
[area_dict, vol_dict] = calculate_volume_and_area(mesh_filename,segment_voxels,segment_area_voxels)
totals_array = {}
specie_list_in_regions = {}
all_species_mem = get_submembrane_species(model_fname,regions)
l_conc = conc_data.shape[0]
for region in regions:
specie_list = []
for specie in all_species_mem['cytosol'][region]:
if specie in specie_type_dict:
specie_list.append(specie)
if region in all_species_mem['submembrane']:
for specie in all_species_mem['submembrane'][region]:
if specie in specie_type_dict:
specie_list.append(specie)
specie_list_in_regions[region] = specie_list[:]
totals_array[region] = {}
for specie in specie_list:
totals_array[region][specie] = np.zeros((l_conc,1))
species_mem = get_species_mem(regions,specie_list_in_regions,all_species_mem)
for i, conc_line in enumerate(conc_data):
number_specie_segment = get_numbers_from_a_fileline(conc_line,specie_type_dict)
conc = concentrations(number_specie_segment,species_mem,area_dict, vol_dict)
for region in regions:
if region in conc['submembrane']:
for specie in specie_list_in_regions[region]:
if specie in conc['submembrane'][region]:
if specie in conc['cytosol'][region]:
totals_array[region][specie][i] = conc['cytosol'][region][specie]
else:
totals_array[region][specie][i] = conc['submembrane'][region][specie]
else:
totals_array[region][specie][i] = conc['cytosol'][region][specie]
else:
for specie in specie_list_in_regions[region]:
try:
totals_array[region][specie][i] = conc['cytosol'][region][specie]
except KeyError:
totals_array[region][specie][i] = 0
totals_array_list.append(totals_array)
return totals_array_list,time
def write_long_concentrations_segments(regions,totals_files,conc,specie_list_in_regions,time):
for region in regions:
totals_files[region].write(str(time)+' ')
for region in regions:
if region in conc['submembrane']: