Ejemplo n.º 1
0
    def get_additional_group(self):
        og = Group(Item('laser_controller', show_label=False,
                    editor=InstanceEditor(view='control_view'),
                    style='custom'),
                   label='Optics',
                   )
        ac = Group(
                   og,
                   show_border=True,
                   label='Additional Controls',
                   layout='tabbed')

        aclist = self.get_additional_controls()
        if aclist is None:
            og.label = 'Optics'
            og.show_border = True
            ac = og
        else:
            for ai in aclist:
                ac.content.append(ai)
        return ac
Ejemplo n.º 2
0

class House(HasTraits):
    address = Str
    bedrooms = Int
    pool = Bool
    price = Int


# View object designed to display two objects of class 'House'
comp_view = View(Group(Group(Item('h1.address', resizable=True),
                             Item('h1.bedrooms'),
                             Item('h1.pool'),
                             Item('h1.price'),
                             show_border=True),
                       Group(Item('h2.address', resizable=True),
                             Item('h2.bedrooms'),
                             Item('h2.pool'),
                             Item('h2.price'),
                             show_border=True),
                       orientation='horizontal'),
                 title='House Comparison')

# A pair of houses to demonstrate the View
house1 = House(address='4743 Dudley Lane',
               bedrooms=3,
               pool=False,
               price=150000)
