Main function to calculate ratios for PSMs, peptides, proteins, genes.
    Can do simple ratios, median-of-ratios and median-centering
    normalization.
965853
def get_isobaric_ratios(psmfn, psmheader, channels, denom_channels, min_int,
                        targetfn, accessioncol, normalize, normratiofn):
    """"""
    psm_or_feat_ratios = get_psmratios(psmfn, psmheader, channels,
                                       denom_channels, min_int, accessioncol)
    if normalize and normratiofn:
        normheader = reader.get_tsv_header(normratiofn)
        normratios = get_ratios_from_fn(normratiofn, normheader, channels)
        ch_medians = get_medians(channels, normratios, report=True)
        outratios = calculate_normalized_ratios(psm_or_feat_ratios, ch_medians,
                                                channels)
    elif normalize:
        flatratios = [[feat[ch] for ch in channels]
                      for feat in psm_or_feat_ratios]
        ch_medians = get_medians(channels, flatratios, report=True)
        outratios = calculate_normalized_ratios(psm_or_feat_ratios, ch_medians,
                                                channels)
    else:
        outratios = psm_or_feat_ratios
    # at this point, outratios look like:
    # [{ch1: 123, ch2: 456, ISOQUANTRATIO_FEAT_ACC: ENSG1244}, ]
    if accessioncol and targetfn:
        outratios = {x[ISOQUANTRATIO_FEAT_ACC]: x for x in outratios}
        return output_to_target_accession_table(targetfn, outratios, channels)
    elif not accessioncol and not targetfn:
        return paste_to_psmtable(psmfn, psmheader, outratios)
    elif accessioncol and not targetfn:
        # generate new table with accessions
        return ({(k if not k == ISOQUANTRATIO_FEAT_ACC
                  else prottabledata.HEADER_ACCESSION): v
                 for k, v in ratio.items()} for ratio in outratios)
976644
def calcMomentsMatlabEmpirical(params):
    """"""
    alpha = params[0]
    a = params[1:5]
    b = params[5:]
    p1 = alpha*a+(1-alpha)*b
    p21 = alpha*a[0]*a[1:]/(1-a[0])+(1-alpha)*b[0]*b[1:]/(1-b[0])
    p22 = alpha*a[1]*np.hstack((a[0],a[2:]))/(1-a[1])+(1-alpha)*b[1]*np.hstack((b[0],b[2:]))/(1-b[1])
    p23 = alpha*a[2]*np.hstack((a[:2],a[3]))/(1-a[2])+(1-alpha)*b[2]*np.hstack((b[:2],b[3]))/(1-b[2])
    p24 = alpha*a[3]*a[:3]/(1-a[3])+(1-alpha)*b[3]*b[:3]/(1-b[3])
    p3 = np.array([
        alpha*a[0]*a[2]*a[3]/(1-a[2])/(a[0]+a[1])+(1-alpha)*b[0]*b[2]*b[3]/(1-b[2])/(b[0]+b[1]),
        alpha*a[0]*a[1]*a[3]/(1-a[3])/(a[1]+a[2])+(1-alpha)*b[0]*b[1]*b[3]/(1-b[3])/(b[1]+b[2]),
        alpha*a[0]*a[1]*a[2]/(1-a[0])/(a[3]+a[2])+(1-alpha)*b[0]*b[1]*b[2]/(1-b[0])/(b[3]+b[2]),
        alpha*a[2]*a[1]*a[3]/(1-a[1])/(a[0]+a[3])+(1-alpha)*b[2]*b[1]*b[3]/(1-b[1])/(b[0]+b[3])
        ])
    return np.concatenate((p1,p21,p22,p23,p24,p3))
