Beispiel #1
0
class FrameInfo(HasTraits):
    """This holds information about each frame. This is to be used in :class:`Video`
    """
    #: frame index
    index = Range(low='_low', high='_high')
    #: frame time
    time = Property(depends_on='index,fps',
                    editor=RangeEditor(is_float=True,
                                       low_name='object._low_',
                                       high_name='duration'))
    #: duration of the movie
    duration = Float(1.)
    #: frame rate
    fps = Float(1.)
    #: number of frames
    n_frames = Long(1)

    view = View('index', 'time')

    _low = Int(0)
    _high = Property(depends_on='n_frames')
    _low_ = Float(0)

    def _get_time(self):
        return self.index / self.fps

    def _set_time(self, value):
        value = int(round(self.fps * value + 0.5))
        if value > self.n_frames - 1:
            value = self.n_frames - 1
        self.index = value

    def _get__high(self):
        return self.n_frames - 1
Beispiel #2
0
class CirclePainter(AbstractOverlay):
    """用半径为r的圆绘制鼠标轨迹,并调用InPaintDemo的fill_circle()
    在其mask图像上绘制选区。当鼠标松开时,调用InPaintDemo的inpaint()
    进行inpaint图像处理。
    """
    x = Float(-1)  # 当前圆心X轴坐标
    y = Float(-1)  # 当前圆心Y轴坐标
    r = Range(2.0, 20.0, 10.0)  # 圆形半径(数据坐标系)
    event_state = Enum("normal", "drawing")
    track = List()  # 储存鼠标轨迹
    updated = Event()

    def clear_track(self):
        self.track = []
        self.request_redraw()

    def fill_circle(self, event):
        self.x = event.x
        self.y = event.y
        plot = self.component
        x = plot.x_mapper.map_data(event.x)
        y = plot.y_mapper.map_data(event.y)
        self.track.append((self.x, self.y, x, y))
        self.request_redraw()

    def normal_mouse_move(self, event):
        self.x = event.x
        self.y = event.y
        self.request_redraw()

    def normal_left_down(self, event):
        self.event_state = "drawing"
        self.fill_circle(event)

    def drawing_mouse_move(self, event):
        self.fill_circle(event)

    def drawing_left_up(self, event):
        self.event_state = "normal"
        self.updated = True

    def normal_mouse_leave(self, event):
        self.x, self.y = -1, -1
        self.request_redraw()

    def overlay(self, component, gc, view_bounds=None, mode="normal"):
        plot = self.component
        r = plot.x_mapper.map_screen(self.r)

        gc.save_state()
        if self.x > 0 and self.y > 0:
            gc.set_stroke_color((1, 1, 1))
            gc.arc(self.x, self.y, r, 0.0, 2 * np.pi)
            gc.stroke_path()

        gc.set_fill_color((1, 1, 1))
        for x, y, _, _ in self.track:
            gc.arc(x, y, r, 0.0, 2 * np.pi)
        gc.fill_path()
        gc.restore_state()
Beispiel #3
0
class BaseDataSource(HasStrictTraits):

    has_data = Bool(False)  # set True when data is loaded

    description = Str
    kind = data_source_kinds
    voxel_sizes = Tuple(Float(1.0), Float(1.0), Float(1.0))
    pixel_sizes = Tuple(Float(1.0), Float(1.0))

    tables = Dict

    is_image_stack = Bool(True)
    is_image_timeseries = Bool(False)
    is_image_stack_timeseries = Bool(False)

    @property
    def data(self):
        return _data[0]

    @data.setter
    def data(self, data):
        _data[0] = data
        self.has_data = data is not None
        if data is None:
            print '%s.data.setter: removing data' % (self.__class__.__name__)
        else:
            print '%s.data.setter: setting data' % (self.__class__.__name__)

    def _kind_changed(self):
        self.is_image_stack = self.kind == 'image_stack'
        self.is_image_timeseries = self.kind == 'image_timeseries'
        self.is_image_stack_timeseries = self.kind == 'image_stack_timeseries'
