Create a XLSX file listing the given sequences.

    Arguments
    =========
    path: str or pathlib.Path
        The name of the file to create.

    seqs: dict
        A mapping of names to sequences, which can be either protein or DNA.
180375
def write_sequences_to_xlsx(path, seqs):
    
    from openpyxl import Workbook

    wb = Workbook()
    ws = wb.active

    for row, id in enumerate(seqs, 1):
        ws.cell(row, 1).value = id
        ws.cell(row, 2).value = seqs[id]

    wb.save(path)
444200
def get_seqs_type(seqs):
    
    region_p = re.compile(r'^(.+):(\d+)-(\d+)$')
    if isinstance(seqs, Fasta):
        return "fasta"
    elif isinstance(seqs, list):
        if len(seqs) == 0:
            raise ValueError("empty list of sequences to scan")
        else:
            if region_p.search(seqs[0]):
                return "regions"
            else:
                raise ValueError("unknown region type")
    elif isinstance(seqs, str) or isinstance(seqs, unicode):
        if os.path.isfile(seqs):
            ftype = determine_file_type(seqs)
            if ftype == "unknown":
                raise ValueError("unknown type")
            elif ftype == "narrowpeak":
                raise ValueError("narrowPeak not yet supported in this function")
            else:
                return ftype + "file"
        else:
            raise ValueError("no file found with name {}".format(seqs))
    else:
        raise ValueError("unknown type {}".format(type(seqs).__name__))
500121
def make_organisms(self, genome_list, genome_dir): 

        '''

            '''

        for genome in genome_list:

            genome_path = genome_dir + genome
            handle = open(genome_path, "rU")
            print 'Adding organism attributes for', genome

            try:
                seq_record = SeqIO.read(handle, "genbank")

                self.organisms.append(Organism(seq_record, genome_path, self))

                del(seq_record)

            except ValueError,e:
                print genome, str(e)

            except AssertionError,e:
                print genome, str(e)

            except UnboundLocalError,e:
                print genome, str(e)

            handle.close()
124144
def seq_str(self):
        """"""

        if not self.seq:
            return None

        return ssbio.protein.sequence.utils.cast_to_str(self.seq)
1073696
def create_parser():
    
    parser = argparse.ArgumentParser(
        prog='riboplot.py', description='Plot and output read counts for a single transcript')

    required = parser.add_argument_group('required arguments')
    required.add_argument('-b', '--ribo_file', help='Ribo-Seq alignment file in BAM format', required=True)
    required.add_argument('-f', '--transcriptome_fasta', help='FASTA format file of the transcriptome', required=True)
    required.add_argument('-t', '--transcript_name', help='Transcript name', metavar='TEXT', required=True)

    # plot function - optional arguments
    parser.add_argument('-n', '--rna_file', help='RNA-Seq alignment file (BAM)')
    parser.add_argument('-l', '--read_lengths', help='Read lengths to consider (default: %(default)s). '
                        'Multiple read lengths should be separated by commas. If multiple read lengths '
                        'are specified, corresponding read offsets should also be specified. If you do '
                        'not wish to apply an offset, please input 0 for the corresponding read length',
                        default='0', type=ribocore.lengths_offsets)
    parser.add_argument('-s', '--read_offsets', help='Read offsets (default: %(default)s). '
                        'Multiple read offsets should be separated by commas',
                        default='0', type=ribocore.lengths_offsets)
    parser.add_argument('-c', '--color_scheme', help='Color scheme to use (default: %(default)s)',
                        choices=['default', 'colorbrewer', 'rgb', 'greyorfs'], default='default')
    parser.add_argument('-m', '--html_file', help='Output file for results (HTML)', default='riboplot.html')
    parser.add_argument('-o', '--output_path', help='Files are saved in this directory', default='output')
    parser.add_argument('-d', '--debug', help='Flag. Produce debug output', action='store_true')

    return parser
