def test__pretty(self):
     res = pretty(self.signal1)
     targ = ("IrregularlySampledSignal\n" +
             "name: '%s'\ndescription: '%s'\nannotations: %s" %
             (self.signal1.name, self.signal1.description,
              pretty(self.signal1.annotations)))
     self.assertEqual(res, targ)
Exemple #2
0
def varinfo(var):
    """Pretty print information about a variable."""
    import numpy
    from IPython import get_ipython
    from IPython.lib.pretty import pretty
    from highlighter import highlight
    ip = get_ipython()
    if ip:
        print(ip.inspector._get_info(var)['text/plain'])
    try:
        s = pretty(var, max_seq_length=20)
    except TypeError:
        s = pretty(var)
    lines = s.splitlines()
    if len(lines) > 20:
        s = '\n'.join(lines[:10] + ['...'] + lines[-10:])
    print(highlight(s).strip())
    print(type(var))
    if isinstance(var, numpy.ndarray):
        print(var.shape, var.dtype)
        print('min = {} max = {}'.format(
            numpy.nanmin(var), numpy.nanmax(var)))
        print('mean = {} std = {}'.format(
            numpy.nanmean(var), numpy.nanstd(var)))
    elif isinstance(var, (dict, list, tuple, set)):
        print('n = %d' % len(var))
Exemple #3
0
def test_super_repr():
    output = pretty.pretty(super(SA))
    nt.assert_in("SA", output)

    sb = SB()
    output = pretty.pretty(super(SA, sb))
    nt.assert_in("SA", output)
    def test__pretty(self):
        res = pretty(self.blk1)
        ann = get_annotations()
        ann['seed'] = self.seed1
        ann = pretty(ann).replace('\n ', '\n  ')

        seg0 = pretty(self.segs1[0])
        seg1 = pretty(self.segs1[1])
        seg0 = seg0.replace('\n', '\n   ')
        seg1 = seg1.replace('\n', '\n   ')

        targ = ("Block with " +
                ("%s segments, %s recordingchannelgroups\n" %
                 (len(self.segs1), len(self.rcgs1))) +
                ("name: '%s'\ndescription: '%s'\n" % (self.blk1.name,
                                                      self.blk1.description)) +
                ("annotations: %s\n" % ann) +
                ("file_origin: '%s'\n" % self.blk1.file_origin) +
                ("file_datetime: %s\n" % repr(self.blk1.file_datetime)) +
                ("rec_datetime: %s\n" % repr(self.blk1.rec_datetime)) +
                ("index: %s\n" % self.blk1.index) +


                ("# segments (N=%s)\n" % len(self.segs1)) +
                ('%s: %s\n' % (0, seg0)) +
                ('%s: %s' % (1, seg1)))

        self.assertEqual(res, targ)
Exemple #5
0
def test_super_repr():
    # "<super: module_name.SA, None>"
    output = pretty.pretty(super(SA))
    nt.assert_regexp_matches(output, r"<super: \S+.SA, None>")

    # "<super: module_name.SA, <module_name.SB at 0x...>>"
    sb = SB()
    output = pretty.pretty(super(SA, sb))
    nt.assert_regexp_matches(output, r"<super: \S+.SA,\s+<\S+.SB at 0x\S+>>")
Exemple #6
0
    def test_super_repr(self):
        # "<super: module_name.SA, None>"
        output = pretty.pretty(super(SA))
        self.assertRegex(output, r"<super: \S+.SA, None>")

        # "<super: module_name.SA, <module_name.SB at 0x...>>"
        sb = SB()
        output = pretty.pretty(super(SA, sb))
        self.assertRegex(output, r"<super: \S+.SA,\s+<\S+.SB at 0x\S+>>")
Exemple #7
0
    def test__pretty(self):
        evt = Event([1.1, 1.5, 1.7] * pq.ms,
                    labels=np.array(['test event 1', 'test event 2', 'test event 3'], dtype='S'),
                    name='test', description='tester', file_origin='test.file')
        evt.annotate(test1=1.1, test0=[1, 2])
        assert_neo_object_is_compliant(evt)

        prepr = pretty(evt)
        targ = ("Event\nname: '%s'\ndescription: '%s'\nannotations: %s"
                "" % (evt.name, evt.description, pretty(evt.annotations)))

        self.assertEqual(prepr, targ)
