Пример #1
0
def execution(self, context):
    # context.write('image ref')
    a = anatomist.Anatomist()
    dims = self.image_reference.get('volume_dimension', [1, 1, 1, 1])
    # context.write(dims[3])
    if dims[3] > 1:
        sumfunc_ref = context.temporary('GIS Image')
        context.system('AimsSumFrame', '-i', self.image_reference.fullPath(),
                       '-o', sumfunc_ref.fullPath())
    else:
        sumfunc_ref = self.image_reference

    # context.write('image test')
    dims = self.image_test.get('volume_dimension', [1, 1, 1, 1])
    # context.write(dims[3])
    if dims[3] > 1:
        sumfunc_test = context.temporary('GIS Image')
        context.system('AimsSumFrame', '-i', self.image_test.fullPath(), '-o',
                       sumfunc_test.fullPath())
    else:
        sumfunc_test = self.image_test

    return a.viewActivationsOnMRI(mriFile=sumfunc_ref,
                                  fmriFile=sumfunc_test,
                                  transformation=self.test_to_ref,
                                  palette=a.getPalette("RED TEMPERATURE"),
                                  mode="linear")
def execution(self, context):

    a = anatomist.Anatomist()
    selfdestroy = []

    epi = a.loadObject(self.epi_series)
    epi.setPalette(a.getPalette("RED TEMPERATURE"))
    selfdestroy.append(epi)

    if self.anatomy is not None:
        anat = a.loadObject(self.anatomy, forceReload=True)
        selfdestroy.append(anat)
        fusion = a.fusionObjects([epi, anat], method='Fusion2DMethod')
        a.execute("Fusion2DParams",
                  object=fusion,
                  mode="linear",
                  rate=0.7,
                  reorder_objects=[epi, anat])
        window = a.createWindow("Sagittal")
        window.assignReferential(epi.referential)
        window.addObjects([fusion])
        selfdestroy.append(fusion)
        selfdestroy.append(window)
        win3 = a.createWindow('Sagittal')
        win3.assignReferential(anat.referential)
        selfdestroy.append(win3)
        win3.addObjects([anat])

    return selfdestroy
def execution(self, context):

    #lazy load just to estimate the number of streamlines
    tractogram, header = load_streamlines(self.streamlines.fullPath(),
                                          lazy=False)
    transformManager = getTransformationManager()
    referential = transformManager.referential(self.streamlines)
    #streamlines are in the LPI mm space
    nb_streamlines = header['nb_streamlines']
    streamlines = tractogram.streamlines
    if nb_streamlines > self.max_number:
        message = "The tractogram you try to display contains" + str(
            nb_streamlines
        ) + "streamlines\n In order to avoid memory crash only the first " + self.max_number, " streamlines will be displayed"
        "If your computer crashes consider decreasing self.max_number value \n. On the contrary if you have enough memory to display the whole tractogram you may want to increase self.max_number value"
        context.write(message)
        bundle = [s for i, s in enumerate(streamlines) if i < self.max_number]
    else:
        bundle = list(streamlines)
    bundle_aims = bundle_to_mesh(bundle, encode_local=True)
    del bundle

    a = anatomist.Anatomist()
    bundle_ana = a.toAObject(bundle_aims)
    bundle_ana.setMaterial(use_shader=1, shader_color_normals=1)
    bundle_ana.assignReferential(referential)

    del bundle_aims
    win = a.createWindow('3D')
    win.addObjects(bundle_ana)
    return [win, bundle_ana]
Пример #4
0
def execution(self, context):
    n_faces = 21
    transformManager = getTransformationManager()
    seeds_referential = transformManager.referential(self.seeds)

    seeds_centers = np.loadtxt(self.seeds.fullPath())
    n_sample = min(len(seeds_centers), self.n_sampling)
    if len(seeds_centers) > self.n_display:
        context.warning(
            "You try to display more than ", str(self.n_display), " seeds. It may causes Memory Error. The first ", str(self.display)," seeds ONLY are displayed in order to prevent crashes")
    radius = np.min(pdist(seeds_centers[:n_sample])) / 2.0
    sphere = aims.SurfaceGenerator.icosphere((0, 0, 0), radius, n_faces)
    vertices = np.array(sphere.vertex())
    triangles = np.array(sphere.polygon())
    seeds_centers = seeds_centers[:min(self.n_display, len(seeds_centers))]
    new_vertices, new_triangles = quick_replicate_meshes(seeds_centers, vertices, triangles)
    mesh = vertices_and_faces_to_mesh(new_vertices, new_triangles)

    a = anatomist.Anatomist()
    w3d = a.createWindow("3D")

    A_graph = a.toAObject(mesh)
    #yellow colors for the seeds (different form Red, Green , Blue so that they appears with orientation coded fibers
    material = a.Material(diffuse=[1, 1, 0, 1])
    A_graph.setMaterial(material)
    A_graph.assignReferential(seeds_referential)
    w3d.addObjects(A_graph)
    return [w3d, A_graph]
