Socket implementation

Inheritance diagram of anatomist.socket.api.Anatomist

This module is an implementation of general interface L{anatomist.base}. Anatomist is runned in another process in server mode, it listens for requests on a socket. So application is driven sending commands on the socket.

This is not the default implementation (except in Brainvisa). So, to use it you have to change default implementation before importing anatomist.api.

>>> import anatomist
>>> anatomist.setDefaultImplementation(anatomist.SOCKET)
>>> import anatomist.api as anatomist
>>> a=anatomist.Anatomist()

It is also possible to directely load socket implementation without changing default implementation, for example if you want to use the 2 implementations in the same application :

>>> import anatomist.socket.api as anatomist

This implementation is thread safe so it can be used in multi-threaded applications.

Anatomist class is a Singleton as it inherits from base.Anatomist. But it redefines the __new__ method to enable to force the creation of another instance of Anatomist. Indeed it is possible with socket implementation to start two anatomist processes that listen on two different socket ports. To do this, use the constructor with forceNewInstance parameter :

>>> a=anatomist.Anatomist(forceNewInstance=True)
class anatomist.socket.api.ASocket(anatomistinstance, host, port=None)[source]

Specialized Socket to communicate with anatomist application. It redefines readMessage and processMessage Socket’s methods. It provides a method to send a command and wait the answer.

eventCallbacks

registers methods to call on messages received on the socket (message -> callback)

Type

dict

Parameters
  • host (str) – socket server machine (localhost if it is current machine)

  • port (int) – port that the socket server listens

addEventHandler(eventName, handlerFunction, requestID=None)[source]

Adds a callback function to handle an event. (eventName, requestID) -> [handlerFunction] in eventCallbacks

Parameters
  • eventName (str) – In Anatomist it is generally the name of the command which causes message sending

  • handlerFunction (function) – the callback function to call on receiving that event

  • requestID (int) – an id associated to the event to recognize a specific command

close()[source]

Closes the connection.

delCallbacks(header)[source]

Thread safe delete of callbacks for that header.

Parameters

header (string or tuple) – command name or (command name, requestID)

executeCallbacks(event, params, callbacks, requestID)[source]

When an event is received, corresponding callbacks must be called. Event content is converted in order to contain Anatomist objects instead of simple identifiers. Only a weak reference is taken on objects and windows mentionned in the event because it can be a reference to a deleted object or window in case it is a DeleteObject or a CloseWindow event. So this reference doesn’t prevent the object or window from being deleted.

getCallbacks(header)[source]

Thread safe acces to callbacks methods registered for that header.

Parameters

header (str or tuple) – command name or (command name, requestID)

processMessage(msg, excep=None)[source]

This method is an handler to process recieved messages sent by Anatomist For example when a window is closed into Anatomist, it send a message to tell this window was closed. So, Anatomist can send various messages at anytime and this method knows what to do with thoses messages.

readMessage(timeout=30)[source]

Reads a message from the socket. Reads two lines : header and data parts of the message. the header is the command name, data is the string representation of a dictionary containing the results of that command.

Parameters

timeout (int) – max time to wait before reading the message.

Returns

message – the message received from the socket (header, data).

Return type

tuple (string, string)

removeEventHandler(eventName, handlerFunction=None, requestID=None)[source]

Removes handler function for a specfic event.

Parameters
  • eventName (str) – In Anatomist it is generally the name of the command which causes message sending

  • handlerFunction (function) – the callback function to call on receiving that event

  • requestID (int) – an id associated to the event to recognize a specific command

sendAndWaitAnswer(command, msg, requestID, timeout=100)[source]

Sends a command to Anatomist application and wait for the answer (message to read on the socket). A request id is affected to the command and a callback function is associated to the command with request id. So when a message with correponding header arrives on the socket, the callback function is called and gets the results.

