openjij#

Subpackages#

Submodules#

Package Contents#

Classes#

CSQASampler

Sampler with continuous-time simulated quantum annealing (CSQA) using

Response

Samples and any other data returned by dimod samplers.

SASampler

Sampler with Simulated Annealing (SA).

SQASampler

Sampler with Simulated Quantum Annealing (SQA).

Functions#

BinaryPolynomialModel(*args, **kwargs)

BinaryQuadraticModel(linear, quadratic, *args, **kwargs)

Generate BinaryQuadraticModel object.

cast_vartype(vartype)

convert_response(response)

solver_benchmark(solver, time_list[, solutions, args, ...])

Calculate 'success probability', 'TTS', 'Residual energy','Standard Error' with computation time

Attributes#

BINARY

SPIN

Vartype

class openjij.CSQASampler(beta=5.0, gamma=1.0, num_sweeps=1000, schedule=None, num_reads=1)[source]#

Bases: openjij.sampler.sqa_sampler.SQASampler

Inheritance diagram of openjij.CSQASampler

Sampler with continuous-time simulated quantum annealing (CSQA) using

Hamiltonian.

H(s)=sHp+Γ(1s)iσixH(s) = s H_p + \Gamma (1-s)\sum_i \sigma_i^x

where HpH_p is the problem Hamiltonian we want to solve.

Parameters
  • beta (float) – Inverse temperature.

  • gamma (float) – Amplitude of quantum fluctuation.

  • schedule (list) – schedule list

  • step_num (int) – Number of Monte Carlo step.

  • schedule_info (dict) – Information about a annealing schedule.

  • num_reads (int) – Number of iterations.

  • num_sweeps (int) – number of sweeps

  • schedule_info – Information about a annealing schedule.

property parameters#

Parameters as a dict, where keys are keyword parameters accepted by the sampler methods and values are lists of the properties relevent to each parameter.

properties#
remove_unknown_kwargs(**kwargs) Dict[str, Any]#

Remove with warnings any keyword arguments not accepted by the sampler.

Parameters

**kwargs – Keyword arguments to be validated.

Return type

Dict[str, Any]

Returns: Updated kwargs dict.

Examples

>>> import warnings
>>> sampler = dimod.RandomSampler()
>>> with warnings.catch_warnings():
...     warnings.filterwarnings('ignore')
...     try:
...         sampler.remove_unknown_kwargs(num_reads=10, non_param=3)
...     except dimod.exceptions.SamplerUnknownArgWarning:
...        pass
{'num_reads': 10}
sample(bqm: Union[openjij.model.model.BinaryQuadraticModel, dimod.BinaryQuadraticModel], beta: Optional[float] = None, gamma: Optional[float] = None, num_sweeps: Optional[int] = None, schedule: Optional[list] = None, trotter: Optional[int] = None, num_reads: Optional[int] = None, initial_state: Optional[Union[list, dict]] = None, updater: Optional[str] = None, sparse: Optional[bool] = None, reinitialize_state: Optional[bool] = None, seed: Optional[int] = None) Response#

Sampling from the Ising model.

Parameters
  • bqm (openjij.BinaryQuadraticModel) –

  • beta (float, optional) – inverse tempareture.

  • gamma (float, optional) – strangth of transverse field. Defaults to None.

  • num_sweeps (int, optional) – number of sweeps. Defaults to None.

  • schedule (list[list[float, int]], optional) – List of annealing parameter. Defaults to None.

  • trotter (int) – Trotter number.

  • num_reads (int, optional) – number of sampling. Defaults to 1.

  • initial_state (list[int], optional) – Initial state. Defaults to None.

  • updater (str, optional) – update method. Defaults to ‘single spin flip’.

  • sparse (bool) – use sparse matrix or not.

  • reinitialize_state (bool, optional) – Re-initilization at each sampling. Defaults to True.

  • seed (int, optional) – Sampling seed. Defaults to None.

Raises

ValueError

Returns

results

Return type

openjij.sampler.response.Response

Examples

for Ising case:

>>> h = {0: -1, 1: -1, 2: 1, 3: 1}
>>> J = {(0, 1): -1, (3, 4): -1}
>>> sampler = openjij.SQASampler()
>>> res = sampler.sample_ising(h, J)

for QUBO case:

>>> Q = {(0, 0): -1, (1, 1): -1, (2, 2): 1, (3, 3): 1, (4, 4): 1, (0, 1): -1, (3, 4): 1}
>>> sampler = openjij.SQASampler()
>>> res = sampler.sample_qubo(Q)
sample_ising(h, J, beta=None, gamma=None, num_sweeps=None, schedule=None, num_reads=None, initial_state=None, updater=None, reinitialize_state=True, seed=None)[source]#

Sampling from the Ising model.

Parameters
  • h (dict) – linear biases

  • J (dict) – quadratic biases

  • beta (float, optional) – inverse temperature

  • gamma (float, optional) – strength of transverse field

  • num_sweeps (int, optional) – number of sampling.

  • schedule (list, optional) – schedule list

  • num_reads (int, optional) – number of iterations

  • initial_state (optional) – initial state of spins

  • updater (str, optional) – updater algorithm

  • reinitialize_state (bool, optional) – Re-initilization at each sampling. Defaults to True.

  • seed (int, optional) – Sampling seed.

Returns

results

Return type

openjij.sampler.response.Response

Examples

for Ising case:

>>> h = {0: -1, 1: -1, 2: 1, 3: 1}
>>> J = {(0, 1): -1, (3, 4): -1}
>>> sampler = openjij.CSQASampler()
>>> res = sampler.sample_ising(h, J)

