<commit_before>const synaptic = require('synaptic')

class Brain {
  constructor (...layers) {
    if (layers[0] instanceof Brain) this.net = mutate(layers[0].net, 0.1)
    else this.net = mutate(new synaptic.Architect.Perceptron(...layers), 0.8)
    // Workaround for a memory leak.
    // https://github.com/cazala/synaptic/issues/164
    this.net.neurons().forEach(n => {
      delete synaptic.Layer.prototype.neurons[n.neuron.ID]
    })
  }

  ask (inputs) {
    return this.net.activate(inputs)
  }
}

function mutate (net, intensity) {
  let serialized = net.toJSON()
  mutateKey(serialized.neurons, 'bias', intensity)
  mutateKey(serialized.connections, 'weight', intensity)
  return synaptic.Network.fromJSON(serialized)
}

function mutateKey (array, key, intensity) {
  array.forEach(el => {
    if (Math.random() < intensity) {
      el[key] = game.math.clamp(el[key] + (Math.random() - 0.5) / 4, -0.5, 0.5)
    }
  })
}

module.exports = Brain
<commit_msg>refactor(Brain): use unoptimized nets to avoid leaking compiled code<commit_after>const synaptic = require('synaptic')

class Brain {
  constructor (...layers) {
    if (layers[0] instanceof Brain) this.net = mutate(layers[0].net, 0.1)
    else this.net = mutate(new synaptic.Architect.Perceptron(...layers), 0.8)
    this.net.setOptimize(false)
    // Workaround for a memory leak.
    // https://github.com/cazala/synaptic/issues/164
    this.net.neurons().forEach(n => {
      delete synaptic.Layer.prototype.neurons[n.neuron.ID]
    })
  }

  ask (inputs) {
    return this.net.activate(inputs)
  }
}

function mutate (net, intensity) {
  let serialized = net.toJSON()
  mutateKey(serialized.neurons, 'bias', intensity)
  mutateKey(serialized.connections, 'weight', intensity)
  return synaptic.Network.fromJSON(serialized)
}

function mutateKey (array, key, intensity) {
  array.forEach(el => {
    if (Math.random() < intensity) {
      el[key] = game.math.clamp(el[key] + (Math.random() - 0.5) / 4, -0.5, 0.5)
    }
  })
}

module.exports = Brain

{'fraction_non_alphanumeric': 0.15685304304799605, 'fraction_numerical': 0.01583374567046017, 'mean_word_length': 3.4342105263157894, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 7, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1489639', 'n_tokens_mistral': 749, 'n_tokens_neox': 699, 'n_words': 139}