/
MMlib.py
executable file
·6475 lines (5719 loc) · 334 KB
/
MMlib.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
import os
import re
import sys
from string import *
import commands
import subprocess
try: import cPickle as pickle
except: import pickle
from copy import copy, deepcopy
from math import log as math_log, sqrt
import random
NUMBERS='0123456789'
DNA_LETT='ACGT'
SS_LETT='0SETBH'
AA_LETT='ACDEFGHIKLMNPQRSTVWYUOB' # including selenocysteine
AA_LETT_STRICT='ACDEFGHIKLMNPQRSTVWY'
RNA_LETT='ACGU'
three_letter_codon_diz={ 'Ala':'A' , 'Cys':'C' , 'Asp':'D' , 'Glu':'E' , 'Phe':'F' , 'Gly':'G' , 'His':'H' , 'Ile':'I' , 'Lys':'K' , 'Leu':'L' , 'Met':'M' , 'Asn':'N' , 'Pro':'P' , 'Gln':'Q' , 'Arg':'R' , 'Ser':'S' , 'Thr':'T' , 'Val':'V' , 'Trp':'W' , 'Tyr':'Y', '***':'*', 'Unk':'X' , '<->':'-', '---':'-','Asx':'B', 'SeC':'U', 'Zed':'Z', 'SeC(e)':'U' }
one_to_three_letter_codon_diz={ 'A':'Ala' , 'C':'Cys' , 'D':'Asp' , 'E':'Glu' , 'F':'Phe' , 'G':'Gly' , 'H':'His' , 'I':'Ile' , 'K':'Lys' , 'L':'Leu' , 'M':'Met' , 'N':'Asn' , 'P':'Pro' , 'Q':'Gln' , 'R':'Arg' , 'S':'Ser' , 'T':'Thr' , 'V':'Val' , 'W':'Trp' , 'Y':'Tyr', '*':'***', 'X':'Unk' , '-':'---' , 'B':'Asx' }
STOP_CODONS= ['UAA', 'UAG', 'UGA', 'URA', 'UAR']
STOP_CODONS_DNA=['TAA', 'TAG', 'TGA', 'TRA', 'TAR']
one_letter_to_three_letter_aa_diz={'A':'alanine',
'R':'arginine', 'N':'asparagine','D':'aspartic_acid','C':'cysteine','E':'glutamic_acid','Q':'glutamine','G':'glycine','H':'histidine','I':'isoleucine','L':'leucine','K':'lysine','M':'methionine','F':'phenylalanine','P':'proline','S':'serine','T':'threonine','W':'tryptophan','Y':'tyrosine','V':'valine','U':'selenocysteine'}
try: from numpy import average, std as std_deviation
except:
sys.exc_clear()
def average(ilist): return sum(ilist)/float(len(ilist))
def std_deviation(ilist):
a=average(ilist)
return sqrt( sum( [pow( v-a, 2) for v in ilist] )/len(ilist) )
def set_temp_folder(folder): set_MMlib_var('temp_folder', folder)
def set_split_folder(folder): set_MMlib_var('split_folder', folder)
def get_temp_folder(): return get_MMlib_var('temp_folder')
def get_split_folder(): return get_MMlib_var('split_folder')
def set_local_folders(temp='/tmp'):
""" Used in ipython to quickly set the environment for fetching chromosomes and other stuff that required temp files"""
try: assert is_directory(opt['temp'])
except: opt['temp']=temp
temp_folder=Folder(random_folder(opt['temp'])); test_writeable_folder(temp_folder, 'temp_folder'); set_temp_folder(temp_folder)
split_folder=Folder(opt['temp']); test_writeable_folder(split_folder); set_split_folder(split_folder)
def mute(also_stderr=False):
""" Turns off any output to stdout (to stderr as well if option is True). To go back to normal , use unmute()"""
sys.stdout = open(os.devnull, "w")
if also_stderr: sys.stderr = open(os.devnull, "w")
def unmute():
sys.stdout = sys.__stdout__; sys.stderr = sys.__stderr__
def phylome_connector():
""" ete2 connector to PhylomeDB. allows retrieving data such as trees, alignments etc. Examples: (calling p the object returned by this function)
p.get_algs("Phy0005QIK_DROME", 8)
p.get_tree("Phy0005QIK_DROME", 8, best_tree = True)
"""
import ete2
p = ete2.PhylomeDB3Connector(host = "phylomedb.org", user = "phyReader", passwd = "phyd10.-Reader", db = 'phylomedb_3')
p._algs = "alignment"
p._trees = "tree"
p._phylomes = "phylome"
p._phy_content = "phylome_content"
return p
def bash(command, print_it=0):
"""Utility to run bash commands. a tuple (exit_status, message) is returned, where message includes both std input and stderr. If argument print_it==1 or the variable print_commands is defined in MMlib, the command is printed before execution. If variable bin_folder is defined in MMlib, this folder is added to bash $PATH before running the command. """
if 'print_commands' in globals() and print_commands: print_it=1
if print_it: write(command, 1)
if 'bin_folder' in globals():
if not bin_folder == os.environ['PATH'].split(':')[0]: os.environ['PATH']=str(bin_folder)+':'+os.environ['PATH']
b1, b2= commands.getstatusoutput(command)
return [b1, b2]
def bbash(command, print_it=0, dont_die=0):
"""Utility to run bash commands. A string is returned, where including both std input and stderr. If the exit status of the command is different than 0, it is assumed something went wrong, so an exception is raised indicating the command and the output. If argument dont_die==1, no exception is raised and output is returned as normal.
If argument print_it==1 or the variable print_commands is defined in MMlib, the command is printed before execution. If variable bin_folder is defined in MMlib, this folder is added to bash $PATH before running the command. """
if 'print_commands' in globals() and print_commands: print_it=1
if print_it: write(command, 1)
cmnd=command
if 'bin_folder' in globals():
if not bin_folder == os.environ['PATH'].split(':')[0]: os.environ['PATH']=str(bin_folder)+':'+os.environ['PATH']
bb=commands.getstatusoutput(cmnd)
if bb[0]!=0 and not dont_die: raise Exception, 'COMMAND: ' + command+' ERROR: "'+bb[1]+' "'
else: return bb[1]
def bash_pipe(cmnd, print_it=0, return_popen=0, stdin=None):
""" Open a filehandler which reads from a pipe opened in bash, given a command. Useful when you want to read one line at the time. If variable bin_folder is defined in MMlib, this folder is added to bash $PATH before running the command.
stdin can be used to input large chunks of data, through a filehandler. valid formats are: stdin=existing_write_filehandler, or stdin='PIPE' (equivalent to subprocess.PIPE); in this last case you want to use return_popen to be able to access the handler (with this option, the popen object is returned instead of its stdout filehandler), like this:
p=bash_pipe('command', stdin='PIPE', return_popen=True)
print >> p.stdin, 'input_lines!' #repeat as many times as needed
p.stdin.close() # important! as most programs wait for a EOF signal to give output, you need to close the input filehandler before reading the lines of output
p.stdout.readline() # --> now you can read the output lines from this handler
"""
if stdin=='PIPE': stdin=subprocess.PIPE
if 'print_commands' in globals() and print_commands: print_it=1
if 'bin_folder' in globals():
if not bin_folder == os.environ['PATH'].split(':')[0]: os.environ['PATH']=str(bin_folder)+':'+os.environ['PATH']
if print_it: write(cmnd, 1)
s=subprocess.Popen(cmnd.split(), stdout=subprocess.PIPE, stdin=stdin, env=os.environ)
if return_popen: return s
else: return s.stdout
def md5_executable():
b=bash('echo | md5sum')
if not b[0]: return 'md5sum' ## command found, no error
b=bash('echo | md5')
if not b[0]: return 'md5' ## command found, no error
else: raise Exception, "ERROR neither md5sum or md5 found on this system!"
def checksum(ffile, is_text=False):
""" Returns the checksum for the file in input """
if is_text:
pipe=bash_pipe(md5_executable()+' ', return_popen=1, stdin='PIPE')
print >> pipe.stdin, ffile
pipe.stdin.close()
m= pipe.stdout.readline().split()[0]
else:
m=bbash(md5_executable()+' '+ffile).split()[0]
return m
def Folder(string):
if not string:
return string
ff=string+'/'*int(string[-1]!='/')
cmnd='mkdir '+ff
bb=bash(cmnd)
return ff
def random_folder(parent_folder='', dont_create_it=0):
if parent_folder:
parent_folder = Folder(parent_folder) #checking or creating parent folder. IF CRASHED: do you have writing privileges here?
a=parent_folder+ bash("date +%F%T%N | "+md5_executable()+" | cut -c 1-32")[1] #creating a random named folder inside the parent folder
if dont_create_it:
return a+'/'
a=Folder(a)
if not bash('cd '+a+' ; cd ..')[0] :
return a
else:
return 'some_error_creating_random_folder.hopefully_there_is_noooo_file_named_like_this_when_you_try_to_delete_it'
temp_folder=random_folder('/tmp', 1)
split_folder=Folder('/tmp')
def set_MMlib_var(varname, value): globals()[varname]=value
def get_MMlib_var(varname): return globals()[varname]
def is_significant(pvalue): return pvalue<opt['alpha']
printed_rchar=0
# trans={};
# trans ['GCA'] = "A"; trans ['GCC'] = "A"; trans ['GCG'] = "A"; trans ['GCT'] = "A"; trans ['TGC'] = "C"; trans ['TGT'] = "C";
# trans ['GAC'] = "D"; trans ['GAT'] = "D"; trans ['GAA'] = "E"; trans ['GAG'] = "E"; trans ['TTC'] = "F"; trans ['TTT'] = "F";
# trans ['GGA'] = "G"; trans ['GGC'] = "G"; trans ['GGG'] = "G"; trans ['GGT'] = "G"; trans ['CAC'] = "H"; trans ['CAT'] = "H";
# trans ['ATA'] = "I"; trans ['ATC'] = "I"; trans ['ATT'] = "I"; trans ['AAA'] = "K"; trans ['AAG'] = "K"; trans ['TTA'] = "L";
# trans ['TTG'] = "L"; trans ['CTA'] = "L"; trans ['CTC'] = "L"; trans ['CTG'] = "L"; trans ['CTT'] = "L"; trans ['ATG'] = "M";
# trans ['AAC'] = "N"; trans ['AAT'] = "N"; trans ['CCA'] = "P"; trans ['CCC'] = "P"; trans ['CCG'] = "P"; trans ['CCT'] = "P";
# trans ['CAA'] = "Q"; trans ['CAG'] = "Q"; trans ['AGA'] = "R"; trans ['AGG'] = "R"; trans ['CGA'] = "R"; trans ['CGC'] = "R";
# trans ['CGG'] = "R"; trans ['CGT'] = "R"; trans ['AGC'] = "S"; trans ['AGT'] = "S"; trans ['TCA'] = "S"; trans ['TCC'] = "S";
# trans ['TCG'] = "S"; trans ['TCT'] = "S"; trans ['ACA'] = "T"; trans ['ACC'] = "T"; trans ['ACG'] = "T"; trans ['ACT'] = "T";
# trans ['GTA'] = "V"; trans ['GTC'] = "V"; trans ['GTG'] = "V"; trans ['GTT'] = "V"; trans ['TGG'] = "W"; trans ['TAC'] = "Y";
# trans ['TAT'] = "Y"; # trans ['taa'] = "!"; trans ['tag'] = "#"; trans ['tga'] = "@";
# trans ['TAA'] = "*"; trans ['TAG'] = "*"; trans ['TGA'] = "*";
# trans ['---'] = "-";
## std: FFLLSSSSYY**CC*WLLLLPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG
# build alternative genetic code translation tables based on NCBI codes
genetic_codes={}
genetic_codes_AAs={ 1:'FFLLSSSSYY**CC*WLLLLPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG',
2:'FFLLSSSSYY**CCWWLLLLPPPPHHQQRRRRIIMMTTTTNNKKSS**VVVVAAAADDEEGGGG',
3:'FFLLSSSSYY**CCWWTTTTPPPPHHQQRRRRIIMMTTTTNNKKSSRRVVVVAAAADDEEGGGG',
4:'FFLLSSSSYY**CCWWLLLLPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG',
5:'FFLLSSSSYY**CCWWLLLLPPPPHHQQRRRRIIMMTTTTNNKKSSSSVVVVAAAADDEEGGGG',
6:'FFLLSSSSYYQQCC*WLLLLPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG',
9:'FFLLSSSSYY**CCWWLLLLPPPPHHQQRRRRIIIMTTTTNNNKSSSSVVVVAAAADDEEGGGG',
10:'FFLLSSSSYY**CCCWLLLLPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG',
11:'FFLLSSSSYY**CC*WLLLLPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG',
12:'FFLLSSSSYY**CC*WLLLSPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG',
13:'FFLLSSSSYY**CCWWLLLLPPPPHHQQRRRRIIMMTTTTNNKKSSGGVVVVAAAADDEEGGGG',
14:'FFLLSSSSYYY*CCWWLLLLPPPPHHQQRRRRIIIMTTTTNNNKSSSSVVVVAAAADDEEGGGG',
16:'FFLLSSSSYY*LCC*WLLLLPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG',
21:'FFLLSSSSYY**CCWWLLLLPPPPHHQQRRRRIIMMTTTTNNNKSSSSVVVVAAAADDEEGGGG',
22:'FFLLSS*SYY*LCC*WLLLLPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG',
23:'FF*LSSSSYY**CC*WLLLLPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG',
24:'FFLLSSSSYY**CCWWLLLLPPPPHHQQRRRRIIIMTTTTNNKKSSSKVVVVAAAADDEEGGGG',
25:'FFLLSSSSYY**CCGWLLLLPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG',
26:'FFLLSSSSYY**CC*WLLLAPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG',
27:'FFLLSSSSYYQQCCWWLLLAPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG',
28:'FFLLSSSSYYQQCCWWLLLAPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG',
29:'FFLLSSSSYYYYCC*WLLLAPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG',
30:'FFLLSSSSYYEECC*WLLLAPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG',
31:'FFLLSSSSYYEECCWWLLLLPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG'}
for gc_code in genetic_codes_AAs:
i=-1
genetic_codes[gc_code]={'---':'-'}
for a in 'TCAG':
for b in 'TCAG':
for c in 'TCAG':
i+=1
genetic_codes[gc_code][ a+b+c ]=genetic_codes_AAs[gc_code][i]
trans=genetic_codes[1]
retrotrans={}
for codon in trans: retrotrans.setdefault( trans[codon], [] ).append(codon)
for aa in retrotrans: retrotrans[aa].sort()
species_code_file="/home/mmariotti/software/selenoprofiles/libraries/species_codes.tab"
genome_config="/home/mmariotti/software/selenoprofiles/libraries/genome.config"
def contain_chars(string, to_check=uppercase+lowercase):
for char in string:
if char in to_check:
return 1
return 0
def is_number(string, mode='int'):
if mode=='float':
try:
float(string)
return True
except ValueError:
return False
else: #mode =int
try:
int(string)
return True
except ValueError:
return False
def is_option(s):
return (s[0]=='-' and contain_chars(s[1:]))
def option_value(value):
"""value=string; returns value changed into the appropriate type.
"""
# if value.startswith('[') and value.endswith(']'):
# write(value, 1, how='yellow')
# return [option_value(x) for x in value[1:-1].split(', ') ]
if is_number(value): return int(value)
elif is_number(value, 'float'): return float(value)
elif value=='None': return None
else:
if value and value[0]==value[-1] and value[0] in ['"', "'"] and len(value)>=2: value=value[1:-1]
return value
def update_opt(new_opt, current_opt):
"""sometimes it is useful to read options from command line, then manipulate them before using them. In this case, it is worth doing to update the opt object and sys.argv.
Each option in new_opt (key) goes to replace the one in current_opt with the same name. Sys.argv is also updated.DONT KNOW ABOUT BOOLEAN VALUES
"""
for k in new_opt:
current_opt[k]=new_opt[k]
for c in range(len(sys.argv)):
if sys.argv[c]=='-'+k:
sys.argv[c+1]=new_opt[k]
return current_opt
def fill_option(default_opt, option, dont_add_to_argv=0): #fill the keys of option (dictionary like {option: value}) that are not present, with default values specified in default_opt
for key in default_opt:
if not option.has_key(key):
option[key]=default_opt[key]
if not dont_add_to_argv:
sys.argv.extend(['-'+key, str(default_opt[key])])
return option
class options(dict):
""" """
def __init__(self, dict_in={}, synonyms={}):
super(options, self).__init__()
for k in dict_in:
self[k]=dict_in[k]
self.set_synonyms(synonyms)
def __getitem__(self, name):
if self.has_key(name): return super(options, self).__getitem__(name)
elif self['__synonyms__'].has_key(name): return self[ self['__synonyms__'][name] ]
elif name in self['__synonyms__'].values():
for k in self['__synonyms__']:
if name== self['__synonyms__'][k]:
return self[k]
else:
return None
def set_synonyms(self, syno_hash):
self['__synonyms__']=syno_hash
def add_synonym(synonym, key):
self['__synonyms__'][synonym]=key
def synonyms(self):
return self['__synonyms__']
def command_line(default_opt, command_line_help='Command line usage:...', default_order='io', synonyms={}, dont_die=0, silent=0, dont_add_to_argv=0, nowarning=0, strict=0, tolerated_regexp=[], advanced={}):
import sys
def command_line_option():
"""this is a utility that read sys.argv and returns a dictionary like {option: value}
options in command line must be preceded by -, and option can't consist only of number ;
if after an option there is no value (for example there is another option), the value is set to 1.
Numberic values are converted to their types; floating point numbers are discriminated from integers if they contains a dot '.'
ex:
[python] prog_name.py -c 12 -verbose -gap -0.45 ----> returns {'c': 12, 'g': -0.45, 'verbose':1}
The default_opt contains all default values for compulsory arguments. These are taken from here if they are not find in the commandline. Also, sys.argv is enriched with these value, therefore if the command_line function is called again (even with specifying def_opt), the resulting returned opt will be the same.
"""
option=options()
llist=sys.argv[1:]+['-EnD!!']
# write_to_file(str( sys.argv), 'btemp')
c=0
#flushing empty values in argv
while c<len(llist):
if not llist[c]:
llist.pop(c)
else:
c+=1
while llist[0]!='-EnD!!':
first=str(llist.pop(0))
#option=option_value(value)
if first[0]=='-':
if is_option(llist[0]): #the next object in the row is a option. So this option is simply set to True (1)
option[first[1:]]=1
else:
value=llist.pop(0)
option[first[1:]]=option_value(value)
return option
if silent: nowarning=1
opt=command_line_option()
if default_order=='*':
obj_list=[]
i=1
while i<len(sys.argv) and ( not is_option(sys.argv[i]) ) : #reading as syntax is --> program_name file1 file2 file3 .... fileN -o 1 -n 7
obj_list.append( sys.argv[i] )
i+=1
if not obj_list and i<len(sys.argv): #it may be that the syntax used in the command line is also: program_name -o 1 -n 7 file1 file2 file3 ....
i=1
while i<len(sys.argv):
if not is_option(sys.argv[i]) and (not is_option(sys.argv[i-1])):
obj_list.append( sys.argv[i] )
i+=1
opt['*']=obj_list
else:
i=1
while i<len(sys.argv) and i<=len(default_order) and ( not is_option(sys.argv[i]) ) :
opt[ default_order[i-1] ]=option_value(sys.argv[i])
i+=1
synonyms['help']='h'; synonyms['-help']='h'
opt.set_synonyms(synonyms)
special_options=['h', 'print_opt', 'print_option', 'print_options', 'config', 'bin_folder', '__synonyms__']
for k in opt:
if not default_opt.has_key(k) and not nowarning and not k in special_options and not k in opt.synonyms() and not match_any_word(k, tolerated_regexp, ignore_case=0) :
if strict!=0:
if type(strict) in [int, bool]: e=Exception
elif issubclass(strict, Exception): e=strict
raise e, "command_line ERROR the option "+k+" is not present among the possible options. run with -print_opt to see the current option configuration"
printerr('WARNING possible typo: the option '+k+' is not present among the possible options. run with -print_opt to see the current option configuration\n')
opt=fill_option(default_opt, opt, dont_add_to_argv)
for k in opt:
if type(opt[k]) == str and opt[k].startswith('$('): opt[k]=bbash(opt[k][2:-1])
#dealing with synonyms
keyss=opt.keys()
for k in keyss:
if k in opt.synonyms():
opt[opt.synonyms()[k]]=opt[k]
del opt[k]
#printing options to screen in case we have -print_opt
if not silent and( opt.has_key('print_opt') or opt.has_key('print_options') or opt.has_key('print_option') ):
write( "| ACTIVE OPTIONS:", 1)
keys=opt.keys()
keys.sort()
for k in keys:
a="| "+str(k)
write( a+' '*(30-len(a))+': '+str(opt[k]), 1)
write('', 1)
#printing help message in case we have -h or --help
if not silent and (len(sys.argv)<2 or opt.has_key('h') ) :
write(command_line_help, 1)
if advanced and opt['h'] in advanced:
write(advanced[opt['h']], 1)
if not dont_die:
sys.exit()
return opt
uniq_id=id
def lineage_string_to_abstract(lineage):
""" lineage is a string which is usually returned by this program. This function condensate it keeping the most interesting classes. """
splt=lineage.split('; ')
if "Bacteria; " in lineage : return 'B; '+join(splt[2:min(5, len(splt))], '; ')
elif 'Archaea; ' in lineage : return 'A; '+join(splt[2:min(5, len(splt))], '; ')
elif 'Eukaryota; ' in lineage:
out='E; '
if 'Metazoa; ' in lineage:
out+='M; '
if 'Deuterostomia; ' in lineage:
out+='Deuterostomia; '
if 'Vertebrata; ' in lineage:
out+='Vertebrata; '
if 'Mammalia; ' in lineage: out+='Mammalia; '
elif 'Sauropsida; ' in lineage: out+='Sauropsida; '
elif 'Amphibia; ' in lineage: out+='Amphibia; '
elif 'Actinopterygii; ' in lineage: out+='Actinopterygii; '
elif 'Chondrichthyes; ' in lineage: out+='Chondrichthyes; '
elif 'Tunicata; ' in lineage:
out+='Tunicata; '
if 'Ascidiacea; ' in lineage: out+='Ascidiacea; '
elif 'Branchiostomidae; ' in lineage: out+='Branchiostomidae; '
elif 'Echinodermata; ' in lineage: out+='Echinodermata; '
elif 'Protostomia; ' in lineage:
out+='Protostomia; '
if 'Arthropoda; ' in lineage:
out+='Arthropoda; '
if 'Insecta; ' in lineage: out+='Insecta; '
elif 'Crustacea; ' in lineage: out+='Crustacea; '
elif 'Myrapoda; ' in lineage: out+='Myrapoda; '
elif 'Arachnida; ' in lineage: out+='Arachnida; '
elif 'Merostomata; ' in lineage: out+='Merostomata; '
elif 'Nematoda; ' in lineage: out+='Nematoda; '
elif 'Mollusca; ' in lineage:
out+='Mollusca; '
if 'Gastropoda; ' in lineage: out+='Gastropoda; '
elif 'Bivalvia; ' in lineage: out+='Bivalvia; '
elif 'Annelida; ' in lineage: out+='Annelida; '
else: out+= lineage.split('Protostomia; ')[1].split(';')[0]+'; '
else: #basal metazoan
if 'Cnidaria; ' in lineage: out+='Cnidaria; '
elif 'Porifera; ' in lineage: out+='Porifera; '
elif 'Ctenophora; ' in lineage: out+='Ctenophora; '
elif 'Placozoa; ' in lineage: out+='Placozoa; '
elif 'Platyhelminthes; ' in lineage: out+='Platyhelminthes; '
else: out+= join(splt[2:min(4, len(splt))], '; ')+'; '
return out[:-2]
else: return join(splt[0:min(4, len(splt))], '; ')
def get_species_fullname(species_name):
b=bash('egrep -w "'+species_name+'" '+species_code_file)
if b[0]:
raise Exception, "get_species_fullname ERROR: "+species_name+' not found'
else:
return b[1].split('\t')[1]
def get_species_code(species_name):
b=bash('egrep -w "'+species_name+'" '+species_code_file)
if b[0]:
raise Exception, "get_species_code ERROR: "+species_name+' not found'
else:
return b[1].split('\t')[0]
def get_genome_file(species_fullname):
b=bash('egrep "'+species_fullname+'.*=" '+genome_config)
if b[0]:
raise Exception, "get_genome_file ERROR: "+species_fullname+' not found'
else:
return del_white(b[1].split('=')[1])
def second_max(alist):
"""returns the second biggest number in a list. if it has only one element, that is returned. If it has none, it returns False
"""
current_max='init'
current_second_max='init'
for item in alist:
if current_max=='init' or item>current_max:
current_second_max=current_max
current_max=item
elif current_second_max=='init' or item>current_second_max:
current_second_max=item
if current_second_max=='init':
if current_max=='init':
return False
return current_max
return current_second_max
blosum62_matrix={}
def load_blosum(from_file="/home/mmariotti/software/selenoprofiles/libraries/BLOSUM62sel"):
try: assert blosum62_matrix
except:
#ncbi format
ordered_aminoacids=[]
main_diz={}
cfile=open(from_file, 'r')
cline=cfile.readline()
index_line=0 #fake, check below
while cline:
if cline[0]=='#':
cline=cfile.readline()
elif not ordered_aminoacids:
ordered_aminoacids=cline.split()
index_line=-1
else:
for index_aa, num in enumerate(cline.split()[1:]):
if not main_diz.has_key(ordered_aminoacids[index_line]):
main_diz[ordered_aminoacids[index_line]]={}
main_diz[ordered_aminoacids[index_line]][ordered_aminoacids[index_aa]]=int(num)
cline=cfile.readline()
index_line+=1
cfile.close()
main_diz['U']=main_diz['*']
for k in main_diz:
main_diz[k]['U']=main_diz[k]['*']
blosum62_matrix=main_diz
return blosum62_matrix
def blosum(aa1, aa2, matrix={}):
if not matrix:
matrix=load_blosum()
if 'x' in [aa1, aa2]: #for my exonerate parser. actual Xs (uppercase) are treated as in the blosum
return 0
#for my recoding of stop codons
if aa1 in 'JZ':
aa1='*'
if aa2 in 'JZ':
aa2='*'
if matrix.has_key(aa1) and matrix[aa1].has_key(aa2):
return matrix[aa1][aa2]
else:
raise Exception, "ERROR blosum score not defined for:"+aa1+' '+aa2
def similar_aas(aa1, aa2):
'''returns True is the two aas are similar, false if not. They are defined as similar if they have a positive value in the blosum62 matrix
'''
similar_diz={"A":["S"], "R":["Q","K"], "N":["D","H","S","B"], "D":["N","E","B","Z"], "C":[], "Q":["R","E","K","Z"], "E":["D","Q","K","B","Z"], "G":[], "H":["N","Y"], "I":["L","M","V"], "L":["I","M","V"], "K":["R","Q","E","Z"], "M":["I","L","V"], "F":["W","Y"], "P":[], "S":["A","N","T"], "T":["S"], "W":["F","Y"], "Y":["H","F","W"], "V":["I","L","M"]}
if similar_diz.has_key(aa1):
if similar_diz.has_key(aa2):
return (aa2 in similar_diz[aa1])
return False
def parsed_blast_to_summary(pline, program='tblastn', chars_per_line=60 ):
return blasthit(pline).pretty_summary()
def all_chars_in(astring):
""" This function returns the list of characters contained in the input string. The characters are in the order of first appearance"""
outlist=[]; chars_hash={}
for c in astring:
if not chars_hash.has_key(c):
outlist.append(c)
chars_hash[c]=1
return outlist
def find_all(substring, sstring):
""" Find all arg1 occunreces in arg2 , and returns their indices. work with overlapping occurrences """
l=len(substring); out=[]
for pos in range(len(sstring)+1-l):
if sstring[pos:pos+l]==substring: out.append(pos)
return out
default_genetic_code=1
def set_genetic_code(code):
""" Set the default translation table to this code; Input is numerical, follows NCBI standards (e.g. 1 is standard, 6 is ciliate).
This affects later calls of transl(seq) """
return set_MMlib_var('default_genetic_code', code)
def get_genetic_code():
""" Get the default translation table code; numerical, follows NCBI standards"""
return get_MMlib_var('default_genetic_code')
def get_genetic_code_table(code=None):
""" Returns a dictionary codon->aminoacid for the given code (numerical, NCBI standard)
If code is not provided, the default set in MMlib is used"""
if code is None: code=get_genetic_code()
return genetic_codes[code]
def transl(cds_seq, include_selenocysteine=False, gaps_to=None, code=None):
'''translate a nucleotide sequence in aminoacids.
Use code=X to give a integer identifying the genetic code to be used, as NCBI codes (see https://www.ncbi.nlm.nih.gov/Taxonomy/Utils/wprintgc.cgi)
Use include_selenocysteine=1 to use U for TGA or UGA
Use gaps_to to force a certain char for gaps codons (---); normally translated as -
'''
if code is None: code=default_genetic_code
out=''
i=0
codon_table=genetic_codes[code]
while i < len(cds_seq):
codon= replace_chars(upper(cds_seq[i:i+3]), 'U', 'T')
if include_selenocysteine and codon=='TGA': out+='U'
elif gaps_to and codon=='---': out+=gaps_to
elif codon_table.has_key(codon): out+=codon_table[codon]
else: out+='X'
i+=3
return out
def retrotransl(aa_seq, gaps_to='', codon_hash={}):
"""translate an aminoacid sequence back to coding sequence. The first codon in alphabetical order is considered, unless a different codon_hash is provided. Argument gaps_to can be used to provide the character for gaps. Notice that a three character argument should be provided"""
if not codon_hash: codon_hash=retrotrans
out=''
if len(gaps_to)==1: gaps_to*=3
if gaps_to and len(gaps_to)!=3: raise Exception, "retrotransl ERROR gaps_to should be a string with length 3 or 1! gaps_to="+str(gaps_to)
for aa in aa_seq:
aa=upper(aa)
if gaps_to and aa=='-': out+=gaps_to
elif codon_hash.has_key(aa):
codon=codon_hash[aa]
if type(codon)==list: codon=codon[0] #taking first in alphabetical order
out+=codon
else: out+='NNN'
return out
class e_v:
""" Class for coping with evalues without going crazy because of out of memory
"""
def __init__(self, anything):
self.string=str(anything)
self.value='!'
try:
self.value=float(self.string)
except ValueError:
"nothing"
def exponent(self):
if 'e' in self.string:
return int(self.string.split('e')[1])
else:
if self.value =='!':
raise ValueError
if self.value==0:
return -1000
elif self.value<1:
a= str(self.value).split('.')[1]
exp=-1
while a and a[0]=='0':
exp-=1
a=a[1:]
return exp
elif self.value>=1:
return len(str(self.value).split('.')[0])-1
def is_minor_than(self, other_e_v, or_equal=0):
if type(other_e_v).__name__ in ["str",'int','float']: #converting if necessary
other_e_v=e_v(str(other_e_v))
if self.exponent() < other_e_v.exponent(): return True
elif self.exponent() > other_e_v.exponent(): return False
else:
if self.string == other_e_v.string: return or_equal
else:
if self.value== "!" or other_e_v.value== "!":
raise ValueError, "ERROR in evalue class! can't compare the two evalues: "+self.string+' AND '+other_e_v.string
else:
if or_equal: return self.value <= other_e_v.value
else: return self.value < other_e_v.value
def __lt__(self, other): return self.is_minor_than(other)
def __le__(self, other): return self.is_minor_than(other, or_equal=1)
def __gt__(self, other): return not self.is_minor_than(other, or_equal=1)
def __ge__(self, other): return not self.is_minor_than(other)
def __repr__(self): return self.string
def __str__(self): return self.string
def __float__(self): return self.value
def __int__(self): return int(self.value)
def __eq__(self, other): return self.is_minor_than(other, or_equal=1) and not self.is_minor_than(other)
def shortcut_log(evalue):
""" utility for evalues e_v ... defining the log(0) as 200, since I think blast is not computing evalues < than e-200"""
try:
if 'e' in str(evalue):
return -int(str(evalue).split('e')[1])
elif evalue>=1:
return 0
elif evalue==0.0:
return 200
else:
a= -int(round(math_log(evalue, 10)))
if a>0:
return a
else:
return 0
except:
print "____________ERROR: ",[evalue], type(evalue)
def match_any_word(main_string, word_list, is_pattern=1, ignore_case=1):
""" Given a string and a list of strings/perl_patterns, it returns 1 is any of them matches the string, 0 otherwise
"""
for w in word_list:
try:
if is_pattern:
if ignore_case:
pattern=re.compile(w, re.IGNORECASE)
else:
pattern=re.compile(w)
if pattern.search(main_string):
return 1
else:
if ignore_case:
if w.lower() in main_string.lower():
return 1
else:
if w in main_string:
return 1
except:
printerr('ERROR with pattern: '+w)
raise
return 0
def score_tags(blast_evalues_and_titles, positive=[], negative=[], neutral=[], verbose=0, max_n_titles=0):
"""Input: list of objects [evalue, title] coming from parsing a blast file; evalue should be a e_v class object. titles should be complete (not just gis). Other arguments are: positive, negative, neutral tags, to be searched in the titles. The lines matching a neutral tag are skipped. Lines matching a negative tag (or no positive tag) are score negatively. Lines matching a positive tag are scored positively. The score depends on the negative logarithm of the evalue.
"""
score=0
if max_n_titles==0:
max_n_titles=len(blast_evalues_and_titles)
for evalue, title in blast_evalues_and_titles[:max_n_titles]:
score_of_this_tag=shortcut_log(evalue)
if not match_any_word(title, neutral):
if match_any_word(title, negative):
score-=score_of_this_tag
if verbose:
print 'NEGATIVE_M ',title, evalue, '*-'+str(score_of_this_tag)
elif match_any_word(title, positive):
score+=score_of_this_tag
if verbose:
print 'POSITIVE ',title, evalue, '*+'+str(score_of_this_tag)
else:
if verbose:
print 'NEGATIVE ',title, evalue, '*-'+str(score_of_this_tag)
score-=score_of_this_tag
elif verbose:
print 'NEUTRAL', title, evalue, '/'+str(score_of_this_tag)
return score
def dict_to_py_obj(sstring):
"""Take as input a string, which is a dictionary (hash) as printed usually by python, like : {'a':'asdasfas', 'b': 'asfdasf'} and return a copy of the original object that was run.
"""
hash_out={}
if sstring[0]=='{':
sstring=sstring[1:]
while sstring and not sstring[0]=='}':
#key
if sstring[0] in ["'", '"']:
#key is string
key=sstring[1:].split(sstring[0]+ ":")[0]
sstring=sstring[1+len(key)+2+1:]
else:
value_string=sstring.split(":")[0]
key=option_value(value_string)
sstring=sstring[len(value_string)+1:]
#value
if sstring[0] in ["'", '"']:
#value is a string
if sstring[1:].split(sstring[0]+",")[0]==sstring[1:]:
#last value
value=sstring[1:].split(sstring[0]+"}")[0]
sstring=''
else:
value=sstring[1:].split(sstring[0]+",")[0]
sstring=sstring[1+len(value)+2+1:]
else:
value_string =sstring.split(',') [0]
if value_string ==sstring.split(',') [0] ==sstring:
#last value
value=option_value(sstring[1:].split("}")[0])
sstring=''
else:
value= option_value(value_string )
sstring=sstring[len(value_string)+2:]
hash_out[key]=value
return hash_out
def dict_to_config_file(diz, fileout=''):
"""Take as input a dictionary (typically a opt dictionary) and return a string corresponding to a configuration file that would be loaded in memory as the input dictionary.
"""
out=''
for k in diz:
out+='\n'+str(k)+' = '+str(diz[k])
if out:
out=out[1:]
if fileout:
write_to_file(out, fileout)
return out
def float_generalized(stringg):
try:
a=float(stringg)
return a
except ValueError:
if stringg[0]=='e':
return float('1'+stringg)
def replace_chars(astring, chars_list, replace_to_this=''):
return ''.join([c if not c in chars_list else replace_to_this for c in astring])
# out=''
# for c in astring:
# if not c in chars_list:
# out+=c
# else:
# out+=replace_to_this
# return out
def debug(msg):
# if opt.has_key('v') and opt['v']:
'nothing'
# print msg
opt=options()
colored_keywords={}
def printerr(msg, put_newline=0, how='', keywords={}, is_service=False):
global printed_rchar
if not keywords and colored_keywords: keywords=colored_keywords
msg=str(msg)
if put_newline: msg=msg+'\n'
no_color_msg=msg
if printed_rchar:
sys.stderr.write('\r'+printed_rchar*' '+'\r' )
printed_rchar=0
if sys.stdout.isatty() and not opt['no_colors']:
if how:
for c in how.split(','):
if not terminal_codes.has_key(c): raise Exception, "ERROR option 'how' for write was not recognized: "+str(c)+' ; possible values are: '+join([i for i in terminal_codes.keys() if i], ',')
msg=terminal_codes[c]+msg+terminal_codes['']
for word in keywords:
code=''
for c in keywords[word].split(','): code+=terminal_codes[c]
msg= replace(msg, word, code+word+terminal_codes[''])
sys.stderr.write(str(msg))
if not is_service and 'log_file' in globals(): print >> log_file, str(no_color_msg),
def service(msg):
""" see write function"""
msg=str(msg)
global printed_rchar, opt
if sys.stderr.isatty() and not opt['Q']:
if printed_rchar:
printerr('\r'+printed_rchar*' ', is_service=True )
printerr( "\r"+msg, is_service=True)
printed_rchar=len(msg)
#if 'log_file' in globals(): print >> log_file, str(msg+'\n') #putting a newline
def verbose(msg, put_newline=0):
global opt
if put_newline: msg=str(msg)+'\n'
if opt['v']:
write( msg )
if 'log_file' in globals(): print >> log_file, str(msg),
terminal_codes={'':'\033[0m', 'red':'\033[31m', 'green':'\033[32m', 'black':'\033[30m', 'yellow':'\033[33m', 'blue':'\033[34m', 'magenta':'\033[35m', 'cyan':'\033[36m', 'white':'\033[37m', 'bright':'\033[1m', 'dim':'\033[2m', 'underscore':'\033[4m', 'blink':'\033[5m', 'reverse':'\033[7m', 'hidden':'\033[8m'}
def write(msg, put_newline=0, how='', keywords={}):
""" Function to extend the functionalities of the standard 'print'. First argument (put_newline) when set to 1 put a newline after the string passed, as print would normally do. The argument "how" can be given a color to write the message in that color (only for atty terminals). This is prevented if opt['no_colors'] is active. The function write is coupled with function "service" which prints service message which are deleted when another service message is printed, or another message is printed with the write function. If you use service, you should only print things with "write".
Argument keywords allows to use certain colors (or other "how" arguments) for certain keywords. The argument is a hash of keywords and correspoding how arguments. for example if you want to higlight all "ERROR" in red, pass keywords={'ERROR':'red'}
"""
msg=str(msg)
global printed_rchar, opt
if not keywords and colored_keywords: keywords=colored_keywords
if put_newline: msg=msg+'\n'
no_color_msg=msg
if sys.stdout.isatty() and not opt['no_colors']:
if how:
for c in how.split(','):
if not terminal_codes.has_key(c): raise Exception, "ERROR option 'how' for write was not recognized: "+str(c)+' ; possible values are: '+join([i for i in terminal_codes.keys() if i], ',')
msg=terminal_codes[c]+msg+terminal_codes['']
for word in keywords:
code=''
for c in keywords[word].split(','): code+=terminal_codes[c]
msg= replace(msg, word, code+word+terminal_codes[''])
if printed_rchar:
sys.stderr.write('\r'+printed_rchar*' '+'\r' )
printed_rchar=0
sys.stdout.write(msg)
if 'log_file' in globals(): print >> log_file, no_color_msg,
warning=write
def is_empty_file(filename):
return is_file(filename) and os.stat(filename)[6]==0
def is_valid_blast_output(filename):
b=bash('tail -30 '+filename)
if not b[0] and 'Lambda' in b[1]:
return True
return False
def framesBlastToTranseq( Blastframe, seq_length ):
### translate the blast notation of frames to the ebi transeq notation
if Blastframe>0:
return Blastframe
else:
return -( 1+ ( seq_length+ Blastframe+1 )%3 )
def overlapping( range1, range2):
if max(range1)<=min(range2) or max(range2) <= min(range1) :
return False
else:
return True
def positions_to_frame(pos_start, strand='+', chr_length=None):
""" Tells the frame (in blast notation) of a genomic range. we just need the starting position (which is > the end if strand is negative). The chr_length is needed only if the strand is negative.
Blast frame notation:
+ positions: 123456789 123456789 123456789
if starts here: |__|__ |__|__ |__|__
then frame: +1 +2 +3
- positions: 123456789 123456789 123456789
if starts here: __|__| __|__| __|__|
then frame: -1 -2 -3
so the trick for neg strand is: pstart%3 - chrlength%3 -1 --> frame ; it doesn't work only if pstart%3 - chrlength%3 -1 > 0, which is only whe pstart%3 is 2 and chrlength%3 is 0 --> supposed result 1, must be -2. I correct it manually. more elegant solutions would be more expensive anyway, so let's do it this way. """
if strand=='+':
frame=pos_start%3
if frame==0: frame=3
elif strand=='-':
if chr_length is None: raise Exception, "ERROR positions_to_frame: if strand is negative, the chromosome length must be provided to know the frame! "
frame = pos_start%3 - chr_length%3 -1
if frame == 1 : frame=-2
else:
raise Exception, "ERROR positions_to_frame: strand not recognized: '"+strand+"'"
return frame
def are_overlapping_ranges( range1, range2): #[min, max], [min, max] ; return False or the new region containing both;
#look into picture (lab notes) for case listing. #n refers to the picture
#taking mininum and maximum of the 2 ranges################################################### ehiiii
if range1[0]<range1[1]:
r1_0, r1_1 =range1[0], range1[1]
else:
r1_1, r1_0 =range1[0], range1[1]
if range2[0]<range2[1]:
r2_0, r2_1 =range2[0], range2[1]
else:
r2_1, r2_0 =range2[0], range2[1]
################################################
if r1_1<r2_0 or r2_1 < r1_0:
return False # 2 or 3
elif r2_0<r1_0:
if r2_1 < r1_1:
return [ r2_0, r1_1 ] # 4
else:
return [ r2_0, r2_1 ] # 6
elif r2_1 < r1_1 :
return [ r1_0, r1_1 ] #5
else:
return [ r1_0, r2_1 ] #1
to_comment=['^', '$', '.', '[', ']', '|', '(', ')', '*', '+', '?', "\\" ]
def comment_for_gawk(string): # comment characthers so that the string can be found with gawk
out=''
for char in string:
if char in to_comment:
out+='\\'
out+=char
return out
def write_to_file(string, filename):
filett =open(filename, 'w')
print >> filett, string
filett.close()
def del_white(string):
"""str-> str with only one white char between words
"""
string=' '+string+' '
c=1
while len(string)!=c:
while string[c-1]==' ' and string[c]==' ' and len(string)!=c+1:
string=string[:c-1]+string[c:]
c=c+1
return string[1:-2]
def configuration_file(filename, just_these_keys={}):
""" Utility to read configuration files and return an opt with the parsed information, having as keys the option names, and reporting the values. These are automatically converted to the "minimal" type. If the value is an integere, it is cast to integer, then float is tried, otherwise string. It the argument just_these_keys is provided, only a subset of keys are reported, those present as keys of the hash just_these_keys.
Example of configuration file format:
temp= /tmp/
profiles_folder = /users/rg/mmariotti/profiles
keep_blast=1
# commented lines like this one are not read. empty lines are also not read.
blast_options.DEFAULT = -b 5000 -F F
blast_options.DEEP = -b 10000 -F F
# For dotted keys (what is before the "="), hashes are returned. In the two last lines, a hash is created as value of the output opt, corresponding to the key "blast_options". This nested hash will have two keys: DEFAULT and DEEP, and the corresponding values will be the strings reported in the config file.
exonerate_options.example.DEEP = prova
# when multiple dots are present in the key, a more complex nested structure of hashes is created. If the configuration file had only the line above, the reported opt would be: {'exonerate_options':{'example':{'DEEP':'prova'}} }