Quick method to let you go from a CDS to a Peptide quickly. It assumes
you are translating only in the first frame

@param dna
The CDS to translate
@return The Protein Sequence
967716
public Sequence<AminoAcidCompound> translate(
			Sequence<NucleotideCompound> dna) {
		Map<Frame, Sequence<AminoAcidCompound>> trans = multipleFrameTranslation(
				dna, Frame.ONE);
		return trans.get(Frame.ONE);
	}
962661
public final String getSequenceCodec() {
    String seqCodec = null;
    if ("BIO".equals(this.sequenceCodec)) {
      seqCodec = BioCodec.class.getName();
    } else if ("BILOU".equals(this.sequenceCodec)) {
      seqCodec = BilouCodec.class.getName();
    }
    return seqCodec;
  }
119231
def make_codon_list(protein_seq, template_dna=None, include_stop=True):
    

    codon_list = []

    if template_dna is None:
        template_dna = []

    # Reverse translate each codon, preferring (in order):
    # 1. The codon with the most similarity to the template codon.
    # 2. The codon with the highest natural usage.

    for i, res in enumerate(protein_seq.upper()):
        try: template_codon = template_dna[3*i:3*i+3]
        except IndexError: template_codon = '---'

        # Already sorted by natural codon usage
        possible_codons = dna.ecoli_reverse_translate[res]

        # Sort by similarity.  Note that this is a stable sort.
        possible_codons.sort(
                key=lambda x: dna.num_mutations(x, template_codon))

        # Pick the best codon.
        codon_list.append(possible_codons[0])

    # Make sure the sequence ends with a stop codon.
    last_codon = codon_list[-1]
    stop_codons = dna.ecoli_reverse_translate['.']

    if include_stop and last_codon not in stop_codons:
        codon_list.append(stop_codons[0])

    return codon_list
1008685
static Map<String, String> readFasta(final File inputFastqFile) throws IOException, NoSuchElementException, BioException{
    	
    	BufferedReader reader = null;
    	HashMap<String, String> fasta = new HashMap<String, String>();
        
    	try{
    		 reader = reader(inputFastqFile);
    		 for (SequenceIterator sequences = SeqIOTools.readFastaDNA(reader); sequences.hasNext(); ) 
    		{
                 Sequence sequence = sequences.nextSequence();
                 String sequenceId = sequence.getName();
                 String fastaSeq   = sequence.seqString();
                 fasta.put(sequenceId, fastaSeq);
             }
    		
    	}finally {
            try {
            	reader.close();
            }
            catch (Exception e) {
            	 e.printStackTrace();
            	 System.exit(1);
            }
        }
    
        
        return fasta;
    	
    }
257105
def get_sequence(self,ref):
    """"""
    strand = '+'
    if not self._options.direction:
      sys.stderr.write("WARNING: no strand information for the transcript\n")
    if self._options.direction: strand = self._options.direction
    seq = ''
    for e in [x.range for x in self.exons]:
      seq += str(ref[e.chr][e.start-1:e.end])
    if strand == '-':  seq = rc(seq)
    return Sequence(seq.upper())
176247
def load_sequences_to_reference(self, sc=None, force_rerun=False):
        """"""
        log.info('Loading sequences to reference GEM-PRO...')
        from random import shuffle
        g_ids = [g.id for g in self.reference_gempro.functional_genes]
        shuffle(g_ids)

        def _load_sequences_to_reference_gene_sc(g_id, outdir=self.sequences_by_gene_dir,
                                                 g_to_pickle=self.gene_protein_pickles,
                                                 strain_infodict=self.strain_infodict,
                                                 orth_matrix=self.df_orthology_matrix, force_rerun=force_rerun):
            """Load orthologous strain sequences to reference Protein object, save as new pickle"""
            import ssbio.utils
            import ssbio.io
            from Bio import SeqIO
            import os.path as op

            protein_seqs_pickle_path = op.join(outdir, '{}_protein_withseqs.pckl'.format(g_id))

            if ssbio.utils.force_rerun(flag=force_rerun, outfile=protein_seqs_pickle_path):
                protein_pickle_path = g_to_pickle[g_id]
                protein_pickle = ssbio.io.load_pickle(protein_pickle_path)

                for strain, info in strain_infodict.items():
                    strain_sequences = SeqIO.index(info['genome_path'], 'fasta')
                    strain_gene_functional = info['functional_genes'][g_id]
                    if strain_gene_functional:
                        # Pull the gene ID of the strain from the orthology matrix
                        strain_gene_key = orth_matrix.at[g_id, strain]
                        new_id = '{}_{}'.format(g_id, strain)
                        if protein_pickle.sequences.has_id(new_id):
                            continue
                        protein_pickle.load_manual_sequence(seq=strain_sequences[strain_gene_key],
                                                            ident=new_id,
                                                            set_as_representative=False)
                protein_pickle.save_pickle(outfile=protein_seqs_pickle_path)

            return g_id, protein_seqs_pickle_path

        if sc:
            genes_rdd = sc.parallelize(g_ids)
            result = genes_rdd.map(_load_sequences_to_reference_gene_sc).collect()
        else:
            result = []
            for g in tqdm(g_ids):
                result.append(self._load_sequences_to_reference_gene(g, force_rerun))

        log.info('Storing paths to new Protein objects in self.gene_protein_pickles...')
        updated = []
        for g_id, protein_pickle in result:
            self.gene_protein_pickles[g_id] = protein_pickle
            updated.append(g_id)
        not_updated = set(list(self.gene_protein_pickles.keys())).difference(updated)
        log.info('No change to {} genes, removing from gene_protein_pickles'.format(len(not_updated)))
        log.debug(not_updated)
        for rem in not_updated:
            del self.gene_protein_pickles[rem]
