feagi-brain-development 0.0.22

Brain Development Utilities - Synaptogenesis and Connectivity
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
// Copyright 2025 Neuraville Inc.
// SPDX-License-Identifier: Apache-2.0

/*!
FFI bindings for Python integration via PyO3.

Exposes Rust functions to Python for seamless interop.
*/

use pyo3::prelude::*;

/// Python-exposed version of syn_projector
///
/// # Arguments (from Python)
///
/// * `src_area_id` - str
/// * `dst_area_id` - str
/// * `src_neuron_id` - int
/// * `src_dimensions` - tuple[int, int, int]
/// * `dst_dimensions` - tuple[int, int, int]
/// * `neuron_location` - tuple[int, int, int]
/// * `transpose` - Optional[tuple[int, int, int]]
/// * `project_last_layer_of` - Optional[int]
///
/// # Returns
///
/// List[tuple[int, int, int]] - List of destination positions
#[pyfunction]
#[pyo3(signature = (src_area_id, dst_area_id, src_neuron_id, src_dimensions, dst_dimensions, neuron_location, transpose=None, project_last_layer_of=None))]
fn py_syn_projector(
    src_area_id: &str,
    dst_area_id: &str,
    src_neuron_id: u64,
    src_dimensions: (usize, usize, usize),
    dst_dimensions: (usize, usize, usize),
    neuron_location: (i32, i32, i32),
    transpose: Option<(usize, usize, usize)>,
    project_last_layer_of: Option<usize>,
) -> PyResult<Vec<(i32, i32, i32)>> {
    let loc_u32 = (neuron_location.0 as u32, neuron_location.1 as u32, neuron_location.2 as u32);
    let result = crate::connectivity::rules::syn_projector(
        src_area_id,
        dst_area_id,
        src_neuron_id,
        src_dimensions,
        dst_dimensions,
        loc_u32,
        transpose,
        project_last_layer_of,
    );

    match result {
        Ok(positions) => Ok(positions.iter().map(|(x, y, z)| (*x as i32, *y as i32, *z as i32)).collect()),
        Err(e) => Err(PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(format!(
            "Rust syn_projector error: {}",
            e
        ))),
    }
}

/// Python-exposed batch projector for parallel processing
///
/// # Arguments
///
/// * `src_area_id` - str
/// * `dst_area_id` - str
/// * `neuron_ids` - List[int]
/// * `neuron_locations` - List[tuple[int, int, int]]
/// * `src_dimensions` - tuple[int, int, int]
/// * `dst_dimensions` - tuple[int, int, int]
/// * `transpose` - Optional[tuple[int, int, int]]
/// * `project_last_layer_of` - Optional[int]
///
/// # Returns
///
/// List[List[tuple[int, int, int]]] - List of position lists (one per neuron)
#[pyfunction]
#[pyo3(signature = (src_area_id, dst_area_id, neuron_ids, neuron_locations, src_dimensions, dst_dimensions, transpose=None, project_last_layer_of=None))]
fn py_syn_projector_batch(
    src_area_id: &str,
    dst_area_id: &str,
    neuron_ids: Vec<u64>,
    neuron_locations: Vec<(i32, i32, i32)>,
    src_dimensions: (usize, usize, usize),
    dst_dimensions: (usize, usize, usize),
    transpose: Option<(usize, usize, usize)>,
    project_last_layer_of: Option<usize>,
) -> PyResult<Vec<Vec<(i32, i32, i32)>>> {
    let locs_u32: Vec<(u32, u32, u32)> = neuron_locations.iter()
        .map(|(x, y, z)| (*x as u32, *y as u32, *z as u32))
        .collect();
    let result = crate::connectivity::rules::syn_projector_batch(
        src_area_id,
        dst_area_id,
        &neuron_ids,
        &locs_u32,
        src_dimensions,
        dst_dimensions,
        transpose,
        project_last_layer_of,
    );

    match result {
        Ok(position_lists) => Ok(position_lists.iter()
            .map(|positions| positions.iter()
                .map(|(x, y, z)| (*x as i32, *y as i32, *z as i32))
                .collect())
            .collect()),
        Err(e) => Err(PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(format!(
            "Rust syn_projector_batch error: {}",
            e
        ))),
    }
}

