コード例 #1
0
def _create_plot_component():
    # Create a GridContainer to hold all of our plots
    container = GridContainer(padding=20, fill_padding=True,
                              bgcolor="lightgray", use_backbuffer=True,
                              shape=(3,3), spacing=(12,12))

    # Create the initial series of data
    x = linspace(-5, 15.0, 100)
    pd = ArrayPlotData(index = x)

    # Plot some bessel functions and add the plots to our container
    for i in range(9):
        pd.set_data("y" + str(i), jn(i,x))
        plot = Plot(pd)
        plot.plot(("index", "y" + str(i)),
                  color=tuple(COLOR_PALETTE[i]), line_width=2.0,
                  bgcolor = "white", border_visible=True)

        # Tweak some of the plot properties
        plot.border_width = 1
        plot.padding = 10

        # Set each plot's aspect ratio based on its position in the
        # 3x3 grid of plots.
        n,m = divmod(i, 3)
        plot.aspect_ratio = float(n+1) / (m+1)

        # Attach some tools to the plot
        plot.tools.append(PanTool(plot))
        zoom = ZoomTool(plot, tool_mode="box", always_on=False)
        plot.overlays.append(zoom)

        # Add to the grid container
        container.add(plot)
    return container
コード例 #2
0
 def test_nonresizable_container(self):
     cont = GridContainer(shape=(1,1), resizable="")
     comp1 = StaticPlotComponent([200,300])
     cont.add(comp1)
     cont.do_layout()
     self.assert_tuple(comp1.position, (0,0))
     self.assert_tuple(comp1.bounds, (200,300))
     return
コード例 #3
0
ファイル: image_stack_viewer.py プロジェクト: pearu/iocbio
    def get_plot(self):
        pixel_sizes = self.data_source.voxel_sizes
        shape = self.data.shape
        m = min(pixel_sizes)
        s = [int(d*sz/m) for d, sz in zip(shape, pixel_sizes)]
        if 1: # else physical aspect ratio is enabled
            ss = max(s)/4
            s = [max(s,ss) for s in s]
        plot_sizes = dict (xy = (s[2], s[1]), xz = (s[2], s[0]), zy = (s[0],s[1]), zz=(s[0],s[0]))

        plots = GridContainer(shape=(2,2), spacing=(3, 3), padding = 50, aspect_ratio=1)
        pxy = Plot(self.plotdata, padding=1, fixed_preferred_size = plot_sizes['xy'],
                   x_axis=PlotAxis (orientation='top'),
                   )
        pxz = Plot(self.plotdata, padding=1, fixed_preferred_size = plot_sizes['xz'],
                   )
        pzy = Plot(self.plotdata, padding=1, fixed_preferred_size = plot_sizes['zy'],
                   #orientation = 'v',  # cannot use 'v' because of img_plot assumes row-major ordering
                   x_axis=PlotAxis(orientation='top'), 
                   y_axis=PlotAxis(orientation='right'),
                   )
        pzz = Plot(self.plotdata, padding=1, fixed_preferred_size = plot_sizes['zz'])

        plots.add(pxy, pzy, pxz, pzz)

        self.plots =  dict(xy = pxy.img_plot('xy', colormap=bone)[0],
                           xz = pxz.img_plot('xz', colormap=bone)[0],
                           zy = pzy.img_plot('zy', colormap=bone)[0],
                           zz = pzz.img_plot('zz')[0],
                           xyp = pxy.plot(('z_x', 'z_y'), type='scatter', color='orange', marker='circle', marker_size=3, 
                                          selection_marker_size = 3, selection_marker='circle')[0],
                           xzp = pxz.plot(('y_x', 'y_z'), type='scatter', color='orange', marker='circle', marker_size=3,
                                          selection_marker_size = 3, selection_marker='circle')[0],
                           zyp = pzy.plot(('x_z', 'x_y'), type='scatter', color='orange', marker='circle', marker_size=3,
                                          selection_marker_size = 3, selection_marker='circle')[0],
                           )

        for p in ['xy', 'xz', 'zy']:
            self.plots[p].overlays.append(ZoomTool(self.plots[p]))
            self.plots[p].tools.append(PanTool(self.plots[p], drag_button='right'))

            imgtool = ImageInspectorTool(self.plots[p])
            self.plots[p].tools.append(imgtool)
            overlay = ImageInspectorOverlay(component=self.plots[p],
                                            bgcolor = 'white',
                                            image_inspector=imgtool)
            self.plots['zz'].overlays.append(overlay)

            self.plots[p+'p'].tools.append (ScatterInspector(self.plots[p+'p'], selection_mode = 'toggle'))

        self.plots['xyp'].index.on_trait_change (self._xyp_metadata_handler, 'metadata_changed')
        self.plots['xzp'].index.on_trait_change (self._xzp_metadata_handler, 'metadata_changed')
        self.plots['zyp'].index.on_trait_change (self._zyp_metadata_handler, 'metadata_changed')

        plot = HPlotContainer()
        # todo: add colormaps
        plot.add(plots)
        return plot
コード例 #4
0
 def test_single_cell(self):
     cont = GridContainer(shape=(1,1))
     comp1 = StaticPlotComponent([200,300])
     cont.add(comp1)
     cont.do_layout()
     # it would be nice to make all boolean tests here trigger
     # assert failures, maybe using Pypy?
     self.assert_tuple(comp1.position, (0,0))
     self.assert_tuple(comp1.bounds, (200,300))
     return
コード例 #5
0
 def _plot_default(self):
     outcomes, results, time = self._prepare_data()
     
     # get the x,y data to plot
     pds = []    
     for outcome in outcomes:
         pd  = ArrayPlotData(index = time)
         result = results.get(outcome)
         for j in range(result.shape[0]): 
             pd.set_data("y"+str(j), result[j, :] )
         pds.append(pd)
     
     # Create a container and add our plots
     container = GridContainer(
                               bgcolor="white", use_backbuffer=True,
                               shape=(len(outcomes),1))
 
     #plot data
     tools = []
     for j, outcome in enumerate(outcomes):
         pd1 = pds[j]
 
         # Create some line plots of some of the data
         plot = Plot(pd1, title=outcome, border_visible=True, 
                     border_width = 1)
         plot.legend.visible = False
     
         a = len(pd1.arrays)- 1
         if a > 1000:
             a = 1000
         for i in range(a):
             plotvalue = "y"+str(i)
             color = colors[i%len(colors)]
             plot.plot(("index", plotvalue), name=plotvalue, color=color)
             
         for value in plot.plots.values():
             for entry in value:
                 entry.index.sort_order = 'ascending'
 
         # Attach the selector tools to the plot
         selectorTool1 = LineSelectorTool(component=plot)
         plot.tools.append(selectorTool1)
         tools.append(selectorTool1)
         container.add(plot)
 
     #make sure the selector tools know each other
     
     for tool in tools:
         a = set(tools) - set([tool])
         tool._other_selectors = list(a)
         tool._demo = self
 
     return container
コード例 #6
0
    def test_non_resizable(self):
        cont = GridContainer(shape=(2,2), spacing=(10,10),
                             halign="center", valign="center")
        ul = StaticPlotComponent([100,100], resizable="")
        ur = StaticPlotComponent([100,100], resizable="")
        ll = StaticPlotComponent([100,100], resizable="")
        lr = StaticPlotComponent([100,100], resizable="")
        cont.component_grid = [[ul, ur], [ll, lr]]

        cont.bounds = [240, 240]
        cont.do_layout()
        self.assert_tuple(ul.position, (10,130))
        self.assert_tuple(ul.bounds, (100,100))
        self.assert_tuple(ur.position, (130,130))
        self.assert_tuple(ur.bounds, (100, 100))
        self.assert_tuple(ll.position, (10,10))
        self.assert_tuple(ll.bounds, (100,100))
        self.assert_tuple(lr.position, (130,10))
        self.assert_tuple(lr.bounds, (100,100))

        cont.bounds = [280, 280]
        cont.do_layout()
        self.assert_tuple(ul.position, (20,160))
        self.assert_tuple(ul.bounds, (100,100))
        self.assert_tuple(ur.position, (160,160))
        self.assert_tuple(ur.bounds, (100, 100))
        self.assert_tuple(ll.position, (20,20))
        self.assert_tuple(ll.bounds, (100,100))
        self.assert_tuple(lr.position, (160,20))
        self.assert_tuple(lr.bounds, (100,100))
