Пример #1
0
class PlotFrontToFileObserver(Observer):
    def __init__(self,
                 output_directory: str,
                 step: int = 100,
                 **kwargs) -> None:
        """ Plot and save Pareto front approximations into files.

        :param output_directory: Output directory.
        """
        self.directory = output_directory
        self.plot_front = Plot(title='Pareto front approximation', **kwargs)
        self.last_front = []
        self.fronts = []
        self.counter = 0
        self.step = step

        if Path(self.directory).is_dir():
            LOGGER.warning('Directory {} exists. Removing contents.'.format(
                self.directory))
            for file in os.listdir(self.directory):
                os.remove('{0}/{1}'.format(self.directory, file))
        else:
            LOGGER.warning('Directory {} does not exist. Creating it.'.format(
                self.directory))
            Path(self.directory).mkdir(parents=True)

    def update(self, *args, **kwargs):
        problem = kwargs['PROBLEM']
        solutions = kwargs['SOLUTIONS']
        evaluations = kwargs['EVALUATIONS']

        if solutions:
            if (evaluations % self.step) == 0:
                if isinstance(problem, DynamicProblem):
                    termination_criterion_is_met = kwargs.get(
                        'TERMINATION_CRITERIA_IS_MET', None)

                    if termination_criterion_is_met:
                        if self.counter > 0:
                            igd = InvertedGenerationalDistance(self.last_front)
                            igd_value = igd.compute(solutions)
                        else:
                            igd_value = 1

                        if igd_value > 0.005:
                            self.fronts += solutions
                            self.plot_front.plot(
                                [self.fronts],
                                label=problem.get_name(),
                                filename=f'{self.directory}/front-{evaluations}'
                            )
                        self.counter += 1
                        self.last_front = solutions
                else:
                    self.plot_front.plot(
                        [solutions],
                        label=f'{evaluations} evaluations',
                        filename=f'{self.directory}/front-{evaluations}')
                    self.counter += 1
Пример #2
0
    def __init__(self, output_directory: str) -> None:
        self.directory = output_directory
        self.plot_front = Plot(plot_title='Pareto front approximation')
        self.last_front = []
        self.fronts = []
        self.counter = 0

        if Path(self.directory).is_dir():
            LOGGER.warning('Directory {} exists. Removing contents.'.format(
                self.directory))
            for file in os.listdir(self.directory):
                os.remove('{0}/{1}'.format(self.directory, file))
        else:
            LOGGER.warning('Directory {} does not exist. Creating it.'.format(
                self.directory))
            Path(self.directory).mkdir(parents=True)
Пример #3
0
def loadDataWithClass(p: DTLZ1P, bag_path: str, label: str):
    with open(bag_path) as f:
        content = f.readlines()
        # you may also want to remove whitespace characters like `\n` at the end of each line
    content = [x.strip() for x in content]
    _bag = []
    for element in content:
        if not ('variables * objectives * constraints' in element):
            line = clean_line(element)
            _bag.append(p.generate_existing_solution([float(_var) for _var in line[:p.number_of_variables]]))
    print(len(_bag))
    # classifier solutions
    _class = [[], [], [], []]
    for _solution in _bag:
        _class_vector = p.classifier.classify(_solution)
        if _class_vector[0] > 0:
            _class[0].append(_solution)
        elif _class_vector[1] > 0:
            _class[1].append(_solution)
        elif _class_vector[2] > 0:
            _class[2].append(_solution)
        else:
            _class[3].append(_solution)
    print(len(_class[0]), len(_class[1]), len(_class[2]), len(_class[3]))
    _front = None
    idx = 0
    for i, _f in enumerate(_class):
        if len(_f) > 0:
            _front = _f
            idx = i
            break
    print(idx, len(_front))
    # Save results to file
    print_solutions_to_file(_front, DIRECTORY_RESULTS + 'front0._class_' + label + p.get_name())
    alabels = []
    for obj in range(p.number_of_objectives):
        alabels.append('Obj-' + str(obj))
    plot_front = Plot(title='Pareto front approximation ' + label + 'F' + str(idx) + p.get_name(), axis_labels=alabels)
    plot_front.plot(_front, label=label + 'F' + str(idx) + p.get_name(),
                    filename=DIRECTORY_RESULTS + 'F0_class_' + label + p.get_name(),
                    format='png')
    # Show best compromise
    _best = p.generate_existing_solution(p.instance_.attributes['best_compromise'][0])
    print('Best compromise:', _best.objectives)
