Runs through proteins that are in a quanted protein table, extracts
    and maps their information based on the quantfields list input.
    Map is a dict with protein_accessions as keys.
342863
def get_quantmap(features, acc_col, quantfields):
    """"""
    qmap = {}
    for feature in features:
        feat_acc = feature.pop(acc_col)
        qmap[feat_acc] = {qf: feature[qf] for qf in quantfields}
    return qmap
889682
private void storeBioassemblyInformation(Map<String, Integer> chainIdToIndexMap, Map<Integer, BioAssemblyInfo> inputBioAss) {
		int bioAssemblyIndex = 0;
		for (Entry<Integer, BioAssemblyInfo> entry : inputBioAss.entrySet()) {
			Map<double[], int[]> transformMap = MmtfUtils.getTransformMap(entry.getValue(), chainIdToIndexMap);
			for(Entry<double[], int[]> transformEntry : transformMap.entrySet()) {
				mmtfDecoderInterface.setBioAssemblyTrans(bioAssemblyIndex, transformEntry.getValue(), transformEntry.getKey(), entry.getKey().toString());
			}
			bioAssemblyIndex++;
		}
	}
1258784
def get_proteins_psms_for_map(self):
        """"""
        fields = ['p.assoc_id', 'sets.set_name',
                  'pep.sequence', 'psm.psm_id']
        firstjoin = ('protein_psm', 'pp', 'protein_acc')
        genetable = self.table_map[self.datatype]['feattable']
        return self.get_unique_gene_psms(genetable, fields, firstjoin)
402326
public void process() throws IOException, StructureException {
		if(sequences == null) { // only process once, then return cached values
			LinkedHashMap<String, ProteinSequence> sequenceMap = reader.process();

			sequences = sequenceMap.values().toArray(new ProteinSequence[0]);
			accessions = new String[sequences.length];
			structures = new Structure[sequences.length];
			residues = new ResidueNumber[sequences.length][];

			// Match each sequence  to a series of PDB Residue numbers
			for(int i=0;i<sequences.length;i++) {
				accessions[i] = sequences[i].getAccession().getID();

				//System.out.println("Fetching "+accession);
				structures[i] = cache.getStructure(accessions[i]);

				residues[i] = StructureSequenceMatcher.matchSequenceToStructure(sequences[i], structures[i]);

				assert( residues[i].length == sequences[i].getLength());
			}
		}
	}
1146145
public static LinkedHashMap<String, ProteinSequence> readFastaProteinSequence(
			File file) throws IOException {
		FileInputStream inStream = new FileInputStream(file);
		LinkedHashMap<String, ProteinSequence> proteinSequences = readFastaProteinSequence(inStream);
		inStream.close();
		return proteinSequences;
	}
648298
def map_column(self, keys, func):
        
        return [[func(v) for v in self[key]] for key in keys]
331742
def add_psms_to_proteindata(proteindata, p_acc, pool, psmdata):
    """"""
    seq, psm_id = psmdata[2], psmdata[3]
    try:
        proteindata[p_acc]['pools'][pool]['psms'].add(psm_id)
    except KeyError:
        emptyinfo = {'psms': set(), 'peptides': set(), 'unipeps': 0}
        try:
            proteindata[p_acc]['pools'][pool] = emptyinfo
        except KeyError:
            proteindata[p_acc].update({'pools': {pool: emptyinfo}})
        proteindata[p_acc]['pools'][pool]['psms'].add(psm_id)
    proteindata[p_acc]['pools'][pool]['peptides'].add(seq)
396978
def protein_sequence(self, protein_id):
        
        if self.protein_sequences is None:
            raise ValueError(
                "No protein FASTA supplied to this Genome: %s" % self)
        return self.protein_sequences.get(protein_id)
5742
def get_msms_annotations(self, outdir, force_rerun=False):
        
        # Now can run on Biopython Model objects exclusively thanks to Biopython updates
        # if self.file_type != 'pdb':
        #     raise ValueError('{}: unable to run MSMS with "{}" file type. Please change file type to "pdb"'.format(self.id,
        #                                                                                                     self.file_type))

        if self.structure:
            parsed = self.structure
        else:
            parsed = self.parse_structure()

        if not parsed:
            log.error('{}: unable to open structure to run MSMS'.format(self.id))
            return

        log.debug('{}: running MSMS'.format(self.id))
        # PDB ID is currently set to the structure file so the output name is the same with _msms.df appended to it
        msms_results = ssbio.protein.structure.properties.msms.get_msms_df(model=parsed.first_model, pdb_id=self.structure_path,
                                                                           outdir=outdir, force_rerun=force_rerun)
        if msms_results.empty:
            log.error('{}: unable to run MSMS'.format(self.id))
            return

        chains = msms_results.chain.unique()

        for chain in chains:
            res_depths = msms_results[msms_results.chain == chain].res_depth.tolist()
            ca_depths = msms_results[msms_results.chain == chain].ca_depth.tolist()

            chain_prop = self.chains.get_by_id(chain)
            chain_seq = chain_prop.seq_record

            # Making sure the X's are filled in
            res_depths = ssbio.protein.structure.properties.residues.match_structure_sequence(orig_seq=chain_seq,
                                                                                              new_seq=res_depths,
                                                                                              fill_with=float('Inf'))

            ca_depths = ssbio.protein.structure.properties.residues.match_structure_sequence(orig_seq=chain_seq,
                                                                                             new_seq=ca_depths,
                                                                                             fill_with=float('Inf'))

            chain_prop.seq_record.letter_annotations['RES_DEPTH-msms'] = res_depths
            chain_prop.seq_record.letter_annotations['CA_DEPTH-msms'] = ca_depths
            log.debug('{}: stored residue depths in chain seq_record letter_annotations'.format(chain))
