Socket implementation¶

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:
- Parameters:
- addEventHandler(eventName, handlerFunction, requestID=None)[source]¶
Adds a callback function to handle an event. (eventName, requestID) -> [handlerFunction] in eventCallbacks
- 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.
- 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.
- removeEventHandler(eventName, handlerFunction=None, requestID=None)[source]¶
Removes handler function for a specfic event.
- 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.
- 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.
- _requestID¶
counter to generates unique id for requests to anatomist application. It is used to match request and answer.
- Type:
- 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:
- mniTemplateRef¶
template mni referential (used by spm) These two referentials and transformation between them are always loaded in anatomist.
- Type:
- 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:
- 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:
- Parameters:
- 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.
- class AObject(anatomistinstance, internalRep=None, *args, **kwargs)[source]¶
Represents an object in Anatomist application.
The following informations can be obtained using ObjectInfo command:
- children¶
list of objects which are children of current object (for example: nodes in a graph). Can be empty.
- Type:
list of AObject
- copy¶
True indicates that this object is a copy of another object, else it is the original object.
- Type:
- material¶
object material parameters
- Type:
Material
- referential¶
referential assigned to this object.
- Type:
Referential
- Parameters:
- 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
- class AWindow(anatomistinstance, internalRep=None, *args, **kwargs)[source]¶
Represents an anatomist window.
- group¶
the group which this window belongs to.
- Type:
AWindowsGroup
- Parameters:
- class AWindowsBlock(anatomistinstance=None, internalRep=None, nbCols=2, nbRows=None, *args, **kwargs)[source]¶
- 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:
- anaServerProcessExited(exitCode=0, exitStatus=0)[source]¶
This method is called when anatomist process exited.
- createCommandMessage(command, **kwargs)[source]¶
Writes a command in the format requested by anatomist processor.
- 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).
- 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:
- 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:
- createWindowsBlock(nbCols=2, nbRows=None)[source]¶
- Returns:
block – a window which can contain several AWindow
- Return type:
- disableListening(event)[source]¶
Set listening of this event off.
- Parameters:
event (str) – name of the event to disable.
- 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.
- fusionObjects(objects, method=None, ask_order=False)[source]¶
Creates a multi object that contains all given objects.
- 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:
- 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:
- getModulesInfo()[source]¶
- Returns:
info – list of modules and their description. dict module name -> dict attribute -> value (description)
- Return type:
- getObject(filename)[source]¶
Get the object corresponding to this filename if it is currently loaded.
- 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
- getReferentials()[source]¶
Gets all referentials in current context.
- Returns:
refs – list of referentials
- Return type:
list of Referential
- getTransformations()[source]¶
Gets all transformations.
- Returns:
trans – list of transformations
- Return type:
list of Transformation
- importObjects(top_level_only=False)[source]¶
Gets objects importing those that are not referenced in current context.
- 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.
- 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.
- 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:
- 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:
- 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:
- runAnatomistServer(*args)[source]¶
Executes Anatomist in server mode. Parameters in args will be passed as anatomist command parameters.