예제 #1
0
def psp_test():
    path = '/home/thinkpad/Documents/jemoa/src/main/resources/instances/psp/o4p25_0.txt'
    psp_instance = PspInstance()
    psp_instance.read_(path)
    max_evaluations = 50000
    binary_string_length = psp_instance.n_var
    problem = PortfolioSocialProblem(psp_instance)

    algorithm = NSGAII(
        problem=problem,
        population_size=100,
        offspring_population_size=100,
        mutation=BitFlipMutation(probability=1.0 / binary_string_length),
        crossover=SPXCrossover(probability=1.0),
        termination_criterion=StoppingByEvaluations(max_evaluations=max_evaluations),
        dominance_comparator=DominanceComparator()
    )
    progress_bar = ProgressBarObserver(max=max_evaluations)
    algorithm.observable.register(progress_bar)

    algorithm.run()
    front = algorithm.get_result()
    for s in front:
        s.objectives = [-1 * obj for obj in s.objectives]
    # Save results to file
    # print_function_values_to_file(front, 'FUN.' + algorithm.get_name() + "-" + problem.get_name())
    print_solutions_to_file(front, DIRECTORY_RESULTS + 'SOLUTIONS.' + algorithm.get_name() + "-" + problem.get_name())

    print('Algorithm (continuous problem): ' + algorithm.get_name())
    print('Problem: ' + problem.get_name())
    print('Computing time: ' + str(algorithm.total_computing_time))
예제 #2
0
def main():
    problem = Knapsack(from_file=True,
                       filename='resources/KnapsackInstance_500_1_19.kp')

    algorithm = Emas(
        number_of_islands=10,
        init_island_population_size=100,
        problem=problem,
        crossover=SPXCrossover(probability=0.8),
        mutation=BitFlipMutation(probability=0.1),
        termination_criterion=StoppingByEvaluations(max_evaluations=5000))
    algorithm.run()

    front = algorithm.get_result()
    print('Algorithm: {}'.format(algorithm.get_name()))
    print('Problem: {}'.format(problem.get_name()))
    max_energy = 0
    for x in front:
        for z in x:
            print('Solution: {}'.format(z.solution.variables))
            print('Fitness: {}'.format(-z.solution.objectives[0]))
            print('Energy: {}'.format(z.energy))
            if -z.solution.objectives[0] > max_energy:
                max_energy = -z.solution.objectives[0]
                best_agent = z
    print('Computing time: {}'.format(algorithm.total_computing_time))
    print(f"Problem Maximum Capacity: {problem.capacity}")

    print("Best oof the best:")
    print('Solution: {}'.format(best_agent.solution.variables))
    print('Fitness: {}'.format(-best_agent.solution.objectives[0]))
    print('Energy: {}'.format(best_agent.energy))
예제 #3
0
 def __SPEA2(self) -> None:
     self.__solver = SPEA2(
         problem=self.__problem,
         population_size=POPULATION_SIZE,
         offspring_population_size=OFFSPRING_SIZE,
         mutation=BitFlipMutation(probability=1.0/self.__problem.number_of_variables),
         crossover=SPXCrossover(probability=1.0),
         termination_criterion=StoppingByEvaluations(max_evaluations=MAX_EVALUATION)
     )
예제 #4
0
def my_binary_mopso(problem: TestSelection, swarm):
    return BMOPSO(
        problem=problem,
        swarm_size=swarm,
        epsilon=0.075,
        mutation=BitFlipMutation(probability=0),
        leaders=CrowdingDistanceArchive(100),
        termination_criterion=StoppingByEvaluations(max=2000),
    )
예제 #5
0
 def __init__(self):
     super(_Store, self).__init__()
     self.default_observable = DefaultObservable()
     self.default_evaluator = SequentialEvaluator()
     self.default_generator = RandomGenerator()
     self.default_termination_criteria = StoppingByEvaluations(max=25000)
     self.default_mutation = {
         'real': PolynomialMutation(probability=0.15,
                                    distribution_index=20),
         'binary': BitFlipMutation(0.15)
     }