コード例 #7
0
    def test_empty_container(self):
        # FIXME:
        #   This test is failing when run with nosetests and coverage.
        #   Therefore, it is skipped when coverage is imported.
        #   If you want to fix this, please look at:
        #     https://svn.enthought.com/enthought/ticket/1618
        #   where I posted more details about this problem.
        if 'coverage' in sys.modules:
            raise nose.SkipTest

        cont = GridContainer(shape=(1,1))
        cont.bounds = [100,100]
        cont.do_layout()
        return
コード例 #8
0
    def test_resizable_mixed_h(self):
        # Tests the layout of a non-resizable component, a resizable with a
        # preferred size, and a fully resizable component in a horizontal
        # GridContainer
        cont = GridContainer(shape=(3,1), spacing=(0,0),
                             halign="center", valign="center")
        left = StaticPlotComponent([50,10], resizable="")
        middle = ResizablePlotComponent([100,10])
        right = StaticPlotComponent([0,0], resizable="hv")

        cont.component_grid = [[left, middle, right]]
        cont.bounds = [200, 10]
        cont.do_layout()
        self.assert_tuple(left.position, (0,0))
        self.assert_tuple(left.bounds, (50,10))
        self.assert_tuple(middle.position, (50,0))
        self.assert_tuple(middle.bounds, (100,10))
        self.assert_tuple(right.position, (150,0))
        self.assert_tuple(right.bounds, (50,10))
コード例 #9
0
 def test_resizable2(self):
     # Tests a resizable component that also has a preferred size
     cont = GridContainer(shape=(2,2), spacing=(0,0),
                          halign="center", valign="center")
     ul = StaticPlotComponent([150,150], resizable="hv")
     lr = StaticPlotComponent([0,0], resizable="hv")
     top = StaticPlotComponent([0,0], resizable="hv")
     left = StaticPlotComponent([0,0], resizable="hv")
     cont.component_grid = [[ul, top], [left, lr]]
     cont.bounds = [200, 200]
     cont.do_layout()
     self.assert_tuple(ul.position, (0,100))
     self.assert_tuple(ul.bounds, (100,100))
     self.assert_tuple(top.position, (100,100))
     self.assert_tuple(top.bounds, (100,100))
     self.assert_tuple(left.position, (0,0))
     self.assert_tuple(left.bounds, (100,100))
     self.assert_tuple(lr.position, (100,0))
     self.assert_tuple(lr.bounds, (100,100))
コード例 #10
0
 def test_two_by_two(self):
     """ Tests a 2x2 grid of components """
     cont = GridContainer(shape=(2,2), halign="center", valign="center")
     ul = StaticPlotComponent([50,50])     # upper-left component
     lr = StaticPlotComponent([100,100])   # lower-right component
     top = StaticPlotComponent([0,0], resizable="hv")
     left = StaticPlotComponent([0,0], resizable="hv")
     cont.component_grid = [[ul, top], [left, lr]]
     cont.bounds = [150, 150]
     cont.do_layout()
     self.assert_tuple(ul.position, (0,100))
     self.assert_tuple(ul.bounds, (50,50))
     self.assert_tuple(top.position, (50,100))
     self.assert_tuple(top.bounds, (100, 50))
     self.assert_tuple(left.position, (0,0))
     self.assert_tuple(left.bounds, (50,100))
     self.assert_tuple(lr.position, (50,0))
     self.assert_tuple(lr.bounds, (100,100))
     return
コード例 #11
0
 def test_spacing(self):
     cont = GridContainer(shape=(2,2), spacing=(10,10),
                          halign="center", valign="center")
     ul = StaticPlotComponent([50,50])     # upper-left component
     lr = StaticPlotComponent([100,100])   # lower-right component
     top = StaticPlotComponent([0,0], resizable="hv")
     left = StaticPlotComponent([0,0], resizable="hv")
     cont.component_grid = [[ul, top], [left, lr]]
     cont.bounds = [190, 190]
     cont.do_layout()
     self.assert_tuple(ul.position, (10,130))
     self.assert_tuple(ul.bounds, (50,50))
     self.assert_tuple(top.position, (80,130))
     self.assert_tuple(top.bounds, (100, 50))
     self.assert_tuple(left.position, (10,10))
     self.assert_tuple(left.bounds, (50,100))
     self.assert_tuple(lr.position, (80,10))
     self.assert_tuple(lr.bounds, (100,100))
     return
コード例 #12
0
 def test_resizable_mixed2(self):
     # Tests laying out resizable components with preferred
     # sized alongside non-resizable components.
     cont = GridContainer(shape=(2,2), spacing=(0,0),
                          halign="center", valign="center")
     ul = ResizablePlotComponent([150,150])
     lr = StaticPlotComponent([50,50], resizable="")
     top = StaticPlotComponent([0,0], resizable="hv")
     left = StaticPlotComponent([0,0], resizable="hv")
     cont.component_grid = [[ul, top], [left, lr]]
     cont.bounds = [200, 200]
     cont.do_layout()
     self.assert_tuple(ul.position, (0,50))
     self.assert_tuple(ul.bounds, (150,150))
     self.assert_tuple(top.position, (150,50))
     self.assert_tuple(top.bounds, (50,150))
     self.assert_tuple(left.position, (0,0))
     self.assert_tuple(left.bounds, (150,50))
     self.assert_tuple(lr.position, (150,0))
     self.assert_tuple(lr.bounds, (50,50))
コード例 #13
0
 def test_resizable_mixed(self):
     """ Tests mixing resizable and non-resizable components """
     cont = GridContainer(shape=(2,2), spacing=(10,10),
                          halign="center", valign="center")
     ul = StaticPlotComponent([0,0], resizable="hv")
     lr = StaticPlotComponent([0,0], resizable="hv")
     top = StaticPlotComponent([0,0], resizable="hv")
     left = StaticPlotComponent([100,100], resizable="")
     cont.component_grid = [[ul, top], [left, lr]]
     cont.bounds = [240, 240]
     cont.do_layout()
     self.assert_tuple(ul.position, (10,130))
     self.assert_tuple(ul.bounds, (100,100))
     self.assert_tuple(top.position, (130,130))
     self.assert_tuple(top.bounds, (100, 100))
     self.assert_tuple(left.position, (10,10))
     self.assert_tuple(left.bounds, (100,100))
     self.assert_tuple(lr.position, (130,10))
     self.assert_tuple(lr.bounds, (100,100))
     return
コード例 #14
0
ファイル: coefficients.py プロジェクト: kieferkat/neuroparser
    def __init__( self, **traits ):
        super( MRIBrainContainer, self ).__init__( **traits )
        
        self.cmap =  chaco_colormaps.center( self.default_cmap )

        sp11 = self.slice_plot( "coronal_anat",  "coronal_coefs"  )
        sp12 = self.slice_plot( "sagittal_anat", "sagittal_coefs" )
        sp21 = self.slice_plot( "axial_anat",    "axial_coefs"    )
        sp22 = self.rate_plot ( "rates" ) 

        container = GridContainer( shape = (2,2),
                                   padding = 20,
                                   fill_padding = True,
                                   bgcolor = "lightgray",
                                   use_backbuffer = True )

        container.add( sp11 ) 
        container.add( sp12 ) 
        container.add( sp21 ) 
        container.add( sp22 ) 

        self.plot = container
コード例 #15
0
 def test_all_empty_cells(self):
     cont = GridContainer(shape=(2,2), spacing=(0,0))
     cont.component_grid = [[None, None], [None, None]]
     size = cont.get_preferred_size()
     self.assert_tuple(size, (0,0))
     cont.bounds = (100,100)
     cont.do_layout()
     return
コード例 #16
0
    def test_row(self):
        cont = GridContainer(shape=(1,3), halign="center", valign="center")
        c1 = StaticPlotComponent([50,50])
        c2 = StaticPlotComponent([30,30])
        c3 = StaticPlotComponent([0,0], resizable="hv")
        cont.add(c1, c2, c3)
        cont.bounds = list(cont.get_preferred_size())
        cont.do_layout()
        self.assert_tuple(c1.position, (0,0))
        self.assert_tuple(c1.bounds, (50,50))
        self.assert_tuple(c2.position, (50,10))
        self.assert_tuple(c2.bounds, (30,30))
        self.assert_tuple(c3.position, (80,0))
        self.assert_tuple(c3.bounds, (0,50))

        cont.bounds = [100, 50]
        cont.do_layout()
        self.assert_tuple(c1.position, (0,0))
        self.assert_tuple(c1.bounds, (50,50))
        self.assert_tuple(c2.position, (50,10))
        self.assert_tuple(c2.bounds, (30,30))
        self.assert_tuple(c3.position, (80,0))
        self.assert_tuple(c3.bounds, (20,50))
        return
