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

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

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

ASocket – socket used to communicate with anatomist application.

launched

bool – indicates if anatomist application has been correclty launched in server mode

_requestID

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

anaServerProcess

QProcess – anatomist application process

centralRef

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

mniTemplateRef

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

anatomistExecutable

str – path to anatomist executable

lock

RLock – lock for thread safety when accessing the singleton instance

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.

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

Anatomist – 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.

internalRep

object – internalRep: representation of this object in anatomist application.

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
class AObject(anatomistinstance, internalRep=None, *args, **kwargs)[source]

Represents an object in Anatomist application.

The following informations can be obtained using ObjectInfo command:

objectType

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

children

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

filename

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

name

str – name of the object presented in Anatomist window.

copy

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

material

Material – object material parameters

referential

Referential – referential assigned to this object.

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

str – windows type (axial, sagittal, …)

group

AWindowsGroup – the group which this window belongs to.

objects

list of AObject – the window contains these objects.

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

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

centralRef

bool – indicates if this referential represents anatomist’s central referential

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