Beispiel #4
0
    def render_fields(self):
        #construct traits for each parameter and place in the class dictionary
        params = self.model.get_params()
        class_dict = {}
        #construct default view
        elements = []
        elements.extend([Label("Parameter"), Label("Error"), Label("Fixed?")])
        for param in params:
            pname = param.name
            class_dict["entry_" + pname] = Float(
                param.value)  #get the initial value
            class_dict["err_" + pname] = Float(
                param.error)  #get the initial value
            class_dict["fixed_" + pname] = Bool(
                param.fixed)  #determine if fixed or not
            elements.append(
                Item("entry_" + pname,
                     format_str="%0.4g",
                     show_label=True,
                     label=pname))
            elements.append(
                Item("err_" + pname,
                     format_str="+/- %0.2g",
                     show_label=False,
                     style='readonly'))
            elements.append(Item("fixed_" + pname, show_label=False))

        kwargs = {'columns': 3}
        class_dict['traits_view'] = View(VGrid(*elements, **kwargs))
        self.fields_class = new.classobj('Fields', (HasTraits, ), class_dict)
        self.fields = self.fields_class()
Beispiel #5
0
class Parameter(HasTraits):
    """Defines parameter for FitFunction

    >>> p = Parameter(name = 'a', value = 10.)
    >>> p.name
    'a'
    >>> p.value
    10.0
    """
    #: parameter name
    name = Str()
    #: actual value
    value = Float(1.)
    #: a string representation of value
    value_str = Property(depends_on='value')
    #: sigma of fitted parameter
    sigma = Float(0.)
    #: a string representation of sigma
    sigma_str = Property(depends_on='sigma')
    #: whether it is treated as a constant
    is_constant = Bool(False)

    def _is_constant_changed(self, value):
        if value == True:
            self.sigma = 0.

    def _get_sigma_str(self):
        return ' +/- %f ' % self.sigma

    def _get_value_str(self):
        return ' %f ' % self.value
Beispiel #6
0
class ParafoilWizard(HasTraits):
    span = Float(7.5)
    chord = Float(3.75)
    number_of_cells = Int(9)
    anhedral_angle = Float(40)
    sectiondata = Instance(SectionData, SectionAFILEData(filename=os.path.join(src_dir, 'testcase', 'avl_case', 'clarky.dat')))
    #le_cut = Range(0.0,1.0,0.0, desc='leading edge cut position')
    inlet_height = Range(0.0, 0.5, 0.1, desc='the height of the inlet cut')
    cut_angle = Range(90., 180., 135, desc='leading edge cut angle with the positive x axis')
    def get_surface(self):
        num_sections = (self.number_of_cells + 1) // 2
        anhedral_angle_r = self.anhedral_angle * numpy.pi / 180
        r = self.span / 2.0 / numpy.sin(anhedral_angle_r)
        sections = []
        y = numpy.linspace(self.number_of_cells % 2, self.number_of_cells, num_sections) / self.number_of_cells
        sectiondata = SectionAIRFOILData.get_clipped_section_data(self.sectiondata, self.inlet_height, self.cut_angle)
        filename = 'parafoil.dat'
        filename = os.path.abspath(filename)
        sectiondata.write_airfoil_file(filename, 'parafoil')
        if self.number_of_cells%2==1:
            le = numpy.zeros((3,))
            sectionafile = SectionAFILEData(filename=filename)
            sections.append(Section(leading_edge=le, chord=self.chord, type=sectionafile.type, data=sectionafile))
        for i, theta in enumerate(anhedral_angle_r * y):
            le = numpy.array([0, r * numpy.sin(theta), r * (numpy.cos(theta) - 1)])
            sectionafile = SectionAFILEData(filename=filename)
            sections.append(Section(leading_edge=le, chord=self.chord, type=sectionafile.type, data=sectionafile))
        surface = Surface(name='Parafoil', yduplicate=0, sections=sections)
        return surface
    traits_view = View('span','chord','number_of_cells','anhedral_angle',
                       Item('object.sectiondata.filename',label='section data file'),
                       'inlet_height','cut_angle')
