PyAims examples

Volume API manipulation and tests

Download source: volume_test.py

# -*- coding: utf-8 -*-

#  This software and supporting documentation are distributed by
#      Institut Federatif de Recherche 49
#      CEA/NeuroSpin, Batiment 145,
#      91191 Gif-sur-Yvette cedex
#      France
#
# This software is governed by the CeCILL-B license under
# French law and abiding by the rules of distribution of free software.
# You can  use, modify and/or redistribute the software under the
# terms of the CeCILL-B license as circulated by CEA, CNRS
# and INRIA at the following URL "http://www.cecill.info".
#
# As a counterpart to the access to the source code and  rights to copy,
# modify and redistribute granted by the license, users are provided only
# with a limited warranty  and the software's author,  the holder of the
# economic rights,  and the successive licensors  have only  limited
# liability.
#
# In this respect, the user's attention is drawn to the risks associated
# with loading,  using,  modifying and/or developing or reproducing the
# software by the user in light of its specific status of free software,
# that may mean  that it is complicated to manipulate,  and  that  also
# therefore means  that it is reserved for developers  and  experienced
# professionals having in-depth computer knowledge. Users are therefore
# encouraged to load and test the software's suitability as regards their
# requirements in conditions enabling the security of their systems and/or
# data to be ensured and,  more generally, to use and operate it in the
# same conditions as regards security.
#
# The fact that you are presently reading this means that you have had
# knowledge of the CeCILL-B license and that you accept its terms.

from __future__ import print_function

from soma import aims
import sys

if sys.version_info[0] >= 3:
    xrange = range


app = aims.AimsApplication(sys.argv, 'Volume test in python')

app.initialize()

infile = aims.carto.Paths.findResourceFile(
    'doc/pyanatomist-%s/examples/irm.ima'
    % '.'.join([str(x) for x in aims.version()]))
if not infile:
    infile = 'irm.ima'
vol = aims.read(infile)
print('vol:', vol)
h = vol.header()
print('header:', h)

dx = vol.getSizeX()
dy = vol.getSizeY()
dz = vol.getSizeZ()
dt = vol.getSizeT()

mi = vol.value(0)
ma = vol.value(0)

dims = [dx, dy, dz, dt]
print('volume_dimensions:', dims)
print('voxel_size:', h['voxel_size'])

# array min/max

arr = vol.arraydata()
# print('array min/max:', Numeric.minimum( arr ), '-', Numeric.maximum( arr ))

print('setting value 1618 at pos (125, 63, 12 )')
vol.setValue(1618, 125, 63, 12)
# print('C++ min/max:', vol.minimum(), '-', vol.maximum())

# print('minIndex:', vol.minIndex())
# print('maxIndex:', vol.maxIndex())

print('(numpy) min:', arr.min(), ' at voxel ', arr.argmin())
print('(numpy) max:', arr.max(), ' at voxel ', arr.argmax())

print('python min/max...')
for t in xrange(dt):
    for z in xrange(dz):
        print('t:', t, 'z:', z)
        for y in xrange(dy):
            for x in xrange(dx):
                v = vol.value(x, y, z, t)
                if mi > v:
                    mi = v
                if ma < v:
                    ma = v

print('min:', mi)
print('max:', ma)

fileout = '/tmp/toto.img'
print('writing volume to', fileout)
w = aims.Writer()
w.write(vol, fileout)
print('object type:', w.writtenObjectType())
print('data type:', w.writtenObjectDataType())
print('full type:', w.writtenObjectFullType())

Older Volumes (AimsData) manipulation and tests

Download source: volume_test.py

# -*- coding: utf-8 -*-

