Example #1
0
def axes(*args, **kwargs):
    """
    Add an axis at positon rect specified by

      axes() by itself creates a default full window axis

      axes(rect, axisbg='w') where rect=[left, bottom, width, height] in
        normalized (0,1) units background is the background color for
        the axis, default white

      axes(h, axisbg='w') where h is an axes instance makes h the
        current axis An Axes instance is returned

    axisbg is a color format string which sets the background color of
    the axes (default white)
    """

    nargs = len(args)
    if args==0: return subplot(111)
    if nargs>1:
        error_msg('Only one non keyword arg to axes allowed')

    arg = args[0]

    if isinstance(arg, Axes):
        Gcf().get_current_figwin().set_current_axes(arg)
        return arg
    else:
        rect = arg
        return Gcf().get_current_figwin().add_axes(
            rect=rect, **kwargs)
    def add_segment(self, button):
        if not self.imageData:
            error_msg("Cannot create surface. Image data of surface renderer is not set.")
            return
        if self.nsurf==0:
            self.__adjust_scrollbar_threshold_for_data()
        self.nsurf +=1

        intensity = self.__calculate_intensity_threshold()
        if intensity is None: return

        name = self.__create_segment_name(self.nsurf)
        if (not name) or name=="":
            return

        tree_iter = self.tree_surf.append(None)
        self.tree_surf.set(tree_iter, 0,self.nsurf, 1, name)
        
        self.__update_treeview_visibility()

        self.paramd[self.nsurf] = SurfParams(self.imageData, intensity, self.lastColor)
        params = self.paramd[self.nsurf]
        if self.nsurf==1:
            self.picker_surface_id = params.uuid
        params.label = name
        params.intensity = intensity
        params.set_color(self.lastColor, self.lastColorName)
        params.update_properties()

        self.render()
Example #3
0
def axes(*args, **kwargs):
    """
    Add an axis at positon rect specified by

      axes() by itself creates a default full window axis

      axes(rect, axisbg='w') where rect=[left, bottom, width, height] in
        normalized (0,1) units background is the background color for
        the axis, default white

      axes(h, axisbg='w') where h is an axes instance makes h the
        current axis An Axes instance is returned

    axisbg is a color format string which sets the background color of
    the axes (default white)
    """

    nargs = len(args)
    if args == 0: return subplot(111)
    if nargs > 1:
        error_msg('Only one non keyword arg to axes allowed')

    arg = args[0]

    if isinstance(arg, Axes):
        Gcf().get_current_figwin().set_current_axes(arg)
        return arg
    else:
        rect = arg
        return Gcf().get_current_figwin().add_axes(rect=rect, **kwargs)
    def add_roi(self,*args):
        dialog = gtk.FileSelection('Choose filename for ROI mask')
        dialog.set_filename(shared.get_last_dir())
        dialog.show()
        response = dialog.run()
        if response==gtk.RESPONSE_OK:
            fname = dialog.get_filename()
            dialog.destroy()
            try: 
                #Actually add ROI 
                self.nroi+=1
                tree_iter = self.tree_roi.append(None)
                self.tree_roi.set(tree_iter,0,self.nroi,1,os.path.split(fname)[1],2,fname,3,True)
                self.__update_treeview_visibility()

                roi_image_reader = vtkNiftiImageReader()
                roi_image_reader.SetFileName(fname)
                roi_image_reader.Update()
                roi_id = self.tree_roi.get(tree_iter,0) 
                self.paramd[roi_id] = RoiParams(roi_image_reader.GetOutput())
                #self.paramd[roi_id].update_pipeline()
                #print self.paramd[roi_id].intensity
                shared.set_file_selection(fname)
            except IOError:
                error_msg(
                    'Could not load ROI mask from %s' % fname, 
                    )
            finally:
                self.__update_treeview_visibility()
        else: dialog.destroy()
        self.render()
    def load_image(self, *args):
        if debug:
            print "loc3djr_maintoolbar.load_image()"
        debug = False
        reader = None

        pars = None
        
        if debug:
            reader = vtk.vtkImageReader2()
            reader.SetDataScalarTypeToUnsignedShort()
            reader.SetDataByteOrderToLittleEndian()
            reader.SetFileNameSliceOffset(120)
            reader.SetDataExtent(0, 511, 0, 511, 0, 106)
            reader.SetFilePrefix('/home/jdhunter/seizure/data/ThompsonK/CT/raw/1.2.840.113619.2.55.1.1762864819.1957.1074338393.')
            reader.SetFilePattern( '%s%d.raw')
            reader.SetDataSpacing(25.0/512, 25.0/512, 0.125 )

            reader.Update()
        else:
    
            dlg = widgets['dlgReader']

            response = dlg.run()

            if response == gtk.RESPONSE_OK:
                try: reader = widgets.reader
                except AttributeError: 
                    pars = widgets.get_params()
                    pars = widgets.validate(pars)
                    if pars is None:
                        error_msg('Could not validate the parameters', dlg)
                        return
                    reader = widgets.get_reader(pars)
                pars = widgets.get_params()
                pars = widgets.validate(pars)
                
            dlg.hide()


        if debug:
            print "reader=", reader
        if not reader:
            if debug:
                print "hit cancel, see if we can survive"
        else:
            imageData = reader.GetOutput()
            if debug:
                print "pars=", pars
                print "loc3djr_maintoolbar.load_image(): reader.GetOutput() is " , imageData
                print "load_image(): imageData.SetSpacing(", reader.GetDataSpacing(), " )"
            imageData.SetSpacing(reader.GetDataSpacing())
            if debug:
                print "calling EventHandler().notify('set image data', imageData)"
            EventHandler().notify('set image data', imageData)
            if type(reader) == vtkNiftiImageReader:
                if debug:
                    print "calling EventHandler().setNifti()"
                #XXX EventHandler().setNifti(reader.GetFilename())
                EventHandler().setNifti(reader.GetQForm())
