GithubHelp home page GithubHelp logo

openjij / cimod Goto Github PK

View Code? Open in Web Editor NEW
13.0 6.0 4.0 14.47 MB

C++ library for a binary quadratic model

Home Page: https://www.openjij.org

License: Apache License 2.0

C++ 56.58% CMake 9.51% Python 33.69% Shell 0.23%
header-only simulated-annealing quantum-annealing python

cimod's Introduction

cimod : C++ header-only library for a binary quadratic model

PyPI version shields.io PyPI pyversions PyPI implementation PyPI format PyPI license PyPI download month Downloads

Test Build&Upload CodeQL Build Documentation pages-build-deployment Codacy Badge Maintainability codecov

Coverage Graph

Sunburst Grid Icicle

How to use

You should only include a header src/binary_quadratic_model.hpp in your project.

Example

C++

#include "src/binary_quadratic_model.hpp"

using namespace cimod;
int main()
{
// Set linear biases and quadratic biases
Linear<uint32_t, double> linear{ {1, 1.0}, {2, 2.0}, {3, 3.0}, {4, 4.0} };
Quadratic<uint32_t, double> quadratic
{
     {std::make_pair(1, 2), 12.0}, {std::make_pair(1, 3), 13.0}, {std::make_pair(1, 4), 14.0},
     {std::make_pair(2, 3), 23.0}, {std::make_pair(2, 4), 24.0},
     {std::make_pair(3, 4), 34.0}
 };

// Set offset
double offset = 0.0;

// Set variable type
Vartype vartype = Vartype::BINARY;
// Create a BinaryQuadraticModel instance
BinaryQuadraticModel<uint32_t, double, cimod::Dense> bqm(linear, quadratic, offset, vartype);

//linear terms -> bqm.get_linear()
//quadratic terms -> bqm.get_quadratic()

return 0;
}

Python

import cimod
import dimod

# Set linear biases and quadratic biases
linear = {1:1.0, 2:2.0, 3:3.0, 4:4.0}
quadratic = {(1,2):12.0, (1,3):13.0, (1,4):14.0, (2,3):23.0, (2,4):24.0, (3,4):34.0}

# Set offset
offset = 0.0

# Set variable type
vartype = dimod.BINARY

# Create a BinaryQuadraticModel instance
bqm = cimod.BinaryQuadraticModel(linear, quadratic, offset, vartype)

print(bqm.linear)
print(bqm.quadratic)

For Contributor

Use pre-commit for auto chech before git commit. .pre-commit-config.yaml

# pipx install pre-commit 
# or 
# pip install pre-commit
pre-commit install

Install

via this directory

$ python -m pip install -vvv .

via pip

# Binary
$ pip install jij-cimod
# From Source 
$ pip install --no-binary=jij-cimod jij-cimod 

Test

Python

$ python -m venv .venv
$ pip install pip-tools 
$ pip-compile setup.cfg
$ pip-compile dev-requirements.in
$ pip-sync requirements.txt dev-requirements.txt
$ source .venv/bin/activate
$ export CMAKE_BUILD_TYPE=Debug
$ python setup.py --force-cmake install --build-type Debug -G Ninja
$ python setup.py --build-type Debug test 
$ python -m coverage html

C++

$ mkdir build 
$ cmake -DCMAKE_BUILD_TYPE=Debug -S . -B build
$ cmake --build build --parallel
$ cd build
$ ./tests/cimod_test
# Alternatively Use CTest 
$ ctest --extra-verbose --parallel --schedule-random

Needs: CMake > 3.22, C++17

  • Format
$ pip-compile format-requirements.in
$ pip-sync format-requirements.txt
$ python -m isort 
$ python -m black 
  • Aggressive Format
$ python -m isort --force-single-line-imports --verbose ./cimod
$ python -m autoflake --in-place --recursive --remove-all-unused-imports --ignore-init-module-imports --remove-unused-variables ./cimod
$ python -m autopep8 --in-place --aggressive --aggressive  --recursive ./cimod
$ python -m isort ./cimod
$ python -m black ./cimod
  • Lint
$ pip-compile setup.cfg
$ pip-compile dev-requirements.in
$ pip-compile lint-requirements.in
$ pip-sync requirements.txt dev-requirements.txt lint-requirements.txt
$ python -m flake8
$ python -m mypy
$ python -m pyright

Benchmark

Benchmark code

import dimod
import cimod
import time

fil = open("benchmark", "w")
fil.write("N t_dimod t_cimod\n")

