Skip to content

Parser

detect_one_letter_name(atoms)

Guess a nucleotide one-letter code based on expected base atoms.

A simple scoring scheme compares the observed atom names with expected base-atom sets in BASE_ATOMS for A, C, G, U, T.

Parameters:

Name Type Description Default
atoms List[Atom]

Atoms belonging to a single residue.

required

Returns:

Name Type Description
str str

Best-scoring nucleotide (A/C/G/U/T) or '?' if no match is found.

Source code in src/rnapolis/parser.py
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
def detect_one_letter_name(atoms: List[Atom]) -> str:
    """Guess a nucleotide one-letter code based on expected base atoms.

    A simple scoring scheme compares the observed atom names with expected
    base-atom sets in ``BASE_ATOMS`` for A, C, G, U, T.

    Args:
        atoms (List[Atom]): Atoms belonging to a single residue.

    Returns:
        str: Best-scoring nucleotide (A/C/G/U/T) or '?' if no match is found.
    """
    atom_names_present = {atom.name for atom in atoms}
    score = {}
    for candidate in "ACGUT":
        atom_names_expected = BASE_ATOMS[candidate]
        count = sum(
            1 for atom in atom_names_expected if atom in atom_names_present
        ) / len(atom_names_expected)
        score[candidate] = count
    items = sorted(score.items(), key=lambda kv: kv[1], reverse=True)
    if items[0][1] == 0:
        return "?"
    return items[0][0]

filter_clashing_atoms(atoms, clash_distance=0.5)

Remove duplicate and clashing atoms, keeping the higher-occupancy ones.

The function first deduplicates atoms by (label, auth, atom name) using occupancy, and then uses a KDTree to detect close contacts below the given distance and resolves them according to occupancy.

Parameters:

Name Type Description Default
atoms List[Atom]

Input list of atoms.

required
clash_distance float

Distance threshold (in Å) for detecting clashes.

0.5

Returns:

Type Description
List[Atom]

Filtered list of atoms.

Source code in src/rnapolis/parser.py
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
def filter_clashing_atoms(atoms: List[Atom], clash_distance: float = 0.5) -> List[Atom]:
    """Remove duplicate and clashing atoms, keeping the higher-occupancy ones.

    The function first deduplicates atoms by (label, auth, atom name) using
    occupancy, and then uses a KDTree to detect close contacts below the given
    distance and resolves them according to occupancy.

    Args:
        atoms (List[Atom]): Input list of atoms.
        clash_distance (float): Distance threshold (in Å) for detecting clashes.

    Returns:
        Filtered list of atoms.
    """
    # First, remove duplicate atoms
    unique_atoms = {}

    for i, atom in enumerate(atoms):
        key = (atom.label, atom.auth, atom.name)
        if key not in unique_atoms or atom.occupancy > unique_atoms[key].occupancy:
            unique_atoms[key] = atom

    unique_atoms_list = list(unique_atoms.values())

    # If there are zero or one atoms, no clashes can occur
    if len(unique_atoms_list) <= 1:
        return unique_atoms_list

    # Now handle clashing atoms
    coords = np.array([(atom.x, atom.y, atom.z) for atom in unique_atoms_list])
    tree = KDTree(coords)

    pairs = tree.query_pairs(r=clash_distance)

    atoms_to_keep = set(range(len(unique_atoms_list)))

    for i, j in pairs:
        if (
            unique_atoms_list[i].occupancy is None
            or unique_atoms_list[j].occupancy is None
        ):
            continue
        if unique_atoms_list[i].occupancy > unique_atoms_list[j].occupancy:
            atoms_to_keep.discard(j)
        else:
            atoms_to_keep.discard(i)

    return [unique_atoms_list[i] for i in atoms_to_keep]

get_one_letter_name(entity_id, label, sequence_by_entity, name)

Infer a one-letter residue code from entity sequence and residue name.

The function first tries to read from the entity-level sequence, then falls back to simple heuristics based on residue name (RNA, DNA, last letter).

Parameters:

Name Type Description Default
entity_id Optional[str]

Entity ID for this residue.

required
label Optional[ResidueLabel]

Label-style residue identifier.

required
sequence_by_entity Dict[str, str]

Mapping from entity ID to sequence.

required
name str

Residue name candidate.

required

Returns:

Name Type Description
str str

One-letter residue code or a generic placeholder.

