Skip to content

Commit c8642f8

Browse files
committed
fix
1 parent 4c0578f commit c8642f8

File tree

13 files changed

+159
-195
lines changed

13 files changed

+159
-195
lines changed

CMakeLists.txt

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ if(NOT DEFINED USE_CUDA)
3636
if(CMAKE_CUDA_COMPILER)
3737
enable_language(CUDA)
3838
set(USE_CUDA ${DEFAULT_USE_CUDA})
39-
message(STATUS "CUDA Support")
39+
4040
#for cuda-memcheck
4141
set(CMAKE_CUDA_FLAGS "${CMAKE_CUDA_FLAGS} -lineinfo")
4242
# set CXX compiler to nvcc host compiler in order to avoid linker error
@@ -63,7 +63,5 @@ endif()
6363

6464

6565
add_subdirectory(src)
66-
6766
add_subdirectory(openjij)
68-
add_subdirectory(tests)
69-
67+
add_subdirectory(tests)

openjij/sampler/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
1-
from .response import Response
21
from .sampler import *
32
from .sa_sampler import SASampler
43
from .sqa_sampler import SQASampler
54
from .gpu_sampler import *
65
from .cmos_annealer import *
6+
from .response import *

openjij/sampler/cmos_annealer.py

Lines changed: 37 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -15,13 +15,11 @@
1515
import requests
1616
import json
1717

18-
from openjij.sampler import BaseSampler
19-
from openjij.sampler import Response
18+
from openjij.sampler import BaseSampler, Response
2019
from openjij.model import KingGraph
2120

2221
import numpy as np
2322

24-
2523
class CMOSAnnealer(BaseSampler):
2624
"""Sampler with CMOS Annealer.
2725
@@ -70,18 +68,18 @@ class CMOSAnnealer(BaseSampler):
7068
"""
7169

