pdbrust 0.7.0

A comprehensive Rust library for parsing and analyzing Protein Data Bank (PDB) files
Documentation
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
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
320
321
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
385
386
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
471
472
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
501
502
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
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
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
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
# CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

## Project Overview

PDBRust is a Rust library for parsing and analyzing Protein Data Bank (PDB) and mmCIF files. It provides comprehensive support for molecular structure data with robust error handling, structural analysis, quality assessment, and RCSB PDB integration.

### Core Architecture

- **Dual Format Support**: Supports both PDB (legacy text format) and mmCIF (modern dictionary format) with automatic format detection
- **Unified Data Model**: Both formats convert to a common `PdbStructure` representation
- **Feature-Gated Modules**: Optional functionality behind feature flags for minimal compile times
- **High Performance**: 40-260x faster than equivalent Python implementations

### Module Structure

```
src/
├── core/           # Core data structures
│   ├── pdb.rs          # PdbStructure definition
│   ├── mmcif.rs        # mmCIF parsing
│   └── mmcif_converter.rs
├── parser/         # Format-specific parsers with auto-detection
│   ├── pdb/            # PDB format parser
│   ├── mmcif/          # mmCIF format parser
│   └── gzip.rs         # [feature: gzip] Gzip-compressed file support
├── records/        # Record types (Atom, Residue, Chain, Model, SSBond, etc.)
├── writer/         # PDB file output
├── error.rs        # Error handling with thiserror
├── guide.rs        # Comprehensive user guide (accessible via cargo doc)
├── filter/         # [feature: filter] Filtering and cleaning operations
├── descriptors/    # [feature: descriptors] Structural descriptors
├── quality/        # [feature: quality] Quality assessment
├── summary/        # [feature: summary] Unified structure summaries
├── rcsb/           # [feature: rcsb] RCSB PDB search and download
├── geometry/       # [feature: geometry] RMSD, LDDT, and structure superposition
├── dssp/           # [feature: dssp] Secondary structure assignment
├── ligand_quality/ # [feature: ligand-quality] PoseBusters-style pose validation
└── dockq/          # [feature: dockq] DockQ v2 interface quality assessment

pdbrust-python/     # Python bindings (PyO3)
├── Cargo.toml          # Rust dependencies for Python bindings
├── pyproject.toml      # Python package configuration (maturin)
├── src/
│   ├── lib.rs          # PyO3 module entry point
│   ├── structure.rs    # PyPdbStructure wrapper
│   ├── atom.rs         # PyAtom wrapper
│   ├── records.rs      # PySSBond, PySeqRes, etc.
│   ├── parsing.rs      # Parsing functions
│   ├── error.rs        # Python exception mapping
│   ├── descriptors.rs  # StructureDescriptors bindings
│   ├── quality.rs      # QualityReport bindings
│   ├── summary.rs      # StructureSummary bindings
│   ├── rcsb.rs         # RCSB search/download bindings
│   ├── geometry.rs     # RMSD/alignment bindings
│   ├── dssp.rs         # Secondary structure bindings
│   ├── ligand_quality.rs # Ligand pose quality bindings
│   └── numpy_support.rs # Numpy array integration
└── python/pdbrust/
    ├── __init__.py     # Python exports
    └── py.typed        # PEP 561 type hint marker

docs/
└── GETTING_STARTED.md  # Quick start guide for new users

examples/
├── pdb_files/          # Sample PDB files for testing
├── analysis_workflow.rs
├── filtering_demo.rs
├── rcsb_workflow.rs
├── batch_processing.rs
├── full_pdb_benchmark.rs  # Full PDB archive benchmark
└── ...                 # Additional examples

.github/workflows/
├── rust.yml            # Rust CI/CD
└── python-publish.yml  # Python wheel building and PyPI publishing

benchmark_results/      # Results from full PDB archive benchmark
├── benchmark_report.txt
├── failures.tsv
└── timing_histogram.txt
```

### Feature Flags

