<commit_before>'''
Created on Jun 14, 2013

@author: jonathanfriedman
'''
from fcm import loadFCS
from bases import BaseSample, BasePlate, to_list

class FCSample(BaseSample):
    '''
    A class for holding flow cytometry data from
    a single well or a single tube.
    '''
    
    def read_data(self, **kwargs):
        '''
        Read the datafile specified in Sample.datafile and 
        return the resulting object.
        Does NOT assign the data to self.data
        '''
        kwargs.setdefault('transform', None)
        data = loadFCS(self.datafile, **kwargs)
        return data
    
    def get_metadata(self, fields, kwargs={}):
        '''
        TODO: change to extract data from other notes fields (not just 'text')
        '''
#         if self.data is None:
#             raise Exception, 'Data must be read before extracting metadata.'
        fields = to_list(fields)
        func = lambda x: [x.notes.text[field] for field in fields]
        kwargs.setdefault('nout',len(fields))
        return self.apply(func, **kwargs)

    def ID_from_data(self):
        '''
        Returns the well ID from the src keyword in the FCS file. (e.g., A2)
        This keyword may not appear in FCS files generated by other machines,
        in which case this function will raise an exception.
        '''
        try:
            return self.get_metadata('src')[0]
        except:
            raise Exception("The keyword 'src' does not exist in the following FCS file: {}".format(self.datafile))
    def plot(self, channel_names, transform=(None, None), plot2d_type='dot2d', **kwargs):
        '''
        Plots the sample on the current axis.
        Follow with a call to matplotlibs show() in order to see the plot.

        Parameters
        ----------
        FCMdata : fcm data object
        channel_names : str| iterable of str | None
            name (names) channels to plot.
            given a single channel plots a histogram
            given two channels produces a 2d plot

        transform : tuple
            each element is set to None or 'logicle'
            if 'logicle' then channel data is transformed with logicle transformation

        plot2d_type : 'dot2d', 'hist2d'

        Returns
        -------
        gHandle: reference to axis
        '''
        import graph
        data = self.read_data()
        return graph.plotFCM(data, channel_names, transform=transform, plot2d_type=plot2d_type, **kwargs)


class FCPlate(BasePlate):
    '''
    A class for holding flow cytometry plate data.
    '''
    _sample_class = FCSample
        
if __name__ == '__main__':
    datadir = '../tests/data/'
#     print get_files(datadir)
    plate = FCPlate('test', datadir=datadir, shape=(4,5))
#     print plate
    print plate.wells 
    print plate.well_IDS
    
    plate.apply(lambda x:x.ID, 'ID', applyto='sample', well_ids=['A1','B1'])
    plate.apply(lambda x:x.datafile, 'file', applyto='sample')
    plate.apply(lambda x:x.shape[0], 'counts', keepdata=True)
    plate.get_well_metadata(['date', 'etim'])
    print plate.extracted['file'].values
    
#     plate.wells['1']['A'].get_metadata()
#     
#     well_ids = ['A2' , 'B3']
#     print plate.get_wells(well_ids)
#     
#     plate.clear_well_data()  
#     plate.clear_well_data(well_ids)             
            
        
<commit_msg>renamed plot function to plotFCM for sample, made sure that plotFCM checks whether data exists<commit_after>'''
Created on Jun 14, 2013

@author: jonathanfriedman
'''
from fcm import loadFCS
from bases import BaseSample, BasePlate, to_list

class FCSample(BaseSample):
    '''
    A class for holding flow cytometry data from
    a single well or a single tube.
    '''
    
    def read_data(self, **kwargs):
        '''
        Read the datafile specified in Sample.datafile and 
        return the resulting object.
        Does NOT assign the data to self.data
        '''
        kwargs.setdefault('transform', None)
        data = loadFCS(self.datafile, **kwargs)
        return data
    
    def get_metadata(self, fields, kwargs={}):
        '''
        TODO: change to extract data from other notes fields (not just 'text')
        '''
#         if self.data is None:
#             raise Exception, 'Data must be read before extracting metadata.'
        fields = to_list(fields)
        func = lambda x: [x.notes.text[field] for field in fields]
        kwargs.setdefault('nout',len(fields))
        return self.apply(func, **kwargs)

    def ID_from_data(self):
        '''
        Returns the well ID from the src keyword in the FCS file. (e.g., A2)
        This keyword may not appear in FCS files generated by other machines,
        in which case this function will raise an exception.
        '''
        try:
            return self.get_metadata('src')[0]
        except:
            raise Exception("The keyword 'src' does not exist in the following FCS file: {}".format(self.datafile))
    def plotFCM(self, channel_names, transform=(None, None), plot2d_type='dot2d', **kwargs):
        '''
        Plots the flow cytometry data associated with the sample on the current axis.
        Follow with a call to matplotlibs show() in order to see the plot.

        Parameters
        ----------
        FCMdata : fcm data object
        channel_names : str| iterable of str | None
            name (names) channels to plot.
            given a single channel plots a histogram
            given two channels produces a 2d plot

        transform : tuple
            each element is set to None or 'logicle'
            if 'logicle' then channel data is transformed with logicle transformation

        plot2d_type : 'dot2d', 'hist2d'

        Returns
        -------
        None: if no data is loaded
        gHandle: reference to axis
        '''
        import graph
        data = self.get_data()
        if data is None:
            return None
        else:
            return graph.plotFCM(data, channel_names, transform=transform, plot2d_type=plot2d_type, **kwargs)


class FCPlate(BasePlate):
    '''
    A class for holding flow cytometry plate data.
    '''
    _sample_class = FCSample

        
if __name__ == '__main__':
    datadir = '../tests/data/'
#     print get_files(datadir)
    plate = FCPlate('test', datadir=datadir, shape=(4,5))
#     print plate
    print plate.wells 
    print plate.well_IDS
    
    plate.apply(lambda x:x.ID, 'ID', applyto='sample', well_ids=['A1','B1'])
    plate.apply(lambda x:x.datafile, 'file', applyto='sample')
    plate.apply(lambda x:x.shape[0], 'counts', keepdata=True)
    plate.get_well_metadata(['date', 'etim'])
    print plate.extracted['file'].values
    
#     plate.wells['1']['A'].get_metadata()
#     
#     well_ids = ['A2' , 'B3']
#     print plate.get_wells(well_ids)
#     
#     plate.clear_well_data()  
#     plate.clear_well_data(well_ids)             
            
        

{'fraction_non_alphanumeric': 0.10454677092383435, 'fraction_numerical': 0.0069504778453518675, 'mean_word_length': 2.2657210401891255, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2179054', 'n_tokens_mistral': 2028, 'n_tokens_neox': 1982, 'n_words': 651}