1use super::envelope::*;
8use super::types::*;
9
10pub const ELASTIC_RECORD_STRIDE: u32 = 64;
11
12pub const ELASTIC_VALID_VELOCITY: u32 = 1 << 0;
13pub const ELASTIC_VALID_STRESS: u32 = 1 << 1;
14pub const ELASTIC_VALID_DISPLACEMENT: u32 = 1 << 2;
15pub const ELASTIC_VALID_ALL: u32 =
16 ELASTIC_VALID_VELOCITY | ELASTIC_VALID_STRESS | ELASTIC_VALID_DISPLACEMENT;
17
18#[derive(Debug, Clone, Copy, PartialEq)]
20pub struct CauchyStress6 {
21 pub xx: f64,
22 pub yy: f64,
23 pub zz: f64,
24 pub xy: f64,
25 pub yz: f64,
26 pub xz: f64,
27}
28
29impl CauchyStress6 {
30 pub const ZERO: Self = Self {
31 xx: 0.0,
32 yy: 0.0,
33 zz: 0.0,
34 xy: 0.0,
35 yz: 0.0,
36 xz: 0.0,
37 };
38
39 pub fn from_wire_f32(s: [f32; 6]) -> Self {
40 Self {
41 xx: f64::from(s[0]),
42 yy: f64::from(s[1]),
43 zz: f64::from(s[2]),
44 xy: f64::from(s[3]),
45 yz: f64::from(s[4]),
46 xz: f64::from(s[5]),
47 }
48 }
49
50 pub fn to_wire_f32(self) -> [f32; 6] {
51 [
52 self.xx as f32,
53 self.yy as f32,
54 self.zz as f32,
55 self.xy as f32,
56 self.yz as f32,
57 self.xz as f32,
58 ]
59 }
60
61 pub fn hydrostatic_pressure_pa(self) -> f64 {
63 -(self.xx + self.yy + self.zz) / 3.0
64 }
65
66 pub fn deviatoric(self) -> Self {
67 let p = self.hydrostatic_pressure_pa();
68 Self {
69 xx: self.xx + p,
70 yy: self.yy + p,
71 zz: self.zz + p,
72 xy: self.xy,
73 yz: self.yz,
74 xz: self.xz,
75 }
76 }
77
78 pub fn rotate(self, q: &QuaternionXyzw) -> Self {
80 let out = q.rotate_symmetric_tensor6([self.xx, self.yy, self.zz, self.xy, self.yz, self.xz]);
81 Self {
82 xx: out[0],
83 yy: out[1],
84 zz: out[2],
85 xy: out[3],
86 yz: out[4],
87 xz: out[5],
88 }
89 }
90
91 pub fn traction_pa(self, n: [f64; 3]) -> [f64; 3] {
93 [
94 self.xx * n[0] + self.xy * n[1] + self.xz * n[2],
95 self.xy * n[0] + self.yy * n[1] + self.yz * n[2],
96 self.xz * n[0] + self.yz * n[1] + self.zz * n[2],
97 ]
98 }
99
100 pub fn from_isotropic_tensor_strain(lambda: f64, mu: f64, eps: [f64; 6]) -> Self {
102 let trace = eps[0] + eps[1] + eps[2];
103 Self {
104 xx: lambda * trace + 2.0 * mu * eps[0],
105 yy: lambda * trace + 2.0 * mu * eps[1],
106 zz: lambda * trace + 2.0 * mu * eps[2],
107 xy: 2.0 * mu * eps[3],
108 yz: 2.0 * mu * eps[4],
109 xz: 2.0 * mu * eps[5],
110 }
111 }
112
113 pub fn from_voigt_engineering_strain(lambda: f64, mu: f64, voigt: [f64; 6]) -> Self {
115 let eps = [
116 voigt[0],
117 voigt[1],
118 voigt[2],
119 0.5 * voigt[5],
120 0.5 * voigt[3],
121 0.5 * voigt[4],
122 ];
123 Self::from_isotropic_tensor_strain(lambda, mu, eps)
124 }
125}
126
127#[derive(Debug, Clone, Copy, PartialEq)]
129pub struct ElasticStressVelocityRecord {
130 pub velocity_m_s: [f32; 3],
131 pub material_ref: u32,
132 pub stress_xx_yy_zz_xy_yz_xz_pa: [f32; 6],
134 pub displacement_m: [f32; 3],
135 pub validity_bits: u32,
136}
137
138impl ElasticStressVelocityRecord {
139 pub fn stress(&self) -> CauchyStress6 {
140 CauchyStress6::from_wire_f32(self.stress_xx_yy_zz_xy_yz_xz_pa)
141 }
142
143 pub fn validate(&self, externally_valid: bool) -> Result<(), ProfileError> {
144 if self.velocity_m_s.iter().any(|v| !v.is_finite())
145 || self.stress_xx_yy_zz_xy_yz_xz_pa.iter().any(|v| !v.is_finite())
146 || self.displacement_m.iter().any(|v| !v.is_finite())
147 {
148 return Err(ProfileError::NonFiniteFloat);
149 }
150 if self.validity_bits & !ELASTIC_VALID_ALL != 0 {
151 return Err(ProfileError::InvalidValidityBits);
152 }
153 if !externally_valid {
154 if self.validity_bits != 0
155 || self.velocity_m_s.iter().any(|v| v.to_bits() != 0)
156 || self.stress_xx_yy_zz_xy_yz_xz_pa.iter().any(|v| v.to_bits() != 0)
157 || self.displacement_m.iter().any(|v| v.to_bits() != 0)
158 {
159 return Err(ProfileError::MaskedLaneNonZero);
160 }
161 return Ok(());
162 }
163 require_zero_vec3_when_masked((self.validity_bits & ELASTIC_VALID_VELOCITY) != 0, self.velocity_m_s)?;
164 let s_valid = (self.validity_bits & ELASTIC_VALID_STRESS) != 0;
165 for c in self.stress_xx_yy_zz_xy_yz_xz_pa {
166 require_zero_when_masked(s_valid, c)?;
167 }
168 require_zero_vec3_when_masked(
169 (self.validity_bits & ELASTIC_VALID_DISPLACEMENT) != 0,
170 self.displacement_m,
171 )?;
172 Ok(())
173 }
174
175 pub fn decode(bytes: &[u8], externally_valid: bool) -> Result<Self, ProfileError> {
176 if bytes.len() != ELASTIC_RECORD_STRIDE as usize {
177 return Err(ProfileError::InvalidPayloadLength);
178 }
179 ensure_zero_bytes(&bytes[56..64])?;
180 let rec = Self {
181 velocity_m_s: read_f32_3(bytes, 0)?,
182 material_ref: read_u32(bytes, 12)?,
183 stress_xx_yy_zz_xy_yz_xz_pa: read_f32_6(bytes, 16)?,
184 displacement_m: read_f32_3(bytes, 40)?,
185 validity_bits: read_u32(bytes, 52)?,
186 };
187 rec.validate(externally_valid)?;
188 Ok(rec)
189 }
190
191 pub fn encode_into(&self, out: &mut [u8], externally_valid: bool) -> Result<(), ProfileError> {
192 if out.len() != ELASTIC_RECORD_STRIDE as usize {
193 return Err(ProfileError::InvalidPayloadLength);
194 }
195 self.validate(externally_valid)?;
196 out.fill(0);
197 write_f32_slice(out, 0, &self.velocity_m_s)?;
198 write_u32(out, 12, self.material_ref);
199 write_f32_slice(out, 16, &self.stress_xx_yy_zz_xy_yz_xz_pa)?;
200 write_f32_slice(out, 40, &self.displacement_m)?;
201 write_u32(out, 52, self.validity_bits);
202 Ok(())
203 }
204}
205
206pub struct ElasticStressChunkView<'a> {
208 bytes: &'a [u8],
209 mask: Option<&'a [u8]>,
210}
211
212impl<'a> ElasticStressChunkView<'a> {
213 pub fn len(&self) -> usize {
214 self.bytes.len() / ELASTIC_RECORD_STRIDE as usize
215 }
216
217 pub fn is_empty(&self) -> bool {
218 self.bytes.is_empty()
219 }
220
221 pub fn get(&self, index: usize) -> Result<ElasticStressVelocityRecord, ProfileError> {
222 let start = index
223 .checked_mul(ELASTIC_RECORD_STRIDE as usize)
224 .ok_or(ProfileError::Overflow)?;
225 let end = start
226 .checked_add(ELASTIC_RECORD_STRIDE as usize)
227 .ok_or(ProfileError::Overflow)?;
228 let slice = self
229 .bytes
230 .get(start..end)
231 .ok_or(ProfileError::OutOfBoundsIndex("elastic record index"))?;
232 let ext_valid = self.mask.map_or(true, |m| m[index] != 0);
233 ElasticStressVelocityRecord::decode(slice, ext_valid)
234 }
235}
236
237#[derive(Debug, Clone, PartialEq)]
239pub enum ElasticMediumSpec {
240 Isotropic {
241 density_kg_m3: f64,
242 bulk_modulus_pa: f64,
243 shear_modulus_pa: f64,
244 matter_digest: Option<[u8; 32]>,
245 material_ids: Vec<u64>,
246 },
247 Anisotropic {
248 model_uri: String,
249 material_ids: Vec<u64>,
250 },
251 Poroelastic {
252 model_uri: String,
253 material_ids: Vec<u64>,
254 },
255 VacuumMask {
256 mask_entry_index: u32,
257 },
258 UnknownMedium,
259}
260
261impl ElasticMediumSpec {
262 pub fn steel() -> Self {
263 Self::Isotropic {
264 density_kg_m3: 7850.0,
265 bulk_modulus_pa: 160.0e9,
266 shear_modulus_pa: 80.0e9,
267 matter_digest: None,
268 material_ids: Vec::new(),
269 }
270 }
271
272 pub fn validate(&self) -> Result<(), ProfileError> {
273 match self {
274 Self::Isotropic {
275 density_kg_m3,
276 bulk_modulus_pa,
277 shear_modulus_pa,
278 ..
279 } => {
280 if !density_kg_m3.is_finite() || *density_kg_m3 <= 0.0 {
281 return Err(ProfileError::MediumMissingOrUnknown("density must be > 0"));
282 }
283 if !bulk_modulus_pa.is_finite() || *bulk_modulus_pa <= 0.0 {
284 return Err(ProfileError::MediumMissingOrUnknown("bulk_modulus must be > 0"));
285 }
286 if !shear_modulus_pa.is_finite() || *shear_modulus_pa < 0.0 {
287 return Err(ProfileError::MediumMissingOrUnknown("shear_modulus must be >= 0"));
288 }
289 Ok(())
290 }
291 Self::Anisotropic { model_uri, .. } | Self::Poroelastic { model_uri, .. } => {
292 validate_identifier_str(model_uri, "elastic.model_uri")
293 }
294 Self::VacuumMask { mask_entry_index } => {
295 if *mask_entry_index == 0 {
296 return Err(ProfileError::MediumMissingOrUnknown("vacuum mask entry must be >= 1"));
297 }
298 Ok(())
299 }
300 Self::UnknownMedium => Ok(()),
301 }
302 }
303
304 pub fn wave_speeds_m_s(&self) -> Result<(f64, f64), ProfileError> {
306 match self {
307 Self::Isotropic {
308 density_kg_m3,
309 bulk_modulus_pa,
310 shear_modulus_pa,
311 ..
312 } => {
313 self.validate()?;
314 let p_mod = bulk_modulus_pa + (4.0 / 3.0) * shear_modulus_pa;
315 Ok(((p_mod / density_kg_m3).sqrt(), (shear_modulus_pa / density_kg_m3).sqrt()))
316 }
317 Self::Anisotropic { .. } | Self::Poroelastic { .. } => {
318 Err(ProfileError::UnsupportedConstitutiveModel(
319 "isotropic (c_p, c_s) undefined for anisotropic/poroelastic medium without directional tensor profile",
320 ))
321 }
322 _ => Err(ProfileError::MediumMissingOrUnknown(
323 "wave speeds undefined in VacuumMask or UnknownMedium",
324 )),
325 }
326 }
327
328 pub fn lame_lambda_mu(&self) -> Result<(f64, f64), ProfileError> {
329 match self {
330 Self::Isotropic {
331 bulk_modulus_pa,
332 shear_modulus_pa,
333 ..
334 } => {
335 self.validate()?;
336 Ok((bulk_modulus_pa - (2.0 / 3.0) * shear_modulus_pa, *shear_modulus_pa))
337 }
338 _ => Err(ProfileError::UnsupportedConstitutiveModel("requires Isotropic elastic medium")),
339 }
340 }
341
342 fn push_schema_200(&self, meta: &mut MetadataBuilder, id: u32) -> Result<u32, ProfileError> {
343 self.validate()?;
344 let mut fields = Vec::new();
345 match self {
346 Self::Isotropic {
347 density_kg_m3,
348 bulk_modulus_pa,
349 shear_modulus_pa,
350 matter_digest,
351 material_ids,
352 } => {
353 fields.push(OwnedField::crit(
354 1,
355 OwnedValue::Utf8("elastic-isotropic".to_owned()),
356 ));
357 fields.push(OwnedField::crit(2, OwnedValue::F64(vec![*density_kg_m3])));
358 fields.push(OwnedField::crit(3, OwnedValue::F64(vec![*bulk_modulus_pa])));
359 fields.push(OwnedField::crit(4, OwnedValue::F64(vec![*shear_modulus_pa])));
360 if let Some(d) = matter_digest {
361 fields.push(OwnedField::opt(8, OwnedValue::Bytes(d.to_vec())));
362 }
363 if !material_ids.is_empty() {
364 fields.push(OwnedField::opt(11, OwnedValue::U64(material_ids.clone())));
365 }
366 }
367 Self::Anisotropic {
368 model_uri,
369 material_ids,
370 }
371 | Self::Poroelastic {
372 model_uri,
373 material_ids,
374 } => {
375 fields.push(OwnedField::crit(1, OwnedValue::Utf8(model_uri.clone())));
376 if !material_ids.is_empty() {
377 fields.push(OwnedField::opt(11, OwnedValue::U64(material_ids.clone())));
378 }
379 }
380 Self::VacuumMask { mask_entry_index } => {
381 fields.push(OwnedField::crit(
382 1,
383 OwnedValue::Utf8("vacuum-mask".to_owned()),
384 ));
385 fields.push(OwnedField::crit(
386 13,
387 OwnedValue::EntryRefs(vec![*mask_entry_index]),
388 ));
389 }
390 Self::UnknownMedium => {
391 fields.push(OwnedField::crit(
392 1,
393 OwnedValue::Utf8("unknown-medium".to_owned()),
394 ));
395 }
396 }
397 meta.push_block(OwnedBlock {
398 id,
399 schema_type: 200,
400 revision: 1,
401 critical: true,
402 fields,
403 })
404 }
405}
406
407pub fn normal_incidence_p_reflection_transmission(z1: f64, z2: f64) -> Result<(f64, f64), ProfileError> {
410 if !z1.is_finite() || !z2.is_finite() || z1 <= 0.0 || z2 <= 0.0 {
411 return Err(ProfileError::MediumMissingOrUnknown("impedances must be finite > 0"));
412 }
413 let r = (z2 - z1) / (z2 + z1);
414 let t = (2.0 * z2) / (z1 + z2);
415 Ok((r, t))
416}
417
418pub fn write_elastic_stress_qac(
420 records: &[ElasticStressVelocityRecord],
421 medium: &ElasticMediumSpec,
422 component_offsets_xyz: Option<&[f64]>,
423 clock: &ClockSpec,
424 sample_rate: RationalRate,
425 frame: &FrameSpec<'_>,
426 provenance: &ProvenanceSpec<'_>,
427 validity_mask: Option<&[u8]>,
428 limits: ProfileLimits,
429) -> Result<Vec<u8>, ProfileError> {
430 if records.is_empty() {
431 return Err(ProfileError::InvalidPayloadLength);
432 }
433 if matches!(medium, ElasticMediumSpec::VacuumMask { .. }) && validity_mask.is_none() {
434 return Err(ProfileError::MediumMissingOrUnknown(
435 "VacuumMask requires an accompanying validity_mask entry",
436 ));
437 }
438 if let Some(m) = validity_mask {
439 if m.len() != records.len() || m.iter().any(|&b| b > 1) {
440 return Err(ProfileError::InvalidValidityBits);
441 }
442 }
443 let mut payload = vec![0u8; records.len() * ELASTIC_RECORD_STRIDE as usize];
444 for (idx, rec) in records.iter().enumerate() {
445 let ext_valid = validity_mask.map_or(true, |m| m[idx] != 0);
446 let off = idx * ELASTIC_RECORD_STRIDE as usize;
447 rec.encode_into(&mut payload[off..off + ELASTIC_RECORD_STRIDE as usize], ext_valid)?;
448 }
449
450 let mut meta = MetadataBuilder::new();
451 meta.push_clock(1, clock)?;
452 meta.push_frame(2, frame)?;
453 meta.push_provenance(3, provenance)?;
454 medium.push_schema_200(&mut meta, 4)?;
455 let shape = [records.len() as u64];
456 meta.push_model_grid(
457 5,
458 &ModelGridSpec {
459 model_uri: "urn:qac:model:elastic-stress-velocity:v1",
460 model_version: "1",
461 discretization: Some("virieux-staggered-grid"),
462 component_offsets_xyz: component_offsets_xyz.unwrap_or(&[]),
463 component_time_offset_num: &[],
464 component_time_offset_den: &[],
465 timestep: Some(sample_rate),
466 tolerance_abs: Some(1e-5),
467 tolerance_rel: Some(1e-4),
468 tensor_shape: &shape,
469 component_names: "vx,vy,vz,sxx,syy,szz,sxy,syz,sxz",
470 },
471 )?;
472
473 let valid_count = validity_mask.map(|m| m.iter().filter(|&&b| b == 1).count() as u64);
474 let mask_entry_idx = if validity_mask.is_some() { Some(2) } else { None };
475 let ext = [5u32];
476 meta.push_descriptor(
477 6,
478 &DescriptorSpec {
479 clock_id: Some(1),
480 frame_id: Some(2),
481 provenance_id: 3,
482 medium_id: Some(4),
483 transform_id: None,
484 calibration_id: None,
485 quantity: "elastic-stress-velocity",
486 units: "mixed:mode-registry",
487 channels: None,
488 layout: None,
489 scalar: None,
490 model_uri: "urn:qac:mode:0x0001:v1",
491 sample_rate: Some(sample_rate),
492 valid_record_count: valid_count,
493 validity_mask_entry: mask_entry_idx,
494 source_entries: &[],
495 extension_metadata: &ext,
496 },
497 )?;
498
499 let mut entries = vec![OwnedEntry {
500 mode: MODE_ELASTIC_STRESS_VELOCITY,
501 flags: 3,
502 stream_id: 1,
503 frame_id: 2,
504 start_tick: 0,
505 time_count: 1,
506 spatial_key: 0,
507 record_count: records.len() as u64,
508 stride: ELASTIC_RECORD_STRIDE,
509 descriptor_id: 6,
510 payload,
511 }];
512 if let Some(mask) = validity_mask {
513 entries.push(push_validity_mask_entry(&mut meta, 7, 3, 1, 0, 1, mask)?);
514 }
515 assemble_qac_v1(&meta, &entries, limits)
516}
517
518pub struct ElasticStressView<'a> {
519 pub records: ElasticStressChunkView<'a>,
520 pub medium: ElasticMediumSpec,
521}
522
523pub fn read_elastic_stress_qac<'a>(
524 bytes: &'a [u8],
525 entry_index: u32,
526 limits: ProfileLimits,
527) -> Result<ElasticStressView<'a>, ProfileError> {
528 let env = AdmittedEnvelope::open_alloc(bytes, limits)?;
529 let (_e, desc, payload, mask) = env.check_structured_entry(
530 entry_index,
531 MODE_ELASTIC_STRESS_VELOCITY,
532 ELASTIC_RECORD_STRIDE,
533 true,
534 Some(205),
535 )?;
536 let med_id = field_u32(field_req(desc, 4)?)?;
537 let med_blk = env.block(med_id)?;
538 let model = field_str(field_req(med_blk, 1)?)?;
539 let medium = match model {
540 "elastic-isotropic" => ElasticMediumSpec::Isotropic {
541 density_kg_m3: field_f64(field_req(med_blk, 2)?)?,
542 bulk_modulus_pa: field_f64(field_req(med_blk, 3)?)?,
543 shear_modulus_pa: field_f64(field_req(med_blk, 4)?)?,
544 matter_digest: field_opt(med_blk, 8).map(field_bytes32).transpose()?,
545 material_ids: field_opt(med_blk, 11).map(field_u64_vec).transpose()?.unwrap_or_default(),
546 },
547 "vacuum-mask" => ElasticMediumSpec::VacuumMask {
548 mask_entry_index: field_u32(field_req(med_blk, 13)?)?,
549 },
550 "unknown-medium" => ElasticMediumSpec::UnknownMedium,
551 other if other.contains("poro") => ElasticMediumSpec::Poroelastic {
552 model_uri: other.to_owned(),
553 material_ids: field_opt(med_blk, 11).map(field_u64_vec).transpose()?.unwrap_or_default(),
554 },
555 other => ElasticMediumSpec::Anisotropic {
556 model_uri: other.to_owned(),
557 material_ids: field_opt(med_blk, 11).map(field_u64_vec).transpose()?.unwrap_or_default(),
558 },
559 };
560 let chunk = ElasticStressChunkView {
561 bytes: payload,
562 mask,
563 };
564 for i in 0..chunk.len() {
565 let _ = chunk.get(i)?;
566 }
567 Ok(ElasticStressView {
568 records: chunk,
569 medium,
570 })
571}