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