def benchmark(N, test_fw):
    linear = {}
    quadratic = {}

    spin = {}

    # interactions

    for i in range(N):
        spin[i] = 1

    for elem in range(N):
        linear[elem] = 2.0*elem;

    for i in range(N):
        for j in range(i+1, N):
            if i != j:
                quadratic[(i,j)] = (i+j)/(N)

    t1 = time.time()

    # initialize
    a = test_fw.BinaryQuadraticModel(linear, quadratic, 0, test_fw.BINARY)
    a.change_vartype(test_fw.SPIN)

    # calculate energy for 50 times.
    for _ in range(50):
        print(a.energy(spin))

    t2 = time.time()

    return t2-t1

d_arr = []
c_arr = []

for N in [25, 50, 100, 200, 300, 400, 600, 800,1000, 1600, 2000, 3200, 5000]:
    print("N {}".format(N))
    d = benchmark(N, dimod)
    c = benchmark(N, cimod)
    print("{} {} {}".format(N, d, c))
    fil.write("{} {} {}\n".format(N, d, c))

Software versions

Package Version
cimod 1.0.3
dimod 0.9.2

Result

benchmark

Notes

  • As explained in #48, specifying self-loop index (e.g. {(2, 2): 5}) in the quadratic argument in BinaryQuadraticModel is not allowed.

Licences

Copyright 2022 Jij Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0  

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

cimod's People

Contributors

29rou avatar dependabot[bot] avatar github-actions[bot] avatar j-i-k-o avatar k-suzuki-jij avatar rej55 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

cimod's Issues

remove_interaction() in BinaryPolynomialModel does not work properly

>>> bpm = cimod.BinaryPolynomialModel({(1,2):-1}, "SPIN")
>>> bpm.polynomial
{(2,): 0.0, (1,): 0.0, (1, 2): -1.0}
>>> bpm.variables
{1, 2}
>>> bpm.remove_interaction((1,2))
>>> bpm.remove_interaction((1,))
>>> bpm.remove_interaction((2,))
>>> bpm.polynomial
{}
>>> bpm.variables
{1, 2}

But that should be
{}

Add env variable to not download dependencies

Hi,

this is in the process of me adding this package to conda-forge since it is a Dimod dependency.

Would it be possible to add an env variable that prevents the dependencies from being downloaded and instead fails the build process, if the dependencies aren't already available in the host system?
Just something simple like try to find dependencies locally -> if not, fail with error message about missing dependency

Reason is that conda-forge prefers to use its own packages so I could be certain that I didn't miss anything and something is downloaded.

Ref:

  1. conda-forge/staged-recipes#19094
  2. Example:
    FetchContent_Declare(
    eigen
    GIT_REPOSITORY https://gitlab.com/libeigen/eigen
    GIT_TAG 3.3.9
    CMAKE_ARGS -DEIGEN_MPL2_ONLY
    )

remove `No-Self loop allowed` restriction

duplicate index such that quadratic={(2,2): 5} should be dealt with:

  • in the case of SPIN:
    linear={} quadratic={} offset=5
  • in the case of BINARY:
    linear={2:5} quadratic={} offset=0

[Bug]: Python module fails to build on FreeBSD

Contact Details

[email protected]

What happened?

===>  Building for py39-jij-cimod-1.4.36


--------------------------------------------------------------------------------
-- Trying "Ninja" generator
--------------------------------
---------------------------
----------------------
-----------------
------------
-------
--
Not searching for unused variables given on the command line.
-- The C compiler identification is Clang 14.0.5
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Check for working C compiler: /usr/bin/cc - skipped
-- Detecting C compile features
-- Detecting C compile features - done
-- The CXX compiler identification is Clang 14.0.5
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Check for working CXX compiler: /usr/bin/c++ - skipped
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Configuring done
-- Generating done
-- Build files have been written to: /disk-samsung/freebsd-ports/math/py-jij-cimod/work-py39/jij_cimod-1.4.36/_cmake_test_compile/build
--
-------
------------
-----------------
----------------------
---------------------------
--------------------------------
-- Trying "Ninja" generator - success
--------------------------------------------------------------------------------

Configuring Project
  Working directory:
    /disk-samsung/freebsd-ports/math/py-jij-cimod/work-py39/jij_cimod-1.4.36/_skbuild/freebsd-13.1-STABLE-amd64-3.9/cmake-build
  Command:
    cmake /disk-samsung/freebsd-ports/math/py-jij-cimod/work-py39/jij_cimod-1.4.36 -G Ninja -DCMAKE_INSTALL_PREFIX:PATH=/disk-samsung/freebsd-ports/math/py-jij-cimod/work-py39/jij_cimod-1.4.36/_skbuild/freebsd-13.1-STABLE-amd64-3.9/cmake-install/cimod -DPYTHON_EXECUTABLE:FILEPATH=/usr/local/bin/python3.9 -DPYTHON_VERSION_STRING:STRING=3.9.13 -DPYTHON_INCLUDE_DIR:PATH=/usr/local/include/python3.9 -DPYTHON_LIBRARY:FILEPATH=/usr/local/lib/libpython3.9.so -DSKBUILD:INTERNAL=TRUE -DCMAKE_MODULE_PATH:PATH=/usr/local/lib/python3.9/site-packages/skbuild/resources/cmake -DCMAKE_BUILD_TYPE:STRING=Release

