Reference documentation

The Interface class

class pyxnat.core.Interface(server=None, user=None, password=None, config=None, anonymous=False, proxy=None, verify=None)

Main entry point to access an XNAT server.

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

Or with config file:

>>> central = Interface(config='/home/me/.xnat.cfg')

Or for interactive use:

>>> central = Interface('http://central.xnat.org')

Note

The interactive mode is triggered whenever an argument (between server, user or password) is missing. In interactive mode pyxnat will check that connection settings are valid.

Note

Proxy support requires the socks module be installed. This can be installed via pip:

pip install SocksiPy-branch

Or anonymously (unauthenticated):

>>> central = Interface('http://central.xnat.org', anonymous=True)
Attributes
_mode: online | offline

Online or offline mode

Methods

close_jsession()

Closes the session with XNAT server and consumes the JSESSIONID token

delete(uri, **kwargs)

Wrapper around requests.delete() returns rquests.response object

disconnect()

Tell XNAT to disconnect this session

get(uri, **kwargs)

Wrapper around requests.get() returns rquests.response object

head(uri, **kwargs)

Wrapper around requests.head() returns rquests.response object

load_config(location)

Loads a configuration file and replaces current connection parameters.

post(uri, **kwargs)

Wrapper around requests.post() returns rquests.response object

put(uri, **kwargs)

Wrapper around requests.put() returns rquests.response object

save_config(location)

Saves current configuration - including password - in a file.

set_logging

version

close_jsession()

Closes the session with XNAT server and consumes the JSESSIONID token

delete(uri, **kwargs)

Wrapper around requests.delete() returns rquests.response object

disconnect()

Tell XNAT to disconnect this session

get(uri, **kwargs)

Wrapper around requests.get() returns rquests.response object

head(uri, **kwargs)

Wrapper around requests.head() returns rquests.response object

load_config(location)

Loads a configuration file and replaces current connection parameters.

Note

This method raises NotImplementedError for an anonymous interface.

Parameters
location: string

Configuration file path.

post(uri, **kwargs)

Wrapper around requests.post() returns rquests.response object

put(uri, **kwargs)

Wrapper around requests.put() returns rquests.response object

save_config(location)

Saves current configuration - including password - in a file.

Warning

Since the password is saved as well, make sure the file is saved at a safe location with appropriate permissions.

Note

This method raises NotImplementedError for an anonymous interface.

Parameters
location: string

Destination config file.

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:
>>> columns = ['xnat:subjectData/PROJECT',
               'xnat:subjectData/SUBJECT_ID'
               ]
>>> criteria = [('xnat:subjectData/SUBJECT_ID', 'LIKE', '*'),
                'AND'
                ]
>>> interface.select('xnat:subjectData', columns
            ).where(criteria)

Methods

__call__(datatype_or_path[, columns])

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

experiment(ID)

Access a particular experiment.

experiments([id_filter])

Returns the list of all visible experiments for the server.

project(ID)

Access a particular project.

projects([id_filter])

Returns the list of all visible projects for the server.

tag

tags

__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 Inspect class

class pyxnat.core.help.Inspector(interface)

Database introspection interface.

Methods

__call__()

Call self as a function.

assessor_types()

Returns the datatypes used at the assessor level in this database.

assessor_values(experiment_type[, project])

Look for the values at the assessor level for a given experiment type in the database.

datatypes([pattern, fields_pattern])

Discovers the datatypes and datafields of the database.

experiment_types()

Returns the datatypes used at the experiment level in this database.

experiment_values(datatype[, project])

Look for the values a the experiment level for a given datatype in the database.

field_values(field_name)

Look for the values a specific datafield takes in the database.

project_values()

Look for the values a the project level in the database.

reconstruction_types()

Returns the datatypes used at the reconstruction level in this database.

reconstruction_values(experiment_type[, project])

Look for the values at the reconstruction level for a given experiment type in the database.

scan_types()

