示例#1
0
    def ric(self, *args, **kwargs):
        '''This method is deprecated, use xic() instead.

        Kept for backwards compatibility.'''

        logger_message(40, 'ric() is deprecated: use xic() instead')
        return self.xic(*args, **kwargs)
示例#2
0
    def prot_report(self, report_file, prot_report):
        '''Adds a protein page to a report (XLS or MZD)'''

        logger_message(30, 'Adding Protein Info...')

        if report_file.lower().endswith('.mzd'):
            prot_rep = mzReport.mzDB.sqlite3.connect(report_file)
            prot_rep.execute(
                'create view ProteinData as select '
                '"Protein Rank","Accession Number","Protein Description",'
                '"Protein Mass","Protein Matches","Protein Score",'
                'count(distinct "Peptide Sequence") as "Unique Peptides"'
                ' from PeptideData group by "Protein Rank","Accession Number"')

            prot_rep.close()
        else:
            cols = [
                'Protein Rank', 'Accession Number', 'Protein Description',
                'Protein Mass', 'Protein Matches', 'Protein Score',
                'Unique Peptides'
            ]

            prot_rep = mzReport.writer(report_file,
                                       columns=cols,
                                       sheet_name='Protein')

            for line in prot_report:
                prot_rep.write(line)

            prot_rep.close()
示例#3
0
    def mascot_headers(self, report_file, mascot_headers):
        '''Combines a list of Mascot header pages into a single page (XLS or MZD)'''

        logger_message(30, 'Adding Mascot Headers...')

        first_columns = set()
        columns = defaultdict(dict)

        report_files = [f for f, mh in mascot_headers]

        for f, mascot_header in mascot_headers:
            first_col = []

            for line in mascot_header[1:]:
                if line[0] == ' ' or (isinstance(line[1], (str, unicode))
                                      and line[1].startswith('-----')):
                    continue
                columns[f][line[0]] = line[1]
                first_col.append(line[0])

            first_columns.add(tuple(first_col))

        if len(first_columns) > 1:
            logger_message(20,
                           'Headers seems different, will try to merge them')

            main_h = list(max(first_columns, key=len))
            main_h += sorted(
                reduce(set.union, first_columns, set()).difference(main_h))
        else:
            main_h = list(first_columns.pop())

        cols = ['Header'] + [(os.path.basename(f) if f else ('-' * 50))
                             for f in report_files]

        if report_file.lower().endswith('.mzd'):
            mascot_rep = mzReport.writer(report_file,
                                         columns=cols,
                                         table_name='MascotHeader')
        else:
            mascot_rep = mzReport.writer(report_file,
                                         columns=cols,
                                         sheet_name='Mascot_Header')

        for col in main_h:
            row = [col]

            for f in report_files:
                if col in columns[f]:
                    row.append(columns[f][col])
                else:
                    row.append(None)

            mascot_rep.write(row)

        mascot_rep.close()
示例#4
0
    def OnSubmit(self, event):
        self.writeback('Submitting Mascot search to %s...' % settings.mascot_server)
        if not self.parameters['FILE']:
            wx.MessageBox("Please select a file","Error")
            return
        elif not self.Validate():
            return

        wx.BeginBusyCursor()
        self.UpdateValues()
        file_list = self.parameters['FILE']
        
        self.parameters['MULTI_SITE_MODS'] = '1'

        if isinstance(file_list, basestring):
            file_list = [file_list] # How did this ever work previously??
        
        ms = MascotSearcher(settings.mascot_server,
                            open_tabs=self.open_tabs.IsChecked()) #, verbose=True)

        if settings.mascot_security:
            ms.login(self.login, self.password)

        results = []
        for f in file_list:
            self.writeback('Performing Mascot search on %s...' % os.path.basename(f))
            self.parameters['FILE'] = f
            logger_message(30, 'Submitting %s...' % os.path.basename(f))
            (dat,err) = ms.search(self.parameters.items())
            if dat:
                results.append(dat)
            if err:
                wx.MessageBox(err[1], 'Mascot Error: %s' % err[0],
                              style=wx.OK|wx.CENTER|wx.ICON_ERROR)

        #ms.close(sys.stdout)
        ms.close()
        self.parameters['FILE'] = file_list
        wx.EndBusyCursor()
        logger_message(40, 'Finished Mascot Search')
        self.writeback('Mascot search completed.')

        if self.getIDs.IsChecked():
            self.mascot_tab.login_text.SetValue(self.login)
            self.mascot_tab.password_text.SetValue(self.password)
            self.mascot_tab.mascot_id_text.SetValue(', '.join(results))
            self.mascot_tab.SetFocus()
示例#5
0
    def write(self, row, metadata=None, ignore_extra=False):
        # error checking: want one value per column and nothing more
        # if row is a dict, keys should be in lower-case
        if len(row) < len(self.columns):
            raise ValueError('Must have values for each column')
        elif (not ignore_extra) and len(row) > len(self.columns):
            raise ValueError('Too many values')
        elif isinstance(row, dict):
            row = dict((k.lower(), v) for k, v in list(row.items()))
            #if not all(k.lower() in row for k in self.columns):
            #raise ValueError('Value dictionary does not match column headers')

        if isinstance(row, dict):
            self.csv.writerow([row[col.lower()] for col in self.columns])
        else:
            self.csv.writerow(row)

        if metadata:
            logger_message(40, 'Metadata not supported in CSV files')