| Feature | Description | Dependencies |
|---------|-------------|--------------|
| `filter` | Filtering, extraction, and cleaning operations | - |
| `descriptors` | Structural descriptors (Rg, composition, geometry) | - |
| `quality` | Quality assessment and reports | - |
| `summary` | Unified summaries combining quality + descriptors | `descriptors`, `quality` |
| `rcsb` | RCSB PDB search API and file download | `reqwest`, `serde`, `serde_json` |
| `rcsb-async` | Async/concurrent bulk downloads with rate limiting | `rcsb`, `tokio`, `futures` |
| `gzip` | Parse gzip-compressed files (.ent.gz, .pdb.gz) | `flate2` |
| `parallel` | Parallel processing with Rayon | `rayon` |
| `geometry` | RMSD, LDDT, and geometric analysis with nalgebra | `nalgebra` |
| `dssp` | DSSP-like secondary structure assignment | - |
| `ligand-quality` | PoseBusters-style ligand pose validation | - |
| `dockq` | DockQ v2 interface quality for protein-protein complexes | `geometry` |
| `analysis` | All analysis features | `filter`, `descriptors`, `quality`, `summary`, `dssp`, `ligand-quality`, `dockq` |
| `full` | Everything | `parallel`, `geometry`, `analysis`, `rcsb`, `rcsb-async`, `gzip` |

## Development Commands

### Building and Testing
```bash
# Build the project
cargo build

# Run all tests
cargo test

# Run tests with all features
cargo test --all-features

# Run tests for a specific feature
cargo test --features filter
cargo test --features rcsb

# Run network tests (RCSB download/search)
cargo test --features rcsb -- --ignored

# Run benchmarks
cargo bench
```

### Code Quality
```bash
# Format code
cargo fmt

# Run clippy lints (CI uses -D warnings flag)
cargo clippy --all-targets --all-features -- -D warnings

# Check documentation
cargo doc --no-deps --all-features

# Security audit
cargo audit
```

### GitHub Actions / CI

```bash
# List recent workflow runs
gh run list --limit 5

# Watch a specific run (with exit status)
gh run watch <run_id> --exit-status

# View logs for failed jobs
gh run view <run_id> --log-failed

# Rerun failed jobs
gh run rerun <run_id> --failed
```

### Benchmarking
```bash
# Run Rust benchmark
cargo run --release --features "filter,descriptors" --example rust_benchmark

# Run Python comparison benchmark
python3 benchmarks/python_benchmark.py
```

## Git Workflow (Gitflow)

This project follows Gitflow branching strategy to protect the main branch.

### Branch Structure
- `main` - Production-ready code only. Protected branch.
- `develop` - Integration branch for features (optional)
- `feature/*` - Feature branches for new development

### Workflow for New Features

When starting work on a new feature from the roadmap or a GitHub issue:

1. **Create feature branch from main:**
   ```bash
   git checkout main
   git pull origin main
   # Use descriptive branch name, optionally reference issue number
   git checkout -b feature/feature-name
   # Or with issue reference: git checkout -b feature/123-feature-name
   ```

2. **Develop and commit on feature branch:**
   ```bash
   # Make changes
   git add <files>
   git commit -m "feat: description"
   ```

3. **Run tests locally (optional but recommended):**
   ```bash
   cargo test --all-features
   cargo clippy --all-targets --all-features -- -D warnings
   cargo fmt --check
   ```

4. **Push feature branch and create Pull Request:**
   ```bash
   git push -u origin feature/feature-name
   # Create PR (use "Closes #123" in body to auto-close linked issue)
   gh pr create --title "feat: description" --body "Description of changes

   Closes #123"
   ```

5. **Merge PR after CI passes:**
   - Wait for GitHub Actions CI to complete
   - Review the changes in the PR
   - Merge via GitHub UI or CLI:
   ```bash
   gh pr merge --squash --delete-branch
   ```

6. **Update local main branch:**
   ```bash
   git checkout main
   git pull origin main
   ```

### Branch Naming Convention
- `feature/alphafold-plddt` - New features
- `feature/42-alphafold-plddt` - New feature linked to issue #42
- `fix/parsing-bug` - Bug fixes
- `fix/15-mmcif-parsing` - Bug fix linked to issue #15
- `refactor/dssp-cleanup` - Code refactoring
- `docs/api-examples` - Documentation updates

