Example #1
0
def ensure_float01(img, dtype=np.float32, copy=True):
    """
    Ensure that an image is encoded using a float32 properly

    Args:
        img (ndarray): an image in uint255 or float01 format.
            Other formats will raise errors.
        dtype (type, default=np.float32): a numpy floating type
        copy (bool, default=False): always copy if True, else copy if needed.

    Returns:
        ndarray: an array of floats in the range 0-1

    Raises:
        ValueError : if the image type is integer and not in [0-255]

    Example:
        >>> ensure_float01(np.array([[0, .5, 1.0]]))
        array([[0. , 0.5, 1. ]], dtype=float32)
        >>> ensure_float01(np.array([[0, 1, 200]]))
        array([[0..., 0.0039..., 0.784...]], dtype=float32)
    """
    if img.dtype.kind in ('i', 'u'):
        if img.dtype.kind != 'u' or img.dtype.itemsize != 1:
            # Only check min/max if the image is not a uint8
            if img.min() < 0 or img.max() > 255:
                import kwarray
                raise ValueError(
                    'The image type is int, but its values are not '
                    'between 0 and 255. Image stats are {}'.format(
                        kwarray.stats_dict(img)))
        img_ = img.astype(dtype, copy=copy) / 255.0
    else:
        img_ = img.astype(dtype, copy=copy)
    return img_
Example #2
0
 def measure(self):
     import kwarray
     current_params = _get_named_params(self.model)
     ret = layer_rotation(current_params, self.init_params)
     values = np.array([v for n, v in ret])
     self.stats = kwarray.stats_dict(values, median=True)
     return self.stats
Example #3
0
def ensure_uint255(img, copy=True):
    """
    Ensure that an image is encoded using a uint8 properly. Either

    Args:
        img (ndarray): an image in uint255 or float01 format.
            Other formats will raise errors.
        copy (bool, default=False): always copy if True, else copy if needed.

    Returns:
        ndarray: an array of bytes in the range 0-255

    Raises:
        ValueError : if the image type is float and not in [0-1]
        ValueError : if the image type is integer and not in [0-255]

    Example:
        >>> ensure_uint255(np.array([[0, .5, 1.0]]))
        array([[  0, 127, 255]], dtype=uint8)
        >>> ensure_uint255(np.array([[0, 1, 200]]))
        array([[  0,   1, 200]], dtype=uint8)
    """
    if img.dtype.kind == 'u':
        img_ = img.astype(np.uint8, copy=copy)
    elif img.dtype.kind == 'i':
        if img.min() < 0 or img.max() > 255:
            import kwarray
            raise AssertionError(
                'The image type is signed int, but its values are not '
                'between 0 and 255. Image stats are {}'.format(
                    kwarray.stats_dict(img)))
        img_ = img.astype(np.uint8, copy=copy)
    else:
        # If the image is a float check that it is between 0 and 1
        # Use a +- epsilon of 1e-3 to account for floating errors
        eps = 1e-3
        if (img.min() < (0 - eps) or img.max() > (1 + eps)):
            import kwarray
            raise ValueError('The image type is float, but its values are not '
                             'between 0 and 1. Image stats are {}'.format(
                                 kwarray.stats_dict(img)))
        img_ = (img.clip(0, 1) * 255).astype(np.uint8, copy=copy)
    return img_
