Creates a new gene randomly inheriting attributes from its parents.
972045
def crossover(self, gene2):
        
        assert self.key == gene2.key

        # Note: we use "a if random() > 0.5 else b" instead of choice((a, b))
        # here because `choice` is substantially slower.
        new_gene = self.__class__(self.key)
        for a in self._gene_attributes:
            if random() > 0.5:
                setattr(new_gene, a.name, getattr(self, a.name))
            else:
                setattr(new_gene, a.name, getattr(gene2, a.name))

        return new_gene
1306002
def new_from_memory(cls, data):
        """"""

        size = len(data)
        copy = g_memdup(data, size)
        ptr = cast(copy, POINTER(guint8))
        try:
            with gerror(GIError) as error:
                return GITypelib._new_from_memory(ptr, size, error)
        except GIError:
            free(copy)
            raise
903857
def create(genome, config, time_constant):
        
        genome_config = config.genome_config
        required = required_for_output(genome_config.input_keys, genome_config.output_keys, genome.connections)

        # Gather inputs and expressed connections.
        node_inputs = {}
        for cg in itervalues(genome.connections):
            if not cg.enabled:
                continue

            i, o = cg.key
            if o not in required and i not in required:
                continue

            if o not in node_inputs:
                node_inputs[o] = [(i, cg.weight)]
            else:
                node_inputs[o].append((i, cg.weight))

        node_evals = {}
        for node_key, inputs in iteritems(node_inputs):
            node = genome.nodes[node_key]
            activation_function = genome_config.activation_defs.get(node.activation)
            aggregation_function = genome_config.aggregation_function_defs.get(node.aggregation)
            node_evals[node_key] = CTRNNNodeEval(time_constant,
                                                 activation_function,
                                                 aggregation_function,
                                                 node.bias,
                                                 node.response,
                                                 inputs)

        return CTRNN(genome_config.input_keys, genome_config.output_keys, node_evals)
397819
public Attribute cloneAttributes(AgBuffer orig, Type type, Attribute seed) {
        Map<Attribute, Attribute> map; // old attributes to new attributes
        Attribute attr;
        State newState;

        map = new HashMap<Attribute, Attribute>();
        for (State state : orig.states) {
            attr = state.getAttribute();
            map.put(attr, new Attribute(attr.symbol, null, type));
        }
        for (State state : orig.states) {
            newState = state.cloneAttributeTransport(map);
            states.add(newState);
        }
        attr = map.get(seed);
        if (attr == null) {
            throw new IllegalArgumentException();
        }
        return attr;
    }
731747
def clone(self, parent=None):
        
        a = Attribute(self.qname(), self.value)
        a.parent = parent
        return a
813623
public T[] generateRandomCandidate(Random rng)
    {
        T[] candidate = elements.clone();
        List<T> list = Arrays.asList(candidate);
        Collections.shuffle(list, rng);
        return list.toArray(candidate);
    }
1109677
def configure_new(self, config):
        """"""

        # Create node genes for the output pins.
        for node_key in config.output_keys:
            self.nodes[node_key] = self.create_node(config, node_key)

        # Add hidden nodes if requested.
        if config.num_hidden > 0:
            for i in range(config.num_hidden):
                node_key = config.get_new_node_key(self.nodes)
                assert node_key not in self.nodes
                node = self.create_node(config, node_key)
                self.nodes[node_key] = node

        # Add connections based on initial connectivity type.

        if 'fs_neat' in config.initial_connection:
            if config.initial_connection == 'fs_neat_nohidden':
                self.connect_fs_neat_nohidden(config)
            elif config.initial_connection == 'fs_neat_hidden':
                self.connect_fs_neat_hidden(config)
            else:
                if config.num_hidden > 0:
                    print(
                        "Warning: initial_connection = fs_neat will not connect to hidden nodes;",
                        "\tif this is desired, set initial_connection = fs_neat_nohidden;",
                        "\tif not, set initial_connection = fs_neat_hidden",
                        sep='\n', file=sys.stderr);
                self.connect_fs_neat_nohidden(config)
        elif 'full' in config.initial_connection:
            if config.initial_connection == 'full_nodirect':
                self.connect_full_nodirect(config)
            elif config.initial_connection == 'full_direct':
                self.connect_full_direct(config)
            else:
                if config.num_hidden > 0:
                    print(
                        "Warning: initial_connection = full with hidden nodes will not do direct input-output connections;",
                        "\tif this is desired, set initial_connection = full_nodirect;",
                        "\tif not, set initial_connection = full_direct",
                        sep='\n', file=sys.stderr);
                self.connect_full_nodirect(config)
        elif 'partial' in config.initial_connection:
            if config.initial_connection == 'partial_nodirect':
                self.connect_partial_nodirect(config)
            elif config.initial_connection == 'partial_direct':
                self.connect_partial_direct(config)
            else:
                if config.num_hidden > 0:
                    print(
                        "Warning: initial_connection = partial with hidden nodes will not do direct input-output connections;",
                        "\tif this is desired, set initial_connection = partial_nodirect {0};".format(
                            config.connection_fraction),
                        "\tif not, set initial_connection = partial_direct {0}".format(
                            config.connection_fraction),
                        sep='\n', file=sys.stderr);
                self.connect_partial_nodirect(config)