Пример #4
0
    def __init__(self, output_directory: str, step: int = 100, **kwargs) -> None:
        """ Plot and save Pareto front approximations into files.

        :param output_directory: Output directory.
        """
        self.directory = output_directory
        self.plot_front = Plot(plot_title='Pareto front approximation', **kwargs)
        self.last_front = []
        self.fronts = []
        self.counter = 0
        self.step = step

        if Path(self.directory).is_dir():
            LOGGER.warning('Directory {} exists. Removing contents.'.format(self.directory))
            for file in os.listdir(self.directory):
                os.remove('{0}/{1}'.format(self.directory, file))
        else:
            LOGGER.warning('Directory {} does not exist. Creating it.'.format(self.directory))
            Path(self.directory).mkdir(parents=True)
Пример #5
0
def run_DynamicNSGAII(problems):

    for problem in problems:

        time_counter = TimeCounter(delay=1)
        time_counter.observable.register(problem[1])
        time_counter.start()

        max_evaluations = 25000
        algorithm = DynamicNSGAII(
            problem=problem[1],
            population_size=100,
            offspring_population_size=100,
            mutation=PolynomialMutation(probability=1.0 / problem[1].number_of_variables, distribution_index=20),
            crossover=SBXCrossover(probability=1.0, distribution_index=20),
            termination_criterion=StoppingByEvaluations(max_evaluations=max_evaluations),
        )

        algorithm.observable.register(observer=ProgressBarObserver(max=max_evaluations))
        algorithm.observable.register(observer=VisualizerObserver())
        algorithm.observable.register(observer=PlotFrontToFileObserver(problem[0] + "_dynamic_front_vis"))
        algorithm.observable.register(observer=WriteFrontToFileObserver(problem[0] + "_dynamic_front"))
        #algorithm.observable.register(observer=BasicObserver())

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

        non_dominated_solutions = get_non_dominated_solutions(front)

        # save to files
        print_function_values_to_file(front, 'FUN.DYNAMICNSGAII.' + problem[0])
        print_variables_to_file(front, 'VAR.DYNAMICNSGAII.' + problem[0])

        # Plot
        plot_front = Plot(title='Pareto front approximation', axis_labels=['x', 'y'])
        plot_front.plot(front, label='DynamicNSGAII-FDA2', filename='DYNAMICNSGAII-'+problem[0], format='png')
