Skip to content

Commit

Permalink
Merge pull request #4 from psrenergy/px/qubotools-v1
Browse files Browse the repository at this point in the history
Create `DWave.Neal` Module
  • Loading branch information
pedromxavier authored Nov 15, 2023
2 parents 9a61011 + 7ed0ba1 commit db06ee9
Show file tree
Hide file tree
Showing 12 changed files with 306 additions and 34 deletions.
3 changes: 1 addition & 2 deletions CondaPkg.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ channels = ["anaconda", "conda-forge"]
python = ">=3.7,<=3.11"

[pip.deps]
# numpy = ">=1.20"
# matplotlib = ">=3.5"
numpy = ">=1.20"
dwave-ocean-sdk = "==6.4.1"
dwave_networkx = "==0.8.14"
10 changes: 8 additions & 2 deletions Project.toml
Original file line number Diff line number Diff line change
@@ -1,13 +1,19 @@
name = "DWave"
uuid = "4d534982-bf11-4157-9e48-fe3a62208a50"
authors = ["pedromxavier <[email protected]>", "pedroripper <[email protected]>"]
version = "0.4.0"
version = "0.4.1"

[deps]
Graphs = "86223c79-3864-5bf0-83f7-82e725a168b6"
MathOptInterface = "b8f27783-ece8-5eb3-8dc8-9495eed66fee"
PythonCall = "6099a3de-0909-46bc-b1f4-468b9a2dfc0d"
QUBODrivers = "a3f166f7-2cd3-47b6-9e1e-6fbfe0449eb0"
QUBOTools = "60eb5b62-0a39-4ddc-84c5-97d2adff9319"

[compat]
PythonCall = "0.9.14"
Graphs = "1"
MathOptInterface = "1"
PythonCall = "0.9.15"
QUBODrivers = "0.3"
QUBOTools = "0.9"
julia = "1.9"
39 changes: 24 additions & 15 deletions src/DWave.jl
Original file line number Diff line number Diff line change
@@ -1,41 +1,50 @@
module DWave

import Graphs
import QUBOTools
import QUBODrivers
import QUBODrivers: MOI, QUBOTools
import MathOptInterface as MOI

using PythonCall

# -*- :: Python D-Wave Module :: -*- #
# const np = PythonCall.pynew()
# const plt = PythonCall.pynew()
const np = PythonCall.pynew()
const dwave_cloud = PythonCall.pynew()
const dwave_dimod = PythonCall.pynew()
const dwave_embedding = PythonCall.pynew()
const dwave_networkx = PythonCall.pynew()
const dwave_system = PythonCall.pynew()

function __init__()
# Python Packages
# PythonCall.pycopy!(np, pyimport("numpy"))
# PythonCall.pycopy!(plt, pyimport("matplotlib.pyplot"))
PythonCall.pycopy!(dwave_cloud, pyimport("dwave.cloud"))
PythonCall.pycopy!(dwave_dimod, pyimport("dimod"))
PythonCall.pycopy!(dwave_embedding, pyimport("dwave.embedding"))
PythonCall.pycopy!(dwave_networkx, pyimport("dwave_networkx"))
PythonCall.pycopy!(dwave_system, pyimport("dwave.system"))

function __auth__()
# D-Wave API Credentials
if !haskey(ENV, "DWAVE_API_TOKEN")
@warn """
The 'DWAVE_API_TOKEN' environment variable is not defined. Please, make sure that another access method is available.
The 'DWAVE_API_TOKEN' environment variable is not defined.
If you want to use D-Wave's cloud services, please make sure that another access method is available.
For more information visit:
https://docs.ocean.dwavesys.com/en/stable/overview/sapi.html
"""
end

return nothing
end

function __init__()
# Python Packages
PythonCall.pycopy!(np, pyimport("numpy"))
PythonCall.pycopy!(dwave_cloud, pyimport("dwave.cloud"))
PythonCall.pycopy!(dwave_dimod, pyimport("dimod"))
PythonCall.pycopy!(dwave_embedding, pyimport("dwave.embedding"))
PythonCall.pycopy!(dwave_networkx, pyimport("dwave_networkx"))
PythonCall.pycopy!(dwave_system, pyimport("dwave.system"))

__auth__()

return nothing
end

include("sampler.jl")
include("neal.jl")
include("neal/sampler.jl")

end # module
26 changes: 11 additions & 15 deletions src/neal.jl → src/neal/sampler.jl
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
module Neal

import QUBOTools
import QUBODrivers
import QUBODrivers: MOI, QUBOTools
import MathOptInterface as MOI

using PythonCall

Expand All @@ -12,18 +13,6 @@ function __init__()
PythonCall.pycopy!(neal, pyimport("neal"))
end

const ATTRIBUTES = [
:num_reads,
:num_sweeps,
:num_sweeps_per_beta,
:beta_range,
:beta_schedule,
:beta_schedule_type,
:seed,
:initial_states_generator,
:interrupt_function,
]

