File: console.py

package info (click to toggle)
python-bumps 1.0.0b2-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 6,144 kB
  • sloc: python: 23,941; xml: 493; ansic: 373; makefile: 209; sh: 91; javascript: 90
file content (214 lines) | stat: -rw-r--r-- 6,680 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
"""
Interactive console widget support.

Defines NumpyConsole class.

TODO: Fix cut/paste for multiline commands
TODO: Trigger change notification when numpy array has changed
"""

import wx, wx.py


def shapestr(v):
    """Return shape string for numeric variables suitable for printing"""
    try:
        shape = v.shape
    except AttributeError:
        return "scalar"
    else:
        return "array " + "x".join([str(i) for i in shape])


class NumpyConsole(wx.py.shell.ShellFrame):
    """
    NumpyConsole defines an interactive console which is aware of all the
    numerical variables in the local name space.  When variables are added
    or removed, it signals that the set of variables has changed.

    This is intended to be used as an embedded console in an interactive
    application for which the user can define and manipulate numerical
    types and automatically show a list of variables, e.g., available for
    plotting.

    If you subclass and replace self.init_code, be sure to do so _before_ calling
    the superclass __init__.
    """

    # code to define the initial namespace
    init_code = """
from pylab import *
"""
    introText = """
Welcome to the numpy console!

Example:

x = linspace(0,1,300)
y = sin(2*pi*x*3)
vars()
plot(x,y)
"""

    def __init__(self, *args, **kwargs):
        # Start interpreter and monitor statement execution
        msg = kwargs.pop("introText", self.introText)
        wx.py.shell.ShellFrame.__init__(self, *args, **kwargs)

        # Print welcome message.
        # TODO: replace this when (if?) ShellFrame allows introText=msg
        print(msg, file=self.shell)
        self.shell.prompt()

        # Initialize the interpreter namespace with useful commands
        self.shell.interp.runcode(compile(self.init_code, "__main__", "exec"))

        # steal draw_if_interactive
        import pylab
        from matplotlib._pylab_helpers import Gcf
        from matplotlib import pyplot

        self._dirty = set()

        def draw_if_interactive():
            # print "calling draw_if_interactive with",Gcf.get_active()
            self._dirty.add(Gcf.get_active())

        pyplot.draw_if_interactive = draw_if_interactive

        # add vars command to the interpreter
        self.shell.interp.locals["vars"] = self._print_vars

        # ignore the variables defined by numpy
        self.ignore = set(self.shell.interp.locals.keys())
        self._existing = {}  # No new variables recorded yet

        # remember which variables are current so we can detect changes
        wx.py.dispatcher.connect(receiver=self._onPush, signal="Interpreter.push")

    def filter(self, key, value):
        """
        Return True if var should be listed in the available variables.
        """
        return key not in self.ignore

    # Dictionary interface
    def items(self):
        """
        Return the list of key,value pairs for all locals not ignored.
        """
        locals = self.shell.interp.locals
        for k, v in locals.items():
            if self.filter(k, v):
                yield k, v

    def update(self, *args, **kw):
        """
        Update a set of variables from a dictionary.
        """
        self.shell.interp.locals.update(*args, **kw)
        self._existing.update(*args, **kw)

    def __setitem__(self, var, val):
        """
        Define or replace a variable in the interpreter.
        """
        self.shell.interp.locals[var] = val
        self._existing[var] = val

    def __getitem__(self, var):
        """
        Retrieve a variable from the interpreter.
        """
        return self.shell.interp.locals[var]

    def __delitem__(self, var):
        """
        Delete a variable from the interpreter.
        """
        del self.shell.interp.locals[var]
        try:
            del self._existing[var]
        except KeyError:
            pass

    # Stream interface
    def write(self, msg):
        """
        Support 'print >>console, blah' for putting output on console.

        TODO: Maybe redirect stdout to console if console is open?
        """
        self.shell.write(self, msg)

    # ==== Internal messages ====
    def OnChanged(self, added=[], changed=[], removed=[]):
        """
        Override this method to perform your changed operation.

        Note that we cannot detect changes within a variable without considerable
        effort: we would need to keep a deep copy of the original value, and
        use a deep comparison to see if it has changed.
        """
        for var in added:
            print("added", var, file=self.shell)
        for var in changed:
            print("changed", var, file=self.shell)
        for var in removed:
            print("deleted", var, file=self.shell)
        print("override the OnChanged message to update your application state", file=self.shell)

    def _print_vars(self):
        """
        Print the available numeric variables and their shapes.

        This is a command available to the user as vars().
        """
        locals = self.shell.interp.locals
        for k, v in self.items():
            print(k, shapestr(v), file=self.shell)

    def _onPush(self, **kw):
        """On command execution, detect if variable list has changed."""
        # Note: checking for modify is too hard ... build it into the types?
        # print >>self.shell, "checking for add/delete..."
        # Update graphs if changed
        if self._dirty:
            import pylab
            from matplotlib._pylab_helpers import Gcf

            # print "figs",Gcf.figs
            # print "dirty",self._dirty
            for fig in self._dirty:
                # print fig, Gcf.figs.values(),fig in Gcf.figs.values()
                if fig and fig in Gcf.figs.values():
                    # print "drawing"
                    fig.canvas.draw()
            pylab.show()
            self._dirty.clear()

        items = dict(list(self.items()))
        oldkeys = set(self._existing.keys())
        newkeys = set(items.keys())
        added = newkeys - oldkeys
        removed = oldkeys - newkeys
        changed = set(k for k in (oldkeys & newkeys) if items[k] is not self._existing[k])
        if added or changed or removed:
            self.OnChanged(added=added, changed=changed, removed=removed)
        self._existing = items


def demo():
    """Example use of the console."""
    import numpy as np

    app = wx.App(redirect=False)
    ignored = {"f": lambda x: 3 + x}
    console = NumpyConsole(locals=ignored)
    console.update({"x": np.array([[42, 15], [-10, 12]]), "z": 42.0})
    console.Show(True)
    app.MainLoop()


if __name__ == "__main__":
    demo()