예제 #6
0
 def __HYPE(self) -> None:
     reference_point = BinarySolution(self.__problem.number_of_variables, self.__problem.number_of_objectives, self.__problem.number_of_constraints)
     reference_point.objectives = [1.0 for _ in range(self.__problem.number_of_objectives)]
     self.__solver = HYPE(
         problem=self.__problem,
         reference_point=reference_point,
         population_size=POPULATION_SIZE,
         offspring_population_size=OFFSPRING_SIZE,
         #mutation=BitFlipMutation(probability=1.0/self.__problem.number_of_variables),
         mutation=BitFlipMutation(probability=0.035),
         crossover=SPXCrossover(probability=1.0),
         termination_criterion=StoppingByEvaluations(max_evaluations=MAX_EVALUATION)
     )
예제 #7
0
 def __NSGAII(self) -> None:
     assert 'mutation' in self.__option
     assert 'crossover' in self.__option
     assert 'max_evaluation' in self.__option
     assert 'tolerance' in self.__option
     self.__solver = NSGAII(
         problem=self.__problem,
         population_size=POPULATION_SIZE,
         offspring_population_size=OFFSPRING_SIZE,
         # mutation=BitFlipMutation(probability=1.0/self.__problem.number_of_variables),
         mutation=BitFlipMutation(probability=self.__option['mutation']),
         crossover=SPXCrossover(probability=self.__option['crossover']),
         termination_criterion=StoppingByEvaluations(max_evaluations=MAX_EVALUATION)
         # termination_criterion=Terminator(max_evaluation=self.__option['max_evaluation'], tolerance=self.__option['tolerance'])
     )
예제 #8
0
def oneRun(problemType, numberOfitems: int, population_size: int,
           maxEvaluations: int):
    filename = 'knapsack_instances/%s/%d.txt' % (problemType, numberOfitems)
    problem = MOKnapsack(from_file=True, filename=filename)
    filename = 'PF/%s/%d.txt' % (problemType, numberOfitems)
    with open(filename) as file:
        lines = file.readlines()
        data = [line.split() for line in lines if len(line.split()) >= 1]
        calibratedFront = np.asfarray(data[0:], dtype=np.int32)

    max_evaluations = maxEvaluations
    utopianPoint = (np.amax(calibratedFront[:,
                                            0]), np.amax(calibratedFront[:,
                                                                         1]))
    algorithm = MyAlgorithm(problem=problem,
                            population_size=population_size,
                            mutation=BitFlipMutation(probability=1.0 /
                                                     problem.number_of_bits),
                            crossover=SPXCrossover(probability=0.9),
                            termination=StoppingByEvaluations(max_evaluations),
                            utopian=utopianPoint,
                            referenceFront=calibratedFront)

    algorithm.run()
    solutions = algorithm.get_result()
    HVbyGen = algorithm.getHyperVolumeByGeneration()
    IGDbyGen = algorithm.getIGDByGeneration()
    front = get_non_dominated_solutions(solutions)
    # for solution in front:
    #     print(solution.variables)

    #     print(-solution.objectives[0],-solution.objectives[1])
    objective1 = -1 / utopianPoint[0] * np.array(
        [solution.objectives[0] for solution in front])
    objective2 = -1 / utopianPoint[1] * np.array(
        [solution.objectives[1] for solution in front])
    # print(calculateHypervolume(list(zip(objective1,objective2))))
    # plt.scatter(objective1, objective2)
    # plt.title('%s_%d'%(problemType,numberOfitems))
    # plt.xlabel("Objective 1")
    # plt.ylabel("Objective 2")
    # plt.savefig('%s_%d'%(problemType,numberOfitems))
    return HVbyGen, IGDbyGen