Example #6
0
def hist(x, bins=10, noplot=0, normed=0):
    """
    Compute the histogram of x.  bins is either an integer number of
    bins or a sequence giving the bins.  x are the data to be binned.

    if noplot is True, just compute the histogram and return the
    number of observations and the bins as an (n, bins) tuple.

    If noplot is False, compute the histogram and plot it, returning
    n, bins, patches

    If normed is true, the first element of the return tuple will be the
    counts normalized to form a probability distribtion, ie,
    n/(len(x)*dbin)
    
    """
    n,bins = mlab.hist(x, bins, normed)
    width = bins[1]-bins[0]
    if noplot: return n, bins
    else:
        try:
            patches = gca().bar(bins, n, width=width)
        except ValueError, msg:
            msg = raise_msg_to_str(msg)
            error_msg(msg)
            raise RuntimeError, msg
Example #7
0
def errorbar(x, y, e, u=None, fmt='b-'):
    """

    Plot x versus y with error bars in e.  if u is not None, then u
    gives the upper error bars and e gives the lower error bars.
    Otherwise e the error bars are symmetrix about y and given in the
    array e.
    
    fmt is the plot format symbol for y

    Return value is a length 2 tuple.  The first element is a list of
    y symbol lines.  The second element is a list of error bar lines.
    
    """

    l0 = plot(x, y, fmt)

    e = to_arrays(Float, e)
    if u is None: u = e
    upper = y + u
    lower = y - e
    width = (max(x) - min(x)) * 0.005
    a = gca()
    try:
        l1 = a.vlines(x, y, lower)
        l2 = a.vlines(x, y, upper)
        l3 = a.hlines(upper, x - width, x + width)
        l4 = a.hlines(lower, x - width, x + width)
    except ValueError, msg:
        msg = raise_msg_to_str(msg)
        error_msg(msg)
        raise RuntimeError, msg
Example #8
0
def errorbar(x, y, e, u=None, fmt='b-'):
    """

    Plot x versus y with error bars in e.  if u is not None, then u
    gives the upper error bars and e gives the lower error bars.
    Otherwise e the error bars are symmetrix about y and given in the
    array e.
    
    fmt is the plot format symbol for y

    Return value is a length 2 tuple.  The first element is a list of
    y symbol lines.  The second element is a list of error bar lines.
    
    """
    
    l0 = plot(x,y,fmt)

    e = to_arrays(Float, e)
    if u is None: u = e
    upper = y+u
    lower = y-e
    width = (max(x)-min(x))*0.005
    a = gca()
    try: 
        l1 = a.vlines(x, y, lower)
        l2 = a.vlines(x, y, upper)
        l3 = a.hlines(upper, x-width, x+width)
        l4 = a.hlines(lower, x-width, x+width)
    except ValueError, msg:
        msg = raise_msg_to_str(msg)
        error_msg(msg)
        raise RuntimeError, msg