Пример #6
0
    Pmut: float = 0.05 
    generations: int = 50
    pop_size: int = 30
    Cr: float = 0.5
    max_evaluations: float = generations*pop_size
    problem: MulticastProblem = MulticastProblem(Graph = gr, root_node = root_node, destination_nodes = destination_nodes)
    algorithm = SPEA2(
        problem=problem,
        population_size=pop_size,
        offspring_population_size=int(pop_size*Cr),
        mutation=MulticastMutation(probability=Pmut, Pnmut=Pnmut, G=gr),
        crossover=MulticastCrossover(probability=1.0, root_node = root_node, destination_nodes = destination_nodes, graph=gr),
        termination_criterion=StoppingByEvaluations(max_evaluations=max_evaluations)
    )

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

    # Save results to file
    print_function_values_to_file(front, 'FUN.' + algorithm.label)
    print_variables_to_file(front, 'VAR.'+ algorithm.label)

    plot_front = Plot(title='Pareto front approximation', axis_labels=['cost', 'delay'])
    plot_front.plot(front, label='SPEA2', filename='SPEA2', format='png')

    print(f'Algorithm: {algorithm.get_name()}')
    print(f'Problem: {problem.get_name()}')
    print(f'Computing time: {algorithm.total_computing_time}')
    
    algorithm.solutions[0].multicast_tree.draw()
        file.write(
            f'\n\tProbability crossover: {config_probability_crossover}')
        file.write(f'\n\tSolution length: {config_solution_length}')
        file.write('\nResults:')
        for sol in nds:
            file.write(f'\n\t\t{sol.variables}\t\t{sol.objectives}')

    print('\nSettings:')
    print(f'\tAlgorithm: {algorithm.get_name()}')
    print(f'\tProblem: {problem.get_name()}')
    print(f'\tComputing time: {algorithm.total_computing_time} seconds')
    print(f'\tMax epochs: {config_max_epochs}')
    print(f'\tPopulation size: {config_population_size}')
    print(f'\tOffspring population size: {config_offspring_population_size}')
    print(f'\tProbability mutation: {config_probability_mutation}')
    print(f'\tProbability crossover: {config_probability_crossover}')
    print(f'\tSolution length: {config_solution_length}')
    print(f'\nResults:')
    for sol in nds:
        print(f'\t{sol.variables}\t\t{sol.objectives}')

    plot_front = Plot(title='Pareto front aproximation',
                      axis_labels=[
                          'runtime', 'codelines', 'tags', 'jumps',
                          'function_tags', 'calls'
                      ])
    plot_front.plot([nds],
                    normalize=False,
                    filename=f'{problem.config_to_str()}_pareto_front',
                    format='eps')
Пример #8
0
        crossover=SBXCrossover(probability=1.0, distribution_index=20),
        dominance_comparator=GDominanceComparator(reference_point),
        termination_criterion=StoppingByEvaluations(max=max_evaluations))

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

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

    # Plot front
    plot_front = Plot(plot_title='Pareto front approximation',
                      axis_labels=problem.obj_labels,
                      reference_point=reference_point,
                      reference_front=problem.reference_front)
    plot_front.plot(front, label='gNSGAII-ZDT1', filename='gNSGAII-ZDT1')

    # Plot interactive front
    plot_front = InteractivePlot(plot_title='Pareto front approximation',
                                 axis_labels=problem.obj_labels,
                                 reference_point=reference_point,
                                 reference_front=problem.reference_front)
    plot_front.plot(front, label='gNSGAII-ZDT1', filename='gNSGAII-ZDT1')

    # 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())
Пример #9
0
        leaders=archives_with_reference_points,
        termination_criterion=StoppingByEvaluations(
            max_evaluations=max_evaluations),
    )

    algorithm.observable.register(
        observer=VisualizerObserver(reference_front=problem.reference_front,
                                    reference_point=reference_point))

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

    # Plot front
    plot_front = Plot(
        title="Pareto front approximation. Problem: " + problem.get_name(),
        reference_front=problem.reference_front,
        axis_labels=problem.obj_labels,
    )
    plot_front.plot(front,
                    label=algorithm.label,
                    filename=algorithm.get_name())

    # Plot interactive front
    plot_front = InteractivePlot(
        title="Pareto front approximation. Problem: " + problem.get_name(),
        reference_front=problem.reference_front,
        axis_labels=problem.obj_labels,
    )
    plot_front.plot(front,
                    label=algorithm.label,
                    filename=algorithm.get_name())
Пример #10
0
from jmetal.algorithm.multiobjective import NSGAII
from jmetal.operator import SBXCrossover, PolynomialMutation
from jmetal.problem import ZDT1
from jmetal.util.termination_criterion import StoppingByEvaluations

problem = ZDT1()

algorithm = NSGAII(
    problem=problem,
    population_size=100,
    offspring_population_size=100,
    mutation=PolynomialMutation(probability=1.0 / problem.number_of_variables, distribution_index=20),
    crossover=SBXCrossover(probability=1.0, distribution_index=20),
    termination_criterion=StoppingByEvaluations(max_evaluations=25000)
)

