pub fn phi_quantized_encode(w: f64, n: usize, step: f64) -> f64Expand description
Encode with quantization: round(approx / step) * step
Examples found in repository?
examples/quantized_demo.rs (line 40)
29fn main() {
30 let (n, step) = parse_args();
31 let values = [-1000.0, -100.0, -1.0, 0.0, 1.0, 42.0, 123.456, 999.99];
32
33 println!("Quantized φ-memory demo (N = {}, step = {})\n", n, step);
34 println!(
35 "{:<10} {:>12} {:>12} {:>12}",
36 "w", "quantized", "recovered", "error"
37 );
38
39 for &w in &values {
40 let q = phi_quantized_encode(w, n, step);
41 let recon = phi_quantized_decode(q, n);
42 let err = (w - recon).abs();
43
44 println!(
45 "{:<10.3} {:>12.6} {:>12.6} {:>12.3e}",
46 w, q, recon, err
47 );
48 }
49}More examples
examples/save_load_demo.rs (line 18)
9fn main() {
10 let values = [-1000.0, -1.0, 0.0, 1.0, 42.0, 123.456, 999.99];
11 let n = 10;
12 let step = 0.01;
13 let path = Path::new("phi_memory.bin");
14
15 // Encode & quantize
16 let encoded: Vec<f64> = values
17 .iter()
18 .map(|&w| phi_quantized_encode(w, n, step))
19 .collect();
20
21 // Save to disk
22 save_quantized(&encoded, &path).expect("save failed");
23 println!("Saved {} entries to {:?}", encoded.len(), path);
24
25 // Load from disk
26 let loaded = load_quantized(&path).expect("load failed");
27 println!("Loaded {} entries from disk\n", loaded.len());
28
29 println!(
30 "{:<10} {:>12} {:>12} {:>12}",
31 "original", "quantized", "recovered", "error"
32 );
33
34 for ((&w, &q), r) in values.iter().zip(loaded.iter()).zip(loaded.iter().map(|&q| hybrid_phi_inverse(q, n))) {
35 let err = (w - r).abs();
36 println!(
37 "{:<10.3} {:>12.6} {:>12.6} {:>12.3e}",
38 w, q, r, err
39 );
40 }
41
42 // Optionally: remove file after demo
43 let _ = std::fs::remove_file(path);
44}examples/fs_demo.rs (line 19)
11fn main() {
12 let n = 10;
13 let step = 0.01;
14 let values = [1.0, 2.0, 3.14, 42.0];
15 let name = "phi_shape";
16 let store = PhiMemoryStore::new(".phi_store");
17
18 // Encode and store
19 let encoded: Vec<f64> = values.iter().map(|&w| phi_quantized_encode(w, n, step)).collect();
20 store.save(name, &encoded).expect("failed to save");
21
22 // Save metadata
23 let metadata_path = Path::new(".phi_store").join(format!("{}.meta.txt", name));
24 let mut meta_file = File::create(&metadata_path).expect("failed to create metadata");
25 writeln!(meta_file, "n={}", n).unwrap();
26 writeln!(meta_file, "step={:.5}", step).unwrap();
27 writeln!(meta_file, "length={}", encoded.len()).unwrap();
28 writeln!(meta_file, "saved_at={:?}", chrono::Utc::now()).unwrap();
29
30 // List contents
31 let entries = store.list().expect("failed to list");
32 println!("Stored φ-entries:");
33 for entry in entries {
34 println!("- {}", entry);
35 }
36
37 // Load and decode
38 let loaded = store.load(name).expect("failed to load");
39 println!("\nDecoded values from '{}':", name);
40 for (i, &q) in loaded.iter().enumerate() {
41 let r = hybrid_phi_inverse(q, n);
42 println!(" index {}: quant = {:.6}, recon = {:.6}", i, q, r);
43 }
44
45 // Optional cleanup
46 let _ = fs::remove_dir_all(".phi_store");
47}examples/router_demo.rs (line 43)
28fn main() {
29 let n = 10;
30 let (step, threshold, verbose) = parse_args();
31 let store = PhiMemoryStore::new(".phi_store");
32
33 // Define and encode reference signals
34 let patterns = vec![
35 ("calm", vec![0.1, 0.1, 0.1, 0.1]),
36 ("ramp", vec![0.1, 0.2, 0.3, 0.4]),
37 ("burst", vec![1.0, 2.0, 3.0, 4.0]),
38 ];
39
40 for (name, signal) in &patterns {
41 let encoded: Vec<f64> = signal
42 .iter()
43 .map(|&x| phi_quantized_encode(x, n, step))
44 .collect();
45 store.save(name, &encoded).expect("save failed");
46 }
47
48 // Simulate input (similar to "burst")
49 let input_signal = vec![0.95, 2.05, 3.1, 3.95];
50 let encoded_input: Vec<f64> = input_signal
51 .iter()
52 .map(|&x| phi_quantized_encode(x, n, step))
53 .collect();
54
55 if verbose {
56 println!("\nSimilarity to each pattern:");
57 let names = store.list().expect("failed to list");
58 for name in names {
59 if let Ok(entry) = store.load(&name) {
60 let score = phi_similarity(&encoded_input, &entry);
61 println!("- {}: {:.3}%", name, score * 100.0);
62 }
63 }
64 }
65
66 // Route input
67 match phi_route(&encoded_input, &store, threshold) {
68 Some((name, score)) => {
69 println!("\nInput routed to '{}', similarity = {:.3}%", name, score * 100.0);
70 }
71 None => println!("\nNo matching route found (threshold = {:.2})", threshold),
72 }
73
74 // Optional cleanup
75 let _ = std::fs::remove_dir_all(".phi_store");
76}examples/phi_app.rs (line 40)
22fn main() {
23 let args: Vec<String> = env::args().collect();
24 if args.len() < 2 {
25 eprintln!("Usage:\n encode <name>\n route --input=... [--threshold=0.9] [--verbose]\n list\n delete <name>\n describe <name>\n export <name> --to=file.json\n import <name> --from=file.json");
26 return;
27 }
28
29 let mode = &args[1];
30 let store = PhiMemoryStore::new(".phi_store");
31 let n = 10;
32 let step = 0.01;
33
34 if mode == "encode" && args.len() >= 3 {
35 let name = &args[2];
36 println!("Encoding input signal for '{}'. Enter comma-separated values:", name);
37 let mut buf = String::new();
38 std::io::stdin().read_line(&mut buf).unwrap();
39 let signal = parse_input_vec(&buf);
40 let encoded: Vec<f64> = signal.iter().map(|&x| phi_quantized_encode(x, n, step)).collect();
41 store.save(name, &encoded).expect("failed to save");
42 let meta = PhiMetadata {
43 n,
44 step,
45 length: encoded.len(),
46 saved_at: chrono::Utc::now(),
47 };
48 meta.save(name, ".phi_store").expect("failed to save metadata");
49 println!("Saved {} values to '{}'.", encoded.len(), name);
50 return;
51 }
52
53 if mode == "route" {
54 let mut input: Option<Vec<f64>> = None;
55 let mut threshold = 0.8;
56 let mut verbose = false;
57
58 for arg in &args[2..] {
59 if let Some(v) = arg.strip_prefix("--input=") {
60 input = Some(parse_input_vec(v));
61 }
62 if let Some(v) = arg.strip_prefix("--threshold=") {
63 threshold = v.parse().unwrap_or(threshold);
64 }
65 if arg == "--verbose" {
66 verbose = true;
67 }
68 }
69
70 let input = input.expect("Missing --input argument");
71 let encoded_input: Vec<f64> = input.iter().map(|&x| phi_quantized_encode(x, n, step)).collect();
72
73 if verbose {
74 println!("Similarity to each stored φ-memory:");
75 for name in store.list().unwrap_or_default() {
76 if let Ok(entry) = store.load(&name) {
77 let score = phi_similarity(&encoded_input, &entry);
78 println!("- {}: {:.3}%", name, score * 100.0);
79 }
80 }
81 }
82
83 match phi_route(&encoded_input, &store, threshold) {
84 Some((name, score)) => println!("\nInput routed to '{}', score = {:.3}%", name, score * 100.0),
85 None => println!("\nNo route found (threshold = {:.2})", threshold),
86 }
87 return;
88 }
89
90 if mode == "list" {
91 let entries = store.list().unwrap_or_default();
92 println!("Stored φ-memories:");
93 for name in entries {
94 println!("- {}", name);
95 }
96 return;
97 }
98
99 if mode == "delete" && args.len() >= 3 {
100 let name = &args[2];
101 let _ = fs::remove_file(format!(".phi_store/{}.bin", name));
102 let _ = fs::remove_file(format!(".phi_store/{}.meta.txt", name));
103 println!("Deleted memory '{}'.", name);
104 return;
105 }
106
107 if mode == "describe" && args.len() >= 3 {
108 let name = &args[2];
109 match PhiMetadata::load(name, ".phi_store") {
110 Ok(meta) => {
111 println!("φ-memory '{}':", name);
112 println!(" length = {}", meta.length);
113 println!(" n = {}", meta.n);
114 println!(" step = {:.5}", meta.step);
115 println!(" saved_at = {}", meta.saved_at);
116 }
117 Err(err) => {
118 println!("Failed to load metadata: {}", err);
119 }
120 }
121 return;
122 }
123
124 if mode == "export" && args.len() >= 4 {
125 let name = &args[2];
126 let mut out_path = None;
127 for arg in &args[3..] {
128 if let Some(p) = arg.strip_prefix("--to=") {
129 out_path = Some(p);
130 }
131 }
132 let out_path = out_path.expect("Missing --to=... argument");
133 let bundle = PhiBundle::from_store(name, &store).expect("failed to bundle");
134 bundle.save_json(out_path).expect("failed to save json");
135 println!("Exported '{}' to '{}'.", name, out_path);
136 return;
137 }
138
139 if mode == "import" && args.len() >= 4 {
140 let name = &args[2];
141 let mut in_path = None;
142 for arg in &args[3..] {
143 if let Some(p) = arg.strip_prefix("--from=") {
144 in_path = Some(p);
145 }
146 }
147 let in_path = in_path.expect("Missing --from=... argument");
148 let bundle = PhiBundle::load_json(in_path).expect("failed to load json");
149 bundle.save_to_store(&store).expect("failed to restore");
150 println!("Imported '{}' from '{}'.", name, in_path);
151 return;
152 }
153
154 eprintln!("Unknown mode '{}'. Use 'encode', 'route', 'list', 'delete', 'describe', 'export', or 'import'", mode);
155}