Example #9
0
def hist(x, bins=10, noplot=0, normed=0):
    """
    Compute the histogram of x.  bins is either an integer number of
    bins or a sequence giving the bins.  x are the data to be binned.

    if noplot is True, just compute the histogram and return the
    number of observations and the bins as an (n, bins) tuple.

    If noplot is False, compute the histogram and plot it, returning
    n, bins, patches

    If normed is true, the first element of the return tuple will be the
    counts normalized to form a probability distribtion, ie,
    n/(len(x)*dbin)
    
    """
    n, bins = mlab.hist(x, bins, normed)
    width = bins[1] - bins[0]
    if noplot: return n, bins
    else:
        try:
            patches = gca().bar(bins, n, width=width)
        except ValueError, msg:
            msg = raise_msg_to_str(msg)
            error_msg(msg)
            raise RuntimeError, msg
    def load_image(self, *args):
        print "loc3djr_maintoolbar.load_image()"
        debug = False
        reader = None

        pars = None

        if debug:
            reader = vtk.vtkImageReader2()
            reader.SetDataScalarTypeToUnsignedShort()
            reader.SetDataByteOrderToLittleEndian()
            reader.SetFileNameSliceOffset(120)
            reader.SetDataExtent(0, 511, 0, 511, 0, 106)
            reader.SetFilePrefix(
                '/home/jdhunter/seizure/data/ThompsonK/CT/raw/1.2.840.113619.2.55.1.1762864819.1957.1074338393.'
            )
            reader.SetFilePattern('%s%d.raw')
            reader.SetDataSpacing(25.0 / 512, 25.0 / 512, 0.125)

            reader.Update()
        else:

            dlg = widgets['dlgReader']

            response = dlg.run()

            if response == gtk.RESPONSE_OK:
                try:
                    reader = widgets.reader
                except AttributeError:
                    pars = widgets.get_params()
                    pars = widgets.validate(pars)
                    if pars is None:
                        error_msg('Could not validate the parameters', dlg)
                        return
                    reader = widgets.get_reader(pars)
                pars = widgets.get_params()
                pars = widgets.validate(pars)

            dlg.hide()

        print "reader=", reader
        if not reader:
            print "hit cancel, see if we can survive"
        else:
            imageData = reader.GetOutput()
            print "pars=", pars
            print "loc3djr_maintoolbar.load_image(): reader.GetOutput() is ", imageData
            print "load_image(): imageData.SetSpacing(", reader.GetDataSpacing(
            ), " )"
            imageData.SetSpacing(reader.GetDataSpacing())
            print "calling EventHandler().notify('set image data', imageData)"
            EventHandler().notify('set image data', imageData)
            if type(reader) == vtkNiftiImageReader:
                print "calling EventHandler().setNifti()"
                #XXX EventHandler().setNifti(reader.GetFilename())
                EventHandler().setNifti(reader.GetQForm())
Example #11
0
 def take_all_shots(self, *args):
     """For each PyLocatorRenderWindow in list, take a SS"""
     if len(self._sts)==0:
         error_msg("Cannot take screenshots: \nNo instances registered.")
         return False
     fn_pattern = self.entryFn.get_text()
     mag = self.sbMag.get_value()
     for st in self._sts:
         st.take_screenshot(fn_pattern, mag)
Example #12
0
 def take_shot(self, button, idx):
     """For one PyLocatorRenderWindow, take a SS"""
     #print "take_shot", args
     if len(self._sts)==0:
         error_msg("Cannot take screenshots: \nNo instances registered.")
         return False
     fn_pattern = self.entryFn.get_text()
     mag = self.sbMag.get_value()
     self._sts[idx].take_screenshot(fn_pattern, mag)
Example #13
0
 def ok_clicked(w):
     fname = dialog.get_filename()
     shared.set_file_selection(fname)
     try: EventHandler().save_registration_as(fname)
     except IOError:
         error_msg('Could not save data to %s' % fname,
                   )
     else:
         self.fileName = fname
         dialog.destroy()
 def ok_clicked(w):
     fname = dialog.get_filename()
     shared.set_file_selection(fname)
     try:
         EventHandler().save_registration_as(fname)
     except IOError:
         error_msg('Could not save data to %s' % fname, )
     else:
         self.fileName = fname
         dialog.destroy()
Example #15
0
 def propose_fn(self,*args):
     mri_fn = shared.lastSel
     if len(mri_fn) == 0:
         error_msg("Cannot propose filename: \nFilename of MRI unknown")
         return False
     for suff in [".nii.gz",".nii"]:
         if mri_fn.endswith(suff):
             mri_fn = mri_fn[:-len(suff)]
     self.entryFn.set_text(mri_fn+"_pylocator%03i.png")
     return True
Example #16
0
def plot(*args, **kwargs):
    """
    plot lines.  *args is a variable length argument, allowing for
    multiple x, y pairs with an optional format string.  For
    example, all of the following are legal
        
      plot(x,y)            # plot Numeric arrays y vs x
      plot(x,y, 'bo')      # plot Numeric arrays y vs x with blue circles
      plot(y)              # plot y using x = arange(len(y))
      plot(y, 'r+')        # ditto with red plusses

    An arbitrary number of x, y, fmt groups can be specified, as in 

      a.plot(x1, y1, 'g^', x2, y2, 'l-')  

    Return value is a list of lines that were added

    The following line styles are supported:

      -  : solid line
      -- : dashed line
      -. : dash-dot line
      :  : dotted line
      |  : verical lines
      .  : points
      ,  : pixels
      o  : circle symbols
      ^  : triangle up symbols
      v  : triangle down symbols
      <  : triangle left symbols
      >  : triangle right symbols
      s  : square symbols
      +  : plus symbols

    The following color strings are supported

      b  : blue
      g  : green
      r  : red
      c  : cyan
      m  : magenta
      y  : yellow
      k  : black 
      w  : white

   Line styles and colors are combined in a single format string
   

    """

    try:
        lines = gca().plot(*args, **kwargs)
    except ValueError, msg:
        msg = raise_msg_to_str(msg)
        error_msg(msg)
