molframe-core 0.5.2

Core types, storage and analysis contracts for molframe
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
//! Declarative adapters from immutable structure snapshots to provider chunks.

use super::{
    BondChunk, ChunkDescriptor, ChunkId, DatasetDescriptor, DatasetId, FrameChunk, LogicalRow,
    PayloadKind, PropertyChunk, ProviderError, StructureChunk,
};
use crate::chunk::TARGET_CHUNK_ATOMS;
use crate::structure::Structure;
use std::sync::Arc;

/// Default maximum number of bonds independently requested in one payload.
pub const TARGET_CHUNK_BONDS: u32 = 65_536;

/// Zero-copy provider for regularly paged chemical bond topology.
#[derive(Clone, Debug)]
pub struct BondChunkProvider {
    structure: Structure,
    dataset: DatasetDescriptor,
    atom_dataset: DatasetId,
    atom_logical_start: LogicalRow,
}

impl BondChunkProvider {
    /// Creates a provider using the default bounded bond payload size.
    ///
    /// # Errors
    ///
    /// Rejects unavailable topology and identity or chunk-range overflow.
    pub fn new(
        dataset: DatasetId,
        first_chunk: ChunkId,
        atom_dataset: DatasetId,
        atom_logical_start: LogicalRow,
        structure: Structure,
    ) -> Result<Self, ProviderError> {
        Self::with_rows_per_chunk(
            dataset,
            first_chunk,
            atom_dataset,
            atom_logical_start,
            structure,
            TARGET_CHUNK_BONDS,
        )
    }

    /// Creates a provider with an explicit bounded payload row count.
    ///
    /// # Errors
    ///
    /// Rejects zero chunk rows, unavailable topology, or identity overflow.
    pub fn with_rows_per_chunk(
        dataset: DatasetId,
        first_chunk: ChunkId,
        atom_dataset: DatasetId,
        atom_logical_start: LogicalRow,
        structure: Structure,
        rows_per_chunk: u32,
    ) -> Result<Self, ProviderError> {
        if !structure.data().bonds.is_available() {
            return Err(ProviderError::BondTopologyUnavailable);
        }
        validate_atom_endpoint_range(atom_dataset, atom_logical_start, structure.atom_count())?;
        let logical_rows = u64::try_from(structure.data().bonds.len()).map_err(|_| {
            ProviderError::IdentityOverflow {
                dataset,
                field: "bond table rows",
            }
        })?;
        let descriptor = DatasetDescriptor::regular(
            dataset,
            PayloadKind::BondTopology,
            logical_rows,
            rows_per_chunk,
            first_chunk,
        )?;
        Ok(Self {
            structure,
            dataset: descriptor,
            atom_dataset,
            atom_logical_start,
        })
    }

    /// Compact dataset metadata; no per-chunk index is retained.
    #[must_use]
    pub const fn dataset(&self) -> DatasetDescriptor {
        self.dataset
    }

    /// Produces one shared topology payload in O(1), without a table scan.
    ///
    /// # Errors
    ///
    /// Rejects chunk identities outside this provider or source index overflow.
    pub fn chunk(&self, chunk: ChunkId) -> Result<BondChunk, ProviderError> {
        let descriptor = self.dataset.regular_chunk(chunk)?;
        let start = u32::try_from(descriptor.logical_start().get()).map_err(|_| {
            ProviderError::IdentityOverflow {
                dataset: self.dataset.id(),
                field: "bond source row",
            }
        })?;
        let end = start
            .checked_add(descriptor.rows())
            .ok_or(ProviderError::IdentityOverflow {
                dataset: self.dataset.id(),
                field: "bond source range",
            })?;
        BondChunk::shared(
            descriptor,
            self.structure.clone(),
            start..end,
            self.atom_dataset,
            self.atom_logical_start,
        )
    }
}

fn validate_atom_endpoint_range(
    dataset: DatasetId,
    first: LogicalRow,
    rows: u32,
) -> Result<(), ProviderError> {
    if rows == 0 {
        return Ok(());
    }
    first
        .get()
        .checked_add(u64::from(rows - 1))
        .map(|_| ())
        .ok_or(ProviderError::IdentityOverflow {
            dataset,
            field: "atom endpoint range",
        })
}

/// Zero-copy provider for structure chunks already present in one snapshot.
#[derive(Clone, Debug)]
pub struct StructureChunkProvider {
    structure: Structure,
    dataset: DatasetDescriptor,
}

