Center the expression of each gene (row).
439319
def center_genes(self, use_median=False, inplace=False):
        """"""
        if use_median:
            X = self.X - \
                np.tile(np.median(self.X, axis=1), (self.n, 1)).T
        else:
            X = self.X - \
                np.tile(np.mean(self.X, axis=1), (self.n, 1)).T

        if inplace:
            self.X[:,:] = X
            matrix = self
        else:
            matrix = ExpMatrix(genes=self.genes, samples=self.samples,
                               X=X)
        return matrix
1150902
def main(args):
   """"""
   txome = Transcriptome()
   #read the reference gpd if one is gven
   if args.reference: 
      rinf = None
      if re.search('\.gz$',args.reference):
         rinf = gzip.open(args.reference)
      else:
         rinf = open(args.reference)
      sys.stderr.write("Reading in reference\n")
      z = 0
      # populate txome with reference transcripts for each chromosome
      for line in rinf:
         z += 1
         gpd = GPD(line)
         gpd.set_payload(z)
         if z%100 == 0:  sys.stderr.write(str(z)+"          \r")
         txome.add_transcript(gpd)
      rinf.close()
      sys.stderr.write(str(z)+"          \r")
      sys.stderr.write("\n")
   txome.sort_transcripts()
   sys.stderr.write("Buffering mappings\n")
   inf = sys.stdin
   if args.input != '-':
      if re.search('\.gz$',args.input):
         inf = gzip.open(args.input)
      else:
         inf = open(args.input)
   tof = gzip.open(args.tempdir+'/reads.gpd.gz','w')
   for line in inf: tof.write(line.rstrip()+"\n")
   tof.close()
  
   sys.stderr.write("1. Process by overlapping locus.\n")
   annotated_reads(txome,gzip.open(args.tempdir+'/reads.gpd.gz'),'initial',args)

   #of.close()

   """Now sequences we should be able to annotate as partial have
      consensus transcripts.  Lets put those to annotation scrutiny again.
   """
   sys.stderr.write("2. Reannotated partially annotated by overlapping locus.\n")
   annotated_reads(txome,gzip.open(args.tempdir+'/initial/partial_annotated_multiexon.sorted.gpd.gz'),'repartial',args)


   txs = {}
   for transcript in txome.transcripts:
      txs[transcript.name] = transcript
   detected = {}
   tinf = gzip.open(args.tempdir+'/initial/annotated.txt.gz')
   for line in tinf:
      f = line.rstrip().split("\t")
      detected[f[1]] = True
   tinf.close()
   tinf = gzip.open(args.tempdir+'/repartial/annotated.txt.gz')
   remove_partial = {}
   for line in tinf:
      f = line.rstrip().split("\t")
      detected[f[1]] = True
      remove_partial[f[1]] = True
   tinf.close()
   tof = gzip.open(args.tempdir+'/candidate.gpd.gz','w')
   for name in detected:
      tof.write(txs[name].get_gpd_line()+"\n")
   tinf = gzip.open(args.tempdir+'/initial/partial_annotated_multiexon.sorted.gpd.gz')
   for line in tinf:
      f = line.rstrip().split("\t")
      if f[1] not in remove_partial:
         tof.write(line)
   tinf = gzip.open(args.tempdir+'/initial/unannotated_singleexon.sorted.gpd.gz')
   for line in tinf:
      f = line.rstrip().split("\t")
      f[0] = str(uuid.uuid4())
      tof.write("\t".join(f)+"\n")
   tinf.close()
   tof.close()
   sort_gpd(args.tempdir+'/candidate.gpd.gz',args.tempdir+'/candidate.sorted.gpd.gz',args)
   """We can ignore the partial annotations that have been detected"""
   ntxome = Transcriptome()
   tinf = gzip.open(args.tempdir+'/candidate.sorted.gpd.gz')
   for line in tinf: ntxome.add_transcript(GPD(line))     
   annotated_reads(ntxome,gzip.open(args.tempdir+'/initial/unannotated_multiexon.sorted.gpd.gz'),'unannotated',args)
   """now we know which unannotated reads actually have annotations"""
   tinf.close()

   tof = gzip.open(args.tempdir+'/final.gpd.gz','w')
   tinf = gzip.open(args.tempdir+'/candidate.sorted.gpd.gz')   
   for line in tinf: tof.write(line)
   tinf.close()
   tinf = gzip.open(args.tempdir+'/unannotated/unannotated_multiexon.sorted.gpd.gz')   
   for line in tinf: tof.write(line)
   tinf.close()
   tinf = gzip.open(args.tempdir+'/unannotated/partial_annotated_multiexon.sorted.gpd.gz')   
   for line in tinf: tof.write(line)
   tinf.close()
   tof.close()
   sort_gpd(args.tempdir+'/final.gpd.gz',args.tempdir+'/final.sorted.gpd.gz',args)
   """Prepare outputs"""
   of = sys.stdout
   if args.output:
      if re.search('\.gz$',args.output):
         of = gzip.open(args.output,'w')
      else:
         of = open(args.output,'w')
   tinf = gzip.open(args.tempdir+'/final.sorted.gpd.gz')
   for line in tinf: of.write(line)
   tinf.close()
   of.close()
