Use cases of Axon python API

Load Brainvisa

The following lines enable to load Brainvisa without the graphical user interface through a python script:

[1]:
import brainvisa.axon
brainvisa.axon.initializeProcesses()
('Qt backend:', 'PyQt5')
Loading toolbox baby
Loading toolbox bioprocessing
Loading toolbox brainrat
Loading toolbox connectomist
Loading toolbox constellation
Loading toolbox cortical_surface
Loading toolbox data management
Loading toolbox datamind
Loading toolbox disco
Loading toolbox freesurfer
Loading toolbox morphologist
Loading toolbox nuclearimaging
Loading toolbox preclinical_imaging
Loading toolbox structural_analysis
Loading toolbox tms
Loading toolbox tools
Loading toolbox viewers
Loading toolbox My processes
The log file for this session is '/home/dr144257/.brainvisa/brainvisa2.log'
Database /volatile/riviere/brainvisa/build-stable-qt5/share/brainvisa-share-4.5
must be updated because the database file is too old.
Database /volatile/riviere/basetests-3.1.0 must be updated because the database
file is too old.
Database /neurospin/hbp/Users/riviere/archi-sulci must be updated because the
database file is too old.
Database /neurospin/archi-private/Users/Analysis/2-Morphologist/DataBaseArchi
must be updated because the database file is too old.
/usr/lib/nvidia-340/libGL.so.340.101
OpenGL lib already loaded. Using Xvfb will not be possible.
The current Xvfb does not have a GLX extension. Aborting it.
Headless Anatomist running in normal (non-headless) mode
global modules: /volatile/riviere/brainvisa/build-stable-qt5/share/anatomist-4.5/python_plugins
home   modules: /home/dr144257/.anatomist/python_plugins
loading module selection
loading module profilewindow
loading module gradientpalette
loading module bundles_split_by_cortical_regions
loading module volumepalettes
loading module histogram
loading module foldsplit
loading module bundles_small_brains
loading module modelGraphs
loading module bsa_proba
loading module meshsplit
loading module palettecontrols
loading module paletteViewer
loading module anacontrolmenu
all python modules loaded
Anatomist started.
launchFreesurferCommand
freesurfer_home_path: /i2bm/local/freesurfer
running command: /volatile/riviere/brainvisa/build-stable-qt5/scripts/runFreesurferCommand.sh /i2bm/local/freesurfer/FreeSurferEnv.sh mri_convert -h
launchFreesurferCommand OK
exec: /volatile/riviere/brainvisa/build-stable-qt5/brainvisa/toolboxes/morphologist/startup.py
/i2bm/local/fsl/data: parse directories and insert items
/i2bm/local/fsl/data: 4 files are stored as 4 DiskItems in 0 seconds
/i2bm/local/spm12-standalone/spm12_mcr/spm12: parse directories and insert items
/i2bm/local/spm12-standalone/spm12_mcr/spm12: 8 files are stored as 8 DiskItems
in 0 seconds

Call a process

The module brainvisa.processes manages the processes, pipelines and their execution.

The object brainvisa.processes.ExecutionContext enables to start a Brainvisa process using the method brainvisa.processes.ExecutionContext.runProcess. When Brainvisa is loaded, a default execution context exists and is returned by the function brainvisa.processes.defaultContext

The following example will run the process Threshold on an image:

[2]:
import brainvisa.processes
context = brainvisa.processes.defaultContext()

# Just to get an example data for running the process
from brainvisa.configuration.neuroConfig import getSharePath, bvShareDirectory
import os
example_data = os.path.join(getSharePath(), bvShareDirectory, "anatomical_templates", "MNI152_T1_1mm_brain_mask.nii")
# creating a temporary file for the output
output_data = context.temporary("NIFTI-1 image")

context.runProcess("threshold", image_input=example_data, image_output=output_data, threshold1=100)

Traitement Seuillage démarré sur 2017/07/06 14:44
Traitement Seuillage terminé sur 2017/07/06 14:44 (1 seconds)