### Commit Message Convention
- `feat:` - New feature
- `fix:` - Bug fix
- `docs:` - Documentation
- `refactor:` - Code refactoring
- `test:` - Test additions/changes
- `chore:` - Maintenance tasks

## Testing Strategy

- **Unit tests**: In individual modules (`#[cfg(test)]` blocks)
- **Integration tests**: In `tests/` directory, one file per feature module
- **Property-based tests**: Using `proptest` for robust validation
- **Benchmark tests**: Using `criterion` for performance tracking
- **Network tests**: Marked with `#[ignore]` for RCSB API tests

Test files:
- `tests/filter_tests.rs` - 18 tests
- `tests/selection_tests.rs` - 30 tests (selection language)
- `tests/descriptors_tests.rs` - 17 tests
- `tests/quality_tests.rs` - 18 tests
- `tests/summary_tests.rs` - 18 tests
- `tests/rcsb_tests.rs` - 28 tests (11 network tests ignored by default)
- `tests/rcsb_async_tests.rs` - 24 tests (12 unit tests + 12 network tests ignored)
- `tests/dssp_tests.rs` - 34 tests (secondary structure assignment)
- `tests/ligand_quality_tests.rs` - 21 tests (PoseBusters-style pose validation)
- `tests/dockq_tests.rs` - 21 tests (DockQ v2 interface quality assessment)

## Key Data Structures

### Core Types
- `PdbStructure`: Main structure containing all parsed data
- `Atom`: Individual atom records with coordinates and metadata
- `Residue`: Amino acid/nucleotide residue information
- `Chain`: Protein/nucleic acid chain organization
- `Model`: Multi-model structures (NMR ensembles)
- `SSBond`: Disulfide bond connectivity

### Feature-Specific Types
- `SelectionError` (filter): Selection language parsing errors
- `QualityReport` (quality): Structure quality assessment
- `StructureDescriptors` (descriptors): Computed structural metrics
- `ResidueBFactor` (descriptors): Per-residue B-factor statistics (mean, min, max)
- `StructureSummary` (summary): Combined quality + descriptors
- `SearchQuery` (rcsb): RCSB search query builder
- `FileFormat` (rcsb): PDB/CIF format selection
- `AsyncDownloadOptions` (rcsb-async): Concurrency and rate limiting configuration
- `AlignmentResult` (geometry): RMSD and transformation from alignment
- `PerResidueRmsd` (geometry): Per-residue RMSD for flexibility analysis
- `AtomSelection` (geometry): Atom selection for RMSD/alignment/LDDT
- `LddtResult` (geometry): LDDT score and per-threshold statistics
- `LddtOptions` (geometry): LDDT configuration (inclusion radius, thresholds)
- `PerResidueLddt` (geometry): Per-residue LDDT for quality analysis
- `SecondaryStructure` (dssp): 9-state SS classification (H, G, I, P, E, B, T, S, C)
- `ResidueSSAssignment` (dssp): Per-residue secondary structure assignment
- `SecondaryStructureAssignment` (dssp): Complete SS assignment with statistics
- `LigandPoseReport` (ligand-quality): PoseBusters-style ligand pose validation report
- `AtomClash` (ligand-quality): Steric clash between protein and ligand atoms
- `DockQResult` (dockq): Overall DockQ result with per-interface scores
- `InterfaceResult` (dockq): Per-interface fnat, iRMSD, LRMSD, DockQ score
- `DockQOptions` (dockq): Configuration for DockQ calculation
- `DockQQuality` (dockq): Quality classification (Incorrect/Acceptable/Medium/High)
- `ChainMappingStrategy` (dockq): Auto or explicit chain correspondence

## Common Patterns

### Parsing
```rust
// Auto-detect format
let structure = parse_structure_file("file.pdb")?;

// Explicit format
let structure = parse_pdb_file("file.pdb")?;
let structure = parse_mmcif_file("file.cif")?;

// From string
let structure = parse_pdb_string(content)?;

// Gzip-compressed files (feature: gzip)
let structure = parse_gzip_pdb_file("pdb1ubq.ent.gz")?;
let structure = parse_gzip_structure_file("structure.pdb.gz")?;  // Auto-detect
```