Пример #5
0
def preloadfiles(self, anim):
    """Preload all files needed for the animation and return a dictionary with
    ID in .banim file as KEY and object file as value"""
    a = anatomist.Anatomist()
    allobj = None
    preloadedfiles = {}
    for iter in anim:  # for each step of the animation
        objectsDict = iter.get("objects")
        for objID, obj in objectsDict.items():
            if objID not in list(preloadedfiles.keys()):
                tmpfilename = obj.get("filename")
                if tmpfilename:
                    preloadedfiles[objID] = a.loadObject(tmpfilename)
                else:
                    chl = obj.get('children')
                    t = obj.get('objectType')
                    if chl and t:
                        if allobj is None:
                            allobj = a.getObjects()
                        for oo in allobj:
                            if oo.objectType == t \
                                and len( chl ) == len( oo.children ) \
                                and oo.name == obj.get( 'name' ) \
                                and len([a.AObject(a, i) in chl
                                         for i in oo.children]) == len(chl):
                                preloadedfiles[objID] = oo
                                break
    return preloadedfiles
Пример #6
0
def execution(self, context):
    print(self.name)

    a = anatomist.Anatomist()
    if self.view is None:
        tosee = context.ask(_t_('What would you like to see ?'),
                            _t_('Activations'), _t_('Activations on MRI'),
                            _t_('Both'), _t_('Cancel'))
    else:
        tosee = self.view

    if tosee is None:
        alone = 1
        onMRI = 1
    elif tosee == 0:
        alone = 1
        onMRI = 0
    elif tosee == 1:
        alone = 0
        onMRI = 1
    elif tosee == 2:
        alone = 1
        onMRI = 1
    else:
        return

    selfdestroy = []
    if alone and not onMRI:
        selfdestroy.append(a.viewObject(self.Zmap))
    if onMRI:
        mri = ReadDiskItem('T1 MRI',
                           ['GIS Image', 'VIDA Image']).findValue(self.Zmap)
        trm = ReadDiskItem('Transformation matrix',
                           'Transformation matrix').findValue(self.Zmap)
        if trm is None:
            trm = [0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1]
        else:
            f = open(trm.fullPath(), 'r')
            trm = f.readlines().join().split()
            f.close()
        view = None
        if mri is not None:
            view = a.viewActivationsOnMRI(mri, self.Zmap, trm, both=alone)
            selfdestroy.append(view)
        if self.dialog and neuroConfig.gui:
            d = context.dialog(
                0, _t_('Co-registration options'),
                Signature(
                    'mri',
                    ReadDiskItem('T1 MRI', ['GIS Image', 'VIDA Image']),
                    'matrix',
                    ListOf(Float()),
                ), (_t_('Update'), update))
            d.setValue('mri', mri)
            d.setValue('matrix', trm)
            d.view = view
            d.Zmap = (self.Zmap)
            context.mainThreadActions().push(d.show)
    return selfdestroy
Пример #7
0
def execution(self, context):
    a = anatomist.Anatomist()
    #elec = ElectrodeEditorDialog(a)
    #elec.open(self.model.fullPath())
    #meshes = elecDialog.getAnatomistObjects()
    w = a.createWindow('Axial')
    #a.addObjects(meshes, [w,])
    #return (w, elec, meshes)
    return (w, )
Пример #8
0
def execution(self, context):
    a = anatomist.Anatomist()
    palette = None
    if self.palette:
        palette = self.palette
    interpolation = None
    if self.rgb_interpolation:
        interpolation = 'rgb'
    return a.viewTextureOnMesh(self.mesh, self.read, palette=palette,
                               interpolation=interpolation)
def execution(self, context):

    a = anatomist.Anatomist()
    text = a.loadObject(self.spherical_function_texture)
    mesh = a.loadObject(self.spherical_function_mesh)

    w = a.createWindow("3D")
    fusionTexture = a.fusionObjects([mesh, text], "FusionTexSurfMethod")
    w.addObjects(fusionTexture)

    return [w, fusionTexture]
Пример #10
0
def execution(self, context):
    a = anatomist.Anatomist()
    if self.roi.format is getFormat('Graph and data'):
        graph_object = a.loadObject(self.roi)
        window = a.createWindow('3D')
        window.assignReferential(graph_object.referential)
        window.addObjects([graph_object])
        nodes = graph_object.children
        a.getDefaultWindowsGroup().setSelection(nodes)
        return (graph_object, window, nodes)
    else:
        return a.viewObject(self.roi)