Returns the datatypes used at the scan level in this database.

scan_values(experiment_type[, project])

Look for the values at the scan level for a given experiment type in the database.

set_autolearn([auto, tick])

Once in a while queries will persist additional information on the server.

structure()

Displays the keywords structure used in XNAT REST API.

subject_values([project])

Look for the values a the subject level in the database.

assessor_types()

Returns the datatypes used at the assessor level in this database.

assessor_values(experiment_type, project=None)

Look for the values at the assessor level for a given experiment type in the database.

Note

The experiment type should be one of Inspector.experiment_types()

Warning

Depending on the number of elements the operation may take a while.

Parameters
datatype: string

An experiment type. eg: xnat:mrsessiondata

project: string

Optional. Restrict operation to a project.

datatypes(pattern='*', fields_pattern=None)

Discovers the datatypes and datafields of the database.

Parameters
pattern: string

Pattern for the datatype. May include wildcards.

fields_pattern: string
  • Pattern for the datafields – may include wildcards.

  • If specified, datafields will be returned instead of datatypes.

Returns
listdatatypes or datafields depending on the argument usage.
experiment_types()

Returns the datatypes used at the experiment level in this database.

experiment_values(datatype, project=None)

Look for the values a the experiment level for a given datatype in the database.

Note

The datatype should be one of Inspector.experiment_types()

Parameters
datatype: string

An experiment type. eg: xnat:mrsessiondata

project: string

Optional. Restrict operation to a project.

field_values(field_name)

Look for the values a specific datafield takes in the database.

project_values()

Look for the values a the project level in the database.

Note

Is equivalent to interface.select.projects().get()

reconstruction_types()

Returns the datatypes used at the reconstruction level in this database.

reconstruction_values(experiment_type, project=None)

Look for the values at the reconstruction level for a given experiment type in the database.

Note

The experiment type should be one of Inspector.experiment_types()

Warning

Depending on the number of elements the operation may take a while.

Parameters
datatype: string

An experiment type.

project: string

Optional. Restrict operation to a project.

scan_types()

Returns the datatypes used at the scan level in this database.

scan_values(experiment_type, project=None)

Look for the values at the scan level for a given experiment type in the database.

Note

The experiment type should be one of Inspector.experiment_types()

Warning

Depending on the number of elements the operation may take a while.

Parameters
datatype: string

An experiment type.

project: string

Optional. Restrict operation to a project.

set_autolearn(auto=None, tick=None)

Once in a while queries will persist additional information on the server. This information is available through the following methods of this class:

  • experiment_types

  • assessor_types

  • scan_types

  • reconstruction_types

It is also transparently used in insert operations.

Parameters
auto: boolean

True to enable auto learn. False to disable.

tick: int

Every ‘tick’ seconds, if a query is issued, additional information will be persisted.

See also

EObject.insert()

structure()

Displays the keywords structure used in XNAT REST API.

subject_values(project=None)

Look for the values a the subject level in the database.

Note

