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
//! Immutable caller-supplied per-atom scalar properties and honest legends.
use crate::{AtomPropertyHandle, CoreError, ScalarFieldSemantics, StructureHandle};
use molgfx_math::Rgba8;
use std::sync::Arc;
#[cfg(test)]
#[path = "atom_property_tests.rs"]
mod tests;
/// Scientific interpretation of one scalar atom column.
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub enum AtomPropertyMeaning {
/// Caller-defined scalar with semantics carried by its name and units.
#[default]
Generic,
/// Confidence rank or calibrated confidence score, never an error radius.
Confidence,
/// Experimental/model occupancy.
Occupancy,
/// Caller-supplied local map resolution.
LocalResolution,
/// Caller-supplied flexibility such as RMSF or a B-factor rank.
Flexibility,
/// Charge or electrostatic scalar.
Charge,
/// Hydrophobicity scale named by provenance.
Hydrophobicity,
/// Solvent exposure or accessibility.
Exposure,
}
/// One immutable scalar value per source atom row.
#[derive(Clone, PartialEq, Debug)]
pub struct AtomProperty {
owner: StructureHandle,
name: Arc<str>,
values: Arc<[f32]>,
interpolated: Vec<f32>,
meaning: AtomPropertyMeaning,
semantics: ScalarFieldSemantics,
finite_domain: [f32; 2],
}
impl AtomProperty {
/// Creates a property without copying the caller's shared values.
///
/// NaN denotes a missing value and is retained; infinities are rejected.
/// Length is validated against the owning structure by
/// [`crate::Scene::add_atom_property`].
///
/// # Errors
///
/// Returns [`CoreError::InvalidProperty`] for an empty name, empty values,
/// infinity, or a column with no finite value.
pub fn new(
owner: StructureHandle,
name: impl Into<Arc<str>>,
values: Arc<[f32]>,
meaning: AtomPropertyMeaning,
semantics: ScalarFieldSemantics,
) -> Result<Self, CoreError> {
let name = name.into();
if name.trim().is_empty() || values.is_empty() {
return Err(invalid("property name and values must be non-empty"));
}
if values.iter().any(|value| value.is_infinite()) {
return Err(invalid(
"property values may be finite or missing NaN, never infinite",
));
}
let finite_domain = finite_domain(&values)
.ok_or_else(|| invalid("property must contain at least one finite value"))?;
Ok(Self {
owner,
name,
values,
interpolated: Vec::new(),
meaning,
semantics,
finite_domain,
})
}
/// Owning placed structure.
#[must_use]
pub const fn owner(&self) -> StructureHandle {
self.owner
}
/// Caller-defined property label.
#[must_use]
pub fn name(&self) -> &str {
&self.name
}
/// Shared values in source atom-row order.
#[must_use]
pub fn values(&self) -> &[f32] {
if self.interpolated.is_empty() {
&self.values
} else {
&self.interpolated
}
}
/// Original shared backing allocation retained without a copy.
///
/// [`Self::values`] returns the active interpolated row after temporal
/// updates; this method continues to expose the immutable source row so a
/// caller can verify the zero-copy handoff.
#[must_use]
pub fn shared_values(&self) -> &Arc<[f32]> {
&self.values
}
/// Interpolates two topology-aligned rows into reusable owned storage.
///
/// The first temporal update reserves one row. Later updates with the same
/// topology perform no allocation and cost `O(atoms)` time with `O(atoms)`
/// persistent storage.
pub(crate) fn interpolate_values(
&mut self,
start: &[f32],
end: &[f32],
alpha: f32,
) -> Result<(), CoreError> {
if start.iter().chain(end).any(|value| value.is_infinite()) {
return Err(invalid(
"property frame values may be finite or missing NaN, never infinite",
));
}
if !start
.iter()
.zip(end)
.any(|(&a, &b)| a.is_finite() && b.is_finite())
{
return Err(invalid(
"property interpolation must contain at least one finite pair",
));
}
self.interpolated.resize(start.len(), 0.0);
// Fixed block partition above the threshold, identical math per
// element either way — the interpolated column is the serial result
// byte for byte on any thread count.
molgfx_math::map_zip_blocks_into(
start,
end,
&mut self.interpolated,
molgfx_math::BLOCK,
|start, end, output| {
for ((output, &a), &b) in output.iter_mut().zip(start).zip(end) {
*output = if a.is_nan() || b.is_nan() {
f32::NAN
} else {
a.mul_add(1.0 - alpha, b * alpha)
};
}
},
);
let Some(domain) = finite_domain(&self.interpolated) else {
return Err(invalid(
"property interpolation must contain a finite result",
));
};
self.finite_domain = domain;
Ok(())
}
/// Reserves one temporal result row during track setup.
pub(crate) fn reserve_interpolation(&mut self) {
if self.interpolated.capacity() < self.values.len() {
self.interpolated
.reserve_exact(self.values.len().saturating_sub(self.interpolated.len()));
}
}
/// Scientific interpretation.
#[must_use]
pub const fn meaning(&self) -> AtomPropertyMeaning {
self.meaning
}
/// Rank or calibrated quantity metadata.
#[must_use]
pub const fn semantics(&self) -> &ScalarFieldSemantics {
&self.semantics
}
/// Minimum and maximum over finite values only.
#[must_use]
pub const fn finite_domain(&self) -> [f32; 2] {
self.finite_domain
}
/// Non-degenerate display domain used by reversible ramps.
#[must_use]
pub fn display_domain(&self) -> [f32; 2] {
let [low, high] = self.finite_domain;
if low < high {
[low, high]
} else {
[low - 0.5, high + 0.5]
}
}
/// Stable legend for a specific visual ramp.
#[must_use]
pub fn legend(&self, ramp: crate::ScalarRamp, missing: Rgba8) -> PropertyLegend {
PropertyLegend {
title: Arc::clone(&self.name),
semantics: self.semantics.clone(),
values: ramp.values(),
colors: ramp.colors(),
missing,
}
}
}
/// Reversible continuous legend emitted with a property encoding.
#[derive(Clone, PartialEq, Debug)]
pub struct PropertyLegend {
/// Display title.
pub title: Arc<str>,
/// Quantity/units/provenance or explicit uncalibrated rank.
pub semantics: ScalarFieldSemantics,
/// Numeric stops in scientific units.
pub values: [f32; 3],
/// CVD-safe colours at those stops.
pub colors: [Rgba8; 3],
/// Colour used for missing values.
pub missing: Rgba8,
}
/// Reversible scalar-to-opacity-and-edge-softness encoding.
///
/// This is an uncertainty presentation, not a spatial error model: it never
/// changes an atom radius or claims that softness is measured in Angstrom.
#[derive(Clone, Copy, PartialEq, Debug)]
pub struct PropertyAppearance {
/// Property column sampled in source atom-row order.
pub property: AtomPropertyHandle,
domain: [f32; 2],
opacity: [f32; 2],
softness_pixels: [f32; 2],
missing: PropertyAppearanceSample,
}
/// Resolved visual response for one property value.
#[derive(Clone, Copy, PartialEq, Debug)]
pub struct PropertyAppearanceSample {
/// Opacity multiplier in `[0, 1]`.
pub opacity: f32,
/// Analytic silhouette transition width in physical pixels.
pub softness_pixels: f32,
}
impl PropertyAppearance {
/// Returns all endpoint and missing-value responses for serialization.
#[must_use]
pub const fn description_values(self) -> ([f32; 2], [f32; 2], [f32; 2], [f32; 2]) {
(
self.domain,
self.opacity,
self.softness_pixels,
[self.missing.opacity, self.missing.softness_pixels],
)
}
/// Creates a monotonic, invertible appearance mapping.
///
/// # Errors
///
/// The scientific domain must increase, endpoints must be finite and in
/// range, and both visual channels must vary monotonically.
pub fn new(
property: AtomPropertyHandle,
domain: [f32; 2],
opacity: [f32; 2],
softness_pixels: [f32; 2],
missing: PropertyAppearanceSample,
) -> Result<Self, CoreError> {
let finite = domain
.into_iter()
.chain(opacity)
.chain(softness_pixels)
.chain([missing.opacity, missing.softness_pixels])
.all(f32::is_finite);
if !finite || domain[0] >= domain[1] {
return Err(invalid("appearance domain must be finite and increasing"));
}
if opacity
.into_iter()
.chain([missing.opacity])
.any(|value| !(0.0..=1.0).contains(&value))
{
return Err(invalid("appearance opacity must be within zero and one"));
}
if softness_pixels
.into_iter()
.chain([missing.softness_pixels])
.any(|value| !(0.0..=8.0).contains(&value))
{
return Err(invalid(
"appearance softness must be within zero and eight pixels",
));
}
if (opacity[0] - opacity[1]).abs() < f32::EPSILON
&& (softness_pixels[0] - softness_pixels[1]).abs() < f32::EPSILON
{
return Err(invalid(
"at least one appearance channel must encode the property",
));
}
Ok(Self {
property,
domain,
opacity,
softness_pixels,
missing,
})
}
/// Honest confidence-rank encoding: low values are diffuse and faint;
/// high values are crisp and opaque.
///
/// # Errors
///
/// The supplied display domain must be finite and increasing.
pub fn confidence(property: AtomPropertyHandle, domain: [f32; 2]) -> Result<Self, CoreError> {
Self::new(
property,
domain,
[0.28, 1.0],
[2.4, 0.0],
PropertyAppearanceSample {
opacity: 0.22,
softness_pixels: 2.8,
},
)
}
/// Flexibility-rank encoding: rigid values remain crisp while mobile
/// values become diffuse and less opaque.
///
/// # Errors
///
/// The supplied display domain must be finite and increasing.
pub fn flexibility(property: AtomPropertyHandle, domain: [f32; 2]) -> Result<Self, CoreError> {
Self::new(
property,
domain,
[1.0, 0.32],
[0.0, 2.2],
PropertyAppearanceSample {
opacity: 0.24,
softness_pixels: 2.6,
},
)
}
/// Scientific value interval represented by both visual channels.
#[must_use]
pub const fn domain(self) -> [f32; 2] {
self.domain
}
/// Resolves a finite value, clamped to the declared domain; NaN uses the
/// explicit missing response.
#[must_use]
pub fn sample(self, value: f32) -> PropertyAppearanceSample {
if !value.is_finite() {
return self.missing;
}
let parameter =
((value - self.domain[0]) / (self.domain[1] - self.domain[0])).clamp(0.0, 1.0);
PropertyAppearanceSample {
opacity: mix(self.opacity, parameter),
softness_pixels: mix(self.softness_pixels, parameter),
}
}
/// Recovers the represented scientific value from opacity when that
/// channel varies.
#[must_use]
pub fn value_from_opacity(self, opacity: f32) -> Option<f32> {
inverse(opacity, self.opacity, self.domain)
}
/// Recovers the represented scientific value from softness when that
/// channel varies.
#[must_use]
pub fn value_from_softness(self, softness_pixels: f32) -> Option<f32> {
inverse(softness_pixels, self.softness_pixels, self.domain)
}
/// True when any finite or missing sample can require alpha composition.
#[must_use]
pub fn is_translucent(self) -> bool {
self.opacity[0] < 1.0
|| self.opacity[1] < 1.0
|| self.missing.opacity < 1.0
|| self.softness_pixels[0] > 0.0
|| self.softness_pixels[1] > 0.0
|| self.missing.softness_pixels > 0.0
}
}
fn mix(range: [f32; 2], parameter: f32) -> f32 {
range[0] + parameter * (range[1] - range[0])
}
fn inverse(value: f32, visual: [f32; 2], domain: [f32; 2]) -> Option<f32> {
if !value.is_finite() || (visual[0] - visual[1]).abs() < f32::EPSILON {
return None;
}
let parameter = ((value - visual[0]) / (visual[1] - visual[0])).clamp(0.0, 1.0);
Some(mix(domain, parameter))
}
fn finite_domain(values: &[f32]) -> Option<[f32; 2]> {
let mut domain: Option<[f32; 2]> = None;
for &value in values.iter().filter(|value| value.is_finite()) {
domain = Some(match domain {
Some([low, high]) => [low.min(value), high.max(value)],
None => [value, value],
});
}
domain
}
const fn invalid(reason: &'static str) -> CoreError {
CoreError::InvalidProperty { reason }
}