Monday, January 19, 2015

PySide Tree Tutorial IA: Models and Views -- The Big Picture

Part of a series on treebuilding in PySide: see Table of Contents.

By separating content from appearance, the model/view framework takes a divide and conquer approach to GUI design. That is, the appearance of the data on the screen, handled by the view, is managed separately from the application's interactions with the data store. Such data wrangling is handled by the model.[1] This division of labor makes both of their jobs simpler: the view can ignore the details of how data are handled by the model, while the model can ignore the details of how data are painted to the screen.

As illustrated in Figure 1, views have two main roles:
  1.  Get data from the model by sending the model queries.
    Figure 1: The model/view framework
  2.    Paint the GUI to the screen: the same content can be viewed as a list, table, or a hierarchically organized tree. These different types of views are instances of QListView, QTableView, and QTreeView, respectively.[2]
Models also have two main roles:
  1. Handle all direct interactions with the data store, wrapping data into indexes to be used by the view.
  2.  Implement the expected interface with the view: when the view needs data, we know that the model will provide it using the mandatory interface.
While models and views are equally important, in this tutorial we will focus mainly on how to implement a model. The view class we will use is the factory-made QTreeView, whose default behavior will be fine for our purposes.

As mentioned above, all models are expected to instantiate a certain interface (or API) for the view to use. This API consists of a set of methods that provide views with all the information they need to paint the GUI to the screen. For instance, by invoking the model's data() method, we will see that the view can determine what text needs to be displayed on the screen. One nice feature of the standard views is that they will only request data about items in the model that presently need to be drawn to the screen.