Source code in src/rnapolis/parser.py
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
def get_one_letter_name(
    entity_id: Optional[str],
    label: Optional[ResidueLabel],
    sequence_by_entity: Dict[str, str],
    name: str,
) -> str:
    """Infer a one-letter residue code from entity sequence and residue name.

    The function first tries to read from the entity-level sequence, then falls
    back to simple heuristics based on residue name (RNA, DNA, last letter).

    Args:
        entity_id (Optional[str]): Entity ID for this residue.
        label (Optional[ResidueLabel]): Label-style residue identifier.
        sequence_by_entity (Dict[str, str]): Mapping from entity ID to sequence.
        name (str): Residue name candidate.

    Returns:
        str: One-letter residue code or a generic placeholder.
    """
    # try getting the value from _entity_poly first
    if entity_id is not None and label is not None and entity_id in sequence_by_entity:
        entity_id_str = cast(str, entity_id)
        return sequence_by_entity[entity_id_str][label.number - 1]
    # RNA
    if len(name) == 1:
        return name
    # DNA
    if len(name) == 2 and name[0].upper() == "D":
        return name[1]
    # try the last letter of the name
    if str.isalpha(name[-1]):
        return name[-1]
    # any nucleotide
    return "n"

get_residue_name(auth, label, modified)

Resolve residue name based on modification annotations and auth/label data.

Parameters:

Name Type Description Default
auth Optional[ResidueAuth]

Author-style residue identifier.

required
label Optional[ResidueLabel]

Label-style residue identifier.

required
modified Dict[Union[ResidueAuth, ResidueLabel], str]

Mapping of modified residues to standard names.

required

Returns:

Name Type Description
str str

Residue name (possibly standardised) or a generic placeholder.

Source code in src/rnapolis/parser.py
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
def get_residue_name(
    auth: Optional[ResidueAuth],
    label: Optional[ResidueLabel],
    modified: Dict[Union[ResidueAuth, ResidueLabel], str],
) -> str:
    """Resolve residue name based on modification annotations and auth/label data.

    Args:
        auth (Optional[ResidueAuth]): Author-style residue identifier.
        label (Optional[ResidueLabel]): Label-style residue identifier.
        modified (Dict[Union[ResidueAuth, ResidueLabel], str]): Mapping of
            modified residues to standard names.

    Returns:
        str: Residue name (possibly standardised) or a generic placeholder.
    """
    if auth is not None and auth in modified:
        name = modified[auth].lower()
    elif label is not None and label in modified:
        name = modified[label].lower()
    elif auth is not None:
        name = auth.name
    elif label is not None:
        name = label.name
    else:
        # any nucleotide
        name = "n"
    return name

group_atoms(atoms, modified, sequence_by_entity, is_nucleic_acid_by_entity, nucleic_acid_only)

Group atoms into residues and build a Structure3D.

This function merges atoms with the same residue identifiers, infers one-letter residue codes (using entity sequences and heuristics for nucleotides) and optionally filters to nucleic-acid residues only.

Parameters:

Name Type Description Default
atoms List[Atom]

Atoms to group.

required
modified Dict[Union[ResidueLabel, ResidueAuth], str]

Mapping for modified residues to their standard names.

required
sequence_by_entity Dict[str, str]

Mapping from entity ID to sequence.

required
is_nucleic_acid_by_entity Dict[str, bool]

Mapping from entity ID to nucleic-acid flag.

required
nucleic_acid_only bool

If True, keep only nucleic-acid residues.

required

Returns:

Name Type Description
Structure3D Structure3D

Assembled structure.