Example #17
0
def plot(*args, **kwargs):
    """
    plot lines.  *args is a variable length argument, allowing for
    multiple x, y pairs with an optional format string.  For
    example, all of the following are legal
        
      plot(x,y)            # plot Numeric arrays y vs x
      plot(x,y, 'bo')      # plot Numeric arrays y vs x with blue circles
      plot(y)              # plot y using x = arange(len(y))
      plot(y, 'r+')        # ditto with red plusses

    An arbitrary number of x, y, fmt groups can be specified, as in 

      a.plot(x1, y1, 'g^', x2, y2, 'l-')  

    Return value is a list of lines that were added

    The following line styles are supported:

      -  : solid line
      -- : dashed line
      -. : dash-dot line
      :  : dotted line
      |  : verical lines
      .  : points
      ,  : pixels
      o  : circle symbols
      ^  : triangle up symbols
      v  : triangle down symbols
      <  : triangle left symbols
      >  : triangle right symbols
      s  : square symbols
      +  : plus symbols

    The following color strings are supported

      b  : blue
      g  : green
      r  : red
      c  : cyan
      m  : magenta
      y  : yellow
      k  : black 
      w  : white

   Line styles and colors are combined in a single format string
   

    """
    
    try: lines =  gca().plot(*args, **kwargs)
    except ValueError, msg:
        msg = raise_msg_to_str(msg)
        error_msg(msg)
Example #18
0
def figure(num=1):
    """
    Create a new figure and return a handle to it

    If figure(num) already exists, make it active and return the
    handle to it.    
    """
    if num == 0:
        error_msg('Figure number can not be 0.\n' + \
                  'Hey, give me a break, this is matlab compatability')
        return
    return Gcf(num).get_current_figwin().figure
Example #19
0
def figure(num=1):
    """
    Create a new figure and return a handle to it

    If figure(num) already exists, make it active and return the
    handle to it.    
    """
    if num==0:
        error_msg('Figure number can not be 0.\n' + \
                  'Hey, give me a break, this is matlab compatability')
        return 
    return Gcf(num).get_current_figwin().figure
Example #20
0
    def load_params_from_file(self, fname):
       dialog = self['dlgReader']
       try: s = file(fname, 'r').read()
       except IOError:
          error_msg('Could not open %s for reading' % fname, dialog)
          return 0

       p = Params()
       p.from_string(s)
       
       widgets.set_params(p)     

       widgets['entryInfoFile'].set_text(fname)
       return 1
Example #21
0
def bar(*args, **kwargs):
    """
    bar(self, x, y, width=0.8)

    Make a bar plot with rectangles at x, x+width, 0, y
    x and y are Numeric arrays

    Return value is a list of Rectangle patch instances
    """

    try: patches =  gca().bar(*args, **kwargs)
    except ValueError, msg:
        msg = raise_msg_to_str(msg)
        error_msg(msg)
        raise RuntimeError, msg
Example #22
0
    def load_params_from_file(self, fname):
        dialog = self['dlgReader']
        try:
            s = file(fname, 'r').read()
        except IOError:
            error_msg('Could not open %s for reading' % fname, dialog)
            return 0

        p = Params()
        p.from_string(s)

        widgets.set_params(p)

        widgets['entryInfoFile'].set_text(fname)
        return 1
Example #23
0
def vlines(*args, **kwargs):    
    """
    lines =  vlines(x, ymin, ymax, color='k'):

    Plot vertical lines at each x from ymin to ymax.  ymin or ymax
    can be scalars or len(x) numpy arrays.  If they are scalars,
    then the respective values are constant, else the heights of
    the lines are determined by ymin and ymax

    Returns a list of lines that were added
    """
    try: lines =  gca().vlines(*args, **kwargs)
    except ValueError, msg:
        msg = raise_msg_to_str(msg)
        error_msg(msg)
        raise RuntimeError, msg
