import codecs
from jinja2 import Template
import string
import glob
import PySimpleGUI as sg
from flask import Flask, render_template
import pandas as pd
import csv
import numpy as np
from pulp import *
from difflib import get_close_matches
import urllib.request
from bs4 import BeautifulSoup
import re
import itertools
import reprlib
import requests
import regex
import time
from pulp import LpProblem, LpMaximize, lpDot, lpSum, value, GLPK_CMD
from ortoolpy import addvar, addvars, addbinvars
from multiprocessing.pool import ThreadPool
from dask.distributed import Client
import numpy as np
from pymoo.util.misc import stack
from pymoo.core.problem import Problem
from pymoo.algorithms.moo.nsga2 import NSGA2
from pymoo.factory import get_sampling, get_crossover, get_mutation, get_termination, get_problem
from pymoo.optimize import minimize
from pymoo.visualization.scatter import Scatter
from pymoo.core.problem import ElementwiseProblem, dask_parallelized_eval
from pymoo.core.crossover import Crossover
from pymoo.core.mutation import Mutation 
from pymoo.core.sampling import Sampling
from pymoo.algorithms.soo.nonconvex.ga import GA
from pymoo.optimize import minimize
from pymoo.util.display import Display
import matplotlib.pyplot as plt
from PIL import Image
import shutil


class MyProblem(ElementwiseProblem):
    def __init__(self):
        super().__init__(n_var=2, # 入力変数の次元
                         n_obj=2, # 目的関数の数
                         n_constr=2, # 制約条件の数
                         xl=np.array([-2,-2]), # 入力変数の下限
                         xu=np.array([2,2]), # 入力変数の上限
                         )
    def _evaluate(self, x, out, *args, **kwargs):
        # 目的関数
        f1 = x[0]**2 + x[1]**2
        f2 = (x[0]-1)**2 + x[1]**2
        # 制約条件
        g1 = 2*(x[0]-0.1) * (x[0]-0.9) / 0.18
        g2 = - 20*(x[0]-0.4) * (x[0]-0.6) / 4.8

        out["F"] = [f1, f2]
        out["G"] = [g1, g2]



n_threads = 1 # スレッド数
pool = ThreadPool(n_threads) # 初期化
problem = MyProblem(parallelization = ('starmap', pool.starmap))
algorithm = NSGA2(pop_size=100)
res = minimize(problem, algorithm,('n_gen', 100),seed=1,verbose=True) # 計算の実行
plot = Scatter()
plot.add(problem.pareto_front(), plot_type="line", color="black", alpha=0.7)
plot.add(res.F, color="red")
plot.show()
print(f'Threads: {res.exec_time} sec')
pool.close()