1144089
def from_nodes(cls, nodes, new_nodes, max_slaves_limit=None):
        '''
        '''
        param = gen_distribution(nodes, new_nodes)
        param['max_slaves_limit'] = max_slaves_limit
        return cls(**param)
280321
def mutate(self, p_mutate):
        
        assert 0 <= p_mutate <= 1
        
        for gene in self.genes:
            gene.mutate(p_mutate)
122772
def copy(self, parent=None):
        """"""
        new = Structure(None, parent=parent)
        new.key = self.key
        new.type_ = self.type_
        new.val_guaranteed = self.val_guaranteed
        new.key_guaranteed = self.key_guaranteed
        for child in self.children:
            new.children.append(child.copy(new))
        return new
933360
public static <T, U> DictionaryFeatureVectorGenerator<T, U> createFromDataWithThreshold(
      Collection<T> data, FeatureGenerator<T, U> generator, int occurrenceThreshold) {
    CountAccumulator<U> featureOccurrenceCounts = FeatureGenerators.getFeatureCounts(generator, data);
    IndexedList<U> features = new IndexedList<U>();
    features.addAll(featureOccurrenceCounts.getKeysAboveCountThreshold(occurrenceThreshold));
    return new DictionaryFeatureVectorGenerator<T, U>(features, generator, true);
  }
223849
def from_gene_ids(cls, gene_ids: List[str]):
        """"""
        genes = [ExpGene(id_) for id_ in gene_ids]
        return cls.from_genes(genes)
987639
public static <S> PVolumeBDGenerator<S> create()
  {
    return new PVolumeBDGenerator<>(new Generator<BigDecimal>()
    {
      private final Random random = new Random();

      @Override
      public BigDecimal next()
      {
        return BigDecimal.valueOf(Math.abs(this.random.nextLong()));
      }
    });
  }
590072
public static <S> PAreaBIGenerator<S> create()
  {
    return new PAreaBIGenerator<>(new Generator<BigInteger>()
    {
      private final Random random = new Random();

      @Override
      public BigInteger next()
      {
        return BigInteger.valueOf(Math.abs(this.random.nextLong()));
      }
    });
  }
1343592
def mutate(self, p_mutate):
        
        new_dna = []
        
        for bit in self.dna:
            if random.random() < p_mutate:
                bit = '1' if bit == '0' else '0'
                
            new_dna.append(bit)
            
        self.dna = ''.join(new_dna)
407197
def random_normal(attrs, inputs, proto_obj):
    """"""
    try:
        from onnx.mapping import TENSOR_TYPE_TO_NP_TYPE
    except ImportError:
        raise ImportError("Onnx and protobuf need to be installed. "
                          "Instructions to install - https://github.com/onnx/onnx")
    new_attr = translation_utils._remove_attributes(attrs, ['seed'])
    new_attr = translation_utils._fix_attribute_names(new_attr, {'mean': 'loc'})
    new_attr['dtype'] = TENSOR_TYPE_TO_NP_TYPE[int(new_attr.get('dtype', 1))]
    return 'random_normal', new_attr, inputs
659961
def uniform_crossover(parents):
    
    chromosome_length = len(parents[0])

    children = [[], []]

    for i in range(chromosome_length):
        selected_parent = random.randint(0, 1)

        # Take from the selected parent, and add it to child 1
        # Take from the other parent, and add it to child 2
        children[0].append(parents[selected_parent][i])
        children[1].append(parents[1 - selected_parent][i])

    return children