### Filtering (feature: filter)
```rust
// Fluent API with method chaining
let cleaned = structure
    .remove_ligands()
    .keep_only_chain("A")
    .keep_only_ca();

// In-place modifications
structure.normalize_chain_ids();
structure.reindex_residues();
structure.center_structure();
```

### Selection Language (feature: filter)
```rust
// PyMOL/VMD-style selection language
let selected = structure.select("chain A and name CA")?;
let backbone = structure.select("backbone and not hydrogen")?;
let residues = structure.select("resid 1:100 and protein")?;
let complex = structure.select("(chain A or chain B) and bfactor < 30.0")?;

// Validate without executing
PdbStructure::validate_selection("chain A and name CA")?;
```

**Selection syntax:**
- Basic: `chain A`, `name CA`, `resname ALA`, `resid 50`, `resid 1:100`, `element C`
- Keywords: `backbone`, `protein`, `nucleic`, `water`, `hetero`, `hydrogen`, `all`
- Numeric: `bfactor < 30.0`, `occupancy >= 0.5`
- Boolean: `and`, `or`, `not`, `()`

### Descriptors (feature: descriptors)
```rust
let rg = structure.radius_of_gyration();
let max_dist = structure.max_ca_distance();
let composition = structure.aa_composition();
let descriptors = structure.structure_descriptors(); // All at once

// B-factor analysis
let mean_b = structure.b_factor_mean();
let profile = structure.b_factor_profile();
let flexible = structure.flexible_residues(50.0);  // B > 50 Ų
let normalized = structure.normalize_b_factors();
```

### Quality (feature: quality)
```rust
let report = structure.quality_report();
if report.is_analysis_ready() {
    // Single model, no altlocs, full atoms
}
```

### RCSB (feature: rcsb)
```rust
// Search
let query = SearchQuery::new()
    .with_text("kinase")
    .with_resolution_max(2.0);
let results = rcsb_search(&query, 10)?;

// Download
let structure = download_structure("1UBQ", FileFormat::Pdb)?;
```

### Async Downloads (feature: rcsb-async)
```rust
use pdbrust::rcsb::{download_multiple_async, AsyncDownloadOptions, FileFormat};

// Download multiple structures concurrently
let pdb_ids = vec!["1UBQ", "8HM2", "4INS"];
let results = download_multiple_async(&pdb_ids, FileFormat::Pdb, None).await;

// With custom options
let options = AsyncDownloadOptions::default()
    .with_max_concurrent(10)
    .with_rate_limit_ms(50);
let results = download_multiple_async(&pdb_ids, FileFormat::Cif, Some(options)).await;

// Preset options
let conservative = AsyncDownloadOptions::conservative(); // 2 concurrent, 500ms delay
let fast = AsyncDownloadOptions::fast();                 // 20 concurrent, 25ms delay

// Handle results
for (pdb_id, result) in results {
    match result {
        Ok(structure) => println!("{}: {} atoms", pdb_id, structure.atoms.len()),
        Err(e) => eprintln!("{}: {}", pdb_id, e),
    }
}
```

### Geometry (feature: geometry)
```rust
use pdbrust::geometry::{AtomSelection, LddtOptions};

// RMSD calculation (without alignment)
let rmsd = structure1.rmsd_to(&structure2)?;  // CA atoms by default

// RMSD with different atom selection
let rmsd = structure1.rmsd_to_with_selection(&structure2, AtomSelection::Backbone)?;

// Structure alignment (Kabsch algorithm)
let (aligned, result) = mobile.align_to(&target)?;
println!("RMSD: {:.4} Angstroms ({} atoms)", result.rmsd, result.num_atoms);

// Per-residue RMSD for flexibility analysis
let per_res = mobile.per_residue_rmsd_to(&target)?;
for r in &per_res {
    if r.rmsd > 2.0 {
        println!("Flexible: {}{} {}", r.residue_id.0, r.residue_id.1, r.rmsd);
    }
}

// LDDT calculation (superposition-free, used in AlphaFold/CASP)
let result = model.lddt_to(&reference)?;
println!("LDDT: {:.4}", result.score);  // 0.0 (poor) to 1.0 (perfect)

// LDDT with custom options
let options = LddtOptions::default()
    .with_inclusion_radius(10.0)
    .with_thresholds(vec![0.5, 1.0, 2.0, 4.0]);
let result = model.lddt_to_with_options(&reference, AtomSelection::Backbone, options)?;

// Per-residue LDDT for quality analysis
let per_res = model.per_residue_lddt_to(&reference)?;
for r in per_res.iter().filter(|r| r.score < 0.7) {
    println!("Low LDDT: {}{} = {:.2}", r.residue_id.0, r.residue_id.1, r.score);
}
```