438198
def run(itf):
    

    if not itf:
        return 1

    # access user input
    options = SplitInput(itf)

    # read input
    inputpath = os.path.abspath(options.inputpath)
    print(" Reading input file ...")
    molecules = csv_interface.read_csv(inputpath, options)
    if not molecules:
        print("\n '{flag}' was unable to be parsed\n".format(flag=os.path.basename(options.inputpath)))
        sys.exit(1)

    # determine the sort order & ensemble_size
    #sort_order = classification.get_sort_order(molecules)
    sort_order = 'asc'
    ensemble_size = options.ensemble_size

    # loop over all ensembles
    # temp 2/3/15 append to auc_list ef_list & write it out for later histogram construction
    auc_list = []
    ef_list = []
    for size in [x + 1 for x in range(ensemble_size)]:
        auc, ef = optimizor(molecules, sort_order, size, options)
        auc_list += auc
        ef_list += ef
    # temp 2/9/15 write auc_list & ef_list out to files for subsequent post-processing
    f = open('auc_histogram.csv', 'w')
    for value in auc_list:
        f.write('%f\n' % value)
        #f.write('%f, %s\n' % (value[0], value[1]))
    f.close()
    f = open('ef_histogram.csv', 'w')
    for value in ef_list:
        f.write('%f\n' % value)
    f.close()
712932
def create_isobaric_quant_lookup(fns, tablefn_map, featmap, pqdb,
                                 featcolnr, allquantcols, psmcolmap):
    """"""
    pqdb.store_quant_channels(
            map_psmnrcol_to_quantcol(allquantcols, psmcolmap, tablefn_map),
            psmcolmap)
    quantmap = pqdb.get_quantchannel_map()
    to_store = []
    for fn, header, pquant in tsvreader.generate_tsv_pep_protein_quants(fns):
        pqdata = get_isob_quant_data(pquant, header, tablefn_map[fn],
                                     featmap, featcolnr, quantmap)
        to_store.extend(pqdata)
        if len(to_store) > 10000:
            pqdb.store_isobaric_quants(to_store, psmcolmap)
            to_store = []
    pqdb.store_isobaric_quants(to_store, psmcolmap)
496476
def convert(data, _first)
      data
        .reject { |o| o['refseq_protein_ids'].empty? }
        .map do |o|
          "#{o['peptide']}\tref|#{o['refseq_protein_ids']}|\t100\t10\t0\t0\t0\t10\t0\t10\t1e-100\t100\n"
        end
        .join
    end
1288342
def build_peptidetable(pqdb, headerfields, isobaric=False,
                       precursor=False, fdr=False, pep=False,
                       genecentric=False):
    """"""
    peptidedatamap = create_featuredata_map(pqdb, genecentric=genecentric, 
            psm_fill_fun=add_psm_to_peptidedata, pgene_fill_fun=add_protgene_to_pepdata,
            is_peptides=True)
    count_psms(peptidedatamap)
    empty_return = lambda x, y, z: {}
    iso_fun = {True: get_isobaric_quant, False: empty_return}[isobaric]
    ms1_fun = {True: get_precursor_quant, False: empty_return}[precursor]
    fdr_fun = {True: get_pep_fdr,
               False: empty_return}[fdr]
    pep_fun = {True: get_peptide_pep,
               False: empty_return}[pep]
    pdata_fun = get_protein_data
    peptide_sql, sqlfieldmap = pqdb.prepare_mergetable_sql(precursor, isobaric,
                                                           probability=False,
                                                           fdr=fdr, pep=pep)
    peptides = pqdb.get_merged_features(peptide_sql)
    peptide = next(peptides)
    outpeptide = {peptabledata.HEADER_PEPTIDE: peptide[sqlfieldmap['p_acc']]}
    check_pep = {k: v for k, v in outpeptide.items()}
    fill_mergefeature(outpeptide, iso_fun, ms1_fun, empty_return, fdr_fun,
                      pep_fun, pdata_fun, peptide, sqlfieldmap,
                      headerfields, peptidedatamap)
    for peptide in peptides:
        p_seq = peptide[sqlfieldmap['p_acc']]
        if p_seq != outpeptide[peptabledata.HEADER_PEPTIDE]:
            if outpeptide != check_pep:
                yield outpeptide
            outpeptide = {peptabledata.HEADER_PEPTIDE: p_seq}
            check_pep = {k: v for k, v in outpeptide.items()}
        fill_mergefeature(outpeptide, iso_fun, ms1_fun, empty_return, fdr_fun,
                          pep_fun, pdata_fun, peptide, sqlfieldmap,
                          headerfields, peptidedatamap)
    yield outpeptide