The complexity of the model's API depends on the type of model you want to create. The simplest read-only list models only need to provide two methods: data() and rowCount().  More complex models, such as editable tree models, need to provide many additional methods. For a helpful overview of the methods required for different types of models, see Qt's Model subclassing reference (http://qt-project.org/doc/qt-4.8/model-view-programming.html#model-subclassing-reference).

If this all seems a bit abstract and useless or confusing, don't spend a lot of time struggling over the details. You will get lots of concrete examples in Part II, which is really the meat of this Tutorial.

[1] Note to keep things simple we will ignore the existence of delegates in this synopsis. Delegates control the display of individual data items and editors for said items, but for now we'll just lump this in as part of the view.

[2] For less standard visual representations of data (e.g., a bar graph or pie chart) you would need to make a custom view (Summerfield (2008), Chapter 16).

Saturday, January 17, 2015

PySide Tree Tutorial: Introduction

I think that I shall never see

A poem lovely as a tree.
                      -Joyce Kilmer


I've written an annotated companion to the simpletreemodel example that comes with PySide/PyQt. The code builds and displays a hierarchically organized data structure (i.e., a tree) using a model subclassed from QAbstractItemModel. I spread it out over multiple posts (see Table of Contents below). When finished, I'll put the entire series of posts into a single PDF and put a link to it in this post.

In Part I we will briefly review the model/view framework, focusing on details relevant for implementing our example. In sections II and III, we will study simpletreemodel. Part IV includes suggestions for future study. Part V shows how you can use other tools (QTreeWidget and QStandardItemModel) to construct a similar tree.

Table of Contents
I:Models and Views
            A. The big picture
            B. The mighty index
II: Building the data structure
            A. An introduction to simpletreemodel
            B. From TreeItem to tree structure
            C. Cross-examining simpletreemodel
III: Making the tree model
            A. Introducing the TreeModel class
            B. QAbstractItemModel's API
            C. Index and parent
            D. Creating the tree with setupModelData()

Acknowledgments
This started as a direct translation of the online Qt documentation on model-view programming. The main sources used were:
Also, thanks also to the folks at stackoverflow and qtcentre.org for answering my many questions. Thanks also to Tim Doty, Anna Stenwick, and Mark Summerfield for comments on previous drafts. Feel free to post questions/suggestions/comments in the comments of the relevant posts, or email them to me: thomson.eric at gmail.

References
Summerfield, M (2008) Rapid Gui Programming with Python and Qt. Prentice Hall.
Summerfield, M (2010) Advanced Qt Programming. Prentice Hall.

Tuesday, October 28, 2014

Database from Ch 19 of Teach Yourself Python

Teach Yourself Python is a really good introduction to Python--my favorite out of the three introductory books I own. Chapter 19, on using databases, references a video game database. I couldn't find the database online, so below is the code I used to make it.

# -*- coding: utf-8 -*-
'''Code to construct database from Chapter 19 of 
Teach Yourself Python in 24 Hours by Katie Cunningham'''
import sqlite3

error = None
conn = sqlite3.connect('videoGames.db')
cursor = conn.cursor()
  
#create games table
sqlCreate = '''CREATE TABLE games 
               (title text, rating text, system text, year int)'''
try:
    cursor.execute(sqlCreate)
except sqlite3.OperationalError as e: 
    error = e

#add data, if database doesn't already exist
if not error:
    print "Successfully created database...populating table"
    gameDataAll=[('Tales of the Abyss', 'T', '3DS', 2011),
              ('Adventure Time', 'E10+', '3DS', 2012),
              ('Hollywood Crimes', 'T', '3DS', 2011),
              ('Forza Motorsport 4', 'E', '360', 2011),
              ('Sonic Generations', 'E', '360', 2011),
              ('Forza Horizon', 'T', '360', 2012),
              ('ZhuZhu Pets', 'E', 'Wii', 2012)];
              
    for gameData in gameDataAll:
        print gameData 
        sqlAdd = '''INSERT INTO games (title, rating, system, year)
                    VALUES (:title, :rating, :system, :year)'''
        cursor.execute(sqlAdd, {'title': gameData[0], 'rating': gameData[1],
                                'system': gameData[2], 'year':gameData[3]})   
    conn.commit()  #commit changes otherwise they will not be saved
else:
    print "Didn't create database because", error
    sqlShow = '''SELECT * FROM games'''
    selectResults = cursor.execute(sqlShow)
    allGames = selectResults.fetchall()
    print "\nThe games table contains the following rows:"
    for game in allGames:
        print game
          
#close shop
cursor.close()
conn.close()
Code highlighting done at highlight.me.

Saturday, September 20, 2014

Pyside or PyQt for beginners?

As I mentioned in the previous post, my hobby recently has been porting Summerfield's book from PyQt to PySide (the code is in the PySide Summer repository).

Now that I'm about halfway through done with the translation process, I have inexorably been pulled to favor PyQt over PySide, at least for beginners. This is mainly because it has a more active community working hard to maintain the code, and there is better overall documentation in PyQt than PySide.1
 
This recommendation isn't based on thinking PyQt is significantly better than PySide: they are roughly the same packages.2 That said, PyQt has a much more active user community, with some amazing developers, such as Phil Thompson, who quickly address bugs and other serious issues. PyQt has kept pace with Qt's version 5, while PySide is still tracking Qt 4. Nokia used to actively maintain PySide, but my understanding is they have dropped it, so there is now no longer a cadre of professionals working on active maintenance. There seem to be lots of bug reports piling up, for instance.

In my experience in the open-source world, when it comes to things like navigating install hell, finding out if something is a feature or a bug, or learning how to optimize code, community is invaluable. There is a large body of know-how that only emerges if a lot of people use something. For that reason alone, I recommend beginners use PyQt to cut their teeth.


Also, PyQt has much better documentation. I have found, countless times, for some reason PySide docs leave out crucial details about methods and classes that PyQt includes. Not sure why, but the automatic documentation generator is much better for PyQt (for one representative example, compare the online docs for QTextEdit.setAlignment method for the two frameworks).

There is another good reason: Summerfield's book is the best introductory book on Qt programming in Python, and it uses PyQt. It rescued me me from floundering as a Qt  cargo cult programmer, where I would just hunt (Google) and peck out something that sometimes worked. His book teaches the fundamentals of the framework from the ground up. Admittedly, the PySide Summer repository does take the sails out of this reason a little bit, as it should make it easier for beginners to work through his book with PySide. (Yes, this entire post is tinged with irony in a few ways).

The main exception to my argument is going to apply to a tiny fraction of beginners. Namely,  if you are working on a commercial product, and don't want to pay a licensing fee, then you should use PySide. The reason PySide exists in the first place is that PySide has a less restrictive license than PyQt. If you want to use PyQt for commercial software, you have to buy the commercial license from Riverbank Computing. This restriction does not hold for PySide.

Note many people start out with dollar signs in their eyes, but in practice if you are building a little application, and are truly a beginner, you could easily build in PyQt first while learning. If you want to commercialize the product you could easily port to PySide.

I should be clear: my argument isn't that PyQt is objectively better than PySide, but that because they are basically the same framework, for beginners I'd suggest going with the package with the most active community.

Notes
1 That is not to say the documentation is fantastic for PyQt. For someone neutral about C++ versus Python, I would recommend starting with Qt in C++. The documentation is incomparable, the number of books you can get, etc.. This post is focused on Python, as between Qt and PyQt, there is really no contest.

2 They are roughly, though not exactly, the same. The PySide binding is built using Shiboken while PyQt uses SIP. This can be a nontrivial difference, as SIP is more mature than Shiboken. Plus, PyQt is on version 5, as mentioned. The differences, as of Fall 2014, don't seem significant enough to be deciding factors. (Note added in early 2015: it is clear this will become a larger factor as time goes on. So far there is talk, but no palpable progress, in moving PySide to Qt 5).

Friday, September 12, 2014

From PyQt to PySide

My hobby the the last few weeks of the summer has been to port Mark Summerfield's book on PyQt to PySide (Qt is a GUI framework written in C++, and PySide/PyQt are Python bindings to this framework). (Note added: I have subsequently completed the project).

The work, so far, is up at Github in a repository called PySideSummer. Frankly, most of the work is in updating the code from 2008 (when Summerfield's book was written) to 2014. Even within PyQt, a lot has changed. We now have new-style signals-and-slots, lots of classes have been deprecated (e.g., QWorkspace), methods have become obsolete (e.g., QColor.light()), and there is a new API.

Now that I've been doing it a few weeks, I can translate between the two frameworks pretty quickly, but I am keeping my foot on the brakes. I'm taking my time because I want to actually understand what is going on in each chapter. I expect to do about a chapter a week until I'm done.

Next post: which is better: PyQt or PySide?

Sunday, July 13, 2014

Python IDEs: Pycharm versus Spyder

Note (added 9/29/2015) this post is a bit obsolete:  in Spyder, be sure to go to Preferences-Editor-Code Introspection/Analysis and turn on Automatic code completion.
----------------------
After just a day with Pycharm (and a few weeks with Spyder), it is clear that for PySide coding, Pycharm wins. However, for scientific computing, especially for those who prefer a quick-responding Matlab-like IDE, Spyder definitely deserves drive space.  

I've been using the Spyder IDE for a few months now. Strangely, while tab completion works in its Python shell, it is not always seamless in the editor window (as discussed at http://code.google.com/p/spyderlib/issues/detail?id=1254).

Note added: to minimize this issue, be sure to go to Preferences-Editor-Code Introspection/Analysis and turn on Automatic code completion. This has made PySide tab completion work in my editor, and now I am back to using Spyder for PySide coding, and this makes this post somewhat obsolete frankly!

I've never placed much stock in IDEs, but as I watched some excellent PySide tutorials (found at http://www.yasinuludag.com/blog/?p=98), it seemed Yasin Uludag was able to type PySide code at mach speeds partly because of the IDE he was using (and also partly because he is a badass PySide ninja). To see for myself, I installed the free version of Pycharm yesterday.

First good thing I noticed: no install hell. Installation was easy on Windows 7. It automatically saw my Anaconda distribution of Python, and automatically used iPython for command line work.

Upon firing it up, the first thing I noticed was that Pycharm was really slow to load, and also very sluggish in response to basic commands (even entering text or surfing the menu system). Thankfully, it grew more responsive over time (or perhaps my temporal expectations adapted to its intrinsic pace). Despite the slow start, after about five minutes of exploring (with the help of the Getting Started page), I started to appreciate the crazy horsepower under my fingertips.

I haven't really touched the surface of Pycharm. I still feel like a 16 year-old who just learned how to drive stick, and was given the keys to a Ferrari. A bit in over my head, but excited nonetheless. Pycharm seems seamlessly integrated with version control, unit testing frameworks, has all sorts of refactoring functionality built in, among other things I have not yet explored and have never used before. I won't go over all the details, as I am just starting to learn them myself, so if interested I'd ask Google.

Tuesday, July 08, 2014

PySide event handling: pos versus globalpos

I'm playing around with Qt in Python using PySide. It is one of the steepest learning curves I've ever been on. I figure I'll start dropping little examples here. The following is a really simple example to demonstrate the difference between the pos and globalPos of an event in a window. Fire up the program, click within the window, and then drag the window and click within it again. It will print out globalPos() and pos() of a mouse click in the command line, and should be fairly self-explanatory.
# -*- coding: utf-8 -*-  
''' 
Click to see coordinates to get a feel for pos versus globalPos of an event  
''' 
   
from PySide import QtGui, QtCore  
   
class MousePos(QtGui.QWidget):  
    def __init__(self):  
        QtGui.QWidget.__init__(self)  
        self.initUI()  
       
    def initUI(self):  
        self.setGeometry(50,50,300,250)  
        self.show()  
   
    def mousePressEvent(self,event):  
        if event.button() == QtCore.Qt.LeftButton:  
            msg="event.globalPos: <{0}, {1}>\n".format(event.globalPos().x(), event.globalPos().y())  
            msg2="event.pos(): <{0}, {1}>\n".format(event.pos().x(), event.pos().y())  
            print msg + "  " + msg2  
       
def main():  
    import sys  
    qtApp=QtGui.QApplication(sys.argv)  
    myMousePos=MousePos()  
    sys.exit(qtApp.exec_())  
   
if __name__=="__main__":  
    main()  
One of my goals is to see if this code formatting worked in blogger. I did it at codeformatter.blogspot.com but am looking for better ways to do it. I want examples to be simple: cut, paste, and it works in your interpreter. Python is all about using space for syntax, and I had to do too much futzing to get the syntax right.

Sunday, March 23, 2014

iPython: clear current line

When you have some junk on the command line, and want to clear it, many interpreters (e.g., Matlab) would use <ctrl>-c. For reasons I don't understand, in the iPython command line, <shift><esc> will clear it up (while <ctrl>-z will undo your most recent action). If you really wanna go crazy, <ctrl>-l clears the entire screen.

Saturday, February 15, 2014

Saving an entire project in Code::Blocks

You are working with projectx in Code::Blocks, and want a copy of  the entire project with all its files
(e.g., header files). You try to save your project by entering File-->Save Project As, but it only saves a single cbp file. What do you do? You could copy over all the files individually, but that would be very time consuming for complex projects.

A more efficient method exists, but is not obvious from the Code::Blocks menu system. It involves two easy steps: 
1. Save template of projectx 
With projectx open, click File-->Save Project as Template and enter whatever name you want for this template. 
2. Open a new project from that template 
Click File-->New-->From Template, then pick the name you entered In Step 1. After clicking Go the program will request a folder to place the project. When it asks if you want to change the project name, you should do so unless you want it to have the exact same name as the template from Step 1. 

That's it. Those steps should give you an exact duplicate (potentially with a different name) of projectx.

Sunday, December 15, 2013

List comprehensions in Python

I was thinking of writing a post about the topic, but discovered an excellent introduction to list comprehensions that is about the level I was going to pitch it (An Introduction to List Comprehensions in Python). Highly recommended.

Why am I writing about Python at a neuroscience blog? Because of Brian.

Wednesday, December 04, 2013

Getting output from a Matlab GUI

Let's say you have a GUI like the one on the right as part of a program that runs a mouse in a simple behavioral task. The GUI requires the user to manually enter some data (the animal's name) and verify that the power is on in your setup. We want the GUI to close and return the relevant outputs when the 'Start Program' button is pressed by the user.

There are three tweaks you will need to make this work, if you made your GUI using the GUIDE functionality in Matlab (note if you want to tinker with an example, I've included one at the end of this post).

1) Make the GUI wait before it returns outputs
The GUI will try to return outputs right when it is invoked, well before any of the values can be specified by the user. To block such behavior, you can pause program execution using the uiwait command at the end of OpeningFcn:
   uiwait(hObject);  
This will make the GUI wait until some additional action is performed (e.g., uiresume is called to resume program flow, or the GUI (with handle hObject) is closed). This gives the user time to enter the actual values. Note you should put this command at the end of OpeningFcn.

2) Specify the output variables
Within OutputFcn, use varargout to specify what outputs you want returned from the GUI. Something like:
 varargout{1} = handles.data1; 
 varargout{2} = handles.data2;