for QUBO case:

>>> Q = {(0, 0): -1, (1, 1): -1, (2, 2): 1, (3, 3): 1, (4, 4): 1, (0, 1): -1, (3, 4): 1}
>>> sampler = openjijj.CSQASampler()
>>> res = sampler.sample_qubo(Q)
sample_qubo(Q, **parameters)#

Sample from a QUBO model using the implemented sample method.

Parameters

Q (dict or numpy.ndarray) – Coefficients of a quadratic unconstrained binary optimization

Returns

results

Return type

openjij.sampler.response.Response

class openjij.Response(record, variables, info, vartype)[source]#

Bases: dimod.SampleSet

Inheritance diagram of openjij.Response

Samples and any other data returned by dimod samplers.

Parameters
  • record (:obj:`numpy.recarray`) – A NumPy record array. Must have ‘sample’, ‘energy’ and ‘num_occurrences’ as fields. The ‘sample’ field should be a 2D NumPy array where each row is a sample and each column represents the value of a variable.

  • variables (iterable) – An iterable of variable labels, corresponding to columns in record.samples.

  • info (dict) – Information about the SampleSet as a whole, formatted as a dict.

  • vartype (:class:.Vartype`/str/set`) –

    Variable type for the SampleSet. Accepted input values:

    • Vartype.SPIN, 'SPIN', {-1, 1}

    • Vartype.BINARY, 'BINARY', {0, 1}

    • ExtendedVartype.DISCRETE, 'DISCRETE'

Examples

This example creates a SampleSet out of a samples_like object (a NumPy array).

>>> import numpy as np
...
>>> sampleset =  dimod.SampleSet.from_samples(np.ones(5, dtype='int8'),
...                                           'BINARY', 0)
>>> sampleset.variables
Variables([0, 1, 2, 3, 4])
property data_vectors#

The per-sample data in a vector.

Returns

A dict where the keys are the fields in the record and the values are the corresponding arrays.

Return type

dict

Examples

>>> sampleset = dimod.SampleSet.from_samples([[-1, 1], [1, 1]], dimod.SPIN,
                                             energy=[-1, 1])
>>> sampleset.data_vectors['energy']
array([-1,  1])

Note that this is equivalent to, and less performant than:

>>> sampleset = dimod.SampleSet.from_samples([[-1, 1], [1, 1]], dimod.SPIN,
                                             energy=[-1, 1])
>>> sampleset.record['energy']
array([-1,  1])
property energies#
property first#

Sample with the lowest-energy.

Raises

ValueError – If empty.

Example

>>> sampleset = dimod.ExactSolver().sample_ising({'a': 1}, {('a', 'b'): 1})
>>> sampleset.first
Sample(sample={'a': -1, 'b': 1}, energy=-2.0, num_occurrences=1)
property indices#
property info#

Dict of information about the SampleSet as a whole.

Examples

This example shows the type of information that might be returned by a dimod sampler by submitting a BQM that sets a value on a D-Wave system’s first listed coupler.