973309
private List<?> joinFeatures(List<?> list) {
        List result = new ArrayList<Object>();

        for (Object object : list) {
            int start = -1;
            int end = -1;

            if (object instanceof Gene) {
                result.add(object);
                start = ((Gene) object).getStart();
                end = ((Gene) object).getEnd();
            }

            if (object instanceof RegulatoryRegion) {
                result.add(object);
                start = ((RegulatoryRegion) object).getStart();
                end = ((RegulatoryRegion) object).getEnd();
            }

            if (object instanceof List) {
                result.addAll(joinFeatures((List) object));
            }

            /* Acutualizamos los valores maximo de end y minimo de start */
            if ((start != -1) && (start < min_start)) {
                min_start = start;
            }

            if ((end != -1) && (end > max_end)) {
                max_end = end;
            }
        }

        return result;
    }
137107
def _add_gene_disease(self, row):  # ::List  getting syntax error here
        
        col = self.files['developmental_disorders']['columns']
        if len(row) != len(col):
            raise ValueError("Unexpected number of fields for row {}".format(row))

        variant_label = "variant of {}".format(row[col.index('gene_symbol')])
        disease_omim_id = row[col.index('disease_omim_id')]
        if disease_omim_id == 'No disease mim':
            # check if we've manually curated
            disease_label = row[col.index('disease_label')]
            if disease_label in self.mondo_map:
                disease_id = self.mondo_map[disease_label]
            else:
                return  # sorry for this
        else:
            disease_id = 'OMIM:' + disease_omim_id

        hgnc_curie = 'HGNC:' + row[col.index('hgnc_id')]

        relation_curie = self.resolve(row[col.index('g2p_relation_label')])
        mutation_consequence = row[col.index('mutation_consequence')]
        if mutation_consequence not in ('uncertain', ''):
            consequence_relation = self.resolve(
                self._get_consequence_predicate(mutation_consequence))
            consequence_curie = self.resolve(mutation_consequence)
            variant_label = "{} {}".format(mutation_consequence, variant_label)
        else:
            consequence_relation = None
            consequence_curie = None

        allelic_requirement = row[col.index('allelic_requirement')]
        if allelic_requirement != '':
            requirement_curie = self.resolve(allelic_requirement)
        else:
            requirement_curie = None

        pmids = row[col.index('pmids')]
        if pmids != '':
            pmid_list = ['PMID:' + pmid for pmid in pmids.split(';')]
        else:
            pmid_list = []

        # build the model
        # Should we build a reusable object and/or tuple that
        # could be passed to a more general model builder for
        # this and orphanet (and maybe clinvar)
        self._build_gene_disease_model(
            hgnc_curie,
            relation_curie,
            disease_id,
            variant_label,
            consequence_relation,
            consequence_curie,
            requirement_curie,
            pmid_list
        )
