amari-gpu 0.24.1

GPU acceleration for mathematical computations
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
//! GPU acceleration for relativistic physics computations
//!
//! This module provides GPU-accelerated implementations of relativistic physics
//! operations from amari-relativistic, including spacetime algebra operations
//! and a narrow Schwarzschild-style particle propagation kernel.
//!
//! The public v1 surface is GPU-backed but intentionally bounded: spacetime
//! vectors store coordinates as `(ct, x, y, z)`, Minkowski products compute
//! `ct² - x² - y² - z²`, and particle propagation uses a simplified GPU
//! geodesic step. Inputs are validated for finite values and basic parameter
//! consistency before dispatch.

use crate::GpuError;
use amari_relativistic::{particle::RelativisticParticle, spacetime::SpacetimeVector};
use bytemuck::{Pod, Zeroable};
use wgpu::util::DeviceExt;

/// GPU-accelerated spacetime vector operations using Cl(1,3) signature
#[repr(C)]
#[derive(Copy, Clone, Debug, Pod, Zeroable)]
pub struct GpuSpacetimeVector {
    /// Temporal component (`ct`, in length units)
    pub t: f32,
    /// Spatial x component
    pub x: f32,
    /// Spatial y component
    pub y: f32,
    /// Spatial z component
    pub z: f32,
}

impl GpuSpacetimeVector {
    /// Create new GPU spacetime vector
    pub fn new(t: f32, x: f32, y: f32, z: f32) -> Self {
        Self { t, x, y, z }
    }

    /// Convert from CPU spacetime vector, preserving coordinates `[ct, x, y, z]`.
    pub fn from_spacetime_vector(sv: &SpacetimeVector) -> Self {
        let coords = sv.coordinates();
        Self::new(
            coords[0] as f32,
            coords[1] as f32,
            coords[2] as f32,
            coords[3] as f32,
        )
    }

    /// Convert to CPU spacetime vector, interpreting `t` as `ct`.
    pub fn to_spacetime_vector(&self) -> SpacetimeVector {
        SpacetimeVector::from_coordinates([
            self.t as f64,
            self.x as f64,
            self.y as f64,
            self.z as f64,
        ])
    }

    fn is_finite(&self) -> bool {
        self.t.is_finite() && self.x.is_finite() && self.y.is_finite() && self.z.is_finite()
    }
}

/// GPU-accelerated relativistic particle for trajectory calculations
#[repr(C)]
#[derive(Copy, Clone, Debug, Pod, Zeroable)]
pub struct GpuRelativisticParticle {
    /// Spacetime position
    pub position: GpuSpacetimeVector,
    /// Four-velocity
    pub velocity: GpuSpacetimeVector,
    /// Rest mass
    pub mass: f32,
    /// Electric charge
    pub charge: f32,
    /// Proper time
    pub proper_time: f32,
    /// Padding for WGSL storage-buffer alignment (64-byte particle stride)
    pub _padding: [f32; 5],
}

/// GPU-accelerated trajectory calculation parameters
#[repr(C)]
#[derive(Copy, Clone, Debug, Pod, Zeroable)]
pub struct GpuTrajectoryParams {
    /// Integration time step
    pub dt: f32,
    /// Number of integration steps
    pub steps: u32,
    /// Normalization tolerance
    pub tolerance: f32,
    /// Renormalization frequency
    pub renorm_freq: u32,
    /// Schwarzschild radius (for gravitational fields)
    pub schwarzschild_radius: f32,
    /// Central mass parameter (GM)
    pub gm_parameter: f32,
    /// Padding for alignment
    pub _padding: [f32; 2],
}

/// GPU compute context for relativistic physics
pub struct GpuRelativisticPhysics {
    device: wgpu::Device,
    queue: wgpu::Queue,
    spacetime_pipeline: wgpu::ComputePipeline,
    geodesic_pipeline: wgpu::ComputePipeline,
    #[allow(dead_code)]
    trajectory_pipeline: wgpu::ComputePipeline,
}

