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.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("DEBUG")
kaiwu.common.recursive_dict_conversion(qubo_expr)#

Turn the expression into a dict.

Args:

qubo_expr (QUBO): Qubo Expression

Returns:

DICT: Set of Hamiltonians.

Examples:
>>> import numpy as np
>>> import kaiwu as kw
>>> a, b, c = kw.qubo.Binary('a'), kw.qubo.Binary('b'), kw.qubo.Binary('c')
>>> y = (a + 2 * b) * (a * 3 + c) * 0.5 / 2
>>> y_dict = kw.common.recursive_dict_conversion(y)
>>> y_dict  
{'coefficient': {('bb', 'bc'): 0.5, ('ba', 'bb'): 1.5, ('ba', 'bc'): 0.25, ('ba', 'ba'): 0.75},
'offset': 0.0, 'hobo_var_dict': {}, 'hobo_constraint': {}}
class kaiwu.common.CheckpointManager#

Bases: object

Manage checkpoints, save the running status of objects, and use them to resume running at subsequent breakpoints. By setting CheckpointManager.save_dir, you can specify the checkpoint save directory.

Args:

save_dir (str): Save directory for checkpoint.

save_dir = None#
classmethod get_path(obj)#

Get the path to the object checkpoint

Args:

Obj (Object): saved object

Returns:

Str: checkpoint path

classmethod load(obj)#

Loading serialized objects

Args:

Obj (Object): saved object

Returns:

Object of the form str: json dict

classmethod dump(obj)#

Objects are serialized and stored on disk

Args:

Obj (Object): saved object

Returns:

None

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

Bases: JsonSerializableMixin

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: Target optimization function, stop when reached, default value is - math.in

no_improve_limit: Convergence condition, stop if the specified number of updates does not improve, the default value is 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: Target optimization function, stop when reached, default value is - math.in

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)#

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

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.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: object

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

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