コード例 #17
0
 def test_some_empty_cells(self):
     cont = GridContainer(shape=(2,2), spacing=(0,0))
     a = StaticPlotComponent([100,30])
     b = StaticPlotComponent([50,40])
     cont.component_grid = [[a, None], [None, b]]
     size = cont.get_preferred_size()
     self.assert_tuple(size, (150, 70))
     cont.bounds = size
     cont.do_layout()
     self.assert_tuple(a.outer_position, (0, 40))
     self.assert_tuple(a.outer_bounds, (100, 30))
     self.assert_tuple(b.outer_position, (100,0))
     self.assert_tuple(b.outer_bounds, (50, 40))
コード例 #18
0
    def _plot_default(self):
        
        #load the data to visualize. 
        # it is a list of data in the 'results' format, each belonging to a cluster - gonenc
        resultsList = cPickle.load(open(self.fileName, 'r'))
        
        
        #get the names of the outcomes to display
        outcome = []
        for entry in resultsList:
            a = entry[0][1].keys()
            outcome.append(a[0])
        
#        outcome = resultsList[0][0][1].keys()
        
        # pop the time axis from the list of outcomes
#        outcome.pop(outcome.index('TIME'))
        x = resultsList[0][0][1]['TIME']
        
        # the list and number of features (clustering related) stored regarding each run
        features = resultsList[0][0][0][0].keys()
        noFeatures = len(features)
    
        # Iterate over each cluster to prepare the cases corresponding to indivisdual runs in
        # each cluster plot. Each case is labeled as, e.g., y1-2 (3rd run in the 2nd cluster) - gonenc
        for c, results in enumerate(resultsList):
            for j, aCase in enumerate(results):
                aCase = [UncertaintyValue(name=key, value=value) for key, value in aCase[0][0].items()]
                self.cases['y'+str(c)+'-'+str(j)] = aCase
        
#        for j, aCase in enumerate(results):
#            aCase = [UncertaintyValue(name="blaat", value=aCase[0][0])] 
#            self.cases['y'+str(j)] = aCase
        
        #make an empty case for default. 
        #if you have multiple datafields associated with a run, iterate over
        #the keys of a dictionary of a case, instead of over lenght(2)
        case = []
        for i in range(noFeatures):
            case.append(UncertaintyValue( name = 'Default',value = 'None'))
        self.case = case
        self.defaultCase = case
    
    
        # Create some x-y data series to plot
        pds = []
        # enumerate over the results of all clusters    
        for c, results in enumerate(resultsList):
            pd  = ArrayPlotData(index = x)
            for j in range(len(results)): 
                data = np.array(results[j][1].get(outcome[c]))
                print "y"+str(c)+'-'+str(j)
                pd.set_data("y"+str(c)+'-'+str(j),  data)
            pds.append(pd)
        
        # Create a container and add our plots
        container = GridContainer(
                                  bgcolor="lightgray", use_backbuffer=True,
                                  shape=(len(resultsList), 1
                                         ))
    
        #plot data
        tools = []
        for c, results in enumerate(resultsList):
            pd1 = pds[c]
    
            # Create some line plots of some of the data
            plot = Plot(pd1, title='Cluster '+ str(c), border_visible=True, 
                        border_width = 1)
            plot.legend.visible = False
        
            #plot the results
            for i in range(len(results)):
                plotvalue = "y"+str(c)+'-'+str(i)
                print plotvalue
                color = colors[i%len(colors)]
                plot.plot(("index", plotvalue), name=plotvalue, color=color)
                
            #make sure that the time axis runs in the right direction
            for value in plot.plots.values():
                for entry in value:
                    entry.index.sort_order = 'ascending'
    
            # Attach the selector tools to the plot
            selectorTool1 = LineSelectorTool(component=plot)
            plot.tools.append(selectorTool1)
            tools.append(selectorTool1)
            
            # Attach some tools to the plot
            plot.tools.append(PanTool(plot))
            zoom = ZoomTool(component=plot, tool_mode="box", always_on=False)
            plot.overlays.append(zoom)
        
            container.add(plot)
    
        #make sure the selector tools knows the main screen
        for tool in tools:
            tool._demo = self
    
        return container
コード例 #19
0
    def _plot_default(self):
        outcomes, results, time = self._prepare_data()
        
        self.outcomes = outcomes
        self.time = time
        self.low = int(np.min(time))
        self.high = int(np.max(time))
        

        self.data = {}
        for outcome in outcomes:
            self.data[outcome] = results[outcome]
        
        # Create some data
        pd = ArrayPlotData()
        
        for entry in outcomes:
            if self.startValue == 'low':
                pd.set_data(entry, self.data[entry][:,0])
            elif self.startValue == 'high':
                pd.set_data(entry, self.data[entry][:,-1])
        self.plotdata = pd
        
#        outcomes = outcomes[0:3]

        container = GridContainer(shape=(len(outcomes),len(outcomes)))
        combis = [(field1, field2) for field1 in outcomes for field2 in outcomes]
        
        selectorTools = []
        for entry1, entry2 in combis:

            # Create the plot
            if entry1 == entry2:
                plot = Plot(pd)
            else:
                plot = Plot(pd)
                
                #set limits for x and y to global limits
                plot.range2d._xrange._high_setting = np.max(self.data[entry1])
                plot.range2d._xrange._high_value = np.max(self.data[entry1])
                plot.range2d._xrange._low_setting = np.min(self.data[entry1])
                plot.range2d._xrange._low_value = np.min(self.data[entry1])
                
                plot.range2d._yrange._high_setting =np.max(self.data[entry2])
                plot.range2d._yrange._high_value = np.max(self.data[entry2])
                plot.range2d._yrange._low_setting = np.min(self.data[entry2])
                plot.range2d._yrange._low_value = np.min(self.data[entry2])

                #make the scatter plot
                plot.plot((entry1, entry2),
                            type="scatter",
                            marker="circle",
                            color="blue",
                            marker_size=3,
                            bgcolor="white")[0]                
            
                tool = ScatterSelectorTool(component=plot)
                tool._index = entry1
                plot.tools.append(tool)
                selectorTools.append(tool)
            
            plot.height = 500
            plot.width = 500
            plot.border_width = 1
            plot.aspect_ratio  = 1.
            
            container.add(plot)
        
        for tool in selectorTools:
            tool._other_selectors = list(set(selectorTools) - set([tool]))
            tool._demo = self
        return container
コード例 #20
0
class Demo(HasTraits):
    plot = Instance(Component)
    fileName = "clusters.cpickle"
    case = List(UncertaintyValue)

    cases = {}
    defaultCase = []

    # Attributes to use for the plot view.
    size = (400, 1600)

    traits_view = View(Group(
        Group(Item('plot', editor=ComponentEditor(size=size),
                   show_label=False),
              orientation="vertical",
              show_border=True,
              scrollable=True),
        Group(Item('case',
                   editor=TabularEditor(adapter=CaseAdapter(can_edit=False)),
                   show_label=False),
              orientation="vertical",
              show_border=True),
        layout='split',
        orientation='horizontal'),
                       title='Interactive Lines',
                       resizable=True)

    def setFileName(self, newName):
        self.fileName = newName

    def _update_case(self, name):

        if name:
            self.case = self.cases.get(name)

        else:
            self.case = self.defaultCase

    def _plot_default(self):

        #load the data to visualize.
        # it is a list of data in the 'results' format, each belonging to a cluster - gonenc
        resultsList = cPickle.load(open(self.fileName, 'r'))

        #get the names of the outcomes to display
        outcome = []
        for entry in resultsList:
            a = entry[0][1].keys()
            outcome.append(a[0])

#        outcome = resultsList[0][0][1].keys()

# pop the time axis from the list of outcomes
#        outcome.pop(outcome.index('TIME'))
        x = resultsList[0][0][1]['TIME']

        # the list and number of features (clustering related) stored regarding each run
        features = resultsList[0][0][0][0].keys()
        noFeatures = len(features)

        # Iterate over each cluster to prepare the cases corresponding to indivisdual runs in
        # each cluster plot. Each case is labeled as, e.g., y1-2 (3rd run in the 2nd cluster) - gonenc
        for c, results in enumerate(resultsList):
            for j, aCase in enumerate(results):
                aCase = [
                    UncertaintyValue(name=key, value=value)
                    for key, value in aCase[0][0].items()
                ]
                self.cases['y' + str(c) + '-' + str(j)] = aCase