>>> from dwave.system import DWaveSampler    
>>> sampler = DWaveSampler()    
>>> bqm = dimod.BQM({}, {sampler.edgelist[0]: -1}, 0, dimod.SPIN)   
>>> sampler.sample(bqm).info   
{'timing': {'qpu_sampling_time': 315,
 'qpu_anneal_time_per_sample': 20,
 'qpu_readout_time_per_sample': 274,
 # Snipped above response for brevity
property min_samples#
property record#

numpy.recarray containing the samples, energies, number of occurences, and other sample data.

Examples

>>> sampler = dimod.ExactSolver()
>>> sampleset = sampler.sample_ising({'a': -0.5, 'b': 1.0}, {('a', 'b'): -1.0})
>>> sampleset.record.sample     
array([[-1, -1],
       [ 1, -1],
       [ 1,  1],
       [-1,  1]], dtype=int8)
>>> len(sampleset.record.energy)
4
property states#
property variables#

Variables of variable labels.

Corresponds to columns of the sample field of SampleSet.record.

property vartype#

Vartype of the samples.

aggregate()#

Create a new SampleSet with repeated samples aggregated.

Returns

SampleSet

Note

SampleSet.record.num_occurrences are accumulated but no other fields are.

Examples

This examples aggregates a sample set with two identical samples out of three.

>>> sampleset = dimod.SampleSet.from_samples([[0, 0, 1], [0, 0, 1],
...                                           [1, 1, 1]],
...                                           dimod.BINARY,
...                                           [0, 0, 1])
>>> print(sampleset)
   0  1  2 energy num_oc.
0  0  0  1      0       1
1  0  0  1      0       1
2  1  1  1      1       1
['BINARY', 3 rows, 3 samples, 3 variables]
>>> print(sampleset.aggregate())
   0  1  2 energy num_oc.
0  0  0  1      0       2
1  1  1  1      1       1
['BINARY', 2 rows, 3 samples, 3 variables]
append_variables(samples_like, sort_labels=True)#

Deprecated in favor of dimod.append_variables.

change_vartype(vartype, energy_offset=0.0, inplace=True)#

Return the SampleSet with the given vartype.

Parameters
  • vartype (:class:.Vartype`/str/set`) –

    Variable type to use for the new SampleSet. Accepted input values:

    • Vartype.SPIN, 'SPIN', {-1, 1}

    • Vartype.BINARY, 'BINARY', {0, 1}

  • energy_offset (number, optional, defaul=0.0) – Constant value applied to the ‘energy’ field of SampleSet.record.

  • inplace (bool, optional, default=True) – If True, the instantiated SampleSet is updated; otherwise, a new SampleSet is returned.

Returns

SampleSet with changed vartype. If inplace is True, returns itself.

Return type

SampleSet

Notes

This function is non-blocking unless inplace==True, in which case the sample set is resolved.

Examples

This example creates a binary copy of a spin-valued SampleSet.

>>> sampleset = dimod.ExactSolver().sample_ising({'a': -0.5, 'b': 1.0}, {('a', 'b'): -1})
>>> sampleset_binary = sampleset.change_vartype(dimod.BINARY, energy_offset=1.0, inplace=False)
>>> sampleset_binary.vartype is dimod.BINARY
True
>>> sampleset_binary.first.sample
{'a': 0, 'b': 0}
copy()#

Create a shallow copy.

data(fields=None, sorted_by='energy', name='Sample', reverse=False, sample_dict_cast=True, index=False)#

Iterate over the data in the SampleSet.

Parameters
  • fields (list, optional, default=None) – If specified, only these fields are included in the yielded tuples. The special field name ‘sample’ can be used to view the samples.

  • sorted_by (str/None, optional, default='energy') – Selects the record field used to sort the samples. If None, the samples are yielded in record order.

  • name (str/None, optional, default='Sample') – Name of the yielded namedtuples or None to yield regular tuples.

  • reverse (bool, optional, default=False) – If True, yield in reverse order.

  • sample_dict_cast (bool, optional, default=True) – Samples are returned as dicts rather than SampleView, which requires heavy memory usage. Set to False to reduce load on memory.

  • index (bool, optional, default=False) – If True, datum.idx gives the corresponding index of the SampleSet.record.

Yields

namedtuple/tuple – The data in the SampleSet, in the order specified by the input fields.

Examples

>>> sampleset = dimod.ExactSolver().sample_ising({'a': -0.5, 'b': 1.0}, {('a', 'b'): -1})
>>> for datum in sampleset.data(fields=['sample', 'energy']):   
...     print(datum)
Sample(sample={'a': -1, 'b': -1}, energy=-1.5)
Sample(sample={'a': 1, 'b': -1}, energy=-0.5)
Sample(sample={'a': 1, 'b': 1}, energy=-0.5)
Sample(sample={'a': -1, 'b': 1}, energy=2.5)
>>> for energy, in sampleset.data(fields=['energy'], sorted_by='energy'):
...     print(energy)
...
-1.5
-0.5
-0.5
2.5
>>> print(next(sampleset.data(fields=['energy'], name='ExactSolverSample')))
ExactSolverSample(energy=-1.5)
done()#

Return True if a pending computation is done.

Used when a SampleSet is constructed with SampleSet.from_future().

Examples

This example uses a Future object directly. Typically a Executor sets the result of the future (see documentation for concurrent.futures).

>>> from concurrent.futures import Future
...
>>> future = Future()
>>> sampleset = dimod.SampleSet.from_future(future)
>>> future.done()
False
>>> future.set_result(dimod.ExactSolver().sample_ising({0: -1}, {}))
>>> future.done()
True
>>> sampleset.first.energy
-1.0
filter(pred: Callable[[Any], bool]) SampleSet#

Return a new sampleset with rows filtered by the given predicate.

Parameters

pred (Callable[[Any], bool]) – A function that accepts a named tuple as returned by data() and returns a bool.

Returns

A new sample set with only the data rows for which pred returns True.

Return type

SampleSet

Examples

>>> sampleset = dimod.SampleSet.from_samples(
...     [{'a': 1, 'b': 0}, {'a': 0, 'b': 1}],
...     vartype=dimod.BINARY,
...     energy=[0, 1],
...     is_feasible=[True, False]
...     )
>>> feasible_sampleset = sampleset.filter(lambda d: d.is_feasible)
>>> print(feasible_sampleset)
   a  b energy num_oc. is_fea.
0  1  0      0       1    True
['BINARY', 1 rows, 1 samples, 2 variables]
classmethod from_future(future, result_hook=None)#

Construct a SampleSet referencing the result of a future computation.

Parameters
  • future (object) – Object that contains or will contain the information needed to construct a SampleSet. If future has a done() method, this determines the value returned by SampleSet.done().

  • result_hook (callable, optional) –

    A function that is called to resolve the future. Must accept the future and return a SampleSet. If not provided, set to

    def result_hook(future):
        return future.result()
    

Returns

SampleSet

Notes

The future is resolved on the first read of any of the SampleSet properties.

Examples

Run a dimod sampler on a single thread and load the returned future into SampleSet.

>>> from concurrent.futures import ThreadPoolExecutor
...
>>> bqm = dimod.BinaryQuadraticModel.from_ising({}, {('a', 'b'): -1})
>>> with ThreadPoolExecutor(max_workers=1) as executor:
...     future = executor.submit(dimod.ExactSolver().sample, bqm)
...     sampleset = dimod.SampleSet.from_future(future)
>>> sampleset.first.energy    
classmethod from_samples(samples_like, vartype, energy, info=None, num_occurrences=None, aggregate_samples=False, sort_labels=True, **vectors)#

Build a SampleSet from raw samples.

Parameters
  • samples_like – A collection of raw samples. ‘samples_like’ is an extension of NumPy’s array_like. See as_samples().

  • vartype (:class:.Vartype`/str/set`) –

    Variable type for the SampleSet. Accepted input values:

    • Vartype.SPIN, 'SPIN', {-1, 1}

    • Vartype.BINARY, 'BINARY', {0, 1}

    • ExtendedVartype.DISCRETE, 'DISCRETE'

  • energy (array_like) – Vector of energies.

  • info (dict, optional) – Information about the SampleSet as a whole formatted as a dict.

  • num_occurrences (array_like, optional) – Number of occurrences for each sample. If not provided, defaults to a vector of 1s.

  • aggregate_samples (bool, optional, default=False) – If True, all samples in returned SampleSet are unique, with num_occurrences accounting for any duplicate samples in samples_like.

  • sort_labels (bool, optional, default=True) – Return SampleSet.variables in sorted order. For mixed (unsortable) types, the given order is maintained.

  • **vectors (array_like) – Other per-sample data.

Returns

SampleSet

Examples

This example creates a SampleSet out of a samples_like object (a dict).

>>> import numpy as np
...
>>> sampleset = dimod.SampleSet.from_samples(
...   dimod.as_samples({'a': 0, 'b': 1, 'c': 0}), 'BINARY', 0)
>>> sampleset.variables
Variables(['a', 'b', 'c'])
classmethod from_samples_bqm(samples_like, bqm, **kwargs)#

Build a sample set from raw samples and a binary quadratic model.

The binary quadratic model is used to calculate energies and set the vartype.

Parameters
  • samples_like – A collection of raw samples. ‘samples_like’ is an extension of NumPy’s array_like. See as_samples().

  • bqm (:obj:.BinaryQuadraticModel``) – A binary quadratic model.

  • info (dict, optional) – Information about the SampleSet as a whole formatted as a dict.

  • num_occurrences (array_like, optional) – Number of occurrences for each sample. If not provided, defaults to a vector of 1s.

  • aggregate_samples (bool, optional, default=False) – If True, all samples in returned SampleSet are unique, with num_occurrences accounting for any duplicate samples in samples_like.

  • sort_labels (bool, optional, default=True) – Return SampleSet.variables in sorted order. For mixed (unsortable) types, the given order is maintained.

  • **vectors (array_like) – Other per-sample data.

Returns

SampleSet

Examples

>>> bqm = dimod.BinaryQuadraticModel.from_ising({}, {('a', 'b'): -1})
>>> sampleset = dimod.SampleSet.from_samples_bqm({'a': -1, 'b': 1}, bqm)
classmethod from_samples_cqm(samples_like, cqm, rtol=1e-06, atol=1e-08, **kwargs)#

Build a sample set from raw samples and a constrained quadratic model.

The constrained quadratic model is used to calculate energies and feasibility.

Parameters
  • samples_like – A collection of raw samples. ‘samples_like’ is an extension of NumPy’s array_like. See as_samples().

  • cqm (:obj:.ConstrainedQuadraticModel``) – A constrained quadratic model.

  • rtol (float, optional, default=1e-6) – Relative tolerance for constraint violation. See ConstrainedQuadraticModel.check_feasible() for more information.

  • atol (float, optional, default=1e-8) – Absolute tolerance for constraint violations. See ConstrainedQuadraticModel.check_feasible() for more information.

  • info (dict, optional) – Information about the SampleSet as a whole formatted as a dict.

  • num_occurrences (array_like, optional) – Number of occurrences for each sample. If not provided, defaults to a vector of 1s.

  • aggregate_samples (bool, optional, default=False) – If True, all samples in returned SampleSet are unique, with num_occurrences accounting for any duplicate samples in samples_like.

  • sort_labels (bool, optional, default=True) – Return SampleSet.variables in sorted order. For mixed (unsortable) types, the given order is maintained.

  • **vectors (array_like) – Other per-sample data.

Returns

SampleSet

Examples

>>> cqm = dimod.ConstrainedQuadraticModel()
>>> x, y, z = dimod.Binaries(['x', 'y', 'z'])
>>> cqm.set_objective(x*y + 2*y*z)
>>> label = cqm.add_constraint(x*y == 1, label='constraint_1')
>>> sampleset = dimod.SampleSet.from_samples_cqm({'x': 0, 'y': 1, 'z': 1}, cqm)
classmethod from_serializable(obj)#

Deserialize a SampleSet.

Parameters

obj (dict) – A SampleSet serialized by to_serializable().

Returns

SampleSet

Examples

This example encodes and decodes using JSON.

>>> import json
...
>>> samples = dimod.SampleSet.from_samples([-1, 1, -1], dimod.SPIN, energy=-.5)
>>> s = json.dumps(samples.to_serializable())
>>> new_samples = dimod.SampleSet.from_serializable(json.loads(s))

See also

to_serializable()

lowest(rtol=1e-05, atol=1e-08)#

Return a sample set containing the lowest-energy samples.

A sample is included if its energy is within tolerance of the lowest energy in the sample set. The following equation is used to determine if two values are equivalent:

absolute(a - b) <= (atol + rtol * absolute(b))

See numpy.isclose() for additional details and caveats.

Parameters
  • rtol (float, optional, default=1.e-5) – The relative tolerance (see above).

  • atol (float, optional, default=1.e-8) – The absolute tolerance (see above).

Returns

A new sample set containing the lowest energy samples as delimited by configured tolerances from the lowest energy sample in the current sample set.

Return type

SampleSet

Examples

>>> sampleset = dimod.ExactSolver().sample_ising({'a': .001},
...                                              {('a', 'b'): -1})
>>> print(sampleset.lowest())
   a  b energy num_oc.
0 -1 -1 -1.001       1
['SPIN', 1 rows, 1 samples, 2 variables]
>>> print(sampleset.lowest(atol=.1))
   a  b energy num_oc.
0 -1 -1 -1.001       1
1 +1 +1 -0.999       1
['SPIN', 2 rows, 2 samples, 2 variables]

Note

“Lowest energy” is the lowest energy in the sample set. This is not always the “ground energy” which is the lowest energy possible for a binary quadratic model.

relabel_variables(mapping, inplace=True)#

Relabel the variables of a SampleSet according to the specified mapping.

Parameters
  • mapping (dict) – Mapping from current variable labels to new, as a dict. If incomplete mapping is specified, unmapped variables keep their current labels.

  • inplace (bool, optional, default=True) – If True, the current SampleSet is updated; otherwise, a new SampleSet is returned.

Returns

SampleSet with relabeled variables. If inplace is True, returns itself.

Return type

SampleSet

Notes

This function is non-blocking unless inplace==True, in which case the sample set is resolved.

Examples

This example creates a relabeled copy of a SampleSet.

>>> sampleset = dimod.ExactSolver().sample_ising({'a': -0.5, 'b': 1.0}, {('a', 'b'): -1})
>>> new_sampleset = sampleset.relabel_variables({'a': 0, 'b': 1}, inplace=False)
>>> new_sampleset.variables
Variables([0, 1])
resolve()#

Ensure that the sampleset is resolved if constructed from a future.

samples(n=None, sorted_by='energy')#

Return an iterable over the samples.

Parameters
  • n (int, optional, default=None) – Maximum number of samples to return in the view.

  • sorted_by (str/None, optional, default='energy') – Selects the record field used to sort the samples. If None, samples are returned in record order.

Returns

A view object mapping variable labels to values.

Return type

SamplesArray

Examples

>>> sampleset = dimod.ExactSolver().sample_ising({'a': 0.1, 'b': 0.0},
...                                              {('a', 'b'): 1})
>>> for sample in sampleset.samples():   
...     print(sample)
{'a': -1, 'b': 1}
{'a': 1, 'b': -1}
{'a': -1, 'b': -1}
{'a': 1, 'b': 1}
>>> sampleset = dimod.ExactSolver().sample_ising({'a': 0.1, 'b': 0.0},
...                                              {('a', 'b'): 1})
>>> samples = sampleset.samples()
>>> samples[0]
{'a': -1, 'b': 1}
>>> samples[0, 'a']
-1
>>> samples[0, ['b', 'a']]
array([ 1, -1], dtype=int8)
>>> samples[1:, ['a', 'b']]
array([[ 1, -1],
       [-1, -1],
       [ 1,  1]], dtype=int8)
slice(*slice_args, **kwargs)#

Create a new sample set with rows sliced according to standard Python slicing syntax.

Parameters
  • start (int, optional, default=None) – Start index for slice.

  • stop (int) – Stop index for slice.

  • step (int, optional, default=None) – Step value for slice.

  • sorted_by (str/None, optional, default='energy') – Selects the record field used to sort the samples before slicing. Note that sorted_by determines the sample order in the returned sample set.

Returns

SampleSet

Examples

>>> import numpy as np
...
>>> sampleset = dimod.SampleSet.from_samples(np.diag(range(1, 11)),
...                   dimod.BINARY, energy=range(10))
>>> print(sampleset)
   0  1  2  3  4  5  6  7  8  9 energy num_oc.
0  1  0  0  0  0  0  0  0  0  0      0       1
1  0  1  0  0  0  0  0  0  0  0      1       1
2  0  0  1  0  0  0  0  0  0  0      2       1
3  0  0  0  1  0  0  0  0  0  0      3       1
4  0  0  0  0  1  0  0  0  0  0      4       1
5  0  0  0  0  0  1  0  0  0  0      5       1
6  0  0  0  0  0  0  1  0  0  0      6       1
7  0  0  0  0  0  0  0  1  0  0      7       1
8  0  0  0  0  0  0  0  0  1  0      8       1
9  0  0  0  0  0  0  0  0  0  1      9       1
['BINARY', 10 rows, 10 samples, 10 variables]

The above example’s first 3 samples by energy == truncate(3):

>>> print(sampleset.slice(3))
   0  1  2  3  4  5  6  7  8  9 energy num_oc.
0  1  0  0  0  0  0  0  0  0  0      0       1
1  0  1  0  0  0  0  0  0  0  0      1       1
2  0  0  1  0  0  0  0  0  0  0      2       1
['BINARY', 3 rows, 3 samples, 10 variables]

The last 3 samples by energy:

>>> print(sampleset.slice(-3, None))
   0  1  2  3  4  5  6  7  8  9 energy num_oc.
0  0  0  0  0  0  0  0  1  0  0      7       1
1  0  0  0  0  0  0  0  0  1  0      8       1
2  0  0  0  0  0  0  0  0  0  1      9       1
['BINARY', 3 rows, 3 samples, 10 variables]

Every second sample in between, skipping top and bottom 3:

>>> print(sampleset.slice(3, -3, 2))
   0  1  2  3  4  5  6  7  8  9 energy num_oc.
0  0  0  0  1  0  0  0  0  0  0      3       1
1  0  0  0  0  0  1  0  0  0  0      5       1
['BINARY', 2 rows, 2 samples, 10 variables]
to_pandas_dataframe(sample_column=False)#

Convert a sample set to a Pandas DataFrame.

Parameters

sample_column (bool, optional, default=False) – If True, samples are represented as a column of type dict.

Returns

pandas.DataFrame.

Examples

>>> samples = dimod.SampleSet.from_samples([{'a': -1, 'b': +1, 'c': -1},
...                                         {'a': -1, 'b': -1, 'c': +1}],
...                                        dimod.SPIN, energy=-.5)
>>> samples.to_pandas_dataframe()    
   a  b  c  energy  num_occurrences
0 -1  1 -1    -0.5                1
1 -1 -1  1    -0.5                1
>>> samples.to_pandas_dataframe(sample_column=True)    
                       sample  energy  num_occurrences
0  {'a': -1, 'b': 1, 'c': -1}    -0.5                1
1  {'a': -1, 'b': -1, 'c': 1}    -0.5                1

Note that sample sets can be constructed to contain data structures incompatible with the target Pandas format.

to_serializable(use_bytes=False, bytes_type=bytes, pack_samples=True)#

Convert a SampleSet to a serializable object.

Note that the contents of the SampleSet.info field are assumed to be serializable.

Parameters
  • use_bytes (bool, optional, default=False) – If True, a compact representation of the biases as bytes is used.

  • bytes_type (class, optional, default=bytes) – If use_bytes is True, this class is used to wrap the bytes objects in the serialization. Useful for Python 2 using BSON encoding, which does not accept the raw bytes type; bson.Binary can be used instead.

  • pack_samples (bool, optional, default=True) – Pack the samples using 1 bit per sample. Samples are never packed when SampleSet.vartype is ~ExtendedVartype.DISCRETE.

Returns

Object that can be serialized.

Return type

dict

Examples

This example encodes using JSON.

>>> import json
...
>>> samples = dimod.SampleSet.from_samples([-1, 1, -1], dimod.SPIN, energy=-.5)
>>> s = json.dumps(samples.to_serializable())

See also

from_serializable()

truncate(n, sorted_by='energy')#

Create a new sample set with up to n rows.

Parameters
  • n (int) – Maximum number of rows in the returned sample set. Does not return any rows above this limit in the original sample set.

  • sorted_by (str/None, optional, default='energy') – Selects the record field used to sort the samples before truncating. Note that this sort order is maintained in the returned sample set.

Returns

SampleSet

Examples

>>> import numpy as np
...
>>> sampleset = dimod.SampleSet.from_samples(np.ones((5, 5)), dimod.SPIN, energy=5)
>>> print(sampleset)
   0  1  2  3  4 energy num_oc.
0 +1 +1 +1 +1 +1      5       1
1 +1 +1 +1 +1 +1      5       1
2 +1 +1 +1 +1 +1      5       1
3 +1 +1 +1 +1 +1      5       1
4 +1 +1 +1 +1 +1      5       1
['SPIN', 5 rows, 5 samples, 5 variables]
>>> print(sampleset.truncate(2))
   0  1  2  3  4 energy num_oc.
0 +1 +1 +1 +1 +1      5       1
1 +1 +1 +1 +1 +1      5       1
['SPIN', 2 rows, 2 samples, 5 variables]
See:

SampleSet.slice()

class openjij.SASampler(beta_min: Optional[float] = None, beta_max: Optional[float] = None, num_sweeps: Optional[int] = None, num_reads: Optional[int] = None, schedule: Optional[list] = None)[source]#

Bases: openjij.sampler.sampler.BaseSampler

Inheritance diagram of openjij.SASampler

Sampler with Simulated Annealing (SA).

Parameters
  • beta_min (float) – Minmum beta (inverse temperature). You can overwrite in methods .sample_*.

  • beta_max (float) – Maximum beta (inverse temperature). You can overwrite in methods .sample_*.

  • num_reads (int) – number of sampling (algorithm) runs. defaults None. You can overwrite in methods .sample_*.

  • num_sweeps (int) – number of MonteCarlo steps during SA. defaults None. You can overwrite in methods .sample_*.

  • schedule_info (dict) – Information about an annealing schedule.

  • schedule (Optional[list]) –

Raises
  • ValueError – If schedules or variables violate as below.

  • - not list or numpy.array.

  • - not list of tuple (beta – float, step_length : int).

  • - beta is less than zero.

property parameters#

Parameters as a dict, where keys are keyword parameters accepted by the sampler methods and values are lists of the properties relevent to each parameter.

properties#
remove_unknown_kwargs(**kwargs) Dict[str, Any]#

Remove with warnings any keyword arguments not accepted by the sampler.

Parameters

**kwargs – Keyword arguments to be validated.

Return type

Dict[str, Any]

Returns: Updated kwargs dict.

Examples

>>> import warnings
>>> sampler = dimod.RandomSampler()
>>> with warnings.catch_warnings():
...     warnings.filterwarnings('ignore')
...     try:
...         sampler.remove_unknown_kwargs(num_reads=10, non_param=3)
...     except dimod.exceptions.SamplerUnknownArgWarning:
...        pass
{'num_reads': 10}
sample(bqm: Union[openj.model.model.BinaryQuadraticModel, dimod.BinaryQuadraticModel], beta_min: Optional[float] = None, beta_max: Optional[float] = None, num_sweeps: Optional[int] = None, num_reads: Optional[int] = None, schedule: Optional[list] = None, initial_state: Optional[Union[list, dict]] = None, updater: Optional[str] = None, sparse: Optional[bool] = None, reinitialize_state: Optional[bool] = None, seed: Optional[int] = None) Response[source]#

Sample Ising model.

Parameters
  • bqm (openjij.model.model.BinaryQuadraticModel) –

  • beta_min (float) – minimal value of inverse temperature

  • beta_max (float) – maximum value of inverse temperature

  • num_sweeps (int) – number of sweeps

  • num_reads (int) – number of reads

  • schedule (list) – list of inverse temperature

  • initial_state (dict) – initial state

  • updater (str) – updater algorithm

  • sparse (bool) – use sparse matrix or not.

  • reinitialize_state (bool) – if true reinitialize state for each run

  • seed (int) – seed for Monte Carlo algorithm

Returns

results

Return type

openjij.sampler.response.Response

Examples

for Ising case:

>>> h = {0: -1, 1: -1, 2: 1, 3: 1}
>>> J = {(0, 1): -1, (3, 4): -1}
>>> sampler = openj.SASampler()
>>> res = sampler.sample_ising(h, J)

for QUBO case:

>>> Q = {(0, 0): -1, (1, 1): -1, (2, 2): 1, (3, 3): 1, (4, 4): 1, (0, 1): -1, (3, 4): 1}
>>> sampler = openj.SASampler()
>>> res = sampler.sample_qubo(Q)
sample_hubo(J: Union[dict, openj.model.model.BinaryPolynomialModel, cimod.BinaryPolynomialModel], vartype: Optional[str] = None, beta_min: Optional[float] = None, beta_max: Optional[float] = None, num_sweeps: Optional[int] = None, num_reads: Optional[int] = None, schedule: Optional[list] = None, initial_state: Optional[Union[list, dict]] = None, updater: Optional[str] = None, reinitialize_state: Optional[bool] = None, seed: Optional[int] = None) Response[source]#

Sampling from higher order unconstrainted binary optimization.

Parameters
  • J (dict) – Interactions.

  • vartype (str, openjij.VarType) – “SPIN” or “BINARY”.

  • beta_min (float, optional) – Minimum beta (initial inverse temperature). Defaults to None.

  • beta_max (float, optional) – Maximum beta (final inverse temperature). Defaults to None.

  • schedule (list, optional) – schedule list. Defaults to None.

  • num_sweeps (int, optional) – number of sweeps. Defaults to None.

  • num_reads (int, optional) – number of reads. Defaults to 1.

  • init_state (list, optional) – initial state. Defaults to None.

  • reinitialize_state (bool) – if true reinitialize state for each run

  • seed (int, optional) – seed for Monte Carlo algorithm. Defaults to None.

  • initial_state (Optional[Union[list, dict]]) –

  • updater (Optional[str]) –

Returns

results

Return type

openjij.sampler.response.Response

Examples::
for Ising case::
>>> sampler = openjij.SASampler()
>>> J = {(0,): -1, (0, 1): -1, (0, 1, 2): 1}
>>> response = sampler.sample_hubo(J, "SPIN")
for Binary case::
>>> sampler = ooenjij.SASampler()
>>> J = {(0,): -1, (0, 1): -1, (0, 1, 2): 1}
>>> response = sampler.sample_hubo(J, "BINARY")
sample_ising(h, J, **parameters)#

Sample from an Ising model using the implemented sample method.

Parameters
  • h (dict) – Linear biases

  • J (dict) – Quadratic biases

Returns

results

Return type

openjij.sampler.response.Response

sample_qubo(Q, **parameters)#

Sample from a QUBO model using the implemented sample method.

Parameters

Q (dict or numpy.ndarray) – Coefficients of a quadratic unconstrained binary optimization

Returns

results

Return type

openjij.sampler.response.Response

class openjij.SQASampler(beta: Optional[float] = None, gamma: Optional[float] = None, num_sweeps: Optional[int] = None, num_reads: Optional[int] = None, schedule: Optional[list] = None, trotter: Optional[int] = None)[source]#

Bases: openjij.sampler.sampler.BaseSampler

Inheritance diagram of openjij.SQASampler

Sampler with Simulated Quantum Annealing (SQA).

Inherits from openjij.sampler.sampler.BaseSampler. Hamiltonian

H(s)=sHp+Γ(1s)iσixH(s) = s H_p + \Gamma (1-s)\sum_i \sigma_i^x

where HpH_p is the problem Hamiltonian we want to solve.

Parameters
  • beta (float) – Inverse temperature.

  • gamma (float) – Amplitude of quantum fluctuation.

  • trotter (int) – Trotter number.

  • num_sweeps (int) – number of sweeps

  • schedule (list) – schedule list

  • num_reads (int) – Number of iterations.

  • schedule_info (dict) – Information about a annealing schedule.

Raises
  • ValueError – If the schedule violates as below.

  • - not list or numpy.array.

  • - schedule range is '0 <= s <= 1'.

property parameters#

Parameters as a dict, where keys are keyword parameters accepted by the sampler methods and values are lists of the properties relevent to each parameter.

properties#
remove_unknown_kwargs(**kwargs) Dict[str, Any]#

Remove with warnings any keyword arguments not accepted by the sampler.

Parameters

**kwargs – Keyword arguments to be validated.

Return type

Dict[str, Any]

Returns: Updated kwargs dict.

Examples

>>> import warnings
>>> sampler = dimod.RandomSampler()
>>> with warnings.catch_warnings():
...     warnings.filterwarnings('ignore')
...     try:
...         sampler.remove_unknown_kwargs(num_reads=10, non_param=3)
...     except dimod.exceptions.SamplerUnknownArgWarning:
...        pass
{'num_reads': 10}
sample(bqm: Union[openjij.model.model.BinaryQuadraticModel, dimod.BinaryQuadraticModel], beta: Optional[float] = None, gamma: Optional[float] = None, num_sweeps: Optional[int] = None, schedule: Optional[list] = None, trotter: Optional[int] = None, num_reads: Optional[int] = None, initial_state: Optional[Union[list, dict]] = None, updater: Optional[str] = None, sparse: Optional[bool] = None, reinitialize_state: Optional[bool] = None, seed: Optional[int] = None) Response[source]#

Sampling from the Ising model.

Parameters
  • bqm (openjij.BinaryQuadraticModel) –

  • beta (float, optional) – inverse tempareture.

  • gamma (float, optional) – strangth of transverse field. Defaults to None.

  • num_sweeps (int, optional) – number of sweeps. Defaults to None.

  • schedule (list[list[float, int]], optional) – List of annealing parameter. Defaults to None.

  • trotter (int) – Trotter number.

  • num_reads (int, optional) – number of sampling. Defaults to 1.

  • initial_state (list[int], optional) – Initial state. Defaults to None.

  • updater (str, optional) – update method. Defaults to ‘single spin flip’.

  • sparse (bool) – use sparse matrix or not.

  • reinitialize_state (bool, optional) – Re-initilization at each sampling. Defaults to True.

  • seed (int, optional) – Sampling seed. Defaults to None.

Raises

ValueError

Returns

results

Return type

openjij.sampler.response.Response

Examples

for Ising case:

>>> h = {0: -1, 1: -1, 2: 1, 3: 1}
>>> J = {(0, 1): -1, (3, 4): -1}
>>> sampler = openjij.SQASampler()
>>> res = sampler.sample_ising(h, J)

for QUBO case:

>>> Q = {(0, 0): -1, (1, 1): -1, (2, 2): 1, (3, 3): 1, (4, 4): 1, (0, 1): -1, (3, 4): 1}
>>> sampler = openjij.SQASampler()
>>> res = sampler.sample_qubo(Q)
sample_ising(h, J, **parameters)#

Sample from an Ising model using the implemented sample method.

Parameters
  • h (dict) – Linear biases

  • J (dict) – Quadratic biases

Returns

results

Return type

openjij.sampler.response.Response

sample_qubo(Q, **parameters)#

Sample from a QUBO model using the implemented sample method.

Parameters

Q (dict or numpy.ndarray) – Coefficients of a quadratic unconstrained binary optimization

Returns

results

Return type

openjij.sampler.response.Response

openjij.BinaryPolynomialModel(*args, **kwargs)[source]#
openjij.BinaryQuadraticModel(linear, quadratic, *args, **kwargs)[source]#

Generate BinaryQuadraticModel object.

openjij.vartype#

variable type SPIN or BINARY

Type

dimod.Vartype

openjij.linear#

represents linear term

Type

dict

openjij.quadratic#

represents quadratic term

Type

dict

openjij.offset#

represents constant energy term when convert to SPIN from BINARY

Type

float

openjij.num_variables#

represents number of variables in the model

Type

int

openjij.variables#

represents variables of the binary quadratic model

Type

list

Parameters
  • linear (dict) – linear biases

  • quadratic (dict) – quadratic biases

  • offset (float) – offset

  • vartype (openjij.variable_type.Vartype) – vartype (‘SPIN’ or ‘BINARY’)

  • gpu (bool) – if true, this can be used for gpu samplers.

  • kwargs

Returns

generated BinaryQuadraticModel

Examples

BinaryQuadraticModel can be initialized by specifing h and J:

>>> h = {0: 1, 1: -2}
>>> J = {(0, 1): -1, (1, 2): -3, (2, 3): 0.5}
>>> bqm = oj.BinaryQuadraticModel(self.h, self.J)

You can also use strings and tuples of integers (up to 4 elements) as indices:

>>> h = {'a': 1, 'b': -2}
>>> J = {('a', 'b'): -1, ('b', 'c'): -3, ('c', 'd'): 0.5}
>>> bqm = oj.BinaryQuadraticModel(self.h, self.J)
openjij.cast_vartype(vartype)[source]#
openjij.convert_response(response)[source]#
openjij.solver_benchmark(solver, time_list, solutions=[], args={}, p_r=0.99, ref_energy=0, measure_with_energy=False, time_name='execution_time')[source]#

Calculate ‘success probability’, ‘TTS’, ‘Residual energy’,’Standard Error’ with computation time

Parameters
  • solver (callable) – returns openjij.Response, and solver has arguments ‘time’ and ‘**args’

  • time_list (list) –

  • solutions (list(list(int)), list(int)) – true solution or list of solution (if solutions are degenerated).

  • args (dict) – Arguments for solver.

  • p_r (float) – Thereshold probability for time to solutions.

  • ref_energy (float) – The ground (reference to calculate success probability and the residual energy) energy.

  • measure_with_energy (bool) – use a energy as measure for success

Returns

dictionary which has the following keys:

  • time: list of compuation time

  • success_prob list of success probability at each computation time

  • tts: list of time to solusion at each computation time

  • residual_energy: list of residual energy at each computation time

  • se_lower_tts: list of tts’s lower standard error at each computation time

  • se_upper_tts: list of tts’s upper standard error at each computation time

  • se_success_prob: list of success probability’s standard error at each computation time

  • se_residual_energy: list of residual_energy’s standard error at each computation time

  • info (dict): Parameter information for the benchmark

Return type

dict

openjij.BINARY#
openjij.SPIN#
openjij.Vartype[source]#