1052392
def calcul_ratios_calage(year_data, year_calage, data_bdf, data_cn):
    '''
    
    '''
    masses = data_cn.merge(
        data_bdf, left_index = True, right_index = True
        )
    masses.rename(columns = {0: 'conso_bdf{}'.format(year_data)}, inplace = True)
    if year_calage != year_data:
        masses['ratio_cn{}_cn{}'.format(year_data, year_calage)] = (
            masses['consoCN_COICOP_{}'.format(year_calage)] / masses['consoCN_COICOP_{}'.format(year_data)]
            )
    if year_calage == year_data:
        masses['ratio_cn{}_cn{}'.format(year_data, year_calage)] = 1

    masses['ratio_bdf{}_cn{}'.format(year_data, year_data)] = (
        1e6 * masses['consoCN_COICOP_{}'.format(year_data)] / masses['conso_bdf{}'.format(year_data)]
        )
    return masses
100029
def set_features(self):
        """""""
        allpsms_str = readers.generate_psms_multiple_fractions_strings(
            self.mergefiles, self.ns)
        allpeps = preparation.merge_peptides(self.mergefiles, self.ns)
        self.features = {'psm': allpsms_str, 'peptide': allpeps}
982269
def get_pepproteins(line):
    
    psm_id = get_psm_id(line)
    proteins = get_proteins_from_psm(line)
    return psm_id, proteins
430090
function scorePattern(point, ratios, matrix) {
        try {
            const horizontalRun = countBlackWhiteRun(point, { x: -1, y: point.y }, matrix, ratios.length);
            const verticalRun = countBlackWhiteRun(point, { x: point.x, y: -1 }, matrix, ratios.length);
            const topLeftPoint = {
                x: Math.max(0, point.x - point.y) - 1,
                y: Math.max(0, point.y - point.x) - 1,
            };
            const topLeftBottomRightRun = countBlackWhiteRun(point, topLeftPoint, matrix, ratios.length);
            const bottomLeftPoint = {
                x: Math.min(matrix.width, point.x + point.y) + 1,
                y: Math.min(matrix.height, point.y + point.x) + 1,
            };
            const bottomLeftTopRightRun = countBlackWhiteRun(point, bottomLeftPoint, matrix, ratios.length);
            const horzError = scoreBlackWhiteRun(horizontalRun, ratios);
            const vertError = scoreBlackWhiteRun(verticalRun, ratios);
            const diagDownError = scoreBlackWhiteRun(topLeftBottomRightRun, ratios);
            const diagUpError = scoreBlackWhiteRun(bottomLeftTopRightRun, ratios);
            const ratioError = Math.sqrt(horzError.error * horzError.error +
                vertError.error * vertError.error +
                diagDownError.error * diagDownError.error +
                diagUpError.error * diagUpError.error);
            const avgSize = (horzError.averageSize + vertError.averageSize + diagDownError.averageSize + diagUpError.averageSize) / 4;
            const sizeError = (Math.pow((horzError.averageSize - avgSize), 2) +
                Math.pow((vertError.averageSize - avgSize), 2) +
                Math.pow((diagDownError.averageSize - avgSize), 2) +
                Math.pow((diagUpError.averageSize - avgSize), 2)) / avgSize;
            return ratioError + sizeError;
        }
        catch (_a) {
            return Infinity;
        }
    }
353956
function Ratio() {
        Channel.apply(this, arguments);
        this.dataType = NUMBER | PERCENT;
        this.cssType = NUMBER;
        this.range = [0, 1];
        this.filter = CLAMP;
        this.initial = 1;
    }
