Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Maint/isort #219

Merged
merged 5 commits into from
Aug 3, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .isort.cfg
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
[settings]
line_length = 99
multi_line_output = 3
include_trailing_comma = True
16 changes: 16 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
repos:
- repo: https://github.com/ambv/black
rev: stable
hooks:
- id: black
language_version: python3.8
args: [--config=pyproject.toml]
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v1.2.3
hooks:
- id: flake8
args: [--config=.flake8]
- repo: https://github.com/pre-commit/mirrors-isort
rev: v4.3.21
hooks:
- id: isort
1 change: 1 addition & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ script:
- black --check .
- flake8 --config=.flake8 .
- mypy cgp
- isort --check-only cgp examples test
- if [ "$DEP" = "[all]" -a $TRAVIS_PYTHON_VERSION = 3.8 ]; then
pip install gym || exit 1;
make -C docs/ html || exit 1;
Expand Down
13 changes: 4 additions & 9 deletions cgp/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,11 @@
__url__ = "https://happy-algorithms-league.github.io/hal-cgp/"
__doc__ = f"{__description__} <{__url__}>"

from .genome import Genome
from . import ea, local_search, utils
from .cartesian_graph import CartesianGraph
from .genome import Genome
from .hl_api import evolve
from .individual import IndividualMultiGenome, IndividualSingleGenome
from .node import OperatorNode
from .node_impl import Add, ConstantFloat, Div, Mul, Parameter, Pow, Sub
from .population import Population

from .hl_api import evolve

from . import utils
from . import ea
from . import local_search

from .individual import IndividualSingleGenome, IndividualMultiGenome
13 changes: 7 additions & 6 deletions cgp/cartesian_graph.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
import collections
import copy
import math # noqa: F401
import numpy as np # noqa: F401
import re
from typing import TYPE_CHECKING, Callable, Dict, List, Optional, Set

import numpy as np # noqa: F401

from .node import Node, OperatorNode
from .node_input_output import InputNode, OutputNode

try:
import sympy
Expand All @@ -19,10 +24,6 @@
except ModuleNotFoundError:
torch_available = False

from typing import Callable, Dict, List, Optional, Set, TYPE_CHECKING

from .node import Node, OperatorNode
from .node_input_output import InputNode, OutputNode

if TYPE_CHECKING:
from .genome import Genome
Expand Down Expand Up @@ -372,7 +373,7 @@ def _format_output_str_sympy_of_all_nodes(self):
for node in active_nodes[hidden_column_idx]:
node.format_output_str_sympy(self)

def to_sympy(self, simplify: Optional[bool] = True,) -> List["sympy_expr.Expr"]:
def to_sympy(self, simplify: Optional[bool] = True) -> List["sympy_expr.Expr"]:
"""Compile the function(s) represented by the graph to a SymPy expression.

Generates one SymPy expression for each output node.
Expand Down
4 changes: 2 additions & 2 deletions cgp/ea/mu_plus_lambda.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import concurrent.futures
import numpy as np

from typing import Callable, List, Union

import numpy as np

from ..individual import IndividualBase
from ..population import Population

Expand Down
16 changes: 8 additions & 8 deletions cgp/genome.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
from typing import Dict, Generator, List, Optional, Tuple, Type, Union

import numpy as np

from .cartesian_graph import CartesianGraph
from .node import Node, OperatorNode
from .primitives import Primitives

try:
import torch # noqa: F401

torch_available = True
except ModuleNotFoundError:
torch_available = False

from typing import Dict, Generator, List, Optional, Tuple, Type, Union

from .cartesian_graph import CartesianGraph
from .node import Node, OperatorNode
from .primitives import Primitives


ID_INPUT_NODE: int = -1
ID_OUTPUT_NODE: int = -2
Expand Down Expand Up @@ -170,7 +170,7 @@ def determine_permissible_values(self) -> List[np.ndarray]:
permissible_values.append(permissible_values_per_gene)
return permissible_values

def _determine_permissible_values_input_region(self, gene_idx: int,) -> np.ndarray:
def _determine_permissible_values_input_region(self, gene_idx: int) -> np.ndarray:

if self._is_function_gene(gene_idx):
return np.array(self._id_input_node)
Expand All @@ -190,7 +190,7 @@ def _determine_permissible_values_hidden_region(
else:
assert False # should never be reached

def _determine_permissible_values_output_region(self, gene_idx: int,) -> np.ndarray:
def _determine_permissible_values_output_region(self, gene_idx: int) -> np.ndarray:

if self._is_function_gene(gene_idx):
return np.array(self._id_output_node)
Expand Down
7 changes: 4 additions & 3 deletions cgp/hl_api.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
from typing import Callable, Optional

import numpy as np
from typing import Optional, Callable

from .population import Population
from .individual import IndividualBase
from .ea import MuPlusLambda
from .individual import IndividualBase
from .population import Population


def evolve(
Expand Down
9 changes: 5 additions & 4 deletions cgp/individual.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import numpy as np
from typing import Callable, List, Union

import numpy as np

from .cartesian_graph import CartesianGraph
from .genome import Genome

try:
import sympy # noqa: F401
from sympy.core import expr as sympy_expr # noqa: F401
Expand All @@ -16,9 +20,6 @@
except ModuleNotFoundError:
torch_available = False

from .genome import Genome
from .cartesian_graph import CartesianGraph


class IndividualBase:
"""Base class for all individuals.
Expand Down
9 changes: 4 additions & 5 deletions cgp/local_search/gradient_based.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
from typing import Callable, List, Optional, Union

