Skip to content

Commit

Permalink
Use simpler type annotations valid for python>=3.9
Browse files Browse the repository at this point in the history
- List[] -> list[]
- Sequence imported from collections.abc
...
  • Loading branch information
nhuet committed Sep 19, 2024
1 parent 2d364bc commit c9d42cc
Show file tree
Hide file tree
Showing 163 changed files with 2,040 additions and 2,098 deletions.
47 changes: 24 additions & 23 deletions discrete_optimization/coloring/coloring_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.

from typing import Dict, Hashable, List, Optional, Set, Type, Union
from collections.abc import Hashable
from typing import Optional, Union

import numpy as np

Expand Down Expand Up @@ -36,7 +37,7 @@ class ColoringSolution(Solution):
Attributes:
problem (ColoringProblem): instance of the graph coloring problem
colors (Union[List[int], np.array]): list/array of the same size of problem.number_of_nodes number.
colors (Union[list[int], np.array]): list/array of the same size of problem.number_of_nodes number.
It should contain integer values representing discrete colors.
nb_color (Optional[int]): number of different colors present in colors attributes. can be used directly
by the problem.evaluate function if this attribute is provided
Expand All @@ -47,7 +48,7 @@ class ColoringSolution(Solution):
def __init__(
self,
problem: Problem,
colors: Optional[Union[List[int], np.ndarray]] = None,
colors: Optional[Union[list[int], np.ndarray]] = None,
nb_color: Optional[int] = None,
nb_violations: Optional[int] = None,
):
Expand All @@ -66,7 +67,7 @@ def copy(self) -> "ColoringSolution":
Returns: A copy that can be considered as a deep copy of the current object.
"""
colors: Optional[Union[List[int], np.ndarray]]
colors: Optional[Union[list[int], np.ndarray]]
if self.colors is None:
colors = None
elif isinstance(self.colors, np.ndarray):
Expand Down Expand Up @@ -109,7 +110,7 @@ def to_reformated_solution(self) -> "ColoringSolution":
Returns: New ColoringSolution object with value precede chain property.
"""
colors: List[int]
colors: list[int]
if self.colors is None:
raise ValueError(
"self.colors should not be None when calling to_reformated_solution()"
Expand Down Expand Up @@ -154,7 +155,7 @@ def change_problem(self, new_problem: Problem) -> None:
raise ValueError(
"new_problem must a ColoringProblem for a ColoringSolution."
)
colors: Optional[Union[List[int], np.ndarray]]
colors: Optional[Union[list[int], np.ndarray]]
if self.colors is None:
self.colors = None
elif isinstance(self.colors, np.ndarray):
Expand All @@ -164,11 +165,11 @@ def change_problem(self, new_problem: Problem) -> None:
self.problem = new_problem


def transform_color_values_to_value_precede(color_vector: List[int]) -> List[int]:
def transform_color_values_to_value_precede(color_vector: list[int]) -> list[int]:
"""See method ColoringSolution.to_reformated_solution().
Args:
color_vector (List[int]): vector representing colors of vertices
color_vector (list[int]): vector representing colors of vertices
Returns: A vector with value precede chain property
Expand All @@ -187,13 +188,13 @@ def transform_color_values_to_value_precede(color_vector: List[int]) -> List[int
class ConstraintsColoring:
"""Data structure to store additional constraints. Attributes will grow
Attributes:
color_constraint (Dict[Hashable, int]): dictionary filled with color constraint.
color_constraint (dict[Hashable, int]): dictionary filled with color constraint.
"""

def __init__(self, color_constraint: Dict[Hashable, int]):
def __init__(self, color_constraint: dict[Hashable, int]):
self.color_constraint = color_constraint

def nodes_fixed(self) -> Set[Hashable]:
def nodes_fixed(self) -> set[Hashable]:
if self.color_constraint is not None:
return set(self.color_constraint.keys())
else:
Expand All @@ -206,17 +207,17 @@ class ColoringProblem(Problem):
Attributes:
graph (Graph): a graph object representing vertices and edges.
number_of_nodes (int): number of nodes in the graph
subset_nodes (Set[Hashable]): subset of nodes id to take into account in the optimisation.
nodes_name (List[Hashable]): list of id of the graph vertices.
index_nodes_name (Dict[Hashable, int]): dictionary node_name->index
index_to_nodes_name (Dict[int, Hashable]): index->node_name
subset_nodes (set[Hashable]): subset of nodes id to take into account in the optimisation.
nodes_name (list[Hashable]): list of id of the graph vertices.
index_nodes_name (dict[Hashable, int]): dictionary node_name->index
index_to_nodes_name (dict[int, Hashable]): index->node_name
"""

def __init__(
self,
graph: Graph,
subset_nodes: Set[Hashable] = None,
subset_nodes: set[Hashable] = None,
constraints_coloring: Optional[ConstraintsColoring] = None,
):
self.graph = graph
Expand Down Expand Up @@ -248,17 +249,17 @@ def is_in_subset_nodes(self, node: Hashable) -> bool:
return True
return node in self.subset_nodes

def count_colors(self, colors_list: List[int]) -> int:
def count_colors(self, colors_list: list[int]) -> int:
if self.use_subset:
nb_color = len(set([colors_list[j] for j in self.index_subset_nodes]))
else:
nb_color = len(set(colors_list))
return nb_color

def count_colors_all_index(self, colors_list: List[int]) -> int:
def count_colors_all_index(self, colors_list: list[int]) -> int:
return len(set(colors_list))

def evaluate(self, variable: ColoringSolution) -> Dict[str, float]: # type: ignore # avoid isinstance checks for efficiency
def evaluate(self, variable: ColoringSolution) -> dict[str, float]: # type: ignore # avoid isinstance checks for efficiency
"""Evaluation implementation for ColoringProblem.
Compute number of colors and violation of the current solution.
Expand Down Expand Up @@ -334,7 +335,7 @@ def get_attribute_register(self) -> EncodingRegister:
}
return EncodingRegister(dict_register)

def get_solution_type(self) -> Type[Solution]:
def get_solution_type(self) -> type[Solution]:
"""Returns the class of a solution instance for ColoringProblem."""
return ColoringSolution

Expand Down Expand Up @@ -397,8 +398,8 @@ def count_violations(self, variable: ColoringSolution) -> int:
return val

def evaluate_from_encoding(
self, int_vector: List[int], encoding_name: str
) -> Dict[str, float]:
self, int_vector: list[int], encoding_name: str
) -> dict[str, float]:
"""Can be used in GA algorithm to build an object solution and evaluate from a int_vector representation.
Args:
Expand Down Expand Up @@ -437,7 +438,7 @@ def compute_constraints_penalty(

def transform_coloring_problem(
coloring_problem: ColoringProblem,
subset_nodes: Optional[Set[Hashable]] = None,
subset_nodes: Optional[set[Hashable]] = None,
constraints_coloring: Optional[ConstraintsColoring] = None,
) -> ColoringProblem:
return ColoringProblem(
Expand Down
9 changes: 5 additions & 4 deletions discrete_optimization/coloring/coloring_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@
# LICENSE file in the root directory of this source tree.

import os
from typing import Any, Dict, Hashable, List, Optional, Tuple
from collections.abc import Hashable
from typing import Any, Optional

from discrete_optimization.coloring.coloring_model import ColoringProblem
from discrete_optimization.datasets import get_data_home
Expand All @@ -12,7 +13,7 @@

def get_data_available(
data_folder: Optional[str] = None, data_home: Optional[str] = None
) -> List[str]:
) -> list[str]:
"""Get datasets available for coloring.
Params:
Expand Down Expand Up @@ -49,8 +50,8 @@ def parse(input_data: str) -> ColoringProblem:
first_line = lines[0].split()
node_count = int(first_line[0])
edge_count = int(first_line[1])
edges: List[Tuple[Hashable, Hashable, Dict[str, Any]]] = []
nodes: List[Tuple[Hashable, Dict[str, Any]]] = [(i, {}) for i in range(node_count)]
edges: list[tuple[Hashable, Hashable, dict[str, Any]]] = []
nodes: list[tuple[Hashable, dict[str, Any]]] = [(i, {}) for i in range(node_count)]
for i in range(1, edge_count + 1):
line = lines[i]
parts = line.split()
Expand Down
16 changes: 8 additions & 8 deletions discrete_optimization/coloring/coloring_solvers.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.

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

from discrete_optimization.coloring.solvers.coloring_asp_solver import ColoringASPSolver
from discrete_optimization.coloring.solvers.coloring_cp_solvers import (
Expand Down Expand Up @@ -46,7 +46,7 @@
ResultStorage,
)

solvers: Dict[str, List[Tuple[Type[SolverColoring], Dict[str, Any]]]] = {
solvers: dict[str, list[tuple[type[SolverColoring], dict[str, Any]]]] = {
"lp": [
(
ColoringLP,
Expand Down Expand Up @@ -92,13 +92,13 @@
for solver, param in solvers[key]:
solvers_map[solver] = (key, param)

solvers_compatibility: Dict[Type[SolverColoring], List[Type[Problem]]] = {}
solvers_compatibility: dict[type[SolverColoring], list[type[Problem]]] = {}
for x in solvers:
for y in solvers[x]:
solvers_compatibility[y[0]] = [ColoringProblem]


def look_for_solver(domain: "ColoringProblem") -> List[Type[SolverColoring]]:
def look_for_solver(domain: "ColoringProblem") -> list[type[SolverColoring]]:
"""Given an instance of ColoringProblem, return a list of class of solvers.
Expand All @@ -112,8 +112,8 @@ def look_for_solver(domain: "ColoringProblem") -> List[Type[SolverColoring]]:


def look_for_solver_class(
class_domain: Type[ColoringProblem],
) -> List[Type[SolverColoring]]:
class_domain: type[ColoringProblem],
) -> list[type[SolverColoring]]:
"""Given a class domain, return a list of class of solvers.
Expand All @@ -130,7 +130,7 @@ def look_for_solver_class(


def solve(
method: Type[SolverColoring], problem: ColoringProblem, **kwargs: Any
method: type[SolverColoring], problem: ColoringProblem, **kwargs: Any
) -> ResultStorage:
"""Solve a coloring instance with a given class of solver.
Expand All @@ -151,7 +151,7 @@ def solve(


def return_solver(
method: Type[SolverColoring], problem: ColoringProblem, **kwargs: Any
method: type[SolverColoring], problem: ColoringProblem, **kwargs: Any
) -> SolverColoring:
"""Return the solver initialized with the coloring problem instance
Expand Down
5 changes: 3 additions & 2 deletions discrete_optimization/coloring/coloring_toolbox.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,15 @@
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.

from typing import Hashable, List, Optional, Tuple
from collections.abc import Hashable
from typing import Optional

import networkx as nx


def compute_cliques(
g: nx.Graph, nb_max: Optional[int] = None
) -> Tuple[List[List[Hashable]], bool]:
) -> tuple[list[list[Hashable]], bool]:
"""Compute nb_max cliques for a given graph (possibly a graph from a coloring model).
A clique of a graph is a subset of nodes that are all adjacent to each other.
Expand Down
4 changes: 2 additions & 2 deletions discrete_optimization/coloring/solvers/coloring_asp_solver.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
# LICENSE file in the root directory of this source tree.
import logging
import os
from typing import Any, List, Optional
from typing import Any, Optional

import clingo

Expand Down Expand Up @@ -130,7 +130,7 @@ def constrained_data_input(self):
s += f"fixed_color({index_node+1}, c_{value}). "
return s

def compute_clever_colors_map(self, colors_name: List[str]):
def compute_clever_colors_map(self, colors_name: list[str]):
colors_to_protect = set()
colors_to_index = {}
if self.problem.has_constraints_coloring:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,9 @@
# LICENSE file in the root directory of this source tree.

import random
from collections.abc import Iterable
from enum import Enum
from typing import Any, Iterable, Optional
from typing import Any, Optional

from minizinc import Instance

Expand Down
7 changes: 4 additions & 3 deletions discrete_optimization/coloring/solvers/coloring_cp_solvers.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,9 @@

import logging
import os
from collections.abc import Iterable
from enum import Enum
from typing import Any, Dict, Iterable, Optional
from typing import Any, Optional

import networkx as nx
import pymzn
Expand Down Expand Up @@ -99,7 +100,7 @@ def __init__(
self.graph = self.problem.graph
self.g = None
self.cp_solver_name = cp_solver_name
self.dict_datas: Optional[Dict[str, Any]] = None
self.dict_datas: Optional[dict[str, Any]] = None

def init_model(self, **kwargs: Any) -> None:
"""Instantiate a minizinc model with the coloring problem data.
Expand Down Expand Up @@ -182,7 +183,7 @@ def export_dzn(
Args:
file_name (str): file path where to dump the data file
keys (List[str]): list of input data names to dump.
keys (list[str]): list of input data names to dump.
Returns: None
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from enum import Enum
from typing import Any, Dict, List, Optional, Union
from typing import Any, Optional, Union

from ortools.sat.python.cp_model import CpModel, CpSolverSolutionCallback, IntVar

Expand Down Expand Up @@ -66,7 +66,7 @@ def __init__(
):
super().__init__(problem, params_objective_function, **kwargs)
self.modeling: Optional[ModelingCPSat] = None
self.variables: Dict[str, Union[List[IntVar], List[Dict[int, IntVar]]]] = {}
self.variables: dict[str, Union[list[IntVar], list[dict[int, IntVar]]]] = {}

def retrieve_solution(self, cpsolvercb: CpSolverSolutionCallback) -> Solution:
if self.modeling == ModelingCPSat.INTEGER:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,9 @@
# LICENSE file in the root directory of this source tree.

import random
from collections.abc import Iterable
from enum import Enum
from typing import Any, Iterable
from typing import Any

from discrete_optimization.coloring.coloring_model import (
ColoringProblem,
Expand Down
Loading

0 comments on commit c9d42cc

Please sign in to comment.