algorithm.run()

from jmetal.util.solution import get_non_dominated_solutions, print_function_values_to_file, \
    print_variables_to_file

front = get_non_dominated_solutions(algorithm.get_result())

print_function_values_to_file(front, 'FUN.NSGAII.ZDT1')
print_variables_to_file(front, 'VAR.NSGAII.ZDT1')

from jmetal.lab.visualization import Plot

plot_front = Plot(title='Pareto front approximation', axis_labels=['x', 'y'])
plot_front.plot(front, label='NSGAII-ZDT1', filename='NSGAII-ZDT1', format='png')
Пример #11
0
                                        problem.number_of_variables,
                                        distribution_index=20),
            crossover=SBXCrossover(probability=1.0, distribution_index=30),
            termination_criterion=StoppingByEvaluations(
                max_evaluations=max_evaluations))
        progress_bar = ProgressBarObserver(max=max_evaluations)
        algorithm.observable.register(progress_bar)

        algorithm.run()
        bag += algorithm.get_result()
    print(len(bag))
    print_solutions_to_file(
        bag, DIRECTORY_RESULTS + 'Solutions.bag.' + algorithm.label)
    ranking = FastNonDominatedRanking()

    ranking.compute_ranking(bag)
    front = ranking.get_subfront(0)
    print(len(front))
    # Save results to file
    print_solutions_to_file(front,
                            DIRECTORY_RESULTS + 'front0.' + algorithm.label)
    plot_front = Plot(title='Pareto front approximation',
                      axis_labels=['x', 'y', 'z'])
    plot_front.plot(front,
                    label='NSGAII-ZDT7',
                    filename=DIRECTORY_RESULTS + 'NSGAII-ZDT1P',
                    format='png')
    print(f'Algorithm: ${algorithm.get_name()}')
    print(f'Problem: ${problem.get_name()}')
    print(f'Computing time: ${algorithm.total_computing_time}')
Пример #12
0
                       population_size=100,
                       offspring_population_size=100,
                       mutation=ShiftClosedGapGroups(probability=0.3),
                       crossover=SPXMSA(probability=0.7),
                       termination_criterion=StoppingByEvaluations(
                           max_evaluations=max_evaluations))

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

    algorithm.run()
    front = algorithm.get_result()
    front = restore_objs(front, problem)

    # plot front
    plot_front = Plot(title='Pareto front approximation',
                      axis_labels=['%SOP', '%TC'])
    plot_front.plot(front, label='NSGAII-BB50011', filename='NSGAII-BB50011')

    pareto_front = MSAPlot(title='Pareto front approximation',
                           axis_labels=['%SOP', '%TC'])
    pareto_front.plot(front, label='NSGAII-BB50011', filename='NSGAII-BB50011')

    # find extreme solutions
    solutions = get_representative_set(front)
    for solution in solutions:
        print(solution.objectives)

    print('Computing time: ' + str(algorithm.total_computing_time))
Пример #13
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.problem import ZDT1, ZDT2, ZDT3
from jmetal.util.solution import get_non_dominated_solutions
from jmetal.util.termination_criterion import StoppingByEvaluations
from jmetal.lab.visualization import Plot

if __name__ == '__main__':
    problem = ZDT1()
    max_evaluations = 10000

    algorithm = NSGAII(
        problem=problem,
        population_size=100,
        offspring_population_size=100,
        mutation=PolynomialMutation(probability=1.0 /
                                    problem.number_of_variables,
                                    distribution_index=20),
        crossover=SBXCrossover(probability=1.0, distribution_index=20),
        termination_criterion=StoppingByEvaluations(max=max_evaluations))

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

    print('Algorithm (continuous problem): ' + algorithm.get_name())
    print('Problem: ' + problem.get_name())
    print('Computing time: ' + str(algorithm.total_computing_time))

    plot_front = Plot(title='Pareto front approximation',
                      axis_labels=['x', 'y'])
    plot_front.plot(front,
                    label=algorithm.get_name() + '-' + problem.get_name())
