source: orange/docs/extend-widgets/rst/basics.rst @ 11883:ea27938c69a1

Revision 11883:ea27938c69a1, 11.2 KB checked in by Jared Forsyth <jabapyth+bitbucket@…>, 2 weeks ago (diff)

fix function naming to match the files

Line 
1###############
2Getting Started
3###############
4
5
6The tutorial on these pages is meant for those who are interested in
7developing widgets in Orange. Orange Widgets are components in
8Orange's visual programming environment. They are wrappers around some
9data analysis code that provide graphical user interface
10(GUI). Widgets communicate, and pass tokens through communication
11channels to interact with other widgets. While simplest widgets
12consist of even less than 100 lines of code, those more complex that
13often implement some fancy graphical display of data and allow for
14some really nice interaction may be over 1000 lines long.
15
16On this page, we will start with some simple essentials, and then
17show how to build a simple widget that will be ready to run within
18Orange Canvas, our visual programming environment.
19
20*************
21Prerequisites
22*************
23
24Each Orange widget belongs to a category and within a
25category has an associated priority. Opening Orange Canvas, a visual
26programming environment that comes with Orange, widgets are listed in
27a toolbox on the left:
28
29.. image:: widgettoolbox.png
30
31The widgets and categories to which they belong are discovered at Orange
32Canvas startup leveraging setuptools/distribute and it's `entry points
33<http://pythonhosted.org/distribute/setuptools.html#dynamic-discovery-of-services-and-plugins>`_
34protocol. In particular Orange Canvas looks for widgets using a
35`orange.widgets` entry point.
36
37
38First we will examine an existing widget in Orange. The Test Learners
39widget which is implemented in `OWTestLearners.py
40<http://orange.biolab.si/trac/browser/orange/Orange/OrangeWidgets/Evaluate/OWTestLearners.py>`_.
41
42Here is its header::
43
44    """
45    <name>Test Learners</name>
46    <description>Estimates the predictive performance of learners on a data set.</description>
47    <icon>icons/TestLearners1.svg</icon>
48    <priority>200</priority>
49    """
50
51OWTestLearners is a Python module, so the header information we
52show about lies within the comment block, with triple quote opening
53and closing the comment. Header defines the name of the widget, its
54description, the name of the picture file the widget will use for an
55icon, and a number expressing the priority of the widget. The name of
56the widget as given in the header will be the one that will be used
57throughout in Orange Canvas. The description of the widget is shown
58once mouse rests on an toolbox icon representing the widget. And for
59the priority: this determines the order in which widgets appear in the
60toolbox within a category.
61
62Widgets communicate. They use typed channels, and exchange
63tokens. Each widget would define its input and output channels in
64something like::
65
66    self.inputs = [("Test Data Set", Orange.data.Table, self.set_data),
67                   ("Learner", Orange.classification.Learner, self.set_learner)]
68    self.outputs = [("Evaluation Results", Orange.evaluation.testing.ExperimentResults)]
69
70
71We will go over the syntax of channel definitions later, but for
72now the following is important:
73
74   - Widgets are defined in a Python files.
75   - Widgets are registered through entry points and are discovered at
76     runtime.
77   - A python module implementing a widget starts with a header. This, given
78     in sort of XMLish style, tells about the name, short description,
79     location of an icon and priority of the widget.
80   - The sole role of priority is to specify the placement (order) of widgets
81     in the Orange Canvas toolbox.
82   - Somewhere in the code (where we will learn later) there are two lines
83     which tell which channels the widgets uses for communication. These,
84     together with the header information, completely specify the widget as it
85     is seen from the outside.
86
87.. note::
88   Orange caches widget descriptions to achieve a faster startup,
89   but this cache is automatically refreshed at startup if any change
90   is detected in widgets' file.
91
92***********
93Let's Start
94***********
95
96Now that we went through some of the more boring stuff, let us now
97have some fun and write a widget. We will start with a very simple
98one, that will receive a data set on the input and will output a data
99set with 10% of the data instances. We will call this widget
100`OWDataSamplerA.py` (OW for Orange Widget, DataSampler since this is what
101widget will be doing, and A since we prototype a number of this widgets
102in our tutorial).
103
104But first we must create a simple `python project`_ layout called *Demo*,
105that we will use in the rest of this tutorial.
106
107.. _`python project`: http://docs.python.org/2/distutils/examples.html#pure-python-distribution-by-package
108
109The layout should be::
110
111   Demo/
112         setup.py
113         orangedemo/
114                     __init__.py
115                     OWDataSamplerA.py
116
117and the :download:`setup.py` should contain
118
119.. literalinclude:: setup.py
120
121Note that we declare our *orangedemo* package as containing widgets
122from an ad hoc defined category *Demo*.
123
124Following the previous example of OWTestLearners, our module defining
125the OWDataSamplerA widget starts with a following header::
126
127    <name>Data Sampler</name>
128    <description>Randomly selects a subset of instances from the data set</description>
129    <icon>icons/DataSamplerA.svg</icon>
130    <priority>10</priority>
131
132This should all be clear now, perhaps just a remark on an icon. We
133can put any name here, and if Orange Canvas won't find the
134corresponding file, it will use a file called Unknown.png (an icon
135with a question mark).
136
137Orange Widgets are all derived from the class OWWidget. The name of
138the class should match the file name, so the lines following the
139header in our Data Sampler widget should look something like
140
141
142.. literalinclude:: OWDataSamplerA.py
143   :start-after: start-snippet-1
144   :end-before: end-snippet-1
145
146
147In initialization, the widget calls the :func:`__init__` method
148of a base class. Widget then defines inputs and outputs. For input,
149this is a *Data* channel, accepting tokens of the type
150:class:`Orange.data.Table` and specifying that :func:`set_data` method will
151be used to handle them. For now, we will use a single output channel
152called "Sampled Data", which will be of the same type
153(:class:`Orange.data.Table`).
154
155Notice that the types of the channels are specified by a class;
156you can use any class here, but if your widgets need to talk with
157other widgets in Orange, you will need to check which classes are
158used there. Luckily, and as one of the main design principles,
159there are just a few channel types that current Orange widgets are
160using.
161
162The next four lines specify the GUI of our widget. This will be
163simple, and will include only two lines of text of which, if nothing
164will happen, the first line will report on "no data yet", and second
165line will be empty. By (another) design principles, in an interface
166Orange widgets are most often split to control and main area. Control
167area appears on the left and should include any controls for settings
168or options that your widget will use. Main area would most often
169include a graph, table or some drawing that will be based on the
170inputs to the widget and current options/setting in the control
171area. OWWidget make these two areas available through its attributes
172:obj:`self.controlArea` and :obj:`self.mainArea`. Notice
173that while it would be nice for all widgets to have this common visual
174look, you can use these areas in any way you want to, even disregarding one
175and composing your widget completely unlike the others in Orange.
176
177As our widget won't display anything apart from some info, we will
178place the two labels in the control area and surround it with the box
179"Info".
180
181In order to complete our widget, we now need to define how will it
182handle the input data. This is done in a method called :func:`set_data`
183(remember, we did introduce this name in the specification of the
184input channel)
185
186.. literalinclude:: OWDataSamplerA.py
187   :start-after: start-snippet-2
188   :end-before: end-snippet-2
189
190The :obj:`dataset` argument is the token sent through the input
191channel which our method needs to handle.
192
193To handle the non-empty token, the widget updates the interface
194reporting on number of data items on the input, then does the data
195sampling using Orange's routines for these, and updates the
196interface reporting on the number of sampled instances. Finally, the
197sampled data is sent as a token to the output channel with a name
198"Sampled Data".
199
200Notice that the token can be empty (``None``), resulting from either
201the sending widget to which we have connected intentionally emptying
202the channel, or when the link between the two widgets is removed.
203In any case, it is important that we always write token handlers
204that appropriately handle the empty tokens. In our implementation,
205we took care of empty input data set by appropriately setting the
206GUI of a widget and sending an empty token to the output channel.
207
208
209Although our widget is now ready to test, for a final touch, let's
210design an icon for our widget. As specified in the widget header, we
211will call it :download:`DataSamplerA.svg <DataSamplerA.svg>` and will
212put it in `icons` subdirectory of `orangedemo` directory.
213
214With this we cen now go ahead and install the orangedemo package. We
215will do this by running ``python setup.py develop`` command from
216the `Demo` directory.
217
218.. note::
219   Depending on your python installation you might need
220   administrator/superuser privileges.
221
222For a test, we now open Orange Canvas. There should be a new pane in a
223widget toolbox called Demo. If we click on this pane, it displays an
224icon of our widget. Try to hover on it to see if the header and channel
225info was processed correctly:
226
227.. image:: samplewidgetontoolbox.png
228
229Now for the real test. We put the File widget on the schema (from
230Data pane) and load the iris.tab data set. We also put our Data
231Sampler widget on the scheme and open it (double click on the icon,
232or right-click and choose Open):
233
234.. image:: datasamplerAempty.png
235
236Now connect the File and Data Sampler widget (click on an output
237connector of the File widget, and drag the line to the input connector
238of the Data Sampler). If everything is ok, as soon as you release the
239mouse, the connection is established and, the token that was waiting
240on the output of the file widget was sent to the Data Sampler widget,
241which in turn updated its window:
242
243.. image:: datasamplerAupdated.png
244
245To see if the Data Sampler indeed sent some data to the output,
246connect it to the Data Table widget:
247
248.. image:: schemawithdatatable.png
249
250Try opening different data files (the change should propagate
251through your widgets and with Data Table window open, you should
252immediately see the result of sampling). Try also removing the
253connection between File and Data Sampler (right click on the
254connection, choose Remove). What happens to the data displayed in the
255Data Table?
256
257*****************************************
258Testing Your Widget Outside Orange Canvas
259*****************************************
260
261When prototyping a single widget, for a fast test I often get
262bored of running Orange Canvas, setting the schema and clicking on
263icons to get widget windows. There are two options to bypass this. The
264first one is to add a testing script at the end of your widget. To do
265this, we finished Data Sampler with
266
267.. literalinclude:: OWDataSamplerA.py
268   :start-after: start-snippet-3
269   :end-before: end-snippet-3
270
271These are essentially some calls to Qt routines that run GUI for our
272widgets. Notice that we call the :func:`set_data` method directly.
Note: See TracBrowser for help on using the repository browser.