-- The C compiler identification is Clang 14.0.5
-- The CXX compiler identification is Clang 14.0.5
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Check for working C compiler: /usr/bin/cc - skipped
-- Detecting C compile features
-- Detecting C compile features - done
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Check for working CXX compiler: /usr/bin/c++ - skipped
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- CMake 3.23.3
-- Looking for a Fortran compiler
-- Looking for a Fortran compiler - /usr/local/bin/gfortran11
-- The Fortran compiler identification is GNU 11.3.0
-- Detecting Fortran compiler ABI info
-- Detecting Fortran compiler ABI info - done
-- Check for working Fortran compiler: /usr/local/bin/gfortran11 - skipped
-- We are on a FreeBSD system
-- The host processor is amd64
-- CMAKE_GENERATOR = Ninja
-- CIBUILDWHEEL = 
-- CMAKE_REQUIRE_FIND_PACKAGE_Eigen3 = 
-- CMAKE_REQUIRE_FIND_PACKAGE_nlohmann_json = 
-- CMAKE_REQUIRE_FIND_PACKAGE_pybind11 = 
-- CMAKE_REQUIRE_FIND_PACKAGE_pybind11_json = 
-- CMAKE_REQUIRE_FIND_PACKAGE_GTest = 
-- Started CMake for cimod 

-- Looking for Fortran sgemm
-- Looking for Fortran sgemm - not found
-- Looking for pthread.h
-- Looking for pthread.h - found
-- Performing Test CMAKE_HAVE_LIBC_PTHREAD
-- Performing Test CMAKE_HAVE_LIBC_PTHREAD - Success
-- Found Threads: TRUE  
-- Looking for Fortran sgemm
-- Looking for Fortran sgemm - found
-- Found BLAS: /usr/local/lib/libopenblas.so  
-- Looking for Fortran cheev
-- Looking for Fortran cheev - found
-- Found LAPACK: /usr/local/lib/libopenblas.so;-lm;-ldl  
-- Found OpenMP_C: -fopenmp=libomp (found version "5.0") 
-- Found OpenMP_CXX: -fopenmp=libomp (found version "5.0") 
-- Found OpenMP_Fortran: -fopenmp (found version "4.5") 
-- Found OpenMP: TRUE (found version "5.0")  
-- OMP_FOUND = YES
-- USE_OMP = ON
-- Skip Download eigen3
-- Found nlohmann_json: /usr/local/lib/cmake/nlohmann_json/nlohmann_jsonConfig.cmake (found version "3.10.5") 
-- Skip Download nlohmann_json
CMake Error at CMakeLists.txt:161 (add_subdirectory):
  add_subdirectory given source "include" which is not an existing directory.