示例#6
0
文件: CSV.py 项目: manor/mz
    def write(self, row, metadata=None):
        # error checking: want one value per column and nothing more
        # if row is a dict, keys should be in lower-case
        if len(row) < len(self.columns):
            raise ValueError('Must have values for each column')
        elif len(row) > len(self.columns):
            raise ValueError('Too many values')
        elif isinstance(row,dict):
            row = dict((k.lower(),v) for k,v in row.items())
            if not all(k.lower() in row for k in self.columns):
                raise ValueError('Value dictionary does not match column headers')

        if isinstance(row,dict):
            self.csv.writerow([row[col.lower()] for col in self.columns])
        else:
            self.csv.writerow(row)

        if metadata:
            logger_message(40, 'Metadata not supported in CSV files')
示例#7
0
    def mascot_header(self, report_file, mascot_header):
        '''Adds a Mascot Header page to a report (XLS or MZD)'''

        logger_message(30, 'Adding Mascot Header...')

        if report_file.lower().endswith('.mzd'):
            mascot_rep = mzReport.writer(report_file,
                                         columns=mascot_header[0],
                                         table_name='MascotHeader')
        else:
            mascot_rep = mzReport.writer(report_file,
                                         columns=mascot_header[0],
                                         sheet_name='Mascot_Header')

        for line in mascot_header[1:]:
            mascot_rep.write(line)

        mascot_rep.close()

        logger_message(20, 'Mascot Header Complete')
示例#8
0
    def mascot_prot_coverage(self, mascot_id, ion_cutoff, date=None):
        logger_message(30, 'Downloading Mascot Protein Coverage...')

        prots = {}

        row = (yield None)

        #for row in dataFile:
        while row:
            acc = row['Accession Number']
            start_pos = row['Start Position']
            end_pos = row['End Position']
            db_idx = row.get('protein database', None)
            if db_idx:
                db_idx = db_idx.split('::')[0]

            if acc in prots:
                (coverage, start_end, cov_per) = prots[acc]
            else:
                logger_message(10, "Getting coverage for: %s" % acc)
                (coverage, start_end,
                 cov_per) = self.mascot.get_coverage(acc,
                                                     mascot_id=mascot_id,
                                                     date=date,
                                                     cutoff=ion_cutoff,
                                                     db_idx=db_idx)
                prots[acc] = (coverage, start_end, cov_per)

            #check if connection error
            if coverage == 'error':
                logger_message(
                    30,
                    'Mascot Login Error. Please check your username and password and try again'
                )
                fh = open('multiplierz_error.txt', 'a')
                fh.write(
                    "Mascot Login Error. Please check your username and password and try again\n"
                )
                fh.close()
                break

            # convert protein-index into text-index
            conv_x = lambda i: i + 6 + ((i - 1) / 50) * 11 + (
                (i - 1) % 50) / 10

            nse = self.mascot.get_range(
                [conv_x(i) for i in range(start_pos, end_pos + 1)])
            metadatatuple = (coverage, start_end, nse)

            row = (yield (cov_per, ('Accession Number', 'prot coverage',
                                    metadatatuple)))
示例#9
0
        arg = sys.argv[1]

        if arg == '--run_register_interfaces':
            print "PERFORMING MZAPI SETUP"
            from multiplierz.mzAPI.management import registerInterfaces
            registerInterfaces()
            print "Setup complete; exiting."
        else:
            arg_ext = os.path.splitext(arg)[1]

            if arg_ext == '.mzd':
                app = wx.App(False)
                _icon = wx.Icon(_exe_name, wx.BITMAP_TYPE_ICO)

                logger_message(60, 'Loading mzResults...')

                from gui.report_viewer import ReportViewer

                report_viewer = ReportViewer(None, arg)
                report_viewer.SetIcon(_icon)
                report_viewer.Show()

                app.MainLoop()
    else:
        app = wx.App(False)

        _icon = wx.Icon(_exe_name, wx.BITMAP_TYPE_ICO)

        from gui import MultiplierzFrame
