Project

General

Profile

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