283272
def plot_eqarea_pars(self, pars, fig):
        
        if pars == {}:
            pass
        elif 'calculation_type' in list(pars.keys()) and pars['calculation_type'] == 'DE-BFP':
            ymin, ymax = fig.get_ylim()
            xmin, xmax = fig.get_xlim()

            D_c, I_c = pmag.circ(pars["specimen_dec"],
                                 pars["specimen_inc"], 90)
            X_c_up, Y_c_up = [], []
            X_c_d, Y_c_d = [], []
            for k in range(len(D_c)):
                XY = pmag.dimap(D_c[k], I_c[k])
                if I_c[k] < 0:
                    X_c_up.append(XY[0])
                    Y_c_up.append(XY[1])
                if I_c[k] > 0:
                    X_c_d.append(XY[0])
                    Y_c_d.append(XY[1])
            fig.plot(X_c_d, Y_c_d, 'b', lw=0.5)
            fig.plot(X_c_up, Y_c_up, 'c', lw=0.5)
            if self.ie_open:
                self.ie.plot(X_c_d, Y_c_d, 'b', lw=0.5)
                self.ie.plot(X_c_up, Y_c_up, 'c', lw=0.5)

            fig.set_xlim(xmin, xmax)
            fig.set_ylim(ymin, ymax)
        # plot best-fit direction
        else:
            if "specimen_dec" in list(pars.keys()) and "specimen_inc" in list(pars.keys()):
                dec = pars["specimen_dec"]
                inc = pars["specimen_inc"]
            elif "dec" in list(pars.keys()) and "inc" in list(pars.keys()):
                dec = pars["dec"]
                inc = pars["inc"]
            else:
                print(("either dec or inc missing from values recived for high level plot, was given %s, aborting" % (
                    str(pars))))
                return
            XY = pmag.dimap(float(dec), float(inc))
            if inc > 0:
                if 'color' in list(pars.keys()):
                    FC = pars['color']
                    EC = pars['color']
                    SIZE = 15*self.GUI_RESOLUTION
                else:
                    FC = 'grey'
                    EC = 'grey'
                    SIZE = 15*self.GUI_RESOLUTION
            else:
                if 'color' in list(pars.keys()):
                    FC = 'white'
                    EC = pars['color']
                    SIZE = 15*self.GUI_RESOLUTION
                else:
                    FC = 'white'
                    EC = 'grey'
                    SIZE = 15*self.GUI_RESOLUTION
            fig.scatter([XY[0]], [XY[1]], marker='o', edgecolor=EC,
                        facecolor=FC, s=SIZE, lw=1, clip_on=False)
            if self.ie_open:
                self.ie.scatter([XY[0]], [XY[1]], marker='o', edgecolor=EC,
                                facecolor=FC, s=SIZE, lw=1, clip_on=False)
684598
def normalize_total(adata, target_sum=None, fraction=1, key_added=None,
                    layers=None, layer_norm=None, inplace=True):
    
    if fraction < 0 or fraction > 1:
        raise ValueError('Choose fraction between 0 and 1.')

    X = adata.X
    gene_subset = None
    if not inplace:
    # not recarray because need to support sparse
        dat = {}

    if fraction < 1:
        logg.msg('normalizing by count per cell for \
                  genes that make up less than fraction * total count per cell', r=True)
        X = adata.X

        counts_per_cell = X.sum(1)
        counts_per_cell = np.ravel(counts_per_cell)

        gene_subset = (X>counts_per_cell[:, None]*fraction).sum(0)
        gene_subset = (np.ravel(gene_subset) == 0)
    else:
        logg.msg('normalizing by total count per cell', r=True)

    X = X if gene_subset is None else adata[:, gene_subset].X
    counts_per_cell = X.sum(1)
    # get rid of adata view
    counts_per_cell = np.ravel(counts_per_cell).copy()
    del X
    del gene_subset

    if key_added is not None:
        adata.obs[key_added] = counts_per_cell

    cell_subset = counts_per_cell>0
    if not np.all(cell_subset):
        logg.warn('Some cells have total count of genes equal to zero')

    if layer_norm == 'after':
        after = target_sum
    elif layer_norm == 'X':
        after = np.median(counts_per_cell[cell_subset])
    elif layer_norm is None:
        after = None
    else:
        raise ValueError('layer_norm should be "after", "X" or None')
    del cell_subset

    if inplace:
        if hasattr(adata.X, '__itruediv__'):
            _normalize_data(adata.X, counts_per_cell, target_sum)
        else:
            adata.X = _normalize_data(adata.X, counts_per_cell, target_sum, copy=True)
    else:
        dat['X'] = _normalize_data(adata.X, counts_per_cell, target_sum, copy=True)

    layers = adata.layers.keys() if layers == 'all' else layers
    if layers is not None:
        for layer in layers:
            L = adata.layers[layer]
            counts = np.ravel(L.sum(1))
            if inplace:
                if hasattr(L, '__itruediv__'):
                    _normalize_data(L, counts, after)
                else:
                    adata.layers[layer] = _normalize_data(L, counts, after, copy=True)
            else:
                dat[layer] = _normalize_data(L, counts, after, copy=True)

    logg.msg('    finished', t=True, end=': ')
    logg.msg('normalized adata.X')
    if key_added is not None:
        logg.msg('and added \'{}\', counts per cell before normalization (adata.obs)'
            .format(key_added))

    return dat if not inplace else None
