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