Reference documentation

The Interface class

class pyxnat.core.Interface(server, user=None, password=None, cachedir='/tmp')

Main entry point to access a XNAT server.

>>> central = Interface(server='http://central.xnat.org:8080',
                        user='login',
                        password='pwd',
                        cachedir='/tmp'
                        )
Attributes:

_mode: online | offline :

Online or offline mode

_memlifespan: float :

Lifespan of in-memory cache

global_callback(func=None)

Defines a callback to execute when collections of resources are accessed.

Parameters:

func: callable :

A callable that takes the current collection object as first argument and the current element object as second argument.

Examples

>>> def notify(cobj, eobj):
>>>    print eobj._uri
>>> interface.global_callback(notify)

The Select class

class pyxnat.core.select.Select(interface)

Data selection interface. Callable object that indicates the data to be returned to the user.

Examples

Select with a path:
>>> interface.select('/projects/myproj/subjects').get()
Select with a datatype:
>>> interface.select('xnat:subjectData', ['xnat:subjectData/PROJECT', 'xnat:subjectData/SUBJECT_ID']
            ).where([('xnat:subjectData/SUBJECT_ID', 'LIKE', '*'), 'AND'])
__call__(datatype_or_path, columns=[])

Select clause to specify what type of data is to be returned.

Parameters:

datatype_or_path: string :

Can either be a resource path or a datatype:
  • when a path, REST resources are returned, the columns argument is useless.
  • when a datatype, a search Object is returned, the columns argument has to be specified.

columns: list :

List of fieldtypes e.g. xnat:subjectData/SUBJECT_ID Datatype and columns are used to specify the search table that has to be returned. Use the method where on the Search object to trigger a search on the database.

project(ID)

Access a particular project.

Parameters:

ID: string :

ID of the project.

projects(id_filter='*')

Returns the list of all visible projects for the server.

Parameters:

id_filter: string :

Name pattern to filter the returned projects.

The SearchManager class

class pyxnat.core.search.SearchManager(interface)

Search interface. Handles operations to save and get back searches on the server.

Examples

>>> interface.search.save(name='mysearch', 
                          row='xnat:subjectData',
                          columns=['xnat:subjectData/PROJECT','xnat:subjectData/SUBJECT_ID'],
                          constraints=[('xnat:subjectData/SUBJECT_ID', 'LIKE', '*'), 'AND'],
                          sharing='public'
                          )
delete(name)
Removes the search from the server.
get(name)
Returns the results of the query saved on the XNAT server.
save(name, row, columns, constraints, sharing='private')

Saves a query on the XNAT server.

Parameters:

name: string :

Name of the query displayed on the Web Interface and used to get back the results.

row: string :

Datatype from Interface.inspect.datatypes(). Usually xnat:subjectData

columns: list :

List of data fields from Interface.inspect.datatypes(‘*’, ‘*’)

constraints: list :

See also: Search.where()

sharing: string | list :

Define by whom the query is visible. If sharing is a string it may be either private or public. Otherwise a list of valid logins for the XNAT server from Interface.users().

See also

Search.where

saved()
Returns the names of accessible saved search on the server.

The Search class

class pyxnat.core.search.Search(row, columns, interface)

Define constraints to make a complex search on the database.

This Search is available at different places throughout the API:
>>> interface.select(DATA_SELECTION).where(QUERY)
>>> interface.search.save('name', TABLE_DEFINITION, QUERY)

Examples

>>> query = [('xnat:subjectData/SUBJECT_ID', 'LIKE', '%'), 
             ('xnat:projectData/ID', '=', 'my_project'),
             [('xnat:subjectData/AGE', '>', '14'),
               'AND'
              ],
             'OR'
            ]
where(constraints)

Triggers the search.

Parameters:

contraints: list :

A query is an unordered list that contains
  • 1 or more constraints

  • 0 or more sub-queries (lists as this one)

  • 1 comparison method between the constraints

    (‘AND’ or ‘OR’)

A constraint is an ordered tuple that contains
  • 1 valid searchable_type/searchable_field
  • 1 operator among ‘=’, ‘<’, ‘>’, ‘<=’, ‘>=’, ‘LIKE’
Returns:

results: JsonTable object :

An table-like object containing the results. It is basically a list of dictionaries that has additional helper methods.

The EObject class

class pyxnat.core.resources.EObject(uri, interface)

Generic Object for an element URI.

absurl()

Returns an absolute URL of the element resource, including the server address and the user login and password.

Note

Not used at the moment.

children()

Returns the children levels of this element.

Examples

>>> subject_object.children()
['experiments', 'resources']
create(**datatypes)

Creates the element if it does not exists. Any non-existing ancestor will be created as well.

Warning

An element resource both have an ID and a label that can be used to access it. At the moment, XNAT REST API defines the label when creating an element, but not the ID, which is generated. It means that the name given to a resource may not appear when listing the resources because the IDs will appear, not the labels.

Parameters:

datatypes: keywords or dict :

Specify the datatype of the element resource and of any ancestor that may need to be created. The keywords correspond to the levels in the REST hierarchy, i.e. Interface.inspect.rest_hierarchy()

If an element is created with no specified type:
  • if its name matches a naming convention, this type will be used
  • else a default type is defined in the schema module

See also

EObject.id, EObject.label, EObject.datatype, Interface.inspect.naming_conventions

Examples

>>> interface.select('/project/PROJECT/subject/SUBJECT/experiment/EXP/scan/SCAN'
            ).create(experiments='xnat:mrSessionData', scans='xnat:mrScanData')
datatype()

Returns the type defined in the XNAT schema for this element resource.

EObject possible xsi types
Project xnat:projectData
Subject xnat:subjectData
Experiment xnat:mrSessionData xnat:petSessionData
delete(delete_files=True)