Exemple #8
0
    def test__pretty(self):
        epc = Epoch([1.1, 1.5, 1.7] * pq.ms, durations=[20, 40, 60] * pq.ns,
                    labels=np.array(['test epoch 1', 'test epoch 2', 'test epoch 3'], dtype='S'),
                    name='test', description='tester', file_origin='test.file')
        epc.annotate(test1=1.1, test0=[1, 2])
        assert_neo_object_is_compliant(epc)

        prepr = pretty(epc)
        targ = ("Epoch\nname: '%s'\ndescription: '%s'\nannotations: %s"
                "" % (epc.name, epc.description, pretty(epc.annotations)))

        self.assertEqual(prepr, targ)
    def test__pretty(self):
        epc = Epoch(1.5*pq.ms, duration=20*pq.ns,
                    label='test epoch', name='test', description='tester',
                    file_origin='test.file')
        epc.annotate(targ1=1.1, targ0=[1])
        assert_neo_object_is_compliant(epc)

        prepr = pretty(epc)
        targ = ("Epoch\nname: '%s'\ndescription: '%s'\nannotations: %s" %
                (epc.name, epc.description, pretty(epc.annotations)))

        self.assertEqual(prepr, targ)
Exemple #10
0
    def test__pretty(self):
        evt = Event(1.5 * pq.ms, label="test epoch", name="test", description="tester", file_origin="test.file")
        evt.annotate(targ1=1.1, targ0=[1])
        assert_neo_object_is_compliant(evt)

        prepr = pretty(evt)
        targ = "Event\nname: '%s'\ndescription: '%s'\nannotations: %s" % (
            evt.name,
            evt.description,
            pretty(evt.annotations),
        )

        self.assertEqual(prepr, targ)
Exemple #11
0
def test_unicode_repr():
    u = u"üniçodé"
    ustr = u
    
    class C(object):
        def __repr__(self):
            return ustr
    
    c = C()
    p = pretty.pretty(c)
    nt.assert_equal(p, u)
    p = pretty.pretty([c])
    nt.assert_equal(p, u'[%s]' % u)
Exemple #12
0
def test_function_pretty():
    "Test pretty print of function"
    # posixpath is a pure python module, its interface is consistent
    # across Python distributions
    import posixpath
    nt.assert_equal(pretty.pretty(posixpath.join), '<function posixpath.join(a, *p)>')
 
    # custom function
    def meaning_of_life(question=None):
        if question:
            return 42
        return "Don't panic"

    nt.assert_in('meaning_of_life(question=None)', pretty.pretty(meaning_of_life))
    def test__pretty(self):
        ann = get_annotations()
        ann['seed'] = self.seed1
        ann = pretty(ann).replace('\n ', '\n  ')
        res = pretty(self.rchan1)
        targ = ("RecordingChannel with " +
                ("%s analogsignals, %s irregularlysampledsignals\n" %
                 (len(self.sigs1), len(self.irsigs1))) +
                ("name: '%s'\ndescription: '%s'\n" % (self.rchan1.name,
                                                      self.rchan1.description)
                 ) +
                ("annotations: %s" % ann))

        self.assertEqual(res, targ)
    def test__pretty(self):
        res = pretty(self.unit1)
        ann = get_annotations()
        ann['seed'] = self.seed1
        ann = pretty(ann).replace('\n ', '\n  ')
        targ = ("Unit with " +
                ("%s spikes, %s spiketrains\n" %
                 (len(self.spikes1a), len(self.trains1a))) +
                ("name: '%s'\ndescription: '%s'\n" % (self.unit1.name,
                                                      self.unit1.description)
                 ) +
                ("annotations: %s" % ann))

        self.assertEqual(res, targ)
Exemple #15
0
 def test__pretty(self):
     name = 'an object'
     description = 'this is a test'
     obj = BaseNeo(name=name, description=description)
     res = pretty(obj)
     targ = "BaseNeo name: '%s' description: '%s'" % (name, description)
     self.assertEqual(res, targ)
Exemple #16
0
    def __repr__(self):
        bnds = [
            "edges",
            "nodes",
            "source",
            "destination",
            "node",
            "edge_title",
            "edge_label",
            "edge_color",
            "edge_weight",
            "point_title",
            "point_label",
            "point_color",
            "point_size",
        ]
        stgs = ["height", "url_params"]

        rep = {
            "bindings": dict([(f, getattr(self, "_" + f)) for f in bnds]),
            "settings": dict([(f, getattr(self, "_" + f)) for f in stgs]),
        }
        if util.in_ipython():
            from IPython.lib.pretty import pretty

            return pretty(rep)
        else:
            return str(rep)