#        for j, aCase in enumerate(results):
#            aCase = [UncertaintyValue(name="blaat", value=aCase[0][0])]
#            self.cases['y'+str(j)] = aCase

#make an empty case for default.
#if you have multiple datafields associated with a run, iterate over
#the keys of a dictionary of a case, instead of over lenght(2)
        case = []
        for i in range(noFeatures):
            case.append(UncertaintyValue(name='Default', value='None'))
        self.case = case
        self.defaultCase = case

        # Create some x-y data series to plot
        pds = []
        # enumerate over the results of all clusters
        for c, results in enumerate(resultsList):
            pd = ArrayPlotData(index=x)
            for j in range(len(results)):
                data = np.array(results[j][1].get(outcome[c]))
                print "y" + str(c) + '-' + str(j)
                pd.set_data("y" + str(c) + '-' + str(j), data)
            pds.append(pd)

        # Create a container and add our plots
        container = GridContainer(bgcolor="lightgray",
                                  use_backbuffer=True,
                                  shape=(len(resultsList), 1))

        #plot data
        tools = []
        for c, results in enumerate(resultsList):
            pd1 = pds[c]

            # Create some line plots of some of the data
            plot = Plot(pd1,
                        title='Cluster ' + str(c),
                        border_visible=True,
                        border_width=1)
            plot.legend.visible = False

            #plot the results
            for i in range(len(results)):
                plotvalue = "y" + str(c) + '-' + str(i)
                print plotvalue
                color = colors[i % len(colors)]
                plot.plot(("index", plotvalue), name=plotvalue, color=color)

            #make sure that the time axis runs in the right direction
            for value in plot.plots.values():
                for entry in value:
                    entry.index.sort_order = 'ascending'

            # Attach the selector tools to the plot
            selectorTool1 = LineSelectorTool(component=plot)
            plot.tools.append(selectorTool1)
            tools.append(selectorTool1)

            # Attach some tools to the plot
            plot.tools.append(PanTool(plot))
            zoom = ZoomTool(component=plot, tool_mode="box", always_on=False)
            plot.overlays.append(zoom)

            container.add(plot)

        #make sure the selector tools knows the main screen
        for tool in tools:
            tool._demo = self

        return container
コード例 #21
0
    def __init__(self):
        super(CyclesPlot, self).__init__()

        # Normally you'd pass in the data, but I'll hardwire things for this
        #    one-off plot.

        srecs = read_time_series_from_csv("./biz_cycles.csv", date_col=0, date_format="%Y-%m-%d")

        dt = srecs["Date"]

        # Industrial production compared with trend (plotted on value axis)
        iprod_vs_trend = srecs["Metric 1"]

        # Industrial production change in last 6 Months (plotted on index axis)
        iprod_delta = srecs["Metric 2"]

        self._dates = dt
        self._series1 = self._selected_s1 = iprod_delta
        self._series2 = self._selected_s2 = iprod_vs_trend

        end_x = np.array([self._selected_s1[-1]])
        end_y = np.array([self._selected_s2[-1]])

        plotdata = ArrayPlotData(
            x=self._series1,
            y=self._series2,
            dates=self._dates,
            selected_x=self._selected_s1,
            selected_y=self._selected_s2,
            endpoint_x=end_x,
            endpoint_y=end_y,
        )

        cycles = Plot(plotdata, padding=20)

        cycles.plot(("x", "y"), type="line", color=(0.2, 0.4, 0.5, 0.4))

        cycles.plot(
            ("selected_x", "selected_y"), type="line", marker="circle", line_width=3, color=(0.2, 0.4, 0.5, 0.9)
        )

        cycles.plot(
            ("endpoint_x", "endpoint_y"),
            type="scatter",
            marker_size=4,
            marker="circle",
            color=(0.2, 0.4, 0.5, 0.2),
            outline_color=(0.2, 0.4, 0.5, 0.6),
        )

        cycles.index_range = DataRange1D(low_setting=80.0, high_setting=120.0)

        cycles.value_range = DataRange1D(low_setting=80.0, high_setting=120.0)

        # dig down to use actual Plot object
        cyc_plot = cycles.components[0]

        # Add the labels in the quadrants
        cyc_plot.overlays.append(
            PlotLabel(
                "\nSlowdown" + 40 * " " + "Expansion",
                component=cyc_plot,
                font="swiss 24",
                color=(0.2, 0.4, 0.5, 0.6),
                overlay_position="inside top",
            )
        )

        cyc_plot.overlays.append(
            PlotLabel(
                "Downturn" + 40 * " " + "Recovery\n ",
                component=cyc_plot,
                font="swiss 24",
                color=(0.2, 0.4, 0.5, 0.6),
                overlay_position="inside bottom",
            )
        )

        timeline = Plot(plotdata, resizable="h", height=50, padding=20)
        timeline.plot(("dates", "x"), type="line", color=(0.2, 0.4, 0.5, 0.8), name="x")
        timeline.plot(("dates", "y"), type="line", color=(0.5, 0.4, 0.2, 0.8), name="y")

        # Snap on the tools
        zoomer = ZoomTool(
            timeline, drag_button="right", always_on=True, tool_mode="range", axis="index", max_zoom_out_factor=1.1
        )

        panner = PanTool(timeline, constrain=True, constrain_direction="x")

        # dig down to get Plot component I want
        x_plt = timeline.plots["x"][0]

        range_selection = RangeSelection(x_plt, left_button_selects=True)
        range_selection.on_trait_change(self.update_interval, "selection")

        x_plt.tools.append(range_selection)
        x_plt.overlays.append(RangeSelectionOverlay(x_plt))

        # Set the plot's bottom axis to use the Scales ticking system
        scale_sys = CalendarScaleSystem(fill_ratio=0.4, default_numlabels=5, default_numticks=10)
        tick_gen = ScalesTickGenerator(scale=scale_sys)

        bottom_axis = ScalesPlotAxis(timeline, orientation="bottom", tick_generator=tick_gen)

        # Hack to remove default axis - FIXME: how do I *replace* an axis?
        del (timeline.underlays[-2])

        timeline.overlays.append(bottom_axis)

        container = GridContainer(
            padding=20, fill_padding=True, bgcolor="lightgray", use_backbuffer=True, shape=(2, 1), spacing=(30, 30)
        )

        # add a central "x" and "y" axis

        x_line = LineInspector(cyc_plot, is_listener=True, color="gray", width=2)
        y_line = LineInspector(cyc_plot, is_listener=True, color="gray", width=2, axis="value")

        cyc_plot.overlays.append(x_line)
        cyc_plot.overlays.append(y_line)

        cyc_plot.index.metadata["selections"] = 100.0
        cyc_plot.value.metadata["selections"] = 100.0

        container.add(cycles)
        container.add(timeline)

        container.title = "Business Cycles"

        self.plot = container