**LDDT vs RMSD:**
- **LDDT** is superposition-free (invariant to rotation/translation)
- **RMSD** requires alignment for meaningful comparison
- LDDT focuses on local distance preservation (default 15Å radius)
- LDDT uses 4 thresholds: 0.5Å, 1.0Å, 2.0Å, 4.0Å
- LDDT is used in AlphaFold (pLDDT) and CASP evaluations

### Secondary Structure (feature: dssp)
```rust
// Compute DSSP-like secondary structure assignment
let ss = structure.assign_secondary_structure();

// Get summary statistics
println!("Helix: {:.1}%", ss.helix_fraction * 100.0);
println!("Sheet: {:.1}%", ss.sheet_fraction * 100.0);
println!("Coil:  {:.1}%", ss.coil_fraction * 100.0);

// Get as compact string (e.g., "HHHHEEEECCCC")
let ss_string = structure.secondary_structure_string();

// Get composition tuple (helix, sheet, coil)
let (helix, sheet, coil) = structure.secondary_structure_composition();

// Iterate over per-residue assignments
for res in &ss.residue_assignments {
    println!("{}{}: {} ({})",
        res.chain_id, res.residue_seq, res.residue_name, res.ss.code());
}
```

**Secondary Structure Codes (DSSP 4):**
- `H`: α-helix (i → i+4 H-bond pattern)
- `G`: 3₁₀-helix (i → i+3 H-bond pattern)
- `I`: π-helix (i → i+5 H-bond pattern)
- `P`: κ-helix/PPII (polyproline II, dihedral-based)
- `E`: Extended strand (β-sheet)
- `B`: Isolated β-bridge
- `T`: Hydrogen-bonded turn
- `S`: Bend (high backbone curvature)
- `C`: Coil (none of the above)

### Ligand Pose Quality (feature: ligand-quality)
```rust
use pdbrust::PdbStructure;

// Check quality of a specific ligand pose
if let Some(report) = structure.ligand_pose_quality("LIG") {
    println!("Ligand: {} ({}{})",
             report.ligand_name, report.ligand_chain_id, report.ligand_residue_seq);

    // Steric clash detection
    println!("Clashes: {}", report.num_clashes);
    if report.has_protein_clash {
        println!("WARNING: {} clashes detected", report.num_clashes);
        for clash in &report.clashes {
            println!("  {:.2}Å < expected {:.2}Å",
                     clash.distance, clash.expected_min_distance);
        }
    }

    // Volume overlap check (PoseBusters threshold: <7.5%)
    println!("Volume overlap: {:.1}%", report.protein_volume_overlap_pct);

    // Overall verdict
    if report.is_geometry_valid {
        println!("Pose passes geometry checks");
    }
}

// Check all ligands at once
let reports = structure.all_ligand_pose_quality();
for report in &reports {
    let status = if report.is_geometry_valid { "PASS" } else { "FAIL" };
    println!("{}: {}", report.ligand_name, status);
}

// Get list of ligands (excluding water)
let ligands = structure.get_ligand_names();
println!("Found {} ligands: {:?}", ligands.len(), ligands);
```

**PoseBusters-style checks:**
- **Distance check**: Detects atom pairs closer than 0.75 × sum of van der Waals radii
- **Volume overlap**: Calculates percentage of ligand volume overlapping with protein (<7.5% threshold)
- **Cofactor clashes**: Checks for clashes with other HETATM atoms

**VdW radii functions:**
```rust
use pdbrust::ligand_quality::{vdw_radius, covalent_radius};

let r_carbon = vdw_radius("C");    // 1.70 Å
let r_oxygen = vdw_radius("O");    // 1.52 Å
let r_cov = covalent_radius("FE"); // 1.52 Å
```