334080
def cause_ratio(self, mechanism, purview):
        """"""
        return self._ratio(Direction.CAUSE, mechanism, purview)
845456
def get_atlas_summary_df(self):
        
        all_info = []
        for g in self.reference_gempro.genes_with_a_representative_sequence:
            info = {}
            info['Gene_ID'] = g.id
            info['Gene_name'] = g.name

            # Protein object
            p = g.protein
            info['Protein_sequences'] = len(p.sequences)
            info['Protein_structures'] = len(p.structures)

            # SeqProp
            rseq = p.representative_sequence
            info['RepSeq_ID'] = rseq.id
            info['RepSeq_sequence_length'] = rseq.seq_len
            info['RepSeq_num_sequence_alignments'] = len([x for x in p.sequence_alignments if x.annotations['ssbio_type'] == 'seqalign'])
            info['RepSeq_num_structure_alignments'] = len([x for x in p.sequence_alignments if x.annotations['ssbio_type'] == 'structalign'])

            # SeqRecord annotations (properties calculated that summarize the whole sequence)
            for annotation_name, annotation in rseq.annotations.items():
                info['RepSeq_' + annotation_name] = annotation

            # SeqRecord alignment annotations
            all_num_mutations = []
            all_num_deletions = []
            all_len_deletions = []
            all_num_insertions = []
            all_len_insertions = []
            all_percent_identity = []
            all_percent_similarity = []
            for aln in p.sequence_alignments:
                # Gather the strain speicific stuff
                if '{}_'.format(p.id) not in aln.annotations['b_seq']:
                    continue
                info[aln.annotations['b_seq'].split('{}_'.format(p.id))[1]] = aln.annotations['percent_identity']

                # Gather the percent identities/similarities
                all_percent_identity.append(aln.annotations['percent_identity'])
                all_percent_similarity.append(aln.annotations['percent_similarity'])

                # Gather the number of residues that are mutated (filter for different mutations of same residue)
                num_mutations = len(list(set([x[1] for x in aln.annotations['mutations']])))
                all_num_mutations.append(num_mutations)

                # Gather the number of deletions as well as the length of the deletion
                if not aln.annotations['deletions']:
                    num_deletions = 0
                    len_deletions = [0]
                else:
                    num_deletions = len(aln.annotations['deletions'])
                    len_deletions = [x[1] for x in aln.annotations['deletions']]
                all_num_deletions.append(num_deletions)
                # Get the total length of the deletion for this one strain
                avg_len_deletions = np.sum(len_deletions)
                all_len_deletions.append(avg_len_deletions)

                # Gather the number of insertions as well as the length of the insertion
                if not aln.annotations['insertions']:
                    num_insertions = 0
                    len_insertions = [0]
                else:
                    num_insertions = len(aln.annotations['insertions'])
                    len_insertions = [x[1] for x in aln.annotations['insertions']]
                all_num_insertions.append(num_insertions)
                # Get the total length of insertion for this one strain
                avg_len_insertions = np.sum(len_insertions)
                all_len_insertions.append(avg_len_insertions)

            info['ATLAS_mean_num_mutations'] = np.mean(all_num_mutations)
            info['ATLAS_mean_num_deletions'] = np.mean(all_num_deletions)
            info['ATLAS_mean_len_deletions'] = np.mean(all_len_deletions)
            info['ATLAS_mean_num_insertions'] = np.mean(all_num_insertions)
            info['ATLAS_mean_len_insertions'] = np.mean(all_len_insertions)
            info['ATLAS_mean_percent_identity'] = np.mean(all_percent_identity)
            info['ATLAS_mean_percent_similarity'] = np.mean(all_percent_similarity)

            # Other mutation analysis
            single, fingerprint = p.sequence_mutation_summary()

            # Mutations that show up in more than 10% of strains
            singles = []
            for k, v in single.items():
                k = [str(x) for x in k]
                if len(v) / len(p.sequence_alignments) >= 0.01:
                    singles.append(''.join(k))  # len(v) is the number of strains which have this mutation
            info['ATLAS_popular_mutations'] = ';'.join(singles)

            # Mutation groups that show up in more than 10% of strains
            allfingerprints = []
            for k, v in fingerprint.items():
                if len(v) / len(p.sequence_alignments) >= 0.01:
                    fingerprints = []
                    for m in k:
                        y = [str(x) for x in m]
                        fingerprints.append(''.join(y))
                    allfingerprints.append('-'.join(fingerprints))
            info['ATLAS_popular_mutation_groups'] = ';'.join(allfingerprints)

            # StructProp
            rstruct = p.representative_structure
            if rstruct:
                if rstruct.structure_file:
                    info['RepStruct_ID'] = rstruct.id
                    info['RepStruct_is_experimental'] = rstruct.is_experimental
                    info['RepStruct_description'] = rstruct.description
                    info['RepStruct_repseq_coverage'] = p.representative_chain_seq_coverage

                    # ChainProp
                    rchain = p.representative_chain
                    info['RepChain_ID'] = rchain

                    # ChainProp SeqRecord annotations
                    rchain_sr = rstruct.chains.get_by_id(rchain).seq_record
                    for annotation_name, annotation in rchain_sr.annotations.items():
                        info['RepChain_' + annotation_name] = annotation

            all_info.append(info)

        cols = ['Gene_ID', 'Gene_name', 'Protein_sequences', 'Protein_structures',
                'RepSeq_ID', 'RepSeq_sequence_length',
                'RepSeq_num_sequence_alignments', 'RepSeq_num_structure_alignments',
                'RepStruct_ID', 'RepChain_ID', 'RepStruct_description',
                'RepStruct_is_experimental', 'RepStruct_repseq_coverage',
                'ATLAS_mean_percent_identity', 'ATLAS_mean_percent_similarity', 'ATLAS_mean_num_mutations',
                'ATLAS_popular_mutations', 'ATLAS_popular_mutation_groups', 'ATLAS_mean_num_deletions',
                'ATLAS_mean_num_insertions', 'ATLAS_mean_len_deletions', 'ATLAS_mean_len_insertions',
                'RepSeq_aromaticity', 'RepSeq_instability_index', 'RepSeq_isoelectric_point', 'RepSeq_molecular_weight',
                'RepSeq_monoisotopic', 'RepSeq_num_tm_helix-tmhmm', 'RepSeq_percent_acidic', 'RepSeq_percent_aliphatic',
                'RepSeq_percent_aromatic', 'RepSeq_percent_B-sspro8', 'RepSeq_percent_basic',
                'RepSeq_percent_buried-accpro', 'RepSeq_percent_buried-accpro20', 'RepSeq_percent_C-sspro',
                'RepSeq_percent_C-sspro8', 'RepSeq_percent_charged', 'RepSeq_percent_E-sspro',
                'RepSeq_percent_E-sspro8', 'RepSeq_percent_exposed-accpro', 'RepSeq_percent_exposed-accpro20',
                'RepSeq_percent_G-sspro8', 'RepSeq_percent_H-sspro', 'RepSeq_percent_H-sspro8',
                'RepSeq_percent_helix_naive', 'RepSeq_percent_I-sspro8', 'RepSeq_percent_non-polar',
                'RepSeq_percent_polar', 'RepSeq_percent_S-sspro8', 'RepSeq_percent_small',
                'RepSeq_percent_strand_naive', 'RepSeq_percent_T-sspro8', 'RepSeq_percent_tiny',
                'RepSeq_percent_turn_naive', 'RepChain_percent_B-dssp', 'RepChain_percent_C-dssp',
                'RepChain_percent_E-dssp', 'RepChain_percent_G-dssp', 'RepChain_percent_H-dssp',
                'RepChain_percent_I-dssp', 'RepChain_percent_S-dssp', 'RepChain_percent_T-dssp',
                'RepChain_SSBOND-biopython']
        cols.extend([x.id for x in self.strains])

        df_atlas_summary = pd.DataFrame(all_info, columns=cols)
        # Drop columns that don't have anything in them
        df_atlas_summary.dropna(axis=1, how='all', inplace=True)

        return df_atlas_summary