Example #24
0
def bar(*args, **kwargs):
    """
    bar(self, x, y, width=0.8)

    Make a bar plot with rectangles at x, x+width, 0, y
    x and y are Numeric arrays

    Return value is a list of Rectangle patch instances
    """

    try:
        patches = gca().bar(*args, **kwargs)
    except ValueError, msg:
        msg = raise_msg_to_str(msg)
        error_msg(msg)
        raise RuntimeError, msg
        def coplanar(self):
            numSelected = EventHandler().get_num_selected()
            if numSelected !=3:
                error_msg("You must first select exactly 3 markers",
                          )
                return

            # SetNormal is missing from the 4.2 python API so this is
            # a long winded way of setting the pw to intersect 3
            # selected markers
            m1, m2, m3 = EventHandler().get_selected()

            p1 = m1.get_center()
            p2 = m2.get_center()
            p3 = m3.get_center()
            
            pw = pwo.get_pw()
            planeO = vtk.vtkPlaneSource()
            planeO.SetOrigin(pw.GetOrigin())
            planeO.SetPoint1(pw.GetPoint1())
            planeO.SetPoint2(pw.GetPoint2())
            planeO.Update()

            planeN = vtk.vtkPlaneSource()
            planeN.SetOrigin(p1)
            planeN.SetPoint1(p2)
            planeN.SetPoint2(p3)
            planeN.Update()

            normal = planeN.GetNormal()
            planeO.SetNormal(normal)
            planeO.SetCenter(
                (p1[0] + p2[0] + p3[0])/3,
                (p1[1] + p2[1] + p3[1])/3,
                (p1[2] + p2[2] + p3[2])/3,
                )
            planeO.Update()

            pwxyz = pwo.get_pwxyz()
            pw.SetOrigin(planeO.GetOrigin())
            pw.SetPoint1(planeO.GetPoint1())
            pw.SetPoint2(planeO.GetPoint2())
            pw.UpdatePlacement()
            pwo.update_plane()
            pwo.Render()
            pwxyz.Render()
Example #26
0
def hlines(*args, **kwargs):    
    """
    lines = hlines(self, y, xmin, xmax, fmt='k-')

    plot horizontal lines at each y from xmin to xmax.  xmin or
    xmax can be scalars or len(x) numpy arrays.  If they are
    scalars, then the respective values are constant, else the
    widths of the lines are determined by xmin and xmax

    Returns a list of line instances that were added

    """
    try: lines =  gca().hlines(*args, **kwargs)
    except ValueError, msg:
        msg = raise_msg_to_str(msg)
        error_msg(msg)
        raise RuntimeError, msg
Example #27
0
def vlines(*args, **kwargs):
    """
    lines =  vlines(x, ymin, ymax, color='k'):

    Plot vertical lines at each x from ymin to ymax.  ymin or ymax
    can be scalars or len(x) numpy arrays.  If they are scalars,
    then the respective values are constant, else the heights of
    the lines are determined by ymin and ymax

    Returns a list of lines that were added
    """
    try:
        lines = gca().vlines(*args, **kwargs)
    except ValueError, msg:
        msg = raise_msg_to_str(msg)
        error_msg(msg)
        raise RuntimeError, msg
Example #28
0
def hlines(*args, **kwargs):
    """
    lines = hlines(self, y, xmin, xmax, fmt='k-')

    plot horizontal lines at each y from xmin to xmax.  xmin or
    xmax can be scalars or len(x) numpy arrays.  If they are
    scalars, then the respective values are constant, else the
    widths of the lines are determined by xmin and xmax

    Returns a list of line instances that were added

    """
    try:
        lines = gca().hlines(*args, **kwargs)
    except ValueError, msg:
        msg = raise_msg_to_str(msg)
        error_msg(msg)
        raise RuntimeError, msg
Example #29
0
    def on_buttonDir_clicked(button=None):

        dialog = gtk.FileSelection('Choose image file directory')
        dialog.set_filename(shared.get_last_dir())
        dialog.set_transient_for(widgets['dlgReader'])
        dialog.set_filename(widgets['entryDir'].get_text())
        response = dialog.run()

        if response == gtk.RESPONSE_OK:
            dir = dialog.get_filename()
            if os.path.isdir(dir):
                widgets['entryDir'].set_text(dir)
                shared.set_file_selection(dir)
                dialog.destroy()
            else:
                error_msg('%s is not a directory' % dir, dialog)
        else:
            dialog.destroy()
Example #30
0
def scatter(*args, **kwargs):
    """

    scatter(self, x, y, s=None, c='b'):

    Make a scatter plot of x versus y.  s is a size (in data
    coords) and can be either a scalar or an array of the same
    length as x or y.  c is a color and can be a single color
    format string or an length(x) array of intensities which will
    be mapped by the colormap jet.        

    If size is None a default size will be used
    """

    try: patches =  gca().scatter(*args, **kwargs)
    except ValueError, msg:
        msg = raise_msg_to_str(msg)
        error_msg(msg)
        raise RuntimeError, msg
Example #31
0
    def on_buttonDir_clicked(button=None):

            
        dialog = gtk.FileSelection('Choose image file directory')
        dialog.set_filename(shared.get_last_dir())
        dialog.set_transient_for(widgets['dlgReader'])
        dialog.set_filename(widgets['entryDir'].get_text())
        response = dialog.run()

        if response == gtk.RESPONSE_OK:
            dir = dialog.get_filename()
            if os.path.isdir(dir):
                widgets['entryDir'].set_text(dir)
                shared.set_file_selection(dir)
                dialog.destroy()
            else:            
                error_msg('%s is not a directory' % dir, dialog)
        else:
           dialog.destroy()