Exemple #17
0
def test_collections_deque():
    # Create deque with cycle
    a = deque()
    a.append(a)

    cases = [
        (deque(), 'deque([])'),
        (deque(i for i in range(1000, 1020)),
         'deque([1000,\n'
         '       1001,\n'
         '       1002,\n'
         '       1003,\n'
         '       1004,\n'
         '       1005,\n'
         '       1006,\n'
         '       1007,\n'
         '       1008,\n'
         '       1009,\n'
         '       1010,\n'
         '       1011,\n'
         '       1012,\n'
         '       1013,\n'
         '       1014,\n'
         '       1015,\n'
         '       1016,\n'
         '       1017,\n'
         '       1018,\n'
         '       1019])'),
        (a, 'deque([deque(...)])'),
    ]
    for obj, expected in cases:
        nt.assert_equal(pretty.pretty(obj), expected)
Exemple #18
0
def test_pprint_break_repr():
    """
    Test that p.break_ is used in repr
    """
    output = pretty.pretty(BreakingReprParent())
    expected = "TG: Breaking(\n    ):"
    nt.assert_equal(output, expected)
Exemple #19
0
def test_collections_counter():
    cases = [
        (Counter(), 'Counter()'),
        (Counter(a=1), "Counter({'a': 1})"),
    ]
    for obj, expected in cases:
        nt.assert_equal(pretty.pretty(obj), expected)
Exemple #20
0
def test_pprint_break():
    """
    Test that p.break_ produces expected output
    """
    output = pretty.pretty(Breaking())
    expected = "TG: Breaking(\n    ):"
    nt.assert_equal(output, expected)
    def test__pretty(self):
        res = pretty(self.rcg1)
        ann = get_annotations()
        ann['seed'] = self.seed1
        ann = pretty(ann).replace('\n ', '\n  ')
        targ = ("RecordingChannelGroup with " +
                ("%s units, %s analogsignalarrays, %s recordingchannels\n" %
                 (len(self.units1a),
                  len(self.sigarrs1a),
                  len(self.rchans1a))) +
                ("name: '%s'\ndescription: '%s'\n" % (self.rcg1.name,
                                                      self.rcg1.description)
                 ) +
                ("annotations: %s" % ann))

        self.assertEqual(res, targ)
def test_indentation():
    """Test correct indentation in groups"""
    count = 40
    gotoutput = pretty.pretty(MyList(range(count)))
    expectedoutput = "MyList(\n" + ",\n".join("   %d" % i for i in range(count)) + ")"

    nt.assert_equals(gotoutput, expectedoutput)
Exemple #23
0
def test_pprint_heap_allocated_type():
    """
    Test that pprint works for heap allocated types.
    """
    import xxlimited
    output = pretty.pretty(xxlimited.Null)
    nt.assert_equal(output, 'xxlimited.Null')
Exemple #24
0
def test_dictproxy():
    # This is the dictproxy constructor itself from the Python API,
    DP = ctypes.pythonapi.PyDictProxy_New
    DP.argtypes, DP.restype = (ctypes.py_object,), ctypes.py_object

    underlying_dict = {}
    mp_recursive = DP(underlying_dict)
    underlying_dict[0] = mp_recursive
    underlying_dict[-3] = underlying_dict

    cases = [
        (DP({}), "dict_proxy({})"),
        (DP({None: DP({})}), "dict_proxy({None: dict_proxy({})})"),
        (DP({k: k.lower() for k in string.ascii_uppercase}),
         "dict_proxy({'A': 'a',\n"
         "            'B': 'b',\n"
         "            'C': 'c',\n"
         "            'D': 'd',\n"
         "            'E': 'e',\n"
         "            'F': 'f',\n"
         "            'G': 'g',\n"
         "            'H': 'h',\n"
         "            'I': 'i',\n"
         "            'J': 'j',\n"
         "            'K': 'k',\n"
         "            'L': 'l',\n"
         "            'M': 'm',\n"
         "            'N': 'n',\n"
         "            'O': 'o',\n"
         "            'P': 'p',\n"
         "            'Q': 'q',\n"
         "            'R': 'r',\n"
         "            'S': 's',\n"
         "            'T': 't',\n"
         "            'U': 'u',\n"
         "            'V': 'v',\n"
         "            'W': 'w',\n"
         "            'X': 'x',\n"
         "            'Y': 'y',\n"
         "            'Z': 'z'})"),
        (mp_recursive, "dict_proxy({-3: {-3: {...}, 0: {...}}, 0: {...}})"),
    ]
    for obj, expected in cases:
        nt.assert_is_instance(obj, types.DictProxyType) # Meta-test
        nt.assert_equal(pretty.pretty(obj), expected)
    nt.assert_equal(pretty.pretty(underlying_dict),
                    "{-3: {...}, 0: dict_proxy({-3: {...}, 0: {...}})}")
 def test__pretty(self):
     name = 'an object'
     description = 'this is a test'
     obj = Container(name=name, description=description)
     res = pretty(obj)
     targ = "Container with  name: '%s' description: '%s'" % (name,
                                                              description)
     self.assertEqual(res, targ)
 def test__pretty(self):
     res = pretty(self.signal1)
     signal = self.signal1
     targ = (("IrregularlySampledSignal with %d channels of length %d; units %s; datatype %s \n" % (signal.shape[1], signal.shape[0], signal.units.dimensionality.unicode, signal.dtype)) +
             ("name: '%s'\ndescription: '%s'\n" % (signal.name, signal.description)) +
             ("annotations: %s\n" % str(signal.annotations)) +
             ("sample times: %s" % (signal.times[:10],)))
     self.assertEqual(res, targ)
 def test__pretty(self):
     ann = {'targ0': self.spike1.annotations['test0']}
     self.spike1.annotations = ann
     res = pretty(self.spike1)
     targ = ("Spike " +
             "name: '%s' description: '%s' annotations: %s" %
             (self.spike1.name, self.spike1.description, ann))
     self.assertEqual(res, targ)