1263993
function row(metric, dimensions, isTarget) {
  let left = '';
  let right = '';

  if (isTarget) {
    left = HIGHLIGHT;
    right = RESET;
  }

  return BORDER_VERT
    + left + padEnd(' ' + metric.label, dimensions.name) + right
    + BORDER_VERT
    + left + padEnd(' ' + metric.avg + UNIT, dimensions.avg) + right
    + BORDER_VERT
    + left + padEnd(' ' + metric.min + UNIT, dimensions.min) + right
    + BORDER_VERT
    + left + padEnd(' ' + metric.max + UNIT, dimensions.max) + right
    + BORDER_VERT
    + '\n';
}
1284551
def genbank_to_gene_coords(infile, genes):
    ''''''
    coords = {}

    for seq_record in SeqIO.parse(infile, "genbank"):
        for feature in seq_record.features:
            if feature.type == 'gene':
                gene_name = feature.qualifiers.get('gene', [None])[0]
                if gene_name not in genes:
                    continue

                if feature.location.strand == 1:
                    coords[gene_name] = {'start': int(feature.location.start), 'end': int(feature.location.end) - 1}
                else:
                    coords[gene_name] = {'end': int(feature.location.start), 'start': int(feature.location.end) - 1}

    return coords
1167150
def _init_objaartall(self):
        """"""
        kws = {
            'sortgo':lambda nt: [nt.NS, nt.dcnt],
            # fmtgo=('{p_fdr_bh:8.2e} {GO} '
            # Formatting for GO terms in grouped GO list
            'fmtgo':('{hdr1usr01:2} {NS} {GO} {s_fdr_bh:8} '
                     '{dcnt:5} {childcnt:3} R{reldepth:02} '
                     '{D1:5} {GO_name} ({study_count} study genes)\n'),
            # Formatting for GO terms listed under each gene
            'fmtgo2':('{hdr1usr01:2} {NS} {GO} {s_fdr_bh:8} '
                      '{dcnt:5} R{reldepth:02} '
                      '{GO_name} ({study_count} study genes)\n'),
            # itemid2name=ensmusg2symbol}
            }
        return AArtGeneProductSetsAll(self.grprdflt, self.hdrobj, **kws)
1156483
def _cnvkit_prioritize(sample, genes, allele_file, metrics_file):
    
    mdf = pd.read_table(metrics_file)
    mdf.columns = [x.lower() for x in mdf.columns]
    if len(genes) > 0:
        mdf = mdf[mdf["gene"].str.contains("|".join(genes))]
    mdf = mdf[["chromosome", "start", "end", "gene", "log2", "ci_hi", "ci_lo"]]
    adf = pd.read_table(allele_file)
    if len(genes) > 0:
        adf = adf[adf["gene"].str.contains("|".join(genes))]
    if "cn1" in adf.columns and "cn2" in adf.columns:
        adf = adf[["chromosome", "start", "end", "cn", "cn1", "cn2"]]
    else:
        adf = adf[["chromosome", "start", "end", "cn"]]
    df = pd.merge(mdf, adf, on=["chromosome", "start", "end"])
    df = df[df["cn"] != 2]
    if len(df) > 0:
        def passes(row):
            spread = abs(row["ci_hi"] - row["ci_lo"])
            return spread < 0.25
        df["passes"] = df.apply(passes, axis=1)
    df.insert(0, "sample", [sample] * len(df))
    return df
