コード例 #1
0
ファイル: test_csp.py プロジェクト: neurodebian/pyspace
    def test_csp(self):
        """
        Tests that CSP produces the expected transformation matrix on the data
        """
        csp_node = CSPNode(retained_channels=2)
        for i in range(self.data.shape[0]):
            ts = TimeSeries(input_array = self.data[i:i+1,:], 
                            channel_names = [("test_channel_%s" % j) for j in range(2)],
                            sampling_frequency = 10, start_time = 0, end_time = 1)
            csp_node.train(ts, self.classes[i])
        csp_node.stop_training()
        
        self.assert_(numpy.allclose(csp_node.filters,
                                       numpy.array([[-0.75319083, -0.35237094],
                                                       [1.,  -1.]])),
                    "CSP transformation matrix is wrong! Got:%s, expected:%s"%(
                    str(csp_node.filters),
                    str(numpy.array([[-0.75319083, -0.35237094],[1.,  -1.]]))
                    ))

        transformed_data = numpy.zeros(self.data.shape)
        for i in range(self.data.shape[0]):
            ts = TimeSeries(input_array = self.data[i:i+1,:], 
                            channel_names = [("test_channel_%s" % j) for j in range(2)],
                            sampling_frequency = 10, start_time = 0, end_time = 1)
            transformed_data[i,:] = csp_node.execute(ts)
        
        self.assert_(numpy.allclose(transformed_data[0:2,:],
                                       numpy.array([[0.14525655, -0.83028934],
                                                    [0.68796176, -0.23672793]])),
                    "CSP-transformed data (%s) does not match expectation (%s)!"%(
                    str(transformed_data[0:2,:]),str(numpy.array([[0.14525655, -0.83028934],
                                                    [0.68796176, -0.23672793]]))
                    ))
コード例 #2
0
ファイル: test_csp.py プロジェクト: pyspace/test
    def test_csp(self):
        """
        Tests that CSP produces the expected transformation matrix on the data
        """
        csp_node = CSPNode(retained_channels=2)
        for i in range(self.data.shape[0]):
            ts = TimeSeries(input_array=self.data[i:i + 1, :],
                            channel_names=[("test_channel_%s" % j)
                                           for j in range(2)],
                            sampling_frequency=10,
                            start_time=0,
                            end_time=1)
            csp_node.train(ts, self.classes[i])
        csp_node.stop_training()

        self.assert_(
            numpy.allclose(
                csp_node.filters,
                numpy.array([[-0.75319083, -0.35237094], [1., -1.]])),
            "CSP transformation matrix is wrong! Got:%s, expected:%s" %
            (str(csp_node.filters),
             str(numpy.array([[-0.75319083, -0.35237094], [1., -1.]]))))

        transformed_data = numpy.zeros(self.data.shape)
        for i in range(self.data.shape[0]):
            ts = TimeSeries(input_array=self.data[i:i + 1, :],
                            channel_names=[("test_channel_%s" % j)
                                           for j in range(2)],
                            sampling_frequency=10,
                            start_time=0,
                            end_time=1)
            transformed_data[i, :] = csp_node.execute(ts)

        self.assert_(
            numpy.allclose(
                transformed_data[0:2, :],
                numpy.array([[0.14525655, -0.83028934],
                             [0.68796176, -0.23672793]])),
            "CSP-transformed data (%s) does not match expectation (%s)!" %
            (str(transformed_data[0:2, :]),
             str(
                 numpy.array([[0.14525655, -0.83028934],
                              [0.68796176, -0.23672793]]))))