Matlab typically passes information among the different elements of a GUI using the handles variable, so this code just exploits this fact. Once the outputs are specified as above, they will be returned as outputs to the calling function for the main GUI:
 [data1, data2]=GUI_Practice; 
Where GUI_Practice is the name of the m-file that defines the GUI.

Caveat: you will probably define the desired outputs (such as handles.data1) within a callback function (using something like handles.data1=x). When you do so, be sure to enter the following within the callback function:
guidata(hObject, handles); 
This saves the local variable handles to the GUI handle, so they will not be annihilated outside the scope of the callback function.

3) Tell the program when to resume
If you only did the above steps, after calling uiwait the program would hang indefinitely. You need to call the uiresume command to bump the program out of wait mode. To resume program flow when the user clicks Start Program, add uiresume to CloseRequestFcn:
%When user clicks button, check to see if GUI is in wait  %mode. If it is, resume program; otherwise close GUI
 if isequal(get(hObject, 'waitstatus'), 'waiting')
     uiresume(hObject);
 else
     delete(hObject);
 end
Note: you should also add the  line delete(hObject); to the end of outputFcn. Otherwise, the user will have to attempt to close the GUI twice: once to resume program flow with uiresume, and again to close the GUI with delete.
   

Example
Below is a simple example called GUI_Practice (m-file and fig file are both needed for this to run, as it was made with GUIDE). Once the files are in your Matlab path, you can instantiate the GUI by entering animal_name=GUI_Practice;
GUI_Practice.m
GUI_Practice.fig