#  This software and supporting documentation are distributed by
#      Institut Federatif de Recherche 49
#      CEA/NeuroSpin, Batiment 145,
#      91191 Gif-sur-Yvette cedex
#      France
#
# This software is governed by the CeCILL-B license under
# French law and abiding by the rules of distribution of free software.
# You can  use, modify and/or redistribute the software under the
# terms of the CeCILL-B license as circulated by CEA, CNRS
# and INRIA at the following URL "http://www.cecill.info".
#
# As a counterpart to the access to the source code and  rights to copy,
# modify and redistribute granted by the license, users are provided only
# with a limited warranty  and the software's author,  the holder of the
# economic rights,  and the successive licensors  have only  limited
# liability.
#
# In this respect, the user's attention is drawn to the risks associated
# with loading,  using,  modifying and/or developing or reproducing the
# software by the user in light of its specific status of free software,
# that may mean  that it is complicated to manipulate,  and  that  also
# therefore means  that it is reserved for developers  and  experienced
# professionals having in-depth computer knowledge. Users are therefore
# encouraged to load and test the software's suitability as regards their
# requirements in conditions enabling the security of their systems and/or
# data to be ensured and,  more generally, to use and operate it in the
# same conditions as regards security.
#
# The fact that you are presently reading this means that you have had
# knowledge of the CeCILL-B license and that you accept its terms.

from __future__ import print_function

from soma import aims
import sys

if sys.version_info[0] >= 3:
    xrange = range


app = aims.AimsApplication(sys.argv, 'AimsData test in python')

app.initialize()

reader = aims.Reader()
# read volumes as AimsData
reader.mapType('Volume', 'AimsData')
infile = aims.carto.Paths.findResourceFile(
    'doc/pyanatomist-%s/examples/irm.ima'
    % '.'.join([str(x) for x in aims.version()]))
if not infile:
    infile = 'irm.ima'
data = reader.read(infile)
print('data:', data)
h = data.header()
print('header:', h)

dx = data.dimX()
dy = data.dimY()
dz = data.dimZ()
dt = data.dimT()

mi = data.value(0)
ma = data.value(0)

dims = [dx, dy, dz, dt]
print('volume_dimensions:', dims)
print('voxel_size:', [data.sizeX(), data.sizeY(), data.sizeZ(), data.sizeT()])

print('C++ min/max:', data.minimum(), '-', data.maximum())
print('setting value 1618 at pos (125, 63, 12 )')
data.setValue(1618, 125, 63, 12)
print('C++ min/max:', data.minimum(), '-', data.maximum())

print('minIndex:', data.minIndex())
print('maxIndex:', data.maxIndex())

print('python min/max...')
for t in xrange(dt):
    for z in xrange(dz):
        print('t:', t, 'z:', z)
        for y in xrange(dy):
            for x in xrange(dx):
                v = data.value(x, y, z, t)
                if mi > v:
                    mi = v
                if ma < v:
                    ma = v

print('min:', mi)
print('max:', ma)

fileout = '/tmp/toto.vimg'
print('writing volume to', fileout)
w = aims.Writer()
w.write(data, fileout)
print('object type:', w.writtenObjectType())
print('data type:', w.writtenObjectDataType())
print('full type:', w.writtenObjectFullType())

Mesh manipulation and tests

Download source: mesh_test.py

# -*- coding: utf-8 -*-

#  This software and supporting documentation are distributed by
#      Institut Federatif de Recherche 49
#      CEA/NeuroSpin, Batiment 145,
#      91191 Gif-sur-Yvette cedex
#      France
#
# This software is governed by the CeCILL-B license under
# French law and abiding by the rules of distribution of free software.
# You can  use, modify and/or redistribute the software under the
# terms of the CeCILL-B license as circulated by CEA, CNRS
# and INRIA at the following URL "http://www.cecill.info".
#
# As a counterpart to the access to the source code and  rights to copy,
# modify and redistribute granted by the license, users are provided only
# with a limited warranty  and the software's author,  the holder of the
# economic rights,  and the successive licensors  have only  limited
# liability.
#
# In this respect, the user's attention is drawn to the risks associated
# with loading,  using,  modifying and/or developing or reproducing the
# software by the user in light of its specific status of free software,
# that may mean  that it is complicated to manipulate,  and  that  also
# therefore means  that it is reserved for developers  and  experienced
# professionals having in-depth computer knowledge. Users are therefore
# encouraged to load and test the software's suitability as regards their
# requirements in conditions enabling the security of their systems and/or
# data to be ensured and,  more generally, to use and operate it in the
# same conditions as regards security.
#
# The fact that you are presently reading this means that you have had
# knowledge of the CeCILL-B license and that you accept its terms.