コード例 #22
0
    def _create_plot_window(self):
        # Create the model
        min_value = 350
        max_value = self.max_data
        image_value_range = DataRange1D(low=min_value, high=max_value)
        self.cmap = jet(range=image_value_range)
        self._update_model()
        datacube = self.colorcube

        # Create the plot
        self.plotdata = ArrayPlotData()
        self.plotdataVoxel = ArrayPlotData()
        self.plotdataSlices = ArrayPlotData()
        self.plotdataVoxelFFT = ArrayPlotData()
        self.plotdataPC = ArrayPlotData()
        self._update_images()

        # Top Left plot
        centerplot = Plot(self.plotdata,
                          resizable='hv',
                          padding=20,
                          title="Slice_X")
        imgplot = centerplot.img_plot("yz",
                                      xbounds=None,
                                      ybounds=None,
                                      colormap=self.cmap)[0]

        centerplot.x_axis.title = "Y"
        centerplot.y_axis.title = "Z"
        self._add_plot_tools(imgplot, "yz")
        self.cursorYZ = CursorTool(imgplot, drag_button='left', color='white')
        self.cursorYZ.current_position = self.slice_y, self.slice_z
        imgplot.overlays.append(self.cursorYZ)
        self.center = imgplot

        # Top Right Plot
        rightplot = Plot(self.plotdata,
                         resizable='hv',
                         padding=20,
                         title="Slice_Y")
        rightplot.x_axis.title = "X"
        rightplot.y_axis.title = "Z"
        imgplot = rightplot.img_plot("xz",
                                     xbounds=None,
                                     ybounds=None,
                                     colormap=self.cmap)[0]

        self._add_plot_tools(imgplot, "xz")
        self.cursorXZ = CursorTool(imgplot, drag_button='left', color='white')
        self.cursorXZ.current_position = self.slice_x, self.slice_z
        imgplot.overlays.append(self.cursorXZ)
        self.right = imgplot

        # Bottom  LeftPlot
        bottomplot = Plot(self.plotdata,
                          resizable='hv',
                          padding=20,
                          title="Slice_Z")
        bottomplot.x_axis.title = "Y"
        bottomplot.y_axis.title = "X"
        imgplot = bottomplot.img_plot("xy",
                                      xbounds=None,
                                      ybounds=None,
                                      colormap=self.cmap)[0]
        """bottomplot.contour_plot("xy", 
                          type="poly",
                          xbounds=None,
                          ybounds=None)[0]"""

        self._add_plot_tools(imgplot, "xy")
        self.cursorXY = CursorTool(imgplot, drag_button='left', color='white')
        self.cursorXY.current_position = self.slice_y, self.slice_x
        imgplot.overlays.append(self.cursorXY)
        self.bottom = imgplot
        """ # Create a colorbar
        cbar_index_mapper = LinearMapper(range=image_value_range)
        self.colorbar = ColorBar(index_mapper=cbar_index_mapper,
                                 plot=centerplot,
                                 padding_top=centerplot.padding_top,
                                 padding_bottom=centerplot.padding_bottom,
                                 padding_right=40,
                                 resizable='v',
                                 width=30, height = 100)"""

        # Create data series to plot
        timeplot = Plot(self.plotdataVoxel, resizable='hv', padding=20)
        timeplot.x_axis.title = "Frames"
        timeplot.plot("TimeVoxel",
                      color='lightblue',
                      line_width=1.0,
                      bgcolor="white",
                      name="Time")[0]
        # for i in range(len(self.tasks)):
        #         timeplot.plot(self.timingNames[i+2],color=tuple(COLOR_PALETTE[i]),
        #         line_width=1.0, bgcolor = "white", border_visible=True, name = self.timingNames[i+2])[0]

        timeplot.legend.visible = True
        timeplot.plot("time",
                      type="scatter",
                      color=tuple(COLOR_PALETTE[2]),
                      line_width=1,
                      bgcolor="white",
                      border_visible=True,
                      name="time")[0]
        self.timePlot = timeplot
        # Create data series to plot
        timeplotBig = Plot(self.plotdataVoxel, resizable='hv', padding=20)
        timeplotBig.x_axis.title = "Frames"
        timeplotBig.plot("TimeVoxel",
                         color='lightblue',
                         line_width=1.5,
                         bgcolor="white",
                         name="Time")[0]
        timeplotBig.legend.visible = True
        timeplotBig.plot("time",
                         type="scatter",
                         color=tuple(COLOR_PALETTE[2]),
                         line_width=1,
                         bgcolor="white",
                         border_visible=True,
                         name="time")[0]
        self.timePlotBig = timeplotBig

        # Create data series to plot
        freqplotBig = Plot(self.plotdataVoxelFFT, resizable='hv', padding=20)
        freqplotBig.x_axis.title = "Frequency (Hz)"
        freqplotBig.plot("FreqVoxel",
                         color='lightblue',
                         line_width=1.5,
                         bgcolor="white",
                         name="Abs(Y)")[0]
        freqplotBig.legend.visible = True
        freqplotBig.plot("peaks",
                         type="scatter",
                         color=tuple(COLOR_PALETTE[2]),
                         line_width=1,
                         bgcolor="white",
                         border_visible=True,
                         name="peaks")[0]
        self.freqPlotBig = freqplotBig

        # Create data series to plot
        PCplotBig = Plot(self.plotdataPC, resizable='hv', padding=20)
        PCplotBig.x_axis.title = "Frames"
        PCplotBig.plot("Principal Component",
                       color='lightblue',
                       line_width=1.5,
                       bgcolor="white",
                       name="Principal Component")[0]
        PCplotBig.legend.visible = True
        PCplotBig.plot("time",
                       type="scatter",
                       color=tuple(COLOR_PALETTE[2]),
                       line_width=1,
                       bgcolor="white",
                       border_visible=True,
                       name="time")[0]
        self.PCplotBig = PCplotBig

        #self.time = time
        # Create a GridContainer to hold all of our plots
        container = GridContainer(padding=10,
                                  fill_padding=True,
                                  bgcolor="white",
                                  use_backbuffer=True,
                                  shape=(2, 2),
                                  spacing=(10, 10))
        containerTime = GridContainer(padding=10,
                                      fill_padding=True,
                                      bgcolor="white",
                                      use_backbuffer=True,
                                      shape=(1, 1),
                                      spacing=(5, 5))

        containerFreq = GridContainer(padding=10,
                                      fill_padding=True,
                                      bgcolor="white",
                                      use_backbuffer=True,
                                      shape=(1, 1),
                                      spacing=(5, 5))
        containerPC = GridContainer(padding=10,
                                    fill_padding=True,
                                    bgcolor="white",
                                    use_backbuffer=True,
                                    shape=(1, 1),
                                    spacing=(5, 5))

        container.add(centerplot)
        container.add(rightplot)
        container.add(bottomplot)
        container.add(timeplot)
        containerTime.add(timeplotBig)
        containerFreq.add(freqplotBig)
        containerPC.add(PCplotBig)
        """container = GridContainer(padding=10, fill_padding=True,
                              bgcolor="white", use_backbuffer=True,
                              shape=(3,3), spacing=(10,10))
       
        for i in range(14,23):
             slicePlot = Plot(self.plotdataSlices, resizable= 'hv', padding=20,title = "slice " + str(i),bgcolor = "white")
             slicePlot.img_plot("slice " + str(i),xbounds= None, ybounds= None, colormap=self.cmap,bgcolor = "white")[0]
             container.add(slicePlot)"""

        self.container = container
        self.nb.DeleteAllPages()
        self.window = Window(self.nb, -1, component=container)
        self.windowTime = Window(self.nb, -1, component=containerTime)
        self.windowFreq = Window(self.nb, -1, component=containerFreq)
        self.windowPC = Window(self.nb, -1, component=containerPC)
        self.sizer.Detach(self.topsizer)
        self.sizer.Detach(self.pnl2)
        self.topsizer.Clear()
        self.topsizer.Add(self.pnl3, 0, wx.ALL, 10)
        self.nb.AddPage(self.window.control, "fMRI Slices")
        self.nb.AddPage(self.windowTime.control, "Time Voxel")
        self.nb.AddPage(self.windowFreq.control, "Frequency Voxel")
        self.nb.AddPage(self.windowPC.control, "Principal Component")
        self.topsizer.Add(self.nb, 1, wx.EXPAND)
        self.sizer.Add(self.topsizer, 1, wx.EXPAND)
        self.sizer.Add(self.pnl2,
                       flag=wx.EXPAND | wx.BOTTOM | wx.TOP,
                       border=10)

        self.SetSizer(self.sizer)
        self.Centre()
        self.Show(True)