Select a step in a pipeline

In a pipeline, some steps may be optional and can be selected or unselected for execution. It is possible to select or unselect a step of a pipeline before running it through a python script. A pipeline is a process that have execution nodes. The method brainvisa.processes.Process.executionNode returns an brainvisa.processes.ExecutionNode. The execution node of the pipeline contains child nodes, the name of these nodes can be obtained with the method brainvisa.processes.ExecutionNode.childrenNames. To get a specific child node, the method brainvisa.processes.ExecutionNode.child can be used.

The following examples gets an instance of the convertOldDatabase pipeline and unselects all its steps:

[4]:
pipeline=brainvisa.processes.getProcessInstance("convertOldDatabase")
nodes=pipeline.executionNode()

nodes.childrenNames()
assert(nodes.childrenNames() == ['ConvertDatabase', 'CheckDatabase', 'CleanDatabase'])
nodes.child("ConvertDatabase").setSelected(0)
assert(not nodes.child("ConvertDatabase").isSelected())
nodes.child("CheckDatabase").setSelected(0)
nodes.child("CleanDatabase").setSelected(0)

The process instance can be given as a parameter for the brainvisa.processes.ExecutionContext.runProcess method instead of the process id.

Query a database

At Brainvisa startup, an internal database and the database selected in the user’s preferences are loaded. The list of databases (brainvisa.data.sqlFSODatabase.SQLDatabases) is stored in the global variable brainvisa.data.neuroHierarchy.databases. Each database is an instance of the class brainvisa.data.sqlFSODatabase.SQLDatabase. Several methods enable to query a database or a list of databases. The results of queries are generally brainvisa.data.neuroDiskItems.DiskItem objects. A DiskItem represents data stored in files and indexed in a database with additionnal information.

In the following example, a DiskItem is searched in the databases by filename:

[9]:
from brainvisa.data.neuroHierarchy import databases
from brainvisa.data.neuroDiskItems import DiskItem

item = databases.getDiskItemFromFileName(example_data)
assert(isinstance(item, DiskItem))
assert(str(item.type) == 'anatomical Mask Template')
assert(str(item.format) == 'NIFTI-1 image')

Here is a request for all DiskItems of type “anatomical Template” with the value of Size attribute being “1 mm”:

[20]:
items = databases.findDiskItems({"_type" : "anatomical Template", "Size": "1 mm"})
assert(str(items).startswith('<generator object findDiskItems'))
model_filename = items.next().fileName()
assert(model_filename.startswith(os.path.join(getSharePath(), bvShareDirectory, "anatomical_templates")))

The object brainvisa.data.readdiskitem.ReadDiskItem enables to search for an existing DiskItem in the databases using the method ReadDiskItem.findValue. If the request is not precise enought and several DiskItems match, the method returns None.

[36]:
from brainvisa.data.readdiskitem import ReadDiskItem
from brainvisa.configuration import neuroConfig
rd = ReadDiskItem("anatomical Template", "Aims readable volume formats")
template = rd.findValue({"Size" : "2 mm"})
assert(template is None)
template = rd.findValue({"Size" : "2 mm", "skull_stripped": "no",
                         "_database": neuroConfig.dataPath[0].directory})
assert(template is not None)
assert(template.fileName().startswith(os.path.join(getSharePath(), bvShareDirectory, "anatomical_templates")))

The object brainvisa.data.writediskitem.WriteDiskItem enables to create new DiskItems to write output data according to Brainvisa hierarchy of directories.

[39]:
from brainvisa.data.writediskitem import WriteDiskItem
wd = WriteDiskItem("Raw T1 MRI", "NIFTI-1 image")
item = wd.findValue({"protocol" : 'test', "subject" : "mysubject"})
# nothe that item is not None only if one (and only one) user database has been setup.

Quit Brainvisa

The function brainvisa.axon.processes.cleanup should be called at the end of the script to quit properly Brainvisa.

[40]:
brainvisa.axon.cleanup()