github.com/RH12503/Triangula@v1.2.0/algorithm/evaluator/parallel.go (about)

     1  package evaluator
     2  
     3  import (
     4  	"github.com/RH12503/Triangula/fitness"
     5  )
     6  
     7  // parallel is a fitness evaluator that supports parallel calculations.
     8  // It stores and updates a cache, and contains a fitness.CacheFunction for each member
     9  // to calculate fitnesses.
    10  type parallel struct {
    11  	evaluators []fitness.CacheFunction
    12  
    13  	cache     []fitness.CacheData // The current cache being used by the fitness functions.
    14  	nextCache []fitness.CacheData // The cache for the next generation.
    15  }
    16  
    17  func (p parallel) Get(i int) fitness.Function {
    18  	return p.evaluators[i]
    19  }
    20  
    21  func (p *parallel) Prepare() {
    22  	p.cache, p.nextCache = p.nextCache, p.cache
    23  }
    24  
    25  func (p *parallel) Update(i int) {
    26  	eval := p.evaluators[i]
    27  
    28  	// Put triangles that have been calculated from the fitness function into the cache
    29  	for _, d := range eval.Cache() {
    30  		p.cache[d.CachedHash()] = d
    31  	}
    32  
    33  	eval.SetCache(p.cache)
    34  }
    35  
    36  func (p *parallel) SetBase(i, base int) {
    37  	p.evaluators[i].SetBase(p.evaluators[base])
    38  }
    39  
    40  func (p *parallel) Swap(i, j int) {
    41  	p.evaluators[i], p.evaluators[j] = p.evaluators[j], p.evaluators[i]
    42  }
    43  
    44  // NewParallel creates a new parallel evaluator.
    45  func NewParallel(fitnessFuncs []fitness.CacheFunction, cachePowerOf2 int) *parallel {
    46  
    47  	return &parallel{
    48  		evaluators: fitnessFuncs,
    49  		cache:      make([]fitness.CacheData, 1<<cachePowerOf2),
    50  		nextCache:  make([]fitness.CacheData, 1<<cachePowerOf2),
    51  	}
    52  }