Пример #11
0
def execution(self, context):
    a = anatomist.Anatomist()
    # info = a.getInfo( name_objects=1, selections=1 )
    time = -1
    if time is not None:
        time = self.time
    mesh = a.loadObject(self.mesh)
    func = a.loadObject(self.volume)
    func.setPalette(palette=a.getPalette("Rainbow1-fusion"))
    fusion = a.fusionObjects([mesh, func], method='Fusion3DMethod')
    win = a.createWindow('3D')
    win.addObjects([fusion])
    # a.execute('Select')
    fusion.exportTexture(filename=self.output_texture.fullPath(), time=time)
Пример #12
0
def execution(self, context):
    a = anatomist.Anatomist()
    bro = None
    hie = a.loadObject(self.read)
    if self.use_existing_browser:
        wins = hie.getWindows()
        for w in wins:
            wi = w.getInfos()
            if wi.get('windowType') == 'Browser':
                bro = w
    if bro is None:
        bro = a.createWindow('Browser')
        bro.addObjects([hie])
    return (hie, bro)
Пример #13
0
def execution(self, context):
    a = anatomist.Anatomist()
    # info = a.getInfo( name_objects=1, selections=1 )
    # sel = info.get( 'selections' )
    sel = a.getSelection()
    if not sel:
        raise RuntimeError('Select one object in Anatomist before running')
    if len(sel) != 1:
        raise RuntimeError('Select a single object')
    sel = sel[0]
    time = -1
    if self.time is not None:
        time = self.time
    sel.exportTexture(filename=self.output_texture.fullPath(), time=time)
Пример #14
0
def execution(self, context):
    sourceUuid = self.image.uuid(saveMinf=False)
    self.ROI.setMinf('source_volume', str(sourceUuid))

    a = anatomist.Anatomist()
    imageObject = a.loadObject(self.image)

    nodesObjects = []
    if not self.ROI.isReadable():
        regionsObject = a.createGraph(object=imageObject,
                                      name=self.ROI.fullPath(),
                                      filename=self.ROI.fullPath())
        # Create a region
        nodesObjects.append(
            regionsObject.createNode(name='region', duplicate=False))
    else:
        regionsObject = a.loadObject(self.ROI)
        nodesObjects = regionsObject.children

    # Show regions and linked image
    block = a.createWindowsBlock()
    windowC = a.createWindow('Coronal', block=block)
    windowS = a.createWindow('Sagittal', block=block)
    windowA = a.createWindow('Axial', block=block)
    window3 = a.createWindow('3D', block=block)

    # set the referential of the image to all the window and to the roi graph
    ref = imageObject.referential
    if ref != a.centralRef:
        a.assignReferential(
            ref, [windowC, windowS, windowA, window3, regionsObject])

    a.addObjects([imageObject, regionsObject], [windowC, windowS, windowA])
    a.setWindowsControl(windows=[windowC, windowS, windowA],
                        control="PaintControl")
    window3.addObjects([regionsObject])

    if nodesObjects:  # the region must be selected to draw
        a.getDefaultWindowsGroup().addToSelection(nodesObjects)

    rep = context.ask("Click here when finished", "OK", "Cancel", modal=0)
    if rep != 1:
        regionsObject.save(self.ROI.fullPath())
        a.sync()
        # make sure that anatomist has finished to process previous
        # commands

    tm = registration.getTransformationManager()
    tm.copyReferential(self.image, self.ROI)
Пример #15
0
def execution(self, context):
    a = anatomist.Anatomist()
    mesh = a.loadObject(self.mesh)
    func = a.loadObject(self.functional_volume)
    func.setPalette(a.getPalette("Rainbow1-fusion"))
    fusion = a.fusionObjects([mesh, func], method='Fusion3DMethod')
    if self.functional_volume is not None \
            and self.functional_volume.type.isA('Label Volume'):
        a.execute("TexturingParams", objects=[fusion], interpolation='rgb')
    context.write(self.calculation_method)
    if self.calculation_method != 'point' or self.submethod != 'max' \
            or self.depth is not None or self.step is not None:
        a.execute(
            "Fusion3DParams", object=fusion, method=self.calculation_method,
                                 submethod=self.submethod,
                                 depth=self.depth, step=self.step)
    win = a.createWindow('3D')
    win.addObjects([fusion])
    return [mesh, func, fusion, win]
Пример #16
0
def update(dialog):
    try:
        a = anatomist.Anatomist()
        if dialog.view is None:
            mri = dialog.getValue('mri')
            if mri is not None:
                print(list(globals().keys()))
                dialog.view = a.viewActivationsOnMRI(mri,
                                                     dialog.Zmap,
                                                     dialog.getValue('matrix'),
                                                     both=0)
        else:
            self.transformation = a.createTransformation(
                dialog.getValue('matrix'), )
            dialog.view.updateTransformation(dialog.getValue('matrix'),
                                             dialog.view["refFMRI"],
                                             dialog.view["refMRI"])
    except:
        neuroConfig.showLastException()