/// Block connection - maps blocks with scaling factor
#[pyfunction]
fn py_syn_block_connection(
    src_area_id: &str,
    dst_area_id: &str,
    neuron_location: (i32, i32, i32),
    src_dimensions: (usize, usize, usize),
    dst_dimensions: (usize, usize, usize),
    scaling_factor: i32,
) -> PyResult<(i32, i32, i32)> {
    // Convert from Python's i32 coordinates to Rust's u32 coordinates
    let loc_u32 = (neuron_location.0 as u32, neuron_location.1 as u32, neuron_location.2 as u32);
    let scale_u32 = scaling_factor as u32;

    match crate::connectivity::rules::syn_block_connection(
        src_area_id, dst_area_id, loc_u32, src_dimensions, dst_dimensions, scale_u32
    ) {
        Ok((x, y, z)) => Ok((x as i32, y as i32, z as i32)),
        Err(e) => Err(PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(format!("{}", e))),
    }
}

/// Expander - scales coordinates from source to destination
#[pyfunction]
fn py_syn_expander(
    src_area_id: &str,
    dst_area_id: &str,
    neuron_location: (i32, i32, i32),
    src_dimensions: (usize, usize, usize),
    dst_dimensions: (usize, usize, usize),
) -> PyResult<(i32, i32, i32)> {
    let loc_u32 = (neuron_location.0 as u32, neuron_location.1 as u32, neuron_location.2 as u32);
    match crate::connectivity::rules::syn_expander(
        src_area_id, dst_area_id, loc_u32, src_dimensions, dst_dimensions
    ) {
        Ok((x, y, z)) => Ok((x as i32, y as i32, z as i32)),
        Err(e) => Err(PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(format!("{}", e))),
    }
}

/// Expander batch - parallel processing
#[pyfunction]
fn py_syn_expander_batch(
    src_area_id: &str,
    dst_area_id: &str,
    neuron_locations: Vec<(i32, i32, i32)>,
    src_dimensions: (usize, usize, usize),
    dst_dimensions: (usize, usize, usize),
) -> PyResult<Vec<(i32, i32, i32)>> {
    let locs_u32: Vec<(u32, u32, u32)> = neuron_locations.iter()
        .map(|(x, y, z)| (*x as u32, *y as u32, *z as u32))
        .collect();
    match crate::connectivity::rules::syn_expander_batch(
        src_area_id, dst_area_id, &locs_u32, src_dimensions, dst_dimensions
    ) {
        Ok(positions) => Ok(positions.iter().map(|(x, y, z)| (*x as i32, *y as i32, *z as i32)).collect()),
        Err(e) => Err(PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(format!("{}", e))),
    }
}

/// Reducer - binary encoding to multiple positions
#[pyfunction]
fn py_syn_reducer_x(
    src_area_id: &str,
    dst_area_id: &str,
    neuron_location: (i32, i32, i32),
    src_dimensions: (usize, usize, usize),
    dst_dimensions: (usize, usize, usize),
    dst_y_index: i32,
    dst_z_index: i32,
) -> PyResult<Vec<(i32, i32, i32)>> {
    let loc_u32 = (neuron_location.0 as u32, neuron_location.1 as u32, neuron_location.2 as u32);
    match crate::connectivity::rules::syn_reducer_x(
        src_area_id, dst_area_id, loc_u32, src_dimensions, dst_dimensions, dst_y_index as u32, dst_z_index as u32
    ) {
        Ok(positions) => Ok(positions.iter().map(|(x, y, z)| (*x as i32, *y as i32, *z as i32)).collect()),
        Err(e) => Err(PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(format!("{}", e))),
    }
}

/// Python wrapper for MortonSpatialHash
#[pyclass]
struct PyMortonSpatialHash {
    inner: std::sync::Arc<crate::spatial::MortonSpatialHash>,
}

#[pymethods]
impl PyMortonSpatialHash {
    #[new]
    fn new() -> Self {
        Self {
            inner: std::sync::Arc::new(crate::spatial::MortonSpatialHash::new()),
        }
    }

    fn add_neuron(&self, cortical_area: String, x: u32, y: u32, z: u32, neuron_id: u64) -> bool {
        self.inner.add_neuron(cortical_area, x, y, z, neuron_id)
    }

    fn get_neuron_at_coordinate(&self, cortical_area: &str, x: u32, y: u32, z: u32) -> Option<u64> {
        self.inner.get_neuron_at_coordinate(cortical_area, x, y, z)
    }

    fn get_neurons_at_coordinate(&self, cortical_area: &str, x: u32, y: u32, z: u32) -> Vec<u64> {
        self.inner.get_neurons_at_coordinate(cortical_area, x, y, z)
    }

    fn get_neurons_in_region(
        &self,
        cortical_area: &str,
        x1: u32, y1: u32, z1: u32,
        x2: u32, y2: u32, z2: u32,
    ) -> Vec<u64> {
        self.inner.get_neurons_in_region(cortical_area, x1, y1, z1, x2, y2, z2)
    }

