Esempio n. 1
0
def simulate_counts(p, C, phys_dim=2, seed=None):
    """Simulate measuring each qubit of ``p`` in the computational basis,
    producing output like that of ``qiskit``.

    Parameters
    ----------
    p : vector or operator
        The quantum state, assumed to be normalized, as either a ket or density
        operator.
    C : int
        The number of counts to perform.
    phys_dim : int, optional
        The assumed size of the subsystems of ``p``, defaults to 2 for qubits.

    Returns
    -------
    results : dict[str, int]
        The counts for each bit string measured.

    Examples
    --------

    Simulate measuring the state of each qubit in a GHZ-state:

    .. code:: python3

        >>> import quimb as qu
        >>> psi = qu.ghz_state(3)
        >>> qu.simulate_counts(psi, 1024)
        {'000': 514, '111': 510}

    """
    if seed is not None:
        np.random.seed(seed)

    n = infer_size(p, phys_dim)
    d = phys_dim**n

    if isop(p):
        pi = np.diag(p).real
    else:
        pi = np.multiply(np.conj(p), p).real

    # probability of each basis state
    pi = pi.reshape(-1)

    # raw counts in terms of integers
    raw_counts = np.random.choice(np.arange(d), size=C, p=pi)

    # convert to frequencies of binary
    bin_str = '{:0>' + str(n) + 'b}'
    results = keymap(bin_str.format, frequencies(raw_counts))

    return results
Esempio n. 2
0
def flatten_params(params: Union[Dict, Param], cls=Param) -> Dict[str, Param]:
    """Flattens params into "." separated values

    e.g.
    {"a":{"b": Param(...)}} -> {"a.b": Param}

    :param params:
    :return:
    """
    if isinstance(params, cls):
        return params
    sol = {}
    for k, v in toolz.valmap(flatten_params, params).items():
        if isinstance(v, cls):
            sol[k] = v
        else:
            sol = toolz.merge(sol, toolz.keymap(lambda x: f"{k}.{x}", v))
    return sol
Esempio n. 3
0
 def json(self):
     return t.keymap(lambda k: k[1:]
                     if k.startswith('_') else k, self.__dict__)
Esempio n. 4
0
 def json(self):
     return t.keymap(lambda k: k[1:] if k.startswith('_') else k,
                     dict(self._asdict()))
Esempio n. 5
0
def alignment_stats(lable_ind,
                    label_val,
                    pred_ind,
                    pred_val,
                    batch_size,
                    debug=False):
    """Returns a list of numpy array representing alignemnt stats. First N elements are
    in aligment_stats_ordering and the last one in identity.

    The return is like this due to tf.py_func requirements --> this function is made for
    embedding as tf operation via tf.py_func

    :param lable_ind:
    :param label_val:
    :param pred_ind:
    :param pred_val:
    :param batch_size:
    :param debug:
    :return:
    """

    prefix = os.environ.get("MINCALL_LOG_DATA", None)
    if prefix:
        fname = os.path.abspath(os.path.join(prefix,
                                             f"{uuid.uuid4().hex}.npz"))
        with open(fname, "wb") as f:
            np.savez(
                f, **{
                    "label_val": label_val,
                    "lable_ind": lable_ind,
                    "pred_val": pred_val,
                    "pred_ind": pred_ind,
                    "batch_size": batch_size,
                })
        logger.debug(f"Saves alignment stats input data to {fname}")

    yt = defaultdict(list)
    for ind, val in zip(lable_ind, label_val):
        yt[ind[0]].append(val)

    yp = defaultdict(list)
    for ind, val in zip(pred_ind, pred_val):
        yp[ind[0]].append(val)

    sol = defaultdict(list)
    identities = []
    for x in range(batch_size):
        query = decode(np.array(yp[x], dtype=int))
        target = decode(np.array(yt[x], dtype=int))
        if len(target) == 0:
            raise ValueError("Empty target sequence")
        if len(query) == 0:
            logger.warning(f"Empty query sequence\n" f"Target: {target}")
            sol[dataset_pb2.MATCH].append(0.0)
            sol[dataset_pb2.MISMATCH].append(0.0)
            sol[dataset_pb2.DELETION].append(1.0)
            sol[dataset_pb2.INSERTION].append(0.0)
            identities.append(0)
            continue
        edlib_res = edlib.align(query, target, task='path')
        stats = ext_cigar_stats(edlib_res['cigar'])

        read_len = stats[dataset_pb2.MISMATCH] + stats[
            dataset_pb2.MATCH] + stats[dataset_pb2.INSERTION]

        #  https://github.com/isovic/samscripts/blob/master/src/errorrates.py
        identities.append(stats[dataset_pb2.MATCH] / sum(stats.values()))

        for op in aligment_stats_ordering:
            sol[op].append(stats[op] / read_len)
        if True:
            msg = "edlib results\n"
            s_query, s_target, _ = squggle(query, target)
            exp_cigar = expand_cigar(edlib_res['cigar'])

            for i in range(0, len(s_query), 80):
                msg += "query:  " + s_query[i:i + 80] + "\n"
                msg += "target: " + s_target[i:i + 80] + "\n"
                msg += "cigar : " + exp_cigar[i:i + 80] + "\n"
                msg += "--------" + 80 * "-" + "\n"

            msg += "query:  " + query + "\n"
            msg += "target: " + target + "\n"
            msg += "full cigar:  " + edlib_res['cigar'] + "\n"
            msg += pformat(
                {dataset_pb2.Cigar.Name(k): v
                 for k, v in stats.items()}) + "\n"
            msg += "readl:  " + str(read_len) + "\n"
            df = pd.DataFrame({
                "query":
                toolz.merge(
                    toolz.frequencies(query),
                    toolz.keymap(
                        "".join,
                        toolz.frequencies(toolz.sliding_window(2, query))),
                ),
                "target":
                toolz.merge(
                    toolz.frequencies(target),
                    toolz.keymap(
                        "".join,
                        toolz.frequencies(toolz.sliding_window(2, target))),
                ),
            })
            df["delta"] = 100 * (df['target'] / df['query'] - 1)
            df = df[['query', 'target', 'delta']]
            msg += "Stats\n" + str(df) + "\n"
            msg += "==================\n"
            logger.info(msg)
    sol = [
        np.array(sol[op], dtype=np.float32) for op in aligment_stats_ordering
    ]
    sol_data = {
        dataset_pb2.Cigar.Name(k): v
        for k, v in zip(aligment_stats_ordering, sol)
    }
    sol_data["IDENTITY"] = identities
    logger.info(f"sol: \n{pd.DataFrame(sol_data)}")
    return sol + [np.array(identities, dtype=np.float32)]
Esempio n. 6
0
 def keymap(self, f):
     return fdict(cytoolz.keymap(f, self))
Esempio n. 7
0
 def json(self):
     return t.keymap(lambda k: k[1:] if k.startswith('_') else k, self.__dict__)
Esempio n. 8
0
 def json(self):
     return t.keymap(lambda k: k[1:] if k.startswith('_') else k,
                     dict(self._asdict()))