| 1 |
|
| 2 |
|
| 3 |
""" |
| 4 |
Interface for uncompressed mzML files. |
| 5 |
|
| 6 |
@author: Manuel Koesters |
| 7 |
""" |
| 8 |
|
| 9 |
|
| 10 |
n |
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
import bisect |
| 32 |
import codecs |
| 33 |
import re |
| 34 |
import os |
| 35 |
from xml.etree.ElementTree import XML, iterparse |
| 36 |
|
| 37 |
from .. import spec |
| 38 |
from .. import regex_patterns |
| 39 |
|
| 40 |
|
| 41 |
class StandardMzml(object): |
| 42 |
""" """ |
| 43 |
|
| 44 |
def __init__( |
| 45 |
self, path, encoding, build_index_from_scratch=False, index_regex=None |
| 46 |
): |
| 47 |
""" |
| 48 |
Initalize Wrapper object for standard mzML files. |
| 49 |
|
| 50 |
Arguments: |
| 51 |
path (str) : path to the file |
| 52 |
encoding (str) : encoding of the file |
| 53 |
""" |
| 54 |
self.index_regex = index_regex |
| 55 |
self.path = path |
| 56 |
self.file_handler = self.get_file_handler(encoding) |
| 57 |
self.offset_dict = dict() |
| 58 |
self.spec_open = regex_patterns.SPECTRUM_OPEN_PATTERN |
| 59 |
self.spec_close = regex_patterns.SPECTRUM_CLOSE_PATTERN |
| 60 |
|
| 61 |
self.seek_list = self._read_extremes() |
| 62 |
self._build_index(from_scratch=build_index_from_scratch) |
| 63 |
|
| 64 |
def get_binary_file_handler(self): |
| 65 |
return open(self.path, "rb") |
| 66 |
|
| 67 |
def get_file_handler(self, encoding): |
| 68 |
return codecs.open(self.path, mode="r", encoding=encoding) |
| 69 |
|
| 70 |
def __getitem__(self, identifier): |
| 71 |
""" |
| 72 |
Access the item with id 'identifier'. |
| 73 |
|
| 74 |
Either use linear, binary or interpolated search. |
| 75 |
|
| 76 |
Arguments: |
| 77 |
identifier (str): native id of the item to access |
| 78 |
|
| 79 |
Returns: |
| 80 |
data (str): text associated with the given identifier |
| 81 |
""" |
| 82 |
|
| 83 |
|
| 84 |
|
| 85 |
|
| 86 |
|
| 87 |
self.file_handler.seek(0) |
| 88 |
|
| 89 |
spectrum = None |
| 90 |
if str(identifier).upper() == "TIC": |
| 91 |
|
| 92 |
found = False |
| 93 |
mzmliter = iter(iterparse(self.file_handler, events=["end"])) |
| 94 |
while found is False: |
| 95 |
event, element = next(mzmliter, ("STOP", "STOP")) |
| 96 |
if event == "end": |
| 97 |
if element.tag.endswith("}chromatogram"): |
| 98 |
if element.get("id") == "TIC": |
| 99 |
found = True |
| 100 |
spectrum = spec.Chromatogram( |
| 101 |
element, measured_precision=5e-6 |
| 102 |
) |
| 103 |
elif event == "STOP": |
| 104 |
raise StopIteration |
| 105 |
|
| 106 |
elif identifier in self.offset_dict: |
| 107 |
|
| 108 |
start = self.offset_dict[identifier] |
| 109 |
|
| 110 |
seeker = self.get_binary_file_handler() |
| 111 |
seeker.seek(start[0]) |
| 112 |
start, end = self._read_to_spec_end(seeker) |
| 113 |
|
| 114 |
self.file_handler.seek(start, 0) |
| 115 |
data = self.file_handler.read(end) |
| 116 |
if data.startswith("<spectrum"): |
| 117 |
spectrum = spec.Spectrum(XML(data), measured_precision=5e-6) |
| 118 |
elif data.startswith("<chromatogram"): |
| 119 |
spectrum = spec.Chromatogram(XML(data)) |
| 120 |
elif type(identifier) == str: |
| 121 |
return self._search_string_identifier(identifier) |
| 122 |
else: |
| 123 |
spectrum = self._binary_search(identifier) |
| 124 |
|
| 125 |
return spectrum |
| 126 |
|
| 127 |
def _binary_search(self, target_index): |
| 128 |
""" |
| 129 |
Retrieve spectrum for a given spectrum ID using binary jumps |
| 130 |
|
| 131 |
Args: |
| 132 |
target_index (int): native id of the spectrum to access |
| 133 |
|
| 134 |
Returns: |
| 135 |
Spectrum (pymzml.spec.Spectrum): pymzML spectrum |
| 136 |
|
| 137 |
|
| 138 |
""" |
| 139 |
chunk_size = 12800 |
| 140 |
offset_scale = 1 |
| 141 |
jump_history = {"forwards": 0, "backwards": 0} |
| 142 |
|
| 143 |
|
| 144 |
with open(self.path, "rb") as seeker: |
| 145 |
if target_index not in self.offset_dict.keys(): |
| 146 |
for jump in range(40): |
| 147 |
scan = None |
| 148 |
insert_position = bisect.bisect_left( |
| 149 |
self.seek_list, (target_index, 0) |
| 150 |
) |
| 151 |
if ( |
| 152 |
target_index < self.seek_list[0][0] |
| 153 |
or target_index > self.seek_list[-1][0] |
| 154 |
): |
| 155 |
raise Exception( |
| 156 |
"Spectrum ID should be between" |
| 157 |
" {0} and {1}".format( |
| 158 |
self.seek_list[0][0], self.seek_list[-1][0] |
| 159 |
) |
| 160 |
) |
| 161 |
|
| 162 |
element_before = self.seek_list[insert_position - 1] |
| 163 |
spec_offset_m1 = target_index - element_before[0] |
| 164 |
|
| 165 |
element_after = self.seek_list[insert_position] |
| 166 |
spec_offset_p1 = element_after[0] - target_index |
| 167 |
|
| 168 |
byte_diff_m1_p1 = element_after[1] - element_before[1] |
| 169 |
scan_diff_m1_p1 = element_after[0] - element_before[0] |
| 170 |
|
| 171 |
average_spec_between_m1_p1 = int( |
| 172 |
round(byte_diff_m1_p1 / scan_diff_m1_p1) |
| 173 |
) |
| 174 |
|
| 175 |
if spec_offset_m1 < spec_offset_p1: |
| 176 |
|
| 177 |
jump_direction = "forwards" |
| 178 |
jump_history["backwards"] = 0 |
| 179 |
jump_history["forwards"] += 1 |
| 180 |
byte_offset = element_before[1] + jump_history["forwards"] * ( |
| 181 |
offset_scale * average_spec_between_m1_p1 * spec_offset_m1 |
| 182 |
) |
| 183 |
if (target_index - element_before[0]) < 10: |
| 184 |
|
| 185 |
|
| 186 |
byte_offset = element_before[1] |
| 187 |
else: |
| 188 |
jump_direction = "backwards" |
| 189 |
jump_history["forwards"] = 0 |
| 190 |
jump_history["backwards"] += 1 |
| 191 |
byte_offset = element_after[1] - jump_history["backwards"] * ( |
| 192 |
offset_scale * average_spec_between_m1_p1 * spec_offset_p1 |
| 193 |
) |
| 194 |
byte_offset = int(byte_offset) |
| 195 |
found_scan = False |
| 196 |
chunk = b"" |
| 197 |
break_outer = False |
| 198 |
|
| 199 |
for x in range(100): |
| 200 |
seeker.seek( |
| 201 |
max([os.SEEK_SET + byte_offset + x * chunk_size, 1]) |
| 202 |
) |
| 203 |
chunk += seeker.read(chunk_size) |
| 204 |
matches = re.finditer(regex_patterns.SPECTRUM_OPEN_PATTERN, chunk) |
| 205 |
for _match_number, match in enumerate(matches): |
| 206 |
if match is not None: |
| 207 |
spec_info = match.groups() |
| 208 |
spec_info = dict(zip(spec_info[0::2], spec_info[1::2])) |
| 209 |
scan = int(re.search(b"[0-9]*$", spec_info[b"id"]).group()) |
| 210 |
|
| 211 |
if jump_direction == "forwards": |
| 212 |
if scan > target_index: |
| 213 |
|
| 214 |
offset_scale = 0.1 |
| 215 |
jump_history["forwards"] = 0 |
| 216 |
else: |
| 217 |
offset_scale = 1 |
| 218 |
if jump_direction == "backwards": |
| 219 |
if scan < target_index: |
| 220 |
offset_scale = 0.1 |
| 221 |
jump_history["backwards"] = 0 |
| 222 |
else: |
| 223 |
offset_scale = 1 |
| 224 |
|
| 225 |
if scan in self.offset_dict.keys(): |
| 226 |
continue |
| 227 |
found_scan = True |
| 228 |
new_entry = ( |
| 229 |
scan, |
| 230 |
byte_offset + match.start(), |
| 231 |
) |
| 232 |
new_pos = bisect.bisect_left(self.seek_list, new_entry) |
| 233 |
self.seek_list.insert(new_pos, new_entry) |
| 234 |
self.offset_dict[scan] = (byte_offset + match.start(),) |
| 235 |
if int(scan) == int(target_index): |
| 236 |
|
| 237 |
break_outer = True |
| 238 |
break |
| 239 |
if break_outer: |
| 240 |
break |
| 241 |
if found_scan: |
| 242 |
offset_scale = 1 |
| 243 |
else: |
| 244 |
offset_scale += 1 |
| 245 |
if int(target_index) in self.offset_dict.keys(): |
| 246 |
break |
| 247 |
|
| 248 |
start = self.offset_dict[target_index] |
| 249 |
seeker.seek(start[0]) |
| 250 |
match = None |
| 251 |
data = b"" |
| 252 |
while b"</spectrum>" not in data: |
| 253 |
data += seeker.read(chunk_size) |
| 254 |
end = data.find(b"</spectrum>") |
| 255 |
seeker.seek(start[0]) |
| 256 |
spec_string = seeker.read(end + len("</spectrum>")) |
| 257 |
spec_string = spec_string.decode("utf-8") |
| 258 |
spectrum = spec.Spectrum(XML(spec_string), measured_precision=5e-6) |
| 259 |
return spectrum |
| 260 |
|
| 261 |
def _build_index(self, from_scratch=False): |
| 262 |
""" |
| 263 |
Build an index. |
| 264 |
|
| 265 |
A list of offsets to which a file pointer can seek |
| 266 |
directly to access a particular spectrum or chromatogram without |
| 267 |
parsing the entire file. |
| 268 |
|
| 269 |
Args: |
| 270 |
|
| 271 |
from_scratch(bool): Whether or not to force building the index from |
| 272 |
scratch, by parsing the file, if no existing |
| 273 |
index can be found. |
| 274 |
|
| 275 |
Returns: |
| 276 |
A file-like object used to access the indexed content by |
| 277 |
seeking to a particular offset for the file. |
| 278 |
""" |
| 279 |
|
| 280 |
seeker = self.get_binary_file_handler() |
| 281 |
self.offset_dict["TIC"] = None |
| 282 |
seeker.seek(0, 2) |
| 283 |
index_found = False |
| 284 |
|
| 285 |
spectrum_index_pattern = regex_patterns.SPECTRUM_INDEX_PATTERN |
| 286 |
for _ in range(1, 10): |
| 287 |
|
| 288 |
|
| 289 |
|
| 290 |
sanity_check_set = set() |
| 291 |
try: |
| 292 |
seeker.seek(-1024 * _, 1) |
| 293 |
except: |
| 294 |
break |
| 295 |
|
| 296 |
for line in seeker: |
| 297 |
match = regex_patterns.CHROMATOGRAM_OFFSET_PATTERN.search(line) |
| 298 |
if match: |
| 299 |
self.offset_dict["TIC"] = int(bytes.decode(match.group("offset"))) |
| 300 |
|
| 301 |
match_spec = spectrum_index_pattern.search(line) |
| 302 |
if match_spec is not None: |
| 303 |
spec_byte_offset = int(bytes.decode(match_spec.group("offset"))) |
| 304 |
sanity_check_set.add(spec_byte_offset) |
| 305 |
|
| 306 |
match = regex_patterns.INDEX_LIST_OFFSET_PATTERN.search(line) |
| 307 |
if match: |
| 308 |
index_found = True |
| 309 |
index_list_offset = int( |
| 310 |
match.group("indexListOffset").decode("utf-8") |
| 311 |
) |
| 312 |
|
| 313 |
if index_found is True and self.offset_dict["TIC"] is not None: |
| 314 |
break |
| 315 |
|
| 316 |
if index_found is True: |
| 317 |
|
| 318 |
seeker.seek(index_list_offset, 0) |
| 319 |
spectrum_index_pattern = regex_patterns.SPECTRUM_INDEX_PATTERN |
| 320 |
sim_index_pattern = regex_patterns.SIM_INDEX_PATTERN |
| 321 |
|
| 322 |
for line in seeker: |
| 323 |
match_spec = spectrum_index_pattern.search(line) |
| 324 |
if match_spec and match_spec.group("nativeID") == b"": |
| 325 |
match_spec = None |
| 326 |
match_sim = sim_index_pattern.search(line) |
| 327 |
if self.index_regex is None: |
| 328 |
if match_spec: |
| 329 |
offset = int(bytes.decode(match_spec.group("offset"))) |
| 330 |
native_id = int(bytes.decode(match_spec.group("nativeID"))) |
| 331 |
self.offset_dict[native_id] = offset |
| 332 |
elif match_sim: |
| 333 |
offset = int(bytes.decode(match_sim.group("offset"))) |
| 334 |
native_id = bytes.decode(match_sim.group("nativeID")) |
| 335 |
try: |
| 336 |
native_id = int( |
| 337 |
regex_patterns.SPECTRUM_ID_PATTERN2.search( |
| 338 |
native_id |
| 339 |
).group(2) |
| 340 |
) |
| 341 |
except AttributeError: |
| 342 |
|
| 343 |
|
| 344 |
pass |
| 345 |
self.offset_dict[native_id] = (offset,) |
| 346 |
else: |
| 347 |
match = self.index_regex.search(line) |
| 348 |
if match: |
| 349 |
native_id = match.group("ID") |
| 350 |
try: |
| 351 |
native_id = int(native_id) |
| 352 |
except ValueError: |
| 353 |
pass |
| 354 |
offset = match.group("offset") |
| 355 |
self.offset_dict[native_id] = (offset,) |
| 356 |
|
| 357 |
elif from_scratch is True: |
| 358 |
seeker.seek(0) |
| 359 |
self._build_index_from_scratch(seeker) |
| 360 |
else: |
| 361 |
print("[Warning] Not index found and build_index_from_scratch is False") |
| 362 |
|
| 363 |
seeker.close() |
| 364 |
|
| 365 |
def _build_index_from_scratch(self, seeker): |
| 366 |
"""Build an index of spectra/chromatogram data with offsets by parsing the file.""" |
| 367 |
|
| 368 |
def get_data_indices(fh, chunksize=8192, lookback_size=100): |
| 369 |
"""Get a dictionary with binary file indices of spectra and |
| 370 |
chromatograms in an mzML file. |
| 371 |
|
| 372 |
Will parse quickly through the file and find all occurences of |
| 373 |
<chromatogram ... id="..." and <spectrum ... id="..." using a |
| 374 |
regex. |
| 375 |
We dont use an XML parser here because we need to know the |
| 376 |
exact location of the filepointer which is usually not possible |
| 377 |
with common xml parsers. |
| 378 |
""" |
| 379 |
chrom_positions = {} |
| 380 |
spec_positions = {} |
| 381 |
chromcnt = 0 |
| 382 |
speccnt = 0 |
| 383 |
|
| 384 |
chromexp = re.compile(b'<\s*chromatogram[^>]*id="([^"]*)"') |
| 385 |
chromcntexp = re.compile(b'<\s*chromatogramList\s*count="([^"]*)"') |
| 386 |
specexp = re.compile(b'<\s*spectrum[^>]*id="([^"]*)"') |
| 387 |
speccntexp = re.compile(b'<\s*spectrumList\s*count="([^"]*)"') |
| 388 |
|
| 389 |
fh.seek(0) |
| 390 |
prev_chunk = "" |
| 391 |
while True: |
| 392 |
|
| 393 |
offset = fh.tell() |
| 394 |
chunk = fh.read(chunksize) |
| 395 |
if not chunk: |
| 396 |
break |
| 397 |
|
| 398 |
|
| 399 |
|
| 400 |
|
| 401 |
if len(prev_chunk) > 0: |
| 402 |
chunk = prev_chunk[-lookback_size:] + chunk |
| 403 |
offset -= lookback_size |
| 404 |
prev_chunk = chunk |
| 405 |
|
| 406 |
|
| 407 |
for m in chromexp.finditer(chunk): |
| 408 |
chrom_positions[m.group(1).decode("utf-8")] = offset + m.start() |
| 409 |
for m in specexp.finditer(chunk): |
| 410 |
spec_positions[m.group(1).decode("utf-8")] = offset + m.start() |
| 411 |
|
| 412 |
|
| 413 |
|
| 414 |
m = chromcntexp.search(chunk) |
| 415 |
if m is not None: |
| 416 |
chromcnt = int(m.group(1)) |
| 417 |
m = speccntexp.search(chunk) |
| 418 |
if m is not None: |
| 419 |
speccnt = int(m.group(1)) |
| 420 |
|
| 421 |
|
| 422 |
if chromcnt == len(chrom_positions) and speccnt == len(spec_positions): |
| 423 |
positions = {} |
| 424 |
positions.update(chrom_positions) |
| 425 |
positions.update(spec_positions) |
| 426 |
else: |
| 427 |
print( |
| 428 |
"[ Warning ] Found {spec_count} spectra " |
| 429 |
"and {chrom_count} chromatograms\n" |
| 430 |
"[ Warning ] However Spectrum index list shows {speccnt} and " |
| 431 |
"Chromatogram index list shows {chromcnt} entries".format( |
| 432 |
spec_count=len(spec_positions), |
| 433 |
chrom_count=len(chrom_positions), |
| 434 |
speccnt=speccnt, |
| 435 |
chromcnt=chromcnt, |
| 436 |
) |
| 437 |
) |
| 438 |
print( |
| 439 |
"[ Warning ] Updating offset dict with found offsets " |
| 440 |
"but some might be still missing\n" |
| 441 |
"[ Warning ] This may happen because your is file truncated" |
| 442 |
) |
| 443 |
positions = {} |
| 444 |
positions.update(chrom_positions) |
| 445 |
positions.update(spec_positions) |
| 446 |
return positions |
| 447 |
|
| 448 |
indices = get_data_indices(seeker) |
| 449 |
if indices is not None: |
| 450 |
tmp_dict = {} |
| 451 |
|
| 452 |
item_list = sorted(list(indices.items()), key=lambda x: x[1]) |
| 453 |
for i in range(len(item_list)): |
| 454 |
key = item_list[i][0] |
| 455 |
tmp_dict[key] = (item_list[i][1],) |
| 456 |
|
| 457 |
self.offset_dict.update(tmp_dict) |
| 458 |
|
| 459 |
|
| 460 |
|
| 461 |
|
| 462 |
|
| 463 |
return |
| 464 |
|
| 465 |
def _interpol_search(self, target_index, chunk_size=8, fallback_cutoff=100): |
| 466 |
""" |
| 467 |
Use linear interpolation search to find spectra faster. |
| 468 |
|
| 469 |
Arguments: |
| 470 |
target_index (str or int) : native id of the item to access |
| 471 |
|
| 472 |
Keyword Arguments: |
| 473 |
chunk_size (int) : size of the chunk to read in one go in kb |
| 474 |
|
| 475 |
""" |
| 476 |
|
| 477 |
seeker = self.get_binary_file_handler() |
| 478 |
seeker.seek(0, 2) |
| 479 |
chunk_size = chunk_size * 512 |
| 480 |
lower_bound = 0 |
| 481 |
upper_bound = seeker.tell() |
| 482 |
mid = int(upper_bound / 2) |
| 483 |
seeker.seek(mid, 0) |
| 484 |
current_position = seeker.tell() |
| 485 |
used_indices = set() |
| 486 |
spectrum_found = False |
| 487 |
spectrum = None |
| 488 |
while spectrum_found is False: |
| 489 |
jumper_scaling = 1 |
| 490 |
file_pointer = seeker.tell() |
| 491 |
data = seeker.read(chunk_size) |
| 492 |
spec_start = self.spec_open.search(data) |
| 493 |
if spec_start is not None: |
| 494 |
spec_start_offset = file_pointer + spec_start.start() |
| 495 |
seeker.seek(spec_start_offset) |
| 496 |
spec_info = self.spec_open.search(data).groups() |
| 497 |
spec_info = dict(zip(spec_info[0::2], spec_info[1::2])) |
| 498 |
current_index = int(re.search(b"[0-9]*$", spec_info[b"id"]).group()) |
| 499 |
|
| 500 |
self.offset_dict[current_index] = (spec_start_offset,) |
| 501 |
if current_index in used_indices: |
| 502 |
if current_index > target_index: |
| 503 |
jumper_scaling -= 0.1 |
| 504 |
else: |
| 505 |
jumper_scaling += 0.1 |
| 506 |
|
| 507 |
used_indices.add(current_index) |
| 508 |
|
| 509 |
dist = current_index - target_index |
| 510 |
if dist < -1 and dist > -(fallback_cutoff): |
| 511 |
spectrum = self._search_linear(seeker, target_index) |
| 512 |
spectrum_found = True |
| 513 |
break |
| 514 |
elif dist > 0 and dist < fallback_cutoff: |
| 515 |
while current_index > target_index: |
| 516 |
offset = int(current_position - chunk_size) |
| 517 |
seeker.seek(offset if offset > 0 else 0) |
| 518 |
lower_bound = current_position |
| 519 |
current_position = seeker.tell() |
| 520 |
data = seeker.read(chunk_size) |
| 521 |
if self.spec_open.search(data): |
| 522 |
spec_info = self.spec_open.search(data).groups() |
| 523 |
spec_info = dict(zip(spec_info[0::2], spec_info[1::2])) |
| 524 |
current_index = int( |
| 525 |
re.search(b"[0-9]*$", spec_info[b"id"]).group() |
| 526 |
) |
| 527 |
seeker.seek(current_position) |
| 528 |
spectrum = self._search_linear(seeker, target_index) |
| 529 |
spectrum_found = True |
| 530 |
break |
| 531 |
|
| 532 |
if int(current_index) == target_index: |
| 533 |
|
| 534 |
seeker.seek(spec_start_offset) |
| 535 |
start, end = self._read_to_spec_end(seeker) |
| 536 |
seeker.seek(start) |
| 537 |
self.offset_dict[current_index] = (start, end) |
| 538 |
xml_string = seeker.read(end - start) |
| 539 |
spectrum = spec.Spectrum(XML(xml_string), measured_precision=5e-6) |
| 540 |
spectrum_found = True |
| 541 |
break |
| 542 |
|
| 543 |
elif int(current_index) > target_index: |
| 544 |
scaling = target_index / current_index |
| 545 |
seeker.seek(int(current_position * scaling * jumper_scaling)) |
| 546 |
upper_bound = current_position |
| 547 |
current_position = seeker.tell() |
| 548 |
elif int(current_index) < target_index: |
| 549 |
scaling = target_index / current_index |
| 550 |
seeker.seek(int(current_position * scaling * jumper_scaling)) |
| 551 |
lower_bound = current_position |
| 552 |
current_position = seeker.tell() |
| 553 |
|
| 554 |
elif len(data) == 0: |
| 555 |
sorted_int_keys = { |
| 556 |
k: v for k, v in self.offset_dict.items() if isinstance(k, int) |
| 557 |
} |
| 558 |
sorted_keys = sorted(sorted_int_keys.keys()) |
| 559 |
pos = ( |
| 560 |
bisect.bisect_left(sorted_int_keys, target_index) - 2 |
| 561 |
) |
| 562 |
try: |
| 563 |
key = sorted_keys[pos] |
| 564 |
spec_start_offset = self.offset_dict[key][0] |
| 565 |
except: |
| 566 |
key = sorted_keys[pos] |
| 567 |
spec_start_offset = self.offset_dict[key][0] |
| 568 |
seeker = self.get_binary_file_handler() |
| 569 |
seeker.seek(spec_start_offset) |
| 570 |
spectrum = self._search_linear(seeker, target_index) |
| 571 |
|
| 572 |
spectrum_found = True |
| 573 |
break |
| 574 |
|
| 575 |
return spectrum |
| 576 |
|
| 577 |
def _read_to_spec_end(self, seeker, chunks_to_read=8): |
| 578 |
""" |
| 579 |
Read from current seeker position to the end of the |
| 580 |
next spectrum tag and return start and end postition |
| 581 |
|
| 582 |
Args: |
| 583 |
seeker (_io.BufferedReader): Reader instance used in calling function |
| 584 |
|
| 585 |
Returns: |
| 586 |
positions (tuple): tuple with start and end postion of the spectrum |
| 587 |
""" |
| 588 |
|
| 589 |
chunk_size = 512 * chunks_to_read |
| 590 |
end_found = False |
| 591 |
start_pos = seeker.tell() |
| 592 |
data_chunk = seeker.read(chunk_size) |
| 593 |
while end_found is False: |
| 594 |
data_chunk += seeker.read(chunk_size) |
| 595 |
tag_end, seeker = self._read_until_tag_end(seeker) |
| 596 |
data_chunk += tag_end |
| 597 |
if regex_patterns.SPECTRUM_CLOSE_PATTERN.search(data_chunk): |
| 598 |
match = regex_patterns.SPECTRUM_CLOSE_PATTERN.search(data_chunk) |
| 599 |
end_pos = match.end() |
| 600 |
end_found = True |
| 601 |
elif regex_patterns.CHROMATOGRAM_CLOSE_PATTERN.search(data_chunk): |
| 602 |
match = regex_patterns.CHROMATOGRAM_CLOSE_PATTERN.search(data_chunk) |
| 603 |
end_pos = match.end() |
| 604 |
end_found = True |
| 605 |
return (start_pos, end_pos) |
| 606 |
|
| 607 |
def _read_extremes(self): |
| 608 |
""" |
| 609 |
Read min and max spectrum ids. Required for binary jumps. |
| 610 |
|
| 611 |
Returns: |
| 612 |
seek_list (list): list of tuples containing spec_id and file_offset |
| 613 |
""" |
| 614 |
chunk_size = 128000 |
| 615 |
|
| 616 |
first_scan = None |
| 617 |
last_scan = None |
| 618 |
seek_list = [] |
| 619 |
with open(self.path, "rb") as seeker: |
| 620 |
buffer = b"" |
| 621 |
for x in range(100): |
| 622 |
try: |
| 623 |
seeker.seek(os.SEEK_SET + x * chunk_size) |
| 624 |
except OSError: |
| 625 |
break |
| 626 |
chunk = seeker.read(chunk_size) |
| 627 |
buffer += chunk |
| 628 |
match = regex_patterns.SPECTRUM_OPEN_PATTERN_SIMPLE.search(buffer) |
| 629 |
if match is not None: |
| 630 |
id_match = regex_patterns.SPECTRUM_ID_PATTERN_SIMPLE.search(buffer) |
| 631 |
try: |
| 632 |
first_scan = int( |
| 633 |
re.search(b"[0-9]*$", id_match.group("id")).group() |
| 634 |
) |
| 635 |
except ValueError: |
| 636 |
first_scan = 0 |
| 637 |
|
| 638 |
seek_list.append( |
| 639 |
(first_scan, seeker.tell() - chunk_size + match.start()) |
| 640 |
) |
| 641 |
break |
| 642 |
buffer = b"" |
| 643 |
seeker.seek(0, os.SEEK_END) |
| 644 |
for x in range(1, 100): |
| 645 |
try: |
| 646 |
seeker.seek(-x * chunk_size, os.SEEK_END) |
| 647 |
except OSError: |
| 648 |
break |
| 649 |
chunk = seeker.read(chunk_size) |
| 650 |
buffer = chunk + buffer |
| 651 |
|
| 652 |
|
| 653 |
matches = list( |
| 654 |
regex_patterns.SPECTRUM_OPEN_PATTERN_SIMPLE.finditer(buffer) |
| 655 |
) |
| 656 |
if len(matches) != 0: |
| 657 |
id_match = regex_patterns.SPECTRUM_ID_PATTERN_SIMPLE.search( |
| 658 |
buffer[matches[-1].start() :] |
| 659 |
) |
| 660 |
last_scan = int(re.search(b"[0-9]*$", id_match.group("id")).group()) |
| 661 |
seek_list.append( |
| 662 |
(last_scan, seeker.tell() - chunk_size + matches[-1].start()) |
| 663 |
) |
| 664 |
break |
| 665 |
return seek_list |
| 666 |
|
| 667 |
def _search_linear(self, seeker, index, chunk_size=8): |
| 668 |
""" |
| 669 |
Fallback to linear search if interpolated search fails. |
| 670 |
""" |
| 671 |
data = None |
| 672 |
i = 0 |
| 673 |
total_chunk_size = chunk_size * 512 |
| 674 |
spec_start = None |
| 675 |
spec_end = None |
| 676 |
i = 0 |
| 677 |
|
| 678 |
while True: |
| 679 |
file_pointer = seeker.tell() |
| 680 |
|
| 681 |
data = seeker.read(total_chunk_size) |
| 682 |
string, seeker = self._read_until_tag_end(seeker) |
| 683 |
data += string |
| 684 |
|
| 685 |
spec_start = self.spec_open.search(data) |
| 686 |
if spec_start: |
| 687 |
spec_start_offset = file_pointer + spec_start.start() |
| 688 |
seeker.seek(spec_start_offset) |
| 689 |
spec_info = spec_start.groups() |
| 690 |
spec_info = dict(zip(spec_info[0::2], spec_info[1::2])) |
| 691 |
current_index = int(re.search(b"[0-9]*$", spec_info[b"id"]).group()) |
| 692 |
|
| 693 |
spec_end = self.spec_close.search(data[spec_start.start() :]) |
| 694 |
if spec_end: |
| 695 |
spec_end_offset = file_pointer + spec_end.end() + spec_start.start() |
| 696 |
seeker.seek(spec_end_offset) |
| 697 |
while spec_end is None: |
| 698 |
|
| 699 |
file_pointer = seeker.tell() |
| 700 |
|
| 701 |
data = seeker.read(total_chunk_size) |
| 702 |
string, seeker = self._read_until_tag_end(seeker) |
| 703 |
data += string |
| 704 |
|
| 705 |
spec_end = self.spec_close.search(data) |
| 706 |
if spec_end: |
| 707 |
spec_end_offset = file_pointer + spec_end.end() |
| 708 |
self.offset_dict[current_index] = ( |
| 709 |
spec_start_offset, |
| 710 |
spec_end_offset, |
| 711 |
) |
| 712 |
seeker.seek(spec_end_offset) |
| 713 |
break |
| 714 |
|
| 715 |
if current_index == index: |
| 716 |
seeker.seek(spec_start_offset) |
| 717 |
spec_string = seeker.read(spec_end_offset - spec_start_offset) |
| 718 |
self.offset_dict[current_index] = ( |
| 719 |
spec_start_offset, |
| 720 |
spec_end_offset, |
| 721 |
) |
| 722 |
xml_string = XML(spec_string) |
| 723 |
|
| 724 |
return spec.Spectrum(xml_string, measured_precision=5e-6) |
| 725 |
|
| 726 |
def _search_string_identifier(self, search_string, chunk_size=8): |
| 727 |
with self.get_binary_file_handler() as seeker: |
| 728 |
data = None |
| 729 |
total_chunk_size = chunk_size * 512 |
| 730 |
spec_start = None |
| 731 |
|
| 732 |
|
| 733 |
|
| 734 |
regex_string = re.compile( |
| 735 |
'<\s*spectrum[^>]*index="[0-9]+"\sid="({0})"\sdefaultArrayLength="[0-9]+">'.format( |
| 736 |
"".join([".*", search_string, ".*"]) |
| 737 |
).encode() |
| 738 |
) |
| 739 |
|
| 740 |
search_string = search_string.encode() |
| 741 |
|
| 742 |
while True: |
| 743 |
file_pointer = seeker.tell() |
| 744 |
|
| 745 |
data = seeker.read(total_chunk_size) |
| 746 |
string, seeker = self._read_until_tag_end(seeker) |
| 747 |
data += string |
| 748 |
spec_start = regex_string.search(data) |
| 749 |
chrom_start = regex_patterns.CHROMO_OPEN_PATTERN.search(data) |
| 750 |
if spec_start: |
| 751 |
spec_start_offset = file_pointer + spec_start.start() |
| 752 |
current_index = spec_start.group(1) |
| 753 |
if search_string in current_index: |
| 754 |
seeker.seek(spec_start_offset) |
| 755 |
start, end = self._read_to_spec_end(seeker) |
| 756 |
seeker.seek(start) |
| 757 |
spec_string = seeker.read(end) |
| 758 |
xml_string = XML(spec_string) |
| 759 |
return spec.Spectrum(xml_string, measured_precision=5e-6) |
| 760 |
elif chrom_start: |
| 761 |
chrom_start_offset = file_pointer + chrom_start.start() |
| 762 |
if search_string == chrom_start.group(1): |
| 763 |
seeker.seek(chrom_start_offset) |
| 764 |
start, end = self._read_to_spec_end(seeker) |
| 765 |
seeker.seek(start) |
| 766 |
chrom_string = seeker.read(end) |
| 767 |
xml_string = XML(chrom_string) |
| 768 |
return spec.Chromatogram(xml_string) |
| 769 |
elif len(data) == 0: |
| 770 |
raise Exception("cant find specified string") |
| 771 |
|
| 772 |
def _read_until_tag_end(self, seeker, max_search_len=12): |
| 773 |
""" |
| 774 |
Help make sure no splitted text appear in chunked data, so regex always find |
| 775 |
<spectrum ...> |
| 776 |
and |
| 777 |
</spectrum> |
| 778 |
""" |
| 779 |
count = 0 |
| 780 |
string = b"" |
| 781 |
curr_byte = "" |
| 782 |
while ( |
| 783 |
count < max_search_len |
| 784 |
and curr_byte != b">" |
| 785 |
and curr_byte != b"<" |
| 786 |
and curr_byte != b" " |
| 787 |
): |
| 788 |
curr_byte = seeker.read(1) |
| 789 |
string += curr_byte |
| 790 |
count += 1 |
| 791 |
return string, seeker |
| 792 |
|
| 793 |
def read(self, size=-1): |
| 794 |
""" |
| 795 |
Read binary data from file handler. |
| 796 |
|
| 797 |
Keyword Arguments: |
| 798 |
size (int): Number of bytes to read from file, -1 to read to end of file |
| 799 |
|
| 800 |
Returns: |
| 801 |
data (str): byte string of len size of input data |
| 802 |
""" |
| 803 |
return self.file_handler.read(size) |
| 804 |
|
| 805 |
def close(self): |
| 806 |
""" """ |
| 807 |
self.file_handler.close() |
| 808 |
|
| 809 |
|
| 810 |
if __name__ == "__main__": |
| 811 |
print(__doc__) |