1use super::phenotype::Phenotype;
2use crate::cell::MutCell;
3use crate::objectives::Scored;
4use crate::{Chromosome, Score};
5#[cfg(feature = "serde")]
6use serde::{Deserialize, Serialize};
7use std::fmt::Debug;
8use std::ops::{Index, IndexMut, Range};
9
10#[derive(Clone, Default, PartialEq)]
37pub struct Population<C: Chromosome> {
38 individuals: Vec<Member<C>>,
39}
40
41impl<C: Chromosome> Population<C> {
42 pub fn new(individuals: Vec<Phenotype<C>>) -> Self {
43 Population {
44 individuals: individuals.into_iter().map(Member::from).collect(),
45 }
46 }
47
48 pub fn members(&self) -> &[Member<C>] {
49 &self.individuals
50 }
51
52 pub fn get(&self, index: usize) -> Option<&Phenotype<C>> {
53 self.individuals.get(index).map(|cell| cell.get())
54 }
55
56 pub fn get_mut(&mut self, index: usize) -> Option<&mut Phenotype<C>> {
57 self.individuals.get_mut(index).map(|cell| cell.get_mut())
58 }
59
60 pub fn get_cell_mut(&mut self, index: usize) -> Option<&mut Member<C>> {
61 self.individuals.get_mut(index)
62 }
63
64 pub fn get_cell(&self, index: usize) -> Option<&Member<C>> {
65 self.individuals.get(index)
66 }
67
68 pub fn push(&mut self, individual: impl Into<Member<C>>) {
69 self.individuals.push(individual.into());
70 }
71
72 pub fn iter(&self) -> impl Iterator<Item = &Phenotype<C>> {
73 self.individuals.iter().map(Member::get)
74 }
75
76 pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut Phenotype<C>> {
77 self.individuals.iter_mut().map(Member::get_mut)
78 }
79
80 pub fn len(&self) -> usize {
81 self.individuals.len()
82 }
83
84 pub fn clear(&mut self) {
85 self.individuals.clear();
86 }
87
88 pub fn is_empty(&self) -> bool {
89 self.individuals.is_empty()
90 }
91
92 pub fn get_scores(&self) -> Vec<&Score> {
93 self.individuals
94 .iter()
95 .filter_map(|individual| individual.get().score())
96 .collect()
97 }
98
99 pub fn get_pair_mut(
100 &mut self,
101 first: usize,
102 second: usize,
103 ) -> Option<(&mut Phenotype<C>, &mut Phenotype<C>)> {
104 if first == second {
105 None
106 } else if first < second {
107 let (left, right) = self.individuals.split_at_mut(second);
108 Some((left[first].get_mut(), right[0].get_mut()))
109 } else {
110 let (left, right) = self.individuals.split_at_mut(first);
111 Some((right[0].get_mut(), left[second].get_mut()))
112 }
113 }
114}
115
116impl<C: Chromosome + Clone> From<&Population<C>> for Population<C> {
117 fn from(population: &Population<C>) -> Self {
118 population
119 .iter()
120 .map(|individual| individual.clone())
121 .collect::<Population<C>>()
122 }
123}
124
125impl<C: Chromosome> From<Vec<Phenotype<C>>> for Population<C> {
126 fn from(individuals: Vec<Phenotype<C>>) -> Self {
127 Population {
128 individuals: individuals.into_iter().map(Member::from).collect(),
129 }
130 }
131}
132
133impl<C: Chromosome> From<Vec<Member<C>>> for Population<C> {
134 fn from(individuals: Vec<Member<C>>) -> Self {
135 Population { individuals }
136 }
137}
138
139impl<C: Chromosome> AsRef<[Member<C>]> for Population<C> {
140 fn as_ref(&self) -> &[Member<C>] {
141 self.individuals.as_ref()
142 }
143}
144
145impl<C: Chromosome> AsMut<[Member<C>]> for Population<C> {
146 fn as_mut(&mut self) -> &mut [Member<C>] {
147 self.individuals.as_mut()
148 }
149}
150
151impl<C: Chromosome> Index<Range<usize>> for Population<C> {
152 type Output = [Member<C>];
153 fn index(&self, index: Range<usize>) -> &Self::Output {
154 &self.individuals[index]
155 }
156}
157
158impl<C: Chromosome> Index<usize> for Population<C> {
159 type Output = Phenotype<C>;
160
161 fn index(&self, index: usize) -> &Self::Output {
162 &self.individuals[index].get()
163 }
164}
165
166impl<C: Chromosome> IndexMut<usize> for Population<C> {
167 fn index_mut(&mut self, index: usize) -> &mut Self::Output {
168 self.individuals[index].get_mut()
169 }
170}
171
172impl<C: Chromosome + Clone> IntoIterator for Population<C> {
173 type Item = Phenotype<C>;
174 type IntoIter = std::vec::IntoIter<Phenotype<C>>;
175
176 fn into_iter(self) -> Self::IntoIter {
177 self.individuals
178 .into_iter()
179 .map(|cell| cell.into_inner())
180 .collect::<Vec<_>>()
181 .into_iter()
182 }
183}
184
185impl<C: Chromosome> FromIterator<Phenotype<C>> for Population<C> {
186 fn from_iter<I: IntoIterator<Item = Phenotype<C>>>(iter: I) -> Self {
187 Population {
188 individuals: iter.into_iter().map(Member::from).collect(),
189 }
190 }
191}
192
193impl<C: Chromosome> FromIterator<Member<C>> for Population<C> {
194 fn from_iter<I: IntoIterator<Item = Member<C>>>(iter: I) -> Self {
195 let individuals = iter.into_iter().collect::<Vec<Member<C>>>();
196 Population { individuals }
197 }
198}
199
200impl<C: Chromosome, F> From<(usize, F)> for Population<C>
204where
205 F: Fn() -> Phenotype<C>,
206{
207 fn from((size, f): (usize, F)) -> Self {
208 let mut individuals = Vec::with_capacity(size);
209 for _ in 0..size {
210 individuals.push(f());
211 }
212
213 Population {
214 individuals: individuals.into_iter().map(Member::from).collect(),
215 }
216 }
217}
218
219impl<C: Chromosome + Debug> Debug for Population<C> {
220 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
221 write!(f, "Population [\n")?;
222 for individual in &self.individuals {
223 write!(f, "{:?},\n ", individual.get())?;
224 }
225 write!(f, "]")
226 }
227}
228
229#[cfg(feature = "serde")]
230impl<C: Chromosome + Serialize> Serialize for Population<C> {
231 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
232 where
233 S: serde::Serializer,
234 {
235 let phenotypes: Vec<&Phenotype<C>> = self.individuals.iter().map(Member::get).collect();
236 phenotypes.serialize(serializer)
237 }
238}
239
240#[cfg(feature = "serde")]
241impl<'de, C: Chromosome + Deserialize<'de>> Deserialize<'de> for Population<C> {
242 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
243 where
244 D: serde::Deserializer<'de>,
245 {
246 let phenotypes = Vec::<Phenotype<C>>::deserialize(deserializer)?;
247
248 Ok(Population {
249 individuals: phenotypes.into_iter().map(Member::from).collect(),
250 })
251 }
252}
253
254#[derive(Clone, PartialEq)]
255pub struct Member<C: Chromosome> {
256 cell: MutCell<Phenotype<C>>,
257}
258
259impl<C: Chromosome> Member<C> {
260 pub fn get(&self) -> &Phenotype<C> {
261 self.cell.get()
262 }
263
264 pub fn get_mut(&mut self) -> &mut Phenotype<C> {
265 self.cell.get_mut()
266 }
267
268 pub fn into_inner(self) -> Phenotype<C>
269 where
270 C: Clone,
271 {
272 self.cell.into_inner()
273 }
274
275 pub fn is_unique(&self) -> bool {
276 self.cell.is_unique()
277 }
278}
279
280impl<C: Chromosome + Debug> Debug for Member<C> {
281 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
282 write!(f, "{:?}", self.get())
283 }
284}
285
286impl<C: Chromosome + PartialEq> PartialOrd for Member<C> {
287 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
288 self.get().partial_cmp(other.get())
289 }
290}
291
292impl<C: Chromosome> From<Phenotype<C>> for Member<C> {
293 fn from(p: Phenotype<C>) -> Self {
294 Member {
295 cell: MutCell::from(p),
296 }
297 }
298}
299
300impl<C: Chromosome> Scored for Member<C> {
301 fn score(&self) -> Option<&Score> {
302 self.get().score()
303 }
304}
305
306unsafe impl<C: Chromosome> Send for Member<C> {}
307unsafe impl<C: Chromosome> Sync for Member<C> {}
308
309#[cfg(test)]
310mod test {
311 use super::*;
312 use crate::{CharChromosome, FloatChromosome, Score, objectives::Optimize};
313
314 #[test]
315 fn test_new() {
316 let population = Population::<CharChromosome>::default();
317 assert_eq!(population.len(), 0);
318 }
319
320 #[test]
321 fn test_from_vec() {
322 let individuals = vec![
323 Phenotype::from((vec![CharChromosome::from("hello")], 0)),
324 Phenotype::from((vec![CharChromosome::from("world")], 0)),
325 ];
326
327 let population = Population::new(individuals.clone());
328 assert_eq!(population.len(), individuals.len());
329 }
330
331 #[test]
332 fn test_from_fn() {
333 let population = Population::from((10, || {
334 Phenotype::from((vec![CharChromosome::from("hello")], 0))
335 }));
336
337 assert_eq!(population.len(), 10);
338
339 for individual in population.iter() {
340 assert_eq!(individual.genotype().len(), 1);
341 assert_eq!(individual.genotype().iter().next().unwrap().len(), 5);
342 }
343 }
344
345 #[test]
346 fn test_is_empty() {
347 let population = Population::<CharChromosome>::default();
348 assert!(population.is_empty());
349 }
350
351 #[test]
352 fn test_sort_by() {
353 let mut population = Population::from((10, || {
354 Phenotype::from((vec![FloatChromosome::from((10, -10.0..10.0))], 0))
355 }));
356
357 for i in 0..population.len() {
358 population[i].set_score(Some(Score::from(i)));
359 }
360
361 let mut minimize_population = population.clone();
362 let mut maximize_population = population.clone();
363
364 Optimize::Minimize.sort(&mut minimize_population);
365 Optimize::Maximize.sort(&mut maximize_population);
366
367 for i in 0..population.len() {
368 assert_eq!(minimize_population[i].score().unwrap().as_usize(), i);
369 assert_eq!(
370 maximize_population[i].score().unwrap().as_usize(),
371 population.len() - i - 1
372 );
373 }
374 }
375
376 #[test]
377 fn test_population_get() {
378 let population = Population::new(vec![
379 Phenotype::from((vec![CharChromosome::from("hello")], 0)),
380 Phenotype::from((vec![CharChromosome::from("world")], 0)),
381 ]);
382
383 assert_eq!(population.get(0).unwrap().genotype().len(), 1);
384 assert_eq!(population.get(1).unwrap().genotype().len(), 1);
385 assert_eq!(population.get(0).unwrap().genotype()[0].len(), 5);
386 assert_eq!(population.get(1).unwrap().genotype()[0].len(), 5);
387 }
388
389 #[test]
390 fn test_population_get_mut() {
391 let mut population = Population::new(vec![
392 Phenotype::from((vec![CharChromosome::from("hello")], 0)),
393 Phenotype::from((vec![CharChromosome::from("world")], 0)),
394 ]);
395
396 if let Some(individual) = population.get_mut(0) {
397 individual.set_score(Some(Score::from(1.0)));
398 }
399
400 if let Some(individual) = population.get_mut(1) {
401 individual.set_score(Some(Score::from(2.0)));
402 }
403
404 assert_eq!(population.get(0).unwrap().score().unwrap().as_f32(), 1.0);
405 assert_eq!(population.get(1).unwrap().score().unwrap().as_f32(), 2.0);
406 }
407
408 #[test]
409 #[cfg(feature = "serde")]
410 fn test_population_can_serialize() {
411 let individuals = vec![
412 Phenotype::from((vec![CharChromosome::from("hello")], 0)),
413 Phenotype::from((vec![CharChromosome::from("world")], 0)),
414 ];
415 let population = Population::new(individuals.clone());
416
417 let serialized =
418 serde_json::to_string(&population).expect("Failed to serialize Population");
419 let deserialized: Population<CharChromosome> =
420 serde_json::from_str(&serialized).expect("Failed to deserialize Population");
421
422 assert_eq!(population, deserialized);
423 }
424}