Skip to main content

neutron_diffusion_dd/
algorithm.rs

1use nalgebra::{DMatrix, DVector};
2use once_cell::sync::Lazy;
3use std::f64; // Para float64 (f64)
4use std::io::{self, Write}; // Para input manual y flush
5use std::time::{Duration, Instant};
6
7use serde::{Deserialize, Serialize};
8
9use std::fs::File;
10use std::io::Read;
11
12// --- Placeholder para datos de cuadratura ---
13// En el código Python, `DATA` viene de un módulo externo.
14// Para este ejemplo, solo incluimos los datos de S4.
15// mu_m: Cosinos direccionales (sólo positivos).
16// omega_m: Pesos de cuadratura.
17/// Quadrature data structure for discrete ordinates method.
18///
19/// Contains quadrature weights and directional cosines for the S_N method.
20/// These are pre-computed values for different quadrature orders.
21#[derive(Debug, Serialize, Deserialize)]
22pub struct QuadratureDataFile {
23    /// Quadrature order values (N for S_N method)
24    pub N: Vec<i32>,
25    /// Direction indices
26    pub m: Vec<i32>,
27    /// Directional cosines (mu values, positive only)
28    pub mu_m: Vec<f64>,
29    /// Quadrature weights (omega values)
30    pub omega_m: Vec<f64>,
31}
32
33const QUADRATURE_FILE_PATH: &str = "data/cuadraturas.json";
34
35pub static ALL_QUADRATURE_DATA: Lazy<QuadratureDataFile> = Lazy::new(|| {
36    // 1. Abrir el archivo
37    let mut file = File::open(QUADRATURE_FILE_PATH).expect(&format!(
38        "No se pudo abrir el archivo de cuadratura: {}",
39        QUADRATURE_FILE_PATH
40    ));
41
42    // 2. Leer el contenido a una cadena
43    let mut contents = String::new();
44    file.read_to_string(&mut contents)
45        .expect("Fallo al leer el archivo a una cadena.");
46
47    // 3. Deserializar la cadena JSON
48    serde_json::from_str(&contents)
49        .expect("Fallo al deserializar los datos de cuadratura JSON. Verifique el formato.")
50});
51
52// =================================================================
53// Paso A: Configuración
54// =================================================================
55
56/// Configuration for the neutron transport problem.
57///
58/// Contains geometry, material properties, quadrature settings, and boundary conditions
59/// for a 1D neutron transport simulation using the discrete ordinates (S_N) method.
60///
61/// # Fields
62///
63/// * `epsilon` - Convergence tolerance for the iterative solver
64/// * `max_iter` - Maximum number of iterations allowed
65/// * `num_regions` - Number of spatial regions in the domain
66/// * `num_zones` - Number of material zones
67/// * `nc` - Number of cells per region
68/// * `hr` - Height (thickness) of each region [cm]
69/// * `izl` - Material zone ID for each region (1-based)
70/// * `q` - External source term per region
71/// * `sct` - Total macroscopic cross section per zone
72/// * `scs` - Scattering macroscopic cross section per zone
73/// * `n` - Order of the discrete ordinates (S_N)
74/// * `n_half` - Half of N (number of directions in one hemisphere)
75/// * `miu_m` - Directional cosines (mu values)
76/// * `omega_m` - Quadrature weights
77/// * `reflex_izq` - Reflective boundary condition at left boundary
78/// * `reflex_der` - Reflective boundary condition at right boundary
79/// * `bound_left` - Incident flux at left boundary (if non-reflective)
80/// * `bound_right` - Incident flux at right boundary (if non-reflective)
81/// * `ntc` - Total number of cells (sum of nc)
82/// * `ntp` - Total number of nodes (ntc + 1)
83/// * `sigma_t_vec` - Total cross section per cell
84/// * `sigma_s_vec` - Scattering cross section per cell
85/// * `q_ext_vec` - External source per cell
86/// * `dx_vec` - Cell widths
87#[derive(Debug, Clone)]
88pub struct Config {
89    pub epsilon: f64,
90    pub max_iter: i32,
91    pub num_regions: usize,
92    pub num_zones: usize,
93
94    // Geometría y materiales por región
95    pub nc: DVector<usize>,  // Celdas por región
96    pub hr: DVector<f64>,    // Espesor por región [cm]
97    pub izl: DVector<usize>, // Zona de material por región (1-based)
98    pub q: DVector<f64>,     // Fuente externa por región
99
100    // Propiedades de material por zona
101    pub sct: DVector<f64>, // Sigma Total por zona
102    pub scs: DVector<f64>, // Sigma Scattering por zona
103
104    // Cuadratura
105    pub n: i32,
106    pub n_half: usize,
107    pub miu_m: DVector<f64>,
108    pub omega_m: DVector<f64>,
109
110    // Condiciones de frontera
111    pub reflex_izq: bool,
112    pub reflex_der: bool,
113    pub bound_left: DVector<f64>,
114    pub bound_right: DVector<f64>,
115
116    // Propiedades vectorizadas a nivel de celda (cálculos preliminares)
117    pub ntc: usize, // Total celdas
118    pub ntp: usize, // Total nodos
119    pub sigma_t_vec: DVector<f64>,
120    pub sigma_s_vec: DVector<f64>,
121    pub q_ext_vec: DVector<f64>,
122    pub dx_vec: DVector<f64>,
123}
124
125impl Config {
126    /// Creates a new configuration by automatically loading from a JSON file.
127    ///
128    /// This method deserializes configuration from a JSON file with the following format:
129    /// ```json
130    /// {
131    ///   "num_regions": 3,
132    ///   "num_zones": 3,
133    ///   "NC": [20, 60, 20],
134    ///   "HR": [10, 30, 10],
135    ///   "IZL": [1, 2, 3],
136    ///   "SCT": [1.0, 0.6, 1],
137    ///   "SCS": [0.99, 0.4, 0.9],
138    ///   "Q": [2, 0, 0],
139    ///   "N": 4,
140    ///   "reflex_izq": 1,
141    ///   "reflex_der": 0,
142    ///   "bound_left": [0, 0],
143    ///   "bound_right": [0, 0]
144    /// }
145    /// ```
146    ///
147    /// # Arguments
148    ///
149    /// * `epsilon` - Convergence tolerance for the iterative solver
150    /// * `max_iter` - Maximum number of iterations
151    /// * `input_path` - Path to the JSON configuration file
152    ///
153    /// # Panics
154    ///
155    /// Panics if the file cannot be opened or deserialized.
156    ///
157    /// # Example
158    ///
159    /// ```no_run
160    /// use neutron_diffusion_dd::algorithm::Config;
161    ///
162    /// let config = Config::new_auto(1e-5, 2000, "data/input.json");
163    /// ```
164    pub fn new_auto(epsilon: f64, max_iter: i32, input_path: &str) -> Self {
165        let mut conf = Config {
166            epsilon,
167            max_iter,
168            num_regions: 0,
169            num_zones: 0,
170            nc: DVector::zeros(0),
171            hr: DVector::zeros(0),
172            izl: DVector::zeros(0),
173            q: DVector::zeros(0),
174            sct: DVector::zeros(0),
175            scs: DVector::zeros(0),
176            n: 0,
177            n_half: 0,
178            miu_m: DVector::zeros(0),
179            omega_m: DVector::zeros(0),
180            reflex_izq: false,
181            reflex_der: false,
182            bound_left: DVector::zeros(0),
183            bound_right: DVector::zeros(0),
184            ntc: 0,
185            ntp: 0,
186            sigma_t_vec: DVector::zeros(0),
187            sigma_s_vec: DVector::zeros(0),
188            q_ext_vec: DVector::zeros(0),
189            dx_vec: DVector::zeros(0),
190        };
191
192        // Leer archivo JSON
193        let mut file = match File::open(input_path) {
194            Ok(f) => f,
195            Err(e) => panic!("No se pudo abrir {}: {}", input_path, e),
196        };
197        let mut contents = String::new();
198        file.read_to_string(&mut contents)
199            .expect("Fallo al leer input.json");
200
201        #[derive(Deserialize)]
202        struct InputFile {
203            num_regions: usize,
204            num_zones: usize,
205            #[serde(rename = "NC")]
206            nc: Vec<usize>,
207            #[serde(rename = "HR")]
208            hr: Vec<f64>,
209            #[serde(rename = "IZL")]
210            izl: Vec<usize>,
211            #[serde(rename = "SCT")]
212            sct: Vec<f64>,
213            #[serde(rename = "SCS")]
214            scs: Vec<f64>,
215            #[serde(rename = "Q")]
216            q: Vec<f64>,
217            #[serde(rename = "N")]
218            n: i32,
219            reflex_izq: i32,
220            reflex_der: i32,
221            bound_left: Vec<f64>,
222            bound_right: Vec<f64>,
223        }
224
225        let data: InputFile =
226            serde_json::from_str(&contents).expect("Fallo al deserializar input.json");
227
228        conf.num_regions = data.num_regions;
229        conf.num_zones = data.num_zones;
230
231        if data.nc.len() != conf.num_regions || data.hr.len() != conf.num_regions {
232            panic!("`NC` o `HR` no tienen longitud num_regions");
233        }
234        conf.nc = DVector::from_vec(data.nc);
235        conf.hr = DVector::from_vec(data.hr);
236
237        if data.izl.len() != conf.num_regions {
238            panic!("`IZL` no tiene longitud num_regions");
239        }
240        conf.izl = DVector::from_vec(data.izl);
241
242        if data.sct.len() != conf.num_zones || data.scs.len() != conf.num_zones {
243            panic!("`SCT` o `SCS` no tienen longitud num_zones");
244        }
245        conf.sct = DVector::from_vec(data.sct);
246        conf.scs = DVector::from_vec(data.scs);
247
248        if data.q.len() != conf.num_regions {
249            panic!("`Q` no tiene longitud num_regions");
250        }
251        conf.q = DVector::from_vec(data.q);
252
253        conf.n = if data.n % 2 == 0 { data.n } else { data.n - 1 };
254        if conf.n < 2 {
255            conf.n = 2;
256        }
257        conf.n_half = (conf.n / 2) as usize;
258
259        conf.reflex_izq = data.reflex_izq != 0;
260        conf.reflex_der = data.reflex_der != 0;
261
262        if !conf.reflex_izq {
263            let mut bl = data.bound_left;
264            bl.resize(conf.n_half, 0.0);
265            conf.bound_left = DVector::from_vec(bl);
266        } else {
267            conf.bound_left = DVector::from_element(conf.n_half, 0.0);
268        }
269
270        if !conf.reflex_der {
271            let mut br = data.bound_right;
272            br.resize(conf.n_half, 0.0);
273            conf.bound_right = DVector::from_vec(br);
274        } else {
275            conf.bound_right = DVector::from_element(conf.n_half, 0.0);
276        }
277
278        conf.weights_directions();
279        conf.prelim_calculations();
280
281        println!("\n--- CONFIGURACIÓN CARGADA DESDE {} ---", input_path);
282        conf
283    }
284
285    /// Creates a new configuration through interactive manual input.
286    ///
287    /// Prompts the user for all configuration parameters interactively.
288    /// This is useful for testing and exploration.
289    ///
290    /// # Arguments
291    ///
292    /// * `epsilon` - Convergence tolerance for the iterative solver
293    /// * `max_iter` - Maximum number of iterations
294    ///
295    /// # Example
296    ///
297    /// ```no_run
298    /// use neutron_diffusion_dd::algorithm::Config;
299    ///
300    /// let config = Config::new_manual(1e-5, 2000);
301    /// ```
302    // Implementación simplificada del constructor manual
303    pub fn new_manual(epsilon: f64, max_iter: i32) -> Self {
304        println!("\n--- CONFIGURACIÓN MANUAL ---");
305
306        let num_regions = Self::read_input::<usize>("Introduzca el número de Regiones: ");
307        let num_zones = Self::read_input::<usize>("Introduzca el número de Zonas: ");
308
309        let mut conf = Config {
310            epsilon,
311            max_iter,
312            num_regions,
313            num_zones,
314            nc: DVector::zeros(num_regions),
315            hr: DVector::zeros(num_regions),
316            izl: DVector::zeros(num_regions),
317            q: DVector::zeros(num_regions),
318            sct: DVector::zeros(num_zones),
319            scs: DVector::zeros(num_zones),
320
321            // Inicialización placeholder para campos de cuadratura/cálculos preliminares
322            n: 0,
323            n_half: 0,
324            miu_m: DVector::zeros(0),
325            omega_m: DVector::zeros(0),
326
327            reflex_izq: false,
328            reflex_der: false,
329            bound_left: DVector::zeros(0),
330            bound_right: DVector::zeros(0),
331
332            ntc: 0,
333            ntp: 0,
334            sigma_t_vec: DVector::zeros(0),
335            sigma_s_vec: DVector::zeros(0),
336            q_ext_vec: DVector::zeros(0),
337            dx_vec: DVector::zeros(0),
338        };
339
340        conf.manual_input();
341        conf.weights_directions();
342        conf.prelim_calculations();
343
344        // println!("\nConfiguración completa: {:?}", conf);
345        conf
346    }
347
348    // Función auxiliar para leer entrada de usuario
349    fn read_input<T: std::str::FromStr>(prompt: &str) -> T {
350        loop {
351            print!("{}", prompt);
352            io::stdout().flush().unwrap();
353            let mut input = String::new();
354            io::stdin()
355                .read_line(&mut input)
356                .expect("Fallo al leer la línea");
357
358            match input.trim().parse() {
359                Ok(val) => return val,
360                Err(_) => println!("Entrada inválida. Intente de nuevo."),
361            }
362        }
363    }
364
365    fn manual_input(&mut self) {
366        println!("\n--- CONFIGURACIÓN ESPACIAL ---");
367
368        // Corrección 1: nc (usize)
369        let nc_vec: Vec<usize> = (0..self.num_regions)
370            .map(|i| Self::read_input(&format!("Celdas en Región {}: ", i + 1)))
371            .collect();
372        self.nc = DVector::from_vec(nc_vec);
373
374        // Corrección 2: hr (f64)
375        let hr_vec: Vec<f64> = (0..self.num_regions)
376            .map(|i| Self::read_input(&format!("Espesor total [cm] Región {}: ", i + 1)))
377            .collect();
378        self.hr = DVector::from_vec(hr_vec);
379
380        // Corrección 3: izl (usize)
381        let izl_vec: Vec<usize> = (0..self.num_regions)
382            .map(|i| {
383                loop {
384                    let zone: usize = Self::read_input(&format!(
385                        "ID Zona Material Región {} (1-based, 1-{}): ",
386                        i + 1,
387                        self.num_zones
388                    ));
389                    if zone >= 1 && zone <= self.num_zones {
390                        return zone;
391                    }
392                    println!(
393                        "ID de zona inválido. Debe estar entre 1 y {}.",
394                        self.num_zones
395                    );
396                }
397            })
398            .collect();
399        self.izl = DVector::from_vec(izl_vec);
400
401        println!("\n--- CONFIGURACIÓN MATERIALES ---");
402
403        // Corrección 4: sct (f64)
404        let sct_vec: Vec<f64> = (0..self.num_zones)
405            .map(|i| Self::read_input(&format!("Sigma_Total Zona {}: ", i + 1)))
406            .collect();
407        self.sct = DVector::from_vec(sct_vec);
408
409        // Corrección 5: scs (f64)
410        let scs_vec: Vec<f64> = (0..self.num_zones)
411            .map(|i| Self::read_input(&format!("Sigma_Scattering Zona {}: ", i + 1)))
412            .collect();
413        self.scs = DVector::from_vec(scs_vec);
414
415        // Corrección 6: q (f64)
416        let q_vec: Vec<f64> = (0..self.num_regions)
417            .map(|i| Self::read_input(&format!("Fuente (Q) Región {}: ", i + 1)))
418            .collect();
419        self.q = DVector::from_vec(q_vec);
420
421        println!("\n--- CONFIGURACIÓN CUADRATURA ---");
422        self.n = loop {
423            let n_input: i32 = Self::read_input("Orden de cuadratura S_N (ej. 2, 4, 8) -> ");
424            if n_input % 2 == 0 {
425                break n_input;
426            }
427            println!("El orden de la cuadratura debe ser un número par.");
428        };
429        self.n_half = (self.n / 2) as usize;
430
431        // --- Condiciones de frontera (Manual) ---
432        let reflex_izq_str: String =
433            Self::read_input("¿Condiciones reflexivas por la Izquierda? (s/n): ");
434        self.reflex_izq = reflex_izq_str.trim().to_lowercase() == "s";
435        let reflex_der_str: String =
436            Self::read_input("¿Condiciones reflexivas por la Derecha? (s/n): ");
437        self.reflex_der = reflex_der_str.trim().to_lowercase() == "s";
438
439        if !self.reflex_izq {
440            println!("Ingrese flujo incidente en IZQUIERDA (mu > 0):");
441            // Corrección 7: bound_left (f64)
442            let bound_left_vec: Vec<f64> = (0..self.n_half)
443                .map(|i| Self::read_input(&format!("  Dirección {}: ", i + 1)))
444                .collect();
445            self.bound_left = DVector::from_vec(bound_left_vec);
446        } else {
447            self.bound_left = DVector::from_element(self.n_half, 0.0); // Correcto (no usa collect)
448        }
449
450        if !self.reflex_der {
451            println!("Ingrese flujo incidente en DERECHA (mu < 0):");
452            // Corrección 8: bound_right (f64)
453            let bound_right_vec: Vec<f64> = (0..self.n_half)
454                .map(|i| Self::read_input(&format!("  Dirección {}: ", i + 1)))
455                .collect();
456            self.bound_right = DVector::from_vec(bound_right_vec);
457        } else {
458            self.bound_right = DVector::from_element(self.n_half, 0.0); // Correcto (no usa collect)
459        }
460    }
461
462    fn auto_imput(&mut self) {
463        // Lee `data/input.json` y llena los campos relevantes de `Config`.
464        #[derive(Deserialize)]
465        struct InputFile {
466            num_regions: usize,
467            num_zones: usize,
468            #[serde(rename = "NC")]
469            nc: Vec<usize>,
470            #[serde(rename = "HR")]
471            hr: Vec<f64>,
472            #[serde(rename = "IZL")]
473            izl: Vec<usize>,
474            #[serde(rename = "SCT")]
475            sct: Vec<f64>,
476            #[serde(rename = "SCS")]
477            scs: Vec<f64>,
478            #[serde(rename = "Q")]
479            q: Vec<f64>,
480            #[serde(rename = "N")]
481            n: i32,
482            reflex_izq: i32,
483            reflex_der: i32,
484            bound_left: Vec<f64>,
485            bound_right: Vec<f64>,
486        }
487
488        let path = "data/input.json";
489        let mut file = match File::open(path) {
490            Ok(f) => f,
491            Err(e) => panic!("No se pudo abrir {}: {}", path, e),
492        };
493        let mut contents = String::new();
494        file.read_to_string(&mut contents)
495            .expect("Fallo al leer data/input.json");
496
497        let data: InputFile =
498            serde_json::from_str(&contents).expect("Fallo al deserializar data/input.json");
499
500        // Asignaciones básicas
501        self.num_regions = data.num_regions;
502        self.num_zones = data.num_zones;
503
504        // Validaciones y asignación de vectores
505        if data.nc.len() != self.num_regions {
506            panic!("`NC` no tiene la longitud esperada (num_regions)");
507        }
508        if data.hr.len() != self.num_regions {
509            panic!("`HR` no tiene la longitud esperada (num_regions)");
510        }
511        self.nc = DVector::from_vec(data.nc);
512        self.hr = DVector::from_vec(data.hr);
513
514        if data.izl.len() != self.num_regions {
515            panic!("`IZL` no tiene la longitud esperada (num_regions)");
516        }
517        self.izl = DVector::from_vec(data.izl);
518
519        if data.sct.len() != self.num_zones {
520            panic!("`SCT` no tiene la longitud esperada (num_zones)");
521        }
522        if data.scs.len() != self.num_zones {
523            panic!("`SCS` no tiene la longitud esperada (num_zones)");
524        }
525        self.sct = DVector::from_vec(data.sct);
526        self.scs = DVector::from_vec(data.scs);
527
528        if data.q.len() != self.num_regions {
529            panic!("`Q` no tiene la longitud esperada (num_regions)");
530        }
531        self.q = DVector::from_vec(data.q);
532
533        // Orden de cuadratura (asegurar par)
534        self.n = if data.n % 2 == 0 { data.n } else { data.n - 1 };
535        if self.n < 2 {
536            self.n = 2;
537        }
538        self.n_half = (self.n / 2) as usize;
539
540        // Condiciones de frontera
541        self.reflex_izq = data.reflex_izq != 0;
542        self.reflex_der = data.reflex_der != 0;
543
544        if !self.reflex_izq {
545            // Asegurar tamaño correcto o rellenar con ceros
546            let mut bl = data.bound_left;
547            bl.resize(self.n_half, 0.0);
548            self.bound_left = DVector::from_vec(bl);
549        } else {
550            self.bound_left = DVector::from_element(self.n_half, 0.0);
551        }
552
553        if !self.reflex_der {
554            let mut br = data.bound_right;
555            br.resize(self.n_half, 0.0);
556            self.bound_right = DVector::from_vec(br);
557        } else {
558            self.bound_right = DVector::from_element(self.n_half, 0.0);
559        }
560
561        // Completar pesos y direcciones y cálculos preliminares
562        self.weights_directions();
563        self.prelim_calculations();
564    }
565
566    fn weights_directions(&mut self) {
567        // Acceder a los datos estáticos que ya están deserializados
568        let all_data = &*ALL_QUADRATURE_DATA;
569
570        let n_required = self.n;
571        let mut miu_filtered = Vec::new();
572        let mut omega_filtered = Vec::new();
573        let mut found = false;
574
575        // Iterar y filtrar los datos para el orden N requerido
576        for (i, &n_val) in all_data.N.iter().enumerate() {
577            if n_val == n_required {
578                miu_filtered.push(all_data.mu_m[i]);
579                omega_filtered.push(all_data.omega_m[i]);
580                found = true;
581            }
582        }
583
584        if !found {
585            // Manejo de error si el orden N no existe en el JSON
586            eprintln!(
587                "Advertencia: No hay datos para S{}. Se usará S2 por defecto.",
588                n_required
589            );
590
591            // Revertir a un S2 simple (o forzar un error si es crítico)
592            self.n = 2;
593            self.n_half = 1;
594            self.miu_m = DVector::from_vec(vec![0.577350269189626]);
595            self.omega_m = DVector::from_vec(vec![1.0]);
596        } else {
597            self.n_half = miu_filtered.len();
598
599            // Convertir Vec<f64> a DVector<f64>
600            self.miu_m = DVector::from_vec(miu_filtered);
601            self.omega_m = DVector::from_vec(omega_filtered);
602        }
603    }
604
605    fn prelim_calculations(&mut self) {
606        self.ntc = self.nc.iter().sum(); // Total celdas
607        self.ntp = self.ntc + 1; // Total nodos
608
609        // Inicializar vectores de celda
610        self.sigma_t_vec = DVector::zeros(self.ntc);
611        self.sigma_s_vec = DVector::zeros(self.ntc);
612        self.q_ext_vec = DVector::zeros(self.ntc);
613        self.dx_vec = DVector::zeros(self.ntc);
614
615        let mut current_idx = 0;
616        for r in 0..self.num_regions {
617            let n_cells = self.nc[r];
618            let zone_idx = self.izl[r] - 1; // Ajuste a base-0
619            let hr_region = self.hr[r];
620            let dx = hr_region / n_cells as f64;
621
622            // Rellenar las secciones del vector para esta región
623            let end_idx = current_idx + n_cells;
624
625            self.sigma_t_vec
626                .view_mut((current_idx, 0), (n_cells, 1))
627                .fill(self.sct[zone_idx]);
628            self.sigma_s_vec
629                .view_mut((current_idx, 0), (n_cells, 1))
630                .fill(self.scs[zone_idx]);
631            self.q_ext_vec
632                .view_mut((current_idx, 0), (n_cells, 1))
633                .fill(self.q[r]);
634            self.dx_vec
635                .view_mut((current_idx, 0), (n_cells, 1))
636                .fill(dx);
637
638            current_idx = end_idx;
639        }
640    }
641}
642
643// =================================================================
644// Paso B: Runner (Motor de Cálculo)
645// =================================================================
646
647/// Solves neutron transport problems using the Discrete Ordinates (S_N) method with domain decomposition.
648///
649/// The `Runner` struct implements the sweep-based algorithm for solving the one-dimensional
650/// neutron transport equation. It maintains the angular flux distribution across spatial
651/// nodes and angular directions, and iteratively updates the scalar flux until convergence.
652///
653/// # Fields
654///
655/// * `config` - The configuration parameters defining the problem domain and materials
656/// * `converged` - Flag indicating whether the iterative solver has converged
657/// * `iteration` - Current iteration count in the convergence loop
658/// * `psi_right` - Angular flux for rightward-moving directions (μ > 0), dimensions: [spatial_nodes × n_half]
659/// * `psi_left` - Angular flux for leftward-moving directions (μ < 0), dimensions: [spatial_nodes × n_half]
660/// * `scalar_flux` - Integrated angular flux over all directions, dimensions: [spatial_cells]
661/// * `total_source` - Total source term including external and scattering contributions, dimensions: [spatial_cells]
662///
663/// # Example
664///
665/// ```no_run
666/// use neutron_diffusion_dd::algorithm::{Config, Runner};
667///
668/// let config = Config::new_auto(1e-5, 2000, "data/input.json");
669/// let mut runner = Runner::new(config);
670/// let result = runner.run();
671/// ```
672pub struct Runner {
673    config: Config,
674    converged: bool,
675    iteration: i32,
676
677    // Flujos Angulares [Nodos x Direcciones] -> DMatrix (NTP x N_HALF)
678    psi_right: DMatrix<f64>, // mu > 0
679    psi_left: DMatrix<f64>,  // mu < 0
680
681    // Flujo Escalar [Celdas] -> DVector (NTC)
682    scalar_flux: DVector<f64>,
683
684    // Fuente Total [Celdas] (Scattering + Externa)
685    total_source: DVector<f64>,
686}
687
688impl Runner {
689    /// Constructs a new `Runner` with the provided configuration.
690    ///
691    /// Initializes all angular flux matrices with zeros and applies initial boundary conditions
692    /// from the configuration. The solver is ready to start iterations after construction.
693    ///
694    /// # Arguments
695    ///
696    /// * `config` - A `Config` struct containing all problem parameters
697    ///
698    /// # Returns
699    ///
700    /// A new `Runner` instance with initialized flux matrices and boundary conditions applied.
701    ///
702    /// # Example
703    ///
704    /// ```no_run
705    /// use neutron_diffusion_dd::algorithm::{Config, Runner};
706    ///
707    /// let config = Config::new_auto(1e-5, 2000, "data/input.json");
708    /// let runner = Runner::new(config);
709    /// ```
710    pub fn new(config: Config) -> Self {
711        let ntp = config.ntp;
712        let ntc = config.ntc;
713        let n_half = config.n_half;
714
715        // Inicializar flujos angulares con ceros
716        let mut psi_right = DMatrix::zeros(ntp, n_half);
717        let mut psi_left = DMatrix::zeros(ntp, n_half);
718
719        // Aplicar condiciones de frontera iniciales
720        if !config.reflex_izq {
721            psi_right
722                .row_mut(0)
723                .copy_from(&config.bound_left.transpose());
724        }
725        if !config.reflex_der {
726            psi_left
727                .row_mut(ntp - 1)
728                .copy_from(&config.bound_right.transpose());
729        }
730
731        Runner {
732            config,
733            converged: false,
734            iteration: 0,
735            psi_right,
736            psi_left,
737            scalar_flux: DVector::zeros(ntc),
738            total_source: DVector::zeros(ntc),
739        }
740    }
741
742    /// Updates angular fluxes at boundaries when reflective conditions are applied.
743    ///
744    /// For reflective boundaries, the outgoing flux at one boundary becomes the incoming
745    /// flux at that boundary. Specifically:
746    /// - At the left boundary (x=0): leftward flux becomes rightward flux
747    /// - At the right boundary (x=L): rightward flux becomes leftward flux
748    ///
749    /// This method is called at the beginning of each iteration before the sweep algorithm.
750    fn update_reflective_boundaries(&mut self) {
751        // Izquierda (x=0): Lo que sale hacia la izquierda (PSI_LEFT[0]) entra hacia la derecha
752        if self.config.reflex_izq {
753            self.psi_right.row_mut(0).copy_from(&self.psi_left.row(0));
754        }
755
756        // Derecha (x=L): Lo que sale hacia la derecha (PSI_RIGHT[NTP-1]) entra hacia la izquierda
757        if self.config.reflex_der {
758            self.psi_left
759                .row_mut(self.config.ntp - 1)
760                .copy_from(&self.psi_right.row(self.config.ntp - 1));
761        }
762    }
763
764    fn sweep(&mut self) {
765        // 1. Pre-cálculo de la Fuente Total
766        // Q_total = 0.5 * (Q_ext + Sigma_S * Phi)
767        self.total_source = 0.5
768            * (&self.config.q_ext_vec + self.config.sigma_s_vec.component_mul(&self.scalar_flux));
769
770        // --- BARRIDO HACIA LA DERECHA (mu > 0) ---
771        for k in 0..self.config.ntc {
772            let dx = self.config.dx_vec[k];
773            let st = self.config.sigma_t_vec[k];
774            let source = self.total_source[k];
775
776            for m in 0..self.config.n_half {
777                let mu = self.config.miu_m[m];
778                let psi_in = self.psi_right[(k, m)]; // Nodo k (entrada)
779
780                let alpha = mu / dx;
781                let num = (alpha - 0.5 * st) * psi_in + source;
782                let den = alpha + 0.5 * st;
783
784                let mut psi_out = num / den;
785
786                // Fixup de Flujo Negativo (step-wise)
787                if psi_out < 0.0 {
788                    // Revertir a esquema de paso completo (paso cero)
789                    psi_out = (source + alpha * psi_in) / (alpha + st);
790                }
791
792                self.psi_right[(k + 1, m)] = psi_out; // Nodo k+1 (salida)
793            }
794        }
795
796        // --- BARRIDO HACIA LA IZQUIERDA (mu < 0) ---
797        for k in (0..self.config.ntc).rev() {
798            // k desde NTC-1 hasta 0
799            let dx = self.config.dx_vec[k];
800            let st = self.config.sigma_t_vec[k];
801            let source = self.total_source[k];
802
803            for m in 0..self.config.n_half {
804                // Usamos valor positivo para la fórmula simétrica
805                let mu = self.config.miu_m[m].abs();
806                let psi_in = self.psi_left[(k + 1, m)]; // Nodo k+1 (entrada desde la derecha)
807
808                let alpha = mu / dx;
809                let num = (alpha - 0.5 * st) * psi_in + source;
810                let den = alpha + 0.5 * st;
811
812                let mut psi_out = num / den;
813
814                // Fixup de Flujo Negativo (step-wise)
815                if psi_out < 0.0 {
816                    psi_out = (source + alpha * psi_in) / (alpha + st);
817                }
818
819                self.psi_left[(k, m)] = psi_out; // Nodo k (salida)
820            }
821        }
822    }
823
824    fn calculo_flujo(&mut self) -> DVector<f64> {
825        let old_flux = self.scalar_flux.clone();
826
827        self.scalar_flux.fill(0.0);
828
829        for k in 0..self.config.ntc {
830            let mut suma = 0.0;
831            for m in 0..self.config.n_half {
832                let w = self.config.omega_m[m];
833
834                // Flujo promedio en la celda (Diamond Difference Average)
835                // psi_avg = 0.5 * (psi_in + psi_out)
836
837                // Dirección derecha (mu > 0)
838                let psi_avg_der = 0.5 * (self.psi_right[(k, m)] + self.psi_right[(k + 1, m)]);
839                // Dirección izquierda (mu < 0)
840                let psi_avg_izq = 0.5 * (self.psi_left[(k, m)] + self.psi_left[(k + 1, m)]);
841
842                // Integración sobre el ángulo sólido (suma de las dos direcciones)
843                suma += w * (psi_avg_der + psi_avg_izq);
844            }
845            self.scalar_flux[k] = suma;
846        }
847
848        old_flux
849    }
850
851    fn check_convergence(&self, old_flux: &DVector<f64>) -> bool {
852        // |actual - old| / actual
853        let diff = (&self.scalar_flux - old_flux).abs();
854
855        // Manejo seguro de división por cero (análogo a np.where)
856        let denom: DVector<f64> = self
857            .scalar_flux
858            .map(|val| if val.abs() > 1e-13 { val.abs() } else { 1.0 });
859
860        let rel_error = (diff.component_div(&denom)).max();
861
862        if self.iteration % 100 == 0 || self.iteration == 1 {
863            println!("Iter {}: Error Max = {:.2e}", self.iteration, rel_error);
864        }
865
866        rel_error < self.config.epsilon
867    }
868
869    /// Runs the iterative S_N solver until convergence or maximum iterations.
870    ///
871    /// Executes the main solution algorithm:
872    /// 1. Updates reflective boundary conditions if applicable
873    /// 2. Performs a complete sweep of angular fluxes in all spatial cells and directions
874    /// 3. Computes scalar flux by integrating angular fluxes
875    /// 4. Checks convergence based on relative change in scalar flux
876    ///
877    /// The iteration process continues until either the convergence tolerance is achieved
878    /// or the maximum number of iterations is exceeded. Convergence diagnostics are printed
879    /// every 100 iterations.
880    ///
881    /// # Returns
882    ///
883    /// A `RunnerResult` containing the final scalar flux distribution, convergence status,
884    /// iteration count, and computation time.
885    ///
886    /// # Example
887    ///
888    /// ```no_run
889    /// use neutron_diffusion_dd::algorithm::{Config, Runner};
890    ///
891    /// let config = Config::new_auto(1e-5, 2000, "data/input.json");
892    /// let mut runner = Runner::new(config);
893    /// let result = runner.run();
894    /// println!("Converged: {}", result.converged);
895    /// println!("Iterations: {}", result.iteration);
896    /// ```
897    pub fn run(&mut self) -> RunnerResult {
898        println!("\n--- INICIANDO CÁLCULO S{} ---", self.config.n);
899        let start = Instant::now();
900
901        while self.iteration < self.config.max_iter {
902            self.iteration += 1;
903
904            // 1. Actualizar fronteras si es reflexiva
905            self.update_reflective_boundaries();
906
907            // 2. Barrido (Transport Sweep)
908            self.sweep();
909
910            // 3. Calcular flujo escalar y obtener el anterior
911            let old_flux = self.calculo_flujo();
912
913            // 4. Chequear convergencia
914            if self.check_convergence(&old_flux) {
915                println!("\nCONVERGENCIA ALCANZADA en iteración {}.", self.iteration);
916                self.converged = true;
917                break;
918            }
919        }
920
921        let duration = start.elapsed();
922        if !self.converged {
923            println!("\nADVERTENCIA: Máximo de iteraciones alcanzado sin convergencia.");
924        }
925        println!("Tiempo de cálculo: {:.2?}", duration);
926
927        RunnerResult {
928            scalar_flux: self.scalar_flux.clone(),
929            iteration: self.iteration,
930            psi_right: self.psi_right.clone(),
931            psi_left: self.psi_left.clone(),
932            converged: self.converged,
933            time: duration, // Aquí se podría crear una estructura para guardar a archivo,
934                            // similar al DataFrame/Excel en Python
935        }
936    }
937}
938
939// Estructura para agrupar los resultados
940pub struct RunnerResult {
941    pub scalar_flux: DVector<f64>,
942    pub iteration: i32,
943    pub time: Duration,
944    pub psi_right: DMatrix<f64>,
945    pub psi_left: DMatrix<f64>,
946    pub converged: bool,
947}
948
949#[cfg(test)]
950mod tests {
951    use super::*;
952
953    #[test]
954    fn test_config_new_auto_basic() {
955        let config = Config::new_auto(1e-5, 2000, "data/input.json");
956        assert_eq!(config.num_regions, 3);
957        assert_eq!(config.num_zones, 3);
958        assert_eq!(config.n, 4);
959    }
960
961    #[test]
962    fn test_weights_directions_s4() {
963        let config = Config::new_auto(1e-5, 2000, "data/input.json");
964        // S4 debe tener 2 direcciones
965        assert_eq!(config.n_half, 2);
966        assert_eq!(config.miu_m.len(), 2);
967        assert_eq!(config.omega_m.len(), 2);
968
969        // Verificar que los pesos integran a 1 (aproximadamente)
970        let sum_weights: f64 = config.omega_m.iter().sum();
971        assert!(
972            (sum_weights - 1.0).abs() < 1e-10,
973            "Suma de pesos debe ser 1"
974        );
975    }
976
977    #[test]
978    fn test_prelim_calculations_vectors() {
979        let config = Config::new_auto(1e-5, 2000, "data/input.json");
980
981        // Verificar tamaños
982        assert_eq!(config.sigma_t_vec.len(), config.ntc);
983        assert_eq!(config.sigma_s_vec.len(), config.ntc);
984        assert_eq!(config.q_ext_vec.len(), config.ntc);
985        assert_eq!(config.dx_vec.len(), config.ntc);
986
987        // Verificar valores no negativos (excepto en especiales)
988        for i in 0..config.ntc {
989            assert!(config.sigma_t_vec[i] > 0.0, "Sigma total debe ser positiva");
990            assert!(
991                config.sigma_s_vec[i] >= 0.0,
992                "Sigma scattering debe ser no negativa"
993            );
994            assert!(config.dx_vec[i] > 0.0, "dx debe ser positivo");
995        }
996    }
997
998    #[test]
999    fn test_runner_initialization() {
1000        let config = Config::new_auto(1e-5, 2000, "data/input.json");
1001        let runner = Runner::new(config.clone());
1002
1003        // Verificar que el runner se inicializó correctamente
1004        assert!(!runner.converged);
1005        assert_eq!(runner.iteration, 0);
1006        assert_eq!(runner.scalar_flux.len(), config.ntc);
1007    }
1008
1009    #[test]
1010    fn test_convergence_check_negative_flux() {
1011        let config = Config::new_auto(1e-5, 2000, "data/input.json");
1012        let mut runner = Runner::new(config);
1013
1014        // Crear un flujo antiguo artificial
1015        let old_flux = DVector::from_element(runner.scalar_flux.len(), 1.0);
1016        runner.scalar_flux.fill(1.01);
1017
1018        // El cambio es 1% = 1e-2, mayor que 1e-5
1019        assert!(!runner.check_convergence(&old_flux));
1020    }
1021
1022    #[test]
1023    fn test_epsilon_effect_on_convergence() {
1024        // Epsilon más grande = menos iteraciones
1025        let config_loose = Config::new_auto(1e-2, 500, "data/input.json");
1026        let mut runner_loose = Runner::new(config_loose);
1027        let result_loose = runner_loose.run();
1028
1029        // Epsilon más pequeño = más iteraciones (generalmente)
1030        let config_tight = Config::new_auto(1e-7, 5000, "data/input.json");
1031        let mut runner_tight = Runner::new(config_tight);
1032        let result_tight = runner_tight.run();
1033
1034        // Ambas deben converger
1035        assert!(result_loose.converged);
1036        assert!(result_tight.converged);
1037
1038        // El criterio más flojo debería converger más rápido
1039        assert!(
1040            result_loose.iteration <= result_tight.iteration,
1041            "Criterio flojo debe converger más rápido"
1042        );
1043    }
1044
1045    #[test]
1046    fn test_reflect_boundary_conditions() {
1047        let config = Config::new_auto(1e-5, 2000, "data/input.json");
1048
1049        // reflex_izq debe ser true
1050        assert!(config.reflex_izq);
1051        assert!(!config.reflex_der);
1052
1053        // Los vectores de frontera deben ser ceros (según input.json)
1054        for i in 0..config.n_half {
1055            assert_eq!(config.bound_left[i], 0.0);
1056            assert_eq!(config.bound_right[i], 0.0);
1057        }
1058    }
1059
1060    #[test]
1061    fn test_material_zones_mapping() {
1062        let config = Config::new_auto(1e-5, 2000, "data/input.json");
1063
1064        // Verificar que las zonas se mapean correctamente
1065        for r in 0..config.num_regions {
1066            let zone_idx = config.izl[r] - 1; // Convertir a base-0
1067            assert!(zone_idx < config.num_zones, "Índice de zona inválido");
1068
1069            // Verificar que los valores están en rango
1070            assert!(zone_idx < config.sct.len());
1071            assert!(zone_idx < config.scs.len());
1072        }
1073    }
1074
1075    #[test]
1076    fn test_quadrature_weights_positive() {
1077        let config = Config::new_auto(1e-5, 2000, "data/input.json");
1078
1079        // Todos los pesos deben ser positivos
1080        for i in 0..config.n_half {
1081            assert!(
1082                config.omega_m[i] > 0.0,
1083                "Peso de cuadratura debe ser positivo"
1084            );
1085            assert!(config.miu_m[i] > 0.0, "Coseno director debe ser positivo");
1086            assert!(config.miu_m[i] <= 1.0, "Coseno debe estar en [0, 1]");
1087        }
1088    }
1089
1090    #[test]
1091    fn test_scalar_flux_non_negative() {
1092        let config = Config::new_auto(1e-5, 2000, "data/input.json");
1093        let mut runner = Runner::new(config);
1094        let result = runner.run();
1095
1096        // Todos los valores del flujo escalar deben ser no negativos
1097        for i in 0..result.scalar_flux.len() {
1098            assert!(
1099                result.scalar_flux[i] >= 0.0,
1100                "Flujo escalar debe ser no negativo"
1101            );
1102        }
1103    }
1104
1105    #[test]
1106    fn test_runner_max_iterations_limit() {
1107        // Usar epsilon muy pequeño para que no converja rápidamente
1108        let config = Config::new_auto(1e-15, 100, "data/input.json");
1109        let mut runner = Runner::new(config);
1110        let result = runner.run();
1111
1112        // No debe exceder max_iter
1113        assert!(result.iteration <= 100, "No debe exceder max_iter");
1114    }
1115}