def generate_qlm_list_results(qiskit_result): """ Generates a QLM Result from a qiskit result. Args: qiskit_result: The qiskit.Result object to convert Returns: A QLM Result object built from the data in qiskit_result """ nbshots = qiskit_result.results[0].shots try: counts = [result.data.counts for result in qiskit_result.results] except AttributeError: print("No measures, so the result is empty") return QlmRes(raw_data=[]) counts = [{int(k, 16): v for k, v in count.items()} for count in counts] ret_list = [] for count in counts: ret = QlmRes(raw_data=[]) for state, freq in count.items(): if not isinstance(state, int): print("State is {type(state)}") ret.raw_data.append( Sample(state=state, probability=freq / nbshots, err=np.sqrt(freq / nbshots * (1. - freq / nbshots) / (nbshots - 1)) if nbshots > 1 else None)) ret_list.append(ret) return ret_list
def generate_qlm_result(cirq_result): """ Converts cirq result to QLM Result Args: cirq_result: The result object generated by cirq Returns: A QLM Result object built from cirq_result """ # Cirq encodes measures in a dictionary where the key is the coordinate of # the qubit, and the value is a list where the ith element is the result # of the measure of the qubit during the ith trial. nbshots = len(cirq_result.measurements[next(iter( cirq_result.measurements))]) measurements = ["" for _ in range(nbshots)] for entry in cirq_result.measurements.values(): for shot, value in enumerate(entry): measurements[shot] += str(int(value[0])) measurements = [int(_, 2) for _ in measurements] counts = Counter(measurements) qlm_result = QlmRes() qlm_result.raw_data = [ Sample(state=state, probability=freq / nbshots, err=np.sqrt(freq / nbshots * (1. - freq / nbshots) / (nbshots - 1)) if nbshots > 1 else None) for state, freq in counts.items() ] return qlm_result
def generate_qlm_result(pyquil_result): """ Converts pyquil result to QLM Result Args: pyquil_result: The result object generated by pyquil Returns: A QLM Result object built from pyquil_result """ # Pyquil encodes measures in a matrix, where line i is the measures # for trial i, and column j contains the measurements for qubit j # Build a list of states nbshots = len(pyquil_result) measurements = [ sum([b << i for i, b in enumerate(entry)]) for entry in pyquil_result ] counts = Counter(measurements) qlm_result = QlmRes() qlm_result.raw_data = [ Sample(state=state, probability=freq / nbshots, err=np.sqrt(freq / nbshots * (1. - freq / nbshots)(nbshots - 1)) if nbshots > 1 else None) for state, freq in counts.items() ] return qlm_result
def generate_qlm_result(pyquil_result): """ Converts pyquil result to QLM Result Args: pyquil_result: The result object generated by pyquil Returns: A QLM Result object built from pyquil_result """ # Pyquil encodes measures in a matrix, where line i is the measures # for trial i, and column j contains the measurements for qubit j # Build a list of states #FIXME only works with PyquilQPU generated results right now! #FIXME should work with native pyquil results also for register_result in pyquil_result.readout_data.values(): nbshots = len(register_result) measurements = [ sum([b << i for i, b in enumerate(entry)]) for entry in register_result ] counts = Counter(measurements) qlm_result = QlmRes() #FIXME check that err is correct qlm_result.raw_data = [ Sample(state=state, probability=freq / nbshots, err=np.sqrt(freq / nbshots * (1. - freq / nbshots) / (nbshots - 1)) if nbshots > 1 else None) for state, freq in counts.items() ] return qlm_result
def submit_job(self, job): """ Execute simulated annealing for a given job. Args: job (:class:`~qat.core.Job`): the job to execute Returns: result (:class:`~qat.core.Result`): a result with the solution spin configuration(s) """ # Check if an observable is present and one can extract the Ising tuple from it. if job.type == ProcessingType.OBSERVABLE: raise QPUException(ErrorType.INVALID_ARGS, 'qat.simulated_annealing', "invalid job type, only accepting SAMPLE") if job.schedule is None: raise QPUException(ErrorType.INVALID_ARGS, modulename='qat.simulated_annealing', message="invalid job, only accepting Schedules") # if job.schedule.gamma_t is not None: # raise QPUException(ErrorType.INVALID_ARGS, # 'qat.simulated_annealing', # "An SA QPU was called, but the job contains gamma_t, " # "which can only be used with an SQA solver, available " # "in the full QLM.") drive = job.schedule.drive if job.schedule.drive is None: raise QPUException( ErrorType.INVALID_ARGS, 'qat.simulated_annealing', "no drive detected, which should contain an Ising observable.") if len(drive) != 1 or drive[0][0] != 1: raise QPUException( ErrorType.INVALID_ARGS, 'qat.simulated_annealing', "the drive should contain only one Observable with " "an Ising tuple and coefficient 1.") # Extract the Ising parameters and tmax J_coupling, h_mag, offset = extract_j_and_h_from_obs(drive[0][1]) tmax = job.schedule.tmax # Specify the list of annealing times time_list = np.linspace(0, tmax, int(self.n_steps)) # Produce the temperatures at the annealing times if "Expression" in str(type(self.temp_t)): temp_list = [self.temp_t(t=t) for t in time_list] else: temp_list = [self.temp_t for t in time_list] # Will appeand QRegister to the result for proper dealing with the states qreg = QRegister(0, length=job.schedule.nbqbits) # Now give all the annealing parameters to the sa solver and get an answer sample_list = [] for shot in range(job.nbshots): solution_configuration = self.sa(J_coupling, h_mag, temp_list) state_int = spins_to_integer(solution_configuration) sample_list.append(Sample(state=state_int)) result = Result(raw_data=sample_list, qregs=[qreg], meta_data=dict()) if job.aggregate_data: result = aggregate_data(result) return result
def submit_job(self, job): """ Returns a Result structure corresponding to the execution of a Job Args: job (:class:`~qat.core.Job`): the job to execute Returns: :class:`~qat.core.Result`: the result """ if not isinstance(job.circuit, WCircuit): job.circuit = WCircuit(job.circuit) has_int_meas = has_intermediate_measurements(job.circuit) if (job.nbshots == 0) or (not has_int_meas): np_state_vec, interm_measurements = simulate( job.circuit) # perform simu if job.qubits is not None: meas_qubits = job.qubits else: meas_qubits = list(range(job.circuit.nbqbits)) all_qubits = (len(meas_qubits) == job.circuit.nbqbits) if not job.amp_threshold: job.amp_threshold = 0.0 result = Result() result.meta_data = dict() result.raw_data = [] if job.type == ProcessingType.SAMPLE: # Sampling if job.nbshots == 0: # Returning the full state/distribution if not all_qubits: sum_axes = tuple([ qb for qb in range(job.circuit.nbqbits) if qb not in meas_qubits ]) # state_vec is transformed into vector of probabilities np_state_vec = np.abs(np_state_vec**2) np_state_vec = np_state_vec.sum(axis=sum_axes) # At this point axes might not be in the same order # as in meas_qubits: restoring this order now: svec_inds = sorted(meas_qubits) # current np_state_vec # indices for target, qb in enumerate(meas_qubits): cur = svec_inds.index(qb) np_state_vec = np_state_vec.swapaxes(target, cur) svec_inds[target], svec_inds[cur] = svec_inds[ cur], svec_inds[target] # loop over states. val is amp if all_qubits else prob for int_state, val in enumerate(np_state_vec.ravel()): amplitude = None # in case not all qubits if all_qubits: amplitude = ComplexNumber(re=val.real, im=val.imag) prob = np.abs(val)**2 else: prob = val if prob <= job.amp_threshold**2: continue sample = Sample( state=int_state, amplitude=amplitude, probability=prob, intermediate_measurements=interm_measurements) # append result.raw_data.append(sample) elif job.nbshots > 0: # Performing shots if has_int_meas: # if intermediate measurements, the entire simulation must # be redone for every shot. Because the intermediate measurements # might change the output distribution probability. intprob_list = [] interm_meas_list = [] for _ in range(job.nbshots): np_state_vec, interm_measurements = simulate( job.circuit) # perform simu intprob = measure(np_state_vec, meas_qubits, nb_samples=1) intprob_list.append(intprob[0]) interm_meas_list.append(interm_measurements) else: # no need to redo the simulation entirely. Just sampling. intprob_list = measure(np_state_vec, meas_qubits, nb_samples=job.nbshots) interm_meas_list = [[] for _ in range(job.nbshots)] # convert to good format and put in container. for k, intprob in enumerate(intprob_list): res_int, prob = intprob amplitude = None # in case not all qubits if all_qubits: # accessing amplitude of result indices = [ res_int >> k & 1 for k in range(len(meas_qubits)) ] indices.reverse() amp = np_state_vec[tuple(indices)] amplitude = ComplexNumber(re=amp.real, im=amp.imag) # final result object sample = Sample( state=res_int, intermediate_measurements=interm_meas_list[k]) # append result.raw_data.append(sample) if job.aggregate_data: result = aggregate_data(result) else: raise QPUException(ErrorType.INVALID_ARGS, "qat.pylinalg", "Invalid number of shots %s" % job.nbshots) return result if job.type == ProcessingType.OBSERVABLE: result.value = compute_observable_average(np_state_vec, job.observable) return result raise QPUException(ErrorType.INVALID_ARGS, "qat.pylinalg", "Unsupported job type %s" % job.type)