optimization_tools 0.1.0

Playground for experimenting with optimization algorithms.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
use crate::*;
use sudoku::{ Board, BlockIndex, CellIndex };
use deterministic_rand::Seed;
// use log::*;

pub fn sleep()
{
  std::thread::sleep( std::time::Duration::from_secs( 5 ) );
}

trait BoardExt
{

  /// Validate that each bloack has at least one non-fixed cell
  fn validate_each_block_has_non_fixed_cell( &self ) -> bool;

}

impl BoardExt for Board
{

  fn validate_each_block_has_non_fixed_cell( &self ) -> bool
  {
    for block in self.blocks()
    {
      let fixed = self.block_cells( block )
      .map( | cell | self.cell( cell ) )
      .fold( 0, | acc, e | if e == 0.into() { acc + 1 } else { acc } )
      ;
      if fixed == 0 || fixed >= 8
      {
        return false;
      }
    }
    true
  }

}

pub fn cells_pair_random_in_block( initial : &Board, block : BlockIndex, hrng : Hrng ) -> ( CellIndex, CellIndex )
{

  debug_assert!( initial.validate_each_block_has_non_fixed_cell() );

  let cell1 = loop
  {
    let cell1 = CellIndex::random_in_block( block, hrng.clone() );
    log::trace!( "cell1 : {cell1:?}" );
    let is_fixed = initial.cell( cell1 ) != 0.into();
    if !is_fixed
    {
      break cell1;
    }
  };

  let cell2 = loop
  {
    let cell2 = CellIndex::random_in_block( block, hrng.clone() );
    log::trace!( "cell2 : {cell2:?}" );
    if cell1 == cell2
    {
      continue;
    }
    let is_fixed = initial.cell( cell2 ) != 0.into();
    if !is_fixed
    {
      break cell2;
    }
  };

  ( cell1, cell2 )
}

use derive_tools::{ FromInner, InnerFrom, Display };
use derive_tools::{ Add, Sub, Mul, Div, AddAssign, SubAssign, MulAssign, DivAssign };

#[ derive( Default, Debug, Display, Clone, Copy, PartialEq, Eq, Ord, PartialOrd, Hash, FromInner, InnerFrom ) ]
#[ derive( Add, Sub, Mul, Div, AddAssign, SubAssign, MulAssign, DivAssign ) ]
pub struct SudokuCost( usize );

// xxx : derive, please
impl SudokuCost
{
  pub fn unwrap( self ) -> usize
  {
    self.0
  }
}

impl From< SudokuCost > for f64
{
  #[ inline ]
  fn from( src : SudokuCost ) -> Self
  {
    src.0 as f64
  }
}

#[ derive( Default, Debug, Display, Clone, Copy, PartialEq, PartialOrd, FromInner, InnerFrom ) ]
#[ derive( Add, Sub, Mul, Div, AddAssign, SubAssign, MulAssign, DivAssign ) ]
pub struct Temperature( f64 );

impl Temperature
{
  pub fn unwrap( &self ) -> f64
  {
    self.0
  }
}

impl From< f32 > for Temperature
{
  #[ inline ]
  fn from( src : f32 ) -> Self
  {
    Self( src as f64 )
  }
}

#[ derive( Debug, Display, Clone, Copy, PartialEq, PartialOrd, FromInner, InnerFrom ) ]
#[ derive( Add, Sub, Mul, Div, AddAssign, SubAssign, MulAssign, DivAssign ) ]
pub struct TemperatureFactor( f64 );

impl TemperatureFactor
{
  pub fn unwrap( &self ) -> f64
  {
    self.0
  }
}

impl Default for TemperatureFactor
{
  fn default() -> Self
  {
    0.001.into()
  }
}

impl From< f32 > for TemperatureFactor
{
  #[ inline ]
  fn from( src : f32 ) -> Self
  {
    Self( src as f64 )
  }
}

#[ derive( PartialEq, Eq, Clone, Copy, Debug, Display ) ]
pub enum Reason
{
  GoodEnough,
  NotFinished,
  ResetLimit,
  GenerationLimit,
}