Пример #15
0
        termination_criterion=StoppingByEvaluations(
            max_evaluations=max_evaluations),
        dominance_comparator=GDominanceComparator(reference_point),
        number_of_cores=ncores,
        client=client)

    algorithm.observable.register(observer=ProgressBarObserver(
        max=max_evaluations))
    algorithm.observable.register(observer=VisualizerObserver(
        reference_point=[-170000, -1.2]))

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

    # plot front
    plot_front = Plot(title='Pareto front approximation',
                      axis_labels=['%SOP', '%TC'])
    plot_front.plot(front, label='NSGAII-BB20019', filename='NSGAII-BB20019')

    plot_front = MSAPlot(title='Pareto front approximation',
                         axis_labels=['%SOP', '%TC'])
    plot_front.plot(front,
                    label='NSGAII-BB20019',
                    filename='NSGAII-BB20019',
                    format='HTML')

    # find extreme solutions
    solutions = get_representative_set(front)
    for solution in solutions:
        print(solution.objectives)

    print('Computing time: ' + str(algorithm.total_computing_time))
Пример #16
0
def dtlz_test(p: FloatProblemGD, label: str = '', experiment: int = 50):
    # problem.reference_front = read_solutions(filename='resources/reference_front/DTLZ2.3D.pf')

    max_evaluations = 25000

    # references = ReferenceDirectionFromSolution(p)
    algorithm = NSGA3C(
        problem=p,
        population_size=100,
        reference_directions=UniformReferenceDirectionFactory(p.instance_.n_obj, n_points=92),
        mutation=PolynomialMutation(probability=1.0 / p.number_of_variables, distribution_index=20),
        crossover=SBXCrossover(probability=1.0, distribution_index=30),
        termination_criterion=StoppingByEvaluations(max_evaluations=max_evaluations)
    )
    bag = []
    total_time = 0
    for i in range(experiment):
        algorithm = NSGA3C(
            problem=p,
            population_size=92,
            reference_directions=UniformReferenceDirectionFactory(p.instance_.n_obj, n_points=91),
            mutation=PolynomialMutation(probability=1.0 / p.number_of_variables, distribution_index=20),
            crossover=SBXCrossover(probability=1.0, distribution_index=30),
            termination_criterion=StoppingByEvaluations(max_evaluations=max_evaluations)
        )
        progress_bar = ProgressBarObserver(max=max_evaluations)
        algorithm.observable.register(progress_bar)
        algorithm.run()
        total_time += algorithm.total_computing_time
        bag = bag + algorithm.get_result()
    print(len(bag))
    print('Total computing time:', total_time)
    print('Average time: ', str(total_time / experiment))
    print_solutions_to_file(bag, DIRECTORY_RESULTS + 'Solutions.bag._class_' + label + algorithm.label)
    ranking = FastNonDominatedRanking()

    ranking.compute_ranking(bag)
    front_ = ranking.get_subfront(0)
    print('Front 0 size : ', len(front_))
    alabels = []
    for obj in range(p.number_of_objectives):
        alabels.append('Obj-' + str(obj))
    plot_front = Plot(title='Pareto front approximation' + ' ' + label,
                      axis_labels=alabels)
    plot_front.plot(front_, label=label + 'F0 ' + algorithm.label,
                    filename=DIRECTORY_RESULTS + 'F0_class_' + 'original_' + label + algorithm.label,
                    format='png')
    class_fronts = [[], [], [], []]

    for s in front_:
        _class = problem.classifier.classify(s)
        if _class[0] > 0:
            class_fronts[0].append(s)
        elif _class[1] > 0:
            class_fronts[1].append(s)
        elif _class[2] > 0:
            class_fronts[2].append(s)
        else:
            class_fronts[3].append(s)
    print(len(class_fronts[0]), len(class_fronts[1]), len(class_fronts[2]), len(class_fronts[3]))

    _front = class_fronts[0] + class_fronts[1]
    if len(_front) == 0:
        _front = class_fronts[2] + class_fronts[3]
    print('Class : ', len(_front))
    # Save results to file
    print_solutions_to_file(_front, DIRECTORY_RESULTS + 'Class_F0' + label + algorithm.label)

    print(f'Algorithm: ${algorithm.get_name()}')
    print(f'Problem: ${p.get_name()}')

    plot_front = Plot(title=label + 'F_' + p.get_name(), axis_labels=alabels)
    plot_front.plot(_front, label=label + 'F_' + p.get_name(),
                    filename=DIRECTORY_RESULTS + 'Class_F0' + label + p.get_name(),
                    format='png')