7270
def __init__(self, token, machine_type="ASIC", beta_min=0.1, beta_max=5.0, step_length=10, step_num=100, iteration=1, **kwargs):
73-
71+
7472
self.token = token
7573
self.machine_type = machine_type
76-
74+
7775
self.cmos_parameters = {"temperature_num_steps": step_num,
7876
"temperature_step_length": step_length,
7977
"temperature_initial": 1/beta_min,
8078
"temperature_target": 1/beta_max,
8179
"num_executions": iteration}
82-
80+
8381
self.cmos_parameters.update(kwargs)
84-
82+
8583
def sample_ising(self, h=None, J=None, king_graph=None):
8684
"""Sample from the specified Ising model.
8785
@@ -116,12 +114,10 @@ def sample_ising(self, h=None, J=None, king_graph=None):
116114

117115
var_type = 'SPIN'
118116
if king_graph is not None:
119-
_king_graph = KingGraph(
120-
machine_type=self.machine_type, king_graph=king_graph, var_type=var_type)
117+
_king_graph = KingGraph(machine_type=self.machine_type, king_graph=king_graph, var_type=var_type)
121118
return self._sampling(_king_graph, var_type=var_type, token=self.token)
122119
elif (h is not None) and (J is not None):
123-
_king_graph = KingGraph(
124-
machine_type=self.machine_type, h=h, J=J, var_type=var_type)
120+
_king_graph = KingGraph(machine_type=self.machine_type, h=h, J=J, var_type=var_type)
125121
return self._sampling(_king_graph, var_type=var_type, token=self.token)
126122
else:
127123
raise ValueError('intput "h and J" or king_graph model')
@@ -157,54 +153,48 @@ def sample_qubo(self, Q=None, king_graph=None):
157153

158154
var_type = 'BINARY'
159155
if king_graph is not None:
160-
_king_graph = KingGraph(
161-
machine_type=self.machine_type, king_graph=king_graph, var_type=var_type)
156+
_king_graph = KingGraph(machine_type=self.machine_type, king_graph=king_graph, var_type=var_type)
162157
return self._sampling(_king_graph, var_type=var_type, token=self.token)
163158
elif Q is not None:
164-
_king_graph = KingGraph(
165-
machine_type=self.machine_type, Q=Q, var_type=var_type)
159+
_king_graph = KingGraph(machine_type=self.machine_type, Q=Q, var_type=var_type)
166160
return self._sampling(_king_graph, var_type=var_type, token=self.token)
167161
else:
168162
raise ValueError('intput Q or king_graph model')
169163

164+
170165
def _sampling(self, king_graph, var_type, token):
171166
indices = king_graph.indices
172167
response = Response(var_type=var_type, indices=indices)
173-
headers, request = self.make_json_request(
174-
king_graph.get_ising_king_graph(), token)
175-
168+
headers, request = self.make_json_request(king_graph.get_ising_king_graph(), token)
169+
176170
url = 'https://annealing-cloud.com/api/v2/solve'
177171
res = requests.post(url, data=json.dumps(request), headers=headers)
178172
res_dict = res.json()
179-
173+
180174
if res_dict['status'] != 0:
181-
raise ValueError('Error status: {}, message: {}'.format(
182-
res_dict['status'], res_dict['message']))
183-
175+
raise ValueError('Error status: {}, message: {}'.format(res_dict['status'], res_dict['message']))
176+
184177
if var_type == "SPIN":
185-
response.states = [[s for x, y, s in spins]
186-
for spins in res_dict['result']['spins']]
187-
else: # qubo
188-
response.states = [[int((s+1)/2) for x, y, s in spins]
189-
for spins in res_dict['result']['spins']]
190-
response.indices = [king_graph.convert_to_index(
191-
x, y) for x, y, s in res_dict['result']['spins'][0]]
192-
response.energies = np.array(
193-
res_dict['result']['energies']) + king_graph.energy_bias
178+
response.states = [[s for x, y, s in spins] for spins in res_dict['result']['spins']]
179+
else: #qubo
180+
response.states = [[int((s+1)/2) for x, y, s in spins] for spins in res_dict['result']['spins']]
181+
response.indices = [king_graph.convert_to_index(x, y) for x, y, s in res_dict['result']['spins'][0]]
182+
response.energies = np.array(res_dict['result']['energies']) + king_graph.energy_bias
183+
194184

195185
# more infomation see : https://annealing-cloud.com/web-api/reference/v2.html
196186
response.info = {
197187
"averaged_spins": res_dict['result']["averaged_spins"],
198188
"averaged_energy": res_dict['result']["averaged_energy"],
199-
'execution_time': res_dict['result']['execution_time'] * 10**(-3),
189+
'execution_time' : res_dict['result']['execution_time'] * 10**(-3),
200190
'job_id': res_dict['job_id'],
201191
}
202-
192+
203193
return response
204-
194+
205195
def make_json_request(self, model, token):
206196
"""Make request for CMOS Annealer API.
207-
197+
208198
Args:
209199
model (list):
210200
A list of 5 integer values representing vertices
@@ -216,22 +206,22 @@ def make_json_request(self, model, token):
216206
"""
217207

218208
headers = {"Authorization": "Bearer " + token}
219-
headers.update({"Accept": "application/json"})
220-
headers.update({'content-type': 'application/json'})
209+
headers.update({ "Accept": "application/json" })
210+
headers.update({ 'content-type': 'application/json' })
221211

222212
request = {}
223-
request["model"] = model # modelのみ必須項目
224-
request["type"] = 1 if self.machine_type == "ASIC" else 2 # FPGA
213+
request["model"] = model # modelのみ必須項目
214+
request["type"] = 1 if self.machine_type == "ASIC" else 2 # FPGA
225215
request["num_executions"] = self.cmos_parameters["num_executions"]
226216
request["parameter"] = {"temperature_num_steps": self.cmos_parameters["temperature_num_steps"],
227-
"temperature_step_length": self.cmos_parameters['temperature_step_length'],
228-
"temperature_initial": self.cmos_parameters['temperature_initial'],
229-
"temperature_target": self.cmos_parameters["temperature_target"]}
217+
"temperature_step_length": self.cmos_parameters['temperature_step_length'],
218+
"temperature_initial": self.cmos_parameters['temperature_initial'],
219+
"temperature_target": self.cmos_parameters["temperature_target"]}
230220
request["outputs"] = {"energies": True,
231-
"spins": True,
232-
"execution_time": True,
233-
"num_outputs": 0,
234-
"averaged_spins": True,
235-
"averaged_energy": True}
221+
"spins": True,
222+
"execution_time": True,
223+
"num_outputs": 0,
224+
"averaged_spins": True,
225+
"averaged_energy": True}
236226

237227
return headers, request

openjij/sampler/gpu_sampler.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
import openjij
1717
from openjij.sampler import SQASampler
1818
from openjij.model import BinaryQuadraticModel, ChimeraModel
19+
from openjij import Response
1920
import numpy as np
2021

2122

@@ -100,10 +101,7 @@ def _post_process4state(self, q_state):
100101

101102
return [list(np.array(state)[indices]) for state in q_state]
102103

103-
def sampling(self, model,
104-
initial_state=None,
105-
reinitialize_state=True, seed=None,
106-
**kwargs):
104+
def sampling(self, model, **kwargs):
107105
# Check the system for GPU is compiled
108106
try:
109107
self.system_class = cxxjij.system.ChimeraTransverseGPU

openjij/sampler/response.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -61,8 +61,8 @@ def __init__(self, var_type, indices):
6161
def __repr__(self):
6262
if len(self.states) == 0:
6363
return "Response\n\tvar_type: {}\n\tstates: empty".format(self.var_type)
64-
65-
if len(self.min_samples) == 0:
64+
65+
if len(min_samples) == 0:
6666
self.min_samples = self._minimum_sample()
6767
min_energy_index = np.argmin(self.energies) if len(
6868
self.energies) != 0 else None

openjij/sampler/sa_sampler.py

Lines changed: 45 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -203,14 +203,14 @@ def sample_qubo(self, Q,
203203

204204
def sampling(self, model,
205205
initial_state=None, updater='single spin flip',
206-
reinitialize_state=True, seed=None,
206+
reinitilize_state=True, seed=None,
207207
**kwargs):
208-
208+
self._sampling_kwargs_setting(**kwargs)
209+
self._set_model(model)
209210
ising_graph = model.get_cxxjij_ising_graph()
210211

211-
# make init state generator
212212
if initial_state is None:
213-
if not reinitialize_state:
213+
if not reinitilize_state:
214214
raise ValueError(
215215
'You need initial_state if reinitilize_state is False.')
216216

@@ -242,19 +242,46 @@ def _generate_init_state(): return np.array(_init_state)
242242
raise ValueError(
243243
'updater is one of "single spin flip or swendsen wang"')
244244

245-
response = self._sampling(
246-
model, _generate_init_state,
247-
algorithm, sa_system, initial_state,
248-
reinitialize_state, seed, **kwargs
249-
)
250-
251-
response.update_ising_states_energies(
252-
response.states, response.energies)
245+
# seed for MonteCarlo
246+
if seed is None:
247+
def simulated_annealing(system): return algorithm(
248+
system, self.schedule)
249+
else:
250+
def simulated_annealing(system): return algorithm(
251+
system, seed, self.schedule)
252+
253+
states = []
254+
energies = []
255+
256+
execution_time = []
257+
258+
@measure_time
259+
def exec_sampling():
260+
previous_state = _generate_init_state()
261+
for _ in range(self.iteration):
262+
if reinitilize_state:
263+
sa_system.reset_spins(_generate_init_state())
264+
else:
265+
sa_system.reset_spins(previous_state)
266+
267+
_exec_time = measure_time(simulated_annealing)(sa_system)
268+
269+
execution_time.append(_exec_time)
270+
previous_state = cxxjij.result.get_solution(sa_system)
271+
states.append(previous_state)
272+
energies.append(model.calc_energy(
273+
previous_state,
274+
need_to_convert_from_spin=True))
275+
sampling_time = exec_sampling()
276+
response = openjij.Response(
277+
var_type=model.var_type, indices=self.indices)
278+
response.update_ising_states_energies(states, energies)
279+
280+
response.info['sampling_time'] = sampling_time * \
281+
10**6 # micro sec
282+
response.info['execution_time'] = np.mean(
283+
execution_time) * 10**6 # micro sec
284+
response.info['list_exec_times'] = np.array(
285+
execution_time) * 10**6 # micro sec
253286

254287
return response
255-
256-
def _post_save(self, result_state, system, model, response):
257-
response.states.append(result_state)
258-
response.energies.append(model.calc_energy(
259-
result_state,
260-
need_to_convert_from_spin=True))

openjij/sampler/sampler.py

Lines changed: 2 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -13,9 +13,10 @@
1313
# limitations under the License.
1414

1515
import numpy as np
16-
import cxxjij
16+
import cxxjij as cj
1717
from openjij.model import BinaryQuadraticModel
1818
import openjij
19+
from .response import Response
1920

2021
import time
2122

@@ -61,47 +62,3 @@ def _sampling_kwargs_setting(self, **kwargs):
6162
self.iteration = kwargs['iteration']
6263
elif 'num_reads' in kwargs:
6364
self.iteration = kwargs['num_reads']
64-
65-
def _sampling(self, model, init_generator, algorithm, system,
66-
initial_state=None,
67-
reinitialize_state=True, seed=None, **kwargs):
68-
self._sampling_kwargs_setting(**kwargs)
69-
self._set_model(model)
70-
71-
# seed for MonteCarlo
72-
if seed is None:
73-
def sampling_algorithm(system): return algorithm(
74-
system, self.schedule)
75-
else:
76-
def sampling_algorithm(system): return algorithm(
77-
system, seed, self.schedule)
78-
79-
# run algorithm
80-
execution_time = []
81-
response = openjij.Response(
82-
var_type=model.var_type, indices=self.indices)
83-
84-
@measure_time
85-
def exec_sampling():
86-
previous_state = init_generator()
87-
for _ in range(self.iteration):
88-
if reinitialize_state:
89-
system.reset_spins(init_generator())
90-
else:
91-
system.reset_spins(previous_state)
92-
_exec_time = measure_time(sampling_algorithm)(system)
93-
execution_time.append(_exec_time)
94-
previous_state = cxxjij.result.get_solution(system)
95-
self._post_save(previous_state, system, model, response)
96-
97-
sampling_time = exec_sampling()
98-
response.info['sampling_time'] = sampling_time * 10**6 # micro sec
99-
response.info['execution_time'] = np.mean(
100-
execution_time) * 10**6 # micro sec
101-
response.info['list_exec_times'] = np.array(
102-
execution_time) * 10**6 # micro sec
103-
104-
return response
105-
106-
def _post_save(self, result_state, system, model, response):
107-
pass

0 commit comments

Comments
 (0)