Example #32
0
    def show_correlation_props(self, button):
        dialog = gtk.FileSelection('Choose filename for correlation data')
        dialog.set_filename(shared.get_last_dir())

        dialog.show()
        response = dialog.run()

        if response==gtk.RESPONSE_OK:
            fname = dialog.get_filename()
            dialog.destroy()
            try: EventHandler().load_correlation_from(fname)
            except IOError:
                error_msg(
                    'Could not load correlation from %s' % fname, 
                    )
            
            else:
                shared.set_file_selection(fname)
                self.fileName = fname
        else: dialog.destroy()
Example #33
0
def scatter(*args, **kwargs):
    """

    scatter(self, x, y, s=None, c='b'):

    Make a scatter plot of x versus y.  s is a size (in data
    coords) and can be either a scalar or an array of the same
    length as x or y.  c is a color and can be a single color
    format string or an length(x) array of intensities which will
    be mapped by the colormap jet.        

    If size is None a default size will be used
    """

    try:
        patches = gca().scatter(*args, **kwargs)
    except ValueError, msg:
        msg = raise_msg_to_str(msg)
        error_msg(msg)
        raise RuntimeError, msg
    def show_correlation_props(self, button):
        dialog = gtk.FileSelection('Choose filename for correlation data')
        dialog.set_filename(shared.get_last_dir())

        dialog.show()
        response = dialog.run()

        if response == gtk.RESPONSE_OK:
            fname = dialog.get_filename()
            dialog.destroy()
            try:
                EventHandler().load_correlation_from(fname)
            except IOError:
                error_msg('Could not load correlation from %s' % fname, )

            else:
                shared.set_file_selection(fname)
                self.fileName = fname
        else:
            dialog.destroy()
Example #35
0
def axis(*v):
    """
    axis() returns the current axis as a length a length 4 vector

    axis(v) where v= [xmin xmax ymin ymax] sets the min and max of the
    x and y axis limits
    """
    
    try: v[0]
    except IndexError:
        xlim = gca().get_xlim()
        ylim = gca().get_ylim()
        return [xlim[0], xlim[1], ylim[0], ylim[1]]
    
    v = v[0]
    if len(v) != 4:
        error_msg('v must contain [xmin xmax ymin ymax]')
        return 
    gca().set_xlim([v[0], v[1]])
    gca().set_ylim([v[2], v[3]])
    draw_if_interactive()
    def add_segment(self, button):
        'render, man'
        val = self.get_intensity()
        if val is None: return
        name = self.entryName.get_text()
        if not len(name):
            error_msg('You must enter a name in the Intensity tab')
            return

        if not self.paramd.has_key(name):
            self.paramd[name] = SurfParams(self.sr.renderer, self.sr.interactor)

        params = self.paramd[name]
        params.label = name
        params.intensity = val
        params.color = self.lastColor
        params.set_image_data(self.sr.imageData)
        params.update_properties()
        
        self.update_segments_frame() 
        self.update_pipeline_frame()
        self.update_picker_frame()
Example #37
0
def axis(*v):
    """
    axis() returns the current axis as a length a length 4 vector

    axis(v) where v= [xmin xmax ymin ymax] sets the min and max of the
    x and y axis limits
    """

    try:
        v[0]
    except IndexError:
        xlim = gca().get_xlim()
        ylim = gca().get_ylim()
        return [xlim[0], xlim[1], ylim[0], ylim[1]]

    v = v[0]
    if len(v) != 4:
        error_msg('v must contain [xmin xmax ymin ymax]')
        return
    gca().set_xlim([v[0], v[1]])
    gca().set_ylim([v[2], v[3]])
    draw_if_interactive()
Example #38
0
    def save_params_to_file(self, fname):
       """
       Pickle the params to file fname.  If successful return 1
       """

       dialog = self['dlgReader']

       pars = widgets.get_params()
       pars = widgets.validate(pars)
       if pars is None:
          error_msg('Invalid parameters')
          return 0

       try: fh = file(fname, 'w')
       except IOError:
          error_msg('Could not open %s for writing' % fname, dialog)
          return 0


       fh.write(str(pars))
       widgets['entryInfoFile'].set_text(fname)
       return 1
Example #39
0
    def save_params_to_file(self, fname):
        """
       Pickle the params to file fname.  If successful return 1
       """

        dialog = self['dlgReader']

        pars = widgets.get_params()
        pars = widgets.validate(pars)
        if pars is None:
            error_msg('Invalid parameters')
            return 0

        try:
            fh = file(fname, 'w')
        except IOError:
            error_msg('Could not open %s for writing' % fname, dialog)
            return 0

        fh.write(str(pars))
        widgets['entryInfoFile'].set_text(fname)
        return 1
Example #40
0
def subplot(*args):
    """
    Create a subplot command, creating axes with

      subplot(numRows, numCols, plotNum)

    where plotNum=1 is the first plot number and increasing plotNums
    fill rows first.  max(plotNum)==numRows*numCols

    You can leave out the commas if numRows<=numCols<=plotNum<10, as
    in

      subplot(211)    # 2 rows, 1 column, first (upper) plot

    subplot(111) is the default axis
    """
    try:
        Gcf().get_current_figwin().add_subplot(*args)
        a =  gca()
    except ValueError, msg:
        msg = raise_msg_to_str(msg)
        error_msg(msg)
        raise RuntimeError, msg