Source code in src/rnapolis/parser.py
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
def group_atoms(
    atoms: List[Atom],
    modified: Dict[Union[ResidueLabel, ResidueAuth], str],
    sequence_by_entity: Dict[str, str],
    is_nucleic_acid_by_entity: Dict[str, bool],
    nucleic_acid_only: bool,
) -> Structure3D:
    """Group atoms into residues and build a Structure3D.

    This function merges atoms with the same residue identifiers, infers
    one-letter residue codes (using entity sequences and heuristics for
    nucleotides) and optionally filters to nucleic-acid residues only.

    Args:
        atoms (List[Atom]): Atoms to group.
        modified (Dict[Union[ResidueLabel, ResidueAuth], str]): Mapping for
            modified residues to their standard names.
        sequence_by_entity (Dict[str, str]): Mapping from entity ID to sequence.
        is_nucleic_acid_by_entity (Dict[str, bool]): Mapping from entity ID to
            nucleic-acid flag.
        nucleic_acid_only (bool): If True, keep only nucleic-acid residues.

    Returns:
        Structure3D: Assembled structure.
    """
    if not atoms:
        return Structure3D([])

    key_previous = (atoms[0].label, atoms[0].auth, atoms[0].model)
    residue_atoms = [atoms[0]]
    residues: List[Residue3D] = []

    for atom in atoms[1:]:
        key = (atom.label, atom.auth, atom.model)
        if key == key_previous:
            residue_atoms.append(atom)
        else:
            label = key_previous[0]
            auth = key_previous[1]
            model = key_previous[2]
            entity_id = residue_atoms[-1].entity_id
            name = get_residue_name(auth, label, modified)
            one_letter_name = get_one_letter_name(
                entity_id, label, sequence_by_entity, name
            )

            if one_letter_name not in "ACGUTN":
                one_letter_name = detect_one_letter_name(residue_atoms)

            residues.append(
                Residue3D(
                    label, auth, model, one_letter_name, tuple(residue_atoms), name
                )
            )

            key_previous = key
            residue_atoms = [atom]

    label = key_previous[0]
    auth = key_previous[1]
    model = key_previous[2]
    entity_id = residue_atoms[-1].entity_id
    name = get_residue_name(auth, label, modified)
    one_letter_name = get_one_letter_name(entity_id, label, sequence_by_entity, name)

    if one_letter_name not in "ACGUTN":
        one_letter_name = detect_one_letter_name(residue_atoms)

    residues.append(
        Residue3D(label, auth, model, one_letter_name, tuple(residue_atoms), name)
    )

    if nucleic_acid_only:
        if is_nucleic_acid_by_entity:
            residues = [
                residue
                for residue in residues
                if (entity_id := residue.atoms[0].entity_id) is not None
                and is_nucleic_acid_by_entity.get(entity_id, False)
            ]
        else:
            residues = [residue for residue in residues if residue.is_nucleotide]

    return Structure3D(residues)

is_cif(cif_or_pdb)

Heuristically check if a file-like object contains mmCIF data.

The function rewinds the stream and looks for _atom_site records.

Parameters:

Name Type Description Default
cif_or_pdb IO[str]

Open file-like object with structural data.

required

Returns:

Name Type Description
bool bool

True if the content looks like mmCIF, False if it is assumed to be PDB.

Source code in src/rnapolis/parser.py
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
def is_cif(cif_or_pdb: IO[str]) -> bool:
    """Heuristically check if a file-like object contains mmCIF data.

    The function rewinds the stream and looks for ``_atom_site`` records.

    Args:
        cif_or_pdb (IO[str]): Open file-like object with structural data.

    Returns:
        bool: True if the content looks like mmCIF, False if it is assumed to be PDB.
    """
    cif_or_pdb.seek(0)
    for line in cif_or_pdb.readlines():
        if line.startswith("_atom_site"):
            return True
    return False

parse_cif(cif)

Parse a mmCIF file into atoms and entity-level metadata.

Parameters:

Name Type Description Default
cif IO[str]

Open file-like object with mmCIF content.

required

Returns:

Name Type Description
tuple Tuple[List[Atom], Dict[Union[ResidueLabel, ResidueAuth], str], Dict[str, str], Dict[str, bool]]

A tuple containing:

  • List[Atom]: list of Atom objects.
  • Dict[Union[ResidueLabel, ResidueAuth], str]: mapping of modified residues to their parent (standard) names.
  • Dict[str, str]: mapping from entity ID to one-letter sequence (if present).
  • Dict[str, bool]: mapping from entity ID to nucleic-acid flag.
Source code in src/rnapolis/parser.py
 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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
