Child pages
  • ConnectomeDB, pyxnat, and the OHBM Hackathon
Skip to end of metadata
Go to start of metadata

You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 10 Next »

One of the datasets available for the OHBM Hackathon is the Q1 public data release from the Human Connectome Project. In addition to the imaging data, which are mirrored on S3 for easy access from AWS, a great deal of imaging metadata and associated non-imaging data is accessible through ConnectomeDB, a web application built on the XNAT imaging informatics platform.

pyxnat is a library that provides a Python language API to XNAT's RESTful web services. In this tutorial, we'll use pyxnat to access behavioral measures stored in ConnectomeDB. Even if you're not a Pythonista, read on, as the underlying XNAT REST API can be accessed from just about any language. I have small examples of code using the REST API in bashJava and Clojure, and I'd probably find it amusing to cook up an example in your favorite language; send me mail if you'd like details.

Getting started

You'll need Python (version 2.7.x recommended) and pyxnat to follow along. Someday soon we'll have a hackathon-customized version of pyxnat to provide easier access to the S3-hosted data, but there's nothing AWS-specific about this introduction, so plain old pyxnat will be fine. I'm writing this using Python 2.7.1 on Mac OS X 10.7.5, but I regularly use pyxnat on Gentoo Linux; other people use pyxnat on other Linuxes and even Windows. In principle, this all should work just about anywhere you can run Python, but send me mail if you run into trouble.

Aside for Python experts: because I'm working on pyxnat and not just with it, I usually don't install pyxnat to the system Python; instead I set up a virtualenv and install to that. We'll probably have to do this in a later tutorial, as we start using not-yet-published pyxnat extensions for working with the S3-hosted data.

You'll also need to create an account on ConnectomeDB and agree to the HCP Open Access Data Use Terms.

We'll look at some behavioral measures in ConnectomeDB: the Non-Toolbox Data Measures, a variety of tests that aren't part of the NIH Toolbox. (NIH Toolbox scores are forthcoming but not available in the Q1 data release.) The non-Toolbox measures are documented in detail herenontoolbox.xsd is an XML Schema document that specifies the non-Toolbox data type in ConnectomeDB; it's not particularly readable, but it does provide the exact naming conventions used in ConnectomeDB.

Let's start by firing up a Python session, loading pyxnat, and setting up a connection to ConnectomeDB.

bash-3.2$ python
Python 2.7.1 (r271:86832, Jul 31 2011, 19:30:53) 
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pyxnat
>>> cdb=pyxnat.Interface('','mylogin','mypasswd')

This Interface object creates a session on ConnectomeDB. Be warned: if the session is idle for a while – say, for example, you're too busy reading documentation to keep typing -- ConnectomeDB may close the session. You can tell that the session has gone stale if, when you try to do a query:


you get a plateful of nonsense that looks like:

['status', 'content-location', 'content-language', ...
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>

If this happens, just create a new Interface:

>>> cdb=pyxnat.Interface('','mylogin','mypasswd')

Any query result objects that you created from the stale Interface will also need to be refreshed. There's an example later in this tutorial.

Exploring the ConnectomeDB data hierarchy

ConnectomeDB's data is organized into projects, which are the main access control structure in XNAT. If you have access to a project, you can see that project's data. Let's see what projects we have access to:

['HCP_Q1']                           # maybe some others, depending on your access settings
>>> asks ConnectomeDB for project details and turns the result into a collection of project objects. The get() method returns the identifiers for each object in the collection. We could get the same result using a list comprehension; let's try that now, because that will be a more convenient form in general:

>>> [ for project in]

Since we're interested in the HCP Q1 data, let's get a handle on just that project:

>>> q1 ='HCP_Q1')

Note that if the session goes stale, so will this object q1. So in addition to refreshing cdb, you'll probably need to refresh q1, too, by reissuing this command:

>>> q1 ='HCP_Q1')

Querying for Subjects in the Q1 Project

What's inside of this project object? Each project contains subjects and experiments. Let's look at the list of subjects:

>>> [subject.label() for subject in q1.subjects()]
['100307', '103515', '103818', '111312', '114924', '117122', '118932', '119833', '120212', '125525', '128632', '130013', '137128', '138231', '142828', '143325', '144226', '149337', '150423', '153429', '156637', '159239', '161731', '162329', '167743', '172332', '182739', '191437', '192439', '192540', '194140', '197550', '199150', '199251', '200614', '201111', '210617', '217429', '249947', '250427', '255639', '304020', '307127', '329440', '499566', '530635', '559053', '585862', '638049', '665254', '672756', '685058', '729557', '732243', '792564', '826353', '856766', '859671', '861456', '865363', '877168', '889579', '894673', '896778', '896879', '901139', '917255', '937160', '131621', '355542', '611231', '144428', '230926', '235128', '707244', '733548']

We used subject.label() instead of, which inside the list comprehension would have given the same result as q1.get(). Why label() instead of id()? The label is the human-readable name for the subject within a specified project (HCP_Q1 in our case); the first label in the list is 100307, which is the HCP-assigned name for that subject. The subject id is the XNAT site-wide unique identifer for that subject, a not-intended-for-human-consumption identifier; the id for subject 100307 is 'ConnectomeDB_S00230'. In principle, different projects might assign different labels to the same subject, or different subjects might share the same label in different projects. We aren't engaging in those sorts of shenanigans on ConnectomeDB, but we do inherit a little complexity from XNAT's flexibility.

Querying for Experiments for each Subject

What data are available for subject 100307? Let's ask:

>>> [expt.label() for expt in q1.subject('100307').experiments()]
['100307_3T', '100307_SubjMeta', '100307_NonToolbox']

There are three "experiments" here: 100307_3T contains the imaging data and associated metadata acquired on the HCP 3T Skyra; 100307_SubjMeta holds some bookkeeping about what data have been collected for this subject; and 100307_NonToolbox has the non-Toolbox scores. Again we use label() instead of id() (or get() on the experiments collection), because each project has a human-readable label for the experiment, whereas the id is the site-wide, XNAT-generated identifier.

Exploring Experiment Data

The experiments are represented by XML documents; we can view the XML for 100307_NonToolbox to see what's inside:

>>> nt_100307 = q1.subject('100307').experiment('100307_NonToolbox')
>>> print(nt_100307.get())
<?xml version="1.0" encoding="UTF-8"?>
<nt:NTScores ID="ConnectomeDB_E00299" project="HCP_Subjects" label="100307_NonToolbox" xmlns:arc="" xmlns:val="" xmlns:pipe="" xmlns:hcp="" xmlns:wrk="" xmlns:scr="" xmlns:xdat="" xmlns:nt="" xmlns:cat="" xmlns:prov="" xmlns:xnat="" xmlns:xnat_a="" xmlns:xsi="" xsi:schemaLocation="">
<xnat:share label="100307_NonToolbox" project="HCP_Q1">
<xnat:share label="100307_NonToolbox" project="HCP_Q2">

That's a lot of stuff. Let's take it line-by-line.

The first line, <?xml version="1.0" ... , just tells us that this is an XML document.

The second line, <nt:NTScores ID="ConnectomeDB_E00299" ..., is the start of the actual content. It tells us that this is a N(on)T(oolbox)Scores document, gives us the experiment ID (the XNAT site-wide identifier), the project ID, the experiment labels (the human-readable, in-project-context name), and ends with a bunch of namespace information in case we want to validate this document against the schema we were looking at earlier. (I don't. You're welcome to if you like.)

The next few lines, <xnat:sharing> through </xnat:sharing>, tell us what projects know about this experiment. We can skip over this. (Yes, there's an HCP_Q2 project. No, it's not ready for you to look at yet.)

Next comes the subject ID; again, this is the XNAT site-wide ID, not the human-readable name (label). We can use pyxnat to ask ConnectomeDB for the label in a specified project:

>>> q1_proj.subject('ConnectomeDB_S00230')

After that come the scores (and lots of them), organized into a few groups. The schema document nontoolbox.xsd may be useful in helping to decipher this. We can ask for individual scores by walking the XML DOM:

>>> nt = q1_proj.subject('100307').experiment('100307_NonToolbox')
>>> nt.xpath('nt:ER40/nt:ER40_CR')
[<Element {}ER40_CR at 0x102065370>]
>>> nt.xpath('nt:ER40/nt:ER40_CR')[0].text()

That's a slow way of retreiving scores, since we need a full HTTP request and response for each field. (Actually, pyxnat does some caching so the requests aren't repeated. Probably. Usually. I'd still recommend doing something else.) If we want multiple scores -- either more than one score from a single experiment, or one or more scores from each of multiple experiments, there are more efficient methods.