Beispiel #7
0
class RegularPolygon(Polygon):
    center = Tuple(Float, Float)
    sides = Int(6)
    radius = Float(1.0)
    theta = Float(0.)  # orientation in radians
    sequence = 'rectangles'

    def __init__(self):
        self._update_vertices()

    def _sides_changed(self, old, new):
        self._update_verts()

    def _theta_changed(self, old, new):
        self._update_verts()

    def _radius_changed(self, old, new):
        self._update_verts()

    def _update_verts(self):

        theta = 2 * npy.pi / self.sides * npy.arange(self.sides) + self.theta
        x, y = self.center

        xy = npy.zeros((self.sides, 2))

        xy[:, 0] = x + self.radius * npy.cos(theta)
        xy[:, 1] = y + self.radius * npy.sin(theta)

        self.vertices = xy
Beispiel #8
0
class TPSModel(HasTraits):
    """Define total station model and specifications."""
    horizontal_sd = Float(
        5, desc='horizontal angle standard deviation in seconds')
    zenith_sd = Float(5, desc='zenith angle standard deviation in seconds')
    chord_sd = Float(.003, desc='chord distance standard deviation in m')
    chord_ppm = Float(2, desc='chord distance ppm variation')
    model = String

    known_models = {
        'SET530R V33-17': {
            'horizontal_sd': 5,
            'zenith_sd': 5,
            'chord_sd': 0.002,
            'chord_ppm': 2
        },
        'SET5F': {
            'horizontal_sd': 5,
            'zenith_sd': 5,
            'chord_sd': 0.003,
            'chord_ppm': 2
        }
    }

    def _model_changed(self, old, new):
        if new in self.known_models.keys():
            self.horizontal_sd = self.known_models[new]['horizontal_sd']
            self.zenith_sd = self.known_models[new]['zenith_sd']
            self.chord_sd = self.known_models[new]['chord_sd']
            self.chord_ppm = self.known_models[new]['chord_ppm']
Beispiel #9
0
class PupilGenerator(HasTraits):
    wavelength = Float(700)
    NA = Float(1.49)
    n = Float(1.51)
    pupilSizeX = Int(61)
    pixelSize = Float(70)

    pupils = List(_pupils)

    aberations = List(ZernikeMode, value=[ZernikeMode(i) for i in range(25)])

    basePupil = Instance(Pupil, _getDefaultPupil)

    pupil = None

    view = View(Item(
        'basePupil',
        label='Pupil source',
        editor=InstanceEditor(name='pupils', editable=True),
    ),
                Item('_'),
                Item('wavelength'),
                Item('n'),
                Item('NA'),
                Item('pupilSizeX'),
                Item('pixelSize'),
                Item('_'),
                Item('aberations'),
                buttons=[OKButton])

    def GetPupil(self):
        u, v, R, pupil = self.basePupil.GeneratePupil(self.pixelSize,
                                                      self.pupilSizeX,
                                                      self.wavelength, self.NA,
                                                      self.n)
Beispiel #10
0
class draft(HasTraits):
    energy = Float(0.5)
    S = Float(4.0)
    V = Float(5.0)
    lamda = Float(1)

    Fi_f = Property(depends_on=[
        'S', 'V', 'lamda', 'E', 'delta_a_f', 'delta_p_f', 'delta_s_f',
        'delta_e'
    ])

    @cached_property
    def _get_Fi_f(self):
        return fh.Fuel_resonance_nuetron_flex(self.energy, self.S, self.V,
                                              self.lamda)

    def draft_y(self, energy):
        S = 4.0
        V = 5.0
        lamda = 1
        E = energy
        delta_p_f = fh.Breit_Wigner(E, 6.67, 'p', 0, 1)
        delta_s_f = 8.9
        delta_e = S / (V * 2.4088 * 10**24)
        delta_a_f = 1.1977 / np.sqrt(E)
        Fi_f = (lamda * delta_p_f + delta_e) / (
            (delta_a_f + lamda * delta_s_f + delta_e) * E)
        return Fi_f
Beispiel #11
0
class Gaussian(Distribution):
    """ A gaussian distribution """
    mean = Float(50.0)
    std = Float(2.0)

    traits_view = View(Item('mean'), Item('std'))

    def _get_value(self, n):
        return self._state.normal(self.mean, self.std, n)
Beispiel #12
0
class SSelectorOnMeshElement(Base):
    shortName = String(ELEMENT_LENGTH)
    imin = Int()
    jmin = Int()
    kmin = Int()
    imax = Int()
    jmax = Int()
    kmax = Int()
    v1 = Float(-1.0)
    v2 = Float(-1.0)
    v3 = Float(-1.0)
