- Created by Unknown User (karchi01), last modified on Apr 02, 2014
All of the publicly available data from the Human Connectome Project are accessible through ConnectomeDB, a web site built on the XNAT imaging informatics platform. In addition to the imaging data, a great deal of imaging metadata and associated non-imaging data are stored on ConnectomeDB.
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 and to view and download the imaging data. 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 bash, Java, Clojure, and Haskell, and I'd probably find it amusing to cook up an example in your favorite language; send me mail if you'd like details.
You'll need Python (version 2.7.x recommended) and pyxnat to follow along. I've been adding features (some HCP-specific) and fixing bugs in pyxnat, so I recommend creating a Python virtual environment and installing our customized version of pyxnat. 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. It's also possible to use pyxnat on an Amazon EC2 instance. In principle, this all should work just about anywhere you can run Python, but send me mail if you run into trouble.
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. The non-Toolbox measures are documented in detail here. nontoolbox.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.
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:
The same error occurs if you provide the wrong username or password.
If this happens, whether due to timeout or mistyping, just create a new Interface:
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:
cdb.select.projects() 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:
Let's use the project for the current (Q2) data release, HCP_Q2. Here we get a handle on just that project:
Note that if the session goes stale, so will this object
q2. So in addition to refreshing cdb, you'll probably need to refresh
q2, too, by reissuing this command:
Querying for Subjects in the Q2 Project
What's inside of this project object? Each project contains subjects and experiments. Let's look at the list of subjects:
subject.label() instead of
subject.id(), which inside the list comprehension would have given the same result as
label() instead of
id()? The label is the human-readable name for the subject within a specified project (HCP_Q2 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:
There are five "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; 100307_Toolbox has NIH Toolbox scores, 100307_NonToolbox the non-Toolbox scores, and 100307_Alertness has scores for the Mini Mental Status Exam (MMSE) and Pittsburgh Sleep Questionnaire (PSQI). Again we use
label() instead of
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 individual experiments are represented by XML documents; we can view the XML for 100307_NonToolbox to see what's inside:
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>, tell us what projects know about this experiment. We can skip over this.
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:
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:
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:
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.
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_Q2', 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:
Next, we build a constraint to use only subjects in project HCP_Q2:
Now, we run the search:
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:
ConnectomeDB gave us subject IDs instead of labels. Let's reorder this result into a dictionary with subject labels as the keys:
Now it's easy to view the scores for a single subject:
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:
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.
Naming fields in searches
Our first step was to build a list naming the fields of interest:
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. pyxnat provides a way to see what search terms are available:
That list is useful, but doesn't really tell you what each field is. 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:
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 that element has a DisplayFieldElement subelement, which includes an attribute "schema-element" containing the field's name as we'd find it in the schema.
The tedious but reliable strategy for finding the search interface field identifiers is:
- Determine from the data type documentation what fields you'll be using.
- Find the field in the schema document (nontoolbox.xsd for the non-Toolbox Data Measures)
- Find the corresponding DisplayElement in the display document (nt_scores_display.xml for the non-Toolbox Data Measures scores data type nt:scores), then use the id attribute value, with the data type prefix.
In practice, the display label returned by cdb.inspect.datatypes() is usually enough detail to save you from digging through the various XML documents.
Next, we build a constraint to use only subjects in project HCP_Q2:
What's happening here? The nt:scores display document defines a PROJECTS DisplayField that is a comma-separated list of all projects that can see the nt:scores experiment: the project that contains the experiment, plus any projects into which the experiment has been shared. Since XNAT checks this constraint by doing a SQL query, the value is compared with a LIKE operation – a pattern match. % is the wildcard character in SQL, so we're looking for HCP_Q2 anywhere in that comma-separated list.
Aside for the obsessively detail-oriented: We'd have to be more clever if there were a project named, say, HCP_Q2b. It's possible to conjoin LIKE constraints with NOT LIKE constraints to make this work, and I'll update this text if that becomes necessary. For now, the project names on ConnectomeDB are probably sufficiently distinct.
Running the search and transforming the results
This part is mostly straightforward: we need to tell pyxnat what datatype we're searching for, what fields we want from it, and what constraints we want to apply. We use a dictionary comprehension to transform the results into a dictionary where the subject labels are the keys.
The first field (index 0) is the subject ID, which we strip out of both the headers and the row contents using Python's slice operator. We then build a dictionary by looking up the subject labels (
q2.subject(row).label()), using those as keys, and using the rows with the subject ID removed as values.
Once we have the subject-to-values dictionary, we can build single-subject field-name-to-value dictionaries by zipping the field names together with the values for that subject, then building a dictionary from the resulting stream of key-value pairs:
Finally, since we've downloaded all the NEO scores, we can search in memory without asking ConnectomeDB anything else:
Here we look up the index of the agreeableness score, store it as ia=0, and extract the subject labels where there is an agreeableness score (
v[ia] evaluates truthy for nonempty scores, false for the empty string) and the value is greater than 40 (
int(v[ia]) > 40).
Building complex searches
The pyxnat search interface documentation explains how to compose simple searches into complex ones, so I'll just present some examples.
This is the same search that we performed on the NEO-FFI scores above, except this time on the server side:
Finding (and counting) subjects scoring from 30 to 34 total correct on the Computerized Penn Word Memory:
Finding subjects scoring either less than 30 or 35 or more total correct on the Computerized Penn Word Memory:
Accessing imaging data
Once you know what you want, the best method to download the HCP imaging data is to use Aspera's faspTM, a proprietary transport protocol supported by ConnectomeDB. You'll need the free (gratis, not libre) Aspera Connect browser plugin. The easiest way to get this plugin is to log in to ConnectomeDB; if you don't have the plugin installed, a message at the top of the screen will hector you until you do.
The HCP-customized version of pyxnat includes a class for browsing and downloading HCP data using the Aspera plugin. For example, we can list the available package types:
The Aspera-downloadable data are organized a little differently from Connectome-in-a-Box; each package is a zip file that contains the associated files. The zip files unpack into the same layout as C-in-a-B.
We can get archive file metadata about packages available for particular subjects:
We can use the Aspera plugin to download the archive files:
This places the .zip files (and .zip.md5 checksums) in your working directory; you can instead specify a directory to place the downloaded zip files:
This download will take a while, even with the Aspera transport – and trust me, it's a lot faster than FTP/HTTP, especially if you're far from St. Louis. You are moving gigabytes of data through the rusty old intertubes. If you're going to download more than a few subjects, consider getting Connectome in a Box. The cost is comparable to the extra disk you were going to need to buy to hold the data anyway.
I hope this tutorial is enough to get you started scripting against ConnectomeDB. If you're working through this tutorial or diving into the data, and you find rough edges that need to be smoothed (or big gaping holes that need to be filled), please let me know, by either submitting a comment below or sending me mail.
Table of Contents
- No labels