751811
def precursor_sequence(loci, reference):
    """"""
    region = "%s\t%s\t%s\t.\t.\t%s" % (loci[1], loci[2], loci[3], loci[4])
    precursor = pybedtools.BedTool(str(region), from_string=True).sequence(fi=reference, s=True)
    return open(precursor.seqfn).read().split("\n")[1]
1120517
def map_to_precursor_biopython(seqs, names, loci, args):
    """"""
    precursor = precursor_sequence(loci, args.ref).upper()
    dat = dict()
    for s, n in itertools.izip(seqs, names):
        res = _align(str(s), precursor)
        if res:
            dat[n] = res
    logger.debug("mapped in %s: %s out of %s" % (loci, len(dat), len(seqs)))
    return dat
897035
def create(self, path, data, ephemeral=False, sequence=False):
        
        return self._zk.create(
            self.__path(path), data, ephemeral=ephemeral, sequence=sequence
        )
732951
def split_sequence_file_on_sample_ids_to_files(seqs,
                                               outdir):
    
    logger = logging.getLogger(__name__)
    logger.info('split_sequence_file_on_sample_ids_to_files'
                ' for file %s into dir %s' % (seqs, outdir))

    outputs = {}

    for bits in sequence_generator(seqs):
        sample = sample_id_from_read_id(bits[0])

        if sample not in outputs:
            outputs[sample] = open(join(outdir, sample + '.fasta'), 'w')
        outputs[sample].write(">%s\n%s\n" % (bits[0], bits[1]))
    for sample in outputs:
        outputs[sample].close()
    logger.info('split to %d files' % len(outputs))
71069
def excel_todictlist(path_to_file, **kwargs):
    
    result = collections.OrderedDict()
    encoding = kwargs.get('encoding', 'utf-8')
    formatting_info = '.xlsx' not in path_to_file
    count = 0

    with xlrd.open_workbook(
        path_to_file,
        encoding_override=encoding, formatting_info=formatting_info) \
            as _excelfile:

        for sheet_name_raw in _excelfile.sheet_names():

            # if empty sheet name put sheet# as name
            sheet_name = sheet_name_raw or "sheet{}".format(count)
            result[sheet_name] = []

            xl_sheet = _excelfile.sheet_by_name(sheet_name_raw)

            for row_idx in range(0, xl_sheet.nrows):
                col_data = []
                for col_idx in range(0, xl_sheet.ncols):

                    # Get cell object by row, col
                    cell_obj = xl_sheet.cell(row_idx, col_idx)
                    merged_info = is_merged(xl_sheet, row_idx, col_idx)

                    # Search for value in merged_info
                    if not cell_obj.value and merged_info:
                        cell_obj = search_mergedcell_value(
                            xl_sheet, merged_info[1])
                        col_data.append(cell_obj.value if cell_obj else '')
                    else:
                        col_data.append(cell_obj.value)

                result[sheet_name].append(col_data)

            count += 1  # increase sheet counter

    return result
