Counting Unique k-mers -- My First Go Program

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。Previously, I wrote a Perl program to count the number of unique k-mers. It is very convenient to implement it in Perl, because Perl supports hash-of-hashes(which could dynamically count distinct k-mers) and sorting hashes by value(which can easily list the occurrences of unique k-mers in descending order).

Unfortunately, comparing to C++, Perl program usually costs more memory and longer time. This is not a big issue when the FASTA files are not large(smaller than 400MB). However, when handling larger FASTA files, my Perl program would require more than 8GB memory, which exceeds the limits of my computer. Therefore, I decided to rewrite the program by Go, a system language that supports concurrent features and can has C/C++-comparable speed.

The syntax of Go is very different from C/C++, which takes me a whole day familiarize. Some operations that can be implemented easily in Perl can only be done in complicated way, such as calling system command, reading file line-by-line, writing file and sorting map by value. Since this small tool doesn't involve network and concurrency, I cannot compare the difficulty of writing Go program to implement such work. 

Although the experience of the first Go program is not happy, I still think it is necessary to continue learning Go language, because Go program really runs very fast and saves memory(comparing to Perl script). And you don't need to worry about the tricky part of C++. 

// kmerfreq - count unique k-mers from a fasta file.package mainimport ("bufio""bytes""flag""fmt""io""os""os/exec""strings""strconv")// Readln returns a single line (without the ending \n)// from the input buffered reader.// An error is returned iff there is an error with the// buffered reader.func Readln(r *bufio.Reader) (string, error) {var (isPrefix bool  = trueerr      error = nilline, ln []byte)for isPrefix && err == nil {line, isPrefix, err = r.ReadLine()ln = append(ln, line...)}return string(ln), err}func main() {// Get optionsvar input = flag.String("i", "", "input fasta file")var kmer = flag.Int("k", 16, "length of k-mer")flag.Parse()// Dynamically parse the input file namecmd := exec.Command("basename", *input)cmd.Stdin = strings.NewReader("some input")var name bytes.Buffercmd.Stdout = &nameerr := cmd.Run()if err != nil {fmt.Println(err)return}var output = flag.String("o", fmt.Sprintf("%s.%d-mer", strings.TrimSpace(name.String()), *kmer), "output file")flag.Parse()// open input filefi, err := os.Open(*input)if err != nil {panic(err)}// close fi on exit and check for its returned errordefer func() {if err := fi.Close(); err != nil {panic(err)}}()// open output filefo, err := os.Create(*output)if err != nil {panic(err)}// close fo on exit and check for its returned errordefer func() {if err := fo.Close(); err != nil {panic(err)}}()// Read and count unique k-mersvar read string = ""var km map[string]int  // k-mer countskm = make(map[string]int)r := bufio.NewReader(fi)for {line, err := Readln(r)if err == io.EOF {if !strings.HasPrefix(line, ">") {read += line}break // done} else if err != nil {panic(err) // error happens}if strings.HasPrefix(line, ">") {// Header of the readif len(read) != 0 {// count k-mersfor i := 0; i < len(read)-*kmer+1; i++ {if km[read[i:i+*kmer]] != 0 {km[read[i:i+*kmer]]++} else {km[read[i:i+*kmer]] = 1}}read = ""}} else {// Readread += line}} // end of for// Don't forget the last readif len(read) != 0 {// count k-mersfor i := 0; i < len(read)-*kmer+1; i++ {if km[read[i:i+*kmer]] != 0 {km[read[i:i+*kmer]]++} else {km[read[i:i+*kmer]] = 1}}}// Write resultsfor k, v := range km {fo.WriteString(k + "\t" + strconv.Itoa(v) + "\n")}}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.