#[ derive( PartialEq, Eq, Clone, Debug ) ]
pub struct SudokuPerson
{
  pub board : Board,
  pub cost : SudokuCost,
}

impl SudokuPerson
{

  pub fn new( initial : &SudokuInitial ) -> Self
  {
    let mut board = initial.board.clone();
    board.fill_missing_randomly( initial.hrng.clone() );
    let cost : SudokuCost = board.total_error().into();
    SudokuPerson { board, cost }
  }

  pub fn mutate( &self, _initial : &SudokuInitial, mutagen : &SudokuMutagen ) -> Self
  {
    let mut new = self.clone();
    log::trace!( "cells_swap( {:?}, {:?} )", mutagen.cell1, mutagen.cell2 );
    new.board.cells_swap( mutagen.cell1, mutagen.cell2 );
    new.cost -= self.board.cross_error( mutagen.cell1 ).into();
    new.cost -= self.board.cross_error( mutagen.cell2 ).into();
    new.cost += new.board.cross_error( mutagen.cell1 ).into();
    new.cost += new.board.cross_error( mutagen.cell2 ).into();
    new
  }

  pub fn mutate_random( &self, initial : &SudokuInitial, hrng : Hrng ) -> Self
  {
    let mutagen = self.mutagen( initial, hrng );
    self.mutate( &initial, &mutagen.into() )
  }

  pub fn mutagen( &self, initial : &SudokuInitial, hrng : Hrng ) -> SudokuMutagen
  {
    let rng_ref = hrng.rng_ref();
    let mut rng = rng_ref.lock().unwrap();
    let block : BlockIndex = rng.gen();
    drop( rng );
    let mutagen = cells_pair_random_in_block( &initial.board, block, hrng );
    mutagen.into()
  }

}

#[ derive( PartialEq, Eq, Clone, Debug, FromInner, InnerFrom ) ]
pub struct SudokuMutagen
{
  pub cell1 : CellIndex,
  pub cell2 : CellIndex,
}

#[ derive( Clone, Debug ) ]
pub struct SudokuInitial
{
  pub board : Board,
  pub seed : Seed,
  pub hrng : Hrng,
  pub n_mutations_per_generation_limit : usize,
  pub n_resets_limit : usize,
  pub n_generations_limit : usize,
  pub temperature_decrease_factor : TemperatureFactor,
  pub temperature_increase_factor : TemperatureFactor,
}

// impl Default for SudokuInitial
// {
//   fn default() -> Self
//   {
//     let board = Default::new();
//     let seed = Default::new();
//     let hrng = Hrng::master_with_seed( seed.clone() );
//     let temperature_decrease_factor = Default::new();
//   }
// }

impl SudokuInitial
{

  pub fn new( board : Board, seed : Seed ) -> Self
  {
    let hrng = Hrng::master_with_seed( seed.clone() );
    let temperature_decrease_factor = Default::default();
    let temperature_increase_factor = 1.0f64.into(); // xxx
    let n_mutations_per_generation_limit = 2_000; // xxx
    let n_resets_limit = 1_000; // xxx
    let n_generations_limit = 1_000_000;
    Self
    {
      board,
      seed,
      hrng,
      n_mutations_per_generation_limit,
      n_resets_limit,
      n_generations_limit,
      temperature_decrease_factor,
      temperature_increase_factor,
    }
  }

  pub fn initial_generation( &self ) -> SudokuGeneration
  {
    let person = SudokuPerson::new( self );
    let temperature = self.initial_temperature();
    let hrng = self.hrng.clone();
    let n_resets = 0;
    let n_generation = 0;
    SudokuGeneration { initial : self, hrng, person, temperature, n_resets, n_generation }
  }

  pub fn initial_temperature( &self ) -> Temperature
  {
    use statrs::statistics::Statistics;
    let state = SudokuPerson::new( self );
    const N : usize = 16;
    let mut costs : [ f64 ; N ] = [ 0.0 ; N ];
    for i in 0..N
    {
      let state2 = state.mutate_random( self, self.hrng.clone() );
      costs[ i ] = state2.cost.into();
    }
    costs[..].std_dev().into()
  }

