Project

General

Profile

1 5079 aaronmk
#!/usr/bin/env python
2 5640 aaronmk
# Scrubs the taxonlabels in VegBIEN using TNRS.
3 5079 aaronmk
4 9530 aaronmk
# to estimate total runtime:
5
# bin/psql_vegbien <<<'SELECT COUNT(*) FROM tnrs_input_name'
6
# # names from above * 1.5 multiplier for scrubbing accepted names
7
# (the test_taxonomic_names sample from Brad produces 8 accepted names for
8
# 15 input names)
9
# * ((# ms/name from log file * 1 sec/1000 ms) + (# sec to run
10
#   `SELECT * FROM "tnrs_input_name"` in log file / tnrs.max_names names/batch))
11
# * 1 hr / 3600 sec * 1 day / 24 hr = # days
12
13 5079 aaronmk
import os.path
14
import sys
15
16
sys.path.append(os.path.dirname(__file__)+"/../lib")
17
18
import csvs
19
import opts
20 5098 aaronmk
import profiling
21 5079 aaronmk
import sql
22
import sql_gen
23
import sql_io
24
import strings
25
import tnrs
26
27 5669 aaronmk
tnrs_input = sql_gen.Table('tnrs_input_name')
28 5079 aaronmk
tnrs_data = sql_gen.Table('tnrs')
29
30
def main():
31
    # Input
32
    env_names = []
33
    db_config = opts.get_env_vars(sql.db_config_names, None, env_names)
34
    verbosity = float(opts.get_env_var('verbosity', 3, env_names))
35
    if not 'engine' in db_config: raise SystemExit('Usage: '
36
        +opts.env_usage(env_names)+' '+sys.argv[0]+' 2>>log')
37
38
    def log(msg, level=1):
39
        '''Higher level -> more verbose'''
40
        if level <= verbosity:
41
            sys.stderr.write(strings.to_raw_str(msg.rstrip('\n')+'\n'))
42
43
    # Connect to DB
44
    db = sql.connect(db_config, log_debug=log)
45
46 9522 aaronmk
    cumulative_tnrs_profiler = profiling.ItersProfiler(iter_text='name')
47 5123 aaronmk
48 5640 aaronmk
    # Iterate over unscrubbed verbatim taxonlabels
49 9515 aaronmk
    while True:
50 5123 aaronmk
        # Fetch next set
51 5837 aaronmk
        cur = sql.select(db, tnrs_input, limit=tnrs.max_names, cacheable=False)
52 5123 aaronmk
        this_ct = cur.rowcount
53 5640 aaronmk
        log('Processing '+str(this_ct)+' taxonlabels')
54 9518 aaronmk
        if this_ct == 0: break
55 5123 aaronmk
        # otherwise, rows found
56
        names = list(sql.values(cur))
57
58 9515 aaronmk
        def process():
59
            # Run TNRS
60
            log('Making TNRS request')
61 9526 aaronmk
            stream = tnrs.tnrs_request(names,
62
                cumulative_profiler=cumulative_tnrs_profiler)
63 9515 aaronmk
64
            log('Storing TNRS response data')
65 9517 aaronmk
            sql_io.append_csv(db, tnrs_data, *csvs.reader_and_header(stream))
66 9516 aaronmk
        # start transaction *before* submitting data, so Time_submitted is
67
        # correctly set to the submission time rather than the insertion time.
68
        # these may differ by several minutes if TNRS is slow.
69
        sql.with_savepoint(db, process)
70 5079 aaronmk
71
main()