Example #41
0
def set(h, s, val):
    """
    Set handle h property in string s to value val

    h can be a handle or vector of handles.

    h is an instance (or vector of instances) of a class, eg a Line2D
    or an Axes or AxisText.  if s is 'somename', this function calls

      o.set_somename(val)

    for every instance in o in h
    """
    if not iterable(h): h = [h]
    else: h = flatten(h)
    for o in h:
        try:
            func = 'o.set_%s(val)' % s
            eval(func, {}, {'o': o, 'val': val})
        except ValueError, msg:
            msg = raise_msg_to_str(msg)
            error_msg(msg)
            raise RuntimeError, msg
Example #42
0
    def add_segment(self, button):
        'render, man'
        val = self.get_intensity()
        if val is None: return
        name = self.entryName.get_text()
        if not len(name):
            error_msg('You must enter a name in the Intensity tab')
            return

        if not self.paramd.has_key(name):
            self.paramd[name] = SurfParams(self.sr.renderer,
                                           self.sr.interactor)

        params = self.paramd[name]
        params.label = name
        params.intensity = val
        params.color = self.lastColor
        params.set_image_data(self.sr.imageData)
        params.update_properties()

        self.update_segments_frame()
        self.update_pipeline_frame()
        self.update_picker_frame()
Example #43
0
def set(h, s, val):
    """
    Set handle h property in string s to value val

    h can be a handle or vector of handles.

    h is an instance (or vector of instances) of a class, eg a Line2D
    or an Axes or AxisText.  if s is 'somename', this function calls

      o.set_somename(val)

    for every instance in o in h
    """
    if not iterable(h): h = [h]
    else: h = flatten(h)
    for o in h:
        try: 
            func = 'o.set_%s(val)' % s
            eval(func, {}, {'o': o, 'val' : val})
        except ValueError, msg:
            msg = raise_msg_to_str(msg)
            error_msg(msg)
            raise RuntimeError, msg
Example #44
0
def subplot(*args):
    """
    Create a subplot command, creating axes with

      subplot(numRows, numCols, plotNum)

    where plotNum=1 is the first plot number and increasing plotNums
    fill rows first.  max(plotNum)==numRows*numCols

    You can leave out the commas if numRows<=numCols<=plotNum<10, as
    in

      subplot(211)    # 2 rows, 1 column, first (upper) plot

    subplot(111) is the default axis
    """
    try:
        Gcf().get_current_figwin().add_subplot(*args)
        a = gca()
    except ValueError, msg:
        msg = raise_msg_to_str(msg)
        error_msg(msg)
        raise RuntimeError, msg
Example #45
0
    def validate(self, o):
        dlg = self['dlgReader']

        if o.readerClass != 'vtkNiftiImageReader':
            if len(o.pattern) == 0:
                msg = 'You must supply a number pattern for entry %s.\n' % \
                      self['labelPattern'].get_label() + 'Consider "%d"'
                return error_msg(msg, dlg)

            if o.pattern[0] != '%':
                msg = '%s format string must begin with a %%.\n' % \
                      self['labelPattern'].get_label() + 'Consider "%d"'
                return error_msg(msg, dlg)

        if widgets['radiobuttonDimOther'].get_active():
            dim1, dim2 = o.dimensions
            val = dim1 = str2posint_or_err(dim1, 'Other: dimension 1', dlg)
            if val is None: return None
            val = dim2 = str2posint_or_err(dim2, 'Other: dimension 2', dlg)
            if val is None: return None
            o.dimensions = dim1, dim2

        val = o.first = str2int_or_err(o.first, widgets['labelFirst'], dlg)
        if val is None:
            return None

        val = o.last = str2posint_or_err(o.last, widgets['labelLast'], dlg)
        if val is None: return None

        if o.readerClass != 'vtkNiftiImageReader':
            fnames = self.get_file_names(o)
            for fname in fnames:
                if debug:
                    print "validate(): doing fname ", fname
                if not os.path.exists(fname):
                    return error_msg('Could not find file %s' % fname, dlg)
                if o.readerClass == 'vtkBMPReader':
                    reader = vtk.vtkBMPReader()
                    b = reader.CanReadFile(fname)
                    if not b:
                        return error_msg(
                            'Could not read file %s with reader %s' %
                            (fname, o.readerClass), dlg)
        else:
            if len(o.extension) > 0:
                fname = os.path.join(o.dir, o.pattern + "." + o.extension)
                if not os.path.exists(fname):
                    return error_msg('Could not find file %s' % fname, dlg)
            else:
                fname = o.pattern
                files = os.listdir(o.dir)
                match = False
                for file in files:
                    file = file.split(".")
                    if len(file) > 1:
                        if file[0] == fname:
                            if file[1] in ["nii", "img", "hdr"]:
                                match = True
                                break
                if not match:
                    return error_msg(
                        'Could not find file %s with extension nii, img, hdr [.gz]'
                        % fname, dlg)

        # Depth Field Of View
        val = o.dfov = str2posnum_or_err(o.dfov, widgets['labelDFOV'], dlg)
        if debug:
            print "dfov=", val
        if val is None: return None

        # Spacing between slices
        val = o.spacing = str2posnum_or_err(o.spacing, widgets['labelSpacing'],
                                            dlg)
        if debug:
            print "spacing=", val
        if val is None: return None

        # Size of header
        if o.header == '': o.header = 0
        else:
            val = o.header = str2int_or_err(o.header, widgets['labelHeader'],
                                            dlg)
            if val is None: return None
        if debug:
            print "header=", val

        # Data mask
        if o.mask is not None:
            if o.mask == '': o.mask = None

            else:
                val = o.mask = str2int_or_err(o.mask, widgets['labelMask'],
                                              dlg)
                if val is None: return None
        if debug:
            print "mask=", val

        return o