コード例 #23
0
ファイル: biz_cycles.py プロジェクト: eshioji/experimental
    def __init__(self):
        super(CyclesPlot, self).__init__()

        # Normally you'd pass in the data, but I'll hardwire things for this
        #    one-off plot.

        srecs = read_time_series_from_csv("./biz_cycles2.csv",
                                          date_col=0,
                                          date_format="%Y-%m-%d")

        dt = srecs["Date"]

        # Industrial production compared with trend (plotted on value axis)
        iprod_vs_trend = srecs["Metric 1"]

        # Industrial production change in last 6 Months (plotted on index axis)
        iprod_delta = srecs["Metric 2"]

        self._dates = dt
        self._series1 = self._selected_s1 = iprod_delta
        self._series2 = self._selected_s2 = iprod_vs_trend

        end_x = np.array([self._selected_s1[-1]])
        end_y = np.array([self._selected_s2[-1]])

        plotdata = ArrayPlotData(x=self._series1,
                                 y=self._series2,
                                 dates=self._dates,
                                 selected_x=self._selected_s1,
                                 selected_y=self._selected_s2,
                                 endpoint_x=end_x,
                                 endpoint_y=end_y)

        cycles = Plot(plotdata, padding=20)

        cycles.plot(("x", "y"), type="line", color=(.2, .4, .5, .4))

        cycles.plot(("selected_x", "selected_y"),
                    type="line",
                    marker="circle",
                    line_width=3,
                    color=(.2, .4, .5, .9))

        cycles.plot(("endpoint_x", "endpoint_y"),
                    type="scatter",
                    marker_size=4,
                    marker="circle",
                    color=(.2, .4, .5, .2),
                    outline_color=(.2, .4, .5, .6))

        cycles.index_range = DataRange1D(low_setting=80., high_setting=120.)

        cycles.value_range = DataRange1D(low_setting=80., high_setting=120.)

        # dig down to use actual Plot object
        cyc_plot = cycles.components[0]

        # Add the labels in the quadrants
        cyc_plot.overlays.append(
            PlotLabel("\nSlowdown" + 40 * " " + "Expansion",
                      component=cyc_plot,
                      font="swiss 24",
                      color=(.2, .4, .5, .6),
                      overlay_position="inside top"))

        cyc_plot.overlays.append(
            PlotLabel("Downturn" + 40 * " " + "Recovery\n ",
                      component=cyc_plot,
                      font="swiss 24",
                      color=(.2, .4, .5, .6),
                      overlay_position="inside bottom"))

        timeline = Plot(plotdata, resizable='h', height=50, padding=20)
        timeline.plot(("dates", "x"),
                      type="line",
                      color=(.2, .4, .5, .8),
                      name='x')
        timeline.plot(("dates", "y"),
                      type="line",
                      color=(.5, .4, .2, .8),
                      name='y')

        # Snap on the tools
        zoomer = ZoomTool(timeline,
                          drag_button="right",
                          always_on=True,
                          tool_mode="range",
                          axis="index",
                          max_zoom_out_factor=1.1)

        panner = PanTool(timeline, constrain=True, constrain_direction="x")

        # dig down to get Plot component I want
        x_plt = timeline.plots['x'][0]

        range_selection = RangeSelection(x_plt, left_button_selects=True)
        range_selection.on_trait_change(self.update_interval, 'selection')

        x_plt.tools.append(range_selection)
        x_plt.overlays.append(RangeSelectionOverlay(x_plt))

        # Set the plot's bottom axis to use the Scales ticking system
        scale_sys = CalendarScaleSystem(
            fill_ratio=0.4,
            default_numlabels=5,
            default_numticks=10,
        )
        tick_gen = ScalesTickGenerator(scale=scale_sys)

        bottom_axis = ScalesPlotAxis(timeline,
                                     orientation="bottom",
                                     tick_generator=tick_gen)

        # Hack to remove default axis - FIXME: how do I *replace* an axis?
        del (timeline.underlays[-2])

        timeline.overlays.append(bottom_axis)

        container = GridContainer(padding=20,
                                  fill_padding=True,
                                  bgcolor="lightgray",
                                  use_backbuffer=True,
                                  shape=(2, 1),
                                  spacing=(30, 30))

        # add a central "x" and "y" axis

        x_line = LineInspector(cyc_plot,
                               is_listener=True,
                               color="gray",
                               width=2)
        y_line = LineInspector(cyc_plot,
                               is_listener=True,
                               color="gray",
                               width=2,
                               axis="value")

        cyc_plot.overlays.append(x_line)
        cyc_plot.overlays.append(y_line)

        cyc_plot.index.metadata["selections"] = 100.0
        cyc_plot.value.metadata["selections"] = 100.0

        container.add(cycles)
        container.add(timeline)

        container.title = "Business Cycles"

        self.plot = container
コード例 #24
0
    def _create_plot_window(self):
        # Create the model
        min_value = 350 
        max_value = self.max_data
        image_value_range = DataRange1D(low=min_value,high=max_value)
        self.cmap = jet(range = image_value_range )
        self._update_model()
        datacube = self.colorcube 
    
        # Create the plot
        self.plotdata = ArrayPlotData()
        self.plotdataVoxel = ArrayPlotData()
        self.plotdataSlices = ArrayPlotData()
        self.plotdataVoxelFFT = ArrayPlotData()
        self.plotdataPC = ArrayPlotData()
        self._update_images()
        
         # Top Left plot
        centerplot = Plot(self.plotdata, resizable= 'hv', padding=20, title = "Slice_X")
        imgplot=centerplot.img_plot("yz", 
                                 xbounds= None,
                                 ybounds= None,
                                colormap=self.cmap)[0]
                                
        centerplot.x_axis.title = "Y"
        centerplot.y_axis.title = "Z"            
        self._add_plot_tools(imgplot, "yz")
        self.cursorYZ = CursorTool(imgplot, drag_button='left', 
                                 color='white')
        self.cursorYZ.current_position = self.slice_y , self.slice_z
        imgplot.overlays.append(self.cursorYZ)
        self.center = imgplot

        # Top Right Plot
        rightplot = Plot(self.plotdata, resizable= 'hv', padding=20,title = "Slice_Y")
        rightplot.x_axis.title = "X"
        rightplot.y_axis.title = "Z" 
        imgplot = rightplot.img_plot("xz", 
                                 xbounds= None,
                                 ybounds= None,
                                colormap=self.cmap)[0]
                   
        self._add_plot_tools(imgplot, "xz")
        self.cursorXZ = CursorTool(imgplot, drag_button='left', 
                                 color='white')
        self.cursorXZ.current_position = self.slice_x , self.slice_z
        imgplot.overlays.append(self.cursorXZ)
        self.right = imgplot

        # Bottom  LeftPlot
        bottomplot = Plot(self.plotdata, resizable= 'hv',padding=20, title = "Slice_Z")
        bottomplot.x_axis.title = "Y"
        bottomplot.y_axis.title = "X"
        imgplot = bottomplot.img_plot("xy", 
                                xbounds= None,
                                ybounds= None, 
                                colormap=self.cmap)[0]
                                
        """bottomplot.contour_plot("xy", 
                          type="poly",
                          xbounds=None,
                          ybounds=None)[0]"""   
                   
        self._add_plot_tools(imgplot, "xy")
        self.cursorXY = CursorTool(imgplot, drag_button='left', 
                                 color='white')
        self.cursorXY.current_position = self.slice_y , self.slice_x
        imgplot.overlays.append(self.cursorXY)
        self.bottom = imgplot
        
        """ # Create a colorbar
        cbar_index_mapper = LinearMapper(range=image_value_range)
        self.colorbar = ColorBar(index_mapper=cbar_index_mapper,
                                 plot=centerplot,
                                 padding_top=centerplot.padding_top,
                                 padding_bottom=centerplot.padding_bottom,
                                 padding_right=40,
                                 resizable='v',
                                 width=30, height = 100)"""
                                 

        # Create data series to plot
        timeplot = Plot(self.plotdataVoxel, resizable= 'hv', padding=20)
        timeplot.x_axis.title = "Frames"
        timeplot.plot("TimeVoxel", color = 'lightblue', line_width=1.0, bgcolor="white", name = "Time")[0]
        # for i in range(len(self.tasks)):
        #         timeplot.plot(self.timingNames[i+2],color=tuple(COLOR_PALETTE[i]), 
        #         line_width=1.0, bgcolor = "white", border_visible=True, name = self.timingNames[i+2])[0]
        
        timeplot.legend.visible = True
        timeplot.plot("time", type = "scatter",color=tuple(COLOR_PALETTE[2]), line_width=1, bgcolor = "white", border_visible=True, 
                        name = "time")[0]
        self.timePlot = timeplot       
        # Create data series to plot
        timeplotBig = Plot(self.plotdataVoxel, resizable= 'hv', padding=20)
        timeplotBig.x_axis.title = "Frames"
        timeplotBig.plot("TimeVoxel", color = 'lightblue', line_width=1.5, bgcolor="white", name = "Time")[0]        
        timeplotBig.legend.visible = True
        timeplotBig.plot("time", type = "scatter",color=tuple(COLOR_PALETTE[2]), 
                line_width=1, bgcolor = "white", border_visible=True, name = "time")[0]
        self.timePlotBig = timeplotBig 

        # Create data series to plot
        freqplotBig = Plot(self.plotdataVoxelFFT, resizable= 'hv', padding=20)
        freqplotBig.x_axis.title = "Frequency (Hz)"
        freqplotBig.plot("FreqVoxel", color = 'lightblue', line_width=1.5, bgcolor="white", name = "Abs(Y)")[0]        
        freqplotBig.legend.visible = True
        freqplotBig.plot("peaks", type = "scatter",color=tuple(COLOR_PALETTE[2]), 
                line_width=1, bgcolor = "white", border_visible=True, name = "peaks")[0]
        self.freqPlotBig = freqplotBig 

         # Create data series to plot
        PCplotBig = Plot(self.plotdataPC, resizable= 'hv', padding=20)
        PCplotBig.x_axis.title = "Frames"
        PCplotBig.plot("Principal Component", color = 'lightblue', line_width=1.5, bgcolor="white", name = "Principal Component")[0]        
        PCplotBig.legend.visible = True
        PCplotBig.plot("time", type = "scatter",color=tuple(COLOR_PALETTE[2]), 
                line_width=1, bgcolor = "white", border_visible=True, name = "time")[0]
        self.PCplotBig = PCplotBig 

        #self.time = time
        # Create a GridContainer to hold all of our plots
        container = GridContainer(padding=10, fill_padding=True,
                              bgcolor="white", use_backbuffer=True,
                              shape=(2,2), spacing=(10,10))
        containerTime = GridContainer(padding=10, fill_padding=True,
                              bgcolor="white", use_backbuffer=True,
                              shape=(1,1), spacing=(5,5))

        containerFreq = GridContainer(padding=10, fill_padding=True,
                              bgcolor="white", use_backbuffer=True,
                              shape=(1,1), spacing=(5,5))
        containerPC = GridContainer(padding=10, fill_padding=True,
                              bgcolor="white", use_backbuffer=True,
                              shape=(1,1), spacing=(5,5))

        
        container.add(centerplot)
        container.add(rightplot)
        container.add(bottomplot)
        container.add(timeplot)
        containerTime.add(timeplotBig)
        containerFreq.add(freqplotBig)
        containerPC.add(PCplotBig)
        
        """container = GridContainer(padding=10, fill_padding=True,
                              bgcolor="white", use_backbuffer=True,
                              shape=(3,3), spacing=(10,10))
       
        for i in range(14,23):
             slicePlot = Plot(self.plotdataSlices, resizable= 'hv', padding=20,title = "slice " + str(i),bgcolor = "white")
             slicePlot.img_plot("slice " + str(i),xbounds= None, ybounds= None, colormap=self.cmap,bgcolor = "white")[0]
             container.add(slicePlot)"""

        self.container = container
        self.nb.DeleteAllPages()
        self.window =  Window(self.nb, -1, component=container)
        self.windowTime =  Window(self.nb, -1, component=containerTime)
        self.windowFreq =  Window(self.nb, -1, component=containerFreq)
        self.windowPC =  Window(self.nb, -1, component=containerPC)
        self.sizer.Detach(self.topsizer)
        self.sizer.Detach(self.pnl2)
        self.topsizer.Clear()
        self.topsizer.Add(self.pnl3, 0, wx.ALL, 10)
        self.nb.AddPage(self.window.control, "fMRI Slices")
        self.nb.AddPage(self.windowTime.control, "Time Voxel")
        self.nb.AddPage(self.windowFreq.control, "Frequency Voxel")
        self.nb.AddPage(self.windowPC.control, "Principal Component")
        self.topsizer.Add(self.nb, 1, wx.EXPAND) 
        self.sizer.Add(self.topsizer, 1, wx.EXPAND)
        self.sizer.Add(self.pnl2, flag=wx.EXPAND | wx.BOTTOM | wx.TOP, border=10)
   
        self.SetSizer(self.sizer)
        self.Centre()
        self.Show(True)
