Files
subcoding/grow/definition.go

88 lines
1.6 KiB
Go
Raw Normal View History

2021-11-20 19:38:31 -10:00
package grow
2021-11-20 18:51:19 -10:00
import "io"
import "gopkg.in/yaml.v2"
2021-11-20 20:17:56 -10:00
import "github.com/firestuff/subcoding/gen"
import "github.com/firestuff/subcoding/vm"
2021-11-20 18:51:19 -10:00
type Definition struct {
GlobalMemorySize uint64 `yaml:"global_memory_size"`
FunctionMemorySize uint64 `yaml:"function_memory_size"`
2021-11-20 19:25:16 -10:00
InstructionLimit uint64 `yaml:"instruction_limit"`
2021-11-20 18:51:19 -10:00
Samples []*Sample `yaml:"samples"`
}
func NewDefinition(r io.Reader) (*Definition, error) {
2021-11-20 18:51:19 -10:00
dec := yaml.NewDecoder(r)
dec.SetStrict(true)
def := &Definition{}
err := dec.Decode(def)
if err != nil {
return nil, err
}
return def, nil
}
2021-11-20 20:17:56 -10:00
func (def *Definition) Grow(statusChan chan<- Status) (*vm.Program, error) {
status := Status{
TargetScore: uint64(len(def.Samples)),
}
if statusChan != nil {
statusChan <- status
}
// TODO: Score should be number of output criteria, not number of Samples
for {
status.Attempts++
prog := gen.RandProgram(def.GlobalMemorySize, def.FunctionMemorySize, def.InstructionLimit)
score, err := def.Score(prog)
if err != nil {
close(statusChan)
return nil, err
}
if score > status.BestScore {
status.BestScore = score
status.BestProgram = prog
if statusChan != nil {
statusChan <- status
}
if status.BestScore == status.TargetScore {
close(statusChan)
return prog, nil
}
}
}
}
func (def *Definition) Score(prog *vm.Program) (uint64, error) {
score := uint64(0)
for _, sample := range def.Samples {
state, err := vm.NewState(prog)
if err != nil {
return 0, err
}
sample.SetInputs(state)
state.Execute() // ignore error
if sample.OutputsMatch(state) {
score += 1
}
}
return score, nil
}