### Install XNAT from source Source: https://xnat.readthedocs.io/en/stable/static/manual.html Use this command to install xnat directly from its source code. ```bash python setup.py install ``` -------------------------------- ### Install XNATpy using pip Source: https://xnat.readthedocs.io/en/stable/static/introduction.html Use this command to install the XNATpy library via pip. Ensure you have pip installed and updated. ```bash pip install xnat ``` -------------------------------- ### List Projects with Hostname and User Source: https://xnat.readthedocs.io/en/stable/static/cli.html Example of listing projects with explicit hostname and user arguments. This is useful for single, specific calls. ```bash $ xnat list project --hostname https://xnat.example.com --user username ``` -------------------------------- ### Install XNATpy using conda Source: https://xnat.readthedocs.io/en/stable/static/introduction.html Use this command to install the XNATpy library via conda, specifically from the conda-forge channel. This is an alternative to pip installation. ```bash conda install -c conda-forge xnat ``` -------------------------------- ### Make GET Request to XNAT Source: https://xnat.readthedocs.io/en/stable/static/manual.html Use the `get` method for low-level REST requests. It utilizes the established session for authentication and error checking. The full server URI is not required. ```python >>> connection.get('/data/projects') # Note that 'https://xnat.example.com/data/projects' would also work but is not needed # as the connection already knows the server connected to ``` -------------------------------- ### Perform GET REST Request Source: https://xnat.readthedocs.io/en/stable/static/cli.html Execute a GET request to a specific path on the XNAT server. This command allows for query parameters and custom headers to be specified. The PATH argument is required. ```bash xnat rest get [OPTIONS] PATH ``` -------------------------------- ### List Available Classes in XNAT Connection Source: https://xnat.readthedocs.io/en/stable/static/manual.html Use `dir()` on `connection.classes` to get a list of all known XNAT classes available through the connection. ```python >>> dir(connection.classes) ``` -------------------------------- ### Tabulate Query Results with Pandas Source: https://xnat.readthedocs.io/en/stable/static/manual.html Use the `tabulate_pandas()` method to get query results as a pandas DataFrame. Requires pandas to be installed. ```python >>> query.tabulate_pandas() subject_label subjectid insert_user insert_date ... dob educ ses quarantine_status 0 Brain-0001 BMIAXNAT34_S00001 ibocharov 2022-11-15 22:26:38.676 ... NaN NaN NaN active 1 Brain-0002 BMIAXNAT34_S00002 ibocharov 2022-11-15 22:42:20.324 ... NaN NaN NaN active [2 rows x 12 columns] ``` -------------------------------- ### Connect to XNAT and query projects Source: https://xnat.readthedocs.io/en/stable/static/introduction.html This snippet demonstrates how to establish a connection to an XNAT server using provided credentials, access project data, and then disconnect. Ensure you replace placeholder credentials with your actual XNAT login details. ```python >>> import xnat >>> session = xnat.connect('https://central.xnat.org', user="", password="") >>> session.projects['Sample_DICOM'].subjects >>> session.disconnect() ``` -------------------------------- ### Create .netrc file for credentials Source: https://xnat.readthedocs.io/en/stable/static/manual.html Configures authentication for XNAT by creating a .netrc file. Ensure file permissions are restricted to the owner. ```bash echo "machine images.xnat.org > login USERNAME > password PASSWORD" > ~/.netrc chmod 600 ~/.netrc ``` -------------------------------- ### xnat rest get Source: https://xnat.readthedocs.io/en/stable/static/cli.html Perform a GET request to the target XNAT. ```APIDOC ## xnat rest get ### Description Perform GET request to the target XNAT. ### Command xnat rest get [OPTIONS] PATH ### Options - **--query ** (string) - The values to be added to the query string in the URI. - **--headers ** (string) - HTTP headers to include. - **--host ** (string) - **Required** URL of the XNAT host to connect to, if not given will check XNAT_HOST or XNAT_HOST environment variables. - **-u, --user ** (string) - Username to connect to XNAT with. - **-n, --netrc ** (string) - .netrc file location, if not given will check NETRC environment variable or default to ~/.netrc. - **--jsession ** (string) - JSESSION value for re-using a previously opened login session. - **--timeout ** (integer) - Timeout for requests made by this command in ms. - **--loglevel ** (string) - Logging verbosity level. Options: DEBUG | INFO | WARNING | ERROR | CRITICAL. ### Arguments - **PATH** (string) - Required argument. ### Environment variables - XNATPY_HOST, XNAT_HOST: Provide a default for `--host` - XNATPY_USER, XNAT_USER: Provide a default for `--user` - XNATPY_JSESSION: Provide a default for `--jsession` - XNATPY_TIMEOUT: Provide a default for `--timeout` - XNATPY_LOGLEVEL: Provide a default for `--loglevel` ``` -------------------------------- ### `xnat` Package - `connect()` Source: https://xnat.readthedocs.io/en/stable/index.html Establishes a connection to an XNAT server using the `xnat` Python package. ```APIDOC ## `xnat` Package - `connect()` ### Description The `connect()` function is used to establish a connection to an XNAT server. ### Method `connect(host, port=None, user=None, password=None, experiment=None, project=None, verify=True, **kwargs)` ### Parameters * **host** (str) - The hostname or IP address of the XNAT server. * **port** (int, optional) - The port number for the XNAT server. Defaults to None. * **user** (str, optional) - The username for authentication. Defaults to None. * **password** (str, optional) - The password for authentication. Defaults to None. * **experiment** (str, optional) - The default experiment to connect to. Defaults to None. * **project** (str, optional) - The default project to connect to. Defaults to None. * **verify** (bool, optional) - Whether to verify SSL certificates. Defaults to True. * **kwargs** - Additional keyword arguments. ### Returns A session object representing the connection to the XNAT server. ``` -------------------------------- ### Exploring your XNAT server Source: https://xnat.readthedocs.io/en/stable/static/manual.html Demonstrates how to explore data on an XNAT server once a session is established. The structure of XNAT data is mirrored as Python objects, allowing access to listings of projects, subjects, and experiments. ```APIDOC ## Exploring your xnat server# When a session is established, it is fairly easy to explore the data on the XNAT server. The data structure of XNAT is mimicked as Python objects. The connection gives access to a listing of all projects, subjects, and experiments on the server. ```python >>> import xnat >>> session = xnat.connect('https://images.xnat.org', user='admin', password='admin') >>> session.projects > ``` The XNATListing is a special type of mapping in which you can access elements by a primary key (usually the _ID_ or _Accession #_) and a secondary key (e.g. the label for a subject or experiment). Selection can be performed the same as a Python dict: ```python >>> sandbox_project = session.projects["sandbox"] >>> sandbox_project.subjects > ``` You can browse the following levels on the XNAT server: projects, subjects, experiments, scans, resources, files. Also under experiments you have assessors which again can contain resources and files. This all following the same structure as XNAT. ``` -------------------------------- ### Download XNAT Project Source: https://xnat.readthedocs.io/en/stable/static/cli.html This command downloads an entire XNAT project to a specified local directory. Ensure you provide the project name and the target directory path. ```bash xnat download project [OPTIONS] PROJECT TARGETDIR ``` -------------------------------- ### get Source: https://xnat.readthedocs.io/en/stable/xnat.html Retrieve data from a given REST path. ```APIDOC ## `get` ### Description Retrieve data from a given REST path. This method queries XNAT REST paths. ### Method GET ### Endpoint [Path specified in the `path` parameter] ### Parameters * **path** (str) - The REST path to retrieve data from (e.g., "/data/archive/projects"). * **headers** (Dict[str, str] | None) - Optional HTTP headers to include in the request. * **query** (Dict[str, str] | None) - Optional query parameters to add to the URI. * **timeout** (float | Tuple[float, float] | None) - Timeout in seconds for the request, or a tuple of (connection timeout, read timeout). ### Returns The response from the GET request. ``` -------------------------------- ### AbstractResource Methods Source: https://xnat.readthedocs.io/en/stable/xnat.html Provides methods for downloading and uploading files and directories associated with an XNAT resource. ```APIDOC ## AbstractResource ### Description Represents an abstract resource within XNAT, providing core functionalities for data management. ### Methods #### `download(path, verbose=True)` Downloads a resource to a specified path. - **path** (str): The local path to download the resource to. - **verbose** (bool, optional): Whether to show download progress. Defaults to True. #### `download_dir(target_dir, verbose=True, flatten_dirs=False)` Downloads the entire resource and unpacks it into a given directory. - **target_dir** (str): The directory to unpack the downloaded resource into. - **verbose** (bool, optional): Whether to show download progress. Defaults to True. - **flatten_dirs** (bool, optional): Whether to flatten the directory structure. Defaults to False. #### `refresh_catalog()` Calls the refresh catalog operation on this object. #### `upload(path, remotepath, overwrite=False, extract=False, file_content=None, file_format=None, file_tags=None, **kwargs)` Uploads a file as an XNAT resource. - **path** (str | Path): The path to the file to upload. - **remotepath** (str): The remote path to which to upload. - **overwrite** (bool, optional): Flag to force overwriting of files. Defaults to False. - **extract** (bool, optional): Extract the files on the XNAT server. Defaults to False. - **file_content** (str | None, optional): Set the Content of the file on XNAT. - **file_format** (str | None, optional): Set the format of the file on XNAT. - **file_tags** (str | None, optional): Set the tags of the file on XNAT. #### `upload_data(data, remotepath, overwrite=False, extract=False, file_content=None, file_format=None, file_tags=None, **kwargs)` Uploads data as an XNAT resource. - **data** (str | bytes | IO): The data to upload, either a string, bytes, or an IO object. - **remotepath** (str): The remote path to which to upload. - **overwrite** (bool, optional): Flag to force overwriting of files. Defaults to False. - **extract** (bool, optional): Extract the files on the XNAT server. Defaults to False. - **file_content** (str | None, optional): Set the Content of the file on XNAT. - **file_format** (str | None, optional): Set the format of the file on XNAT. - **file_tags** (str | None, optional): Set the tags of the file on XNAT. #### `upload_dir(directory, overwrite=False, method='tgz_file', **kwargs)` Uploads a directory to an XNAT resource. - **directory** (str | Path): The directory to upload. - **overwrite** (bool, optional): Flag to force overwriting of files. Defaults to False. - **method** (str, optional): The method to use for uploading the directory. Options include 'per_file', 'tar_memory', 'tgz_memory', 'tar_file', 'tgz_file'. Defaults to 'tgz_file'. ``` -------------------------------- ### BaseXNATSession.get Source: https://xnat.readthedocs.io/en/stable/xnat.html Retrieves data from XNAT using a GET request. ```APIDOC ## BaseXNATSession.get ### Description Retrieves data from a specified XNAT resource using an HTTP GET request. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Method GET ### Endpoint This method is used to interact with XNAT resources via their URIs. ### Request Example ```python data = session.get(uri='/projects/project_id') ``` ### Response #### Success Response (200) Returns the data retrieved from the specified URI. #### Response Example None ``` -------------------------------- ### Users Class Source: https://xnat.readthedocs.io/en/stable/xnat.html Provides a listing of all users on the connected XNAT installation. Supports caching and clearing the cache. ```APIDOC ## Class: Users ### Description Listing of the users on the connected XNAT installation. ### Methods - `clearcache()`: Clears the cache for the users listing. ### Properties - `_caching` (bool): Indicates if caching is enabled. - `_data`: Raw data for the users listing. - `_xnat_session`: The XNAT session object. ``` -------------------------------- ### Connect to XNAT with credentials Source: https://xnat.readthedocs.io/en/stable/static/manual.html Connects to an XNAT server providing user and password directly. Be cautious as credentials may be exposed. ```python >>> session = xnat.connect('http://my.xnat.server', user='admin', password='secret') ``` -------------------------------- ### Connect to XNAT Server Source: https://xnat.readthedocs.io/en/stable/static/manual.html Establish a connection to an XNAT server using the `xnat.connect` function, providing the server URL and user credentials. This is the first step to interacting with XNAT data. ```python >>> import xnat >>> session = xnat.connect('https://images.xnat.org', user='admin', password='admin') >>> session.projects > ``` -------------------------------- ### get_json Source: https://xnat.readthedocs.io/en/stable/xnat.html A helper function that performs a GET request, sets the format to JSON, and parses the result as JSON. ```APIDOC ## get_json ### Description Helper function that perform a GET, but sets the format to JSON and parses the result as JSON. ### Parameters * **uri** (str) - The path of the uri to retrieve (e.g. “/data/archive/projects”). * **query** (Dict[str, str] | None, optional) - The values to be added to the query string in the uri. * **accepted_status** (Container[int] | None, optional) - A list of the valid values for the return code, default [200]. ### Returns None | int | str | bool | List[Any] | Dict[str, Any] ``` -------------------------------- ### get Source: https://xnat.readthedocs.io/en/stable/xnat.html Retrieves the content of a given REST directory with specified format, query parameters, accepted status codes, timeout, and headers. ```APIDOC ## get ### Description Retrieve the content of a given REST directory. ### Parameters * **path** (str) - The path of the uri to retrieve (e.g. “/data/archive/projects”). * **format** (str | None, optional) - The format of the request, this will add the format= to the query string. * **query** (Dict[str, str] | None, optional) - The values to be added to the query string in the uri. * **accepted_status** (Container[int] | None, optional) - A list of the valid values for the return code, default [200]. * **timeout** (float | Tuple[float, float] | None, optional) - Timeout in seconds, float or (connection timeout, read timeout). * **headers** (Dict[str, str] | None, optional) - The HTTP headers to include. ### Returns The requests response. ``` -------------------------------- ### `session` Module - `BaseXNATSession` Methods Source: https://xnat.readthedocs.io/en/stable/index.html Methods available on the `BaseXNATSession` object for interacting with XNAT. ```APIDOC ## `session` Module - `BaseXNATSession` Methods The `BaseXNATSession` class provides a comprehensive set of methods for interacting with an XNAT server. ### Core Methods: * **`access_levels`**: Accesses the available access levels. * **`batch_download()`**: Initiates a batch download of data. * **`clearcache()`**: Clears the session cache. * **`create_object()`**: Creates a new object in XNAT. * **`delete()`**: Deletes an object from XNAT. * **`download()`**: Downloads a specific object or data. * **`download_stream()`**: Downloads data as a stream. * **`download_zip()`**: Downloads data as a ZIP archive. * **`experiments`**: Property to access experiments. * **`get()`**: Performs an HTTP GET request. * **`get_json()`**: Retrieves JSON data from an endpoint. * **`head()`**: Performs an HTTP HEAD request. * **`interface`**: Property to access the session interface. * **`plugins`**: Property to access available plugins. * **`post()`**: Performs an HTTP POST request. * **`prearchive`**: Property to access prearchive data. * **`projects`**: Property to access projects. * **`put()`**: Performs an HTTP PUT request. * **`scan_types`**: Property to access available scan types. * **`scanners`**: Property to access scanner information. * **`search()`**: Executes a search query on XNAT. * **`services`**: Property to access available services. ``` -------------------------------- ### Create _netrc file on Windows Source: https://xnat.readthedocs.io/en/stable/static/manual.html Sets up credential storage on Windows using the _netrc file in the user profile directory. ```batch (echo machine images.xnat.org & echo login USERNAME & echo password PASSWORD) > %userprofile%/_netrc ``` -------------------------------- ### Download XNAT Experiments Source: https://xnat.readthedocs.io/en/stable/static/cli.html Use this command to download specific experiments from an XNAT project to a local directory. It supports specifying the XNAT host, user credentials, and other connection options. ```bash xnat download experiments [OPTIONS] PROJECT [EXPERIMENTS]... TARGETDIR ``` -------------------------------- ### Get External URI for XNAT Object Source: https://xnat.readthedocs.io/en/stable/static/manual.html Retrieve the full external URL for an XNAT object. You can customize the query string and scheme. ```python >>> experiment_01.external_uri() 'https://xnat.server.com/data/archive/projects/project/subjects/XNAT_S09618/experiments/XNAT_E36346' ``` ```python >>> experiment_01.external_uri(scheme='test', query={'hello': 'world'}) 'test://xnat.server.com/data/archive/projects/project/subjects/XNAT_S09618/experiments/XNAT_E36346?hello=world' ``` -------------------------------- ### SubjectData.download_dir Source: https://xnat.readthedocs.io/en/stable/xnat.html Downloads the entire subject and unpacks it in a given directory. It creates a directory structure following $target_dir/{subject.label}/{experiment.label} and unzips experiment zips as given by XNAT into that. If the $target_dir/{subject.label} does not exist, it will be created. ```APIDOC ## SubjectData.download_dir ### Description Downloads the entire subject and unpacks it in a given directory. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Method None (This is a method call on an object) ### Endpoint None (This is a method call on an object) ### Request Example ```python subject_data.download_dir(target_dir='/path/to/download', verbose=True, progress_callback=my_callback_function) ``` ### Response #### Success Response (None) This method does not return a value, but performs a file operation. #### Response Example None ``` -------------------------------- ### Clone XNAT Python Client Source Code Source: https://xnat.readthedocs.io/en/stable/index.html Get the source code for the XNAT Python client by cloning the GitLab repository. ```bash git clone https://gitlab.com/radiology/infrastructure/xnatpy ``` -------------------------------- ### Create an Experiment Object from URI Source: https://xnat.readthedocs.io/en/stable/static/manual.html Instantiate an experiment object using its URI. This allows direct access to the object's properties and methods. ```python experiment_object = connection.create_object('/data/projects/$PROJECT_ID/experiments/$EXPERIMENT_ID') ``` -------------------------------- ### XNAT Download Batch Options Source: https://xnat.readthedocs.io/en/stable/static/cli.html Illustrates the various options available for the 'xnat download batch' command, including filtering by project, experiment, subject, scan, and resource. ```bash --project Filter for the project names --experiment Filter for the experiment labels --subject Filter for the subject labels --scan Filter for the scan types --resource Filter for the resource labels --level What resource level to search on Options: MappingLevel.CONNECTION | MappingLevel.PROJECT | MappingLevel.PROJECT_RESOURCE | MappingLevel.SUBJECT | MappingLevel.SUBJECT_RESOURCE | MappingLevel.EXPERIMENT | MappingLevel.EXPERIMENT_RESOURCE | MappingLevel.SCAN | MappingLevel.SCAN_RESOURCE --regex# Flag to switch from fnmatch to regular expressions --host **Required** URL of the XNAT host to connect to, if not given will check XNAT_HOST or XNATPY_HOST environment variables -u, --user Username to connect to XNAT with. -n, --netrc .netrc file location, if not given will check NETRC environment variable or default to ~/.netrc --jsession JSESSION value for re-using a previously opened login session --timeout Timeout for requests made by this command in ms. --loglevel Logging verbosity level. Options: DEBUG | INFO | WARNING | ERROR | CRITICAL Arguments TARGETDIR# Required argument Environment variables ['XNATPY_HOST', 'XNAT_HOST'] > Provide a default for `--host` ['XNATPY_USER', 'XNAT_USER'] > Provide a default for `--user` XNATPY_JSESSION > Provide a default for `--jsession` XNATPY_TIMEOUT > Provide a default for `--timeout` XNATPY_LOGLEVEL > Provide a default for `--loglevel` ``` -------------------------------- ### Perform REST Requests Source: https://xnat.readthedocs.io/en/stable/static/cli.html This is the main command for interacting with the XNAT REST API. It serves as a base for specific HTTP methods like DELETE and GET. ```bash xnat rest [OPTIONS] COMMAND [ARGS]... ``` -------------------------------- ### Get and Unpack JSON Data from XNAT Source: https://xnat.readthedocs.io/en/stable/static/manual.html The `get_json` method is a helper for retrieving and automatically unpacking JSON responses from XNAT. It simplifies fetching structured data. ```python >>> connection.get_json('/data/project/PROJECT_ID') {'items': [{'children': ..... }]} ``` -------------------------------- ### Connect to XNAT Server (Context Manager) Source: https://xnat.readthedocs.io/en/stable/xnat.html Use this snippet to establish a connection to an XNAT server using a context manager, ensuring the connection is automatically closed. Requires the 'xnat' package to be imported. ```python >>> import xnat >>> with xnat.connect('https://central.xnat.org') as connection: ... subjects = connection.projects['Sample_DICOM'].subjects ... print('Subjects in the SampleDICOM project: {}'.format(subjects)) ``` -------------------------------- ### Connect to XNAT server Source: https://xnat.readthedocs.io/en/stable/static/manual.html Establishes a connection to an XNAT server. The session object holds login information and server details. ```python >>> import xnat >>> session = xnat.connect('https://central.xnat.org') ``` -------------------------------- ### Query Subjects with Multiple Filters Source: https://xnat.readthedocs.io/en/stable/static/manual.html Combine multiple constraints in a single filter call to narrow down search results. This example filters subjects by project and a like pattern on their label. ```python >>> SubjectData.query().filter(SubjectData.project == 'sandbox', SubjectData.label.like('Brain*')).all() [, ] ``` -------------------------------- ### Low-level REST Directives Source: https://xnat.readthedocs.io/en/stable/static/manual.html Provides direct access to default REST verbs (GET, HEAD, PUT, POST, DELETE) through session methods. These methods accept a partial URI and return a requests response, leveraging the established xnatpy session for authentication and error checking. ```APIDOC ## Low level REST directives Though xnatpy is designed to offer a high level pythonic interface, it also easily exposes all default REST verbs using the following functions: * `xnat.session.BaseXNATSession.get()` * `xnat.session.BaseXNATSession.head()` * `xnat.session.BaseXNATSession.put()` * `xnat.session.BaseXNATSession.post()` * `xnat.session.BaseXNATSession.delete()` These methods take a (partial) uri and return a requests response. However they do make use of the session established by xnatpy, so user auth and default error checking are still in place, for example: ```python >>> connection.get('/data/projects') # Note that 'https://xnat.example.com/data/projects' would also work but is not needed # as the connection already knows the server connected to ``` These methods also accept arguments for query strings and data (for `put` and `post`). The details can be found in the documentation of the separate methods. There is also a useful helper method that gets and unpacks json data `xnat.session.BaseXNATSession.get_json()`: ```python >>> connection.get_json('/data/project/PROJECT_ID') {'items': [{'children': ..... }]} ``` Finally there are also methods for data upload and download: * `xnat.session.BaseXNATSession.download()` * `xnat.session.BaseXNATSession.download_zip()` * `xnat.session.BaseXNATSession.download_stream()` * `xnat.session.BaseXNATSession.upload()` These methods can help you implement arbitrary functionality without limitations. ``` -------------------------------- ### Prearchive Management Source: https://xnat.readthedocs.io/en/stable/static/cli.html Commands for managing the prearchive in XNAT. ```APIDOC ## xnat prearchive ### Description Commands for prearchive management. ### Usage ``` xnat prearchive [OPTIONS] COMMAND [ARGS]... ``` ``` -------------------------------- ### xnat download project Source: https://xnat.readthedocs.io/en/stable/static/cli.html Downloads an entire XNAT project to a specified local directory. Supports various connection and logging configurations. ```APIDOC ## xnat download project ### Description Download XNAT project to the target directory. ### Method CLI Command ### Endpoint xnat download project [OPTIONS] PROJECT TARGETDIR ### Parameters #### Path Parameters - **PROJECT** (string) - Required - The XNAT project identifier. - **TARGETDIR** (string) - Required - The local directory to download the project to. #### Query Parameters - **--host** (string) - Required - URL of the XNAT host. Defaults to XNAT_HOST or XNATPY_HOST environment variables. - **-u, --user** (string) - Username to connect to XNAT. - **-n, --netrc** (string) - Path to the .netrc file. Defaults to NETRC environment variable or ~/.netrc. - **--jsession** (string) - JSESSION value for re-using a previously opened login session. - **--timeout** (integer) - Timeout for requests in milliseconds. - **--loglevel** (string) - Logging verbosity level. Options: DEBUG, INFO, WARNING, ERROR, CRITICAL. ### Environment variables - ['XNATPY_HOST', 'XNAT_HOST']: Provide a default for `--host` - ['XNATPY_USER', 'XNAT_USER']: Provide a default for `--user` - XNATPY_JSESSION: Provide a default for `--jsession` - XNATPY_TIMEOUT: Provide a default for `--timeout` - XNATPY_LOGLEVEL: Provide a default for `--loglevel` ``` -------------------------------- ### ProjectData Methods Source: https://xnat.readthedocs.io/en/stable/xnat.html Provides methods for interacting with Project data, including creating resources and downloading project data. ```APIDOC ## `ProjectData` Class ### Description Represents a Project data object within XNAT. ### Methods #### `create_resource(label, format=None, data_dir=None, method=None)` Creates a new resource associated with the project. #### `download_dir(target_dir, verbose=True, progress_callback=None)` Downloads the entire project and unpacks it in a given directory. Creates a directory structure following $target_dir/{project.name}/{subject.label}/{experiment.label} and unzips the experiment zips as given by XNAT into that. If the $target_dir/{project.name} does not exist, it will be created. **Parameters:** - **target_dir** (str) – directory to create project directory in - **verbose** (bool) – show progress - **progress_callback** (callable, optional) – A callback function to report progress. ``` -------------------------------- ### BaseXNATSession.batch_download Source: https://xnat.readthedocs.io/en/stable/xnat.html Initiates a batch download operation for multiple items from XNAT. ```APIDOC ## BaseXNATSession.batch_download ### Description Performs a batch download of specified resources or data from XNAT. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Method None (This is a method call on an object) ### Endpoint None (This is a method call on an object) ### Request Example ```python session.batch_download(items_to_download, target_dir='/path/to/save') ``` ### Response #### Success Response (None) This method initiates a download process and typically does not return a direct value, but may indicate success or failure through other means. #### Response Example None ``` -------------------------------- ### xnat.connect Source: https://xnat.readthedocs.io/en/stable/xnat.html Establishes a connection to an XNAT server. This function can be used as a context manager or directly. It returns an XNAT session object. ```APIDOC ## `xnat.connect` ### Description Connect to a server and generate the correct classes based on the server's xnat.xsd schema. This function returns an object that can be used as a context operator. It will call disconnect automatically when the context is left. If it is used as a function, then the user should call `.disconnect()` to destroy the session and temporary code file. ### Parameters * **server** (_str_) – uri of the server to connect to (including http:// or https://), leave empty to use the XNATPY_HOST or XNAT_HOST environment variables * **user** (_str_) – username to use, leave empty to use the XNATPY_USER or XNAT_USER environment variables, netrc entry or anonymous login (in that order). * **password** (_str_) – password to use with the username, leave empty when using netrc or the XNATPY_PASS or XNAT_PASS environment variables. If a username is given and no password, there will be a prompt on the console requesting the password. * **verify** (_bool_) – verify the https certificates, if this is false the connection will be encrypted with ssl, but the certificates are not checked. This is potentially dangerous, but required for self-signed certificates. * **netrc_file** (_str_) – alternative location to use for the netrc file (path pointing to a file following the netrc syntax) * **debug** (_bool_) – Set debug information printing on and print extra debug information. This is meant for xnatpy developers and not for normal users. If you want to debug your code using xnatpy, just set the loglevel to DEBUG which will show you all requests being made, but spare you the xnatpy internals. * **extension_types** (_bool_) – Flag to indicate whether or not to build an object model for extension types added by plugins. * **loglevel** (_str_) – Set the level of the logger to desired level * **logger** (_logging.Logger_) – A logger to reuse instead of creating an own logger * **detect_redirect** (_bool_) – Try to detect a redirect (via a 302 response) and short-cut for subsequent requests * **no_parse_model** (_bool_) – Create an XNAT connection without parsing the server data model, this create a connection for which the simple get/head/put/post/delete functions where, but anything requiring the data model will file (e.g. any wrapped classes) * **default_timeout** (_int_) – The default timeout of requests sent by xnatpy, is a 5 minutes per default. * **auth_provider** (_str_) – Set the auth provider to use to log in to XNAT. ### Returns XNAT session object ### Return type XNATSession ### Preferred use ```python >>> import xnat >>> with xnat.connect('https://central.xnat.org') as connection: ... subjects = connection.projects['Sample_DICOM'].subjects ... print('Subjects in the SampleDICOM project: {}'.format(subjects)) Subjects in the SampleDICOM project: , (CENTRAL_S00461, PACE_HF_SUPINE): > ``` ### Alternative use ```python >>> import xnat >>> connection = xnat.connect('https://central.xnat.org') >>> subjects = connection.projects['Sample_DICOM'].subjects >>> print('Subjects in the SampleDICOM project: {}'.format(subjects)) ``` ``` -------------------------------- ### Login to XNAT Source: https://xnat.readthedocs.io/en/stable/static/cli.html Establishes a connection to XNAT and prints the JSESSIONID for use in subsequent calls. The session remains open until it times out. ```APIDOC ## xnat login ### Description Establish a connection to XNAT and print the JSESSIONID so it can be used in sequent calls. The session is purposefully not closed so will live for next commands to use until it will time-out. ### Usage ``` xnat login [OPTIONS] ``` ### Options - `--host `: **Required** URL of the XNAT host to connect to, if not given will check XNAT_HOST or XNATPY_HOST environment variables. - `-u, --user `: Username to connect to XNAT with. - `-n, --netrc `: .netrc file location, if not given will check NETRC environment variable or default to ~/.netrc. - `--jsession `: JSESSION value for re-using a previously opened login session. - `--timeout `: Timeout for requests made by this command in ms. - `--loglevel `: Logging verbosity level. Options: DEBUG | INFO | WARNING | ERROR | CRITICAL. ### Environment variables - `XNATPY_HOST`, `XNAT_HOST`: Provide a default for `--host` - `XNATPY_USER`, `XNAT_USER`: Provide a default for `--user` - `XNATPY_JSESSION`: Provide a default for `--jsession` - `XNATPY_TIMEOUT`: Provide a default for `--timeout` - `XNATPY_LOGLEVEL`: Provide a default for `--loglevel` ``` -------------------------------- ### Import Experiment into XNAT Source: https://xnat.readthedocs.io/en/stable/static/cli.html Use this command to import an experiment from a local folder into XNAT. You can specify the destination project, subject, and experiment details, as well as control quarantine and pipeline triggers. ```bash xnat import experiment [OPTIONS] FOLDER ``` -------------------------------- ### Configure Hostname and Login Session Source: https://xnat.readthedocs.io/en/stable/static/cli.html Set the XNAT hostname and obtain a JSESSION ID for authentication using environment variables and the 'xnat login' command. This allows for session reuse across multiple commands. ```bash $ XNATPY_HOST=https://xnat.example.com $ XNATPY_JSESSION=`xnat login --user username` $ xnat list project $ xnat logout ``` -------------------------------- ### XNATSimpleListing Methods Source: https://xnat.readthedocs.io/en/stable/index.html Methods for the XNATSimpleListing class, a simplified listing for XNAT objects. ```APIDOC ## XNATSimpleListing Methods ### Description Provides a simplified listing for XNAT objects, including insertion and cache management. ### Methods - `clearcache()`: Clears the cache for the simple listing. - `insert(data)`: Inserts new data into the listing. ### Attributes - `data_maps` (dict): Mapped data for the listing. - `fulldata` (dict): The full data of the listing. - `uri` (str): The URI for the listing. - `xnat_session` (XNATSession): The XNAT session object. ``` -------------------------------- ### Map a Function to Scans with Logging Source: https://xnat.readthedocs.io/en/stable/static/manual.html Apply the `get_scan_info` function to all scans within a project, logging results to 'sandbox.yaml'. This demonstrates batch processing. ```python sandbox_project.map(get_scan_info, level='scan', logfile='sandbox.yaml') ``` -------------------------------- ### Execute Search Query and Retrieve Results Source: https://xnat.readthedocs.io/en/stable/static/manual.html Execute a constructed search query using methods like all(), first(), last(), tabulate_csv(), or tabulate_dict(). This demonstrates retrieving all matching objects, the first, the last, and formatted table outputs. ```python >>> query = SubjectData.query().filter((SubjectData.project == 'sandbox') & (SubjectData.label.like('Brain*'))) >>> query.all() [, ] ``` ```python >>> query.first() ``` ```python >>> query.last() ``` ```python >>> query.tabulate_csv() 'subject_label,subjectid,insert_user,insert_date,projects,project,gender,handedness,dob,educ,ses,quarantine_status\nBrain-0001,BMIAXNAT34_S00001,ibocharov,2022-11-15 22:26:38.676,\"\",sandbox,,,,,,active\nBrain-0002,BMIAXNAT34_S00002,ibocharov,2022-11-15 22:42:20.324,\"\",sandbox,,,,,,active\n' ``` ```python >>> query.tabulate_dict() [{'subject_label': 'Brain-0001', 'subjectid': 'BMIAXNAT34_S00001', 'insert_user': 'ibocharov', 'insert_date': '2022-11-15 22:26:38.676', 'projects': ',', 'project': 'sandbox', 'gender': '', 'handedness': '', 'dob': '', 'educ': '', 'ses': '', 'quarantine_status': 'active'}, {'subject_label': 'Brain-0002', 'subjectid': 'BMIAXNAT34_S00002', 'insert_user': 'ibocharov', 'insert_date': '2022-11-15 22:42:20.324', 'projects': ',', 'project': 'sandbox', 'gender': '', 'handedness': '', 'dob': '', 'educ': '', 'ses': '', 'quarantine_status': 'active'}] ``` -------------------------------- ### Connect to XNAT Server (Manual Disconnect) Source: https://xnat.readthedocs.io/en/stable/xnat.html This snippet shows how to connect to an XNAT server and manually disconnect later. Remember to call `.disconnect()` to clean up the session and temporary files. ```python >>> import xnat >>> connection = xnat.connect('https://central.xnat.org') >>> subjects = connection.projects['Sample_DICOM'].subjects >>> print('Subjects in the SampleDICOM project: {}'.format(subjects)) ``` -------------------------------- ### Command-line interface reference Source: https://xnat.readthedocs.io/en/stable/index.html Reference for the XNAT command-line interface (CLI) tools. ```APIDOC ## Command-line interface reference This section details the commands available in the XNAT command-line interface (CLI). ### `xnat` command The `xnat` command is the primary interface for interacting with XNAT via the command line. It supports the following subcommands: * **`download`**: Downloads data from XNAT. * **`import`**: Imports data into XNAT. * **`list`**: Lists various XNAT resources (e.g., projects, experiments). * **`login`**: Authenticates with an XNAT server. * **`logout`**: Logs out from an XNAT server. * **`prearchive`**: Manages prearchive data. * **`rest`**: Executes arbitrary REST API calls. * **`script`**: Runs XNAT scripts. * **`upload`**: Uploads data to XNAT. ``` -------------------------------- ### PrearchiveSession Methods Source: https://xnat.readthedocs.io/en/stable/xnat.html Methods for managing pre-archive sessions. ```APIDOC ## `PrearchiveSession.archive()` ### Description Archives a pre-archive session. ### Method POST ### Endpoint `/prearchive/sessions/{sessionId}/archive` ### Parameters #### Path Parameters - **sessionId** (string) - Required - The ID of the session to archive. ``` ```APIDOC ## `PrearchiveSession.delete()` ### Description Deletes a pre-archive session. ### Method DELETE ### Endpoint `/prearchive/sessions/{sessionId}` ### Parameters #### Path Parameters - **sessionId** (string) - Required - The ID of the session to delete. ``` ```APIDOC ## `PrearchiveSession.download()` ### Description Downloads a pre-archive session. ### Method GET ### Endpoint `/prearchive/sessions/{sessionId}/download` ### Parameters #### Path Parameters - **sessionId** (string) - Required - The ID of the session to download. ``` ```APIDOC ## `PrearchiveSession.move()` ### Description Moves a pre-archive session to a different project. ### Method POST ### Endpoint `/prearchive/sessions/{sessionId}/move` ### Parameters #### Path Parameters - **sessionId** (string) - Required - The ID of the session to move. #### Request Body - **destinationProject** (string) - Required - The name of the destination project. ``` ```APIDOC ## `PrearchiveSession.rebuild()` ### Description Rebuilds a pre-archive session. ### Method POST ### Endpoint `/prearchive/sessions/{sessionId}/rebuild` ### Parameters #### Path Parameters - **sessionId** (string) - Required - The ID of the session to rebuild. ``` -------------------------------- ### BaseXNATSession.url_for Source: https://xnat.readthedocs.io/en/stable/xnat.html Constructs a URL for a specific XNAT resource. ```APIDOC ## BaseXNATSession.url_for ### Description Constructs the full URL for a given XNAT resource URI, including the base URL of the XNAT instance. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Method None (This is a method call on an object) ### Endpoint None (This is a method call on an object) ### Request Example ```python full_url = session.url_for(uri='/projects/project_id') ``` ### Response #### Success Response (None) Returns the complete URL as a string. #### Response Example None ``` -------------------------------- ### experiments Source: https://xnat.readthedocs.io/en/stable/xnat.html Provides a listing of all experiments on the XNAT server. ```APIDOC ## experiments ### Description Listing of all experiments on the XNAT server. ### Returns An `XNATListing` with elements that are subclasses of `ExperimentData`. ``` -------------------------------- ### batch_download Source: https://xnat.readthedocs.io/en/stable/xnat.html Download a batch of data in one go. Will download all data matching a set of filters. The filters are by default applied using fnmatch can using the `use_regex` flag this will be changed to regular expression matching. The level to search on is controlled by the enum `MappingLevel`. ```APIDOC ## `batch_download` ### Description Download a batch of data in one go. Will download all data matching a set of filters. The filters are by default applied using fnmatch can using the `use_regex` flag this will be changed to regular expression matching. The level to search on is controlled by the enum `MappingLevel`. ### Parameters * **target_directory** (str | Path) - Target directory to download in * **project** (str | None) - filter for project names * **subject** (str | None) - filter for subject labels * **experiment** (str | None) - filter for experiment labels * **scan** (str | None) - filter for scan types * **resource** (str | None) - filter for resource labels * **use_regex** (bool) - flag to indicate using regular expression matching * **level** (MappingLevel) - level of the objects to download ### Returns None ``` -------------------------------- ### Connect to XNAT with Shared JSESSION Source: https://xnat.readthedocs.io/en/stable/static/manual.html Establishes a new connection using an existing JSESSION ID. The `cli=True` argument allows the new connection to be closed independently of the original. ```python >>> connection2 = xnat.connect('https://xnat.example.com', jsession=connection.JSESSION, cli=True) ``` ```python >>> connection2.JSESSION '24FA18BFA3DD4EB9C634AD79FE050339' ``` ```python >>> connection2.disconnect() ``` ```python >>> connection.projects[...].subjects ... ``` ```python >>> connection.disconnect ```