예제 #9
0
    def train(self):
        problem = BinProblem(X=self.Xtrain,
                             Y=self.Ytrain,
                             kernel=self.kernel,
                             gamma=self.gamma,
                             degree=self.degree,
                             C=self.C,
                             coef0=self.coef0)

        max_evaluations = self.maxEvaluations
        algorithm = NSGAII(
            problem=problem,
            population_size=self.popsize,
            offspring_population_size=self.popsize,
            mutation=BitFlipMutation(probability=1.0 /
                                     np.shape(self.Xtrain)[0]),
            crossover=SPXCrossover(probability=1.0),
            termination_criterion=StoppingByEvaluations(max=max_evaluations))

        algorithm.run()
        front = algorithm.get_result()

        normed_matrix = normalize(
            list(map(lambda result: result.objectives, front)))

        scores = list(map(lambda item: sum(item), normed_matrix))
        solution = front[scores.index(min(scores))]

        self.instances = solution.variables[0]
        self.attributes = solution.variables[1]

        X = self.Xtrain[self.instances, :]
        X = X[:, self.attributes]
        Y = self.Ytrain[self.instances]

        self.model = SVC(gamma=self.gamma,
                         C=self.C,
                         degree=self.degree,
                         kernel=self.kernel)
        self.model.fit(X=X, y=Y)

        return self.model
         1323, 1146, 5192, 6547, 343, 7584, 3765, 8660, 9318,
         5098, 5185, 9253, 4495, 892, 5080, 5297, 9275, 7515,
         9729, 6200, 2138, 5480, 860, 8295, 8327, 9629, 4212,
         3087, 5276, 9250, 1835, 9241, 1790, 1947, 8146, 8328,
         973, 1255, 9733, 4314, 6912, 8007, 8911, 6802, 5102,
         5451, 1026, 8029, 6628, 8121, 5509, 3603, 6094, 4447,
         683, 6996, 3304, 3130, 2314, 7788, 8689, 3253, 5920,
         3660, 2489, 8153, 2822, 6132, 7684, 3032, 9949, 59,
         6669, 6334]

    problem = SubsetSum(C, W)

    algorithm = GeneticAlgorithm(
        problem=problem,
        population_size=100,
        offspring_population_size=1,
        mutation=BitFlipMutation(probability=0.1),
        crossover=SPXCrossover(probability=0.8),
        selection=BinaryTournamentSelection(),
        termination_criterion=StoppingByEvaluations(max_evaluations=25000)
    )

    algorithm.run()
    subset = algorithm.get_result()

    print('Algorithm: {}'.format(algorithm.get_name()))
    print('Problem: {}'.format(problem.get_name()))
    print('Solution: {}'.format(subset.variables))
    print('Fitness: {}'.format(subset.objectives[0]))
    print('Computing time: {}'.format(algorithm.total_computing_time))
예제 #11
0
 def default_mutation(self):
     return {
         'real': PolynomialMutation(probability=0.15,
                                    distribution_index=20),
         'binary': BitFlipMutation(0.15)
     }
예제 #12
0
from jmetal.algorithm.singleobjective.simulated_annealing import SimulatedAnnealing
from jmetal.operator import BitFlipMutation
from jmetal.problem import OneMax
from jmetal.util.solution import print_function_values_to_file, print_variables_to_file
from jmetal.util.termination_criterion import StoppingByEvaluations

if __name__ == '__main__':
    problem = OneMax(number_of_bits=1024)

    max_evaluations = 20000

    algorithm = SimulatedAnnealing(
        problem=problem,
        mutation=BitFlipMutation(probability=1.0 / problem.number_of_bits),
        termination_criterion=StoppingByEvaluations(max=max_evaluations))

    algorithm.run()
    result = algorithm.get_result()

    # Save results to file
    print_function_values_to_file(
        result, 'FUN.' + algorithm.get_name() + "." + problem.get_name())
    print_variables_to_file(
        result, 'VAR.' + algorithm.get_name() + "." + problem.get_name())

    print('Algorithm: ' + algorithm.get_name())
    print('Problem: ' + problem.get_name())
    print('Solution: ' + result.get_binary_string())
    print('Fitness:  ' + str(result.objectives[0]))
    print('Computing time: ' + str(algorithm.total_computing_time))
예제 #13
0
from jmetal.util.comparator import DominanceComparator
from jmetal.util.observer import PrintObjectivesObserver
from jmetal.util.solutions_utils import print_function_values_to_file, print_variables_to_file
from jmetal.util.termination_criterion import StoppingByEvaluations