Пример #17
0
def validate_interclass(problem):
    with open('/home/thinkpad/Documents/jemoa/experiments/dtlz_preferences/Class_F0DTLZ1_P3.out') as f:
        content = f.readlines()
        # you may also want to remove whitespace characters like `\n` at the end of each line
    content = [x.strip() for x in content]
    solutions = []
    print(problem.get_preference_model(0))
    for idx, line in enumerate(content):
        split = line.split('*')[1].split(',')
        _s = problem.generate_existing_solution([float(x) for x in split],is_objectives=True)
        _s.bag = 'java'
        solutions.append(_s)
    with open('/home/thinkpad/PycharmProjects/jMetalPy/results/Class_F0enfoque_frontsNSGAIII_custom.DTLZ1P_3.csv') as f:
        content = f.readlines()
        # you may also want to remove whitespace characters like `\n` at the end of each line
    content = [x.strip() for x in content]
    for idx, line in enumerate(content):
        if not 'variables' in line:
            split = line.split('*')[1].split(',')
            _s = problem.generate_existing_solution([float(x) for x in split], is_objectives=True)
            _s.bag = 'python'
            solutions.append(_s)
    ranking = FastNonDominatedRanking()

    ranking.compute_ranking(solutions)
    front_ = ranking.get_subfront(0)
    print('Solutions:',len(solutions))
    print('Front 0:', len(front_))
    class_fronts = [[], [], [], []]
    fjava = 0
    fpython = 0
    classifier = InterClassNC(problem)
    for s in front_:
        if s.bag == 'java':
            fjava += 1
        else:
            fpython += 1
        # problem.evaluate(s)
        _class = classifier.classify(s)
        if _class[0] > 0:
            class_fronts[0].append(s)
        elif _class[1] > 0:
            class_fronts[1].append(s)
        elif _class[2] > 0:
            class_fronts[2].append(s)
        else:
            class_fronts[3].append(s)
    print('Java solutions:', (fjava / len(front_)))
    print('Python solutions:', (fpython / len(front_)))
    print('HSat : ', len(class_fronts[0]), ', Sat : ', len(class_fronts[1]), ', Dis : ', len(class_fronts[2]),
          ', HDis : ', len(class_fronts[3]))
    _sat = class_fronts[0] + class_fronts[1]
    fjava = 0
    fpython = 0
    for s in _sat:
        if s.bag == 'java':
            fjava += 1
        else:
            fpython += 1

    print('Sat Java solutions:', (fjava / len(_sat)))
    print('Sat Python solutions:', (fpython / len(_sat)))
    plot_front = Plot(title='Sat and HSat Front')
    plot_front.plot(_sat, label= 'Sat and HSat Front',
                    filename=DIRECTORY_RESULTS + 'SatFront' +  problem.get_name(),
                    format='png')
Пример #18
0
    mutation=PolynomialMutation(probability=1.0 / problem.number_of_variables,
                                distribution_index=20),
    crossover=SBXCrossover(probability=1.0, distribution_index=20),
    population_evaluator=MultiprocessEvaluator(processes=num_cpu),
    termination_criterion=StoppingByEvaluations(
        max_evaluations=max_evaluations))