def parse_cif(
    cif: IO[str],
) -> Tuple[
    List[Atom],
    Dict[Union[ResidueLabel, ResidueAuth], str],
    Dict[str, str],
    Dict[str, bool],
]:
    """Parse a mmCIF file into atoms and entity-level metadata.

    Args:
        cif (IO[str]): Open file-like object with mmCIF content.

    Returns:
        tuple:
            A tuple containing:

            - **List[Atom]**: list of Atom objects.
            - **Dict[Union[ResidueLabel, ResidueAuth], str]**:
              mapping of modified residues to their parent (standard) names.
            - **Dict[str, str]**:
              mapping from entity ID to one-letter sequence (if present).
            - **Dict[str, bool]**:
              mapping from entity ID to nucleic-acid flag.
    """
    cif.seek(0)

    try:
        content = cif.read()
    except io.UnsupportedOperation:
        if hasattr(cif, "name"):
            with open(cif.name, "r", encoding="utf-8") as handle:
                content = handle.read()
        else:
            raise
    if isinstance(content, bytes):
        content = content.decode("utf-8")

    content = re.sub(r"(^\s*data_)\s*$", r"\1unnamed", content, flags=re.MULTILINE)
    for axis in ("x", "y", "z"):
        content = re.sub(
            rf"(_atom_site\.)cartn_{axis}\b",
            rf"\1Cartn_{axis}",
            content,
            flags=re.IGNORECASE,
        )

    io_adapter = IoAdapterPy()
    with tempfile.NamedTemporaryFile(mode="w+", suffix=".cif", delete=False) as temp:
        temp.write(content)
        temp_path = temp.name
    try:
        data = io_adapter.readFile(temp_path)
    finally:
        os.remove(temp_path)
    atoms_to_process: List[Atom] = []
    modified: Dict[Union[ResidueLabel, ResidueAuth], str] = {}
    sequence_by_entity: Dict[str, str] = {}
    is_nucleic_acid_by_entity: Dict[str, bool] = {}

    if data:
        atom_site = data[0].getObj("atom_site")
        mod_residue = data[0].getObj("pdbx_struct_mod_residue")
        entity_poly = data[0].getObj("entity_poly")
        entity = data[0].getObj("entity")

        if atom_site:
            for row in atom_site.getRowList():
                row_dict = dict(zip(atom_site.getAttributeList(), row))

                label_entity_id = _mmcif_value(row_dict.get("label_entity_id", None))
                label_chain_name = _mmcif_value(row_dict.get("label_asym_id", None))
                label_residue_number = try_parse_int(
                    _mmcif_value(row_dict.get("label_seq_id", None))
                )
                label_residue_name = _mmcif_value(row_dict.get("label_comp_id", None))
                auth_chain_name = _mmcif_value(row_dict.get("auth_asym_id", None))
                auth_residue_number = try_parse_int(
                    _mmcif_value(row_dict.get("auth_seq_id", None))
                )
                auth_residue_name = _mmcif_value(row_dict.get("auth_comp_id", None))
                insertion_code = _mmcif_value(row_dict.get("pdbx_PDB_ins_code", None))

                if label_chain_name is None and auth_chain_name is None:
                    logger.warning(
                        f"Skipping atom line with both label and auth chain names empty: {row}"
                    )
                    continue
                if label_residue_number is None and auth_residue_number is None:
                    raise RuntimeError(
                        f"Cannot parse an atom line with empty residue number: {row}"
                    )
                if label_residue_name is None and auth_residue_name is None:
                    raise RuntimeError(
                        f"Cannot parse an atom line with empty residue name: {row}"
                    )

                label = None
                if label_residue_number is not None and label_residue_name is not None:
                    label = ResidueLabel(
                        label_chain_name, label_residue_number, label_residue_name
                    )

                auth = None
                if auth_residue_number is not None and auth_residue_name is not None:
                    auth = ResidueAuth(
                        auth_chain_name,
                        auth_residue_number,
                        insertion_code,
                        auth_residue_name,
                    )

                if label is None and auth is None:
                    # this should not happen in a valid mmCIF file
                    # skipping the line
                    logger.debug(
                        f"Cannot parse an atom line without chain name, residue number, and residue name: {row}"
                    )
                    continue

                model = int(row_dict.get("pdbx_PDB_model_num", "1"))
                atom_name = row_dict["label_atom_id"]
                x = float(row_dict["Cartn_x"])
                y = float(row_dict["Cartn_y"])
                z = float(row_dict["Cartn_z"])

                occupancy = (
                    float(row_dict["occupancy"])
                    if "occupancy" in row_dict
                    and row_dict["occupancy"] not in (".", "?")
                    else None
                )

                atoms_to_process.append(
                    Atom(
                        label_entity_id,
                        label,
                        auth,
                        model,
                        atom_name,
                        x,
                        y,
                        z,
                        occupancy,
                    )
                )

        if mod_residue:
            for row in mod_residue.getRowList():
                row_dict = dict(zip(mod_residue.getAttributeList(), row))

                label_chain_name = _mmcif_value(row_dict.get("label_asym_id", None))
                label_residue_number = try_parse_int(
                    _mmcif_value(row_dict.get("label_seq_id", None))
                )
                label_residue_name = _mmcif_value(row_dict.get("label_comp_id", None))
                auth_chain_name = _mmcif_value(row_dict.get("auth_asym_id", None))
                auth_residue_number = try_parse_int(
                    _mmcif_value(row_dict.get("auth_seq_id", None))
                )
                auth_residue_name = _mmcif_value(row_dict.get("auth_comp_id", None))
                insertion_code = _mmcif_value(row_dict.get("PDB_ins_code", None))

                label = None
                if label_residue_number is not None and label_residue_name is not None:
                    label = ResidueLabel(
                        label_chain_name, label_residue_number, label_residue_name
                    )

                auth = None
                if auth_residue_number is not None and auth_residue_name is not None:
                    auth = ResidueAuth(
                        auth_chain_name,
                        auth_residue_number,
                        insertion_code,
                        auth_residue_name,
                    )

                # TODO: is processing this data for each model separately required?
                # model = row_dict.get('PDB_model_num', '1')
                standard_residue_name = _mmcif_value(
                    row_dict.get("parent_comp_id", "n")
                )
                if standard_residue_name is None:
                    standard_residue_name = "n"

                if label is not None:
                    modified[label] = standard_residue_name
                if auth is not None:
                    modified[auth] = standard_residue_name

        if entity_poly:
            for row in entity_poly.getRowList():
                row_dict = dict(zip(entity_poly.getAttributeList(), row))

                entity_id = _mmcif_value(row_dict.get("entity_id", None))
                type_ = _mmcif_value(row_dict.get("type", None))
                pdbx_seq_one_letter_code_can = _mmcif_value(
                    row_dict.get("pdbx_seq_one_letter_code_can", None)
                )

                if entity_id and type_:
                    is_nucleic_acid_by_entity[entity_id] = type_ in (
                        "peptide nucleic acid",
                        "polydeoxyribonucleotide",
                        "polydeoxyribonucleotide/polyribonucleotide hybrid",
                        "polyribonucleotide",
                    )

                if entity_id and pdbx_seq_one_letter_code_can:
                    sequence_by_entity[entity_id] = (
                        pdbx_seq_one_letter_code_can.replace("\n", "")
                    )

        if entity:
            for row in entity.getRowList():
                row_dict = dict(zip(entity.getAttributeList(), row))

                entity_id = _mmcif_value(row_dict.get("id", None))
                type_ = _mmcif_value(row_dict.get("type", None))

                if entity_id:
                    sequence_by_entity[entity_id] = sequence_by_entity.get(
                        entity_id, ""
                    )

                    if type_:
                        is_nucleic_acid_by_entity[entity_id] = (
                            is_nucleic_acid_by_entity.get(
                                entity_id,
                                type_
                                in (
                                    "peptide nucleic acid",
                                    "polydeoxyribonucleotide",
                                    "polydeoxyribonucleotide/polyribonucleotide hybrid",
                                    "polyribonucleotide",
                                ),
                            )
                        )

    atoms = filter_clashing_atoms(atoms_to_process)
    return atoms, modified, sequence_by_entity, is_nucleic_acid_by_entity