Пример #17
0
def save_roi(self, message=None):
    context = self.context
    if not isinstance(message, str) or not message:
        message = 'Save ROI ?'
    rep = context.ask(message, "OK", "Cancel", modal=0)
    if rep != 1:
        self.voigraphnum.save(self.voigraph)
        a = anatomist.Anatomist()
        a.sync()
        # make sure that anatomist has finished to process previous commands
        # a.getInfo()
        context.system('AimsGraphConvert', '-i', self.voigraph, '-o',
                       self.finalgraph, '--volume')
        if self.background_label != 'minimum':
            val = self.background_label
        else:
            val = 0
        context.system('AimsReplaceLevel', '-i',
                       os.path.join(self.fgraphbase + '.data', 'roi_Volume'),
                       '-o', self.label_volume, '-g', -1, '-n', val)
Пример #18
0
    def __init__(self, app=None):
        QtGui.QDialog.__init__(self)
        self.ui = uic.loadUi("locateleds.ui", self)
        self.pb = plasticbrain.PlasticBrain()
        self.ui.startLocaButton.clicked.connect(self.start)
        self.ui.loadMeshButton.clicked.connect(self.loadMesh)
        self.ui.deviceCombo.currentIndexChanged.connect(
            self.updatedDeviceCombo)
        self.ui.saveButton.clicked.connect(self.save)
        self.ui.nextLedButton.clicked.connect(self.nextLed)
        self.ui.previousLedButton.clicked.connect(self.previousLed)
        self.ui.ReceiveLSLButton.clicked.connect(self.ReceiveAndDisplayEEG)
        self.ui.StopReceiveData.clicked.connect(self.StopReceiveData)
        self.a = anatomist.Anatomist('-b')  #Batch mode (hide Anatomist window)
        self.a.onCursorNotifier.add(self.clickHandler)
        pix = QtGui.QPixmap('control.xpm')
        self.app = app
        anatomistControl.cpp.IconDictionary.instance().addIcon(
            'MyControl', pix)
        ad = anatomistControl.cpp.ActionDictionary.instance()
        ad.addAction('MyAction', lambda: MyAction())
        cd = anatomistControl.cpp.ControlDictionary.instance()
        cd.addControl('MyControl', lambda: MyControl(), 25)
        cm = anatomistControl.cpp.ControlManager.instance()
        cm.addControl('QAGLWidget3D', '', 'MyControl')

        self.axWindow = self.a.createWindow('Axial')

        layoutAx = QtGui.QHBoxLayout(self.frame)
        self.axWindow.setParent(self.frame)
        layoutAx.addWidget(self.axWindow.getInternalRep())
        self.currentElec = 0
        self.coords = [
            [0, 0, 0],
        ]
        self.mesh = None
        self.aimsMesh = None
        self.texture = None
        self.currentObj = None
        self.TextObj = None
def execution(self, context):
    a = anatomist.Anatomist()
    selfdestroy = []

    mesh = a.loadObject(self.WM_mesh_in_DWI, duplicate=True)
    selfdestroy.append(mesh)
    mesh.setMaterial(a.Material(diffuse=[0.3, 0.5, 0.7, 1]))

    win3 = a.createWindow('Axial')
    win3.assignReferential(mesh.referential)
    selfdestroy.append(win3)

    # side = self.white_mesh.get('side')
    # if side is not None and side == 'right':
    #     win3.camera(view_quaternion=[0.5, -0.5, -0.5, 0.5])

    if self.T1_to_b0 is not None:
        anat = a.loadObject(self.T1_to_b0)
        selfdestroy.append(anat)
        win3.addObjects([anat])

    win3.addObjects([mesh])

    return selfdestroy