455825
def run(self):
        

        S = self.model.stoichiometry_matrix
        amat = self.model.propensities
        ymat = self.model.species
        n_species = len(ymat)

        # dPdt is matrix of each species differentiated w.r.t. time
        # The code below literally multiplies the stoichiometry matrix to a column vector of propensities
        # from the right (::math::`\frac{dP}{dt} = \mathbf{Sa}`)
        dPdt =  S * amat


        # A Is a matrix of each species (rows) and the derivatives of their stoichiometry matrix rows
        # against each other species
        # Code below computes the matrix A, that is of size `len(ymat) x len(ymat)`, for which each entry
        # ::math::`A_{ik} = \sum_j S_{ij} \frac{\partial a_j}{\partial y_k} = \mathfb{S_i} \frac{\partial \mathbf{a}}{\partial y_k}`
        A = sp.Matrix(len(ymat), len(ymat), lambda i, j: 0)
        for i in range(A.rows):
            for k in range(A.cols):
                A[i, k] = reduce(operator.add, [S[i, j] * sp.diff(amat[j], ymat[k]) for j in range(len(amat))])


        # `diagA` is a matrix that has values sqrt(a[i]) on the diagonal (0 elsewhere)
        diagA = sp.Matrix(len(amat), len(amat), lambda i, j: amat[i] ** sp.Rational(1,2) if i==j else 0)
        # E is stoichiometry matrix times diagA
        E = S * diagA

        variance_terms = []
        cov_matrix = []
        for i in range(len(ymat)):
            row = []
            for j in range(len(ymat)):
                if i <= j:
                    symbol = 'V_{0}_{1}'.format(i, j)
                    variance_terms.append(VarianceTerm(position=(i,j), symbol=symbol))
                else:
                    # Since Vi,j = Vj,i, i.e. covariance are equal, we only record Vi,j but not Vj,i
                    symbol = 'V_{0}_{1}'.format(j, i)
                    variance_terms.append(VarianceTerm(position=(j,i), symbol=symbol))
                row.append(symbol)
            cov_matrix.append(row)

        V = sp.Matrix(cov_matrix)


        # Matrix of variances (diagonal) and covariances of species i and j differentiated wrt time.
        # I.e. if i=j, V_ij is the variance, and if i!=j, V_ij is the covariance between species i and species j
        dVdt = A * V + V * (A.T) + E * (E.T)


        # build ODEProblem object
        rhs_redundant = sp.Matrix([i for i in dPdt] + [i for i in dVdt])


        #generate ODE terms
        n_vectors = [tuple([1 if i==j else 0 for i in range(n_species)]) for j in range(n_species)]
        moment_terms = [Moment(nvec,lhs) for (lhs, nvec) in zip(ymat, n_vectors)]

        ode_description = moment_terms + variance_terms


        non_redundant_idx = []
        ode_terms = []
        # remove repetitive covariances, as Vij = Vji
        for i, cov in enumerate(ode_description):
            if cov in ode_terms:
                continue
            else:
                ode_terms.append(cov)
                non_redundant_idx.append(i)
        rhs = []
        for i in non_redundant_idx:
            rhs.append(rhs_redundant[i])


        out_problem = ODEProblem("LNA", ode_terms, rhs, sp.Matrix(self.model.parameters))


        return out_problem