Acknowledgment
I got some of the ideas for this from Mathworks (here). If you are having trouble getting it to work, let me know in the comments, and I'll try to help.

 

Saturday, April 06, 2013

Matlab question marks and exclamation points

Random Matlab things I find cool or perplexing. Updated periodically. Some of the comments are very dense, basically just lines of code I will likely forget, but will want to remember at some point.

5/6/13
To check what mfile is currently running, enter mfilename (useful in debug mode).


4/6/13
1. Filtering an image stored in matrix M:
%build the filter to convolve with the image
imFilt=fspecial('gaussian',10,10);
%convolve them
smoothed=imfilter(M,imFilt,'symmetric','conv');
 
2. To change your gridlines to solid grey without changing the colors of the tick labels:
grid
%make gridlines solid
set(gca,'gridlinestyle','-'); 
%make them grey
set(gca,'Xcolor',[.8 .8 .8],'Ycolor',[.8 .8 .8])
%unfortunately, the above changes everything to grey

%copy the axes
c=copyobj(gca,gcf);
%redo them in black. 
set(c,'color','none','xcolor','k','xgrid','off', ...
    'ycolor','k','ygrid','off','Box','off');

8/24/12
If your Windows machine doesn't show the .mat file extension (and you have already unclicked 'Hide extensions for known file types' in your folder options menu) you can fix it within an open folder. First, select Tools->Folder Options->File Types-->New. A GUI to create a new extension will open: type MAT in the field. Then click 'Advanced' and select Matlab Data from the list. It will warn you that this is already associated with a different file type. Accept the change. Problem solved. I stole this simple solution here, and Matlab has a page about it here.

7/9/12
1. If you have a cell array that contains strings, and want to get a numeric array with 1's where a particular string occurs, and 0's otherwise, you can use the cellfun function coupled with strfind: 
>>out=~cellfun('isempty', strfind(cell_array,'string'));

2. Why doesn't the following yield a 1?
>>NaN==NaN


3/24/12
You can use plotyy to display data on different y axes in the same figure. While there isn't presently a scatteryy command (why?), you can try something like the following:

>>[ax,h1,h2]=plotyy(x1,y1,x2,y2);
>>set(h1,'Marker','o');  

Note for older versions of Matlab, you used 'LineStyle' instead of 'Marker'.


2/17/12
1. It would be cool if, on a documentation page for a function, it let you click on a 'function history' link that showed when the function was introduced, and the changes added with each version.

2. Check out the grpstats function. Enter your data, and the group assigned to each data point, and it calculates all sorts of statistics sorted by group (e.g., mean, standard error, standard deviation, etc). I had done this on my own, but their function is better than what I had.

3. Why isn't the following legal?
>>scatter(x,y,'Color',[a b c])
Why must we use CData (and not Color) for scatter plots?

Saturday, May 12, 2012

What is a p value?

A p-value is a number associated with a statistical test. There are basically two things you need to know to understand p-values (understand them well enough to get you through a paper that throws around the term, anyway).

First, statistical tests examine differences between quantities. For instance, is the mean height of men different from the mean height of women? The null hypothesis is that the two things being compared are the same.

The second thing to understand is the p-value itself. The p-value, generated by mathematical procedures we will not discuss, is the probability that your data would look the way it does if you assume the null hypothesis is true. That is, assuming that the two quantities are the same, what are the chances that you would observe what you did?

For instance, let's say you randomly select 20 men and 20 women. The mean height of the 20 men is five foot ten, and the mean height of the 20 women is five foot seven. Would your data support the claim that men (on average) are taller than women, or could the observed height difference simply be due to chance? This is what the p-value tells you. It tells you the probability of making the observations that you did, under the assumption that men and women have the same average height.

Interpreting the p value follows from the above. If the p-value is very high (e.g., 0.99), then your observations are well within the bounds of what we would expect if the null hypothesis were true. That is, your data doesn't support a rejection of the null hypothesis. Such instances of high p-values yield a failure to reject the null hypothesis (for technical reasons, we typically avoid saying we accept the null hypothesis).

Alternatively, if the p-value is very low (the convention is below 0.05), this suggests that the two quantities you are comparing are truly different, i.e., that the null hypothesis is not true. That is, it would be very unlikely to observe what you did if the two quantities were indeed the same. In this case, we say we have rejected the null hypothesis. For our example, we would reject the null hypothesis that men and women are the same average height.

------------------------

For the mavens:  technically the p-value is the probability of getting the measured test statistic, or a more extreme value. But that is a wrinkle that makes things too complicated for this very dirty synopsis.

Friday, January 20, 2012

Filtering images in Matlab

Given image stored in matrix M:

%build the filter to convolve with the image
imFilt=fspecial('gaussian',10,10);
%convolve them
smoothed=imfilter(M,imFilt,'symmetric','conv');

Monday, November 07, 2011

Prepping for SFN

