Summary Files Commits Branches @commit @diff @stats
path: root / Year 4 / Artificial Intelligence / hw03 / src
diff options
context:
space:
mode:
Commit78d3b4c7dd965539229ca7ec7c43f8174a6b1b36 (patch)
Author
 Syndamia <kamen@syndamia.com>
2024-11-17 19:17:56 +0200
Committer
 Syndamia <kamen@syndamia.com>
2024-11-17 19:17:56 +0200
Files19de36166187030de2b5d941e5ce9b228825069f /Year 4/Artificial Intelligence/hw03/src
uni-projects-78d3b4c7dd965539229ca7ec7c43f8174a6b1b36.tar
uni-projects-78d3b4c7dd965539229ca7ec7c43f8174a6b1b36.tar.gz
uni-projects-78d3b4c7dd965539229ca7ec7c43f8174a6b1b36.zip
Parent10c4219db0fd5957c332e2a98e276107bd5a37b3 (diff)
hw(3/AI): Initial solution
2 files changed, 216 insertions, 0 deletions
-rw-r--r--Year 4/Artificial Intelligence/hw03/src/ex1.rs211
-rw-r--r--Year 4/Artificial Intelligence/hw03/src/main.rs5
diff --git a/Year 4/Artificial Intelligence/hw03/src/ex1.rs b/Year 4/Artificial Intelligence/hw03/src/ex1.rs
new file mode 100644
index 0000000..5da7c9b
--- /dev/null
+++ b/Year 4/Artificial Intelligence/hw03/src/ex1.rs
@@ -0,0 +1,211 @@
+use text_io::{read};
+use rand::{Rng, thread_rng, seq::SliceRandom};
+
+#[derive(Debug)]
+struct Gene {
+ x: f64,
+ y: f64,
+ name: String,
+}
+
+impl Gene {
+ // Eucledian distance between two points
+ fn dist(&self, other: &Self) -> f64 {
+ ((self.x - other.x).powi(2) + (self.y - other.y).powi(2)).sqrt()
+ }
+}
+
+#[derive(Clone, PartialEq, Debug)]
+struct Chromosome {
+ genes: Vec<usize>,
+ fitness: f64,
+}
+
+impl Chromosome {
+ fn new(genes: Vec<usize>, map: &Vec<Gene>) -> Chromosome {
+ let mut ret = Chromosome {
+ genes,
+ fitness: 0.0,
+ };
+ ret.evaluate_fitness(map);
+ ret
+ }
+
+ fn evaluate_fitness(&mut self, map: &Vec<Gene>) {
+ self.fitness = 0.0;
+ for i in 0..self.genes.len() - 1 {
+ self.fitness += map[self.genes[i]].dist(&map[self.genes[i+1]]);
+ }
+ }
+
+ // self & other - parents
+ // Single-point crossover
+ fn crossover_with(&self, other: &Self, map: &Vec<Gene>) -> Vec<Chromosome> {
+ let i = thread_rng().gen_range(0..other.genes.len());
+
+ let mut child1 = self.genes[..i].to_vec();
+ for elem in &other.genes {
+ if child1.len() == other.genes.len() { break; }
+
+ if ! child1.contains(&elem) {
+ child1.push(*elem);
+ }
+ }
+
+ let mut child2 = other.genes[..i].to_vec();
+ for elem in &self.genes {
+ if child2.len() == self.genes.len() { break; }
+
+ if ! child2.contains(&elem) {
+ child2.push(*elem);
+ }
+ }
+
+ vec![
+ Chromosome::new(child1, map),
+ Chromosome::new(child2, map),
+ ]
+ }
+
+ const MUTATION_PROBABILITY: f64 = 0.1;
+
+ fn mutate(&mut self, map: &Vec<Gene>) {
+ let mut rng = thread_rng();
+ if ! rng.gen_bool(Self::MUTATION_PROBABILITY) { return; }
+
+ let (i, j) = (rng.gen_range(0..self.genes.len()), rng.gen_range(0..self.genes.len()));
+ let temp = self.genes[i].clone();
+ self.genes[i] = self.genes[j];
+ self.genes[j] = temp;
+
+ self.evaluate_fitness(map);
+ }
+}
+
+#[derive(Debug)]
+struct Generation {
+ t: usize,
+ map: Vec<Gene>,
+
+ population: Vec<Chromosome>,
+}
+
+impl Generation {
+ const POPULATION_SIZE: usize = 250;
+
+ fn new_population(map: &Vec<Gene>) -> Vec<Chromosome> {
+ let mut rng = thread_rng();
+
+ let mut perm: Vec<usize> = (0..map.len()).collect();
+ let mut ret: Vec<Chromosome> = Vec::new();
+
+ for _ in 0..Self::POPULATION_SIZE {
+ perm.shuffle(&mut rng);
+ ret.push(Chromosome::new(perm.clone(), map));
+ }
+ ret
+ }
+
+ fn new_from_map(map: Vec<Gene>) -> Generation {
+ Generation {
+ t: 0,
+ population: Self::new_population(&map),
+ map,
+ }
+ }
+
+ fn new() -> Generation {
+ Generation {
+ t: 0,
+ map: Vec::new(),
+ population: Vec::new(),
+ }
+ }
+
+ fn selection_crossover(&mut self) {
+ let mut rng = thread_rng();
+ // Roulette selection
+ let sum_fitness: f64 = self.population.iter().map(|x| x.fitness).sum();
+
+ let mut prev_parent = usize::MAX;
+ for i in 0..self.population.len() {
+ if ! rng.gen_bool(self.population[i].fitness / sum_fitness) { continue; }
+
+ if prev_parent != usize::MAX {
+ let children = self.population[prev_parent].crossover_with(&self.population[i], &self.map);
+ self.population[prev_parent] = children[0].clone();
+ self.population[i] = children[1].clone();
+ prev_parent = usize::MAX;
+ }
+ else {
+ prev_parent = i;
+ }
+ }
+ }
+
+ fn mutate(&mut self) {
+ for p in &mut self.population {
+ p.mutate(&self.map);
+ }
+ }
+
+ fn next_generation(mut self) -> Generation {
+ self.t += 1;
+ self
+ }
+
+ const MAX_GENERATIONS: usize = 2000;
+
+ fn terminated(&self) -> bool {
+ self.t == Self::MAX_GENERATIONS || self.population[1..].iter().all(|x| *x == self.population[0])
+ }
+
+ fn best_fitness(&self) -> f64 {
+ self.population
+ .iter()
+ .map(|x| x.fitness)
+ .min_by(|a, b| a.partial_cmp(b).unwrap())
+ .unwrap()
+ }
+}
+
+pub fn main() {
+ let mut G: Generation;
+ let input: String = read!();
+ let N = input.parse::<usize>();
+
+ if N.is_ok() {
+ let N = N.unwrap();
+ G = Generation::new();
+ }
+ else {
+ let names: Vec<String> = std::fs::read_to_string([input.clone(), "_name.csv".to_string()].concat())
+ .expect("Couldn't open points file: ..._name.csv")
+ .lines()
+ .map(|x| x.to_string())
+ .collect();
+ let points: Vec<Gene> = std::fs::read_to_string([input, "_xy.csv".to_string()].concat())
+ .expect("Couldn't open points file: ..._xy.csv")
+ .lines()
+ .enumerate()
+ .map(|(i, l)| {
+ let coords: Vec<&str> = l.split(',').collect();
+ Gene {
+ x: coords[0].parse::<f64>().unwrap(),
+ y: coords[1].parse::<f64>().unwrap(),
+ name: names[i].clone(),
+ }
+ })
+ .collect();
+ G = Generation::new_from_map(points);
+ println!("{:?}", G);
+ }
+
+ println!("{}", G.best_fitness());
+ while ! G.terminated() {
+ G.selection_crossover();
+ G.mutate();
+ G = G.next_generation();
+ }
+ println!("{}", G.best_fitness());
+}
diff --git a/Year 4/Artificial Intelligence/hw03/src/main.rs b/Year 4/Artificial Intelligence/hw03/src/main.rs
new file mode 100644
index 0000000..e43d43f
--- /dev/null
+++ b/Year 4/Artificial Intelligence/hw03/src/main.rs
@@ -0,0 +1,5 @@
+mod ex1;
+
+fn main() {
+ ex1::main();
+}