algorithm.observable.register(observer=ProgressBarObserver(
    max=max_evaluations))
# algorithm.observable.register(
#     observer=VisualizerObserver(reference_front=problem.reference_front, display_frequency=100))

algorithm.run()
front = algorithm.get_result()
print(front)
plot_front = Plot(title='Pareto front approximation',
                  reference_front=problem.reference_front,
                  axis_labels=problem.obj_labels)
plot_front.plot(front,
                label='NSGAIII-' + problem.get_name(),
                filename='../images/' + algorithm.get_name() + "-" +
                problem.get_name(),
                format='png')

# Plot interactive front
plot_front = InteractivePlot(title='Pareto front approximation. Problem: ' +
                             problem.get_name(),
                             reference_front=problem.reference_front,
                             axis_labels=problem.obj_labels)
plot_front.plot(
    front,
    label='NSGAIII-' + problem.get_name(),
                               population_size=pop_size,
                               offspring_population_size=int(pop_size * Cr),
                               mutation=MulticastMutation(probability=Pmut,
                                                          Pnmut=Pnmut,
                                                          G=gr),
                               crossover=MulticastCrossover(
                                   probability=Cr,
                                   root_node=root_node,
                                   destination_nodes=destination_nodes,
                                   graph=gr),
                               termination_criterion=StoppingByEvaluations(
                                   max_evaluations=max_evaluations))

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

        # Save results to file
        print_function_values_to_file(
            front,
            f"results/multiobjective/{params['algorithm']}/{params['pop_size']}_{params['nbr_generations']}_{params['network']}_{params['experiment']}_{i}"
        )
        plot_front = Plot(title='Pareto front approximation',
                          axis_labels=['cost', 'delay'])
        plot_front.plot(front,
                        label=f'{params["algorithm"]}',
                        filename=f'{params["algorithm"]}',
                        format='png')
        print(f'Algorithm: ${algorithm.get_name()}')
        print(f'Problem: ${problem.get_name()}')
        print(f'Computing time: ${algorithm.total_computing_time}')
Пример #20
0
    def train(self):
        problem = SVM_Problem(X=self.Xtrain, Y=self.Ytrain)
        #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=PolynomialMutation(probability=1.0 /
                                        problem.number_of_variables,
                                        distribution_index=20),
            crossover=SBXCrossover(probability=1.0, distribution_index=20),
            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())

        print(
            "-----------------------------------------------------------------------------"
        )
        print('Problem: ' + problem.get_name())
        print('Computing time: ' + str(algorithm.total_computing_time))

        # 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))]

        # Get our variables
        self.gamma = solution.variables[0]
        self.C = solution.variables[1]
        self.coef0 = solution.variables[2]
        self.degree = solution.variables[3]
        self.kernel = solution.variables[4]

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

        # Select pick a random array with length of the variable
        X = self.Xtrain[self.instances, :]
        X = X[:, self.attributes]
        Y = self.Ytrain[self.instances]

        print(*front, sep=", ")

        # Contruct model
        self.model = SVM(Xtrain=X,
                         Ytrain=Y,
                         kernel=self.kernel,
                         C=self.C,
                         degree=self.degree,
                         coef0=self.coef0,
                         gamma=self.gamma,
                         seed=self.seed).train()

        print('Objectives: ', *solution.objectives, sep=", ")
        # write your code here
        return self.model
Пример #21
0
    problem = DTLZ1()
    problem.reference_front = read_solutions(
        filename='esources/reference_front/DTLZ1.3D.pf')

    max_evaluations = 25000

    algorithm = NSGAIII(
        problem=problem,
        population_size=92,
        reference_directions=UniformReferenceDirectionFactory(3, n_points=91),
        mutation=PolynomialMutation(probability=1.0 /
                                    problem.number_of_variables,
                                    distribution_index=20),
        crossover=SBXCrossover(probability=1.0, distribution_index=30),
        termination_criterion=StoppingByEvaluations(max=max_evaluations))

    algorithm.observable.register(observer=ProgressBarObserver(
        max=max_evaluations))

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

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

    print('Algorithm (continuous problem): ' + algorithm.get_name())
    print('Problem: ' + problem.get_name())
    print('Computing time: ' + str(algorithm.total_computing_time))