Example #46
0
 def set_current_axes(self, a):
     if a not in self.axes.values():
         error_msg('Axes is not in current figure')
     self.currentAxis = a
Example #47
0
    def validate(self, o):
        dlg = self['dlgReader']

        if o.readerClass!='vtkNiftiImageReader':
            if len(o.pattern)==0:
                msg = 'You must supply a number pattern for entry %s.\n' % \
                      self['labelPattern'].get_label() + 'Consider "%d"'
                return error_msg(msg, dlg)

            if o.pattern[0]!='%':
                msg = '%s format string must begin with a %%.\n' % \
                      self['labelPattern'].get_label() + 'Consider "%d"'
                return error_msg(msg, dlg)

        if widgets['radiobuttonDimOther'].get_active():
            dim1, dim2 = o.dimensions
            val = dim1 = str2posint_or_err(dim1, 'Other: dimension 1', dlg)
            if val is None: return None
            val = dim2 = str2posint_or_err(dim2, 'Other: dimension 2', dlg)
            if val is None: return None
            o.dimensions = dim1, dim2
            
        val = o.first = str2int_or_err(o.first, widgets['labelFirst'], dlg)
        if val is None:
            return None

        val = o.last = str2posint_or_err(o.last, widgets['labelLast'], dlg)
        if val is None: return None

        if o.readerClass!='vtkNiftiImageReader':
            fnames = self.get_file_names(o)
            for fname in fnames:
                print "validate(): doing fname ", fname
                if not os.path.exists(fname):
                    return error_msg('Could not find file %s' % fname, dlg)
                if o.readerClass=='vtkBMPReader':
                    reader = vtk.vtkBMPReader()
                    b = reader.CanReadFile(fname)
                    if not b:
                        return error_msg('Could not read file %s with reader %s'
                                         % (fname, o.readerClass), dlg)
        else:
            if len(o.extension) > 0:
                fname=os.path.join(o.dir,o.pattern+"."+o.extension)
                if not os.path.exists(fname):
                    return error_msg('Could not find file %s' % fname, dlg)
            else:
                fname=o.pattern
                files=os.listdir(o.dir)
                match=False
                for file in files:
                    file=file.split(".")
                    if len(file)>1:
                        if file[0]==fname:
                            if file[1] in ["nii","img","hdr"]:
                                match=True
                                break
                if not match:
                    return error_msg('Could not find file %s with extension nii, img, hdr [.gz]' % fname, dlg)

        # Depth Field Of View
        val = o.dfov = str2posnum_or_err(o.dfov, widgets['labelDFOV'], dlg)
        print "dfov=", val
        if val is None: return None

        # Spacing between slices
        val = o.spacing = str2posnum_or_err(
            o.spacing, widgets['labelSpacing'], dlg)
        print "spacing=", val
        if val is None: return None

        # Size of header
        if o.header=='': o.header = 0
        else:
           val = o.header = str2int_or_err(
              o.header, widgets['labelHeader'], dlg)
           if val is None: return None
        print "header=", val

        # Data mask
        if o.mask is not None:
           if o.mask=='': o.mask = None

           else:
               val = o.mask = str2int_or_err(
                   o.mask, widgets['labelMask'], dlg)
               if val is None: return None
        print "mask=", val

        return o
Example #48
0
 def checkPickerName():
     if self.pickerName is None:
         error_msg("You must select the pick segment in the Picker tab")
         return False
     return True
Example #49
0
 def checkPickerName():
     if self.pickerName is None:
         error_msg('You must select the pick segment in the Picker tab')
         return False
     return True
Example #50
0
 def set_current_axes(self, a):
     if a not in self.axes.values():
         error_msg('Axes is not in current figure')
     self.currentAxis = a
Example #51
0
 def checkPickerId():
     if not self.picker_id:
         error_msg('Cannot insert marker. Choose surface first.')
         return False
     return True