def crossover(ParentA, ParentB):
     if np.random.rand() < 0.8:
         weight = np.random.rand()
         eta = 3.0
         rows = np.size(ParentA.S, 0)
         columns = np.size(ParentA.S, 1)
         if weight <= 0.5:
             byq = (2 * weight)**(1 / (eta + 1))
         else:
             byq = (1 / (2 * (1 - weight)))**(1 / (eta + 1))
         #utworzenie obiekt�w dzieci
         Sa = 0.5 * ((1 + byq) * ParentA.S + (1 - byq) * ParentB.S)
         Sa_diagonal = np.diagonal(Sa)
         Sa_diagonal = np.sort(Sa_diagonal)[::-1]
         for j in range(len(Sa_diagonal)):
             Sa.itemset((j, j), Sa_diagonal[j])
         Sb = 0.5 * ((1 + byq) * ParentB.S + (1 - byq) * ParentA.S)
         Sb_diagonal = np.diagonal(Sb)
         Sb_diagonal = np.sort(Sb_diagonal)[::-1]
         for j in range(len(Sb_diagonal)):
             Sb.itemset((j, j), Sb_diagonal[j])
         Ua = 0.5 * ((1 + byq) * ParentA.U + (1 - byq) * ParentB.U)
         Ub = 0.5 * ((1 + byq) * ParentB.U + (1 - byq) * ParentA.U)
         Vta = 0.5 * ((1 + byq) * ParentA.Vt + (1 - byq) * ParentB.Vt)
         Vtb = 0.5 * ((1 + byq) * ParentB.Vt + (1 - byq) * ParentA.Vt)
         ChildA = Specimen(Ua, Sa, Vta)
         ChildB = Specimen(Ub, Sb, Vtb)
     else:
         #kopiowanie rodzic�w, je�li crossover nie zaszed�
         ChildA = copy.deepcopy(ParentA)
         ChildB = copy.deepcopy(ParentB)
     return ChildA, ChildB
 def crossover(ParentA, ParentB):
     if np.random.rand() < 0.8:
         weight = np.random.rand()
         rows = np.size(ParentA.S, 0)
         columns = np.size(ParentA.S, 1)
         #utworzenie obiekt�w dzieci
         Sa = weight * ParentA.S + (1 - weight) * ParentB.S
         Sa_diagonal = np.diagonal(Sa)
         Sa_diagonal = np.sort(Sa_diagonal)[::-1]
         for j in range(len(Sa_diagonal)):
             Sa.itemset((j, j), Sa_diagonal[j])
         Sb = weight * ParentB.S + (1 - weight) * ParentA.S
         Sb_diagonal = np.diagonal(Sb)
         Sb_diagonal = np.sort(Sb_diagonal)[::-1]
         for j in range(len(Sb_diagonal)):
             Sb.itemset((j, j), Sb_diagonal[j])
         Ua = weight * ParentA.U + (1 - weight) * ParentB.U
         Ub = weight * ParentB.U + (1 - weight) * ParentA.U
         Vta = weight * ParentA.Vt + (1 - weight) * ParentB.Vt
         Vtb = weight * ParentB.Vt + (1 - weight) * ParentA.Vt
         ChildA = Specimen(Ua, Sa, Vta)
         ChildB = Specimen(Ub, Sb, Vtb)
     else:
         #kopiowanie rodzic�w, je�li crossover nie zaszed�
         ChildA = copy.deepcopy(ParentA)
         ChildB = copy.deepcopy(ParentB)
     return ChildA, ChildB
    def crossover(self, pais):
        #genes dos filhos
        filhos = []

        #pontos de corte
        cutoff_1 = random.randint(0,(len(pais[0].genetic_code)/2)-2) + 1
        cutoff_2 = (random.randint(0,(len(pais[0].genetic_code)/2)-2) + len(pais[0].genetic_code)//2)

        #genes dos pais
        gene_pai1 = pais[0].genetic_code
        gene_pai2 = pais[1].genetic_code

        #corte do gene
        gene_filho1 = gene_pai1[0:cutoff_1]
        gene_filho1 = gene_filho1 + gene_pai2[cutoff_1:cutoff_2]
        gene_filho1  = gene_filho1 + gene_pai1[cutoff_2:]

        gene_filho2 = gene_pai2[0:cutoff_1]
        gene_filho2 = gene_filho2 + gene_pai1[cutoff_1:cutoff_2]
        gene_filho2 = gene_filho2 + gene_pai2[cutoff_2:]

        f1 = Specimen()
        f1.create_specimen(gene_filho1, self.mutation)

        f2 = Specimen()
        f2.create_specimen(gene_filho2, self.mutation)

        filhos.append(f1)
        filhos.append(f2)

        return filhos
Exemple #4
0
 def crossover(ParentA, ParentB):
     if np.random.rand() < 0.8:
         weight = np.random.rand()
         n = 7
         int_weight = np.random.randint(7)
         rows = np.size(ParentA.S, 0)
         columns = np.size(ParentA.S, 1)
         #liczenie pot�g macierzy U do �redniej geometrycznej wa�onej
         Ua1_weighted = np.linalg.matrix_power(ParentA.U, int_weight)
         Ub1_weighted = np.linalg.matrix_power(ParentB.U, n - int_weight)
         Ua2_weighted = np.linalg.matrix_power(ParentA.U, n - int_weight)
         Ub2_weighted = np.linalg.matrix_power(ParentB.U, int_weight)
         #liczenie pot�g macierzy Vt do �redniej geometrycznej wa�onej
         Vta1_weighted = np.linalg.matrix_power(ParentA.Vt, int_weight)
         Vtb1_weighted = np.linalg.matrix_power(ParentB.Vt, n - int_weight)
         Vta2_weighted = np.linalg.matrix_power(ParentA.Vt, n - int_weight)
         Vtb2_weighted = np.linalg.matrix_power(ParentB.Vt, int_weight)
         #utworzenie dzieci ze �rednich wa�onych i pocz�tkowo macierzy zerowej jako Sigma (do dalszego uzupe�niania)
         ChildA = Specimen(
             np.real(
                 lin.fractional_matrix_power(Ua1_weighted.dot(Ub1_weighted),
                                             1 / n)),
             np.zeros((rows, columns)),
             np.real(
                 lin.fractional_matrix_power(
                     Vta1_weighted.dot(Vtb1_weighted), 1 / n)))
         ChildB = Specimen(
             np.real(
                 lin.fractional_matrix_power(Ua2_weighted.dot(Ub2_weighted),
                                             1 / n)),
             np.zeros((rows, columns)),
             np.real(
                 lin.fractional_matrix_power(
                     Vta2_weighted.dot(Vtb2_weighted), 1 / n)))
         #uzupe�nianie sigm
         for i in range(min(rows, columns)):
             ChildA.S.itemset((i, i),
                              weight * ParentA.S.item(
                                  (i, i)) + (1 - weight) * ParentB.S.item(
                                      (i, i)))
             ChildB.S.itemset((i, i),
                              weight * ParentB.S.item(
                                  (i, i)) + (1 - weight) * ParentA.S.item(
                                      (i, i)))
     else:
         #kopiowanie rodzic�w, je�li crossover nie zaszed�
         ChildA = copy.deepcopy(ParentA)
         ChildB = copy.deepcopy(ParentB)
     return ChildA, ChildB
def generate_inital_population(population_size, board_size):
    population=[]
    for i in range(population_size):
        subject = Specimen()
        for j in range(board_size):
            subject.board.append(random.randrange(board_size))
        population.append(subject)
    return population   
Exemple #6
0
    def cross_all(parent_list: list) -> list:
        child_list = []

        while len(parent_list) > 1:
            parent_1 = parent_list.pop(0)
            parent_2 = parent_list.pop(0)
            cross_length_1 = random.randrange(0, len(parent_1.route))
            cross_length_2 = random.randrange(0, len(parent_2.route))

            temp_1 = parent_1.route[:cross_length_1]  # krzyżowanie
            temp_2 = parent_2.route[:cross_length_2]
            temp_3 = parent_1.route[cross_length_1:]
            temp_4 = parent_1.route[cross_length_2:]

            child_1 = Specimen(temp_1 + temp_3)  # tworzenie potomków
            child_2 = Specimen(temp_2 + temp_4)
            child_list.append(child_1)
            child_list.append(child_2)
        return child_list
Exemple #7
0
 def load_multiple_specimens(
         self, file: str = "tests/start_specimens/specimens.txt"):
     f = open(file)
     for line in f:
         temp = []
         specimen_route = line.split()
         for elem in specimen_route:
             temp.append(int(elem))
         self.current_generation.append(Specimen(temp))
     f.close()
Exemple #8
0
 def select_worst_allowed_specimen(self):
     whole_population = copy(self.current_generation)
     allowed_specimen = []
     for specimen in whole_population:
         if specimen.is_allowed == 1:
             allowed_specimen.append(specimen)
     if len(allowed_specimen) == 0:
         # raise NoSpecimenFound
         return Specimen([0])
     allowed_specimen.sort()
     return allowed_specimen.pop()
Exemple #9
0
 def specimens(self):
     try:
         return self._specimens
     except AttributeError:
         specs = []
         spec_paths = ls(SPECIMENS_DIR, depth=0)
         for path in spec_paths:
             spec = Specimen(os.path.basename(path))
             specs.append(spec)
         self._specimens = specs
         return self._specimens
 def __init__(self, left_name, right_name):
     self.name = "{}_{}".format(left_name, right_name)
     self.logger = logging.getLogger('EXP: ' + self.name)
     self.logger.debug("Setting up specimens")
     self.left = Specimen(left_name)
     self.logger.info("Left specimen set to {}".format(self.left))
     self.right = Specimen(right_name)
     self.logger.info("Right specimen set to {}".format(self.right))
     self.path = experiments_abs(self.name)
     self.logger.info("Path set to {}".format(self.path))
     self.docx = (self.left.docx, self.right.docx)
     self.logger.debug("Docx files set to {} and {}".format(*self.docx))
     self.ugly = (self.left.ugly, self.right.ugly)
     self.logger.debug("Ugly directories set to {} and {}".format(*self.ugly))
     self.pretty = (self.left.pretty, self.right.pretty)
     self.logger.debug("Pretty directories set to {} and {}".format(*self.pretty))
     self.uglies = (self.left.uglies, self.right.uglies)
     self.logger.debug("Pretty files set to {} and {}".format(*self.uglies))
     self.pretties = (self.left.pretties, self.right.pretties)
     self.logger.debug("Pretty files set to {} and {}".format(*self.pretties))
Exemple #11
0
 def __init__(self, **kwargs):
     super(Settings, self).__init__(**kwargs)
     self.specimen = Specimen(size_hint=(1, 0.2))
     self.title = 'Settings'
     self.create_btns()
     self.create_bond_editor()
     # assign the text values to the buttons
     self.assign_initial_values()
     self.create_content()
     self.numpad = Numpad()
     self.numpad.p = self
     self.editNumpad = Popup(content=self.numpad)
def crossover(subject1, subject2):
    chromossome_size = len(subject1.board)
    crossover_point = random.randrange(0,chromossome_size)
    children1 = Specimen()
    children1.board = subject1.board[:crossover_point] + subject2.board[crossover_point:]
    children2 = Specimen()
    children2.board = subject1.board[crossover_point:] + subject2.board[:crossover_point]
    return children1, children2
 def __init__(self, left_name, right_name):
     self.name = "{}_{}".format(left_name, right_name)
     self.logger = logging.getLogger('EXP: ' + self.name)
     self.logger.debug("Setting up specimens")
     self.left = Specimen(left_name)
     self.logger.info("Left specimen set to {}".format(self.left))
     self.right = Specimen(right_name)
     self.logger.info("Right specimen set to {}".format(self.right))
     self.path = experiments_abs(self.name)
     self.logger.info("Path set to {}".format(self.path))
     self.docx = (self.left.docx, self.right.docx)
     self.logger.debug("Docx files set to {} and {}".format(*self.docx))
     self.ugly = (self.left.ugly, self.right.ugly)
     self.logger.debug(
         "Ugly directories set to {} and {}".format(*self.ugly))
     self.pretty = (self.left.pretty, self.right.pretty)
     self.logger.debug(
         "Pretty directories set to {} and {}".format(*self.pretty))
     self.uglies = (self.left.uglies, self.right.uglies)
     self.logger.debug("Pretty files set to {} and {}".format(*self.uglies))
     self.pretties = (self.left.pretties, self.right.pretties)
     self.logger.debug(
         "Pretty files set to {} and {}".format(*self.pretties))
Exemple #14
0
 def create_population(M):
     xmax = abs(max(M.min(), M.max(), key=abs))
     rows = np.size(M, 0)
     columns = np.size(M, 1)
     population = []
     for i in range(20):
         S = np.zeros((rows, columns))
         for j in range(min(rows, columns)):
             S.itemset((j, j), np.random.rand() * xmax)
         U = ortho_group.rvs(rows)
         Vt = ortho_group.rvs(columns)
         item = Specimen(U, S, Vt)
         population.append(item)
     return population
Exemple #15
0
 def reset(self):
     self.current_generation = []
     self.gen_num = 0
     if self.set_specimens:
         self.load_multiple_specimens()
     else:
         temp_list = []
         for j in range(0, configuration.values["population_size"]):
             for i in range(random.randrange(
                     1, self.map.max_point,
                     1)):  # tworzę losowo generację początkową
                 temp_list.append(random.randrange(1, self.map.max_point,
                                                   1))
             self.current_generation.append(Specimen(temp_list))
             temp_list = []
     self.rate_all()
Exemple #16
0
 def create_population(M, r):
     xmax = abs(max(M.min(), M.max(), key=abs))
     rows = np.size(M, 0)
     columns = np.size(M, 1)
     population = []
     for i in range(20):
         S = np.zeros((r, r))
         for j in range(r):
             S.itemset((j, j), np.random.rand() * xmax)
         S_diagonal = np.diagonal(S)
         S_diagonal = np.sort(S_diagonal)[::-1]
         for j in range(len(S_diagonal)):
             S.itemset((j, j), S_diagonal[j])
         U = (np.random.rand(rows, r) * 2) - 1
         Vt = (np.random.rand(r, columns) * 2) - 1
         item = Specimen(U, S, Vt)
         population.append(item)
     return population
    def predict_one(self, spec):

        """
            A utility function to performs a prediction
            for a single specimen

            :param spec:    A single training example for which we make the prediction

            :return:        Same example with modified (when predicting) class
            :rtype:         Specimen
         """
        numOfTrue = 0
        numOfFalse = 0
        for tree in self.trees:
            if tree.decide(spec):
                numOfTrue += 1
            else:
                numOfFalse += 1
        predicted_spec = Specimen(spec.data, numOfTrue > numOfFalse)
        return predicted_spec
Exemple #18
0
def read_data(csv_filename):
    """
        A utility function to read the data and return a list of training examples

        :param csv_filename:    a path to the data
        
        :return:                list of training examples
        :rtype:                 list
    """
    data = pd.read_csv(csv_filename)
    features, labels = data.loc[:, data.columns != 'Class'], data.loc[:,
                                                                      'Class']

    list_of_specimen = []

    for index, row_val_series in features.iterrows():
        values = list(row_val_series)
        speciman = Specimen(values, bool(labels[index]))
        list_of_specimen.append(speciman)

    return list_of_specimen
Exemple #19
0
 def __init__(self,
              my_map: Map,
              size: int = configuration.values["population_size"],
              set_specimens: bool = False) -> None:
     self.size = size
     self.gen_num = 0  # aktualna generacja
     # wstepna inicjalizacja dla t=0
     self.current_generation: list = []  # generacja obecna
     self.map = my_map
     self.set_specimens: bool = set_specimens
     if set_specimens:
         self.load_multiple_specimens()
     else:
         temp_list = []
         for j in range(0, configuration.values["population_size"]):
             for i in range(random.randrange(
                     1, self.map.max_point,
                     1)):  # tworzę losowo generację początkową
                 temp_list.append(random.randrange(1, self.map.max_point,
                                                   1))
             self.current_generation.append(Specimen(temp_list))
             temp_list = []
     self.rate_all()
class Experiment(object):
    def __init__(self, left_name, right_name):
        self.name = "{}_{}".format(left_name, right_name)
        self.logger = logging.getLogger('EXP: ' + self.name)
        self.logger.debug("Setting up specimens")
        self.left = Specimen(left_name)
        self.logger.info("Left specimen set to {}".format(self.left))
        self.right = Specimen(right_name)
        self.logger.info("Right specimen set to {}".format(self.right))
        self.path = experiments_abs(self.name)
        self.logger.info("Path set to {}".format(self.path))
        self.docx = (self.left.docx, self.right.docx)
        self.logger.debug("Docx files set to {} and {}".format(*self.docx))
        self.ugly = (self.left.ugly, self.right.ugly)
        self.logger.debug(
            "Ugly directories set to {} and {}".format(*self.ugly))
        self.pretty = (self.left.pretty, self.right.pretty)
        self.logger.debug(
            "Pretty directories set to {} and {}".format(*self.pretty))
        self.uglies = (self.left.uglies, self.right.uglies)
        self.logger.debug("Pretty files set to {} and {}".format(*self.uglies))
        self.pretties = (self.left.pretties, self.right.pretties)
        self.logger.debug(
            "Pretty files set to {} and {}".format(*self.pretties))

    # essential progression
    def extract_left(self):
        self.logger.debug("Extracting left specimen")
        self.left.extract()

    def extract_right(self):
        self.logger.debug("Extracting right specimen")
        self.right.extract()

    def prettify_left(self):
        self.logger.debug("Prettifying left specimen")
        self.left.prettify()

    def prettify_right(self):
        self.logger.debug("Prettifying right specimen")
        self.right.prettify()

    def write_diff_reports(self):
        mkdir(self.path)
        changed = self.get_changed()
        for f in changed:
            diffs = filediff.get_diff_battery(self._left(f), self._right(f))
            for diff in diffs:
                diff.write(self.path, f)

    def get_common(self):
        common = dirdiff.get_common(self.left.pretty, self.right.pretty)
        self.logger.info("Got common files: {}".format(common))
        return common

    def get_changed(self):
        changed = [
            f for f in self.get_common()
            if filediff.changed(self._left(f), self._right(f))
        ]
        self.logger.info("Got changed files: {}".format(changed))
        return changed

    # path aliases for convenience
    def _left(self, f):
        path = mkpath(self.left.pretty, f)
        self.logger.debug("Left path requested: {}".format(path))
        return path

    def _right(self, f):
        path = mkpath(self.right.pretty, f)
        self.logger.debug("Right path requested: {}".format(path))
        return path

    def _exp(self, f):
        path = mkpath(self.path, f)
        self.logger.debug("Exp path requested: {}".format(path))
        return path
class Experiment (object):
    def __init__(self, left_name, right_name):
        self.name = "{}_{}".format(left_name, right_name)
        self.logger = logging.getLogger('EXP: ' + self.name)
        self.logger.debug("Setting up specimens")
        self.left = Specimen(left_name)
        self.logger.info("Left specimen set to {}".format(self.left))
        self.right = Specimen(right_name)
        self.logger.info("Right specimen set to {}".format(self.right))
        self.path = experiments_abs(self.name)
        self.logger.info("Path set to {}".format(self.path))
        self.docx = (self.left.docx, self.right.docx)
        self.logger.debug("Docx files set to {} and {}".format(*self.docx))
        self.ugly = (self.left.ugly, self.right.ugly)
        self.logger.debug("Ugly directories set to {} and {}".format(*self.ugly))
        self.pretty = (self.left.pretty, self.right.pretty)
        self.logger.debug("Pretty directories set to {} and {}".format(*self.pretty))
        self.uglies = (self.left.uglies, self.right.uglies)
        self.logger.debug("Pretty files set to {} and {}".format(*self.uglies))
        self.pretties = (self.left.pretties, self.right.pretties)
        self.logger.debug("Pretty files set to {} and {}".format(*self.pretties))

    # essential progression
    def extract_left(self):
        self.logger.debug("Extracting left specimen")
        self.left.extract()
    def extract_right(self):
        self.logger.debug("Extracting right specimen")
        self.right.extract()
    def prettify_left(self):
        self.logger.debug("Prettifying left specimen")
        self.left.prettify()
    def prettify_right(self):
        self.logger.debug("Prettifying right specimen")
        self.right.prettify()
    def write_diff_reports(self):
        mkdir(self.path)
        changed = self.get_changed()
        for f in changed:
            diffs = filediff.get_diff_battery(self._left(f), self._right(f))
            for diff in diffs:
                diff.write(self.path, f)
    def get_common(self):
        common = dirdiff.get_common(self.left.pretty, self.right.pretty)
        self.logger.info("Got common files: {}".format(common))
        return common
    def get_changed(self):
        changed = [f for f in self.get_common()
                if filediff.changed(self._left(f), self._right(f))]
        self.logger.info("Got changed files: {}".format(changed))
        return changed

    # path aliases for convenience
    def _left(self, f):
        path = mkpath(self.left.pretty, f)
        self.logger.debug("Left path requested: {}".format(path))
        return path
    def _right(self, f):
        path = mkpath(self.right.pretty, f)
        self.logger.debug("Right path requested: {}".format(path))
        return path
    def _exp(self, f):
        path = mkpath(self.path, f)
        self.logger.debug("Exp path requested: {}".format(path))
        return path
def evolve(
    function_table,
    fit_function,
    inputs_num,
    nodes_num,
    outputs_num,
    desired_fit=None,
    generations_num=100,
    population_size=5,
    mutation_prob=0.01,
    max_mutations=None,
):
    """Evolve a `Specimen` according to the provided fit function.

    Args:
        function_table (tuple) : lookup table of functions to compose specimen
                                 from.
        fit_function (callable) : function evaluating fit, **see note below**.
        inputs_num (int) : number of input values taken by a specimen.
        nodes_num (int) : number of nodes in the genome.
        outputs_num (int) : number of output values produced by a specimen.
        desired_fit (float) : terminate evolution if fit >= (default None).
        generations_num(int) : number of generations (default 100).
        population_size (int) : per-generation population size (defalut 5).
        mutation_prob (float) : probability of mutation (default 0.01).
        max_mutations (int) : maximum number of genes that can be mutated in
                              a single application of the mutation operator
                              (default None).

    Returns:
        A `Specimen` with desired fit OR the best fit after `gen` generations.

    **Note**: the `fit_function` should accept a `callable` as it's argument,
    and utilize it like so:
    `
    def example_fit_function(get_outputs: callable): -> float
        inputs = ...
        expected_outputs = ...
        actual_outputs = get_outputs(inputs)
        # Return fit based on how good the outputs are
    `
    The return value of `fit_function` doesn't have to be `float`, but should be
    comparable and never `None`.
    """

    # Handle incorrect input
    if generations_num < 1 or int(generations_num) != generations_num:
        raise ValueError('Wrong or non-integer number of generations.')
    if population_size < 1 or int(population_size) != population_size:
        raise ValueError('Wrong or non-integer population size.')
    if not isfunction(fit_function) or isinstance(fit_function, type(print)):
        raise TypeError(f'Not a valid fit function: {fit_function}.')

    # Create a random population
    population = [
        Specimen(
            inputs_num,
            outputs_num,
            nodes_num,
            function_table,
            mutation_prob,
            max_mutations,
        ) for _ in range(population_size)
    ]

    # No parent for now since we are just starting
    parent = None

    # Begin the process of evolution
    for _ in range(generations_num):
        # Set up threads to assign fit in paralell
        threads = [
            Thread(target=specimen.assign_fit, args=(fit_function, ))
            for specimen in population
        ]
        for thread in threads:
            thread.start()
        # Wait for all threads to complete before proceeding
        for thread in threads:
            thread.join()
        # Find the specimen with fit >= parent fit
        for specimen in population:
            if parent is None or parent.fit <= specimen.fit:
                parent = specimen

            # If the desired fit has been acheived we can terminate
            if desired_fit is not None and parent.fit >= desired_fit:
                return parent
        # Recreate the population by mutating the new parent
        population = []
        threads = [
            Thread(target=lambda l: l.append(parent.mutate()),
                   args=(population, )) for _ in range(population_size)
        ]
        for thread in threads:
            thread.start()
        for thread in threads:
            thread.join()

    # Return the best we achieved by evolving
    return parent
Exemple #23
0
class Settings(Popup):

    def __init__(self, **kwargs):
        super(Settings, self).__init__(**kwargs)
        self.specimen = Specimen(size_hint=(1, 0.2))
        self.title = 'Settings'
        self.create_btns()
        self.create_bond_editor()
        # assign the text values to the buttons
        self.assign_initial_values()
        self.create_content()
        self.numpad = Numpad()
        self.numpad.p = self
        self.editNumpad = Popup(content=self.numpad)

    def create_bond_editor(self):
        self.bond = BondEditor()
        self.bond_editor = Popup(
            content=self.bond, title='edit bond-slip law')
        self.bond.ok_button.bind(on_press=self.confirm_bond_edit)
        self.bond.cancel_button.bind(on_press=self.cancel_bond_edit)

    def confirm_bond_edit(self, btn):
        self.bond_editor.dismiss()

    def cancel_bond_edit(self, btn):
        self.bond_editor.dismiss()
        self.bond.mats = self.specimen.tl.ts.mats_eval
        self.bond.update_graph()
        self.bond.e_b_button.text = str(self.bond.mats.E_b)
        self.bond.sig_y_button.text = str(self.bond.mats.sigma_y)
        self.bond.K_button.text = str(self.bond.mats.K_bar)
        self.bond.H_button.text = str(self.bond.mats.H_bar)

    def create_btns(self):
        # matrix stiffness
        self.m_s = Button()
        self.m_s.btn_name = 'Matrix stiffness [MPa]'
        self.m_s.bind(on_press=self.show_numpad)

        # reinforcement stiffness
        self.r_s = Button()
        self.r_s.btn_name = 'Reinforcement stiffness [MPa]'
        self.r_s.bind(on_press=self.show_numpad)

        # bond property
        self.b_p = Button(text='configure...')
        self.b_p.bind(on_press=self.show_bond_editor)

        # matrix area
        self.m_a = Button()
        self.m_a.btn_name = 'Matrix area [mm2]'
        self.m_a.bind(on_press=self.show_numpad)

        # reinforcement area
        self.r_a = Button()
        self.r_a.btn_name = 'Reinforcement area [mm2]'
        self.r_a.bind(on_press=self.show_numpad)

        # specimen length
        self.s_l = Button()
        self.s_l.btn_name = 'Specimen length [mm]'
        self.s_l.bind(on_press=self.show_numpad)

        # number of elements
        self.n_e = Button()
        self.n_e.btn_name = 'Number of elements'
        self.n_e.bind(on_press=self.show_numpad)

        # pull-out displacement
        self.p_d = Button()
        self.p_d.btn_name = 'Maximum pullout displacement[mm]'
        self.p_d.bind(on_press=self.show_numpad)

    def create_content(self):
        box = BoxLayout(orientation='vertical')

        # material settings
        mat = GridLayout(cols=6, padding=[5, 5, 5, 5])
        mat.add_widget(Label(text='Matrix\nStiffness'))
        mat.add_widget(self.m_s)
        mat.add_widget(Label(text='Reinforcement\nStiffness'))
        mat.add_widget(self.r_s)
        mat.add_widget(Label(text='Bond\nProperty'))
        mat.add_widget(self.b_p)

        geo = GridLayout(cols=6, padding=[5, 5, 5, 5])
        geo.add_widget(Label(text='Matrix\nArea'))
        geo.add_widget(self.m_a)
        geo.add_widget(Label(text='Reinforcement\nArea'))
        geo.add_widget(self.r_a)
        geo.add_widget(Label(text='Specimen\nLength'))
        geo.add_widget(self.s_l)

        fe = GridLayout(cols=4, padding=[5, 5, 5, 5])
        fe.add_widget(Label(text='Number of Elements'))
        fe.add_widget(self.n_e)
        fe.add_widget(Label(text='Maximum displacement'))
        fe.add_widget(self.p_d)

        upper = BoxLayout(orientation='vertical')
        upper.add_widget(
            Label(text='material properties', size_hint=(1, 0.5)))
        upper.add_widget(mat)
        box.add_widget(upper)
        box.add_widget(Separator())
        middle = BoxLayout(orientation='vertical')
        middle.add_widget(
            Label(text='geometric properties', size_hint=(1, 0.5)))
        middle.add_widget(geo)
        box.add_widget(middle)
        box.add_widget(Separator())
        lower = BoxLayout(orientation='vertical')
        lower.add_widget(
            Label(text='general settings', size_hint=(1, 0.5)))
        lower.add_widget(fe)
        box.add_widget(lower)
        box.add_widget(Separator())

        # ok and cancel
        self.ok = Button(text='OK')
#         self.ok.bind(on_press=self.confirm_settings)
        cancel = Button(text='Cancel')
        cancel.bind(on_press=self.dismiss_panel)
        ok_cancel = BoxLayout(
            orientation='horizontal', size_hint=(1, 0.5), padding=[5, 5, 5, 5])
        ok_cancel.add_widget(Label())
        ok_cancel.add_widget(Label())
        ok_cancel.add_widget(self.ok)
        ok_cancel.add_widget(cancel)
        box.add_widget(ok_cancel)
        self.content = box

    def show_bond_editor(self, btn):
        self.bond_editor.open()

    def dismiss_panel(self, btn):
        self.cancel_settings()
        self.dismiss()

    def reset(self, btn):
        self.specimen.tl.initialize_arrays()
        self.specimen.x_current = 53.
        self.specimen.f_u_line.points = [(0, 0)]
        self.specimen.eps_sig_line.points = [(0, 0)]
        zero_line = self.specimen.list_tuple(
            self.specimen.x_coord, np.zeros_like(self.specimen.x_coord))
        self.specimen.shear_flow_line.points = zero_line
        self.specimen.reinf_disp_line.points = zero_line
        self.specimen.matrix_disp_line.points = zero_line
        self.specimen.slip_line.points = zero_line
        self.specimen.reinf.xrange = [10, 50]
        self.specimen.controller.xrange = [50, 56]

    def show_numpad(self, btn):
        self.focusBtn = btn
        self.numpad.lblTextinput.text = btn.text
        self.editNumpad.title = btn.btn_name
        self.editNumpad.open()

    def close_numpad(self):
        self.editNumpad.dismiss()

    def finished_numpad(self):
        self.focusBtn.text = str(float(self.numpad.lblTextinput.text))
        self.editNumpad.dismiss()

    def cancel_settings(self):
        self.cancel_bond_edit(btn=None)
        self.assign_initial_values()

    def assign_initial_values(self):
        self.m_s.text = str(self.specimen.tl.ts.mats_eval.E_m)
        self.r_s.text = str(self.specimen.tl.ts.mats_eval.E_f)
        self.m_a.text = str(self.specimen.tl.ts.A_m)
        self.r_a.text = str(self.specimen.tl.ts.A_f)
        self.s_l.text = str(self.specimen.tl.ts.L_x)
        self.n_e.text = str(self.specimen.tl.ts.n_e_x)
        self.p_d.text = str(self.specimen.max_displacement)

    def confirm_settings(self, btn):
        material = MATSEval(E_m=float(self.m_s.text),
                            E_f=float(self.r_s.text),
                            E_b=self.bond.mats.E_b,
                            sigma_y=self.bond.mats.sigma_y,
                            K_bar=self.bond.mats.K_bar,
                            H_bar=self.bond.mats.H_bar,
                            f_damage_x=self.bond.mats.f_damage_x,
                            f_damage_y=self.bond.mats.f_damage_y)
        tstepper = TStepper(mats_eval=material,
                            A_m=float(self.m_a.text),
                            A_f=float(self.r_a.text),
                            n_e_x=int(float(self.n_e.text)),
                            L_x=float(self.s_l.text))

        self.specimen.tl = TLoop(ts=tstepper)
        self.specimen.max_displacement = float(self.p_d.text)

        self.specimen.x_current = 53.
        self.specimen.f_u_line.points = [(0, 0)]
        self.specimen.eps_sig_line.points = [(0, 0)]
        zero_line = self.specimen.list_tuple(
            self.specimen.x_coord, np.zeros_like(self.specimen.x_coord))
        self.specimen.shear_flow_line.points = zero_line
        self.specimen.reinf_disp_line.points = zero_line
        self.specimen.matrix_disp_line.points = zero_line
        self.specimen.slip_line.points = zero_line
        self.specimen.reinf.xrange = [10, 50]
        self.specimen.controller.xrange = [50, 56]

        self.specimen.x_coord = np.linspace(
            0, self.specimen.tl.ts.L_x, self.specimen.tl.ts.n_e_x + 1)
        self.specimen.x_ip_coord = np.repeat(self.specimen.x_coord, 2)[1:-1]

        self.dismiss()
 def create_random_population(self):
     for spci in range(0, self.tamPop):
         specimen = Specimen()
         specimen.random_cromossomo()
         self.specimens.append(specimen)
 def create_none_population(self):
     for spci in range(0, self.tamPop):
         self.specimens.append(Specimen())