コード例 #3
0
ファイル: xdawn.py プロジェクト: ahmedadelhassan/pyspace
    def store_state(self, result_dir, index=None):
        """ Stores this node in the given directory *result_dir* """
        if self.store:
            try:
                node_dir = os.path.join(result_dir, self.__class__.__name__)
                create_directory(node_dir)
                # This node only stores the learned spatial filters
                name = "%s_sp%s.pickle" % ("patterns", self.current_split)
                result_file = open(os.path.join(node_dir, name), "wb")
                result_file.write(
                    cPickle.dumps((self.filters, self.wi, self.ai),
                                  protocol=2))
                result_file.close()

                # Stores the signal to signal plus noise ratio resulted
                # by the spatial filter
                #fname = "SNR_sp%s.csv" % ( self.current_split)
                #numpy.savetxt(os.path.join(node_dir, fname), self.SNR,
                #    delimiter=',', fmt='%2.5e')

                # Store spatial filter plots if desired
                if self.visualize_pattern:
                    from pySPACE.missions.nodes.spatial_filtering.csp \
                        import CSPNode
                    # Compute, accumulate and analyze signal components
                    # estimated by xDAWN
                    vmin = numpy.inf
                    vmax = -numpy.inf

                    signal_components = []
                    complete_signal = numpy.zeros(
                        (self.wi.shape[1], self.ai.shape[1]))
                    for filter_index in range(self.retained_channels):
                        #self.ai.shape[0]):
                        signal_component = numpy.outer(
                            self.wi[filter_index, :], self.ai[filter_index, :])
                        vmin = min(signal_component.min(), vmin)
                        vmax = max(signal_component.max(), vmax)

                        signal_components.append(signal_component)
                        complete_signal += signal_component
                    # Plotting
                    import pylab
                    for index, signal_component in enumerate(
                            signal_components):
                        pylab.figure(0, figsize=(18, 8))
                        pylab.gcf().clear()

                        # Plot spatial distribution
                        ax = pylab.axes([0.0, 0.0, 0.2, 0.5])
                        CSPNode._plot_spatial_values(ax, self.wi[index, :],
                                                     self.channel_names,
                                                     'Spatial distribution')
                        # Plot spatial filter
                        ax = pylab.axes([0.0, 0.5, 0.2, 0.5])
                        CSPNode._plot_spatial_values(ax, self.filters[:,
                                                                      index],
                                                     self.channel_names,
                                                     'Spatial filter')
                        # Plot signal component in electrode coordinate system
                        self._plotTimeSeriesInEC(signal_component,
                                                 vmin=vmin,
                                                 vmax=vmax,
                                                 bb=(0.2, 1.0, 0.0, 1.0))

                        pylab.savefig("%s%ssignal_component%02d.png" %
                                      (node_dir, os.sep, index))

                    CSPNode._store_spatial_filter_plots(
                        self.filters[:, :self.retained_channels],
                        self.channel_names, node_dir)
                    # Plot entire signal
                    pylab.figure(0, figsize=(15, 8))
                    pylab.gcf().clear()
                    self._plotTimeSeriesInEC(
                        complete_signal,
                        file_name="%s%ssignal_complete.png" %
                        (node_dir, os.sep))
                    pylab.savefig("%s%ssignal_complete.png" %
                                  (node_dir, os.sep))

            except Exception as e:
                print e
                raise
        super(XDAWNNode, self).store_state(result_dir)
コード例 #4
0
ファイル: xdawn.py プロジェクト: MMKrell/pyspace
    def store_state(self, result_dir, index=None): 
        """ Stores this node in the given directory *result_dir* """
        if self.store:
            try:
                node_dir = os.path.join(result_dir, self.__class__.__name__)
                create_directory(node_dir)
                # This node only stores the learned spatial filters
                name = "%s_sp%s.pickle" % ("patterns", self.current_split)
                result_file = open(os.path.join(node_dir, name), "wb")
                result_file.write(cPickle.dumps((self.filters, self.wi,
                                                 self.ai), protocol=2))
                result_file.close()
                
                # Stores the signal to signal plus noise ratio resulted
                # by the spatial filter
                #fname = "SNR_sp%s.csv" % ( self.current_split)
                #numpy.savetxt(os.path.join(node_dir, fname), self.SNR,
                #    delimiter=',', fmt='%2.5e')
                
                # Store spatial filter plots if desired
                if self.visualize_pattern:
                    from pySPACE.missions.nodes.spatial_filtering.csp \
                        import CSPNode
                    # Compute, accumulate and analyze signal components
                    # estimated by xDAWN
                    vmin = numpy.inf
                    vmax = -numpy.inf
    
                    signal_components = []
                    complete_signal = numpy.zeros((self.wi.shape[1],
                                                   self.ai.shape[1]))
                    for filter_index in range(self.retained_channels):
                        #self.ai.shape[0]):
                        signal_component = numpy.outer(self.wi[filter_index, :], 
                                                       self.ai[filter_index, :])
                        vmin = min(signal_component.min(), vmin)
                        vmax = max(signal_component.max(), vmax)
                        
                        signal_components.append(signal_component)
                        complete_signal += signal_component
                    # Plotting
                    import pylab
                    for index, signal_component in enumerate(signal_components):
                        pylab.figure(0, figsize=(18,8))
                        pylab.gcf().clear()
                        
                        # Plot spatial distribution
                        ax=pylab.axes([0.0, 0.0, 0.2, 0.5])
                        CSPNode._plot_spatial_values(ax, self.wi[index, :], 
                                                     self.channel_names,
                                                     'Spatial distribution')
                        # Plot spatial filter
                        ax=pylab.axes([0.0, 0.5, 0.2, 0.5])
                        CSPNode._plot_spatial_values(ax, self.filters[:, index],
                                                     self.channel_names,
                                                     'Spatial filter')
                        # Plot signal component in electrode coordinate system 
                        self._plotTimeSeriesInEC(signal_component, vmin=vmin, 
                                                 vmax=vmax,
                                                 bb=(0.2, 1.0, 0.0, 1.0))

                        pylab.savefig("%s%ssignal_component%02d.png" 
                                      % (node_dir, os.sep, index))
    
                    CSPNode._store_spatial_filter_plots(
                        self.filters[:, :self.retained_channels],
                        self.channel_names, node_dir)
                    # Plot entire signal
                    pylab.figure(0, figsize=(15, 8))
                    pylab.gcf().clear()
                    self._plotTimeSeriesInEC(
                        complete_signal,
                        file_name="%s%ssignal_complete.png" % (node_dir, os.sep)
                        )
                    pylab.savefig(
                        "%s%ssignal_complete.png" % (node_dir, os.sep))

            except Exception as e:
                print e
                raise
        super(XDAWNNode, self).store_state(result_dir)