- Created by Unknown User (karchi01), last modified on May 21, 2013
You are viewing an old version of this page. View the current version.
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 bash, Java 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.
You'll need Python (version 2.7.x recommended) and pyxnat to follow along. Because of bugs in the released version of pyxnat, I recommend creating a Python virtual environment and installing a development 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. (NIH Toolbox scores are forthcoming but not available in the Q1 data release.) 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:
Since we're interested in the HCP Q1 data, let's get a handle on just that project:
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:
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() 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_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:
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
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:
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. (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:
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, 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:
Next, we build a constraint to use only subjects in project HCP_Q1:
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; 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 process for finding the search interface field identifiers, then, 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 many cases, the description in the display document is sufficient information and you can skip step 2.
Next, we build a constraint to use only subjects in project HCP_Q1:
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_Q1 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_Q1b. 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 used 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 (
q1.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
Before trying to access the data, it's important to understand what's in the Q1 release. The Q1 data release documentation describes the session structure and file layout in detail. The Q1 imaging data are mirrored on Amazon's S3, which is particularly useful for copying data into an EC2 instance. The Python library boto provides an interface for many of Amazon's web services, including S3. If you installed the HCP-customized pyxnat, you already have boto.
I'm working to extend pyxnat to translate between the internal storage paths on ConnectomeDB and the (differently organized) copy of the data on S3. You really don't need to wait for this, though: the example searches above produce subject labels, which is enough information to point you to the right data directories on S3 – for example, subject 100307's data can be found at s3://hcp.aws.amazon.com/q1/100307/ . Consult the hackathon HCP data release announcement for more details.
Browsing the imaging data
In order to start exploring and using the S3 Q1 mirror, you'll need to set up your AWS account and get access to the Amazon-hosted data. This process will get you an access key and a secret key, which you'll use to authenticate against S3. From a Python command line, you can browse the Q1 data by getting a handle to the "bucket" where the data are stored:
S3 is a key-value-oriented store, rather than a hierarchical filesystem, but the HCP Q1 data is stored with keys that echo a regular file system. boto's interface to S3 makes it easy to pretend you're walking a file tree. There is a single root element
q1, and each subject is a child of that root:
Each subject is organized as described in the Q1 data release documentation.
The three key fragments associated with the "minimally preprocessed" data are
T1w. The key fragment
.xdlm marks file manifests for download integrity checking, including checksums; while
unprocessed marks unprocessed data.
Downloading files from S3
Now let's copy all files for the motor task with left-to-right phase encoding from S3 to a local disk.
Note that we use
bucket.list(...) a little differently here: with one argument, it returns all keys starting with the provided text, which is comparable to a full recursive listing in a hierarchical file system.
The instructions above all handle ConnectomeDB and S3 as different worlds; I'm working on extending pyxnat to bridge the gap to map directly from ConnectomeDB results to S3-hosted data, and I'll be documenting those new features here as they're ready.
More important than the new integration features – which I only suspect will be useful -- is the actual experience of OHBM hackathon participants. Go write some code! 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), let me know, by either submitting a comment below or sending me mail.
See you in Seattle!
Table of Contents
- No labels