Alone in Bryan Research Building. Surprised there aren't more people here furiously getting their posters ready...

Monday, July 25, 2011

Catterall's group cracks the (closed) sodium channel

I haven't read it yet, so have no comments, just wanted to get the abstract here so I don't forget to take a closer look.

Reference
Payandeh, Scheuer, Zheng, Catterall (2011) The crystal structure of a voltage-gated sodium channel. Nature 475: 353-358.
Pubmed link

Abstract
Voltage-gated sodium (NaV) channels initiate electrical signalling in excitable cells and are the molecular targets for drugs and disease mutations, but the structural basis for their voltage-dependent activation, ion selectivity and drug block is unknown. Here we report the crystal structure of a voltage-gated Na+ channel from Arcobacter butzleri (NavAb) captured in a closed-pore conformation with four activated voltage sensors at 2.7 Ã… resolution. The arginine gating charges make multiple hydrophilic interactions within the voltage sensor, including unanticipated hydrogen bonds to the protein backbone. Comparisons to previous open-pore potassium channel structures indicate that the voltage-sensor domains and the S4–S5 linkers dilate the central pore by pivoting together around a hinge at the base of the pore module. The NavAb selectivity filter is short, ~4.6 Ã… wide, and water filled, with four acidic side chains surrounding the narrowest part of the ion conduction pathway. This unique structure presents a high-field-strength anionic coordination site, which confers Na+ selectivity through partial dehydration via direct interaction with glutamate side chains. Fenestrations in the sides of the pore module are unexpectedly penetrated by fatty acyl chains that extend into the central cavity, and these portals are large enough for the entry of small, hydrophobic pore-blocking drugs. This structure provides the template for understanding electrical signalling in excitable cells and the actions of drugs used for pain, epilepsy and cardiac arrhythmia at the atomic level.

Thursday, June 03, 2010

Consciousness (15): Opening the time capsule

Table of Contents of posts on consciousness.
-------------------------------------

Below you'll find a series of quotations that highlight the topics we have been discussing in the last nine posts. I chose them for their exceptional eloquence, clarity, and influence. They are not in chronological order, but are roughly in ascending order of specificity of the claims. This will be the final post in this narrative arc.

The quotes
[V]ision is the process of discovering from images what is present in the world, and where it is.
     -David Marr (1982)
We may define visual perception as attributing objects to images.
     -Richard Gregory (2009)
Visual perception involves coordination between sensory sampling of the world and active interpretation of the sensory data. Human perception of objects and scenes is normally stable and robust, but it falters when one is presented with patterns that are inherently ambiguous or contradictory. Under such conditions, vision lapses into a chain of continually alternating percepts, whereby a viable visual interpretation dominates for a few seconds and is then replaced by a rival interpretation. This multistable vision, or ‘multistability’, is thought to result from destabilization of fundamental visual mechanisms, and has offered valuable insights into how sensory patterns are actively organized and interpreted in the brain…
     -Nikos Logothetis (2002)
[The Necker cube] has an interesting property. Look at it fairly steadily for a while, and the cube will invert, as if it were being viewed from another angle. After a time the percept switches back to the original one, and so on. In this case there are two equally plausible 3D interpretations of the image, and the brain is uncertain which it prefers. Notice that it only chooses one at a time, not some odd mixture of both of them…

The reason you normally see without ambiguity is that the brain combines the information provided by the many distinct features of the visual scene (aspects of shape, color, movement, etc) and settles on the most plausible interpretation of all these various visual clues taken together…[W]hat the brain has to build up is a many-leveled interpretation of the visual scene, usually in terms of objects and events and their meaning to us.
     -Francis Crick (1995)
We don’t directly experience what happens on our retinas, in our ears, on the surface of our skin. What we actually experience is a product of many processes of interpretation—editorial processes, in effect. They take in relatively raw and one-sided representations, and yield collated, revised, enhanced representations, and they take place in the stream of activity occurring in various parts of the brain. This much is recognized by virtually all theories of perception…
     -Dan Dennett (1991)
The mental activities that lead us to infer that in front of us at a certain place there is a certain object of a certain character, are generally not conscious activities, but unconscious ones. In their result they are equivalent to a conclusion, to the extent that the observed action on our senses enables us to form an idea as to the possible cause of this action; although, as a matter of fact, it is invariably simply the nervous stimulations that are perceived directly, that is, the actions, but never the external objects themselves. But what seems to differentiate them from a conclusion, in the ordinary sense of that word, is that a conclusion is an act of conscious thought… Still it may be permissible to speak of the mental acts of ordinary perception as unconscious conclusions, thereby making a distinction of some sort between them and the common so-called conscious conclusions.
     -Hermann von Helmholtz (1866)
Perception consists of interpreting two-dimensional retinal images of a three-dimensional world. The process of projecting a three-dimensional scene onto a two-dimensional retina necessarily discards information about the three-dimensional structure of the scene. This makes it impossible, in principle, to deduce all of the three-dimensional structure of a scene…However, even though such problems cannot be solved by deduction, acceptable solutions can be found using statistical inference.
     -JV Stone (2009)
Our visual experience evidently is the product of highly sophisticated and deeply entrenched inferential principles that operate at a level of our visual system that is quite inaccessible to conscious introspection or voluntary control. We do not first experience a two-dimensional image and then consciously calculate or infer the external three-dimensional scene that is most likely, given that image. The first thing we experience is the three-dimensional world—as our visual system has already inferred it for us on the basis of the two-dimensional input. Hermann von Helmholtz, the great nineteenth century scientist who more than any other single individual laid the foundations for our present understanding of visual and auditory perception, expressed this by characterizing perception as “unconscious inference.”
     -Roger Shepard (1991)