284315
def rev_comp( seq, molecule='dna' ):
	
	
	if molecule == 'dna':
		nuc_dict = { "A":"T", "B":"V", "C":"G", "D":"H", "G":"C", "H":"D", "K":"M", "M":"K", "N":"N", "R":"Y", "S":"S", "T":"A", "V":"B", "W":"W", "Y":"R" }
	elif molecule == 'rna':
		nuc_dict = { "A":"U", "B":"V", "C":"G", "D":"H", "G":"C", "H":"D", "K":"M", "M":"K", "N":"N", "R":"Y", "S":"S", "U":"A", "V":"B", "W":"W", "Y":"R" }
	else:
		raise ValueError( "rev_comp requires molecule to be dna or rna" )
	
	if not isinstance( seq, six.string_types ):
		raise TypeError( "seq must be a string!" )
	
	return ''.join( [ nuc_dict[c] for c in seq.upper()[::-1] ] )
662260
public int addReference(NucleotideSequence sequence) {
        if (sequence.containWildcards())
            throw new IllegalArgumentException("Reference sequences with wildcards not supported.");
        int id = mapper.addReference(sequence);
        assert sequences.size() == id;
        sequences.add(sequence);
        return id;
    }
1056843
public static int countAT(Sequence<NucleotideCompound> sequence) {
		CompoundSet<NucleotideCompound> cs = sequence.getCompoundSet();
		NucleotideCompound A = cs.getCompoundForString("A");
		NucleotideCompound T = cs.getCompoundForString("T");
		NucleotideCompound a = cs.getCompoundForString("a");
		NucleotideCompound t = cs.getCompoundForString("t");
		return countCompounds(sequence, A, T, a, t);
	}
562936
public static boolean isAmbiguosProtein(String sequence) {
	sequence = SequenceUtil.cleanSequence(sequence);
	if (SequenceUtil.isNonAmbNucleotideSequence(sequence)) {
		return false;
	}
	if (SequenceUtil.DIGIT.matcher(sequence).find()) {
		return false;
	}
	if (SequenceUtil.NON_AA.matcher(sequence).find()) {
		return false;
	}
	if (SequenceUtil.AA.matcher(sequence).find()) {
		return false;
	}
	final Matcher amb_prot = SequenceUtil.AMBIGUOUS_AA.matcher(sequence);
	return amb_prot.find();
	}
302214
public static AFPChain fastaToAfpChain(String sequence1, String sequence2, Structure structure1,
			Structure structure2) throws StructureException, CompoundNotFoundException {
		ProteinSequence s1 = new ProteinSequence(sequence1);
		s1.setUserCollection(getAlignedUserCollection(sequence1));
		ProteinSequence s2 = new ProteinSequence(sequence2);
		s2.setUserCollection(getAlignedUserCollection(sequence2));
		return fastaToAfpChain(s1, s2, structure1, structure2);
	}
847227
public static Sequence createSequence(final org.biojava.bio.seq.Sequence sequence) {
        checkNotNull(sequence);

        Sequence s = new Sequence();
        if (!DNATools.getDNA().equals(sequence.getAlphabet())) {
            throw new IllegalArgumentException("alphabet must be DNA");
        }
        s.setValue(sequence.seqString());
        return s;
    }