impl StructureChunkProvider {
    /// Creates a provider whose chunk namespace begins at `first_chunk`.
    ///
    /// # Errors
    ///
    /// Returns a typed error when chunk count or identity arithmetic overflows.
    pub fn new(
        dataset: DatasetId,
        first_chunk: ChunkId,
        structure: Structure,
    ) -> Result<Self, ProviderError> {
        let chunk_count = u64::try_from(structure.data().chunks.len()).map_err(|_| {
            ProviderError::IdentityOverflow {
                dataset,
                field: "structure chunk count",
            }
        })?;
        let descriptor = DatasetDescriptor::source_defined(
            dataset,
            PayloadKind::Structure,
            u64::from(structure.atom_count()),
            chunk_count,
            first_chunk,
            TARGET_CHUNK_ATOMS,
        )?;
        Ok(Self {
            structure,
            dataset: descriptor,
        })
    }

    /// Compact dataset metadata.
    #[must_use]
    pub const fn dataset(&self) -> DatasetDescriptor {
        self.dataset
    }

    /// Produces one shared structure payload in constant time.
    ///
    /// # Errors
    ///
    /// Rejects chunk identities outside this provider.
    pub fn chunk(&self, chunk: ChunkId) -> Result<StructureChunk, ProviderError> {
        let ordinal = self.dataset.chunk_ordinal(chunk)?;
        let index = usize::try_from(ordinal).map_err(|_| ProviderError::IdentityOverflow {
            dataset: self.dataset.id(),
            field: "storage chunk index",
        })?;
        let storage = self
            .structure
            .data()
            .chunks
            .get(index)
            .ok_or(ProviderError::StorageChunkUnavailable { index })?;
        let descriptor = ChunkDescriptor::new(
            self.dataset.id(),
            chunk,
            super::LogicalRow::new(u64::from(storage.atoms().start)),
            storage.len(),
        )?;
        StructureChunk::shared(descriptor, self.structure.clone(), index)
    }
}

/// Zero-copy provider for one typed atom property.
#[derive(Clone, Debug)]
pub struct PropertyChunkProvider {
    structure: Structure,
    name: Arc<str>,
    dataset: DatasetDescriptor,
}

impl PropertyChunkProvider {
    /// Creates a provider for the canonical atom-aligned pLDDT confidence column.
    ///
    /// # Errors
    ///
    /// Rejects structures without lowered pLDDT, row misalignment, or identity overflow.
    pub fn plddt(
        dataset: DatasetId,
        first_chunk: ChunkId,
        structure: Structure,
    ) -> Result<Self, ProviderError> {
        Self::new(
            dataset,
            first_chunk,
            structure,
            crate::annotation::PLDDT_ANNOTATION,
        )
    }

    /// Creates a property provider over the structure's existing chunk layout.
    ///
    /// # Errors
    ///
    /// Rejects absent properties, row misalignment, or identity overflow.
    pub fn new(
        dataset: DatasetId,
        first_chunk: ChunkId,
        structure: Structure,
        name: impl Into<Arc<str>>,
    ) -> Result<Self, ProviderError> {
        let name = name.into();
        let property = structure.annotations().get(&name).ok_or_else(|| {
            ProviderError::PropertyUnavailable {
                name: Box::from(name.as_ref()),
            }
        })?;
        if property.len() != structure.atom_count() {
            return Err(ProviderError::PropertyLengthMismatch {
                name: Box::from(name.as_ref()),
                expected: structure.atom_count(),
                actual: property.len(),
            });
        }
        let chunk_count = u64::try_from(structure.data().chunks.len()).map_err(|_| {
            ProviderError::IdentityOverflow {
                dataset,
                field: "property chunk count",
            }
        })?;
        let descriptor = DatasetDescriptor::source_defined(
            dataset,
            PayloadKind::Property,
            u64::from(structure.atom_count()),
            chunk_count,
            first_chunk,
            TARGET_CHUNK_ATOMS,
        )?;
        Ok(Self {
            structure,
            name,
            dataset: descriptor,
        })
    }

    /// Compact dataset metadata.
    #[must_use]
    pub const fn dataset(&self) -> DatasetDescriptor {
        self.dataset
    }