Пример #20
0
def execution(self, context):
    a = anatomist.Anatomist()
    if self.pipeline_mask_nomenclature is not None:
        hie = a.loadObject(self.pipeline_mask_nomenclature)

    context.write('background:', self.background_label)
    if self.background_label != 'minimum':
        mask = context.temporary('GIS image', 'Label Volume')
        context.write('not min')
        context.system('AimsReplaceLevel', '-i',
                       self.label_volume, '-o', mask, '-g',
                       int(self.background_label), '-g', -32767, '-n', -32767,
                       '-n', -32766)
    else:
        mask = self.label_volume
    if self.support_volume:
        vol = self.support_volume
    else:
        vol = mask
    tmpdir = context.temporary('directory')
    voi = os.path.join(tmpdir.fullPath(), 'voi.ima')
    voigraph = os.path.join(tmpdir.fullPath(), 'voigraph.arg')
    fgraphbase = os.path.join(tmpdir.fullPath(), 'finalgraph')
    finalgraph = fgraphbase + '.arg'

    context.system('AimsGraphConvert', '-i', mask.fullPath(), '-o', voigraph,
                   '--bucket')

    imagenum = a.loadObject(vol)
    voigraphnum = a.loadObject(voigraph)
    ref = imagenum.referential
    if ref != a.centralRef:
        voigraphnum.assignReferential(ref)
        windownum = a.createWindow('Axial')
        windownum.assignReferential(ref)
    else:
        windownum = a.createWindow('Axial')
    a.addObjects(objects=[voigraphnum, imagenum], windows=[windownum])

    voigraphnum.setMaterial(a.Material(diffuse=[0.8, 0.8, 0.8, 0.5]))
    # selects the graph
    children = voigraphnum.children
    windownum.group.addToSelection(children)
    windownum.group.unSelect(children[1:])

    del children

    a.execute('SetControl', windows=[windownum], control='PaintControl')
    windownum.showToolbox(True)

    self.context = context
    self.voigraph = voigraph
    self.window = windownum
    self.fgraphbase = fgraphbase
    self.finalgraph = finalgraph
    self.voigraphnum = voigraphnum
    self.finished = False
    ac = mainThreadActions().call(self.add_save_button, windownum)
    if ac:
        self.wait_for_close(windownum)
        import threading
        from soma.qt_gui.qt_backend import Qt
        done = False
        while not done:
            if isinstance(threading.current_thread(), threading._MainThread):
                Qt.qApp.processEvents()
            time.sleep(0.1)
            done = mainThreadActions().call(getattr, self, 'win_deleted')
    else:
        # ac is None, probably socket mode
        self.save_roi(message='Click here when finished')

    # mainThreadActions().call(self.remove_save_button, windownum, ac)
    del self.context
    del self.voigraph
    del self.window
    del self.fgraphbase
    del self.finalgraph
    del self.voigraphnum
Пример #21
0
def execution(self, context):
    a = anatomist.Anatomist()
    return a.viewBias(self.mri)
Пример #22
0
def execution(self, context):
    a = anatomist.Anatomist()
    windows = self.windows()
    if windows:
        a.setReusableWindow(windows)
Пример #23
0
def execution(self, context):

    a = anatomist.Anatomist()

    return a.viewObject(self.epi_series, "Sagittal",
                        a.getPalette("RED TEMPERATURE"))
Пример #24
0
def execution(self, context):
    a = anatomist.Anatomist()
    return a.loadObject(self.graph)