from __future__ import print_function

from soma import aims
import sys

if sys.version_info[0] >= 3:
    xrange = range


mesh = aims.read('/home/dr144257/data/ra_head.mesh')
print('mesh:', mesh)
h = mesh.header()
print('header:', h)

print('timesteps:', mesh.size())
for t in xrange(mesh.size()):
    print('time:', t)
    v = mesh.vertex(t)
    print('vertices:', v)
    n = mesh.normal(t)
    print('normals:', n)
    p = mesh.polygon(t)
    print('polygons:', p)

fileout = '/tmp/toto.mesh'
print('writing mesh to', fileout)
w = aims.Writer()
w.write(mesh, fileout)
print('object type:', w.writtenObjectType())
print('data type:', w.writtenObjectDataType())
print('full type:', w.writtenObjectFullType())

Mesh modification

Download source: meshTimeCollapse.py <../examples/meshTimeCollapse.py>`_

# -*- coding: utf-8 -*-
#  This software and supporting documentation are distributed by
#      Institut Federatif de Recherche 49
#      CEA/NeuroSpin, Batiment 145,
#      91191 Gif-sur-Yvette cedex
#      France
#
# This software is governed by the CeCILL-B license under
# French law and abiding by the rules of distribution of free software.
# You can  use, modify and/or redistribute the software under the
# terms of the CeCILL-B license as circulated by CEA, CNRS
# and INRIA at the following URL "http://www.cecill.info".
#
# As a counterpart to the access to the source code and  rights to copy,
# modify and redistribute granted by the license, users are provided only
# with a limited warranty  and the software's author,  the holder of the
# economic rights,  and the successive licensors  have only  limited
# liability.
#
# In this respect, the user's attention is drawn to the risks associated
# with loading,  using,  modifying and/or developing or reproducing the
# software by the user in light of its specific status of free software,
# that may mean  that it is complicated to manipulate,  and  that  also
# therefore means  that it is reserved for developers  and  experienced
# professionals having in-depth computer knowledge. Users are therefore
# encouraged to load and test the software's suitability as regards their
# requirements in conditions enabling the security of their systems and/or
# data to be ensured and,  more generally, to use and operate it in the
# same conditions as regards security.
#
# The fact that you are presently reading this means that you have had
# knowledge of the CeCILL-B license and that you accept its terms.

# ce truc me sert a aplatir temporelement le mesh (c'est a dire que je passe
# de morceaux de mesh (aux indices temporels croissants) vers un seul mesh)

# Script sous-optimal car il travaille sur des numpyarray (donc conversion en
# entree et en sortie), alors qu'on doit pouvoir faire l'equivalent sur les
# aimsmesh via les fonctions de aims.surfacemanip.
# Et car il charge tout en memoire.

from soma import aims
from numpy import *
v = aims.read('/home/dr144257/data/ra_head.mesh')


def getFromMesh(v, t):
    vertex = array(v.vertex(t))
    normal = array(v.normal(t))
    polygon = array(v.polygon(t))
    return(vertex, normal, polygon)


def meshlistMerge(meshlist):
    outv = vstack([x[0] for x in meshlist])
    outn = vstack([x[1] for x in meshlist])
    outplst = []
    n = 0
    for x in meshlist:
        outplst.append(x[2] + n)
        n += len(x[0])
    outp = vstack(outplst)
    return (outv, outn, outp)


def writeMesh(vertex, normal, polygon):
    vv = aims.vector_POINT3DF()
    vn = aims.vector_POINT3DF()
    vp = aims.vector_AimsVector_U32_3()
    for x in vertex:
        vv.append(x)
    for x in normal:
        vn.append(x)
    for x in polygon:
        vp.append(x)
    m = aims.AimsTimeSurface_3()
    m.vertex().assign(vv)
    m.normal().assign(vn)
    m.polygon().assign(vp)
    aims.write(m, '/tmp/mesh0')


M = meshlistMerge([getFromMesh(v, x) for x in range(v.size())])
writeMesh(*M)

Texture manipulation and tests

Download source: texture_test.py

# -*- coding: utf-8 -*-

#  This software and supporting documentation are distributed by
#      Institut Federatif de Recherche 49
#      CEA/NeuroSpin, Batiment 145,
#      91191 Gif-sur-Yvette cedex
#      France
#
# This software is governed by the CeCILL-B license under
# French law and abiding by the rules of distribution of free software.
# You can  use, modify and/or redistribute the software under the
# terms of the CeCILL-B license as circulated by CEA, CNRS
# and INRIA at the following URL "http://www.cecill.info".
#
# As a counterpart to the access to the source code and  rights to copy,
# modify and redistribute granted by the license, users are provided only
# with a limited warranty  and the software's author,  the holder of the
# economic rights,  and the successive licensors  have only  limited
# liability.
#
# In this respect, the user's attention is drawn to the risks associated
# with loading,  using,  modifying and/or developing or reproducing the
# software by the user in light of its specific status of free software,
# that may mean  that it is complicated to manipulate,  and  that  also
# therefore means  that it is reserved for developers  and  experienced
# professionals having in-depth computer knowledge. Users are therefore
# encouraged to load and test the software's suitability as regards their
# requirements in conditions enabling the security of their systems and/or
# data to be ensured and,  more generally, to use and operate it in the
# same conditions as regards security.
#
# The fact that you are presently reading this means that you have had
# knowledge of the CeCILL-B license and that you accept its terms.

from __future__ import print_function
from soma import aims
import sys

tex = aims.read('/home/dr144257/data/texture2d.tex')
print('texture:', tex)
h = tex.header()
print('header:', h)

print('timesteps:', tex.size())
for t in range(tex.size()):
    print('time:', t)
    tx = tex[t]
    print('texture:', tx, ', size:', tx.nItem())

fileout = '/tmp/toto.tex'
print('writing texture to', fileout)
w = aims.Writer()
w.write(tex, fileout)
print('object type:', w.writtenObjectType())
print('data type:', w.writtenObjectDataType())
print('full type:', w.writtenObjectFullType())

Buckets manipulation and tests

Download source: bucket_test.py

# -*- coding: utf-8 -*-

#  This software and supporting documentation are distributed by
#      Institut Federatif de Recherche 49
#      CEA/NeuroSpin, Batiment 145,
#      91191 Gif-sur-Yvette cedex
#      France
#
# This software is governed by the CeCILL-B license under
# French law and abiding by the rules of distribution of free software.
# You can  use, modify and/or redistribute the software under the
# terms of the CeCILL-B license as circulated by CEA, CNRS
# and INRIA at the following URL "http://www.cecill.info".
#
# As a counterpart to the access to the source code and  rights to copy,
# modify and redistribute granted by the license, users are provided only
# with a limited warranty  and the software's author,  the holder of the
# economic rights,  and the successive licensors  have only  limited
# liability.
#
# In this respect, the user's attention is drawn to the risks associated
# with loading,  using,  modifying and/or developing or reproducing the
# software by the user in light of its specific status of free software,
# that may mean  that it is complicated to manipulate,  and  that  also
# therefore means  that it is reserved for developers  and  experienced
# professionals having in-depth computer knowledge. Users are therefore
# encouraged to load and test the software's suitability as regards their
# requirements in conditions enabling the security of their systems and/or
# data to be ensured and,  more generally, to use and operate it in the
# same conditions as regards security.
#
# The fact that you are presently reading this means that you have had
# knowledge of the CeCILL-B license and that you accept its terms.

from __future__ import print_function

from soma import aims
import sys

if sys.version_info[0] >= 3:
    xrange = range

bck = aims.read(
    '/neurospin/lnao/Panabase/data/diffusion/chaos/t1mri/default_acquisition/default_analysis/folds/3.0/base2005_manual/Rchaos_base2005_manual.data/ss_Bucket.bck')
print('bucket:', bck)

print('timesteps:', bck.size())
for t in xrange(bck.size()):
    print('time:', t)
    b = bck[t]
    print('bucket:', b, ', size:', b.size())
    for p in b.keys():
        sys.stdout.write(str(p.list()) + ' ')
    print

fileout = '/tmp/toto.bck'
print('writing bucket to', fileout)
w = aims.Writer()
w.write(bck, fileout)
print('object type:', w.writtenObjectType())
print('data type:', w.writtenObjectDataType())
print('full type:', w.writtenObjectFullType())

Graph manipulation and tests

Download source: graph_test.py

# -*- coding: utf-8 -*-

#  This software and supporting documentation are distributed by
#      Institut Federatif de Recherche 49
#      CEA/NeuroSpin, Batiment 145,
#      91191 Gif-sur-Yvette cedex
#      France
#
# This software is governed by the CeCILL-B license under
# French law and abiding by the rules of distribution of free software.
# You can  use, modify and/or redistribute the software under the
# terms of the CeCILL-B license as circulated by CEA, CNRS
# and INRIA at the following URL "http://www.cecill.info".
#
# As a counterpart to the access to the source code and  rights to copy,
# modify and redistribute granted by the license, users are provided only
# with a limited warranty  and the software's author,  the holder of the
# economic rights,  and the successive licensors  have only  limited
# liability.
#
# In this respect, the user's attention is drawn to the risks associated
# with loading,  using,  modifying and/or developing or reproducing the
# software by the user in light of its specific status of free software,
# that may mean  that it is complicated to manipulate,  and  that  also
# therefore means  that it is reserved for developers  and  experienced
# professionals having in-depth computer knowledge. Users are therefore
# encouraged to load and test the software's suitability as regards their
# requirements in conditions enabling the security of their systems and/or
# data to be ensured and,  more generally, to use and operate it in the
# same conditions as regards security.
#
# The fact that you are presently reading this means that you have had
# knowledge of the CeCILL-B license and that you accept its terms.

from __future__ import print_function

from soma import aims
import sys

infile = aims.carto.Paths.findResourceFile(
    'doc/pyanatomist-%s/examples/Rbase.arg'
    % '.'.join([str(x) for x in aims.version()]))
if not infile:
    infile = 'Rbase.arg'
graph = aims.read(infile)
print('graph:', graph)
print('global properties:', graph.keys())
print('nodes:', graph.order())
print('relations:', graph.edgesSize())

# iterate on properties
for p in graph:
    print('property:', p, ', type:',
          (graph[p].type() if isinstance(graph[p], aims.Object)
           else type(graph[p])))

# iterate on vertices
for v in graph.vertices():
    print('vertex:', v.getSyntax(), ', edges:', v.edgesSize())
    if 'name' in v:
        print('  name:', v['name'])
    if 'label' in v:
        print('  label:', v['label'])
    try:
        # access mesh in attribute 'aims_Tmtktri'
        mesh = v['aims_Tmtktri']
        print('mesh:', mesh, ', polygons:', mesh.polygon().size())
    except:
        pass

# iterate on edges
for e in graph.edges():
    print('edge:', e.getSyntax(), ', links', e.verticesSize(), 'vertices')

fileout = '/tmp/toto.arg'
print('writing graph to', fileout)
w = aims.Writer()
w.write(graph, fileout)
print('object type:', w.writtenObjectType())
print('data type:', w.writtenObjectDataType())
print('full type:', w.writtenObjectFullType())

ROIs manipulation and tests

Download source: roi_test.py

# -*- coding: utf-8 -*-
#  This software and supporting documentation are distributed by
#      Institut Federatif de Recherche 49
#      CEA/NeuroSpin, Batiment 145,
#      91191 Gif-sur-Yvette cedex
#      France
#
# This software is governed by the CeCILL-B license under
# French law and abiding by the rules of distribution of free software.
# You can  use, modify and/or redistribute the software under the
# terms of the CeCILL-B license as circulated by CEA, CNRS
# and INRIA at the following URL "http://www.cecill.info".
#
# As a counterpart to the access to the source code and  rights to copy,
# modify and redistribute granted by the license, users are provided only
# with a limited warranty  and the software's author,  the holder of the
# economic rights,  and the successive licensors  have only  limited
# liability.
#
# In this respect, the user's attention is drawn to the risks associated
# with loading,  using,  modifying and/or developing or reproducing the
# software by the user in light of its specific status of free software,
# that may mean  that it is complicated to manipulate,  and  that  also
# therefore means  that it is reserved for developers  and  experienced
# professionals having in-depth computer knowledge. Users are therefore
# encouraged to load and test the software's suitability as regards their
# requirements in conditions enabling the security of their systems and/or
# data to be ensured and,  more generally, to use and operate it in the
# same conditions as regards security.
#
# The fact that you are presently reading this means that you have had
# knowledge of the CeCILL-B license and that you accept its terms.
from __future__ import print_function
import sys
from soma import aims
import math

# Read regions of interests from sys.argv[ 1 ]
roiIterator = aims.getRoiIterator(sys.argv[1])


# Read image from sys.argv[ 2 ]
reader = aims.Reader({'Volume': 'AimsData'})
image = reader.read(sys.argv[2])
interpolator = aims.getLinearInterpolator(image)


# Iterate on each region
while roiIterator.isValid():
    print(roiIterator.regionName() + ':')
    maskIterator = roiIterator.maskIterator()
    print('maskIterator:', maskIterator)
    valid = 0
    invalid = 0
    sum = None
    sqsum = 0
    # Iterate on each point of a region
    print('iter on maskIterator')
    while maskIterator.isValid():
        print(' point')
        p = maskIterator.valueMillimeters()
        print(p)
        # Check if the point is in the image limit
        print('4:', interpolator)
        if interpolator.isValid(p):
            print('6')
            value = interpolator.value(p)
            print('7:', value)
            if sum is None:
                sum = value
            else:
                sum += value
            valid += 1
            sqsum += value * value
        else:
            invalid += 1
        print('8')
        maskIterator.next()
    print('  valid points:', valid)
    print('  invalid points:', invalid)
    if valid:
        mean = sum / float(valid)
        if valid >= 2:
            stddev = math.sqrt((sqsum - mean * mean) / (valid - 1))
        else:
            stddev = math.sqrt((sqsum - mean * mean) / valid)
    else:
        mean = 'N/A'
        stddev = 'N/A'
    print('  mean value:', mean)
    print('  std dev   :', stddev)
    roiIterator.next()

Merging hierarchies example

Download source: hierarchy_merge.py

#  This software and supporting documentation are distributed by
#      Institut Federatif de Recherche 49
#      CEA/NeuroSpin, Batiment 145,
#      91191 Gif-sur-Yvette cedex
#      France
#
# This software is governed by the CeCILL-B license under
# French law and abiding by the rules of distribution of free software.
# You can  use, modify and/or redistribute the software under the
# terms of the CeCILL-B license as circulated by CEA, CNRS
# and INRIA at the following URL "http://www.cecill.info".
#
# As a counterpart to the access to the source code and  rights to copy,
# modify and redistribute granted by the license, users are provided only
# with a limited warranty  and the software's author,  the holder of the
# economic rights,  and the successive licensors  have only  limited
# liability.
#
# In this respect, the user's attention is drawn to the risks associated
# with loading,  using,  modifying and/or developing or reproducing the
# software by the user in light of its specific status of free software,
# that may mean  that it is complicated to manipulate,  and  that  also
# therefore means  that it is reserved for developers  and  experienced
# professionals having in-depth computer knowledge. Users are therefore
# encouraged to load and test the software's suitability as regards their
# requirements in conditions enabling the security of their systems and/or
# data to be ensured and,  more generally, to use and operate it in the
# same conditions as regards security.
#
# The fact that you are presently reading this means that you have had
# knowledge of the CeCILL-B license and that you accept its terms.
from soma import aims

# read 2 hierarchies as h1 and h2, and merge them into h3

h1 = aims.read(aims.carto.Paths.shfjShared()
               + '/nomenclature/hierarchy/sulcal_root_colors.hie')
h2 = aims.read(aims.carto.Paths.shfjShared()
               + '/nomenclature/hierarchy/stereotaxy.hie')

h3 = aims.Hierarchy()
h3.setSyntax('hierarchy')
h3['graph_syntax'] = 'RoiArg'  # this hie applies to RoiArg graphs

# create 2 main nodes
h3.insert(aims.Tree(True, 'fold_name'))
h3.children()[0]['name'] = 'sulci'
h3.insert(aims.Tree(True, 'fold_name'))
h3.children()[1]['name'] = 'stereotaxy'

for c in h1.children():
    h3.children()[0].insert(c)

for c in h2.children():
    h3.children()[1].insert(c)

outputfile = '/tmp/mergedhierarchy.hie'
aims.write(h3, outputfile)

Python / C++ Reference-counting sharing tests

Download source: refcounting_test.py

#!/usr/bin/env python2

#  This software and supporting documentation are distributed by
#      Institut Federatif de Recherche 49
#      CEA/NeuroSpin, Batiment 145,
#      91191 Gif-sur-Yvette cedex
#      France
#
# This software is governed by the CeCILL-B license under
# French law and abiding by the rules of distribution of free software.
# You can  use, modify and/or redistribute the software under the
# terms of the CeCILL-B license as circulated by CEA, CNRS
# and INRIA at the following URL "http://www.cecill.info".
#
# As a counterpart to the access to the source code and  rights to copy,
# modify and redistribute granted by the license, users are provided only
# with a limited warranty  and the software's author,  the holder of the
# economic rights,  and the successive licensors  have only  limited
# liability.
#
# In this respect, the user's attention is drawn to the risks associated
# with loading,  using,  modifying and/or developing or reproducing the
# software by the user in light of its specific status of free software,
# that may mean  that it is complicated to manipulate,  and  that  also
# therefore means  that it is reserved for developers  and  experienced
# professionals having in-depth computer knowledge. Users are therefore
# encouraged to load and test the software's suitability as regards their
# requirements in conditions enabling the security of their systems and/or
# data to be ensured and,  more generally, to use and operate it in the
# same conditions as regards security.
#
# The fact that you are presently reading this means that you have had
# knowledge of the CeCILL-B license and that you accept its terms.
from __future__ import print_function
from soma import aims

_created = False
_deleted = False


class MyVol (aims.Volume_S16):

    def __init__(self, *args):
        print('creating MyVol')
        aims.Volume_S16.__init__(self, *args)
        global _created, _deleted
        _created = True
        _deleted = False

    def __del__(self):
        print('deleting MyVol, C++ refs:',  self.__refcount__())
        aims.Volume_S16.__del__(self)
        global _deleted
        _deleted = True


class MyVol2 (aims.pyaims.DebuggingVolume):

    def __init__(self, *args):
        print('creating MyVol2')
        aims.pyaims.DebuggingVolume.__init__(self, *args)
        global _created, _deleted
        _created = True
        _deleted = False

    def __del__(self):
        print('deleting MyVol2, C++ refs:', self.__refcount__())
        aims.pyaims.DebuggingVolume.__del__(self)
        global _deleted
        _deleted = True


class MyClass(object):

    def __init__(self):
        print('creating Myclass')
        object.__init__(self)
        global _created, _deleted
        _created = True
        _deleted = False

    def __del__(self):
        print('deleting Myclass')
        global _deleted
        _deleted = True


print(
    'testing rc_ptr<inherited Python instance> built from temporary instance')
r = aims.rc_ptr_Volume_S16(MyVol())
print('ref created')
if _deleted:
    print(
        'ERROR: Python instance deleted whereas a rc_ptr still points to it.')
    print('(this error is "normal" for sip <= 4.7.x)')
print('deleting ref')
del r
if not _deleted:
    print('ERROR: Python instance not deleted when last reference is deleted')
_created = False
_deleted = False

print('testing rc_ptr<inherited C++ instance> built from temporary instance')
r = aims.rc_ptr_Volume_S16(aims.pyaims.DebuggingVolume())
print('ref created')
if aims.pyaims.DebuggingVolume.deleted:
    print('ERROR: C++ instance deleted whereas a rc_ptr still points to it.')
print('deleting ref')
del r
if not aims.pyaims.DebuggingVolume.deleted:
    print('ERROR: C++ instance not deleted when last reference is deleted')
aims.pyaims.DebuggingVolume.created = False
aims.pyaims.DebuggingVolume.deleted = False

print('testing rc_ptr<inherited Python instance from inherited C++ class> '
      'built from temporary instance')
r = aims.rc_ptr_Volume_S16(MyVol2())
print('ref created')
if _deleted:
    print(
        'ERROR: Python instance deleted whereas a rc_ptr still points to it.')
    print('(this error is "normal" for sip <= 4.7.x)')
if aims.pyaims.DebuggingVolume.deleted:
    print('ERROR: C++ instance deleted whereas a rc_ptr still points to it.')
print('deleting ref')
del r
if not _deleted:
    print('ERROR: Python instance not deleted when last reference is deleted')
if not aims.pyaims.DebuggingVolume.deleted:
    print('ERROR: C++ instance not deleted when last reference is deleted')
_created = False
_deleted = False
aims.pyaims.DebuggingVolume.created = False
aims.pyaims.DebuggingVolume.deleted = False

print('testing Object->GenericObject on-the-fly temporary conversion')
o = aims.Object(aims.pyaims.DebuggingVolume())
if aims.pyaims.DebuggingVolume.deleted:
    print('ERROR: C++ instance deleted whereas a rc_ptr still points to it.')
try:
    aims.carto.NumericGenericObjectConverter.asBool(o)
except:
    pass  # it's normal it raises an exception
if aims.pyaims.DebuggingVolume.deleted:
    print('ERROR: C++ instance deleted after Object->GenricObject temporary '
          'conversion whereas a rc_ptr still points to it.')
del o
if not aims.pyaims.DebuggingVolume.deleted:
    print('ERROR: C++ instance not deleted when last reference is deleted')

print('testing python dict -> GenericObject on-the-fly temporary conversion')
try:
    aims.carto.NumericGenericObjectConverter.asBool({'toto': 12})
except:
    pass
print('no crash, good...')
print('testing leaks in same situation')
try:
    aims.carto.NumericGenericObjectConverter.asBool(MyClass())
except:
    pass
if not _deleted:
    print('ERROR: Python instance not deleted when last reference is deleted')
_created = False
_deleted = False

print('testing python dict -> GenericObject conversion + ref-counting')
x = MyClass()
o = aims.Object(x)
print('ref created. deleting dict.')
del x
if _deleted:
    print(
        'ERROR: Python instance deleted whereas a rc_ptr still points to it.')
print('deleting ref')
del o
if not _deleted:
    print('ERROR: Python instance not deleted when last reference is deleted')
_created = False
_deleted = False


print('ending.')

More advanced examples

see PyAims advanced examples