[T]he brains’ representations are hypotheses, predictive like the hypotheses of science. Like science, perception bets from available evidence on what is likely to be true…For perception, there is always guessing and going beyond available evidence. On this view, the closest we ever come to the object world is by somewhat uncertain hypotheses, selected from present evidence and enriched by knowledge from the past. Some of this knowledge is inherited—learned by the statistical processes of natural selection and stored by the genetic code. The rest is brain-learning from individual experience, especially important for humans.
     -Richard Gregory (2009)
It is the business of the brain to represent the outside world. Perceiving is not just sensing but rather an effect of sensory input on the representational system. An ambiguous figure provides the viewer with an input for which there are two or more possible representations that are quite different and about equally good, by whatever criteria the perceptual system employs. When alternative representations or descriptions of the input are equally good, the perceptual system will sometimes adopt one and sometimes another. In other words, the perception is multistable.
     -Fred Attneave (1971)
We have suggested that the biological usefulness of visual consciousness in humans is to produce the best current interpretation of the visual scene in the light of past experience, either of ourselves or of our ancestors (embodied in our genes), and to make this interpretation directly available, for a sufficient time, to the parts of the brain that contemplate and plan voluntary motor output, of one sort or another, including speech.
     -Francis Crick and Christof Koch (1998)

References
Attneave, F (1971) Multistability in perception. Sci Am. 6: 63-71.

Crick, Francis (1995) The Astonishing Hypothesis: The Scientific Search for the Soul. Scribner.

Crick, F, and Koch, K (1998) Cerebral Cortex, 8:97-107.

Dennett, D (1991) Consciousness Explained. Back Bay Books.

Gregory, RL (2009) Seeing Through Illusions. Oxford University Press.

Helmholtz, H. von 1866 Concerning the perceptions in general. In Treatise on physiological optics, vol. III, 3rd edn (translated by J. P. C. Southall 1925 Opt. Soc. Am. Section 26, reprinted New York: Dover, 1962).

Leopold, Wilke, Maier, and Logothetis (2002) Stable perception of visually ambiguous patterns. Nature Neuroscience 5: 605-609.

Marr, D (1982) Vision. WH Freeman, NY.

Shepard, RN (1991) Mind Sights, W.H.Freeman & Co Ltd.

Stone, JV, Kerrigan, IS, and Porrill, J (2009) Where is the light? Bayesian perceptual priors for lighting direction. Proc R Soc B 276: 1797-1804.

-------------------------------------
Table of Contents of posts on consciousness.

Friday, May 28, 2010

Consciousness (14): Interpretation Mechanics

Number fourteen in my series of posts on consciousness. Table of Contents is here.
-------------------------------------

The perception-as-interpretation view, summarized in the previous post, is useful as an informal ordinary-language hypothesis about consciousness. However, it is obviously a long shot from a final literal scientific theory. While it seems to be a useful way of speaking, I think we should look at it as an interesting suggestion, or perhaps even an inspiration that will lead us toward a more specific and fleshed-out theory.

There is a diverse range of theories that turn out to be special cases of the perception-as-interpretation hypothesis. These theories describe the interpretation-building mechanism alternatively as neuronal ‘model building’, ‘emulation,’ ‘virtual reality construction,’ ‘simulation of a world’, or ‘unconscious inference.’ Each specific theory carries slightly different assumptions about how the brain constructs experience, but most of them share two or more of the general features of the interpretation view delineated in previous posts.

Among psychologists, the most influential of these views is that the brain uses an unconscious inference procedure to construct a hypothesis about the source of a retinal projection. Because this theory of perception is so interesting, influential, and useful, I’ll describe it in a little bit of detail before stepping back to speak more generally about all of these theories.

Marty the Brain Scientist
To help us understand this theory, let’s imagine a tiny scientist, Marty, who lives and works in your brain (Figure 1). His sole occupation, every moment, is to monitor the movies playing on your retinae, and to build a hypothesis about their source in the world. Our conscious experience is identical to the specific hypotheses that Marty generates. For instance, if Marty’s best hypothesis about the source of the stimuli is that there is a red ball three feet to your left, that is precisely what you will see. Marty is fairly motivated to generate hypotheses accurately and quickly: after all, if you die, he dies. The more accurate his hypotheses, the better you will be able to interact with the world.

Figure 1: Marty the brain scientist.


Retinal movies are Marty’s primary source of evidence. He uses such evidence, along with various assumptions and background knowledge about how the world works, to generate hypotheses about the source of the observed projections (that is, he makes an inference about the source of the stimuli). We are only conscious of the outputs of Marty’s vocation, not any details of his inference-generating procedures. Hence the hypothesis that perception is unconscious inference.

Hypothesis formation is a special case of inference. It is a type of inference that doesn't enjoy the level of certainty granted to deductive inferences (as you’d find in mathematical proofs). Rather, when we form a hypothesis we are often throwing out our best hunch, an educated guess based on limited evidence and previous assumptions about the way the world works. Philosophers sometimes call this type of inference an ‘inference to the best explanation’ or ‘abductive inference.’

For instance, say the evidence we wish to explain includes late-night scratching sounds in the cupboard and small fecal nuggets deposited in the pantry. We could use such evidence, and our general understanding of how the world works (mice are nocturnal, etc), to construct a hypothesis that would best explain the evidence. In this case, we would likely hypothesize that there are mice living in our kitchen. Perhaps Marty settles on his hypotheses about visual stimuli using a similar process of abductive reasoning.

Obviously, Marty is merely a useful fiction. Nobody thinks there is literally a little man in your head viewing your retinal movies. Advocates of this theory believe that we will ultimately be able to give a more literal story that describes how brains construct hypotheses based on information coming in from the retinae. In the meantime, I should spell out why the unconscious inference theory appeals to psychologists.