import numpy as np

from ..individual import IndividualBase

try:
import torch # noqa: F401
from torch.optim.optimizer import Optimizer # noqa: F401
Expand All @@ -8,11 +12,6 @@
except ModuleNotFoundError:
torch_available = False

from typing import Callable, List, Optional, Union


from ..individual import IndividualBase


def gradient_based(
individual: IndividualBase,
Expand Down
3 changes: 1 addition & 2 deletions cgp/node.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import math # noqa: F401
import re

from typing import Callable, Dict, List, Tuple, Type, TYPE_CHECKING
from typing import TYPE_CHECKING, Callable, Dict, List, Tuple, Type

from . import node_validation

Expand Down
2 changes: 1 addition & 1 deletion cgp/node_input_output.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import List, TYPE_CHECKING
from typing import TYPE_CHECKING, List

from .node import Node

Expand Down
7 changes: 4 additions & 3 deletions cgp/node_validation.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from typing import TYPE_CHECKING, Type

import numpy as np

try:
Expand All @@ -15,16 +17,15 @@
except ModuleNotFoundError:
torch_available = False

from typing import Type, TYPE_CHECKING

if TYPE_CHECKING:
from .node import OperatorNode # noqa: F401
from .genome import Genome # noqa: F401
from .node import OperatorNode # noqa: F401


def _create_genome(cls: Type["OperatorNode"]) -> "Genome":
# delayed imports to avoid circular imports
from .genome import Genome, ID_INPUT_NODE, ID_OUTPUT_NODE, ID_NON_CODING_GENE
from .genome import ID_INPUT_NODE, ID_NON_CODING_GENE, ID_OUTPUT_NODE, Genome

primitives = (cls,)
genome = Genome(1, 1, 1, 1, 1, primitives)
Expand Down
6 changes: 3 additions & 3 deletions cgp/population.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import numpy as np

from typing import List, Union

import numpy as np

from .genome import Genome
from .individual import IndividualBase, IndividualSingleGenome, IndividualMultiGenome
from .individual import IndividualBase, IndividualMultiGenome, IndividualSingleGenome


class Population:
Expand Down
4 changes: 2 additions & 2 deletions cgp/primitives.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
from dataclasses import dataclass, field
import numpy as np

from typing import Iterator, Tuple, Type

import numpy as np

from .node import Node


Expand Down
12 changes: 4 additions & 8 deletions cgp/utils.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import functools
import hashlib
import numpy as np
import os
import pickle

from typing import Any, Callable, Dict, List, Tuple, Type, Union

from .node import primitives_dict, Node
import numpy as np

from .node import Node, primitives_dict


def __check_cache_consistency(fn: str, func: Callable[..., float]) -> None:
Expand Down Expand Up @@ -53,11 +53,7 @@ def __store_new_cache_entry(
) -> None:
with open(fn, "ab") as f:

result = {
"args": args,
"kwargs": kwargs,
"return_value": return_value,
}
result = {"args": args, "kwargs": kwargs, "return_value": return_value}

pickle.dump({key: result}, f)

Expand Down
3 changes: 2 additions & 1 deletion examples/example_caching.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,10 @@
second time and when you comment out the decorator on
`inner_objective`."""

import numpy as np
import time

import numpy as np

import cgp

# %%
Expand Down
8 changes: 2 additions & 6 deletions examples/example_differential_evo_regression.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
"""

import functools

import matplotlib.pyplot as plt
import numpy as np
import scipy.constants
Expand Down Expand Up @@ -89,12 +90,7 @@ def objective(individual, seed):
"primitives": (cgp.Add, cgp.Sub, cgp.Mul, cgp.Parameter),
}

ea_params = {
"n_offsprings": 4,
"tournament_size": 1,
"n_processes": 1,
"k_local_search": 2,
}
ea_params = {"n_offsprings": 4, "tournament_size": 1, "n_processes": 1, "k_local_search": 2}

evolve_params = {"max_generations": 2000, "min_fitness": 0.0}

Expand Down
3 changes: 2 additions & 1 deletion examples/example_evo_regression.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,11 @@


import functools
import warnings

import matplotlib.pyplot as plt
import numpy as np
import scipy.constants
import warnings

import cgp

Expand Down
13 changes: 7 additions & 6 deletions examples/example_mountain_car.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,13 @@


import functools
import warnings

import matplotlib.pyplot as plt
import numpy as np
import sympy

import cgp

try:
import gym
Expand All @@ -22,12 +29,6 @@
"Failed to import the OpenAI Gym package. Please install it via `pip install gym`."
)

import matplotlib.pyplot as plt
import numpy as np
import sympy
import warnings

import cgp

# %%
# For more flexibility in the evolved expressions, we define two
Expand Down
6 changes: 2 additions & 4 deletions examples/example_parametrized_nodes.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,14 @@

import functools
import math

import matplotlib.pyplot as plt
import numpy as np
import scipy.constants
import torch

import cgp


# %%
# We first define a new node that adds two inputs then scales and
# finally shifts the result. The scale ("w") and shift factors ("b")
Expand Down Expand Up @@ -138,9 +138,7 @@ def recording_callback(pop):

obj = functools.partial(objective, seed=population_params["seed"])

cgp.evolve(
pop, obj, ea, **evolve_params, print_progress=True, callback=recording_callback,
)
cgp.evolve(pop, obj, ea, **evolve_params, print_progress=True, callback=recording_callback)

# %%
# After the evolutionary search has ended, we print the expression
Expand Down
Loading