### DockQ Interface Quality (feature: dockq)
```rust
use pdbrust::PdbStructure;
use pdbrust::dockq::{DockQOptions, ChainMappingStrategy};

// Compute DockQ with automatic chain mapping
let result = model.dockq_to(&native)?;
println!("DockQ: {:.4} ({} interfaces)", result.total_dockq, result.num_interfaces);

for iface in &result.interfaces {
    println!("Interface {}-{}: DockQ={:.3} fnat={:.3} iRMSD={:.2} LRMSD={:.2} ({})",
        iface.native_chains.0, iface.native_chains.1,
        iface.dockq, iface.fnat, iface.irmsd, iface.lrmsd, iface.quality);
}

// With explicit chain mapping
let options = DockQOptions {
    chain_mapping: ChainMappingStrategy::Explicit(vec![
        ("A".to_string(), "A".to_string()),
        ("B".to_string(), "B".to_string()),
    ]),
    ..Default::default()
};
let result = model.dockq_to_with_options(&native, options)?;
```

**DockQ score components:**
- **fnat**: Fraction of native contacts (heavy atoms within 5.0 A)
- **iRMSD**: Interface RMSD (backbone atoms at interface, within 10.0 A)
- **LRMSD**: Ligand RMSD (smaller chain RMSD after receptor alignment)
- **DockQ** = (fnat + 1/(1+(iRMSD/1.5)^2) + 1/(1+(LRMSD/8.5)^2)) / 3

**Quality classification:**
- Incorrect: DockQ < 0.23
- Acceptable: 0.23 <= DockQ < 0.49
- Medium: 0.49 <= DockQ < 0.80
- High: DockQ >= 0.80

## Examples

The `examples/` directory contains runnable examples demonstrating common workflows:

| Example | Features Required | Description |
|---------|-------------------|-------------|
| `analysis_workflow.rs` | filter, descriptors, quality, summary | Complete pipeline: load → clean → analyze → export |
| `filtering_demo.rs` | filter | Fluent filtering API, method chaining, in-place modifications |
| `selection_demo.rs` | filter | PyMOL/VMD-style selection language: chain A and name CA |
| `geometry_demo.rs` | geometry | RMSD calculation, Kabsch alignment, per-residue RMSD |
| `lddt_demo.rs` | geometry | LDDT calculation (superposition-free), per-residue LDDT |
| `ligand_quality_demo.rs` | ligand-quality | PoseBusters-style ligand pose validation |
| `dockq_demo.rs` | dockq | DockQ v2 interface quality assessment |
| `rcsb_workflow.rs` | rcsb, descriptors | RCSB search queries, download, analyze (requires network) |
| `async_download_demo.rs` | rcsb-async, descriptors | Concurrent bulk downloads with rate limiting |
| `batch_processing.rs` | descriptors, summary | Process multiple files, compute summaries, export CSV |
| `full_pdb_benchmark.rs` | gzip, parallel, descriptors, quality, summary | Full PDB archive benchmark (230K structures) |
| `read_pdb.rs` | (none) | Basic PDB file reading and structure inspection |
| `write_pdb.rs` | (none) | Creating and writing PDB files |
| `basic_usage.rs` | (none) | Creating structures programmatically |
| `atom_interactive.rs` | (none) | Atom operations, distances, angles |
| `rust_benchmark.rs` | filter, descriptors | Performance benchmarking |

### Python Examples

The `pdbrust-python/examples/` directory contains Python examples:

| Example | Description |
|---------|-------------|
| `basic_usage.py` | Parsing, accessing atoms/residues, basic filtering |
| `writing_files.py` | Write PDB/mmCIF files, round-trip demonstration |
| `geometry_rmsd.py` | RMSD calculation, structure alignment, per-residue RMSD |
| `lddt_demo.py` | LDDT calculation (superposition-free), per-residue LDDT analysis |
| `numpy_integration.py` | Coordinate arrays, distance matrices, contact maps |
| `rcsb_search.py` | RCSB search queries and structure downloads |
| `selection_language.py` | PyMOL/VMD-style selection language with boolean operators |
| `secondary_structure.py` | DSSP secondary structure assignment and analysis |
| `b_factor_analysis.py` | B-factor statistics, flexible/rigid residues, normalization |
| `alphafold_analysis.py` | AlphaFold pLDDT confidence scores, disordered regions |
| `ramachandran_analysis.py` | Phi/Psi dihedrals, Ramachandran validation, H-bond network |
| `ligand_interactions.py` | Protein-ligand binding sites, H-bonds, salt bridges |
| `quality_and_summary.py` | Quality reports, structure summaries, CSV export |
| `batch_processing.py` | Process multiple files, quality filtering, dataset statistics |
| `advanced_filtering.py` | Method chaining, normalization, centering, translation |
| `dockq_demo.py` | DockQ v2 interface quality assessment |