示例#10
0
    def legacy_get_reports(self,
                           mascot_ids,
                           dates=None,
                           chosen_folder=None,
                           combined_file=False,
                           rank_one=False,
                           protein_report=False,
                           mascot_options=None,
                           peaks=False,
                           peaks_options=None,
                           mascot_web=False,
                           mascot_web_options=None,
                           mascot_prot_cov=False,
                           ext='.xlsx',
                           local_dat_files=None,
                           mascotIDInResultName=False,
                           percolatorDirectory=None,
                           **kwargs):

        # mascot_ids should be a list/tuple of IDs. dates should be a matching list/tuple of dates,
        # or False. combined_file should be None for individual files or an output file name

        # mascot options: (max_hits, ion_cutoff, bold_red, unassigned_queries,
        #                  show_query_data, show_same_set, show_sub_set, quant) + mascot_id, date
        # mascot_web options: (ms2_img, mascot_ms2, mascot_var_mods,
        #                      draw_pep, instrument, im_size) + mascot_id, date
        # mascot_prot_cov options: ion_cutoff, mascot_id, date

        # defaults and overrides. The priority is:  keyword > option_dict > default

        # Using local .DATs means you don't have access to certain fancy
        # Mascot features.
        if local_dat_files:
            mascot_web = False
            mascot_prot_cov = False

        assert not peaks, (
            "precursor_peaks and images in result files are no longer supported; "
            "peaks argument to get_reports must be False.")

        # defaults
        _mascot_options = dict(max_hits=1000,
                               ion_cutoff=20,
                               bold_red=True,
                               unassigned_queries=False,
                               show_query_data=True,
                               show_same_set=False,
                               show_sub_set=False,
                               quant=False)
        # option_dict
        if mascot_options:
            _mascot_options.update(mascot_options)
        # keywords
        _mascot_options.update(
            (k, kwargs[k]) for k in kwargs if k in _mascot_options)
        for k in _mascot_options:
            if k in kwargs:
                _mascot_options[k] = kwargs[k]

        if peaks:
            # defaults
            _peaks_options = dict(time_window=(0.5, 0.5),
                                  mz_window=(0.1, 0.1),
                                  plot_ms1=False,
                                  plot_xic=False,
                                  plot_ms2=False,
                                  peak_area=False,
                                  reporter_ions=False,
                                  peakfilter=None,
                                  ion_list=['b', 'y'],
                                  instrument='ESI-TRAP',
                                  im_size=(8.0, 6.0))
            # option_dict
            if peaks_options:
                _peaks_options.update(peaks_options)
            # keywords
            _peaks_options.update(
                (k, kwargs[k]) for k in kwargs
                if (k in _peaks_options or k == 'peak_data_path'))

            # need a path (file or directory) to actually do this,
            # so we raise an exception if it's not present
            if 'peak_data_path' not in _peaks_options:
                raise ValueError(
                    'peak_data_path value is required for peak extraction')

        if mascot_web:
            # defaults
            _mascot_web_options = dict(ms2_img=True,
                                       mascot_ms2=True,
                                       mascot_var_mods=True,
                                       instrument='ESI-TRAP',
                                       im_size=(8.0, 6.0))
            # option_dict
            if mascot_web_options:
                _mascot_web_options.update(mascot_web_options)
            # keywords
            _mascot_web_options.update(
                (k, kwargs[k]) for k in kwargs if k in _mascot_web_options)

        # if version is 2.2+, mod positions are extracted automatically
        if mascot_web and self.mascot.version >= '2.2':
            _mascot_web_options['mascot_var_mods'] = False
            if not _mascot_web_options['ms2_img']:
                mascot_web = False

        # require agreement 'instrument' between two dictionaries
        if peaks and mascot_web:
            if _peaks_options['instrument'] != _mascot_web_options[
                    'instrument']:
                raise ValueError(
                    'instrument value must be consistent; input dictionaries disagree'
                )

        # Getting both of these would be redundant, so force at most one
        if mascot_web and peaks and _mascot_web_options['ms2_img']:
            _peaks_options['plot_ms2'] = False

        if chosen_folder is None:
            chosen_folder = myData

        # if creating a single file, we'll create the writer now
        if combined_file:
            # figuring out the report columns. start with defaults...
            repcols = mzReport.default_columns[:]

            # mascot 2.3 can have multiple databases so add a column for that
            if self.mascot.version >= '2.3':
                repcols.insert(1, 'Protein Database')

            # these are the columns coming out of the dat file, need them separate
            res_cols = repcols[:]

            # add columns for peak extraction
            if peaks:
                repcols.extend(c for c in [
                    'MS2 Time', 'Peak Time', 'Peak Intensity',
                    'Peak Width (sec)', 'Peak Comment'
                ] if c not in repcols)
                if _peaks_options['peak_area'] and 'Peak Area' not in repcols:
                    repcols.append('Peak Area')
                if _peaks_options['reporter_ions']:
                    repcols.extend(
                        c for c in ['Rep114', 'Rep115', 'Rep116', 'Rep117']
                        if c not in repcols)

            repcols.insert(0, 'File')

            report_file = os.path.join(chosen_folder, combined_file)

            if os.path.exists(report_file):
                os.remove(report_file)

            report = mzReport.writer(report_file, columns=repcols)
            isMZD = isinstance(report, mzReport.mzDB.SQLiteWriter)

            mascot_headers = []
        else:
            report_files = []

        if dates:
            mid_d = zip(mascot_ids, dates, [None] * len(mascot_ids))
        elif local_dat_files:
            mid_d = zip(["Local File"] * len(local_dat_files),
                        [None] * len(local_dat_files), local_dat_files)
        else:
            mid_d = [(mid, None, None) for mid in mascot_ids]

        for mascot_id, date, local in mid_d:
            mascot_id = str(mascot_id)

            if ':' in mascot_id:
                (mascot_id, date) = mascot_id.split(':', 1)

            mascot_id = str(mascot_id).zfill(6)

            if not (date or local):
                date = self.mascot.get_date(mascot_id)

            logger_message(
                30, 'Generating Multiplierz-Mascot Report for JobID %s...' %
                mascot_id)

            if ext == '.mzid':
                logger_message(30, 'Downloading mzIdentML File...')
                destination = chosen_folder if chosen_folder else myData

                reportfilename = "F%s.mzid" % mascot_id
                outputfile = os.path.join(destination, reportfilename)
                report_file = self.mascot.download_mzid(mascot_id,
                                                        save_file=outputfile,
                                                        date=date)
                assert report_file == outputfile

                report_files.append(report_file)
                continue
                # mzIdentML files don't use the rest of this function;
                # what they contain is essentially fixed, to multiplierz.

            if not local:
                logger_message(30, 'Downloading Mascot DAT File...')
                dat_file = self.mascot.download_dat(chosen_folder, mascot_id,
                                                    date)
            else:
                dat_file = os.path.abspath(local)
                mascot_id = os.path.basename(local).split('.')[0]

            if dat_file:
                logger_message(20, 'Mascot DAT File Downloaded!')
                mascot_dat_file = interface.MascotDatFile(
                    dat_file, **_mascot_options)

                if percolatorDirectory and mascot_dat_file.hasDecoyHits():
                    print "Running Mascot Percolator..."
                    mascot_dat_file.close()
                    percolatedDatFile = runPercolator(dat_file,
                                                      percolatorDirectory)
                    mascot_dat_file = interface.MascotDatFile(
                        dat_file, **mascot_options)

                    if self.cleanup:
                        os.remove(dat_file)
                    dat_file = percolatedDatFile

            else:
                logger_message(
                    40, 'Failed to download DAT file for %s' % mascot_id)
                continue

            if self.mascot.version != mascot_dat_file.res_file.getMascotVer(
            )[:len(self.mascot.version)]:
                print(
                    "Mascot version mismatch detected; changing version from %s to %s"
                    % (self.mascot.version,
                       mascot_dat_file.res_file.getMascotVer()
                       [:len(self.mascot.version)]))
                self.mascot.version = mascot_dat_file.res_file.getMascotVer(
                )[:len(self.mascot.version)]

            if not combined_file:
                # Report column stuff moved from above, in order to handle version dependency.  (Heavy sigh.)
                # figuring out the report columns. start with defaults...
                repcols = mzReport.default_columns[:]

                # mascot 2.3 can have multiple databases so add a column for that
                if self.mascot.version >= '2.3':
                    repcols.insert(1, 'Protein Database')

                # these are the columns coming out of the dat file, need them separate
                res_cols = repcols[:]

                # add columns for peak extraction
                if peaks:
                    repcols.extend(c for c in [
                        'MS2 Time', 'Peak Time', 'Peak Intensity',
                        'Peak Width (sec)', 'Peak Comment'
                    ] if c not in repcols)
                    if _peaks_options[
                            'peak_area'] and 'Peak Area' not in repcols:
                        repcols.append('Peak Area')
                    if _peaks_options['reporter_ions']:
                        repcols.extend(
                            c
                            for c in ['Rep114', 'Rep115', 'Rep116', 'Rep117']
                            if c not in repcols)

                if mascot_prot_cov:
                    repcols.append('Protein Coverage')

            #Get MS File Name
            mascot_header = mascot_dat_file.mascot_header()

            ms_file_name = mascot_header[7][1] or ('F%s' % mascot_id)

            if not combined_file:
                filename = os.path.basename(ms_file_name)
                if mascotIDInResultName and filename.endswith('.mgf'):
                    filename = filename[:-4] + "." + mascot_id

                report_file = os.path.join(chosen_folder, filename + ext)

                if os.path.exists(report_file):
                    os.remove(report_file)

                report = mzReport.writer(report_file, columns=repcols)
                isMZD = isinstance(report, mzReport.mzDB.SQLiteWriter)

            if mascot_web and (_mascot_web_options['ms2_img']
                               or _mascot_web_options['mascot_var_mods']):
                gen_options = {}
                try:
                    gen_options['ms2_img'] = _mascot_web_options['ms2_img']
                except KeyError:
                    pass
                try:
                    gen_options['mascot_var_mods'] = _mascot_web_options[
                        'mascot_var_mods']
                except KeyError:
                    pass

                mascot_web_gen = self.mascot_web(
                    mascot_id,
                    date=date,
                    dat_file=(dat_file
                              if _mascot_web_options['mascot_ms2'] else None),
                    isMZD=isMZD,
                    **gen_options)
                mascot_web_gen.next()

            if mascot_prot_cov:
                prot_cov_gen = self.mascot_prot_coverage(
                    mascot_id, _mascot_options['ion_cutoff'], date)
                prot_cov_gen.next()

            prot_desc_dict = {}

            if self.mascot.version != mascot_dat_file.res_file.getMascotVer(
            )[:len(self.mascot.version)]:
                raise TypeError, "Incorrect version of Mascot selected. %s %s" % (
                    self.mascot.version, mascot_dat_file.res_file.getMascotVer(
                    )[:len(self.mascot.version)])

            missing_desc_count = 0
            for row in mascot_dat_file.peptide_report():
                row = mzReport.ReportEntry(res_cols, row)

                if rank_one and row['Peptide Rank'] != 1:
                    continue

                if (not local) and not (row['Protein Description']
                                        or row['Protein Mass']):
                    if row['Accession Number'] not in prot_desc_dict:
                        missing_desc_count += 1
                        # Very slow!
                        #prot_desc_dict[row['Accession Number']] = self.mascot.get_description(row['Accession Number'],
                        #row.get('protein database', '1').split('::')[0],
                        #mascot_id,
                        #date)
                    row['Protein Description'], row[
                        'Protein Mass'] = prot_desc_dict.get(
                            row['Accession Number'], ('-', '-'))

                md = []
                #if peaks:
                #(new_row, img_tuples) = peak_gen.send(row)
                #row.update(new_row)
                #md.extend(img_tuples)

                if mascot_web and (_mascot_web_options['ms2_img']
                                   or _mascot_web_options['mascot_var_mods']):
                    (vartext, img_tup) = mascot_web_gen.send(row)
                    if _mascot_web_options['mascot_var_mods']:
                        row['Variable Modifications'] = vartext
                    if _mascot_web_options['ms2_img']:
                        md.append(img_tup)

                if mascot_prot_cov:
                    (prot_cov, md_tup) = prot_cov_gen.send(row)
                    row['Protein Coverage'] = prot_cov
                    md.append(md_tup)

                if combined_file:
                    row['File'] = ms_file_name

                report.write(row, metadata=md)
            if missing_desc_count:
                print "Missing protein info for %d PSMs." % missing_desc_count

            if peaks:
                peak_gen.close()
            if mascot_web and (_mascot_web_options['ms2_img']
                               or _mascot_web_options['mascot_var_mods']):
                mascot_web_gen.close()
            if mascot_prot_cov:
                prot_cov_gen.close()

            # Mascot-decoy-data finder!
            if mascot_dat_file.hasDecoyHits():
                decoy_dat_file = interface.MascotDatFile(dat_file,
                                                         decoyMode=True,
                                                         **_mascot_options)
                for row in decoy_dat_file.peptide_report():
                    report.write(row)
                decoy_dat_file.close()

            if not combined_file:
                if os.path.splitext(report_file)[1].lower() in ('.xls',
                                                                '.xlsx',
                                                                '.mzd'):
                    report.close()

                    self.mascot_headers(report_file, [(None, mascot_header)])
                    if protein_report:
                        self.prot_report(report_file,
                                         mascot_dat_file.protein_report())
                else:
                    report.close()

                report_files.append(report_file)
            else:
                if os.path.splitext(report_file)[1].lower() in ('.xls',
                                                                '.xlsx',
                                                                '.mzd'):
                    mascot_headers.append((ms_file_name, mascot_header))

            mascot_dat_file.close()
            if self.cleanup and not local_dat_files:
                os.remove(dat_file)

            logger_message(
                30, 'Multiplierz-Mascot Report for JobID %s Generated!' %
                mascot_id)

        if combined_file:
            if os.path.splitext(report_file)[1].lower() in ('.xls', '.xlsx',
                                                            '.mzd'):
                report.close()

                self.mascot_headers(report_file, mascot_headers)
                # not supported right now: protein reports for XLS.
                if isMZD and protein_report:
                    self.prot_report(report_file, None)
            else:
                report.close()

        return [report_file] if combined_file else report_files