837484
def translate(dnaseq,host='human',fmtout=str,tax_id=None):
    
    if isinstance(dnaseq,str): 
        dnaseq=Seq.Seq(dnaseq,Alphabet.generic_dna)
    if tax_id is None:
        tax_id=1 # stanndard codon table. ref http://biopython.org/DIST/docs/tutorial/Tutorial.html#htoc25
    prtseq=dnaseq.translate(table=tax_id)
    if fmtout is str:
        return str(prtseq)
    else:
        return prtseq
595014
private IAtomContainer readMolecule(IAtomContainer molecule) throws CDKException {
        AtomTypeFactory atFactory = null;
        try {
            atFactory = AtomTypeFactory.getInstance("org/openscience/cdk/config/data/mol2_atomtypes.xml",
                    molecule.getBuilder());
        } catch (Exception exception) {
            String error = "Could not instantiate an AtomTypeFactory";
            logger.error(error);
            logger.debug(exception);
            throw new CDKException(error, exception);
        }
        try {
            int atomCount = 0;
            int bondCount = 0;

            String line;
            while (true) {
                line = input.readLine();
                if (line == null) return null;
                if (line.startsWith("@<TRIPOS>MOLECULE")) break;
                if (!line.startsWith("#") && line.trim().length() > 0) break;
            }

            // ok, if we're coming from the chemfile functoion, we've alreay read the molecule RTI
            if (firstLineisMolecule)
                molecule.setTitle(line);
            else {
                line = input.readLine();
                molecule.setTitle(line);
            }

            // get atom and bond counts
            String counts = input.readLine();
            StringTokenizer tokenizer = new StringTokenizer(counts);
            try {
                atomCount = Integer.parseInt(tokenizer.nextToken());
            } catch (NumberFormatException nfExc) {
                String error = "Error while reading atom count from MOLECULE block";
                logger.error(error);
                logger.debug(nfExc);
                throw new CDKException(error, nfExc);
            }
            if (tokenizer.hasMoreTokens()) {
                try {
                    bondCount = Integer.parseInt(tokenizer.nextToken());
                } catch (NumberFormatException nfExc) {
                    String error = "Error while reading atom and bond counts";
                    logger.error(error);
                    logger.debug(nfExc);
                    throw new CDKException(error, nfExc);
                }
            } else {
                bondCount = 0;
            }
            logger.info("Reading #atoms: ", atomCount);
            logger.info("Reading #bonds: ", bondCount);

            // we skip mol type, charge type and status bit lines
            logger.warn("Not reading molecule qualifiers");

            line = input.readLine();
            boolean molend = false;
            while (line != null) {
                if (line.startsWith("@<TRIPOS>MOLECULE")) {
                    molend = true;
                    break;
                } else if (line.startsWith("@<TRIPOS>ATOM")) {
                    logger.info("Reading atom block");
                    for (int i = 0; i < atomCount; i++) {
                        line = input.readLine().trim();
                        if (line.startsWith("@<TRIPOS>MOLECULE")) {
                            molend = true;
                            break;
                        }
                        tokenizer = new StringTokenizer(line);
                        tokenizer.nextToken(); // disregard the id token
                        String nameStr = tokenizer.nextToken();
                        String xStr = tokenizer.nextToken();
                        String yStr = tokenizer.nextToken();
                        String zStr = tokenizer.nextToken();
                        String atomTypeStr = tokenizer.nextToken();

                        // replace unrecognised atom type
                        if (ATOM_TYPE_ALIASES.containsKey(atomTypeStr))
                            atomTypeStr = ATOM_TYPE_ALIASES.get(atomTypeStr);

                        IAtom atom = molecule.getBuilder().newInstance(IAtom.class);
                        IAtomType atomType;
                        try {
                            atomType = atFactory.getAtomType(atomTypeStr);
                        } catch (Exception exception) {
                            // ok, *not* an mol2 atom type
                            atomType = null;
                        }
                        // Maybe it is just an element
                        if (atomType == null && isElementSymbol(atomTypeStr)) {
                            atom.setSymbol(atomTypeStr);
                        } else {
                            if (atomType == null) {
                                atomType = atFactory.getAtomType("X");
                                logger.error("Could not find specified atom type: ", atomTypeStr);
                            }
                            AtomTypeManipulator.configure(atom, atomType);
                        }

                        atom.setAtomicNumber(Elements.ofString(atom.getSymbol()).number());
                        atom.setID(nameStr);
                        atom.setAtomTypeName(atomTypeStr);
                        try {
                            double x = Double.parseDouble(xStr);
                            double y = Double.parseDouble(yStr);
                            double z = Double.parseDouble(zStr);
                            atom.setPoint3d(new Point3d(x, y, z));
                        } catch (NumberFormatException nfExc) {
                            String error = "Error while reading atom coordinates";
                            logger.error(error);
                            logger.debug(nfExc);
                            throw new CDKException(error, nfExc);
                        }
                        molecule.addAtom(atom);
                    }
                } else if (line.startsWith("@<TRIPOS>BOND")) {
                    logger.info("Reading bond block");
                    for (int i = 0; i < bondCount; i++) {
                        line = input.readLine();
                        if (line.startsWith("@<TRIPOS>MOLECULE")) {
                            molend = true;
                            break;
                        }
                        tokenizer = new StringTokenizer(line);
                        tokenizer.nextToken(); // disregard the id token
                        String atom1Str = tokenizer.nextToken();
                        String atom2Str = tokenizer.nextToken();
                        String orderStr = tokenizer.nextToken();
                        try {
                            int atom1 = Integer.parseInt(atom1Str);
                            int atom2 = Integer.parseInt(atom2Str);
                            if ("nc".equals(orderStr)) {
                                // do not connect the atoms
                            } else {
                                IBond bond = molecule.getBuilder().newInstance(IBond.class,
                                        molecule.getAtom(atom1 - 1), molecule.getAtom(atom2 - 1));
                                if ("1".equals(orderStr)) {
                                    bond.setOrder(Order.SINGLE);
                                } else if ("2".equals(orderStr)) {
                                    bond.setOrder(Order.DOUBLE);
                                } else if ("3".equals(orderStr)) {
                                    bond.setOrder(Order.TRIPLE);
                                } else if ("am".equals(orderStr) || "ar".equals(orderStr)) {
                                    bond.setOrder(Order.SINGLE);
                                    bond.setFlag(CDKConstants.ISAROMATIC, true);
                                    bond.getBegin().setFlag(CDKConstants.ISAROMATIC, true);
                                    bond.getEnd().setFlag(CDKConstants.ISAROMATIC, true);
                                } else if ("du".equals(orderStr)) {
                                    bond.setOrder(Order.SINGLE);
                                } else if ("un".equals(orderStr)) {
                                    bond.setOrder(Order.SINGLE);
                                }
                                molecule.addBond(bond);
                            }
                        } catch (NumberFormatException nfExc) {
                            String error = "Error while reading bond information";
                            logger.error(error);
                            logger.debug(nfExc);
                            throw new CDKException(error, nfExc);
                        }
                    }
                }
                if (molend) return molecule;
                line = input.readLine();
            }
        } catch (IOException exception) {
            String error = "Error while reading general structure";
            logger.error(error);
            logger.debug(exception);
            throw new CDKException(error, exception);
        }
        return molecule;
    }