Run Python examples:
```bash
cd pdbrust-python/examples
python basic_usage.py
python geometry_rmsd.py
python numpy_integration.py
python selection_language.py
python secondary_structure.py
python b_factor_analysis.py
python alphafold_analysis.py
python ramachandran_analysis.py
python ligand_interactions.py
```

### Running Rust Examples
```bash
# Complete analysis workflow
cargo run --example analysis_workflow --features "filter,descriptors,quality,summary"

# Filtering operations
cargo run --example filtering_demo --features "filter"

# Geometry: RMSD and alignment
cargo run --example geometry_demo --features "geometry"

# DockQ interface quality
cargo run --example dockq_demo --features "dockq"

# RCSB search and download
cargo run --example rcsb_workflow --features "rcsb,descriptors"

# Async bulk downloads
cargo run --example async_download_demo --features "rcsb-async,descriptors"

# Batch processing
cargo run --example batch_processing --features "descriptors,summary"

# Full PDB archive benchmark
cargo run --release --example full_pdb_benchmark \
    --features "gzip,parallel,descriptors,quality,summary" \
    -- /path/to/pdb/archive --output-dir ./benchmark_results

# Basic file reading
cargo run --example read_pdb -- examples/pdb_files/1UBQ.pdb
```

## File Structure Notes

- Test PDB files: `examples/pdb_files/`
- Examples: `examples/`
- Documentation: `docs/GETTING_STARTED.md`
- Benchmarks: `benchmarks/`
- MSRV: 1.85.0
- CI: Ubuntu, Windows, macOS + stable, MSRV

## Performance Notes

Rust vs Python benchmarks show:
- Parsing: 2-3x faster
- In-memory operations: 40-270x faster
- O(n²) operations (max_ca_distance): 260x faster

The speedup comes from:
1. Parse once, reuse structure (Python re-parses each call)
2. Zero-cost abstractions
3. No GIL
4. CPU cache locality

### Full PDB Archive Validation

PDBRust has been validated against the entire Protein Data Bank (230,655 structures):

| Metric | Value |
|--------|-------|
| Total Structures | 230,655 |
| Success Rate | 100% |
| Failed Parses | 0 |
| Total Atoms Parsed | 2,057,302,767 |
| Processing Rate | ~92 files/sec (128 threads) |
| Largest Structure | 2ku2 (1,290,100 atoms) |
| Smallest Structure | 5zmz (31 atoms) |

Results are stored in `benchmark_results/` directory.

## Python Bindings

The Python package is published to PyPI as `pdbrust`. It uses PyO3 for Rust-Python bindings and Maturin for building.

### Python Development Commands

```bash
# Install maturin
pip install maturin

# Build and install in development mode
cd pdbrust-python
maturin develop --release

# Build wheel for distribution
maturin build --release

# Publish to PyPI (requires MATURIN_PYPI_TOKEN or ~/.pypirc)
maturin publish --no-sdist
```

### Python Package Features

All features are enabled by default in the Python package:
- Parsing: PDB, mmCIF, gzip-compressed files
- Filtering: remove_ligands, keep_only_chain, keep_only_ca, etc.
- Descriptors: radius_of_gyration, max_ca_distance, aa_composition, B-factor analysis
- B-factor: b_factor_mean, b_factor_profile, flexible_residues, normalize_b_factors
- Quality: quality_report, has_altlocs, has_multiple_models
- RCSB: download_structure, rcsb_search with SearchQuery
- Numpy: get_coords_array, get_ca_coords_array (returns numpy.ndarray)
- DSSP: assign_secondary_structure, secondary_structure_string, secondary_structure_composition