コード例 #25
0
    def get_plot(self):
        pixel_sizes = self.data_source.voxel_sizes
        shape = self.data.shape
        m = min(pixel_sizes)
        s = [int(d * sz / m) for d, sz in zip(shape, pixel_sizes)]
        if 1:  # else physical aspect ratio is enabled
            ss = max(s) / 4
            s = [max(s, ss) for s in s]
        plot_sizes = dict(xy=(s[2], s[1]),
                          xz=(s[2], s[0]),
                          zy=(s[0], s[1]),
                          zz=(s[0], s[0]))

        plots = GridContainer(shape=(2, 2),
                              spacing=(3, 3),
                              padding=50,
                              aspect_ratio=1)
        pxy = Plot(
            self.plotdata,
            padding=1,
            fixed_preferred_size=plot_sizes['xy'],
            x_axis=PlotAxis(orientation='top'),
        )
        pxz = Plot(
            self.plotdata,
            padding=1,
            fixed_preferred_size=plot_sizes['xz'],
        )
        pzy = Plot(
            self.plotdata,
            padding=1,
            fixed_preferred_size=plot_sizes['zy'],
            #orientation = 'v',  # cannot use 'v' because of img_plot assumes row-major ordering
            x_axis=PlotAxis(orientation='top'),
            y_axis=PlotAxis(orientation='right'),
        )
        pzz = Plot(self.plotdata,
                   padding=1,
                   fixed_preferred_size=plot_sizes['zz'])

        plots.add(pxy, pzy, pxz, pzz)

        self.plots = dict(
            xy=pxy.img_plot('xy', colormap=bone)[0],
            xz=pxz.img_plot('xz', colormap=bone)[0],
            zy=pzy.img_plot('zy', colormap=bone)[0],
            zz=pzz.img_plot('zz')[0],
            xyp=pxy.plot(('z_x', 'z_y'),
                         type='scatter',
                         color='orange',
                         marker='circle',
                         marker_size=3,
                         selection_marker_size=3,
                         selection_marker='circle')[0],
            xzp=pxz.plot(('y_x', 'y_z'),
                         type='scatter',
                         color='orange',
                         marker='circle',
                         marker_size=3,
                         selection_marker_size=3,
                         selection_marker='circle')[0],
            zyp=pzy.plot(('x_z', 'x_y'),
                         type='scatter',
                         color='orange',
                         marker='circle',
                         marker_size=3,
                         selection_marker_size=3,
                         selection_marker='circle')[0],
        )

        for p in ['xy', 'xz', 'zy']:
            self.plots[p].overlays.append(ZoomTool(self.plots[p]))
            self.plots[p].tools.append(
                PanTool(self.plots[p], drag_button='right'))

            imgtool = ImageInspectorTool(self.plots[p])
            self.plots[p].tools.append(imgtool)
            overlay = ImageInspectorOverlay(component=self.plots[p],
                                            bgcolor='white',
                                            image_inspector=imgtool)
            self.plots['zz'].overlays.append(overlay)

            self.plots[p + 'p'].tools.append(
                ScatterInspector(self.plots[p + 'p'], selection_mode='toggle'))

        self.plots['xyp'].index.on_trait_change(self._xyp_metadata_handler,
                                                'metadata_changed')
        self.plots['xzp'].index.on_trait_change(self._xzp_metadata_handler,
                                                'metadata_changed')
        self.plots['zyp'].index.on_trait_change(self._zyp_metadata_handler,
                                                'metadata_changed')

        plot = HPlotContainer()
        # todo: add colormaps
        plot.add(plots)
        return plot
コード例 #26
0
 def _plot_default(self):
     results = cPickle.load(open(self.fileName, 'r'))
     outcomes = results[0][1].keys()
     outcomes.pop(outcomes.index('TIME'))
     x = results[0][1]['TIME']
 
     for j, aCase in enumerate(results):
         aCase = [UncertaintyValue(name=key, value=value) for key, value in aCase[0][0].items()]
         self.cases['y'+str(j)] = aCase
 
     uncertainties = results[0][0][0]
     uncertaintynames = uncertainties.keys()
     uncertaintyvalues = []
     for key in uncertainties.keys():
         uncertaintyvalues.append(uncertainties[key])
     
     case = []
     for i in range(len(uncertainties)):
         case.append(UncertaintyValue( name = str(uncertaintynames[i]),value = "")) #haydaa
     self.case = case
     self.defaultCase = case
 
     # Create some x-y data series to plot
     pds = []    
     for i, outcome in enumerate(outcomes):
         pd  = ArrayPlotData(index = x)
         for j in range(len(results)): 
             pd.set_data("y"+str(j), results[j][1].get(outcome) )
         pds.append(pd)
     
     # Create a container and add our plots
     container = GridContainer(
                               bgcolor="lightgray", use_backbuffer=True,
                               shape=(1, 1))
 
     #plot data
     tools = []
     for j in range(len(outcomes)):
         pd1 = pds[j]
 
         # Create some line plots of some of the data
         plot = Plot(pd1, title=outcomes[j], border_visible=True, 
                     border_width = 1)
         plot.legend.visible = False
     
         for i in range(len(results)):
             plotvalue = "y"+str(i)
             color = colors[i%len(colors)]
             plot.plot(("index", plotvalue), name=plotvalue, color=color)
             
         for value in plot.plots.values():
             for entry in value:
                 entry.index.sort_order = 'ascending'
 
         # Attach the selector tools to the plot
         selectorTool1 = LineSelectorTool(component=plot)
         plot.tools.append(selectorTool1)
         tools.append(selectorTool1)
         
         # Attach some tools to the plot
         plot.tools.append(PanTool(plot))
         zoom = ZoomTool(component=plot, tool_mode="box", always_on=False)
         plot.overlays.append(zoom)
     
         container.add(plot)
 
     #make sure the selector tools know each other
     
     for tool in tools:
         tool._demo = self
 
     return container