1285542
def run(n = 10)
      raise NotEnoughHitsError if hits.length < opt[:min_blast_hits]
      raise unless prediction.is_a?(Query) && !prediction.raw_sequence.nil? &&
                   hits[0].is_a?(Query)

      start = Time.new
      # get the first n hits
      n_hits = [n - 1, @hits.length].min
      less_hits = @hits[0..n_hits]
      # get raw sequences for less_hits
      less_hits.delete_if do |hit|
        if hit.raw_sequence.nil?
          hit.raw_sequence = FetchRawSequences.run(hit.identifier,
                                                   hit.accession_no)
        end
        hit.raw_sequence.nil? ? true : false
      end

      raise NoInternetError if less_hits.length.zero?

      averages = []

      less_hits.each do |hit|
        coverage = Array.new(hit.length_protein, 0)
        # each residue of the protein should be evluated once only
        ranges_prediction = []

        hit.hsp_list.each do |hsp|
          # align subsequences from the hit and prediction that match
          if !hsp.hit_alignment.nil? && !hsp.query_alignment.nil?
            hit_alignment   = hsp.hit_alignment
            query_alignment = hsp.query_alignment
          else
            align = find_local_alignment(hit, prediction, hsp)
            hit_alignment   = align[0]
            query_alignment = align[1]
          end

          coverage = check_multiple_coverage(hit_alignment, query_alignment,
                                             hsp, coverage, ranges_prediction)

          ranges_prediction << (hsp.match_query_from..hsp.match_query_to)
        end
        overlap = coverage.reject(&:zero?)
        if overlap != []
          averages.push((overlap.inject(:+) / (overlap.length + 0.0)).round(2))
        end
      end

      # if all hsps match only one time
      if averages.reject { |x| x == 1 } == []
        @validation_report = DuplicationValidationOutput.new(@short_header,
                                                             @header,
                                                             @description, 1,
                                                             averages)
        @validation_report.run_time = Time.now - start
        return @validation_report
      end

      pval = wilcox_test(averages)

      @validation_report = DuplicationValidationOutput.new(@short_header,
                                                           @header,
                                                           @description, pval,
                                                           averages)
      @run_time = Time.now - start
      @validation_report
    rescue NotEnoughHitsError
      @validation_report = ValidationReport.new('Not enough evidence', :warning,
                                                @short_header, @header,
                                                @description)
    rescue NoMafftInstallationError
      @validation_report = ValidationReport.new('Mafft error', :error,
                                                @short_header, @header,
                                                @description)
      @validation_report.errors.push NoMafftInstallationError
    rescue NoInternetError
      @validation_report = ValidationReport.new('Internet error', :error,
                                                @short_header, @header,
                                                @description)
      @validation_report.errors.push NoInternetError
    rescue StandardError
      @validation_report = ValidationReport.new('Unexpected error', :error,
                                                @short_header, @header,
                                                @description)
      @validation_report.errors.push 'Unexpected Error'
    end
58685
def get_proteins_for_peptide(self, psm_id):
        """"""
        protsql = self.get_sql_select(['protein_acc'], 'protein_psm')
        protsql = '{0} WHERE psm_id=?'.format(protsql)
        cursor = self.get_cursor()
        proteins = cursor.execute(protsql, psm_id).fetchall()
        return [x[0] for x in proteins]
405683
def sort_protein_group(pgroup, sortfunctions, sortfunc_index):
    """"""
    pgroup_out = []
    subgroups = sortfunctions[sortfunc_index](pgroup)
    sortfunc_index += 1
    for subgroup in subgroups:
        if len(subgroup) > 1 and sortfunc_index < len(sortfunctions):
            pgroup_out.extend(sort_protein_group(subgroup,
                                                 sortfunctions,
                                                 sortfunc_index))
        else:
            pgroup_out.extend(subgroup)
    return pgroup_out
523769
def create_merge_psm_map(peptides, ns):
    """"""
    psmmap = {}
    for peptide in peptides:
        seq = reader.get_peptide_seq(peptide, ns)
        psm_ids = reader.get_psm_ids_from_peptide(peptide, ns)
        for psm_id in psm_ids:
            try:
                psmmap[seq][psm_id.text] = 1
            except KeyError:
                psmmap[seq] = {psm_id.text: 2}
    for seq, psm_id_dict in psmmap.items():
        psmmap[seq] = [x for x in psm_id_dict]
    return psmmap