Parameters
  • command (str) – name of the command to send

  • msg (str) – message to send (command + parameters)

  • requestID (int) – an id associated to the event to recognize a specific command

  • timeout (int) – timeout: max time to wait before receiving the answer.

class anatomist.socket.api.Anatomist(*args, **kwargs)[source]

Interface to communicate with an Anatomist Application sending commands on a socket. Anatomist is launched in server mode and listens for commands arriving on a socket.

comm

socket used to communicate with anatomist application.

Type

ASocket

launched

indicates if anatomist application has been correclty launched in server mode

Type

bool

_requestID

counter to generates unique id for requests to anatomist application. It is used to match request and answer.

Type

int

anaServerProcess

anatomist application process

Type

QProcess

centralRef

anatomist’s central referential. First time it is accessed, an id is affected to the central referential.

Type

Referential

mniTemplateRef

template mni referential (used by spm) These two referentials and transformation between them are always loaded in anatomist.

Type

Referential

anatomistExecutable

path to anatomist executable

Type

str

lock

lock for thread safety when accessing the singleton instance

Type

RLock

The __init__ method of Singleton derived class should do nothing. Derived classes must define __singleton_init__() instead of __init__.

class AGraph(anatomistinstance, internalRep=None, *args, **kwargs)[source]

Represents a graph.

Parameters
  • anatomistinstance (Anatomist) – reference to Anatomist object which created this object.

  • internalRep (object) – representation of this object in anatomist application.

createNode(name=None, syntax=None, with_bucket=None, duplicate=True)[source]

Creates a new node with optionally an empty bucket inside and adds it in the graph.

Parameters
  • name (str) – node name. default is RoiArg.

  • syntax (str) – node syntax attribute. default is roi.

  • with_bucket (bool) – if True, creates an empty bucket in the node and returns it with the node. default is None, so the bucket is created but not returned

  • duplicate (bool) – enables duplication of nodes with the same name attribute.

Returns

elements – (the created node, the created bucket) or only the created node if with_bucket is False

Return type

(AObject, AObject)

class AItem(anatomistinstance, internalRep=None, *args, **kwargs)[source]

Base class for representing an object in Anatomist application.

anatomistinstance

reference to Anatomist object which created this object. Useful because some methods defined in AItem objects will need to send a command to Anatomist application.

Type

Anatomist

internalRep

internalRep: representation of this object in anatomist application.

Type

object

Parameters
  • anatomistinstance (Anatomist) – reference to Anatomist object which created this object.

  • internalRep (object) – representation of this object in anatomist application.

getInfo(name_children=0)[source]

Gets information about this object.

Returns

info – information about the object (property -> value)

Return type

dictionary

releaseAppRef()[source]

Release anatomist application reference on this object: so object life is controled by references on it. If there is no more references on the object, it is deleted. Used when an object is created by python api. It is not owned by anatomist application.

releaseRef()[source]

Release a reference on this object.

takeAppRef()[source]

Take anatomist application reference on this object : so object life is controled the normal way by Anatomist. Inverse of releaseAppRef(). The object is now owned by anatomist application.

takeRef()[source]

Take a reference on this object.

class AObject(anatomistinstance, internalRep=None, *args, **kwargs)[source]

Represents an object in Anatomist application.

The following informations can be obtained using ObjectInfo command:

objectType

object type. For example : volume, bucket, graph, texture…

Type

str

children

list of objects which are children of current object (for example: nodes in a graph). Can be empty.

Type

list of AObject

filename

name of the file from which the object has been loaded. May be None.

Type

str

name

name of the object presented in Anatomist window.

Type

str

copy

True indicates that this object is a copy of another object, else it is the original object.

Type

bool

material

object material parameters

Type

Material

referential

referential assigned to this object.

Type

Referential

Parameters
  • anatomistinstance (Anatomist) – reference to Anatomist object which created this object.

  • internalRep (object) – representation of this object in anatomist application.

extractTexture(time=None)[source]