Exemple #28
0
def _uprint(obj, ret=False):
    try:
        from IPython.lib.pretty import pretty
    except Exception:
        from pprint import pformat as pretty
    print(pretty(obj).decode('unicode-escape'))
    if ret:
        return obj
Exemple #29
0
def getsource(obj, oname=""):
    """Wrapper around inspect.getsource.

    This can be modified by other projects to provide customized source
    extraction.

    Parameters
    ----------
    obj : object
        an object whose source code we will attempt to extract
    oname : str
        (optional) a name under which the object is known

    Returns
    -------
    src : unicode or None

    """

    if isinstance(obj, property):
        sources = []
        for attrname in ["fget", "fset", "fdel"]:
            fn = getattr(obj, attrname)
            if fn is not None:
                encoding = get_encoding(fn)
                oname_prefix = ("%s." % oname) if oname else ""
                sources.append(cast_unicode("".join(("# ", oname_prefix, attrname)), encoding=encoding))
                if inspect.isfunction(fn):
                    sources.append(dedent(getsource(fn)))
                else:
                    # Default str/repr only prints function name,
                    # pretty.pretty prints module name too.
                    sources.append(
                        cast_unicode("%s%s = %s\n" % (oname_prefix, attrname, pretty(fn)), encoding=encoding)
                    )
        if sources:
            return "\n".join(sources)
        else:
            return None

    else:
        # Get source for non-property objects.

        obj = _get_wrapped(obj)

        try:
            src = inspect.getsource(obj)
        except TypeError:
            # The object itself provided no meaningful source, try looking for
            # its class definition instead.
            if hasattr(obj, "__class__"):
                try:
                    src = inspect.getsource(obj.__class__)
                except TypeError:
                    return None

        encoding = get_encoding(obj)
        return cast_unicode(src, encoding=encoding)
Exemple #30
0
 def _log_pretty_(self, p, cycle): # remove _
     if cycle:
         p.text('HookFunction(..)')
         return
     with p.group(len(self.log_prefix), self.log_prefix):
         p.text( pretty(self.field_value))
         p.text(' was set into ')
         p.breakable()
         p.text(self.field_name)
Exemple #31
0
def test_simplenamespace():
    SN = types.SimpleNamespace

    sn_recursive = SN()
    sn_recursive.first = sn_recursive
    sn_recursive.second = sn_recursive
    cases = [
        (SN(), "namespace()"),
        (SN(x=SN()), "namespace(x=namespace())"),
        (SN(a_long_name=[SN(s=string.ascii_lowercase)] * 3, a_short_name=None),
         "namespace(a_long_name=[namespace(s='abcdefghijklmnopqrstuvwxyz'),\n"
         "                       namespace(s='abcdefghijklmnopqrstuvwxyz'),\n"
         "                       namespace(s='abcdefghijklmnopqrstuvwxyz')],\n"
         "          a_short_name=None)"),
        (sn_recursive,
         "namespace(first=namespace(...), second=namespace(...))"),
    ]
    for obj, expected in cases:
        assert pretty.pretty(obj) == expected
    def _repr_pretty_(self, p, cycle):
        from IPython.lib.pretty import pretty

        if cycle:
            p.text('...')
            return

        for key, item in six.iteritems(self):
            p.text('[%s]' % key)
            p.break_()
            with p.indent(1):
                for line in pretty(item).splitlines():
                    p.break_()
                    p.text(line)
            p.break_()
            p.break_()

        if getattr(self, 'performance'):
            p.text(self._performance_str_())