impl GpuRelativisticPhysics {
    /// Initialize GPU context for relativistic physics computations
    pub async fn new() -> Result<Self, GpuError> {
        let instance = wgpu::Instance::default();

        let adapter = instance
            .request_adapter(&wgpu::RequestAdapterOptions::default())
            .await
            .ok_or_else(|| {
                GpuError::InitializationError("No suitable GPU adapter found".to_string())
            })?;

        let (device, queue) = adapter
            .request_device(
                &wgpu::DeviceDescriptor {
                    label: Some("Relativistic Physics GPU"),
                    required_features: wgpu::Features::empty(),
                    required_limits: wgpu::Limits::default(),
                },
                None,
            )
            .await
            .map_err(|e| {
                GpuError::InitializationError(format!("Failed to create device: {}", e))
            })?;

        // Compile compute shaders for different operations
        let spacetime_pipeline = Self::create_spacetime_pipeline(&device)?;
        let geodesic_pipeline = Self::create_geodesic_pipeline(&device)?;
        let trajectory_pipeline = Self::create_trajectory_pipeline(&device)?;

        Ok(Self {
            device,
            queue,
            spacetime_pipeline,
            geodesic_pipeline,
            trajectory_pipeline,
        })
    }

    /// Create compute pipeline for spacetime algebra operations
    fn create_spacetime_pipeline(device: &wgpu::Device) -> Result<wgpu::ComputePipeline, GpuError> {
        let shader_source = r#"
            @group(0) @binding(0) var<storage, read_write> vectors: array<vec4<f32>>;
            @group(0) @binding(1) var<storage, read_write> results: array<f32>;

            @compute @workgroup_size(64)
            fn main(@builtin(global_invocation_id) global_id: vec3<u32>) {
                let index = global_id.x;
                if (index >= arrayLength(&vectors)) {
                    return;
                }

                let v = vectors[index];

                // Minkowski inner product: t² - x² - y² - z²
                let minkowski_norm_sq = v.x * v.x - v.y * v.y - v.z * v.z - v.w * v.w;
                results[index] = minkowski_norm_sq;

                // Normalize four-velocity if needed (u·u = c²)
                let c_sq = 299792458.0 * 299792458.0;
                if (abs(minkowski_norm_sq - c_sq) > 1e-6) {
                    let norm = sqrt(abs(minkowski_norm_sq));
                    if (norm > 1e-12) {
                        let factor = sqrt(c_sq) / norm;
                        vectors[index] = vec4<f32>(v.x * factor, v.y * factor, v.z * factor, v.w * factor);
                    }
                }
            }
        "#;

        let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: Some("Spacetime Algebra Compute Shader"),
            source: wgpu::ShaderSource::Wgsl(shader_source.into()),
        });

        let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("Spacetime Bind Group Layout"),
            entries: &[
                wgpu::BindGroupLayoutEntry {
                    binding: 0,
                    visibility: wgpu::ShaderStages::COMPUTE,
                    ty: wgpu::BindingType::Buffer {
                        ty: wgpu::BufferBindingType::Storage { read_only: false },
                        has_dynamic_offset: false,
                        min_binding_size: None,
                    },
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 1,
                    visibility: wgpu::ShaderStages::COMPUTE,
                    ty: wgpu::BindingType::Buffer {
                        ty: wgpu::BufferBindingType::Storage { read_only: false },
                        has_dynamic_offset: false,
                        min_binding_size: None,
                    },
                    count: None,
                },
            ],
        });

        let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("Spacetime Pipeline Layout"),
            bind_group_layouts: &[&bind_group_layout],
            push_constant_ranges: &[],
        });

        Ok(
            device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
                label: Some("Spacetime Compute Pipeline"),
                layout: Some(&pipeline_layout),
                module: &shader,
                entry_point: "main",
            }),
        )
    }

    /// Create compute pipeline for geodesic integration
    fn create_geodesic_pipeline(device: &wgpu::Device) -> Result<wgpu::ComputePipeline, GpuError> {
        let shader_source = r#"
            struct Particle {
                position: vec4<f32>,
                velocity: vec4<f32>,
                mass: f32,
                charge: f32,
                proper_time: f32,
                padding: array<f32, 5>,
            };

            struct TrajectoryParams {
                dt: f32,
                steps: u32,
                tolerance: f32,
                renorm_freq: u32,
                rs: f32,
                gm: f32,
                padding: vec2<f32>,
            };

            @group(0) @binding(0) var<storage, read_write> particles: array<Particle>;
            @group(0) @binding(1) var<uniform> params: TrajectoryParams;

            // Schwarzschild metric Christoffel symbols (simplified)
            fn christoffel_t_rr(r: f32, rs: f32) -> f32 {
                let factor = rs / (2.0 * r * r);
                return factor * (1.0 - rs / r);
            }

            fn christoffel_r_tr(r: f32, rs: f32) -> f32 {
                return rs / (2.0 * r * r * (1.0 - rs / r));
            }

            fn christoffel_r_rr(r: f32, rs: f32) -> f32 {
                return -rs / (2.0 * r * (r - rs));
            }

            @compute @workgroup_size(64)
            fn main(@builtin(global_invocation_id) global_id: vec3<u32>) {
                let index = global_id.x;
                if (index >= arrayLength(&particles)) {
                    return;
                }

                var particle = particles[index];
                let pos = particle.position;
                let vel = particle.velocity;

                // Compute spatial radius
                let r = sqrt(pos.y * pos.y + pos.z * pos.z + pos.w * pos.w);

                if (r < params.rs * 1.1) {
                    // Too close to singularity, skip
                    return;
                }

                // Velocity Verlet step for geodesic equation
                // Simplified for Schwarzschild metric

                // Compute acceleration components
                let c_trr = christoffel_t_rr(r, params.rs);
                let c_rtr = christoffel_r_tr(r, params.rs);
                let c_rrr = christoffel_r_rr(r, params.rs);

                // Geodesic equation: d²x^μ/dτ² = -Γ^μ_αβ v^α v^β
                var accel = vec4<f32>(0.0, 0.0, 0.0, 0.0);

                // Simplified acceleration calculation
                accel.x = -c_trr * vel.y * vel.y; // dt component
                accel.y = -c_rtr * vel.x * vel.y - c_rrr * vel.y * vel.y; // dr component

                // Update position and velocity
                let dt = params.dt;
                particle.position = pos + vel * dt + 0.5 * accel * dt * dt;
                particle.velocity = vel + accel * dt;

                // Renormalize four-velocity periodically
                let step_mod = u32(particle.proper_time / dt) % params.renorm_freq;
                if (step_mod == 0u) {
                    let c_sq = 299792458.0 * 299792458.0;
                    let norm_sq = particle.velocity.x * particle.velocity.x -
                                  particle.velocity.y * particle.velocity.y -
                                  particle.velocity.z * particle.velocity.z -
                                  particle.velocity.w * particle.velocity.w;

                    if (abs(norm_sq - c_sq) > params.tolerance) {
                        let norm = sqrt(abs(norm_sq));
                        if (norm > 1e-12) {
                            let factor = sqrt(c_sq) / norm;
                            particle.velocity *= factor;
                        }
                    }
                }

                particle.proper_time += dt;
                particles[index] = particle;
            }
        "#;

        let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: Some("Geodesic Integration Compute Shader"),
            source: wgpu::ShaderSource::Wgsl(shader_source.into()),
        });

        let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("Geodesic Bind Group Layout"),
            entries: &[
                wgpu::BindGroupLayoutEntry {
                    binding: 0,
                    visibility: wgpu::ShaderStages::COMPUTE,
                    ty: wgpu::BindingType::Buffer {
                        ty: wgpu::BufferBindingType::Storage { read_only: false },
                        has_dynamic_offset: false,
                        min_binding_size: None,
                    },
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 1,
                    visibility: wgpu::ShaderStages::COMPUTE,
                    ty: wgpu::BindingType::Buffer {
                        ty: wgpu::BufferBindingType::Uniform,
                        has_dynamic_offset: false,
                        min_binding_size: None,
                    },
                    count: None,
                },
            ],
        });

        let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("Geodesic Pipeline Layout"),
            bind_group_layouts: &[&bind_group_layout],
            push_constant_ranges: &[],
        });

        Ok(
            device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
                label: Some("Geodesic Compute Pipeline"),
                layout: Some(&pipeline_layout),
                module: &shader,
                entry_point: "main",
            }),
        )
    }

    /// Create compute pipeline for trajectory calculations
    fn create_trajectory_pipeline(
        device: &wgpu::Device,
    ) -> Result<wgpu::ComputePipeline, GpuError> {
        // For now, use the same pipeline as geodesic integration
        Self::create_geodesic_pipeline(device)
    }

    /// Compute Minkowski norm-squared values for multiple spacetime vectors.
    ///
    /// Returns `ct² - x² - y² - z²` for each vector.
    pub async fn compute_minkowski_products(
        &self,
        vectors: &[GpuSpacetimeVector],
    ) -> Result<Vec<f32>, GpuError> {
        if vectors.is_empty() {
            return Ok(Vec::new());
        }
        for (index, vector) in vectors.iter().enumerate() {
            if !vector.is_finite() {
                return Err(GpuError::BufferError(format!(
                    "spacetime vector {index} contains non-finite values"
                )));
            }
        }

        let vectors_buffer = self
            .device
            .create_buffer_init(&wgpu::util::BufferInitDescriptor {
                label: Some("Spacetime Vectors Buffer"),
                contents: bytemuck::cast_slice(vectors),
                usage: wgpu::BufferUsages::STORAGE
                    | wgpu::BufferUsages::COPY_DST
                    | wgpu::BufferUsages::COPY_SRC,
            });

        let results_buffer = self.device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("Results Buffer"),
            size: (vectors.len() * std::mem::size_of::<f32>()) as u64,
            usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
            mapped_at_creation: false,
        });

        let bind_group_layout = self.spacetime_pipeline.get_bind_group_layout(0);
        let bind_group = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("Spacetime Bind Group"),
            layout: &bind_group_layout,
            entries: &[
                wgpu::BindGroupEntry {
                    binding: 0,
                    resource: vectors_buffer.as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 1,
                    resource: results_buffer.as_entire_binding(),
                },
            ],
        });

        let mut encoder = self
            .device
            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
                label: Some("Spacetime Compute Encoder"),
            });

        {
            let mut compute_pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
                label: Some("Spacetime Compute Pass"),
                timestamp_writes: None,
            });

            compute_pass.set_pipeline(&self.spacetime_pipeline);
            compute_pass.set_bind_group(0, &bind_group, &[]);

            let workgroup_size = 64;
            let num_workgroups = vectors.len().div_ceil(workgroup_size);
            compute_pass.dispatch_workgroups(num_workgroups as u32, 1, 1);
        }

        // Read back results
        let staging_buffer = self.device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("Staging Buffer"),
            size: results_buffer.size(),
            usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });

        encoder.copy_buffer_to_buffer(
            &results_buffer,
            0,
            &staging_buffer,
            0,
            results_buffer.size(),
        );

        self.queue.submit([encoder.finish()]);

        let buffer_slice = staging_buffer.slice(..);
        let (sender, receiver) = futures::channel::oneshot::channel();
        buffer_slice.map_async(wgpu::MapMode::Read, move |v| {
            let _ = sender.send(v);
        });

        self.device.poll(wgpu::Maintain::wait()).panic_on_timeout();
        receiver
            .await
            .map_err(|_| GpuError::BufferError("Failed to receive buffer mapping".to_string()))?
            .map_err(|e| GpuError::BufferError(format!("Buffer mapping failed: {:?}", e)))?;

        let data = buffer_slice.get_mapped_range();
        let results: Vec<f32> = bytemuck::cast_slice(&data).to_vec();

        drop(data);
        staging_buffer.unmap();

        Ok(results)
    }

    /// Propagate multiple particles through spacetime using the simplified GPU geodesic kernel.
    pub async fn propagate_particles(
        &self,
        particles: &[GpuRelativisticParticle],
        params: &GpuTrajectoryParams,
    ) -> Result<Vec<GpuRelativisticParticle>, GpuError> {
        if particles.is_empty() || params.steps == 0 {
            return Ok(particles.to_vec());
        }
        Self::validate_trajectory_params(params)?;
        for (index, particle) in particles.iter().enumerate() {
            Self::validate_particle(index, particle)?;
        }

        let particles_buffer = self
            .device
            .create_buffer_init(&wgpu::util::BufferInitDescriptor {
                label: Some("Particles Buffer"),
                contents: bytemuck::cast_slice(particles),
                usage: wgpu::BufferUsages::STORAGE
                    | wgpu::BufferUsages::COPY_DST
                    | wgpu::BufferUsages::COPY_SRC,
            });

        let params_buffer = self
            .device
            .create_buffer_init(&wgpu::util::BufferInitDescriptor {
                label: Some("Trajectory Params Buffer"),
                contents: bytemuck::cast_slice(&[*params]),
                usage: wgpu::BufferUsages::UNIFORM,
            });

        let bind_group_layout = self.geodesic_pipeline.get_bind_group_layout(0);
        let bind_group = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("Geodesic Bind Group"),
            layout: &bind_group_layout,
            entries: &[
                wgpu::BindGroupEntry {
                    binding: 0,
                    resource: particles_buffer.as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 1,
                    resource: params_buffer.as_entire_binding(),
                },
            ],
        });

        // Execute integration steps
        for _ in 0..params.steps {
            let mut encoder = self
                .device
                .create_command_encoder(&wgpu::CommandEncoderDescriptor {
                    label: Some("Geodesic Compute Encoder"),
                });

            {
                let mut compute_pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
                    label: Some("Geodesic Compute Pass"),
                    timestamp_writes: None,
                });

                compute_pass.set_pipeline(&self.geodesic_pipeline);
                compute_pass.set_bind_group(0, &bind_group, &[]);

                let workgroup_size = 64;
                let num_workgroups = particles.len().div_ceil(workgroup_size);
                compute_pass.dispatch_workgroups(num_workgroups as u32, 1, 1);
            }

            self.queue.submit([encoder.finish()]);
            self.device.poll(wgpu::Maintain::wait()).panic_on_timeout();
        }

        // Read back final particle states
        let staging_buffer = self.device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("Particles Staging Buffer"),
            size: particles_buffer.size(),
            usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });

        let mut encoder = self
            .device
            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
                label: Some("Copy Encoder"),
            });

        encoder.copy_buffer_to_buffer(
            &particles_buffer,
            0,
            &staging_buffer,
            0,
            particles_buffer.size(),
        );
        self.queue.submit([encoder.finish()]);

        let buffer_slice = staging_buffer.slice(..);
        let (sender, receiver) = futures::channel::oneshot::channel();
        buffer_slice.map_async(wgpu::MapMode::Read, move |v| {
            let _ = sender.send(v);
        });

        self.device.poll(wgpu::Maintain::wait()).panic_on_timeout();
        receiver
            .await
            .map_err(|_| GpuError::BufferError("Failed to receive buffer mapping".to_string()))?
            .map_err(|e| GpuError::BufferError(format!("Buffer mapping failed: {:?}", e)))?;

        let data = buffer_slice.get_mapped_range();
        let results: Vec<GpuRelativisticParticle> = bytemuck::cast_slice(&data).to_vec();

        drop(data);
        staging_buffer.unmap();

        Ok(results)
    }

    fn validate_trajectory_params(params: &GpuTrajectoryParams) -> Result<(), GpuError> {
        if !params.dt.is_finite() || params.dt <= 0.0 {
            return Err(GpuError::BufferError(
                "trajectory dt must be finite and positive".to_string(),
            ));
        }
        if !params.tolerance.is_finite() || params.tolerance < 0.0 {
            return Err(GpuError::BufferError(
                "trajectory tolerance must be finite and non-negative".to_string(),
            ));
        }
        if params.renorm_freq == 0 {
            return Err(GpuError::BufferError(
                "trajectory renorm_freq must be greater than zero".to_string(),
            ));
        }
        if !params.schwarzschild_radius.is_finite() || params.schwarzschild_radius < 0.0 {
            return Err(GpuError::BufferError(
                "schwarzschild_radius must be finite and non-negative".to_string(),
            ));
        }
        if !params.gm_parameter.is_finite() {
            return Err(GpuError::BufferError(
                "gm_parameter must be finite".to_string(),
            ));
        }

        Ok(())
    }

    fn validate_particle(index: usize, particle: &GpuRelativisticParticle) -> Result<(), GpuError> {
        if !particle.position.is_finite() {
            return Err(GpuError::BufferError(format!(
                "particle {index} position contains non-finite values"
            )));
        }
        if !particle.velocity.is_finite() {
            return Err(GpuError::BufferError(format!(
                "particle {index} velocity contains non-finite values"
            )));
        }
        if !particle.mass.is_finite() || particle.mass < 0.0 {
            return Err(GpuError::BufferError(format!(
                "particle {index} mass must be finite and non-negative"
            )));
        }
        if !particle.charge.is_finite() {
            return Err(GpuError::BufferError(format!(
                "particle {index} charge must be finite"
            )));
        }
        if !particle.proper_time.is_finite() {
            return Err(GpuError::BufferError(format!(
                "particle {index} proper_time must be finite"
            )));
        }

        Ok(())
    }
}