コード例 #27
0
    def get_plot(self):
        #pd = ArrayPlotData()
        index_label = 'index'
        index = None
        colors = ['purple','blue','green','gold', 'orange', 'red', 'black']
        groups = defaultdict(lambda:[])

        pd = ArrayPlotData()

        index_values = None
        if 'relative time' in self.table:
            index_key = 'relative time'
            index_values = self.table[index_key]
        else:
            index_key = 'index'
        index_label = index_key

        for key, values in self.table.items():
            if index_values is None:
                index_values = range(len(values))
            if key==index_label:
                continue
            if key.startswith('stage '):
                label = key[6:].strip()
                group = groups['stages']
            elif key=='contact position':
                label = key
                group = groups['stages']
            elif key.startswith('fiber '):

                if key.endswith('deformation'):
                    label = key[5:-11].strip()
                    group = groups['fiber deformation']
                elif key.endswith('position'):
                    label = key[5:-8].strip()
                    group = groups['fiber position']
                else:
                    label = key[5:].strip ()
                    group = groups['fiber']
            elif key.startswith('sarcomere '):
                label = key[10:].strip()
                if label=='orientation': # this is artificial information
                    continue
                group = groups['sarcomere']
            else:
                label = key
                group = groups[key]

            group.append((index_label, label, index_key, key))
            pd.set_data(key, values)

        pd.set_data (index_key, index_values)

        if 'force' in self.table and 'stage right current' in self.table:
            group = groups['position-force']
            group.append(('position','force','stage right current','force'))



        n = len (groups)
        if n in [0,1,2,3,5,7]:
            shape = (n, 1)
        elif n in [4,6,8,10]:
            shape = (n//2,2)
        elif n in [9]:
            shape = (n//3,3)
        else:
            raise NotImplementedError (`n`)

        container = GridContainer(padding=10, #fill_padding=True,
                                  #bgcolor="lightgray", use_backbuffer=True,
                                  shape=shape, spacing=(0,0))

        for i, (group_label, group_info) in enumerate(groups.items ()):
            plot = Plot (pd)
            for j, (index_label, label, index_key, key) in enumerate(group_info):
                color = colors[j % len (colors)]
                plot.plot((index_key, key), name=label, color=color, x_label=index_label)
            plot.legend.visible = True
            plot.title = group_label
            plot.tools.append(PanTool(plot))
            zoom = ZoomTool(component=plot, tool_mode="box", always_on=False)
            plot.overlays.append(zoom)
            container.add (plot)

        return container
コード例 #28
0
ファイル: clusterPlotter.py プロジェクト: bram32/EMAworkbench
 def _plot_default(self):
     
     noDataPoint = len(self.data[0][1])
     x = range(noDataPoint)
 
     for run in self.data:
         tempCase = [Feature(name=key, value=value) for key, value in run[0].items()]
         self.cases[str(run[0]['Index'])] = tempCase
 
     features = self.data[0][0]
     featureNames = features.keys()
     featureValues = []
     for key in features.keys():
         featureValues.append(features[key])
     
     case = []
     for i in range(len(features)):
         case.append(Feature( name = str(featureNames[i]),value = "None")) 
     self.case = case
     self.defaultCase = case
     
     # Create some x-y data series to plot
     pd  = ArrayPlotData(index = x)
     for j in range(len(self.data)): 
         pd.set_data(str(self.data[j][0]['Index']), self.data[j][1] )
     
     # Create a container and add our plots
     container = GridContainer(bgcolor="lightgray", use_backbuffer=True, shape=(1, 1))
 
     #plot data
     tools = []
     plot = Plot(pd, title=self.varName, border_visible=True, border_width = 1)
     plot.legend.visible = False
     
     for i in range(len(self.data)):
         plotvalue = str(self.data[i][0]['Index'])
         color = colors[i%len(colors)]
         plot.plot(("index", plotvalue), name=plotvalue, color=color)
                  
     for value in plot.plots.values():
         for entry in value:
             entry.index.sort_order = 'ascending'
 
     # Attach the selector tools to the plot
     selectorTool1 = LineSelectorTool(component=plot)
     plot.tools.append(selectorTool1)
     tools.append(selectorTool1)
         
     # Attach some tools to the plot
     plot.tools.append(PanTool(plot))
     zoom = ZoomTool(component=plot, tool_mode="box", always_on=False)
     plot.overlays.append(zoom)
     
     container.add(plot)
 
     #make sure the selector tools know each other
     
     for tool in tools:
         tool._demo = self
 
     return container
コード例 #29
0
class Demo(HasTraits):
    plot = Instance(Component)
    fileName = "default.txt"
    case = List(UncertaintyValue)
    cases = {}

    defaultCase = []

    # Attributes to use for the plot view.
    size = (400, 250)

    traits_view = View(Group(
        Group(Item('plot', editor=ComponentEditor(size=size),
                   show_label=False),
              orientation="vertical",
              show_border=True),
        Group(Item('case',
                   editor=TabularEditor(adapter=CaseAdapter(can_edit=False)),
                   show_label=False),
              orientation="vertical",
              show_border=True),
        layout='split',
        orientation='horizontal'),
                       title='Interactive Lines',
                       resizable=True)

    def setFileName(self, newName):
        self.fileName = newName

    def _update_case(self, name):

        if name:
            self.case = self.cases.get(name)

        else:
            self.case = self.defaultCase

    def _plot_default(self):
        results = cPickle.load(open(self.fileName, 'r'))
        outcomes = results[0][1].keys()
        outcomes.pop(outcomes.index('TIME'))
        x = results[0][1]['TIME']

        for j, aCase in enumerate(results):
            aCase = [
                UncertaintyValue(name=key, value=value)
                for key, value in aCase[0][0].items()
            ]
            self.cases['y' + str(j)] = aCase

        uncertainties = results[0][0][0]
        uncertaintynames = uncertainties.keys()
        uncertaintyvalues = []
        for key in uncertainties.keys():
            uncertaintyvalues.append(uncertainties[key])

        case = []
        for i in range(len(uncertainties)):
            case.append(
                UncertaintyValue(name=str(uncertaintynames[i]),
                                 value=""))  #haydaa
        self.case = case
        self.defaultCase = case

        # Create some x-y data series to plot
        pds = []
        for i, outcome in enumerate(outcomes):
            pd = ArrayPlotData(index=x)
            for j in range(len(results)):
                pd.set_data("y" + str(j), results[j][1].get(outcome))
            pds.append(pd)

        # Create a container and add our plots
        container = GridContainer(bgcolor="lightgray",
                                  use_backbuffer=True,
                                  shape=(1, 1))

        #plot data
        tools = []
        for j in range(len(outcomes)):
            pd1 = pds[j]

            # Create some line plots of some of the data
            plot = Plot(pd1,
                        title=outcomes[j],
                        border_visible=True,
                        border_width=1)
            plot.legend.visible = False

            for i in range(len(results)):
                plotvalue = "y" + str(i)
                color = colors[i % len(colors)]
                plot.plot(("index", plotvalue), name=plotvalue, color=color)

            for value in plot.plots.values():
                for entry in value:
                    entry.index.sort_order = 'ascending'

            # Attach the selector tools to the plot
            selectorTool1 = LineSelectorTool(component=plot)
            plot.tools.append(selectorTool1)
            tools.append(selectorTool1)

            # Attach some tools to the plot
            plot.tools.append(PanTool(plot))
            zoom = ZoomTool(component=plot, tool_mode="box", always_on=False)
            plot.overlays.append(zoom)

            container.add(plot)

        #make sure the selector tools know each other

        for tool in tools:
            tool._demo = self

        return container