示例#11
0
文件: __init__.py 项目: manor/mz
 def AddImage(self, *args, **kwargs):
     logger_message(50, 'This method is deprecated, use add_image() instead')
     self.add_image(*args, **kwargs)
示例#12
0
 def cursor(self):
     logger_message(
         50, "The cursor attribute is deprecated, use self.conn instead")
     return self.conn
示例#13
0
文件: DB.py 项目: manor/mz
 def cursor(self):
     logger_message(50, "The cursor attribute is deprecated, use self.conn instead")
     return self.conn
示例#14
0
    def __init__(self, parent, login='', password='', writeback = (lambda x: None)):
        """Instantiate the MascotSearch class. This creates a window for submitting to Mascot via Multiplierz.

        The basic workflow of this editor is:
        1. Select file(s)
        2. Customize settings via the GUI
        3. Submit to Mascot server
        4. Wait (or do other things) while the search runs
        """
        wx.Frame.__init__(self, None, -1, "Mascot MS/MS Ions Search", style=wx.DEFAULT_FRAME_STYLE ^ (wx.RESIZE_BORDER | wx.MAXIMIZE_BOX))
        self.SetExtraStyle(wx.WS_EX_VALIDATE_RECURSIVELY)
        pane = wx.Panel(self, -1, style = wx.TAB_TRAVERSAL | wx.CLIP_CHILDREN)

        for i in range(parent.nb.GetPageCount()):
            if parent.nb.GetPageText(i) == "Download Mascot":
                self.mascot_tab = parent.nb.GetPage(i)
                break
        else:
            logger_message(40, "Couldn't find Mascot downloader")
            self.mascot_tab = None

        self.login = login
        self.password = password
        self.writeback = writeback
        ms = MascotSearcher(settings.mascot_server)
        if settings.mascot_security:
            err = ms.login(self.login, self.password)
            if err:
                logger_message(40, "Error logging in to server: %s" % err)
                self.Close()
                return

        fields = ms.get_fields(settings.mascot_version)
        #fields = ms.get_fields_better()
        ms.close()

        menu_bar = wx.MenuBar()

        file_menu = wx.Menu()
        load_par = wx.MenuItem(file_menu, -1, "&Open PAR File\tCtrl+O")
        file_menu.AppendItem(load_par)
        self.Bind(wx.EVT_MENU, self.OnLoadPar, load_par)

        save_par = wx.MenuItem(file_menu, -1, "&Save Parameters\tCtrl+S")
        file_menu.AppendItem(save_par)
        self.Bind(wx.EVT_MENU, self.OnSavePar, save_par)

        menu_bar.Append(file_menu, "&File")

        output_menu = wx.Menu()
        self.open_tabs = wx.MenuItem(output_menu, -1, "&Open Results in Browser", kind=wx.ITEM_CHECK)
        output_menu.AppendItem(self.open_tabs)

        self.getIDs = wx.MenuItem(output_menu, -1, "&Send IDs to Mascot Downloader", kind=wx.ITEM_CHECK)
        output_menu.AppendItem(self.getIDs)
	
        if settings.mascot_server.find('www.matrixscience.com') != -1 or self.mascot_tab is None:
            self.getIDs.Enable(False)
            self.open_tabs.Check() # set default to open a browser
        else:
            self.getIDs.Check() # for non-public server, default to report-downloader

        menu_bar.Append(output_menu, "&Output")

        self.SetMenuBar(menu_bar)

        gbs = wx.GridBagSizer(10, 5)

        # parameter hash stores the values
        self.parameters = {'USERNAME':'',
                           'USEREMAIL':'',
                           'COM':'',
                           'DB':'',
                           'TAXONOMY':'',
                           'CLE':'',
                           'PFA':'',
                           'MODS':'',
                           'IT_MODS':'',
                           'TOL':'',
                           'TOLU':'',
                           'PEP_ISOTOPE_ERROR':'',
                           'ITOL':'',
                           'ITOLU':'',
                           'CHARGE':'',
                           'MASS':'',
                           'FILE':'',
                           'FORMAT':'',
                           'PRECURSOR':'',
                           'INSTRUMENT':'',
                           'REPORT':''
                           }

        if settings.mascot_version == '2.1':
            self.parameters.update( { 'SEG':'', 'ICAT':'', 'OVERVIEW':'' } )
        elif settings.mascot_version >= '2.2':
            self.parameters.update( { 'QUANTITATION':'', 'ERRORTOLERANT':'', 'DECOY':'', } )

        # labels
        labels = (zip(range(6) + range(7,11) + [0,4,5,7,10,11],
                      [0 for i in range(10)] + [5 for i in range(6)],
                      ['Name',
                       'Search title',
                       'Database',
                       'Taxonomy',
                       'Enzyme',
                       'Fixed\nModifications',
                       u'Peptipe tol. \xb1',
                       'Peptide Charge',
                       'Data File',
                       'Instrument',
                       'Email',
                       'Missed\nCleavages',
                       'Variable\nModifications',
                       u'MS/MS tol. \xb1',
                       'Precursor',
                       'Report Top']))

        if settings.mascot_version == '2.1':
            labels += (6, 0, 'Protein Mass'),
            gbs.Add( wx.StaticText(pane, -1, 'kDa'), (6,3), flag=wx.EXPAND )
        elif settings.mascot_version >= '2.2':
            labels += (6, 0, 'Quantitation'),
            # one fancytext label (for superscript)
            gbs.Add( FT.StaticFancyText(pane, -1, '# <sup>13</sup>C', style=wx.ALIGN_RIGHT),
                     (7,3), flag=wx.EXPAND )

        else:
            wx.MessageBox("This version of Mascot may not be supported correctly.")

        # ----- add labels -----
        for x,y,lbl in labels:
            gbs.Add( wx.StaticText(pane, -1, lbl, style=wx.ALIGN_RIGHT), (x,y), flag=wx.EXPAND )

        gbs.Add( wx.StaticText(pane, -1, 'm/z'), (10,8), flag=wx.EXPAND )

        # ----- add controls -----

        # name
        gbs.Add( wx.TextCtrl(pane, -1, "Your name here", name="USERNAME"), (0,1), (1,4), flag=wx.EXPAND )
        # email
        gbs.Add( wx.TextCtrl(pane, -1, "", name="USEREMAIL"), (0,6), (1,4), flag=wx.EXPAND )

        # title
        gbs.Add( wx.TextCtrl(pane, -1, "", name="COM"), (1,1), (1,7), flag=wx.EXPAND )

        # database
        if settings.mascot_version < '2.3':
            gbs.Add( wx.Choice(pane, -1, choices=fields['DB'], name="DB"), (2,1), (1,4), flag=wx.EXPAND )
        else:
            dbSelector = wx.CheckListBox(pane, -1, choices=fields['DB'], size=(228,81), name="DB")
            gbs.Add(dbSelector, (2,1), (1,4), flag=wx.EXPAND )
            self.Bind(wx.EVT_CHECKLISTBOX, self.onDatabaseSelect, dbSelector)

        # taxonomy
        gbs.Add( wx.Choice(pane, -1, choices=fields['TAXONOMY'], name="TAXONOMY"), (3,1), (1,8) )

        # enzyme
        gbs.Add( wx.Choice(pane, -1, choices=fields['CLE'], name="CLE"), (4,1), (1,4), flag=wx.EXPAND )
        # missed cleavages
        pfa_min = min(int(s) for s in fields['PFA'])
        pfa_max = max(int(s) for s in fields['PFA'])
        gbs.Add( wx.SpinCtrl(pane, -1, min=pfa_min, max=pfa_max, initial=int(fields['PFA'][0]), size=(40,21),
                             style=wx.SP_WRAP|wx.SP_ARROW_KEYS, name="PFA"), (4,6) )

        # fixed and variable modifications
        mods = wx.CheckListBox(pane, -1, choices=fields['MODS'], size=(228,81), name="MODS")
        gbs.Add( mods, (5,1), (1,4), flag=wx.EXPAND )
        mods.Bind(wx.EVT_CHECKLISTBOX, self.OnModSelect)

        it_mods = wx.CheckListBox(pane, -1, choices=fields['IT_MODS'], size=(228,81), name="IT_MODS")
        gbs.Add( it_mods, (5,6), (1,4), flag=wx.EXPAND )
        it_mods.Bind(wx.EVT_CHECKLISTBOX, self.OnModSelect)

        if settings.mascot_version == '2.1':
            gbs.Add( wx.TextCtrl(pane, -1, "", name="SEG", validator=ProtMassVal()), (6,1), (1,2), flag=wx.EXPAND )
            gbs.Add( wx.CheckBox(pane, -1, "ICAT", style=wx.ALIGN_RIGHT, name="ICAT"), (6,6), (1,2) )
        elif settings.mascot_version >= '2.2':
            # quantitation
            gbs.Add( wx.Choice(pane, -1, choices=fields['QUANTITATION'], name="QUANTITATION"), (6,1), (1,4), flag=wx.EXPAND )

        # peptide tolerance
        gbs.Add( wx.TextCtrl(pane, -1, "1.2", size=(40,21), validator=TolValidator(), name="TOL"), (7,1) )
        # pep tol units
        gbs.Add( wx.Choice(pane, -1, choices=fields['TOLU'], name="TOLU"), (7,2) )

        if settings.mascot_version >= '2.2':
            # isotope error (# 13C)
            pie_min = min(int(s) for s in fields['PEP_ISOTOPE_ERROR'])
            pie_max = max(int(s) for s in fields['PEP_ISOTOPE_ERROR'])
            gbs.Add( wx.SpinCtrl(pane, -1, min=pie_min, max=pie_max, initial=int(fields.selected['PEP_ISOTOPE_ERROR']),
                                 size=(40,21), style=wx.SP_WRAP|wx.SP_ARROW_KEYS, name="PEP_ISOTOPE_ERROR"), (7,4) )

        # MS/MS tolerance
        gbs.Add( wx.TextCtrl(pane, -1, "0.6", size=(40,21), validator=TolValidator(), name="ITOL"), (7,6) )
        # MS/MS tol units
        gbs.Add( wx.Choice(pane, -1, choices=fields['ITOLU'], name="ITOLU"), (7,7) )

        # peptide charge
        gbs.Add( wx.Choice(pane, -1, choices=fields['CHARGE'], name="CHARGE"), (8,1), (1,4) )

        # monoisotopic/average radiobox
        gbs.Add( wx.RadioBox( pane, -1, choices=['Monoisotopic','Average'], style=wx.ALIGN_RIGHT, name="MASS"), (8,6), (2,4) )

        # file control
        self.fname = wx.TextCtrl(pane, -1, "", style=wx.TE_READONLY)
        self.fname.BackgroundColour = wx.NamedColour("LIGHT GREY")
        gbs.Add( self.fname, (9,1), (1,4), flag=wx.EXPAND )
        self.fname.Bind(wx.EVT_LEFT_UP, self.OnChooseFile)

        fbutton = wx.Button(pane, -1, "Browse...")
        gbs.Add( fbutton, (9,5) )
        fbutton.Bind(wx.EVT_BUTTON, self.OnChooseFile)

        # instrument
        gbs.Add( wx.Choice(pane, -1, choices=fields['INSTRUMENT'], name="INSTRUMENT"), (10,1), (1,4), flag=wx.EXPAND )

        # precursor
        gbs.Add( wx.TextCtrl(pane, -1, "", size=(60,21), name="PRECURSOR", validator=PreValidator()),
                 (10,6), (1,2), flag=wx.EXPAND )

        if settings.mascot_version == '2.1':
            gbs.Add( wx.CheckBox(pane, -1, "Overview", style=wx.ALIGN_RIGHT, name="OVERVIEW"), (11,1), (1,2) )
        elif settings.mascot_version >= '2.2':
            # decoy/error tolerant checkboxes
            gbs.Add( wx.CheckBox(pane, -1, "Decoy", style=wx.ALIGN_RIGHT, name="DECOY"), (11,1), (1,2) )
            gbs.Add( wx.CheckBox(pane, -1, "Error Tolerant",
                                 style=wx.ALIGN_RIGHT, name="ERRORTOLERANT", validator=ErrorTolVal()), (11,3), (1,2) )

        # report top hits
        gbs.Add( wx.Choice(pane, -1, choices=fields['REPORT'], name="REPORT"), (11, 6), (1,2) )

        # Submit button
        submit = wx.Button(pane, -1, "Submit")
        gbs.Add( submit, (12,0), (1,10), flag=wx.EXPAND )
        submit.Bind(wx.EVT_BUTTON, self.OnSubmit)

        box = wx.BoxSizer()
        box.Add(gbs, 0, wx.ALL, 10)

        for child in pane.GetChildren():
            if isinstance(child,wx.Choice):
                if child.GetName() in fields.selected:
                    child.SetSelection(child.FindString(fields.selected[child.GetName()]))
                else:
                    child.SetSelection(0)

        pane.SetSizerAndFit(box)
        self.SetClientSize(pane.GetSize())
