Project

General

Profile

1
#!/usr/bin/env python
2
# Scrubs the taxonpaths in VegBIEN using TNRS.
3
# Runs continuously until no new rows are added after max_pause.
4

    
5
import os.path
6
import StringIO
7
import sys
8
import time
9

    
10
sys.path.append(os.path.dirname(__file__)+"/../lib")
11

    
12
import csvs
13
import opts
14
import profiling
15
import sql
16
import sql_gen
17
import sql_io
18
import streams
19
import strings
20
import tnrs
21

    
22
# Config
23
pause = 2*60*60 # sec; = 2 hr
24
max_pause = 9*60*60 # sec; = 9 hr; must be >= max partition import time (1.5 hr)
25
assert pause <= max_pause
26

    
27
tnrs_data = sql_gen.Table('tnrs')
28

    
29
def main():
30
    # Input
31
    env_names = []
32
    db_config = opts.get_env_vars(sql.db_config_names, None, env_names)
33
    verbosity = float(opts.get_env_var('verbosity', 3, env_names))
34
    if not 'engine' in db_config: raise SystemExit('Usage: '
35
        +opts.env_usage(env_names)+' '+sys.argv[0]+' 2>>log')
36
    
37
    def log(msg, level=1):
38
        '''Higher level -> more verbose'''
39
        if level <= verbosity:
40
            sys.stderr.write(strings.to_raw_str(msg.rstrip('\n')+'\n'))
41
    
42
    # Connect to DB
43
    db = sql.connect(db_config, log_debug=log)
44
    
45
    tnrs_profiler = profiling.ItersProfiler(iter_text='name')
46
    
47
    # Iterate over unscrubbed verbatim taxonpaths
48
    total_pause = 0
49
    tables = ['taxonpath', sql_gen.Join('tnrs',
50
        {'Name_submitted': 'identifyingtaxonomicname'}, sql_gen.filter_out)]
51
    # Has a concatenated name and not already linked to an accepted name
52
    conds = [('identifyingtaxonomicname', sql_gen.CompareCond(None, '!=')),
53
        ('canon_taxonpath_id', None)]
54
    while True:
55
        # Fetch next set
56
        cur = sql.select(db, tables, ['identifyingtaxonomicname'], conds,
57
            limit=tnrs.max_names, cacheable=False)
58
        this_ct = cur.rowcount
59
        if this_ct == 0:
60
            log('Waited '+str(total_pause)+' sec total')
61
            total_pause += pause
62
            if total_pause > max_pause: break
63
            log('Waiting '+str(pause)+' sec...')
64
            time.sleep(pause) # wait for more rows
65
            continue # try again
66
        # otherwise, rows found
67
        total_pause = 0
68
        names = list(sql.values(cur))
69
        
70
        # Run TNRS
71
        log('Processing '+str(this_ct)+' taxonpaths')
72
        log('Making TNRS request')
73
        tnrs_profiler.start()
74
        try:
75
            try: stream = tnrs.repeated_tnrs_request(names)
76
            finally:
77
                tnrs_profiler.stop(iter_ct=this_ct)
78
                log('Cumulatively: '+tnrs_profiler.msg())
79
        except tnrs.InvalidResponse: pass # skip set in case it caused error
80
        else:
81
            log('Storing TNRS response data')
82
            stream_info = csvs.stream_info(stream, parse_header=True)
83
            stream = streams.ProgressInputStream(stream, sys.stderr, n=1000)
84
            sql_io.append_csv(db, tnrs_data, stream_info, stream)
85

    
86
main()
(56-56/61)