Extract object’s texture to create a new texture object.

Parameters

time (float) – for temporal objects, if this parameter is mentionned the texture will be extracted at this time. if not mentionned, All times will be extracted and the texture will be a temporal object. In socket implementation, it is necessary to get a new id for the texture object and to pass it to the command.

Returns

texture – the newly created texture object

Return type

AObject

generateTexture(dimension=1)[source]

Generates an empty texture (value 0 everywhere) for a mesh object.

Parameters

dimension (int) – texture dimension (1 or 2)

Returns

texture – the newly created texture object

Return type

AObject

class AWindow(anatomistinstance, internalRep=None, *args, **kwargs)[source]

Represents an anatomist window.

windowType

windows type (axial, sagittal, …)

Type

str

group

the group which this window belongs to.

Type

AWindowsGroup

objects

the window contains these objects.

Type

list of AObject

Parameters
  • anatomistinstance (Anatomist) – reference to Anatomist object which created this object.

  • internalRep (object) – representation of this object in anatomist application.

getReferential()[source]

Get the referential attached to the window (the coordinates system used for 3D positions in this window)

class AWindowsBlock(anatomistinstance=None, internalRep=None, nbCols=2, nbRows=None, *args, **kwargs)[source]
Parameters
  • anatomistinstance (Anatomist) – reference to Anatomist object which created this object.

  • internalRep (object) – representation of this object in anatomist application.

class Referential(anatomistinstance, internalRep=None, uuid=None, centralRef=False, *args, **kwargs)[source]
refUuid

a unique id representing this referential. Two referential are equal if they have the same uuid.

Type

str

centralRef

indicates if this referential represents anatomist’s central referential

Type

bool

Parameters
  • anatomistinstance (Anatomist) – reference to Anatomist object which created this object.

  • internalRep (object) – representation of this object in anatomist application.

anaServerProcessExited(exitCode=0, exitStatus=0)[source]

This method is called when anatomist process exited.

close()[source]

Kill current session of Anatomist.

createCommandMessage(command, **kwargs)[source]

Writes a command in the format requested by anatomist processor.

Parameters
  • command (str) – name of the command to execute.

  • kwargs (dict) – parameters for the command

Returns

message – a tree representing the command

Return type

str

createGraph(object, name=None, syntax=None, filename=None)[source]

Creates a graph associated to a object (volume for example). This object initializes graph’s dimensions (voxel size, extrema).

Parameters
  • object (AObject) – the new graph is based on this object

  • name (str) – graph name. default is RoiArg.

  • syntax (str) – graph syntax attribute. default is RoiArg.

  • filename (str) – filename used for saving. Default is None.

Returns

graph – the new graph object

Return type

AGraph

createPalette(name)[source]

Creates an empty palette and adds it in the palettes list.

Parameters

name (str) – name of the new palette

Returns

palette – the newly created palette

Return type

APalette

createReferential(filename=None)[source]

This command does not exist in Anatomist because the command AssignReferential can create a new referential if needed. But the way of creating a new referential depends on the connection with Anatomist, so it seems to be better to encapsulate this step on another command. So referentials are treated the same as other objects. (LoadObject -> addAobject | createReferential -> assignReferential) In this implementation, creating a new referential is just reserving an id for it. The corresponding object will only be created when the referential is assigned to an object or a window.

Parameters

filename (str) – name of a file (minf file, extension .referential) containing informations about the referential : its name and uuid

Returns

ref – the newly created referential

Return type

Referential

createTransformation(matrix, origin, destination)[source]

Creates a transformation from a referential to another. The transformation informations are given in a matrix.

Parameters
  • matrix (float vector, size 12) – transformation matrix (4 lines, 3 colons ; 1st line: translation, others: rotation)

  • origin (Referential) – origin of the transformation

  • destination (Referential) – coordinates’ referential after applying transformation

Returns

trans – transformation to apply to convert coordinates from one referent