Beispiel #13
0
class Person(HasTraits):
    weight_kg = Float(0.0)
    height_m = Float(1.0)
    bmi = Float(0.0)

    def _weight_kg_changed(self, old, new):
        print 'weight_kg changed from %s to %s ' % (old, new)
        if self.height_m != 0.0:
            self.bmi = self.weight_kg / (self.height_m**2)

    def _anytrait_changed(self, name, old, new):
        print 'The %s trait changed from %s to %s ' % (name, old, new)
Beispiel #14
0
class Rectangle(HasTraits):
    width = Float(1.0)
    height = Float(2.0)

    area = Property(depends_on=['width', 'height'])

    @cached_property
    def _get_area(self):
        "area的get函数,注意此函数名和对应的Property属性名的关系"

        print 'recalculating'
        return self.width * self.height
Beispiel #15
0
class PupilTools(HasTraits):
    wavelength = Float(700)
    #NA = Float(1.49)
    sizeX = Int(61)
    sizeZ = Int(61)
    zSpacing = Float(50)

    view = View(
        Item('wavelength'),
        #Item('NA'),
        Item('zSpacing'),
        Item('sizeZ'),
        Item('sizeX'),
        buttons=[OKButton])

    def __init__(self, dsviewer):
        self.dsviewer = dsviewer
        self.do = dsviewer.do

        self.image = dsviewer.image

        dsviewer.AddMenuItem('Processing', "Generate PSF from pupil",
                             self.OnPSFFromPupil)

    def OnPSFFromPupil(self, event):
        import numpy as np
        #import pylab
        from PYME.PSFGen import fourierHNA

        from PYME.DSView.image import ImageStack
        from PYME.DSView import ViewIm3D

        self.configure_traits(kind='modal')

        z_ = np.arange(self.sizeZ) * float(self.zSpacing)
        z_ -= z_.mean()

        ps = fourierHNA.PsfFromPupil(
            self.image.data[:, :], z_, self.image.mdh['voxelsize.x'] * 1e3,
            self.wavelength)  #, shape = [self.sizeX, self.sizeX])

        ps = ps / ps[:, :, self.sizeZ / 2].sum()

        im = ImageStack(ps, titleStub='Generated PSF')
        im.mdh.copyEntriesFrom(self.image.mdh)
        im.mdh['Parent'] = self.image.filename
        #im.mdh['Processing.CropROI'] = roi
        mode = 'psf'

        dv = ViewIm3D(im,
                      mode=mode,
                      glCanvas=self.dsviewer.glCanvas,
                      parent=wx.GetTopLevelParent(self.dsviewer))
Beispiel #16
0
class WormlikeSource(PointSource):
    kbp = Float(100)
    steplength=Float(10.0)
    lengthPerKbp=Float(10.0)
    persistLength=Float(150.0)
    #name = Str('Wormlike Chain')

    def getPoints(self):
        from PYME.Acquire.Hardware.Simulator import wormlike2
        wc = wormlike2.wormlikeChain(self.kbp, self.steplength, self.lengthPerKbp, self.persistLength)

        return wc.xp, wc.yp
Beispiel #17
0
class Rectangle(HasTraits):
    width = Float(1.0)
    height = Float(2.0)

    #area是一个属性,当width,height的值变化时,它对应的_get_area函数将被调用
    area = Property(depends_on=['width', 'height'])

    # 通过cached_property修饰器缓存_get_area()的输出
    @cached_property
    def _get_area(self):
        "area的get函数,注意此函数名和对应的Proerty名的关系"
        print('recalculating')
        return self.width * self.height