The appeal of the theory
There are three main reasons for the theory’s appeal (aside from its impressive intellectual pedigree since Helmholtz (1866)). For one, the theory would explain how certain illusions are generated. For instance, recall Shepard’s Monsters (Figure 2) from post eleven. Shepard explains the illusion as follows:
[T]he linear perspective of the subterranean tunnel (along with other depth cues, such as the relative heights of the projections of the two monsters on our retinas) supports the automatic perceptual inference that one of the two monsters is farther back in depth. The two monsters, nevertheless being exactly the same size in the drawing, subtend the same visual angle at the eye [i.e., their projections occupy the same surface area on the retinae]. The visual system therefore makes the additional inference that in order to subtend the same visual angle, the monster that is farther back in depth must also be larger.
Notice how the idea of inference-making is built into multiple layers of Shepard’s explanation of the illusion. The brain makes inferences about which monster is further away, and then uses this information to make further inferences about which monster is larger, which explains why one monster looks bigger than the other. Note the claim isn’t that the brain only uses inferences in cases of illusions (how would the brain know if it were seeing an illusion or not?), but that illusions help reveal the underlying inferential machinery of normal perception.

Figure 2: Terra Subterranea, or Shepard’s Monsters


A second appeal is that the theory finds a mathematical home in probability theory and statistics. The brain lives in an uncertain world, and even the brain’s own responses to identical stimuli are not the same every single time (that is, the brain itself is a “noisy” processor). In mathematics, the principles of sound inference in such uncertain contexts are provided by statistics. Couching theories of brain function in the language of probability and statistics allows psychologists to state their theories with more rigor than can be done in ordinary language. Perhaps most importantly, such theories allow them to generate quantitative predictions that can be tested against the data.

Figure 3: The eye lives between a noisy brain and an uncertain world.


The third appeal applies to the ‘unconscious’ side of the ‘unconscious inference’ thesis. That is, it seems pretty clear that the processes which generate our perceptual experiences are not consciously accessible to us (as discussed in post ten and post thirteen).

Hopefully this gloss on the unconscious inference theory of perception was half as fair as it was brief. At this point I don’t want to push too hard against it (for instance, you would be right to ask what it means for the brain to perform an inference). Rather, my goal was to showcase the most prominent species of the perception-as-interpretation thesis. More than one-hundred years after Helmholtz initially suggested the hypothesis that perception is unconscious inference, Fodor and Pylyshyn were able to describe the theory, without much overstatement, as the ‘Establishment theory' of perception.

Representations within interpretations
Enough with unconscious inferences: what about all the other theories I mentioned above, such as the view that the brain builds a ‘simulation’ of the world? I am going to avoid jumping down the historical rabbit hole of comparing/contrasting the often subtle differences in this panoply of psychological-level theories of perception. Rather, it will be more productive to extract a common denominator shared by all of these theories, something all of the advocates would agree upon. If such a common factor turns out to be useful and correct, then great. If not, then we will have eliminated an entire class of models of perception with one parsimonious swing of the blade. This seems much easier than starting by contrasting every such theory pair in detail.

The one theoretical commitment shared by all these theories of perception is that the brain constructs representations of the world, and the contents of such neuronal representations are the contents of experience. Our first priority will be to analyze this idea of neuronal ‘representation’: what the heck does it mean, and how far can it take us in our quest to understand visual experiences?

While I won’t analyze the notion yet, the notion of a ‘representation’ should be intuitively familiar to most of us. Three squiggly lines on a map represent water. A photograph of someone represents the person. I’ve already sneaked in the claim that the brain constructs a ‘portrait’ of the world: a portrait of something is one type of representation. The claim we will evaluate is that one component of the brain’s interpretation of a stimulus is an internal representation of the world constructed partly based on that stimulus.

Before heading into brains, however, in the next post I will finish this chapter by posting a broad range of quotations from the literature on the topics we have explored in the last eight posts. This will help us to see how these ideas of interpretation, simulation, representation, etc are used in practice.

References
Fodor, JA, and Pylyshyn ZW (1981) How direct is visual perception? Cognition 9: 139-196.

Helmholtz, H. von 1866 Concerning the perceptions in general. In Treatise on physiological optics, vol. III, 3rd edn (translated by J. P. C. Southall 1925 Opt. Soc. Am. Section 26, reprinted New York: Dover, 1962).

Shepard, RN (1991) Mind Sights, W.H.Freeman & Co Ltd.

-------------------------------------
Table of Contents of my posts on consciousness.

Friday, May 07, 2010

How to run R code in Matlab

R (site here) is a great open-source environment for statistical analysis. But I'm a Matlab user. Luckily, it is pretty easy to run R code from Matlab. Since I just set it up in my Matlab environment, I thought I'd write out the recipe I followed. I have only done the following in Windows XP, and I used Matlab version 7.8. I think it will only work in Windows. It assumes you already have R and Matlab properly installed on your computer.

Of course, this doesn't mean I don't have to learn how to use R, it just means I get to do it all in Matlab (and note for fellow Matlab users, there is a great cheat sheet that shows how to translate between the two).

1. Install the R package rscproxy.
In R, enter:
>install.packages("rscproxy")
to install the package.

2. Install the R(D)Com server.
Download it here. The server allows Matlab to talk with R. I installed it using the default settings without checking or unchecking any boxes. Note this server is built for Scilab, which is an open source version of Matlab, but it seems to work for Matlab too.

3. Download the Matlab R-Link toolbox
Get MATLAB_RLINK.zip here, unzip the contents, and paste MATLAB_RLINK in Matlab's toolbox folder (or whatever folder you want). Be sure to add MATLAB_RLINK to your Matlab path.

4. Restart your computer.

5. Is it working?
To see if the toolbox is working, start Matlab and enter 'Rdemo' at the command prompt. This should evoke:
b =
1 4 9 16 25 36 49 64 81 100

c =
2 5 10 17 26 37 50 65 82 101

6. Have fun!
If Rdemo worked, you are ready to go!