Пример #22
0
    solution = Solution(number_of_variables=7, number_of_objectives=2)
    result = eval(line)
    solution.objectives[0] = result[0]
    solution.objectives[1] = result[1]
    solution_list.append(solution)
    count += 1

print('Obtaining the pareto front')
pareto_front = get_non_dominated_solutions(solution_list)

with open('Paretofront.pf', 'w') as f:
    for pareto in pareto_front:
        f.write(str(pareto.objectives))
        f.write('\n')

plot_front = Plot(title='Pareto front approximation', axis_labels=['Interfaces', 'TIRF'])
plot_front.plot(pareto_front, label='NSGAII-OTN')

# ------------------------Saving multithread implementation ----------------
# from jmetal.core.solution import Solution
# from jmetal.lab.visualization import Plot
# from jmetal.util.solution import get_non_dominated_solutions
#
# from Models.Network import Network
# from Problem.Evaluation import evaluateNetwork
# import timeit
# from itertools import product
#
# from Utils.Log import Log
# import multiprocessing as mp
#
        problem=problem,
        swarm_size=100,
        mutation=PolynomialMutation(probability=1.0 / problem.number_of_variables, distribution_index=20),
        leaders=CrowdingDistanceArchive(100),
        termination_criterion=StoppingByEvaluations(max=max_evaluations)
    )

    algorithm.observable.register(observer=ProgressBarObserver(max=max_evaluations))

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

    label = algorithm.get_name() + "." + problem.get_name()

    # Plot front
    plot_front = Plot(plot_title='Pareto front approximation', reference_front=problem.reference_front,
                      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', reference_front=problem.reference_front,
                                 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())
    print('Problem: ' + problem.get_name())
    print('Computing time: ' + str(algorithm.total_computing_time))
Пример #24
0
    algorithm = NSGAII_MEDA(
        problem=problem,
        population_size=Paras.N_IND,
        offspring_population_size=Paras.N_IND,
        mutation=IntegerPolynomialMutation(probability=1.0 / problem.number_of_variables, distribution_index=20),
        crossover=IntegerSBXCrossover(probability=0.8, distribution_index=20),
        termination_criterion=StoppingByEvaluations(max_evaluations=no_evaluations)
    )
    progress_bar = ProgressBarObserver(max=no_evaluations)
    algorithm.observable.register(progress_bar)
    algorithm.run()
    solutions = algorithm.get_result()
    non_dominated_ranking = FastNonDominatedRanking(algorithm.dominance_comparator)
    non_dominated_ranking.compute_ranking(solutions)
    non_dominated_sols = non_dominated_ranking.get_nondominated()
    plot_front = Plot(title='Pareto front approximation', axis_labels=['Dis', 'Mani'])
    plot_front.plot(non_dominated_sols, label='NSGAII-ZDT1')

    list_labels = []
    for sol in non_dominated_sols:
        list_labels.append(sol.variables)
        dis = sol.objectives[0]
        man = sol.objectives[1]
        # train_acc = sol.objectives[2]
        Yt_sol = sol.variables
        acc = (np.sum(Yt_sol == problem.Yt)+0.0)/len(Yt_sol)
        print("Dis: %.5f, man: %.5f, acc: %.5f" %(dis, man, acc))
        # print("Dis: %.5f, man: %.5f, train acc: %.5f, acc: %.5f" % (dis, man, train_acc ,acc))

    vote_label = Helpers.voting(list_labels)
    acc = (np.sum(Yt_sol == problem.Yt)+0.0)/len(Yt_sol)