    fn get_neuron_position(&self, neuron_id: u64) -> Option<(String, u32, u32, u32)> {
        self.inner.get_neuron_position(neuron_id)
    }

    fn remove_neuron(&self, neuron_id: u64) -> bool {
        self.inner.remove_neuron(neuron_id)
    }

    fn clear(&self) {
        self.inner.clear();
    }

    fn get_stats(&self) -> PyResult<PyObject> {
        Python::with_gil(|py| {
            let stats = self.inner.get_stats();
            let dict = pyo3::types::PyDict::new_bound(py);
            dict.set_item("total_areas", stats.total_areas)?;
            dict.set_item("total_neurons", stats.total_neurons)?;
            dict.set_item("total_occupied_positions", stats.total_occupied_positions)?;
            Ok(dict.to_object(py))
        })
    }
}

/// Morton encode 3D coordinates
#[pyfunction]
fn py_morton_encode_3d(x: u32, y: u32, z: u32) -> PyResult<u64> {
    use crate::spatial::morton_encode_3d;
    Ok(morton_encode_3d(x, y, z))
}

/// Morton decode to 3D coordinates
#[pyfunction]
fn py_morton_decode_3d(morton_code: u64) -> PyResult<(u32, u32, u32)> {
    use crate::spatial::morton_decode_3d;
    Ok(morton_decode_3d(morton_code))
}

/// Vector offset - apply single vector to position
#[pyfunction]
fn py_apply_vector_offset(
    src_position: (i32, i32, i32),
    vector: (i32, i32, i32),
    morphology_scalar: f32,
    dst_dimensions: (usize, usize, usize),
) -> PyResult<Option<(i32, i32, i32)>> {
    let src_u32 = (src_position.0 as u32, src_position.1 as u32, src_position.2 as u32);
    Ok(
        crate::connectivity::rules::apply_vector_offset(src_u32, vector, morphology_scalar, dst_dimensions)
            .map(|(x, y, z)| (x as i32, y as i32, z as i32)),
    )
}

/// Vector batch - apply vector to multiple positions
#[pyfunction]
fn py_match_vectors_batch(
    src_positions: Vec<(i32, i32, i32)>,
    vector: (i32, i32, i32),
    morphology_scalar: f32,
    dst_dimensions: (usize, usize, usize),
) -> PyResult<Vec<(i32, i32, i32)>> {
    let srcs_u32: Vec<(u32, u32, u32)> = src_positions.iter()
        .map(|(x, y, z)| (*x as u32, *y as u32, *z as u32))
        .collect();
    match crate::connectivity::rules::match_vectors_batch(
        &srcs_u32, vector, morphology_scalar, dst_dimensions
    ) {
        Ok(positions) => Ok(positions.iter().map(|(x, y, z)| (*x as i32, *y as i32, *z as i32)).collect()),
        Err(e) => Err(PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(format!("{}", e))),
    }
}

/// Pattern matching - find destinations from pattern rules
/// patterns: list of (src_pattern, dst_pattern) tuples
/// Each pattern is (x, y, z) where elements can be:
///   -1 = wildcard "*"
///   -2 = skip "?"
///   -3 = exclude "!"
///   -10 = direction positive "?+" (all coords > src)
///   -11 = direction negative "?-" (all coords < src)
///   -12 = direction positive inclusive "?+=" (all coords >= src)
///   -13 = direction negative inclusive "?-=" (all coords <= src)
///   >= 0 = exact value
/// Note: Offset and Range patterns require string-based genome encoding.
#[pyfunction]
fn py_match_patterns(
    src_coordinate: (i32, i32, i32),
    patterns: Vec<((i32, i32, i32), (i32, i32, i32))>,
    src_dimensions: (usize, usize, usize),
    dst_dimensions: (usize, usize, usize),
) -> PyResult<Vec<(i32, i32, i32)>> {
    use crate::connectivity::rules::patterns::{PatternElement, match_patterns_batch};

    let src_u32 = (src_coordinate.0 as u32, src_coordinate.1 as u32, src_coordinate.2 as u32);

    // Convert integer patterns to PatternElement
    let parsed_patterns: Vec<_> = patterns.iter().map(|(src, dst)| {
        let src_pattern = (
            PatternElement::from_int(src.0),
            PatternElement::from_int(src.1),
            PatternElement::from_int(src.2),
        );
        let dst_pattern = (
            PatternElement::from_int(dst.0),
            PatternElement::from_int(dst.1),
            PatternElement::from_int(dst.2),
        );
        (src_pattern, dst_pattern)
    }).collect();

    let results = match_patterns_batch(
        src_u32,
        &parsed_patterns,
        src_dimensions,
        dst_dimensions,
    );

    Ok(results.iter().map(|(x, y, z)| (*x as i32, *y as i32, *z as i32)).collect())
}