Пример #25
0
def execution(self, context):
    selfdestroy = []
    try:
        with open(self.anim.fullPath(), 'rb') as f:
            code = compile(f.read(), f.name, 'exec')
        six.exec_(code)
        anim = brainvisaAnim
        f.close()
    except:
        raise IOError(self.anim.fullPath()
                      + _t_(' is not a brainvisa/Antomist animation file'))

    a = anatomist.Anatomist()
    win = self.window()
    winlife = MainThreadLife(win)

    context.ask(_t_('Now setup the window (add objects in the window)'),
                _t_('OK'))

    group = win.group

    if not group:
        group = 0

    if self.animation is not None:
        # force window size to multiples of 16
        info = win.getInfos()
        geom = info['view_size']
        if geom is not None and \
           (int(geom[0] / 16) * 16 != geom[0] or int(geom[1] / 16) * 16 != geom[1]):
            w = int(geom[0] / 16 + 1) * 16
            h = int(geom[1] / 16 + 1) * 16
            # dw = w - geom[0]
            # dh = h - geom[1]
            # g = info[ 'geometry' ]
            # g[2] += dw
            # g[3] += dh
            a.execute("WindowConfig", windows=[win], view_size=[w, h])
            # check again
            time.sleep(1)  # let anatomist time to finish resize
            info = win.getInfos()
            geom = info['view_size']
            if geom[0] != w or geom[1] != h:
                context.write('warning: Anatomist refuses to resize its '
                              'window as requested (Qt-3?) - using trick...')
                context.write('target size: ', [w, h])
                context.write('current size: ', geom)
                w1 = w * 2 - geom[0]
                h1 = h * 2 - geom[1]
                context.write('asked size: ', [w1, h1])
                a.execute("WindowConfig", windows=[win],
                          view_size=[w1, h1])
                # last checking...
                time.sleep(1)  # let anatomist time to finish resize
                info = win.getInfos()
                geom = info['view_size']
                if geom[0] != w or geom[1] != h:
                    context.write('Sorry, Anatomist windows are too '
                                  'undisciplined, I can\'t correctly '
                                  'set their size')
                    context.write('current size: ', geom)
                    return

    # temp directory to store images
    tmpdir = context.temporary('Directory')
    tmp = tmpdir.fullPath()
    if self.images_basename is None:
        self.keep_images = 0
        context.write('<font color="#e00000"> <i><b>' + _t_('Warning')
                      + ':</b></i> '
                      + _t_('images_basename field is not filled: I won\'t '
                            'keep generated images') + '</font>')
    if self.keep_images == 0:
        imgbase = os.path.join(tmp, 'anim.jpg')
    else:
        imgbase = os.path.join(
            tmp, os.path.basename(self.images_basename.fullPath()))
    p = imgbase.rfind('.')
    imgpattern = imgbase[:p] + '%04d' + imgbase[p:]

    objects = []
    translationtable = {}
    n = len(anim)
    num = 0

    preloadedFiles = self.preloadfiles(anim)
    # Loop over scenes
    for j in range(n - 1):
        x0 = anim[j]
        x1 = anim[j + 1]
        obj0 = x0.get('objects')
        obj1 = x1.get('objects')
        v0 = x0['view_quaternion']
        v1 = x1['view_quaternion']
        pos0 = x0['observer_position']
        pos = x1['observer_position']
        cpos0 = x0.get('cursor_position')
        cpos = x1.get('cursor_position')
        zoom0 = x0['zoom']
        zoom = x1['zoom']
        s0 = x0['slice_quaternion']
        s1 = x1['slice_quaternion']
        steps = x1['steps']
        incr = 1. / steps
        params = {}

        # manage objects
        if self.use_recorded_objects and obj1:
            # Find files that are to add/remove/select/deselect to the window
            # (check the differences between the new image and the previous
            # one)
            toadd = []
            for o in obj1:
                if not o in objects and o in preloadedFiles:
                    toadd.append(preloadedFiles[o])
                    objects.append(o)
                    mat1 = obj1[o].get("material")
                    if mat1:
                        preloadedFiles[o].setMaterial(a.Material(**mat1),
                                                      refresh=0)

            toremove = []
            for o in objects:
                if o not in obj1:
                    toremove.append(preloadedFiles[o])
                    objects.remove(o)

            tosel = []
            tounsel = []
            for o in obj1:
                if o in preloadedFiles:
                    if o in obj0:
                        sel0 = obj0[o].get("selected", 0)
                    sel1 = obj1[o].get("selected", 0)
                    # Check if the selected state has changed
                    if sel0 != sel1 and sel1:
                        # The object has been selected
                        tosel.append(preloadedFiles[o])
                    else:
                        # else it has been deselected
                        tounsel.append(preloadedFiles[o])

            if toremove:
                win.removeObjects(toremove)
            if toadd:
                win.addObjects(toadd)
            if tosel:
                group.addToSelection(tosel)
            if tounsel:
                group.unSelect(tounsel)

        # play anim
        for i in range(steps):
            if self.use_recorded_objects and obj0 and obj1:
                for o in obj1:
                    if o in obj0 and o in preloadedFiles:
                        no = preloadedFiles[o]
                        # material
                        mat0 = obj0[o].get('material')
                        mat1 = obj1[o].get('material')
                        if mat0 and mat1:
                            amb0 = mat0['ambient']
                            amb1 = mat1['ambient']
                            dif0 = mat0['diffuse']
                            dif1 = mat1['diffuse']
                            emi0 = mat0['emission']
                            emi1 = mat1['emission']
                            spe0 = mat0['specular']
                            spe1 = mat1['specular']
                            shi0 = mat0['shininess']
                            shi1 = mat1['shininess']

                            no.setMaterial(a.Material(
                                ambient=[
                                amb0[0] * (
                                    1 - incr * i) + amb1[0] * incr * i,
                                    amb0[1] * (
                                        1 - incr * i) + amb1[1] * incr * i,
                                           amb0[2] * (
                                               1 - incr * i) + amb1[
                                                   2] * incr * i,
                                           amb0[3] * (
                                               1 - incr * i) + amb1[
                                                   3] * incr * i],
                                       diffuse=[
                                           dif0[0] * (
                                               1 - incr * i) + dif1[
                                                   0] * incr * i,
                                           dif0[1] * (
                                               1 - incr * i) + dif1[
                                                   1] * incr * i,
                                           dif0[2] * (
                                               1 - incr * i) + dif1[
                                                   2] * incr * i,
                                           dif0[3] * (
                                               1 - incr * i) + dif1[
                                                   3] * incr * i],
                                       emission=[
                                           emi0[0] * (
                                               1 - incr * i) + emi1[
                                                   0] * incr * i,
                                           emi0[1] * (
                                               1 - incr * i) + emi1[
                                                   1] * incr * i,
                                           emi0[2] * (
                                               1 - incr * i) + emi1[
                                                   2] * incr * i,
                                           emi0[3] * (
                                               1 - incr * i) + emi1[
                                                   3] * incr * i],
                                       specular=[
                                           spe0[0] * (
                                               1 - incr * i) + spe1[
                                                   0] * incr * i,
                                           spe0[1] * (
                                               1 - incr * i) + spe1[
                                                   1] * incr * i,
                                           spe0[2] * (
                                               1 - incr * i) + spe1[
                                                   2] * incr * i,
                                           spe0[3] * (
                                               1 - incr * i) + spe1[
                                                   3] * incr * i],
                                       shininess=shi0 * (
                                           1 - incr * i) + shi1 * incr * i),
                                refresh=0
                            )
                        # slice info
                        sl0 = obj0[o].get('slice_quaternion')
                        sl1 = obj1[o].get('slice_quaternion')
                        opos0 = obj0[o].get('slice_position')
                        opos1 = obj1[o].get('slice_position')
                        if sl0 and sl1:
                            sl0 = aims.Point4df(sl0)
                            sl1 = aims.Point4df(sl1)
                            opos0 = aims.Point3df(opos0)
                            opos1 = aims.Point3df(opos1)
                            a.execute('SliceParams', objects=[no],
                                      quaternion=sl0 *
                                      (1 - incr * i) + sl1 * incr * i,
                                      position=opos0 * (1 - incr * i) + opos1 * incr * i)

                        # palette

            params = {
                'zoom': zoom0 * (1 - incr * i) + zoom * incr * i,
                'view_quaternion':
                quaternion.Quaternion((
                                      v0[0] * (1 - incr * i) + v1[
                                      0] * incr * i,
                                      v0[1] * (1 - incr * i) + v1[
                                      1] * incr * i,
                                      v0[2] * (1 - incr * i) + v1[
                                      2] * incr * i,
                                      v0[3] * (1 - incr * i) + v1[3] * incr * i
                                      )).normalized().vector(),
                'observer_position': (
                    pos0[0] * (1 - incr * i) + pos[0] * incr * i,
                    pos0[1] * (1 - incr * i) + pos[1] * incr * i,
                    pos0[2] * (1 - incr * i) + pos[2] * incr * i),
                'slice_quaternion':
                quaternion.Quaternion((
                                      s0[0] * (1 - incr * i) + s1[
                                      0] * incr * i,
                                      s0[1] * (1 - incr * i) + s1[
                                      1] * incr * i,
                                      s0[2] * (1 - incr * i) + s1[
                                      2] * incr * i,
                                      s0[3] * (1 - incr * i) + s1[3] * incr * i
                                      )).normalized().vector(),
                'force_redraw': 1,
            }
            if cpos and cpos0:
                params['cursor_position'] = (
                    cpos0[0] * (1 - incr * i) + cpos[0] * incr * i,
                    cpos0[1] * (1 - incr * i) + cpos[1] * incr * i,
                    cpos0[2] * (1 - incr * i) + cpos[2] * incr * i,
                    cpos0[3] * (1 - incr * i) + cpos[3] * incr * i)
            win.camera(**params)
            # if i == 0 and j == 0 and \
              #( self.animation is not None or self.keep_images ):
                # get anatomist to record mode
                # a.execute("WindowConfig", windows=[win], record_mode=1,
                  # record_basename=imgbase )
            if self.animation is not None or self.keep_images:
                # get a snapshot
                a.execute("WindowConfig", windows=[win],
                          snapshot=imgpattern % num)
                num += 1
        # last step
        params = {
            'zoom': zoom,
            'view_quaternion':
            quaternion.Quaternion((v1[0], v1[1], v1[2], v1[3]
                                   )).normalized().vector(),
            'observer_position': (pos[0], pos[1], pos[2]),
            'slice_quaternion':
            quaternion.Quaternion((s1[0], s1[1], s1[2], s1[3]
                                   )).normalized().vector(),
            #'force_redraw' : 1
        }
        if cpos and cpos0:
            params['cursor_position'] = cpos
        win.camera(**params)
        if self.animation is not None or self.keep_images:
            # get a snapshot
            a.execute("WindowConfig", windows=[win],
                      snapshot=imgpattern % num)
            num += 1

    print('loop done')
    if self.animation is not None or self.keep_images:
        # a.execute("WindowConfig", windows=[win], record_mode = 0 )
        # This is needed to wait for Anatomist to finish what it is doing
        a.sync()
        # a.getInfo()
    print('last sync done')
    del win  # we don't need the window any longer
    del winlife
    print('window released')

    if self.animation is not None:
        if len(mpegConfig.findEncoders()) != 0:
            # make sure anatomist has finished its work
            a.sync()
            # a.getInfo()
            context.write('temp dir: ', tmp)
            context.write('imgbase: ', imgbase)
            inputs = os.listdir(tmp)
            inputs.sort()
            for i in range(len(inputs)):
                inputs[i] = os.path.join(tmp, inputs[i])
            context.write('num images: ', len(inputs))
            # context.ask( 'check ' + tmp, 'OK' )
            # context.write( 'encoder:', self.encoder )
            # context.write( 'encoding:', self.encoding )
            self._executionNode.mpegEncode.images = inputs
            self._executionNode.run(context)
        else:
            context.warning('No animation encorder available - '
                            'skipping the encoding step')
    if self.keep_images:
        context.write('Moving images...')
        inputs = os.listdir(tmp)
        context.write('images:', len(inputs))
        dst = os.path.dirname(self.images_basename.fullPath())
        for i in range(len(inputs)):
            s = os.path.join(tmp, inputs[i])
            d = os.path.join(dst, inputs[i])
            # context.write( 'move: ', s, ' -> ', d )
            try:
                os.rename(s, d)
            except:
                # context.write( 'move failed, trying to copy' )
                try:
                    shutil.copy(s, d)
                except:
                    context.write('can\'t copy')
                os.unlink(s)

    return(selfdestroy)