parse_pdb(pdb)

Parse a PDB file into atoms and modification information.

Parameters:

Name Type Description Default
pdb IO[str]

Open file-like object with PDB content.

required

Returns:

Name Type Description
tuple Tuple[List[Atom], Dict[Union[ResidueLabel, ResidueAuth], str], Dict[str, str], Dict[str, bool]]

A tuple containing:

  • List[Atom]: list of Atom objects.
  • Dict[Union[ResidueLabel, ResidueAuth], str]: mapping of modified residues to standard residue names.
  • Dict[str, str]: empty sequence-by-entity dictionary.
  • Dict[str, bool]: empty is-nucleic-acid-by-entity dictionary.
Source code in src/rnapolis/parser.py
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
def parse_pdb(
    pdb: IO[str],
) -> Tuple[
    List[Atom],
    Dict[Union[ResidueLabel, ResidueAuth], str],
    Dict[str, str],
    Dict[str, bool],
]:
    """Parse a PDB file into atoms and modification information.

    Args:
        pdb (IO[str]): Open file-like object with PDB content.

    Returns:
        tuple:
            A tuple containing:

            - **List[Atom]**: list of Atom objects.
            - **Dict[Union[ResidueLabel, ResidueAuth], str]**:
              mapping of modified residues to standard residue names.
            - **Dict[str, str]**:
              empty sequence-by-entity dictionary.
            - **Dict[str, bool]**:
              empty is-nucleic-acid-by-entity dictionary.
    """
    pdb.seek(0)
    atoms_to_process: List[Atom] = []
    modified: Dict[Union[ResidueLabel, ResidueAuth], str] = {}
    model = 1

    for line in pdb.readlines():
        if line.startswith("MODEL"):
            model = int(line[10:14].strip())
        elif line.startswith("ATOM") or line.startswith("HETATM"):
            atom_name = line[12:16].strip()
            residue_name = line[17:20].strip()
            chain_identifier = line[21]
            residue_number = int(line[22:26].strip())
            insertion_code = line[26] if line[26] != " " else None
            x = float(line[30:38].strip())
            y = float(line[38:46].strip())
            z = float(line[46:54].strip())
            occupancy = float(line[54:60].strip())
            auth = ResidueAuth(
                chain_identifier, residue_number, insertion_code, residue_name
            )

            atoms_to_process.append(
                Atom(None, None, auth, model, atom_name, x, y, z, occupancy)
            )
        elif line.startswith("MODRES"):
            original_name = line[12:15]
            chain_identifier = line[16]
            residue_number = int(line[18:22].strip())
            insertion_code = line[23]
            standard_residue_name = line[24:27].strip()
            auth = ResidueAuth(
                chain_identifier, residue_number, insertion_code, original_name
            )
            modified[auth] = standard_residue_name

    atoms = filter_clashing_atoms(atoms_to_process)
    return atoms, modified, {}, {}

