Coverage for biobb_vs/gnina/common.py: 72%
87 statements
« prev ^ index » next coverage.py v7.18.0, created at 2026-12-03 15:52 +0000
« prev ^ index » next coverage.py v7.18.0, created at 2026-12-03 15:52 +0000
1"""Common functions for package biobb_vs.gnina"""
3import gzip
4import json
5import re
6from pathlib import Path, PurePath
8from biobb_common.tools import file_utils as fu
10# Matches an SDF data field header, e.g. "> <minimizedAffinity>"
11SDF_TAG_PATTERN = re.compile(r">\s*<([^>]+)>")
12# Record terminator of the SDF format
13SDF_TERMINATOR = "$$$$"
16# CHECK PARAMETERS
19def check_gzip_extension(path, argument, out_log, classname):
20 """Checks that a gzip compressed file also declares the format it wraps
22 gnina and Open Babel take the molecular format from the file extension, and
23 a bare .gz gives them nothing to work with. Only .sdf.gz is accepted.
24 """
25 suffixes = PurePath(path).suffixes
26 if suffixes[-1:] == ['.gz'] and suffixes[-2:-1] != ['.sdf']:
27 fu.log(classname + ': %s must use a .sdf.gz extension to be gzip compressed' % argument, out_log)
28 raise SystemExit(classname + ': %s must use a .sdf.gz extension to be gzip compressed' % argument)
29 return path
32# READ / WRITE SDF
35def open_sdf(path, mode='rt'):
36 """Opens a plain or gzip compressed SDF file, transparently"""
37 if PurePath(path).suffix == '.gz':
38 return gzip.open(path, mode, newline='')
39 return open(path, mode, newline='')
42def read_sdf_records(path):
43 """Splits a multi record SDF file into its records
45 Returns a list of dictionaries, one per record, each holding:
46 * **text**: the raw record text, terminator included, so that a record
47 can be written back out verbatim.
48 * **name**: the molecule name, that is the first line of the record.
49 * **data**: the SD data fields of the record, as a tag to value mapping.
50 * **ligand_index**: 1 based index of the ligand the record belongs to.
51 * **pose**: 1 based rank of the record within its ligand.
53 gnina writes the poses of every input ligand consecutively and does not tag
54 them with a ligand identifier, so records are grouped into ligands whenever
55 the molecule name changes. Consecutive ligands sharing the same name are
56 therefore reported as a single ligand.
57 """
58 with open_sdf(path, 'rt') as sdf_file:
59 content = sdf_file.read()
61 records = []
62 record_lines = []
63 for line in content.splitlines(keepends=True):
64 record_lines.append(line)
65 if line.strip() == SDF_TERMINATOR:
66 records.append(parse_sdf_record(record_lines))
67 record_lines = []
69 # keep a trailing record that is missing its terminator instead of losing it
70 if any(line.strip() for line in record_lines):
71 records.append(parse_sdf_record(record_lines))
73 # group the records into ligands, gnina writes each ligand's poses together
74 ligand_index = 0
75 previous_name = None
76 pose = 0
77 for record in records:
78 if record['name'] != previous_name:
79 ligand_index += 1
80 previous_name = record['name']
81 pose = 0
82 pose += 1
83 record['ligand_index'] = ligand_index
84 record['pose'] = pose
86 return records
89def parse_sdf_record(record_lines):
90 """Parses a single SDF record into its name, data fields and raw text"""
91 name = record_lines[0].strip() if record_lines else ''
92 data = {}
93 tag = None
94 values = []
96 for line in record_lines:
97 if line.strip() == SDF_TERMINATOR:
98 break
99 match = SDF_TAG_PATTERN.match(line)
100 if match:
101 if tag is not None:
102 data[tag] = '\n'.join(values)
103 tag = match.group(1)
104 values = []
105 continue
106 if tag is not None:
107 if not line.strip():
108 data[tag] = '\n'.join(values)
109 tag = None
110 values = []
111 else:
112 values.append(line.strip())
114 if tag is not None:
115 data[tag] = '\n'.join(values)
117 return {'text': ''.join(record_lines), 'name': name, 'data': data}
120def to_number(value):
121 """Converts an SD data value to a float, leaving it untouched if it is not numeric"""
122 try:
123 return float(value)
124 except (TypeError, ValueError):
125 return value
128# PROCESS OUTPUTS
131def process_output_gnina(output_sdf_path, output_summary_path, out_log, classname):
132 """Generates the output_summary_path JSON file from the poses written by gnina
134 Every pose becomes one entry holding the ligand it belongs to, its rank
135 within that ligand and every score gnina attached to it as an SD data field
136 (minimizedAffinity, CNNscore, CNNaffinity, CNN_VS and, for model ensembles,
137 CNNvariance). Which scores are present depends on the cnn_scoring property.
138 """
139 if not Path(output_sdf_path).exists():
140 fu.log(classname + ': %s not found, skipping the summary' % output_sdf_path, out_log)
141 raise SystemExit(classname + ': Error executing gnina, %s was not created' % output_sdf_path)
143 records = read_sdf_records(output_sdf_path)
145 data = {}
146 for index, record in enumerate(records, start=1):
147 entry = {
148 'ligand_name': record['name'],
149 'ligand_index': record['ligand_index'],
150 'pose': record['pose']
151 }
152 for tag, value in record['data'].items():
153 entry[tag] = to_number(value)
154 data['pose' + str(index)] = entry
156 ligands = len({record['ligand_index'] for record in records})
157 fu.log('%d poses found for %d ligand(s)' % (len(records), ligands), out_log)
159 fu.log('Saving summary to %s file' % output_summary_path, out_log)
160 with open(output_summary_path, 'w') as outfile:
161 json.dump(data, outfile, indent=4)
163 return data