@doc raw"""
DWave.Neal.Optimizer
Expand Down Expand Up @@ -51,8 +40,15 @@ function QUBODrivers.sample(sampler::Optimizer{T}) where {T}

# Retrieve Optimizer Attributes
params = Dict{Symbol,Any}(
param => MOI.get(sampler, MOI.RawOptimizerAttribute(string(param)))
for param in ATTRIBUTES
:num_reads => MOI.get(sampler, MOI.RawOptimizerAttribute("num_reads")),
:num_sweeps => MOI.get(sampler, MOI.RawOptimizerAttribute("num_sweeps")),
:num_sweeps_per_beta => MOI.get(sampler, MOI.RawOptimizerAttribute("num_sweeps_per_beta")),
:beta_range => MOI.get(sampler, MOI.RawOptimizerAttribute("beta_range")),
:beta_schedule => MOI.get(sampler, MOI.RawOptimizerAttribute("beta_schedule")),
:beta_schedule_type => MOI.get(sampler, MOI.RawOptimizerAttribute("beta_schedule_type")),
:seed => MOI.get(sampler, MOI.RawOptimizerAttribute("seed")),
:initial_states_generator => MOI.get(sampler, MOI.RawOptimizerAttribute("initial_states_generator")),
:interrupt_function => MOI.get(sampler, MOI.RawOptimizerAttribute("interrupt_function")),
)

# Call D-Wave Neal API
Expand Down
3 changes: 3 additions & 0 deletions src/wrapper/QUBOTools_DWave.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module QUBOTools_DWave

end
3 changes: 3 additions & 0 deletions src/wrapper/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# D-Wave

This folder constains specific interface definitions related to D-Wave hardware.
8 changes: 8 additions & 0 deletions src/wrapper/architecture.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
@doc raw"""
DWaveArchitecture
"""
abstract type DWaveArchitecture <: QUBOTools.AbstractArchitecture end

include("device.jl")
include("chimera.jl")
include("hfs/format.jl")
170 changes: 170 additions & 0 deletions src/wrapper/chimera.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
# NOTE: This file is temporary. In the future, it should be moved to the
# DWave.jl package, so that this functionality is activated only given a
# specific context of use.

@doc raw"""
Chimera
The format of the instance-description file starts with a line giving the size of the Chimera graph[^alex1770].
Two numbers are given to specify an ``m \times n`` rectangle, but currently only a square (``m = n``) is accepted.
The subsequent lines are of the form
```
<Chimera vertex> <Chimera vertex> <weight>
```
where `<Chimera vertex>` is specified by four numbers using the format, Chimera graph, ``C_N``:
Vertices are ``v = (x, y, o, i)`` where
- ``x, y \in [0, N - 1]`` are the horizontal, vertical coordinates of the ``K_{4, 4}``
- ``o \in [0, 1]`` is the **orientation**: (``0 = \text{horizontally connected}``, ``1 = \text{vertically connected}``)
- ``i \in [0, 3]`` is the index within the "semi-``K_{4,4}``" or "bigvertex"
- There is an involution given by ``x \iff y``, ``o \iff 1 - o``
There is an edge from ``v_p`` to ``v_q`` if at least one of the following holds:
- ``(x_p, y_p) = (x_q, y_q) \wedge o_p \neq o_q``
- ``|x_p - x_q| = 1 \wedge y_p = y_q \wedge o_p = o_q = 0 \wedge i_p = i_q``
- ``x_p = x_q \wedge |y_p-y_q| = 1 \wedge o_p = o_q = 1 \wedge i_p = i_q``
[^alex1770]:
`alex1770`'s QUBO-Chimera Git Repository [{git}](https://github.com/alex1770/QUBO-Chimera)
[^dwave]:
**D-Wave QPU Architecture: Topologies** [{docs}](https://docs.dwavesys.com/docs/latest/c_gs_4.html)
"""
struct Chimera <: DWaveArchitecture
grid_size::NTuple{2,Int}
cell_size::Int
precision::Int
coordinates::Dict{Int,NTuple{4,Int}}
degree::Int
effective_degree::Int
end

function Chimera(
m::Integer = 2_048, # 2000Q
n::Integer = m;
cell_size::Integer = 8,
precision::Integer = 5,
degree::Union{Integer,Nothing} = nothing,
)
@assert m > 0
@assert n > 0
@assert m == n # TODO: relax

grid_size = (m, n)
dimension = m * n

min_degree = ceil(Int, sqrt(dimension / cell_size))

if isnothing(degree)
degree = min_degree
end

if degree < min_degree
error(
"""
Error: degree of '$(degree)' was specified.
However, the minimum degree required for a system with '$(dimension)' sites is '$(min_degree)'.
""",
)
end

cell_row_size = cell_size ÷ 2

# These values are used to transform a variable index into a chimera
# coordinate (x,y,o,i)
# x - row
# y - col
# o - cell_col - indicates the first or the second row of a chimera cell
# i - cell_col_id - indicates ids within a chimera cell
# Note that knowing the size of source chimera graph is essential to doing this mapping correctly

cell = Dict{Int,Int}(i => (i ÷ cell_size) for i in 1:dimension)
row = Dict{Int,Int}(i => (j ÷ degree) for (i, j) in cell)
col = Dict{Int,Int}(i => (j % degree) for (i, j) in cell)
cell_col = Dict{Int,Int}(i => (i % cell_size) ÷ cell_row_size for i in 1:dimension)
cell_col_id = Dict{Int,Int}(i => (i % cell_row_size) for i in 1:dimension)

coordinates = Dict{Int,NTuple{4,Int}}(
i => (row[i], col[i], cell_col[i], cell_col_id[i])
for i in 1:dimension
)

# Get the maximum of both row id and column id (namely 'c[1]', 'c[2]')
effective_degree = 1 + maximum((_, c) -> max(c[1], c[2]), coordinates)

if effective_degree > degree
error(
"""
The effective degree '$effective_degree' value is greater than the chimera degree '$(degree)', which is infeasible.
""",
)
end

return Chimera(
grid_size,
cell_size,
precision,
coordinates,
degree,
effective_degree,
)
end

function DWaveDevice(arch::Chimera, model::QUBOTools.AbstractModel{V}) where {V}
L = collect(QUBOTools.linear_terms(model))
Q = collect(QUBOTools.quadratic_terms(model))
α = QUBOTools.scale(model)
β = QUBOTools.offset(model)

γ = max( # maximum absolute value for a coefficient in 'model'
maximum((_, v) -> abs(v), L),
maximum((_, v) -> abs(v), Q),
)

γχ = 10 ^ arch.precision / γ

# Chimera Coefficients
= sizehint!(Dict{V,Int}(), length(L))
= sizehint!(Dict{Tuple{V,V},Int}(), length(Q))

for (i, v) in L
xi = QUBOTools.variable(model, i)

Lχ[xi] = round(Int, v * αχ)
end

for ((i, j), v) in Q
xi = QUBOTools.variable(model, i)
xj = QUBOTools.variable(model, j)

Qχ[(xi, xj)] = round(Int, v * αχ)
end

αχ = 1
βχ = round(Int, β * γχ)

factor = α * γχ

return DWaveDevice(
arch,
QUBOTools.Model{V,Int,Int}(
Set{V}(QUBOTools.variables(model)),
Lχ,
Qχ;
scale = αχ,
offset = βχ,
sense = QUBOTools.sense(model),
domain = QUBOTools.domain(model),
metadata = copy(QUBOTools.metadata(model)),
start = QUBOTools.start(model),
),
factor,
)
end

function layout(arch::Chimera)
# TODO: Retrieve this information from dwave-networkx?

return nothing
end
20 changes: 20 additions & 0 deletions src/wrapper/device.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# NOTE: This file is temporary. In the future, it should be moved to the
# DWave.jl package, so that this functionality is activated only given a
# specific context of use.

struct DWaveDevice{A<:DWaveArchitecture,V} <: QUBOTools.AbstractDevice{A,V,Int,Int}
arch::A
model::QUBOTools.Model{V,Int,Int}
factor::Float64

function DWaveDevice(
arch::A,
model::QUBOTools.Model{V,Int,Int},
factor::Float64 = 1.0,
) where {A<:DWaveArchitecture,V}
return new{A,V}(arch, model, factor)
end
end

QUBOTools.architecture(dev::DWaveDevice) = dev.arch
QUBOTools.backend(dev::DWaveDevice) = dev.model
20 changes: 20 additions & 0 deletions src/wrapper/hfs/format.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
@doc raw"""
HFS(;
chimera_cell_size::Union{Integer,Nothing} = nothing,
chimera_precision::Union{Integer,Nothing} = nothing,
chimera_degree::Union{Integer,Nothing} = nothing,
)
This format offers a description for the setup of chimera graphs.
"""
struct HFS <: AbstractFormat
chimera::Chimera

function HFS(chimera::Chimera)
return new(chimera)
end
end

format(::Val{:hfs}) = HFS(Chimera())

include("printer.jl")
Loading

2 comments on commit db06ee9

@pedromxavier
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@JuliaRegistrator
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Registration pull request created: JuliaRegistries/General/95347

Tip: Release Notes

Did you know you can add release notes too? Just add markdown formatted text underneath the comment after the text
"Release notes:" and it will be added to the registry PR, and if TagBot is installed it will also be added to the
release that TagBot creates. i.e.

@JuliaRegistrator register

Release notes:

## Breaking changes

- blah

To add them here just re-invoke and the PR will be updated.

Tagging

After the above pull request is merged, it is recommended that a tag is created on this repository for the registered package version.

This will be done automatically if the Julia TagBot GitHub Action is installed, or can be done manually through the github interface, or via:

git tag -a v0.4.1 -m "<description of version>" db06ee960b6b00bdc27b06e76e0ab7312b506551
git push origin v0.4.1

Please sign in to comment.