-
Notifications
You must be signed in to change notification settings - Fork 0
/
geo.py
executable file
·1404 lines (1128 loc) · 45.9 KB
/
geo.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
"""Library to interface with the GEO (GDS- GEO DataSets) repository"""
import os
import re
import sys
import urllib
import traceback
from datetime import datetime
import time
import enchant
import cPickle
# from classifiers import *
from django.db.models import Q
import re
from datacollection.models import Samples
try:
import xml.etree.cElementTree as ET
except ImportError:
import xml.etree.ElementTree as ET
from xml.dom.minidom import parseString
#AUTO-load classifiers
#a trick to get the current module
_modname = globals()['__name__']
_this_mod = sys.modules[_modname]
_ppath = "/".join(_this_mod.__file__.split("/")[:-1])
d = enchant.Dict("en_US")
import json
# #CAN drop this if this is an app!
# DEPLOY_DIR="/home/lentaing/envs/newdc1.4/src"
# sys.path.insert(0, DEPLOY_DIR)
# from django.core.management import setup_environ
# from django.utils.encoding import smart_str
# import settings
# setup_environ(settings)
from django.utils.encoding import smart_str
from datacollection import models
#dynamically load classifiers
#import classifiers
import sra
import pubmed
### HELPER fns
def getFromPost(geoPost, cat):
"""tries to search for cat(VALUE) returns VALUE if found, otherwise ""
NOTE: categories can be in UPPER or lowercase, eg. TITLE or title
"""
m = re.search("%s\((.+)\)" % cat.upper(), geoPost)
if m:
return m.group(1)
else:
return ""
def cleanCategory(s):
"""Given a string, replaces ' ' with '_'
'/', '&', '.', '(', ')'with ''
"""
tmp = s.replace(" ", "_")
for bad in ['/', '&', '.', '(', ')', ',']:
tmp = tmp.replace(bad, "")
return tmp
def isXML(doc):
"""TEST if it is a valid geo XML record
NOTE: first lines are-
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
"""
f = doc.split("\n")
return f[0].strip() == """<?xml version="1.0" encoding="UTF-8" standalone="no"?>"""
def readGeoXML(path, docString=None):
"""
Input: a file path or a string--default is to use the path
Tries to read in the geo xml record,
**KEY: REMOVES the xmlns line
Returns the xml record text WITHOUT the xmlns line!!!
"""
if docString:
f = docString.split("\n")
else:
f = open(path)
tmp = []
for l in f:
if l.find("xmlns=\"http://www.ncbi.nlm.nih.gov/geo/info/MINiML\"") == -1:
tmp.append(l)
if not docString:
f.close()
return "".join(tmp)
### GDS interface
def getGDSSamples():
"""Will run the predefined query and return a list of GDS ids
NOTE: this returns ALL GDS samples which are of SRA type i.e.
ALL CHIP-SEQ, RNA-SEQ, etc.
"""
#expireDate = now - 30 days in seconds
#ref: http://stackoverflow.com/questions/7430928/python-comparing-date-check-for-old-file
# _expireDate = time.time() - 60 * 60 * 24 * 30
ret = []
#
# #TRY: to read a file first -- IF IT IS NOT STALE
path = os.path.join(_ppath, "gdsSamples.txt")
# if os.path.exists(path) and not os.path.getctime(path) < _expireDate:
# f = open(path)
# for l in f:
# ret.append(l.strip())
# f.close()
# else:
# #REFRESH!
#REAL URL
URL = """http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=gds&term=SRA[Sample Type] AND gsm[Entry Type] AND ("homo sapiens"[Organism] OR "mus musculus"[Organism])&retmax=100000"""
#TEST URL
#URL = """http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=gds&term=SRA[Sample Type] AND gsm[Entry Type] AND ("homo sapiens"[Organism] OR "mus musculus"[Organism])&retmax=10"""
try:
#print "getGDSSample: %s" % URL
f = urllib.urlopen(URL)
root = ET.fromstring(f.read())
f.close()
#Get the IDList
tmp = root.findall("IdList/Id")
ret = [i.text for i in tmp]
#write to disk
f = open(path, "w")
for l in ret:
f.write("%s\n" % l)
f.close()
print "Refresh %s"%path
except:
print "Exception in user code:"
print '-' * 60
traceback.print_exc(file=sys.stdout)
print '-' * 60
return ret
### Translation fns
def gsm_idToAcc(gdsId):
"""Given a GDS id, e.g. 300982523, tries to give a GDS accession, e.g.
GSM982523
NOTE: there is an algorithm: acc = "GSM"+gdsId[1:] (strip leading 0s)
"""
#Cut = dropping of the "3" (which indicates sample) and removal of leading
#leading 0s
cut = gdsId[1:].lstrip("0")
return "GSM%s" % cut
def gse_idToAcc(gdsId):
"""Given a GDS id, e.g. 200030833, tries to give a GDS accession, e.g.
GSE30833
NOTE: there is an algorithm: acc = "GSE"+gdsId[1:] (strip leading 0s)
"""
#Cut = dropping of the "2" (which indicates series) and removal of leading
#leading 0s
cut = gdsId[1:].lstrip("0")
return "GSE%s" % cut
### Librarian fns
def gsmToGse(gsmid):
"""Given a gsmid, will try to get the geo series id (GSE) that the
sample is associated with; if it is associated with several GSEs, then
returns the first.
STORES the GSE ID, e.g. 200030833 in the file
NOTE: if we want GSEs then we need to translate IDs to GSEXXXXX just
like we do for GSMs above
uses this query:
http://www.ncbi.nlm.nih.gov/gds/?term=gse%5BEntry+Type%5D+AND+GSM764990%5BGEO+Accession%5D&report=docsum&format=text
"""
ret = None
path = os.path.join(_ppath, "GSM_GSE")
if not os.path.exists(path):
os.mkdir(path)
subdir = os.path.join(path, gsmid[:7])
if not os.path.exists(subdir):
os.mkdir(subdir)
path = os.path.join(subdir, "%s.txt" % gsmid)
if os.path.exists(path):
f = open(path)
ret = f.read().strip()
f.close()
else:
#This URL is slow!
#NOTE: for every ncbi query, try to find the eutils equivalent!
#--it's faster
#URL = "http://www.ncbi.nlm.nih.gov/gds/?term=gse[Entry Type] AND %s[GEO Accession]&report=docsum&format=text" % gsmid
URL = "http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=gds&term=gse[Entry Type] AND %s[GEO Accession]" % gsmid
try:
#print "gsmToGse: %s" % URL
urlf = urllib.urlopen(URL)
root = ET.fromstring(urlf.read())
urlf.close()
#Get the IDList
tmp = root.findall("IdList/Id")
if tmp:
ret = tmp[0].text.strip()
f = open(path, "w")
f.write(ret)
f.close()
#FIRST URL
# m = re.search("ID:\ (\d+)", urlf.read())
# urlf.close()
# if m:
# ret = m.group(1).strip()
# f = open(path, "w")
# f.write(ret)
# f.close()
except:
print "gsmToGse"
print "URL is" + URL
print '-' * 60
traceback.print_exc(file=sys.stdout)
print '-' * 60
return ret
def gseToPubmed(gseid):
"""Given a gseid, will try to get the pubmed id
"""
ret = None
path = os.path.join(_ppath, "GSE_PUB")
if not os.path.exists(path):
os.mkdir(path)
subdir = os.path.join(path, gseid[:6])
if not os.path.exists(subdir):
os.mkdir(subdir)
path = os.path.join(subdir, "%s.txt" % gseid)
if os.path.exists(path):
f = open(path)
ret = f.read().strip()
f.close()
else:
URL = "http://eutils.ncbi.nlm.nih.gov/entrez/eutils/elink.fcgi?id=%s&db=pubmed&dbfrom=gds" % gseid
try:
print "gseToPubmed: %s" % URL
urlf = urllib.urlopen(URL)
root = ET.fromstring(urlf.read())
urlf.close()
#Get the IDList
tmp = root.findall("LinkSet/LinkSetDb/Link/Id")
if tmp:
ret = tmp[0].text.strip()
f = open(path, "w")
f.write(ret)
f.close()
except:
print "gsmToGse"
print '-' * 60
traceback.print_exc(file=sys.stdout)
print '-' * 60
return ret
def gsmToSra(gsmid):
"""Given a gsm id, will try to get an SRA id, using this query:
http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=sra&term=GSM530220 to get the SRA id
Returns the SRA id corresponding to the GSM, None otherwise
"""
ret = None
path = os.path.join(_ppath, "GSM_SRA")
if not os.path.exists(path):
os.mkdir(path)
subdir = os.path.join(path, gsmid[:7])
if not os.path.exists(subdir):
os.mkdir(subdir)
path = os.path.join(subdir, "%s.txt" % gsmid)
if os.path.exists(path):
f = open(path)
ret = f.read().strip()
f.close()
else:
URL = "http://www.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=sra&term=%s" % gsmid
try:
#print "gsmToSra: %s" % URL
urlf = urllib.urlopen(URL)
root = ET.fromstring(urlf.read())
urlf.close()
#Get the IDList--should just be one
tmp = root.findall("IdList/Id")
if tmp:
ret = tmp[0].text.strip()
f = open(path, "w")
f.write(ret)
f.close()
except:
print '-' * 60
traceback.print_exc(file=sys.stdout)
print '-' * 60
return ret
def getGeoXML(accession):
"""HANDLES GEO XML records--i.e. our GEO XML librarian!
Given a GEO ACCESSION ID, return the xml record for it
(making the urllib call)"""
#path pattern: EXAMPLE-GSM1126513 geo/GSM1126/GSM1126513
path = os.path.join(_ppath, "geo")
if not os.path.exists(path):
os.mkdir(path)
subdir = os.path.join(path, accession[:7])
if not os.path.exists(subdir):
os.mkdir(subdir)
path = os.path.join(subdir, "%s.xml" % accession)
if os.path.exists(path):
f = open(path)
docString = f.read()
f.close()
else:
#print accession
URL = "http://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=%s&view=quick&form=xml&targ=self" % accession
try:
#print "getGeoXML: %s" % URL
urlf = urllib.urlopen(URL)
docString = urlf.read()
urlf.close()
if isXML(docString):
#write to file
f = open(path, "w")
f.write(docString)
f.close()
else:
print accession
print "ERROR: accession is NOT xml. (The accession may be deleted from GEO repository)"
return None
except:
print "Exception in user code:"
print '-' * 60
traceback.print_exc(file=sys.stdout)
print '-' * 60
docString = None
return docString
def parseGeoInfo(accession):
"""parse necessary information (detailed description from the Geo XML file"""
xmlString = readGeoXML(None, getGeoXML(accession))
tree = ET.fromstring(xmlString)
ret = {}
for node in tree.findall("Sample/Channel/Characteristics"):
if node.get("tag"):
ret[node.get("tag").replace("_", " ")] = node.text.strip()
ret["source name"] = tree.find("Sample/Channel/Source").text.strip()
ret["title"] = tree.find("Sample/Title").text.strip()
ret['last update date'] = tree.find("Sample/Status/Last-Update-Date").text.strip()
ret['release date'] = tree.find("Sample/Status/Release-Date").text.strip()
return ret
def postProcessGeo(accession, docString=None):
"""post processes the GEO record to feed into the classifiers
uses docString IF it is available, otherwise will read the record
"""
#ignore these tags
ignore = ["Growth-Protocol", "Extract-Protocol", "Treatment-Protocol"]
_thresh = 10 #max 10 words
path = os.path.join(_ppath, "geoPost")
if not os.path.exists(path):
os.mkdir(path)
subdir = os.path.join(path, accession[:7])
if not os.path.exists(subdir):
os.mkdir(subdir)
path = os.path.join(subdir, "%s.txt" % accession)
if os.path.exists(path):
f = open(path)
docString = f.read()
f.close()
return docString
else:
#need to build the doc
if not docString:
#read the document from geo
docString = getGeoXML(accession)
#process the string
if not docString:
return None
text = readGeoXML(None, docString=docString)
try:
root = ET.fromstring(text)
except:
print "Could not parse: %s" % accession
print '-' * 60
traceback.print_exc(file=sys.stdout)
print '-' * 60
return None
#3. collect all of the information under Sample/Channel
tmp = []
#Things in sample to get:
ls = ['Title', 'Source', 'Library-Strategy', 'Library-Source',
'Library-Selection', 'Supplementary-Data']
for t in ls:
tag = root.findall("Sample/%s" % t)
for tt in tag:
tmp.append("%s(%s)" % (t.upper(), tt.text.strip().upper()))
channels = root.findall("Sample/Channel")
for c in channels:
for child in c:
category = ""
if child.tag in ignore:
continue
#Special case: Characteristic--take the tag attrib
if child.tag == "Characteristics":
if "tag" in child.attrib and child.attrib["tag"]:
category = child.attrib["tag"].lstrip().rstrip()
else:
category = child.tag.lstrip().rstrip()
#convert categories like "cell line" to "CELL_LINE"
#tmp.append("%s(%s)" % (category.replace(" ","_").upper(),
# child.text.strip()))
val = child.text.strip()
#THRESHOLD: values can be at most 10 words
if len(val.split()) <= _thresh:
tmp.append("%s(%s)" % (cleanCategory(category).upper(),
val.upper()))
else:
#take first 10 words
tmp.append("%s(%s)" % (cleanCategory(category).upper(),
" ".join(val.split()[:_thresh]).upper()))
#4. write the information to file
f = open(path, "w")
f.write("%s" % smart_str("\n".join(tmp)))
f.close()
return "\n".join(tmp)
### Syncing fns
def syncGeo_GeoPost():
"""will ensure that the records in geo are post processed
Returns a list of newly created records
"""
ret = []
p = os.path.join(_ppath, "geo")
for root, dirs, files in os.walk(p):
for fname in files:
path = os.path.join(root, fname)
acc = fname.split(".")[0]
dest = os.path.join(_ppath, "geoPost", acc[:7], "%s.txt" % acc)
if not os.path.exists(dest):
#update geoPost
if postProcessGeo(acc):
ret.append(acc)
return ret
def syncGeo_SRA():
"""will try to ensure that there is one SRA record for every geo record
KEY: use this to query the SRA db- see gsmToSra
http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=sra&term=GSM530220 to get the SRA id
Returns a list of newly created records (in SRA)
"""
ret = []
p = os.path.join(_ppath, "geo")
for root, dirs, files in os.walk(p):
for fname in files:
path = os.path.join(root, fname)
gsm = fname.split(".")[0]
sraId = gsmToSra(gsm)
if sraId:
dest = os.path.join(_ppath, "sra", sraId[:3], "%s.xml" % sraId)
if not os.path.exists(dest):
#create the new record
tmp = sra.getSraXML(sraId)
if tmp:
ret.append(sraId)
return ret
def syncSRA_Geo():
"""
NOTE: this fn is NOT as important as syncGeo_SRA b/c Geo is our
primary model!!!
will try to ensure that there is one Geo record for every SRA record
NOTE: tries to find the GSM first in the GSM_SRA map, then in the SRA recrd
Returns a list of newly created records (in GEO)
"""
#relies on the GSM_SRA map first
#1. load the map
_map = {}
p = os.path.join(_ppath, "GSM_SRA")
for root, dirs, files in os.walk(p):
for fname in files:
path = os.path.join(root, fname)
gsm = fname.split(".")[0]
f = open(path)
sraId = f.read().strip()
f.close()
_map[sraId] = gsm
#2. check the sra db
ret = []
p = os.path.join(_ppath, "sra")
for root, dirs, files in os.walk(p):
for fname in files:
gsm = None
path = os.path.join(root, fname)
sraId = fname.split(".")[0]
if sraId in _map:
gsm = _map[sraId]
else:
# try to get the gsm from the file:
docString = sra.getSraXML(sraId)
#try to grep the GSMid
m = re.search("GSM\d+", docString)
if m:
gsm = m.group(0)
if gsm:
dest = os.path.join(_ppath, "geo", gsm[:7], "%s.xml" % gsm)
if not os.path.exists(dest):
if getGeoXML(gsm):
ret.append(gsm)
return ret
def syncGSM_GSE():
"""will ensure that the records in geo have a gse id
Returns a list of newly created records
"""
ret = []
p = os.path.join(_ppath, "geo")
for root, dirs, files in os.walk(p):
for fname in files:
path = os.path.join(root, fname)
acc = fname.split(".")[0]
if acc:
dest = os.path.join(_ppath, "GSM_GSE", acc[:7], "%s.txt" % acc)
if not os.path.exists(dest):
#"update GSM_GSE"
if gsmToGse(acc):
ret.append(acc)
return ret
def syncGSE_PUB():
"""will ensure that every gse record have a pubmed id
Returns a list of newly created records
"""
ret = []
p = os.path.join(_ppath, "GSM_GSE")
for root, dirs, files in os.walk(p):
for fname in files:
path = os.path.join(root, fname)
f = open(path)
acc = f.read().strip()
f.close()
dest = os.path.join(_ppath, "GSE_PUB", acc[:6], "%s.txt" % acc)
if not os.path.exists(dest):
#update GSE_PUB
if gseToPubmed(acc):
ret.append(acc)
return ret
def getGeoSamples_byType(ddir="geo", ttype="ChIP-Seq", refresh=False):
"""A filter for our Geo model; searches our db for the specific sample
type.
NOTE: hones in on Library-Strategy tag
Returns a list of samples fitting the specified
NOTE: building this up takes time, around 10 secs almost 1 minute!
TRY: caching the result, reading from a cached file takes only 1 minute
Store them in files by the .ttype--in the local dir
"""
ret = []
#check for a cached file:
p = os.path.join(_ppath, ddir, ".%s" % ttype)
if not refresh and os.path.exists(p):
f = open(p)
for l in f:
ret.append(l.strip())
f.close()
else:
#NEED to generate the file, and make the call recursively
#actually, just one level of recursion b/c geo is pretty flat
p = os.path.join(_ppath, ddir)
ls = os.listdir(p)
for df in ls:
path = os.path.join(p, df)
if os.path.isfile(path): #it's a file--check if it's ChIP-Seq
acc = df.split(".")[0]
#NOTE: we need readGeoXML to process
text = readGeoXML(path)
try:
rt = ET.fromstring(text)
#check for Library-Strategy
tag = rt.findall("Sample/Library-Strategy")
if tag and tag[0].text.strip() == ttype:
#It's a match!
ret.append(acc)
except:
#ignored!
pass
else:
#it's a dir recur
newd = os.path.join(ddir, df)
ret.extend(getGeoSamples_byType(newd, ttype, refresh))
#write the local file:
f = open(os.path.join(_ppath, ddir, ".%s" % ttype), "w")
for gsm in ret:
f.write("%s\n" % gsm)
f.close()
return ret
def getGeoSamples_byTypes(path, ddir="geo", refresh=False, ttypes = ["ChIP-Seq", "DNase-Hypersensitivity"]):
ret = []
if not refresh and os.path.exists(path):
ret = cPickle.load(open(path))
return ret
for t in ttypes:
ret += getGeoSamples_byType(ddir, t, refresh)
cPickle.dump(ret, open(path, "w"))
return ret
def parseUpdateTime(description_dict):
# a trick to convert time string into a datetime object
time_struct = time.strptime(description_dict["last update date"], "%Y-%m-%d")
return datetime.fromtimestamp(time.mktime(time_struct))
def parseReleaseTime(description_dict):
# a trick to convert time string into a datetime object
time_struct = time.strptime(description_dict["release date"], "%Y-%m-%d")
return datetime.fromtimestamp(time.mktime(time_struct))
def parseAntibody(description_dict):
"""Given a geoPost, will 1. try to parse out the antibody information
2. create the new antibody if necessary with the name as:
VENDOR Catalog# (TARGET) OR
VENDOR Catalog# --if there is no target OR
TARGET --if there is no vendor info
To do this we key in on some key concepts
Returns the sample's antibody, None otherwise
"""
targetFlds = ["antibody source", "chip antibody", "antibody"]
vendorFlds = ["antibody vendorname", "chip antibody provider",
"antibody vendor", "antibody manufacturer",
"chip antibody vendor", "chip antibody manufacturer", "antibody vendorcatalog#",
"antibody vendor and catalog number", "antibody vendor/catalog", "antobody vendor/catalog#"
]
catalogFlds = ["antibody vendorid", "chip antibody catalog",
"antibody CATALOG NUMBER", "chip antibody cat #", "antibody catalog #"]
lotFlds = ["chip antibody lot #"]
#1. try to get the values
vals = [None, None, None, None]
used_fld = []
for (i, ls) in enumerate([targetFlds, vendorFlds, catalogFlds, lotFlds]):
for f in ls:
tmp = description_dict.get(f)
if tmp:
vals[i] = tmp
used_fld.append(f)
break
#2. get each term of the antibody separately
(target, vendor, cat, lot) = tuple(vals)
if target and "input" in target.lower():
ret, created = models.Antibodies.objects.get_or_create(name="input")
return ret
def if_match_then_get(keyword, current_key):
if keyword in current_key:
current_value = description_dict[current_key]
if current_value and current_key not in used_fld:
used_fld.append(current_key)
if current_value.startswith("catalog#"):
current_value = current_value.replace("catalog#, or reference):", "").strip()
return current_value
return None
#3. sometimes the field name is not standard, in other words, it is not included in xxxFlds
#If so, use string matching to parse these fields
for k, v in description_dict.items():
if not (k and v):
continue
if not vendor:
vendor = if_match_then_get("vendor", k)
if not cat:
cat = if_match_then_get("catalog", k)
if not lot:
lot = if_match_then_get("lot", k)
#4. compose the complete antibody name
name_list = []
if vendor:
name_list.append(vendor)
if cat:
name_list.append(cat)
if lot:
name_list.append(lot)
if not vendor and not cat and not lot:
if not target:
target = if_match_then_get('antibody', k)
if target:
name_list.append(target)
name = ", ".join(name_list)
if name:
ret, created = models.Antibodies.objects.get_or_create(name=name)
return ret
else:
return None
# def parseFactor(description_dict):
# # TODO: use description dict to parse, instead of using geoPost
#
# standard_fields = ["chip antibody", "antibody", "chip", "antibody source", "antibody antibodydescription",
# "antibody targetdescription", "factor"]
# avoid_words = ["MILLIPORE", "ABCAM", "METHYLCAP"]
#
# non_standard_fields = [i for i in description_dict.keys() if "antibody" in i and i not in standard_fields] + [
# 'title']
# #1. try to get the values
# factor_pattern = re.compile(r"[a-z]+[-\.]?[a-z0-9]+", re.I)
# factor_term_pattern = re.compile(r"^[a-z]+[-\.]?[a-z0-9]+$", re.I)
# possible_new_factor = None
#
# for t in standard_fields + non_standard_fields:
# print t
# tmp = description_dict.get(t, "").strip()
# # skip the null field
# if not tmp:
# continue
#
# # make all character upper case, then delete strings like `ANTI` and `_`
# tmp = tmp.upper().replace("ANTI-", " ").replace("ANTI", " ").replace("_", " ").strip()
#
# # `N/A` often concurs with `Input`
# if "N/A" in tmp:
# return models.Factors.objects.get_or_create(name="Input")[0]
#
# if "antibody" in t and ("NONE" in tmp or "INPUT" in tmp or "IGG" in tmp):
# return models.Factors.objects.get_or_create(name="Input")[0]
#
# # If the field has very short description and it is not `TITLE`, the description is usually the factor name.
# if t not in non_standard_fields and not possible_new_factor \
# and len(tmp) < 10 and tmp not in avoid_words and factor_term_pattern.match(tmp) \
# and not models.Aliases.objects.filter(name__icontains=tmp) \
# and not models.Factors.objects.filter(name__icontains=tmp):
# possible_new_factor = tmp
#
#
#
# # split the description into tokens
# splited = factor_pattern.findall(tmp)
# print splited
# for s in splited:
#
# if d.check(s):
# continue
# if s in avoid_words:
# continue
# # POL2 factor usually starts with `POL2`
# if (s.startswith("POL2") and len(s) < 10):
# return models.Factors.objects.get_or_create(name="POL2")[0]
#
# # If a token is neither a number nor a vocabulary in dictionary, it may be the factor name
# if models.Factors.objects.filter(name__iexact=s):
# return models.Factors.objects.get(name__iexact=s)
#
# if models.Aliases.objects.filter(name__iexact=s):
# try:
# alias = models.Aliases.objects.get(name__iexact=s)
# return alias.factor
# except Exception as e:
# print e
# print "FATAL!"
# return None
#
#
#
# # special cases for `Input` and `POL2`
# if "INPUT" in splited:
# return models.Factors.objects.get_or_create(name="Input")[0]
# if ("POLYMERASE" in splited) or ("POL" in splited):
# return models.Factors.objects.get_or_create(name="POL2")[0]
#
# if possible_new_factor:
# ret, created = models.Factors.objects.get_or_create(name=possible_new_factor)
# if created:
# ret.status = 'new'
# ret.save()
# return ret
#
# return None
def _parse_a_field(description_dict, a_field, DCmodel, max_create_length=100, new=False):
if not description_dict.get(a_field, None):
return None
if len(description_dict.get(a_field, "")) > 0:
result_searched_by_name = sorted(
DCmodel.objects.extra(where={"%s REGEXP CONCAT('([^a-zA-Z0-9]|^)', `name`, '([^a-rt-zA-RT-Z0-9]|$)')"},
params=[description_dict[a_field]]),
key=lambda o: len(o.name),
reverse=True)
if result_searched_by_name and len(result_searched_by_name[0].name.strip()) > 0:
return result_searched_by_name[0]
if DCmodel not in [models.Factors, models.Aliases] :
result_searched_by_aliases = sorted(DCmodel.objects.exclude(aliases=None).exclude(aliases="").extra(
where={"%s REGEXP CONCAT('([^a-zA-Z0-9]|^)', `aliases`, '([^a-rt-zA-RT-Z0-9]|$)')"},
params=[description_dict[a_field]]),
key=lambda o: len(o.name),
reverse=True)
if result_searched_by_aliases and len(result_searched_by_aliases[0].name.strip()) > 0:
return result_searched_by_aliases[0]
if new and len(description_dict[a_field]) <= max_create_length:
ret, created = DCmodel.objects.get_or_create(name=description_dict[a_field])
if created:
ret.status = 'new'
return ret
return None
def _parse_fields(description_dict, strict_fields, greedy_fields, DCmodel, greedy_length=100):
for sf in strict_fields:
ret = _parse_a_field(description_dict, sf, DCmodel, greedy_length, new=False)
if ret:
return ret
for gf in greedy_fields:
ret = _parse_a_field(description_dict, gf, DCmodel, greedy_length, new=True)
if ret:
return ret
return None
#
# def parseCellLineBySourceName(description_dict):
# return _parse_fields(description_dict, ['source name'], [],lambda m: m.CellLines, 15, )
#
def _search_factor_by_pattern(field_name, field_content):
field_content = field_content.upper()
if "antibody" in field_name or 'Chip' in field_name or 'title' in field_name:
if "NONE" in field_content or "INPUT" in field_content or "IGG" in field_content or "N/A" in field_content:
return models.Factors.objects.get_or_create(name="Input")[0]
if "POL2" in field_content or "POLYMERASE" in field_content:
return models.Factors.objects.get_or_create(name="POL2")[0]
if "CTCF" in field_content:
return models.Factors.objects.get_or_create(name="CTCF")[0]
return None
def _guess_factor_boldly(field_name, field_content):
factor_finder = re.compile(r"anti[^a-z]([a-z]+[-\.]?[a-z0-9]{0,4})", re.I)
# get the word after anti
factor_pattern = re.compile(r"^[a-z]+[-\.]?[a-z0-9]+$", re.I)
factor_found = factor_finder.findall(field_content)
stop_words_pattern = re.compile(r"(mouse)|(abcam)|(dmso)|(negative)|(seq)|(chip)", re.I)
if factor_found and not stop_words_pattern.match(factor_found[0]):
return models.Factors.objects.get_or_create(name=factor_found[0])[0]
if len(field_content) < 10 and factor_pattern.match(field_content) and not stop_words_pattern.match(field_content):
return models.Factors.objects.get_or_create(name=field_content)[0]
return None
def parseFactor(description_dict):
standard_fields = [i for i in
["antibody targetdescription", "factor", "title", 'hgn'] if i in description_dict.keys()]
non_standard_fields = [i for i in description_dict.keys() if "antibody" in i and i not in standard_fields]
fields = standard_fields + non_standard_fields
first_try = _parse_fields(description_dict, fields, [], models.Factors)
if first_try:
return first_try
print ".",
second_try = _parse_fields(description_dict, fields, [], models.Aliases)
if second_try:
return second_try.factor
print ".",
for f in fields:
third_try = _search_factor_by_pattern(f, description_dict[f])
if third_try:
return third_try
print ".",
for f in standard_fields:
fourth_try = _guess_factor_boldly(f, description_dict[f])
if fourth_try:
return fourth_try
print ".",
return None
def parseCellType(description_dict):
return _parse_fields(description_dict,
['cell type', 'cell lineage', 'cell', 'cell line', 'source name', 'cell description', 'title'],
['cell type'],
models.CellTypes)
def parseCellLine(description_dict):
return _parse_fields(description_dict,
['cell', 'cell line', 'source name', 'cell description', 'title'],
['cell line'],
models.CellLines)
def parseCellPop(description_dict):
return _parse_fields(description_dict, ['cell', 'source name', 'cell description', 'title'], [], models.CellPops)
def parseTissue(description_dict):
return _parse_fields(description_dict,
['tissue', 'tissue type', 'tissue depot', 'source name', 'cell description', 'title'],
['tissue', 'tissue type'],
models.TissueTypes, )
def parseStrain(description_dict):
return _parse_fields(description_dict,