Ejemplo n.º 1
0
    def qiskit_progress_bar(self, line='', cell=None):  # pylint: disable=unused-argument
        """A Jupyter magic function to generate progressbar.
        """
        args = magic_arguments.parse_argstring(self.qiskit_progress_bar, line)
        if args.type == 'html':
            pbar = HTMLProgressBar()
        elif args.type == 'text':
            pbar = TextProgressBar()
        else:
            raise qiskit.QiskitError('Invalid progress bar type.')

        return pbar
Ejemplo n.º 2
0
    def qiskit_progress_bar(self, line='', cell=None):
        """A Jupyter magic function to generate progressbar.
        """
        args = magic_arguments.parse_argstring(self.qiskit_progress_bar, line)
        if args.type == 'html':
            HTMLProgressBar()
        elif args.type == 'text':
            TextProgressBar()
        else:
            raise qiskit.QiskitError('Invalid progress bar type.')

        self.shell.ex(cell)
Ejemplo n.º 3
0
 def quantum_prob(self, row: int) -> np.float:
     """ Return quantum probability according to Born rule."""
     if self.pre_meas_gates is None or self.rho is None:
         raise qiskit.QiskitError(
             "To calculate quantum probability, please provide rho and pre_meas_gates.")
     m = self.inputs(row)
     rid = int(float(row))%(self.d**self.n)
     U = functools.reduce(np.kron, [np.linalg.inv( self.pre_meas_gates[i][j] ) 
                             for i, j in enumerate(m)])
     p = 0*1j
     for l in range(self.d**self.n):
         for k in range(self.d**self.n):
             p += U[k][rid].conjugate() * self.rho[k][l] * U[l][rid]   
     return  np.real(p)
Ejemplo n.º 4
0
 def get_quantum_corr(self, source: str, row: int) -> np.float:
     """ Return quantum correlation for inputs and outputs of a given row. 
     
     Args: 
         source (str): source of quantum correlations:
             'meas':  probabilities from qiskit experiment results.
             'calc':  probabilities calculated according to Born rule.
         row (int): an index of a constraint in an optimization problem.
         
     Returns:
         np.float: quantum probability.
     """
     if source.lower() == 'meas': 
         if self.meas_qcorr is not None:
             return self._meas_qcorr[self._check_int(row)]
         else:
             raise qiskit.QiskitError(
                 "To return measured quantum correlations please add qiskit results.")
     elif source.lower() == 'calc':
         return self._calc_qcorr.setdefault(row,self.quantum_prob(row))
     else:
         raise qiskit.QiskitError(
             "Invalid source of quantum correlations. Should be 'meas' or 'calc'.")
Ejemplo n.º 5
0
    def random(cls, sett: Sequence[int]):
        """ Construct BLocCircuits object with random unitary gates preceding the measurements.

        Args:
            sett (list[int]): possible measurement settings per subsystem. 
                len(sett) is the number of subsystems.
                
        Returns:
            BLocCircuits: instance with random pre measurement gates.
            
        Raises:
            QiskitError: if invalid sett argument.
        """
        if any(not isinstance(i, int) or i <= 0 for i in sett):
            raise qiskit.QiskitError('sett should be list of int > 0.')        
        pre_meas_gates = [[qiskit.extensions.UnitaryGate(
            qiskit.quantum_info.random.utils.random_unitary(2)) 
                           for s in range(sett[i])] for i in range(len(sett))]
        return BLocCircuits(pre_meas_gates)
Ejemplo n.º 6
0
 def new_LP(self, LP_type: str) -> None:
     """ Build new cplex LP model and set it to self.LP. 
     Args:
         LP_type (str): type of an optimization problem, can be either 'feasibility' 
             or 'optimization'.
     """
     self._LP = cplex.Cplex()
     
     # set objective
     if LP_type.lower() == 'feasibility':
         self.LP.variables.add(ub = np.ones(self.cols), 
                               lb = np.zeros(self.cols))
     elif LP_type.lower() in ['optimization','optimisation']:
         self.LP.variables.add(obj = np.hstack((np.zeros(self.cols),[1.0])), 
                               ub = np.ones(self.cols+1), 
                               lb = np.zeros(self.cols+1))
     else: 
         raise qiskit.QiskitError(
             "Invalid LP_type. Should be either 'feasibility' or "
             "'optimization'. Objective hasn't been set.")      
     self.LP.objective.set_sense(self.LP.objective.sense.maximize)
     
     # summation constraint
     self.LP.linear_constraints.add(
         lin_expr = [cplex.SparsePair(ind = range(self.cols), 
                                      val = np.ones(self.cols))], 
         rhs = [1.0], senses = 'E', range_values = [0.0], names = ['sum'])
     
     # restrict output
     self.LP.set_log_stream(None)
     self.LP.set_error_stream(None)
     self.LP.set_warning_stream(None)
     self.LP.set_results_stream(None)
     
     # solving method
     alg = self.LP.parameters.lpmethod.values
     self.LP.parameters.lpmethod.set(alg.dual)
     self.LP.parameters.threads.set(3)
     self.LP.parameters.parallel.set(1)
Ejemplo n.º 7
0
 def calc_qcorr(self, corr: Dict[int, np.float]):
     if not isinstance(corr,dict):
         raise qiskit.QiskitError(
             "corr should be a dict mapping rows to the corresponding quantum probabilities.")
     self._calc_qcorr = corr
Ejemplo n.º 8
0
 def meas_qcorr(self, corr: List[float]):
     if not np.isclose(sum(corr),np.prod(self.s)): 
         raise qiskit.QiskitError('Invalid sum of correlations.')
     self._meas_qcorr = corr
Ejemplo n.º 9
0
 def pre_meas_gates(self, gates: List[List[GateType]]):
     if (len(gates) != self.n or any(len(gates[i]) != self.s[i] for i in range(self.n))): 
         raise qiskit.QiskitError(
             "pre_meas_gates are incompatible with the settings scenario.")
     self._gates = [[self.__check_single_gate(i) for i in j] for j in gates]
     self._calc_qcorr.clear()