  pub fn solve_with_sa( &self ) -> ( Reason, Option< SudokuGeneration > )
  {
    let mut generation = self.initial_generation();
    // let mut n_generation : usize = 0;

    // xxx : optimize, make sure it use not more than 2 enitties of generation
    loop
    {
      // n_generation += 1;
      if generation.n_generation > self.n_generations_limit
      {
        return ( Reason::GenerationLimit, None );
      }

      log::trace!( "\n= n_generation : {}\n", generation.n_generation );

      // log::trace!( "\n= n_generation : {n_generation}\n" );
      // println!( "max_level : {}", log::max_level() );

      let ( reason, generation2 ) = generation.mutate( generation.hrng.clone() );
      if generation2.is_none()
      {
        return ( reason, None );
      }
      let generation2 = generation2.unwrap();
      if generation2.is_good_enough()
      {
        return ( Reason::GoodEnough, Some( generation2 ) );
      }

      generation = generation2;
    }
  }

}

#[ derive( Clone, Debug ) ]
pub struct SudokuGeneration< 'a >
{
  initial : &'a SudokuInitial,
  hrng : Hrng,
  pub person : SudokuPerson,
  temperature : Temperature,
  n_resets : usize,
  n_generation : usize,
}

impl< 'a > SudokuGeneration< 'a >
{

  pub fn mutate( &self, hrng : Hrng ) -> ( Reason, Option< Self > )
  {
    let initial = self.initial;
    let mut temperature = self.temperature;
    let mut n_mutations : usize = 0;
    let mut n_resets : usize = self.n_resets;

    let person = loop
    {

      if n_mutations > initial.n_mutations_per_generation_limit
      {
        n_resets += 1;
        if n_resets >= initial.n_resets_limit
        {
          return ( Reason::ResetLimit, None );
        }
        let temperature2 = ( temperature.unwrap() + initial.temperature_increase_factor.unwrap() ).into();
        log::trace!( " 🔄 reset temperature {temperature} -> {temperature2}" );
        sleep();
        temperature = temperature2;
        n_mutations = 0;
      }

      let mutagen = self.person.mutagen( initial, hrng.clone() );
      let person = self.person.mutate( initial, &mutagen );

      let rng_ref = hrng.rng_ref();
      let mut rng = rng_ref.lock().unwrap();

      let cost_difference = 0.5 + person.cost.unwrap() as f64 - self.person.cost.unwrap() as f64;
      let threshold = ( - cost_difference / temperature.unwrap() ).exp();
      log::trace!
      (
        "cost : {} -> {} | cost_difference : {cost_difference} | temperature : {temperature}",
        self.person.cost,
        person.cost,
      );
      let rand : f64 = rng.gen();
      let vital = rand < threshold;
      if vital
      {
        let emoji = if cost_difference > 0.0
        {
          "🔼"
        }
        else if cost_difference < 0.0
        {
          "✔️"
        }
        else
        {
          "🔘"
        };
        log::trace!( " {emoji} vital | rand( {rand} ) < threshold( {threshold} )" );
        if cost_difference == 0.0
        {
          // sleep();
        }
      }
      else
      {
        log::trace!( " ❌ non-vital | rand( {rand} ) > threshold( {threshold} )" );
      }


      // info!( target = threshold ); xxx

      if vital
      {
        break person;
      }

      n_mutations += 1;
    };

    temperature = Temperature::from( temperature.unwrap() * ( 1.0f64 - self.initial.temperature_decrease_factor.unwrap() ) );
    let n_generation = self.n_generation + 1;

    let generation = SudokuGeneration { initial, hrng, person, temperature, n_resets, n_generation };

    ( Reason::NotFinished, Some( generation ) )
  }

  pub fn is_good_enough( &self ) -> bool
  {
    self.person.cost == 0.into()
  }

}