house2 = House(address='11604 Autumn Ridge',
               bedrooms=3,
               pool=True,
Ejemplo n.º 3
0
class MATS3DDesmorat(MATSBondSlipBase):

    node_name = 'bond model: damage-plasticity'
    '''Damage - plasticity model of bond.
    '''

    #-------------------------------------------------------------------------
    # Material parameters
    #-------------------------------------------------------------------------

    E_m = tr.Float(16e+3,
                   label="E_m",
                   desc="Young's Modulus",
                   auto_set=False,
                   input=True)
    E_b = tr.Float(19e+3,
                   label="E_b",
                   desc="Young's Modulus Bond",
                   auto_set=False,
                   input=True)

    nu = tr.Float(0.2,
                  label='nu',
                  desc="Poison ratio",
                  auto_set=False,
                  input=True)

    def _get_lame_m_params(self):
        la = self.E_m * self.nu / ((1. + self.nu) * (1. - 2. * self.nu))
        # second Lame parameter (shear modulus)
        mu = self.E_m / (2. + 2. * self.nu)
        return la, mu

    D_m_abef = tr.Property(tr.Array, depends_on='+input')

    @tr.cached_property
    def _get_D_m_abef(self):
        la = self._get_lame_m_params()[0]
        mu = self._get_lame_m_params()[1]
        delta = np.identity(3)
        D_m_abef = (np.einsum(',ij,kl->ijkl', la, delta, delta) +
                    np.einsum(',ik,jl->ijkl', mu, delta, delta) +
                    np.einsum(',il,jk->ijkl', mu, delta, delta))

        return D_m_abef

    def _get_lame_b_params(self):
        la = self.E_b * self.nu / ((1. + self.nu) * (1. - 2. * self.nu))
        # second Lame parameter (shear modulus)
        mu = self.E_b / (2. + 2. * self.nu)
        return la, mu

    D_b_abef = tr.Property(tr.Array, depends_on='+input')

    @tr.cached_property
    def _get_D_b_abef(self):
        la = self._get_lame_b_params()[0]
        mu = self._get_lame_b_params()[1]
        delta = np.identity(3)
        D_b_abef = (np.einsum(',ij,kl->ijkl', la, delta, delta) +
                    np.einsum(',ik,jl->ijkl', mu, delta, delta) +
                    np.einsum(',il,jk->ijkl', mu, delta, delta))

        return D_b_abef

    tree_node_list = List([])

    gamma = Float(110,
                  label="Gamma",
                  desc="kinematic hardening modulus",
                  MAT=True,
                  symbol=r'\gamma',
                  unit='MPa/mm',
                  enter_set=True,
                  auto_set=False)

    K = Float(130,
              label="K",
              desc="isotropic hardening modulus",
              MAT=True,
              symbol='K',
              unit='MPa/mm',
              enter_set=True,
              auto_set=False)

    S = Float(476e-6,
              label="S",
              desc="damage strength",
              MAT=True,
              symbol='S',
              unit='MPa/mm',
              enter_set=True,
              auto_set=False)

    tau_bar = Float(6,
                    label="Tau_0 ",
                    desc="yield stress",
                    symbol=r'\bar{\tau}',
                    unit='MPa',
                    MAT=True,
                    enter_set=True,
                    auto_set=False)

    sv_names = [
        'tau_e',
        'tau',
        'eps_pi',
        'X'
        'z',
        'D',
        'Y',
        'eps_cum',
    ]

    def get_next_state(self, eps, eps_pi, Y, D, z, X, tau_e, tau, g, eps_cum):

        D_m = self.D_m_abef
        D_b = self.D_b_abef

        for i in range(len(s) - 1):

            # trial stress - assuming elastic increment.
            eps_diff = eps[i + 1] - eps_pi[i]
            tau_trial = (np.einsum('ijkl,lk->ij', D_m, eps[i + 1]) *
                         (1. - D[i]) +
                         (np.einsum('ijkl,lk->ij', D_b, eps[i + 1])) *
                         (1. - D[i]) - np.einsum('ijkl,lk->ij', D_b,
                                                 eps_pi[i])) * (1. - D[i])
            tau_e_trial = (np.einsum('ijkl,lk->ij', D_b, eps_diff))
            norm = tau_e_trial - X[i]
            f_trial = np.sqrt(np.einsum('nj,nj', norm,
                                        norm)) - self.tau_bar - self.K * z[i]

            if f_trial <= 0:
                tau_e[i + 1] = tau_e_trial
                tau[i + 1] = tau_trial
                eps_pi[i + 1] = eps_pi[i]
                z[i + 1] = z[i]
                X[i + 1] = X[i]
                D[i + 1] = D[i]
                Y[i + 1] = Y[i]
                g[i + 1] = g[i]
                eps_cum[i + 1] = eps_cum[i]

            # identify values beyond the elastic limit
            else:
                # identify values beyond the elastic limit

                # sliding  multiplier
                delta_pi = f_trial / \
                    (self.E_b + (self.K + self.gamma) * (1. - D[i]))

                # return mapping for isotropic and kinematic hardening
                numerador = tau_e_trial - X[i]
                norm = np.sqrt(np.einsum('nj,nj', numerador, numerador))
                sign = numerador / norm
                eps_pi[i + 1] = eps_pi[i] + delta_pi * sign
                eps_cum[i + 1] = eps_cum[i] + delta_pi * \
                    np.einsum('ij,lk->ik', sign, sign)
                Y[i + 1] = 0.5 * (np.einsum('ij,ijkl,lk', eps[i + 1], D_m, eps[i + 1])) + \
                    0.5 * (np.einsum('ij,ijkl,lk', eps_diff, D_b, eps_diff))
                D_trial = D[i] + (Y[i + 1] / self.S) * delta_pi
                if D[i] > 0.9:
                    break
                else:
                    D[i + 1] = D_trial
                g[i + 1] = g[i] + (1. - D[i + 1]) * delta_pi * sign
                X[i + 1] = self.gamma * g[i + 1]
                z[i + 1] = z[i] + delta_pi * (1. - D[i + 1])

                # apply damage law to the effective stress
                eps_diff = eps[i + 1] - eps_pi[i + 1]
                tau[i + 1] = (np.einsum('ijkl,lk->ij', D_m, eps[i + 1]) *
                              (1. - D[i + 1]) +
                              (np.einsum('ijkl,lk->ij', D_b, eps[i + 1])) *
                              (1. - D[i + 1]) -
                              np.einsum('ijkl,lk->ij', D_b, eps_pi[i + 1])) * (
                                  1. - D[i + 1])
                tau_e[i + 1] = (np.einsum('ijkl,lk->ij', D_b, eps_diff))


#                 if tau[i, 0, 0] > 0:
#                     tau[i, 0, 0] = 0
#                     D[i] = 0
#                     s_cum = [i, 0, 0]
#                     break
        return eps_pi, Y, D, z, X, tau_e, tau, g, eps_cum

    traits_view = View(
        Group(
            VGroup(
                Item('E_b', full_size=True, resizable=True),
                Item('E_m'),
                Item('gamma'),
                Item('K'),
                Item('S'),
                Item('tau_bar'),
            ), ),
        width=0.4,
        height=0.8,
    )

    tree_view = traits_view
Ejemplo n.º 4
0
    font = "Courier 10"

    def __init__(self, **traits):
        super(SegmentAdapter, self).__init__(**traits)

    def _get_Segment_bg_color(self):
        col = self.item.color
        return col


from ..cluster_ui import ClusterEditor, ClusterAdapter

segment_editor_group = \
        VGroup( Group(
            Item("auto_aggregate"),
            Item("render_segments"),
            Item("render_tracks"),
                 ),
                 Include("algorithm_widgets"),
                     Group(Item("segments",
                      name='segments',
                      editor=TabularEditor(
                          adapter=SegmentAdapter(),
                          editable=False),
                      height=400, width=200, show_label=False),
                      label="Segmentation Options",
                      show_border=True)
                    )


class SegmentationEditor(ClusterEditor):
Ejemplo n.º 5
0
class TwoPlots(HasTraits):
    global numboards

    data = Instance(AbstractPlotData)
    normalize = False

    p1 = Instance(Plot)

    # set up appropriate view(s)
    view = View( Item('p1', show_label=False, editor=ComponentEditor() ),
                 width=1000,
                 height=500,
                 resizable=True)
#    print "TwoPlots numboards = ",numboards
    if numboards==2:
        plot2 = Instance(Plot)
        view = View(Group(
                          Item('p1', show_label=False, editor=ComponentEditor() ),
                          Item('p2', show_label=False, editor=ComponentEditor() ),
                         ),
                    width=1000,
                    height=600,
                    resizable=True)

    # DATA INITIALIZATION STEP   timer
    startdata1 = np.zeros((2,Nsources*8),np.int32)
    x = np.linspace(0, 1, 2)
    data = ArrayPlotData(x=x,                         #need to be extended to y0-y63
                         y0=startdata1[:,0],  y1=startdata1[:,1],  y2=startdata1[:,2],
                         y3=startdata1[:,3],  y4=startdata1[:,4],  y5=startdata1[:,5],
                         y6=startdata1[:,6],  y7=startdata1[:,7],  y8=startdata1[:,8],
                         y9=startdata1[:,9],  y10=startdata1[:,10], y11=startdata1[:,11],
                         y12=startdata1[:,12], y13=startdata1[:,13], y14=startdata1[:,14],
                         y15=startdata1[:,15], y16=startdata1[:,16], y17=startdata1[:,17],
                         y18=startdata1[:,18], y19=startdata1[:,19], y20=startdata1[:,20],
                         y21=startdata1[:,21], y22=startdata1[:,22], y23=startdata1[:,23],
                         y24=startdata1[:,24], y25=startdata1[:,25], y26=startdata1[:,26],
                         y27=startdata1[:,27], y28=startdata1[:,28], y29=startdata1[:,29],
                         y30=startdata1[:,30], y31=startdata1[:,31], y32=startdata1[:,32],
                         y33=startdata1[:,33], y34=startdata1[:,34], y35=startdata1[:,35],
                         y36=startdata1[:,36], y37=startdata1[:,37], y38=startdata1[:,38],
                         y39=startdata1[:,39], y40=startdata1[:,40], y41=startdata1[:,41],
                         y42=startdata1[:,42], y43=startdata1[:,43], y44=startdata1[:,44],
                         y45=startdata1[:,45], y46=startdata1[:,46], y47=startdata1[:,47],
                         y48=startdata1[:,48], y49=startdata1[:,49], y50=startdata1[:,50],
                         y51=startdata1[:,51], y52=startdata1[:,52], y53=startdata1[:,53],
                         y54=startdata1[:,54], y55=startdata1[:,55], y56=startdata1[:,56],
                         y57=startdata1[:,57], y58=startdata1[:,58], y59=startdata1[:,59],
                         y60=startdata1[:,60], y61=startdata1[:,61], y62=startdata1[:,62],
                         y63=startdata1[:,63])
                         

    # PLOT CREATION STEP
    p1 = Plot(data)

    plotchan = ['x','y0','y1','y2','y3','y4','y5','y6','y7','y8','y9','y10','y11','y12','y13','y14','y15','y16','y17',
                'y18','y19','y20','y21','y22','y23','y24','y25','y26','y27','y28','y29','y30','y31','y32','y33','y34','y35',
                'y36','y37','y38','y39','y40','y41','y42','y43','y44','y45','y46','y47','y48','y49','y50','y51','y52','y53',
                'y54','y55','y56','y57','y58','y59','y60','y61','y62','y63']
    p1.plot(plotchan,color_mapper=COLOR_PALETTE)
    p1.padding_top = 5
    p1.padding_bottom = 6  # hide xlabel
    p1.padding_left = 40
    p1.padding_right = 5

    # color_mapper doesn't work so ...           need to be extended to y0-y63
    p1.plots['plot0'][0].color = 'blue'
    p1.plots['plot0'][1].color = 'green'
    p1.plots['plot0'][2].color = 'red'
    p1.plots['plot0'][3].color = 'cyan'
    p1.plots['plot0'][4].color = 'magenta'
    p1.plots['plot0'][5].color = 'yellow'
    p1.plots['plot0'][6].color = 'black'
    p1.plots['plot0'][7].color = 'brown'
    p1.plots['plot0'][8].color = 'blue'
    p1.plots['plot0'][9].color = 'green'
    p1.plots['plot0'][10].color = 'red'
    p1.plots['plot0'][11].color = 'cyan'
    p1.plots['plot0'][12].color = 'magenta'
    p1.plots['plot0'][13].color = 'yellow'
    p1.plots['plot0'][14].color = 'black'
    p1.plots['plot0'][15].color = 'brown'
    p1.plots['plot0'][16].color = 'blue'
    p1.plots['plot0'][17].color = 'green'
    p1.plots['plot0'][18].color = 'red'
    p1.plots['plot0'][19].color = 'cyan'
    p1.plots['plot0'][20].color = 'magenta'
    p1.plots['plot0'][21].color = 'yellow'
    p1.plots['plot0'][22].color = 'black'
    p1.plots['plot0'][23].color = 'brown'
    p1.plots['plot0'][24].color = 'blue'
    p1.plots['plot0'][25].color = 'green'
    p1.plots['plot0'][26].color = 'red'
    p1.plots['plot0'][27].color = 'cyan'
    p1.plots['plot0'][28].color = 'magenta'
    p1.plots['plot0'][29].color = 'yellow'
    p1.plots['plot0'][30].color = 'black'
    p1.plots['plot0'][31].color = 'brown'
    p1.plots['plot0'][32].color = 'blue'
    p1.plots['plot0'][33].color = 'green'
    p1.plots['plot0'][34].color = 'red'
    p1.plots['plot0'][35].color = 'cyan'
    p1.plots['plot0'][36].color = 'magenta'
    p1.plots['plot0'][37].color = 'yellow'
    p1.plots['plot0'][38].color = 'black'
    p1.plots['plot0'][39].color = 'brown'
    p1.plots['plot0'][40].color = 'blue'
    p1.plots['plot0'][41].color = 'green'
    p1.plots['plot0'][42].color = 'red'
    p1.plots['plot0'][43].color = 'cyan'
    p1.plots['plot0'][44].color = 'magenta'
    p1.plots['plot0'][45].color = 'yellow'
    p1.plots['plot0'][46].color = 'black'
    p1.plots['plot0'][47].color = 'brown'
    p1.plots['plot0'][48].color = 'blue'
    p1.plots['plot0'][49].color = 'green'
    p1.plots['plot0'][50].color = 'red'
    p1.plots['plot0'][51].color = 'cyan'
    p1.plots['plot0'][52].color = 'magenta'
    p1.plots['plot0'][53].color = 'yellow'
    p1.plots['plot0'][54].color = 'black'
    p1.plots['plot0'][55].color = 'brown'
    p1.plots['plot0'][56].color = 'blue'
    p1.plots['plot0'][57].color = 'green'
    p1.plots['plot0'][58].color = 'red'
    p1.plots['plot0'][59].color = 'cyan'
    p1.plots['plot0'][60].color = 'magenta'
    p1.plots['plot0'][61].color = 'yellow'
    p1.plots['plot0'][62].color = 'black'
    p1.plots['plot0'][63].color = 'brown'
 
    if normalize:
        p1.value_range.set_bounds(0,1)
    else:
        p1.value_range.set_bounds(int_yscale_min,int_yscale_max)
Ejemplo n.º 6
0
class MayaviGrid(HasTraits):
    ''' This class is used to plot the data in a vlsv file as a mayavi grid The following will bring up a new window and plot the grid in the vlsv file:

   .. code-block:: python

      grid = pt.grid.MayaviGrid(vlsvReader=f, variable="rho", operator='pass', threaded=False)

   Once you have the window open you can use the picker tool in the right-upper corner and use various point-click tools for analyzing data.

   Picker options:
   
   **None** Does nothing upon clicking somewhere in the grid
   
   **Velocity_space** Plots the velocity space at a specific position upon clicking somewhere in the grid Note: If the vlsv file does not have the velocity space at the position where you are clicking, this will not work
   
   **Velocity_space_iso_surface** Plots the velocity space at a specific position upon clicking somewhere in the grid in iso-surface plotting style Note: If the vlsv file does not have the velocity space at the position where you are clicking, this will not work
   
   **Velocity_space_nearest_cellid** Plots the velocity space of the closest cell id to the picking point Note: If the vlsv file does not have velocity space saved at all, this will not work
   
   **Velocity_space_nearest_cellid_iso_surface** Plots the velocity space of the closest cell id to the picking point in iso-surface plotting style Note: If the vlsv file does not have velocity space saved at all, this will not work
   
   **Pitch_angle** Plots the pitch angle distribution at the clicking position Note: If the vlsv file does not have the velocity space at the position where you are clicking, this will not work
   
   **Gyrophase_angle** Plots the gyrophase angle distribution at the clicking position Note: If the vlsv file does not have the velocity space at the position where you are clicking, this will not work
   
   **Cut_through** Is used to plot or save the cut-through between two clicking points. This option requires you to use the args section at top-left. To use the args section to plot variables you must write for example: **plot rho B,x E,y** Upon clicking at two points a new window would open with a cut-through plot of rho, x-component of B and y-component of E Alternatively, you can save the cut-through to a variable in the MayaviGrid class by typing instead: **rho B,x E,y** and then going to the terminal and typing
   
   .. code-block:: python

      cut_through_data = grid.cut_through
      print cut_through_data

   '''
    picker = Enum('None', "Velocity_space_nearest_cellid",
                  'Velocity_space_nearest_cellid_iso_surface', "Pitch_angle",
                  "Gyrophase_angle", "Cut_through", "Themis_detector",
                  "Themis_contour", "Themis_helistyle")

    args = ""

    variable_plotted = ""

    labels = []

    cut_through = []

    plot = []

    scene = Instance(MlabSceneModel, ())

    engine_view = Instance(EngineView)

    current_selection = Property

    dataset = []

    values = []

    picker_functions = {}

    # Define the view:
    view = View(
        HGroup(
            Item('scene',
                 editor=SceneEditor(scene_class=MayaviScene),
                 height=250,
                 width=300,
                 show_label=False,
                 resizable=True),
            Group(
                #'cell_pick',
                'picker',
                'args',
                show_labels=True),
        ),
        resizable=True,
    )

    def __init__(self,
                 vlsvReader,
                 variable,
                 operator="pass",
                 threaded=False,
                 **traits):
        ''' Initializes the class and loads the mayavi grid

          :param vlsvReader:        Some vlsv reader with a file open
          :type vlsvReader:         :class:`vlsvfile.VlsvReader`
          :param variable:          Name of the variable
          :param operator:          Operator for the variable
          :param threaded:          Boolean value for using threads or not using threads to draw the grid (threads enable interactive mode)
      '''
        HasTraits.__init__(self, **traits)
        self.vlsvReader = vlsvReader
        self.engine_view = EngineView(engine=self.scene.engine)
        self.__engine = self.scene.engine
        self.__picker = []
        self.__mins = []
        self.__maxs = []
        self.__cells = []
        self.__last_pick = []
        self.__grid_figure = mayavi.mlab.gcf(engine=self.__engine)
        self.__structured_figures = []
        self.__unstructured_figures = []
        self.__thread = []
        self.__load_grid(variable=variable,
                         operator=operator,
                         threaded=threaded)
        self.values = []
        self.variable_plotted = variable

    def __module_manager(self):
        import mayavi.core.module_manager as MM
        module_manager = self.scene.mayavi_scene
        # Find the module manager:
        while (True):
            module_manager = module_manager.children[0]
            if type(module_manager) == type(MM.ModuleManager()):
                break
        return module_manager

    def __add_label(self, cellid):
        # Get spatial grid sizes:
        xcells = (int)(self.vlsvReader.read_parameter("xcells_ini"))
        ycells = (int)(self.vlsvReader.read_parameter("ycells_ini"))
        zcells = (int)(self.vlsvReader.read_parameter("zcells_ini"))

        xmin = self.vlsvReader.read_parameter("xmin")
        ymin = self.vlsvReader.read_parameter("ymin")
        zmin = self.vlsvReader.read_parameter("zmin")
        xmax = self.vlsvReader.read_parameter("xmax")
        ymax = self.vlsvReader.read_parameter("ymax")
        zmax = self.vlsvReader.read_parameter("zmax")

        dx = (xmax - xmin) / (float)(xcells)
        dy = (ymax - ymin) / (float)(ycells)
        dz = (zmax - zmin) / (float)(zcells)

        # Add a point in the place:
        cell_coordinates = self.vlsvReader.get_cell_coordinates(cellid)
        x = [cell_coordinates[0]]
        y = [cell_coordinates[1]]
        z = [cell_coordinates[2]]
        s = [(dx + dy + dx) / 3.0]
        points = self.scene.mlab.points3d(x,
                                          y,
                                          z,
                                          s,
                                          scale_factor=3,
                                          figure=self.__grid_figure,
                                          reset_zoom=False)

    def __add_normal_labels(self, point1, point2):
        # Get spatial grid sizes:
        xcells = (int)(self.vlsvReader.read_parameter("xcells_ini"))
        ycells = (int)(self.vlsvReader.read_parameter("ycells_ini"))
        zcells = (int)(self.vlsvReader.read_parameter("zcells_ini"))

        xmin = self.vlsvReader.read_parameter("xmin")
        ymin = self.vlsvReader.read_parameter("ymin")
        zmin = self.vlsvReader.read_parameter("zmin")
        xmax = self.vlsvReader.read_parameter("xmax")
        ymax = self.vlsvReader.read_parameter("ymax")
        zmax = self.vlsvReader.read_parameter("zmax")

        dx = (xmax - xmin) / (float)(xcells)
        dy = (ymax - ymin) / (float)(ycells)
        dz = (zmax - zmin) / (float)(zcells)

        # Get normal vector from point2 and point1
        point1 = np.array(point1)
        point2 = np.array(point2)
        normal_vector = (point2 - point1) / np.linalg.norm(point2 - point1)
        normal_vector = np.dot(rotation_matrix_2d(
            -0.5 * np.pi), (point2 - point1)) / np.linalg.norm(point2 - point1)
        normal_vector = normal_vector * np.array([1, 1, 0])
        point1_shifted = point1 + 0.5 * (point2 -
                                         point1) - normal_vector * (8 * dx)
        point2_shifted = point1 + 0.5 * (point2 -
                                         point1) + normal_vector * (8 * dx)
        point1 = np.array(point1_shifted)
        point2 = np.array(point2_shifted)

        cellid1 = self.vlsvReader.get_cellid(point1)
        cellid2 = self.vlsvReader.get_cellid(point2)

        # Input label:
        self.__add_label(cellid1)
        self.__add_label(cellid2)

    def __load_grid(self, variable, operator="pass", threaded=False):
        ''' Creates a grid and inputs scalar variables from a vlsv file
          :param variable:        Name of the variable to plot
          :param operator:        Operator for the variable
          :param threaded:        Boolean value for using threads or not using threads to draw the grid (threads enable interactive mode)
      '''
        # Get the cell params:
        mins = np.array([
            self.vlsvReader.read_parameter("xmin"),
            self.vlsvReader.read_parameter("ymin"),
            self.vlsvReader.read_parameter("zmin")
        ])
        cells = np.array([
            self.vlsvReader.read_parameter("xcells_ini"),
            self.vlsvReader.read_parameter("ycells_ini"),
            self.vlsvReader.read_parameter("zcells_ini")
        ])
        maxs = np.array([
            self.vlsvReader.read_parameter("xmax"),
            self.vlsvReader.read_parameter("ymax"),
            self.vlsvReader.read_parameter("zmax")
        ])
        # Get the variables:
        index_for_cellid_dict = self.vlsvReader.get_cellid_locations()
        if isinstance(variable, str):
            variable_array = self.vlsvReader.read_variable(name=variable,
                                                           operator=operator)
        else:
            variable_array = variable
        # Sort the dictionary by cell id
        import operator as oper
        sorted_index_for_cellid_dict = sorted(
            index_for_cellid_dict.iteritems(), key=oper.itemgetter(0))
        # Add the variable values:
        variable_array_sorted = []
        for i in sorted_index_for_cellid_dict:
            variable_array_sorted.append(variable_array[i[1]])
        # Store the mins and maxs:
        self.__mins = mins
        self.__maxs = maxs
        self.__cells = cells
        # Draw the grid:
        if threaded == True:
            thread = threading.Thread(target=self.__generate_grid,
                                      args=(mins, maxs, cells,
                                            variable_array_sorted, variable))
            thread.start()
        else:
            self.__generate_grid(mins=mins,
                                 maxs=maxs,
                                 cells=cells,
                                 datas=variable_array_sorted,
                                 names=variable)

    def __picker_callback(self, picker):
        """ This gets called when clicking on a cell
      """
        if (self.picker != "Cut_through"):
            # Make sure the last pick is null (used in cut_through)
            self.__last_pick = []

        coordinates = picker.pick_position
        coordinates = np.array(
            [coordinates[0], coordinates[1], coordinates[2]])
        # Check for 2d
        for i in xrange(3):
            if self.__cells[i] == 1:
                coordinates[i] = (self.__mins[i] + self.__maxs[i]) / 2.0
        print "CLICKED COORDINATES:" + str(coordinates)
        cellid = self.vlsvReader.get_cellid(coordinates)
        print "CLICKED CELL ID: " + str(int(cellid))
        # Check for an invalid cell id
        if cellid == 0:
            print "Invalid cell id"
            return

        args = self.args.split()  # Split args field in the mayavi into a list

        if (self.picker == "Velocity_space"):
            # Set label to give out the location of the cell:
            self.__add_label(cellid)
            # Generate velocity space
            self.__generate_velocity_grid(cellid)
        elif (self.picker == "Velocity_space_nearest_cellid"):
            # Find the nearest cell id with distribution:
            # Read cell ids with velocity distribution in:
            cell_candidates = self.vlsvReader.read(mesh="SpatialGrid",
                                                   tag="CELLSWITHBLOCKS")
            # Read in the coordinates of the cells:
            cell_candidate_coordinates = [
                self.vlsvReader.get_cell_coordinates(cell_candidate)
                for cell_candidate in cell_candidates
            ]
            # Read in the cell's coordinates:
            pick_cell_coordinates = self.vlsvReader.get_cell_coordinates(
                cellid)
            if len(cell_candidates) == 0:
                print "No velocity distribution data found in this file!"
                return
            # Find the nearest:
            from operator import itemgetter
            norms = np.sum(
                (cell_candidate_coordinates - pick_cell_coordinates)**2,
                axis=-1)**(1. / 2)
            norm, i = min((norm, idx) for (idx, norm) in enumerate(norms))
            # Get the cell id:
            cellid = cell_candidates[i]
            print "PLOTTED CELL ID: " + str(cellid)
            # Set label to give out the location of the cell:
            self.__add_label(cellid)
            # Generate velocity grid
            self.__generate_velocity_grid(cellid)
        elif (self.picker == "Velocity_space_iso_surface"):
            # Set label to give out the location of the cell:
            self.__add_label(cellid)
            self.__generate_velocity_grid(cellid, True)
        elif (self.picker == "Velocity_space_nearest_cellid_iso_surface"):
            # Find the nearest cell id with distribution:
            # Read cell ids with velocity distribution in:
            cell_candidates = self.vlsvReader.read(mesh="SpatialGrid",
                                                   tag="CELLSWITHBLOCKS")
            if len(cell_candidates) == 0:
                print "No velocity distribution data found in this file!"
                return
            # Read in the coordinates of the cells:
            cell_candidate_coordinates = [
                self.vlsvReader.get_cell_coordinates(cell_candidate)
                for cell_candidate in cell_candidates
            ]
            # Read in the cell's coordinates:
            pick_cell_coordinates = self.vlsvReader.get_cell_coordinates(
                cellid)
            # Find the nearest:
            from operator import itemgetter
            norms = np.sum(
                (cell_candidate_coordinates - pick_cell_coordinates)**2,
                axis=-1)**(1. / 2)
            norm, i = min((norm, idx) for (idx, norm) in enumerate(norms))
            # Get the cell id:
            cellid = cell_candidates[i]
            print "PLOTTED CELL ID: " + str(cellid)
            # Set label to give out the location of the cell:
            self.__add_label(cellid)
            # Generate velocity grid
            self.__generate_velocity_grid(cellid, True)
        elif (self.picker == "Pitch_angle"):
            # Find the nearest cell id with distribution:
            # Read cell ids with velocity distribution in:
            cell_candidates = self.vlsvReader.read(mesh="SpatialGrid",
                                                   tag="CELLSWITHBLOCKS")
            if len(cell_candidates) == 0:
                print "No velocity distribution data found in this file!"
                return
            # Read in the coordinates of the cells:
            cell_candidate_coordinates = [
                self.vlsvReader.get_cell_coordinates(cell_candidate)
                for cell_candidate in cell_candidates
            ]
            # Read in the cell's coordinates:
            pick_cell_coordinates = self.vlsvReader.get_cell_coordinates(
                cellid)
            # Find the nearest:
            from operator import itemgetter
            norms = np.sum(
                (cell_candidate_coordinates - pick_cell_coordinates)**2,
                axis=-1)**(1. / 2)
            norm, i = min((norm, idx) for (idx, norm) in enumerate(norms))
            # Get the cell id:
            cellid = cell_candidates[i]
            print "PLOTTED CELL ID: " + str(cellid)
            # Set label to give out the location of the cell:
            self.__add_label(cellid)
            # Plot pitch angle distribution:
            from pitchangle import pitch_angles
            result = pitch_angles(vlsvReader=self.vlsvReader,
                                  cellid=cellid,
                                  cosine=True,
                                  plasmaframe=True)
            # plot:
            pl.hist(result[0].data, weights=result[1].data, bins=50, log=False)
            pl.show()
        elif (self.picker == "Gyrophase_angle"):
            # Find the nearest cell id with distribution:
            # Read cell ids with velocity distribution in:
            cell_candidates = self.vlsvReader.read(mesh="SpatialGrid",
                                                   tag="CELLSWITHBLOCKS")
            if len(cell_candidates) == 0:
                print "No velocity distribution data found in this file!"
                return
            # Read in the coordinates of the cells:
            cell_candidate_coordinates = [
                self.vlsvReader.get_cell_coordinates(cell_candidate)
                for cell_candidate in cell_candidates
            ]
            # Read in the cell's coordinates:
            pick_cell_coordinates = self.vlsvReader.get_cell_coordinates(
                cellid)
            # Find the nearest:
            from operator import itemgetter
            norms = np.sum(
                (cell_candidate_coordinates - pick_cell_coordinates)**2,
                axis=-1)**(1. / 2)
            norm, i = min((norm, idx) for (idx, norm) in enumerate(norms))
            # Get the cell id:
            cellid = cell_candidates[i]
            print "PLOTTED CELL ID: " + str(cellid)
            # Set label to give out the location of the cell:
            self.__add_label(cellid)

            # Plot gyrophase angle distribution:
            from gyrophaseangle import gyrophase_angles_from_file
            result = gyrophase_angles_from_file(vlsvReader=self.vlsvReader,
                                                cellid=cellid)
            # plot:
            pl.hist(result[0].data,
                    weights=result[1].data,
                    bins=36,
                    range=[-180.0, 180.0],
                    log=True,
                    normed=1)
            pl.show()
        elif (self.picker == "Cut_through"):
            # Get the cut-through points
            point1 = self.__last_pick
            point2 = coordinates
            if len(self.__last_pick) == 3:
                from lineout import lineout
                from variable import VariableInfo
                if len(args) == 0:
                    #Do nothing
                    print "Bad args"
                    self.__last_pick = []
                    return
                plotCut = False
                # Optimize file read:
                self.vlsvReader.optimize_open_file()
                variables = []
                distances = []
                # Save variables
                plotCut = False
                for i in xrange(len(args)):
                    # Check if the user has given the plot argument
                    if args[i] == "plot":
                        plotCut = True
                    else:
                        # Get the name of the variable and its operator as given by the user
                        if args[i].find(",") != -1:
                            _variable = args[i].split(',')[0]
                            _operator = args[i].split(',')[1]
                        else:
                            _variable = args[i]
                            _operator = "pass"
                        # Get the lineout
                        line = lineout(self.vlsvReader,
                                       point1,
                                       point2,
                                       _variable,
                                       operator=_operator,
                                       interpolation_order=1,
                                       points=1000)
                        distance = line[0]
                        coordinates = line[1]
                        values = line[2]
                        variables.append(
                            VariableInfo(values,
                                         name=_variable + " "
                                         " " + _operator,
                                         units=""))
                        distances.append(
                            VariableInfo(distance, name="distance", units="m"))
                        self.cut_through.append(values)
                if plotCut == True:
                    # Add also streamline
                    self.draw_streamline(point1, point2)
                    from plot import plot_multiple_variables
                    fig = plot_multiple_variables(distances,
                                                  variables,
                                                  figure=[])
                    pl.show()
                # Close the optimized file read:
                self.vlsvReader.optimize_close_file()
                # Read in the necessary variables:
                self.__last_pick = []
            else:
                self.__last_pick = coordinates
        elif (self.picker == "Themis_detector"):
            # Parse args: Spacecraft detector axis
            if len(args) == 0:
                detectoraxis = np.array([0, 1, 0])
            else:
                detectoraxis = np.array(
                    [float(args[0]),
                     float(args[1]),
                     float(args[2])])

            # Find the nearest cell id with distribution:
            # Read cell ids with velocity distribution in:
            cell_candidates = self.vlsvReader.read(mesh="SpatialGrid",
                                                   tag="CELLSWITHBLOCKS")
            if len(cell_candidates) == 0:
                print "No velocity distribution data found in this file!"
                return
            # Read in the coordinates of the cells:
            cell_candidate_coordinates = [
                self.vlsvReader.get_cell_coordinates(cell_candidate)
                for cell_candidate in cell_candidates
            ]
            # Read in the cell's coordinates:
            pick_cell_coordinates = self.vlsvReader.get_cell_coordinates(
                cellid)
            # Find the nearest:
            from operator import itemgetter
            norms = np.sum(
                (cell_candidate_coordinates - pick_cell_coordinates)**2,
                axis=-1)**(1. / 2)
            norm, i = min((norm, idx) for (idx, norm) in enumerate(norms))
            # Get the cell id:
            cellid = cell_candidates[i]
            print "PLOTTED CELL ID: " + str(cellid)
            # Set label to give out the location of the cell:
            self.__add_label(cellid)
            # Plot pitch angle distribution:
            from themis_observation import themis_plot_detector
            themis_plot_detector(self.vlsvReader, cellid, detectoraxis)
        elif (self.picker == "Themis_contour"):
            # Find the nearest cell id with distribution:
            # Read cell ids with velocity distribution in:
            cell_candidates = self.vlsvReader.read(mesh="SpatialGrid",
                                                   tag="CELLSWITHBLOCKS")
            if len(cell_candidates) == 0:
                print "No velocity distribution data found in this file!"
                return
            # Read in the coordinates of the cells:
            cell_candidate_coordinates = [
                self.vlsvReader.get_cell_coordinates(cell_candidate)
                for cell_candidate in cell_candidates
            ]
            # Read in the cell's coordinates:
            pick_cell_coordinates = self.vlsvReader.get_cell_coordinates(
                cellid)
            # Find the nearest:
            from operator import itemgetter
            norms = np.sum(
                (cell_candidate_coordinates - pick_cell_coordinates)**2,
                axis=-1)**(1. / 2)
            norm, i = min((norm, idx) for (idx, norm) in enumerate(norms))
            # Get the cell id:
            cellid = cell_candidates[i]
            print "PLOTTED CELL ID: " + str(cellid)
            # Parse args: Plotting plane
            plane = [np.array([1., 0, 0]), np.array([0, 1., 0])]
            labels = ["Vx", "Vy"]
            for i in range(len(args)):
                if args[i] == "x":
                    plane[i] = np.array([1., 0, 0])
                    labels[i] = "Vx"
                if args[i] == "y":
                    plane[i] = np.array([0, 1., 0])
                    labels[i] = "Vy"
                if args[i] == "z":
                    plane[i] = np.array([0, 0, 1.])
                    labels[i] = "Vz"
                if args[i] == "B":
                    B = self.vlsvReader.read_variable("B", cellid)
                    plane[i] = B
                    labels[i] = "V||B"
                if args[i] == "v":
                    v = self.vlsvReader.read_variable("v", cellid)
                    plane[i] = v
                    labels[i] = "V_perp, direction of V_bulk"
                if args[i] == "Bxv":
                    v = self.vlsvReader.read_variable("v", cellid)
                    B = self.vlsvReader.read_variable("B", cellid)
                    plane[i] = np.cross(B, v)
                    labels[i] = "V_perp, direction of B x V"

            print(
                "Getting data from nearest velocity space cell with cellid " +
                str(cellid))
            # Set label to give out the location of the cell:
            self.__add_label(cellid)
            from themis_observation import themis_plot_phasespace_contour
            themis_plot_phasespace_contour(self.vlsvReader,
                                           cellid,
                                           plane[0],
                                           plane[1],
                                           xlabel=labels[0],
                                           ylabel=labels[1])
        elif (self.picker == "Themis_helistyle"):

            # Find the nearest cell id with distribution:
            # Read cell ids with velocity distribution in:
            cell_candidates = self.vlsvReader.read(mesh="SpatialGrid",
                                                   tag="CELLSWITHBLOCKS")
            if len(cell_candidates) == 0:
                print "No velocity distribution data found in this file!"
                return
            # Read in the coordinates of the cells:
            cell_candidate_coordinates = [
                self.vlsvReader.get_cell_coordinates(cell_candidate)
                for cell_candidate in cell_candidates
            ]
            # Read in the cell's coordinates:
            pick_cell_coordinates = self.vlsvReader.get_cell_coordinates(
                cellid)
            # Find the nearest:
            from operator import itemgetter
            norms = np.sum(
                (cell_candidate_coordinates - pick_cell_coordinates)**2,
                axis=-1)**(1. / 2)
            norm, i = min((norm, idx) for (idx, norm) in enumerate(norms))
            # Get the cell id:
            cellid = cell_candidates[i]
            print "PLOTTED CELL ID: " + str(cellid)
            # Parse args: Plotting plane
            plane = [np.array([1., 0, 0]), np.array([0, 1., 0])]
            labels = ["Vx", "Vy"]
            for i in range(len(args)):
                if args[i] == "x":
                    plane[i] = np.array([1., 0, 0])
                    labels[i] = "Vx"
                if args[i] == "y":
                    plane[i] = np.array([0, 1., 0])
                    labels[i] = "Vy"
                if args[i] == "z":
                    plane[i] = np.array([0, 0, 1.])
                    labels[i] = "Vz"
                if args[i] == "B":
                    B = self.vlsvReader.read_variable("B", cellid)
                    plane[i] = B
                    labels[i] = "V||B"
                if args[i] == "v":
                    v = self.vlsvReader.read_variable("v", cellid)
                    plane[i] = v
                    labels[i] = "V_perp, direction of V_bulk"
                if args[i] == "Bxv":
                    v = self.vlsvReader.read_variable("v", cellid)
                    B = self.vlsvReader.read_variable("B", cellid)
                    plane[i] = np.cross(B, v)
                    labels[i] = "V_perp, direction of B x V"

            print(
                "Getting data from nearest velocity space cell with cellid " +
                str(cellid))
            # Set label to give out the location of the cell:
            self.__add_label(cellid)
            from themis_observation import themis_plot_phasespace_helistyle
            themis_plot_phasespace_helistyle(self.vlsvReader,
                                             cellid,
                                             plane[0],
                                             plane[1],
                                             xlabel=labels[0],
                                             ylabel=labels[1])

        elif self.picker in self.picker_functions:
            # Call the corresponding pickerfunction
            self.picker_functions[self.picker](self, self.vlsvReader,
                                               coordinates, args)

    def draw_streamline(self, x0, x1):
        ''' Draws a line from x0 to x1 coordinates

      '''
        self.scene.mlab.plot3d([x0[0], x1[0]], [x0[1], x1[1]],
                               [x0[2] + 4.0e5, x1[2] + 4.0e5],
                               tube_radius=3.0e5)
        return

    def draw_streamline_long(self, list_of_coordinates):
        ''' Draws a set of lines as given by list of coordinates

      '''
        self.scene.mlab.plot3d(list_of_coordinates[0],
                               list_of_coordinates[1],
                               list_of_coordinates[2] +
                               np.ones(len(list_of_coordinates[2])) * 4e5,
                               tube_radius=1.0e5)
        return

    def __generate_grid(self, mins, maxs, cells, datas, names):
        ''' Generates a grid from given data
          :param mins:           An array of minimum coordinates for the grid for ex. [-100, 0, 0]
          :param maxs:           An array of maximum coordinates for the grid for ex. [-100, 0, 0]
          :param cells:          An array of number of cells in x, y, z direction
          :param datas:          Scalar data for the grid e.g. array([ cell1Rho, cell2Rho, cell3Rho, cell4Rho, .., cellNRho ])
          :param names:          Name for the scalar data
      '''
        # Create nodes
        x, y, z = mgrid[mins[0]:maxs[0]:(cells[0] + 1) * complex(0, 1),
                        mins[1]:maxs[1]:(cells[1] + 1) * complex(0, 1),
                        mins[2]:maxs[2]:(cells[2] + 1) * complex(0, 1)]

        # Create points for the nodes:
        pts = empty(z.shape + (3, ), dtype=float)
        pts[..., 0] = x
        pts[..., 1] = y
        pts[..., 2] = z

        # Input scalars
        scalars = np.array(datas)

        # We reorder the points, scalars and vectors so this is as per VTK's
        # requirement of x first, y next and z last.
        pts = pts.transpose(2, 1, 0, 3).copy()
        pts.shape = pts.size / 3, 3
        scalars = scalars.T.copy()

        # Create the dataset.
        sg = tvtk.StructuredGrid(dimensions=x.shape, points=pts)
        sg.cell_data.scalars = ravel(scalars.copy())
        if isinstance(names, str) == False:
            names = "custom"
        sg.cell_data.scalars.name = names

        # Visualize the data
        d = self.scene.mlab.pipeline.add_dataset(sg)
        iso = self.scene.mlab.pipeline.surface(d)

        # Add labels:
        #      from mayavi.modules.labels import Labels
        #      testlabels = self.scene.mlab.pipeline.labels(d)

        self.dataset = d
        print scalars[0]
        # Configure traits
        self.configure_traits()

        self.__grid_figure = mayavi.mlab.gcf(engine=self.__engine)

        # Note: This is not working properly -- it seemingly works out at first but it eventually causes segmentation faults in some places
        #self.__thread = threading.Thread(target=self.configure_traits, args=())
        #self.__thread.start()

    def __generate_velocity_grid(self, cellid, iso_surface=False):
        '''Generates a velocity grid from a given spatial cell id
         :param cellid:           The spatial cell's ID
         :param iso_surface:      If true, plots the iso surface
      '''
        # Create nodes
        # Get velocity blocks and avgs:
        blocksAndAvgs = self.vlsvReader.read_blocks(cellid)
        if len(blocksAndAvgs) == 0:
            print "CELL " + str(cellid) + " HAS NO VELOCITY BLOCK"
            return False
        # Create a new scene
        self.__engine.new_scene()
        mayavi.mlab.set_engine(self.__engine)  #CONTINUE
        # Create a new figure
        figure = mayavi.mlab.gcf(engine=self.__engine)
        figure.scene.disable_render = True
        blocks = blocksAndAvgs[0]
        avgs = blocksAndAvgs[1]
        # Get nodes:
        nodesAndKeys = self.vlsvReader.construct_velocity_cell_nodes(blocks)
        # Create an unstructured grid:
        points = nodesAndKeys[0]
        tets = nodesAndKeys[1]
        tet_type = tvtk.Voxel().cell_type  #VTK_VOXEL

        ug = tvtk.UnstructuredGrid(points=points)
        # Set up the cells
        ug.set_cells(tet_type, tets)
        # Input data
        values = np.ravel(avgs)
        ug.cell_data.scalars = values
        ug.cell_data.scalars.name = 'avgs'

        # Plot B if possible:
        # Read B vector and plot it:
        if self.vlsvReader.check_variable("B") == True:
            B = self.vlsvReader.read_variable(name="B", cellids=cellid)
        elif self.vlsvReader.check_variable("B_vol") == True:
            B = self.vlsvReader.read_variable(name="B_vol", cellids=cellid)
        else:
            B = self.vlsvReader.read_variable(
                name="background_B",
                cellids=cellid) + self.vlsvReader.read_variable(
                    name="perturbed_B", cellids=cellid)

        points2 = np.array([[0, 0, 0]])
        ug2 = tvtk.UnstructuredGrid(points=points2)
        ug2.point_data.vectors = [B / np.linalg.norm(B)]
        ug2.point_data.vectors.name = 'B_vector'
        #src2 = VTKDataSource(data = ug2)
        d2 = mayavi.mlab.pipeline.add_dataset(ug2)
        #mayavi.mlab.add_module(Vectors())
        vec = mayavi.mlab.pipeline.vectors(d2)
        vec.glyph.mask_input_points = True
        vec.glyph.glyph.scale_factor = 1e6
        vec.glyph.glyph_source.glyph_source.center = [0, 0, 0]

        # Visualize
        d = mayavi.mlab.pipeline.add_dataset(ug)
        if iso_surface == False:
            iso = mayavi.mlab.pipeline.surface(d)
        else:
            ptdata = mayavi.mlab.pipeline.cell_to_point_data(d)
            iso = mayavi.mlab.pipeline.iso_surface(
                ptdata, contours=[1e-15, 1e-14, 1e-12], opacity=0.3)
        figure.scene.disable_render = False
        self.__unstructured_figures.append(figure)
        # Name the figure
        figure.name = str(cellid) + ", " + self.variable_plotted + " = " + str(
            self.vlsvReader.read_variable(self.variable_plotted,
                                          cellids=cellid))

        from mayavi.modules.axes import Axes
        axes = Axes()
        axes.name = 'Axes'
        axes.axes.fly_mode = 'none'
        axes.axes.number_of_labels = 8
        axes.axes.font_factor = 0.5
        #module_manager = self.__module_manager()
        # Add the label / marker:
        self.__engine.add_filter(axes)
        from mayavi.modules.outline import Outline
        outline = Outline()
        outline.name = 'Outline'
        self.__engine.add_filter(outline)
        return True

    def generate_diff_grid(self, cellid1, cellid2):
        ''' Generates a diff grid of given cell ids (shows avgs diff)

          :param cellid1:          The first cell id
          :param cellid2:          The second cell id

          .. code-block:: python

             # Example:
             grid.generate_diff_grid( 29219, 2910 )

          .. note:: If the cell id does not have a certain velocity cell, it is assumed that the avgs value of that cell is 0

      '''
        # Create nodes
        # Get velocity blocks and avgs (of cellid 1)
        blocksAndAvgs1 = self.vlsvReader.read_blocks(cellid1)
        if len(blocksAndAvgs1) == 0:
            print "CELL " + str(cellid1) + " HAS NO VELOCITY BLOCK"
            return False
        blocks1 = blocksAndAvgs1[0]
        avgs1 = blocksAndAvgs1[1]

        # Get velocity blocks and avgs (of cellid 2)
        blocksAndAvgs2 = self.vlsvReader.read_blocks(cellid2)
        if len(blocksAndAvgs2) == 0:
            print "CELL " + str(cellid2) + " HAS NO VELOCITY BLOCK"
            return False
        blocks2 = blocksAndAvgs2[0]
        avgs2 = blocksAndAvgs2[1]
        print len(avgs2)
        print len(blocks2)

        # Compare blocks and create a new avgs array values:
        avgs_same = []
        avgs_cellid1 = []
        avgs_cellid2 = []
        blocks_same = []
        blocks_cellid1 = []
        blocks_cellid2 = []
        print np.shape(avgs1[0])
        for i in xrange(len(blocks1)):
            b = blocks1[i]
            # Get index of block
            i2 = np.where(blocks2 == b)[0]
            if len(i2) != 0:
                # Fetch the block:
                #print avgs1[64*i:64*(i+1)]
                #print avgs2[64*i2[0]:64*(i2[0]+1)]
                avgs_same.append(avgs1[i:(i + 1)] - avgs2[i2[0]:(i2[0] + 1)])
                blocks_same.append(b)
            else:
                avgs_cellid1.append(avgs1[i:(i + 1)])
                blocks_cellid1.append(b)
        for i in xrange(len(blocks2)):
            b = blocks2[i]
            if (b in blocks1) == False:
                avgs_cellid2.append(avgs2[i:(i + 1)])
                blocks_cellid2.append(b)
        # Make a list for the avgs etc
        avgs = np.zeros(
            64 * (len(avgs_same) + len(avgs_cellid1) + len(avgs_cellid2)))
        #avgs = np.reshape(avgs, (len(avgs_same)+len(avgs_cellid1)+len(avgs_cellid2), 64))
        print np.shape(avgs_same)
        blocks = np.zeros(
            len(blocks_same) + len(blocks_cellid1) + len(blocks_cellid2))

        index = 0
        avgs[64 * index:64 * (index + len(blocks_same))] = np.ravel(
            np.array(avgs_same))
        blocks[index:index + len(blocks_same)] = np.array(blocks_same)

        index = index + len(blocks_same)
        avgs[64 * index:64 * (index + len(blocks_cellid1))] = np.ravel(
            np.array(avgs_cellid1))
        blocks[index:index + len(blocks_cellid1)] = np.array(blocks_cellid1)

        index = index + len(blocks_cellid1)
        avgs[64 * index:64 * (index + len(blocks_cellid2))] = np.ravel(
            np.array(avgs_cellid2))
        blocks[index:index + len(blocks_cellid2)] = np.array(blocks_cellid2)

        blocks = blocks.astype(int)

        # Get nodes:
        nodesAndKeys = self.vlsvReader.construct_velocity_cell_nodes(blocks)

        # Create an unstructured grid:
        points = nodesAndKeys[0]
        tets = nodesAndKeys[1]

        # Create a new scene
        self.__engine.new_scene()
        mayavi.mlab.set_engine(self.__engine)  #CONTINUE
        # Create a new figure
        figure = mayavi.mlab.gcf(engine=self.__engine)
        figure.scene.disable_render = True
        tet_type = tvtk.Voxel().cell_type  #VTK_VOXEL

        ug = tvtk.UnstructuredGrid(points=points)
        #Thissetsupthecells.
        ug.set_cells(tet_type, tets)
        #Attributedata.
        values = np.ravel(avgs)
        ug.cell_data.scalars = values
        ug.cell_data.scalars.name = 'avgs'
        d = mayavi.mlab.pipeline.add_dataset(ug)
        iso = mayavi.mlab.pipeline.surface(d)
        figure.scene.disable_render = False
        self.__unstructured_figures.append(figure)
        # Name the figure
        figure.name = str(cellid1) + " " + str(cellid2)
        mayavi.mlab.show()
        return True

    def __do_nothing(self, picker):
        return

    # Trait events:
    @on_trait_change('scene.activated')
    def set_mouse_click(self):
        # Temporary bug fix (MayaVi needs a dummy pick to be able to remove cells callbacks from picker.. )
        #self.figure.on_mouse_pick( self.__do_nothing, type='world'
        self.figure = self.scene.mlab.gcf()
        # Cell picker
        func = self.__picker_callback
        typeid = 'world'
        click = 'Left'
        picker = self.figure.on_mouse_pick(func, type='world')
        self.__picker = [func, typeid, click]
        #picker.tolerance = 0
        # Show legend bar
        manager = self.figure.children[0].children[0]
        manager.scalar_lut_manager.show_scalar_bar = True
        manager.scalar_lut_manager.show_legend = True
class MandelbrotDemo(HasTraits):
    color_maps = List
    current_map = Str("Blues_r")
    loc_info = Str
    figure = Instance(Figure)
    N = Int(100)
    R = Float(10)
    cx = Float(0)
    cy = Float(0)
    d = Float(1.5)

    view = View(VGroup(
        HGroup(Item("current_map",
                    label=u"Color map",
                    editor=EnumEditor(name="object.color_maps")),
               "R",
               "N",
               show_labels=True),
        Item("loc_info", show_label=False, style="readonly"),
        Group(Item("figure", editor=MPLFigureEditor(toolbar=False)),
              show_labels=False,
              orientation='horizontal')),
                width=SIZE,
                height=SIZE + 80,
                title=u"Mandelbrot Demo",
                resizable=True)

    def __init__(self, **kw):
        super(MandelbrotDemo, self).__init__(**kw)
        self.array = np.zeros((SIZE, SIZE))
        self.img = self.figure.figimage(self.array, cmap=self.current_map)

    def _figure_default(self):
        return Figure(figsize=(SIZE / 100.0, SIZE / 100.0), dpi=100)

    def _color_maps_default(self):
        return sorted(cm.cmap_d.keys())

    def init_plot(self):
        self.figure.canvas.mpl_connect('button_press_event', self.on_press)
        self.figure.canvas.mpl_connect('motion_notify_event', self.on_move)
        self.figure.canvas.mpl_connect('scroll_event', self.on_scroll)
        self.update_plot()

    def _current_map_changed(self):
        self.img.set_cmap(self.current_map)
        self.update_plot()

    @on_trait_change("R, N")
    def update_plot(self):
        mandelbrot(self.cx,
                   self.cy,
                   self.d,
                   out=self.array,
                   n=self.N,
                   R=self.R)
        self.loc_info = "%g, %g, d=%g" % (self.cx, self.cy, self.d)
        self.img.set_data(self.array)
        self.figure.canvas.draw()

    def on_press(self, evt):
        if evt.button == 1:
            self.last_pos = evt.x, evt.y, self.cx, self.cy

    def on_move(self, evt):
        if evt.button != 1:
            return

        x, y, cx, cy = self.last_pos
        dx = (x - evt.x) * 2 * self.d / SIZE
        dy = (evt.y - y) * 2 * self.d / SIZE
        self.cx = cx + dx
        self.cy = cy + dy
        self.update_plot()

    def on_scroll(self, evt):
        x0, x1, y0, y1 = self.cx - self.d, self.cx + self.d, self.cy - self.d, self.cy + self.d
        x = x0 + float(evt.x) / SIZE * 2 * self.d
        y = y0 + float(SIZE - evt.y) / SIZE * 2 * self.d

        if evt.step < 0:
            d2 = self.d * 1.2
        else:
            d2 = self.d / 1.2

        scale = d2 / self.d

        self.cx = (2 * x + (x0 + x1 - 2 * x) * scale) / 2
        self.cy = (2 * y + (y0 + y1 - 2 * y) * scale) / 2
        self.d = d2
        self.update_plot()
Ejemplo n.º 8
0
 def traits_view(self):
     grp = Group(Item('server_username', label='Username'),
                 Item('server_password', label='Password'),
                 label='SMTP')
     v = View(grp)
     return v
Ejemplo n.º 9
0
 def traits_view(self):
     grps = self.get_additional_groups()
     v = View(Group(*grps, layout='tabbed'))
     return v
Ejemplo n.º 10
0
class SpectralConverter(HasTraits):

    h = float(6.626068 * 10**-34)  # m**2 kg / s
    eVtoJ = float(1.60217646 * 10**-19)  #Number of Joules in one Ev
    c = float(299792458)  #speed of light m/
    Units = Trait(
        'Meters',
        {
            'Meters': 1.0,
            'Centimeters': .01,
            'Micrometers': .000001,
            'Nanometers': .000000001,  #DEFINE RELATIVE TO METERS
            'eV': h * c /
            (eVtoJ),  #RECIPROCAL UNITS (THESE ARE INVERTED BELOW)
            'cm-1': .01,
            'Wavenumber(nm-1)':
            .000000001,  #WAVENUMBER IS INVERSE WAVELENGTH IN NM
            'Frequency(Hz)': c,  #SIMPLY INVERTED
            'Angular Frequency(rad)': 2.0 * pi * c
        })

    proportional = ['Meters', 'Nanometers', 'Centimeters',
                    'Micrometers']  #proportional to distance
    reciprocal = [
        'cm-1', 'eV', 'Wavenumber(nm-1)', 'Frequency(Hz)',
        'Angular Frequency(rad)'
    ]  #Inverse to distance (aka energy is recicprocal E=hc/lam)s

    input_array = Array()  #Set on initialization
    input_units = Units()  #Set on initialization
    output_array = Property(
        Array, depends_on=['input_array', 'input_units', 'output_units'])
    output_units = Units()  #Default unit

    valid_units = Property(
        List,
        depends_on='proportional, reciprocal')  #All valid units in the system

    xstart = Property(Float, depends_on='input_array')
    xend = Property(Float, depends_on='input_array')

    xnewstart = Property(Float, depends_on='output_array')
    xnewend = Property(Float, depends_on='output_array')

    traits_view = View(VSplit(
        Group(
            HSplit(Item('xstart', label='Old Spectral Min', style='readonly'),
                   Item('xend', label='Old Spectral Max', style='readonly'),
                   Item('input_units', style='simple', label='Input Units'))),
        Group(
            HSplit(
                Item('xnewstart', label='New Spectral Min', style='readonly'),
                Item('xnewend', label='New Spectral Max', style='readonly'),
                Item('output_units', label='Output Units')), )),
                       kind='modal',
                       buttons=['Undo', 'OK', 'Cancel', 'Help'],
                       height=500,
                       width=500,
                       resizable=True)

    def _get_xstart(self):
        return self.input_array[0]

    def _get_xend(self):
        return self.input_array[-1]

    def _get_xnewstart(self):
        return self.output_array[0]

    def _get_xnewend(self):
        return self.output_array[-1]

    def _get_valid_units(self):
        return self.proportional + self.reciprocal

    def specific_array(self, new_unit):
        """Return a unit-converted array without changing current settings"""
        if new_unit not in self.valid_units:
            raise ConversionError('Invalid spectral unit: %s' % new_unit)

        # Temporarily change outunit, send, return it back
        old_unit = self.output_units
        self.output_units = new_unit
        specificarray = self.output_array  #propety so not copied
        self.output_units = old_unit
        return specificarray

    # Property implementations
    def _get_output_array(self):
        if self.input_units in self.proportional and self.output_units in self.proportional:
            return (self.input_array * self.input_units_) / self.output_units_

        elif self.input_units in self.proportional and self.output_units in self.reciprocal:
            return 1.0 / (
                (self.input_array * self.input_units_) / self.output_units_)

        elif self.input_units in self.reciprocal and self.output_units in self.proportional:
            return 1.0 / (
                (self.input_array * self.output_units_) / self.input_units_
            )  #Output/input

        elif self.input_units in self.reciprocal and self.output_units in self.reciprocal:
            return (self.input_array * self.output_units_) / self.input_units_
Ejemplo n.º 11
0
    def init(self, parent):
        """Finishes initializing the editor by creating the underlying toolkit
        widget."""

        factory = self.factory
        self.filter = factory.filter

        columns = factory.columns[:]
        if (len(columns) == 0) and (len(self.value) > 0):
            columns = [
                ObjectColumn(name=name)
                for name in self.value[0].editable_traits()
            ]
        self.columns = columns

        if factory.table_view_factory is not None:
            self.table_view = factory.table_view_factory(editor=self)
        if factory.source_model_factory is not None:
            self.source_model = factory.source_model_factory(editor=self)
        if factory.model_factory is not None:
            self.model = factory.model_factory(editor=self)

        # Create the table view and model
        self.model.setDynamicSortFilter(True)
        self.model.setSourceModel(self.source_model)
        self.table_view.setModel(self.model)

        # Create the vertical header context menu and connect to its signals
        self.header_menu = QtGui.QMenu(self.table_view)
        insertable = factory.row_factory is not None
        if factory.editable:
            if insertable:
                action = self.header_menu.addAction("Insert new item")
                action.triggered.connect(self._on_context_insert)
            if factory.deletable:
                action = self.header_menu.addAction("Delete item")
                action.triggered.connect(self._on_context_remove)
        if factory.reorderable:
            if factory.editable and (insertable or factory.deletable):
                self.header_menu.addSeparator()
            self.header_menu_up = self.header_menu.addAction("Move item up")
            self.header_menu_up.triggered.connect(self._on_context_move_up)
            self.header_menu_down = self.header_menu.addAction(
                "Move item down")
            self.header_menu_down.triggered.connect(self._on_context_move_down)

        # Create the empty space context menu and connect its signals
        self.empty_menu = QtGui.QMenu(self.table_view)
        action = self.empty_menu.addAction("Add new item")
        action.triggered.connect(self._on_context_append)

        # When sorting is enabled, the first column is initially displayed with
        # the triangle indicating it is the sort index, even though no sorting
        # has actually been done. Sort here for UI/model consistency.
        if self.factory.sortable and not self.factory.reorderable:
            self.model.sort(0, QtCore.Qt.AscendingOrder)

        # Connect to the mode specific selection handler and select the first
        # row/column/cell. Do this before creating the edit_view to make sure
        # that it has a valid item to use when constructing its view.
        smodel = self.table_view.selectionModel()
        mode_slot = getattr(self, "_on_%s_selection" % factory.selection_mode)
        smodel.selectionChanged.connect(mode_slot)
        self.table_view.setCurrentIndex(self.model.index(0, 0))

        # Create the toolbar if necessary
        if factory.show_toolbar and len(factory.filters) > 0:
            main_view = QtGui.QWidget()
            layout = QtGui.QVBoxLayout(main_view)
            layout.setContentsMargins(0, 0, 0, 0)
            self.toolbar_ui = self.edit_traits(
                parent=parent,
                kind="subpanel",
                view=View(
                    Group(
                        Item("filter{View}", editor=factory._filter_editor),
                        Item("filter_summary{Results}", style="readonly"),
                        spring,
                        orientation="horizontal",
                    ),
                    resizable=True,
                ),
            )
            self.toolbar_ui.parent = self.ui
            layout.addWidget(self.toolbar_ui.control)
            layout.addWidget(self.table_view)
        else:
            main_view = self.table_view

        # Create auxiliary editor and encompassing splitter if necessary
        mode = factory.selection_mode
        if (factory.edit_view == " ") or mode not in {"row", "rows"}:
            self.control = main_view
        else:
            if factory.orientation == "horizontal":
                self.control = QtGui.QSplitter(QtCore.Qt.Horizontal)
            else:
                self.control = QtGui.QSplitter(QtCore.Qt.Vertical)
            self.control.setSizePolicy(QtGui.QSizePolicy.Expanding,
                                       QtGui.QSizePolicy.Expanding)
            self.control.addWidget(main_view)
            self.control.setStretchFactor(0, 2)

            # Create the row editor below the table view
            editor = InstanceEditor(view=factory.edit_view, kind="subpanel")
            self._ui = self.edit_traits(
                parent=self.control,
                kind="subpanel",
                view=View(
                    Item(
                        "selected_row",
                        style="custom",
                        editor=editor,
                        show_label=False,
                        resizable=True,
                        width=factory.edit_view_width,
                        height=factory.edit_view_height,
                    ),
                    resizable=True,
                    handler=factory.edit_view_handler,
                ),
            )
            self._ui.parent = self.ui
            self.control.addWidget(self._ui.control)
            self.control.setStretchFactor(1, 1)

        # Connect to the click and double click handlers
        self.table_view.clicked.connect(self._on_click)
        self.table_view.doubleClicked.connect(self._on_dclick)

        # Make sure we listen for 'items' changes as well as complete list
        # replacements
        self.context_object.on_trait_change(self.update_editor,
                                            self.extended_name + "_items",
                                            dispatch="ui")

        # Listen for changes to traits on the objects in the list
        self.context_object.on_trait_change(self.refresh_editor,
                                            self.extended_name + ".-",
                                            dispatch="ui")

        # Listen for changes on column definitions
        self.on_trait_change(self._update_columns, "columns", dispatch="ui")
        self.on_trait_change(self._update_columns,
                             "columns_items",
                             dispatch="ui")

        # Set up the required externally synchronized traits
        is_list = mode in ("rows", "columns", "cells")
        self.sync_value(factory.click, "click", "to")
        self.sync_value(factory.dclick, "dclick", "to")
        self.sync_value(factory.columns_name, "columns", is_list=True)
        self.sync_value(factory.selected, "selected", is_list=is_list)
        self.sync_value(factory.selected_indices,
                        "selected_indices",
                        is_list=is_list)
        self.sync_value(factory.filter_name, "filter", "from")
        self.sync_value(factory.filtered_indices, "filtered_indices", "to")
        self.sync_value(factory.update_filter_name, "update_filter", "from")

        self.auto_size = self.factory.auto_size

        # Initialize the ItemDelegates for each column
        self._update_columns()
Ejemplo n.º 12
0
class TableFilterEditor(HasTraits):
    """ An editor that manages table filters.
    """

    # -------------------------------------------------------------------------
    #  Trait definitions:
    # -------------------------------------------------------------------------

    #: TableEditor this editor is associated with
    editor = Instance(TableEditor)

    #: The list of filters
    filters = List(TableFilter)

    #: The list of available templates from which filters can be created
    templates = Property(List(TableFilter), depends_on="filters")

    #: The currently selected filter template
    selected_template = Instance(TableFilter)

    #: The currently selected filter
    selected_filter = Instance(TableFilter, allow_none=True)

    #: The view to use for the current filter
    selected_filter_view = Property(depends_on="selected_filter")

    #: Buttons for add/removing filters
    add_button = Button("New")
    remove_button = Button("Delete")

    # The default view for this editor
    view = View(
        Group(
            Group(
                Group(
                    Item("add_button", enabled_when="selected_template"),
                    Item(
                        "remove_button",
                        enabled_when="len(templates) > 1 and "
                        "selected_filter is not None",
                    ),
                    orientation="horizontal",
                    show_labels=False,
                ),
                Label("Base filter for new filters:"),
                Item("selected_template", editor=EnumEditor(name="templates")),
                Item(
                    "selected_filter",
                    style="custom",
                    editor=EnumEditor(name="filters", mode="list"),
                ),
                show_labels=False,
            ),
            Item(
                "selected_filter",
                width=0.75,
                style="custom",
                editor=InstanceEditor(view_name="selected_filter_view"),
            ),
            id="TableFilterEditorSplit",
            show_labels=False,
            layout="split",
            orientation="horizontal",
        ),
        id="traitsui.qt4.table_editor.TableFilterEditor",
        buttons=["OK", "Cancel"],
        kind="livemodal",
        resizable=True,
        width=800,
        height=400,
        title="Customize filters",
    )

    # -------------------------------------------------------------------------
    #  Private methods:
    # -------------------------------------------------------------------------

    # -- Trait Property getter/setters ----------------------------------------

    @cached_property
    def _get_selected_filter_view(self):
        view = None
        if self.selected_filter:
            model = self.editor.model
            index = model.mapToSource(model.index(0, 0))
            if index.isValid():
                obj = self.editor.items()[index.row()]
            else:
                obj = None
            view = self.selected_filter.edit_view(obj)
        return view

    @cached_property
    def _get_templates(self):
        templates = [f for f in self.editor.factory.filters if f.template]
        templates.extend(self.filters)
        return templates

    # -- Trait Change Handlers ------------------------------------------------

    def _editor_changed(self):
        self.filters = [
            f.clone_traits() for f in self.editor.factory.filters
            if not f.template
        ]
        self.selected_template = self.templates[0]

    def _add_button_fired(self):
        """ Create a new filter based on the selected template and select it.
        """
        new_filter = self.selected_template.clone_traits()
        new_filter.template = False
        new_filter.name = new_filter._name = "New filter"
        self.filters.append(new_filter)
        self.selected_filter = new_filter

    def _remove_button_fired(self):
        """ Delete the currently selected filter.
        """
        if self.selected_template == self.selected_filter:
            self.selected_template = self.templates[0]

        index = self.filters.index(self.selected_filter)
        del self.filters[index]
        if index < len(self.filters):
            self.selected_filter = self.filters[index]
        else:
            self.selected_filter = None

    @on_trait_change("selected_filter:name")
    def _update_filter_list(self):
        """ A hack to make the EnumEditor watching the list of filters refresh
            their text when the name of the selected filter changes.
        """
        filters = self.filters
        self.filters = []
        self.filters = filters
Ejemplo n.º 13
0
class GeoCellView(CellView):
    '''View a single cell instance.
    '''
    implements(ICellView)

    cell_X_arr = Array

    cell_x_arr = Array

    def set_cell_traits(self):
        self.cell_X_arr = self.cell_grid.get_cell_point_X_arr(self.cell_idx)
        self.cell_x_arr = self.cell_grid.get_cell_point_x_arr(self.cell_idx)

    #-----------------------------------------------------------------------
    # Visualization
    #-----------------------------------------------------------------------
    draw_cell = Bool(False)

    view = View(
        Item('cell_idx', style='readonly', label='Cell index',
             resizable=False),
        Group(
            Item('cell_X_arr',
                 editor=coord_tabular_editor,
                 style='readonly',
                 show_label=False)),
        Item('draw_cell', label='show geometrical nodes'))

    # register the pipelines for plotting labels and geometry
    #
    mvp_cell_node_labels = Trait(MVPointLabels)

    def _mvp_cell_node_labels_default(self):
        return MVPointLabels(name='Geo node numbers',
                             points=self._get_cell_mvpoints,
                             scalars=self._get_cell_node_labels,
                             color=(0.254902, 0.411765, 0.882353))

    mvp_cell_geo = Trait(MVPolyData)

    def _mvp_cell_geo_default(self):
        return MVPolyData(name='Geo node numbers',
                          points=self._get_cell_points,
                          lines=self._get_cell_lines,
                          color=(0.254902, 0.411765, 0.882353))

    def redraw(self):
        if self.draw_cell:
            self.mvp_cell_node_labels.redraw()

    #-----------------------------------------------------------------------
    # Private methods
    #-----------------------------------------------------------------------
    def _get_cell_mvpoints(self):
        return self.cell_grid.get_cell_mvpoints(self.cell_idx)

    def _get_cell_node_labels(self):
        return self.cell_grid.get_cell_node_labels(self.cell_idx)

    def _get_cell_lines(self):
        return self.cell_grid.grid_cell_spec.cell_lines
Ejemplo n.º 14
0
class InteractiveAnimation(HasTraits):
    """
    Animator that renders in the WxWidgets main loop, using idle events.
    """
    startButton = Button('Start Animation')
    stopButton = Button('Stop Animation')
    speed = Range(0.01, 1.0)

    traits_view = View(Group(Item('startButton'),
                             Item('stopButton'),
                             show_labels=False),
                       Item('_'),
                       Item(name='speed'),
                       title='Animation Controller',
                       buttons=['OK'])

    def __init__(self, tMin, tMax, *renderers):
        """
        Initialise idle animator.

        @param tMin: Time to start animation.
        @param tMax: Time at which to wrap back to tMin.
        @param renderers: List of L{AnimatedRenderer} objects.
        """
        HasTraits.__init__(self)
        self._renderers = renderers
        self._tMin = tMin
        self._tMax = tMax
        self.speed = 1
        self.time = tMin
        self.playing = False
        self._scene = mlab.gcf().scene
        autoPositionCamera()
        for r in self._renderers:
            r.renderUpdate(self.time)
        self.edit_traits()

    def _startButton_fired(self):
        self.playing = True
        self.lastRenderTime = time.time()
        wx.GetApp().Bind(wx.EVT_IDLE, self._onIdleEvent)

    def start(self):
        """ Start animation. """
        self._startButton_fired()

    def _stopButton_fired(self):
        wx.GetApp().Bind(wx.EVT_IDLE, None)
        self.playing = False

    def stop(self):
        """ Stop animation. """
        self._stopButton_fired()

    def _onIdleEvent(self, event):
        if self.playing:
            self._scene.disable_render = True
            timeNow = time.time()
            t = self.time + (timeNow - self.lastRenderTime) * self.speed
            if t > self._tMax:
                self.time = self._tMin + t - self._tMax
            else:
                self.time = t
            self.time = t % self._tMax
            self.lastRenderTime = timeNow
            for r in self._renderers:
                r.renderUpdate(self.time)
            self._scene.disable_render = False
            event.RequestMore()
Ejemplo n.º 15
0
class VolumeSlicer(HasTraits):
    # The data to plot
    data = Array()

    # The 4 views displayed
    scene3d = Instance(MlabSceneModel, ())
    scene_x = Instance(MlabSceneModel, ())
    scene_y = Instance(MlabSceneModel, ())
    scene_z = Instance(MlabSceneModel, ())

    # The data source
    data_src3d = Instance(Source)

    # The image plane widgets of the 3D scene
    ipw_3d_x = Instance(PipelineBase)
    ipw_3d_y = Instance(PipelineBase)
    ipw_3d_z = Instance(PipelineBase)

    _axis_names = dict(x=0, y=1, z=2)

    #---------------------------------------------------------------------------
    def __init__(self, **traits):
        super(VolumeSlicer, self).__init__(**traits)
        # Force the creation of the image_plane_widgets:
        self.ipw_3d_x
        self.ipw_3d_y
        self.ipw_3d_z

    #---------------------------------------------------------------------------
    # Default values
    #---------------------------------------------------------------------------
    def _data_src3d_default(self):
        return mlab.pipeline.scalar_field(self.data,
                                          figure=self.scene3d.mayavi_scene)

    def make_ipw_3d(self, axis_name):
        ipw = mlab.pipeline.image_plane_widget(
            self.data_src3d,
            figure=self.scene3d.mayavi_scene,
            plane_orientation='%s_axes' % axis_name)

        ipw.ipw.reslice_interpolate = 'nearest_neighbour'
        return ipw

    def _ipw_3d_x_default(self):
        return self.make_ipw_3d('x')

    def _ipw_3d_y_default(self):
        return self.make_ipw_3d('y')

    def _ipw_3d_z_default(self):
        return self.make_ipw_3d('z')

    #---------------------------------------------------------------------------
    # Scene activation callbaks
    #---------------------------------------------------------------------------
    @on_trait_change('scene3d.activated')
    def display_scene3d(self):
        outline = mlab.pipeline.outline(
            self.data_src3d,
            figure=self.scene3d.mayavi_scene,
        )
        self.scene3d.mlab.view(40, 50)
        # Interaction properties can only be changed after the scene
        # has been created, and thus the interactor exists
        for ipw in (self.ipw_3d_x, self.ipw_3d_y, self.ipw_3d_z):
            # Turn the interaction off
            ipw.ipw.interaction = 0
            # choose the flag style lut and reverse it
            # this makes it nice for segmentations
            ipw.parent.scalar_lut_manager.lut_mode = 'flag'
            ipw.parent.scalar_lut_manager.reverse_lut = True

        self.scene3d.scene.background = (0, 0, 0)
        # Keep the view always pointing up
        self.scene3d.scene.interactor.interactor_style = \
                                 tvtk.InteractorStyleTerrain()

    def make_side_view(self, axis_name):
        scene = getattr(self, 'scene_%s' % axis_name)

        # To avoid copying the data, we take a reference to the
        # raw VTK dataset, and pass it on to mlab. Mlab will create
        # a Mayavi source from the VTK without copying it.
        # We have to specify the figure so that the data gets
        # added on the figure we are interested in.
        outline = mlab.pipeline.outline(
            self.data_src3d.mlab_source.dataset,
            figure=scene.mayavi_scene,
        )
        ipw = mlab.pipeline.image_plane_widget(outline,
                                               plane_orientation='%s_axes' %
                                               axis_name)
        setattr(self, 'ipw_%s' % axis_name, ipw)

        # Synchronize positions between the corresponding image plane
        # widgets on different views.
        ipw.ipw.sync_trait('slice_position',
                           getattr(self, 'ipw_3d_%s' % axis_name).ipw)

        # Make left-clicking create a crosshair
        ipw.ipw.left_button_action = 0

        # Add a callback on the image plane widget interaction to
        # move the others
        def move_view(obj, evt):
            position = obj.GetCurrentCursorPosition()
            for other_axis, axis_number in self._axis_names.iteritems():
                if other_axis == axis_name:
                    continue
                ipw3d = getattr(self, 'ipw_3d_%s' % other_axis)
                ipw3d.ipw.slice_position = position[axis_number]

        ipw.ipw.add_observer('InteractionEvent', move_view)
        ipw.ipw.add_observer('StartInteractionEvent', move_view)

        # Center the image plane widget
        ipw.ipw.slice_position = 0.5 * self.data.shape[
            self._axis_names[axis_name]]

        # choose the flag style lut and reverse it
        # this makes it nice for segmentations
        ipw.parent.scalar_lut_manager.lut_mode = 'flag'
        ipw.parent.scalar_lut_manager.reverse_lut = True
        ipw.ipw.reslice_interpolate = 'nearest_neighbour'

        # Position the view for the scene
        views = dict(
            x=(0, 90),
            y=(90, 90),
            z=(0, 0),
        )
        scene.mlab.view(*views[axis_name])
        # 2D interaction: only pan and zoom
        scene.scene.interactor.interactor_style = \
                                 tvtk.InteractorStyleImage()
        scene.scene.background = (0, 0, 0)

    @on_trait_change('scene_x.activated')
    def display_scene_x(self):
        return self.make_side_view('x')

    @on_trait_change('scene_y.activated')
    def display_scene_y(self):
        return self.make_side_view('y')

    @on_trait_change('scene_z.activated')
    def display_scene_z(self):
        return self.make_side_view('z')

    #---------------------------------------------------------------------------
    # The layout of the dialog created
    #---------------------------------------------------------------------------
    view = View(
        HGroup(
            Group(
                Item('scene_y',
                     editor=SceneEditor(scene_class=Scene),
                     height=250,
                     width=300),
                Item('scene_z',
                     editor=SceneEditor(scene_class=Scene),
                     height=250,
                     width=300),
                show_labels=False,
            ),
            Group(
                Item('scene_x',
                     editor=SceneEditor(scene_class=Scene),
                     height=250,
                     width=300),
                Item('scene3d',
                     editor=SceneEditor(scene_class=MayaviScene),
                     height=250,
                     width=300),
                show_labels=False,
            ),
        ),
        resizable=True,
        title='Volume Slicer',
    )
Ejemplo n.º 16
0
    """
    Validator function that returns *val* if *val* is either a number or
    the word 'auto'.  This is used as a validator for the text editor
    in the Traits UI for the **tick_interval** trait.
    """
    try:
        return float(val)
    except:
        if isinstance(val, str) and val == "auto":
            return val
    raise TraitError("Tick interval must be a number or 'auto'.")

# Traits UI for a PlotAxis.
AxisView = View(VGroup(
                Group(
                    Item("object.mapper.range.low", label="Low Range"),
                    Item("object.mapper.range.high", label="High Range"),
                    ),
                Group(
                    Item("title", label="Title", editor=TextEditor()),
                    Item("title_font", label="Font", style="simple"),
                    Item("title_color", label="Color", style="custom"),
                    Item("tick_interval", label="Interval", editor=TextEditor(evaluate=float_or_auto)),
                    label="Main"),
                Group(
                    Item("tick_color", label="Color", style="custom"),
                    Item("tick_weight", label="Thickness"),
                    Item("tick_label_color", label="Label color", style="custom"),
                    HGroup(
                        Item("tick_in", label="Tick in"),
                        Item("tick_out", label="Tick out"),
                        ),
Ejemplo n.º 17
0
    def get_additional_groups(self):
        archivergrp = Group(Item('use_video_archiver'),
                            Item(
                                'video_archive_days',
                                label='Archive after N. days',
                                enabled_when='use_video_archiver',
                            ),
                            Item(
                                'video_archive_hours',
                                label='Archive after N. hours',
                                enabled_when='use_video_archiver',
                            ),
                            Item(
                                'video_archive_months',
                                label='Delete after N. months',
                                enabled_when='use_video_archiver',
                            ),
                            show_border=True,
                            label='Archiver')
        recgrp = Group(
            # Item('record_lasing_video', label='Record Lasing'),
            #                        Item('record_brightness',
            #                             label='Record Brightness Measure',
            #                             ),
            Item('video_directory',
                 label='Save to',
                 enabled_when='record_lasing_video_video'),
            #                        Item('recording_zoom', enabled_when='record_lasing_video'),
            show_border=True,
            label='Record')
        vservergrp = VGroup(Item('use_video_server', label='Use Server'),
                            Item('video_server_port',
                                 label='Port',
                                 enabled_when='use_video_server'),
                            Item('video_server_quality',
                                 label='Quality',
                                 enabled_when='use_video_server'),
                            show_border=True,
                            label='Server')
        videogrp = VGroup(Item('use_video'),
                          VGroup(Item('video_identifier',
                                      label='ID',
                                      enabled_when='use_video'),
                                 Item('video_output_mode',
                                      label='Output Mode'),
                                 Item('ffmpeg_path', label='FFmpeg Location'),
                                 Item('use_autocenter', label='Auto Center'),
                                 Item('render_with_markup',
                                      label='Render Snapshot with markup'),
                                 recgrp,
                                 archivergrp,
                                 vservergrp,
                                 enabled_when='use_video'),
                          label='Video')
        canvasgrp = VGroup(
            Item('show_bounds_rect'),
            Item('show_map'),
            Item('show_grids'),
            Item('show_laser_position'),
            Item('show_desired_position'),
            Item('desired_position_color',
                 show_label=False,
                 enabled_when='show_desired_position'),
            Item('crosshairs_kind',
                 label='Crosshairs',
                 enabled_when='show_laser_position'),
            Item('crosshairs_radius',
                 visible_when='crosshairs_kind=="UserRadius"'),
            Item('crosshairs_color', enabled_when='show_laser_position'),
            HGroup(
                Item('crosshairs_offsetx', label='Offset'),
                Item('crosshairs_offsety', show_label=False),
            ),
            Item(
                'crosshairs_offset_color',
                show_label=False,
            ),
            Item('calibration_style'),
            Item('scaling'),
            label='Canvas',
        )

        patgrp = Group(Item('record_patterning'),
                       Item('show_patterning'),
                       label='Pattern')
        powergrp = Group(
            #                         Item('record_lasing_power'),
            Item('use_calibrated_power'),
            label='Power')
        return [canvasgrp, videogrp, patgrp, powergrp]
Ejemplo n.º 18
0
class GridPlane(Component):
    # The version of this class.  Used for persistence.
    __version__ = 0

    # The TVTK object that extracts the grid plane.  This is created
    # dynamically based on the input data type.
    plane = Instance(tvtk.Object)

    # The axis which is normal to the plane chosen.
    axis = Enum('x',
                'y',
                'z',
                desc='specifies the axis normal to the grid plane')

    # The position of the grid plane.
    position = Range(value=0,
                     low='_low',
                     high='_high',
                     enter_set=True,
                     auto_set=False)

    ########################################
    # Private traits.

    # Determines the lower limit of the position trait and is always 0.
    _low = Int(0)

    # Determines the upper limit of the position trait.  The value is
    # dynamically set depending on the input data and state of the
    # axis trait.  The default is some large value to avoid errors in
    # cases where the user may set the position before adding the
    # object to the mayavi tree.
    _high = Int(10000)

    ########################################
    # View related traits.

    # The View for this object.
    view = View(
        Group(Item(name='axis'), Item(name='position',
                                      enabled_when='_high > 0')))

    ######################################################################
    # `object` interface
    ######################################################################
    def __get_pure_state__(self):
        d = super(GridPlane, self).__get_pure_state__()
        # These traits are dynamically created.
        for name in ('plane', '_low', '_high'):
            d.pop(name, None)

        return d

    def __set_pure_state__(self, state):
        state_pickler.set_state(self, state)
        self._position_changed(self.position)

    ######################################################################
    # `Component` interface
    ######################################################################
    def setup_pipeline(self):
        """Override this method so that it *creates* its tvtk
        pipeline.

        This method is invoked when the object is initialized via
        `__init__`.  Note that at the time this method is called, the
        tvtk data pipeline will *not* yet be setup.  So upstream data
        will not be available.  The idea is that you simply create the
        basic objects and setup those parts of the pipeline not
        dependent on upstream sources and filters.
        """
        pass

    def update_pipeline(self):
        """Override this method so that it *updates* the tvtk pipeline
        when data upstream is known to have changed.

        This method is invoked (automatically) when the input fires a
        `pipeline_changed` event.
        """
        if len(self.inputs) == 0:
            return
        input = self.inputs[0].get_output_dataset()
        plane = None
        if input.is_a('vtkStructuredGrid'):
            plane = tvtk.StructuredGridGeometryFilter()
        elif input.is_a('vtkStructuredPoints') or input.is_a('vtkImageData'):
            plane = tvtk.ImageDataGeometryFilter()
        elif input.is_a('vtkRectilinearGrid'):
            plane = tvtk.RectilinearGridGeometryFilter()
        else:
            msg = "The GridPlane component does not support the %s dataset."\
                  % (input.class_name)
            error(msg)
            raise TypeError(msg)

        self.configure_connection(plane, self.inputs[0])
        self.plane = plane
        self.plane.update()
        self.outputs = [plane]
        self._update_limits()
        self._update_extents()
        # If the data is 2D make sure that we default to the
        # appropriate axis.
        extents = list(_get_extent(input))
        diff = [y - x for x, y in zip(extents[::2], extents[1::2])]
        if diff.count(0) > 0:
            self.axis = ['x', 'y', 'z'][diff.index(0)]

    def update_data(self):
        """Override this method to do what is necessary when upstream
        data changes.

        This method is invoked (automatically) when any of the inputs
        sends a `data_changed` event.
        """
        self._update_limits()
        self._update_extents()
        # Propagate the data_changed event.
        self.data_changed = True

    def has_output_port(self):
        """ The filter has an output port."""
        return True

    def get_output_object(self):
        """ Returns the output port."""
        return self.plane.output_port

    ######################################################################
    # Non-public methods.
    ######################################################################
    def _get_axis_index(self):
        return {'x': 0, 'y': 1, 'z': 2}[self.axis]

    def _update_extents(self):
        inp = self.plane.input
        extents = list(_get_extent(inp))
        pos = self.position
        axis = self._get_axis_index()
        extents[2 * axis] = pos
        extents[2 * axis + 1] = pos
        try:
            self.plane.set_extent(extents)
        except AttributeError:
            self.plane.extent = extents

    def _update_limits(self):
        extents = _get_extent(self.plane.input)
        axis = self._get_axis_index()
        pos = min(self.position, extents[2 * axis + 1])
        self._high = extents[2 * axis + 1]
        return pos

    def _axis_changed(self, val):
        if len(self.inputs) == 0:
            return
        pos = self._update_limits()
        if self.position == pos:
            self._update_extents()
            self.data_changed = True
        else:
            self.position = pos

    def _position_changed(self, val):
        if len(self.inputs) == 0:
            return
        self._update_extents()
        self.data_changed = True
Ejemplo n.º 19
0
class LoggerView(TraitsUIView):
    """The Workbench View showing the list of log items."""

    id = Str("apptools.logger.plugin.view.logger_view.LoggerView")
    name = Str("Logger")
    service = Instance(LoggerService)

    log_records = List(Instance(logging.LogRecord))
    formatted_records = Property(Str, depends_on="log_records")

    activated = Instance(logging.LogRecord)
    activated_text = Property(Str, depends_on="activated")
    reset_button = Button("Reset Logs")
    show_button = Button("Complete Text Log")
    copy_button = Button("Copy Log to Clipboard")

    code_editor = CodeEditor(lexer="null", show_line_numbers=False)
    log_records_editor = TabularEditor(adapter=LogRecordAdapter(),
                                       editable=False,
                                       activated="activated")
    trait_view = View(
        Group(
            Item("log_records", editor=log_records_editor),
            Group(
                Item("reset_button"),
                spring,
                Item("show_button"),
                Item("copy_button"),
                orientation="horizontal",
                show_labels=False,
            ),
            show_labels=False,
        ))

    ###########################################################################
    # LogQueueHandler view interface
    ###########################################################################

    def update(self, force=False):
        """Update 'log_records' if our handler has new records or 'force' is
        set.
        """
        service = self.service
        if service.handler.has_new_records() or force:
            log_records = [
                rec for rec in service.handler.get()
                if rec.levelno >= service.preferences.level_
            ]
            log_records.reverse()
            self.log_records = log_records

    ###########################################################################
    # Private interface
    ###########################################################################

    @on_trait_change("service.preferences.level_")
    def _update_log_records(self):
        self.service.handler._view = self
        self.update(force=True)

    def _reset_button_fired(self):
        self.service.handler.reset()
        self.log_records = []

    def _show_button_fired(self):
        self.edit_traits(view=View(
            Item(
                "formatted_records",
                editor=self.code_editor,
                style="readonly",
                show_label=False,
            ),
            width=800,
            height=600,
            resizable=True,
            buttons=["OK"],
            title="Complete Text Log",
        ))

    def _copy_button_fired(self):
        clipboard.text_data = self.formatted_records

    @cached_property
    def _get_formatted_records(self):
        return "\n".join([
            self.service.handler.formatter.format(record)
            for record in self.log_records
        ])

    def _activated_changed(self):
        if self.activated is None:
            return
        msg = self.activated.getMessage()
        if self.service.preferences.enable_agent:
            dialog = QualityAgentView(msg=msg, service=self.service)
            dialog.open()
        else:
            self.edit_traits(view=View(
                Item(
                    "activated_text",
                    editor=self.code_editor,
                    style="readonly",
                    show_label=False,
                ),
                width=800,
                height=600,
                resizable=True,
                buttons=["OK"],
                title="Log Message Detail",
            ))

    @cached_property
    def _get_activated_text(self):
        if self.activated is None:
            return ""
        else:
            return self.activated.getMessage()
Ejemplo n.º 20
0
class ContainerExample(HasTraits):
    plot = Instance(HPlotContainer)
    display_button = Button()
    display_button1 = Button()
    prev = Button()
    next = Button()
    unzoom = Button()

    traits_view = View(
        Group(Item('display_button', show_label=False),
              Item('display_button1', show_label=False),
              Item('prev', show_label=False),
              Item('next', show_label=False),
              Item('unzoom', show_label=False),
              orientation="horizontal"),
        Item('plot', editor=ComponentEditor(), show_label=False),
        # put the info box that lists the mouse location tuple kls karl
        width=1000,
        height=600,
        resizable=True,
        title="Chaco Plot",
        # How do I activate these? buttons=["do_nothing","do_nothing_1"]
    )

    def __init__(self):

        super(ContainerExample, self).__init__()

        filenames = []
        for parameter in sys.argv[1:]:
            print("processing parameter", parameter)
            if parameter.find("=") == -1:
                print("no = in parameter", parameter, "must be a file name")
                filenames.append(parameter)
        if len(filenames) < 1:
            print("just to help me test, if there are no files in the list, ")
            print("I will append the file foldplot1.rsf")
            filenames.append('foldplot1.rsf')

        self.seis_data_0 = SeisData(filenames[0])
        self.cmap = jet

        self.displayParameters = DisplayParameters()

        self.slice_y = self.displayParameters.slice_y

        print("self.slice_y=", self.slice_y)
        self.arrayPlotData = ArrayPlotData()
        self._update_images()

        x_extents = (self.seis_data_0.axis_start[1],
                     self.seis_data_0.axis_end[1])
        y_extents = (self.seis_data_0.axis_start[2],
                     self.seis_data_0.axis_end[2])
        bottomplot = Plot(self.arrayPlotData, origin="top left")
        self.bottomplot = bottomplot
        imgplot = bottomplot.img_plot("xz",
                                      xbounds=x_extents,
                                      ybounds=y_extents,
                                      colormap=self.cmap)[0]
        self.bottom = imgplot

        plotright = Plot(self.arrayPlotData,
                         origin="top left",
                         range2d=bottomplot.range2d)
        imgplotright = plotright.img_plot("xz",
                                          xbounds=x_extents,
                                          ybounds=y_extents,
                                          colormap=self.cmap)[0]
        self.right = imgplotright

        container = HPlotContainer(fill_padding=True,
                                   bgcolor="white",
                                   use_backbuffer=True)
        container.add(bottomplot)
        container.add(plotright)

        self.plot = container

        self.displayParameters = DisplayParameters()
        self.slice_y = self.displayParameters.slice_y

        imgplot.tools.append(CustomTool(imgplot))
        imgplot.tools.append(PanTool(imgplot, constrain_key="shift"))
        imgplot.overlays.append(
            ZoomTool(component=imgplot, tool_mode="box", always_on=False))
        imgplotright.tools.append(PanTool(imgplotright, constrain_key="shift"))
        imgplotright.overlays.append(
            ZoomTool(component=self.right, tool_mode="box", always_on=False))

    def _update_images(self):
        if self.displayParameters.gain != 0:
            rgain = 1. / self.displayParameters.gain
        else:
            rgain = 1
        print("rgain=", rgain)
        range = DataRange1D(low=self.seis_data_0.minval * rgain,
                            high=self.seis_data_0.maxval * rgain)
        self.colormap = self.cmap(range)

        slice = transpose(self.seis_data_0.vals[self.slice_y, :, :])
        self.slice = slice
        colorslice = (self.colormap.map_screen(slice) * 255).astype(uint8)
        # Transposed required because img_plot() expects data in row-major order
        #        self.arrayPlotData.set_data("xz", colorslicexz)
        self.arrayPlotData.set_data("xz", colorslice)

    def _marker_size_changed(self):
        self.scatter.marker_size = self.marker_size

    def _color_changed(self):
        self.scatter.marker_size = self.marker_size

    def _display_button_fired(self):
        print("Display button pushed")
        self.displayParameters.edit_traits()
        self._update_images()

    def _prev_fired(self):
        print("prev button pushed")
        slice_y = self.slice_y - self.displayParameters.slice_inc
        if (slice_y < 0):
            slice_y = self.seis_data_0.vals.shape[0] - 1
        print("after decrement slice_y=", slice_y)
        self.slice_y = slice_y
        self._update_images()

    def _next_fired(self):
        print("next button pushed")
        slice_y = self.slice_y + self.displayParameters.slice_inc
        print("shape=", self.seis_data_0.vals.shape)
        if (slice_y >= self.seis_data_0.vals.shape[0]):
            slice_y = 0
        print("after increment slice_y=", slice_y)
        self.slice_y = slice_y
        self._update_images()

    def _unzoom_fired(self):
        print("unzoom button pushed")
        print("self.bottomplot.range2d=", self.bottomplot.range2d)
        print("xmin/xmax=", \
            self.bottomplot.range2d.x_range.low, \
            self.bottomplot.range2d.x_range.high)
        print("ymin/ymax=", \
            self.bottomplot.range2d.y_range.low, \
            self.bottomplot.range2d.y_range.high)

        self.bottomplot.range2d.x_range.low = self.seis_data_0.axis_start[1]
        self.bottomplot.range2d.x_range.high = self.seis_data_0.axis_end[1]
        self.bottomplot.range2d.y_range.low = self.seis_data_0.axis_start[2]
        self.bottomplot.range2d.y_range.high = self.seis_data_0.axis_end[2]
Ejemplo n.º 21
0
"""
# Authors: Prabhu Ramachandran <*****@*****.**>
#          Judah De Paula <*****@*****.**>
# Copyright (c) 2005-2008, Enthought, Inc.
# License: BSD Style.

from traitsui.api import Item, Group, View, InstanceEditor
from mayavi.components.ui.actor import actor_view, texture_view

view = View(Group(
    Group(Item(name='contour', style='custom'),
          show_labels=False,
          show_border=True,
          label='Contours'),
    Group(Item(name='compute_normals'),
          Item(name='normals',
               style='custom',
               show_label=False,
               enabled_when='compute_normals'),
          show_border=True,
          label='Normals'),
    label='Contours',
),
            Group(
                Item('actor',
                     resizable=True,
                     style='custom',
                     editor=InstanceEditor(view=actor_view)),
                label='Actor',
                show_labels=False,
            ),
            Group(
Ejemplo n.º 22
0
class NINM_board0(HasTraits):
    # haven't figured out how to have a class that takes arguments (board 0/1)
    board = 0
    s = []
    m=8
#    print 'ninm1 root has board',board

    #s.append(Instance(Source,(board,1)))
    s1 = Instance(Source,(board,1))
    s2 = Instance(Source,(board,2))
    s3 = Instance(Source,(board,3))
    s4 = Instance(Source,(board,4))
    s5 = Instance(Source,(board,5))
    s6 = Instance(Source,(board,6))
    s7 = Instance(Source,(board,7))
    s8 = Instance(Source,(board,8))
    
    d1 = Instance(Detector,(board,1))
    d2 = Instance(Detector,(board,2))
    d3 = Instance(Detector,(board,3))
    d4 = Instance(Detector,(board,4))
    d5 = Instance(Detector,(board,5)) 
    d6 = Instance(Detector,(board,6))
    d7 = Instance(Detector,(board,7))
    d8 = Instance(Detector,(board,8))

    SallON = Button('Plot ALL Src')
    SallOFF = Button('Plot NO Src')
    DallON = Button('Plot ALL Det')
    DallOFF = Button('Plot NO Det')

    view = View( Group(

                   HGroup( Item('s1',label='S0',style='custom',show_label=True),
                           Item('s2',label='S1',style='custom',show_label=True),
                           Item('s3',label='S2',style='custom',show_label=True),
                           Item('s4',label='S3',style='custom',show_label=True),
                           Item('s5',label='S4',style='custom',show_label=True),
                           Item('s6',label='S5',style='custom',show_label=True),
                           Item('s7',label='S6',style='custom',show_label=True),
                           Item('s8',label='S7',style='custom',show_label=True),

                           VGroup(  Item('SallON',style="custom",show_label=False,width=-74,height=-25),
                                    Item('SallOFF',style="custom",show_label=False,width=-74,height=-25),
                                 ),
                           ),
                   
                   HGroup( Item('d1',label='D0',style='custom',show_label=True),
                           Item('d2',label='D1',style='custom',show_label=True),
                           Item('d3',label='D2',style='custom',show_label=True),
                           Item('d4',label='D3',style='custom',show_label=True),
                           Item('d5',label='D4',style='custom',show_label=True),
                           Item('d6',label='D5',style='custom',show_label=True),
                           Item('d7',label='D6',style='custom',show_label=True),
                           Item('d8',label='D7',style='custom',show_label=True),
                           
                           VGroup(  Item('DallON',style="custom",show_label=False,width=-74,height=-25),
                                    Item('DallOFF',style="custom",show_label=False,width=-74,height=-25),
                                    
                                 )                          
                         ),
                       ),
                 height=0.2,
                 buttons=NoButtons
               )

    #all source on and off button
                 
    def _SallON_fired(self):
#        print "allON fired"

        self.s1.enable = True
        self.s2.enable = True
        self.s3.enable = True
        self.s4.enable = True
        self.s5.enable = True
        self.s6.enable = True
        self.s7.enable = True
        self.s8.enable = True

    def _SallOFF_fired(self):
#        print "allOFF fired"
        self.s1.enable = False
        self.s2.enable = False
        self.s3.enable = False
        self.s4.enable = False
        self.s5.enable = False
        self.s6.enable = False
        self.s7.enable = False
        self.s8.enable = False

    def _DallON_fired(self):
#        print "allOFF fired"
        self.d1.enable = True
        self.d2.enable = True
        self.d3.enable = True
        self.d4.enable = True
        self.d5.enable = True
        self.d6.enable = True
        self.d7.enable = True
        self.d8.enable = True

    def _DallOFF_fired(self):
#        print "allOFF fired"
        self.d1.enable = False
        self.d2.enable = False
        self.d3.enable = False
        self.d4.enable = False
        self.d5.enable = False
        self.d6.enable = False
        self.d7.enable = False
        self.d8.enable = False

    def set_defaults(self):
        self._DallON_fired()
        self._SallON_fired()
Ejemplo n.º 23
0
class MATS2DScalarDamage(MATS2DEval):
    '''
    Scalar Damage Model.
    '''

    implements(IMATSEval)

    #---------------------------------------------------------------------------
    # Parameters of the numerical algorithm (integration)
    #---------------------------------------------------------------------------

    stress_state = Enum("plane_stress", "plane_strain")
    stiffness = Enum("secant", "algoritmic")

    #---------------------------------------------------------------------------
    # Material parameters
    #---------------------------------------------------------------------------

    E = Float(34e+3, label="E", desc="Young's Modulus", auto_set=False)
    nu = Float(0.2, label='nu', desc="Poison's ratio", auto_set=False)
    epsilon_0 = Float(59e-6,
                      label="eps_0",
                      desc="Breaking Strain",
                      auto_set=False)

    epsilon_f = Float(191e-4,
                      label="eps_f",
                      desc="Shape Factor",
                      auto_set=False)

    strain_norm = EitherType(
        klasses=[Mazars, Euclidean, Energy, Mises, Rankine])

    D_el = Property(Array(float), depends_on='E, nu, stress_state')

    @cached_property
    def _get_D_el(self):
        if self.stress_state == "plane_stress":
            return self._get_D_plane_stress()
        else:
            return self._get_D_plane_strain()

    # This event can be used by the clients to trigger an action upon
    # the completed reconfiguration of the material model
    #
    changed = Event

    #--------------------------------------------------------------------------
    # View specification
    #--------------------------------------------------------------------------

    view_traits = View(VSplit(
        Group(Item('E'), Item('nu'), Item('epsilon_0'), Item('epsilon_f'),
              Item('strain_norm')),
        Group(
            Item('stress_state', style='custom'),
            Item('stiffness', style='custom'),
            Spring(resizable=True),
            label='Configuration parameters',
            show_border=True,
        ),
    ),
                       resizable=True)

    #--------------------------------------------------------------------------
    # Private initialization methods
    #--------------------------------------------------------------------------

    #--------------------------------------------------------------------------
    # Setup for computation within a supplied spatial context
    #--------------------------------------------------------------------------

    def get_state_array_size(self):
        '''
        Return number of number to be stored in state array
        @param sctx:spatial context
        '''
        return 2

    def setup(self, sctx):
        '''
        Intialize state variables.
        @param sctx:spatial context
        '''
        state_arr_size = self.get_state_array_size()
        sctx.mats_state_array = zeros(state_arr_size, 'float_')
        # sctx.update_state_on = False

    def new_cntl_var(self):
        '''
        Return contoll variable array
        '''
        return zeros(3, float_)

    def new_resp_var(self):
        '''
        Return contoll response array
        '''
        return zeros(3, float_)

    #--------------------------------------------------------------------------
    # Evaluation - get the corrector and predictor
    #--------------------------------------------------------------------------

    def get_corr_pred(self, sctx, eps_app_eng, d_eps, tn, tn1, eps_avg=None):
        '''
        Corrector predictor computation.
        @param eps_app_eng input variable - engineering strain
        '''
        if eps_avg != None:
            pass
        else:
            eps_avg = eps_app_eng

        if sctx.update_state_on:

            eps_n = eps_avg - d_eps

            e_max, omega = self._get_state_variables(sctx, eps_n)

            sctx.mats_state_array[0] = e_max
            sctx.mats_state_array[1] = omega

        e_max, omega = self._get_state_variables(sctx, eps_app_eng)

        if self.stiffness == "algorithmic" and \
                    e_max > self.epsilon_0 and \
                    e_max > sctx.mats_state_array[0]:
            D_e_dam = self._get_alg_stiffness(eps_app_eng, e_max, omega)
        else:
            D_e_dam = (1 - omega) * self.D_el

        sigma = dot(((1 - omega) * self.D_el), eps_app_eng)

        # You print the stress you just computed and the value of the apparent E
        return sigma, D_e_dam

    #--------------------------------------------------------------------------
    # Subsidiary methods realizing configurable features
    #--------------------------------------------------------------------------
    def _get_state_variables(self, sctx, eps_app_eng):
        e_max = sctx.mats_state_array[0]
        omega = sctx.mats_state_array[1]

        f_trial = self.strain_norm.get_f_trial(eps_app_eng, self.D_el, self.E,
                                               self.nu, e_max)
        if f_trial > 0:
            e_max += f_trial
            omega = self._get_omega(e_max)

        return e_max, omega

    def _get_omega(self, kappa):
        '''
        Return new value of damage parameter
        @param kappa:
        '''
        epsilon_0 = self.epsilon_0
        epsilon_f = self.epsilon_f
        if kappa >= epsilon_0:
            # return 1.-epsilon_0/kappa*exp(-1*(kappa-epsilon_0)/epsilon_f)
            return 1. - epsilon_0 / kappa * exp(-1 * (kappa - epsilon_0) / \
                                                  (epsilon_f - epsilon_0))
        else:
            return 0.

    def _get_alg_stiffness(self, eps_app_eng, e_max, omega):
        '''
        Return algorithmic stiffness matrix
        @param eps_app_eng:strain
        @param e_max:kappa
        @param omega:damage parameter
        '''
        epsilon_0 = self.epsilon_0
        epsilon_f = self.epsilon_f
        dodk = epsilon_0 / (e_max * e_max) * exp(-(e_max - epsilon_0) / epsilon_f) + \
                epsilon_0 / e_max / epsilon_f * exp(-(e_max - epsilon_0) / epsilon_f)
        dede = self.strain_norm.get_dede(eps_app_eng, self.D_el, self.E,
                                         self.nu)
        D_alg = (1 - omega) * self.D_el - \
                dot(dot(self.D_el, eps_app_eng), dede) * dodk
        return D_alg

    def _get_D_plane_stress(self):
        '''
        Elastic Matrix - Plane Stress
        '''
        E = self.E
        nu = self.nu
        D_stress = zeros([3, 3])
        D_stress[0][0] = E / (1.0 - nu * nu)
        D_stress[0][1] = E / (1.0 - nu * nu) * nu
        D_stress[1][0] = E / (1.0 - nu * nu) * nu
        D_stress[1][1] = E / (1.0 - nu * nu)
        D_stress[2][2] = E / (1.0 - nu * nu) * (1.0 / 2.0 - nu / 2.0)
        return D_stress

    def _get_D_plane_strain(self):
        '''
        Elastic Matrix - Plane Strain
        '''
        E = self.E
        nu = self.nu
        D_strain = zeros([3, 3])
        D_strain[0][0] = E * (1.0 - nu) / (1.0 + nu) / (1.0 - 2.0 * nu)
        D_strain[0][1] = E / (1.0 + nu) / (1.0 - 2.0 * nu) * nu
        D_strain[1][0] = E / (1.0 + nu) / (1.0 - 2.0 * nu) * nu
        D_strain[1][1] = E * (1.0 - nu) / (1.0 + nu) / (1.0 - 2.0 * nu)
        D_strain[2][2] = E * (1.0 - nu) / (1.0 + nu) / (2.0 - 2.0 * nu)
        return D_strain

    #--------------------------------------------------------------------------
    # Response trace evaluators
    #--------------------------------------------------------------------------

    def get_omega(self, sctx, eps_app_eng, *args, **kw):
        '''
        Return damage parameter for RT
        @param sctx:spatial context
        @param eps_app_eng:actual strain
        '''
        return array([sctx.mats_state_array[1]])

    # Declare and fill-in the rte_dict - it is used by the clients to
    # assemble all the available time-steppers.
    #
    rte_dict = Trait(Dict)

    def _rte_dict_default(self):
        return {
            'sig_app': self.get_sig_app,
            'eps_app': self.get_eps_app,
            'omega': self.get_omega
        }
Ejemplo n.º 24
0
 Group(
     VGroup(
         HGroup(
             VGroup(
                 HGroup(  # Simulation Control
                     VGroup(
                         Item(
                             name="bit_rate",
                             label="Bit Rate (Gbps)",
                             tooltip="bit rate",
                             show_label=True,
                             enabled_when="True",
                             editor=TextEditor(auto_set=False, enter_set=True, evaluate=float),
                         ),
                         Item(
                             name="nbits",
                             label="Nbits",
                             tooltip="# of bits to run",
                             editor=TextEditor(auto_set=False, enter_set=True, evaluate=int),
                         ),
                         Item(
                             name="nspb",
                             label="Nspb",
                             tooltip="# of samples per bit",
                             editor=TextEditor(auto_set=False, enter_set=True, evaluate=int),
                         ),
                         Item(
                             name="mod_type",
                             label="Modulation",
                             tooltip="line signalling/modulation scheme",
                             editor=CheckListEditor(values=[(0, "NRZ"), (1, "Duo-binary"), (2, "PAM-4")]),
                         ),
                     ),
                     VGroup(
                         Item(name="do_sweep", label="Do Sweep", tooltip="Run parameter sweeps."),
                         Item(
                             name="sweep_aves",
                             label="SweepAves",
                             tooltip="# of trials, per sweep, for averaging.",
                             enabled_when="do_sweep == True",
                         ),
                         Item(
                             name="pattern_len",
                             label="PatLen",
                             tooltip="length of random pattern to use to construct bit stream",
                             editor=TextEditor(auto_set=False, enter_set=True, evaluate=int),
                         ),
                         Item(
                             name="eye_bits",
                             label="EyeBits",
                             tooltip="# of bits to use to form eye diagrams",
                             editor=TextEditor(auto_set=False, enter_set=True, evaluate=int),
                         ),
                     ),
                     VGroup(
                         Item(name="vod", label="Vod (V)", tooltip="Tx output voltage into matched load"),
                         Item(name="rn", label="Rn (V)", tooltip="standard deviation of random noise"),
                         Item(name="pn_mag", label="Pn (V)", tooltip="peak magnitude of periodic noise"),
                         Item(name="pn_freq", label="f(Pn) (MHz)", tooltip="frequency of periodic noise"),
                     ),
                 ),
                 label="Simulation Control",
                 show_border=True,
             ),
             VGroup(
                 Item(
                     name="thresh",
                     label="Pj Threshold (sigma)",
                     tooltip="Threshold for identifying periodic jitter spectral elements. (sigma)",
                 ),
                 Item(
                     name="impulse_length",
                     label="Impulse Response Length (ns)",
                     tooltip="Manual impulse response length override",
                 ),
                 Item(name="debug", label="Debug", tooltip="Enable to log extra information to console."),
                 label="Analysis Parameters",
                 show_border=True,
             ),
         ),
         HGroup(
             VGroup(
                 VGroup(
                     HGroup(
                         VGroup(
                             HGroup(
                                 Item(name="tx_ami_valid", show_label=False, style="simple", enabled_when="False"),
                                 Item(name="tx_ami_file", label="AMI File:", tooltip="Choose AMI file."),
                             ),
                             HGroup(
                                 Item(name="tx_dll_valid", show_label=False, style="simple", enabled_when="False"),
                                 Item(name="tx_dll_file", label="DLL File:", tooltip="Choose DLL file."),
                             ),
                         ),
                         VGroup(
                             Item(
                                 name="tx_use_ami",
                                 label="Use AMI",
                                 tooltip="You must select both files, first.",
                                 enabled_when="tx_ami_valid == True and tx_dll_valid == True",
                             ),
                             Item(
                                 name="tx_use_getwave",
                                 label="Use GetWave",
                                 tooltip="Use the model's GetWave() function.",
                                 enabled_when="tx_use_ami and tx_has_getwave",
                             ),
                             Item(
                                 "btn_cfg_tx",
                                 show_label=False,
                                 tooltip="Configure Tx AMI parameters.",
                                 enabled_when="tx_ami_valid == True",
                             ),
                         ),
                     ),
                     label="IBIS-AMI",
                     show_border=True,
                 ),
                 VGroup(
                     Item(
                         name="tx_taps",
                         editor=TableEditor(
                             columns=[
                                 ObjectColumn(name="name", editable=False),
                                 ObjectColumn(name="enabled", style="simple"),
                                 ObjectColumn(name="min_val", horizontal_alignment="center"),
                                 ObjectColumn(name="max_val", horizontal_alignment="center"),
                                 ObjectColumn(name="value", format="%+05.3f", horizontal_alignment="center"),
                                 ObjectColumn(name="steps", horizontal_alignment="center"),
                             ],
                             configurable=False,
                             reorderable=False,
                             sortable=False,
                             selection_mode="cell",
                             # auto_size=True,
                             rows=4,
                         ),
                         show_label=False,
                     ),
                     label="Native",
                     show_border=True,
                     enabled_when="tx_use_ami == False",
                 ),
                 label="Tx Equalization",
                 show_border=True,
             ),
             VGroup(
                 VGroup(
                     HGroup(
                         VGroup(
                             HGroup(
                                 Item(name="rx_ami_valid", show_label=False, style="simple", enabled_when="False"),
                                 Item(name="rx_ami_file", label="AMI File:", tooltip="Choose AMI file."),
                             ),
                             HGroup(
                                 Item(name="rx_dll_valid", show_label=False, style="simple", enabled_when="False"),
                                 Item(name="rx_dll_file", label="DLL File:", tooltip="Choose DLL file."),
                             ),
                         ),
                         VGroup(
                             Item(
                                 name="rx_use_ami",
                                 label="Use AMI",
                                 tooltip="You must select both files, first.",
                                 enabled_when="rx_ami_valid == True and rx_dll_valid == True",
                             ),
                             Item(
                                 name="rx_use_getwave",
                                 label="Use GetWave",
                                 tooltip="Use the model's GetWave() function.",
                                 enabled_when="rx_use_ami and rx_has_getwave",
                             ),
                             Item(
                                 "btn_cfg_rx",
                                 show_label=False,
                                 tooltip="Configure Rx AMI parameters.",
                                 enabled_when="rx_ami_valid == True",
                             ),
                         ),
                     ),
                     label="IBIS-AMI",
                     show_border=True,
                 ),
                 HGroup(
                     VGroup(
                         HGroup(
                             Item(
                                 name="use_ctle_file",
                                 label="fromFile",
                                 tooltip="Select CTLE impulse/step response from file.",
                             ),
                             Item(name="ctle_file", label="Filename", enabled_when="use_ctle_file == True",
                                 editor=FileEditor(dialog_style="open"),),
                         ),
                         HGroup(
                             Item(
                                 name="peak_freq",
                                 label="CTLE fp (GHz)",
                                 tooltip="CTLE peaking frequency (GHz)",
                                 enabled_when="use_ctle_file == False",
                             ),
                             Item(
                                 name="rx_bw",
                                 label="Bandwidth (GHz)",
                                 tooltip="unequalized signal path bandwidth (GHz).",
                                 enabled_when="use_ctle_file == False",
                             ),
                         ),
                         HGroup(
                             Item(
                                 name="peak_mag",
                                 label="CTLE boost (dB)",
                                 tooltip="CTLE peaking magnitude (dB)",
                                 format_str="%4.1f",
                                 enabled_when="use_ctle_file == False",
                             ),
                             Item(
                                 name="ctle_mode",
                                 label="CTLE mode",
                                 tooltip="CTLE Operating Mode",
                                 enabled_when="use_ctle_file == False",
                             ),
                             Item(
                                 name="ctle_offset",
                                 tooltip="CTLE d.c. offset (dB)",
                                 show_label=False,
                                 enabled_when='ctle_mode == "Manual"',
                             ),
                         ),
                     ),
                     label="Native",
                     show_border=True,
                     enabled_when="rx_use_ami == False",
                 ),
                 label="Rx Equalization",
                 show_border=True,
             ),
             springy=True,
         ),
         HGroup(
             VGroup(
                 HGroup(
                     Item(name="delta_t", label="Delta-t (ps)", tooltip="magnitude of CDR proportional branch"),
                     Item(name="alpha", label="Alpha", tooltip="relative magnitude of CDR integral branch"),
                 ),
                 HGroup(
                     Item(
                         name="n_lock_ave",
                         label="Lock Nave.",
                         tooltip="# of UI estimates to average, when determining lock",
                     ),
                     Item(
                         name="rel_lock_tol", label="Lock Tol.", tooltip="relative tolerance for determining lock"
                     ),
                     Item(
                         name="lock_sustain",
                         label="Lock Sus.",
                         tooltip="length of lock determining hysteresis vector",
                     ),
                 ),
                 label="CDR Parameters",
                 show_border=True,
                 # enabled_when='rx_use_ami == False  or  rx_use_ami == True and rx_use_getwave == False',
             ),
             VGroup(
                 Item(name="use_dfe", label="Use DFE", tooltip="Include DFE in simulation."),
                 Item(
                     name="sum_ideal",
                     label="Ideal DFE",
                     tooltip="Use ideal DFE. (performance boost)",
                     enabled_when="use_dfe == True",
                 ),
             ),
             VGroup(
                 HGroup(
                     Item(name="n_taps", label="Taps", tooltip="# of taps"),
                     Item(name="gain", label="Gain", tooltip="error feedback gain"),
                     Item(name="decision_scaler", label="Level", tooltip="target output magnitude"),
                 ),
                 HGroup(
                     Item(name="n_ave", label="Nave.", tooltip="# of CDR adaptations per DFE adaptation"),
                     Item(
                         name="sum_bw",
                         label="BW (GHz)",
                         tooltip="summing node bandwidth",
                         enabled_when="sum_ideal == False",
                     ),
                 ),
                 label="DFE Parameters",
                 show_border=True,
                 enabled_when="use_dfe == True",
                 # enabled_when='rx_use_ami == False  or  rx_use_ami == True and rx_use_getwave == False',
             ),
         ),
         # spring,
         label="Config.",
         id="config",
     ),
     # "Channel" tab.
     VGroup(  # Channel Parameters
         HGroup(
             VGroup(
                 Item(
                     name="rs",
                     label="Tx_Rs (Ohms)",
                     tooltip="Tx differential source impedance",
                 ),
                 Item(
                     name="cout",
                     label="Tx_Cout (pF)",
                     tooltip="Tx parasitic output capacitance (each pin)",
                 ),
                 label="Tx",
                 show_border=True,
             ),
             VGroup(
                 Item(
                     name="rin",
                     label="Rx_Rin (Ohms)",
                     tooltip="Rx differential input impedance",
                 ),
                 Item(
                     name="cin",
                     label="Rx_Cin (pF)",
                     tooltip="Rx parasitic input capacitance (each pin)",
                 ),
                 Item(
                     name="cac",
                     label="Rx_Cac (uF)",
                     tooltip="Rx a.c. coupling capacitance (each pin)",
                 ),
                 label="Rx",
                 show_border=True,
             ),
         ),
         VGroup(  # Interconnect
             HGroup(  # From File
                 Item(
                     name="use_ch_file",
                     show_label=False,
                     tooltip="Select channel frequency/impulse/step response from file.",
                 ),
                 Item(name="ch_file", label="File", enabled_when="use_ch_file == True", springy=True,
                     editor=FileEditor(dialog_style="open"),),
                 Item(name="Zref", label="Zref", enabled_when="use_ch_file == True",
                     tooltip="Reference (or, nominal) interconnect impedance."),
                 Item(name="padded", label="Zero-padded", enabled_when="use_ch_file == True"),
                 Item(name="windowed", label="Windowed", enabled_when="use_ch_file == True"),
                 Item(
                     name="f_step",
                     label="f_step",
                     enabled_when="use_ch_file == True",
                     tooltip="Frequency step to use in generating H(f).",
                 ),
                 Item(label="MHz"),
                 label="From File",
                 show_border=True,
             ),
             VGroup(  # Channel Designer
                 HGroup(
                     Item(
                         name="l_ch",
                         label="Length (m)",
                         enabled_when="use_ch_file == False",
                         tooltip="interconnect length",
                     ),
                     HGroup(
                         Item(
                             name="Theta0",
                             label="Loss Tan.",
                             tooltip="dielectric loss tangent",
                         ),
                         Item(
                             name="Z0",
                             label="Z0 (Ohms)",
                             tooltip="characteristic differential impedance",
                         ),
                         Item(
                             name="v0",
                             label="v_rel (c)",
                             # enabled_when="use_ch_file == False",
                             tooltip="normalized propagation velocity",
                         ),
                         Item(
                             name="Rdc",
                             label="Rdc (Ohms)",
                             tooltip="d.c. resistance",
                         ),
                         Item(
                             name="w0",
                             label="w0 (rads./s)",
                             tooltip="transition frequency",
                         ),
                         Item(
                             name="R0",
                             label="R0 (Ohms)",
                             tooltip="skin effect resistance",
                         ),
                         label="Native Channel Parameters",
                         show_border=True,
                         enabled_when="use_native == True and use_ch_file == False",
                     ),
                 ),
                 label="Channel Designer",
                 show_border=True,
             ),
             label="Interconnect",
             show_border=True,
         ),
         label="Channel",
         id="channel",
     ),
     # "Optimizer" tab.
     VGroup(
         HGroup(
             Group(
                 Item(
                     name="tx_tap_tuners",
                     editor=TableEditor(
                         columns=[
                             ObjectColumn(name="name", editable=False),
                             ObjectColumn(name="enabled"),
                             ObjectColumn(name="min_val"),
                             ObjectColumn(name="max_val"),
                             ObjectColumn(name="value", format="%+05.3f"),
                         ],
                         configurable=False,
                         reorderable=False,
                         sortable=False,
                         selection_mode="cell",
                         auto_size=False,
                         rows=4,
                         orientation="horizontal",
                         is_grid_cell=True,
                     ),
                     show_label=False,
                 ),
                 label="Tx Equalization",
                 show_border=True,
                 springy=True,
             ),
             # HGroup(
                 VGroup(
                     Item(
                         name="peak_mag_tune",
                         label="CTLE: boost (dB)",
                         tooltip="CTLE peaking magnitude (dB)",
                         format_str="%4.1f",
                     ),
                     HGroup(
                         Item(name="peak_freq_tune",
                              label="fp (GHz)",
                              tooltip="CTLE peaking frequency (GHz)"
                         ),
                         Item(
                             name="rx_bw_tune",
                             label="BW (GHz)",
                             tooltip="unequalized signal path bandwidth (GHz).",
                         ),
                     ),
                     HGroup(
                         Item(name="ctle_mode_tune", label="mode", tooltip="CTLE Operating Mode"),
                         Item(
                             name="ctle_offset_tune",
                             tooltip="CTLE d.c. offset (dB)",
                             show_label=False,
                             enabled_when='ctle_mode_tune == "Manual"',
                         ),
                     ),
                     HGroup(
                         Item(name="use_dfe_tune", label="DFE: Enable", tooltip="Include ideal DFE in optimization."),
                         Item(name="n_taps_tune", label="Taps", tooltip="Number of DFE taps."),
                     ),
                 label="Rx Equalization",
                 show_border=True,
                 ),
             # ),
             VGroup(
                 Item(
                     name="max_iter",
                     label="Max. Iterations",
                     tooltip="Maximum number of iterations to allow, during optimization.",
                 ),
                 Item(
                     name="rel_opt",
                     label="Rel. Opt.:",
                     format_str="%7.4f",
                     tooltip="Relative optimization metric.",
                     style="readonly",
                 ),
                 Item(
                     name="przf_err",
                     label="PRZF Err.:",
                     format_str="%5.3f",
                     tooltip="Pulse Response Zero Forcing approximation error.",
                     style="readonly",
                 ),
                 label="Tuning Options",
                 show_border=True,
             ),
             springy=False,
         ),
         Item(
             label="Note: Only CTLE boost will be optimized; please, set peak frequency, bandwidth, and mode appropriately.",
         ),
         Item("plot_h_tune", editor=ComponentEditor(), show_label=False, springy=True),
         HGroup(
             Item("btn_rst_eq", show_label=False, tooltip="Reset all values to those on the 'Config.' tab."),
             Item("btn_save_eq", show_label=False, tooltip="Store all values to 'Config.' tab."),
             Item("btn_opt_tx", show_label=False, tooltip="Run Tx tap weight optimization."),
             Item("btn_opt_rx", show_label=False, tooltip="Run Rx CTLE optimization."),
             Item("btn_coopt", show_label=False, tooltip="Run co-optimization."),
             Item("btn_abort", show_label=False, tooltip="Abort all optimizations."),
         ),
         label="Optimizer",
         id="eq_tune",
     ),
     Group(  # Responses
         Group(Item("plots_h", editor=ComponentEditor(), show_label=False), label="Impulses", id="plots_h"),
         Group(Item("plots_s", editor=ComponentEditor(), show_label=False), label="Steps", id="plots_s"),
         Group(Item("plots_p", editor=ComponentEditor(), show_label=False), label="Pulses", id="plots_p"),
         Group(Item("plots_H", editor=ComponentEditor(), show_label=False), label="Freq. Resp.", id="plots_H"),
         layout='tabbed',
         label='Responses',
         id='responses'
     ),
     Group(  # Results
         Group(Item("plots_dfe", editor=ComponentEditor(), show_label=False), label="DFE", id="plots_dfe"),
         Group(Item("plots_out", editor=ComponentEditor(), show_label=False), label="Outputs", id="plots_out"),
         Group(Item("plots_eye", editor=ComponentEditor(), show_label=False), label="Eyes", id="plots_eye"),
         Group(Item("plots_bathtub", editor=ComponentEditor(), show_label=False), label="Bathtubs", id="plots_bathtub"),
         Group(Item("sweep_info", style="readonly", show_label=False), label="Sweep Info"),
         layout='tabbed',
         label='Results',
         id='results'
     ),
     Group(  # Jitter
         Group(
             Item("plots_jitter_dist", editor=ComponentEditor(), show_label=False),
             label="Jitter Dist.",
             id="plots_jitter_dist",
         ),
         Group(
             Item("plots_jitter_spec", editor=ComponentEditor(), show_label=False),
             label="Jitter Spec.",
             id="plots_jitter_spec",
         ),
         Group(Item("jitter_info", style="readonly", show_label=False), label="Jitter Info"),
         layout='tabbed',
         label='Jitter',
         id='jitter'
     ),
     Group(  # Help
         Group(
             Item("ident", style="readonly", show_label=False),
             Item("perf_info", style="readonly", show_label=False),
             label="About",
         ),
         Group(Item("instructions", style="readonly", show_label=False), label="Guide"),
         Group(Item("console_log", show_label=False, style="custom"), label="Console", id="console"),
         layout='tabbed',
         label='Help',
         id='help'
     ),
     layout="tabbed",
     springy=True,
     id="tabs",
 ),
Ejemplo n.º 25
0
#  License: BSD Style.

# configure_traits_view_group.py -- Sample code to demonstrate
# configure_traits()

# --[Imports]--------------------------------------------------------------
from traits.api import HasTraits, Str, Int
from traitsui.api import View, Item, Group

# --[Code]-----------------------------------------------------------------


class SimpleEmployee(HasTraits):
    first_name = Str()
    last_name = Str()
    department = Str()

    employee_number = Str()
    salary = Int()


view1 = View(
    Group(Item(name='first_name'),
          Item(name='last_name'),
          Item(name='department'),
          label='Personnel profile',
          show_border=True))

sam = SimpleEmployee()
sam.configure_traits(view=view1)
Ejemplo n.º 26
0
class SegmentationEditor(ClusterEditor):
    # Options for track aggregation
    render_segments = Bool(False)
    segments_drawn = Bool(False)
    segments = List(Instance(Segment))
    parameters = []

    # Collect labels?
    segment_lookup = List()

    # local ui
    segment_editor_group = segment_editor_group

    def __init__(self, **traits):
        """ Creates a panel for editing cluster assignments.
        """
        super(SegmentationEditor, self).__init__(**traits)
        self.segment_editor_group = segment_editor_group

    def update_clusters(self):
        self.update_segments()

    def _auto_aggregate_changed(self):
        print "+ automatic aggregation changed:", self.auto_aggregate
        if self.auto_aggregate:
            self.update_segments()

    @on_trait_change('+parameter')
    def aggregation_param_changed(self, obj, name, old, new):
        print name, "parameter on aggregator changed"
        if name in self.parameters and self.auto_aggregate:
            self.update_segments()

    def _render_segments_changed(self):
        print "+ render_segments changed to", self.render_segments
        self.scene3d.disable_render = True
        for tds in self.track_sets:
            tds.set_segment_visibility(self.render_segments)
        self.scene3d.disable_render = False

    def update_segments(self):
        """ Creates new segments when a aggregation parameter has been
        changed. Will CREATE MayaVi objects if ``self.interactive``
        and ``self.render_segments`` are true.
        """

        print "+ Updating segment assignments."
        _segments = []
        for tnum, tds in enumerate(self.track_sets):
            __segments = []
            segments = self.segment(tds)
            number_of_labeled_segments, indices = summarize_segments(segments)
            labels = sorted(number_of_labeled_segments.keys())
            for labelnum, label in enumerate(labels):
                __segments.append(
                    Segment(ntracks=len(indices[label]),
                            segment_id=label,
                            indices=np.array(indices[label]),
                            scan_id=tds.scan_id,
                            segments=segments,
                            ncoords=number_of_labeled_segments[label]))

            # This grabs the colors from the rendered streamlines
            tds.set_segments(__segments)
            _segments += tds.segments  # collect the colorized version
        self.segments = _segments
        # Take care of the graphics
        if self.render_segments:
            print "\t++ rendering tracks"
            self.draw_segments()
        print "+ Aggregation Complete"

    ## Must be overwritten by a subclass
    def segment(self, track_datasets):
        raise NotImplementedError()

    def draw_segments(self):
        if not self.render_segments: return
        print "+ Drawing Segments"
        self.scene3d.disable_render = True
        for tds in self.track_sets:
            tds.draw_segments()
        self.scene3d.disable_render = False

    segment_table = TabularEditor(adapter=SegmentAdapter(), editable=False)

    segment_rows = Group(Item(name='segments',
                              editor=segment_table,
                              height=400,
                              show_label=False),
                         label="Segmentation Options",
                         show_border=True)
    algorithm_widgets = Group()

    def default_traits_view(self):
        return View(self.segment_editor_group)

    browser_view = View(
        HSplit(Item('scene3d',
                    editor=SceneEditor(scene_class=Scene),
                    height=500,
                    width=500),
               segment_editor_group,
               show_labels=False), )
Ejemplo n.º 27
0
class Volume(Module):
    """The Volume module visualizes scalar fields using volumetric
    visualization techniques.  This supports ImageData and
    UnstructuredGrid data.  It also supports the FixedPointRenderer
    for ImageData.  However, the performance is slow so your best bet
    is probably with the ImageData based renderers.
    """

    # The version of this class.  Used for persistence.
    __version__ = 0

    volume_mapper_type = DEnum(values_name='_mapper_types',
                               desc='volume mapper to use')

    ray_cast_function_type = DEnum(values_name='_ray_cast_functions',
                                   desc='Ray cast function to use')

    volume = ReadOnly

    volume_mapper = Property(record=True)

    volume_property = Property(record=True)

    ray_cast_function = Property(record=True)

    lut_manager = Instance(VolumeLUTManager, args=(), allow_none=False,
                           record=True)

    input_info = PipelineInfo(datasets=['image_data',
                                        'unstructured_grid'],
                              attribute_types=['any'],
                              attributes=['scalars'])

    ########################################
    # View related code.

    update_ctf = Button('Update CTF')

    view = View(Group(Item(name='_volume_property', style='custom',
                           editor=VolumePropertyEditor,
                           resizable=True),
                      Item(name='update_ctf'),
                      label='CTF',
                      show_labels=False),
                Group(Item(name='volume_mapper_type'),
                      Group(Item(name='_volume_mapper',
                                 style='custom',
                                 resizable=True),
                            show_labels=False
                            ),
                      Item(name='ray_cast_function_type'),
                      Group(Item(name='_ray_cast_function',
                                 enabled_when='len(_ray_cast_functions) > 0',
                                 style='custom',
                                 resizable=True),
                            show_labels=False),
                      label='Mapper',
                      ),
                Group(Item(name='_volume_property', style='custom',
                           resizable=True),
                      label='Property',
                      show_labels=False),
                Group(Item(name='volume', style='custom',
                           editor=InstanceEditor(),
                           resizable=True),
                      label='Volume',
                      show_labels=False),
                Group(Item(name='lut_manager', style='custom',
                           resizable=True),
                      label='Legend',
                      show_labels=False),
                resizable=True
                )

    ########################################
    # Private traits
    _volume_mapper = Instance(tvtk.AbstractVolumeMapper)
    _volume_property = Instance(tvtk.VolumeProperty)
    _ray_cast_function = Instance(tvtk.Object)

    _mapper_types = List(Str, ['TextureMapper2D', 'RayCastMapper', ])

    _available_mapper_types = List(Str)

    _ray_cast_functions = List(Str)

    current_range = Tuple

    # The color transfer function.
    _ctf = Instance(ColorTransferFunction)
    # The opacity values.
    _otf = Instance(PiecewiseFunction)

    ######################################################################
    # `object` interface
    ######################################################################
    def __get_pure_state__(self):
        d = super(Volume, self).__get_pure_state__()
        d['ctf_state'] = save_ctfs(self._volume_property)
        for name in ('current_range', '_ctf', '_otf'):
            d.pop(name, None)
        return d

    def __set_pure_state__(self, state):
        self.volume_mapper_type = state['_volume_mapper_type']
        state_pickler.set_state(self, state, ignore=['ctf_state'])
        ctf_state = state['ctf_state']
        ctf, otf = load_ctfs(ctf_state, self._volume_property)
        self._ctf = ctf
        self._otf = otf
        self._update_ctf_fired()

    ######################################################################
    # `Module` interface
    ######################################################################
    def start(self):
        super(Volume, self).start()
        self.lut_manager.start()

    def stop(self):
        super(Volume, self).stop()
        self.lut_manager.stop()

    def setup_pipeline(self):
        """Override this method so that it *creates* the tvtk
        pipeline.
        """
        v = self.volume = tvtk.Volume()
        vp = self._volume_property = tvtk.VolumeProperty()

        self._ctf = ctf = default_CTF(0, 255)
        self._otf = otf = default_OTF(0, 255)
        vp.set_color(ctf)
        vp.set_scalar_opacity(otf)
        vp.shade = True
        vp.interpolation_type = 'linear'
        v.property = vp

        v.on_trait_change(self.render)
        vp.on_trait_change(self.render)

        available_mappers = find_volume_mappers()
        if is_volume_pro_available():
            self._mapper_types.append('VolumeProMapper')
            available_mappers.append('VolumeProMapper')

        self._available_mapper_types = available_mappers
        if 'FixedPointVolumeRayCastMapper' in available_mappers:
            self._mapper_types.append('FixedPointVolumeRayCastMapper')

        self.actors.append(v)

    def update_pipeline(self):
        """Override this method so that it *updates* the tvtk pipeline
        when data upstream is known to have changed.

        This method is invoked (automatically) when any of the inputs
        sends a `pipeline_changed` event.
        """
        mm = self.module_manager
        if mm is None:
            return


        dataset = mm.source.get_output_dataset()

        ug = hasattr(tvtk, 'UnstructuredGridVolumeMapper')
        if ug:
            if not dataset.is_a('vtkImageData') \
                   and not dataset.is_a('vtkUnstructuredGrid'):
                error('Volume rendering only works with '\
                      'StructuredPoints/ImageData/UnstructuredGrid datasets')
                return
        elif not dataset.is_a('vtkImageData'):
            error('Volume rendering only works with '\
                  'StructuredPoints/ImageData datasets')
            return

        self._setup_mapper_types()
        self._setup_current_range()
        self._volume_mapper_type_changed(self.volume_mapper_type)
        self._update_ctf_fired()
        self.pipeline_changed = True

    def update_data(self):
        """Override this method so that it flushes the vtk pipeline if
        that is necessary.

        This method is invoked (automatically) when any of the inputs
        sends a `data_changed` event.
        """
        self._setup_mapper_types()
        self._setup_current_range()
        self._update_ctf_fired()
        self.data_changed = True

    ######################################################################
    # Non-public methods.
    ######################################################################
    def _setup_mapper_types(self):
        """Sets up the mapper based on input data types.
        """
        dataset = self.module_manager.source.get_output_dataset()
        if dataset.is_a('vtkUnstructuredGrid'):
            if hasattr(tvtk, 'UnstructuredGridVolumeMapper'):
                check = ['UnstructuredGridVolumeZSweepMapper',
                         'UnstructuredGridVolumeRayCastMapper',
                         ]
                mapper_types = []
                for mapper in check:
                    if mapper in self._available_mapper_types:
                        mapper_types.append(mapper)
                if len(mapper_types) == 0:
                    mapper_types = ['']
                self._mapper_types = mapper_types
                return
        else:
            if dataset.point_data.scalars.data_type not in \
               [vtkConstants.VTK_UNSIGNED_CHAR,
                vtkConstants.VTK_UNSIGNED_SHORT]:
                if 'FixedPointVolumeRayCastMapper' \
                       in self._available_mapper_types:
                    self._mapper_types = ['FixedPointVolumeRayCastMapper']
                else:
                    error('Available volume mappers only work with \
                    unsigned_char or unsigned_short datatypes')
            else:
                mapper_types = ['TextureMapper2D', 'RayCastMapper']
                check = ['FixedPointVolumeRayCastMapper',
                         'VolumeProMapper'
                         ]
                for mapper in check:
                    if mapper in self._available_mapper_types:
                        mapper_types.append(mapper)
                self._mapper_types = mapper_types

    def _setup_current_range(self):
        mm = self.module_manager
        # Set the default name and range for our lut.
        lm = self.lut_manager
        slm = mm.scalar_lut_manager
        lm.set(default_data_name=slm.default_data_name,
               default_data_range=slm.default_data_range)

        # Set the current range.
        dataset = mm.source.get_output_dataset()
        sc = dataset.point_data.scalars
        if sc is not None:
            rng = sc.range
        else:
            error('No scalars in input data!')
            rng = (0, 255)

        if self.current_range != rng:
            self.current_range = rng

    def _get_volume_mapper(self):
        return self._volume_mapper

    def _get_volume_property(self):
        return self._volume_property

    def _get_ray_cast_function(self):
        return self._ray_cast_function

    def _volume_mapper_type_changed(self, value):
        mm = self.module_manager
        if mm is None:
            return

        old_vm = self._volume_mapper
        if old_vm is not None:
            old_vm.on_trait_change(self.render, remove=True)

        if value == 'RayCastMapper':
            new_vm = tvtk.VolumeRayCastMapper()
            self._volume_mapper = new_vm
            self._ray_cast_functions = ['RayCastCompositeFunction',
                                        'RayCastMIPFunction',
                                        'RayCastIsosurfaceFunction']
            new_vm.volume_ray_cast_function = tvtk.VolumeRayCastCompositeFunction()
        elif value == 'TextureMapper2D':
            new_vm = tvtk.VolumeTextureMapper2D()
            self._volume_mapper = new_vm
            self._ray_cast_functions = ['']
        elif value == 'VolumeProMapper':
            new_vm = tvtk.VolumeProMapper()
            self._volume_mapper = new_vm
            self._ray_cast_functions = ['']
        elif value == 'FixedPointVolumeRayCastMapper':
            new_vm = tvtk.FixedPointVolumeRayCastMapper()
            self._volume_mapper = new_vm
            self._ray_cast_functions = ['']
        elif value == 'UnstructuredGridVolumeRayCastMapper':
            new_vm = tvtk.UnstructuredGridVolumeRayCastMapper()
            self._volume_mapper = new_vm
            self._ray_cast_functions = ['']
        elif value == 'UnstructuredGridVolumeZSweepMapper':
            new_vm = tvtk.UnstructuredGridVolumeZSweepMapper()
            self._volume_mapper = new_vm
            self._ray_cast_functions = ['']

        src = mm.source
        self.configure_connection(new_vm, src)
        self.volume.mapper = new_vm
        new_vm.on_trait_change(self.render)

    def _update_ctf_fired(self):
        set_lut(self.lut_manager.lut, self._volume_property)
        self.render()

    def _current_range_changed(self, old, new):
        rescale_ctfs(self._volume_property, new)
        self.render()

    def _ray_cast_function_type_changed(self, old, new):
        rcf = self.ray_cast_function
        if len(old) > 0:
            rcf.on_trait_change(self.render, remove=True)

        if len(new) > 0:
            new_rcf = getattr(tvtk, 'Volume%s'%new)()
            new_rcf.on_trait_change(self.render)
            self._volume_mapper.volume_ray_cast_function = new_rcf
            self._ray_cast_function = new_rcf
        else:
            self._ray_cast_function = None

        self.render()

    def _scene_changed(self, old, new):
        super(Volume, self)._scene_changed(old, new)
        self.lut_manager.scene = new
Ejemplo n.º 28
0
class Animator(HasTraits):
    """ Convenience class to manage a timer and present a convenient
        UI.  This is based on the code in `tvtk.tools.visual`.
        Here is a simple example of using this class::

            >>> from mayavi import mlab
            >>> def anim():
            ...     f = mlab.gcf()
            ...     while 1:
            ...         f.scene.camera.azimuth(10)
            ...         f.scene.render()
            ...         yield
            ...
            >>> anim = anim()
            >>> t = Animator(500, anim.next)
            >>> t.edit_traits()

        This makes it very easy to animate your visualizations and control
        it from a simple UI.

        **Notes**

        If you want to modify the data plotted by an `mlab` function call,
        please refer to the section on: :ref:`mlab-animating-data`
    """

    ########################################
    # Traits.

    start = Button('Start Animation')
    stop = Button('Stop Animation')
    delay = Range(10, 100000, 500, desc='frequency with which timer is called')

    # The internal timer we manage.
    timer = Any

    ######################################################################
    # User interface view

    traits_view = View(Group(Item('start'), Item('stop'), show_labels=False),
                       Item('_'),
                       Item(name='delay'),
                       title='Animation Controller',
                       buttons=['OK'])

    ######################################################################
    # Initialize object
    def __init__(self, millisec, callable, *args, **kwargs):
        """Constructor.

        **Parameters**

          :millisec: int specifying the delay in milliseconds
                     between calls to the callable.

          :callable: callable function to call after the specified
                     delay.

          :\*args: optional arguments to be passed to the callable.

          :\*\*kwargs: optional keyword arguments to be passed to the callable.

        """
        HasTraits.__init__(self)
        self.delay = millisec
        self.ui = None
        self.timer = Timer(millisec, callable, *args, **kwargs)

    ######################################################################
    # `Animator` protocol.
    ######################################################################
    def show(self):
        """Show the animator UI.
        """
        self.ui = self.edit_traits()

    def close(self):
        """Close the animator UI.
        """
        if self.ui is not None:
            self.ui.dispose()

    ######################################################################
    # Non-public methods, Event handlers
    def _start_fired(self):
        self.timer.Start(self.delay)

    def _stop_fired(self):
        self.timer.Stop()

    def _delay_changed(self, value):
        t = self.timer
        if t is None:
            return
        if t.IsRunning():
            t.Stop()
            t.Start(value)
Ejemplo n.º 29
0
            elif self.position < 1:
                raise ValueError("Invalid position")
            PhaseValue(self.model, self, *self._get_attributes())
            self.error = False
        except Exception, e:
            self.error = True
            self.error_msg = str(e)

    view = View(Group(VGroup(
        Item("position", style="custom"),
        Item("id", label="Port-ID", style="custom"),
        Item("name"),
        Item("start_value"),
        Item("end_value"),
        Item("ticks"),
        Item("reset_time"),
    ),
                      Group(UItem("error_msg", style="readonly"),
                            label="Error:",
                            visible_when="error",
                            show_border=True,
                            style_sheet="*{color:red}"),
                      label="Value-Phase"),
                buttons=[ConfirmButton, CancelButton],
                resizable=True,
                width=300,
                height=200,
                title="Create Value-Phase")


class PhaseTime(Phase):
Ejemplo n.º 30
0
class DofCellView(CellView):

    '''View a single cell instance.
    '''
    # implements(ICellView)

    elem_dofs = Array

    def set_cell_traits(self):
        '''Set the trait values for the current cell_idx
        '''
        self.elem_dofs = self.cell_grid.get_cell_dofs(self.cell_idx)

    #---------------------------------------------------------------------
    # Visualize
    #---------------------------------------------------------------------
    draw_cell = Bool(False)

    view = View(
        Item('cell_idx', style='readonly',
             resizable=False, label='Cell index'),
        Group(Item('elem_dofs',
                   editor=dof_tabular_editor,
                   show_label=False,
                   resizable=True,
                   style='readonly')),
        Item('draw_cell', label='show DOFs')
    )

    # register the pipelines for plotting labels and geometry
    #
    # mvp_elem_labels = Trait(MVPointLabels)
    #
    # def _mvp_elem_labels_default(self):
    #     return MVPointLabels(name='Geo node numbers',
    #                          points=self._get_cell_mvpoints,
    #                          vectors=self._get_cell_labels,
    #                          color=(0.0, 0.411765, 0.882353))
    #
    # mvp_elem_geo = Trait(MVPolyData)
    #
    # def _mvp_elem_geo_default(self):
    #     return MVPolyData(name='Geo node numbers',
    #                       points=self._get_elem_points,
    #                       lines=self._get_elem_lines,
    #                       color=(0.254902, 0.411765, 0.882353))

    def _get_cell_mvpoints(self):
        return self.cell_grid.get_cell_mvpoints(self.cell_idx)

    def _get_cell_labels(self):
        cell_dofs = self.cell_grid.get_cell_dofs(self.cell_idx)
        shape = cell_dofs.shape
        if shape[1] < 3:
            cd = np.zeros((shape[0], 3))
            cd[:, :shape[1]] = cell_dofs
            return cd
        else:
            return cell_dofs

    def redraw(self):
        if self.draw_cell:
            self.mvp_elem_labels.redraw(label_mode='label_vectors')
Ejemplo n.º 31
0
# View描述了界面的视图类,Item模块描述了界面中的控件类
g1 = [
    Item("model_name", label=u"模型名称"),
    Item("category", label=u"模型类型"),
]
g2 = [
    Item("model_number", label=u"模型数量"),
    Item("vertices", label=u"顶点数量"),
]


class ModelManager(HasTraits):
    model_name = Str
    category = Str
    model_number = Int
    vertices = Int

    traits_view = View(Group(*g1, label=u"模型信息", show_border=True),
                       Group(*g2, label=u"统计数据", show_border=True),
                       title=u"内部视图")


global_view = View(Group(*g1, label=u"模型信息11", show_border=True),
                   Group(*g2, label=u"统计数据11", show_border=True),
                   title=u"外部视图")

model = ModelManager()
# model.configure_traits()    #默认是内部视图
# model.configure_traits(view="traits_view")  #有选择的选中某个内部视图
model.configure_traits(view=global_view)  #直接将外部视图赋给view