kaiwu.common package#

Module contents#

tool collection

kaiwu.common.hamiltonian(ising_matrix, c_list)#

Calculating the Hamiltonian

Args:

ising_matrix (np.ndarray): CIM Ising matrix.

c_list (np.ndarray): The set of variable combinations for which the Hamiltonian is to be computed.

Returns:

np.ndarray: Set of Hamiltonians.

Examples:
>>> import numpy as np
>>> import kaiwu as kw
>>> ising_matrix = -np.array([[ 0. ,  1. ,  0. ,  1. ,  1. ],
...                     [ 1. ,  0. ,  0. ,  1.,   1. ],
...                     [ 0. ,  0. ,  0. ,  1.,   1. ],
...                     [ 1. ,  1.,   1. ,  0. ,  1. ],
...                     [ 1. ,  1.,   1. ,  1. ,  0. ]])
>>> rng = np.random.default_rng(10)
>>> optimizer = kw.classical.SimulatedAnnealingOptimizer()
>>> output = optimizer.solve(ising_matrix)
>>> h = kw.common.hamiltonian(ising_matrix, output)
>>> h   
array([-0.60179257, -0.60179257, -0.60179257, -0.60179257, -0.60179257,
       -1.20358514, -0.60179257, -0.60179257, -0.60179257, -1.20358514])
kaiwu.common.check_symmetric(mat, tolerance=1e-08)#

Check if the matrix is a symmetric matrix, allowing for a certain margin of error.

kaiwu.common.set_log_level(level)#

Set SDK log output level

The SDK outputs logs above the info level by default, and the output level can be modified through this function

Args:

Level (str or int): supports logging. ERROR, logging.INFO,…, logging. ERROR or string ERROR, INFO,…, ERROR, case insensitive

Examples:
>>> import kaiwu as kw
>>> kw.common.set_log_level(level="DEBUG")  
kaiwu.common.set_log_path(path='/tmp/output.log')#

Set the path to the SDK log output file; an absolute path is required.

Args:

path (str): Custom log file output path

Examples:
>>> import kaiwu as kw
>>> kw.common.set_log_path("/tmp/output.log")  
class kaiwu.common.CheckpointManager#

Bases: object

Manage checkpoints, saving the running state of objects for subsequent resumption from breakpoints. The directory for saving checkpoints can be specified by setting CheckpointManager.save_dir.

Args:

save_dir (str): The directory where the checkpoint is saved.

save_dir = None#
classmethod get_path(obj)#

Get the path to the object checkpoint

Args:

obj (Object): The object to be stored

Returns:

str: checkpoint path

classmethod load(obj)#

Load serialized objects

Args:

obj (Object): The object to be stored

Returns:

str: An object in JSON dictionary format

classmethod dump(obj)#

The object is serialized and stored on the disk.

Args:

obj (Object): The object to be stored

Returns:

None

class kaiwu.common.BaseLoopController(max_repeat_step=inf, target_objective=-inf, no_improve_limit=inf, iterate_per_update=5)#

Bases: JsonSerializableMixin

A loop controller is used to calculate the time. This is for debugging and testing the algorithm.

Args:

max_repeat_step: Maximum number of steps, default value is math.inf.

target_objective: The target optimization function; optimization stops once the target is reached. The default value is -math.inf.

no_improve_limit: Convergence condition, specifies the number of updates to stop if no improvement is achieved. The default value is in math.inf.

iterate_per_update: The number of times to run before each update of the Hamiltonian, the default value is 5

update_status(objective, unsatisfied_constraints_count=None)#

Update status after calculating subissues

Args:

Objective (float): objective function value

unsatisfied_constraints_count (int): number of unmet constraints

is_finished()#

Determine whether to stop

Returns:

Bool: Should we stop?

restart()#

Reinitialize count

to_json_dict(exclude_fields=('timer',))#

Convert to JSON dictionary

Returns:

Dict: json dictionary

load_json_dict(json_dict)#

The dict recovery object read from the JSON file

Returns:

Dict: json dictionary

class kaiwu.common.OptimizerLoopController(max_repeat_step=inf, target_objective=-inf, no_improve_limit=20000, iterate_per_update=5)#

Bases: BaseLoopController

Optimizer loop controller and calculate time. For debugging and testing algorithms

Args:

max_repeat_step: Maximum number of steps, default value is math.inf.

target_objective: The target optimization function; optimization stops once the target is reached. The default value is -math.inf.

no_improve_limit: Convergence condition, stop if the specified number of updates is not improved, the default value is 20000

iterate_per_update: The number of times to run before each update of the Hamiltonian, the default value is 5

is_finished()#

Determine whether to stop

Returns:

Bool: Should we stop?

load_json_dict(json_dict)#

The dict recovery object read from the JSON file

Returns:

Dict: json dictionary

restart()#

Reinitialize count

to_json_dict(exclude_fields=('timer',))#

Convert to JSON dictionary

Returns:

Dict: json dictionary

update_status(objective, unsatisfied_constraints_count=None)#

Update status after calculating subissues

Args:

Objective (float): objective function value

unsatisfied_constraints_count (int): number of unmet constraints

class kaiwu.common.SolverLoopController(max_repeat_step=inf, target_objective=-inf, no_improve_limit=inf, iterate_per_update=5, stop_after_feasible_count=None)#

Bases: BaseLoopController, JsonSerializableMixin

Solver loop controller and calculate time. For debugging and testing algorithms

Args:

max_repeat_step (int): Maximum number of steps, default is math.inf

target_objective (float): Target optimization function, stop when reached, default value is -math.inf

no_improve_limit (int): Convergence condition, stop if the specified number of updates does not improve, the default value is 20000

iterate_per_update (int): The number of times to run before each update of the Hamiltonian, the default value is 5

stop_after_feasible_count (int): Stop after finding the specified number of feasible solutions.

update_status(objective, unsatisfied_constraints_count=None)#

Update status after calculating subissues

Args:

Objective (float): objective function value

unsatisfied_constraints_count (int): number of unmet constraints

is_finished()#

Determine whether to stop

Returns:

Bool: Should we stop?

load_json_dict(json_dict)#

The dict recovery object read from the JSON file

Returns:

Dict: json dictionary

restart()#

Reinitialize count

to_json_dict(exclude_fields=('timer',))#

Convert to JSON dictionary

Returns:

Dict: json dictionary

class kaiwu.common.JsonSerializableMixin#

Bases: object

Serializer

to_json_dict(exclude_fields=('_optimizer',))#

Convert to JSON dictionary

Returns:

Dict: json dictionary

load_json_dict(json_dict)#

The dict recovery object read from the JSON file

Returns:

Dict: json dictionary

class kaiwu.common.HeapUniquePool(mat, size, size_limit)#

Bases: JsonSerializableMixin

Solution. Use a heap for maintenance

extend(solutions)#

Insert multiple solutions

push(solution, hamilton)#

Add a solution

get_solutions()#

Returns the maintained solution, the number of which is self.size_limit

clear()#

Clear solution set

to_json_dict(exclude_fields=None)#

Convert to JSON dictionary

Returns:

Dict: json dictionary

load_json_dict(json_dict)#

Construct a HeapUniquePool object from a dictionary read from a JSON file.

Args:

json_dict (dict): json dict

Returns:

HeapUniquePool: Object instance

class kaiwu.common.ArgpartitionUniquePool(mat, size, size_limit)#

Bases: object

Solution set. Use the linear expected complexity k of argpartition to maintain

extend(solutions, final=False)#

Insert multiple solutions

get_solutions()#

Get solution set

clear()#

Clear solution set

to_json_dict()#

Convert to JSON dictionary

Returns:

Dict: json dictionary

classmethod from_json_dict(json_dict)#

Construct a HeapUniquePool object from a dictionary read from a JSON file.

Args:

json_dict (dict): json dict

Returns:

ArgpartitionUniquePool: Object instance