if __name__ == '__main__':
    binary_string_length = 512
    problem = OneMax(binary_string_length)

    max_evaluations = 20000

    algorithm = NSGAII(
        problem=problem,
        population_size=100,
        offspring_population_size=1,
        mutation=BitFlipMutation(probability=1.0 / binary_string_length),
        crossover=SPXCrossover(probability=1.0),
        termination_criterion=StoppingByEvaluations(max=max_evaluations),
        dominance_comparator=DominanceComparator()
    )

    algorithm.observable.register(observer=PrintObjectivesObserver(1000))

    algorithm.run()
    front = algorithm.get_result()

    # Save results to file
    print_function_values_to_file(front, 'FUN.'+ algorithm.get_name()+"-"+problem.get_name())
    print_variables_to_file(front, 'VAR.' + algorithm.get_name()+"-"+problem.get_name())

    print('Algorithm (continuous problem): ' + algorithm.get_name())
예제 #14
0
    def train(self):
        problem = Ejemplo(X=self.Xtrain,
                          Y=self.Ytrain,
                          kernel=self.kernel,
                          gamma=self.gamma,
                          degree=self.degree,
                          C=self.C,
                          coef0=self.coef0)
        #problem.reference_front = read_solutions(filename='resources/reference_front/ZDT1.pf')

        max_evaluations = self.maxEvaluations
        algorithm = NSGAII(
            problem=problem,
            population_size=self.popsize,
            offspring_population_size=self.popsize,
            mutation=BitFlipMutation(probability=1.0 /
                                     np.shape(self.Xtrain)[0]),
            crossover=SPXCrossover(probability=1.0),
            termination_criterion=StoppingByEvaluations(max=max_evaluations))

        algorithm.observable.register(observer=ProgressBarObserver(
            max=max_evaluations))
        #algorithm.observable.register(observer=VisualizerObserver(reference_front=problem.reference_front))

        algorithm.run()
        front = algorithm.get_result()

        # Plot front
        plot_front = Plot(plot_title='Pareto front approximation',
                          reference_front=None,
                          axis_labels=problem.obj_labels)
        plot_front.plot(front,
                        label=algorithm.label,
                        filename=algorithm.get_name())

        # Plot interactive front
        plot_front = InteractivePlot(plot_title='Pareto front approximation',
                                     axis_labels=problem.obj_labels)
        plot_front.plot(front,
                        label=algorithm.label,
                        filename=algorithm.get_name())

        # Save results to file
        print_function_values_to_file(front, 'FUN.' + algorithm.label)
        print_variables_to_file(front, 'VAR.' + algorithm.label)
        print('Algorithm (continuous problem): ' + algorithm.get_name())

        # Get normalized matrix of results
        normed_matrix = normalize(
            list(map(lambda result: result.objectives, front)))

        # Get the sum of each objective results and select the best (min)
        scores = list(map(lambda item: sum(item), normed_matrix))
        solution = front[scores.index(min(scores))]

        self.instances = solution.variables[0]
        self.attributes = solution.variables[1]

        # Generate masks
        # Crop by characteristics and instances
        X = self.Xtrain[self.instances, :]
        X = X[:, self.attributes]
        Y = self.Ytrain[self.instances]

        self.model = SVC(gamma=self.gamma,
                         C=self.C,
                         degree=self.degree,
                         kernel=self.kernel)
        self.model.fit(X=X, y=Y)

        # write your code here
        return self.model
from jmetal.algorithm.singleobjective.genetic_algorithm import GeneticAlgorithm
from jmetal.operator import BinaryTournamentSelection, BitFlipMutation, SPXCrossover
from jmetal.problem import OneMax
from jmetal.util.observer import PrintObjectivesObserver
from jmetal.util.termination_criterion import StoppingByEvaluations

if __name__ == "__main__":
    problem = OneMax(number_of_bits=512)

    algorithm = GeneticAlgorithm(
        problem=problem,
        population_size=40,
        offspring_population_size=40,
        mutation=BitFlipMutation(1.0 / problem.number_of_bits),
        crossover=SPXCrossover(1.0),
        selection=BinaryTournamentSelection(),
        termination_criterion=StoppingByEvaluations(max_evaluations=20000),
    )

    algorithm.observable.register(observer=PrintObjectivesObserver(100))

    algorithm.run()
    result = algorithm.get_result()

    print("Algorithm: {}".format(algorithm.get_name()))
    print("Problem: {}".format(problem.get_name()))
    print("Solution: " + result.get_binary_string())
    print("Fitness:  " + str(result.objectives[0]))
    print("Computing time: {}".format(algorithm.total_computing_time))