Let's start with selecting multiple scores for a single experiment. A reasonable approach is to grab and parse the entire experiment XML document, using the Python standard library module ElementTree:

>>> import xml.etree.ElementTree as ET
>>> nt_dom = ET.fromstring(nt.get())
>>> nt_dom.tag
>>> er40 = nt_dom.find('{}ER40')
>>> [[e.tag,e.text] for e in er40]
[['{}ER40_CR', '39'], ['{}ER40_CRT', '1471.0'], ['{}ER40ANG', '8'], ['{}ER40FEAR', '8'], ['{}ER40HAP', '8'], ['{}ER40NOE', '8'], ['{}ER40SAD', '7']]

Getting scores from multiple experiments can be done either by iterating over experiment IDs with the methods described above (single-attribute or XML document requests), or by using the pyxnat search interface, which will be covered in an update coming soon.

Searching on ConnectomeDB

Retrieving values for multiple subjects or experiments is usually best done through the pyxnat search interface. Let's start with an example: getting all of the NEO-FFI scores for all subjects in project 'HCP_Q1', with the corresponding subject labels. Parts of this example won't yet make sense, but we'll march ahead to a result, then backtrack to fill in the missing details.

First, we identify the fields we want to retrieve:

>>> xsitype = 'nt:scores'
>>> fields = ['SUBJECT_ID']+['NEO_NEOFAC_{}'.format(e) for e in 'AOCNE']
>>> fields = ['{}/{}'.format(xsitype, f) for f in fields]
>>> fields
 'nt:scores/NEO_NEOFAC_A', 'nt:scores/NEO_NEOFAC_O', 
'nt:scores/NEO_NEOFAC_C', 'nt:scores/NEO_NEOFAC_N', 

Next, we build a constraint to use only subjects in project HCP_Q1:

>>> constraints = [(xsitype+'/PROJECTS', 'LIKE', '%HCP_Q1%']]

Now, we run the search:

>>> table =,fields).where(constraints)
<JsonTable 76:6> subject_id,neo_neofac_a ... neo_neofac_n,neo_neofac_o

The result is an instance of a pyxnat-defined class (JsonTable). The most useful methods on this class are headers(), which shows the ordering of each row; and items(), which returns the content as an array of rows, each row a list:

>>> table.headers()
['subject_id', 'neo_neofac_a', 'neo_neofac_c', 'neo_neofac_e', 'neo_neofac_n', 'neo_neofac_o']
>>> table.items()
[('ConnectomeDB_S00230', '33', '24', '35', '15', '37'), ('ConnectomeDB_S00231', '19', '27', '32', '25', '25'), ...

ConnectomeDB gave us subject IDs instead of labels. Let's reorder this result into a dictionary with subject labels as the keys:

>>> neoffi_fields = table.headers()[1:]
>>> neoffi = {q1.subject(row[0]).label():row[1:] for row in table.items()}
>>> neoffi.keys()
['143325', '937160', '889579', '707244', '197550', ... ]

Now it's easy to view the scores for a single subject:

>>> dict(zip(neoffi_fields, neoffi['143325']))
{'neo_neofac_a': '28', 'neo_neofac_c': '25', 'neo_neofac_e': '32', 'neo_neofac_n': '25', 'neo_neofac_o': '15'}

We can also do simple local searches with data in this form. For example, here are all the subjects with agreeableness (neo_neofac_a) score higher than 40:

>>> ia = neoffi_fields.index('neo_neofac_a')
>>> [k for [k,v] in neoffi if v[ia] and int(v[ia]) > 40]
['792564', '877168', '732243', '149337']

Simple searching (once more, with details)

Now that we've seen that it's possible to do something with the search interface, let's dig into the details. Our first step was to build a list naming the fields of interest:

>>> xsitype = 'nt:scores'
>>> fields = ['SUBJECT_ID']+['NEO_NEOFAC_{}'.format(e) for e in 'AOCNE']
>>> fields = ['{}/{}'.format(xsitype, f) for f in fields]
>>> fields
 'nt:scores/NEO_NEOFAC_A', 'nt:scores/NEO_NEOFAC_O', 
'nt:scores/NEO_NEOFAC_C', 'nt:scores/NEO_NEOFAC_N', 

All of the fields we're retrieving are defined in the nt:scores datatype; we need to include the datatype name as a prefix to the field names. If you look at nontoolbox.xsd, the XML Schema document where the scores datatype is defined, you'll see the definitions of all these fields, but with a twist: none of the names in the schema match the names we're using above. For example, the NEO fields are all defined inside a wrapper element. We might expect the fields to have names like NEO/NEOFAC_A; instead, we have names like NEO_NEOFAC_A.

Why does the pyxnat search interface use a different field naming convention than the datatype definitions? It's a historical accident, and XNAT's fault. The search interface uses an field naming system that is independent of field naming elsewhere in the application; the mapping between search-service field names and everywhere-else field names is defined in the display document, which primarily specifies how data types appear in the web application. The display document for nt:scores lists all the fields that can be displayed in the web application, with some information about how they are to be displayed. An excerpt follows:

nt:scores display document excerpt
<?xml version="1.0" encoding="UTF-8"?>
<Displays xmlns:xsi="" xsi:noNamespaceSchemaLocation="../../xdat/display.xsd" schema-element="nt:scores" full-description="NTScores" brief-description="NTScores">
                <CommonField id="PART_ID" local-field="SUBJECT_ID"/>
                <CommonField id="DATE" local-field="DATE"/>
                <CommonField id="EXPT_ID" local-field="EXPT_ID"/>
        <DisplayField id="SUBJECT_ID" header="Subject" visible="true" searchable="true">
                <DisplayFieldElement name="Field1" schema-element="nt:scores.subject_ID"/>
                        <Property name="HREF" value="none"/>
                        <Property name="ONCLICK" value="return rpt('@Field1','xnat:subjectData','xnat:subjectData.ID');">
                                <InsertValue id="Field1" field="SUBJECT_ID"/>
                <description>Subject Label</description>
        <DisplayField id="EXPT_ID" header="ID" visible="true" searchable="true">
                <DisplayFieldElement name="Field1" schema-element="nt:scores.ID"/>
                        <Property name="HREF" value="none"/>
                        <Property name="ONCLICK" value="return rpt('@Field1','nt:scores','nt:scores.ID');">
                                <InsertValue id="Field1" field="EXPT_ID"/>
                <description>Experiment ID</description>
        <DisplayField id="NEO_NEO" header="NEO" visible="true" searchable="true">
                <DisplayFieldElement name="Field1" schema-element="nt:scores/NEO/NEO"/>
                <description>NEO Combined Factor (Total) Score</description>
        <DisplayField id="NEO_NEOFAC_A" header="NEOFAC_A" visible="true" searchable="true">
                <DisplayFieldElement name="Field1" schema-element="nt:scores/NEO/NEOFAC_A"/>
                <description>NEO Factor A (Agreeableness)</description>
        <DisplayField id="NEO_NEOFAC_O" header="NEOFAC_O" visible="true" searchable="true">
                <DisplayFieldElement name="Field1" schema-element="nt:scores/NEO/NEOFAC_O"/>
                <description>NEO Factor O (Openness to Experience)</description>
        <DisplayField id="NEO_NEOFAC_C" header="NEOFAC_C" visible="true" searchable="true">
                <DisplayFieldElement name="Field1" schema-element="nt:scores/NEO/NEOFAC_C"/>
                <description>NEO Factor C (Conscientiousness)</description>
        <DisplayField id="NEO_NEOFAC_N" header="NEOFAC_N" visible="true" searchable="true">
                <DisplayFieldElement name="Field1" schema-element="nt:scores/NEO/NEOFAC_N"/>
                <description>NEO Factor N (Neuroticism)</description>
        <DisplayField id="NEO_NEOFAC_E" header="NEOFAC_E" visible="true" searchable="true">
                <DisplayFieldElement name="Field1" schema-element="nt:scores/NEO/NEOFAC_E"/>
                <description>NEO Factor E (Extraversion)</description>
        <DisplayField id="SPCPTNL_SCPT_TP" header="SCPT_TP" visible="true" searchable="true">
                <DisplayFieldElement name="Field1" schema-element="nt:scores/SPCPTNL/SCPT_TP"/>
                <description>Short CPT True Positives = Sum of CPN_TP and CPL_TP</description>

Each field that can be accessed through the search interface has a corresponding DIsplayField element; the id attribute is the name by which the field is addressed in searches. Look carefully at the DIsplayField element with id=NEO_NEOFAC_A ; note that it has DisplayFieldElement subelement, which includes an attribute "schema-element"  that contains the field's name as we'd find it in the schema.

Table of Contents

  • No labels