668170
def mdl(ll, k, data):
    

    """
    N - no. of genes
    n - no. of cells 
    k - no. of cell types
    R - sum(Dataset) i.e. total no. of reads

    function TotCost = TotBits(N,m,p,R,C)
        # C is the cost from the cost function
        TotCost = C + (N*m + m*p)*(log(R/(N*p)));
    """
    N, m = data.shape
    cost = ll + (N*m + m*k)*(np.log(data.sum()/(N*k)))
    return cost
1255977
def effect_ratio(self, mechanism, purview):
        """"""
        return self._ratio(Direction.EFFECT, mechanism, purview)
204748
def show_stacking(self):
        """"""
        grp = self.getPseudoBondGroup("pi-Stacking-%i" % self.tid, associateWith=[self.model])
        grp.lineWidth = 3
        grp.lineType = self.chimera.Dash
        for i, stack in enumerate(self.plcomplex.pistacking):

            m = self.model
            r = m.newResidue("pseudoatoms", " ", 1, " ")
            centroid_prot = m.newAtom("CENTROID", self.chimera.Element("CENTROID"))
            x, y, z = stack.proteinring_center
            centroid_prot.setCoord(self.chimera.Coord(x, y, z))
            r.addAtom(centroid_prot)

            centroid_lig = m.newAtom("CENTROID", self.chimera.Element("CENTROID"))
            x, y, z = stack.ligandring_center
            centroid_lig.setCoord(self.chimera.Coord(x, y, z))
            r.addAtom(centroid_lig)

            b = grp.newPseudoBond(centroid_lig, centroid_prot)
            b.color = self.colorbyname('forest green')

            self.bs_res_ids += stack.proteinring_atoms