Exemple #33
0
def test_mappingproxy():
    MP = types.MappingProxyType
    underlying_dict = {}
    mp_recursive = MP(underlying_dict)
    underlying_dict[2] = mp_recursive
    underlying_dict[3] = underlying_dict

    cases = [
        (MP({}), "mappingproxy({})"),
        (MP({None: MP({})}), "mappingproxy({None: mappingproxy({})})"),
        (MP({k: k.upper() for k in string.ascii_lowercase}),
         "mappingproxy({'a': 'A',\n"
         "              'b': 'B',\n"
         "              'c': 'C',\n"
         "              'd': 'D',\n"
         "              'e': 'E',\n"
         "              'f': 'F',\n"
         "              'g': 'G',\n"
         "              'h': 'H',\n"
         "              'i': 'I',\n"
         "              'j': 'J',\n"
         "              'k': 'K',\n"
         "              'l': 'L',\n"
         "              'm': 'M',\n"
         "              'n': 'N',\n"
         "              'o': 'O',\n"
         "              'p': 'P',\n"
         "              'q': 'Q',\n"
         "              'r': 'R',\n"
         "              's': 'S',\n"
         "              't': 'T',\n"
         "              'u': 'U',\n"
         "              'v': 'V',\n"
         "              'w': 'W',\n"
         "              'x': 'X',\n"
         "              'y': 'Y',\n"
         "              'z': 'Z'})"),
        (mp_recursive, "mappingproxy({2: {...}, 3: {2: {...}, 3: {...}}})"),
        (underlying_dict,
         "{2: mappingproxy({2: {...}, 3: {...}}), 3: {...}}"),
    ]
    for obj, expected in cases:
        nt.assert_equal(pretty.pretty(obj), expected)
def test_sets():
    """
    Test that set and frozenset use Python 3 formatting.
    """
    objects = [
        set(),
        frozenset(),
        set([1]),
        frozenset([1]),
        set([1, 2]),
        frozenset([1, 2]),
        set([-1, -2, -3])
    ]
    expected = [
        'set()', 'frozenset()', '{1}', 'frozenset({1})', '{1, 2}',
        'frozenset({1, 2})', '{-3, -2, -1}'
    ]
    for obj, expected_output in zip(objects, expected):
        got_output = pretty.pretty(obj)
        yield nt.assert_equal, got_output, expected_output
Exemple #35
0
def test_collections_defaultdict():
    # Create defaultdicts with cycles
    a = defaultdict()
    a.default_factory = a
    b = defaultdict(list)
    b["key"] = b

    # Dictionary order cannot be relied on, test against single keys.
    cases = [
        (defaultdict(list), "defaultdict(list, {})"),
        (
            defaultdict(list, {"key": "-" * 50}),
            "defaultdict(list,\n"
            "            {'key': '--------------------------------------------------'})",
        ),
        (a, "defaultdict(defaultdict(...), {})"),
        (b, "defaultdict(list, {'key': defaultdict(...)})"),
    ]
    for obj, expected in cases:
        nt.assert_equal(pretty.pretty(obj), expected)
Exemple #36
0
    def __repr__(self):
        bindings = [
            'edges', 'nodes', 'source', 'destination', 'node', 'edge_label',
            'edge_color', 'edge_size', 'edge_weight', 'edge_title',
            'edge_icon', 'edge_opacity', 'edge_source_color',
            'edge_destination_color', 'point_label', 'point_color',
            'point_size', 'point_weight', 'point_title', 'point_icon',
            'point_opacity', 'point_x', 'point_y'
        ]
        settings = ['height', 'url_params']

        rep = {
            'bindings': dict([(f, getattr(self, '_' + f)) for f in bindings]),
            'settings': dict([(f, getattr(self, '_' + f)) for f in settings])
        }
        if util.in_ipython():
            from IPython.lib.pretty import pretty
            return pretty(rep)
        else:
            return str(rep)