read_3d_structure(cif_or_pdb, model=None, nucleic_acid_only=False)

Read a PDB or mmCIF structure into a Structure3D object.

The function auto-detects whether the input is mmCIF or PDB, parses atoms, groups them into residues and optionally filters to nucleic-acid residues only.

Parameters:

Name Type Description Default
cif_or_pdb IO[str]

Open file-like object with PDB or mmCIF content.

required
model Optional[int]

Model number to extract (1-based). If None, the first model encountered is used.

None
nucleic_acid_only bool

If True, keep only nucleic-acid residues.

False

Returns:

Name Type Description
Structure3D Structure3D

Parsed 3D structure.

Source code in src/rnapolis/parser.py
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
def read_3d_structure(
    cif_or_pdb: IO[str], model: Optional[int] = None, nucleic_acid_only: bool = False
) -> Structure3D:
    """Read a PDB or mmCIF structure into a Structure3D object.

    The function auto-detects whether the input is mmCIF or PDB, parses atoms,
    groups them into residues and optionally filters to nucleic-acid residues only.

    Args:
        cif_or_pdb (IO[str]): Open file-like object with PDB or mmCIF content.
        model (Optional[int]): Model number to extract (1-based). If None, the
            first model encountered is used.
        nucleic_acid_only (bool): If True, keep only nucleic-acid residues.

    Returns:
        Structure3D: Parsed 3D structure.
    """
    atoms, modified, sequence_by_entity, is_nucleic_acid_by_entity = (
        parse_cif(cif_or_pdb) if is_cif(cif_or_pdb) else parse_pdb(cif_or_pdb)
    )
    if not atoms:
        logger.warning("No atoms parsed from file, returning empty Structure3D.")
        return Structure3D([])
    available_models = {atom.model: None for atom in atoms}
    atoms_by_model = {
        model: list(filter(lambda atom: atom.model == model, atoms))
        for model in available_models
    }
    if model is not None and model in available_models:
        atoms = atoms_by_model[model]
    else:
        atoms = atoms_by_model[list(available_models.keys())[0]]
    return group_atoms(
        atoms,
        modified,
        sequence_by_entity,
        is_nucleic_acid_by_entity,
        nucleic_acid_only,
    )

try_parse_int(s)

Try to convert a string to int, returning None on failure.

Parameters:

Name Type Description Default
s str

String to parse.

required

Returns:

Type Description
Optional[int]

Parsed integer, or None if conversion fails.

Source code in src/rnapolis/parser.py
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
def try_parse_int(s: Optional[str]) -> Optional[int]:
    """Try to convert a string to int, returning None on failure.

    Args:
        s (str): String to parse.

    Returns:
        Parsed integer, or None if conversion fails.
    """
    if s is None:
        return None
    try:
        return int(s)
    except ValueError:
        return None