    /// Produces one property payload without copying its values.
    ///
    /// # Errors
    ///
    /// Rejects chunk identities outside this provider.
    pub fn chunk(&self, chunk: ChunkId) -> Result<PropertyChunk, ProviderError> {
        let ordinal = self.dataset.chunk_ordinal(chunk)?;
        let index = usize::try_from(ordinal).map_err(|_| ProviderError::IdentityOverflow {
            dataset: self.dataset.id(),
            field: "storage chunk index",
        })?;
        let storage = self
            .structure
            .data()
            .chunks
            .get(index)
            .ok_or(ProviderError::StorageChunkUnavailable { index })?;
        let descriptor = ChunkDescriptor::new(
            self.dataset.id(),
            chunk,
            super::LogicalRow::new(u64::from(storage.atoms().start)),
            storage.len(),
        )?;
        PropertyChunk::shared(
            descriptor,
            self.structure.clone(),
            Arc::clone(&self.name),
            index,
        )
    }
}

/// Zero-copy provider for one coordinate frame over an existing chunk layout.
#[derive(Clone, Debug)]
pub struct FrameChunkProvider {
    structure: Structure,
    model: crate::ModelIndex,
    storage_chunks: std::ops::Range<usize>,
    dataset: DatasetDescriptor,
}

impl FrameChunkProvider {
    /// Creates a frame provider for one directly stored model.
    ///
    /// # Errors
    ///
    /// Rejects ragged or absent model storage and identity overflow.
    pub fn new(
        dataset: DatasetId,
        first_chunk: ChunkId,
        structure: Structure,
        model: crate::ModelIndex,
    ) -> Result<Self, ProviderError> {
        let Some(coordinates) = structure.data().coords.block(model) else {
            return Err(ProviderError::ModelUnavailable { model: model.get() });
        };
        let storage_chunks = model_chunk_range(&structure, model);
        let chunk_count =
            u64::try_from(storage_chunks.len()).map_err(|_| ProviderError::IdentityOverflow {
                dataset,
                field: "frame chunk count",
            })?;
        let descriptor = DatasetDescriptor::source_defined(
            dataset,
            PayloadKind::Frame,
            u64::from(coordinates.len()),
            chunk_count,
            first_chunk,
            TARGET_CHUNK_ATOMS,
        )?;
        Ok(Self {
            structure,
            model,
            storage_chunks,
            dataset: descriptor,
        })
    }

    /// Compact dataset metadata.
    #[must_use]
    pub const fn dataset(&self) -> DatasetDescriptor {
        self.dataset
    }

    /// Produces one coordinate payload sharing the frame's aligned storage.
    ///
    /// # Errors
    ///
    /// Rejects chunk identities outside this provider or inconsistent models.
    pub fn chunk(&self, chunk: ChunkId) -> Result<FrameChunk, ProviderError> {
        let ordinal = self.dataset.chunk_ordinal(chunk)?;
        let local = usize::try_from(ordinal).map_err(|_| ProviderError::IdentityOverflow {
            dataset: self.dataset.id(),
            field: "storage chunk index",
        })?;
        let index = self.storage_chunks.start.checked_add(local).ok_or(
            ProviderError::IdentityOverflow {
                dataset: self.dataset.id(),
                field: "storage chunk index",
            },
        )?;
        if index >= self.storage_chunks.end {
            return Err(ProviderError::UnknownChunk {
                dataset: self.dataset.id(),
                chunk,
            });
        }
        let storage = &self.structure.data().chunks[index];
        let range = storage.atoms();
        let descriptor = ChunkDescriptor::new(
            self.dataset.id(),
            chunk,
            super::LogicalRow::new(u64::from(range.start)),
            storage.len(),
        )?;
        let coordinates = self
            .structure
            .data()
            .coords
            .block(self.model)
            .cloned()
            .ok_or(ProviderError::ModelUnavailable {
                model: self.model.get(),
            })?;
        FrameChunk::shared(descriptor, coordinates, range)
    }
}

fn model_chunk_range(structure: &Structure, model: crate::ModelIndex) -> std::ops::Range<usize> {
    let chunks = structure.data().chunks.as_slice();
    let start = chunks.partition_point(|chunk| chunk.model() < model.get());
    let end = chunks.partition_point(|chunk| chunk.model() <= model.get());
    start..end
}

#[cfg(test)]
#[path = "source_tests.rs"]
mod tests;

#[cfg(test)]
#[path = "bond_source_tests.rs"]
mod bond_tests;