Exemple #37
0
    def test_same_layout(self, g2):
        e1, e2 = g2.basis_vectors_lst

        dual_matrix = np.array([
            [ 0,  0, 0, 1],
            [ 0,  0, 1, 0],
            [ 0, -1, 0, 0],
            [-1,  0, 0, 0]
        ])
        f_dual = transformations.LinearMatrix(dual_matrix, g2)
        x = 1 + 2*e2 + 3*e1*e2
        assert f_dual(x) == x.dual()

        assert pretty.pretty(f_dual) == textwrap.dedent("""\
        LinearMatrix(array([[ 0,  0,  0,  1],
                            [ 0,  0,  1,  0],
                            [ 0, -1,  0,  0],
                            [-1,  0,  0,  0]]),
                     Layout([1, 1],
                            ids=BasisVectorIds(['u', 'v']),
                            order=BasisBladeOrder.shortlex(2),
                            names=['', 'eu', 'ev', 'euv']))""")
def test_collections_ordereddict():
    # Create OrderedDict with cycle
    a = OrderedDict()
    a['key'] = a

    cases = [
        (OrderedDict(), 'OrderedDict()'),
        (OrderedDict(
            (i, i) for i in range(1000, 1010)), 'OrderedDict([(1000, 1000),\n'
         '             (1001, 1001),\n'
         '             (1002, 1002),\n'
         '             (1003, 1003),\n'
         '             (1004, 1004),\n'
         '             (1005, 1005),\n'
         '             (1006, 1006),\n'
         '             (1007, 1007),\n'
         '             (1008, 1008),\n'
         '             (1009, 1009)])'),
        (a, "OrderedDict([('key', OrderedDict(...))])"),
    ]
    for obj, expected in cases:
        nt.assert_equal(pretty.pretty(obj), expected)
Exemple #39
0
def test_helper_parantheses():
    class A(object):
        def __repr__(self):
            r = ReprHelper(self)
            r.parantheses = ('<', '>')
            r.keyword_with_value('id', hex(id(self)), raw=True)
            return str(r)

        def _repr_pretty_(self, p, cycle):
            r = PrettyReprHelper(self, p, cycle)
            r.parantheses = ('<', '>')
            with r:
                r.keyword_with_value('id', hex(id(self)), raw=True)

    a = A()
    assert repr(a) == 'A<id={}>'.format(hex(id(a)))
    assert pretty(a) == 'A<id={}>'.format(hex(id(a)))

    # Test namedtuple for parantheses property
    r = ReprHelper(a)
    assert repr(r.parantheses) == "Parantheses(left='(', right=')')"
    r.parantheses = ('<', '>')
    assert repr(r.parantheses) == "Parantheses(left='<', right='>')"
Exemple #40
0
    def _repr_pretty_(self, p, cycle):
        """Print list of interfaces in IPython.

    Args:
      p: Pretty printer to pass output to.
      cycle: True, if printer detected a cycle.

    Returns:
      Nothing.
    """
        if cycle:
            raise AssertionError('Cycle in an interface list')

        if not self:
            p.text('No results.')
            return

        with p.group(0, '', ''):
            p.group_stack[-1].want_break = True

            for iface in self:
                p.breakable()
                p.text(pretty.pretty(_InterfaceData(iface)))
Exemple #41
0
    def _repr_pretty_(self, p: pretty.PrettyPrinter, cycle: bool) -> None:
        """Print list of clients in IPython.

    Args:
      p: Pretty printer to pass output to.
      cycle: True, if printer detected a cycle.

    Returns:
      Nothing.
    """
        if cycle:
            raise AssertionError('Cycle in a client list')

        if not self:
            p.text('No results.')
            return

        with p.group(0, '', ''):
            p.group_stack[-1].want_break = True

            for c in self:
                p.breakable()
                p.text(pretty.pretty(c))
            p.breakable()
Exemple #42
0
    def test_invariants(self, g2):
        e1, e2 = g2.basis_vectors_lst

        matrix = np.array([[ 0, 1],
                           [-1, 0]])
        f = transformations.OutermorphismMatrix(matrix, g2)

        # test the vector transform is as requested
        assert f(e1) == -e2
        assert f(e2) == e1
        # test the generalization is correct
        assert f(e1^e2) == f(e1)^f(e2)
        assert f(g2.scalar) == g2.scalar

        # test that distributivity is respected
        assert f(g2.scalar + 2*e1 + 3*(e1^e2)) == f(g2.scalar) + 2*f(e1) + 3*f(e1^e2)

        assert pretty.pretty(f) == textwrap.dedent("""\
        OutermorphismMatrix(array([[ 0,  1],
                                   [-1,  0]]),
                            Layout([1, 1],
                                   ids=BasisVectorIds(['u', 'v']),
                                   order=BasisBladeOrder.shortlex(2),
                                   names=['', 'eu', 'ev', 'euv']))""")