-- Build Python Extension.
-- Found Python: /usr/local/bin/python3.9 (found version "3.9.13") found components: Interpreter Development Development.Module Development.Embed 
'/usr/local/bin/python3.9' '-c' 'import pybind11; print(pybind11.get_cmake_dir())'
-- Performing Test HAS_FLTO
-- Performing Test HAS_FLTO - Failed
-- Performing Test HAS_FLTO_THIN
-- Performing Test HAS_FLTO_THIN - Failed
-- Found pybind11: /usr/local/lib/python3.9/site-packages/pybind11/include (found version "2.10.0")
-- Could NOT find pybind11_json (missing: pybind11_json_DIR)
-- Downlod pybind11_json
-- Fetching Pybind11 Json
--   Populating pybind11_json
-- Configuring done
-- Generating done
-- Build files have been written to: /disk-samsung/freebsd-ports/math/py-jij-cimod/work-py39/jij_cimod-1.4.36/_skbuild/freebsd-13.1-STABLE-amd64-3.9/cmake-build/_deps/pybind11_json-subbuild
[1/9] Creating directories for 'pybind11_json-populate'
[1/9] Performing download step (git clone) for 'pybind11_json-populate'
Cloning into 'pybind11_json-src'...
HEAD is now at 1727c0b Release 0.2.12
[2/9] Performing update step for 'pybind11_json-populate'
[3/9] No patch step for 'pybind11_json-populate'
[5/9] No configure step for 'pybind11_json-populate'
[6/9] No build step for 'pybind11_json-populate'
[7/9] No install step for 'pybind11_json-populate'
[8/9] No test step for 'pybind11_json-populate'
[9/9] Completed 'pybind11_json-populate'
-- Fetching Pybind11 Json - fetched
-- Configuring incomplete, errors occurred!
See also "/disk-samsung/freebsd-ports/math/py-jij-cimod/work-py39/jij_cimod-1.4.36/_skbuild/freebsd-13.1-STABLE-amd64-3.9/cmake-build/CMakeFiles/CMakeOutput.log".
See also "/disk-samsung/freebsd-ports/math/py-jij-cimod/work-py39/jij_cimod-1.4.36/_skbuild/freebsd-13.1-STABLE-amd64-3.9/cmake-build/CMakeFiles/CMakeError.log".
Traceback (most recent call last):
  File "/usr/local/lib/python3.9/site-packages/skbuild/setuptools_wrap.py", line 637, in setup
    env = cmkr.configure(
  File "/usr/local/lib/python3.9/site-packages/skbuild/cmaker.py", line 308, in configure
    raise SKBuildError(

An error occurred while configuring with CMake.
  Command:
    cmake /disk-samsung/freebsd-ports/math/py-jij-cimod/work-py39/jij_cimod-1.4.36 -G Ninja -DCMAKE_INSTALL_PREFIX:PATH=/disk-samsung/freebsd-ports/math/py-jij-cimod/work-py39/jij_cimod-1.4.36/_skbuild/freebsd-13.1-STABLE-amd64-3.9/cmake-install/cimod -DPYTHON_EXECUTABLE:FILEPATH=/usr/local/bin/python3.9 -DPYTHON_VERSION_STRING:STRING=3.9.13 -DPYTHON_INCLUDE_DIR:PATH=/usr/local/include/python3.9 -DPYTHON_LIBRARY:FILEPATH=/usr/local/lib/libpython3.9.so -DSKBUILD:INTERNAL=TRUE -DCMAKE_MODULE_PATH:PATH=/usr/local/lib/python3.9/site-packages/skbuild/resources/cmake -DCMAKE_BUILD_TYPE:STRING=Release
  Source directory:
    /disk-samsung/freebsd-ports/math/py-jij-cimod/work-py39/jij_cimod-1.4.36
  Working directory:
    /disk-samsung/freebsd-ports/math/py-jij-cimod/work-py39/jij_cimod-1.4.36/_skbuild/freebsd-13.1-STABLE-amd64-3.9/cmake-build
Please see CMake's output for more information.
*** Error code 1

Stop.

Python Version

3.9

What os are you seeing the problem on?

Linux

What arch are you seeing the problem on?

No response

Relevant log output

$ cat /disk-samsung/freebsd-ports/math/py-jij-cimod/work-py39/jij_cimod-1.4.36/_skbuild/freebsd-13.1-STABLE-amd64-3.9/cmake-build/CMakeFiles/CMakeError.log
Determining if the Fortran sgemm exists failed with the following output:
Change Dir: /disk-samsung/freebsd-ports/math/py-jij-cimod/work-py39/jij_cimod-1.4.36/_skbuild/freebsd-13.1-STABLE-amd64-3.9/cmake-build/CMakeFiles/CMakeTmp

Run Build Command(s):/usr/local/bin/ninja cmTC_7d237 && [1/4] Building Fortran preprocessed CMakeFiles/cmTC_7d237.dir/testFortranCompiler.f-pp.f
[2/4] Generating Fortran dyndep file CMakeFiles/cmTC_7d237.dir/Fortran.dd
[3/4] Building Fortran object CMakeFiles/cmTC_7d237.dir/testFortranCompiler.f.o
[4/4] Linking Fortran executable cmTC_7d237
FAILED: cmTC_7d237 
: && /usr/local/bin/gfortran11 -lpthread -lcblas -llapack -lpthread -Wl,-rpath=/usr/local/lib/gcc11  -L/usr/local/lib/gcc11 -B/usr/local/bin -fstack-protector-strong -L/usr/local/lib -O -Wl,-rpath=/usr/local/lib/gcc11 CMakeFiles/cmTC_7d237.dir/testFortranCompiler.f.o -o cmTC_7d237   && :
/usr/local/bin/ld: /usr/local/lib/libcblas.so: undefined reference to symbol 'sgemm_'
/usr/local/bin/ld: /usr/local/lib/libblas.so.3: error adding symbols: DSO missing from command line
collect2: error: ld returned 1 exit status
ninja: build stopped: subcommand failed.



Performing C++ SOURCE FILE Test HAS_FLTO failed with the following output:
Change Dir: /disk-samsung/freebsd-ports/math/py-jij-cimod/work-py39/jij_cimod-1.4.36/_skbuild/freebsd-13.1-STABLE-amd64-3.9/cmake-build/CMakeFiles/CMakeTmp

Run Build Command(s):/usr/local/bin/ninja cmTC_b7e50 && [1/2] Building CXX object CMakeFiles/cmTC_b7e50.dir/src.cxx.o
[2/2] Linking CXX executable cmTC_b7e50
FAILED: cmTC_b7e50 
: && /usr/bin/c++ -O2 -pipe -fno-omit-frame-pointer -fstack-protector-strong -isystem /usr/local/include -fno-strict-aliasing -fno-omit-frame-pointer  -isystem /usr/local/include -lpthread -lcblas -llapack -lpthread -Wl,-rpath=/usr/local/lib/gcc11  -L/usr/local/lib/gcc11 -B/usr/local/bin -fstack-protector-strong -L/usr/local/lib CMakeFiles/cmTC_b7e50.dir/src.cxx.o -o cmTC_b7e50  -flto && :
/usr/local/bin/ld: /usr/bin/../lib/LLVMgold.so: error loading plugin: Cannot open "/usr/bin/../lib/LLVMgold.so"
c++: error: linker command failed with exit code 1 (use -v to see invocation)
ninja: build stopped: subcommand failed.


Source file was:
int main() { return 0; }
Performing C++ SOURCE FILE Test HAS_FLTO_THIN failed with the following output:
Change Dir: /disk-samsung/freebsd-ports/math/py-jij-cimod/work-py39/jij_cimod-1.4.36/_skbuild/freebsd-13.1-STABLE-amd64-3.9/cmake-build/CMakeFiles/CMakeTmp

Run Build Command(s):/usr/local/bin/ninja cmTC_b68bd && [1/2] Building CXX object CMakeFiles/cmTC_b68bd.dir/src.cxx.o
[2/2] Linking CXX executable cmTC_b68bd
FAILED: cmTC_b68bd 
: && /usr/bin/c++ -O2 -pipe -fno-omit-frame-pointer -fstack-protector-strong -isystem /usr/local/include -fno-strict-aliasing -fno-omit-frame-pointer  -isystem /usr/local/include -lpthread -lcblas -llapack -lpthread -Wl,-rpath=/usr/local/lib/gcc11  -L/usr/local/lib/gcc11 -B/usr/local/bin -fstack-protector-strong -L/usr/local/lib CMakeFiles/cmTC_b68bd.dir/src.cxx.o -o cmTC_b68bd  -flto=thin && :
/usr/local/bin/ld: /usr/bin/../lib/LLVMgold.so: error loading plugin: Cannot open "/usr/bin/../lib/LLVMgold.so"
c++: error: linker command failed with exit code 1 (use -v to see invocation)
ninja: build stopped: subcommand failed.


Source file was:
int main() { return 0; }

Modify features in order to be consistent with dimod interface

In order to be consistent with dimod interface, The following fixes are required:

Check out dimod AdjVectorBQM

Hey folks, awesome project!

Have you had a chance to check out the c++ bqms introduced in dimod 0.9.0?

I reran the benchmark in the README using the AdjVectorBQM as a third option and got the following results:

N t_dimod t_cimod t_dimod_cpp
25 0.020157337188720703 0.0018649101257324219 0.0015666484832763672
50 0.06899404525756836 0.0029358863830566406 0.0020656585693359375
100 0.264096736907959 0.008856534957885742 0.003901958465576172
200 1.6795814037322998 0.036122798919677734 0.017549514770507812
300 3.6162827014923096 0.06078672409057617 0.032536983489990234
400 5.6712517738342285 0.10113716125488281 0.04827380180358887
600 11.07354474067688 0.26193881034851074 0.07327771186828613
800 18.849993467330933 0.5112695693969727 0.1237478256225586
1000 28.324119806289673 0.8851237297058105 0.19241881370544434
1600 71.51328182220459 2.7170562744140625 0.521592378616333
2000 109.51392722129822 4.897304534912109 0.8010129928588867
3200 279.1616187095642 15.554394483566284 2.06180739402771
5000 683.7101364135742 52.369715213775635 5.278014421463013

They are also header-only though right now the API is not considered stable (see dwavesystems/dimod#756).

I'd love to talk more about it and see if there are ideas from both that can be combined to make a best-of-both worlds implementation.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.