Is equivalent to interface.select(‘//subjects’).get()

The SearchManager class

class pyxnat.core.search.SearchManager(interface)

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

Examples

>>> row = 'xnat:subjectData'
>>> columns = ['xnat:subjectData/PROJECT',
               'xnat:subjectData/SUBJECT_ID'
               ]
>>> criteria = [('xnat:subjectData/SUBJECT_ID', 'LIKE', '*'),
                'AND'
                ]
>>> interface.manage.search.save('mysearch', row, columns,
                                 criteria, sharing='public',
                                 description='my first search'
                                 )

Methods

delete(name)

Removes the search from the server.

delete_template(name)

Deletes a search template.

get(name[, out_format])

Returns the results of the query saved on the XNAT server or the query itself to know what it does.

get_template(name[, as_xml])

Get a saved template, either as an xml document, or as a pyxnat representation, with the keys to be used in the template between the parentheses in %()s.

save(name, row, columns, constraints[, …])

Saves a query on the XNAT server.

save_template(name[, row, columns, …])

Define and save a search template.

saved([with_description])

Returns the names of accessible saved search on the server.

saved_templates([with_description])

Returns the names of accessible saved search templates on the server.

use_template(name, values)

Parameters

eval_rpn_exp

delete(name)

Removes the search from the server.

delete_template(name)

Deletes a search template.

get(name, out_format='results')

Returns the results of the query saved on the XNAT server or the query itself to know what it does.

Parameters
name: string

Name of the saved search. An exception is raised if the name does not exist.

out_format: string
Can take the following values:
  • results to download the results of the search

  • xml to download the XML document defining the search

  • query to get the pyxnat representation of the search

get_template(name, as_xml=False)

Get a saved template, either as an xml document, or as a pyxnat representation, with the keys to be used in the template between the parentheses in %()s.

Parameters
name: str

Name under which the template is saved

as_xml: boolean

If True returns an XML document, else return a list of constraints. Defaults to False.

save(name, row, columns, constraints, sharing='private', description='')

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()

save_template(name, row=None, columns=[], constraints=[], sharing='private', description='')

Define and save a search template. Same as the save method, but the values in the constraints are used as keywords for value replacement when using the template.

Parameters
name: string

Name under which the template is save in XNAT. A ‘template_’ is prepended to the name so that it appear clearly as a template on the web interface.

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(), values are keywords for the template

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().

saved(with_description=False)

Returns the names of accessible saved search on the server.

saved_templates(with_description=False)

Returns the names of accessible saved search templates on the server.

use_template(name, values)
Parameters
name: string

Name of the template.

values: dict

Values to put in the template, get the valid keys using the get_template method.

Examples

>>> interface.manage.search.use_template(name,
              {'subject_id':'ID',
               'age':'32'
               })

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.manage.search.save('name', TABLE_DEFINITION, QUERY)

Examples

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

Methods

where([constraints, template, query])

Triggers the search.

all

where(constraints=None, template=None, query=None)

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.

Methods

children([show_names])

Returns the children levels of this element.

create(**params)

Creates the element if it does not exists.

datatype()

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

delete([delete_files])

Deletes an element resource.

exists([consistent])

Test whether an element resource exists.

get()

Retrieves the XML document corresponding to this element.

id()

Returns the element resource id.

insert(**params)

Creates the element if it does not exists.

label()

Returns the element resource label.

tag(name)

Tag the element.

untag(name)

Remove a tag for the element.

namespaces

parent

xpath

children(show_names=True)

Returns the children levels of this element.

Parameters
show_name: boolean

If True returns a list of strings. If False returns a collection object referencing all child objects of this elements.

Examples

>>> subject_object.children()
['experiments', 'resources']
>>> subject_object.children(False)
<Collection Object> 170976556
create(**params)

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.

Note

To set up additional variables for the element at its creation it is possible to use shortcuts defined in the XNAT REST documentation or xpath in the schema:

  • element.create(ID=’theid’)

  • subject.create(**{‘xnat:subjectData/ID’:’theid’})

Parameters
params: keywords
  • 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, see Interface.inspect.architecture()

  • 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

  • To give the ID the same value as the label use use_label=True e.g element.create(use_label=True)

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: boolean

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

exists(consistent=False)

Test whether an element resource exists.

get()

Retrieves the XML document corresponding to this element.

id()

Returns the element resource id.

insert(**params)

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.

Note

To set up additional variables for the element at its creation it is possible to use shortcuts defined in the XNAT REST documentation or xpath in the schema:

  • element.create(ID=’theid’)

  • subject.create(**{‘xnat:subjectData/ID’:’theid’})

Parameters
params: keywords
  • 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, see Interface.inspect.architecture()

  • 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

  • To give the ID the same value as the label use use_label=True e.g element.create(use_label=True)

Examples

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

Returns the element resource label.

tag(name)

Tag the element.

untag(name)

Remove a tag for the element.

The CObject class

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

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

Methods

fetchall(*args)

Returns every element.

fetchone()

Returns the first element of the collection.

first()

Returns the first element of the collection.

get(*args)

Returns every element.

tag(name)

Tag the collection.

untag(name)

Remove the tag from the collection.

where([constraints, template, query])

Only the element objects whose subject that are matching the constraints will be returned.

fetchall(*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: strings
  • Specify the information to return for the elements within ID, label and 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.

fetchone()

Returns the first element of the collection.

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: strings
  • Specify the information to return for the elements within ID, label and 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.

tag(name)

Tag the collection.

untag(name)

Remove the tag from the collection.

where(constraints=None, template=None, query=None)

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)

Methods

accessibility()

Gets project accessibility.

add_custom_variables(custom_variables[, …])

Adds a custom variable to a specified group

add_user(login[, role])

Adds a user to the project.

aliases()

Returns the aliases for this project.

children([show_names])

Returns the children levels of this element.

collaborators()

Gets collaborator of this project.

create(**params)

Creates the element if it does not exists.

current_arc()

Gets project current archive folder on the server.

datatype()

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

delete([delete_files])

Deletes an element resource.

exists([consistent])

Test whether an element resource exists.

get()

Retrieves the XML document corresponding to this element.

get_custom_variables()

Retrieves custom variables as a dictionary

id()

Returns the element resource id.

insert(**params)

Creates the element if it does not exists.

label()

Returns the element resource label.

last_modified()

Gets the last modified dates for all the project subjects.

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.

set_accessibility([accessibility])

Sets project accessibility.

set_prearchive_code(code)

Sets project prearchive code.

set_quarantine_code(code)

Sets project quarantine code.

set_subfolder_in_current_arc(subfolder)

Changes project current archive subfolder on the server.

tag(name)

Tag the element.

untag(name)

Remove a tag for the element.

user_role(login)

Gets the user level of the user for this project.

users()

Gets all registered users for this project.

experiment

experiments

namespaces

parent

resource

resources

subject

subjects

xpath

accessibility()

Gets project accessibility.

add_custom_variables(custom_variables, allow_data_deletion=False)

Adds a custom variable to a specified group

Parameters
custom_variables: a dictionary
allow_data_deletiona boolean

Examples

>>> variables = {'Subjects' : {'newgroup' : {'foo' : 'string', 'bar' : 'int'}}}
>>> project.add_custom_variables(variables)
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.

aliases()

Returns the aliases for this project.

Returns
List of aliases
collaborators()

Gets collaborator of this project.

current_arc()

Gets project current archive folder on the server.

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

get_custom_variables()

Retrieves custom variables as a dictionary

It has the format {studyProtocol: { setname : {field: type, …}}}

last_modified()

Gets the last modified dates for all the project subjects.

If any element related to a subject changes, experiment, variable, scan, image etc… the date will be changed.

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.

Note

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

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.

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
stringowner | 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.

Methods

attributes()

Files attributes include:

children([show_names])

Returns the children levels of this element.

content()

Gets the file content description.

create(src[, format, content, tags, overwrite])

Uploads a file to XNAT.

datatype()

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

delete()

Deletes the file on the server.

exists([consistent])

Test whether an element resource exists.

format()

Gets the file format.

get([dest, force_default])

Downloads the file.

get_copy([dest])

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

id()

Returns the element resource id.

insert(src[, format, content, tags, overwrite])

Uploads a file to XNAT.

label()

Returns the element resource label.

labels()

Gets the file labels.

last_modified()

Gets the file last-modified date.

put(src[, format, content, tags, overwrite])

Uploads a file to XNAT.

size()

Gets the file size.

tag(name)

Tag the element.

untag(name)

Remove a tag for the element.

namespaces

parent

xpath

attributes()
Files attributes include:
  • URI

  • Name

  • Size in bytes

  • path (relative to the parent resource)

  • file_tags

  • file_format

  • file_content

Returns
dicta dictionnary with the file attributes
content()

Gets the file content description.

create(src, format='U', content='U', tags='U', overwrite=False, **datatypes)

Uploads a file to XNAT.

Parameters
src: string

Location of the local file to upload or the actual content 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’.

overwrite: boolean

Optional parameter to specify if the file should be overwritten. Defaults to False

delete()

Deletes the file on the server.

format()

Gets the file format.

get(dest=None, force_default=False)

Downloads the file.

Parameters
dest: string | None
  • If dest is None, then the user’s Downloads directory is used

    as the default download location.

  • Else the file is downloaded at the requested location.

    Path should include the file name. eg: /path/to/file.txt

force_default: boolean
  • Depricated as of 1.0.0.0

  • Has no effect if the file is downloaded for the first time

  • If the file was previously download with a custom path, calling get() will remember the custom location unless:

    • another custom location is set in dest

    • force_default is set to True and the file will be moved to the cache

Returns
stringthe file location.
get_copy(dest=None)

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

Parameters
dest: string | None
  • file path for the copy

  • if None a copy is created at a default location based on the file URI on the server

Returns
stringthe copy location.
insert(src, format='U', content='U', tags='U', overwrite=False, **datatypes)

Uploads a file to XNAT.

Parameters
src: string

Location of the local file to upload or the actual content 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’.

overwrite: boolean

Optional parameter to specify if the file should be overwritten. Defaults to False

labels()

Gets the file labels.

last_modified()

Gets the file last-modified date.

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

Uploads a file to XNAT.

Parameters
src: string

Location of the local file to upload or the actual content 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’.

overwrite: boolean

Optional parameter to specify if the file should be overwritten. Defaults to False

size()

Gets the file size.

The Attributes class

class pyxnat.core.attributes.EAttrs(eobj)

Accessor class to resource fields.

Help to retrieve the attributes paths relevant to this element::
>>> subject.attrs()
['xnat:subjectData/sharing',
 'xnat:subjectData/sharing/share',
 'xnat:subjectData/resources',
 ...
 'xnat:subjectData/experiments/experiment'
 ]

All paths are not valid but they give an indication of what is available. To retrieve the paths, the corresponding schemas must be downloaded first through the schema management interface in order to be parsed:

>>> interface.manage.schemas.add('xnat.xsd')
>>> interface.manage.schemas.add('myschema/myschema.xsd')

Methods

__call__()

List the attributes paths relevant to this element.

get(path)

Get an attribute value.

mget(paths)

Set multiple attributes at once.

mset(dict_attrs, **kwargs)

Set multiple attributes at once.

set(path, value, **kwargs)

Set an attribute.

get(path)

Get an attribute value.

Note

The value is always returned in a Python string. It must be explicitly casted or transformed if needed.

Parameters
path: string

The xpath of the attribute relative to the element.

Returns
A string containing the value.
mget(paths)

Set multiple attributes at once.

It is more efficient to use this method instead of multiple times the get() method when getting more than one attribute because only a single HTTP call is issued to the server.

Parameters
paths: list

List of attributes’ paths.

Returns
list: ordered list of values (in the order of the
requested paths)
mset(dict_attrs, **kwargs)

Set multiple attributes at once.

It is more efficient to use this method instead of multiple times the set() method when setting more than one attribute because only a single HTTP call is issued to the server.

Parameters
dict_attrs: dict

The dict of key values to set. It follows the same principles as the single set() method.

set(path, value, **kwargs)

Set an attribute.

Parameters
path: string

The xpath of the attribute relative to the element.

value: string

The attribute’s value. Note that the python type is always a string but the content of the value must match what is defined in the schema.

e.g. an element defined as a float in the schema must be given a string containing a number, a valid date must follow the ISO 8601 which is the standard representation for dates and times established by the W3C.

The Provenance class

class pyxnat.core.provenance.Provenance(eobject)

Class to annotate processed data with provenance information. The following parameters are available:

  • program

  • program_version

  • program_arguments

  • timestamp

  • cvs

  • user

  • machine

  • platform

  • platform_version

  • compiler

  • compiler_version

Examples

>>> prov = {'program':'young',
            'timestamp':'2011-03-01T12:01:01.897987',
            'user':'angus',
            'machine':'war',
            'platform':'linux',
            }
>>> element.provenance.set(prov)
>>> element.provenance.get()
>>> element.delete()

Methods

delete()

Removes the provenance attached to this object.

get()

Gets all the provenance information for that object.

set(process_steps[, overwrite])

Set provenance information for the data within this element.

delete()

Removes the provenance attached to this object.

Warning

doesn’t work because of a bug with the allowDataDeletion flag in XNAT

get()

Gets all the provenance information for that object.

Returns
A list of dicts.
set(process_steps, overwrite=False)

Set provenance information for the data within this element.

Note

If some required parameters are not provided, theses parameters will be extracted from the current machine and set automatically. Those parameters are:

  • machine

  • platform

  • timestamp

  • user

Warning

overwrite option doesn’t work because of a bug with the allowDataDeletion flag in XNAT

Parameters
process_steps: list or dict

dict or list of dicts to define the processing steps of the data. The minimum set of information to give is: program, timestamp, user, machine and platform. More keywords in the class documentation.

overwrite: boolean

If False the process_steps are added to the existing ones. Else the processing steps overwrite any existing provenance.

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.manage.users()
['list_of_users']
>>> interface.manage.users.firstname('nosetests')
'nose'

Methods

__call__()

Returns the list of all registered users on the server.

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.

resources()

Returns the resources of the user.

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.

resources()

Returns the resources of the user.

The Inspector class

class pyxnat.core.help.Inspector(interface)

Database introspection interface.

Methods

__call__()

Call self as a function.

assessor_types()

Returns the datatypes used at the assessor level in this database.

assessor_values(experiment_type[, project])

Look for the values at the assessor level for a given experiment type in the database.

datatypes([pattern, fields_pattern])

Discovers the datatypes and datafields of the database.

experiment_types()

Returns the datatypes used at the experiment level in this database.

experiment_values(datatype[, project])

Look for the values a the experiment level for a given datatype in the database.

field_values(field_name)

Look for the values a specific datafield takes in the database.

project_values()

Look for the values a the project level in the database.

reconstruction_types()

Returns the datatypes used at the reconstruction level in this database.

reconstruction_values(experiment_type[, project])

Look for the values at the reconstruction level for a given experiment type in the database.

scan_types()

Returns the datatypes used at the scan level in this database.

scan_values(experiment_type[, project])

Look for the values at the scan level for a given experiment type in the database.

set_autolearn([auto, tick])

Once in a while queries will persist additional information on the server.

structure()

Displays the keywords structure used in XNAT REST API.

subject_values([project])

Look for the values a the subject level in the database.

assessor_types()

Returns the datatypes used at the assessor level in this database.

assessor_values(experiment_type, project=None)

Look for the values at the assessor level for a given experiment type in the database.

Note

The experiment type should be one of Inspector.experiment_types()

Warning

Depending on the number of elements the operation may take a while.

Parameters
datatype: string

An experiment type. eg: xnat:mrsessiondata

project: string

Optional. Restrict operation to a project.

datatypes(pattern='*', fields_pattern=None)

Discovers the datatypes and datafields of the database.

Parameters
pattern: string

Pattern for the datatype. May include wildcards.

fields_pattern: string
  • Pattern for the datafields – may include wildcards.

  • If specified, datafields will be returned instead of datatypes.

Returns
listdatatypes or datafields depending on the argument usage.
experiment_types()

Returns the datatypes used at the experiment level in this database.

experiment_values(datatype, project=None)

Look for the values a the experiment level for a given datatype in the database.

Note

The datatype should be one of Inspector.experiment_types()

Parameters
datatype: string

An experiment type. eg: xnat:mrsessiondata

project: string

Optional. Restrict operation to a project.

field_values(field_name)

Look for the values a specific datafield takes in the database.

project_values()

Look for the values a the project level in the database.

Note

Is equivalent to interface.select.projects().get()

reconstruction_types()

Returns the datatypes used at the reconstruction level in this database.

reconstruction_values(experiment_type, project=None)

Look for the values at the reconstruction level for a given experiment type in the database.

Note

The experiment type should be one of Inspector.experiment_types()

Warning

Depending on the number of elements the operation may take a while.

Parameters
datatype: string

An experiment type.

project: string

Optional. Restrict operation to a project.

scan_types()

Returns the datatypes used at the scan level in this database.

scan_values(experiment_type, project=None)

Look for the values at the scan level for a given experiment type in the database.

Note

The experiment type should be one of Inspector.experiment_types()

Warning

Depending on the number of elements the operation may take a while.

Parameters
datatype: string

An experiment type.

project: string

Optional. Restrict operation to a project.

set_autolearn(auto=None, tick=None)

Once in a while queries will persist additional information on the server. This information is available through the following methods of this class:

  • experiment_types

  • assessor_types

  • scan_types

  • reconstruction_types

It is also transparently used in insert operations.

Parameters
auto: boolean

True to enable auto learn. False to disable.

tick: int

Every ‘tick’ seconds, if a query is issued, additional information will be persisted.

See also

EObject.insert()

structure()

Displays the keywords structure used in XNAT REST API.

subject_values(project=None)

Look for the values a the subject level in the database.

Note

Is equivalent to interface.select(‘//subjects’).get()

The CacheManager class

class pyxnat.core.cache.CacheManager(interface)

Management interface for the cache.

It provides a few methods to::
  • evaluate the size a the cache

  • check if there is space left on the disk

  • clear the cache

  • define cache usage parameters

Methods

available_disk([path, unit])

Available disk on partition.

clear()

Clears all files tracked by pyxnat.

disk_ready([path, ready_ratio])

Checks the status of the disk.

set_usage([mode, expiration])

Customize cache usage.

size([unit])

Returns the amount of space taken by the cache.

total_disk([path, unit])

Total disk on partition.

used_disk([path, unit])

Used disk on partition.

enable_warnings

available_disk(path=None, unit='bytes')

Available disk on partition. Default location is cache folder.

clear()

Clears all files tracked by pyxnat.

disk_ready(path=None, ready_ratio=90.0)

Checks the status of the disk. Basically if there is enough space left. The default location is cache dir.

set_usage(mode=None, expiration=1.0)

Customize cache usage.

Parameters
mode: string
‘online’ or ‘offline’:
  • online will always query the server to have up to date data.

  • offline will only try to query the server if the data is not cached.

expiration: float

Relevant only to online mode. The cache has an expiration mechanism. If two queries on the same resource are issued under the specified value, the cache will be used and the server will not be requested.

size(unit='bytes')

Returns the amount of space taken by the cache.

Parameters
unit: str

unit in which to return the size can be bytes (default), mega or giga

Returns
size: float
total_disk(path=None, unit='bytes')

Total disk on partition. Default location is cache folder.

used_disk(path=None, unit='bytes')

Used disk on partition. Default location is cache folder.

The SchemaManager class

class pyxnat.core.manage.SchemaManager(interface)

Management interface for XNAT schemas.

The aim is to provide a minimal set of functionalities to parse and look at XNAT schemas.

Methods

__call__()

Call self as a function.

add(url)

Loads an additional schema.

remove(name)

Removes a schema.

add(url)

Loads an additional schema.

Parameters
url: str
url of the schema relative to the server.

e.g. for http://central.xnat.org/schemas/xnat/xnat.xsd give schemas/xnat/xnat.xsd or even only xnat.xsd

remove(name)

Removes a schema.