Deletes an element resource.

Parameters:

delete_files: True | False :

Tells if files attached to the element resources are removed as well from the server filesystem.

exists()
Test whether an element resource exists.
id()
Returns the element resource id.
label()
Returns the element resource label.

The CObject class

class pyxnat.core.resources.CObject(cbase, interface, pattern='*', nested=None, id_header='ID', columns=[])

Generic Object for a collection resource.

A collection resource is a list of element resources. There is however several ways to obtain such a list:

  • a collection URI e.g. /REST/projects
  • a list of element URIs
  • a list of collections e.g. /REST/projects/ONE/subjects and /REST/projects/TWO/subjects
  • a list of element objects
  • a list a collection objects
Collections objects built in different ways share the same behavior:
  • they behave as iterators, which enables a lazy access to the data
  • they always yield EObjects
  • they can be nested with any other collection

Examples

No access to the data:
>>> interface.select.projects()
<Collection Object> 173667084
Lazy access to the data:
>>> for project in interface.select.projects():
>>>     print project
Nesting:
>>> for subject in interface.select.projects().subjects():
>>>     print subject
first()
Returns the first element of the collection.
get(*args)

Returns every element.

Warning

If a collection needs to issue thousands of queries it may be better to access the resources within a for-loop.

Parameters:

args: ID, label, obj :

Specify to return the element ID, label or Object. Any combination of ID, label and obj is valid, if more than one is given, a list of tuple is returned instead of a list.

where(constraints)

Only the element objects whose subject that are matching the constraints will be returned. It means that it is not possible to use this method on an element that is not linked to a subject, such as a project.

See also

search.Search

Examples

The where clause should be on the first select:
>>> for experiment in interface.select('//experiments'
>>>                           ).where([('atest/FIELD', '=', 'value'), 'AND']):
>>>     print experiment
Do NOT do this:
>>> for experiment in interface.select('//experiments'):
>>>     for assessor in experiment.assessors(
>>>                              ).where([('atest/FIELD', '=', 'value'), 'AND']):
>>>         print assessor
Or this:
>>> for project in interface.select('//projects'
>>>                        ).where([('atest/FIELD', '=', 'value'), 'AND']):
>>>     print project

The Project class

class pyxnat.core.resources.Project(uri, interface)
accessibility()
Gets project accessibility.
add_user(login, role='member')

Adds a user to the project. The user must already exist on the server.

Parameters:

login: string :

Valid username for the XNAT database.

role: owner | member | collaborator :

The user level for this project:
  • owner: read and write access, as well as administrative privileges

    such as adding and removing users.

  • member: read access and can create new resources but not remove them.

  • collaborator: read access only.

collaborators()
Gets collaborator of this project.
current_arc()
Gets project current archive folder on the server.
members()
Gets members of this project.
owners()
Gets owners of this project.
prearchive_code()
Gets project prearchive code.
quarantine_code()
Gets project quarantine code.
remove_user(login)

Removes a user from the project.

Parameters:

login: string :

Valid username for the XNAT database.

set_accessibility(accessibility='protected')

Sets project accessibility.

Parameters:

accessibility: public | protected | private :

Sets the project accessibility:
  • public: the project is visible and provides read access

    for anyone.

  • protected: the project is visible by anyone but the data

    is accessible for allowed users only.

  • private: the project is visible by allowed users only.

Write access is given or not by the user level for a specic project.

set_prearchive_code(code)

Sets project prearchive code.

Parameters:code: 0 to 4 :
set_quarantine_code(code)

Sets project quarantine code.

Parameters:code: 0 to 1 :
set_subfolder_in_current_arc(subfolder)
Changes project current archive subfolder on the server.
user_role(login)

Gets the user level of the user for this project.

Parameters:

login: string :

A user of the project.

Returns:

owner | member | collaborator :

users()
Gets all registered users for this project.

The File class

class pyxnat.core.resources.File(uri, interface)

EObject for files stored in XNAT.

attributes()
Files attributes include:
  • URI
  • Name
  • Size in bytes
  • file_tags
  • file_format
  • file_content
Returns:A dictionnary with the file attributes. :
content()
Gets the file content description.
create(src, format='U', content='U', tags='U')
Same as put.
delete()
Deletes the file on the server.
format()
Gets the file format.
get()

Downloads the file to the cache directory.

Note

The path is computed like this: path_to_cache/urichecksum_filename

Returns:The location of the file in the cache directory . :
get_copy(dest=None)

Downloads the file to the cache directory but creates a copy at the specified location.

Parameters:

dest: string | None :

Path for the copy. Defaults to None. If None a copy is created at a default location.

Returns:

The location of the copy. :

put(src, format='U', content='U', tags='U', **datatypes)

Uploads a file to XNAT.

Parameters:

src: string :

Location of the local file to upload.

format: string :

Optional parameter to specify the file format. Defaults to ‘U’.

content: string :

Optional parameter to specify the file content. Defaults to ‘U’.

tags: string :

Optional parameter to specify tags for the file. Defaults to ‘U’.

size()
Gets the file size.
tags()
Gets the file tags.

The Users class

class pyxnat.core.users.Users(interface)

Database user management interface. It is used to retrieve information on users registered on a server.

Note

At the moment user creation and deletion is not supported through the REST API but it will be at some point.

See also

Project.users, Project.add_user, Project.remove_user

Examples

>>> interface.users()
['list_of_users']
>>> interface.firstname('nosetests')
'nose'
email(login)
Returns the email of the user.
firstname(login)
Returns the firstname of the user.
id(login)
Returns the id of the user.
lastname(login)
Returns the lastname of the user.

The Inspector class

class pyxnat.core.help.Inspector(interface)
Database introspection interface.