/// Convert CPU relativistic particle to GPU format
impl From<&RelativisticParticle> for GpuRelativisticParticle {
    fn from(particle: &RelativisticParticle) -> Self {
        let pos = &particle.position;
        let vel = particle.four_velocity.as_spacetime_vector();

        Self {
            position: GpuSpacetimeVector::from_spacetime_vector(pos),
            velocity: GpuSpacetimeVector::from_spacetime_vector(vel),
            mass: particle.mass as f32,
            charge: particle.charge as f32,
            proper_time: 0.0, // Will be updated during integration
            _padding: [0.0; 5],
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_gpu_spacetime_vector_conversion() {
        let cpu_vector = SpacetimeVector::new(1.0, 2.0, 3.0, 4.0);
        let gpu_vector = GpuSpacetimeVector::from_spacetime_vector(&cpu_vector);
        let converted_back = gpu_vector.to_spacetime_vector();

        assert!((converted_back.time() - 1.0).abs() < 1e-6);
        assert_eq!(converted_back.x(), 2.0);
        assert_eq!(converted_back.y(), 3.0);
        assert_eq!(converted_back.z(), 4.0);
    }

    #[tokio::test]
    #[ignore] // Skip in CI due to GPU hardware requirements
    async fn test_gpu_minkowski_products() {
        let gpu_physics = match GpuRelativisticPhysics::new().await {
            Ok(physics) => physics,
            Err(_) => {
                println!("GPU not available, skipping test");
                return;
            }
        };

        let vectors = vec![
            GpuSpacetimeVector::new(1.0, 0.5, 0.0, 0.0),
            GpuSpacetimeVector::new(2.0, 1.0, 0.0, 0.0),
        ];

        let results = gpu_physics
            .compute_minkowski_products(&vectors)
            .await
            .unwrap();

        // Check that we got results for each vector
        assert_eq!(results.len(), vectors.len());

        // Verify Minkowski inner product calculation (t² - x² - y² - z²)
        assert!((results[0] - (1.0 - 0.25)).abs() < 1e-6); // 1² - 0.5² = 0.75
        assert!((results[1] - (4.0 - 1.0)).abs() < 1e-6); // 2² - 1² = 3.0
    }
}