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