Beispiel #18
0
class Axis(ArtistContainer):
    zorder = Float(1.5)
    tickmarker = Instance(Marker, ())
    line = Instance(Line, ())
    ticklocs = Array('d')
    ticksize = Float(7.0)

    loc = Float(0.)  # the y location of the x-axis
    tickoffset = Float(0)  # -1 for outer, -0.5 for centered, 0 for inner
    sequence = 'axes'

    def __init__(self):
        ArtistContainer.__init__(self)
        self.affine.on_trait_change(self._update_blended_affine, 'vec6')
        self.tickmarker.antialiased = False
        self.line.antialiased = False

        self.add_artist(self.line, followdata=False)
        self.add_artist(self.tickmarker, followdata=False)

        # XXX, do we have to manually call these or will they get
        # calle dautomagically in init
        self._update_tick_path()
        self._update_marker_locations()
        self._update_blended_affine()
        self._update_linepath()

    def _ticklocs_changed(self, old, new):
        self._update_marker_locations()

    def _loc_changed(self, old, new):
        self._update_blended_affine()

    def _ticksize_changed(self, old, new):
        self._update_tick_path()

    def _tickoffset_changed(self, old, new):
        self._update_tick_path()

    def _update_blended_affine(self):
        'blend of xdata and y axis affine'
        raise NotImplementedError

    def _update_marker_locations(self):
        raise NotImplementedError

    def _update_tick_path(self):
        raise NotImplementedError

    def _update_linepath(self):
        raise NotImplementedError
Beispiel #19
0
class Point(HasTraits): 
    x = Float(0.0)
    y = Float(0.0)
    updated = Event
            
    @on_trait_change( "x,y" )
    def pos_changed(self): 
        self.updated = True

    def _updated_fired(self): 
        self.redraw()
    
    def redraw(self): 
        print "redraw at %s, %s" % (self.x, self.y)
Beispiel #20
0
class MTraitsNamespace:
    DPI = Float(72.)

    Alpha = traits.Range(0., 1., 0.)
    Affine = Trait(Affine())
    AntiAliased = traits.true
    Color = Trait('black', ColorHandler())
    DPI = Float(72.)
    Interval = Array('d', (2, ), npy.array([0.0, 1.0], npy.float_))
    LineStyle = Trait('-', '--', '-.', ':', 'steps', None)
    LineWidth = Float(1.0)
    Marker = Trait(None, '.', ',', 'o', '^', 'v', '<', '>', 's', '+', 'x', 'd',
                   'D', '|', '_', 'h', 'H', 'p', '1', '2', '3', '4')
    MarkerSize = Float(6)
    Visible = traits.true
class NBSMoreParameter(HasTraits):

    THRES = Float(3)
    K = Int(10)
    TAIL = Enum('left', ['left', 'equal', 'right'])

    view = View(Item('first_edge_value', label="Edge value for first group"),
                Item('second_edge_value', label="Edge value for second group"),
                Item('THRES', label="Threshold"),
                Item('K', label="# Interations"),
                Item('TAIL', label="Tail"),
                buttons=['OK'],
                resizable=True,
                title="More parameters")

    def __init__(self, cfile, selected_network1, selected_network2, **traits):
        super(NBSMoreParameter, self).__init__(**traits)

        for cobj in cfile.connectome_network:
            if cobj.name == selected_network1:
                cnet1 = cobj
                break
        # get edge parameters
        edval1 = cnet1._get_edge_values()

        for cobj in cfile.connectome_network:
            if cobj.name == selected_network2:
                cnet2 = cobj
                break
        # get edge parameters
        edval2 = cnet2._get_edge_values()

        self.add_trait('first_edge_value', Enum(edval1))
        self.add_trait('second_edge_value', Enum(edval2))
Beispiel #22
0
class ImageSource(PointSource):
    image = WRDictEnum(image.openImages)
    points_per_pixel = Float(0.1)

    #name = Str('Density Image')
    #foo = Enum([1,2,3,4])

    def getPoints(self):
        from PYME.simulation import locify
        print((self.image))

        im = image.openImages[self.image]
        #import numpy as np
        d = im.data[:, :, 0, 0].astype('f')

        #normalise the image
        d = d / d.max()

        return locify.locify(d,
                             pixelSize=im.pixelSize,
                             pointsPerPixel=self.points_per_pixel)

    def refresh_choices(self):
        ed = self.trait('image').editor

        if ed:
            ed._values_changed()
Beispiel #23
0
class TVTKMapperWidget(HasTraits):
    alpha = Float(1.0)
    post_call = Any
    lut_manager = Instance(LUTManager)

    def _alpha_changed(self, old, new):
        self.lut_manager.lut.alpha_range = (new, new)
        self.post_call()