### Python API Pattern

```python
import pdbrust
import numpy as np

# Parse
structure = pdbrust.parse_pdb_file("protein.pdb")

# Filter (method chaining)
cleaned = structure.remove_ligands().keep_only_chain("A")

# Descriptors
rg = structure.radius_of_gyration()
desc = structure.structure_descriptors()

# Numpy arrays (efficient coordinate access)
coords = structure.get_coords_array()        # Shape: (N, 3)
ca_coords = structure.get_ca_coords_array()  # Shape: (CA, 3)

# RCSB
from pdbrust import download_structure, FileFormat, SearchQuery, rcsb_search
structure = download_structure("1UBQ", FileFormat.pdb())
results = rcsb_search(SearchQuery().with_text("kinase"), 10)

# Secondary structure (DSSP)
ss = structure.assign_secondary_structure()
print(f"Helix: {ss.helix_fraction*100:.1f}%")
print(f"Sheet: {ss.sheet_fraction*100:.1f}%")
ss_string = structure.secondary_structure_string()  # e.g., "HHHHEEEECCCC"

# B-factor analysis
mean_b = structure.b_factor_mean()
profile = structure.b_factor_profile()
flexible = structure.flexible_residues(50.0)
print(f"Mean B-factor: {mean_b:.2f} Ų")
print(f"Found {len(flexible)} flexible residues")
```

### CI/CD for Python

The `.github/workflows/python-publish.yml` workflow:
- Builds wheels for Linux (x86_64, aarch64), macOS (x86_64, aarch64), Windows (x64)
- Supports Python 3.9, 3.10, 3.11, 3.12
- Automatically publishes to PyPI on version tags (v*)
- Uses PyPI trusted publishing (no token needed in CI)

### Releasing a New Version

**IMPORTANT:** Always update CHANGELOG.md before releasing!

1. **Update CHANGELOG.md** with new version entry:
   - Move items from `[Unreleased]` to new version section
   - Follow [Keep a Changelog]https://keepachangelog.com/ format
   - Include: Added, Changed, Fixed, etc. sections as needed

2. **Update version numbers** in all files:
   - `Cargo.toml` (main library)
   - `pdbrust-python/Cargo.toml`
   - `pdbrust-python/pyproject.toml`
   - `pdbrust-python/python/pdbrust/__init__.py` (`__version__`)
   - `README.md` (version in dependency examples)

3. **Commit all changes**:
   ```bash
   git add -A
   git commit -m "chore: release vX.Y.Z"
   ```

4. **Wait for CI to pass** on the commit

5. **Create and push tag**:
   ```bash
   git tag vX.Y.Z
   git push origin main vX.Y.Z
   ```

6. **Publish to crates.io** (after GitHub Actions wheel builds pass):
   ```bash
   cargo publish
   ```

7. **Verify releases**:
   - Check https://crates.io/crates/pdbrust
   - Check https://pypi.org/project/pdbrust/
   - GitHub Actions will auto-publish to PyPI on tag push

### Zenodo Integration

PDBRust uses Zenodo for DOI-based academic citations. Once enabled, each GitHub release automatically gets archived with a unique DOI.

**Initial Setup (one-time):**
1. Go to https://zenodo.org and log in with GitHub
2. Navigate to Settings > GitHub
3. Enable the repository (HFooladi/pdbrust)
4. Create a GitHub release - Zenodo will automatically archive it

**After First Zenodo Release:**
1. Get your DOI from https://zenodo.org/account/settings/github/
2. Update `README.md`: uncomment and update the Zenodo badge with your DOI
3. Update `README.md`: uncomment and update the BibTeX citation with your DOI
4. Update `CITATION.cff`: add the `doi:` field with your DOI
5. Commit these changes

**Files for Zenodo:**
- `CITATION.cff` - Machine-readable citation metadata (GitHub recognizes this)
- `.zenodo.json` - Zenodo-specific metadata (keywords, related identifiers, etc.)

**Version-Specific vs Concept DOI:**
- Each release gets a unique version DOI (e.g., `10.5281/zenodo.1234567`)
- There's also a "concept DOI" that always resolves to the latest version
- Use the concept DOI in documentation for always-current citations