Пример #26
0
def execution(self, context):
    a = anatomist.Anatomist()
    views = []
    for m in self.mesh:
        views.append(a.viewMesh(m))
    return views
Пример #27
0
def execution(self, context):
    selfdestroy = []
    a = anatomist.Anatomist()
    # a.eventFilter( default_filtering = 0 )
    win = self.window()

    context.write(
        _t_('Now setup the window (add objects in the window and '
            'set its starting point of view)'))

    group = win.group

    positions = []
    steps = 100

    while 1:
        # r = context.ask( 'Set next point of view', 'OK', 'Stop' )
        # dialog box
        dial = context.dialog(1, 'Set next point of view',
                              Signature('steps', Number()), _t_('OK'),
                              _t_('Stop'))
        dial.setValue('steps', steps)
        r = dial.call()
        if r != 0:
            break
        steps = dial.getValue('steps')
        info = win.getInfos()
        quat = info['view_quaternion']
        pos = info['observer_position']
        cpos = info['position']
        zoom = info['zoom']
        slicequat = info['slice_quaternion']
        a.importObjects()
        objects = win.objects
        objectsInfos = {}
        for o in objects:
            infos = o.getInfos()
            sel = infos.get('selected_in_groups')
            if sel and group in sel:
                infos['selected'] = 1
            objectsInfos[o.name] = infos
        positions.append({
            'view_quaternion': quat,
            'observer_position': pos,
            'cursor_position': cpos,
            'zoom': zoom,
            'slice_quaternion': slicequat,
            'steps': steps,
            'objects': objectsInfos
        })
        if len(positions) >= 2:
            v0 = quat0
            v1 = quat
            s0 = slicequat0
            s1 = slicequat
            incr = 1. / (steps - 1)
            for i in six.moves.xrange(steps):
                win.camera(
                    zoom=zoom0 * (1 - incr * i) + zoom * incr * i,
                    view_quaternion=quaternion.Quaternion(
                        (v0[0] * (1 - incr * i) + v1[0] * incr * i,
                         v0[1] * (1 - incr * i) + v1[1] * incr * i,
                         v0[2] * (1 - incr * i) + v1[2] * incr * i,
                         v0[3] * (1 - incr * i) +
                         v1[3] * incr * i)).normalized().vector(),
                    observer_position=(pos0[0] * (1 - incr * i) +
                                       pos[0] * incr * i, pos0[1] *
                                       (1 - incr * i) + pos[1] * incr * i,
                                       pos0[2] * (1 - incr * i) +
                                       pos[2] * incr * i),
                    cursor_position=(cpos0[0] * (1 - incr * i) +
                                     cpos[0] * incr * i, cpos0[1] *
                                     (1 - incr * i) + cpos[1] * incr * i,
                                     cpos0[2] * (1 - incr * i) +
                                     cpos[2] * incr * i),
                    slice_quaternion=quaternion.Quaternion(
                        (s0[0] * (1 - incr * i) + s1[0] * incr * i,
                         s0[1] * (1 - incr * i) + s1[1] * incr * i,
                         s0[2] * (1 - incr * i) + s1[2] * incr * i,
                         s0[3] * (1 - incr * i) +
                         s1[3] * incr * i)).normalized().vector(),
                )
        quat0 = copy.copy(quat)
        pos0 = copy.copy(pos)
        cpos0 = copy.copy(cpos)
        zoom0 = zoom
        slicequat0 = copy.copy(slicequat)
        objects0 = copy.copy(objectsInfos)

    # context.write( self.output_anim )
    if self.output_anim is not None:
        f = open(self.output_anim.fullPath(), 'w')
        f.write('brainvisaAnim = ')
        f.write(repr(positions))
        f.close()
    return selfdestroy
Пример #28
0
def execution(self, context):
    a = anatomist.Anatomist()
    views = []
    for v in self.volumes:
        views.append(a.viewObject(v))
    return views
Пример #29
0
def execution(self, context):
    a = anatomist.Anatomist()
    return a.viewMesh(self.read)