For instance, enter the following in Matlab:
openR; %Open connection to R server
x=[1:50]; %create x values in Matlab
putRdata('x',x); %put data into R workspace
evalR('y<-sqrt(x)'); %evaluate in R
evalR('plot(x,y)') %plot in R
To close the connection to R, and the graphs opened from R, enter:
closeR;

7. Problems?
If the above doesn't work, go to C:\Program Files\R, open the (D)COM Server folder, go to 'bin', copy 'sciproxy.dll', and paste it in C:\Program Files\MATLAB\R2009a\bin (obviously you may have a different path to Matlab's binary folder). Close Matlab, and restart your computer.

If that doesn't help, I probably won't be able to help, but go ahead and ask as someone might know. The site where you downloaded R-Matlab has some useful Q&A so you might inquire there.

8. Acknowledgments
This is basically an updated version of Kevin Murphy's site. Please let me know if anything here becomes obsolete.

9. Caveat (added 6/18/12)

From the comments section:
After using R(D)COM and Matlab R-link for a while, I do not recommend it. The COM interface has trouble parsing many commands and it is difficult to debug the code. I recommend using a system command from Matlab as described in the R Wiki. This also avoids having to install all of the RAndFriends programs. 

Thursday, May 06, 2010

Consciousness (13): The Interpreter versus the Scribe

Number thirteen in my series of posts on consciousness. Table of Contents is here.
---------------------------

While elaborating on the parallels between perception and language interpretation, we have unpacked many features of the nature of visual perception that should hold up even if we end up finding the view of perception-as-interpretation wanting. In this post I’ll briefly integrate the data and theory from the past seven posts into a more tidy and (hopefully) coherent story.

As we discussed in some detail in post ten, the contents of experience have properties that are, on the surface, quite different from the properties of the underlying neural machinery doing the experiencing. I can see an iridescent jewel two feet in front of me (that’s the content), but the vehicle doing the experiencing is neither iridescent nor two feet in front of me.

We can be intimately familiar with the contents of our experience while remaining in complete ignorance of facts about nervous systems. I hope I don’t offend my fellow neuroscientists when I claim that our species’ great artists, playwrights, musicians, and novelists have revealed more about the contents of experience than any neuroscientist. Yet most of these artists worked without knowing the most basic facts of neuroscience. The vehicles of experience are effectively invisible to us, while the contents of experience are as familiar as breathing. Anyone that has savored an authentic lobster roll from a rundown shack on the coast of Maine knows what it is like to revel in the contents of experience (and those who have not have yet to fully live).

In sum, the contents of our experience seem to be a neurally-constructed portrait of what is happening beyond the brain. The brain faces some rather severe obstacles if its goal is to make this portrait accurate. For one, a great deal of information is lost in the projection from the scene to the retina (a projection we discussed in some detail in post nine).

Consider the case in which a projection onto the retina is square-shaped. What can we say about the object that generated that projection? Assuming there are no distance cues present, the same square shape on the retina could be produced by a tiny square that is extremely close to the eye, a medium-sized square a moderate distance away, or a colossal square that is extremely far away. It could even be generated by non-square shapes transmitted through a distorting funhouse-type medium.

Purves and Lotto state the point nicely:
[T]he retinal output in response to a given stimulus can signify any of an infinite combination of illuminants, reflectances, transmittances, sizes, distances, and orientations in the real world. It is thus impossible to derive by a process of logic the combination of these factors that actually generated the stimulus[.]
In other words, given only retinal movies as data, the brain cannot determine with perfect accuracy the scene in the world that generated said movies. Given the often striking ambiguity of the source of a retinal projection, it is remarkable that our visual system usually locks in on a single perceptual response to a given stimulus. Even during bistable perception we typically experience one object at a time, not a superposition of two objects.

How does the brain settle on a unique percept when provided with an inherently ambiguous retinal projection? It seems the brain uses context (post eleven) as well as background assumptions and knowledge (post twelve) to help narrow down the range of reasonable interpretations. Bistable percepts merely serve to highlight those rare instances when these contributions from the brain are not sufficient to settle on a single interpretation for an extended period of time.

In general, while we know that the retinal movies strongly influence the brain’s construction of experience, our experience is obviously not a mere report or transcription of what is happening in the retinae. If it were, ambiguous stimuli wouldn’t spontaneously reorganize in such drastic ways such as we observe in the Spinning Girl and Rotating Necker Cube (post seven), the angles in Purves’ Plumbing would look the same, the tabletop dimensions in Turning the Tables would look identical (post twelve), the yellow and blue squares in Purves’ Cubes would look grey, Shepard's subterranean monsters would look identical in size (post eleven), etc..

Hopefully the previous seven posts have made it clear why psychologists often say that the brain constructs interpretations of stimuli in a context-sensitive way, based on background knowledge and assumptions, in the light of sometimes intense ambiguity of the actual source of the stimulus. If we were forced to choose between the false dichotomy of saying that experience is an interpretation of what is happening in the retinae versus a transcription of what is happening on the retinae, I think the choice is clear.

Richard Gregory (1966) summed up the view quite well when he said that “Perception is not determined simply by the stimulus patterns; rather it is a dynamic searching for the best interpretation of the available data.” Our visual experience is clearly the result of neuronal events downstream from the stimulus, a construction of an experience whose contents mostly include worldly events beyond the eyes. It is such worldly events that we must engage with, after all, and such engagement with the world determines whether we eat, reproduce, flee, or die.

Next up
In the next couple of posts we’ll persue the idea that perception is interpretation down more specific paths, looking at a prominent view that the mechanism of interpretation is a kind of unconscious inference, and finally we’ll end up heading into the brain, looking at the neuronal basis of these internal “portraits” of the world.

References
Gregory, RL (1966). Eve and Brain. London: Weidenfeld and Nicolson.

Purves, DP, and Lotto, RB (2003) Why we see what we do: An empirical theory of vision Sinauer Associates.


-------------------------------------
Table of Contents of posts on consciousness.