Exemple #43
0
def test_pprint_nomod():
    """
    Test that pprint works for classes with no __module__.
    """
    output = pretty.pretty(NoModule)
    assert output == "NoModule"
Exemple #44
0
def test_pretty_environ():
    dict_repr = pretty.pretty(dict(os.environ))
    # reindent to align with 'environ' prefix
    dict_indented = dict_repr.replace('\n', '\n' + (' ' * len('environ')))
    env_repr = pretty.pretty(os.environ)
    nt.assert_equal(env_repr, 'environ' + dict_indented)
Exemple #45
0
def test_metaclass_repr():
    output = pretty.pretty(ClassWithMeta)
    assert output == "[CUSTOM REPR FOR CLASS ClassWithMeta]"
Exemple #46
0
def getsource(obj, oname=''):
    """Wrapper around inspect.getsource.

    This can be modified by other projects to provide customized source
    extraction.

    Parameters
    ----------
    obj : object
        an object whose source code we will attempt to extract
    oname : str
        (optional) a name under which the object is known

    Returns
    -------
    src : unicode or None

    """

    if isinstance(obj, property):
        sources = []
        for attrname in ['fget', 'fset', 'fdel']:
            fn = getattr(obj, attrname)
            if fn is not None:
                encoding = get_encoding(fn)
                oname_prefix = ('%s.' % oname) if oname else ''
                sources.append(
                    cast_unicode(''.join(('# ', oname_prefix, attrname)),
                                 encoding=encoding))
                if inspect.isfunction(fn):
                    sources.append(dedent(getsource(fn)))
                else:
                    # Default str/repr only prints function name,
                    # pretty.pretty prints module name too.
                    sources.append(
                        cast_unicode('%s%s = %s\n' %
                                     (oname_prefix, attrname, pretty(fn)),
                                     encoding=encoding))
        if sources:
            return '\n'.join(sources)
        else:
            return None

    else:
        # Get source for non-property objects.

        obj = _get_wrapped(obj)

        try:
            src = inspect.getsource(obj)
        except TypeError:
            # The object itself provided no meaningful source, try looking for
            # its class definition instead.
            if hasattr(obj, '__class__'):
                try:
                    src = inspect.getsource(obj.__class__)
                except TypeError:
                    return None

        encoding = get_encoding(obj)
        return cast_unicode(src, encoding=encoding)
Exemple #47
0
def main():
    from pyqgl2.qreg import QRegister
    import pyqgl2.test_cl
    from pyqgl2.main import compile_function, qgl2_compile_to_hardware
    import numpy as np

    toHW = True
    plotPulses = False  # This tries to produce graphics to display
    pyqgl2.test_cl.create_default_channelLibrary(toHW, True)

    #    # To turn on verbose logging in compile_function
    #    from pyqgl2.ast_util import NodeError
    #    from pyqgl2.debugmsg import DebugMsg
    #    NodeError.MUTE_ERR_LEVEL = NodeError.NODE_ERROR_NONE
    #    DebugMsg.set_level(0)

    # Now compile the QGL2 to produce the function that would generate the expected sequence.
    # Supply the path to the QGL2, the main function in that file, and a list of the args to that function.
    # Can optionally supply saveOutput=True to save the qgl1.py
    # file,
    # and intermediate_output="path-to-output-file" to save
    # intermediate products

    # Pass in QRegister(s) NOT real Qubits
    q1 = QRegister("q1")

    # Axis Descriptor generator functions here
    # This is ugly; they're method dependent, but I can't do them in the QGL2 itself
    # Additionally, each uses values from the args to the function
    # So here we make those arguments be constants so we can use them twice
    # without rewriting the values
    hahnSpacings = np.linspace(0, 5e-6, 11)
    tCalR = 2  # calRepeats
    cpmgNumPulses = [0, 2, 4, 6]
    cpmgSpacing = 500e-9

    def getHahnAxisDesc(pulseSpacings, calRepeats):
        return [
            delay_descriptor(2 * pulseSpacings),
            cal_descriptor(('qubit', ), calRepeats)
        ]

    def getCPMGAxisDesc(pulseSpacing, numPulses, calRepeats):
        return [
            # NOTE: numPulses is not a numpy array, so cannot multiply by a float
            # But thankfully, np.array(np.array) = np.array so this is always a good move here.
            delay_descriptor(pulseSpacing * np.array(numPulses)),
            cal_descriptor(('qubit', ), calRepeats)
        ]

    # FIXME: See issue #44: Must supply all args to qgl2main for now