Return type

Transformation

createWindow(wintype, geometry=None, block=None, no_decoration=False, options=None)[source]

Creates a new window and opens it.

Parameters
  • wintype (str) – type of window to open (“Axial”, “Sagittal”, “Coronal”, “3D”, “Browser”, “Profile”)

  • geometry (int vector) – position on screen and size of the new window (x, y, w, h)

  • block (AWindowsBlock) – a block in which the new window must be added

  • no_decoration (bool) – indicates if decorations (menus, buttons) can be painted around the view.

Returns

win – the newly created window

Return type

AWindow

createWindowsBlock(nbCols=2, nbRows=None)[source]
Returns

block – a window which can contain several AWindow

Return type

AWindowsBlock

disableListening(event)[source]

Set listening of this event off.

Parameters

event (str) – name of the event to disable.

duplicateObject(source, shallowCopy=True)[source]

Creates a copy of source object.

Parameters

source (AObject) – the object to copy.

Returns

object – the copy. it has a reference to its source object, so original object will not be deleted since the copy exists.

Return type

AObject

enableListening(event, notifier)[source]

Set listening of this event on. So when the event occurs, the notifier’s notify method is called.

Parameters
  • event (str) – name of the event to listen

  • notifier (Notifier) – the notifier whose notify method must be called when this event occurs

executeAndWaitAnswer(command, timeout=100, **kwargs)[source]

Executes a command in anatomist application and returns the result. It should be a command that can be processed by Anatomist command processor. The list of available commands is in http://brainvisa.info/doc/anatomist/html/fr/programmation/commands.html. Parameters are converted before sending the request to anatomist application.

Parameters
  • command (str) – name of the command to execute.

  • timeout (int) – max time before returning

  • kwargs (dict) – parameters for the command

Returns

command – a dictionary describing the result of the command.

Return type

dict

fusionObjects(objects, method=None, ask_order=False)[source]

Creates a multi object that contains all given objects.

Parameters
  • objects (list of AObject) – list of objects that must be fusionned

  • method (str) – method to apply for the fusion (Fusion2DMethod…)

  • ask_order (bool) – if True, asks user in what order the fusion must be processed.

Returns

object – the newly created fusion object.

Return type

AObject

getAimsInfo()[source]
Returns

info – information about AIMS library.

Return type

string

getCommandsList()[source]
Returns

commands – list of commands available in Anatomist with their parameters. dict command name -> dict parameter name -> dict attribute -> value (needed, type)

Return type

dict

getFusionInfo(objects=None)[source]

Gets information about fusion methods. If objects is not specified, the global list of all fusion methods is returned. Otherwise the allowed fusions for those specific objects is returned.

Returns

info – Fusion methods

Return type

dict

getModulesInfo()[source]
Returns

info – list of modules and their description. dict module name -> dict attribute -> value (description)

Return type

dict

getObject(filename)[source]

Get the object corresponding to this filename if it is currently loaded.

Parameters

filename (str) – filename of the requested object

Returns

object – the object if it is loaded, else returns None.

Return type

AObject

getObjects()[source]

Gets all objects referenced in current context. Sends getInfo command.

Returns

objects – list of existing objects

Return type

list of AObject

getPalette(name)[source]

Returns a new APalette with name attribute = name. Returns None if the palette doesn’t exist in Anatomist.

Returns

palette – the named palette

Return type

APalette

getPalettes()[source]
Returns

palettes – list of palettes.

Return type

list of APalette

getReferentials()[source]

Gets all referentials in current context.

Returns

refs – list of referentials

Return type

list of Referential

getSelection(group=None)[source]
Parameters

group (AWindowsGroup) – get the selection in this group. If None, returns the selection in default group.

Returns

objects – the list of selected objects in the group of windows

Return type

list of AObject

getTransformations()[source]

Gets all transformations.

Returns

trans – list of transformations

Return type

