def initState_1_0(matrixType, n): """ Generate an n-qubit state """ if matrixType == MatrixType.Dense: return initStateDense_1_0(n) else: raise Error.RuntimeError('Not implemented')
def _waitTask(token, taskId, fetchMeasure=False, downloadResult=True): """ Wait for a task from the taskId """ task = { "token": token, "taskId": taskId } stepStatus = "waiting" while True: try: time.sleep(pollInterval) ret = invokeBackend("task/checkTask", task) if ret["status"] in ("success", "failed", "manual_term"): if outputInfo: print(f"status changed {stepStatus} => {ret['status']}") stepStatus = ret["status"] result = {"status": ret["status"]} if ret["status"] == "success" and "originUrl" in ret.get("result", {}): if downloadResult: originFile, measureFile = _fetchResult(token, taskId) result["origin"] = originFile if fetchMeasure: result["counts"] = _fetchMeasureResult(taskId) else: result["measure"] = measureFile break elif ret["status"] == "failed": result = ret["reason"] break elif ret["status"] == "manual_term": break else: # go on loop # pprint(ret) pass else: if ret["status"] == stepStatus: continue if outputInfo: print(f"status changed {stepStatus} => {ret['status']}") stepStatus = ret["status"] except Error.Error as err: raise err except Exception: raise Error.RuntimeError(traceback.format_exc()) return result
def __init__(self, matrixType, algorithm, measureMethod): """ To choose the algorithms by the parameters. """ if measureMethod == MeasureMethod.Probability: if matrixType == MatrixType.Dense: self.proc = self.measureDenseByProbability else: raise Error.RuntimeError('Not implemented') else: self.Transfer = TransferProcessor(matrixType, algorithm) self.proc = self.measureBySingleAccumulation
def loadGates(matrixType, operationDict): """ Load the matrix of the gate """ if matrixType == MatrixType.Dense: operationDict[FixedGateEnum.X] = X.matrix operationDict[FixedGateEnum.Y] = Y.matrix operationDict[FixedGateEnum.Z] = Z.matrix operationDict[FixedGateEnum.H] = H.matrix operationDict[FixedGateEnum.CX] = CX.matrix.reshape(2, 2, 2, 2) else: raise Error.RuntimeError('Not implemented')
def _agentCommit(self, shots, **kwargs): """ Agent commitment :return: task result """ if noLocalTask is not None: raise Error.RuntimeError( 'Agent tasks are not allowed in the online environment') try: self.publish() # circuit in Protobuf format # import the agent plugin according to the backend name module = _loadPythonModule(f'QCompute.Agent.{self.backendName}') if module is None: raise Error.ParamError( f"invalid agent backend => {self.backendName}") simulatorClass = getattr(module, 'Backend') # configure the parameters agent = simulatorClass() agent.program = self.program agent.shots = shots agent.backendParam = self.backendParam # execution agent.commit() # wrap taskResult output = agent.result.output if agent.result.code != 0: return {"status": "error", "reason": output} if agent.result.counts: cRegCount = max(self.program.head.usingCRegs) + 1 agent.result.counts = _formatMeasure(agent.result.counts, cRegCount) originFd, originFn = tempfile.mkstemp(suffix=".json", prefix="local.", dir="./Output") with os.fdopen(originFd, "wt") as fObj: fObj.write(output) taskResult = {"status": "success", "origin": originFn} if kwargs.get("fetchMeasure", False): taskResult["counts"] = agent.result.counts else: measureFd, measureFn = tempfile.mkstemp(suffix=".json", prefix="local.", dir="./Output") with os.fdopen(measureFd, "wt") as fObj: fObj.write(json.dumps(agent.result.counts)) taskResult["measure"] = measureFn return taskResult return {"status": "failed", "reason": output} except Exception: raise Error.RuntimeError(traceback.format_exc())
def core(program, matrixType, algorithm, measureMethod, shots, seed): """ Simulaton process Check if the argument is available. The accepted ones are: 1)DENSE-EINSUM-SINGLE 2)DENSE-EINSUM-PROB 3)DENSE-MATMUL-SINGLE 4)DENSE-MATMUL-PROB """ compositeGate = CompositeGate() program = compositeGate(program) unrollProcedure = UnrollProcedure() program = unrollProcedure(program) unrollCircuit = UnrollCircuit() program = unrollCircuit( program ) # must unrollProcedure before, because of paramIds to paramValues if doCompressGate: compressGate = CompressGate() program = compressGate(program) qRegsMap = { qReg: index for index, qReg in enumerate(program.head.usingQRegs) } qRegCount = len(qRegsMap) operationDict = {} loadGates(matrixType, operationDict) if seed is None: seed = numpy.random.randint(0, 2147483647 + 1) numpy.random.seed(seed) state = initState_1_0(matrixType, qRegCount) transfer = TransferProcessor(matrixType, algorithm) measurer = Measurer(matrixType, algorithm, measureMethod) # collect the result to simulator for the subsequent invoking result = QuantumResult() result.startTimeUtc = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f') measured = False counts = {} measuredQRegsToCRegsBidict = bidict() for circuitLine in program.body.circuit: # Traverse the circuit if measured and not circuitLine.HasField('measure'): raise Error.ParamError('measure must be the last operation') qRegs = [] for qReg in circuitLine.qRegs: qRegs.append(qRegsMap[qReg]) if circuitLine.HasField('fixedGate'): # fixed gate matrix = operationDict.get(circuitLine.fixedGate) if matrix is None: raise Error.ParamError( f'unsupported operation {FixedGateEnum.Name(circuitLine.fixedGate)}' ) state = transfer(state, matrix, qRegs) elif circuitLine.HasField('rotationGate'): # rotation gate if circuitLine.rotationGate != RotationGateEnum.U: raise Error.ParamError( f'unsupported operation {RotationGateEnum.Name(circuitLine.rotationGate)}' ) uGate = U(*circuitLine.paramValues) if matrixType == MatrixType.Dense: matrix = uGate.matrix else: raise Error.RuntimeError('Not implemented') state = transfer(state, matrix, qRegs) elif circuitLine.HasField('customizedGate'): # customized gate if matrixType == MatrixType.Dense: matrix = _protobufMatrixToNumpyMatrix( circuitLine.customizedGate.matrix) else: raise Error.RuntimeError('Not implemented') state = transfer(state, matrix, qRegs) elif circuitLine.HasField('procedureName'): # procedure Error.ParamError( 'unsupported operation procedure, please flatten by UnrollProcedureModule' ) # it is not implemented, flattened by UnrollProcedureModule elif circuitLine.HasField('measure'): # measure if circuitLine.measure.type != PBMeasure.Type.Z: # only Z measure is supported raise Error.ParamError( f'unsupported operation measure {PBMeasure.Type.Name(circuitLine.measure.type)}' ) if not measured: counts = measurer(state, shots) measured = True cRegs = [] for cReg in circuitLine.measure.cRegs: cRegs.append(cReg) for i in range(len(cRegs)): if measuredQRegsToCRegsBidict.get(qRegs[i]) is not None: raise Error.ParamError('measure must be once on a QReg') if measuredQRegsToCRegsBidict.inverse.get( cRegs[i]) is not None: raise Error.ParamError('measure must be once on a CReg') measuredQRegsToCRegsBidict[qRegs[i]] = cRegs[i] elif circuitLine.HasField('barrier'): # barrier pass # unimplemented operation else: # unsupported operation raise Error.ParamError('unsupported operation') measuredCRegsList = list(measuredQRegsToCRegsBidict.keys()) result.endTimeUtc = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f') result.shots = shots result.counts = _filterMeasure(counts, measuredCRegsList) result.seed = int(seed) return result