├── .gitignore ├── DNE4py ├── __init__.py ├── mpi_extensions.py ├── optimizers │ ├── __init__.py │ ├── deepga │ │ ├── __init__.py │ │ ├── base.py │ │ ├── deepga.py │ │ ├── member.py │ │ ├── mutation.py │ │ └── selection.py │ └── optimizer.py └── version_v2 │ ├── new_optimizers │ ├── cmaes │ │ ├── __init__.py │ │ └── cmaes.py │ ├── deepga2 │ │ ├── __init__.py │ │ ├── base.py │ │ ├── deepga.py │ │ ├── member.py │ │ ├── mutation.py │ │ ├── ranking.py │ │ └── selection.py │ └── random │ │ ├── __init__.py │ │ └── batch.py │ ├── new_tutorials │ └── tutorials2 │ │ ├── README.md │ │ ├── pp_run.py │ │ ├── render.py │ │ └── run.py │ ├── postprocessing │ ├── __init__.py │ ├── test.py │ └── utils.py │ └── sliceops.py ├── LICENSE ├── README.md ├── setup.py └── tutorials ├── 1_optimizing_user_defined_function ├── TruncatedRealMutatorGA.yaml └── run.py ├── 2_postprocessing_the_results ├── gif │ ├── cmaes.gif │ ├── deepga_truncatedrealmutatorga.gif │ └── randomsearch.gif ├── pp_run.py └── render.py └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | # pyenv 2 | .python-version 3 | 4 | # Byte-compiled / optimized / DLL files 5 | __pycache__/ 6 | *.py[cod] 7 | *$py.class 8 | 9 | # C extensions 10 | *.so 11 | 12 | # Distribution / packaging 13 | .Python 14 | build/ 15 | develop-eggs/ 16 | dist/ 17 | downloads/ 18 | eggs/ 19 | .eggs/ 20 | lib/ 21 | lib64/ 22 | parts/ 23 | sdist/ 24 | var/ 25 | wheels/ 26 | share/python-wheels/ 27 | *.egg-info/ 28 | .installed.cfg 29 | *.egg 30 | MANIFEST 31 | 32 | # PyInstaller 33 | # Usually these files are written by a python script from a template 34 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 35 | *.manifest 36 | *.spec 37 | 38 | # Installer logs 39 | pip-log.txt 40 | pip-delete-this-directory.txt 41 | 42 | # Unit test / coverage reports 43 | htmlcov/ 44 | .tox/ 45 | .nox/ 46 | .coverage 47 | .coverage.* 48 | .cache 49 | nosetests.xml 50 | coverage.xml 51 | *.cover 52 | *.py,cover 53 | .hypothesis/ 54 | .pytest_cache/ 55 | cover/ 56 | 57 | # Translations 58 | *.mo 59 | *.pot 60 | 61 | # Django stuff: 62 | *.log 63 | local_settings.py 64 | db.sqlite3 65 | db.sqlite3-journal 66 | 67 | # Flask stuff: 68 | instance/ 69 | .webassets-cache 70 | 71 | # Scrapy stuff: 72 | .scrapy 73 | 74 | # Sphinx documentation 75 | docs/_build/ 76 | 77 | # PyBuilder 78 | .pybuilder/ 79 | target/ 80 | 81 | # Jupyter Notebook 82 | .ipynb_checkpoints 83 | 84 | # IPython 85 | profile_default/ 86 | ipython_config.py 87 | 88 | # pyenv 89 | # For a library or package, you might want to ignore these files since the code is 90 | # intended to run in multiple environments; otherwise, check them in: 91 | # .python-version 92 | 93 | # pipenv 94 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 95 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 96 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 97 | # install all needed dependencies. 98 | #Pipfile.lock 99 | 100 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 101 | __pypackages__/ 102 | 103 | # Celery stuff 104 | celerybeat-schedule 105 | celerybeat.pid 106 | 107 | # SageMath parsed files 108 | *.sage.py 109 | 110 | # Environments 111 | .env 112 | .venv 113 | env/ 114 | venv/ 115 | ENV/ 116 | env.bak/ 117 | venv.bak/ 118 | 119 | # Spyder project settings 120 | .spyderproject 121 | .spyproject 122 | 123 | # Rope project settings 124 | .ropeproject 125 | 126 | # mkdocs documentation 127 | /site 128 | 129 | # mypy 130 | .mypy_cache/ 131 | .dmypy.json 132 | dmypy.json 133 | 134 | # Pyre type checker 135 | .pyre/ 136 | 137 | # pytype static type analyzer 138 | .pytype/ 139 | 140 | # Cython debug symbols 141 | cython_debug/ 142 | -------------------------------------------------------------------------------- /DNE4py/__init__.py: -------------------------------------------------------------------------------- 1 | def load_optimizer(config): 2 | 3 | from DNE4py.optimizers.deepga import TruncatedRealMutatorGA 4 | 5 | optimizer_classes = {"TruncatedRealMutatorGA": TruncatedRealMutatorGA} 6 | 7 | optimizer = optimizer_classes[config['id']](config) 8 | return optimizer 9 | 10 | def load_mpidata(name, folder_path): 11 | 12 | import json 13 | import glob 14 | import numpy as np 15 | 16 | # Internals: 17 | nb_files = len(glob.glob1(f'{folder_path}', f'{name}*')) 18 | with open(f'{folder_path}/info.json', 'rb') as f: 19 | info = json.load(f) 20 | nb_generations = info['nb_generations'] 21 | 22 | # Get data: 23 | if name in ['costs', 'genotypes']: 24 | data = [[] for i in range(nb_files)] 25 | for i in range(nb_files): 26 | generation_data = [] 27 | with open(f'{folder_path}/{name}_w{i}.npy', 'rb') as f: 28 | for g in range(nb_generations): 29 | generation_data.append(np.load(f, allow_pickle=True).tolist()) 30 | data[i] = generation_data 31 | data = np.array(data, object) 32 | data = np.transpose(data, (1, 0, 2)) 33 | data = data.reshape((data.shape[0], data.shape[1] * data.shape[2])) 34 | return data 35 | elif name in ['initial_guess']: 36 | with open(f'{folder_path}/initial_guess.npy', 'rb') as f: 37 | return np.load(f, allow_pickle=True) 38 | else: 39 | print(f'load_mpidata failed, name "{name}" not found!') 40 | exit() 41 | 42 | def get_best_phenotype(folder_path): 43 | 44 | import json 45 | import numpy as np 46 | from DNE4py.optimizers.deepga.mutation import Member 47 | 48 | # Internals: 49 | # with open(f'{folder_path}/info.json', 'rb') as f: 50 | # info = json.load(f) 51 | # sigma = info['sigma'] 52 | 53 | # Read Input: 54 | costs = load_mpidata("costs", f"{folder_path}") 55 | genotypes = load_mpidata("genotypes", f"{folder_path}") 56 | initial_guess = load_mpidata("initial_guess", f"{folder_path}") 57 | 58 | # Select Best Idx: 59 | best_idx = np.unravel_index(costs.argmin(), costs.shape) 60 | 61 | # Create member and get phonetype: 62 | phenotype = Member(initial_guess, genotypes[best_idx]).phenotype 63 | return phenotype 64 | 65 | def get_best_phenotype_generator(folder_path): 66 | 67 | import json 68 | import numpy as np 69 | from DNE4py.optimizers.deepga.mutation import Member 70 | 71 | # Internals: 72 | with open(f'{folder_path}/info.json', 'rb') as f: 73 | info = json.load(f) 74 | nb_generations = info['nb_generations'] 75 | 76 | # Read Input: 77 | costs = load_mpidata("costs", f"{folder_path}") 78 | genotypes = load_mpidata("genotypes", f"{folder_path}") 79 | initial_guess = load_mpidata("initial_guess", f"{folder_path}") 80 | 81 | # Select Best Idxs: 82 | min_idxs = np.argmin(costs, axis=1) 83 | for i in range(nb_generations): 84 | genotype = genotypes[i, min_idxs[i]] 85 | yield Member(initial_guess, genotype).phenotype 86 | -------------------------------------------------------------------------------- /DNE4py/mpi_extensions.py: -------------------------------------------------------------------------------- 1 | import os 2 | import pickle 3 | import logging 4 | 5 | import numpy as np 6 | 7 | class MPISaver: 8 | 9 | def __init__(self, file_path): 10 | 11 | self.file_path = file_path 12 | self.folder_path, self.filename = os.path.split(self.file_path) 13 | 14 | try: 15 | os.makedirs(self.folder_path) 16 | except: 17 | pass 18 | 19 | assert os.path.isfile(self.file_path) == False, f'You should delete all files inside the folder: {self.folder_path} | {self.file_path}' 20 | 21 | def write(self, data): 22 | with open(self.file_path, 'ab') as f: 23 | np.save(f, data) 24 | 25 | class MPILogger: 26 | 27 | def __init__(self, file_path): 28 | 29 | self.file_path = file_path 30 | self.folder_path, self.filename = os.path.split(file_path) 31 | 32 | try: 33 | os.makedirs(self.folder_path) 34 | except: 35 | pass 36 | 37 | assert os.path.isfile(self.file_path) == False, f'You should delete all files inside the folder: {self.folder_path} | {self.file_path}' 38 | 39 | logging.basicConfig(filename=self.file_path, 40 | level=logging.DEBUG, 41 | format='%(message)s') 42 | 43 | def debug(self, msg): 44 | logging.debug(msg) 45 | -------------------------------------------------------------------------------- /DNE4py/optimizers/__init__.py: -------------------------------------------------------------------------------- 1 | #from .deepga import TruncatedRealMutatorGA 2 | -------------------------------------------------------------------------------- /DNE4py/optimizers/deepga/__init__.py: -------------------------------------------------------------------------------- 1 | from .deepga import TruncatedRealMutatorGA 2 | 3 | __all__ = [ 4 | "TruncatedRealMutatorGA", 5 | ] 6 | -------------------------------------------------------------------------------- /DNE4py/optimizers/deepga/base.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import json 3 | import random 4 | 5 | from abc import ABC, abstractmethod 6 | 7 | from DNE4py.mpi_extensions import MPISaver, MPILogger 8 | 9 | #from DNE4py.optimizers.optimizer import Optimizer 10 | 11 | class BaseGA: 12 | 13 | r''' 14 | Example config: 15 | 16 | id: TruncatedRealMutatorGA 17 | initial_guess = np.array([-0.3, 0.7]) 18 | workers_per_rank: 10 19 | num_elite: 3 20 | num_parents: 5 21 | sigma: 0.05 22 | global_seed: 42 23 | output_folder: 'results/DeepGA/TruncatedRealMutatorGA' 24 | save_steps: 1 25 | verbose: 0 26 | 27 | Description: 28 | 29 | * output_folder (int) 30 | => path for the raw_data that will be processed with 31 | postprocessing module 32 | 33 | * save_steps (int) 34 | => save per each save_steps generations 35 | 36 | * verbose (int) 37 | => 0 no printing 38 | => 1 print number of generations with rank 0 39 | => 2 save debug file 40 | 41 | ''' 42 | 43 | def __init__(self, config): 44 | 45 | # config.get('env_options').get('max_iteration') 46 | 47 | # super().__init__(**config) 48 | 49 | # Initiate MPI 50 | from mpi4py import MPI 51 | self._MPI = MPI 52 | self._comm = MPI.COMM_WORLD 53 | self._size = self._comm.Get_size() 54 | self._rank = self._comm.Get_rank() 55 | 56 | # Configuration: 57 | self.id = config.get('id') 58 | self.workers_per_rank = config.get('workers_per_rank') 59 | self.num_elite = config.get('num_elite') 60 | self.num_parents = config.get('num_parents') 61 | self.sigma_initial = config.get('sigma_initial') 62 | self.sigma_min = config.get('sigma_min') 63 | self.sigma_decay = config.get('sigma_decay') 64 | 65 | self.global_seed = config.get('global_seed') 66 | 67 | self.output_folder = config.get('output_folder') 68 | self.save_steps = config.get('save_steps') 69 | self.verbose = config.get('verbose') 70 | 71 | self.initial_guess = config.get('initial_guess') 72 | 73 | # Internal: 74 | self.sigma = self.sigma_initial 75 | self.generation = 0 76 | self.population_size = self._size * self.workers_per_rank 77 | 78 | # Initialize Mutator and Selection 79 | self.mutator_initialize() 80 | self.selection_initialize() 81 | 82 | 83 | # Logger and DataCollector for MPI: 84 | 85 | if self.output_folder != None and self.verbose == 2: 86 | self.logger = MPILogger(f'{self.output_folder}/info_w{self._rank}.log') 87 | 88 | if self.output_folder != None: 89 | self.saver_genotypes = MPISaver(f'{self.output_folder}/genotypes_w{self._rank}.npy') 90 | self.saver_costs = MPISaver(f'{self.output_folder}/costs_w{self._rank}.npy') 91 | 92 | if self._rank == 0: 93 | self.saver_initialguess = MPISaver(f'{self.output_folder}/initial_guess.npy') 94 | 95 | #@abstractmethod 96 | #def apply_selection(self, ranks_by_performance): 97 | # pass 98 | 99 | #@abstractmethod 100 | #def apply_mutation(self, ranks_by_performance): 101 | # pass 102 | 103 | def run(self, objective_function, steps): 104 | 105 | self.objective_function = objective_function 106 | 107 | if self._rank == 0: 108 | self.saver_initialguess.write(self.initial_guess) 109 | 110 | for _ in range(steps): 111 | 112 | # =================== LOGGING ===================================== 113 | if self.verbose == 1: 114 | if self._rank == 0: 115 | print(f"Generation: {self.generation}/{steps}") 116 | elif self.verbose == 2: 117 | self.logger.debug(f"\nGeneration: {self.generation}/{steps}") 118 | # =================== LOGGING ===================================== 119 | 120 | self.step() 121 | 122 | # CLOSING: 123 | if self._rank == 0: 124 | if self.output_folder != None: 125 | info = {'nb_generations': steps} 126 | with open(f'{self.output_folder}/info.json', "w") as f: 127 | json.dump(info, f) 128 | 129 | def step(self): 130 | 131 | # Evaluate member: 132 | self.cost_list = np.zeros(self.workers_per_rank) 133 | for i in range(len(self.cost_list)): 134 | self.cost_list[i] = self.objective_function(self.members[i].phenotype) 135 | 136 | # ======================= LOGGING ===================================== 137 | if self.verbose == 2: 138 | self.logger.debug(f"\nPopulation Members (Initial):") 139 | self.logger.debug(f"| index | seed | x0 | x1 | y |") 140 | for index in range(len(self.members)): 141 | seed = self.members[index].genotype 142 | x0 = self.members[index].phenotype[0].round(10) 143 | x1 = self.members[index].phenotype[1].round(10) 144 | y = self.cost_list[index].round(10) 145 | self.logger.debug(f"| {index} | {seed} | {x0} | {x1} | {y} |") 146 | # ===================== END LOGGING =================================== 147 | 148 | # ======================= SAVING ===================================== 149 | if (self.generation % self.save_steps == 0): 150 | self.saver_genotypes.write(self.genotypes) 151 | self.saver_costs.write(self.costs) 152 | else: 153 | self.saver_genotypes.write(np.array(np.nan)) 154 | self.saver_costs.write(np.array(np.nan)) 155 | # ===================== END SAVING =================================== 156 | 157 | # Broadcast fitness: 158 | cost_matrix = np.empty((self._size, self.workers_per_rank)) 159 | self._comm.Allgather([self.cost_list, self._MPI.FLOAT], 160 | [cost_matrix, self._MPI.FLOAT]) 161 | 162 | # Truncate Selection (broadcast genotypes and update members): 163 | order = np.argsort(cost_matrix.flatten()) 164 | rank = np.argsort(order) 165 | ranks_and_members_by_performance = rank.reshape(cost_matrix.shape) 166 | 167 | # Apply selection: 168 | self.apply_selection(ranks_and_members_by_performance) 169 | 170 | # ======================= LOGGING ===================================== 171 | if self.verbose == 2: 172 | self.logger.debug(f"\nPopulation Members (After Selection):") 173 | self.logger.debug(f"| index | seed | x0 | x1 |") 174 | for index in range(len(self.members)): 175 | seed = self.members[index].genotype 176 | x0 = self.members[index].phenotype[0].round(10) 177 | x1 = self.members[index].phenotype[1].round(10) 178 | self.logger.debug(f"| {index} | {seed} | {x0} | {x1} |") 179 | # ===================== END LOGGING =================================== 180 | 181 | # Apply mutations: 182 | self.update_sigma() 183 | self.apply_mutation(ranks_and_members_by_performance) 184 | 185 | # ======================= LOGGING ===================================== 186 | if self.verbose == 2: 187 | self.logger.debug(f"\nPopulation Members (After Mutation):") 188 | self.logger.debug(f"| index | seed | x0 | x1 |") 189 | for index in range(len(self.members)): 190 | seed = self.members[index].genotype 191 | x0 = self.members[index].phenotype[0].round(10) 192 | x1 = self.members[index].phenotype[1].round(10) 193 | self.logger.debug(f"| {index} | {seed} | {x0} | {x1} |") 194 | # ===================== END LOGGING =================================== 195 | 196 | # Next generation: 197 | self.generation += 1 198 | 199 | @ property 200 | def genotypes(self): 201 | genotypes = [] 202 | for member in self.members: 203 | genotypes.append(member.genotype) 204 | return np.array(genotypes, dtype=object) 205 | 206 | @ property 207 | def costs(self): 208 | return self.cost_list 209 | 210 | def update_sigma(self): 211 | self.sigma *= self.sigma_decay 212 | if self.sigma < self.sigma_min: 213 | self.sigma = self.sigma_min -------------------------------------------------------------------------------- /DNE4py/optimizers/deepga/deepga.py: -------------------------------------------------------------------------------- 1 | 2 | from .base import BaseGA 3 | from .mutation import RealMutator 4 | from .selection import TruncatedSelection 5 | 6 | 7 | class TruncatedRealMutatorGA(TruncatedSelection, RealMutator, BaseGA): 8 | pass 9 | -------------------------------------------------------------------------------- /DNE4py/optimizers/deepga/member.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | 4 | class Member: 5 | r''' 6 | Initialization: 7 | initial_phenotype: initial list of parameters 8 | initial_genotype: initial seed and initial sigma 9 | 10 | Internal attributes: 11 | genotype: list of seeds 12 | phenotype: list of parameters 13 | 14 | Methods: 15 | recreate(new_genotype): 16 | update genotype and phenotype from new_genotype 17 | mutate(rng_genes): 18 | create a new gene and update genotype and phenotype 19 | ''' 20 | 21 | def __init__(self, initial_phenotype, genotype): 22 | 23 | # Define initial phenotype: 24 | self.initial_phenotype = initial_phenotype 25 | self.phenotype = self.initial_phenotype.copy() 26 | 27 | # Internal attributes: 28 | self.rng = np.random.RandomState() 29 | self.size = len(self.initial_phenotype) 30 | 31 | # Define genotype and phenotype: 32 | self.recreate(genotype) 33 | 34 | def mutate(self, rng_genes, sigma): 35 | r'''create a new gene and update genotype and phenotype''' 36 | 37 | # Increase genotype: 38 | seed = rng_genes.randint(0, 2 ** 32 - 1) 39 | self.genotype.append([seed, sigma]) 40 | 41 | # Mutate phenotype: 42 | self.rng.seed(seed) 43 | self.phenotype += self.rng.randn(self.size) * sigma 44 | 45 | 46 | def recreate(self, new_genotype): 47 | r'''update genotype and phenotype from new_genotype''' 48 | 49 | # Set genotype: 50 | self.genotype = new_genotype[:] 51 | 52 | # Set phenotype: 53 | self.phenotype[:] = self.initial_phenotype[:] 54 | for seed, sigma in self.genotype: 55 | self.rng.seed(seed) 56 | self.phenotype += self.rng.randn(self.size) * sigma -------------------------------------------------------------------------------- /DNE4py/optimizers/deepga/mutation.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | import numpy as np 4 | 5 | from .base import BaseGA 6 | from .member import Member 7 | 8 | class RealMutator(BaseGA): 9 | 10 | def mutator_initialize(self): 11 | 12 | # Global Random Generator: 13 | self.rgn_global = random.Random(self.global_seed) 14 | 15 | # Global seedmatrix: 16 | self.seedmatrix = np.zeros((self._size, self.workers_per_rank), dtype=np.int64) 17 | for i in range(self._size): 18 | row = self.rgn_global.sample(range(2**32 - 1), self.workers_per_rank) 19 | self.seedmatrix[i] = row 20 | 21 | # Generate Genes Random Generator: 22 | self.rng_genes_list = [np.random.RandomState(self.seedmatrix[self._rank, i]) for i in range(self.workers_per_rank)] 23 | 24 | # Generate Initial genes 25 | self.initial_genotypes = [] 26 | for i in range(self.workers_per_rank): 27 | initial_genotype = self.rng_genes_list[i].randint(2**32 - 1) 28 | self.initial_genotypes.append([[initial_genotype, self.sigma]]) 29 | 30 | self.members = [Member(initial_phenotype=self.initial_guess, 31 | genotype=self.initial_genotypes[i]) 32 | for i in range(self.workers_per_rank)] 33 | 34 | def apply_mutation(self, ranks_and_members_by_performance): 35 | """ 36 | Preserve the top num_elite members, mutate the rest 37 | """ 38 | no_elite_mask = ranks_and_members_by_performance >= self.num_elite 39 | 40 | row, column = np.where(no_elite_mask) 41 | no_elite_tuples = tuple(zip(row, column)) 42 | 43 | # ======================= LOGGING ===================================== 44 | if self.verbose == 2: 45 | self.logger.debug(f"\nSelected Elite:") 46 | self.logger.debug(f"| rank | member_id |") 47 | elite_mask = np.invert(no_elite_mask) 48 | row, column = np.where(elite_mask) 49 | elite_indexes = tuple(zip(row, column)) 50 | for rank, member_id in elite_indexes: 51 | self.logger.debug(f"| {rank} | {member_id} |") 52 | # ===================== END LOGGING =================================== 53 | 54 | for rank, member_id in no_elite_tuples: 55 | if rank == self._rank: 56 | rng_genes = self.rng_genes_list[member_id] 57 | self.members[member_id].mutate(rng_genes, self.sigma) 58 | -------------------------------------------------------------------------------- /DNE4py/optimizers/deepga/selection.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | from .base import BaseGA 4 | 5 | class TruncatedSelection(BaseGA): 6 | 7 | def selection_initialize(self): 8 | 9 | # Init: 10 | self.rgn_selection = np.random.RandomState(self.global_seed) 11 | 12 | if self.num_elite > self.num_parents: 13 | raise AssertionError("Number of elite has to be less than the" 14 | " number of parents") 15 | 16 | def apply_selection(self, ranks_and_members_by_performance): 17 | 18 | # 1 - Define parents and no parents: 19 | parents_mask = ranks_and_members_by_performance < self.num_parents 20 | no_parents_mask = np.invert(parents_mask) 21 | 22 | row, column = np.where(parents_mask) 23 | parents_indexes = tuple(zip(row, column)) 24 | parent_options = range(len(parents_indexes)) 25 | 26 | row, column = np.where(no_parents_mask) 27 | no_parents_indexes = tuple(zip(row, column)) 28 | 29 | # ======================= LOGGING ===================================== 30 | if self.verbose == 2: 31 | self.logger.debug(f"\nSelected Parents:") 32 | self.logger.debug(f"| rank | member_id |") 33 | for rank, member_id in parents_indexes: 34 | self.logger.debug(f"| {rank} | {member_id} |") 35 | # ===================== END LOGGING =================================== 36 | 37 | # 2 - Update member for each rank: 38 | # Build message_list: 39 | messenger_list = [] 40 | for dest_rank, dest_member_id in no_parents_indexes: 41 | choice = self.rgn_selection.choice(parent_options) 42 | src_rank, src_member_id = parents_indexes[choice] 43 | messenger_list.append((src_rank, 44 | src_member_id, 45 | dest_rank, 46 | dest_member_id)) 47 | 48 | # ======================= LOGGING ===================================== 49 | if self.verbose == 2: 50 | self.logger.debug(f"\nSelection Messenger List") 51 | self.logger.debug(f"| src_rank | src_member_id | dest_rank | dest_member_id |") 52 | for (src_rank, 53 | src_member_id, 54 | dest_rank, 55 | dest_member_id) in messenger_list: 56 | self.logger.debug(f"| {src_rank} | {src_member_id} | {dest_rank} | {dest_member_id} |") 57 | # ===================== END LOGGING =================================== 58 | 59 | # Dispatch message_list: 60 | for (src_rank, 61 | src_member_id, 62 | dest_rank, 63 | dest_member_id) in messenger_list: 64 | if src_rank != dest_rank: # Need send to MPI 65 | if src_rank == self._rank: 66 | message = (self.members[src_member_id].genotype, 67 | dest_member_id) 68 | self._comm.send(message, dest=dest_rank) 69 | elif dest_rank == self._rank: 70 | new_genotype, member_id = self._comm.recv(source=src_rank) 71 | self.members[member_id].recreate(new_genotype) 72 | else: 73 | if (self._rank == src_rank): 74 | new_genotype = self.members[src_member_id].genotype 75 | member_id = dest_member_id 76 | self.members[member_id].recreate(new_genotype) 77 | -------------------------------------------------------------------------------- /DNE4py/optimizers/optimizer.py: -------------------------------------------------------------------------------- 1 | r""" 2 | Abstract base module for all DNE4py optimizers. 3 | """ 4 | 5 | from abc import ABC, abstractmethod 6 | 7 | 8 | class Optimizer(ABC): 9 | r"""Abstract base class for optimizers.""" 10 | 11 | @abstractmethod 12 | def run(self, objective_function, steps): 13 | r"""Optimize the objective function. 14 | 15 | Args: 16 | objective_function: function to be optimized 17 | steps: Number of iterations 18 | """ 19 | pass 20 | -------------------------------------------------------------------------------- /DNE4py/version_v2/new_optimizers/cmaes/__init__.py: -------------------------------------------------------------------------------- 1 | from .cmaes import CMAES 2 | 3 | __all__ = [ 4 | "CMAES", 5 | ] 6 | -------------------------------------------------------------------------------- /DNE4py/version_v2/new_optimizers/cmaes/cmaes.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | from ..optimizer import Optimizer 4 | from DNE4py.utils.mpi_extensions import MPISaver, MPILogger 5 | import cma 6 | 7 | 8 | class CMAES(Optimizer): 9 | 10 | def __init__(self, objective_function, config): 11 | 12 | super().__init__(objective_function, config) 13 | 14 | # self.objective_function 15 | # self.initial_guess 16 | # self.workers_per_rank 17 | # self.sigma 18 | # self.global_seed 19 | # self.save 20 | # self.verbose 21 | # self.output_folder 22 | 23 | # Initiate MPI 24 | from mpi4py import MPI 25 | self._MPI = MPI 26 | self._comm = MPI.COMM_WORLD 27 | self._size = self._comm.Get_size() 28 | self._rank = self._comm.Get_rank() 29 | 30 | # Input: 31 | #self.objective_function = kwargs.get('objective_function') 32 | #self.initial_guess = kwargs.get('initial_guess') 33 | #self.sigma = kwargs.get('sigma') 34 | #self.global_seed = kwargs.get('seed') 35 | 36 | #self.save = kwargs.get('save', 0) 37 | #self.verbose = kwargs.get('verbose', 0) 38 | #self.output_folder = kwargs.get('output_folder', 'DNE4py_result') 39 | 40 | #self.workers_per_rank = kwargs.get('workers_per_rank') 41 | 42 | # Internal: 43 | self.population_size = self._size * self.workers_per_rank 44 | self.optimizer = cma.CMAEvolutionStrategy(self.initial_guess, self.sigma, {'verb_disp': 0, 'seed': self.global_seed, 'popsize': self.population_size}) 45 | self.my_ids = np.array_split(range(self.population_size), self._size)[self._rank] 46 | self.generation = 0 47 | 48 | # Logger and DataCollector for MPI: 49 | if (self.verbose == 2) or (self.save > 0): 50 | 51 | if self.verbose == 2: 52 | self.logger = MPILogger(self.output_folder, 'debug_logger', self._rank) 53 | if self.save > 0: 54 | self.mpidata_genotypes = MPIData(self.output_folder, 55 | 'genotypes', 56 | self._rank) 57 | self.mpidata_costs = MPIData(self.output_folder, 58 | 'costs', 59 | self._rank) 60 | self.mpidata_initialguess = MPIData(self.output_folder, 61 | 'initial_guess', 62 | 0) 63 | 64 | def run(self, steps): 65 | 66 | for _ in range(steps): 67 | 68 | # =================== LOGGING ===================================== 69 | if self.verbose > 0 and self._rank == 0: 70 | print(f"Generation: {self.generation}/{steps}") 71 | elif self.verbose == 2: 72 | self.logger.debug(f"\nGeneration: {self.generation}/{steps}") 73 | # =================== LOGGING ===================================== 74 | 75 | self.step() 76 | 77 | def step(self): 78 | 79 | # Ask solutions: 80 | self.solutions = np.array(self.optimizer.ask()) 81 | 82 | # Evaluate only your own solutions: 83 | self.my_solutions = self.solutions[self.my_ids] 84 | self.cost_list = np.zeros(self.workers_per_rank) 85 | for i in range(len(self.cost_list)): 86 | self.cost_list[i] = self.objective_function(self.my_solutions[i]) 87 | 88 | # Broadcast fitness: 89 | self.all_costs = np.empty(self.population_size) 90 | self._comm.Allgather([self.cost_list, self._MPI.FLOAT], 91 | [self.all_costs, self._MPI.FLOAT]) 92 | 93 | # Tell solutions and evaluations: 94 | self.optimizer.tell(self.solutions, self.all_costs) 95 | 96 | # Save: 97 | if (self.save > 0) and (self.generation % self.save == 0): 98 | self.mpi_save(self.generation) 99 | 100 | # ======================= LOGGING ===================================== 101 | if self.verbose == 2: 102 | self.logger.debug(f"\n| index | x0 | x1 | y |") 103 | for index, sol in enumerate(self.solutions): 104 | 105 | x0 = sol[0].round(10) 106 | x1 = sol[1].round(10) 107 | y = self.all_costs[index].round(10) 108 | if index in self.my_ids: 109 | self.logger.debug(f"| {index} | {x0} | {x1} | {y} | X |") 110 | else: 111 | self.logger.debug(f"| {index} | {x0} | {x1} | {y} |") 112 | # ===================== END LOGGING =================================== 113 | 114 | # Next generation: 115 | self.generation += 1 116 | 117 | # Evaluate member: 118 | # self.cost_list = np.zeros(self.workers_per_rank) 119 | # for i in range(len(self.cost_list)): 120 | # self.cost_list[i] = self.objective_function(self.members[i].phenotype) 121 | 122 | 123 | # # Save: 124 | # if (self.save > 0) and (self.generation % self.save == 0): 125 | # self.mpi_save(self.generation) 126 | 127 | # # Broadcast fitness: 128 | # cost_matrix = np.empty((self._size, self.workers_per_rank)) 129 | # self._comm.Allgather([self.cost_list, self._MPI.FLOAT], 130 | # [cost_matrix, self._MPI.FLOAT]) 131 | 132 | # # Truncate Selection (broadcast genotypes and update members): 133 | # order = np.argsort(cost_matrix.flatten()) 134 | # rank = np.argsort(order) 135 | # ranks_and_members_by_performance = rank.reshape(cost_matrix.shape) 136 | 137 | # Apply selection: 138 | # self.apply_selection(ranks_and_members_by_performance) 139 | 140 | # # ======================= LOGGING ===================================== 141 | # if self.verbose == 2: 142 | # self.logger.debug(f"\nPopulation Members (After Selection):") 143 | # self.logger.debug(f"| index | seed | x0 | x1 |") 144 | # for index in range(len(self.members)): 145 | # seed = self.members[index].genotype 146 | # x0 = self.members[index].phenotype[0].round(10) 147 | # x1 = self.members[index].phenotype[1].round(10) 148 | # self.logger.debug(f"| {index} | {seed} | {x0} | {x1} |") 149 | # ===================== END LOGGING =================================== 150 | 151 | # Apply mutations: 152 | # self.apply_mutation(ranks_and_members_by_performance) 153 | 154 | # # ======================= LOGGING ===================================== 155 | # if self.verbose == 2: 156 | # self.logger.debug(f"\nPopulation Members (After Mutation):") 157 | # self.logger.debug(f"| index | seed | x0 | x1 |") 158 | # for index in range(len(self.members)): 159 | # seed = self.members[index].genotype 160 | # x0 = self.members[index].phenotype[0].round(10) 161 | # x1 = self.members[index].phenotype[1].round(10) 162 | # self.logger.debug(f"| {index} | {seed} | {x0} | {x1} |") 163 | # # ===================== END LOGGING =================================== 164 | 165 | # # Next generation: 166 | # self.generation += 1 167 | 168 | def mpi_save(self, s): 169 | 170 | self.mpidata_genotypes.write(self.my_solutions) 171 | self.mpidata_costs.write(self.cost_list) 172 | if s == 0: 173 | self.mpidata_initialguess.write(self.initial_guess) 174 | -------------------------------------------------------------------------------- /DNE4py/version_v2/new_optimizers/deepga2/__init__.py: -------------------------------------------------------------------------------- 1 | from .deepga import TruncatedRealMutatorCompactGA, TruncatedRealMutatorCompositeGA 2 | 3 | __all__ = [ 4 | "TruncatedRealMutatorCompactGA", 5 | "TruncatedRealMutatorCompositeGA" 6 | ] 7 | 8 | -------------------------------------------------------------------------------- /DNE4py/version_v2/new_optimizers/deepga2/base.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import pickle 3 | import random 4 | 5 | from abc import ABC, abstractmethod 6 | 7 | from DNE4py.utils import MPIData, MPILogger 8 | 9 | from DNE4py.optimizers.optimizer import Optimizer 10 | #from .mutation import RealMutator 11 | #from .selection import TruncatedSelection 12 | 13 | class BaseGA(Optimizer): 14 | 15 | def __init__(self, objective_function, config): 16 | 17 | super().__init__(objective_function, config) 18 | 19 | # self.initial_guess 20 | # workers_per_rank 21 | # num_elite 22 | # num_parents 23 | # sigma 24 | # seed 25 | # save 26 | # verbose 27 | # output_folder 28 | 29 | # Initiate MPI 30 | from mpi4py import MPI 31 | self._MPI = MPI 32 | self._comm = MPI.COMM_WORLD 33 | self._size = self._comm.Get_size() 34 | self._rank = self._comm.Get_rank() 35 | 36 | # mutator and selection 37 | self.mutator_initialize() 38 | self.selection_initialize() 39 | 40 | # Internal: 41 | self.generation = 0 42 | self.population_size = self._size * self.workers_per_rank 43 | 44 | # Logger and DataCollector for MPI: 45 | if (self.verbose == 2) or (self.save > 0): 46 | 47 | if self.verbose == 2: 48 | self.logger = MPILogger(self.output_folder, 'debug_logger', self._rank) 49 | if self.save > 0: 50 | self.mpidata_genotypes = MPIData(self.output_folder, 51 | 'genotypes', 52 | self._rank) 53 | self.mpidata_costs = MPIData(self.output_folder, 54 | 'costs', 55 | self._rank) 56 | self.mpidata_initialguess = MPIData(self.output_folder, 57 | 'initial_guess', 58 | 0) 59 | self.mpidata_rankings = MPIData(self.output_folder, 60 | 'rankings', 61 | self._rank) 62 | #@abstractmethod 63 | def apply_ranking(self, ranks_by_performance): 64 | pass 65 | 66 | #@abstractmethod 67 | def apply_selection(self, ranks_by_performance): 68 | pass 69 | 70 | #@abstractmethod 71 | def apply_mutation(self, ranks_by_performance): 72 | pass 73 | 74 | def run(self, steps): 75 | 76 | for _ in range(steps): 77 | 78 | # =================== LOGGING ===================================== 79 | if self.verbose > 0 and self._rank == 0: 80 | print(f"Generation: {self.generation}/{steps}") 81 | elif self.verbose == 2: 82 | self.logger.debug(f"\nGeneration: {self.generation}/{steps}") 83 | # =================== LOGGING ===================================== 84 | 85 | self.step() 86 | 87 | def step(self): 88 | # Apply ranking : 89 | ranks_and_members_by_performance = self.apply_ranking() 90 | 91 | # Apply selection: 92 | self.apply_selection(ranks_and_members_by_performance) 93 | 94 | # ======================= LOGGING ===================================== 95 | if self.verbose == 2: 96 | self.logger.debug(f"\nPopulation Members (After Selection):") 97 | self.logger.debug(f"| index | seed | x0 | x1 |") 98 | for index in range(len(self.members)): 99 | seed = self.members[index].genotype 100 | x0 = self.members[index].phenotype[0].round(10) 101 | x1 = self.members[index].phenotype[1].round(10) 102 | self.logger.debug(f"| {index} | {seed} | {x0} | {x1} |") 103 | # ===================== END LOGGING =================================== 104 | 105 | # Apply mutations: 106 | self.apply_mutation(ranks_and_members_by_performance) 107 | 108 | # ======================= LOGGING ===================================== 109 | if self.verbose == 2: 110 | self.logger.debug(f"\nPopulation Members (After Mutation):") 111 | self.logger.debug(f"| index | seed | x0 | x1 |") 112 | for index in range(len(self.members)): 113 | seed = self.members[index].genotype 114 | x0 = self.members[index].phenotype[0].round(10) 115 | x1 = self.members[index].phenotype[1].round(10) 116 | self.logger.debug(f"| {index} | {seed} | {x0} | {x1} |") 117 | # ===================== END LOGGING =================================== 118 | 119 | # Next generation: 120 | self.generation += 1 121 | 122 | def mpi_save(self, s): 123 | 124 | self.mpidata_genotypes.write(self.genotypes) 125 | self.mpidata_costs.write(self.costs) 126 | if s == 0: 127 | self.mpidata_initialguess.write(self.initial_guess) 128 | 129 | @ property 130 | def genotypes(self): 131 | genotypes = [] 132 | for member in self.members: 133 | genotypes.append(member.genotype) 134 | return np.array(genotypes) 135 | 136 | @ property 137 | def costs(self): 138 | return self.cost_list 139 | -------------------------------------------------------------------------------- /DNE4py/version_v2/new_optimizers/deepga2/deepga.py: -------------------------------------------------------------------------------- 1 | 2 | from .base import BaseGA 3 | from .mutation import RealMutator 4 | from .selection import TruncatedSelection 5 | from .ranking import CompactRanking, CompositeRanking 6 | 7 | 8 | class TruncatedRealMutatorCompactGA(TruncatedSelection, RealMutator, CompactRanking, BaseGA): 9 | pass 10 | 11 | class TruncatedRealMutatorCompositeGA(TruncatedSelection, RealMutator, CompositeRanking, BaseGA): 12 | pass 13 | -------------------------------------------------------------------------------- /DNE4py/version_v2/new_optimizers/deepga2/member.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | 4 | class Member: 5 | r''' 6 | Initialization: 7 | initial_phenotype: initial list of parameters 8 | initial_gene: initial seed 9 | sigma: parameter to apply on mutations 10 | 11 | Internal attributes: 12 | genotype: list of seeds 13 | phenotype: list of parameters 14 | 15 | Methods: 16 | recreate(new_genotype): 17 | update genotype and phenotype from new_genotype 18 | mutate(rng_genes): 19 | create a new gene and update genotype and phenotype 20 | ''' 21 | 22 | def __init__(self, 23 | initial_phenotype, 24 | initial_genotype, 25 | sigma): 26 | 27 | # Define initial phenotype: 28 | self.initial_phenotype = initial_phenotype 29 | self.phenotype = self.initial_phenotype.copy() 30 | 31 | #self.initial_genotype = initial_genotype.copy() 32 | 33 | # Internal attributes: 34 | self.rng = np.random.RandomState() 35 | self.size, self.sigma = len(self.phenotype), sigma 36 | 37 | # Define genotype and phenotype: 38 | self.recreate(initial_genotype) 39 | 40 | def mutate(self, rng_genes): 41 | r'''create a new gene and update genotype and phenotype''' 42 | 43 | # Increase genotype: 44 | seed = rng_genes.randint(0, 2 ** 32 - 1) 45 | self.genotype.append(seed) 46 | 47 | # Mutate phenotype: 48 | self.rng.seed(seed) 49 | self.phenotype += self.rng.randn(self.size) * self.sigma 50 | 51 | def recreate(self, new_genotype): 52 | r'''update genotype and phenotype from new_genotype''' 53 | 54 | # Set genotype: 55 | self.genotype = new_genotype[:] 56 | 57 | # Set phenotype: 58 | self.phenotype[:] = self.initial_phenotype[:] 59 | 60 | for seed in self.genotype: 61 | self.rng.seed(seed) 62 | self.phenotype += self.rng.randn(self.size) * self.sigma 63 | -------------------------------------------------------------------------------- /DNE4py/version_v2/new_optimizers/deepga2/mutation.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | import numpy as np 4 | 5 | from .base import BaseGA 6 | from .member import Member 7 | 8 | class RealMutator(BaseGA): 9 | 10 | def mutator_initialize(self): 11 | 12 | # Global Random Generator: 13 | self.rgn_global = random.Random(self.global_seed) 14 | 15 | # Global seedmatrix: 16 | self.seedmatrix = np.zeros((self._size, self.workers_per_rank), dtype=np.int64) 17 | for i in range(self._size): 18 | row = self.rgn_global.sample(range(2**32 - 1), self.workers_per_rank) 19 | self.seedmatrix[i] = row 20 | 21 | # Generate Genes Random Generator: 22 | self.rng_genes_list = [np.random.RandomState(self.seedmatrix[self._rank, i]) for i in range(self.workers_per_rank)] 23 | 24 | # Generate Initial genes 25 | self.initial_genotypes = [] 26 | for i in range(self.workers_per_rank): 27 | initial_genotype = self.rng_genes_list[i].randint(2**32 - 1) 28 | self.initial_genotypes.append([initial_genotype]) 29 | 30 | self.members = [Member(initial_phenotype=self.initial_guess, 31 | initial_genotype=self.initial_genotypes[i], 32 | sigma=self.sigma) 33 | for i in range(self.workers_per_rank)] 34 | 35 | def apply_mutation(self, ranks_and_members_by_performance): 36 | """ 37 | Preserve the top num_elite members, mutate the rest 38 | """ 39 | no_elite_mask = ranks_and_members_by_performance >= self.num_elite 40 | 41 | row, column = np.where(no_elite_mask) 42 | no_elite_tuples = tuple(zip(row, column)) 43 | 44 | # ======================= LOGGING ===================================== 45 | if self.verbose == 2: 46 | self.logger.debug(f"\nSelected Elite:") 47 | self.logger.debug(f"| rank | member_id |") 48 | elite_mask = np.invert(no_elite_mask) 49 | row, column = np.where(elite_mask) 50 | elite_indexes = tuple(zip(row, column)) 51 | for rank, member_id in elite_indexes: 52 | self.logger.debug(f"| {rank} | {member_id} |") 53 | # ===================== END LOGGING =================================== 54 | 55 | for rank, member_id in no_elite_tuples: 56 | if rank == self._rank: 57 | rng_genes = self.rng_genes_list[member_id] 58 | self.members[member_id].mutate(rng_genes) 59 | -------------------------------------------------------------------------------- /DNE4py/version_v2/new_optimizers/deepga2/ranking.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | from .base import BaseGA 4 | from DNE4py.utils import MPIData 5 | # class Ranking(BaseGA): 6 | # def ranking_initialize(self): 7 | # self.n_tasks = len(self.objective_function(self.members[0].phenotype)) 8 | 9 | # def apply_ranking(self): 10 | 11 | # # Evaluate member: 12 | # self.cost_list = np.zeros((self.workers_per_rank, self.n_tasks)) # (W,T) vs (W) 13 | # for i in range(len(self.cost_list)): 14 | # self.cost_list[i] = self.objective_function(self.members[i].phenotype) 15 | 16 | 17 | # # ======================= LOGGING ===================================== 18 | # if self.verbose == 2: 19 | # self.logger.debug(f"\nPopulation Members (Initial):") 20 | # self.logger.debug(f"| index | seed | x0 | x1 | y |") 21 | # for index in range(len(self.members)): 22 | # seed = self.members[index].genotype 23 | # x0 = self.members[index].phenotype[0].round(10) 24 | # x1 = self.members[index].phenotype[1].round(10) 25 | # y = self.cost_list[index].round(10) 26 | # self.logger.debug(f"| {index} | {seed} | {x0} | {x1} | {y} |") 27 | # # ===================== END LOGGING =================================== 28 | # # Save: 29 | # if (self.save > 0) and (self.generation % self.save == 0): 30 | # self.mpi_save(self.generation) 31 | 32 | # # Broadcast fitness: 33 | # cost_matrix = np.empty((self._size, self.workers_per_rank)) # (S,W,T) vs (S,W) 34 | # self._comm.Allgather([self.cost_list, self._MPI.FLOAT], 35 | # [cost_matrix, self._MPI.FLOAT]) 36 | 37 | # order = self.ordering(cost_matrix) # (S*W,T) vs (S*W) 38 | # rank = np.argsort(order) 39 | # ranks_and_members_by_performance = rank.reshape(self._size, self.workers_per_rank) #--# 40 | 41 | # return ranks_and_members_by_performance 42 | 43 | 44 | # def ordering(cost_matrix): 45 | # pass 46 | 47 | 48 | 49 | class CompactRanking(BaseGA): 50 | def apply_ranking(self): 51 | 52 | # Evaluate member: 53 | self.cost_list = np.zeros(self.workers_per_rank) 54 | for i in range(len(self.cost_list)): 55 | self.cost_list[i] = self.objective_function(self.members[i].phenotype) 56 | 57 | 58 | # ======================= LOGGING ===================================== 59 | if self.verbose == 2: 60 | self.logger.debug(f"\nPopulation Members (Initial):") 61 | self.logger.debug(f"| index | seed | x0 | x1 | y |") 62 | for index in range(len(self.members)): 63 | seed = self.members[index].genotype 64 | x0 = self.members[index].phenotype[0].round(10) 65 | x1 = self.members[index].phenotype[1].round(10) 66 | y = self.cost_list[index].round(10) 67 | self.logger.debug(f"| {index} | {seed} | {x0} | {x1} | {y} |") 68 | # ===================== END LOGGING =================================== 69 | # Save: 70 | if (self.save > 0) and (self.generation % self.save == 0): 71 | self.mpi_save(self.generation) 72 | 73 | # Broadcast fitness: 74 | cost_matrix = np.empty((self._size, self.workers_per_rank)) 75 | self._comm.Allgather([self.cost_list, self._MPI.FLOAT], 76 | [cost_matrix, self._MPI.FLOAT]) 77 | 78 | # Truncate Selection (broadcast genotypes and update members): 79 | order = np.argsort(cost_matrix.flatten()) 80 | rank = np.argsort(order) 81 | ranks_and_members_by_performance = rank.reshape(cost_matrix.shape) 82 | return ranks_and_members_by_performance 83 | 84 | 85 | class CompositeRanking(BaseGA): 86 | 87 | def apply_ranking(self): 88 | 89 | # Evaluate member: 90 | self.cost_list = [] #--# 91 | for i in range(self.workers_per_rank): 92 | self.cost_list.append(self.objective_function(self.members[i].phenotype)) 93 | self.cost_list = np.array(self.cost_list) 94 | self.n_tasks = self.cost_list.shape[1] 95 | 96 | # ======================= LOGGING ===================================== 97 | if self.verbose == 2: 98 | self.logger.debug(f"\nPopulation Members (Initial):") 99 | self.logger.debug(f"| index | seed | x0 | x1 | y |") 100 | for index in range(len(self.members)): 101 | seed = self.members[index].genotype 102 | x0 = self.members[index].phenotype[0].round(10) 103 | x1 = self.members[index].phenotype[1].round(10) 104 | y = self.cost_list[index].round(10) 105 | self.logger.debug(f"| {index} | {seed} | {x0} | {x1} | {y} |") 106 | # ===================== END LOGGING =================================== 107 | 108 | 109 | if (self.save > 0) and (self.generation % self.save == 0): 110 | self.mpi_save(self.generation) 111 | # Broadcast fitness: 112 | cost_matrix = np.empty((self._size, self.workers_per_rank, self.n_tasks)) #--# 113 | self._comm.Allgather([self.cost_list, self._MPI.FLOAT], 114 | [cost_matrix, self._MPI.FLOAT]) 115 | 116 | # Compute "on instances" average rankings 117 | average_ranking = self.ranking(cost_matrix) 118 | 119 | # Save: 120 | 121 | if (self.save > 0) and (self.generation % self.save == 0): 122 | # add the specific ranking data 123 | self.mpidata_rankings.write(average_ranking) 124 | 125 | # Truncate Selection (broadcast genotypes and update members): 126 | order = np.argsort(average_ranking) #--# 127 | rank = np.argsort(order) 128 | ranks_and_members_by_performance = rank.reshape(self._size, self.workers_per_rank) #--# 129 | return ranks_and_members_by_performance 130 | 131 | 132 | 133 | def ranking(self, cost_matrix): 134 | """ 135 | @TODO : gèrer les ex-aequo 136 | """ 137 | data = cost_matrix.reshape(self._size * self.workers_per_rank, self.n_tasks) 138 | 139 | for inst in range(data.shape[1]): 140 | data[:,inst] = rankdata(data[:,inst]) 141 | return np.mean(data, axis=1) 142 | 143 | 144 | # Move somewhere else 145 | # https://github.com/numbbo/coco/blob/master/code-postprocessing/cocopp/toolsstats.py 146 | def rankdata(a): 147 | """Ranks the data in a, dealing with ties appropriately. 148 | Equal values are assigned a rank that is the average of the ranks that 149 | would have been otherwise assigned to all of the values within that set. 150 | Ranks begin at 1, not 0. 151 | Example: 152 | In [15]: stats.rankdata([0, 2, 2, 3]) 153 | Out[15]: array([ 1. , 2.5, 2.5, 4. ]) 154 | Parameters: 155 | - *a* : array 156 | This array is first flattened. 157 | Returns: 158 | An array of length equal to the size of a, containing rank scores. 159 | """ 160 | a = np.ravel(a) 161 | n = len(a) 162 | svec, ivec = fastsort(a) 163 | sumranks = 0 164 | dupcount = 0 165 | newarray = np.zeros(n, float) 166 | for i in range(n): 167 | sumranks += i 168 | dupcount += 1 169 | if i == n - 1 or svec[i] != svec[i + 1]: 170 | averank = sumranks / float(dupcount) + 1 171 | for j in range(i - dupcount + 1, i + 1): 172 | newarray[ivec[j]] = averank 173 | sumranks = 0 174 | dupcount = 0 175 | return newarray 176 | # Dimensions 177 | # Calcul des ranks (non trivial dans le cas composite) 178 | 179 | def fastsort(a): 180 | it = np.argsort(a) 181 | as_ = a[it] 182 | return as_, it -------------------------------------------------------------------------------- /DNE4py/version_v2/new_optimizers/deepga2/selection.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | from .base import BaseGA 4 | 5 | class TruncatedSelection(BaseGA): 6 | 7 | def selection_initialize(self): 8 | 9 | # Init: 10 | self.rgn_selection = np.random.RandomState(self.global_seed) 11 | 12 | if self.num_elite > self.num_parents: 13 | raise AssertionError("Number of elite has to be less than the" 14 | " number of parents") 15 | 16 | def apply_selection(self, ranks_and_members_by_performance): 17 | 18 | # 1 - Define parents and no parents: 19 | parents_mask = ranks_and_members_by_performance < self.num_parents 20 | no_parents_mask = np.invert(parents_mask) 21 | 22 | row, column = np.where(parents_mask) 23 | parents_indexes = tuple(zip(row, column)) 24 | parent_options = range(len(parents_indexes)) 25 | 26 | row, column = np.where(no_parents_mask) 27 | no_parents_indexes = tuple(zip(row, column)) 28 | 29 | # ======================= LOGGING ===================================== 30 | if self.verbose == 2: 31 | self.logger.debug(f"\nSelected Parents:") 32 | self.logger.debug(f"| rank | member_id |") 33 | for rank, member_id in parents_indexes: 34 | self.logger.debug(f"| {rank} | {member_id} |") 35 | # ===================== END LOGGING =================================== 36 | 37 | # 2 - Update member for each rank: 38 | # Build message_list: 39 | messenger_list = [] 40 | for dest_rank, dest_member_id in no_parents_indexes: 41 | choice = self.rgn_selection.choice(parent_options) 42 | src_rank, src_member_id = parents_indexes[choice] 43 | messenger_list.append((src_rank, 44 | src_member_id, 45 | dest_rank, 46 | dest_member_id)) 47 | 48 | # ======================= LOGGING ===================================== 49 | if self.verbose == 2: 50 | self.logger.debug(f"\nSelection Messenger List") 51 | self.logger.debug(f"| src_rank | src_member_id | dest_rank | dest_member_id |") 52 | for (src_rank, 53 | src_member_id, 54 | dest_rank, 55 | dest_member_id) in messenger_list: 56 | self.logger.debug(f"| {src_rank} | {src_member_id} | {dest_rank} | {dest_member_id} |") 57 | # ===================== END LOGGING =================================== 58 | 59 | # Dispatch message_list: 60 | for (src_rank, 61 | src_member_id, 62 | dest_rank, 63 | dest_member_id) in messenger_list: 64 | if src_rank != dest_rank: # Need send to MPI 65 | if src_rank == self._rank: 66 | message = (self.members[src_member_id].genotype, 67 | dest_member_id) 68 | self._comm.send(message, dest=dest_rank) 69 | elif dest_rank == self._rank: 70 | new_genotype, member_id = self._comm.recv(source=src_rank) 71 | self.members[member_id].recreate(new_genotype) 72 | else: 73 | if (self._rank == src_rank): 74 | new_genotype = self.members[src_member_id].genotype 75 | member_id = dest_member_id 76 | self.members[member_id].recreate(new_genotype) 77 | -------------------------------------------------------------------------------- /DNE4py/version_v2/new_optimizers/random/__init__.py: -------------------------------------------------------------------------------- 1 | from .batch import BatchRandomSearch 2 | -------------------------------------------------------------------------------- /DNE4py/version_v2/new_optimizers/random/batch.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | #import pickle 3 | #import random 4 | 5 | #from abc import ABC, abstractmethod 6 | 7 | from ..optimizer import Optimizer 8 | from DNE4py.utils.mpi_extensions import MPISaver, MPILogger 9 | 10 | class BatchRandomSearch(Optimizer): 11 | 12 | def __init__(self, objective_function, config): 13 | 14 | super().__init__(objective_function, config) 15 | 16 | # self.objective_function 17 | # self.dim 18 | # self.workers_per_rank 19 | # self.bounds 20 | # self.global_seed 21 | # self.save 22 | # self.verbose 23 | # self.output_folder 24 | 25 | # Initiate MPI 26 | from mpi4py import MPI 27 | self._MPI = MPI 28 | self._comm = MPI.COMM_WORLD 29 | self._size = self._comm.Get_size() 30 | self._rank = self._comm.Get_rank() 31 | 32 | # Input: 33 | #self.objective_function = kwargs.get('objective_function') 34 | #self.initial_guess = kwargs.get('initial_guess') 35 | #self.bounds = kwargs.get('bounds') 36 | #self.global_seed = kwargs.get('seed') 37 | 38 | #self.save = kwargs.get('save', 0) 39 | #self.verbose = kwargs.get('verbose', 0) 40 | #self.output_folder = kwargs.get('output_folder', 'DNE4py_result') 41 | 42 | #self.workers_per_rank = kwargs.get('workers_per_rank') 43 | 44 | # Internal: 45 | self.population_size = self._size * self.workers_per_rank 46 | self.generator = np.random.RandomState(self.global_seed) 47 | self.my_ids = np.array_split(range(self.population_size), self._size)[self._rank] 48 | self.generation = 0 49 | 50 | # Logger and DataCollector for MPI: 51 | if (self.verbose == 2) or (self.save > 0): 52 | 53 | if self.verbose == 2: 54 | self.logger = MPILogger(self.output_folder, 'debug_logger', self._rank) 55 | if self.save > 0: 56 | self.mpidata_genotypes = MPIData(self.output_folder, 57 | 'genotypes', 58 | self._rank) 59 | self.mpidata_costs = MPIData(self.output_folder, 60 | 'costs', 61 | self._rank) 62 | 63 | def run(self, steps): 64 | 65 | for _ in range(steps): 66 | 67 | # =================== LOGGING ===================================== 68 | if self.verbose > 0 and self._rank == 0: 69 | print(f"Generation: {self.generation}/{steps}") 70 | elif self.verbose == 2: 71 | self.logger.debug(f"\nGeneration: {self.generation}/{steps}") 72 | # =================== LOGGING ===================================== 73 | 74 | self.step() 75 | 76 | def step(self): 77 | 78 | # Get solutions: 79 | self.solutions = self.generator.uniform(self.bounds[0], self.bounds[1], (self.population_size, self.dim)) 80 | 81 | # Evaluate only your own solutions: 82 | self.my_solutions = self.solutions[self.my_ids] 83 | self.cost_list = np.zeros(self.workers_per_rank) 84 | for i in range(len(self.cost_list)): 85 | self.cost_list[i] = self.objective_function(self.my_solutions[i]) 86 | 87 | # Save: 88 | if (self.save > 0) and (self.generation % self.save == 0): 89 | self.mpi_save(self.generation) 90 | 91 | # ======================= LOGGING ===================================== 92 | if self.verbose == 2: 93 | self.logger.debug(f"\n| index | x0 | x1 | y |") 94 | for index, sol in enumerate(self.solutions): 95 | 96 | x0 = sol[0].round(10) 97 | x1 = sol[1].round(10) 98 | y = self.all_costs[index].round(10) 99 | if index in self.my_ids: 100 | self.logger.debug(f"| {index} | {x0} | {x1} | {y} | X |") 101 | else: 102 | self.logger.debug(f"| {index} | {x0} | {x1} | {y} |") 103 | # ===================== END LOGGING =================================== 104 | 105 | # Next generation: 106 | self.generation += 1 107 | 108 | def mpi_save(self, s): 109 | 110 | self.mpidata_genotypes.write(self.my_solutions) 111 | self.mpidata_costs.write(self.cost_list) 112 | -------------------------------------------------------------------------------- /DNE4py/version_v2/new_tutorials/tutorials2/README.md: -------------------------------------------------------------------------------- 1 | ## `run.py` 2 | * It changes results folder 3 | ```console 4 | foo@bar:~$ mpiexec -n 2 python3 run.py 3 5 | ``` 6 | 7 | ## `pp_run.py` 8 | * It changes pp_results folder 9 | * To Optimize: (Use Optimize Transparency 10%) https://ezgif.com/optimize/ 10 | 11 | ```console 12 | foo@bar:~$ python3 pp_run.py 3 13 | foo@bar:~$ cd pp_results/RandomSearch/ 14 | foo@bar:~$ convert -layers OptimizeTransparency -delay 20 -loop 0 `ls -v` randomsearch.gif 15 | ``` 16 | 17 | ## `render.py` 18 | * It defines the behaviour to render the optimization procedure 19 | 20 | -------------------------------------------------------------------------------- /DNE4py/version_v2/new_tutorials/tutorials2/pp_run.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import numpy as np 3 | 4 | from render import deepga_render, composite_deepga_render, cmaes_render, randomsearch_render 5 | 6 | 7 | def objective(x): 8 | result = np.sum(x**2) 9 | return result 10 | 11 | def render_Compact_DeepGA(): 12 | sigma = 0.05 13 | num_parents = 3 14 | num_elite = 1 15 | deepga_render("results/DeepGA/TruncatedRealMutatorCompactGA", 20, objective, sigma, num_parents, num_elite) 16 | 17 | def render_Composite_DeepGA(): 18 | 19 | n_tasks = 4 20 | sigma = 0.05 21 | num_parents = 3 22 | num_elite = 1 23 | composite_deepga_render("results/DeepGA/TruncatedRealMutatorCompositeGA", 20, objective, sigma, num_parents, num_elite) 24 | 25 | def render_CMAES(): 26 | sigma = 0.05 27 | cmaes_render("results/CMAES", 20, objective, sigma) 28 | 29 | def render_RandomSearch(): 30 | randomsearch_render("results/RandomSearch", 20, objective) 31 | 32 | # Composite example task 33 | # def multi_objective(x, n_tasks = 4): 34 | # """ 35 | # The composite objective is composed of n_tasks functions of the form f:(x,y) -> (x^2 + y^2) * i 36 | # The sum of the component individual objectives is used to evaluate the optimizer 37 | # (we expect it to optimize the average) 38 | # """ 39 | # result = np.array([np.sum(x**2 + i*x ) * i for i in range(n_tasks)]) 40 | # return sum(result) 41 | 42 | 43 | if "__main__" == __name__: 44 | 45 | # Options: 46 | switcher = { 47 | 0: render_Compact_DeepGA, 48 | 1: render_Composite_DeepGA, 49 | 2: render_CMAES, 50 | 3: render_RandomSearch, 51 | } 52 | renderize = switcher.get(int(sys.argv[1]), lambda: "Invalid index for optimizer") 53 | renderize() 54 | -------------------------------------------------------------------------------- /DNE4py/version_v2/new_tutorials/tutorials2/render.py: -------------------------------------------------------------------------------- 1 | # After running these methods, you can generate a compressed .gif in the following command: 2 | # $: convert -layers OptimizeTransparency -delay 20 -loop 0 `ls -v` myimage.gif 3 | # To Optimizer: (Use Optimize Transparency 10%) https://ezgif.com/optimize/ 4 | 5 | 6 | import pickle 7 | 8 | from scipy.stats import multivariate_normal, find_repeats 9 | import numpy as np 10 | 11 | from DNE4py.postprocessing.utils import load_mpidata 12 | from DNE4py.optimizers.cmaes import CMAES 13 | 14 | 15 | def randomsearch_render(folder_path, nb_generations, objective): 16 | 17 | import numpy as np 18 | import matplotlib.pyplot as plt 19 | 20 | def start_image(): 21 | fig, ax = plt.subplots() 22 | ax.set_xlim([-1, 1]) 23 | ax.set_ylim([-1, 1]) 24 | ax.set_xticks(np.arange(-1, 1, 0.2)) 25 | ax.set_yticks(np.arange(-1, 1, 0.2)) 26 | return fig, ax 27 | 28 | # Read Input: 29 | costs = load_mpidata(f"{folder_path}", "costs", nb_generations) 30 | genotypes = load_mpidata(f"{folder_path}", "genotypes", nb_generations) 31 | initial_guess = load_mpidata(f"{folder_path}", "initial_guess", 1)[0] 32 | 33 | # Start figure: 34 | fig, ax = start_image() 35 | 36 | # Plot function: 37 | resolution = 100 38 | x1, x2 = np.meshgrid(np.linspace(-1, 1, resolution), np.linspace(-1, 1, resolution)) 39 | X = np.array([x1.flatten(), x2.flatten()]).T 40 | Y = np.array([objective(x) for x in X]).reshape(resolution, resolution) 41 | ax.pcolormesh(x1, x2, Y, cmap=plt.cm.coolwarm) 42 | 43 | for g in range(nb_generations - 1): 44 | 45 | # Image 1: 46 | 47 | # Plot function: 48 | fig, ax = start_image() 49 | ax.pcolormesh(x1, x2, Y, cmap=plt.cm.coolwarm) 50 | 51 | # Plot points: 52 | ax.scatter(genotypes[g][:, 0], genotypes[g][:, 1], s=10, c='black') 53 | plt.savefig(f"pp_{folder_path}/{g+1}_1.jpeg") 54 | 55 | def cmaes_render(folder_path, nb_generations, objective, sigma): 56 | 57 | import numpy as np 58 | import matplotlib.pyplot as plt 59 | 60 | def start_image(): 61 | fig, ax = plt.subplots() 62 | ax.set_xlim([-1, 1]) 63 | ax.set_ylim([-1, 1]) 64 | ax.set_xticks(np.arange(-1, 1, 0.2)) 65 | ax.set_yticks(np.arange(-1, 1, 0.2)) 66 | return fig, ax 67 | 68 | # Read Input: 69 | costs = load_mpidata(f"{folder_path}", "costs", nb_generations) 70 | genotypes = load_mpidata(f"{folder_path}", "genotypes", nb_generations) 71 | initial_guess = load_mpidata(f"{folder_path}", "initial_guess", 1)[0] 72 | 73 | # Start figure: 74 | fig, ax = start_image() 75 | 76 | # Plot function: 77 | resolution = 100 78 | x1, x2 = np.meshgrid(np.linspace(-1, 1, resolution), np.linspace(-1, 1, resolution)) 79 | X = np.array([x1.flatten(), x2.flatten()]).T 80 | Y = np.array([objective(x) for x in X]).reshape(resolution, resolution) 81 | ax.pcolormesh(x1, x2, Y, cmap=plt.cm.coolwarm) 82 | 83 | # Show Initial Guess 84 | ax.scatter(initial_guess[0], initial_guess[1], c='black', s=20) 85 | plt.savefig(f"pp_{folder_path}/0.jpeg") 86 | 87 | cmaes = CMAES(objective=objective, 88 | initial_guess=initial_guess, 89 | workers_per_rank=10, 90 | sigma=sigma, 91 | seed=100, 92 | save=0, 93 | verbose=0, 94 | output_folder='DNE4py_result') 95 | optimizer = cmaes.optimizer 96 | 97 | # Loop: 98 | contour_x0, contour_x1 = np.mgrid[-1:1:.01, -1:1:.01] 99 | pos = np.dstack((contour_x0, contour_x1)) 100 | for g in range(nb_generations - 1): 101 | 102 | # Image 1: 103 | 104 | # Plot function: 105 | fig, ax = start_image() 106 | ax.pcolormesh(x1, x2, Y, cmap=plt.cm.coolwarm) 107 | 108 | # Plot current distribution (black): 109 | mu_x0, mu_x1 = optimizer.mean 110 | variance = optimizer.sigma 111 | rv = multivariate_normal([mu_x0, mu_x1], [[variance, 0], [0, variance]]) 112 | ax.contour(contour_x0, contour_x1, rv.pdf(pos), colors='black', alpha=0.3) 113 | # plt.savefig(f"{folder_path}/pp/{g+1}_1.jpeg") 114 | 115 | # Plot current points (black): 116 | ax.scatter(genotypes[g][:, 0], genotypes[g][:, 1], s=10, c='black') 117 | plt.savefig(f"pp_{folder_path}/{g+1}_1.jpeg") 118 | 119 | # Update CMAES 120 | solutions = np.array(optimizer.ask()) 121 | optimizer.tell(genotypes[g], costs[g]) 122 | 123 | # Plot next distribution (red): 124 | mu_x0, mu_x1 = optimizer.mean 125 | variance = optimizer.sigma 126 | rv = multivariate_normal([mu_x0, mu_x1], [[variance, 0], [0, variance]]) 127 | ax.contour(contour_x0, contour_x1, rv.pdf(pos), colors='red', alpha=0.3) 128 | plt.savefig(f"pp_{folder_path}/{g+1}_2.jpeg") 129 | 130 | # Plot current points (red): 131 | ax.scatter(genotypes[g + 1][:, 0], genotypes[g + 1][:, 1], s=10, c='red') 132 | plt.savefig(f"pp_{folder_path}/{g+1}_3.jpeg") 133 | 134 | def deepga_render(folder_path, nb_generations, objective, sigma, num_parents, num_elite): 135 | 136 | import numpy as np 137 | import matplotlib.pyplot as plt 138 | 139 | from DNE4py.optimizers.deepga.mutation import Member 140 | 141 | def start_image(): 142 | fig, ax = plt.subplots() 143 | ax.set_xlim([-1, 1]) 144 | ax.set_ylim([-1, 1]) 145 | ax.set_xticks(np.arange(-1, 1, 0.2)) 146 | ax.set_yticks(np.arange(-1, 1, 0.2)) 147 | return fig, ax 148 | 149 | # Read Input: 150 | raw_folder_path = f"{folder_path}/raw_data" 151 | costs = load_mpidata(f"{raw_folder_path}", "costs", nb_generations) 152 | genotypes = load_mpidata(f"{raw_folder_path}", "genotypes", nb_generations) 153 | initial_guess = load_mpidata(f"{raw_folder_path}", "initial_guess", 1)[0] 154 | print(' costs toto ', folder_path) 155 | # Start figure: 156 | fig, ax = start_image() 157 | 158 | # Plot function: 159 | resolution = 100 160 | x1, x2 = np.meshgrid(np.linspace(-1, 1, resolution), np.linspace(-1, 1, resolution)) 161 | X = np.array([x1.flatten(), x2.flatten()]).T 162 | Y = np.array([objective(x) for x in X]).reshape(resolution, resolution) 163 | ax.pcolormesh(x1, x2, Y, cmap=plt.cm.coolwarm) 164 | 165 | # Show Initial Guess 166 | ax.scatter(initial_guess[0], initial_guess[1], c='black', s=20) 167 | plt.savefig(f"pp_{folder_path}/0.jpeg") 168 | 169 | # Loop: 170 | for g in range(nb_generations - 1): 171 | 172 | # Plot function: 173 | fig, ax = start_image() 174 | ax.pcolormesh(x1, x2, Y, cmap=plt.cm.coolwarm) 175 | 176 | # Image 1: 177 | phenotypes = [] 178 | for genotype in genotypes[g]: 179 | phenotype = Member(initial_guess, genotype, sigma).phenotype 180 | phenotypes.append(phenotype) 181 | phenotypes = np.array(phenotypes) 182 | 183 | ax.scatter(phenotypes[:, 0], phenotypes[:, 1], c='black', s=10) 184 | plt.savefig(f"pp_{folder_path}/{g+1}_1.jpeg") 185 | 186 | # Image 2: 187 | order = np.argsort(costs[g]) 188 | rank = np.argsort(order) 189 | parents_mask = rank < num_parents 190 | elite_mask = rank < num_elite 191 | 192 | parents_phenotypes = phenotypes[parents_mask] 193 | elite_phenotypes = phenotypes[elite_mask] 194 | ax.scatter(parents_phenotypes[:, 0], parents_phenotypes[:, 1], c='green', s=10) 195 | ax.scatter(elite_phenotypes[:, 0], elite_phenotypes[:, 1], c='blue', s=10) 196 | plt.savefig(f"pp_{folder_path}/{g+1}_2.jpeg") 197 | 198 | # Image 3 199 | phenotypes = [] 200 | for genotype in genotypes[g + 1]: 201 | phenotype = Member(initial_guess, genotype, sigma).phenotype 202 | phenotypes.append(phenotype) 203 | phenotypes = np.array(phenotypes) 204 | ax.scatter(phenotypes[:, 0], phenotypes[:, 1], c='red', s=10) 205 | plt.savefig(f"pp_{folder_path}/{g+1}_3.jpeg") 206 | 207 | def composite_deepga_render(folder_path, nb_generations, objective, sigma, num_parents, num_elite): 208 | 209 | import numpy as np 210 | import matplotlib.pyplot as plt 211 | 212 | from DNE4py.optimizers.deepga.mutation import Member 213 | 214 | def ranking(data): 215 | """ 216 | @TODO : gèrer les ex-aequo 217 | """ 218 | for inst in range(data.shape[1]): 219 | data[:,inst] = rankdata(data[:,inst]) 220 | return np.mean(data, axis=1) 221 | 222 | def start_image(): 223 | fig, ax = plt.subplots() 224 | ax.set_xlim([-1, 1]) 225 | ax.set_ylim([-1, 1]) 226 | ax.set_xticks(np.arange(-1, 1, 0.2)) 227 | ax.set_yticks(np.arange(-1, 1, 0.2)) 228 | return fig, ax 229 | 230 | # Read Input: 231 | raw_folder_path = f"{folder_path}/raw_data" 232 | costs = load_mpidata(f"{raw_folder_path}", "costs", nb_generations) 233 | genotypes = load_mpidata(f"{raw_folder_path}", "genotypes", nb_generations) 234 | initial_guess = load_mpidata(f"{raw_folder_path}", "initial_guess", 1)[0] 235 | # Start figure: 236 | fig, ax = start_image() 237 | 238 | # Plot function: 239 | resolution = 100 240 | x1, x2 = np.meshgrid(np.linspace(-1, 1, resolution), np.linspace(-1, 1, resolution)) 241 | X = np.array([x1.flatten(), x2.flatten()]).T 242 | Y = np.array([objective(x) for x in X]).reshape(resolution, resolution) 243 | ax.pcolormesh(x1, x2, Y, cmap=plt.cm.coolwarm) 244 | 245 | # Show Initial Guess 246 | ax.scatter(initial_guess[0], initial_guess[1], c='black', s=20) 247 | plt.savefig(f"pp_{folder_path}/0.jpeg") 248 | 249 | # Loop: 250 | for g in range(nb_generations - 1): 251 | 252 | # Plot function: 253 | fig, ax = start_image() 254 | ax.pcolormesh(x1, x2, Y, cmap=plt.cm.coolwarm) 255 | 256 | # Image 1: 257 | phenotypes = [] 258 | for genotype in genotypes[g]: 259 | phenotype = Member(initial_guess, genotype, sigma).phenotype 260 | phenotypes.append(phenotype) 261 | 262 | phenotypes = np.array(phenotypes) 263 | ax.scatter(phenotypes[:, 0], phenotypes[:, 1], c='black', s=10) 264 | plt.savefig(f"pp_{folder_path}/{g+1}_1.jpeg") 265 | 266 | # Image 2: 267 | average_ranking = ranking(costs[g]) 268 | order = np.argsort(average_ranking) 269 | rank = np.argsort(order) 270 | parents_mask = rank < num_parents 271 | elite_mask = rank < num_elite 272 | 273 | parents_phenotypes = phenotypes[parents_mask] 274 | elite_phenotypes = phenotypes[elite_mask] 275 | ax.scatter(parents_phenotypes[:, 0], parents_phenotypes[:, 1], c='green', s=10) 276 | ax.scatter(elite_phenotypes[:, 0], elite_phenotypes[:, 1], c='blue', s=10) 277 | plt.savefig(f"pp_{folder_path}/{g+1}_2.jpeg") 278 | 279 | # Image 3 280 | phenotypes = [] 281 | for genotype in genotypes[g + 1]: 282 | phenotype = Member(initial_guess, genotype, sigma).phenotype 283 | phenotypes.append(phenotype) 284 | phenotypes = np.array(phenotypes) 285 | ax.scatter(phenotypes[:, 0], phenotypes[:, 1], c='red', s=10) 286 | plt.savefig(f"pp_{folder_path}/{g+1}_3.jpeg") 287 | 288 | # Move somewhere else 289 | def rankdata(a): 290 | """Ranks the data in a, dealing with ties appropriately. 291 | Equal values are assigned a rank that is the average of the ranks that 292 | would have been otherwise assigned to all of the values within that set. 293 | Ranks begin at 1, not 0. 294 | Example: 295 | In [15]: stats.rankdata([0, 2, 2, 3]) 296 | Out[15]: array([ 1. , 2.5, 2.5, 4. ]) 297 | Parameters: 298 | - *a* : array 299 | This array is first flattened. 300 | Returns: 301 | An array of length equal to the size of a, containing rank scores. 302 | """ 303 | a = np.ravel(a) 304 | n = len(a) 305 | svec, ivec = fastsort(a) 306 | sumranks = 0 307 | dupcount = 0 308 | newarray = np.zeros(n, float) 309 | for i in range(n): 310 | sumranks += i 311 | dupcount += 1 312 | if i == n - 1 or svec[i] != svec[i + 1]: 313 | averank = sumranks / float(dupcount) + 1 314 | for j in range(i - dupcount + 1, i + 1): 315 | newarray[ivec[j]] = averank 316 | sumranks = 0 317 | dupcount = 0 318 | return newarray 319 | # Dimensions 320 | # Calcul des ranks (non trivial dans le cas composite) 321 | 322 | def fastsort(a): 323 | it = np.argsort(a) 324 | as_ = a[it] 325 | return as_, it -------------------------------------------------------------------------------- /DNE4py/version_v2/new_tutorials/tutorials2/run.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import numpy as np 3 | 4 | from DNE4py.optimizers.deepga2 import TruncatedRealMutatorCompactGA, TruncatedRealMutatorCompositeGA 5 | from DNE4py.optimizers.cmaes import CMAES 6 | from DNE4py.optimizers.random import BatchRandomSearch 7 | 8 | # Compact example task 9 | def objective_function(x): 10 | result = np.sum(x**2) 11 | return result 12 | 13 | def get_deepga_TruncatedRealMutatorCompactGA(): 14 | 15 | initial_guess = np.array([-0.3, 0.7]) 16 | workers_per_rank = 10 17 | num_elite = 1 18 | num_parents = 3 19 | sigma = 0.05 20 | seed = 100 21 | 22 | optimizer = TruncatedRealMutatorCompactGA(objective_function, 23 | {'initial_guess': initial_guess, 24 | 'workers_per_rank': workers_per_rank, 25 | 'num_elite': num_elite, 26 | 'num_parents': num_parents, 27 | 'sigma': sigma, 28 | 'global_seed': seed, 29 | 'save': 1, 30 | 'verbose': 1, 31 | 'output_folder': 'results/DeepGA/TruncatedRealMutatorCompactGA'}) 32 | return optimizer 33 | 34 | def get_cmaes_CMAES(): 35 | 36 | initial_guess = np.array([-0.3, 0.7]) 37 | workers_per_rank = 10 38 | sigma = 0.05 39 | seed = 100 40 | 41 | optimizer = CMAES(objective_function, 42 | {'initial_guess': initial_guess, 43 | 'workers_per_rank': workers_per_rank, 44 | 'sigma': sigma, 45 | 'global_seed': seed, 46 | 'save': 1, 47 | 'verbose': 1, 48 | 'output_folder': 'results/CMAES'}) 49 | return optimizer 50 | 51 | def get_random_BatchRandomSearch(): 52 | 53 | dim = 2 54 | workers_per_rank = 10 55 | bounds = np.array((-1, 1)) 56 | global_seed = 100 57 | 58 | optimizer = BatchRandomSearch(objective_function, 59 | {'dim': dim, 60 | 'bounds': bounds, 61 | 'workers_per_rank': workers_per_rank, 62 | 'global_seed': global_seed, 63 | 'save': 1, 64 | 'verbose': 1, 65 | 'output_folder': 'results/BatchRandomSearch'}) 66 | return optimizer 67 | 68 | 69 | # Composite example task 70 | def composite_objective_function(x, n_tasks=50): 71 | """ 72 | The composite objective is composed of n_tasks functions of the form f_i:(x,y) -> (x^2 + y^2) + i 73 | for i in {-n_task/2, ..., n_task/2}. 74 | Thus mean(f_i) = (x^2 + y^2) 75 | """ 76 | result = np.array([np.sum(x**2) + i for i in range(-(n_tasks//2), n_tasks//2)]) 77 | return result 78 | 79 | 80 | def get_deepga_TruncatedRealMutatorCompositeGA(): 81 | 82 | initial_guess = np.array([-0.3, 0.7]) 83 | workers_per_rank = 10 84 | num_elite = 1 85 | num_parents = 3 86 | sigma = 0.05 87 | seed = 100 88 | 89 | optimizer = TruncatedRealMutatorCompositeGA(composite_objective_function, 90 | {'initial_guess': initial_guess, 91 | 'workers_per_rank': workers_per_rank, 92 | 'num_elite': num_elite, 93 | 'num_parents': num_parents, 94 | 'sigma': sigma, 95 | 'global_seed': seed, 96 | 'save': 1, 97 | 'verbose': 1, 98 | 'output_folder': 'results/DeepGA/TruncatedRealMutatorCompositeGA'}) 99 | return optimizer 100 | 101 | 102 | if "__main__" == __name__: 103 | # Options: 104 | switcher = { 105 | 0: get_deepga_TruncatedRealMutatorCompactGA, 106 | 1: get_deepga_TruncatedRealMutatorCompositeGA, 107 | 2: get_cmaes_CMAES, 108 | 3: get_random_BatchRandomSearch, 109 | } 110 | optimizer = switcher.get(int(sys.argv[1]), lambda: "Invalid index for optimizer")() 111 | optimizer.run(20) 112 | -------------------------------------------------------------------------------- /DNE4py/version_v2/postprocessing/__init__.py: -------------------------------------------------------------------------------- 1 | from .utils import load_mpidata # get_best_phenotype, get_best_phenotype_generator, print_statistics, plot_cost_over_generation, save_meta_losses 2 | -------------------------------------------------------------------------------- /DNE4py/version_v2/postprocessing/test.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | 4 | a = np.array([[12341], [5123, 123], [1234]], dtype=object) 5 | b = np.array([[5123], [1234], [1237, 4124, 1231]], dtype=object) 6 | 7 | print() 8 | print(a) 9 | print(b) 10 | print() 11 | 12 | with open('test.npy', 'ab') as f: 13 | np.save(f, a) 14 | 15 | with open('test.npy', 'rb') as f: 16 | for _ in range(1): 17 | print(np.load(f, allow_pickle=True)) 18 | print() 19 | 20 | with open('test.npy', 'ab') as f: 21 | np.save(f, b) 22 | 23 | with open('test.npy', 'rb') as f: 24 | print('!!!') 25 | for _ in range(2): 26 | print(np.load(f, allow_pickle=True)) 27 | print() 28 | -------------------------------------------------------------------------------- /DNE4py/version_v2/postprocessing/utils.py: -------------------------------------------------------------------------------- 1 | import os 2 | import glob 3 | import logging 4 | import numpy as np 5 | import json 6 | 7 | def load_mpidata(name, folder_path): 8 | 9 | # Internals: 10 | nb_files = len(glob.glob1(f'{folder_path}', f'{name}*')) 11 | with open(f'{folder_path}/info.json', 'rb') as f: 12 | info = json.load(f) 13 | nb_generations = info['nb_generations'] 14 | 15 | full_data = [[]] * nb_generations 16 | for w in range(nb_files): 17 | with open(f'{folder_path}/{name}_w{w}.npy', 'rb') as f: 18 | for g in range(nb_generations): 19 | full_data[g] = np.load(f, allow_pickle=True).tolist() 20 | 21 | return np.array(full_data, object) 22 | 23 | # def get_best_x(folder_path): 24 | 25 | # from DNE4py.optimizers.deepga.mutation import Member 26 | 27 | # # Read Input: 28 | # costs = load_mpidata("costs", f"{folder_path}") 29 | # genotypes = load_mpidata("genotypes", f"{folder_path}") 30 | # initial_guess = load_mpidata("initial_guess", f"{folder_path}")[0] 31 | 32 | # print(initial_guess) 33 | # exit() 34 | 35 | # def get_best_phenotype(folder_path, nb_generations, sigma): 36 | 37 | # from DNE4py.optimizers.deepga.mutation import Member 38 | 39 | # # Read Input: 40 | # costs = load_mpidata(f"{folder_path}", "costs", nb_generations) 41 | # genotypes = load_mpidata(f"{folder_path}", "genotypes", nb_generations) 42 | # initial_guess = load_mpidata(f"{folder_path}", "initial_guess", 1)[0] 43 | 44 | # # Select Best Idxs: 45 | # best_idxs = np.unravel_index(costs.argmin(), costs.shape) 46 | 47 | # # Create member and get phonetype: 48 | # phenotype = Member(initial_guess, genotypes[best_idxs], sigma).phenotype 49 | # return phenotype 50 | 51 | # def get_best_phenotype_generator(folder_path, nb_generations, sigma): 52 | 53 | # from DNE4py.optimizers.deepga.mutation import Member 54 | 55 | # # Read Input: 56 | # costs = load_mpidata(f"{folder_path}", "costs", nb_generations) 57 | # genotypes = load_mpidata(f"{folder_path}", "genotypes", nb_generations) 58 | # initial_guess = load_mpidata(f"{folder_path}", "initial_guess", 1)[0] 59 | 60 | # # Select Best Idxs: 61 | # min_idxs = np.argmin(costs, axis=1) 62 | # for i in range(nb_generations): 63 | # genotype = genotypes[i, min_idxs[i]] 64 | # yield Member(initial_guess, genotype, sigma).phenotype 65 | 66 | # def print_statistics(folder_path, nb_generations): 67 | 68 | # costs = load_mpidata(f"{folder_path}", "costs", nb_generations) 69 | 70 | # final_best_cost = np.min(costs[-1]) 71 | # best_cost = np.min(np.min(costs, axis=1)) 72 | 73 | # print(f"Final Best cost: {final_best_cost}") 74 | # print(f"Best cost: {best_cost}") 75 | 76 | # def plot_cost_over_generation(folder_path, nb_generations, sigma=None, test_objective=None): 77 | 78 | # import matplotlib.pyplot as plt 79 | 80 | # # Load data: 81 | # costs = load_mpidata(f"{folder_path}", "costs", nb_generations) 82 | 83 | # # Calculate data: 84 | # means = np.mean(costs, axis=1) 85 | # stds = np.std(costs, axis=1) 86 | # mins = np.min(costs, axis=1) 87 | # maxes = np.max(costs, axis=1) 88 | 89 | # # Plot Population errorbar: 90 | # plt.errorbar(np.arange(nb_generations), means, stds, fmt='ok', lw=3) 91 | # plt.errorbar(np.arange(nb_generations), means, [means - mins, maxes - means], 92 | # fmt='.k', ecolor='gray', lw=1) 93 | 94 | # # Plot Best Individuals (blue line): 95 | # plt.plot(np.arange(nb_generations), mins) 96 | 97 | # # Plot Test Performance of Best Individuals (red line): 98 | # if test_objective is not None: 99 | # best_phenotypes = get_best_phenotype_generator(folder_path, nb_generations, sigma) 100 | 101 | # test_evaluations = [] 102 | # for i, phenotype in enumerate(best_phenotypes): 103 | # if i % 4 == 0: 104 | # print(f'{i}/{nb_generations}\r', end='') 105 | # evaluation = test_objective(phenotype) 106 | # test_evaluations.append(evaluation) 107 | # test_evaluations = np.array(test_evaluations) 108 | # plt.plot(np.arange(0, nb_generations, 4), test_evaluations) 109 | 110 | # # Configuration: 111 | # plt.xlim(-1, nb_generations) 112 | # plt.xticks(np.arange(-1, nb_generations + 1, nb_generations // 10.0)) 113 | 114 | # # Save 115 | # plt.savefig(f"{folder_path}/cost_over_generation.png") 116 | 117 | 118 | # def save_meta_losses(input_path, output_path, nb_generations, test_objective=None, sigma=None): 119 | 120 | # # Graph 1 (generation x (meta_train_loss, meta_test_loss)) 121 | 122 | # # Meta-Train Loss: 123 | # # Load data: 124 | # costs = load_mpidata(f"{input_path}", "costs", nb_generations) 125 | 126 | # # Calculate data: 127 | # meta_train_loss_y = np.min(costs, axis=1) 128 | 129 | # # Meta-Test Loss: 130 | # if test_objective is not None: 131 | # best_phenotypes = get_best_phenotype_generator(input_path, nb_generations, sigma) 132 | 133 | # meta_test_loss_y = [] 134 | # for i, phenotype in enumerate(best_phenotypes): 135 | # if i % 1 == 0: 136 | # print(f'{i}/{nb_generations}\r', end='') 137 | # evaluation = test_objective(phenotype) 138 | # meta_test_loss_y.append(evaluation) 139 | # meta_test_loss_y = np.array(meta_test_loss_y) 140 | 141 | # with open(f"{output_path}/meta_train_loss_y.npy", "wb") as f: 142 | # np.save(f, meta_train_loss_y) 143 | 144 | # with open(f"{output_path}/meta_test_loss_y.npy", "wb") as f: 145 | # np.save(f, meta_test_loss_y) 146 | -------------------------------------------------------------------------------- /DNE4py/version_v2/sliceops.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | 4 | def multi_slice_add(x1_inplace, x2, x1_slices=(), x2_slices=()): 5 | """ 6 | Does an inplace addition on x1 given a list of slice objects 7 | If slices for both are given, it is assumed that they will be of 8 | the same size and each slice will have the same # of elements 9 | """ 10 | 11 | if (len(x1_slices) != 0) and (len(x2_slices) == 0): 12 | for x1_slice in x1_slices: 13 | x1_inplace[x1_slice] += x2 14 | 15 | elif (len(x1_slices) != 0) and (len(x2_slices) != 0) \ 16 | and (len(x2_slices) == len(x1_slices)): 17 | 18 | for i in range(len(x1_slices)): 19 | x1_inplace[x1_slices[i]] += x2[x2_slices[i]] 20 | 21 | elif (len(x1_slices) == 0) and (len(x2_slices) == 0): 22 | x1_inplace += x2 23 | 24 | 25 | def multi_slice_subtract(x1_inplace, x2, x1_slices=(), x2_slices=()): 26 | """ 27 | Does an inplace addition on x1 given a list of slice objects 28 | If slices for both are given, it is assumed that they will be of 29 | the same size and each slice will have the same # of elements 30 | """ 31 | 32 | if (len(x1_slices) != 0) and (len(x2_slices) == 0): 33 | for x1_slice in x1_slices: 34 | x1_inplace[x1_slice] -= x2 35 | 36 | elif (len(x1_slices) != 0) and (len(x2_slices) != 0) \ 37 | and (len(x2_slices) == len(x1_slices)): 38 | 39 | for i in range(len(x1_slices)): 40 | x1_inplace[x1_slices[i]] -= x2[x2_slices[i]] 41 | 42 | elif (len(x1_slices) == 0) and (len(x2_slices) == 0): 43 | x1_inplace -= x2 44 | 45 | 46 | def multi_slice_multiply(x1_inplace, x2, x1_slices=(), x2_slices=()): 47 | """ 48 | Does an inplace multiplication on x1 given a list of slice objects 49 | If slices for both are given, it is assumed that they will be of 50 | the same size and each slice will have the same # of elements 51 | """ 52 | 53 | if (len(x1_slices) != 0) and (len(x2_slices) == 0): 54 | for x1_slice in x1_slices: 55 | x1_inplace[x1_slice] *= x2 56 | 57 | elif (len(x1_slices) != 0) and (len(x2_slices) != 0) \ 58 | and (len(x2_slices) == len(x1_slices)): 59 | 60 | for i in range(len(x1_slices)): 61 | x1_inplace[x1_slices[i]] *= x2[x2_slices[i]] 62 | 63 | elif (len(x1_slices) == 0) and (len(x2_slices) == 0): 64 | x1_inplace *= x2 65 | 66 | 67 | def multi_slice_divide(x1_inplace, x2, x1_slices=(), x2_slices=()): 68 | """ 69 | Does an inplace multiplication on x1 given a list of slice objects 70 | If slices for both are given, it is assumed that they will be of 71 | the same size and each slice will have the same # of elements 72 | """ 73 | 74 | if (len(x1_slices) != 0) and (len(x2_slices) == 0): 75 | for x1_slice in x1_slices: 76 | x1_inplace[x1_slice] /= x2 77 | 78 | elif (len(x1_slices) != 0) and (len(x2_slices) != 0) \ 79 | and (len(x2_slices) == len(x1_slices)): 80 | 81 | for i in range(len(x1_slices)): 82 | x1_inplace[x1_slices[i]] /= x2[x2_slices[i]] 83 | 84 | elif (len(x1_slices) == 0) and (len(x2_slices) == 0): 85 | x1_inplace /= x2 86 | 87 | 88 | def multi_slice_assign(x1_inplace, x2, x1_slices=(), x2_slices=()): 89 | """ 90 | Does an inplace assignment on x1 given a list of slice objects 91 | If slices for both are given, it is assumed that they will be of 92 | the same size and each slice will have the same # of elements 93 | """ 94 | 95 | if (len(x1_slices) != 0) and (len(x2_slices) == 0): 96 | for x1_slice in x1_slices: 97 | x1_inplace[x1_slice] = x2 98 | 99 | elif (len(x1_slices) != 0) and (len(x2_slices) != 0) \ 100 | and (len(x2_slices) == len(x1_slices)): 101 | 102 | for i in range(len(x1_slices)): 103 | x1_inplace[x1_slices[i]] = x2[x2_slices[i]] 104 | 105 | elif (len(x1_slices) == 0) and (len(x2_slices) == 0): 106 | x1_inplace = x2 107 | 108 | 109 | def multi_slice_mod(x1_inplace, x2, x1_slices=(), x2_slices=()): 110 | """ 111 | Does an inplace modulo on x1 given a list of slice objects 112 | If slices for both are given, it is assumed that they will be of 113 | the same size and each slice will have the same # of elements 114 | """ 115 | 116 | if (len(x1_slices) != 0) and (len(x2_slices) == 0): 117 | for x1_slice in x1_slices: 118 | x1_inplace[x1_slice] %= x2 119 | 120 | elif (len(x1_slices) != 0) and (len(x2_slices) != 0) \ 121 | and (len(x2_slices) == len(x1_slices)): 122 | 123 | for i in range(len(x1_slices)): 124 | x1_inplace[x1_slices[i]] %= x2[x2_slices[i]] 125 | 126 | elif (len(x1_slices) == 0) and (len(x2_slices) == 0): 127 | x1_inplace %= x2 128 | 129 | 130 | def multi_slice_fabs(x1_inplace, x1_slices=()): 131 | """ 132 | Does an inplace fabs on x1 given a list of slice objects 133 | """ 134 | 135 | if len(x1_slices) != 0: 136 | for x1_slice in x1_slices: 137 | np.fabs(x1_inplace[x1_slice], out=x1_inplace[x1_slice]) 138 | 139 | else: 140 | np.fabs(x1_inplace, out=x1_inplace) 141 | 142 | 143 | def multi_slice_clip(x1_inplace, lower, upper, xslices=None, 144 | lslices=None, uslices=None): 145 | """ 146 | Does an inplace clip on x1 147 | """ 148 | 149 | if (lslices is None) and (uslices is None) and (xslices is None): 150 | np.clip(x1_inplace, lower, upper, out=x1_inplace) 151 | 152 | elif (lslices is None) or (uslices is None) and (xslices is not None): 153 | for xslice in xslices: 154 | np.clip(x1_inplace[xslice], lower, upper, out=x1_inplace[xslice]) 155 | 156 | elif (lslices is not None) and (uslices is not None) \ 157 | and (len(lslices) == len(uslices) and (xslices is not None)): 158 | for i in range(len(xslices)): 159 | np.clip(x1_inplace[xslices[i]], lower[lslices[i]], upper[uslices[i]], 160 | out=x1_inplace[xslices[i]]) 161 | 162 | else: 163 | raise NotImplementedError("Invalid arguments in multi_slice_clip") 164 | 165 | 166 | def random_slices(rng, iterator_size, size_of_slice, max_step=1): 167 | """ 168 | Returns a list of slice objects given the size of the iterator it 169 | will be used for and the number of elements desired for the slice 170 | This will return additional slice each time it wraps around the 171 | iterator 172 | 173 | iterator_size - the number of elements in the iterator 174 | size_of_slice - the number of elements the slices will cover 175 | max_step - the maximum number of steps a slice will take. 176 | This affects the number of slice objects created, as 177 | larger max_step will create more wraps around the iterator 178 | and so return more slice objects 179 | 180 | The number of elements is not guaranteed when slices overlap themselves 181 | """ 182 | 183 | step_size = rng.randint(1, max_step + 1) # randint is exclusive 184 | start_step = rng.randint(0, iterator_size) 185 | 186 | return build_slices(start_step, iterator_size, size_of_slice, step_size) 187 | 188 | 189 | def build_slices(start_step, iterator_size, size_of_slice, step_size): 190 | """ 191 | Given a starting index, the size of the total members of the window, 192 | a step size, and the size of the iterator the slice will act upon, 193 | this function returns a list of slice objects that will cover that full 194 | window. Upon reaching the endpoints of the iterator, it will wrap around. 195 | """ 196 | 197 | if step_size >= iterator_size: 198 | raise NotImplementedError("Error: step size must be less than the " + 199 | "size of the iterator") 200 | end_step = start_step + step_size * size_of_slice 201 | slices = [] 202 | slice_start = start_step 203 | for i in range(1 + (end_step - step_size) // iterator_size): 204 | remaining = end_step - i * iterator_size 205 | if remaining > iterator_size: 206 | remaining = iterator_size 207 | 208 | slice_end = (slice_start + 1) + ((remaining - 209 | (slice_start + 1)) // step_size) * step_size 210 | slices.append(np.s_[slice_start:slice_end:step_size]) 211 | slice_start = (slice_end - 1 + step_size) % iterator_size 212 | 213 | return slices 214 | 215 | 216 | def match_slices(slice_list1, slice_list2): 217 | """ 218 | Will attempt to create additional slices to match the # elements of 219 | each slice from list1 to the corresponding slice of list 2. 220 | Will fail if the total # elements is different for each list 221 | """ 222 | 223 | slice_list1 = list(slice_list1) 224 | slice_list2 = list(slice_list2) 225 | if slice_size(slice_list1) == slice_size(slice_list2): 226 | slice_list1.reverse() 227 | slice_list2.reverse() 228 | new_list1_slices = [] 229 | new_list2_slices = [] 230 | 231 | while len(slice_list1) != 0 and len(slice_list2) != 0: 232 | slice_1 = slice_list1.pop() 233 | slice_2 = slice_list2.pop() 234 | size_1 = slice_size(slice_1) 235 | size_2 = slice_size(slice_2) 236 | 237 | if size_1 < size_2: 238 | new_slice_2, slice_2 = splice_slice(slice_2, size_1) 239 | slice_list2.append(slice_2) 240 | new_list2_slices.append(new_slice_2) 241 | new_list1_slices.append(slice_1) 242 | 243 | elif size_2 < size_1: 244 | new_slice_1, slice_1 = splice_slice(slice_1, size_2) 245 | slice_list1.append(slice_1) 246 | new_list1_slices.append(new_slice_1) 247 | new_list2_slices.append(slice_2) 248 | 249 | elif size_1 == size_2: 250 | new_list1_slices.append(slice_1) 251 | new_list2_slices.append(slice_2) 252 | 253 | else: 254 | raise AssertionError("Error: slices not compatible") 255 | 256 | return new_list1_slices, new_list2_slices 257 | 258 | 259 | def splice_slice(slice_obj, num_elements): 260 | """ 261 | Returns two slices spliced from a single slice. 262 | The size of the first slice will be # elements 263 | The size of the second slice will be the remainder 264 | """ 265 | 266 | splice_point = slice_obj.step * (num_elements - 1) + slice_obj.start + 1 267 | new_start = splice_point - 1 + slice_obj.step 268 | return np.s_[slice_obj.start: splice_point: slice_obj.step], \ 269 | np.s_[new_start: slice_obj.stop: slice_obj.step] 270 | 271 | 272 | def slice_size(slice_objects): 273 | """ 274 | Returns the total number of elements in the combined slices 275 | Also works if given a single slice 276 | """ 277 | 278 | num_elements = 0 279 | 280 | try: 281 | for sl in slice_objects: 282 | num_elements += (sl.stop - (sl.start + 1)) // sl.step + 1 283 | except TypeError: 284 | num_elements += (slice_objects.stop - (slice_objects.start + 1)) \ 285 | // slice_objects.step + 1 286 | 287 | return num_elements 288 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # DNE4py: Deep-Neuroevolution with mpi4py 2 | 3 | Status: Maintenance (expect bug fixes and major updates) 4 | 5 | DNE4py is a python library that aims to run and visualize many different evolutionary algorithms with high performance using mpi4py. It allows easy evaluation of evolutionary algorithms in high dimension (e.g. neural networks for reinforcement learning) 6 | 7 | Implementation available: 8 | 9 | * [Genetic Algorithms Are a Competitive Alternative for Training Deep Neural Networks for Reinforcement Learning](https://arxiv.org/pdf/1712.06567.pdf) 10 | 11 | ## Installation 12 | 13 | ```console 14 | foo@bar:~$ git clone https://github.com/optimization-toolbox/DNE4py 15 | foo@bar:~$ cd deep-neuroevolution-mpi4py/ 16 | foo@bar:~$ python3 -m pip install -e . 17 | ``` 18 | 19 | ## Running 20 | 21 | Create main.py: 22 | 23 | ```python 24 | from DNE4py.optimizers.deepga import TruncatedRealMutatorGA 25 | 26 | def objective(x): 27 | result = np.sum(x**2) 28 | return result 29 | 30 | initial_guess = [1.0, 1.0] 31 | 32 | optimizer = TruncatedRealMutatorGA(objective=objective, 33 | initial_guess=initial_guess, 34 | workers_per_rank=10, 35 | num_elite=1, 36 | num_parents=3, 37 | sigma=0.01, 38 | seed=100, 39 | save=1, 40 | verbose=1, 41 | output_folder='results/experiment') 42 | 43 | optimizer(100) 44 | ``` 45 | 46 | Execute main.py (relies on MPI): 47 | 48 | ```console 49 | foo@bar:~$ mpiexec -n 4 python3 main.py 50 | ``` 51 | 52 | This will create a result folder based on output_folder 53 | 54 | ##### DeepGA 55 | 56 | ![DeepGA: population over generations](https://github.com/optimization-toolbox/DNE4py/blob/master/tutorials/2_postprocessing_the_results/gif/deepga_truncatedrealmutatorga.gif) 57 | 58 | 59 | 60 | ##### CMA-ES 61 | 62 | ![CMA-ES: population over generations](https://github.com/optimization-toolbox/DNE4py/blob/master/tutorials/2_postprocessing_the_results/gif/cmaes.gif) 63 | 64 | ##### RandomSearch 65 | 66 | ![RandomSearch: population over generations](https://github.com/optimization-toolbox/DNE4py/blob/master/tutorials/2_postprocessing_the_results/gif/randomsearch.gif) 67 | 68 | ## Post-processing 69 | 70 | You can import and generate some visualizations: 71 | ```python 72 | from DNE4py import load_mpidata, get_best_phenotype, get_best_phenotype_generator 73 | ``` 74 | 75 | 76 | 77 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import setuptools 2 | 3 | with open("README.md", "r") as fh: 4 | long_description = fh.read() 5 | 6 | setuptools.setup( 7 | name="DNE4py", 8 | version="0.2", 9 | author="Hugo Dovs", 10 | author_email="hugodovs@gmail.com", 11 | description="DNE4py: Deep Neuroevolution Algorithms using mpi4py", 12 | long_description=long_description, 13 | long_description_content_type="text/markdown", 14 | url="https://github.com/optimization-toolbox/DNE4py", 15 | packages=setuptools.find_packages(), 16 | classifiers=[ 17 | "Programming Language :: Python :: 3", 18 | "License :: GNU General Public License v3.0", 19 | "Operating System :: OS Independent", 20 | ], 21 | python_requires='>=3.5', 22 | ) 23 | -------------------------------------------------------------------------------- /tutorials/1_optimizing_user_defined_function/TruncatedRealMutatorGA.yaml: -------------------------------------------------------------------------------- 1 | optimizer: 2 | id: TruncatedRealMutatorGA 3 | workers_per_rank: 64 4 | num_elite: 1 5 | num_parents: 1 6 | sigma_initial: 0.1 7 | sigma_min: 0.01 8 | sigma_decay: 0.95 9 | global_seed: 42 10 | output_folder: '../2_postprocessing_the_results/results/TruncatedRealMutatorGA' 11 | save_steps: 1 12 | verbose: 2 13 | -------------------------------------------------------------------------------- /tutorials/1_optimizing_user_defined_function/run.py: -------------------------------------------------------------------------------- 1 | import yaml 2 | import numpy as np 3 | from DNE4py import load_optimizer 4 | np.random.seed(10) 5 | 6 | 7 | def objective_function(x): 8 | return np.sum(x**2) 9 | 10 | 11 | if "__main__" == __name__: 12 | 13 | # Read config: 14 | with open(f'TruncatedRealMutatorGA.yaml') as f: 15 | config = yaml.load(f, Loader=yaml.FullLoader) 16 | optimizer_config = config.get('optimizer') 17 | 18 | # Declare Optimizer: 19 | optimizer_config['initial_guess'] = np.random.random(7000) 20 | optimizer = load_optimizer(optimizer_config) 21 | 22 | # Run Optimizer: 23 | optimizer.run(objective_function, 2) 24 | -------------------------------------------------------------------------------- /tutorials/2_postprocessing_the_results/gif/cmaes.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/optimization-toolbox/DNE4py/4639ff4f869f07d6f5858edf12bbc96e2c2c1824/tutorials/2_postprocessing_the_results/gif/cmaes.gif -------------------------------------------------------------------------------- /tutorials/2_postprocessing_the_results/gif/deepga_truncatedrealmutatorga.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/optimization-toolbox/DNE4py/4639ff4f869f07d6f5858edf12bbc96e2c2c1824/tutorials/2_postprocessing_the_results/gif/deepga_truncatedrealmutatorga.gif -------------------------------------------------------------------------------- /tutorials/2_postprocessing_the_results/gif/randomsearch.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/optimization-toolbox/DNE4py/4639ff4f869f07d6f5858edf12bbc96e2c2c1824/tutorials/2_postprocessing_the_results/gif/randomsearch.gif -------------------------------------------------------------------------------- /tutorials/2_postprocessing_the_results/pp_run.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import numpy as np 3 | 4 | from DNE4py import load_mpidata, get_best_phenotype, get_best_phenotype_generator 5 | import matplotlib.pyplot as plt 6 | 7 | 8 | def objective_function(x): 9 | return np.sum(x**2) 10 | 11 | 12 | if "__main__" == __name__: 13 | 14 | costs = load_mpidata('costs', 'results/TruncatedRealMutatorGA/') 15 | genotypes = load_mpidata('genotypes', 'results/TruncatedRealMutatorGA/') 16 | initial_guess = load_mpidata('initial_guess', 'results/TruncatedRealMutatorGA/') 17 | 18 | # for i, c in enumerate(costs): 19 | # print(i) 20 | # print(f'{np.min(c)}') 21 | # print(f'{c}') 22 | # print() 23 | 24 | print(f'costs shape: {costs.shape}') 25 | print(f'genotypes shape: {genotypes.shape}') 26 | print(f'initial_guess shape: {initial_guess.shape}') 27 | 28 | print(genotypes[0]) 29 | print(genotypes[-1]) 30 | #print(initial_guess) 31 | #print(costs[-1][0]) 32 | 33 | x = get_best_phenotype('results/TruncatedRealMutatorGA/') 34 | 35 | #exit() 36 | #print(x) 37 | #print(objective_function(x)) 38 | #exit() 39 | 40 | generator = get_best_phenotype_generator('results/TruncatedRealMutatorGA/') 41 | 42 | y = np.min(costs, axis=1) 43 | plt.plot(y) 44 | plt.show() 45 | # for i in generator: 46 | # print(i) 47 | -------------------------------------------------------------------------------- /tutorials/2_postprocessing_the_results/render.py: -------------------------------------------------------------------------------- 1 | # After running these methods, you can generate a compressed .gif in the following command: 2 | # $: convert -layers OptimizeTransparency -delay 20 -loop 0 `ls -v` myimage.gif 3 | # To Optimizer: (Use Optimize Transparency 10%) https://ezgif.com/optimize/ 4 | 5 | 6 | import pickle 7 | 8 | from scipy.stats import multivariate_normal 9 | 10 | from DNE4py.postprocessing.utils import load_mpidata 11 | from DNE4py.optimizers.cmaes import CMAES 12 | 13 | 14 | def randomsearch_render(folder_path, nb_generations, objective): 15 | 16 | import numpy as np 17 | import matplotlib.pyplot as plt 18 | 19 | def start_image(): 20 | fig, ax = plt.subplots() 21 | ax.set_xlim([-1, 1]) 22 | ax.set_ylim([-1, 1]) 23 | ax.set_xticks(np.arange(-1, 1, 0.2)) 24 | ax.set_yticks(np.arange(-1, 1, 0.2)) 25 | return fig, ax 26 | 27 | # Read Input: 28 | costs = load_mpidata(f"{folder_path}", "costs", nb_generations) 29 | genotypes = load_mpidata(f"{folder_path}", "genotypes", nb_generations) 30 | initial_guess = load_mpidata(f"{folder_path}", "initial_guess", 1)[0] 31 | 32 | # Start figure: 33 | fig, ax = start_image() 34 | 35 | # Plot function: 36 | resolution = 100 37 | x1, x2 = np.meshgrid(np.linspace(-1, 1, resolution), np.linspace(-1, 1, resolution)) 38 | X = np.array([x1.flatten(), x2.flatten()]).T 39 | Y = np.array([objective(x) for x in X]).reshape(resolution, resolution) 40 | ax.pcolormesh(x1, x2, Y, cmap=plt.cm.coolwarm) 41 | 42 | for g in range(nb_generations - 1): 43 | 44 | # Image 1: 45 | 46 | # Plot function: 47 | fig, ax = start_image() 48 | ax.pcolormesh(x1, x2, Y, cmap=plt.cm.coolwarm) 49 | 50 | # Plot points: 51 | ax.scatter(genotypes[g][:, 0], genotypes[g][:, 1], s=10, c='black') 52 | plt.savefig(f"pp_{folder_path}/{g+1}_1.jpeg") 53 | 54 | def cmaes_render(folder_path, nb_generations, objective, sigma): 55 | 56 | import numpy as np 57 | import matplotlib.pyplot as plt 58 | 59 | def start_image(): 60 | fig, ax = plt.subplots() 61 | ax.set_xlim([-1, 1]) 62 | ax.set_ylim([-1, 1]) 63 | ax.set_xticks(np.arange(-1, 1, 0.2)) 64 | ax.set_yticks(np.arange(-1, 1, 0.2)) 65 | return fig, ax 66 | 67 | # Read Input: 68 | costs = load_mpidata(f"{folder_path}", "costs", nb_generations) 69 | genotypes = load_mpidata(f"{folder_path}", "genotypes", nb_generations) 70 | initial_guess = load_mpidata(f"{folder_path}", "initial_guess", 1)[0] 71 | 72 | # Start figure: 73 | fig, ax = start_image() 74 | 75 | # Plot function: 76 | resolution = 100 77 | x1, x2 = np.meshgrid(np.linspace(-1, 1, resolution), np.linspace(-1, 1, resolution)) 78 | X = np.array([x1.flatten(), x2.flatten()]).T 79 | Y = np.array([objective(x) for x in X]).reshape(resolution, resolution) 80 | ax.pcolormesh(x1, x2, Y, cmap=plt.cm.coolwarm) 81 | 82 | # Show Initial Guess 83 | ax.scatter(initial_guess[0], initial_guess[1], c='black', s=20) 84 | plt.savefig(f"pp_{folder_path}/0.jpeg") 85 | 86 | cmaes = CMAES(objective=objective, 87 | initial_guess=initial_guess, 88 | workers_per_rank=10, 89 | sigma=sigma, 90 | seed=100, 91 | save=0, 92 | verbose=0, 93 | output_folder='DNE4py_result') 94 | optimizer = cmaes.optimizer 95 | 96 | # Loop: 97 | contour_x0, contour_x1 = np.mgrid[-1:1:.01, -1:1:.01] 98 | pos = np.dstack((contour_x0, contour_x1)) 99 | for g in range(nb_generations - 1): 100 | 101 | # Image 1: 102 | 103 | # Plot function: 104 | fig, ax = start_image() 105 | ax.pcolormesh(x1, x2, Y, cmap=plt.cm.coolwarm) 106 | 107 | # Plot current distribution (black): 108 | mu_x0, mu_x1 = optimizer.mean 109 | variance = optimizer.sigma 110 | rv = multivariate_normal([mu_x0, mu_x1], [[variance, 0], [0, variance]]) 111 | ax.contour(contour_x0, contour_x1, rv.pdf(pos), colors='black', alpha=0.3) 112 | # plt.savefig(f"{folder_path}/pp/{g+1}_1.jpeg") 113 | 114 | # Plot current points (black): 115 | ax.scatter(genotypes[g][:, 0], genotypes[g][:, 1], s=10, c='black') 116 | plt.savefig(f"pp_{folder_path}/{g+1}_1.jpeg") 117 | 118 | # Update CMAES 119 | solutions = np.array(optimizer.ask()) 120 | optimizer.tell(genotypes[g], costs[g]) 121 | 122 | # Plot next distribution (red): 123 | mu_x0, mu_x1 = optimizer.mean 124 | variance = optimizer.sigma 125 | rv = multivariate_normal([mu_x0, mu_x1], [[variance, 0], [0, variance]]) 126 | ax.contour(contour_x0, contour_x1, rv.pdf(pos), colors='red', alpha=0.3) 127 | plt.savefig(f"pp_{folder_path}/{g+1}_2.jpeg") 128 | 129 | # Plot current points (red): 130 | ax.scatter(genotypes[g + 1][:, 0], genotypes[g + 1][:, 1], s=10, c='red') 131 | plt.savefig(f"pp_{folder_path}/{g+1}_3.jpeg") 132 | 133 | def deepga_render(folder_path, nb_generations, objective, sigma, num_parents, num_elite): 134 | 135 | import numpy as np 136 | import matplotlib.pyplot as plt 137 | 138 | from DNE4py.optimizers.deepga.mutation import Member 139 | 140 | def start_image(): 141 | fig, ax = plt.subplots() 142 | ax.set_xlim([-1, 1]) 143 | ax.set_ylim([-1, 1]) 144 | ax.set_xticks(np.arange(-1, 1, 0.2)) 145 | ax.set_yticks(np.arange(-1, 1, 0.2)) 146 | return fig, ax 147 | 148 | # Read Input: 149 | costs = load_mpidata(f"{folder_path}", "costs", nb_generations) 150 | genotypes = load_mpidata(f"{folder_path}", "genotypes", nb_generations) 151 | initial_guess = load_mpidata(f"{folder_path}", "initial_guess", 1)[0] 152 | 153 | # Start figure: 154 | fig, ax = start_image() 155 | 156 | # Plot function: 157 | resolution = 100 158 | x1, x2 = np.meshgrid(np.linspace(-1, 1, resolution), np.linspace(-1, 1, resolution)) 159 | X = np.array([x1.flatten(), x2.flatten()]).T 160 | Y = np.array([objective(x) for x in X]).reshape(resolution, resolution) 161 | ax.pcolormesh(x1, x2, Y, cmap=plt.cm.coolwarm) 162 | 163 | # Show Initial Guess 164 | ax.scatter(initial_guess[0], initial_guess[1], c='black', s=20) 165 | plt.savefig(f"pp_{folder_path}/0.jpeg") 166 | 167 | # Loop: 168 | for g in range(nb_generations - 1): 169 | 170 | # Plot function: 171 | fig, ax = start_image() 172 | ax.pcolormesh(x1, x2, Y, cmap=plt.cm.coolwarm) 173 | 174 | # Image 1: 175 | phenotypes = [] 176 | for genotype in genotypes[g]: 177 | phenotype = Member(initial_guess, genotype, sigma).phenotype 178 | phenotypes.append(phenotype) 179 | phenotypes = np.array(phenotypes) 180 | 181 | ax.scatter(phenotypes[:, 0], phenotypes[:, 1], c='black', s=10) 182 | plt.savefig(f"pp_{folder_path}/{g+1}_1.jpeg") 183 | 184 | # Image 2: 185 | order = np.argsort(costs[g]) 186 | rank = np.argsort(order) 187 | parents_mask = rank < num_parents 188 | elite_mask = rank < num_elite 189 | 190 | parents_phenotypes = phenotypes[parents_mask] 191 | elite_phenotypes = phenotypes[elite_mask] 192 | ax.scatter(parents_phenotypes[:, 0], parents_phenotypes[:, 1], c='green', s=10) 193 | ax.scatter(elite_phenotypes[:, 0], elite_phenotypes[:, 1], c='blue', s=10) 194 | plt.savefig(f"pp_{folder_path}/{g+1}_2.jpeg") 195 | 196 | # Image 3 197 | phenotypes = [] 198 | for genotype in genotypes[g + 1]: 199 | phenotype = Member(initial_guess, genotype, sigma).phenotype 200 | phenotypes.append(phenotype) 201 | phenotypes = np.array(phenotypes) 202 | ax.scatter(phenotypes[:, 0], phenotypes[:, 1], c='red', s=10) 203 | plt.savefig(f"pp_{folder_path}/{g+1}_3.jpeg") 204 | -------------------------------------------------------------------------------- /tutorials/README.md: -------------------------------------------------------------------------------- 1 | ## `run.py` 2 | * It changes results folder 3 | ```console 4 | foo@bar:~$ mpiexec -n 2 python3 run.py 3 5 | ``` 6 | 7 | ## `pp_run.py` 8 | * It changes pp_results folder 9 | * To Optimize: (Use Optimize Transparency 10%) https://ezgif.com/optimize/ 10 | 11 | ```console 12 | foo@bar:~$ python3 pp_run.py 3 13 | foo@bar:~$ cd pp_results/RandomSearch/ 14 | foo@bar:~$ convert -layers OptimizeTransparency -delay 20 -loop 0 `ls -v` randomsearch.gif 15 | ``` 16 | 17 | ## `render.py` 18 | * It defines the behaviour to render the optimization procedure 19 | 20 | --------------------------------------------------------------------------------