list of Transformation

getVersion()[source]
Returns

version – Anatomist version

Return type

str

getWindows()[source]

Gets all windows referenced in current context.

Returns

windows – list of open windows

Return type

list of AWindow

groupObjects(objects)[source]

Creates a multi object containing objects in parameters.

Parameters

objects (list of AObject) – object to put in a group

Returns

group – the newly created multi object

Return type

AObject

importObjects(top_level_only=False)[source]

Gets objects importing those that are not referenced in current context.

Parameters

top_level_only (bool) – if True imports only top-level objects (that have no parents), else all objects are imported.

Returns

objects – list of existing objects

Return type

list of AObject

importReferentials()[source]

Gets all referentials importing those that are not referenced in current context.

Returns

refs – list of referentials

Return type

list of Referential

importTransformations()[source]

Gets all transformations importing those that are not referenced in current context.

Returns

trans – list of transformations

Return type

list of Transformation

importWindows()[source]

Gets all windows importing those that are not referenced in current context.

Returns

windows – list of open windows

Return type

list of AWindow

linkCursorLastClickedPosition(ref=None)[source]

Gives the last clicked position of the cursor.

Parameters

ref (Referential) – if given, cursor position value will be in this referential. Else, anatomist central referential is used.

Returns

position – last position of the cursor

Return type

float vector, size 3

loadCursor(filename)[source]

Loads a cursor for 3D windows from a file. Any mesh can be loaded as cursor. The loaded file is added to cursor choice list in anatomist parameters.

Parameters

filename (str) – the file containing object data

Returns

cursor – the loaded object

Return type

AObject

loadObject(filename, objectName=None, restrict_object_types=None, forceReload=True, duplicate=False, hidden=False)[source]

Loads an object from a file (volume, mesh, graph, texture…)

Parameters
  • filename (str) – the file containing object data

  • objectName (str) – object name

  • restrict_object_types (dictionary) – object -> accpepted types list. Ex: {'Volume' : ['S16', 'FLOAT']}

  • forceReload (bool) – if True the object will be loaded even if it is already loaded in Anatomist. Otherwise, the already loaded one is returned.

  • duplicate (bool) – if the object already exists, duplicate it. The original and the copy will share the same data but not display parameters as palette. If the object is not loaded yet, load it hidden and duplicate it (unable to keep the original object with default display parameters).

  • hidden (bool) – a idden object does not appear in Anatomist main control window.

Returns

object – the loaded object

Return type

AObject

loadTransformation(filename, origin, destination)[source]

Loads a transformation from a referential to another. The transformation informations are given in a file.

Parameters
  • filename (str) – file containing transformation informations

  • origin (Referential) – origin of the transformation

  • destination (Referential) – coordinates’ referential after applying transformation

Returns

trans – transformation to apply to convert coordinates from one referent

Return type

Transformation

newId()[source]

In this implementation, anatomist objects are not accessibles. In the commands send to Anatomist, objects are referenced by unique identifier. Objects defined in this module encapsulate the id of the corresponding Anatomist object.

Returns

id – a new unused ID.

Return type

int

newItemRep()[source]

Creates a new item representation. In this implementation, generates a new non zero Id.

newRequestID()[source]

Generates a new unique id for a request to send to anatomist.

Returns

id – a unique id

Return type

int

runAnatomistServer(*args)[source]

Executes Anatomist in server mode. Parameters in args will be passed as anatomist command parameters.

send(command, **kwargs)[source]

Sends a command to anatomist application. Call this method if there is no answer to get.

Parameters
  • command (str) – name of the command to execute. Any command that can be processed by anatomist command processor.

  • kwargs (dict) – parameters for the command

sync()[source]

Wait for anatomist finishing current processing. Some commands gives no answer so we don’t know when anatomist has finished to process them. Use this method to make sure anatomist has finished all current processing. It sends a simple request to anatomist and wait for the answer.