/// Find source coordinates that match a pattern
#[pyfunction]
fn py_find_source_coordinates(
    src_pattern: (i32, i32, i32),
    src_dimensions: (usize, usize, usize),
) -> PyResult<Vec<(i32, i32, i32)>> {
    use crate::connectivity::rules::patterns::{PatternElement, find_source_coordinates};

    let pattern = (
        PatternElement::from_int(src_pattern.0),
        PatternElement::from_int(src_pattern.1),
        PatternElement::from_int(src_pattern.2),
    );

    let results = find_source_coordinates(&pattern, src_dimensions);
    Ok(results.iter().map(|(x, y, z)| (*x as i32, *y as i32, *z as i32)).collect())
}

/// Randomizer - select random position in destination area
#[pyfunction]
fn py_syn_randomizer(dst_dimensions: (usize, usize, usize)) -> PyResult<(i32, i32, i32)> {
    let (x, y, z) = crate::connectivity::rules::syn_randomizer(dst_dimensions);
    Ok((x as i32, y as i32, z as i32))
}

/// Lateral pairs X - connect neurons in pairs along X axis
#[pyfunction]
fn py_syn_lateral_pairs_x(
    neuron_location: (i32, i32, i32),
    src_dimensions: (usize, usize, usize),
) -> PyResult<Option<(i32, i32, i32)>> {
    let loc_u32 = (neuron_location.0 as u32, neuron_location.1 as u32, neuron_location.2 as u32);
    Ok(crate::connectivity::rules::syn_lateral_pairs_x(loc_u32, src_dimensions)
        .map(|(x, y, z)| (x as i32, y as i32, z as i32)))
}

/// Last to first - connect last neuron to first (feedback connection)
#[pyfunction]
fn py_syn_last_to_first(
    neuron_location: (i32, i32, i32),
    src_dimensions: (usize, usize, usize),
) -> PyResult<Option<(i32, i32, i32)>> {
    let loc_u32 = (neuron_location.0 as u32, neuron_location.1 as u32, neuron_location.2 as u32);
    Ok(crate::connectivity::rules::syn_last_to_first(loc_u32, src_dimensions)
        .map(|(x, y, z)| (x as i32, y as i32, z as i32)))
}

/// Python module initialization (PyO3 0.22 API with Bound)
#[pymodule]
fn feagi_brain_development(m: &Bound<'_, PyModule>) -> PyResult<()> {
    // Projector functions
    m.add_function(wrap_pyfunction!(py_syn_projector, m)?)?;
    m.add_function(wrap_pyfunction!(py_syn_projector_batch, m)?)?;

    // Phase 2 morphologies
    m.add_function(wrap_pyfunction!(py_syn_block_connection, m)?)?;
    m.add_function(wrap_pyfunction!(py_syn_expander, m)?)?;
    m.add_function(wrap_pyfunction!(py_syn_expander_batch, m)?)?;
    m.add_function(wrap_pyfunction!(py_syn_reducer_x, m)?)?;

    // Phase 3C: Vector morphologies
    m.add_function(wrap_pyfunction!(py_apply_vector_offset, m)?)?;
    m.add_function(wrap_pyfunction!(py_match_vectors_batch, m)?)?;

    // Phase 3D: Pattern morphologies
    m.add_function(wrap_pyfunction!(py_match_patterns, m)?)?;
    m.add_function(wrap_pyfunction!(py_find_source_coordinates, m)?)?;

    // Phase 3E: Trivial morphologies
    m.add_function(wrap_pyfunction!(py_syn_randomizer, m)?)?;
    m.add_function(wrap_pyfunction!(py_syn_lateral_pairs_x, m)?)?;
    m.add_function(wrap_pyfunction!(py_syn_last_to_first, m)?)?;

    // Phase 3B: Morton spatial hash
    m.add_class::<PyMortonSpatialHash>()?;
    m.add_function(wrap_pyfunction!(py_morton_encode_3d, m)?)?;
    m.add_function(wrap_pyfunction!(py_morton_decode_3d, m)?)?;

    // Version info
    m.add("__version__", env!("CARGO_PKG_VERSION"))?;
    m.add("__doc__", "FEAGI BDU - High-performance Brain Development Utilities")?;

    Ok(())
}

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

    #[test]
    fn test_ffi_compatibility() {
        // Smoke test to ensure FFI functions compile
        let result = py_syn_projector(
            "src",
            "dst",
            42,
            (128, 128, 3),
            (128, 128, 1),
            (64, 64, 1),
            None,
            None,
        );
        assert!(result.is_ok());
    }
}