Beispiel #24
0
        class AcmeUI(HasTraits):
            """ The Acme UI class! """

            # The traits that we want to initialize from preferences.
            bgcolor = Str('blue')
            width = Int(50)
            ratio = Float(1.0)
            visible = Bool(True)
class Solenoid(WireLoop):
    pitch = Float(0.2)
    diameter = Float(1.0)
    turns = Float(10.0)
    resolution = Int(64)
    radius = 0.02

    traits_view = View("pitch", "diameter", "turns", "resolution", "radius")

    @on_trait_change("pitch, diameter, turns, resolution")
    def on_change(self):
        a = np.arange(0, 2 * np.pi * self.turns, 2 * np.pi / self.resolution)
        r = self.diameter / 2.
        x = np.cos(a) * r
        y = np.sin(a) * r
        z = (np.arange(len(a)) - len(a) / 2.0) * self.pitch / self.resolution
        self.nodes = np.column_stack((x, y, z))
Beispiel #26
0
        class AcmeUI(HasTraits):
            """ The Acme UI class! """

            # The traits that we want to initialize from preferences.
            bgcolor = Str('red')
            width = Int(60)
            ratio = Float(2.0)
            visible = Bool(False)
Beispiel #27
0
class Explorer(SplitApplicationWindow):
    """ The main application window. """

    #### 'Window' interface ###################################################

    title = Str('Naming System Explorer')

    #### 'SplitApplicationWindow' interface ###################################

    # The direction in which the panel is split.
    direction = Str('vertical')

    # The ratio of the size of the left/top pane to the right/bottom pane.
    ratio = Float(0.3)

    # The root binding (usually a binding to a context!).
    root = Instance(Binding)

    ###########################################################################
    # Protected 'SplitApplicationWindow' interface.
    ###########################################################################

    def _create_lhs(self, parent):
        """ Creates the left hand side or top depending on the style. """

        return self._create_tree(parent, self.root)

    def _create_rhs(self, parent):
        """ Creates the panel containing the selected preference page. """

        return self._create_python_shell(parent)

    ###########################################################################
    # Private interface.
    ###########################################################################

    def _create_tree(self, parent, root):
        """ Creates the tree. """

        self._tree = tree = NamingTree(parent, root=root)

        return tree.control

    def _create_python_shell(self, parent):
        """ Creates the Python shell. """

        self._python_shell = python_shell = PythonShell(parent)

        # Bind useful names.
        python_shell.bind('widget', self._tree)
        python_shell.bind('w', self._tree)
        python_shell.bind('window', self)
        python_shell.bind('explore', explore)

        # Execute useful commands to bind useful names ;^)
        python_shell.execute_command('from enthought.naming.api import *')

        return python_shell.control
Beispiel #28
0
class PerspectiveItem(HasTraits):
    """ An item in a Perspective contents list. """

    implements(IPerspectiveItem)

    # The Id of the view to display in the perspective.
    id = Str

    # The position of the view relative to the item specified in the
    # 'relative_to' trait.
    #
    # 'top'    puts the view above the 'relative_to' item.
    # 'bottom' puts the view below the 'relative_to' item.
    # 'left'   puts the view to the left of  the 'relative_to' item.
    # 'right'  puts the view to the right of the 'relative_to' item.
    # 'with'   puts the view in the same region as the 'relative_to' item.
    #
    # If the position is specified as 'with' you must specify a 'relative_to'
    # item other than the editor area (i.e., you cannot position a view 'with'
    # the editor area).
    position = Enum('left', 'top', 'bottom', 'right', 'with')

    # The Id of the view to position relative to. If this is not specified
    # (or if no view exists with this Id) then the view will be placed relative
    # to the editor area.
    relative_to = Str

    # The width of the item (as a fraction of the window width).
    #
    # e.g. 0.5 == half the window width.
    #
    # Note that this is treated as a suggestion, and it may not be possible
    # for the workbench to allocate the space requested.
    width = Float(-1)

    # The height of the item (as a fraction of the window height).
    #
    # e.g. 0.5 == half the window height.
    #
    # Note that this is treated as a suggestion, and it may not be possible
    # for the workbench to allocate the space requested.
    height = Float(-1)

    # The style of the dock control created.
    style_hint = Enum('tab', 'vertical', 'horizontal', 'fixed')