1332731
def centering_centroid(data, xi, yi, box, nloop=10, toldist=1e-3,
                       maxdist=10.0):
    '''
        
    '''

    # Store original center
    cxy = (xi, yi)
    origin = (xi, yi)
    # initial background
    back = 0.0

    if nloop == 0:
        return xi, yi, 0.0, 0, 'not recentering'

    for i in range(nloop):
        nxy, back = _centering_centroid_loop_xy(data, cxy, box)
        # _logger.debug('new center is %s', ncenter)
        # if we are to far away from the initial point, break
        dst = distance.euclidean(origin, nxy)
        if dst > maxdist:
            msg = 'maximum distance (%5.2f) from origin reached' % maxdist
            return cxy[0], cxy[1], back, 2, msg

        # check convergence
        dst = distance.euclidean(nxy, cxy)
        if dst < toldist:
            return nxy[0], nxy[1], back, 1, 'converged in iteration %i' % i
        else:
            cxy = nxy

    return nxy[0], nxy[1], back, 3, 'not converged in %i iterations' % nloop
603006
def _balanced_strand_gen(base_aligns, limit):
    ''''''
    predicate=lambda align: align.is_reverse
    gen1, gen2 = itertools.tee((predicate(align), align) for align in base_aligns)
    for_strand_gen = (align for pred, align in gen1 if not pred)
    rev_strand_gen = (align for pred, align in gen2 if pred)
    combined_gen = iter_zip(for_strand_gen, rev_strand_gen)
    interleaved_gen = (align for for_rev_aligns in combined_gen for align in for_rev_aligns)
    return itertools.islice(interleaved_gen, limit)
1118889
def parseNoise(rawArray): 
    '''
    
    '''
    nnGenes=[] 
    for i in range(0,(rawArray.shape[1])): #Checks all genes
        count0=np.asarray(np.where(rawArray[:,i]==0))
        count1=np.asarray(np.where(rawArray[:,i]==1))
        if ((count1.shape[1]+count0.shape[1])<rawArray.shape[0]):
            nnGenes=np.append(nnGenes,i)
    return nnGenes.astype(int)
235517
def cell_centers(dataset, vertex=True):
        
        alg = vtk.vtkCellCenters()
        alg.SetInputDataObject(dataset)
        alg.SetVertexCells(vertex)
        alg.Update()
        output = _get_output(alg)
        return output
1109620
def _match(self):
        """"""
        #disable optimized matching
        optimized_rows = None
        optimized_columns = None
        for match in self.__match_rows(optimized_rows):
            #match in rows
            yield match
        for match in self.__match_rows(optimized_columns,
                                       transpose=True):
            #match in columns and transpose coordinates
            yield match
393312
def from_genes(cls, genes: List[ExpGene]):
        """"""
        data = [g.to_dict() for g in genes]
        index = [d.pop('ensembl_id') for d in data]
        table = cls(data, index=index)
        return table
1113574
def enrich_rnas_with_genes(graph):
    
    for rna_node in list(graph):
        if rna_node[FUNCTION] not in {MIRNA, RNA} or FUSION in rna_node or VARIANTS in rna_node:
            continue

        gene_node = rna_node.get_gene()
        graph.add_transcription(gene_node, rna_node)
895599
def _refine_j(seq, species):
        '''
        
        '''
        jgerm = germlines.get_germline(seq['j_gene']['full'], species)
        aln = global_alignment(seq['vdj_nt'], jgerm)
        append = ''
        for s, g in zip(aln.aligned_query[::-1], aln.aligned_target[::-1]):
            if s != '-':
                break
            else:
                append += g
        seq['vdj_nt'] = seq['vdj_nt'] + append[::-1]
233246
def generate_poisson_lineage(n_states, n_cells_per_cluster, n_genes, means=300):
    
    # means...
    M = np.random.random((n_genes, n_states))*means
    center = M.mean(1)
    W = np.zeros((n_states, n_cells_per_cluster*n_states))
    # TODO
    # start at a center where all the clusters have equal probability, and for
    # each cluster, interpolate linearly towards the cluster.
    index = 0
    means = np.array([1.0/n_states]*n_states)
    for c in range(n_states):
        for i in range(n_cells_per_cluster):
            w = np.copy(means)
            new_value = w[c] + i*(1.0 - 1.0/n_states)/n_cells_per_cluster
            w[:] = (1.0 - new_value)/(n_states - 1.0)
            w[c] = new_value
            W[:, index] = w
            index += 1
    return M, W