File size: 12,430 Bytes
7f50cd1 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 | """JSON/standoff adapter for unmodified BioSem 1.2.0.
The event learner and extractor are exclusively the vendored upstream Java code.
"""
import hashlib
import json
import os
from pathlib import Path
import re
import shutil
import subprocess
import sys
import tempfile
import time
HERE = Path(__file__).resolve().parent
KINDS = dict(zip(('kind_' + c for c in 'abcdefghij'),
('Gene_expression', 'Transcription', 'Protein_catabolism',
'Phosphorylation', 'Localization', 'Binding', 'Process',
'Regulation', 'Positive_regulation', 'Negative_regulation')))
NODES = dict(zip(('node_' + c for c in 'abcdef'),
('Protein', 'Chemical', 'Organism', 'Two-component-system',
'Regulon-operon', 'Entity')))
ROLES = {'argxx': 'Theme', 'cause': 'Cause'}
REVERSE = {v: k for k, v in {**KINDS, **ROLES}.items()}
def utf16_map(text):
offsets = [0]
for c in text:
offsets.append(offsets[-1] + (2 if ord(c) > 65535 else 1))
return offsets
def span_line(line, text):
ident, fields, surface = line.split('\t')
kind, start, end = fields.split()
offsets = utf16_map(text)
return f'{ident}\t{KINDS.get(kind, NODES.get(kind, kind))} {offsets[int(start)]} {offsets[int(end)]}\t{surface}'
def training_annotations(record):
"""Project annotations to the existing GENIA core-event input schema.
BioSem has no Process class or additional-argument classifier. Its loader
reads a Theme and at most one Cause/second Theme. No new rules are added.
"""
given = {line.split('\t')[0] for line in record['given']
if line.startswith('T') and line.split('\t')[1].split()[0] == 'node_a'}
triggers = {line.split('\t')[0]: line for line in record['target']
if line.startswith('T') and line.split('\t')[1].split()[0] in KINDS
and line.split('\t')[1].split()[0] != 'kind_g'}
events = {}
for line in record['target']:
if not line.startswith('E'):
continue
ident, body = line.split('\t')
head, *args = body.split()
kind, trigger = head.split(':')
if trigger not in triggers:
continue
themes, causes = [], []
for arg in args:
role, ref = arg.split(':')
role = re.sub(r'\d+$', '', role)
if role == 'argxx':
themes.append(ref)
elif role == 'cause':
causes.append(ref)
if not themes:
continue
selected = [('Theme', themes[0])]
if kind == 'kind_f' and len(themes) > 1:
selected.append(('Theme2', themes[1]))
elif causes:
selected.append(('Cause', causes[0]))
events[ident] = (kind, trigger, selected)
while True:
bad = [eid for eid, (_, _, args) in events.items()
if any(ref not in given and ref not in events for _, ref in args)]
if not bad:
break
for eid in bad:
del events[eid]
used = {trigger for _, trigger, _ in events.values()}
lines = [span_line(line, record['text']) for tid, line in triggers.items() if tid in used]
for eid, (kind, trigger, args) in events.items():
lines.append(f'{eid}\t{KINDS[kind]}:{trigger} ' + ' '.join(f'{r}:{a}' for r, a in args))
for line in record['target']:
if line.startswith('*'):
refs = line.split()[2:]
if all(ref in given for ref in refs):
lines.append(line.replace('\tequal ', '\tEquiv ', 1))
elif line.startswith('M'):
ident, body = line.split('\t')
flag, ref = body.split()
if ref in events:
lines.append(f'{ident}\t' + {'flag_a': 'Negation', 'flag_b': 'Speculation'}[flag] + ' ' + ref)
return lines
def write_standoff(records, directory, train=False):
directory.mkdir(parents=True, exist_ok=True)
for i, record in enumerate(records):
# File names are adapter indices, never interpreted as biomedical IDs.
stem = directory / str(i)
stem.with_suffix('.txt').write_text(record['text'], encoding='utf-8')
lines = [span_line(line, record['text']) for line in record['given']
if line.startswith('T') and line.split('\t')[1].split()[0] == 'node_a']
stem.with_suffix('.a1').write_text('\n'.join(lines) + '\n' if lines else '', encoding='utf-8')
if train:
lines = training_annotations(record)
stem.with_suffix('.a2').write_text('\n'.join(lines) + '\n' if lines else '', encoding='utf-8')
def java_stage(stage, input_root, db_root, dataset, destination=None):
command = [str(HERE / 'vendor/jre/bin/java'), '-Xms64m', '-Xmx1024m', '-Xss32m',
'-XX:ActiveProcessorCount=2', '-XX:+UseSerialGC', '-Dfile.encoding=UTF-8',
'-Dlogback.configurationFile=' + str(HERE / 'vendor/logback.xml'),
'-cp', str(HERE / 'vendor/biosem-1.2.0.jar'), 'application.BioSemApplication',
'-m', stage, '-i', str(input_root), '-o', str(db_root), '-s', dataset]
if destination:
command += ['-d', destination]
subprocess.run(command, cwd=HERE, check=True)
def train(records, model_dir, work):
input_root, db_root = work / 'input', work / 'db'
db_root.mkdir(parents=True)
write_standoff(records, input_root / 'train', train=True)
java_stage('data-preparation', input_root, db_root, 'train')
java_stage('trigger-learn', input_root, db_root, 'train', 'train')
java_stage('pattern-learn', input_root, db_root, 'train', 'train')
model_dir.mkdir(parents=True, exist_ok=True)
for path in db_root.glob('train.*'):
shutil.copy2(path, model_dir / path.name)
digest = hashlib.sha256(json.dumps(records, sort_keys=True).encode()).hexdigest()
(model_dir / 'provenance.json').write_text(json.dumps({'training_records': len(records),
'training_sha256': digest}) + '\n')
def prediction_lines(path, record):
lines = path.read_text(encoding='utf-8').splitlines() if path.exists() else []
reverse_offsets = {offset: i for i, offset in enumerate(utf16_map(record['text']))}
next_id = 1 + max([int(line.split('\t')[0][1:]) for line in record['given']
if line.startswith('T')] + [0])
trigger_ids = [line.split('\t')[0] for line in lines if line.startswith('T')]
rename = {ident: f'T{next_id + i}' for i, ident in enumerate(trigger_ids)}
result = []
for line in lines:
ident, body = line.split('\t', 1)
if ident.startswith('T'):
fields, surface = body.split('\t')
kind, start, end = fields.split()
start, end = reverse_offsets[int(start)], reverse_offsets[int(end)]
result.append(f'{rename[ident]}\t{REVERSE[kind]} {start} {end}\t{record["text"][start:end]}')
elif ident.startswith('E'):
parts = []
for part in body.split():
role, ref = part.split(':')
base = re.sub(r'\d+$', '', role)
parts.append(REVERSE[base] + role[len(base):] + ':' + rename.get(ref, ref))
result.append(ident + '\t' + ' '.join(parts))
else:
raise ValueError('Unexpected BioSem annotation: ' + line)
return result
def check_prediction(lines, record):
"""Reject unrepresentable upstream records, without inventing annotations."""
given = {line.split('\t')[0] for line in record['given'] if line.startswith('T')}
spans, events, ids = {}, {}, set(given)
for line in lines:
if '\n' in line or '\r' in line:
raise ValueError('Multiline annotation')
ident, body = line.split('\t', 1)
if ident in ids:
raise ValueError('Duplicate annotation ID')
ids.add(ident)
if ident.startswith('T'):
fields, surface = body.split('\t')
kind, start, end = fields.split()
start, end = int(start), int(end)
if not 0 <= start < end <= len(record['text']):
raise ValueError('Invalid trigger offsets')
if record['text'][start:end] != surface:
raise ValueError('Invalid trigger surface')
spans[ident] = kind
else:
head, *args = body.split()
kind, trigger = head.split(':')
events[ident] = (kind, trigger, [arg.split(':')[1] for arg in args])
for kind, trigger, args in events.values():
if spans.get(trigger) != kind or any(ref not in given and ref not in events for ref in args):
raise ValueError('Unresolved or mistyped reference')
visiting, done = set(), set()
def visit(ident):
if ident in visiting:
raise ValueError('Recursive event cycle')
if ident in done:
return
visiting.add(ident)
for ref in events[ident][2]:
if ref in events:
visit(ref)
visiting.remove(ident)
done.add(ident)
for ident in events:
visit(ident)
def extract(input_root, db_root, work, timeout):
command = [str(HERE / 'vendor/jre/bin/java'), '-Xms64m', '-Xmx1024m', '-Xss32m',
'-XX:ActiveProcessorCount=2', '-XX:+UseSerialGC', '-Dfile.encoding=UTF-8',
'-Dlogback.configurationFile=' + str(HERE / 'vendor/logback.xml'),
'-cp', os.pathsep.join((str(HERE / 'classes'), str(HERE / 'vendor/biosem-1.2.0.jar'))),
'BioSemBatch', str(input_root / 'test'), str(db_root / 'train'), str(work / 'results')]
try:
# subprocess.run kills AND waits for the JVM on a timeout. No child survives return.
completed = subprocess.run(command, cwd=HERE, timeout=max(0.001, timeout))
if completed.returncode:
print('BioSem worker exited with code', completed.returncode,
'; preserving completed records', file=sys.stderr)
except subprocess.TimeoutExpired:
print('BioSem invocation deadline; preserving completed records', file=sys.stderr)
def main():
started = time.monotonic()
if hasattr(os, 'sched_getaffinity'):
os.sched_setaffinity(0, sorted(os.sched_getaffinity(0))[:2])
if sys.argv[1] == '--train':
data_root = Path(sys.argv[2])
inputs = [data_root / 'input.json'] if (data_root / 'input.json').exists() else sorted(data_root.glob('*/input.json'))
records, seen = [], set()
for path in inputs:
for record in json.loads(path.read_text())['training']:
key = json.dumps(record, sort_keys=True)
if key not in seen:
seen.add(key)
records.append(record)
if not records:
raise ValueError('No visible training records')
with tempfile.TemporaryDirectory(prefix='biosem_train_', dir=HERE) as temp:
train(records, HERE / 'model', Path(temp))
return
data = json.loads((Path(sys.argv[1]) / 'input.json').read_text())
output = Path(sys.argv[2]).resolve()
output.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(prefix='biosem_', dir=output) as temp:
work = Path(temp)
input_root, db_root = work / 'input', work / 'db'
db_root.mkdir()
model = HERE / 'model'
if not (model / 'train.script').exists():
raise RuntimeError('Run train.sh before inference')
for path in model.glob('train.*'):
shutil.copy2(path, db_root / path.name)
write_standoff(data['records'], input_root / 'test')
budget = float(os.environ.get('TASK_BUDGET_SEC', '120'))
extract(input_root, db_root, work, budget - 5 - (time.monotonic() - started))
result = {}
for i, record in enumerate(data['records']):
try:
lines = prediction_lines(work / 'results' / f'{i}.ready', record)
check_prediction(lines, record)
except (ValueError, KeyError, IndexError, RecursionError) as error:
print('BioSem output for record', i, 'cannot be represented:', error, file=sys.stderr)
lines = []
result[record['id']] = lines
(output / 'prediction.json').write_text(json.dumps(result, ensure_ascii=False) + '\n')
if __name__ == '__main__':
main()
|