1134860
private static <S extends Sequence<S>> BlastDB build(List<S> sequences, boolean buildIdIndex,
                                                         Path path, boolean tmp) {
        if (sequences.isEmpty())
            throw new IllegalArgumentException("No records.");

        if (path == null)
            path = getTmpDBPath();

        Alphabet<S> alphabet = sequences.get(0).getAlphabet();

        try {
            String name = RandomUtil.getThreadLocalRandomData().nextHexString(40);
            String fullName = path.resolve(name).toString();
            List<String> cmd = new ArrayList<>();
            cmd.addAll(Arrays.asList(Blast.CMD_MAKEBLASTDB, "-dbtype", Blast.toBlastAlphabet(alphabet),
                    "-out", fullName, "-title", name));
            cmd.addAll(Arrays.asList("-parse_seqids", "-hash_index"));
            Process proc = Blast.getProcessBuilder(cmd).start();
            FastaWriter<S> writer = new FastaWriter<>(proc.getOutputStream(), FastaWriter.DEFAULT_MAX_LENGTH);
            for (int i = 0; i < sequences.size(); i++)
                writer.write(getIdFasta(i), sequences.get(i));
            writer.close();
            String err = IOUtils.toString(proc.getErrorStream(), Charset.forName("US-ASCII"));
            if (proc.waitFor() != 0)
                throw new RuntimeException("Something goes wrong: " + err);
            return BlastDB.get(fullName, tmp);
        } catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
289969
def fasta_cmd_get_seqs(acc_list,
                 blast_db=None,
                 is_protein=None,
                 out_filename=None,
                 params={},
                 WorkingDir=tempfile.gettempdir(),
                 SuppressStderr=None,
                 SuppressStdout=None):
    

    if is_protein is None:
        params["-p"] = 'G'
    elif is_protein:
        params["-p"] = 'T'
    else:
        params["-p"] = 'F'

    if blast_db:
        params["-d"] = blast_db

    if out_filename:
        params["-o"] = out_filename

    # turn off duplicate accessions
    params["-a"] = "F"

    # create Psi-BLAST
    fasta_cmd = FastaCmd(params=params,
                       InputHandler='_input_as_string',
                       WorkingDir=WorkingDir,
                       SuppressStderr=SuppressStderr,
                       SuppressStdout=SuppressStdout)

    # return results
    return fasta_cmd("\"%s\"" % ','.join(acc_list))
89693
def get_structure_seqs(self, model):
        

        # Don't overwrite existing ChainProp objects
        dont_overwrite = []
        chains = list(model.get_chains())
        for x in chains:
            if self.chains.has_id(x.id):
                if self.chains.get_by_id(x.id).seq_record:
                    dont_overwrite.append(x.id)
        if len(dont_overwrite) == len(chains):
            log.debug('Not writing structure sequences, already stored')
            return

        # Returns the structures sequences with Xs added
        structure_seqs = ssbio.protein.structure.properties.residues.get_structure_seqrecords(model)
        log.debug('{}: gathered chain sequences'.format(self.id))

        # Associate with ChainProps
        for seq_record in structure_seqs:
            log.debug('{}: adding chain sequence to ChainProp'.format(seq_record.id))
            my_chain = self.chains.get_by_id(seq_record.id)
            my_chain.seq_record = seq_record
58925
def sequence_path(self, fasta_path):
        
        if not fasta_path:
            self.sequence_dir = None
            self.sequence_file = None

        else:
            if not op.exists(fasta_path):
                raise OSError('{}: file does not exist'.format(fasta_path))

            if not op.dirname(fasta_path):
                self.sequence_dir = '.'
            else:
                self.sequence_dir = op.dirname(fasta_path)
            self.sequence_file = op.basename(fasta_path)

            tmp_sr = SeqIO.read(fasta_path, 'fasta')
            if self.name == '<unknown name>':
                self.name = tmp_sr.name
            if self.description == '<unknown description>':
                self.description = tmp_sr.description
            if not self.dbxrefs:
                self.dbxrefs = tmp_sr.dbxrefs
            if not self.features:
                self.features = tmp_sr.features
            if not self.annotations:
                self.annotations = tmp_sr.annotations
            if not self.letter_annotations:
                self.letter_annotations = tmp_sr.letter_annotations
287461
def make_fasta_dna_url(
        ensembl_release,
        species,
        contig,
        server=ENSEMBL_FTP_SERVER):
    
    ensembl_release, species, _ = \
        normalize_release_properties(ensembl_release, species)
    subdir = _species_subdir(
        ensembl_release,
        species=species,
        filetype="fasta",
        server=server,)
    server_subdir = urllib_parse.urljoin(server, subdir)
    server_sequence_subdir = join(server_subdir, "dna")
    filename = make_fasta_dna_filename(
        ensembl_release=ensembl_release,
        species=species,
        contig=contig)
    return join(server_sequence_subdir, filename)
1024169
def setup_jobs(outpath, options, input_files):
    ''' 
    '''

    job_inputs = None
    reverse_mapping = None
    fasta_file_contents = {}

    # Generate FASTA files for PDB inputs
    # fasta_file_contents is a mapping from a file path to a pair (FASTA contents, file type). We remember the file type
    # since we offset residue IDs depending on file type i.e. for FASTA files, we treat each sequence separately and do
    # not renumber the fragments in postprocessing. For PDB files, however, we need to respect the order and length of
    # sequences so that we renumber the fragments appropriately in postprocessing - we assume that if a PDB file is passed in
    # then all chains (protein, RNA, or DNA) will be used in a Rosetta run.
    for input_file in input_files:
        assert(not(fasta_file_contents.get(input_file)))
        if any(fnmatch(input_file, x) for x in pdb_file_wildcards):
            pdb = PDB.from_filepath(input_file, strict=True)
            pdb.pdb_id = os.path.basename(input_file).split('.')[0]            
            if pdb.pdb_id.startswith('pdb') and len(pdb.pdb_id) >= 7:
                # Hack to rename FASTA identifiers for pdb*.ent files which are present in mirrors of the PDB
                pdb.pdb_id = pdb.pdb_id.replace('pdb', '')    
            fasta_file_contents[input_file] = (pdb.create_fasta(prefer_seqres_order = False), 'PDB')
        else:
            fasta_file_contents[input_file] = (read_file(input_file), 'FASTA')

    # Extract sequences from the input FASTA files.
    found_sequences, reverse_mapping, errors = get_sequences(options, fasta_file_contents)
    if found_sequences:
        reformat(found_sequences)
    if errors:
        return None, False, errors

    # Discard sequences that are the wrong chain.
    desired_sequences = {}
    for key, sequence in found_sequences.iteritems():
        pdb_id, chain, file_name = key
        if options.chain is None or chain == options.chain:
            desired_sequences[key] = sequence

    # Create the input FASTA and script files.
    job_inputs, errors = create_inputs(options, outpath, desired_sequences)

    # Create the reverse mapping file
    if reverse_mapping:
        segment_mapping_file = os.path.join(outpath, "segment_map.json")
        colorprinter.message("Creating a reverse mapping file %s." % segment_mapping_file)
        write_file(segment_mapping_file, json.dumps(reverse_mapping))

    # Create the post-processing script file
    post_processing_script = read_file(os.path.join(os.path.split(os.path.realpath(__file__))[0], 'post_processing.py'))
    write_file(os.path.join(outpath, 'post_processing.py'), post_processing_script, 'w')

    # Create the secondary structure filter file
    if options.secondary_structure_file:
        write_file(os.path.join(outpath, 'ss_filter.json'), json.dumps({'secondary_structure_filter' : SecondaryStructureDefinition.from_filepath(options.secondary_structure_file).data}), 'w')

    return job_inputs, reverse_mapping != None, errors
967236
def build_tree_raxml(self,
                   new_path    = None,
                   seq_type    = 'nucl' or 'prot',
                   num_threads = None,
                   free_cores  = 2,
                   keep_dir    = False):
        """"""
        # Check output #
        if new_path is None: new_path = self.prefix_path + '.tree'
        # What model to choose #
        if seq_type == 'nucl': model = "GTRGAMMA"
        if seq_type == 'prot': model = "PROTGAMMAJTTF"
        # Threads #
        if num_threads is None: num_threads = multiprocessing.cpu_count() - free_cores
        else:                   num_threads = int(num_threads) - free_cores
        num_threads = max(1, num_threads)
        # Run it #
        temp_dir = new_temp_dir()
        sh.raxml811('-m', model, "-T", num_threads, '-p', 1, '-s', self.path, '-n', 'tree', '-w', temp_dir, '-f', 'a', '-x', 1, '-N', 'autoMR')
        # Move into place #
        if keep_dir:
            shutil.rmtree(new_path)
            shutil.move(temp_dir, new_path)
        if not keep_dir:
            shutil.move(temp_dir + 'RAxML_bestTree.tree', new_path)
        # Return #
        return FilePath(new_path)