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