1100984
public static double[] getBiologicalMoleculeCentroid( final Structure asymUnit,List<BiologicalAssemblyTransformation> transformations ) throws IllegalArgumentException {
		if ( asymUnit == null ) {
			throw new IllegalArgumentException( "null structure" );
		}

		Atom[] atoms = StructureTools.getAllAtomArray(asymUnit);
		int atomCount = atoms.length;
		double[] centroid = new double[3];

		if ( atomCount <= 0 ) {
			return centroid;
		}

		if ( transformations.size() == 0) {
			return Calc.getCentroid(atoms).getCoords();

		}



		int count = 0;
		double[] transformedCoordinate = new double[3];

		for (int i = 0; i < atomCount; i++)
		{
			Atom atom = atoms[i];
			Chain chain = atom.getGroup().getChain();
			String intChainID = chain.getId();


			for (BiologicalAssemblyTransformation m: transformations) {
				if (!  m.getChainId().equals(intChainID))
					continue;

				Point3d coords = atom.getCoordsAsPoint3d();
				transformedCoordinate[0] = coords.x;
				transformedCoordinate[1] = coords.y;
				transformedCoordinate[2] = coords.z;
				m.transformPoint(transformedCoordinate);
				centroid[0] += transformedCoordinate[0];
				centroid[1] += transformedCoordinate[1];
				centroid[2] += transformedCoordinate[2];
				count++;
			}
		}



		centroid[0] /= count;
		centroid[1] /= count;
		centroid[2] /= count;

		return centroid;
	}
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;
	}
308593
public static void writeNucleotideSequence(OutputStream outputStream, Collection<DNASequence> dnaSequences) throws Exception {
		FastaWriter<DNASequence, NucleotideCompound> fastaWriter = new FastaWriter<DNASequence, NucleotideCompound>(
				outputStream, dnaSequences,
				new GenericFastaHeaderFormat<DNASequence, NucleotideCompound>());
		fastaWriter.process();

	}