示例#15
0
文件: __init__.py 项目: manor/mz
 def Close(self, *args, **kwargs):
     logger_message(50, 'This method is deprecated, use close() instead')
     self.close(*args, **kwargs)
示例#16
0
 def add_image(self, column, image):
     logger_message(40, 'Images are not supported in CSV files')
示例#17
0
    def format(self, new_file_name=None):
        fh = open(self.orig_file)

        #Change header names
        header_line = fh.readline()
        headers = header_line.strip().split('\t')

        new_headers = multiplierz.mzReport.default_columns[:]
        new_headers.extend(('MS2 Time', 'Protein Coverage'))
        new_headers.remove('Peptide Rank')
        new_headers.remove('Query')
        new_headers.extend(h for h in headers if h not in self.reps)
        if 'Unused' in new_headers:
            new_headers.remove('Unused')
        if 'Contrib' in new_headers:
            new_headers.remove('Contrib')
        if 'Sc' in new_headers:
            new_headers.remove('Sc')

        rows = []

        protein_matches = defaultdict(int)

        for line in fh:
            new_data = dict((h, None) for h in new_headers)
            data = dict(zip(headers, line[:-1].split('\t')))

            protein_matches[data['Accessions']] += 1

            for h in data:
                if h in self.reps and self.reps[h] in new_data:
                    new_data[self.reps[h]] = data[h]
                elif h in new_data:
                    new_data[h] = data[h]
                elif h not in ('Unused', 'Contrib', 'Sc'):
                    logger_message(10, 'Missing key: %s' % h)

            if 'Modifications' in data:
                new_data['Variable Modifications'] = self.convert_var_mod(
                    data['Modifications'])

            if 'Cleavages' in data:
                new_data['Missed Cleavages'] = data['Cleavages'].count(
                    'missed')

            if 'Time' in data and 'Spectrum' in data:
                new_data['Spectrum Description'] = self.convert_spectrum(
                    data['Spectrum'], data['Time'])

            rows.append(new_data)

        fh.close()

        for row in rows:
            row['Protein Matches'] = protein_matches[row['Accession Number']]

        dir_split = os.path.split(self.orig_file)
        if not new_file_name:
            new_file_name = os.path.join(dir_split[0], "mz_" + dir_split[1])

        report = multiplierz.mzReport.writer(new_file_name,
                                             columns=new_headers)

        for row in rows:
            report.write(row)

        report.close()
