1 |
5169
|
aaronmk
|
# TNRS
|
2 |
4990
|
aaronmk
|
|
3 |
13464
|
aaronmk
|
import os.path
|
4 |
4990
|
aaronmk
|
import re
|
5 |
|
|
import sys
|
6 |
|
|
import time
|
7 |
|
|
import urllib2
|
8 |
|
|
|
9 |
5149
|
aaronmk
|
import csvs
|
10 |
5107
|
aaronmk
|
import exc
|
11 |
5120
|
aaronmk
|
import profiling
|
12 |
4990
|
aaronmk
|
import streams
|
13 |
5144
|
aaronmk
|
import strings
|
14 |
4990
|
aaronmk
|
|
15 |
|
|
# Config
|
16 |
|
|
initial_pause = 0.35 # sec
|
17 |
|
|
pause_growth_factor = 1.3
|
18 |
5125
|
aaronmk
|
max_pause = 30*60 # sec; = 30 min; TNRS sometimes freezes for ~10 min
|
19 |
4990
|
aaronmk
|
assert initial_pause <= max_pause
|
20 |
13548
|
aaronmk
|
#max_names = 5000 #according to http://tnrs.iplantcollaborative.org/TNRSapp.html
|
21 |
5121
|
aaronmk
|
max_names = 500 # the maximum above crashes the TNRS server
|
22 |
4990
|
aaronmk
|
|
23 |
|
|
# Protocol params
|
24 |
13464
|
aaronmk
|
server = streams.file_get_contents(os.path.dirname(__file__)+"/tnrs.url")
|
25 |
|
|
#server = 'tnrs.iplantcollaborative.org' # live server
|
26 |
13462
|
aaronmk
|
url_base = 'http://'+server+'/tnrsdemo/'
|
27 |
4990
|
aaronmk
|
url = url_base+'search'
|
28 |
|
|
initial_headers = {
|
29 |
|
|
'Content-Type': 'text/x-gwt-rpc; charset=utf-8',
|
30 |
|
|
'X-GWT-Module-Base': url_base,
|
31 |
|
|
'X-GWT-Permutation': '574AA16D15D917C7704646FD92AFF6B3',
|
32 |
|
|
}
|
33 |
|
|
submission_request_template = ('7|0|7|'+url_base+
|
34 |
9912
|
aaronmk
|
'|1E87C78041CEFBF0992F46BDF84D7D60|org.iplantc.tnrs.demo.client.SearchService|\
|
35 |
13544
|
aaronmk
|
doSearch|java.lang.String/2004016611|{"sources":"gcc,tpl,tropicos,usda", \
|
36 |
9912
|
aaronmk
|
"names":"[names]", "type":"matching", "taxonomic":"true", \
|
37 |
|
|
"classification":"tropicos", "match_to_rank":"true"}|0.05|1|2|3|4|2|5|5|6|7|')
|
38 |
4990
|
aaronmk
|
submission_response_pattern = r'^//OK\[1,\["(\w+)"\],0,7\]$'
|
39 |
|
|
retrieval_request_template = ('7|0|15|'+url_base+
|
40 |
|
|
'|1E87C78041CEFBF0992F46BDF84D7D60|org.iplantc.tnrs.demo.client.SearchService\
|
41 |
|
|
|getRemoteData|com.extjs.gxt.ui.client.data.PagingLoadConfig|\
|
42 |
|
|
java.lang.String/2004016611|com.extjs.gxt.ui.client.data.BasePagingLoadConfig/\
|
43 |
|
|
2011366567|com.extjs.gxt.ui.client.data.RpcMap/3441186752|sortField|sortDir|\
|
44 |
|
|
com.extjs.gxt.ui.client.Style$SortDir/640452531|offset|java.lang.Integer/\
|
45 |
|
|
3438268394|limit|{"email":"tnrs@lka5jjs.orv", "key":"[key]", \
|
46 |
9909
|
aaronmk
|
"taxonomic_constraint":"true", "source_sorting":"false", "first":"false"}\
|
47 |
4990
|
aaronmk
|
|1|2|3|4|2|5|6|7|0|1|8|4|9|0|10|11|0|12|13|0|14|13|100|15|')
|
48 |
13436
|
aaronmk
|
# taxonomic_constraint (Constrain by Higher Taxonomy): selects lower ranks
|
49 |
|
|
# only from within the matched higher ranks. must be turned on, to ensure
|
50 |
|
|
# that higher ranks are always authoritative.
|
51 |
|
|
# source_sorting (Constrain by Source): always selects a match from the
|
52 |
|
|
# first source in the list, no matter how low the match score. must be
|
53 |
|
|
# turned off, to avoid worse matches being selected instead of better ones.
|
54 |
4990
|
aaronmk
|
retrieval_response_pattern = '^//OK\[.*?\["com.extjs.gxt.ui.client.data.\
|
55 |
|
|
BasePagingLoadResult/496878394","java.util.ArrayList/4159755760","org.iplantc.\
|
56 |
|
|
tnrs.demo.shared.BeanTNRSEntry/1039545748",".*"\],0,7\]$'
|
57 |
|
|
retrieval_response_info_pattern = r'(?ms).*^Set-Cookie: JSESSIONID=(\w+);'
|
58 |
|
|
download_request_template = ('7|0|6|'+url_base+
|
59 |
|
|
'|1E87C78041CEFBF0992F46BDF84D7D60|org.iplantc.tnrs.demo.client.SearchService|\
|
60 |
|
|
downloadRemoteResults|java.lang.String/2004016611|{"name":"tnrs_results.txt", \
|
61 |
9910
|
aaronmk
|
"mode":"Best", "type":"Detailed", "encoding":"utf8", "dirty":"true", \
|
62 |
9911
|
aaronmk
|
"sources":"false", "taxonomic":"true", "email":"tnrs@lka5jjs.orv", \
|
63 |
4990
|
aaronmk
|
"key":"[key]"}|1|2|3|4|1|5|6|')
|
64 |
|
|
download_response_pattern = '^//OK\[1,\["(.*)"\],0,7\]$'
|
65 |
|
|
download_url_suffix = '&name=tnrs_results.txt&encoding=utf8'
|
66 |
|
|
|
67 |
5083
|
aaronmk
|
class InvalidResponse(Exception): pass
|
68 |
|
|
|
69 |
5144
|
aaronmk
|
def gwt_encode(str_):
|
70 |
|
|
return strings.esc_quotes(strings.json_encode(str_), '|', quote_esc='\!')
|
71 |
4990
|
aaronmk
|
|
72 |
5149
|
aaronmk
|
def make_spliced_decode_map(decode_map):
|
73 |
|
|
return [(r'(?: |(?<=\t)|^)'+re.escape(from_.strip())+r'(?: |(?=\t)|$)',
|
74 |
|
|
strings.regexp_repl_esc(to)) for from_, to in decode_map]
|
75 |
|
|
|
76 |
5154
|
aaronmk
|
padding = ' !pad ' # prepend to empty and whitespace-only strings
|
77 |
5149
|
aaronmk
|
encode_map = [
|
78 |
5167
|
aaronmk
|
('!', ' !exc '), # our escape char
|
79 |
|
|
('\t', ' !tab '), # TNRS replaces with " "
|
80 |
|
|
('\n', ' !nl '), # used to separate multiple names
|
81 |
|
|
('\r', ' !cr '), # used to separate multiple names
|
82 |
5168
|
aaronmk
|
('"', ' !quo '), # TNRS removes it when at the beginning or end
|
83 |
5167
|
aaronmk
|
('%', ' !pct '), # TNRS URL-decodes it in matched fields
|
84 |
5168
|
aaronmk
|
("'", ' !apo '), # TNRS removes it when at the beginning or end
|
85 |
5167
|
aaronmk
|
(';', ' !sem '), # changes TNRS response format
|
86 |
|
|
('\\', ' !bsl '), # TNRS removes it
|
87 |
5165
|
aaronmk
|
('_', ' !und '), # TNRS replaces with " "
|
88 |
5171
|
aaronmk
|
('', ' !sub '), # TNRS removes it
|
89 |
5169
|
aaronmk
|
('×', ' !mul '), # TNRS replaces with "x"
|
90 |
5149
|
aaronmk
|
]
|
91 |
|
|
decode_map = strings.flip_map(encode_map)
|
92 |
5154
|
aaronmk
|
decode_map.append((padding, ''))
|
93 |
5149
|
aaronmk
|
spliced_decode_map = make_spliced_decode_map(decode_map)
|
94 |
|
|
|
95 |
5154
|
aaronmk
|
def encode(str_):
|
96 |
|
|
str_ = strings.replace_all(encode_map, str_)
|
97 |
|
|
# Empty and whitespace-only strings are ignored by TNRS (no response row)
|
98 |
|
|
if str_.strip() == '': str_ = padding+str_
|
99 |
|
|
return str_
|
100 |
5149
|
aaronmk
|
|
101 |
|
|
def decode(str_): return strings.replace_all_re(spliced_decode_map, str_)
|
102 |
|
|
|
103 |
|
|
decode_for_tsv_map = make_spliced_decode_map([(from_, strings.replace_all(
|
104 |
|
|
csvs.tsv_encode_map, to)) for from_, to in decode_map])
|
105 |
|
|
|
106 |
|
|
def decode_for_tsv(str_):
|
107 |
|
|
return strings.replace_all_re(decode_for_tsv_map, str_)
|
108 |
|
|
|
109 |
|
|
class TnrsOutputStream(streams.FilterStream):
|
110 |
|
|
'''Decodes a TNRS response whose names were encoded with encode()'''
|
111 |
|
|
def __init__(self, stream):
|
112 |
|
|
streams.FilterStream.__init__(self, decode_for_tsv, stream)
|
113 |
|
|
|
114 |
5106
|
aaronmk
|
def parse_response(name, pattern, str_, response, response_info):
|
115 |
|
|
match = re.match(pattern, str_)
|
116 |
|
|
if not match:
|
117 |
|
|
raise InvalidResponse('Invalid '+name+' response:\n'+response_info+'\n'
|
118 |
|
|
+response)
|
119 |
4990
|
aaronmk
|
return match.groups()
|
120 |
|
|
|
121 |
9525
|
aaronmk
|
def single_tnrs_request(names, debug=False, cumulative_profiler=None):
|
122 |
5127
|
aaronmk
|
'''
|
123 |
|
|
Note that names containing only whitespace characters (after gwt_encode())
|
124 |
|
|
are ignored by TNRS and do not receive a response row. Thus, you should
|
125 |
|
|
always match up the Name_submitted returned by TNRS with the actual
|
126 |
|
|
submitted name to determine the corresponding TNRS response row.
|
127 |
|
|
'''
|
128 |
5121
|
aaronmk
|
name_ct = len(names)
|
129 |
|
|
assert name_ct <= max_names
|
130 |
4990
|
aaronmk
|
|
131 |
|
|
# Logging
|
132 |
|
|
def debug_log(label, str_=''):
|
133 |
|
|
if debug: sys.stderr.write('\n'+label+':\n'+str_+'\n')
|
134 |
|
|
|
135 |
|
|
## HTTP
|
136 |
5119
|
aaronmk
|
headers = initial_headers.copy() # don't modify global constant!
|
137 |
4990
|
aaronmk
|
|
138 |
5005
|
aaronmk
|
def do_request(request):
|
139 |
4990
|
aaronmk
|
debug_log('request', str(request))
|
140 |
|
|
response = urllib2.urlopen(urllib2.Request(url, request, headers))
|
141 |
|
|
response_str = streams.read_all(response)
|
142 |
|
|
response_info = str(response.info())
|
143 |
|
|
debug_log('response info', response_info)
|
144 |
|
|
debug_log('response str', response_str)
|
145 |
|
|
return response_str, response_info
|
146 |
|
|
|
147 |
|
|
def do_repeated_request(request):
|
148 |
|
|
pause = initial_pause
|
149 |
|
|
total_pause = 0
|
150 |
|
|
while True:
|
151 |
|
|
total_pause += pause
|
152 |
|
|
if total_pause > max_pause: raise # error is not temporary
|
153 |
|
|
debug_log('total_pause', str(total_pause)+'s')
|
154 |
|
|
time.sleep(pause) # wait for job to complete
|
155 |
|
|
|
156 |
|
|
try: return do_request(request)
|
157 |
|
|
except urllib2.HTTPError: pass # try again
|
158 |
|
|
pause *= pause_growth_factor
|
159 |
|
|
|
160 |
5120
|
aaronmk
|
profiler = profiling.ItersProfiler(start_now=True, iter_text='name')
|
161 |
|
|
try:
|
162 |
|
|
debug_log('Submit')
|
163 |
5121
|
aaronmk
|
request = submission_request_template.replace('[names]',
|
164 |
5150
|
aaronmk
|
gwt_encode('\n'.join(map(encode, names))))
|
165 |
5120
|
aaronmk
|
response, response_info = do_request(request)
|
166 |
5151
|
aaronmk
|
key, = parse_response('submission', submission_response_pattern,
|
167 |
|
|
response, response, response_info)
|
168 |
5120
|
aaronmk
|
debug_log('key', key)
|
169 |
|
|
key_enc = gwt_encode(key)
|
170 |
|
|
|
171 |
|
|
debug_log('Retrieve')
|
172 |
|
|
request = retrieval_request_template.replace('[key]', key_enc)
|
173 |
|
|
response, response_info = do_repeated_request(request)
|
174 |
5151
|
aaronmk
|
parse_response('retrieval', retrieval_response_pattern, response,
|
175 |
|
|
response, response_info)
|
176 |
|
|
session_id, = parse_response('retrieval info',
|
177 |
|
|
retrieval_response_info_pattern, response_info, response,
|
178 |
5120
|
aaronmk
|
response_info)
|
179 |
|
|
debug_log('session_id', session_id)
|
180 |
|
|
headers['Cookie'] = 'JSESSIONID='+session_id
|
181 |
|
|
|
182 |
|
|
# The output of the retrieve step is unusable because the array has
|
183 |
5151
|
aaronmk
|
# different lengths depending on the taxonomic ranks present in the
|
184 |
|
|
# provided taxon name. The extra download step is therefore necessary.
|
185 |
5120
|
aaronmk
|
|
186 |
|
|
debug_log('Prepare download')
|
187 |
|
|
request = download_request_template.replace('[key]', key_enc)
|
188 |
|
|
response, response_info = do_request(request)
|
189 |
5151
|
aaronmk
|
csv_url, = parse_response('download', download_response_pattern,
|
190 |
|
|
response, response, response_info)
|
191 |
5120
|
aaronmk
|
csv_url += download_url_suffix
|
192 |
|
|
debug_log('csv_url', csv_url)
|
193 |
|
|
|
194 |
|
|
debug_log('Download')
|
195 |
|
|
response = urllib2.urlopen(urllib2.Request(csv_url))
|
196 |
|
|
debug_log('response info', str(response.info()))
|
197 |
5150
|
aaronmk
|
return TnrsOutputStream(response)
|
198 |
5120
|
aaronmk
|
finally:
|
199 |
5121
|
aaronmk
|
profiler.stop(name_ct)
|
200 |
5120
|
aaronmk
|
sys.stderr.write(profiler.msg()+'\n')
|
201 |
9525
|
aaronmk
|
|
202 |
|
|
if cumulative_profiler != None:
|
203 |
|
|
cumulative_profiler.add_subprofiler(profiler)
|
204 |
|
|
sys.stderr.write('Cumulatively: '+cumulative_profiler.msg()+'\n')
|
205 |
5088
|
aaronmk
|
|
206 |
9520
|
aaronmk
|
def tnrs_request(names, debug=False, **kw_args):
|
207 |
5108
|
aaronmk
|
for try_num in xrange(2):
|
208 |
9519
|
aaronmk
|
try: return single_tnrs_request(names, debug, **kw_args)
|
209 |
5160
|
aaronmk
|
except (urllib2.HTTPError, InvalidResponse), e:
|
210 |
5107
|
aaronmk
|
exc.print_ex(e, detail=False)
|
211 |
5108
|
aaronmk
|
debug = True
|
212 |
|
|
# try again with debug turned on
|
213 |
5088
|
aaronmk
|
raise # error is not temporary
|