Utilities

The Result class encapsulates the output of the solution process.

class Result(best_solution: Set[int] = <factory>, best_obj_value: float = inf, num_iterations: int = 0, runtime: float = 0.0, best_found_at_time: float = 0.0, stats: 'Statistics' | None = None)[source]

Container for the results of a Critical Node Problem solver run.

This dataclass stores all relevant information about an algorithm execution, including the best solution found, associated metrics, and optional detailed statistics collected during the search process.

The result object is returned by Model.solve() and MemeticSearch.run().

Examples

Access result properties:

>>> result = model.solve("CNP", 5, MaxIterations(100))
>>> print(f"Removed nodes: {result.best_solution}")
>>> print(f"Connectivity after removal: {result.best_obj_value}")
>>> print(f"Iterations: {result.num_iterations}")

Check statistics if available:

>>> if result.stats:
...     df = result.stats.to_dataframe()
...     df.plot(x="iteration", y="best_obj_value")
visualize_graph(problem_data: ProblemData, critical_nodes_set: Set[int] | List[int], filename: str = 'interactive_graph.html') str[source]

Generate interactive graph visualization HTML file and open it automatically.

Parameters:
  • problem_data (ProblemData) – ProblemData object containing graph nodes and edges information.

  • critical_nodes_set (set or list) – Critical nodes set.

  • filename (str, default="interactive_graph.html") – Output HTML filename.

Returns:

Absolute path of the generated HTML file.

Return type:

str

Raises:

ImportError – If the pyvis library is not installed.

class Statistics(collect_stats: bool = True)[source]

Collects and manages statistics during a MemeticSearch run.

The Statistics class provides functionality to record runtime, best objective value, population size, and idle generation counts for each iteration of the memetic algorithm.

data

List of iteration statistics collected during the search.

Type:

List[_IterationStats]

num_iterations

Total number of iterations recorded.

Type:

int

Examples

>>> from pycnp import Statistics
>>> stats = Statistics(collect_stats=True)
>>> # During search...
>>> stats.collect(best_obj_value=100.5, population_size=10, num_idle_generations=0)
>>> stats.collect(best_obj_value=98.2, population_size=10, num_idle_generations=0)
>>> print(f"Iterations: {stats.num_iterations}")
Iterations: 2
is_collecting() bool[source]

Returns whether statistics are being collected.

Returns:

True if statistics are being collected, False otherwise.

Return type:

bool

collect(best_obj_value: float, population_size: int, num_idle_generations: int)[source]

Collects statistics for the current iteration.

Parameters:
  • best_obj_value (float) – The best objective value found in the current iteration.

  • population_size (int) – The current population size.

  • num_idle_generations (int) – The number of idle generations (no improvement).

Exceptions module.

Provides custom exception and warning classes for the PyCNP package.

These exceptions are raised when invalid or unsupported parameters are provided to various functions and classes in the package.

Classes

InvalidProblemTypeError

Raised when an unsupported problem type is provided.

InvalidSearchStrategyError

Raised when an unsupported search strategy is provided.

exception InvalidProblemTypeError[source]

Exception raised when an unsupported problem type is provided.

This error is typically raised by pycnp.validation.validate_problem_type() when the provided problem type is not "CNP" or "DCNP".

Examples

>>> from pycnp.exceptions import InvalidProblemTypeError
>>> raise InvalidProblemTypeError("Unsupported problem type: TEST")
InvalidProblemTypeError: Unsupported problem type: TEST
exception InvalidSearchStrategyError[source]

Exception raised when an unsupported search strategy is provided.

This error is typically raised by pycnp.validation.validate_search_strategy() when the provided search strategy is not one of "CBNS", "CHNS", "DLAS", or "BCLS".

Examples

>>> from pycnp.exceptions import InvalidSearchStrategyError
>>> raise InvalidSearchStrategyError("Unsupported search strategy: ABC")
InvalidSearchStrategyError: Unsupported search strategy: ABC