#    for func, args, label, axisDesc in [("HahnEcho", (q1, hahnSpacings), "Echo", getHahnAxisDesc(hahnSpacings, tCalR)),
#                              ("CPMG", (q1, cpmgNumPulses, cpmgSpacing), "CPMG", getCPMGAxisDesc(cpmgSpacing, cpmgNumPulses, tCalR)),
#                          ]:
    for func, args, label, axisDesc in [
        ("HahnEcho", (q1, hahnSpacings, 0, tCalR), "Echo",
         getHahnAxisDesc(hahnSpacings, tCalR)),
        ("CPMG", (q1, cpmgNumPulses, cpmgSpacing, tCalR), "CPMG",
         getCPMGAxisDesc(cpmgSpacing, cpmgNumPulses, tCalR)),
    ]:

        print(f"\nRun {func}...")
        # Here we know the function is in the current file
        # You could use os.path.dirname(os.path.realpath(__file)) to find files relative to this script,
        # Or os.getcwd() to get files relative to where you ran from. Or always use absolute paths.
        resFunc = compile_function(__file__, func, args)
        # Run the QGL2. Note that the generated function takes no arguments itself
        seq = resFunc()
        if toHW:
            print(f"Compiling {func} sequences to hardware\n")
            fileNames = qgl2_compile_to_hardware(seq,
                                                 filename=f'{label}/{label}',
                                                 axis_descriptor=axisDesc)
            print(f"Compiled sequences; metafile = {fileNames}")
            if plotPulses:
                from QGL.PulseSequencePlotter import plot_pulse_files
                # FIXME: As called, this returns a graphical object to display
                plot_pulse_files(fileNames)
        else:
            print(f"\nGenerated {func} sequences:\n")
            from QGL.Scheduler import schedule

            scheduled_seq = schedule(seq)
            from IPython.lib.pretty import pretty
            print(pretty(scheduled_seq))
def test_bad_repr():
    """Don't catch bad repr errors"""
    with nt.assert_raises(ZeroDivisionError):
        output = pretty.pretty(BadRepr())
def test_custom_repr():
    """A custom repr should override a pretty printer for a parent type"""
    oc = OrderedCounter("abracadabra")
    nt.assert_in("OrderedCounter(OrderedDict", pretty.pretty(oc))

    nt.assert_equal(pretty.pretty(MySet()), 'mine')
def test_unbound_method():
    output = pretty.pretty(MyObj.somemethod)
    nt.assert_in('MyObj.somemethod', output)
def test_metaclass_repr():
    output = pretty.pretty(ClassWithMeta)
    nt.assert_equal(output, "[CUSTOM REPR FOR CLASS ClassWithMeta]")
def test_long_tuple():
    tup = tuple(range(10000))
    p = pretty.pretty(tup)
    last2 = p.rsplit('\n', 2)[-2:]
    nt.assert_equal(last2, [' 999,', ' ...)'])
def test_long_dict():
    d = {n: n for n in range(10000)}
    p = pretty.pretty(d)
    last2 = p.rsplit('\n', 2)[-2:]
    nt.assert_equal(last2, [' 999: 999,', ' ...}'])
def test_long_set():
    s = set(range(10000))
    p = pretty.pretty(s)
    last2 = p.rsplit('\n', 2)[-2:]
    nt.assert_equal(last2, [' 999,', ' ...}'])
def test_long_list():
    lis = list(range(10000))
    p = pretty.pretty(lis)
    last2 = p.rsplit('\n', 2)[-2:]
    nt.assert_equal(last2, [' 999,', ' ...]'])
def test_really_bad_repr():
    with nt.assert_raises(BadException):
        output = pretty.pretty(ReallyBadRepr())
Exemple #57
0
def test_sets(obj, expected_output):
    """
    Test that set and frozenset use Python 3 formatting.
    """
    got_output = pretty.pretty(obj)
    assert got_output == expected_output
Exemple #58
0
def format_code(code, language):
    if language == 'lisp':
        return pretty.pretty(SExprWrapper(code))
    else:
        raise NotImplementedError(language)
Exemple #59
0
 def test_unbound_method(self):
     output = pretty.pretty(MyObj.somemethod)
     self.assertIn('MyObj.somemethod', output)
def test_pprint_nomod():
    """
    Test that pprint works for classes with no __module__.
    """
    output = pretty.pretty(NoModule)
    nt.assert_equal(output, 'NoModule')