Example #4
0
def test_last_digits():

    mapping = {}
    tail_edge_hist = ub.ddict(lambda: 0)

    for x in ub.ProgIter(range(1, int(1e5))):
        import ubelt as ub
        for y in collatz(x):
            if x in mapping:
                break
            x_tail = x - (10 * (x // 10))
            y_tail = y - (10 * (y // 10))
            mapping[x] = y
            tail_edge_hist[(str(x_tail), str(y_tail))] += 1
            x = y

    import kwarray
    print(kwarray.stats_dict(np.array(list(tail_edge_hist.values()))))

    import networkx as nx
    tail_g = nx.DiGraph()
    tail_g.add_edges_from(tail_edge_hist.keys())

    for cycle in nx.simple_cycles(tail_g):
        print('cycle = {!r}'.format(cycle))

    print('tail_g.adj = {!r}'.format(tail_g.adj))

    for n in sorted(tail_g.nodes, key=int):
        pred = tuple(tail_g.pred[n].keys())
        succ = tuple(tail_g.succ[n].keys())
        in_d = tail_g.in_degree(n)
        out_d = tail_g.out_degree(n)
        print(
            f'{str(pred):>15} -> {n:>2} -> {str(succ):<15} : {out_d:<2} {in_d:<2}'
        )

    import kwplot
    import graphid
    plt = kwplot.autoplt()
    sccs = list(nx.strongly_connected_components(tail_g))
    nx.draw_networkx(tail_g)
    # nx.draw_circular(tail_g)

    ax = plt.gca()
    ax.cla()
    # nx.draw_networkx(tail_g)
    graphid.util.util_graphviz.show_nx(tail_g)

    CCs = list(nx.connected_components(tail_g.to_undirected()))
Example #5
0
def count_ubelt_usage():
    """
    import sys, ubelt
    sys.path.append(ubelt.expandpath('~/code/ubelt/dev'))
    from gen_api_for_docs import *  # NOQA
    """
    from count_usage_freq import count_ubelt_usage
    usage = count_ubelt_usage()

    import numpy as np
    import kwarray
    import ubelt as ub

    gaurd = ('=' * 64 + ' ' + '=' * 16)
    print(gaurd)
    print('{:<64} {:>8}'.format(' Function name ', 'Usefulness'))
    print(gaurd)
    for key, value in usage.items():
        print('{:<64} {:>16}'.format(':func:`ubelt.' + key + '`', value))
    print(gaurd)

    raw_scores = np.array(list(usage.values()))

    print('\n.. code:: python\n')
    print(
        ub.indent('usage stats = ' + ub.repr2(
            kwarray.stats_dict(raw_scores, median=True, sum=True), nl=1)))

    for attrname in ub.__all__:
        member = getattr(ub, attrname)

        submembers = getattr(member, '__all__', None)

        if attrname.startswith('util_'):
            if not submembers:
                from mkinit.static_mkinit import _extract_attributes
                submembers = _extract_attributes(member.__file__)

        if submembers:
            print('\n:mod:`ubelt.{}`'.format(attrname))
            print('-------------')
            for subname in submembers:
                if not subname.startswith('_'):
                    print(':func:`ubelt.{}`'.format(subname))
            submembers = dir(member)
Example #6
0
        elif strategy == 'loop':
            chosen_indexes = []
            next_choice = player_index
            for chance_index in range(allowed_chances):
                chosen_indexes.append(next_choice)
                result = boxes[next_choice]
                next_choice = result
        else:
            raise NotImplementedError
        selected = boxes[chosen_indexes]
        success = player_index in selected
        num_success += success
    return num_success


num_monte_carlo_trials = 1000
results = [
    run_iteration(strategy='random') for _ in range(num_monte_carlo_trials)
]
print(ub.repr2(kwarray.stats_dict(results, n_extreme=True), nl=0))

results = [
    run_iteration(strategy='shift') for _ in range(num_monte_carlo_trials)
]
print(ub.repr2(kwarray.stats_dict(results, n_extreme=True), nl=0))

results = [
    run_iteration(strategy='loop') for _ in range(num_monte_carlo_trials)
]
print(ub.repr2(kwarray.stats_dict(results, n_extreme=True), nl=0))
Example #7
0
def count_ubelt_usage():
    """
    import sys, ubelt
    sys.path.append(ubelt.expandpath('~/code/ubelt/dev'))
    from gen_api_for_docs import *  # NOQA
    """
    from count_usage_freq import count_ubelt_usage
    usage = count_ubelt_usage()

    # Reorgnaize data to contain more information
    rows = []
    unseen = usage.copy()
    import ubelt as ub
    for attrname in ub.__all__:
        member = getattr(ub, attrname)
        submembers = getattr(member, '__all__', None)
        if attrname.startswith('util_'):
            if not submembers:
                from mkinit.static_mkinit import _extract_attributes
                submembers = _extract_attributes(member.__file__)
        if submembers:
            for subname in submembers:
                parent_module = 'ubelt.{}'.format(attrname)
                short_name = 'ubelt.{subname}'.format(**locals())
                full_name = '{parent_module}.{subname}'.format(**locals())
                url = 'https://ubelt.readthedocs.io/en/latest/{parent_module}.html#{full_name}'.format(
                    **locals())
                rst_ref = ':func:`{short_name}<{full_name}>`'.format(
                    **locals())
                url_ref = '`{short_name} <{url}>`__'.format(**locals())
                rows.append({
                    'attr': subname,
                    'parent_module': parent_module,
                    'usage': unseen.pop(subname, 0),
                    'short_name': short_name,
                    'full_name': full_name,
                    'url': url,
                    'rst_ref': rst_ref,
                    'url_ref': url_ref,
                })

    attr_to_infos = ub.group_items(rows, lambda x: x['attr'])

    import numpy as np
    import kwarray
    import ubelt as ub

    if ub.argflag('--url-mode'):
        ref_key = 'url_ref'
    else:
        ref_key = 'rst_ref'

    name_len = max(len(row[ref_key]) for row in rows) + 1
    num_len = 16

    gaurd = ('=' * name_len + ' ' + '=' * num_len)
    print(gaurd)
    column_fmt = '{:<' + str(name_len) + '} {:>' + str(num_len) + '}'
    print(column_fmt.format(' Function name ', 'Usefulness'))
    print(gaurd)
    for key, value in usage.items():
        infos = attr_to_infos[key]
        if len(infos) == 0:
            print(column_fmt.format(':func:`ubelt.' + key + '`', value))
        else:
            assert len(infos) == 1
            info = infos[0]
            print(column_fmt.format(info[ref_key], value))
    print(gaurd)

    raw_scores = np.array(list(usage.values()))

    print('\n.. code:: python\n')
    print(
        ub.indent('usage stats = ' + ub.repr2(
            kwarray.stats_dict(raw_scores, median=True, sum=True), nl=1)))

    for attrname in ub.__all__:
        member = getattr(ub, attrname)

        submembers = getattr(member, '__all__', None)

        if attrname.startswith('util_'):
            if not submembers:
                from mkinit.static_mkinit import _extract_attributes
                submembers = _extract_attributes(member.__file__)

        if submembers:
            parent_module = 'ubelt.{}'.format(attrname)

            title = ':mod:`{}`'.format(parent_module)
            print('\n' + title)
            print('-' * len(title))
            for subname in submembers:
                if not subname.startswith('_'):
                    rst_ref = (
                        ':func:`<ubelt.{subname}><{parent_module}.{subname}>`'
                    ).format(subname=subname, parent_module=parent_module)
                    print(rst_ref)
            submembers = dir(member)