class ImageSource(PointSource):
    image = WRDictEnum(image.openImages)
    points_per_pixel = Float(0.1)
    #name = Str('Density Image')
    #foo = Enum([1,2,3,4])

    helpInfo = {
        'points_per_pixel': '''
Select average number of points (dye molecules or docking sites) per pixel in image regions where the density values are 1.
The number is a floating point fraction, e.g. 0.1, and shouldn't exceed 1. It is used for Monte-Carlo rejection of positions and larger values (>~0.2) will result in images which have visible pixel-grid structure because the Monte-Carlo sampling is no longer a good approximation to random sampling over the grid. If this is a problem for your application / you can't get high enough density without a high acceptance fraction, use an up-sampled source image with a smaller pixel size.
''',
        'image': '''
Select an image from the list of open images.
Note that you need to open or generate the source image you want to use so that this
list is not empty. The image will be normalised for the purpose of the simulation,
with its maximum set to 1. It describes the density of markers in the simulated sample,
where values of 1 have a density of markers as given by the `points per pixel` parameter, i.e.
in the Monte-Carlo sampling the acceptance probability = image*points_per_pixel. Smaller
density values therefore give rise to proportionally fewer markers per pixel.
''',
    }
    
    def helpStr(self, name):
        def cleanupHelpStr(str):
            return str.strip().replace('\n', ' ').replace('\r', '')
        
        return cleanupHelpStr(self.helpInfo[name])

    def default_traits_view( self ):
        from traitsui.api import View, Item, EnumEditor, InstanceEditor

        traits_view = View(Item('points_per_pixel',help=self.helpStr('points_per_pixel'),
                                tooltip='mean number of marker points per pixel'),
                           Item('image',help=self.helpStr('image'),
                                tooltip='select the marker density image from the list of open images'),
                           buttons = ['OK', 'Help'])
        
        return traits_view
                           
    def getPoints(self):
        from PYME.simulation import locify
        print((self.image))

        im = image.openImages[self.image]
        #import numpy as np
        d = im.data[:,:,0,0].astype('f')

        #normalise the image
        d = d/d.max()

        return locify.locify(d, pixelSize=im.pixelSize, pointsPerPixel=self.points_per_pixel)

    def refresh_choices(self):
        ed = self.trait('image').editor

        if ed:
            ed._values_changed()
Beispiel #30
0
class IVTKWithCrust(SplitApplicationWindow):
    """ Provides an Scene along with an embedded PyCrust Python shell.
    In the shell, 'scene' and 's' are bound to the Scene."""

    # The ratio of the size of the left/top pane to the right/bottom pane.
    ratio = Float(0.7)

    # The direction in which the panel is split.
    direction = Str('horizontal')

    # The `Scene` instance into which VTK renders.
    scene = Instance(Scene)

    # The `PythonShell` instance.
    python_shell = Instance(PythonShell)

    ###########################################################################
    # 'object' interface.
    ###########################################################################
    def __init__(self, **traits):
        """ Creates a new window. """

        # Base class constructor.
        super(IVTKWithCrust, self).__init__(**traits)
        self.title = 'TVTK Scene'
        # Create the window's menu bar.
        self.menu_bar_manager = create_ivtk_menu(self)

    ###########################################################################
    # `IWindow` interface.
    ###########################################################################
    def close(self):
        if self.scene is not None:
            self.scene.close()
        super(IVTKWithCrust, self).close()

    ###########################################################################
    # Protected 'SplitApplicationWindow' interface.
    ###########################################################################
    def _create_lhs(self, parent):
        """ Creates the left hand side or top depending on the style. """

        self.scene = DecoratedScene(parent)
        self.scene.renderer.background = 0.5, 0.5, 0.5
        return self.scene.control

    def _create_rhs(self, parent):
        """ Creates the right hand side or bottom depending on the
        style.  's' and 'scene' are bound to the Scene instance."""

        self.python_shell = PythonShell(parent)
        self.python_shell.bind('scene', self.scene)
        self.python_shell.bind('s', self.scene)
        self.python_shell.bind('tvtk', tvtk)

        return self.python_shell.control