388750
def _calculate_ratios(self, list_a, list_b):
        

        comparisons = []
        l = Levenshtein()

        # For all strings in list a
        for i, str_a in enumerate(list_a):

            # Add a new list to our list of lists of comparisons
            comparisons.append([])

            # Compare str_a to every string in list_b
            for str_b in list_b:

                # If the sanitize, input flag is set, make the ratio with the sanitized values
                if self.sanitize_input:
                    new_comparison = Comparison(
                                            str_a['text'],
                                            str_b['text'],
                                            l.ratio(str_a['sanitized'], str_b['sanitized'])
                                        )

                # Otherwise, make the ratio with the original, unsanitize text strings
                else:
                    new_comparison = Comparison(
                                            str_a['text'],
                                            str_b['text'],
                                            l.ratio(str_a['text'], str_b['text'])
                                        )

                # If text metadata is set on this class for text a or b, save that data with the
                # comparison
                if self.text_ref_a:
                    new_comparison.set_ref_a(self.text_ref_a)
                if self.text_ref_b:
                    new_comparison.set_ref_b(self.text_ref_b)

                # Finally, append the new comparison to the list of comparisons
                comparisons[i].append(new_comparison)

        return comparisons
7395
def create_pep_protein_quant_lookup(fns, pqdb, poolnames, featcolnr, patterns,
                                    storefuns, isobqcolpattern=None,
                                    psmnrpattern=None):
    """"""
    tablefn_map = create_tablefn_map(fns, pqdb, poolnames)
    feat_map = pqdb.get_feature_map()
    for pattern, storefun in zip(patterns, storefuns):
        if pattern is None:
            continue
        colmap = get_colmap(fns, pattern, single_col=True)
        if colmap:
            store_single_col_data(fns, tablefn_map, feat_map,
                                  storefun, featcolnr, colmap)
    if isobqcolpattern is not None:
        isocolmap = get_colmap(fns, isobqcolpattern, antipattern=psmnrpattern)
    else:
        return
    if psmnrpattern is not None:
        psmcolmap = get_colmap(fns, psmnrpattern)
    else:
        psmcolmap = False
    create_isobaric_quant_lookup(fns, tablefn_map,
                                 feat_map, pqdb,
                                 featcolnr,
                                 isocolmap, psmcolmap)