示例#18
0
    def mascot_web(self,
                   mascot_id,
                   ms2_img,
                   mascot_var_mods=True,
                   instrument='ESI-TRAP',
                   date=None,
                   isMZD=False,
                   dat_file=None,
                   im_size=(8.0, 6.0)):

        logger_message(30, 'Downloading Mascot Spectra...')

        if mascot_var_mods and not ms2_img:
            mods_only = True
        if ms2_img:
            mods_only = False
        if mascot_var_mods and self.mascot.version >= '2.2':
            logger_message(
                40,
                'Warning: Variable modifications already present, overwriting')

        if dat_file:
            info_gen = interface.mascot_ms2(dat_file)
            info_gen.next()

        row = (yield None)

        while row:
            query = row['Query']
            logger_message(10,
                           'Downloading Mascot Spectra for query: %s' % query)

            peptide = row['Peptide Sequence']
            charge = row['Charge']
            score = row['Peptide Score']
            pep_rank = row['Peptide Rank']

            if dat_file:
                (peptide, var_text, mass_int, mass_labels,
                 ion_list) = info_gen.send((query, pep_rank))

                mass_int = tuple(sorted(mass_int))

                if ms2_img:
                    if isMZD:
                        image_tup = ('Peptide Sequence', 'ms2',
                                     (mass_int, 'c', peptide, mass_labels,
                                      ion_list, charge, score))
                    else:
                        (h, img_file) = mkstemp(suffix='.png',
                                                prefix='mascot_',
                                                dir=myTemp)
                        os.close(h)

                        logger_message(20, 'Drawing MS MS Mass Plot...')

                        mz_image.make_ms2_im(img_file[:-4],
                                             mass_int,
                                             'c',
                                             peptide,
                                             mass_labels,
                                             ion_list,
                                             charge,
                                             score,
                                             im_size=im_size)

                        image_tup = ('Peptide Sequence', 'image', img_file)
                else:
                    image_tup = None
            else:
                (h, img_file) = mkstemp(suffix='.gif',
                                        prefix='mascot_',
                                        dir=myTemp)
                os.close(h)

                (var_text, ionInfo, phosphoPos,
                 oxidPos) = self.mascot.get_msms(query,
                                                 img_file,
                                                 mascot_id=mascot_id,
                                                 score=score,
                                                 pep_rank=pep_rank,
                                                 date=date,
                                                 sequence=peptide,
                                                 mod_only=mods_only,
                                                 dat_file=dat_file)

                if ms2_img:
                    (h, gifpath) = mkstemp(suffix='.png',
                                           prefix='combo_',
                                           dir=myTemp)
                    os.close(h)

                    mz_image.make_mascot_ms2_im(gifpath, img_file, peptide,
                                                charge, score, ionInfo,
                                                phosphoPos, oxidPos,
                                                instrument)

                    image_tup = ('Peptide Sequence', 'image', gifpath)
                else:
                    image_tup = None

            if not mascot_var_mods:
                var_text = None

            row = (yield (var_text, image_tup))
示例#19
0
文件: CSV.py 项目: manor/mz
 def add_image(self, column, image):
     logger_message(40, 'Images are not supported in CSV files')
示例#20
0
文件: __init__.py 项目: manor/mz
 def WriteRow(self, *args, **kwargs):
     logger_message(50, 'This method is deprecated, use write() instead')
     self.write(*args, **kwargs)